Python integration
Python 3.11 or newer is required. Install the downloaded aiws_sdk-0.5.0-py3-none-any.whl, or run python -m pip install ./packages/python from the repository root. jsonschema is the runtime dependency. This is a native Python implementation and is not published to PyPI in this release.
Runnable coordinator
Section titled “Runnable coordinator”Execute an adapter through the trusted coordinator · Executable local adapter demonstration; fixed demo identity and fixture evidence
import { readFileSync, writeFileSync, mkdtempSync, openSync, writeSync, fsyncSync, closeSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { parseContract, parseCommand, canonical, assessSuccess } from '@aiws/sdk';import { SqliteStore } from '@aiws/sdk/sqlite';import { Coordinator, type EffectAdapter } from '@aiws/sdk/runtime';// A local demonstration. Replace this fixed demo identity with authenticated policy.const demo = JSON.parse(readFileSync('examples/review.json', 'utf8'));const directory = mkdtempSync(join(tmpdir(), 'aiws-review-'));const store = new SqliteStore(join(directory, 'mission.db'), parseContract(canonical(demo.contract)));const coordinator = new Coordinator(store, async () => ({ allowed: true, policy: 'ALLOW', mandatoryChecksOk: true,context:{actor:"demo:operator",policyRevision:"policy:1",decisionClass:"DETERMINISTIC"} }), () => '10');const adapter: EffectAdapter = { async execute(operation) { const file = openSync(join(directory, 'review.txt'), 'wx'); try { writeSync(file, canonical(operation.action.payload)); fsyncSync(file); } finally { closeSync(file); } return { effect: 'CONFIRMED_APPLIED', actualCost: '3' }; }, async reconcile(operation) { try { return readFileSync(join(directory, 'review.txt'), 'utf8') === canonical(operation.action.payload) ? { effect: 'CONFIRMED_APPLIED', actualCost: '3' } : { effect: 'UNKNOWN', actualCost: '0' }; } catch { return { effect: 'UNKNOWN', actualCost: '0' }; } }};try { for (const raw of demo.commands) { const command = parseCommand(canonical(raw)); if (command.type === 'dispatch') await coordinator.dispatch(command.attemptId, adapter, command.nodeId); else await coordinator.apply(command); } console.log(JSON.stringify({ directory, ...assessSuccess(store.snapshot(), 'r') })); writeFileSync(join(directory, 'audit.json'), store.exportAudit());}finally { store.close();}use aiws_sdk::runtime::*;use aiws_sdk::sqlite::SqliteStore;use aiws_sdk::*;use serde_json::{json, Value};struct DemoIdentity;impl Authorizer for DemoIdentity { fn authorize(&mut self, _: &Command, _: &Snapshot, _: &str) -> Result<Authorization> { Ok(Authorization { allowed: true, policy: "ALLOW".into(), mandatory_checks_ok: true, context: json!({"actor":"demo:operator","policyRevision":"policy:1","decisionClass":"DETERMINISTIC"}), }) }}struct Fixed;impl Clock for Fixed { fn now_ms(&self) -> String { "10".into() }}struct LocalReview(std::path::PathBuf);impl EffectAdapter for LocalReview { fn execute(&mut self, operation: &Value, _: &Value) -> Result<Outcome> { use std::io::Write; let mut file = std::fs::OpenOptions::new() .create_new(true) .write(true) .open(&self.0) .map_err(|_| error("FILE_ERROR"))?; file.write_all(canonical(&operation["action"]["payload"])?.as_bytes()) .map_err(|_| error("FILE_ERROR"))?; file.sync_all().map_err(|_| error("FILE_ERROR"))?; Ok(Outcome { effect: "CONFIRMED_APPLIED".into(), actual_cost: "3".into(), }) } fn reconcile(&mut self, operation: &Value, _: &Value) -> Result<Outcome> { let applied = std::fs::read_to_string(&self.0).ok() == Some(canonical(&operation["action"]["payload"])?); let (effect, actual_cost) = if applied { ("CONFIRMED_APPLIED", "3") } else { ("UNKNOWN", "0") }; Ok(Outcome { effect: effect.into(), actual_cost: actual_cost.into(), }) }}fn main() -> std::result::Result<(), Box<dyn std::error::Error>> { let demo: Value = serde_json::from_str(include_str!("../../../../../examples/review.json"))?; let directory = std::env::temp_dir().join(format!( "aiws-review-{}-{}", std::process::id(), std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH)? .as_nanos() )); std::fs::create_dir(&directory)?; let store = SqliteStore::open( directory.join("mission.db").to_str().unwrap(), Some(&Contract::parse(&demo["contract"].to_string())?), )?; let mut c = Coordinator::new(store, DemoIdentity, Fixed); let mut adapter = LocalReview(directory.join("review.txt")); for raw in demo["commands"].as_array().unwrap() { let command = Command::from_value(raw.clone())?; if raw["type"] == "dispatch" { c.dispatch( raw["attemptId"].as_str().unwrap(), &mut adapter, raw["nodeId"].as_str(), )?; } else { c.apply(&command, None)?; } } println!( "{}", json!({"directory":directory,"result":assess_success(&c.store.snapshot()?,"r")?}) ); std::fs::write(directory.join("audit.json"), c.store.export_audit()?)?; Ok(())}"""Run a governed file effect with the independently implemented Python SDK."""import jsonimport osimport tempfilefrom pathlib import Pathfrom aiws.core import canonical, assess_success, parse_contractfrom aiws.sqlite import SqliteStorefrom aiws.runtime import Coordinator
demo = json.loads(Path('examples/review.json').read_text())directory = Path(tempfile.mkdtemp(prefix='aiws-python-review-'))class Adapter: def execute(self, operation, attempt): with (directory/'review.txt').open('x') as out: out.write(canonical(operation['action']['payload'])); out.flush(); os.fsync(out.fileno()) return {'effect':'CONFIRMED_APPLIED','actualCost':'3'} def reconcile(self, operation, attempt): try: effect='CONFIRMED_APPLIED' if (directory/'review.txt').read_text()==canonical(operation['action']['payload']) else 'UNKNOWN' except OSError: effect='UNKNOWN' return {'effect':effect,'actualCost':'3' if effect=='CONFIRMED_APPLIED' else '0'}with SqliteStore(str(directory/'mission.db'),parse_contract(json.dumps(demo['contract']))) as store: # Demo identity only: replace with real authenticated and versioned policy. c=Coordinator(store,lambda *_:dict(allowed=True,policy='ALLOW',mandatoryChecksOk=True,context=dict(actor='demo:operator',policyRevision='policy:1',decisionClass='DETERMINISTIC')),lambda:'10') for command in demo['commands']: if command['type']=='dispatch': c.dispatch(command['attemptId'],Adapter(),command.get('nodeId')) else: c.apply(command) print(json.dumps({'directory':str(directory),**assess_success(store.snapshot(),'r')})) (directory/'audit.json').write_text(store.export_audit())The full program uses a local adapter, fixed trusted demo identity and fixture evidence. Replace those three boundaries with real identity, a scoped adapter and measured validation evidence before using this pattern in production. The tab set includes equivalent Rust, TypeScript and Python implementations.
Protocol-bound workflow correlation
Section titled “Protocol-bound workflow correlation”SDK 0.5.1 includes a small protocol-correlation helper that the earlier 0.3.0 packages lack. It records the exact Praxis binding revision and remote identity alongside the AIWS work/run/operation/attempt identity. It does not implement MCP, A2A or AG-UI transport behavior and always validates authoritative: false.
Correlate governed work with a protocol binding · Executable source-only SDK correlation example; no protocol client or authority is created
import assert from 'node:assert/strict';import {createMission,parseContract,reduce,protocolCorrelation,validateProtocolCorrelation} from '@aiws/sdk';
const contract=parseContract(JSON.stringify({id:'contract:protocol',missionId:'mission:protocol',aiwsEdition:'0.4',profile:'finite-v1',budget:'20',deadline:'1000',criteria:['remote-result-reviewed'],actions:['remote.invoke'],resources:['protocol:mcp'],requiresApproval:false,maxAttempts:'2',maxAuthorizationAgeMs:'100',features:[]}));let state=createMission(contract);state=reduce(state,{type:'startRun',runId:'run:1'},'10');state=reduce(state,{type:'grant',grant:{id:'grant:1',subject:'agent:1',profile:'finite-v1',actions:['remote.invoke'],resources:['protocol:mcp'],notBefore:'0',expiresAt:'1000',limit:'20',canDelegate:false,depth:'0'}},'10');state=reduce(state,{type:'admit',runId:'run:1',operationId:'operation:1',attemptId:'attempt:1',grantId:'grant:1',subject:'agent:1',action:{capability:'remote.invoke',resource:'protocol:mcp',payload:{tool:'echo'},preconditions:{}},amount:'5',authorizationCheckedAt:'10',policy:'ALLOW',mandatoryChecksOk:true},'10');
const correlation=protocolCorrelation( {bindingId:'mcp:official-v2',bindingRevision:'1',protocol:'MCP',protocolVersion:'2026-07-28',manifestDigest:'a'.repeat(64),capabilityDigest:'b'.repeat(64)}, {workOrderId:'mission:protocol',runId:'run:1',taskId:null,operationId:'operation:1',attemptId:'attempt:1',remoteIdentityRef:'mcp:praxis-m9-fixture@1.0.0',remoteOperationId:null});assert.equal(correlation.operation.operationId,'operation:1');assert.equal(correlation.authoritative,false);assert.equal(state.operations['operation:1'].runId,'run:1');
// The record is portable JSON: read back from the wire, it passes the same closed check unchanged.const wire=JSON.parse(JSON.stringify(correlation));assert.deepEqual(validateProtocolCorrelation(wire),correlation);// A record that claims authority, or carries a key the schema does not define, is refused.const refused=(e:any)=>e.code==='INVALID_PROTOCOL_CORRELATION';assert.throws(()=>validateProtocolCorrelation({...wire,authoritative:true}),refused);assert.throws(()=>validateProtocolCorrelation({...wire,approved:true}),refused);console.log(JSON.stringify(correlation));console.log('PASS: protocol-correlation');use aiws_sdk::*;use serde_json::json;
fn main()->Result<()>{ let contract=Contract::parse(&json!({"id":"contract:protocol","missionId":"mission:protocol","aiwsEdition":"0.4","profile":"finite-v1","budget":"20","deadline":"1000","criteria":["remote-result-reviewed"],"actions":["remote.invoke"],"resources":["protocol:mcp"],"requiresApproval":false,"maxAttempts":"2","maxAuthorizationAgeMs":"100","features":[]}).to_string())?; let mut state=create_mission(&contract)?; state=reduce(&state,&Command::from_value(json!({"type":"startRun","runId":"run:1"}))?,"10")?; state=reduce(&state,&Command::from_value(json!({"type":"grant","grant":{"id":"grant:1","subject":"agent:1","profile":"finite-v1","actions":["remote.invoke"],"resources":["protocol:mcp"],"notBefore":"0","expiresAt":"1000","limit":"20","canDelegate":false,"depth":"0"}}))?,"10")?; state=reduce(&state,&Command::from_value(json!({"type":"admit","runId":"run:1","operationId":"operation:1","attemptId":"attempt:1","grantId":"grant:1","subject":"agent:1","action":{"capability":"remote.invoke","resource":"protocol:mcp","payload":{"tool":"echo"},"preconditions":{}},"amount":"5","authorizationCheckedAt":"10","policy":"ALLOW","mandatoryChecksOk":true}))?,"10")?;
let correlation=protocol_correlation( ProtocolBindingRef{binding_id:"mcp:official-v2".into(),binding_revision:"1".into(),protocol:"MCP".into(),protocol_version:"2026-07-28".into(),manifest_digest:"a".repeat(64),capability_digest:"b".repeat(64)}, ProtocolOperationRef{work_order_id:"mission:protocol".into(),run_id:"run:1".into(),task_id:None,operation_id:"operation:1".into(),attempt_id:"attempt:1".into(),remote_identity_ref:Some("mcp:praxis-m9-fixture@1.0.0".into()),remote_operation_id:None} ).map_err(|code|AiwsError{code})?; assert_eq!(correlation.operation.operation_id,"operation:1"); assert!(!correlation.authoritative); assert_eq!(state.as_value()["operations"]["operation:1"]["runId"],json!("run:1"));
// The record is portable JSON: read back from the wire, it passes the same closed check unchanged. let wire=serde_json::to_value(&correlation).map_err(|_|AiwsError{code:"ENCODE".into()})?; assert_eq!(ProtocolCorrelation::from_value(wire.clone()).map_err(|code|AiwsError{code})?,correlation); // A record that claims authority, or carries a key the schema does not define, is refused. for (key,value) in [("authoritative",json!(true)),("approved",json!(true))]{ let mut claim=wire.clone(); claim[key]=value; assert_eq!(ProtocolCorrelation::from_value(claim),Err("INVALID_PROTOCOL_CORRELATION".to_string())); } println!("{wire}"); println!("PASS: protocol-correlation"); Ok(())}import jsonfrom aiws import create_mission,parse_contract,reduce,protocol_correlation,validate_protocol_correlation,ProtocolCorrelationError
contract=parse_contract(json.dumps({'id':'contract:protocol','missionId':'mission:protocol','aiwsEdition':'0.4','profile':'finite-v1','budget':'20','deadline':'1000','criteria':['remote-result-reviewed'],'actions':['remote.invoke'],'resources':['protocol:mcp'],'requiresApproval':False,'maxAttempts':'2','maxAuthorizationAgeMs':'100','features':[]}))state=create_mission(contract)state=reduce(state,{'type':'startRun','runId':'run:1'},'10')state=reduce(state,{'type':'grant','grant':{'id':'grant:1','subject':'agent:1','profile':'finite-v1','actions':['remote.invoke'],'resources':['protocol:mcp'],'notBefore':'0','expiresAt':'1000','limit':'20','canDelegate':False,'depth':'0'}},'10')state=reduce(state,{'type':'admit','runId':'run:1','operationId':'operation:1','attemptId':'attempt:1','grantId':'grant:1','subject':'agent:1','action':{'capability':'remote.invoke','resource':'protocol:mcp','payload':{'tool':'echo'},'preconditions':{}},'amount':'5','authorizationCheckedAt':'10','policy':'ALLOW','mandatoryChecksOk':True},'10')
correlation=protocol_correlation( {'bindingId':'mcp:official-v2','bindingRevision':'1','protocol':'MCP','protocolVersion':'2026-07-28','manifestDigest':'a'*64,'capabilityDigest':'b'*64}, {'workOrderId':'mission:protocol','runId':'run:1','taskId':None,'operationId':'operation:1','attemptId':'attempt:1','remoteIdentityRef':'mcp:praxis-m9-fixture@1.0.0','remoteOperationId':None})assert correlation['operation']['operationId']=='operation:1'assert correlation['authoritative'] is Falseassert state['operations']['operation:1']['runId']=='run:1'
# The record is portable JSON: read back from the wire, it passes the same closed check unchanged.wire=json.loads(json.dumps(correlation))assert validate_protocol_correlation(wire)==correlation# A record that claims authority, or carries a key the schema does not define, is refused.for claim in ({'authoritative':True},{'approved':True}): try: validate_protocol_correlation({**wire,**claim}) raise AssertionError('accepted '+json.dumps(claim)) except ProtocolCorrelationError as error: assert error.code=='INVALID_PROTOCOL_CORRELATION'print(json.dumps(correlation))print('PASS: protocol-correlation')In current source, after the 0.4.0 archives, validate_protocol_correlation reports the same error codes as TypeScript and Rust, in the same order, and a remote reference is bounded in UTF-8 bytes; see the API mapping.
Use official protocol SDKs and the Praxis adapters for wire behavior. Use this helper only for portable correlation in application code, evidence indexes or integration metadata.
Integration details
Section titled “Integration details”Core records are validated dictionaries, not Pydantic models or mutable workflow classes. Import parse_contract, parse_command, reduce and AiwsError from aiws or aiws.core, and use aiws.runtime, aiws.sqlite and aiws.observability for the runtime boundaries. The package contains these modules:
| Module | Contents |
|---|---|
aiws |
Re-exports the core parsers and reducer, validate_graph, diagnose_graph, ready_nodes, due_slots and the protocol-correlation helpers |
aiws.core |
Core records and finite-v1 semantics; reducers never perform external effects |
aiws.workflow |
Trigger admission, fixed-interval scheduling and graph checkpoints |
aiws.runtime |
Coordinator and the EffectAdapter protocol |
aiws.sqlite |
SqliteStore, diagnostics, leased telemetry delivery and import_audit |
aiws.observability |
Correlated audit metadata, OTLP projections, metrics and alerts (observability) |
aiws.handoff, aiws.handoff_records, aiws.handoff_store |
The opt-in handoff profile: journal semantics, checked records, and the SQLite store with local artifacts (handoffs) |
aiws.limits, aiws.limits_store |
Opt-in nested accounting and its SQLite ledger (budgets) |
aiws.dynamic_controls, aiws.dynamic_types |
The aiws-dynamic-controls/1 client and its generated types (dynamic controls) |
aiws.readiness, aiws.readiness_types, aiws.readiness_types_v1 |
Advisory readiness records, with generated types for the current and the frozen readiness versions (readiness) |
aiws.access_policy, aiws.access_policy_types |
The access-policy contract codec and its generated types (access policy) |
aiws.protocol |
Protocol-correlation records |
aiws.cli |
The aiws-python command line |
The authorizer is a callable returning allowed, policy, mandatoryChecksOk and context. Current source names its shape aiws.runtime.Authorizer, a Protocol, names the clock aiws.runtime.Clock, and names the ledger authorizer aiws.limits_store.LimitAuthorizer; the coordinators accept plain functions of those shapes, as before. The clock returns str(time.time_ns() // 1_000_000) in a real host. Demo clocks are deterministic test inputs and must not become production authorization clocks. Adapter execute and reconcile return dictionaries containing effect and actualCost.
The SDK is synchronous. If an async web framework is used, execute blocking work in a suitable worker with its own connection lifecycle. Do not move an existing SQLite connection freely between threads; create and use it under the host’s defined ownership rules. A with SqliteStore(…) block closes the connection, but that does not imply cancellation of an external job.
Python integers are unbounded, but the cross-language wire format is deliberately bounded. Do not bypass the safe-number rule just because Python can decode a large integer. Costs and timestamps remain canonical decimal strings. Catch AiwsError and inspect code at an integration boundary; never turn a generic Exception into automatic permission to retry an external action.
Diagnostics and next steps
Section titled “Diagnostics and next steps”Use the API mapping to translate native calls without changing camelCase wire keys. Use observability for exporter configuration and recovery for interrupted effects. All examples are included as individual executable source files under examples/guide/.
The package’s aiws-python CLI offers aiws-python validate FILE for a contract, aiws-python graph FILE for a graph, aiws-python replay FILE for an audit export, aiws-python fixtures FILE for a shared scenario file, and aiws-python snapshot FILE and aiws-python observe FILE for a SQLite mission database. The source build, not the 0.4.0 archives, also provides aiws-python agents sync, which copies the version-matched agent docs pack into .aiws/agent-docs/python/, gitignored through .aiws/.gitignore, writes the Python line of the managed AGENTS.md block beside any other languages’ lines, and adds @AGENTS.md to an existing CLAUDE.md, and aiws-python agents check, which exits 1 when the copied pack, the block’s Python line or the synced skills are missing or differ from the installed SDK version. Sync also installs the aiws skills shipped beside the pack in the package’s aiws/skills/ folder: it copies each aiws-* skill folder into .claude/skills/ and .agents/skills/, writes a .gitignore containing * inside each copied folder, so the copies are never committed and your own skills beside them are untouched, and records the SDK version in the folder’s .aiws-skill.json. When the installed skills are at another version and another language’s synced pack in .aiws/agent-docs/ also differs from this SDK, sync still syncs the Python pack, leaves the skills unchanged and prints one stderr line naming both versions; aiws-python agents check exits 1 until the skills match. The installed skills’ version is read from the stamps of the aiws-* skills present in either folder, so the rule holds when this SDK ships a skill the installed set lacks. Sync refuses with FILE_ERROR, before writing anything, when .aiws, AGENTS.md, .claude, .agents, their skills folders or a synced skill folder is a symlink or junction. Both take an optional project directory; without one they use the working directory or the nearest directory above it that has an AGENTS.md, a .aiws folder or a pyproject.toml depending on aiws-sdk. When that project’s pack has drifted, the other commands print one line on stderr, except when CI is set, and keep their exit status. The file commands’ output, error codes and exit statuses match the TypeScript and Rust CLIs (command-line tools). In the 0.4.0 archives its usage text comes from argparse, and its error record has a space after the colon. Its observe projection uses a fixed test timestamp and is not a live monitoring service. Run operational_summary with a trusted current timestamp in your application instead.