Identity, authority and human approval
An authorization record has meaning only when supplied by a trusted component. The coordinator calls your authorizer for every command and replaces caller-supplied context. It also replaces policy, mandatoryChecksOk and authorizationCheckedAt on admission, dispatch and retry.
Authorizer contract
Section titled “Authorizer contract”Return allowed, policy, mandatoryChecksOk and context. Context requires actor, policy revision and decision class. TypeScript uses an async callback, typed Authorizer in @aiws/sdk/runtime; Python uses a callable returning the same JSON-shaped fields, whose shape current source names aiws.runtime.Authorizer; Rust implements Authorizer and returns Authorization, whose field names follow Rust conventions.
Use an authenticated session or workload identity established by the host. Never read a command’s context.actor as proof of who sent it. Bind permission evaluation to the selected mission and resource, not just the command name. A valid “approve” command shape is not evidence that the approver is authorized.
Deny agent attempts to issue new grants · Executable application recipe
import assert from 'node:assert/strict';import {readFileSync} from 'node:fs';import {parseContract,type Command} from '@aiws/sdk';import {SqliteStore} from '@aiws/sdk/sqlite';import {Coordinator,type Authorizer} from '@aiws/sdk/runtime';// A demonstration of the human-only boundary, not authentication. The host verifies each session// before a command reaches the authorizer; identity never comes from command.context or an event payload.type Session={actor:string;isHuman:boolean};const agent:Session={actor:'agent:builder',isHuman:false},human:Session={actor:'human:owner',isHuman:true};const humanOnly=new Set(['grant','revokeGrant','approve','withdrawApproval']);const allowedCommands=new Set(['startRun']); // deliberately narrow teaching policyconst authorizerFor=(session:Session):Authorizer=>async(command)=>{ const allowed=humanOnly.has(command.type)?session.isHuman:allowedCommands.has(command.type); return {allowed,policy:allowed?'ALLOW':'DENY',mandatoryChecksOk:true, context:{actor:session.actor,policyRevision:'policy:example:1',decisionClass:session.isHuman?'HUMAN':'DETERMINISTIC'}};};const contract=parseContract(readFileSync('examples/guide/contract.json','utf8'));const store=new SqliteStore(':memory:',contract);const clock=()=>'10';try { await new Coordinator(store,authorizerFor(agent),clock).apply({type:'startRun',runId:'r'}); const grant:Command={type:'grant',grant:{id:'g',subject:agent.actor,profile:'finite-v1',actions:['write'],resources:['doc'],notBefore:'0',expiresAt:'10000',limit:'100',canDelegate:false,depth:'0'}}; // The agent session cannot grant itself authority. await assert.rejects(new Coordinator(store,authorizerFor(agent),clock).apply(grant),(e:any)=>e.code==='AUTHORITY_DENIED'); assert.equal(store.snapshot().revision,'1'); assert.equal(store.diagnostics()[0].command.code,'AUTHORITY_DENIED'); // A verified human session can. await new Coordinator(store,authorizerFor(human),clock).apply(grant); assert.equal(store.snapshot().revision,'2'); assert.equal(store.snapshot().grants.g.subject,agent.actor);} finally {store.close();}use aiws_sdk::*;use aiws_sdk::runtime::*;use aiws_sdk::sqlite::SqliteStore;use serde_json::json;// A demonstration of the human-only boundary, not authentication. The host verifies each session// before a command reaches the authorizer; identity never comes from a caller-supplied command field.struct Session{actor:&'static str,is_human:bool}static AGENT:Session=Session{actor:"agent:builder",is_human:false};static HUMAN:Session=Session{actor:"human:owner",is_human:true};const HUMAN_ONLY:[&str;4]=["grant","revokeGrant","approve","withdrawApproval"];const ALLOWED_COMMANDS:[&str;1]=["startRun"]; // deliberately narrow teaching policystruct SessionPolicy(&'static Session);impl Authorizer for SessionPolicy { fn authorize(&mut self,command:&Command,_:&Snapshot,_:&str)->Result<Authorization>{ let kind=command.as_value()["type"].as_str().unwrap_or_default(); let allowed=if HUMAN_ONLY.contains(&kind){self.0.is_human}else{ALLOWED_COMMANDS.contains(&kind)}; Ok(Authorization{allowed,policy:if allowed{"ALLOW"}else{"DENY"}.into(),mandatory_checks_ok:true, context:json!({"actor":self.0.actor,"policyRevision":"policy:example:1","decisionClass":if self.0.is_human{"HUMAN"}else{"DETERMINISTIC"}})}) }}struct FixedClock;impl Clock for FixedClock{fn now_ms(&self)->String{"10".into()}}fn main()->std::result::Result<(),Box<dyn std::error::Error>>{ let contract=Contract::parse(&std::fs::read_to_string("examples/guide/contract.json")?)?; let store=SqliteStore::open(":memory:",Some(&contract))?; // The coordinator owns the store, so each verified session gets its own coordinator. let mut coordinator=Coordinator::new(store,SessionPolicy(&AGENT),FixedClock); coordinator.apply(&Command::from_value(json!({"type":"startRun","runId":"r"}))?,None)?; let grant=Command::from_value(json!({"type":"grant","grant":{"id":"g","subject":AGENT.actor,"profile":"finite-v1","actions":["write"],"resources":["doc"],"notBefore":"0","expiresAt":"10000","limit":"100","canDelegate":false,"depth":"0"}}))?; // The agent session cannot grant itself authority. assert_eq!(coordinator.apply(&grant,None).unwrap_err().code,"AUTHORITY_DENIED"); assert_eq!(coordinator.store.snapshot()?.as_value()["revision"],"1"); assert_eq!(coordinator.store.diagnostics()?[0]["command"]["code"],"AUTHORITY_DENIED"); // A verified human session can. let mut coordinator=Coordinator::new(coordinator.store,SessionPolicy(&HUMAN),FixedClock); coordinator.apply(&grant,None)?; assert_eq!(coordinator.store.snapshot()?.as_value()["revision"],"2"); assert_eq!(coordinator.store.snapshot()?.as_value()["grants"]["g"]["subject"],AGENT.actor); Ok(())}from pathlib import Pathfrom aiws import parse_contract,AiwsErrorfrom aiws.sqlite import SqliteStorefrom aiws.runtime import Coordinator# A demonstration of the human-only boundary, not authentication. The host verifies each session# before a command reaches the authorizer; identity never comes from a caller-supplied command field.agent={'actor':'agent:builder','isHuman':False}human={'actor':'human:owner','isHuman':True}HUMAN_ONLY={'grant','revokeGrant','approve','withdrawApproval'}ALLOWED_COMMANDS={'startRun'} # deliberately narrow teaching policydef authorizer_for(session): def authorize(command,state,now): allowed=session['isHuman'] if command['type'] in HUMAN_ONLY else command['type'] in ALLOWED_COMMANDS return dict(allowed=allowed,policy='ALLOW' if allowed else 'DENY',mandatoryChecksOk=True, context=dict(actor=session['actor'],policyRevision='policy:example:1',decisionClass='HUMAN' if session['isHuman'] else 'DETERMINISTIC')) return authorizeclock=lambda:'10'contract=parse_contract(Path('examples/guide/contract.json').read_text())with SqliteStore(':memory:',contract) as store: Coordinator(store,authorizer_for(agent),clock).apply(dict(type='startRun',runId='r')) grant=dict(type='grant',grant=dict(id='g',subject=agent['actor'],profile='finite-v1',actions=['write'],resources=['doc'],notBefore='0',expiresAt='10000',limit='100',canDelegate=False,depth='0')) # The agent session cannot grant itself authority. try: Coordinator(store,authorizer_for(agent),clock).apply(grant) raise AssertionError('expected denial') except AiwsError as error: assert error.code=='AUTHORITY_DENIED' assert store.snapshot()['revision']=='1' assert store.diagnostics()[0]['command']['code']=='AUTHORITY_DENIED' # A verified human session can. Coordinator(store,authorizer_for(human),clock).apply(grant) assert store.snapshot()['revision']=='2' assert store.snapshot()['grants']['g']['subject']==agent['actor']This example permits grant, revokeGrant, approve and withdrawApproval only to a verified human session, and otherwise permits only run creation. It rejects the agent session’s grant, records a diagnostic and leaves the mission revision unchanged by the rejection, then accepts the same grant from the human session. Its session flag demonstrates the boundary; it is not authentication. It is a shape and enforcement example, not a complete organizational policy service. Replace its fixed sessions and command allowlist before deployment.
Grants and delegated scope
Section titled “Grants and delegated scope”A grant defines an exact subject, finite actions/resources, validity interval, allowance, delegation flag and depth. Child grants cannot expand their parent’s scope, lifetime or allocation. Wildcards, regular expressions and inferred resource containment are not supported. Ancestor revocation is checked again at dispatch.
Reject an expanded child grant · Executable control simulation
import assert from 'node:assert/strict';import { createMission, parseContract, parseCommand, reduce } from '@aiws/sdk';
// Trusted simulation: this example makes no external calls.const contract = parseContract(JSON.stringify({ "id": "c", "missionId": "m", "aiwsEdition": "0.4", "profile": "finite-v1", "budget": "100", "deadline": "10000", "criteria": [ "review" ], "actions": [ "write" ], "resources": [ "doc" ], "requiresApproval": false, "maxAttempts": "2", "maxAuthorizationAgeMs": "10", "features": [ "triggers", "graphs" ]}));let state = createMission(contract);
// Step 1state = reduce(state, parseCommand(JSON.stringify({ "type": "grant", "grant": { "id": "g", "subject": "agent", "profile": "finite-v1", "actions": [ "write" ], "resources": [ "doc" ], "notBefore": "0", "expiresAt": "10000", "limit": "100", "canDelegate": true, "depth": "2" }})), '10');
// Step 2assert.throws(() => reduce(state, parseCommand(JSON.stringify({ "type": "grant", "grant": { "id": "child", "subject": "agent", "profile": "finite-v1", "actions": [ "write" ], "resources": [ "doc" ], "notBefore": "0", "expiresAt": "10000", "limit": "100", "canDelegate": true, "depth": "2", "parentId": "g" }})), '10'), (error: any) => error.code === 'AUTHORITY_DENIED');console.log('PASS: grant-scope');use aiws_sdk::*;use serde_json::json;
fn main() -> Result<()> { // Trusted simulation: no external calls. let contract = Contract::parse(&json!({ "id": "c", "missionId": "m", "aiwsEdition": "0.4", "profile": "finite-v1", "budget": "100", "deadline": "10000", "criteria": [ "review" ], "actions": [ "write" ], "resources": [ "doc" ], "requiresApproval": false, "maxAttempts": "2", "maxAuthorizationAgeMs": "10", "features": [ "triggers", "graphs" ]}).to_string())?; let mut state = create_mission(&contract)?;
// Step 1 state = reduce(&state, &Command::from_value(json!({ "type": "grant", "grant": { "id": "g", "subject": "agent", "profile": "finite-v1", "actions": [ "write" ], "resources": [ "doc" ], "notBefore": "0", "expiresAt": "10000", "limit": "100", "canDelegate": true, "depth": "2" }}))?, "10")?;
// Step 2 let rejected = Command::from_value(json!({ "type": "grant", "grant": { "id": "child", "subject": "agent", "profile": "finite-v1", "actions": [ "write" ], "resources": [ "doc" ], "notBefore": "0", "expiresAt": "10000", "limit": "100", "canDelegate": true, "depth": "2", "parentId": "g" }})).and_then(|command| reduce(&state, &command, "10")); assert_eq!(rejected.unwrap_err().code, "AUTHORITY_DENIED"); println!("PASS: grant-scope"); Ok(())}import jsonfrom aiws import create_mission, parse_contract, reduce, AiwsError
# Trusted simulation: this example makes no external calls.contract = parse_contract(json.dumps({'id': 'c', 'missionId': 'm', 'aiwsEdition': '0.4', 'profile': 'finite-v1', 'budget': '100', 'deadline': '10000', 'criteria': ['review'], 'actions': ['write'], 'resources': ['doc'], 'requiresApproval': False, 'maxAttempts': '2', 'maxAuthorizationAgeMs': '10', 'features': ['triggers', 'graphs']}))state = create_mission(contract)
# Step 1state = reduce(state, {'type': 'grant', 'grant': {'id': 'g', 'subject': 'agent', 'profile': 'finite-v1', 'actions': ['write'], 'resources': ['doc'], 'notBefore': '0', 'expiresAt': '10000', 'limit': '100', 'canDelegate': True, 'depth': '2'}}, '10')
# Step 2try: reduce(state, {'type': 'grant', 'grant': {'id': 'child', 'subject': 'agent', 'profile': 'finite-v1', 'actions': ['write'], 'resources': ['doc'], 'notBefore': '0', 'expiresAt': '10000', 'limit': '100', 'canDelegate': True, 'depth': '2', 'parentId': 'g'}}, '10') raise AssertionError('expected AUTHORITY_DENIED')except AiwsError as error: assert error.code == 'AUTHORITY_DENIED'print('PASS: grant-scope')CONTAINED means the supported finite comparison succeeded. INDETERMINATE is not a permissive result. Failure to interpret authority must block admission. Grant containment alone does not authenticate a principal or enforce operating-system and network access.
Check a record in a contract’s context
Section titled “Check a record in a contract’s context”The SDK has no separate validate_grant, validate_trigger or validate_graph. A definition editor checks a contract, a grant, a trigger or a graph with the reducer, in a scratch mission. This recipe is supported SDK API in all three languages:
- Parse the contract with
parseContract/parse_contract/Contract::parse. A contract without criteria, or without a positive attempt limit, fails here withINVALID_CONTRACT. - Build a fresh snapshot with
createMission(contract)/create_mission. - If the grant has a
parentId, replay the parent grant first withreduce. The child is compared with the parent as the reducer holds it, and a missing parent isNOT_FOUND. - Call
reduceonce with agrant,registerTriggerorregisterGraphcommand and a caller-suppliednow. A return is acceptance. A thrownAiwsErrorcarries the refusal code. - Discard the snapshot. Make the next check from a fresh one.
reduce is pure: it clones its input and returns the next snapshot, and nothing persists. Each record reports its first error, in the order the reducer checks, so fixing one error can reveal the next. The contract gives the record its context (the triggers and graphs features, the action and resource sets, the budget and the deadline), so check a record against the contract it will run under.
Check a grant or trigger in a contract's context · Executable control simulation
import assert from 'node:assert/strict';import { createMission, parseContract, parseCommand, reduce } from '@aiws/sdk';
// Trusted simulation: this example makes no external calls.const contractText = JSON.stringify({ "id": "c", "missionId": "m", "aiwsEdition": "0.4", "profile": "finite-v1", "budget": "100", "deadline": "10000", "criteria": [ "review" ], "actions": [ "write" ], "resources": [ "doc" ], "requiresApproval": false, "maxAttempts": "2", "maxAuthorizationAgeMs": "10", "features": [ "triggers" ]});const parentGrant = { "type": "grant", "grant": { "id": "g", "subject": "agent", "profile": "finite-v1", "actions": [ "write" ], "resources": [ "doc" ], "notBefore": "0", "expiresAt": "10000", "limit": "100", "canDelegate": true, "depth": "2" }};
// The caller's clock decides what "now" is; the SDK only checks that it is a decimal.function check(record: object, now: string) { // A fresh snapshot per check: reduce is pure and nothing persists. let scratch = createMission(parseContract(contractText)); // Replay the parent grant so a child grant has a parent to be compared with. scratch = reduce(scratch, parseCommand(JSON.stringify(parentGrant)), now); reduce(scratch, parseCommand(JSON.stringify(record)), now);}const childGrant = (depth: string) => ({ "type": "grant", "grant": { "id": "child", "subject": "agent", "profile": "finite-v1", "actions": [ "write" ], "resources": [ "doc" ], "notBefore": "0", "expiresAt": "10000", "limit": "50", "canDelegate": true, "depth": depth, "parentId": "g" }});const trigger = (rateLimit: string) => ({ "type": "registerTrigger", "trigger": { "id": "t", "revision": "1", "kind": "EVENT", "source": "trusted", "eventType": "doc.changed", "contractId": "c", "action": "START_RUN", "enabled": true, "notBefore": "0", "expiresAt": "10000", "maxAgeMs": "100", "maxConcurrent": "2", "rateLimit": rateLimit, "rateWindowMs": "100", "maxDepth": "3" }});
// Step 1: acceptance. A narrower child grant and a well-formed trigger return without error.check(childGrant('1'), '10');check(trigger('10'), '10');
// Step 2: refusals. Each record reports its first error.assert.throws(() => check(childGrant('2'), '10'), (error: any) => error.code === 'AUTHORITY_DENIED');assert.throws(() => check(trigger('0'), '10'), (error: any) => error.code === 'TRIGGER_LIMIT');console.log('PASS: scratch-check');use aiws_sdk::*;use serde_json::{json, Value};
fn contract_text() -> String { json!({ "id": "c", "missionId": "m", "aiwsEdition": "0.4", "profile": "finite-v1", "budget": "100", "deadline": "10000", "criteria": [ "review" ], "actions": [ "write" ], "resources": [ "doc" ], "requiresApproval": false, "maxAttempts": "2", "maxAuthorizationAgeMs": "10", "features": [ "triggers" ]}).to_string()}
fn parent_grant() -> Value { json!({ "type": "grant", "grant": { "id": "g", "subject": "agent", "profile": "finite-v1", "actions": [ "write" ], "resources": [ "doc" ], "notBefore": "0", "expiresAt": "10000", "limit": "100", "canDelegate": true, "depth": "2" }})}
fn child_grant(depth: &str) -> Value { json!({ "type": "grant", "grant": { "id": "child", "subject": "agent", "profile": "finite-v1", "actions": [ "write" ], "resources": [ "doc" ], "notBefore": "0", "expiresAt": "10000", "limit": "50", "canDelegate": true, "depth": depth, "parentId": "g" }})}
fn trigger(rate_limit: &str) -> Value { json!({ "type": "registerTrigger", "trigger": { "id": "t", "revision": "1", "kind": "EVENT", "source": "trusted", "eventType": "doc.changed", "contractId": "c", "action": "START_RUN", "enabled": true, "notBefore": "0", "expiresAt": "10000", "maxAgeMs": "100", "maxConcurrent": "2", "rateLimit": rate_limit, "rateWindowMs": "100", "maxDepth": "3" }})}
// The caller's clock decides what "now" is; the SDK only checks that it is a decimal.fn check(record: Value, now: &str) -> Result<()> { // A fresh snapshot per check: reduce is pure and nothing persists. let scratch = create_mission(&Contract::parse(&contract_text())?)?; // Replay the parent grant so a child grant has a parent to be compared with. let scratch = reduce(&scratch, &Command::from_value(parent_grant())?, now)?; reduce(&scratch, &Command::from_value(record)?, now)?; Ok(())}
fn main() -> Result<()> { // Trusted simulation: no external calls. // Step 1: acceptance. A narrower child grant and a well-formed trigger return without error. check(child_grant("1"), "10")?; check(trigger("10"), "10")?;
// Step 2: refusals. Each record reports its first error. assert_eq!(check(child_grant("2"), "10").unwrap_err().code, "AUTHORITY_DENIED"); assert_eq!(check(trigger("0"), "10").unwrap_err().code, "TRIGGER_LIMIT"); println!("PASS: scratch-check"); Ok(())}import jsonfrom aiws import create_mission, parse_contract, reduce, AiwsError
# Trusted simulation: this example makes no external calls.contract_text = json.dumps({'id': 'c', 'missionId': 'm', 'aiwsEdition': '0.4', 'profile': 'finite-v1', 'budget': '100', 'deadline': '10000', 'criteria': ['review'], 'actions': ['write'], 'resources': ['doc'], 'requiresApproval': False, 'maxAttempts': '2', 'maxAuthorizationAgeMs': '10', 'features': ['triggers']})parent_grant = {'type': 'grant', 'grant': {'id': 'g', 'subject': 'agent', 'profile': 'finite-v1', 'actions': ['write'], 'resources': ['doc'], 'notBefore': '0', 'expiresAt': '10000', 'limit': '100', 'canDelegate': True, 'depth': '2'}}
# The caller's clock decides what "now" is; the SDK only checks that it is a decimal.def check(record, now): # A fresh snapshot per check: reduce is pure and nothing persists. scratch = create_mission(parse_contract(contract_text)) # Replay the parent grant so a child grant has a parent to be compared with. scratch = reduce(scratch, parent_grant, now) reduce(scratch, record, now)
def child_grant(depth): return {'type': 'grant', 'grant': {'id': 'child', 'subject': 'agent', 'profile': 'finite-v1', 'actions': ['write'], 'resources': ['doc'], 'notBefore': '0', 'expiresAt': '10000', 'limit': '50', 'canDelegate': True, 'depth': depth, 'parentId': 'g'}}
def trigger(rate_limit): return {'type': 'registerTrigger', 'trigger': {'id': 't', 'revision': '1', 'kind': 'EVENT', 'source': 'trusted', 'eventType': 'doc.changed', 'contractId': 'c', 'action': 'START_RUN', 'enabled': True, 'notBefore': '0', 'expiresAt': '10000', 'maxAgeMs': '100', 'maxConcurrent': '2', 'rateLimit': rate_limit, 'rateWindowMs': '100', 'maxDepth': '3'}}
def refusal_code(record, now): try: check(record, now) except AiwsError as error: return error.code raise AssertionError('expected a refusal')
# Step 1: acceptance. A narrower child grant and a well-formed trigger return without error.check(child_grant('1'), '10')check(trigger('10'), '10')
# Step 2: refusals. Each record reports its first error.assert refusal_code(child_grant('2'), '10') == 'AUTHORITY_DENIED'assert refusal_code(trigger('0'), '10') == 'TRIGGER_LIMIT'print('PASS: scratch-check')The example checks a narrower child grant and a well-formed trigger, which the reducer accepts, then a child grant that does not reduce its parent’s delegation depth, refused with AUTHORITY_DENIED, and a trigger with a zero rate limit, refused with TRIGGER_LIMIT. Its check function is the recipe; its contract and records are fixed for the demonstration.
Whether a time has already passed is the caller’s clock, not the SDK’s. now must be a decimal string (INVALID_TIME otherwise), but the reducer does not compare a grant’s or trigger’s validity window with now when it registers the record; it requires only that the window is well formed and, for a trigger, that it ends within the contract’s deadline. A definition editor that wants to flag a window that has already ended compares it with its own clock.
The recipe can return these codes. Each is thrown by the reducer arm for that record, and the shared vectors in spec/fixtures.json pin the ones in the Vector column; all three SDKs replay them in the parity tests.
| Code | Raised when | Vector |
|---|---|---|
INVALID_CONTRACT |
The contract has no criteria or no positive attempt limit (parseContract, before the mission exists). |
contract-without-criteria |
AUTHORITY_DENIED |
A grant asks for actions, resources, a limit or an expiry beyond the contract, is not contained by its parent, or has a revoked ancestor. | delegation-cannot-expand |
AUTHORITY_INDETERMINATE |
A grant’s notBefore is not before its expiresAt, so its interval cannot be compared. |
none |
TRIGGER_CONTRACT |
The trigger names another contract, has an empty validity window, or ends after the contract’s deadline. | trigger-outside-contract |
TRIGGER_LIMIT |
maxConcurrent, rateLimit or rateWindowMs is not positive. |
trigger-zero-limit |
TRIGGER_TARGET |
A RESUME_WAIT trigger has no waitId, or another action has one. |
trigger-resume-without-wait |
TRIGGER_CONDITION |
A CONDITION trigger has no filter or condition mode. |
trigger-condition-without-filter |
SCHEDULE_CONFIG |
A SCHEDULED trigger has no schedule, another kind has one, or the schedule’s interval or catch-up bound is out of range. |
trigger-scheduled-without-schedule |
UNSUPPORTED_FEATURE |
The contract’s features lack triggers (for registerTrigger) or graphs (for registerGraph). |
trigger-feature-required |
INVALID_RECORD |
The command does not match the closed wire record. | run-criteria-must-be-non-empty-and-unique |
AUTHORITY_INDETERMINATE has no vector in spec/fixtures.json today. registerGraph can also return the graph-structure codes in Troubleshooting, and any command can return INVALID_TIME, DUPLICATE_ID or NOT_FOUND.
A successful check is not authorization. It shows that the SDK would admit the record into that contract; whether the person editing it may do so is the host’s policy, as in Identity, authority and human approval.
Material-bound action approval
Section titled “Material-bound action approval”Approval covers a run and action fingerprint, with expiry and a use count. The fingerprint includes capability, resource, payload and preconditions. Changing those values requires a new material decision rather than reusing approval for the old action.
Bind approval to action material and use count · Executable control simulation
import assert from 'node:assert/strict';import { createMission, parseContract, parseCommand, reduce } from '@aiws/sdk';
// Trusted simulation: this example makes no external calls.const contract = parseContract(JSON.stringify({ "id": "c", "missionId": "m", "aiwsEdition": "0.4", "profile": "finite-v1", "budget": "100", "deadline": "10000", "criteria": [ "review" ], "actions": [ "write" ], "resources": [ "doc" ], "requiresApproval": true, "maxAttempts": "2", "maxAuthorizationAgeMs": "10", "features": [ "triggers", "graphs" ]}));let state = createMission(contract);
// Step 1state = reduce(state, parseCommand(JSON.stringify({ "type": "startRun", "runId": "r"})), '10');
// Step 2state = reduce(state, parseCommand(JSON.stringify({ "type": "grant", "grant": { "id": "g", "subject": "agent", "profile": "finite-v1", "actions": [ "write" ], "resources": [ "doc" ], "notBefore": "0", "expiresAt": "10000", "limit": "100", "canDelegate": true, "depth": "2" }})), '10');
// Step 3state = reduce(state, parseCommand(JSON.stringify({ "type": "approve", "approval": { "id": "ap", "runId": "r", "approver": "owner", "fingerprint": "sha256:50487a924d1b8f40e5051f0f8d278469acb1cd15d08dbef8f1010e7f54ae9ef0", "expiresAt": "1000", "uses": "1" }})), '10');
// Step 4state = reduce(state, parseCommand(JSON.stringify({ "type": "admit", "runId": "r", "operationId": "o", "attemptId": "a", "grantId": "g", "subject": "agent", "action": { "capability": "write", "resource": "doc", "payload": { "value": 1 }, "preconditions": { "revision": 1 } }, "amount": "10", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true, "approvalId": "ap"})), '10');
// Step 5assert.throws(() => reduce(state, parseCommand(JSON.stringify({ "type": "admit", "runId": "r", "operationId": "o2", "attemptId": "a2", "grantId": "g", "subject": "agent", "action": { "capability": "write", "resource": "doc", "payload": { "value": 1 }, "preconditions": { "revision": 1 } }, "amount": "10", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true, "approvalId": "ap"})), '10'), (error: any) => error.code === 'APPROVAL_CONSUMED');
// Step 6state = reduce(state, parseCommand(JSON.stringify({ "type": "withdrawApproval", "approvalId": "ap"})), '10');
// Step 7assert.throws(() => reduce(state, parseCommand(JSON.stringify({ "type": "dispatch", "attemptId": "a", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true})), '10'), (error: any) => error.code === 'APPROVAL_INVALID');console.log('PASS: approval');use aiws_sdk::*;use serde_json::json;
fn main() -> Result<()> { // Trusted simulation: no external calls. let contract = Contract::parse(&json!({ "id": "c", "missionId": "m", "aiwsEdition": "0.4", "profile": "finite-v1", "budget": "100", "deadline": "10000", "criteria": [ "review" ], "actions": [ "write" ], "resources": [ "doc" ], "requiresApproval": true, "maxAttempts": "2", "maxAuthorizationAgeMs": "10", "features": [ "triggers", "graphs" ]}).to_string())?; let mut state = create_mission(&contract)?;
// Step 1 state = reduce(&state, &Command::from_value(json!({ "type": "startRun", "runId": "r"}))?, "10")?;
// Step 2 state = reduce(&state, &Command::from_value(json!({ "type": "grant", "grant": { "id": "g", "subject": "agent", "profile": "finite-v1", "actions": [ "write" ], "resources": [ "doc" ], "notBefore": "0", "expiresAt": "10000", "limit": "100", "canDelegate": true, "depth": "2" }}))?, "10")?;
// Step 3 state = reduce(&state, &Command::from_value(json!({ "type": "approve", "approval": { "id": "ap", "runId": "r", "approver": "owner", "fingerprint": "sha256:50487a924d1b8f40e5051f0f8d278469acb1cd15d08dbef8f1010e7f54ae9ef0", "expiresAt": "1000", "uses": "1" }}))?, "10")?;
// Step 4 state = reduce(&state, &Command::from_value(json!({ "type": "admit", "runId": "r", "operationId": "o", "attemptId": "a", "grantId": "g", "subject": "agent", "action": { "capability": "write", "resource": "doc", "payload": { "value": 1 }, "preconditions": { "revision": 1 } }, "amount": "10", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true, "approvalId": "ap"}))?, "10")?;
// Step 5 let rejected = Command::from_value(json!({ "type": "admit", "runId": "r", "operationId": "o2", "attemptId": "a2", "grantId": "g", "subject": "agent", "action": { "capability": "write", "resource": "doc", "payload": { "value": 1 }, "preconditions": { "revision": 1 } }, "amount": "10", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true, "approvalId": "ap"})).and_then(|command| reduce(&state, &command, "10")); assert_eq!(rejected.unwrap_err().code, "APPROVAL_CONSUMED");
// Step 6 state = reduce(&state, &Command::from_value(json!({ "type": "withdrawApproval", "approvalId": "ap"}))?, "10")?;
// Step 7 let rejected = Command::from_value(json!({ "type": "dispatch", "attemptId": "a", "authorizationCheckedAt": "10", "policy": "ALLOW", "mandatoryChecksOk": true})).and_then(|command| reduce(&state, &command, "10")); assert_eq!(rejected.unwrap_err().code, "APPROVAL_INVALID"); println!("PASS: approval"); Ok(())}import jsonfrom aiws import create_mission, parse_contract, reduce, AiwsError
# Trusted simulation: this example makes no external calls.contract = parse_contract(json.dumps({'id': 'c', 'missionId': 'm', 'aiwsEdition': '0.4', 'profile': 'finite-v1', 'budget': '100', 'deadline': '10000', 'criteria': ['review'], 'actions': ['write'], 'resources': ['doc'], 'requiresApproval': True, 'maxAttempts': '2', 'maxAuthorizationAgeMs': '10', 'features': ['triggers', 'graphs']}))state = create_mission(contract)
# Step 1state = reduce(state, {'type': 'startRun', 'runId': 'r'}, '10')
# Step 2state = reduce(state, {'type': 'grant', 'grant': {'id': 'g', 'subject': 'agent', 'profile': 'finite-v1', 'actions': ['write'], 'resources': ['doc'], 'notBefore': '0', 'expiresAt': '10000', 'limit': '100', 'canDelegate': True, 'depth': '2'}}, '10')
# Step 3state = reduce(state, {'type': 'approve', 'approval': {'id': 'ap', 'runId': 'r', 'approver': 'owner', 'fingerprint': 'sha256:50487a924d1b8f40e5051f0f8d278469acb1cd15d08dbef8f1010e7f54ae9ef0', 'expiresAt': '1000', 'uses': '1'}}, '10')
# Step 4state = reduce(state, {'type': 'admit', 'runId': 'r', 'operationId': 'o', 'attemptId': 'a', 'grantId': 'g', 'subject': 'agent', 'action': {'capability': 'write', 'resource': 'doc', 'payload': {'value': 1}, 'preconditions': {'revision': 1}}, 'amount': '10', 'authorizationCheckedAt': '10', 'policy': 'ALLOW', 'mandatoryChecksOk': True, 'approvalId': 'ap'}, '10')
# Step 5try: reduce(state, {'type': 'admit', 'runId': 'r', 'operationId': 'o2', 'attemptId': 'a2', 'grantId': 'g', 'subject': 'agent', 'action': {'capability': 'write', 'resource': 'doc', 'payload': {'value': 1}, 'preconditions': {'revision': 1}}, 'amount': '10', 'authorizationCheckedAt': '10', 'policy': 'ALLOW', 'mandatoryChecksOk': True, 'approvalId': 'ap'}, '10') raise AssertionError('expected APPROVAL_CONSUMED')except AiwsError as error: assert error.code == 'APPROVAL_CONSUMED'
# Step 6state = reduce(state, {'type': 'withdrawApproval', 'approvalId': 'ap'}, '10')
# Step 7try: reduce(state, {'type': 'dispatch', 'attemptId': 'a', 'authorizationCheckedAt': '10', 'policy': 'ALLOW', 'mandatoryChecksOk': True}, '10') raise AssertionError('expected APPROVAL_INVALID')except AiwsError as error: assert error.code == 'APPROVAL_INVALID'print('PASS: approval')The SDK binds approval use to logical operations, not every retry attempt. It rechecks current approval validity before dispatch. It does not send an approval notification or authenticate the approver. Store the human decision and relevant evidence in your application, and issue the command through a policy that verifies the human’s authority.
Engine rule: humans control permissions and resource limits
Section titled “Engine rule: humans control permissions and resource limits”The proposed engine requires human approval for any agent-requested change to its permissions or resource limits. Enforce this in the trusted application policy; the low-level SDK contains no built-in concept of an authenticated human. Dynamic graph proposals must not smuggle in new grants, reset budgets or choose an alternate policy revision. Read engine decisions for the adopted design direction.