Skip to content

Wire a protocol call into an SDK host

A protocol such as MCP or A2A gives a host connectivity: a way to call a remote tool or delegate a task, and a way for the remote side to report back. It never gives the host authority. The recipes on this page show the SDK half of that rule, with released SDK 0.5.1 APIs and the source-only aiws-protocol-correlation/1 helper (capability row “Cross-language protocol correlation helper”). They follow spec/engine-v1/PROTOCOL-BINDINGS.md §2: a protocol adapter never grants authority, approves, marks verification PASS, accepts a deliverable or turns an UNKNOWN effect into success without reconciliation evidence.

The recipes use no real MCP or A2A client. Each injects a client port and runs it against a local stand-in, marked “replace before deployment”, so the same code runs under docs:examples with no network. The official protocol SDKs remain the wire implementations; the Praxis protocol bindings are engine source that no host wires yet, and they are not covered here.

An aiws-protocol-correlation/1 record ties one AIWS operation and attempt to the exact binding revision, protocol version and manifest and capability digests it ran under, and to the remote identity and remote operation ID when they are known. Its authoritative field is always the literal false. The record is closed: each SDK refuses an unknown key or a missing one, and checks the result against the shared schema in spec/protocol-correlation-v1 before returning it. The recipe builds a record for an admitted operation, reads it back from JSON, and shows that a record claiming authority, or carrying an approved key, is refused.

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');

A remote tool call is an external effect, so it goes through an effect adapter like any other: the coordinator commits DISPATCHED first, and the adapter reports CONFIRMED_APPLIED, CONFIRMED_NOT_APPLIED or UNKNOWN.

  • An injected client port. The adapter receives the client; it has a mutating callTool and two read-only calls, listTools and readBack.
  • Re-discovery before each call. The adapter lists the server’s tools again and compares their digest with the reviewed capability digest (PROTOCOL-BINDINGS §8.1). A changed digest blocks before the call is sent, which is the one case where the adapter knows nothing was applied.
  • UNKNOWN on a timeout or a transport error. Neither shows whether the server ran the tool. A tool error result is UNKNOWN too, because it carries no proof that nothing changed.
  • A read-only reconcile by read-back. reconcile looks the idempotency key up in the server’s ticket index and never calls the tool. A recorded key proves the call applied; anything else stays UNKNOWN for a human.
  • The correlation record stored with the evidence. Every observation the adapter makes is appended to the host’s evidence log with its correlation record, including the remote ticket ID once read-back finds it.
  • Remote data stays data. The stand-in server marks its own ticket approved: true. The host stores that in the evidence and nothing else: the mission has no approval, no assessment, and a worker that tried to turn it into an approve command would be refused by the deny-by-default authorizer.

Call a protocol tool through an effect adapter: injected client port, correlated evidence, UNKNOWN on a timeout, read-back reconcile · Executable local adapter demonstration; SDK 0.4.0 APIs; a simulated MCP server and identity, no protocol client or real transport

import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { canonical, parseCommand, parseContract, protocolCorrelation, type ProtocolBindingRef, type ProtocolCorrelation } from '@aiws/sdk';
import { SqliteStore } from '@aiws/sdk/sqlite';
import { Coordinator, type Authorizer, type EffectAdapter, type Outcome } from '@aiws/sdk/runtime';
/*
* Operation contract (STANDARD E-01, E-04) for `ticket.create` on `protocol:mcp:tickets`, the ToolCallAdapter below.
* - Effect: the remote MCP tool `create_ticket` opens one ticket. Idempotent under the key: the server stores the
* key with the ticket in one transaction and returns the same ticket for a repeated key.
* - Binding: the reviewed binding revision. Before each call the adapter lists the server's tools again and compares
* their digest with the reviewed capability digest (PROTOCOL-BINDINGS 8.1). A changed digest blocks before the
* call is sent, so nothing was applied.
* - Timeout: 30 seconds. A tool result reports applied, at a cost of 2. A timeout, a transport error or a tool error
* result proves nothing: the outcome is UNKNOWN.
* - Reconciliation: read-only `readBack` of the key from the server's ticket index. A ticket recorded under the key
* proves the call applied. Anything else, an absent key included, stays UNKNOWN for a human.
* - Evidence: every observation is stored with its aiws-protocol-correlation/1 record. What the server returns is
* data: an `approved: true` in a result approves nothing, verifies nothing and accepts nothing.
*/
interface Tool { name: string; inputSchema: Record<string, unknown> }
type ToolReply = { timedOut: true } | { isError: boolean; structuredContent: Record<string, unknown> };
/** Own-property check on the client's plain reply object, never `in`. */
const timedOut = (reply: ToolReply): reply is { timedOut: true } => Object.hasOwn(reply, 'timedOut');
type ReadBack = { recorded: true; ticketId: string; content: Record<string, unknown> } | { recorded: false };
/** The client port, injected by the host: an MCP client session in production, a fake server in tests. */
interface ToolClient {
/** Read-only: lists the server's tools as it declares them now. */
listTools(): Promise<Tool[]>;
callTool(request: { name: string; arguments: unknown; idempotencyKey: string; timeoutMs: number }): Promise<ToolReply>;
/** Read-only: looks the key up in the server's ticket index; never calls a tool. */
readBack(idempotencyKey: string): Promise<ReadBack>;
}
interface Evidence { id: string; correlation: ProtocolCorrelation; observation: string; data: Record<string, unknown> | null }
/** The evidence port: an append-only store the host keeps beside the mission store. It grants nothing. */
interface EvidenceLog { append(entry: Evidence): void }
const sha256 = (value: unknown): string => createHash('sha256').update(canonical(value)).digest('hex');
const idempotencyKey = (missionId: string, operation: Readonly<Record<string, any>>): string =>
`${missionId}/${operation.id}/${operation.fingerprint}`;
const applied: Outcome = { effect: 'CONFIRMED_APPLIED', actualCost: '2' };
const notApplied: Outcome = { effect: 'CONFIRMED_NOT_APPLIED', actualCost: '0' };
const unknown: Outcome = { effect: 'UNKNOWN', actualCost: '0' };
class ToolCallAdapter implements EffectAdapter {
private missionId: string;
private binding: ProtocolBindingRef;
private remoteIdentityRef: string;
private client: ToolClient;
private evidence: EvidenceLog;
constructor(missionId: string, binding: ProtocolBindingRef, remoteIdentityRef: string, client: ToolClient, evidence: EvidenceLog) {
this.missionId = missionId; this.binding = binding; this.remoteIdentityRef = remoteIdentityRef; this.client = client; this.evidence = evidence;
}
private record(operation: Readonly<Record<string, any>>, attempt: Readonly<Record<string, any>>, observation: string, data: Record<string, unknown> | null, remoteOperationId: string | null): void {
const correlation = protocolCorrelation(this.binding, { workOrderId: this.missionId, runId: operation.runId, taskId: null, operationId: operation.id, attemptId: attempt.id, remoteIdentityRef: this.remoteIdentityRef, remoteOperationId });
this.evidence.append({ id: `evidence:${attempt.id}:${observation}`, correlation, observation, data });
}
async execute(operation: Readonly<Record<string, any>>, attempt: Readonly<Record<string, any>>): Promise<Outcome> {
let reply: ToolReply;
try {
if (sha256(await this.client.listTools()) !== this.binding.capabilityDigest) {
this.record(operation, attempt, 'CAPABILITY_CHANGED', null, null);
return notApplied; // Blocked before the call was sent: nothing reached the server.
}
reply = await this.client.callTool({ name: 'create_ticket', arguments: operation.action.payload, idempotencyKey: idempotencyKey(this.missionId, operation), timeoutMs: 30_000 });
} catch {
this.record(operation, attempt, 'TRANSPORT_ERROR', null, null);
return unknown; // A thrown transport error does not show whether the server ran the tool.
}
if (timedOut(reply)) {
this.record(operation, attempt, 'TIMED_OUT', null, null);
return unknown; // A timeout never proves the call did not happen.
}
this.record(operation, attempt, reply.isError ? 'TOOL_ERROR' : 'RESULT', reply.structuredContent, null);
return reply.isError ? unknown : applied; // A tool error result carries no proof that nothing changed.
}
async reconcile(operation: Readonly<Record<string, any>>, attempt: Readonly<Record<string, any>>): Promise<Outcome> {
let found: ReadBack;
try {
found = await this.client.readBack(idempotencyKey(this.missionId, operation));
} catch {
return unknown;
}
if (!found.recorded) return unknown; // An absent key does not prove that a late call will not land.
this.record(operation, attempt, 'READ_BACK', found.content, found.ticketId);
return applied;
}
}
// ---- A local MCP server stand-in that runs the tool and then loses the response: replace before deployment. ----
class LossyTicketServer implements ToolClient {
tools: Tool[] = [{ name: 'create_ticket', inputSchema: { type: 'object', required: ['title'] } }];
calls = 0;
tickets = new Map<string, { ticketId: string; content: Record<string, unknown> }>();
async listTools(): Promise<Tool[]> { return structuredClone(this.tools); }
async callTool(request: { arguments: unknown; idempotencyKey: string }): Promise<ToolReply> {
this.calls++;
if (!this.tickets.has(request.idempotencyKey)) {
// The remote side marks its own ticket approved. That is the server's data, not an AIWS approval.
this.tickets.set(request.idempotencyKey, { ticketId: `ticket:T-${this.tickets.size + 1}`, content: { ticket: `T-${this.tickets.size + 1}`, approved: true, request: request.arguments } });
}
return { timedOut: true }; // Applied, but the response never arrived.
}
async readBack(key: string): Promise<ReadBack> {
const ticket = this.tickets.get(key);
return ticket ? { recorded: true, ...structuredClone(ticket) } : { recorded: false };
}
}
// The reviewed binding: its digests are computed from the manifest and tool list a human reviewed.
const server = new LossyTicketServer();
const binding: ProtocolBindingRef = { bindingId: 'mcp:tickets', bindingRevision: '1', protocol: 'MCP', protocolVersion: '2026-07-28',
manifestDigest: sha256({ bindingId: 'mcp:tickets', protocol: 'MCP', protocolVersion: '2026-07-28', endpointRef: 'endpoint:tickets' }), capabilityDigest: sha256(server.tools) };
const log: Evidence[] = [];
const adapter = new ToolCallAdapter('m', binding, 'mcp:tickets-server@3.1.0', server, { append: (entry) => log.push(structuredClone(entry)) });
// Simulated identity: replace before deployment. Deny by default; each rule names the one session it allows.
type Session = { actor: string; kind: 'HUMAN' | 'RULE' | 'AGENT' };
const RUNNER: Session = { actor: 'host:runner', kind: 'RULE' }, AGENT: Session = { actor: 'agent:triage', kind: 'AGENT' };
const OWNER: Session = { actor: 'human:owner', kind: 'HUMAN' }, WORKER: Session = { actor: 'host:worker-1', kind: 'RULE' };
function permits(session: Session, c: any): boolean {
switch (c.type) {
case 'startRun': return session === RUNNER;
case 'grant': return session === OWNER;
case 'admit': return session === AGENT && c.subject === AGENT.actor && c.action.capability === 'ticket.create';
case 'dispatch': case 'settle': return session === WORKER;
default: return false; // approve, revokeGrant, verify, accept and the rest: never from this host's rules.
}
}
const authorizerFor = (session: Session): Authorizer => async (command) => {
const allowed = permits(session, command);
return { allowed, policy: allowed ? 'ALLOW' : 'DENY', mandatoryChecksOk: true, context: { actor: session.actor, policyRevision: 'policy:1', decisionClass: session.kind === 'HUMAN' ? 'HUMAN' : 'DETERMINISTIC' } };
};
const contract = parseContract(canonical({ id: 'c', missionId: 'm', aiwsEdition: '0.4', profile: 'finite-v1', budget: '100', deadline: '10000', criteria: ['ticket-reviewed'], actions: ['ticket.create'], resources: ['protocol:mcp:tickets'], requiresApproval: false, maxAttempts: '2', maxAuthorizationAgeMs: '10', features: [] }));
const store = new SqliteStore(join(mkdtempSync(join(tmpdir(), 'aiws-protocol-call-')), 'mission.db'), contract);
const as = (session: Session) => new Coordinator(store, authorizerFor(session), () => '10');
const admit = (operationId: string, attemptId: string) => as(AGENT).apply(parseCommand(canonical({ type: 'admit', runId: 'r', operationId, attemptId, grantId: 'g', subject: AGENT.actor,
action: { capability: 'ticket.create', resource: 'protocol:mcp:tickets', payload: { title: 'Guard missing on press 4' }, preconditions: {} }, amount: '10', authorizationCheckedAt: '10', policy: 'ALLOW', mandatoryChecksOk: true })));
try {
await as(RUNNER).apply(parseCommand(canonical({ type: 'startRun', runId: 'r' })));
await as(OWNER).apply(parseCommand(canonical({ type: 'grant', grant: { id: 'g', subject: AGENT.actor, profile: 'finite-v1', actions: ['ticket.create'], resources: ['protocol:mcp:tickets'], notBefore: '0', expiresAt: '10000', limit: '100', canDelegate: false, depth: '0' } })));
await admit('o1', 'a1');
let state = await as(WORKER).dispatch('a1', adapter);
assert.equal(state.attempts.a1.status, 'UNKNOWN'); // The tool ran, but the timeout proves nothing.
assert.equal(state.reserved, '10'); // UNKNOWN keeps the reservation.
state = await as(WORKER).reconcile('a1', adapter); // Read-only: reads the key back, never calls the tool.
assert.equal(state.operations.o1.effect, 'CONFIRMED_APPLIED');
assert.equal(state.spent, '2');
assert.equal(server.calls, 1); // Called exactly once.
// The server's `approved: true` is stored as evidence data. It is not an approval, a PASS or an acceptance.
assert.equal(log[1].data?.approved, true);
assert.equal(Object.keys(state.approvals).length, 0);
assert.equal(Object.keys(state.assessments).length, 0);
// A host that turned it into an approve command would be refused: no rule lets a worker approve.
await assert.rejects(as(WORKER).apply(parseCommand(canonical({ type: 'approve', approval: { id: 'ap', runId: 'r', approver: WORKER.actor, fingerprint: state.operations.o1.fingerprint, expiresAt: '1000', uses: '1' } }))), (e: any) => e.code === 'AUTHORITY_DENIED');
// The server changes its tool declaration. The next call is blocked before it is sent.
server.tools[0].inputSchema = { type: 'object', required: ['title', 'assignee'] };
await admit('o2', 'a2');
state = await as(WORKER).dispatch('a2', adapter);
assert.equal(state.operations.o2.effect, 'CONFIRMED_NOT_APPLIED');
assert.equal(server.calls, 1);
// A transport that fails reports UNKNOWN: classification checked on a scripted client, outside the coordinator.
const failing: ToolClient = { listTools: async () => [{ name: 'create_ticket', inputSchema: { type: 'object', required: ['title'] } }], callTool: async () => { throw new Error('connection reset'); }, readBack: async () => { throw new Error('connection reset'); } };
const scratch: Evidence[] = [];
const probe = new ToolCallAdapter('m', binding, 'mcp:tickets-server@3.1.0', failing, { append: (entry) => scratch.push(entry) });
assert.equal((await probe.execute(state.operations.o1, state.attempts.a1)).effect, 'UNKNOWN');
assert.equal((await probe.reconcile(state.operations.o1, state.attempts.a1)).effect, 'UNKNOWN');
assert.deepEqual(log.map((e) => e.observation), ['TIMED_OUT', 'READ_BACK', 'CAPABILITY_CHANGED']);
for (const entry of log) console.log(JSON.stringify(entry.correlation));
console.log('PASS: protocol-call');
} finally {
store.close();
}

Remote completion as an EXTERNAL_RESPONSE resume

Section titled “Remote completion as an EXTERNAL_RESPONSE resume”

When the remote side reports back later, its completion resumes a wait through an EXTERNAL_RESPONSE trigger. The host stored one correlation record per delegated attempt, keyed by the remote task ID, and correlated the wait to the current attempt’s record. An inbound request then passes these steps in order:

  1. Authenticate the sender before reading the body. The event source comes from the authenticated principal, never from a source field in the body.
  2. Find the stored record for the remote task. A remote task ID the host never delegated is refused, and a remote ID never becomes a local one.
  3. Fire the trigger through the coordinator, whose authorizer allows fireTrigger only from that principal and allows nothing else to an inbound request.

The SDK then refuses a result for a superseded attempt (WAIT_CORRELATION), a result older than the trigger’s maxAgeMs (EVENT_EXPIRED) and a changed redelivery under the same event ID (EVENT_ID_CONFLICT). An identical redelivery is absorbed by its event ID. The completion resumes the wait and does nothing more: its approved: true approves nothing, verifies nothing and settles no attempt. The operation’s effect still comes from its adapter or a read-only reconcile.

Resume on a correlated remote completion: authenticated inbound request, event-ID idempotency, stale and superseded results refused · Executable local control demonstration; SDK 0.4.0 APIs; simulated peer authentication, scripted clock, no protocol client or real transport

import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { AiwsError, canonical, parseCommand, parseContract, parseStrict, protocolCorrelation, type ProtocolBindingRef, type ProtocolCorrelation, type Snapshot } from '@aiws/sdk';
import { SqliteStore } from '@aiws/sdk/sqlite';
import { Coordinator, type Authorizer, type Clock } from '@aiws/sdk/runtime';
/*
* Remote completion of the A2A task the host delegated for operation `o1` through the reviewed binding `a2a:reviewer`.
* - The host stored one aiws-protocol-correlation/1 record per delegated attempt, keyed by the remote task ID. The
* task of attempt a1 was superseded when the host delegated attempt a2, so only a2's completion may resume the run.
* - Inbound: the remote agent posts its completion to the host. The host authenticates the sender first and takes the
* event source from the authenticated principal, never from the body.
* - The completion becomes a fireTrigger on an EXTERNAL_RESPONSE trigger, correlated to the current attempt's record.
* The SDK refuses a stale event (EVENT_EXPIRED), a result for any other attempt (WAIT_CORRELATION) and a changed
* redelivery (EVENT_ID_CONFLICT); an identical redelivery is absorbed by its event ID.
* - The completion's content is data: its `approved: true` approves nothing, verifies nothing and settles no attempt.
*/
const sha256 = (value: unknown): string => createHash('sha256').update(canonical(value)).digest('hex');
const binding: ProtocolBindingRef = { bindingId: 'a2a:reviewer', bindingRevision: '1', protocol: 'A2A', protocolVersion: '1.0',
manifestDigest: sha256({ bindingId: 'a2a:reviewer', protocol: 'A2A', protocolVersion: '1.0', endpointRef: 'endpoint:reviewer' }), capabilityDigest: sha256({ skills: ['review'] }) };
const delegated = (attemptId: string, remoteTaskId: string): ProtocolCorrelation => protocolCorrelation(binding,
{ workOrderId: 'm', runId: 'r', taskId: null, operationId: 'o1', attemptId, remoteIdentityRef: 'a2a:reviewer-agent@2.0.0', remoteOperationId: remoteTaskId });
/** The records the host stored when it delegated each attempt, by remote task ID. A remote ID is never a local one. */
const correlations = new Map<string, ProtocolCorrelation>([['a2a-task:7', delegated('a1', 'a2a-task:7')], ['a2a-task:9', delegated('a2', 'a2a-task:9')]]);
/** The wait correlation for one delegated attempt: a completion for any other attempt cannot match it. */
const completionCorrelation = (record: ProtocolCorrelation): string => `${record.operation.operationId}/${record.operation.attemptId}`;
// Simulated identity: replace before deployment. A deployed host verifies the peer's certificate or signature; here
// the transport's verified peer name maps to the one event source the trigger accepts.
type Session = { actor: string; kind: 'RULE' | 'SERVICE' };
const RUNNER: Session = { actor: 'host:runner', kind: 'RULE' };
const peers = new Map<string, Session>([['mtls:reviewer-agent', { actor: 'a2a:reviewer', kind: 'SERVICE' }]]);
const authenticate = (peer: string): Session | null => peers.get(peer) ?? null;
function permits(session: Session, c: any): boolean {
switch (c.type) {
case 'startRun': case 'registerTrigger': case 'wait': case 'transition': case 'join': return session === RUNNER;
case 'fireTrigger': return session.kind === 'SERVICE' && c.event.source === session.actor;
default: return false; // approve, settle, verify, accept and the rest: never from an inbound request.
}
}
const authorizerFor = (session: Session): Authorizer => async (command) => {
const allowed = permits(session, command);
return { allowed, policy: allowed ? 'ALLOW' : 'DENY', mandatoryChecksOk: true, context: { actor: session.actor, policyRevision: 'policy:1', decisionClass: 'DETERMINISTIC' } };
};
let nowMs = 20n;
const clock: Clock = () => nowMs.toString(); // Scripted: a deployed host injects its trusted UTC clock.
const contract = parseContract(canonical({ id: 'c', missionId: 'm', aiwsEdition: '0.4', profile: 'finite-v1', budget: '100', deadline: '10000', criteria: ['review-complete'], actions: ['review.request'], resources: ['protocol:a2a:reviewer'], requiresApproval: false, maxAttempts: '2', maxAuthorizationAgeMs: '10', features: ['triggers'] }));
const store = new SqliteStore(join(mkdtempSync(join(tmpdir(), 'aiws-protocol-completion-')), 'mission.db'), contract);
const as = (session: Session) => new Coordinator(store, authorizerFor(session), clock);
interface InboundRequest { peer: string; body: string }
/** The inbound endpoint: authenticate, find the stored record for the remote task, then fire the trigger. */
async function receive(request: InboundRequest): Promise<Snapshot> {
const session = authenticate(request.peer);
if (session === null) throw new AiwsError('UNAUTHENTICATED'); // Refused before the body is read.
const body = parseStrict(request.body) as Record<string, any>;
const record = typeof body.taskId === 'string' ? correlations.get(body.taskId) : undefined;
if (record === undefined) throw new AiwsError('UNKNOWN_REMOTE_TASK');
const event = { id: body.eventId, source: session.actor, type: 'task.completed', occurredAt: body.occurredAt, data: body.result, depth: '0', correlation: completionCorrelation(record) };
return as(session).apply(parseCommand(canonical({ type: 'fireTrigger', triggerId: 't', runId: record.operation.runId, event })));
}
const completion = (peer: string, taskId: string, eventId: string, occurredAt: string, result: Record<string, unknown>): InboundRequest =>
({ peer, body: JSON.stringify({ taskId, eventId, occurredAt, result, source: 'a2a:reviewer' }) });
const refused = (code: string) => (e: any) => e.code === code;
try {
for (const command of [
{ type: 'startRun', runId: 'r' },
{ type: 'registerTrigger', trigger: { id: 't', revision: '1', kind: 'EXTERNAL_RESPONSE', source: 'a2a:reviewer', eventType: 'task.completed', contractId: 'c', action: 'RESUME_WAIT', waitId: 'w', enabled: true, notBefore: '0', expiresAt: '10000', maxAgeMs: '100', maxConcurrent: '1', rateLimit: '10', rateWindowMs: '1000', maxDepth: '0' } },
{ type: 'wait', runId: 'r', waitId: 'w', correlation: completionCorrelation(correlations.get('a2a-task:9')!), deadline: '5000', kind: 'EXTERNAL' },
{ type: 'transition', runId: 'r', to: 'WAITING' },
]) await as(RUNNER).apply(parseCommand(canonical(command)));
// A sender the host cannot authenticate never reaches the trigger, whatever source its body claims.
await assert.rejects(receive(completion('mtls:unknown', 'a2a-task:9', 'e0', '15', { verdict: 'done' })), refused('UNAUTHENTICATED'));
// The superseded attempt's late result is refused: its correlation is not the wait's.
await assert.rejects(receive(completion('mtls:reviewer-agent', 'a2a-task:7', 'e1', '15', { verdict: 'done' })), refused('WAIT_CORRELATION'));
// A remote task the host never delegated has no stored record.
await assert.rejects(receive(completion('mtls:reviewer-agent', 'a2a-task:99', 'e2', '15', { verdict: 'done' })), refused('UNKNOWN_REMOTE_TASK'));
// A result older than the trigger's maxAgeMs is stale.
nowMs = 300n;
await assert.rejects(receive(completion('mtls:reviewer-agent', 'a2a-task:9', 'e3', '150', { verdict: 'done' })), refused('EVENT_EXPIRED'));
// The current attempt's fresh result resumes the wait.
const current = completion('mtls:reviewer-agent', 'a2a-task:9', 'e4', '290', { verdict: 'done', approved: true });
let state = await receive(current);
assert.equal(state.waits.w.status, 'SATISFIED');
// A redelivery with the same event ID and content is absorbed; a changed one is refused.
state = await receive(current);
assert.equal(Object.keys(state.receipts).length, 1);
await assert.rejects(receive(completion('mtls:reviewer-agent', 'a2a-task:9', 'e4', '290', { verdict: 'rejected' })), refused('EVENT_ID_CONFLICT'));
state = await as(RUNNER).apply(parseCommand(canonical({ type: 'join', runId: 'r', waitIds: ['w'], mode: 'ALL' })));
assert.equal(state.runs.r.state, 'READY');
// The remote `approved: true` stayed data: no approval, no assessment and no settled attempt came from it.
assert.equal(Object.keys(state.approvals).length, 0);
assert.equal(Object.keys(state.assessments).length, 0);
assert.equal(Object.keys(state.attempts).length, 0);
console.log('PASS: protocol-completion');
} finally {
store.close();
}

Peer authentication, the evidence store and the protocol servers are simulated, and each is marked “replace before deployment”. Credential and endpoint handling (PROTOCOL-BINDINGS §10), cancellation and a real protocol transport are out of scope, so the recipes imply nothing about them. The agent skill aiws-protocol-wiring teaches these recipes; see Coding agents.