TypeScript integration
Use Node 24 or newer, as declared by this release. Install the downloaded aiws-sdk-0.3.0.tgz with npm, or run npm ci and npm run build:sdk in the source workspace. The package is ESM. Import core/workflow APIs from @aiws/sdk and infrastructure APIs from @aiws/sdk/runtime, @aiws/sdk/sqlite and @aiws/sdk/observability. This is a native Node library; the SQLite/runtime modules are not browser APIs.
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 } 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) { writeFileSync(join(directory, 'review.txt'), canonical(operation.action.payload), { flag: 'wx' }); return { effect: 'CONFIRMED_APPLIED', actualCost: '3' }; }, async reconcile(operation) { try { return { effect: readFileSync(join(directory, 'review.txt'), 'utf8') === canonical(operation.action.payload) ? 'CONFIRMED_APPLIED' : 'UNKNOWN', actualCost: '3' }; } 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 effect = if std::fs::read_to_string(&self.0).ok() == Some(canonical(&operation["action"]["payload"])?) { "CONFIRMED_APPLIED" } else { "UNKNOWN" }; Ok(Outcome { effect: effect.into(), actual_cost: "3".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::from_value(demo["contract"].clone())?), )?; 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 tempfilefrom pathlib import Pathfrom aiws.core import canonical, assess_successfrom 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'])) 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'),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”The current repository source adds a small protocol-correlation helper after the previously built SDK 0.3.0 binary baseline. 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,reduce,protocolCorrelation,type Contract} from '@aiws/sdk';
const contract:Contract={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');console.log('PASS: protocol-correlation');use aiws_sdk::*;use serde_json::json;
fn main()->Result<()>{ let contract=Contract::from_value(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":[]}))?; 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")); println!("PASS: protocol-correlation"); Ok(())}from aiws import create_mission,reduce,protocol_correlation
contract={'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'print('PASS: protocol-correlation')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”TypeScript annotations do not validate external JSON. Use parseContract and parseCommand on original input text. Preserve amounts and times as strings; convert to BigInt only for local exact calculations, then serialize back to canonical decimal strings. Do not JSON.stringify a BigInt directly.
Authorizer and EffectAdapter callbacks are asynchronous. Await apply, dispatch, reconcile and flushTelemetry, and retain errors at the host boundary. Snapshot and SQLite methods are synchronous. Long-running blocking adapters belong in a suitable worker, and cancellation of a JavaScript promise is not proof that an external effect stopped.
Use AiwsError.code to decide how to report a failure. A REVISION_CONFLICT requires a fresh state/policy decision. An UNKNOWN outcome requires human-controlled reconciliation. Neither should be handled by a generic retry-every-exception wrapper.
The source workspace’s Node 24 examples execute TypeScript directly. Applications may instead compile with their own TypeScript build. The package contains declarations; source example execution and static type checking are separate verification steps.
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 supplied CLI validates contracts and graphs and replays audit records. Its observe projection uses a fixed test timestamp and is not a live monitoring service. Run operationalSummary/operational_summary with a trusted current timestamp in your application instead.