@agenticprimitives/a2a 0.0.0-alpha.48 → 0.0.0-alpha.49
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 +4 -1
- package/README.md +1 -1
- package/dist/agent.d.ts +38 -9
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +256 -38
- package/dist/agent.js.map +1 -1
- package/dist/auth.d.ts +12 -2
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +34 -3
- package/dist/auth.js.map +1 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +3 -1
- package/dist/client.js.map +1 -1
- package/dist/conform/index.d.ts.map +1 -1
- package/dist/conform/index.js +15 -0
- package/dist/conform/index.js.map +1 -1
- package/dist/index.d.ts +7 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -4
- 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/runtime.d.ts.map +1 -1
- package/dist/runtime.js +31 -10
- package/dist/runtime.js.map +1 -1
- package/dist/session-wire.d.ts +37 -13
- package/dist/session-wire.d.ts.map +1 -1
- package/dist/session-wire.js +74 -8
- package/dist/session-wire.js.map +1 -1
- package/dist/standard/caller.d.ts +9 -1
- package/dist/standard/caller.d.ts.map +1 -1
- package/dist/standard/caller.js +14 -4
- package/dist/standard/caller.js.map +1 -1
- package/dist/standard/client.d.ts +13 -2
- package/dist/standard/client.d.ts.map +1 -1
- package/dist/standard/client.js +27 -6
- package/dist/standard/client.js.map +1 -1
- package/dist/standard/delegated.d.ts +6 -0
- package/dist/standard/delegated.d.ts.map +1 -1
- package/dist/standard/delegated.js +10 -1
- package/dist/standard/delegated.js.map +1 -1
- package/dist/standard/from-agent.d.ts +2 -0
- package/dist/standard/from-agent.d.ts.map +1 -1
- package/dist/standard/from-agent.js +16 -0
- package/dist/standard/from-agent.js.map +1 -1
- package/dist/standard/index.d.ts +2 -0
- package/dist/standard/index.d.ts.map +1 -1
- package/dist/standard/index.js +4 -0
- package/dist/standard/index.js.map +1 -1
- package/dist/standard/mount.d.ts +7 -0
- package/dist/standard/mount.d.ts.map +1 -1
- package/dist/standard/mount.js +3 -3
- package/dist/standard/mount.js.map +1 -1
- 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 +20 -0
- package/dist/standard/server.d.ts.map +1 -1
- package/dist/standard/server.js +87 -9
- package/dist/standard/server.js.map +1 -1
- package/dist/subject-hop.d.ts +24 -0
- package/dist/subject-hop.d.ts.map +1 -1
- package/dist/subject-hop.js +58 -12
- package/dist/subject-hop.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.map +1 -1
- package/dist/wire-verify.js +4 -0
- package/dist/wire-verify.js.map +1 -1
- package/package.json +5 -5
package/CLAUDE.md
CHANGED
|
@@ -36,9 +36,12 @@ us), `@modelcontextprotocol/sdk`, and any Cloudflare type in core `src/` outside
|
|
|
36
36
|
|
|
37
37
|
## Security invariants (DO NOT BREAK)
|
|
38
38
|
- Every transition fail-closed via `canTaskTransition`; an unknown skill → `rejected`.
|
|
39
|
-
- No task for an unverifiable grant; `task.permissionGrantRef = hashDelegation(grant)
|
|
39
|
+
- No task for an unverifiable grant; `task.permissionGrantRef = hashDelegation(grant)` — also after `resubmit`, which takes only a grant from the task's own principal (RUNB-3).
|
|
40
|
+
- An artifact is its task's: random id, stored under (task, artifact), written once, hash-checked on read (RUNB-2). A session wire verifies only against THIS host's `target` (RUN-9).
|
|
41
|
+
- Every message binds recipient + chain (no unbound form); a `0x…01`/zero delegate, an unknown session-wire caveat and a stale caller signature are refused; a payment park resumes once, via `settlePayment` (spec 445 decision 8, AUDIT §8).
|
|
40
42
|
- Bodies live in the vault (`VaultRef`); task state holds hashes and refs only (A2A-INV-04).
|
|
41
43
|
- Authorization ≠ identity: caveats + assignee decide *what*; the token proves *who*.
|
|
44
|
+
- A credential leaves only to the card's own origin (or a pinned card's endpoint); outbound fetches are public-https, bounded, no redirects (RUNB-9/RUN-16).
|
|
42
45
|
- No long-lived signing key for a claimed agent — KMS/session signer only.
|
|
43
46
|
- A card audience is degraded to `public` on any verification failure; visibility is disclosure, not authorization.
|
|
44
47
|
|
package/README.md
CHANGED
|
@@ -13,7 +13,7 @@ Concretely: an async, delegation-authorized **Agent-to-Agent task transport**. A
|
|
|
13
13
|
All five implementation waves have landed:
|
|
14
14
|
|
|
15
15
|
- **Task runtime core** — `newTaskRecord`, `applyTransition` (fail-closed via `canTaskTransition`), `dispatchTask`, the `TaskStore` port + an in-memory reference implementation, and the `SkillHandler` contract. Unknown skill → `rejected`, never silently dropped.
|
|
16
|
-
- **Delegation-auth gate** — `authorizeA2aMessage`: delegate === requester, timestamp window, target + skill scoping via caveats, on-chain `isRevoked` + ERC-1271 injected fail-closed, signed message, single-use message-id. Plus `buildA2aGrantCaveats` and `hashA2aMessage`.
|
|
16
|
+
- **Delegation-auth gate** — `authorizeA2aMessage`: delegate === requester, a fresh signed `createdAt`, the message's own `recipient` + `chainId` (mandatory on every message — spec 445 decision 8), timestamp window, target + skill scoping via caveats, on-chain `isRevoked` + ERC-1271 injected fail-closed, signed message, single-use message-id. Plus `buildA2aGrantCaveats` and `hashA2aMessage`.
|
|
17
17
|
- **Agent surface** — `createA2aAgent` (message/send → authorize + persist; tasks/get + tasks/cancel with party auth; alarm-driven `processDue`; agent card) + JSON-RPC 2.0 handlers (`dispatchA2aRpc` / `handleA2aRpcBody`) + the `A2aWireAdapter` client over an injected transport.
|
|
18
18
|
- **Vault body residency + signed push** — message and artifact bodies live in the assignee's vault; only hashes/refs appear in task state. Terminal results are delivered as signed push envelopes (`deliverPush` / `verifyPushEnvelope`) with bounded retry, or streamed via SSE framing, or polled via `tasks/get`.
|
|
19
19
|
- **Two-agent acceptance harness** — the happy path, delegation-gate denials at the agent surface, a cross-vault entitlement deposit, and the auth-required round-trip via `resubmit`, all exercised in `test/harness.test.ts`.
|
package/dist/agent.d.ts
CHANGED
|
@@ -9,7 +9,7 @@ import { mintVerificationReceipt, type ReceiptProof, type Sha256, type Verificat
|
|
|
9
9
|
import type { A2aEnforcers } from './grant.js';
|
|
10
10
|
import { type TerminalSigner, type PushSender } from './push.js';
|
|
11
11
|
import { type ApAuthorityExtensionParams } from './authority-extension.js';
|
|
12
|
-
import { type PaymentGate, type SkillPayment } from './payment-gate.js';
|
|
12
|
+
import { type PaymentGate, type PaymentSettlementV1, type SkillPayment } from './payment-gate.js';
|
|
13
13
|
/**
|
|
14
14
|
* Spec 290 §6 Stage-3 — an injected per-Smart-Agent HARD budget. STRUCTURAL (no `rate-control` import —
|
|
15
15
|
* ADR-0034 keeps this package transport/vendor-agnostic); the app wires a `rate-control` HardBudgetStore
|
|
@@ -39,7 +39,8 @@ export interface A2aBudgetPort {
|
|
|
39
39
|
* Absent ⇒ no receipts, byte-identical behavior (INV-303-5).
|
|
40
40
|
*/
|
|
41
41
|
export interface A2aReceiptsConfig {
|
|
42
|
-
/** The verifying agent identity stamped into receipts (this agent's SA — Mode-1 public).
|
|
42
|
+
/** The verifying agent identity stamped into receipts (this agent's SA — Mode-1 public). It is the signer a reader
|
|
43
|
+
* EXPECTS: `sign`'s proof must verify against it (ERC-1271 for an SA, ECDSA for a key address). */
|
|
43
44
|
verifier: string;
|
|
44
45
|
policyVersion: string;
|
|
45
46
|
onReceipt: (minted: Awaited<ReturnType<typeof mintVerificationReceipt>>, ctx: {
|
|
@@ -48,7 +49,9 @@ export interface A2aReceiptsConfig {
|
|
|
48
49
|
skill: string;
|
|
49
50
|
taskId?: Hex;
|
|
50
51
|
}) => Promise<void>;
|
|
51
|
-
/** Injected signer over the canonical receiptHash
|
|
52
|
+
/** Injected signer over the canonical receiptHash; the proof must resolve to `verifier`. REQUIRED for a receipt
|
|
53
|
+
* anyone else is to rely on: since DATA-8 (spec 445) `verifyVerificationReceipt` never returns `valid` for an
|
|
54
|
+
* unsigned receipt — omit ⇒ the receipt is a local log line (`inspectUnverifiedReceipt`), not evidence. */
|
|
52
55
|
sign?: (receiptHash: Sha256) => Promise<ReceiptProof>;
|
|
53
56
|
/** Duty-3 evidence provider (latest block); omit ⇒ blockNumber '0' + zero hash. */
|
|
54
57
|
statusEvidence?: () => Promise<{
|
|
@@ -93,6 +96,7 @@ export interface A2aAgentConfig {
|
|
|
93
96
|
/** Clock + id generators — injected for determinism in tests. */
|
|
94
97
|
now?: () => number;
|
|
95
98
|
newTaskId?: () => Hex;
|
|
99
|
+
/** Default: 32 random bytes (RUNB-2). An injected generator is still held to insert-only per task. */
|
|
96
100
|
newArtifactId?: () => Hex;
|
|
97
101
|
/** Hash of an arbitrary body (default keccak256 via the consumer; here a required injection). */
|
|
98
102
|
hashBody: (data: unknown) => Hex;
|
|
@@ -127,18 +131,28 @@ export interface A2aAgentConfig {
|
|
|
127
131
|
* rejected (fail-closed). */
|
|
128
132
|
handoffPolicy?: HandoffPolicy;
|
|
129
133
|
/** Spec 272 PAY-A2A — the injected x402 payment gate. When a priced skill (handler.payment) is
|
|
130
|
-
* invoked, the gate decides paid/unpaid (the app wires the payments x402 rail). Omit ⇒ priced
|
|
131
|
-
*
|
|
134
|
+
* invoked, the gate decides paid/unpaid (the app wires the payments x402 rail). Omit ⇒ a priced skill
|
|
135
|
+
* NEVER runs: a static one refuses construction (A2A-5), a resolved one parks `input-required` (RUNB-6). */
|
|
132
136
|
paymentGate?: PaymentGate;
|
|
133
137
|
/** Spec 290 §6 Stage-3 — the per-Smart-Agent hard-budget port (post-authority, keyed by the verified
|
|
134
138
|
* principal). Omit ⇒ no Stage-3 budget (authority + single-use message-id still apply). */
|
|
135
139
|
budget?: A2aBudgetPort;
|
|
136
|
-
/** N-2 (seam audit)
|
|
137
|
-
* pushNotificationConfig/set) MUST carry a recent `issuedAt`
|
|
138
|
-
*
|
|
140
|
+
/** N-2 (seam audit) — read/control caller signatures (tasks/get, tasks/cancel, tasks/artifact,
|
|
141
|
+
* pushNotificationConfig/set) MUST carry a recent `issuedAt` within this many seconds, bounding replay of a
|
|
142
|
+
* captured signature to the window. ON BY DEFAULT since spec 445 §9 decision 8: omit ⇒
|
|
143
|
+
* `A2A_CALLER_SIG_MAX_AGE_SEC` (300 s). The only way off is the named opt-out below. */
|
|
139
144
|
callerSigMaxAgeSec?: number;
|
|
145
|
+
/** The explicit, named opt-out of caller-signature freshness (spec 445 decision 8): `true` ⇒ a read/control
|
|
146
|
+
* signature with no `issuedAt` (the legacy unbounded digest) is accepted for the life of the task. For a
|
|
147
|
+
* deployment that must still serve legacy callers; never the default. */
|
|
148
|
+
unsafeAllowUnboundedCallerSignatures?: true;
|
|
140
149
|
/** Spec 303 W3 — verification receipts at the message/send + resubmit terminals. Omit ⇒ none. */
|
|
141
150
|
receipts?: A2aReceiptsConfig;
|
|
151
|
+
/** RUNB-4 — how old a message's signed `createdAt` may be (seconds; default 600). */
|
|
152
|
+
messageMaxAgeSec?: number;
|
|
153
|
+
/** RUNB-8 — how many dispatch passes may fail before a task's handler runs, before the task is rejected
|
|
154
|
+
* (default 3). */
|
|
155
|
+
maxDispatchAttempts?: number;
|
|
142
156
|
}
|
|
143
157
|
export type RpcOk<T> = {
|
|
144
158
|
ok: true;
|
|
@@ -162,7 +176,8 @@ export interface MessageSendParams {
|
|
|
162
176
|
};
|
|
163
177
|
}
|
|
164
178
|
/** Resubmit an auth-required task with a fresh grant (FR-3.5). Carries a NEW signed message (new
|
|
165
|
-
* messageId → no replay) + the input the suspended handler asked for. Only the original sender may
|
|
179
|
+
* messageId → no replay) + the input the suspended handler asked for. Only the original sender may, and
|
|
180
|
+
* only with a grant from the task's OWN principal (RUNB-3) — a grant from any other delegator is refused. */
|
|
166
181
|
export interface ResubmitParams extends MessageSendParams {
|
|
167
182
|
taskId: Hex;
|
|
168
183
|
}
|
|
@@ -249,6 +264,18 @@ export interface A2aAgent {
|
|
|
249
264
|
taskId: Hex;
|
|
250
265
|
registered: true;
|
|
251
266
|
}>>;
|
|
267
|
+
/** Spec 445 §9 decision 8 — RESUME a payment-parked task once its payment settles. The settlement must name exactly
|
|
268
|
+
* what the task awaits (amount, asset, payee, the park's reference) and the gate's `verifySettlement` must show the
|
|
269
|
+
* proof paid exactly that; the rail's settlement id and the park are each consumed once. On success the task moves
|
|
270
|
+
* input-required → working and the next `processDue` runs it with its ORIGINAL arguments (the inbound body is not
|
|
271
|
+
* replaced). A mismatched, unverifiable, replayed or second settlement leaves the task as it is. */
|
|
272
|
+
settlePayment(params: {
|
|
273
|
+
taskId: Hex;
|
|
274
|
+
settlement: PaymentSettlementV1;
|
|
275
|
+
}): Promise<RpcResult<{
|
|
276
|
+
taskId: Hex;
|
|
277
|
+
state: Task['state'];
|
|
278
|
+
}>>;
|
|
252
279
|
/** The alarm() body — process every due task to a next state. Returns the events to fan out (W4 delivery). */
|
|
253
280
|
processDue(): Promise<TaskEvent[]>;
|
|
254
281
|
/**
|
|
@@ -290,5 +317,7 @@ export interface AgentCardAudience {
|
|
|
290
317
|
/** The VERIFIED requester. Required for `private`; absent ⇒ no private skill matches. */
|
|
291
318
|
requester?: string;
|
|
292
319
|
}
|
|
320
|
+
/** Spec 445 §9 decision 8 — the default maximum age of a read/control caller signature (seconds). */
|
|
321
|
+
export declare const A2A_CALLER_SIG_MAX_AGE_SEC = 300;
|
|
293
322
|
export declare function createA2aAgent(config: A2aAgentConfig): A2aAgent;
|
|
294
323
|
//# sourceMappingURL=agent.d.ts.map
|
package/dist/agent.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,KAAK,EAAE,IAAI,EAAc,SAAS,EAAE,UAAU,EAAe,QAAQ,EAAc,MAAM,YAAY,CAAC;AAE7G,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAEjD,OAAO,EAAsB,KAAK,YAAY,EAAE,KAAK,WAAW,EAAE,KAAK,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC7G,OAAO,EACe,KAAK,aAAa,EAAE,KAAK,WAAW,EAAE,MAAM,WAAW,CAAC;AAI9E,OAAO,EACL,uBAAuB,EACvB,KAAK,YAAY,EAEjB,KAAK,MAAM,EACX,KAAK,qBAAqB,EAC3B,MAAM,0CAA0C,CAAC;AAClD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAAe,KAAK,cAAc,EAAE,KAAK,UAAU,EAAE,MAAM,WAAW,CAAC;AAC9E,OAAO,EAAwB,KAAK,0BAA0B,EAAE,MAAM,0BAA0B,CAAC;AACjG,OAAO,EAA4C,KAAK,WAAW,EAAE,KAAK,mBAAmB,EAAE,KAAK,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAE5I;;;;;;GAMG;AACH,MAAM,WAAW,aAAa;IAC5B,OAAO,CAAC,KAAK,EAAE;QAAE,YAAY,EAAE,O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,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE;QACZ,SAAS,EAAE,OAAO,CAAC;QACnB,iBAAiB,EAAE,OAAO,CAAC;QAC3B,sBAAsB,EAAE,OAAO,CAAC;QAChC,sGAAsG;QACtG,UAAU,CAAC,EAAE;YAAE,GAAG,EAAE,MAAM,CAAC;YAAC,QAAQ,EAAE,OAAO,CAAC;YAAC,WAAW,EAAE,MAAM,CAAA;SAAE,EAAE,CAAC;KACxE,CAAC;IACF,wFAAwF;IACxF,MAAM,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,YAAY,CAAA;KAAE,EAAE,CAAC;CAClD;AAED;;;;;;GAMG;AACH,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,QAAQ,GAAG,eAAe,GAAG,SAAS,CAAC;IACjD,yFAAyF;IACzF,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AA8BD,qGAAqG;AACrG,eAAO,MAAM,0BAA0B,MAAM,CAAC;AAS9C,wBAAgB,cAAc,CAAC,MAAM,EAAE,cAAc,GAAG,QAAQ,CAgmB/D"}
|
package/dist/agent.js
CHANGED
|
@@ -4,17 +4,18 @@
|
|
|
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, hashA2aMessage, hashA2aTaskRequest, hashPushConfigParams, hashArtifactParams } from './auth.js';
|
|
11
|
+
import { authorizeA2aMessage, decodeTimestampTerms, hashA2aMessage, hashA2aTaskRequest, hashPushConfigParams, hashArtifactParams } from './auth.js';
|
|
11
12
|
// Spec 303 W3 — the A2A verification-receipt mint point. The primitive (commitment
|
|
12
13
|
// profile, canonical receiptHash, injected signing) lives in the leaf package; the
|
|
13
14
|
// agent only assembles what the auth gate already computed.
|
|
14
15
|
import { mintVerificationReceipt, } from '@agenticprimitives/verification-receipts';
|
|
15
16
|
import { deliverPush } from './push.js';
|
|
16
17
|
import { apAuthorityExtension } from './authority-extension.js';
|
|
17
|
-
import { x402AgentCardExtension } from './payment-gate.js';
|
|
18
|
+
import { x402AgentCardExtension, samePaymentTerms } from './payment-gate.js';
|
|
18
19
|
const EXPOSURE_RANK = {
|
|
19
20
|
public: 0,
|
|
20
21
|
authenticated: 1,
|
|
@@ -38,10 +39,13 @@ function isSkillVisible(h, audience, requester) {
|
|
|
38
39
|
}
|
|
39
40
|
return true;
|
|
40
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;
|
|
41
44
|
const RPC_INVALID_REQUEST = -32600;
|
|
42
45
|
const RPC_UNAUTHORIZED = -32001;
|
|
43
46
|
const RPC_NOT_FOUND = -32004;
|
|
44
47
|
const RPC_BUDGET_EXHAUSTED = -32005;
|
|
48
|
+
const RPC_INTERNAL = -32603;
|
|
45
49
|
const eq = (a, b) => a.toLowerCase() === b.toLowerCase();
|
|
46
50
|
export function createA2aAgent(config) {
|
|
47
51
|
// A2A-5 (seam audit): fail closed at construction — a PRICED handler (declares `payment`) with no
|
|
@@ -66,8 +70,28 @@ export function createA2aAgent(config) {
|
|
|
66
70
|
globalThis.crypto.getRandomValues(b);
|
|
67
71
|
return `0x${Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('')}`;
|
|
68
72
|
};
|
|
69
|
-
|
|
70
|
-
|
|
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
|
+
}
|
|
71
95
|
// AUDIT NEW-A2A-2 — the caller of a read/control op MUST prove control of `caller` by signing the
|
|
72
96
|
// request digest. Fail-closed: missing or invalid signature → UNAUTHORIZED, before any party check.
|
|
73
97
|
async function verifyCaller(method, taskId, caller, signature, paramsHash, issuedAt) {
|
|
@@ -76,13 +100,16 @@ export function createA2aAgent(config) {
|
|
|
76
100
|
// N-2: when the operator configures a freshness window, the caller MUST stamp `issuedAt` and it must be
|
|
77
101
|
// recent — bounding replay of a captured read/control signature to that window instead of the life of
|
|
78
102
|
// the task. Fail-closed: window configured but no/stale/future issuedAt → reject.
|
|
79
|
-
|
|
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;
|
|
80
107
|
const nowSec = Math.floor(now() / 1000);
|
|
81
108
|
if (typeof issuedAt !== 'number' || issuedAt <= 0)
|
|
82
109
|
return { ok: false, code: RPC_UNAUTHORIZED, message: 'issuedAt required (freshness)' };
|
|
83
110
|
if (issuedAt > nowSec + 30)
|
|
84
111
|
return { ok: false, code: RPC_UNAUTHORIZED, message: 'issuedAt in the future' };
|
|
85
|
-
if (nowSec - issuedAt >
|
|
112
|
+
if (nowSec - issuedAt > maxAge)
|
|
86
113
|
return { ok: false, code: RPC_UNAUTHORIZED, message: 'caller signature expired' };
|
|
87
114
|
}
|
|
88
115
|
// N-1: `paramsHash` binds method-specific params (e.g. the push url/token) into the signed digest so a
|
|
@@ -130,7 +157,13 @@ export function createA2aAgent(config) {
|
|
|
130
157
|
toolName: `a2a.${input.message.skill}`,
|
|
131
158
|
argsHash: input.message.bodyHash,
|
|
132
159
|
delegationHash: hashDelegation(input.delegation, config.chainId, config.delegationManager),
|
|
133
|
-
|
|
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
|
+
} })(),
|
|
134
167
|
scopeDecision: input.scopeDecision,
|
|
135
168
|
status: {
|
|
136
169
|
revocation: input.decision === 'allow' ? 'active' : 'unavailable',
|
|
@@ -158,6 +191,27 @@ export function createA2aAgent(config) {
|
|
|
158
191
|
return undefined;
|
|
159
192
|
}
|
|
160
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
|
+
}
|
|
161
215
|
return {
|
|
162
216
|
async messageSend(params) {
|
|
163
217
|
const auth = await authorizeA2aMessage({
|
|
@@ -171,6 +225,8 @@ export function createA2aAgent(config) {
|
|
|
171
225
|
store: config.taskStore,
|
|
172
226
|
now: now(),
|
|
173
227
|
scopeCovers: config.scopeCovers,
|
|
228
|
+
chainId: config.chainId,
|
|
229
|
+
...(config.messageMaxAgeSec !== undefined ? { messageMaxAgeSec: config.messageMaxAgeSec } : {}),
|
|
174
230
|
});
|
|
175
231
|
// NEW-A2A-1: do NOT surface the raw authorization reason — it's an oracle (reveals delegation
|
|
176
232
|
// revocation / party / method-scope state to an unauthorized caller). Return a generic denial.
|
|
@@ -263,40 +319,78 @@ export function createA2aAgent(config) {
|
|
|
263
319
|
delegation: params.delegation, requester: params.requester, message: params.message,
|
|
264
320
|
thisAgentSA: config.agentSA, skill: rec.skill, enforcers: config.enforcers,
|
|
265
321
|
checks: config.checks, store: config.taskStore, now: now(), scopeCovers: config.scopeCovers,
|
|
322
|
+
chainId: config.chainId,
|
|
323
|
+
...(config.messageMaxAgeSec !== undefined ? { messageMaxAgeSec: config.messageMaxAgeSec } : {}),
|
|
266
324
|
});
|
|
267
325
|
if (!auth.ok) {
|
|
268
326
|
await mintReceipt({ decision: 'deny', reasonCode: 'unauthorized', scopeDecision: 'not_evaluated', message: params.message, delegation: params.delegation, taskId: params.taskId });
|
|
269
327
|
return { ok: false, code: RPC_UNAUTHORIZED, message: 'unauthorized' }; // NEW-A2A-1: generic denial
|
|
270
328
|
}
|
|
271
|
-
//
|
|
272
|
-
//
|
|
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);
|
|
359
|
+
};
|
|
273
360
|
try {
|
|
274
361
|
if (!eq(config.hashBody(params.input), params.message.bodyHash)) {
|
|
275
|
-
await
|
|
362
|
+
await release();
|
|
276
363
|
await mintReceipt({ decision: 'deny', reasonCode: 'invalid-request', scopeDecision: 'out_of_scope', principal: auth.principal, message: params.message, delegation: params.delegation, taskId: params.taskId });
|
|
277
364
|
return { ok: false, code: RPC_INVALID_REQUEST, message: 'input does not match signed bodyHash' };
|
|
278
365
|
}
|
|
279
|
-
const bodyRef = await config.vault.write({
|
|
280
|
-
owner: config.agentSA, recordType: `a2a:msg:${params.message.messageId}`, data: params.input,
|
|
281
|
-
});
|
|
282
366
|
const t = applyTransition(rec, 'submitted', { now: now() });
|
|
283
367
|
if (!t.ok) {
|
|
284
|
-
await
|
|
368
|
+
await release();
|
|
285
369
|
return { ok: false, code: RPC_INVALID_REQUEST, message: t.reason };
|
|
286
370
|
}
|
|
287
|
-
|
|
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).
|
|
288
377
|
const updated = {
|
|
289
378
|
...t.record, delegation: params.delegation,
|
|
290
|
-
task: {
|
|
379
|
+
task: {
|
|
380
|
+
...t.record.task, inputHash: params.message.bodyHash,
|
|
381
|
+
permissionGrantRef: hashDelegation(params.delegation, config.chainId, config.delegationManager),
|
|
382
|
+
},
|
|
291
383
|
inbound: [...t.record.inbound, { ...params.message, bodyRef }],
|
|
292
384
|
};
|
|
293
385
|
await config.taskStore.put(updated);
|
|
294
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);
|
|
295
389
|
const receipt = await mintReceipt({ decision: 'allow', reasonCode: 'verified', scopeDecision: 'in_scope', principal: auth.principal, message: params.message, delegation: params.delegation, taskId: params.taskId });
|
|
296
390
|
return { ok: true, result: { taskId: params.taskId, state: 'submitted', ...(receipt ? { receipt } : {}) } };
|
|
297
391
|
}
|
|
298
392
|
catch (e) {
|
|
299
|
-
await
|
|
393
|
+
await release();
|
|
300
394
|
throw e;
|
|
301
395
|
}
|
|
302
396
|
},
|
|
@@ -329,8 +423,10 @@ export function createA2aAgent(config) {
|
|
|
329
423
|
// must not learn which artifact ids exist on task B.
|
|
330
424
|
if (!artifact)
|
|
331
425
|
return { ok: false, code: RPC_NOT_FOUND, message: 'unknown artifact' };
|
|
332
|
-
const
|
|
333
|
-
|
|
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 } };
|
|
334
430
|
},
|
|
335
431
|
async tasksCancel({ taskId, caller, signature, issuedAt }) {
|
|
336
432
|
const rec = await config.taskStore.get(taskId);
|
|
@@ -366,8 +462,10 @@ export function createA2aAgent(config) {
|
|
|
366
462
|
const artifact = rec.artifacts.find((a) => eq(a.artifactId, artifactId));
|
|
367
463
|
if (!artifact)
|
|
368
464
|
return { ok: false, code: RPC_NOT_FOUND, message: 'unknown artifact' };
|
|
369
|
-
const
|
|
370
|
-
|
|
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 } };
|
|
371
469
|
},
|
|
372
470
|
async pushConfigSet({ taskId, caller, signature, url, token, issuedAt }) {
|
|
373
471
|
const rec = await config.taskStore.get(taskId);
|
|
@@ -385,24 +483,133 @@ export function createA2aAgent(config) {
|
|
|
385
483
|
await config.taskStore.put({ ...rec, pushConfig });
|
|
386
484
|
return { ok: true, result: { taskId, registered: true } };
|
|
387
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
|
+
},
|
|
388
549
|
async processDue() {
|
|
389
550
|
const events = [];
|
|
390
551
|
const due = await config.taskStore.listDue(now());
|
|
391
|
-
|
|
392
|
-
// here is indistinguishable, from outside, from one that ran and produced nothing.
|
|
393
|
-
if (due.length)
|
|
394
|
-
console.log('[a2a processDue] due:', due.length, 'agent:', config.agentSA);
|
|
552
|
+
const maxAttempts = Math.max(1, config.maxDispatchAttempts ?? 3);
|
|
395
553
|
for (const taskId of due) {
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
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);
|
|
400
567
|
}
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
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];
|
|
404
612
|
}
|
|
405
|
-
console.log('[a2a processDue] dispatching', rec.skill, taskId);
|
|
406
613
|
// Per-task context: read the input from the vault, persist emitted artifact bodies to the
|
|
407
614
|
// assignee's vault (A2A-INV-04), expose vault/mcp.
|
|
408
615
|
const captured = [];
|
|
@@ -413,7 +620,13 @@ export function createA2aAgent(config) {
|
|
|
413
620
|
mcp: config.mcp,
|
|
414
621
|
emitArtifact: async (a) => {
|
|
415
622
|
const artifactId = newArtifactId();
|
|
416
|
-
|
|
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 });
|
|
417
630
|
captured.push({
|
|
418
631
|
artifactId,
|
|
419
632
|
caseId: a.caseId ?? (`0x${'00'.repeat(32)}`),
|
|
@@ -434,13 +647,18 @@ export function createA2aAgent(config) {
|
|
|
434
647
|
const { record: processed, events: evs } = await dispatchTask(rec, registry, () => ({ ...ctxBase, input }), now(), { ...(config.handoffPolicy ? { handoffPolicy: config.handoffPolicy } : {}), paymentGate: config.paymentGate });
|
|
435
648
|
const merged = { ...processed, artifacts: [...processed.artifacts, ...captured] };
|
|
436
649
|
await config.taskStore.put(merged);
|
|
437
|
-
|
|
438
|
-
//
|
|
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.
|
|
439
652
|
if (isTerminal(merged.task.state) && merged.pushConfig && config.pushSender && config.signTerminal) {
|
|
440
|
-
|
|
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
|
+
}
|
|
441
659
|
}
|
|
660
|
+
return evs;
|
|
442
661
|
}
|
|
443
|
-
return events;
|
|
444
662
|
},
|
|
445
663
|
agentCard(forAudience) {
|
|
446
664
|
// Default to the PUBLIC card. A caller that has not stated an audience has not authenticated
|