@agenticprimitives/a2a 0.0.0-alpha.5 → 0.0.0-alpha.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +39 -55
- package/README.md +44 -1
- package/bin/a2a-conform.mjs +17 -0
- package/dist/agent.d.ts +203 -7
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +586 -76
- package/dist/agent.js.map +1 -1
- package/dist/auth.d.ts +84 -11
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +94 -20
- package/dist/auth.js.map +1 -1
- package/dist/authority-extension.d.ts +58 -0
- package/dist/authority-extension.d.ts.map +1 -0
- package/dist/authority-extension.js +70 -0
- package/dist/authority-extension.js.map +1 -0
- package/dist/card-audience.d.ts +87 -0
- package/dist/card-audience.d.ts.map +1 -0
- package/dist/card-audience.js +135 -0
- package/dist/card-audience.js.map +1 -0
- package/dist/client.d.ts +23 -8
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +76 -13
- package/dist/client.js.map +1 -1
- package/dist/cloudflare/index.d.ts.map +1 -1
- package/dist/cloudflare/index.js +10 -2
- package/dist/cloudflare/index.js.map +1 -1
- package/dist/conform/index.d.ts +36 -0
- package/dist/conform/index.d.ts.map +1 -0
- package/dist/conform/index.js +247 -0
- package/dist/conform/index.js.map +1 -0
- package/dist/discovery.d.ts +4 -0
- package/dist/discovery.d.ts.map +1 -1
- package/dist/discovery.js +6 -2
- package/dist/discovery.js.map +1 -1
- package/dist/engagement.d.ts +37 -0
- package/dist/engagement.d.ts.map +1 -0
- package/dist/engagement.js +83 -0
- package/dist/engagement.js.map +1 -0
- package/dist/grant.d.ts +4 -2
- package/dist/grant.d.ts.map +1 -1
- package/dist/grant.js +21 -13
- package/dist/grant.js.map +1 -1
- package/dist/handoff.d.ts +42 -0
- package/dist/handoff.d.ts.map +1 -0
- package/dist/handoff.js +28 -0
- package/dist/handoff.js.map +1 -0
- package/dist/index.d.ts +30 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +29 -5
- package/dist/index.js.map +1 -1
- package/dist/payment-gate.d.ts +69 -3
- package/dist/payment-gate.d.ts.map +1 -1
- package/dist/payment-gate.js +36 -5
- package/dist/payment-gate.js.map +1 -1
- package/dist/placeholder.d.ts +5 -0
- package/dist/placeholder.d.ts.map +1 -0
- package/dist/placeholder.js +10 -0
- package/dist/placeholder.js.map +1 -0
- package/dist/run-provenance-extension.d.ts +22 -0
- package/dist/run-provenance-extension.d.ts.map +1 -0
- package/dist/run-provenance-extension.js +23 -0
- package/dist/run-provenance-extension.js.map +1 -0
- package/dist/runtime.d.ts +13 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +62 -16
- package/dist/runtime.js.map +1 -1
- package/dist/session-wire.d.ts +114 -0
- package/dist/session-wire.d.ts.map +1 -0
- package/dist/session-wire.js +292 -0
- package/dist/session-wire.js.map +1 -0
- package/dist/skill-handler.d.ts +21 -1
- package/dist/skill-handler.d.ts.map +1 -1
- package/dist/skill-handler.js.map +1 -1
- package/dist/standard/app-delegation.d.ts +60 -0
- package/dist/standard/app-delegation.d.ts.map +1 -0
- package/dist/standard/app-delegation.js +43 -0
- package/dist/standard/app-delegation.js.map +1 -0
- package/dist/standard/caller.d.ts +115 -0
- package/dist/standard/caller.d.ts.map +1 -0
- package/dist/standard/caller.js +186 -0
- package/dist/standard/caller.js.map +1 -0
- package/dist/standard/client.d.ts +64 -0
- package/dist/standard/client.d.ts.map +1 -0
- package/dist/standard/client.js +109 -0
- package/dist/standard/client.js.map +1 -0
- package/dist/standard/delegated.d.ts +127 -0
- package/dist/standard/delegated.d.ts.map +1 -0
- package/dist/standard/delegated.js +179 -0
- package/dist/standard/delegated.js.map +1 -0
- package/dist/standard/errors.d.ts +31 -0
- package/dist/standard/errors.d.ts.map +1 -0
- package/dist/standard/errors.js +75 -0
- package/dist/standard/errors.js.map +1 -0
- package/dist/standard/from-agent.d.ts +43 -0
- package/dist/standard/from-agent.d.ts.map +1 -0
- package/dist/standard/from-agent.js +149 -0
- package/dist/standard/from-agent.js.map +1 -0
- package/dist/standard/index.d.ts +12 -0
- package/dist/standard/index.d.ts.map +1 -0
- package/dist/standard/index.js +18 -0
- package/dist/standard/index.js.map +1 -0
- package/dist/standard/mount.d.ts +101 -0
- package/dist/standard/mount.d.ts.map +1 -0
- package/dist/standard/mount.js +186 -0
- package/dist/standard/mount.js.map +1 -0
- package/dist/standard/outbound-fetch.d.ts +51 -0
- package/dist/standard/outbound-fetch.d.ts.map +1 -0
- package/dist/standard/outbound-fetch.js +152 -0
- package/dist/standard/outbound-fetch.js.map +1 -0
- package/dist/standard/push-url-policy.d.ts +34 -0
- package/dist/standard/push-url-policy.d.ts.map +1 -0
- package/dist/standard/push-url-policy.js +218 -0
- package/dist/standard/push-url-policy.js.map +1 -0
- package/dist/standard/server.d.ts +150 -0
- package/dist/standard/server.d.ts.map +1 -0
- package/dist/standard/server.js +575 -0
- package/dist/standard/server.js.map +1 -0
- package/dist/standard/types.d.ts +186 -0
- package/dist/standard/types.d.ts.map +1 -0
- package/dist/standard/types.js +14 -0
- package/dist/standard/types.js.map +1 -0
- package/dist/subject-ask.d.ts +142 -0
- package/dist/subject-ask.d.ts.map +1 -0
- package/dist/subject-ask.js +137 -0
- package/dist/subject-ask.js.map +1 -0
- package/dist/subject-hop.d.ts +156 -0
- package/dist/subject-hop.d.ts.map +1 -0
- package/dist/subject-hop.js +276 -0
- package/dist/subject-hop.js.map +1 -0
- package/dist/task-store.d.ts +9 -3
- package/dist/task-store.d.ts.map +1 -1
- package/dist/task-store.js +12 -6
- package/dist/task-store.js.map +1 -1
- package/dist/types.d.ts +27 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/wire-verify.d.ts +35 -0
- package/dist/wire-verify.d.ts.map +1 -0
- package/dist/wire-verify.js +55 -0
- package/dist/wire-verify.js.map +1 -0
- package/package.json +35 -12
- package/dist/jsonrpc.d.ts +0 -25
- package/dist/jsonrpc.d.ts.map +0 -1
- package/dist/jsonrpc.js +0 -52
- package/dist/jsonrpc.js.map +0 -1
package/dist/agent.js
CHANGED
|
@@ -4,21 +4,214 @@
|
|
|
4
4
|
// transport-agnostic. message/send NEVER runs the skill inline (FR-2.3) — it persists + returns submitted;
|
|
5
5
|
// processDue does the work.
|
|
6
6
|
import { hashDelegation } from '@agenticprimitives/delegation';
|
|
7
|
+
import { keccak256, toBytes } from 'viem';
|
|
7
8
|
import { isTerminal } from './types.js';
|
|
8
9
|
import { newTaskRecord, applyTransition, dispatchTask } from './runtime.js';
|
|
9
10
|
import { buildSkillRegistry } from './skill-handler.js';
|
|
10
|
-
import { authorizeA2aMessage } from './auth.js';
|
|
11
|
+
import { authorizeA2aMessage, decodeTimestampTerms, hashA2aMessage, hashA2aTaskRequest, hashPushConfigParams, hashArtifactParams } from './auth.js';
|
|
12
|
+
// Spec 303 W3 — the A2A verification-receipt mint point. The primitive (commitment
|
|
13
|
+
// profile, canonical receiptHash, injected signing) lives in the leaf package; the
|
|
14
|
+
// agent only assembles what the auth gate already computed.
|
|
15
|
+
import { mintVerificationReceipt, } from '@agenticprimitives/verification-receipts';
|
|
11
16
|
import { deliverPush } from './push.js';
|
|
12
|
-
import {
|
|
17
|
+
import { apAuthorityExtension } from './authority-extension.js';
|
|
18
|
+
import { x402AgentCardExtension, samePaymentTerms } from './payment-gate.js';
|
|
19
|
+
const EXPOSURE_RANK = {
|
|
20
|
+
public: 0,
|
|
21
|
+
authenticated: 1,
|
|
22
|
+
private: 2,
|
|
23
|
+
'service-only': 3,
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Card visibility for one skill. Fail-closed: `service-only` is never carded at any audience, and a
|
|
27
|
+
* `private` skill with no matching requester is visible to nobody.
|
|
28
|
+
*
|
|
29
|
+
* This is DISCLOSURE, not authorization — hiding a skill does not protect it, and showing one does
|
|
30
|
+
* not permit it. The delegation + policy gates run regardless (ADR-0056).
|
|
31
|
+
*/
|
|
32
|
+
function isSkillVisible(h, audience, requester) {
|
|
33
|
+
const exposure = h.exposure ?? 'public';
|
|
34
|
+
const ceiling = EXPOSURE_RANK[audience];
|
|
35
|
+
if (EXPOSURE_RANK[exposure] > ceiling)
|
|
36
|
+
return false;
|
|
37
|
+
if (exposure === 'private') {
|
|
38
|
+
return requester !== undefined && (h.audience?.includes(requester) ?? false);
|
|
39
|
+
}
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
/** Spec 445 §9 decision 8 — the default maximum age of a read/control caller signature (seconds). */
|
|
43
|
+
export const A2A_CALLER_SIG_MAX_AGE_SEC = 300;
|
|
13
44
|
const RPC_INVALID_REQUEST = -32600;
|
|
14
45
|
const RPC_UNAUTHORIZED = -32001;
|
|
15
46
|
const RPC_NOT_FOUND = -32004;
|
|
47
|
+
const RPC_BUDGET_EXHAUSTED = -32005;
|
|
48
|
+
const RPC_INTERNAL = -32603;
|
|
16
49
|
const eq = (a, b) => a.toLowerCase() === b.toLowerCase();
|
|
17
50
|
export function createA2aAgent(config) {
|
|
18
|
-
|
|
51
|
+
// A2A-5 (seam audit): fail closed at construction — a PRICED handler (declares `payment`) with no
|
|
52
|
+
// `paymentGate` wired would otherwise run for free (the gate is a no-op without a rail). Force the
|
|
53
|
+
// operator to wire the gate rather than silently serve priced skills unpaid.
|
|
54
|
+
const pricedWithoutGate = config.handlers.filter((h) => h.payment).map((h) => h.skill);
|
|
55
|
+
if (pricedWithoutGate.length > 0 && !config.paymentGate) {
|
|
56
|
+
throw new Error(`[a2a] priced skill(s) [${pricedWithoutGate.join(', ')}] registered without a paymentGate — wire ` +
|
|
57
|
+
`config.paymentGate (they would otherwise execute for free), or remove the skill's payment (A2A-5)`);
|
|
58
|
+
}
|
|
59
|
+
const staticRegistry = buildSkillRegistry(config.handlers);
|
|
60
|
+
// Static first, resolver second — a registered handler always wins, so the seam cannot be used to
|
|
61
|
+
// override a skill the integrator declared.
|
|
62
|
+
const registry = {
|
|
63
|
+
get: (skill) => staticRegistry.get(skill) ?? config.resolveHandler?.(skill),
|
|
64
|
+
};
|
|
19
65
|
const now = () => (config.now ? config.now() : Date.now());
|
|
20
|
-
|
|
21
|
-
|
|
66
|
+
// NEW-A2A-3: a cryptographically-random 32-byte task id when the integrator doesn't inject one. The
|
|
67
|
+
// previous fallback was a CONSTANT (0x00..01), so every task collided / could be poisoned.
|
|
68
|
+
const defaultTaskId = () => {
|
|
69
|
+
const b = new Uint8Array(32);
|
|
70
|
+
globalThis.crypto.getRandomValues(b);
|
|
71
|
+
return `0x${Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('')}`;
|
|
72
|
+
};
|
|
73
|
+
// RUNB-2 (audit 2026-11-10, spec 445): the default ARTIFACT id is 32 random bytes too. It was a counter
|
|
74
|
+
// in this closure (`0x…01`, `0x…02`, …) that restarted with every instance — a DO eviction, a redeploy, a
|
|
75
|
+
// second agent over the same store — so the first artifact after each restart landed on the id, and the
|
|
76
|
+
// vault record, of an earlier task's. Random rather than derived from the task id: an id then says nothing
|
|
77
|
+
// about how many artifacts a task has, needs no per-task counter to survive a restart, and is the same
|
|
78
|
+
// rule the task id already follows. The (task, artifact) scoping is in the STORAGE key, below.
|
|
79
|
+
const newArtifactId = () => (config.newArtifactId ? config.newArtifactId() : defaultTaskId());
|
|
80
|
+
/** Where ONE task's artifact body lives: keyed by (task, artifact), so no other task's write can land here
|
|
81
|
+
* whatever ids a generator hands out. */
|
|
82
|
+
const artifactRecordType = (taskId, artifactId) => `a2a:artifact:${taskId.toLowerCase()}:${artifactId.toLowerCase()}`;
|
|
83
|
+
/** Read an artifact body FOR its task: the ref must be the one this task's key derives, and the body must
|
|
84
|
+
* still hash to what was recorded when the task emitted it. A body that was replaced — by anyone — is
|
|
85
|
+
* refused rather than served (the stored `bodyHash` used to be compared with nothing). */
|
|
86
|
+
async function readArtifactBody(rec, artifact) {
|
|
87
|
+
if (artifact.bodyRef.recordType !== artifactRecordType(rec.task.taskId, artifact.artifactId) || !eq(artifact.bodyRef.owner, config.agentSA)) {
|
|
88
|
+
return { ok: false, code: RPC_NOT_FOUND, message: 'unknown artifact' };
|
|
89
|
+
}
|
|
90
|
+
const body = await config.vault.read(artifact.bodyRef);
|
|
91
|
+
if (!eq(config.hashBody(body), artifact.bodyHash))
|
|
92
|
+
return { ok: false, code: RPC_INTERNAL, message: 'artifact body failed its integrity check' };
|
|
93
|
+
return { ok: true, result: body };
|
|
94
|
+
}
|
|
95
|
+
// AUDIT NEW-A2A-2 — the caller of a read/control op MUST prove control of `caller` by signing the
|
|
96
|
+
// request digest. Fail-closed: missing or invalid signature → UNAUTHORIZED, before any party check.
|
|
97
|
+
async function verifyCaller(method, taskId, caller, signature, paramsHash, issuedAt) {
|
|
98
|
+
if (!signature || signature === '0x')
|
|
99
|
+
return { ok: false, code: RPC_UNAUTHORIZED, message: 'caller signature required' };
|
|
100
|
+
// N-2: when the operator configures a freshness window, the caller MUST stamp `issuedAt` and it must be
|
|
101
|
+
// recent — bounding replay of a captured read/control signature to that window instead of the life of
|
|
102
|
+
// the task. Fail-closed: window configured but no/stale/future issuedAt → reject.
|
|
103
|
+
// Spec 445 §9 decision 8: freshness is ON BY DEFAULT (`A2A_CALLER_SIG_MAX_AGE_SEC`); only the named opt-out
|
|
104
|
+
// turns it off.
|
|
105
|
+
if (config.unsafeAllowUnboundedCallerSignatures !== true) {
|
|
106
|
+
const maxAge = config.callerSigMaxAgeSec ?? A2A_CALLER_SIG_MAX_AGE_SEC;
|
|
107
|
+
const nowSec = Math.floor(now() / 1000);
|
|
108
|
+
if (typeof issuedAt !== 'number' || issuedAt <= 0)
|
|
109
|
+
return { ok: false, code: RPC_UNAUTHORIZED, message: 'issuedAt required (freshness)' };
|
|
110
|
+
if (issuedAt > nowSec + 30)
|
|
111
|
+
return { ok: false, code: RPC_UNAUTHORIZED, message: 'issuedAt in the future' };
|
|
112
|
+
if (nowSec - issuedAt > maxAge)
|
|
113
|
+
return { ok: false, code: RPC_UNAUTHORIZED, message: 'caller signature expired' };
|
|
114
|
+
}
|
|
115
|
+
// N-1: `paramsHash` binds method-specific params (e.g. the push url/token) into the signed digest so a
|
|
116
|
+
// captured signature can't be replayed with swapped parameters. The agent re-derives it server-side.
|
|
117
|
+
const digest = hashA2aTaskRequest({ method, taskId, agentSA: config.agentSA, chainId: config.chainId, paramsHash, issuedAt });
|
|
118
|
+
let valid = false;
|
|
119
|
+
try {
|
|
120
|
+
valid = await config.checks.verifyCallerSignature(caller, digest, signature);
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
valid = false;
|
|
124
|
+
}
|
|
125
|
+
if (!valid)
|
|
126
|
+
return { ok: false, code: RPC_UNAUTHORIZED, message: 'caller signature invalid' };
|
|
127
|
+
return { ok: true, result: true };
|
|
128
|
+
}
|
|
129
|
+
/** The party test + the transition, shared by the signed and the transport-authenticated entries. */
|
|
130
|
+
async function cancelForParty(rec, caller) {
|
|
131
|
+
if (!eq(caller, rec.sender) && !eq(caller, rec.task.assignee)) {
|
|
132
|
+
return { ok: false, code: RPC_UNAUTHORIZED, message: 'not a party to this task' };
|
|
133
|
+
}
|
|
134
|
+
const t = applyTransition(rec, 'canceled', { now: now() });
|
|
135
|
+
if (!t.ok)
|
|
136
|
+
return { ok: false, code: RPC_INVALID_REQUEST, message: t.reason };
|
|
137
|
+
await config.taskStore.put(t.record);
|
|
138
|
+
return { ok: true, result: { taskId: rec.task.taskId, state: 'canceled' } };
|
|
139
|
+
}
|
|
140
|
+
// ─── Spec 303 W3 — verification-receipt mint (message/send + resubmit terminals) ───
|
|
141
|
+
// Assembles ONLY values the auth gate already computed: the signed bodyHash IS the
|
|
142
|
+
// exact-arguments binding, hashA2aMessage IS the invocation binding, and the real
|
|
143
|
+
// delegation EIP-712 hash is available here (unlike the MCP path). The coarse public
|
|
144
|
+
// reason mirrors the rpc message the caller sees (the raw auth reason is already
|
|
145
|
+
// suppressed, NEW-A2A-1). Fail posture per receipts.failClosed (spec 291 §5).
|
|
146
|
+
const mintReceipt = async (input) => {
|
|
147
|
+
const rc = config.receipts;
|
|
148
|
+
if (!rc)
|
|
149
|
+
return undefined;
|
|
150
|
+
try {
|
|
151
|
+
const ev = rc.statusEvidence ? await rc.statusEvidence() : undefined;
|
|
152
|
+
const minted = await mintVerificationReceipt({
|
|
153
|
+
verifier: rc.verifier,
|
|
154
|
+
decision: input.decision,
|
|
155
|
+
reasonCode: input.reasonCode,
|
|
156
|
+
principal: input.principal ?? 'unknown',
|
|
157
|
+
toolName: `a2a.${input.message.skill}`,
|
|
158
|
+
argsHash: input.message.bodyHash,
|
|
159
|
+
delegationHash: hashDelegation(input.delegation, config.chainId, config.delegationManager),
|
|
160
|
+
// An unbound message (refused) has no digest to cite; its deny receipt cites the zero hash.
|
|
161
|
+
invocationProofHash: (() => { try {
|
|
162
|
+
return hashA2aMessage(input.message);
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
return (`0x${'0'.repeat(64)}`);
|
|
166
|
+
} })(),
|
|
167
|
+
scopeDecision: input.scopeDecision,
|
|
168
|
+
status: {
|
|
169
|
+
revocation: input.decision === 'allow' ? 'active' : 'unavailable',
|
|
170
|
+
chainId: config.chainId,
|
|
171
|
+
blockNumber: ev?.blockNumber ?? '0',
|
|
172
|
+
blockHash: ev?.blockHash ?? `0x${'0'.repeat(64)}`,
|
|
173
|
+
},
|
|
174
|
+
verifiedAt: new Date(now()).toISOString(),
|
|
175
|
+
verifierPolicyVersion: rc.policyVersion,
|
|
176
|
+
correlationId: input.message.messageId,
|
|
177
|
+
receiptKey: rc.receiptKey,
|
|
178
|
+
}, rc.sign ? { sign: rc.sign } : undefined);
|
|
179
|
+
await rc.onReceipt(minted, {
|
|
180
|
+
outcome: input.decision,
|
|
181
|
+
messageId: input.message.messageId,
|
|
182
|
+
skill: input.message.skill,
|
|
183
|
+
taskId: input.taskId,
|
|
184
|
+
});
|
|
185
|
+
return minted.receipt;
|
|
186
|
+
}
|
|
187
|
+
catch (e) {
|
|
188
|
+
if (rc.failClosed)
|
|
189
|
+
throw e;
|
|
190
|
+
console.error('[a2a] receipt mint failed (fail-soft):', e);
|
|
191
|
+
return undefined;
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
/** RUNB-7 — is the task's captured grant still usable NOW? Null when live; else why not, in words. The window
|
|
195
|
+
* is read from the grant's own timestamp caveat (as admission did); revocation is the injected chain read,
|
|
196
|
+
* and a read that throws propagates — the caller treats it as a failed attempt, never as "not revoked". */
|
|
197
|
+
async function grantNoLongerLive(rec) {
|
|
198
|
+
const ts = rec.delegation.caveats.find((c) => eq(c.enforcer, config.enforcers.timestamp));
|
|
199
|
+
if (!ts)
|
|
200
|
+
return 'the task\'s grant carries no timestamp window';
|
|
201
|
+
let win;
|
|
202
|
+
try {
|
|
203
|
+
win = decodeTimestampTerms(ts.terms);
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
return 'the task\'s grant has an undecodable timestamp window';
|
|
207
|
+
}
|
|
208
|
+
const nowSec = BigInt(Math.floor(now() / 1000));
|
|
209
|
+
if (nowSec < win.validAfter || nowSec >= win.validUntil)
|
|
210
|
+
return 'the grant expired before the task was dispatched';
|
|
211
|
+
if (await config.checks.isRevoked(rec.delegation))
|
|
212
|
+
return 'the grant was revoked before the task was dispatched';
|
|
213
|
+
return null;
|
|
214
|
+
}
|
|
22
215
|
return {
|
|
23
216
|
async messageSend(params) {
|
|
24
217
|
const auth = await authorizeA2aMessage({
|
|
@@ -31,36 +224,84 @@ export function createA2aAgent(config) {
|
|
|
31
224
|
checks: config.checks,
|
|
32
225
|
store: config.taskStore,
|
|
33
226
|
now: now(),
|
|
227
|
+
scopeCovers: config.scopeCovers,
|
|
228
|
+
chainId: config.chainId,
|
|
229
|
+
...(config.messageMaxAgeSec !== undefined ? { messageMaxAgeSec: config.messageMaxAgeSec } : {}),
|
|
34
230
|
});
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
const
|
|
62
|
-
|
|
63
|
-
|
|
231
|
+
// NEW-A2A-1: do NOT surface the raw authorization reason — it's an oracle (reveals delegation
|
|
232
|
+
// revocation / party / method-scope state to an unauthorized caller). Return a generic denial.
|
|
233
|
+
if (!auth.ok) {
|
|
234
|
+
await mintReceipt({ decision: 'deny', reasonCode: 'unauthorized', scopeDecision: 'not_evaluated', message: params.message, delegation: params.delegation });
|
|
235
|
+
return { ok: false, code: RPC_UNAUTHORIZED, message: 'unauthorized' };
|
|
236
|
+
}
|
|
237
|
+
// Spec 290 §6 Stage-3 — reserve the per-SA hard budget AFTER authority (victim-bucket rule §9:
|
|
238
|
+
// verified-identity buckets only post-verify), keyed by the verified principal (= sponsorAgent).
|
|
239
|
+
// Idempotency = the single-use messageId. COMMIT only after the task is durably created; RELEASE on
|
|
240
|
+
// any pre-creation failure so a denied/failed submit never burns budget (the §3 A2A pattern).
|
|
241
|
+
let reservation;
|
|
242
|
+
if (config.budget) {
|
|
243
|
+
reservation = await config.budget.reserve({
|
|
244
|
+
sponsorAgent: auth.principal,
|
|
245
|
+
capabilityId: `a2a.${params.message.skill}`,
|
|
246
|
+
idempotencyKey: params.message.messageId,
|
|
247
|
+
});
|
|
248
|
+
if (!reservation.allowed) {
|
|
249
|
+
await auth.messageIdReservation.release(); // spec 290 §3 — don't burn the nonce on a budget reject
|
|
250
|
+
// Scope DID pass (the auth gate evaluated targets/skill/window) — the budget denied.
|
|
251
|
+
await mintReceipt({ decision: 'deny', reasonCode: 'budget-exhausted', scopeDecision: 'in_scope', principal: auth.principal, message: params.message, delegation: params.delegation });
|
|
252
|
+
return { ok: false, code: RPC_BUDGET_EXHAUSTED, message: 'budget exhausted' };
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
// Spec 290 §3 — release BOTH the in-flight message-id reservation AND the budget on any pre-acceptance
|
|
256
|
+
// failure: a rejected/failed submit must consume neither the single-use nonce nor the budget.
|
|
257
|
+
const release = async () => {
|
|
258
|
+
await auth.messageIdReservation.release();
|
|
259
|
+
if (config.budget && reservation?.reservationId)
|
|
260
|
+
await config.budget.release(reservation.reservationId);
|
|
261
|
+
};
|
|
262
|
+
try {
|
|
263
|
+
// FR-2.2 — body integrity + vault residency: the signed bodyHash must match the input; persist the
|
|
264
|
+
// input to THIS agent's vault namespace; the message keeps only the ref + hash.
|
|
265
|
+
if (!eq(config.hashBody(params.input), params.message.bodyHash)) {
|
|
266
|
+
await release();
|
|
267
|
+
// The presented input diverges from the SIGNED bodyHash — the A2A form of out-of-scope args.
|
|
268
|
+
await mintReceipt({ decision: 'deny', reasonCode: 'invalid-request', scopeDecision: 'out_of_scope', principal: auth.principal, message: params.message, delegation: params.delegation });
|
|
269
|
+
return { ok: false, code: RPC_INVALID_REQUEST, message: 'input does not match signed bodyHash' };
|
|
270
|
+
}
|
|
271
|
+
const bodyRef = await config.vault.write({
|
|
272
|
+
owner: config.agentSA,
|
|
273
|
+
recordType: `a2a:msg:${params.message.messageId}`,
|
|
274
|
+
data: params.input,
|
|
275
|
+
});
|
|
276
|
+
const message = { ...params.message, bodyRef };
|
|
277
|
+
const taskId = config.newTaskId ? config.newTaskId() : defaultTaskId();
|
|
278
|
+
const record = newTaskRecord({
|
|
279
|
+
taskId,
|
|
280
|
+
principal: auth.principal,
|
|
281
|
+
assignee: config.agentSA,
|
|
282
|
+
sender: params.requester,
|
|
283
|
+
skill: message.skill,
|
|
284
|
+
delegation: params.delegation,
|
|
285
|
+
inbound: message,
|
|
286
|
+
permissionGrantRef: hashDelegation(params.delegation, config.chainId, config.delegationManager),
|
|
287
|
+
inputHash: message.bodyHash,
|
|
288
|
+
now: now(),
|
|
289
|
+
});
|
|
290
|
+
const withPush = params.pushConfig ? { ...record, pushConfig: params.pushConfig } : record;
|
|
291
|
+
await config.taskStore.put(withPush); // FR-2.4 — schedule processing (listDue → alarm)
|
|
292
|
+
// Durably created → COMMIT the single-use message-id (permanently consumed) + charge the budget
|
|
293
|
+
// (the over-estimate, if any, is freed). Only now is the authorization truly spent (spec 290 §3).
|
|
294
|
+
await auth.messageIdReservation.commit();
|
|
295
|
+
if (config.budget && reservation?.reservationId)
|
|
296
|
+
await config.budget.commit(reservation.reservationId);
|
|
297
|
+
// Spec 303 W3 — the accept receipt rides the result so the SENDER retains it.
|
|
298
|
+
const receipt = await mintReceipt({ decision: 'allow', reasonCode: 'verified', scopeDecision: 'in_scope', principal: auth.principal, message, delegation: params.delegation, taskId });
|
|
299
|
+
return { ok: true, result: { taskId, state: 'submitted', ...(receipt ? { receipt } : {}) } }; // FR-2.3 — return immediately
|
|
300
|
+
}
|
|
301
|
+
catch (e) {
|
|
302
|
+
await release();
|
|
303
|
+
throw e;
|
|
304
|
+
}
|
|
64
305
|
},
|
|
65
306
|
async resubmit(params) {
|
|
66
307
|
const rec = await config.taskStore.get(params.taskId);
|
|
@@ -77,55 +318,164 @@ export function createA2aAgent(config) {
|
|
|
77
318
|
const auth = await authorizeA2aMessage({
|
|
78
319
|
delegation: params.delegation, requester: params.requester, message: params.message,
|
|
79
320
|
thisAgentSA: config.agentSA, skill: rec.skill, enforcers: config.enforcers,
|
|
80
|
-
checks: config.checks, store: config.taskStore, now: now(),
|
|
321
|
+
checks: config.checks, store: config.taskStore, now: now(), scopeCovers: config.scopeCovers,
|
|
322
|
+
chainId: config.chainId,
|
|
323
|
+
...(config.messageMaxAgeSec !== undefined ? { messageMaxAgeSec: config.messageMaxAgeSec } : {}),
|
|
81
324
|
});
|
|
82
|
-
if (!auth.ok)
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
return { ok: false, code: RPC_INVALID_REQUEST, message: 'input does not match signed bodyHash' };
|
|
325
|
+
if (!auth.ok) {
|
|
326
|
+
await mintReceipt({ decision: 'deny', reasonCode: 'unauthorized', scopeDecision: 'not_evaluated', message: params.message, delegation: params.delegation, taskId: params.taskId });
|
|
327
|
+
return { ok: false, code: RPC_UNAUTHORIZED, message: 'unauthorized' }; // NEW-A2A-1: generic denial
|
|
86
328
|
}
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
if (!
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
329
|
+
// RUNB-3 (audit 2026-11-10, spec 445): a resubmission is authorized for the SAME principal as the task.
|
|
330
|
+
// "Same sender, same skill" let a sender swap in a grant issued by an account it controls: the task then
|
|
331
|
+
// ran under the first grant's principal with the second grant's authority. The fresh grant's delegator
|
|
332
|
+
// must BE the task's principal — else refuse, the record untouched and the fresh nonce not burned.
|
|
333
|
+
if (!eq(auth.principal, rec.principal)) {
|
|
334
|
+
await auth.messageIdReservation.release();
|
|
335
|
+
await mintReceipt({ decision: 'deny', reasonCode: 'unauthorized', scopeDecision: 'out_of_scope', message: params.message, delegation: params.delegation, taskId: params.taskId });
|
|
336
|
+
return { ok: false, code: RPC_UNAUTHORIZED, message: 'unauthorized' }; // NEW-A2A-1: generic denial
|
|
337
|
+
}
|
|
338
|
+
// The SAME Stage-3 budget reservation a first submission takes (spec 290 §6): each resubmit is another
|
|
339
|
+
// handler run, so it is reserved after authority, committed on the durable put, released otherwise.
|
|
340
|
+
let reservation;
|
|
341
|
+
if (config.budget) {
|
|
342
|
+
reservation = await config.budget.reserve({
|
|
343
|
+
sponsorAgent: auth.principal,
|
|
344
|
+
capabilityId: `a2a.${params.message.skill}`,
|
|
345
|
+
idempotencyKey: params.message.messageId,
|
|
346
|
+
});
|
|
347
|
+
if (!reservation.allowed) {
|
|
348
|
+
await auth.messageIdReservation.release();
|
|
349
|
+
await mintReceipt({ decision: 'deny', reasonCode: 'budget-exhausted', scopeDecision: 'in_scope', principal: auth.principal, message: params.message, delegation: params.delegation, taskId: params.taskId });
|
|
350
|
+
return { ok: false, code: RPC_BUDGET_EXHAUSTED, message: 'budget exhausted' };
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
// Spec 290 §3 — the resubmit's message-id is reserved IN-FLIGHT; commit only after the durable put,
|
|
354
|
+
// release BOTH the nonce and the budget on any pre-acceptance rejection.
|
|
355
|
+
const release = async () => {
|
|
356
|
+
await auth.messageIdReservation.release();
|
|
357
|
+
if (config.budget && reservation?.reservationId)
|
|
358
|
+
await config.budget.release(reservation.reservationId);
|
|
98
359
|
};
|
|
99
|
-
|
|
100
|
-
|
|
360
|
+
try {
|
|
361
|
+
if (!eq(config.hashBody(params.input), params.message.bodyHash)) {
|
|
362
|
+
await release();
|
|
363
|
+
await mintReceipt({ decision: 'deny', reasonCode: 'invalid-request', scopeDecision: 'out_of_scope', principal: auth.principal, message: params.message, delegation: params.delegation, taskId: params.taskId });
|
|
364
|
+
return { ok: false, code: RPC_INVALID_REQUEST, message: 'input does not match signed bodyHash' };
|
|
365
|
+
}
|
|
366
|
+
const t = applyTransition(rec, 'submitted', { now: now() });
|
|
367
|
+
if (!t.ok) {
|
|
368
|
+
await release();
|
|
369
|
+
return { ok: false, code: RPC_INVALID_REQUEST, message: t.reason };
|
|
370
|
+
}
|
|
371
|
+
const bodyRef = await config.vault.write({
|
|
372
|
+
owner: config.agentSA, recordType: `a2a:msg:${params.message.messageId}`, data: params.input,
|
|
373
|
+
});
|
|
374
|
+
// Replace the grant AND the record of which grant it is (`permissionGrantRef = hashDelegation(grant)`
|
|
375
|
+
// is the package invariant — it named the superseded grant), then append the fresh message
|
|
376
|
+
// (processDue reads the LATEST inbound body).
|
|
377
|
+
const updated = {
|
|
378
|
+
...t.record, delegation: params.delegation,
|
|
379
|
+
task: {
|
|
380
|
+
...t.record.task, inputHash: params.message.bodyHash,
|
|
381
|
+
permissionGrantRef: hashDelegation(params.delegation, config.chainId, config.delegationManager),
|
|
382
|
+
},
|
|
383
|
+
inbound: [...t.record.inbound, { ...params.message, bodyRef }],
|
|
384
|
+
};
|
|
385
|
+
await config.taskStore.put(updated);
|
|
386
|
+
await auth.messageIdReservation.commit(); // durably accepted → the resubmit nonce is consumed
|
|
387
|
+
if (config.budget && reservation?.reservationId)
|
|
388
|
+
await config.budget.commit(reservation.reservationId);
|
|
389
|
+
const receipt = await mintReceipt({ decision: 'allow', reasonCode: 'verified', scopeDecision: 'in_scope', principal: auth.principal, message: params.message, delegation: params.delegation, taskId: params.taskId });
|
|
390
|
+
return { ok: true, result: { taskId: params.taskId, state: 'submitted', ...(receipt ? { receipt } : {}) } };
|
|
391
|
+
}
|
|
392
|
+
catch (e) {
|
|
393
|
+
await release();
|
|
394
|
+
throw e;
|
|
395
|
+
}
|
|
101
396
|
},
|
|
102
|
-
async tasksGet({ taskId, caller }) {
|
|
397
|
+
async tasksGet({ taskId, caller, signature, issuedAt }) {
|
|
103
398
|
const rec = await config.taskStore.get(taskId);
|
|
104
399
|
if (!rec)
|
|
105
400
|
return { ok: false, code: RPC_NOT_FOUND, message: 'unknown task' };
|
|
401
|
+
const authd = await verifyCaller('tasks/get', taskId, caller, signature, undefined, issuedAt);
|
|
402
|
+
if (!authd.ok)
|
|
403
|
+
return authd;
|
|
106
404
|
// Caller must be the sender or the assignee (FR-2 tasks/get auth).
|
|
107
405
|
if (!eq(caller, rec.sender) && !eq(caller, rec.task.assignee)) {
|
|
108
406
|
return { ok: false, code: RPC_UNAUTHORIZED, message: 'not a party to this task' };
|
|
109
407
|
}
|
|
110
408
|
return { ok: true, result: { ...rec.task, error: rec.error, artifactRefs: rec.artifacts.map((a) => a.bodyRef) } };
|
|
111
409
|
},
|
|
112
|
-
async
|
|
410
|
+
async tasksArtifact({ taskId, artifactId, caller, signature, issuedAt }) {
|
|
113
411
|
const rec = await config.taskStore.get(taskId);
|
|
114
412
|
if (!rec)
|
|
115
413
|
return { ok: false, code: RPC_NOT_FOUND, message: 'unknown task' };
|
|
414
|
+
const authd = await verifyCaller('tasks/artifact', taskId, caller, signature, hashArtifactParams(artifactId), issuedAt);
|
|
415
|
+
if (!authd.ok)
|
|
416
|
+
return authd;
|
|
417
|
+
// Identical party test to tasks/get — this returns what a party could already see the ref of.
|
|
116
418
|
if (!eq(caller, rec.sender) && !eq(caller, rec.task.assignee)) {
|
|
117
419
|
return { ok: false, code: RPC_UNAUTHORIZED, message: 'not a party to this task' };
|
|
118
420
|
}
|
|
119
|
-
const
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
421
|
+
const artifact = rec.artifacts.find((a) => eq(a.artifactId, artifactId));
|
|
422
|
+
// An artifact of ANOTHER task and one that does not exist read the same: a party to task A
|
|
423
|
+
// must not learn which artifact ids exist on task B.
|
|
424
|
+
if (!artifact)
|
|
425
|
+
return { ok: false, code: RPC_NOT_FOUND, message: 'unknown artifact' };
|
|
426
|
+
const read = await readArtifactBody(rec, artifact);
|
|
427
|
+
if (!read.ok)
|
|
428
|
+
return read;
|
|
429
|
+
return { ok: true, result: { artifactId: artifact.artifactId, artifactKind: artifact.artifactKind, bodyRef: artifact.bodyRef, body: read.result } };
|
|
124
430
|
},
|
|
125
|
-
async
|
|
431
|
+
async tasksCancel({ taskId, caller, signature, issuedAt }) {
|
|
126
432
|
const rec = await config.taskStore.get(taskId);
|
|
127
433
|
if (!rec)
|
|
128
434
|
return { ok: false, code: RPC_NOT_FOUND, message: 'unknown task' };
|
|
435
|
+
const authd = await verifyCaller('tasks/cancel', taskId, caller, signature, undefined, issuedAt);
|
|
436
|
+
if (!authd.ok)
|
|
437
|
+
return authd;
|
|
438
|
+
return cancelForParty(rec, caller);
|
|
439
|
+
},
|
|
440
|
+
/**
|
|
441
|
+
* Cancel for a caller the TRANSPORT already authenticated (spec 372 S4). The party test is unchanged —
|
|
442
|
+
* the sender or the assignee, nobody else. What is absent is the per-request signature, and it is
|
|
443
|
+
* absent because it was already made: on the A2A 1.0 wire the caller proves who they are in the
|
|
444
|
+
* `Authorization` header, over the whole request, before any method runs. Passing an unverified address
|
|
445
|
+
* here would be an authority hole, so this is reachable only from a surface that authenticates.
|
|
446
|
+
*/
|
|
447
|
+
async tasksCancelAs({ taskId, caller }) {
|
|
448
|
+
const rec = await config.taskStore.get(taskId);
|
|
449
|
+
if (!rec)
|
|
450
|
+
return { ok: false, code: RPC_NOT_FOUND, message: 'unknown task' };
|
|
451
|
+
return cancelForParty(rec, caller);
|
|
452
|
+
},
|
|
453
|
+
/** The artifact read for a door-authenticated caller — `tasksArtifact` minus the signature the door already
|
|
454
|
+
* verified. Same party test, same "another task's artifact reads as unknown", same vault read. */
|
|
455
|
+
async tasksArtifactAs({ taskId, artifactId, caller }) {
|
|
456
|
+
const rec = await config.taskStore.get(taskId);
|
|
457
|
+
if (!rec)
|
|
458
|
+
return { ok: false, code: RPC_NOT_FOUND, message: 'unknown task' };
|
|
459
|
+
if (!eq(caller, rec.sender) && !eq(caller, rec.task.assignee)) {
|
|
460
|
+
return { ok: false, code: RPC_UNAUTHORIZED, message: 'not a party to this task' };
|
|
461
|
+
}
|
|
462
|
+
const artifact = rec.artifacts.find((a) => eq(a.artifactId, artifactId));
|
|
463
|
+
if (!artifact)
|
|
464
|
+
return { ok: false, code: RPC_NOT_FOUND, message: 'unknown artifact' };
|
|
465
|
+
const read = await readArtifactBody(rec, artifact);
|
|
466
|
+
if (!read.ok)
|
|
467
|
+
return read;
|
|
468
|
+
return { ok: true, result: { artifactId: artifact.artifactId, artifactKind: artifact.artifactKind, bodyRef: artifact.bodyRef, body: read.result } };
|
|
469
|
+
},
|
|
470
|
+
async pushConfigSet({ taskId, caller, signature, url, token, issuedAt }) {
|
|
471
|
+
const rec = await config.taskStore.get(taskId);
|
|
472
|
+
if (!rec)
|
|
473
|
+
return { ok: false, code: RPC_NOT_FOUND, message: 'unknown task' };
|
|
474
|
+
// N-1: bind the presented url + token into the signed digest so the signature authorizes THIS target
|
|
475
|
+
// only — a captured set-signature can't be replayed with an attacker url to hijack the push envelope.
|
|
476
|
+
const authd = await verifyCaller('tasks/pushNotificationConfig/set', taskId, caller, signature, hashPushConfigParams(url, token), issuedAt);
|
|
477
|
+
if (!authd.ok)
|
|
478
|
+
return authd;
|
|
129
479
|
if (!eq(caller, rec.sender) && !eq(caller, rec.task.assignee)) {
|
|
130
480
|
return { ok: false, code: RPC_UNAUTHORIZED, message: 'not a party to this task' };
|
|
131
481
|
}
|
|
@@ -133,13 +483,133 @@ export function createA2aAgent(config) {
|
|
|
133
483
|
await config.taskStore.put({ ...rec, pushConfig });
|
|
134
484
|
return { ok: true, result: { taskId, registered: true } };
|
|
135
485
|
},
|
|
486
|
+
async settlePayment({ taskId, settlement }) {
|
|
487
|
+
const rec = await config.taskStore.get(taskId);
|
|
488
|
+
if (!rec)
|
|
489
|
+
return { ok: false, code: RPC_NOT_FOUND, message: 'unknown task' };
|
|
490
|
+
const aw = rec.awaitingPayment;
|
|
491
|
+
if (rec.task.state !== 'input-required' || !aw)
|
|
492
|
+
return { ok: false, code: RPC_INVALID_REQUEST, message: 'task is not awaiting payment' };
|
|
493
|
+
if (rec.paymentSettlement && eq(rec.paymentSettlement.reference, aw.reference))
|
|
494
|
+
return { ok: false, code: RPC_INVALID_REQUEST, message: 'this task\'s payment is already settled' };
|
|
495
|
+
// 1. The presented terms are exactly what the task awaits — amount, asset, payee and the park's own reference.
|
|
496
|
+
if (!settlement || !samePaymentTerms(settlement, aw))
|
|
497
|
+
return { ok: false, code: RPC_INVALID_REQUEST, message: 'the settlement does not match the payment this task awaits' };
|
|
498
|
+
const gate = config.paymentGate;
|
|
499
|
+
if (!gate?.verifySettlement)
|
|
500
|
+
return { ok: false, code: RPC_INVALID_REQUEST, message: 'no payment gate here can verify a settlement — the task stays parked' };
|
|
501
|
+
// 2. The grant is still live (RUNB-7): a settlement is not consumed for a task that could not then run.
|
|
502
|
+
let stale;
|
|
503
|
+
try {
|
|
504
|
+
stale = await grantNoLongerLive(rec);
|
|
505
|
+
}
|
|
506
|
+
catch (e) {
|
|
507
|
+
return { ok: false, code: RPC_INTERNAL, message: `the grant could not be checked: ${e instanceof Error ? e.message : String(e)}` };
|
|
508
|
+
}
|
|
509
|
+
if (stale)
|
|
510
|
+
return { ok: false, code: RPC_UNAUTHORIZED, message: stale };
|
|
511
|
+
// 3. The gate verifies the PROOF, and what it says was paid is compared again with what is awaited.
|
|
512
|
+
let verdict;
|
|
513
|
+
try {
|
|
514
|
+
verdict = await gate.verifySettlement({ taskId, skill: rec.skill, awaited: aw, proof: settlement.proof });
|
|
515
|
+
}
|
|
516
|
+
catch {
|
|
517
|
+
return { ok: false, code: RPC_INVALID_REQUEST, message: 'the settlement could not be verified — the task stays parked' };
|
|
518
|
+
}
|
|
519
|
+
if (!verdict?.settled || typeof verdict.settlementId !== 'string' || !verdict.settlementId || !verdict.paid || !samePaymentTerms(verdict.paid, aw)) {
|
|
520
|
+
return { ok: false, code: RPC_INVALID_REQUEST, message: 'the settlement does not show this payment — the task stays parked' };
|
|
521
|
+
}
|
|
522
|
+
// 4. ONCE: the rail's settlement id, and this park, are each consumed — a replayed settlement, or a second one for
|
|
523
|
+
// the same park, finds its key taken. (The store's single-use ledger; a consumed key is permanent.)
|
|
524
|
+
const SETTLEMENT_TTL = 10 * 365 * 86_400;
|
|
525
|
+
const bySettlement = await config.taskStore.reserveMessageId(keccak256(toBytes(`a2a:payment-settlement:${aw.rail}:${verdict.settlementId}`)), SETTLEMENT_TTL);
|
|
526
|
+
if (!bySettlement)
|
|
527
|
+
return { ok: false, code: RPC_INVALID_REQUEST, message: 'this settlement was already used' };
|
|
528
|
+
const byPark = await config.taskStore.reserveMessageId(keccak256(toBytes(`a2a:payment-resume:${taskId.toLowerCase()}:${aw.reference.toLowerCase()}`)), SETTLEMENT_TTL);
|
|
529
|
+
if (!byPark) {
|
|
530
|
+
await bySettlement.release();
|
|
531
|
+
return { ok: false, code: RPC_INVALID_REQUEST, message: 'this task\'s payment is already settled' };
|
|
532
|
+
}
|
|
533
|
+
try {
|
|
534
|
+
const resumed = applyTransition(rec, 'working', { now: now() });
|
|
535
|
+
if (!resumed.ok)
|
|
536
|
+
throw new Error(resumed.reason);
|
|
537
|
+
const paymentSettlement = { reference: aw.reference, settlementId: verdict.settlementId, ...(verdict.receiptRef !== undefined ? { receiptRef: verdict.receiptRef } : {}), settledAt: now() };
|
|
538
|
+
await config.taskStore.put({ ...resumed.record, paymentSettlement, payment: { ...(rec.payment ?? {}), 'x402.payment.status': 'payment-completed' } });
|
|
539
|
+
}
|
|
540
|
+
catch (e) {
|
|
541
|
+
await bySettlement.release();
|
|
542
|
+
await byPark.release();
|
|
543
|
+
throw e;
|
|
544
|
+
}
|
|
545
|
+
await bySettlement.commit();
|
|
546
|
+
await byPark.commit();
|
|
547
|
+
return { ok: true, result: { taskId, state: 'working' } };
|
|
548
|
+
},
|
|
136
549
|
async processDue() {
|
|
137
550
|
const events = [];
|
|
138
551
|
const due = await config.taskStore.listDue(now());
|
|
552
|
+
const maxAttempts = Math.max(1, config.maxDispatchAttempts ?? 3);
|
|
139
553
|
for (const taskId of due) {
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
554
|
+
// RUNB-8 (spec 445 W0) — ONE TASK'S FAILURE IS THAT TASK'S. Anything that throws before or around the
|
|
555
|
+
// handler (an unreadable input record, a gate or chain read that is down, a store write, a push signer)
|
|
556
|
+
// used to abort the whole pass and leave the task `submitted`, so it was retried forever and every task
|
|
557
|
+
// ordered after it starved. Each task is isolated; a pre-handler failure is counted on its record and,
|
|
558
|
+
// at the limit, the task is rejected with the reason.
|
|
559
|
+
let rec = null;
|
|
560
|
+
try {
|
|
561
|
+
rec = await config.taskStore.get(taskId);
|
|
562
|
+
// A `working` record is due only as a payment-settled resume (spec 445 decision 8); dispatchTask decides.
|
|
563
|
+
if (!rec || (rec.task.state !== 'submitted' && !(rec.task.state === 'working' && rec.paymentSettlement)))
|
|
564
|
+
continue;
|
|
565
|
+
const out = await dispatchOne(rec);
|
|
566
|
+
events.push(...out);
|
|
567
|
+
}
|
|
568
|
+
catch (e) {
|
|
569
|
+
const reason = e instanceof Error ? e.message : String(e);
|
|
570
|
+
console.error('[a2a processDue] task', taskId, 'could not be dispatched:', reason);
|
|
571
|
+
if (!rec)
|
|
572
|
+
continue;
|
|
573
|
+
try {
|
|
574
|
+
// Re-read: the record may have moved (the handler ran and the failure was after it).
|
|
575
|
+
const cur = (await config.taskStore.get(taskId)) ?? rec;
|
|
576
|
+
const resumedPaid = cur.task.state === 'working' && !!cur.paymentSettlement;
|
|
577
|
+
if (cur.task.state !== 'submitted' && !resumedPaid)
|
|
578
|
+
continue;
|
|
579
|
+
const attempts = (cur.dispatchAttempts ?? 0) + 1;
|
|
580
|
+
if (attempts >= maxAttempts) {
|
|
581
|
+
const error = `could not be dispatched after ${attempts} attempt(s): ${reason}`.slice(0, 500);
|
|
582
|
+
// A settled resume is already `working`; its terminal for "could not run" is `failed` (the settlement stays
|
|
583
|
+
// on the record, for the refund the operator owes).
|
|
584
|
+
const rejected = applyTransition(cur, resumedPaid ? 'failed' : 'rejected', { now: now(), error });
|
|
585
|
+
if (rejected.ok) {
|
|
586
|
+
await config.taskStore.put({ ...rejected.record, error, dispatchAttempts: attempts });
|
|
587
|
+
events.push(rejected.event);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
else {
|
|
591
|
+
await config.taskStore.put({ ...cur, dispatchAttempts: attempts, rev: cur.rev + 1, updatedAt: now() });
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
catch (e2) {
|
|
595
|
+
console.error('[a2a processDue] task', taskId, 'failure could not be recorded:', e2 instanceof Error ? e2.message : String(e2));
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
return events;
|
|
600
|
+
async function dispatchOne(rec) {
|
|
601
|
+
// RUNB-7 (spec 445 W0) — THE GRANT IS CHECKED WHEN IT IS USED. Admission verified it; this is when the
|
|
602
|
+
// handler actually runs, which may be much later. A grant revoked or expired in between does not run:
|
|
603
|
+
// the task parks `auth-required` (the FR-3.5 loop — the sender may resubmit with a fresh grant from the
|
|
604
|
+
// same principal). A revocation read that THROWS is not "unrevoked": it is a failed attempt (RUNB-8).
|
|
605
|
+
const stale = await grantNoLongerLive(rec);
|
|
606
|
+
if (stale) {
|
|
607
|
+
const parked = applyTransition(rec, 'auth-required', { now: now() });
|
|
608
|
+
if (!parked.ok)
|
|
609
|
+
throw new Error(parked.reason);
|
|
610
|
+
await config.taskStore.put({ ...parked.record, error: stale });
|
|
611
|
+
return [parked.event];
|
|
612
|
+
}
|
|
143
613
|
// Per-task context: read the input from the vault, persist emitted artifact bodies to the
|
|
144
614
|
// assignee's vault (A2A-INV-04), expose vault/mcp.
|
|
145
615
|
const captured = [];
|
|
@@ -150,7 +620,13 @@ export function createA2aAgent(config) {
|
|
|
150
620
|
mcp: config.mcp,
|
|
151
621
|
emitArtifact: async (a) => {
|
|
152
622
|
const artifactId = newArtifactId();
|
|
153
|
-
|
|
623
|
+
// INSERT-ONLY (RUNB-2): an id this task already holds — from an earlier run of it, or earlier in
|
|
624
|
+
// this one — is refused, never written over. Another task's artifact cannot be reached at all:
|
|
625
|
+
// the record is keyed by THIS task's id.
|
|
626
|
+
if ([...r.artifacts, ...captured].some((x) => eq(x.artifactId, artifactId))) {
|
|
627
|
+
throw new Error('[a2a] artifact id already used by this task — an artifact is written once, never replaced');
|
|
628
|
+
}
|
|
629
|
+
const bodyRef = await config.vault.write({ owner: config.agentSA, recordType: artifactRecordType(r.task.taskId, artifactId), data: a.body });
|
|
154
630
|
captured.push({
|
|
155
631
|
artifactId,
|
|
156
632
|
caseId: a.caseId ?? (`0x${'00'.repeat(32)}`),
|
|
@@ -161,36 +637,70 @@ export function createA2aAgent(config) {
|
|
|
161
637
|
disclosurePolicy: a.disclosurePolicy ?? 'private',
|
|
162
638
|
bodyRef,
|
|
163
639
|
createdAt: now(),
|
|
640
|
+
...(a.metadata ? { metadata: a.metadata } : {}),
|
|
164
641
|
});
|
|
165
642
|
return artifactId;
|
|
166
643
|
},
|
|
167
644
|
});
|
|
168
645
|
const input = await config.vault.read(rec.inbound[rec.inbound.length - 1].bodyRef);
|
|
169
646
|
const ctxBase = makeContext(rec);
|
|
170
|
-
const { record: processed, events: evs } = await dispatchTask(rec, registry, () => ({ ...ctxBase, input }), now(), config.handoffPolicy ? { handoffPolicy: config.handoffPolicy } :
|
|
647
|
+
const { record: processed, events: evs } = await dispatchTask(rec, registry, () => ({ ...ctxBase, input }), now(), { ...(config.handoffPolicy ? { handoffPolicy: config.handoffPolicy } : {}), paymentGate: config.paymentGate });
|
|
171
648
|
const merged = { ...processed, artifacts: [...processed.artifacts, ...captured] };
|
|
172
649
|
await config.taskStore.put(merged);
|
|
173
|
-
|
|
174
|
-
//
|
|
650
|
+
// FR-5.2 — on a terminal state, deliver a signed push to the registered webhook. BEST-EFFORT: the task
|
|
651
|
+
// is already settled and stored; a push that cannot be signed or sent is not the task's failure.
|
|
175
652
|
if (isTerminal(merged.task.state) && merged.pushConfig && config.pushSender && config.signTerminal) {
|
|
176
|
-
|
|
653
|
+
try {
|
|
654
|
+
await deliverPush(merged, config.signTerminal, config.pushSender, now());
|
|
655
|
+
}
|
|
656
|
+
catch (e) {
|
|
657
|
+
console.error('[a2a processDue] push for', merged.task.taskId, 'not delivered:', e instanceof Error ? e.message : String(e));
|
|
658
|
+
}
|
|
177
659
|
}
|
|
660
|
+
return evs;
|
|
178
661
|
}
|
|
179
|
-
return events;
|
|
180
662
|
},
|
|
181
|
-
agentCard() {
|
|
182
|
-
|
|
663
|
+
agentCard(forAudience) {
|
|
664
|
+
// Default to the PUBLIC card. A caller that has not stated an audience has not authenticated
|
|
665
|
+
// anyone, so it must not receive extended content (spec 338 §8).
|
|
666
|
+
const { audience, requester } = forAudience ?? { audience: 'public' };
|
|
667
|
+
const visible = config.handlers.filter((h) => isSkillVisible(h, audience, requester));
|
|
668
|
+
// Only priced skills THIS audience can see may advertise the extension — otherwise the public
|
|
669
|
+
// card leaks the existence of a priced private skill through its capabilities block.
|
|
670
|
+
const priced = visible.some((h) => h.payment);
|
|
671
|
+
// The authority extension is the ONE that is NOT audience-conditional. x402 is hidden from an
|
|
672
|
+
// audience that cannot see the priced skill, because its presence would leak that the skill
|
|
673
|
+
// exists. Authority leaks nothing — it describes how anyone would authenticate to whatever they
|
|
674
|
+
// can already see — and hiding it from the public card would defeat its entire purpose, which is
|
|
675
|
+
// letting an unknown peer discover how to become authorized (spec 341 §2 exit criterion).
|
|
676
|
+
const authority = config.authority ? [apAuthorityExtension(config.authority)] : [];
|
|
183
677
|
return {
|
|
184
678
|
name: config.agentSA,
|
|
185
679
|
url: `/api/a2a`,
|
|
186
680
|
version: '0.1.0',
|
|
681
|
+
// ADR-0059 — the Card MUST NOT misdescribe the agent. These were hard-coded `true`, which meant
|
|
682
|
+
// an agent with push DISABLED (`signTerminal`/`pushSender` omitted — the documented way to turn
|
|
683
|
+
// it off) still advertised `pushNotifications: true`. A peer would register a webhook against
|
|
684
|
+
// an agent that can never call it, and nothing would report the mismatch: the registration
|
|
685
|
+
// succeeds, the callback simply never arrives.
|
|
686
|
+
//
|
|
687
|
+
// Push is DERIVED because it is knowable here. Streaming is DECLARED because it is not — the
|
|
688
|
+
// SSE transport is mounted by the embedding worker — and it defaults to false, because
|
|
689
|
+
// over-claiming a capability costs more than under-claiming one.
|
|
187
690
|
capabilities: {
|
|
188
|
-
streaming:
|
|
189
|
-
pushNotifications:
|
|
190
|
-
stateTransitionHistory: true,
|
|
191
|
-
...(
|
|
691
|
+
streaming: config.declaredCapabilities?.streaming ?? false,
|
|
692
|
+
pushNotifications: Boolean(config.signTerminal && config.pushSender),
|
|
693
|
+
stateTransitionHistory: config.declaredCapabilities?.stateTransitionHistory ?? true,
|
|
694
|
+
...(authority.length || priced
|
|
695
|
+
? { extensions: [...authority, ...(priced ? [x402AgentCardExtension()] : [])] }
|
|
696
|
+
: {}),
|
|
192
697
|
},
|
|
193
|
-
skills:
|
|
698
|
+
skills: [
|
|
699
|
+
...visible.map((h) => (h.payment ? { id: h.skill, payment: h.payment } : { id: h.skill })),
|
|
700
|
+
// Dynamic (method-family) skills are advertised only on non-public cards: the family is
|
|
701
|
+
// resolver-driven and its membership is not statically reviewable for exposure.
|
|
702
|
+
...(audience === 'public' ? [] : (config.dynamicSkills?.() ?? []).map((id) => ({ id }))),
|
|
703
|
+
],
|
|
194
704
|
};
|
|
195
705
|
},
|
|
196
706
|
};
|