@providerkit/agents 0.0.0-stage → 0.2.0
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/LICENSE +21 -0
- package/LICENSE-APACHE-2.0 +202 -0
- package/README.md +2328 -2
- package/THIRD_PARTY_NOTICES.md +521 -0
- package/dist/a2a/auth.d.ts +10 -0
- package/dist/a2a/auth.d.ts.map +1 -0
- package/dist/a2a/auth.js +52 -0
- package/dist/a2a/auth.js.map +1 -0
- package/dist/a2a/client.d.ts +74 -0
- package/dist/a2a/client.d.ts.map +1 -0
- package/dist/a2a/client.js +601 -0
- package/dist/a2a/client.js.map +1 -0
- package/dist/a2a/index.d.ts +22 -0
- package/dist/a2a/index.d.ts.map +1 -0
- package/dist/a2a/index.js +11 -0
- package/dist/a2a/index.js.map +1 -0
- package/dist/a2a/memory-runs.d.ts +62 -0
- package/dist/a2a/memory-runs.d.ts.map +1 -0
- package/dist/a2a/memory-runs.js +349 -0
- package/dist/a2a/memory-runs.js.map +1 -0
- package/dist/a2a/policy.d.ts +15 -0
- package/dist/a2a/policy.d.ts.map +1 -0
- package/dist/a2a/policy.js +114 -0
- package/dist/a2a/policy.js.map +1 -0
- package/dist/a2a/push.d.ts +34 -0
- package/dist/a2a/push.d.ts.map +1 -0
- package/dist/a2a/push.js +180 -0
- package/dist/a2a/push.js.map +1 -0
- package/dist/a2a/remote.d.ts +155 -0
- package/dist/a2a/remote.d.ts.map +1 -0
- package/dist/a2a/remote.js +1196 -0
- package/dist/a2a/remote.js.map +1 -0
- package/dist/a2a/server.d.ts +110 -0
- package/dist/a2a/server.d.ts.map +1 -0
- package/dist/a2a/server.js +1139 -0
- package/dist/a2a/server.js.map +1 -0
- package/dist/a2a/signing.d.ts +21 -0
- package/dist/a2a/signing.d.ts.map +1 -0
- package/dist/a2a/signing.js +305 -0
- package/dist/a2a/signing.js.map +1 -0
- package/dist/a2a/tasks.d.ts +88 -0
- package/dist/a2a/tasks.d.ts.map +1 -0
- package/dist/a2a/tasks.js +170 -0
- package/dist/a2a/tasks.js.map +1 -0
- package/dist/a2a/wire.d.ts +267 -0
- package/dist/a2a/wire.d.ts.map +1 -0
- package/dist/a2a/wire.js +1202 -0
- package/dist/a2a/wire.js.map +1 -0
- package/dist/background-types.d.ts +76 -0
- package/dist/background-types.d.ts.map +1 -0
- package/dist/background-types.js +2 -0
- package/dist/background-types.js.map +1 -0
- package/dist/child.d.ts +25 -0
- package/dist/child.d.ts.map +1 -0
- package/dist/child.js +129 -0
- package/dist/child.js.map +1 -0
- package/dist/code-driver.d.ts +40 -0
- package/dist/code-driver.d.ts.map +1 -0
- package/dist/code-driver.js +2 -0
- package/dist/code-driver.js.map +1 -0
- package/dist/code-mode.d.ts +3 -0
- package/dist/code-mode.d.ts.map +1 -0
- package/dist/code-mode.js +2 -0
- package/dist/code-mode.js.map +1 -0
- package/dist/code-script.d.ts +3 -0
- package/dist/code-script.d.ts.map +1 -0
- package/dist/code-script.js +149 -0
- package/dist/code-script.js.map +1 -0
- package/dist/code.d.ts +75 -0
- package/dist/code.d.ts.map +1 -0
- package/dist/code.js +326 -0
- package/dist/code.js.map +1 -0
- package/dist/compaction.d.ts +15 -0
- package/dist/compaction.d.ts.map +1 -0
- package/dist/compaction.js +168 -0
- package/dist/compaction.js.map +1 -0
- package/dist/delegation.d.ts +135 -0
- package/dist/delegation.d.ts.map +1 -0
- package/dist/delegation.js +401 -0
- package/dist/delegation.js.map +1 -0
- package/dist/evals/driver.d.ts +10 -0
- package/dist/evals/driver.d.ts.map +1 -0
- package/dist/evals/driver.js +192 -0
- package/dist/evals/driver.js.map +1 -0
- package/dist/evals/journal.d.ts +26 -0
- package/dist/evals/journal.d.ts.map +1 -0
- package/dist/evals/journal.js +483 -0
- package/dist/evals/journal.js.map +1 -0
- package/dist/evals/judge.d.ts +31 -0
- package/dist/evals/judge.d.ts.map +1 -0
- package/dist/evals/judge.js +142 -0
- package/dist/evals/judge.js.map +1 -0
- package/dist/evals/report.d.ts +38 -0
- package/dist/evals/report.d.ts.map +1 -0
- package/dist/evals/report.js +241 -0
- package/dist/evals/report.js.map +1 -0
- package/dist/evals/runner.d.ts +24 -0
- package/dist/evals/runner.d.ts.map +1 -0
- package/dist/evals/runner.js +655 -0
- package/dist/evals/runner.js.map +1 -0
- package/dist/evals/scorers.d.ts +36 -0
- package/dist/evals/scorers.d.ts.map +1 -0
- package/dist/evals/scorers.js +259 -0
- package/dist/evals/scorers.js.map +1 -0
- package/dist/evals/simulation.d.ts +7 -0
- package/dist/evals/simulation.d.ts.map +1 -0
- package/dist/evals/simulation.js +38 -0
- package/dist/evals/simulation.js.map +1 -0
- package/dist/evals/testing.d.ts +36 -0
- package/dist/evals/testing.d.ts.map +1 -0
- package/dist/evals/testing.js +87 -0
- package/dist/evals/testing.js.map +1 -0
- package/dist/evals/trajectory.d.ts +11 -0
- package/dist/evals/trajectory.d.ts.map +1 -0
- package/dist/evals/trajectory.js +180 -0
- package/dist/evals/trajectory.js.map +1 -0
- package/dist/evals/types.d.ts +431 -0
- package/dist/evals/types.d.ts.map +1 -0
- package/dist/evals/types.js +4 -0
- package/dist/evals/types.js.map +1 -0
- package/dist/evals.d.ts +14 -0
- package/dist/evals.d.ts.map +1 -0
- package/dist/evals.js +9 -0
- package/dist/evals.js.map +1 -0
- package/dist/extensions.d.ts +33 -0
- package/dist/extensions.d.ts.map +1 -0
- package/dist/extensions.js +188 -0
- package/dist/extensions.js.map +1 -0
- package/dist/handoff.d.ts +58 -0
- package/dist/handoff.d.ts.map +1 -0
- package/dist/handoff.js +160 -0
- package/dist/handoff.js.map +1 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +11 -0
- package/dist/index.js.map +1 -0
- package/dist/input.d.ts +42 -0
- package/dist/input.d.ts.map +1 -0
- package/dist/input.js +266 -0
- package/dist/input.js.map +1 -0
- package/dist/mcp.d.ts +77 -0
- package/dist/mcp.d.ts.map +1 -0
- package/dist/mcp.js +505 -0
- package/dist/mcp.js.map +1 -0
- package/dist/memory-store.d.ts +11 -0
- package/dist/memory-store.d.ts.map +1 -0
- package/dist/memory-store.js +272 -0
- package/dist/memory-store.js.map +1 -0
- package/dist/memory.d.ts +212 -0
- package/dist/memory.d.ts.map +1 -0
- package/dist/memory.js +613 -0
- package/dist/memory.js.map +1 -0
- package/dist/otel.d.ts +74 -0
- package/dist/otel.d.ts.map +1 -0
- package/dist/otel.js +427 -0
- package/dist/otel.js.map +1 -0
- package/dist/progress.d.ts +17 -0
- package/dist/progress.d.ts.map +1 -0
- package/dist/progress.js +193 -0
- package/dist/progress.js.map +1 -0
- package/dist/quickjs.d.ts +19 -0
- package/dist/quickjs.d.ts.map +1 -0
- package/dist/quickjs.js +519 -0
- package/dist/quickjs.js.map +1 -0
- package/dist/recovery.d.ts +10 -0
- package/dist/recovery.d.ts.map +1 -0
- package/dist/recovery.js +62 -0
- package/dist/recovery.js.map +1 -0
- package/dist/request.d.ts +88 -0
- package/dist/request.d.ts.map +1 -0
- package/dist/request.js +422 -0
- package/dist/request.js.map +1 -0
- package/dist/run.d.ts +20 -0
- package/dist/run.d.ts.map +1 -0
- package/dist/run.js +2407 -0
- package/dist/run.js.map +1 -0
- package/dist/runs.d.ts +110 -0
- package/dist/runs.d.ts.map +1 -0
- package/dist/runs.js +438 -0
- package/dist/runs.js.map +1 -0
- package/dist/schema-to-ts.d.ts +4 -0
- package/dist/schema-to-ts.d.ts.map +1 -0
- package/dist/schema-to-ts.js +191 -0
- package/dist/schema-to-ts.js.map +1 -0
- package/dist/session.d.ts +23 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/session.js +137 -0
- package/dist/session.js.map +1 -0
- package/dist/snapshot.d.ts +75 -0
- package/dist/snapshot.d.ts.map +1 -0
- package/dist/snapshot.js +1607 -0
- package/dist/snapshot.js.map +1 -0
- package/dist/steering.d.ts +75 -0
- package/dist/steering.d.ts.map +1 -0
- package/dist/steering.js +214 -0
- package/dist/steering.js.map +1 -0
- package/dist/subagents.d.ts +141 -0
- package/dist/subagents.d.ts.map +1 -0
- package/dist/subagents.js +746 -0
- package/dist/subagents.js.map +1 -0
- package/dist/tool-retry.d.ts +12 -0
- package/dist/tool-retry.d.ts.map +1 -0
- package/dist/tool-retry.js +53 -0
- package/dist/tool-retry.js.map +1 -0
- package/dist/tree.d.ts +98 -0
- package/dist/tree.d.ts.map +1 -0
- package/dist/tree.js +320 -0
- package/dist/tree.js.map +1 -0
- package/dist/types.d.ts +1007 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/workflow-snapshot.d.ts +8 -0
- package/dist/workflow-snapshot.d.ts.map +1 -0
- package/dist/workflow-snapshot.js +276 -0
- package/dist/workflow-snapshot.js.map +1 -0
- package/dist/workflow-types.d.ts +171 -0
- package/dist/workflow-types.d.ts.map +1 -0
- package/dist/workflow-types.js +2 -0
- package/dist/workflow-types.js.map +1 -0
- package/dist/workflow.d.ts +19 -0
- package/dist/workflow.d.ts.map +1 -0
- package/dist/workflow.js +1053 -0
- package/dist/workflow.js.map +1 -0
- package/examples/a2a-remote.ts +85 -0
- package/examples/a2a-server.ts +100 -0
- package/examples/background.ts +59 -0
- package/examples/basic.ts +44 -0
- package/examples/code-mode.ts +76 -0
- package/examples/conversation.ts +57 -0
- package/examples/evals.ts +79 -0
- package/examples/guardrails.ts +56 -0
- package/examples/handoff.ts +79 -0
- package/examples/memory.ts +44 -0
- package/examples/otel.ts +99 -0
- package/examples/specialists.ts +99 -0
- package/examples/steering.ts +69 -0
- package/examples/structured-handoff.ts +92 -0
- package/examples/subagents.ts +127 -0
- package/examples/workflow.ts +74 -0
- package/package.json +114 -4
- package/src/a2a/auth.ts +62 -0
- package/src/a2a/client.ts +733 -0
- package/src/a2a/index.ts +74 -0
- package/src/a2a/memory-runs.ts +448 -0
- package/src/a2a/policy.ts +148 -0
- package/src/a2a/push.ts +251 -0
- package/src/a2a/remote.ts +1652 -0
- package/src/a2a/server.ts +1390 -0
- package/src/a2a/signing.ts +348 -0
- package/src/a2a/tasks.ts +260 -0
- package/src/a2a/wire.ts +1443 -0
- package/src/background-types.ts +86 -0
- package/src/child.ts +181 -0
- package/src/code-driver.ts +48 -0
- package/src/code-mode.ts +12 -0
- package/src/code-script.ts +149 -0
- package/src/code.ts +424 -0
- package/src/compaction.ts +212 -0
- package/src/delegation.ts +694 -0
- package/src/evals/driver.ts +222 -0
- package/src/evals/journal.ts +605 -0
- package/src/evals/judge.ts +188 -0
- package/src/evals/report.ts +295 -0
- package/src/evals/runner.ts +826 -0
- package/src/evals/scorers.ts +339 -0
- package/src/evals/simulation.ts +46 -0
- package/src/evals/testing.ts +126 -0
- package/src/evals/trajectory.ts +223 -0
- package/src/evals/types.ts +463 -0
- package/src/evals.ts +72 -0
- package/src/extensions.ts +247 -0
- package/src/handoff.ts +214 -0
- package/src/index.ts +62 -0
- package/src/input.ts +319 -0
- package/src/mcp.ts +690 -0
- package/src/memory-store.ts +366 -0
- package/src/memory.ts +893 -0
- package/src/otel.ts +568 -0
- package/src/progress.ts +214 -0
- package/src/quickjs.ts +524 -0
- package/src/recovery.ts +90 -0
- package/src/request.ts +513 -0
- package/src/run.ts +3199 -0
- package/src/runs.ts +696 -0
- package/src/schema-to-ts.ts +194 -0
- package/src/session.ts +178 -0
- package/src/snapshot.ts +2099 -0
- package/src/steering.ts +329 -0
- package/src/subagents.ts +1084 -0
- package/src/tool-retry.ts +86 -0
- package/src/tree.ts +366 -0
- package/src/types.ts +944 -0
- package/src/workflow-snapshot.ts +366 -0
- package/src/workflow-types.ts +213 -0
- package/src/workflow.ts +1316 -0
|
@@ -0,0 +1,1139 @@
|
|
|
1
|
+
// Fail-closed serving policy follows Google ADK (Apache-2.0, Google LLC).
|
|
2
|
+
// Generic failures/owner scoping follow Microsoft Agent Framework (MIT, Microsoft Corporation).
|
|
3
|
+
// Public cards and version selection follow Mastra (Apache-2.0, Kepler Software, Inc.).
|
|
4
|
+
import { sleep } from "@providerkit/core";
|
|
5
|
+
import { copyData, equalData, immutableCopy, isRecord, isImageMime, isFileMime, } from "../snapshot.js";
|
|
6
|
+
import { openRequests, requestRecords, untilAbort } from "../tree.js";
|
|
7
|
+
import { authenticateA2A } from "./auth.js";
|
|
8
|
+
import { decodeA2AHttpRequest, readA2AJson } from "./client.js";
|
|
9
|
+
import { checkA2APushConfig, deliverA2APush } from "./push.js";
|
|
10
|
+
import { canonicalA2AJson, hashA2AJson, signAgentCard } from "./signing.js";
|
|
11
|
+
import { a2aTerminal, A2ATaskConflict, taskScope, } from "./tasks.js";
|
|
12
|
+
import { A2AError, a2aLimits, a2aStateClosed, decodeA2AAgentCard, decodeA2ARpcRequest, encodeA2AError, encodeA2AEvent, encodeA2AResult, parseA2AJson, parseA2AVersion, } from "./wire.js";
|
|
13
|
+
export class A2ATaskRejected extends Error {
|
|
14
|
+
constructor() {
|
|
15
|
+
super("The host refused this task.");
|
|
16
|
+
this.name = "A2ATaskRejected";
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/** Maps content only, never settings, instructions or tools. URL parts require the host's
|
|
20
|
+
* prepare callback; this function never fetches them. JSON parts are untrusted input text. */
|
|
21
|
+
export function a2aInput(message, inlineBytes = 10 * 1024 * 1024) {
|
|
22
|
+
let bytes = 0;
|
|
23
|
+
const parts = message.parts.map((part) => {
|
|
24
|
+
if (part.kind === "text")
|
|
25
|
+
return { type: "text", text: part.text };
|
|
26
|
+
if (part.kind === "data")
|
|
27
|
+
return { type: "text", text: `Untrusted message data:\n${canonicalA2AJson(part.data)}` };
|
|
28
|
+
if (part.kind === "url")
|
|
29
|
+
throw new A2AError("protocol", { code: -32005 });
|
|
30
|
+
const raw = part.raw.replaceAll("-", "+").replaceAll("_", "/");
|
|
31
|
+
let decoded;
|
|
32
|
+
try {
|
|
33
|
+
decoded = atob(raw);
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
throw new A2AError("invalid");
|
|
37
|
+
}
|
|
38
|
+
bytes += decoded.length;
|
|
39
|
+
if (bytes > inlineBytes)
|
|
40
|
+
throw new A2AError("limit");
|
|
41
|
+
const data = btoa(decoded);
|
|
42
|
+
if (isImageMime(part.mediaType))
|
|
43
|
+
return { type: "image", data, mimeType: part.mediaType };
|
|
44
|
+
if (isFileMime(part.mediaType))
|
|
45
|
+
return { type: "file", data, mimeType: part.mediaType };
|
|
46
|
+
throw new A2AError("protocol", { code: -32005 });
|
|
47
|
+
});
|
|
48
|
+
return parts;
|
|
49
|
+
}
|
|
50
|
+
function json(value) {
|
|
51
|
+
return parseA2AJson(JSON.stringify(value));
|
|
52
|
+
}
|
|
53
|
+
function object(value) {
|
|
54
|
+
const result = json(value);
|
|
55
|
+
if (!result || typeof result !== "object" || Array.isArray(result))
|
|
56
|
+
throw new A2AError("invalid");
|
|
57
|
+
return result;
|
|
58
|
+
}
|
|
59
|
+
function protocol(code) {
|
|
60
|
+
throw new A2AError("protocol", { code });
|
|
61
|
+
}
|
|
62
|
+
function positive(value) {
|
|
63
|
+
if (!Number.isSafeInteger(value) || value < 1)
|
|
64
|
+
throw new A2AError("invalid");
|
|
65
|
+
return value;
|
|
66
|
+
}
|
|
67
|
+
function historyMessage(message, task) {
|
|
68
|
+
const parts = message.parts
|
|
69
|
+
.filter((part) => part.kind === "text")
|
|
70
|
+
.map((part) => ({ kind: "text", text: part.text }));
|
|
71
|
+
return parts.length
|
|
72
|
+
? {
|
|
73
|
+
kind: "message",
|
|
74
|
+
messageId: message.messageId,
|
|
75
|
+
role: message.role,
|
|
76
|
+
parts,
|
|
77
|
+
taskId: task.id,
|
|
78
|
+
contextId: task.contextId,
|
|
79
|
+
}
|
|
80
|
+
: undefined;
|
|
81
|
+
}
|
|
82
|
+
function context(record) {
|
|
83
|
+
return {
|
|
84
|
+
principal: { owner: record.owner, actorId: record.actorId },
|
|
85
|
+
tenant: record.tenant,
|
|
86
|
+
taskId: record.id,
|
|
87
|
+
contextId: record.contextId,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/** CAS retries only pure record updates, never start/resume/send/cancel or network writes. */
|
|
91
|
+
async function patchTask(tasks, scope, id, update) {
|
|
92
|
+
for (let attempt = 0;; attempt++) {
|
|
93
|
+
const record = await tasks.get(scope, id);
|
|
94
|
+
if (!record)
|
|
95
|
+
protocol(-32001);
|
|
96
|
+
const changes = update(record);
|
|
97
|
+
if (!changes)
|
|
98
|
+
return record;
|
|
99
|
+
try {
|
|
100
|
+
return await tasks.update(scope, id, changes, record.revision);
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
if (!(error instanceof A2ATaskConflict) || attempt === 3)
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
async function receipt(tasks, scope, id, messageId, acceptance, segment) {
|
|
109
|
+
return patchTask(tasks, scope, id, (current) => {
|
|
110
|
+
const message = current.messages.find((m) => m.id === messageId);
|
|
111
|
+
if (!message)
|
|
112
|
+
throw new A2AError("invalid");
|
|
113
|
+
// A host claim may finish before the queue reply fails. Never downgrade that evidence.
|
|
114
|
+
if (message.acceptance === "accepted") {
|
|
115
|
+
if (segment && message.segment !== segment)
|
|
116
|
+
throw new A2ATaskConflict();
|
|
117
|
+
return undefined;
|
|
118
|
+
}
|
|
119
|
+
return {
|
|
120
|
+
messages: current.messages.map((m) => m.id === messageId ? { ...m, acceptance, ...(segment ? { segment } : {}) } : m),
|
|
121
|
+
...(segment && (!current.segment || current.segment === message.source) ? { segment } : {}),
|
|
122
|
+
};
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
/** Web-standard handler. Work belongs to runs, not to the request or a stream reader. The
|
|
126
|
+
* host must retain the process for memory runs; production uses a durable run-service binding. */
|
|
127
|
+
export function createA2AServer(options) {
|
|
128
|
+
if (!options.authenticate && !options.allowAnonymous)
|
|
129
|
+
throw new TypeError("Provide authenticate before serving tasks. Use allowAnonymous only for local development.");
|
|
130
|
+
const { tasks, runs } = options;
|
|
131
|
+
const { blockMs: block = 60_000, inlineBytes = 10 * 1024 * 1024, pushConfigs = 10, hops: maxHops = 16, ...wireLimits } = options.limits ?? {};
|
|
132
|
+
const limits = a2aLimits(wireLimits);
|
|
133
|
+
const blockMs = positive(block);
|
|
134
|
+
positive(inlineBytes);
|
|
135
|
+
positive(pushConfigs);
|
|
136
|
+
positive(maxHops);
|
|
137
|
+
const base = new URL(options.card.url);
|
|
138
|
+
if (base.username ||
|
|
139
|
+
base.password ||
|
|
140
|
+
base.search ||
|
|
141
|
+
base.hash ||
|
|
142
|
+
!["https:", "http:"].includes(base.protocol))
|
|
143
|
+
throw new A2AError("invalid");
|
|
144
|
+
base.pathname = `${base.pathname.replace(/\/+$/, "")}/`;
|
|
145
|
+
const rpcUrl = new URL("jsonrpc", base);
|
|
146
|
+
const restUrl = new URL("rest", base);
|
|
147
|
+
const cardPath = new URL(".well-known/agent-card.json", base).pathname;
|
|
148
|
+
const stopped = new AbortController();
|
|
149
|
+
const watchers = new Map();
|
|
150
|
+
async function principal(request) {
|
|
151
|
+
return options.authenticate
|
|
152
|
+
? authenticateA2A(request, options.authenticate)
|
|
153
|
+
: options.allowAnonymous
|
|
154
|
+
? { owner: "anonymous", actorId: "anonymous" }
|
|
155
|
+
: null;
|
|
156
|
+
}
|
|
157
|
+
function scope(p) {
|
|
158
|
+
return { ...p, ...(options.tenant ? { tenant: options.tenant } : {}) };
|
|
159
|
+
}
|
|
160
|
+
async function access(s, operation, taskId, request) {
|
|
161
|
+
if (request) {
|
|
162
|
+
const current = await principal(request);
|
|
163
|
+
if (!current || current.owner !== s.owner || current.actorId !== s.actorId)
|
|
164
|
+
protocol(-32001);
|
|
165
|
+
}
|
|
166
|
+
if (options.authorize &&
|
|
167
|
+
!(await options.authorize({
|
|
168
|
+
principal: { owner: s.owner, actorId: s.actorId },
|
|
169
|
+
tenant: s.tenant,
|
|
170
|
+
operation,
|
|
171
|
+
taskId,
|
|
172
|
+
})))
|
|
173
|
+
protocol(-32001);
|
|
174
|
+
}
|
|
175
|
+
async function get(s, id, operation, request) {
|
|
176
|
+
await access(s, operation, id, request);
|
|
177
|
+
const record = await tasks.get(s, id);
|
|
178
|
+
if (!record)
|
|
179
|
+
protocol(-32001);
|
|
180
|
+
return record;
|
|
181
|
+
}
|
|
182
|
+
function visibleRequest(request, record) {
|
|
183
|
+
return (request.scope.actorId === record.actorId &&
|
|
184
|
+
(request.ask.type === "question" ||
|
|
185
|
+
(request.ask.type === "approval" && options.remoteApprovals === true) ||
|
|
186
|
+
(request.ask.type === "client" && options.remoteClientTools === true)) &&
|
|
187
|
+
(!options.exposeRequest || options.exposeRequest(immutableCopy(request), context(record))));
|
|
188
|
+
}
|
|
189
|
+
function offered(row, record) {
|
|
190
|
+
return openRequests(row.snapshot).filter((request) => request.scope.expiresAt > Date.now() && visibleRequest(request, record));
|
|
191
|
+
}
|
|
192
|
+
function requestMessage(record, messageId, requests) {
|
|
193
|
+
const data = requests.map((r) => ({
|
|
194
|
+
id: r.id,
|
|
195
|
+
type: r.ask.type,
|
|
196
|
+
...(r.ask.type === "client" ? { schema: r.ask.resultSchema } : { message: r.ask.message }),
|
|
197
|
+
...(r.ask.type === "question"
|
|
198
|
+
? {
|
|
199
|
+
choices: r.ask.choices,
|
|
200
|
+
multiple: r.ask.multiple,
|
|
201
|
+
freeText: r.ask.freeText,
|
|
202
|
+
schema: r.ask.schema,
|
|
203
|
+
}
|
|
204
|
+
: {}),
|
|
205
|
+
expiresAt: r.scope.expiresAt,
|
|
206
|
+
...(r.problem
|
|
207
|
+
? {
|
|
208
|
+
problem: {
|
|
209
|
+
code: r.problem.code,
|
|
210
|
+
message: "That answer was not accepted. Check the question and send a new answer.",
|
|
211
|
+
},
|
|
212
|
+
}
|
|
213
|
+
: {}),
|
|
214
|
+
}));
|
|
215
|
+
return {
|
|
216
|
+
kind: "message",
|
|
217
|
+
role: "agent",
|
|
218
|
+
taskId: record.id,
|
|
219
|
+
contextId: record.contextId,
|
|
220
|
+
messageId,
|
|
221
|
+
parts: [
|
|
222
|
+
{
|
|
223
|
+
kind: "text",
|
|
224
|
+
text: requests
|
|
225
|
+
.map((r) => r.ask.type === "client"
|
|
226
|
+
? "The host needs a client result."
|
|
227
|
+
: (r.ask.message ?? "An action needs approval."))
|
|
228
|
+
.join("\n"),
|
|
229
|
+
},
|
|
230
|
+
{ kind: "data", data: object({ requests: data }) },
|
|
231
|
+
],
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
async function project(record, row) {
|
|
235
|
+
let state = record.state;
|
|
236
|
+
let message;
|
|
237
|
+
let parts = [];
|
|
238
|
+
const say = (text) => {
|
|
239
|
+
message = {
|
|
240
|
+
kind: "message",
|
|
241
|
+
role: "agent",
|
|
242
|
+
taskId: record.id,
|
|
243
|
+
contextId: record.contextId,
|
|
244
|
+
messageId: `${record.id}:status`,
|
|
245
|
+
parts: [{ kind: "text", text }],
|
|
246
|
+
};
|
|
247
|
+
};
|
|
248
|
+
if (!row) {
|
|
249
|
+
if (record.messages.some((m) => m.acceptance === "unknown") ||
|
|
250
|
+
(record.state !== "rejected" && Date.now() - record.createdAt >= 60_000)) {
|
|
251
|
+
state = "unknown";
|
|
252
|
+
say("The task may have started. Check its status before sending more work.");
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
else if (row.status === "cancelled" && row.outcome?.status !== "completed")
|
|
256
|
+
state = "canceled";
|
|
257
|
+
else if (row.status === "failed" && row.outcome?.status !== "completed") {
|
|
258
|
+
state = "failed";
|
|
259
|
+
say("The task could not finish. Check with the host before starting it again.");
|
|
260
|
+
}
|
|
261
|
+
else if ((row.status === "queued" || row.status === "running") &&
|
|
262
|
+
row.outcome?.status !== "completed")
|
|
263
|
+
state = row.status === "queued" && record.messages.length === 1 ? "submitted" : "working";
|
|
264
|
+
else if (row.outcome) {
|
|
265
|
+
const result = row.outcome;
|
|
266
|
+
switch (result.status) {
|
|
267
|
+
case "completed":
|
|
268
|
+
state = "completed";
|
|
269
|
+
parts = structuredClone((await options.projectOutput?.(result, context(record))) ?? []);
|
|
270
|
+
if (parts.length)
|
|
271
|
+
message = {
|
|
272
|
+
kind: "message",
|
|
273
|
+
role: "agent",
|
|
274
|
+
messageId: `${record.id}:answer`,
|
|
275
|
+
taskId: record.id,
|
|
276
|
+
contextId: record.contextId,
|
|
277
|
+
parts: structuredClone(parts),
|
|
278
|
+
};
|
|
279
|
+
break;
|
|
280
|
+
case "cancelled":
|
|
281
|
+
state = "canceled";
|
|
282
|
+
say("The task stopped. Work already sent to another service may still finish.");
|
|
283
|
+
break;
|
|
284
|
+
case "limited":
|
|
285
|
+
state = "failed";
|
|
286
|
+
say(options.describeFailure?.({ limit: result.limit }) ??
|
|
287
|
+
"The task reached its limit. Check its saved result before starting more work.");
|
|
288
|
+
break;
|
|
289
|
+
case "failed":
|
|
290
|
+
state = "failed";
|
|
291
|
+
say(options.describeFailure?.(result.error) ??
|
|
292
|
+
"The task could not finish. Check with the host before starting it again.");
|
|
293
|
+
break;
|
|
294
|
+
case "suspended": {
|
|
295
|
+
const requests = offered(row, record);
|
|
296
|
+
state = requests.length ? "input_required" : "working";
|
|
297
|
+
if (Date.now() >= row.snapshot.tree.startedAt + row.snapshot.tree.limits.elapsedMs) {
|
|
298
|
+
state = "failed";
|
|
299
|
+
say("The task waited too long for an answer. Start a new task.");
|
|
300
|
+
break;
|
|
301
|
+
}
|
|
302
|
+
if (requests.length)
|
|
303
|
+
message = requestMessage(record, `${record.id}:request:${row.snapshot.attemptId}`, requests);
|
|
304
|
+
else
|
|
305
|
+
say(row.wakeAt === undefined
|
|
306
|
+
? "Waiting for the operator to continue this task."
|
|
307
|
+
: "Waiting for the scheduled continuation.");
|
|
308
|
+
break;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
const publicTask = {
|
|
313
|
+
kind: "task",
|
|
314
|
+
id: record.id,
|
|
315
|
+
contextId: record.contextId,
|
|
316
|
+
status: {
|
|
317
|
+
state,
|
|
318
|
+
...(message ? { message } : {}),
|
|
319
|
+
timestamp: new Date(record.updatedAt).toISOString(),
|
|
320
|
+
},
|
|
321
|
+
...(parts.length ? { artifacts: [{ artifactId: "answer", parts }] } : {}),
|
|
322
|
+
};
|
|
323
|
+
// Validate all host projections before putting them on the wire or in public history.
|
|
324
|
+
encodeA2AEvent(publicTask, { version: "1.0", binding: "JSONRPC" });
|
|
325
|
+
return publicTask;
|
|
326
|
+
}
|
|
327
|
+
async function view(s, id, operation = "GetTask", request, historyLength = 100) {
|
|
328
|
+
let record = await get(s, id, operation, request);
|
|
329
|
+
const row = record.segment ? await runs.read(s.owner, record.segment) : undefined;
|
|
330
|
+
if (row && row.snapshot.runId !== id)
|
|
331
|
+
throw new A2AError("invalid");
|
|
332
|
+
const task = await project(record, row);
|
|
333
|
+
const publicMessage = task.status.message;
|
|
334
|
+
record = await patchTask(tasks, s, id, (current) => {
|
|
335
|
+
// A continuation can win while this read projects an older segment. Never regress it.
|
|
336
|
+
if (current.segment !== record.segment)
|
|
337
|
+
return undefined;
|
|
338
|
+
const history = publicMessage && !current.history.some((m) => m.messageId === publicMessage.messageId)
|
|
339
|
+
? [...current.history, publicMessage].slice(-100)
|
|
340
|
+
: current.history;
|
|
341
|
+
if (current.state === task.status.state && history === current.history)
|
|
342
|
+
return undefined;
|
|
343
|
+
if (a2aTerminal(current.state) && current.state !== task.status.state)
|
|
344
|
+
return undefined;
|
|
345
|
+
return { state: task.status.state, history };
|
|
346
|
+
});
|
|
347
|
+
if (row && record.segment !== row.id)
|
|
348
|
+
return view(s, id, operation, request, historyLength);
|
|
349
|
+
task.status.timestamp = new Date(record.updatedAt).toISOString();
|
|
350
|
+
if (historyLength > 0) {
|
|
351
|
+
const requests = new Map(row
|
|
352
|
+
? [...requestRecords(row.snapshot)].map(({ record: r }) => [r.request.id, r.request])
|
|
353
|
+
: []);
|
|
354
|
+
// Stored projections are a cache, not continuing permission. Rebuild agent content from
|
|
355
|
+
// the current output/request policy; obsolete statuses have no independent disclosure.
|
|
356
|
+
const history = record.history.flatMap((message) => {
|
|
357
|
+
if (message.role === "user")
|
|
358
|
+
return [message];
|
|
359
|
+
if (message.messageId === publicMessage?.messageId)
|
|
360
|
+
return [publicMessage];
|
|
361
|
+
if (!message.messageId.startsWith(`${id}:request:`))
|
|
362
|
+
return [];
|
|
363
|
+
const visible = message.parts.flatMap((part) => {
|
|
364
|
+
if (part.kind !== "data" || !isRecord(part.data) || !Array.isArray(part.data.requests))
|
|
365
|
+
return [];
|
|
366
|
+
return part.data.requests.flatMap((value) => {
|
|
367
|
+
const request = isRecord(value) && typeof value.id === "string" ? requests.get(value.id) : undefined;
|
|
368
|
+
return request && visibleRequest(request, record) ? [request] : [];
|
|
369
|
+
});
|
|
370
|
+
});
|
|
371
|
+
return visible.length ? [requestMessage(record, message.messageId, visible)] : [];
|
|
372
|
+
});
|
|
373
|
+
task.history = structuredClone(history.slice(-Math.min(historyLength, 100)));
|
|
374
|
+
}
|
|
375
|
+
await access(s, operation, id, request);
|
|
376
|
+
return { task, record, row };
|
|
377
|
+
}
|
|
378
|
+
async function notify(s, id) {
|
|
379
|
+
if (!options.push)
|
|
380
|
+
return;
|
|
381
|
+
const current = await view(s, id, "Push");
|
|
382
|
+
await deliverA2APush({
|
|
383
|
+
tasks,
|
|
384
|
+
scope: s,
|
|
385
|
+
taskId: id,
|
|
386
|
+
event: current.task,
|
|
387
|
+
policy: options.push,
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
function watch(s, id) {
|
|
391
|
+
if (!options.push)
|
|
392
|
+
return;
|
|
393
|
+
const key = JSON.stringify([s, id]);
|
|
394
|
+
if (watchers.has(key) || stopped.signal.aborted)
|
|
395
|
+
return;
|
|
396
|
+
const watching = (async () => {
|
|
397
|
+
for (;;) {
|
|
398
|
+
stopped.signal.throwIfAborted();
|
|
399
|
+
const current = await view(s, id, "Push");
|
|
400
|
+
await notify(s, id);
|
|
401
|
+
if (a2aStateClosed(current.task.status.state))
|
|
402
|
+
return;
|
|
403
|
+
await sleep(250, stopped.signal);
|
|
404
|
+
}
|
|
405
|
+
})()
|
|
406
|
+
.catch(() => {
|
|
407
|
+
/* No replay after uncertain writes or revoked access. Host can refresh. */
|
|
408
|
+
})
|
|
409
|
+
.finally(() => {
|
|
410
|
+
watchers.delete(key);
|
|
411
|
+
});
|
|
412
|
+
watchers.set(key, watching);
|
|
413
|
+
}
|
|
414
|
+
async function pushConfig(s, config, d) {
|
|
415
|
+
if (!options.push)
|
|
416
|
+
protocol(-32003);
|
|
417
|
+
const validated = structuredClone({
|
|
418
|
+
...config,
|
|
419
|
+
id: config.id ?? crypto.randomUUID(),
|
|
420
|
+
...(s.tenant ? { tenant: s.tenant } : {}),
|
|
421
|
+
});
|
|
422
|
+
await checkA2APushConfig(validated, s, options.push);
|
|
423
|
+
return { config: validated, dialect: d };
|
|
424
|
+
}
|
|
425
|
+
async function accept(s, params, request, dialect) {
|
|
426
|
+
const message = params.message;
|
|
427
|
+
const fingerprint = await hashA2AJson(object(params));
|
|
428
|
+
const existing = await tasks.findMessage(s, message.messageId);
|
|
429
|
+
if (existing) {
|
|
430
|
+
await access(s, "SendMessage", existing.id, request);
|
|
431
|
+
if (existing.messages.find((m) => m.id === message.messageId)?.fingerprint !== fingerprint)
|
|
432
|
+
protocol(-32602);
|
|
433
|
+
return existing.id;
|
|
434
|
+
}
|
|
435
|
+
if (message.referenceTaskIds?.length)
|
|
436
|
+
protocol(-32004);
|
|
437
|
+
if (message.taskId) {
|
|
438
|
+
const current = await view(s, message.taskId, "SendMessage", request);
|
|
439
|
+
if (message.contextId && message.contextId !== current.record.contextId)
|
|
440
|
+
protocol(-32602);
|
|
441
|
+
if (a2aTerminal(current.task.status.state) ||
|
|
442
|
+
(current.record.cancel && current.record.cancel !== "refused") ||
|
|
443
|
+
current.record.messages.some((receipt) => receipt.kind !== "start" && receipt.acceptance !== "accepted"))
|
|
444
|
+
protocol(-32004);
|
|
445
|
+
if (!current.record.segment || !current.row)
|
|
446
|
+
protocol(-32004);
|
|
447
|
+
if (params.configuration?.pushNotificationConfig)
|
|
448
|
+
protocol(-32004);
|
|
449
|
+
const open = offered(current.row, current.record);
|
|
450
|
+
let answers;
|
|
451
|
+
let input;
|
|
452
|
+
const kind = current.task.status.state === "input_required" ? "resume" : "steer";
|
|
453
|
+
if (kind === "resume") {
|
|
454
|
+
const maps = message.parts.filter((part) => part.kind === "data" && isRecord(part.data) && Object.hasOwn(part.data, "answers"));
|
|
455
|
+
let values;
|
|
456
|
+
if (maps.length === 1 &&
|
|
457
|
+
maps[0]?.kind === "data" &&
|
|
458
|
+
isRecord(maps[0].data) &&
|
|
459
|
+
isRecord(maps[0].data.answers))
|
|
460
|
+
values = maps[0].data.answers;
|
|
461
|
+
else if (!maps.length &&
|
|
462
|
+
message.parts.every((part) => part.kind === "text") &&
|
|
463
|
+
open.length === 1 &&
|
|
464
|
+
open[0]?.ask.type === "question" &&
|
|
465
|
+
open[0].ask.freeText === true)
|
|
466
|
+
values = {
|
|
467
|
+
[open[0].id]: {
|
|
468
|
+
type: "answer",
|
|
469
|
+
answer: {
|
|
470
|
+
text: message.parts
|
|
471
|
+
.map((part) => (part.kind === "text" ? part.text : ""))
|
|
472
|
+
.join("\n"),
|
|
473
|
+
},
|
|
474
|
+
},
|
|
475
|
+
};
|
|
476
|
+
else
|
|
477
|
+
protocol(-32602);
|
|
478
|
+
if (!Object.keys(values).length ||
|
|
479
|
+
Object.keys(values).some((id) => !open.some((r) => r.id === id)))
|
|
480
|
+
protocol(-32602);
|
|
481
|
+
answers = Object.fromEntries(Object.entries(values).map(([id, answer]) => [
|
|
482
|
+
id,
|
|
483
|
+
{
|
|
484
|
+
via: "a2a",
|
|
485
|
+
...taskScope(s),
|
|
486
|
+
taskId: current.record.id,
|
|
487
|
+
messageId: message.messageId,
|
|
488
|
+
requestId: id,
|
|
489
|
+
answer: copyData(answer),
|
|
490
|
+
},
|
|
491
|
+
]));
|
|
492
|
+
}
|
|
493
|
+
else {
|
|
494
|
+
if (!runs.send ||
|
|
495
|
+
current.row.status !== "running" ||
|
|
496
|
+
!message.parts.every((p) => p.kind === "text"))
|
|
497
|
+
protocol(-32004);
|
|
498
|
+
input = a2aInput(message, inlineBytes);
|
|
499
|
+
}
|
|
500
|
+
const publicMessage = historyMessage(message, current.record);
|
|
501
|
+
const claim = {
|
|
502
|
+
id: message.messageId,
|
|
503
|
+
fingerprint,
|
|
504
|
+
kind,
|
|
505
|
+
acceptance: "pending",
|
|
506
|
+
source: current.record.segment,
|
|
507
|
+
...(answers ? { answers } : {}),
|
|
508
|
+
};
|
|
509
|
+
// One CAS before the effect. A competing continuation is refused, not retried.
|
|
510
|
+
await tasks.update(s, current.record.id, {
|
|
511
|
+
messages: [...current.record.messages, claim],
|
|
512
|
+
history: [...current.record.history, ...(publicMessage ? [publicMessage] : [])].slice(-100),
|
|
513
|
+
state: "working",
|
|
514
|
+
}, current.record.revision);
|
|
515
|
+
let next;
|
|
516
|
+
try {
|
|
517
|
+
await access(s, kind, current.record.id, request);
|
|
518
|
+
if (answers)
|
|
519
|
+
next = (await runs.resume(s.owner, current.record.segment, answers)).id;
|
|
520
|
+
else {
|
|
521
|
+
if (!runs.send ||
|
|
522
|
+
input === undefined ||
|
|
523
|
+
(typeof input === "object" && "messages" in input))
|
|
524
|
+
protocol(-32004);
|
|
525
|
+
await runs.send(s.owner, current.record.segment, {
|
|
526
|
+
id: message.messageId,
|
|
527
|
+
content: typeof input === "string" ? input : [...input],
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
await receipt(tasks, s, current.record.id, message.messageId, "accepted", next);
|
|
531
|
+
}
|
|
532
|
+
catch (error) {
|
|
533
|
+
await receipt(tasks, s, current.record.id, message.messageId, "unknown", next);
|
|
534
|
+
throw error;
|
|
535
|
+
}
|
|
536
|
+
watch(s, current.record.id);
|
|
537
|
+
return current.record.id;
|
|
538
|
+
}
|
|
539
|
+
if (message.contextId && !(await tasks.hasContext(s, message.contextId)))
|
|
540
|
+
protocol(-32602);
|
|
541
|
+
const hops = params.metadata?.["providerkit.hops"] ?? 0;
|
|
542
|
+
if (typeof hops !== "number" || !Number.isSafeInteger(hops) || hops < 0 || hops > maxHops)
|
|
543
|
+
protocol(-32602);
|
|
544
|
+
const preparedInput = options.prepare ? undefined : a2aInput(message, inlineBytes);
|
|
545
|
+
const id = crypto.randomUUID();
|
|
546
|
+
const record = {
|
|
547
|
+
...s,
|
|
548
|
+
id,
|
|
549
|
+
contextId: message.contextId ?? crypto.randomUUID(),
|
|
550
|
+
hops,
|
|
551
|
+
state: "submitted",
|
|
552
|
+
messages: [{ id: message.messageId, fingerprint, kind: "start", acceptance: "pending" }],
|
|
553
|
+
history: [],
|
|
554
|
+
push: [],
|
|
555
|
+
deliveries: [],
|
|
556
|
+
createdAt: Date.now(),
|
|
557
|
+
updatedAt: Date.now(),
|
|
558
|
+
revision: "",
|
|
559
|
+
};
|
|
560
|
+
const publicMessage = historyMessage(message, record);
|
|
561
|
+
if (publicMessage)
|
|
562
|
+
record.history.push(publicMessage);
|
|
563
|
+
if (params.configuration?.pushNotificationConfig)
|
|
564
|
+
record.push.push(await pushConfig(s, { ...params.configuration.pushNotificationConfig, taskId: id }, dialect));
|
|
565
|
+
const created = await tasks.create(record);
|
|
566
|
+
if (!created.created)
|
|
567
|
+
return created.record.id;
|
|
568
|
+
let segment;
|
|
569
|
+
try {
|
|
570
|
+
await access(s, "start", id, request);
|
|
571
|
+
const start = { runId: id, ...(options.sessions ? { sessionId: record.contextId } : {}) };
|
|
572
|
+
// The request's abort only detaches after reservation. No uncertain start is repeated.
|
|
573
|
+
if (options.prepare) {
|
|
574
|
+
const input = await options.prepare(immutableCopy(message), {
|
|
575
|
+
principal: { owner: s.owner, actorId: s.actorId },
|
|
576
|
+
request,
|
|
577
|
+
});
|
|
578
|
+
await access(s, "start", id, request);
|
|
579
|
+
segment = (await options.runs.start(s.owner, input, start)).id;
|
|
580
|
+
}
|
|
581
|
+
else {
|
|
582
|
+
if (preparedInput === undefined)
|
|
583
|
+
throw new A2AError("invalid");
|
|
584
|
+
segment = (await options.runs.start(s.owner, preparedInput, start)).id;
|
|
585
|
+
}
|
|
586
|
+
await receipt(tasks, s, id, message.messageId, "accepted", segment);
|
|
587
|
+
}
|
|
588
|
+
catch (error) {
|
|
589
|
+
await receipt(tasks, s, id, message.messageId, error instanceof A2ATaskRejected ? "accepted" : "unknown", segment);
|
|
590
|
+
if (error instanceof A2ATaskRejected) {
|
|
591
|
+
await patchTask(tasks, s, id, () => ({ state: "rejected" }));
|
|
592
|
+
return id;
|
|
593
|
+
}
|
|
594
|
+
throw error;
|
|
595
|
+
}
|
|
596
|
+
watch(s, id);
|
|
597
|
+
return id;
|
|
598
|
+
}
|
|
599
|
+
async function wait(s, id, request, historyLength) {
|
|
600
|
+
const deadline = Date.now() + blockMs;
|
|
601
|
+
for (;;) {
|
|
602
|
+
const current = await view(s, id, "SendMessage", request, historyLength);
|
|
603
|
+
if (a2aStateClosed(current.task.status.state) || Date.now() >= deadline)
|
|
604
|
+
return current.task;
|
|
605
|
+
await sleep(Math.min(25, Math.max(1, deadline - Date.now())), request.signal);
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
async function* events(s, id, request, signal, historyLength) {
|
|
609
|
+
let current = await view(s, id, "SubscribeToTask", request, historyLength);
|
|
610
|
+
yield current.task;
|
|
611
|
+
let previous = canonicalA2AJson(object(current.task));
|
|
612
|
+
let operation;
|
|
613
|
+
let hasArtifact = !!current.task.artifacts?.length;
|
|
614
|
+
while (!a2aStateClosed(current.task.status.state)) {
|
|
615
|
+
signal.throwIfAborted();
|
|
616
|
+
if (!current.record.segment)
|
|
617
|
+
throw new A2AError("stream-cut");
|
|
618
|
+
const segment = current.record.segment;
|
|
619
|
+
for await (const stored of runs.observe(s.owner, segment, 0, signal)) {
|
|
620
|
+
signal.throwIfAborted();
|
|
621
|
+
await access(s, "SubscribeToTask", id, request);
|
|
622
|
+
if (stored.type === "agent.gap" || stored.type === "agent.resync") {
|
|
623
|
+
current = await view(s, id, "SubscribeToTask", request, historyLength);
|
|
624
|
+
yield current.task;
|
|
625
|
+
previous = canonicalA2AJson(object(current.task));
|
|
626
|
+
operation = undefined;
|
|
627
|
+
hasArtifact = !!current.task.artifacts?.length;
|
|
628
|
+
if (a2aStateClosed(current.task.status.state))
|
|
629
|
+
return;
|
|
630
|
+
continue;
|
|
631
|
+
}
|
|
632
|
+
const delta = await text(stored, current.record);
|
|
633
|
+
if (delta) {
|
|
634
|
+
const append = operation === delta.operation && hasArtifact;
|
|
635
|
+
yield {
|
|
636
|
+
kind: "artifact-update",
|
|
637
|
+
taskId: id,
|
|
638
|
+
contextId: current.record.contextId,
|
|
639
|
+
artifact: { artifactId: "answer", parts: [{ kind: "text", text: delta.text }] },
|
|
640
|
+
append,
|
|
641
|
+
lastChunk: false,
|
|
642
|
+
};
|
|
643
|
+
operation = delta.operation;
|
|
644
|
+
hasArtifact = true;
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
// Every authoritative read goes through emission before closure, including a continuation
|
|
648
|
+
// that finishes entirely between polls of an operator-only suspension.
|
|
649
|
+
for (;;) {
|
|
650
|
+
current = await view(s, id, "SubscribeToTask", request, historyLength);
|
|
651
|
+
const value = canonicalA2AJson(object(current.task));
|
|
652
|
+
if (value !== previous) {
|
|
653
|
+
if (current.task.artifacts?.length)
|
|
654
|
+
for (const artifact of current.task.artifacts)
|
|
655
|
+
yield {
|
|
656
|
+
kind: "artifact-update",
|
|
657
|
+
taskId: id,
|
|
658
|
+
contextId: current.record.contextId,
|
|
659
|
+
artifact,
|
|
660
|
+
append: false,
|
|
661
|
+
lastChunk: true,
|
|
662
|
+
};
|
|
663
|
+
else if (hasArtifact)
|
|
664
|
+
yield {
|
|
665
|
+
kind: "artifact-update",
|
|
666
|
+
taskId: id,
|
|
667
|
+
contextId: current.record.contextId,
|
|
668
|
+
artifact: { artifactId: "answer", parts: [{ kind: "text", text: "" }] },
|
|
669
|
+
append: false,
|
|
670
|
+
lastChunk: true,
|
|
671
|
+
};
|
|
672
|
+
yield {
|
|
673
|
+
kind: "status-update",
|
|
674
|
+
taskId: id,
|
|
675
|
+
contextId: current.record.contextId,
|
|
676
|
+
status: current.task.status,
|
|
677
|
+
};
|
|
678
|
+
previous = value;
|
|
679
|
+
hasArtifact = !!current.task.artifacts?.length;
|
|
680
|
+
}
|
|
681
|
+
if (a2aStateClosed(current.task.status.state))
|
|
682
|
+
return;
|
|
683
|
+
if (current.record.segment !== segment)
|
|
684
|
+
break;
|
|
685
|
+
if (current.row && ["queued", "running"].includes(current.row.status))
|
|
686
|
+
throw new A2AError("stream-cut");
|
|
687
|
+
await sleep(250, signal);
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
async function text(stored, record) {
|
|
692
|
+
const data = stored.data;
|
|
693
|
+
if (!options.projectText ||
|
|
694
|
+
stored.type !== "agent" ||
|
|
695
|
+
!isRecord(data) ||
|
|
696
|
+
data.type !== "model_chunk" ||
|
|
697
|
+
data.runId !== record.id ||
|
|
698
|
+
typeof data.operationId !== "string" ||
|
|
699
|
+
typeof data.attemptId !== "string" ||
|
|
700
|
+
!isRecord(data.chunk) ||
|
|
701
|
+
data.chunk.type !== "delta" ||
|
|
702
|
+
typeof data.chunk.content !== "string")
|
|
703
|
+
return undefined;
|
|
704
|
+
const value = await options.projectText(data.chunk.content, context(record));
|
|
705
|
+
return value
|
|
706
|
+
? { text: value, operation: JSON.stringify([data.operationId, data.attemptId]) }
|
|
707
|
+
: undefined;
|
|
708
|
+
}
|
|
709
|
+
function stream(s, id, request, d, rpcId, historyLength) {
|
|
710
|
+
const detached = new AbortController();
|
|
711
|
+
const signal = AbortSignal.any([detached.signal, request.signal, stopped.signal]);
|
|
712
|
+
const iterator = events(s, id, request, signal, historyLength);
|
|
713
|
+
let pending;
|
|
714
|
+
let ended = false;
|
|
715
|
+
const encoder = new TextEncoder();
|
|
716
|
+
const body = new ReadableStream({
|
|
717
|
+
async pull(controller) {
|
|
718
|
+
if (ended)
|
|
719
|
+
return;
|
|
720
|
+
let timer;
|
|
721
|
+
try {
|
|
722
|
+
pending ??= iterator.next();
|
|
723
|
+
const next = await untilAbort(Promise.race([
|
|
724
|
+
pending,
|
|
725
|
+
new Promise((resolve) => {
|
|
726
|
+
timer = setTimeout(() => resolve(null), 15_000);
|
|
727
|
+
}),
|
|
728
|
+
]), signal);
|
|
729
|
+
if (next === null) {
|
|
730
|
+
await access(s, "SubscribeToTask", id, request);
|
|
731
|
+
controller.enqueue(encoder.encode(": keep-alive\n\n"));
|
|
732
|
+
return;
|
|
733
|
+
}
|
|
734
|
+
pending = undefined;
|
|
735
|
+
if (next.done) {
|
|
736
|
+
ended = true;
|
|
737
|
+
controller.close();
|
|
738
|
+
return;
|
|
739
|
+
}
|
|
740
|
+
await access(s, "SubscribeToTask", id, request);
|
|
741
|
+
const value = encodeA2AEvent(next.value, d);
|
|
742
|
+
controller.enqueue(encoder.encode(`data: ${JSON.stringify(d.binding === "JSONRPC" ? { jsonrpc: "2.0", id: rpcId, result: value } : value)}\n\n`));
|
|
743
|
+
}
|
|
744
|
+
catch (error) {
|
|
745
|
+
ended = true;
|
|
746
|
+
if (!signal.aborted) {
|
|
747
|
+
const failure = encodeA2AError(error instanceof A2AError ? (error.code ?? -32603) : -32603, d, rpcId);
|
|
748
|
+
controller.enqueue(encoder.encode(`event: error\ndata: ${JSON.stringify(failure.body)}\n\n`));
|
|
749
|
+
}
|
|
750
|
+
controller.close();
|
|
751
|
+
detached.abort();
|
|
752
|
+
void iterator.return(undefined).catch(() => { });
|
|
753
|
+
}
|
|
754
|
+
finally {
|
|
755
|
+
clearTimeout(timer);
|
|
756
|
+
}
|
|
757
|
+
},
|
|
758
|
+
cancel() {
|
|
759
|
+
ended = true;
|
|
760
|
+
detached.abort();
|
|
761
|
+
void iterator.return(undefined).catch(() => { });
|
|
762
|
+
},
|
|
763
|
+
}, { highWaterMark: 0 });
|
|
764
|
+
return new Response(body, {
|
|
765
|
+
headers: {
|
|
766
|
+
"content-type": "text/event-stream",
|
|
767
|
+
"cache-control": "no-store",
|
|
768
|
+
"A2A-Version": d.version,
|
|
769
|
+
},
|
|
770
|
+
});
|
|
771
|
+
}
|
|
772
|
+
async function card(version = "1.0") {
|
|
773
|
+
const host = options.card;
|
|
774
|
+
const security = host.security?.[version];
|
|
775
|
+
const capabilities = {
|
|
776
|
+
streaming: true,
|
|
777
|
+
pushNotifications: !!options.push,
|
|
778
|
+
...(version === "1.0" ? { extendedAgentCard: !!options.extendedCard } : {}),
|
|
779
|
+
extensions: host.extensions ?? [],
|
|
780
|
+
};
|
|
781
|
+
const common = {
|
|
782
|
+
name: host.name,
|
|
783
|
+
description: host.description,
|
|
784
|
+
version: host.version ?? "1",
|
|
785
|
+
skills: host.skills ?? [],
|
|
786
|
+
defaultInputModes: ["text/plain", "application/json"],
|
|
787
|
+
defaultOutputModes: ["text/plain", "application/json"],
|
|
788
|
+
capabilities,
|
|
789
|
+
...(security
|
|
790
|
+
? {
|
|
791
|
+
securitySchemes: security.schemes,
|
|
792
|
+
[version === "1.0" ? "securityRequirements" : "security"]: security.requirements,
|
|
793
|
+
}
|
|
794
|
+
: {}),
|
|
795
|
+
...(host.provider ? { provider: host.provider } : {}),
|
|
796
|
+
};
|
|
797
|
+
const document = version === "1.0"
|
|
798
|
+
? {
|
|
799
|
+
...common,
|
|
800
|
+
supportedInterfaces: ["1.0", "0.3"].flatMap((v) => ["JSONRPC", "HTTP+JSON"].map((binding) => ({
|
|
801
|
+
url: binding === "JSONRPC" ? rpcUrl.href : restUrl.href,
|
|
802
|
+
protocolBinding: binding,
|
|
803
|
+
protocolVersion: v,
|
|
804
|
+
...(v === "1.0" && options.tenant ? { tenant: options.tenant } : {}),
|
|
805
|
+
}))),
|
|
806
|
+
}
|
|
807
|
+
: {
|
|
808
|
+
...common,
|
|
809
|
+
protocolVersion: "0.3.0",
|
|
810
|
+
url: rpcUrl.href,
|
|
811
|
+
preferredTransport: "JSONRPC",
|
|
812
|
+
additionalInterfaces: [{ url: restUrl.href, transport: "HTTP+JSON" }],
|
|
813
|
+
supportsAuthenticatedExtendedCard: !!options.extendedCard,
|
|
814
|
+
};
|
|
815
|
+
const decoded = decodeA2AAgentCard(document, version);
|
|
816
|
+
return options.sign ? signAgentCard(decoded, options.sign) : decoded;
|
|
817
|
+
}
|
|
818
|
+
async function operation(s, decoded, request, d, rpcId) {
|
|
819
|
+
if (decoded.params.tenant !== undefined && decoded.params.tenant !== s.tenant)
|
|
820
|
+
protocol(-32001);
|
|
821
|
+
await access(s, decoded.method, undefined, request);
|
|
822
|
+
switch (decoded.method) {
|
|
823
|
+
case "SendMessage":
|
|
824
|
+
case "SendStreamingMessage": {
|
|
825
|
+
const id = await accept(s, decoded.params, request, d);
|
|
826
|
+
if (decoded.method === "SendStreamingMessage")
|
|
827
|
+
return stream(s, id, request, d, rpcId, decoded.params.configuration?.historyLength);
|
|
828
|
+
const task = decoded.params.configuration?.returnImmediately
|
|
829
|
+
? (await view(s, id, decoded.method, request, decoded.params.configuration.historyLength))
|
|
830
|
+
.task
|
|
831
|
+
: await wait(s, id, request, decoded.params.configuration?.historyLength);
|
|
832
|
+
return { method: "SendMessage", result: task };
|
|
833
|
+
}
|
|
834
|
+
case "GetTask":
|
|
835
|
+
return {
|
|
836
|
+
method: "GetTask",
|
|
837
|
+
result: (await view(s, decoded.params.id, decoded.method, request, decoded.params.historyLength)).task,
|
|
838
|
+
};
|
|
839
|
+
case "SubscribeToTask": {
|
|
840
|
+
const current = await view(s, decoded.params.id, decoded.method, request);
|
|
841
|
+
if (a2aTerminal(current.task.status.state))
|
|
842
|
+
protocol(-32004);
|
|
843
|
+
return stream(s, decoded.params.id, request, d, rpcId);
|
|
844
|
+
}
|
|
845
|
+
case "CancelTask": {
|
|
846
|
+
const current = await view(s, decoded.params.id, decoded.method, request);
|
|
847
|
+
if (a2aTerminal(current.task.status.state) || !current.record.segment)
|
|
848
|
+
protocol(-32002);
|
|
849
|
+
if (current.record.cancel === "refused")
|
|
850
|
+
protocol(-32002);
|
|
851
|
+
if (!current.record.cancel) {
|
|
852
|
+
await tasks.update(s, current.record.id, { cancel: "pending" }, current.record.revision);
|
|
853
|
+
try {
|
|
854
|
+
const result = await runs.cancel(s.owner, current.record.segment);
|
|
855
|
+
await patchTask(tasks, s, current.record.id, (record) => {
|
|
856
|
+
// Follow the physical segment even without onSegment. A newer continuation
|
|
857
|
+
// may have won meanwhile; an old acknowledgement cannot overwrite its ID.
|
|
858
|
+
if (record.segment !== current.record.segment && record.segment !== result.id)
|
|
859
|
+
throw new A2ATaskConflict();
|
|
860
|
+
return { segment: result.id, cancel: result.requested ? "accepted" : "refused" };
|
|
861
|
+
});
|
|
862
|
+
if (!result.requested)
|
|
863
|
+
protocol(-32002);
|
|
864
|
+
}
|
|
865
|
+
catch (error) {
|
|
866
|
+
await patchTask(tasks, s, current.record.id, (r) => r.cancel === "pending" ? { cancel: "unknown" } : undefined);
|
|
867
|
+
throw error;
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
watch(s, current.record.id);
|
|
871
|
+
return {
|
|
872
|
+
method: "CancelTask",
|
|
873
|
+
result: (await view(s, current.record.id, decoded.method, request)).task,
|
|
874
|
+
};
|
|
875
|
+
}
|
|
876
|
+
case "ListTasks": {
|
|
877
|
+
const p = decoded.params;
|
|
878
|
+
if (p.contextId && !(await tasks.hasContext(s, p.contextId)))
|
|
879
|
+
protocol(-32001);
|
|
880
|
+
const size = p.pageSize ?? 50;
|
|
881
|
+
let cursor;
|
|
882
|
+
let pastCursor = !p.pageToken;
|
|
883
|
+
let foundCursor = !p.pageToken;
|
|
884
|
+
let nextPageToken = "";
|
|
885
|
+
let totalSize = 0;
|
|
886
|
+
const result = [];
|
|
887
|
+
const after = p.statusTimestampAfter ? Date.parse(p.statusTimestampAfter) : undefined;
|
|
888
|
+
if (after !== undefined && !Number.isFinite(after))
|
|
889
|
+
protocol(-32602);
|
|
890
|
+
// Count fresh authorized matches, including those outside this response page.
|
|
891
|
+
do {
|
|
892
|
+
const page = await tasks.list(s, {
|
|
893
|
+
contextId: p.contextId,
|
|
894
|
+
pageSize: 100,
|
|
895
|
+
pageToken: cursor,
|
|
896
|
+
});
|
|
897
|
+
for (const record of page.tasks) {
|
|
898
|
+
if (record.id === p.pageToken) {
|
|
899
|
+
foundCursor = true;
|
|
900
|
+
pastCursor = true;
|
|
901
|
+
}
|
|
902
|
+
let current;
|
|
903
|
+
try {
|
|
904
|
+
current = await view(s, record.id, decoded.method, request, p.historyLength ?? 0);
|
|
905
|
+
}
|
|
906
|
+
catch (error) {
|
|
907
|
+
if (error instanceof A2AError && error.code === -32001)
|
|
908
|
+
continue;
|
|
909
|
+
throw error;
|
|
910
|
+
}
|
|
911
|
+
if ((p.status && current.task.status.state !== p.status) ||
|
|
912
|
+
(after !== undefined && current.record.updatedAt < after))
|
|
913
|
+
continue;
|
|
914
|
+
totalSize++;
|
|
915
|
+
if (!pastCursor || record.id === p.pageToken)
|
|
916
|
+
continue;
|
|
917
|
+
if (result.length < size) {
|
|
918
|
+
if (!p.includeArtifacts)
|
|
919
|
+
delete current.task.artifacts;
|
|
920
|
+
result.push(current.task);
|
|
921
|
+
}
|
|
922
|
+
else if (!nextPageToken)
|
|
923
|
+
nextPageToken = result.at(-1).id;
|
|
924
|
+
}
|
|
925
|
+
cursor = page.nextPageToken;
|
|
926
|
+
} while (cursor);
|
|
927
|
+
if (!foundCursor)
|
|
928
|
+
protocol(-32602);
|
|
929
|
+
return {
|
|
930
|
+
method: "ListTasks",
|
|
931
|
+
result: { tasks: result, nextPageToken, pageSize: size, totalSize },
|
|
932
|
+
};
|
|
933
|
+
}
|
|
934
|
+
case "CreateTaskPushNotificationConfig": {
|
|
935
|
+
if (!decoded.params.taskId)
|
|
936
|
+
protocol(-32602);
|
|
937
|
+
const current = await get(s, decoded.params.taskId, decoded.method, request);
|
|
938
|
+
const configured = await pushConfig(s, decoded.params, d);
|
|
939
|
+
const previous = current.push.find((p) => p.config.id === configured.config.id);
|
|
940
|
+
if (previous && d.version === "1.0")
|
|
941
|
+
protocol(-32602);
|
|
942
|
+
if (!previous && current.push.length >= Math.min(10, pushConfigs))
|
|
943
|
+
throw new A2AError("limit");
|
|
944
|
+
await tasks.update(s, current.id, {
|
|
945
|
+
push: [...current.push.filter((p) => p.config.id !== configured.config.id), configured],
|
|
946
|
+
}, current.revision);
|
|
947
|
+
watch(s, current.id);
|
|
948
|
+
return { method: decoded.method, result: configured.config };
|
|
949
|
+
}
|
|
950
|
+
case "GetTaskPushNotificationConfig":
|
|
951
|
+
case "ListTaskPushNotificationConfigs":
|
|
952
|
+
case "DeleteTaskPushNotificationConfig": {
|
|
953
|
+
const current = await get(s, decoded.params.taskId, decoded.method, request);
|
|
954
|
+
if (!options.push)
|
|
955
|
+
protocol(-32003);
|
|
956
|
+
if (decoded.method === "ListTaskPushNotificationConfigs") {
|
|
957
|
+
const configs = current.push.map((p) => p.config);
|
|
958
|
+
const start = decoded.params.pageToken
|
|
959
|
+
? configs.findIndex((p) => p.id === decoded.params.pageToken) + 1
|
|
960
|
+
: 0;
|
|
961
|
+
if (decoded.params.pageToken && start === 0)
|
|
962
|
+
protocol(-32602);
|
|
963
|
+
const end = start + (decoded.params.pageSize ?? 10);
|
|
964
|
+
const page = configs.slice(start, end);
|
|
965
|
+
return {
|
|
966
|
+
method: decoded.method,
|
|
967
|
+
result: { configs: page, nextPageToken: end < configs.length ? page.at(-1).id : "" },
|
|
968
|
+
};
|
|
969
|
+
}
|
|
970
|
+
const config = current.push.find((p) => p.config.id === decoded.params.id) ??
|
|
971
|
+
(decoded.params.id === undefined && current.push.length === 1
|
|
972
|
+
? current.push[0]
|
|
973
|
+
: undefined);
|
|
974
|
+
if (!config)
|
|
975
|
+
protocol(-32001);
|
|
976
|
+
if (decoded.method === "GetTaskPushNotificationConfig")
|
|
977
|
+
return { method: decoded.method, result: config.config };
|
|
978
|
+
await tasks.update(s, current.id, { push: current.push.filter((p) => p.config.id !== config.config.id) }, current.revision);
|
|
979
|
+
return { method: decoded.method, result: null };
|
|
980
|
+
}
|
|
981
|
+
case "GetExtendedAgentCard": {
|
|
982
|
+
if (!options.extendedCard)
|
|
983
|
+
protocol(-32007);
|
|
984
|
+
return {
|
|
985
|
+
method: decoded.method,
|
|
986
|
+
result: await options.extendedCard({ owner: s.owner, actorId: s.actorId }, d.version),
|
|
987
|
+
};
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
return {
|
|
992
|
+
card,
|
|
993
|
+
/** Explicit host reconciliation/read, also useful after an out-of-band segment completes. */
|
|
994
|
+
async refresh(principal, id) {
|
|
995
|
+
const s = scope(principal);
|
|
996
|
+
const current = await view(s, id);
|
|
997
|
+
await notify(s, id);
|
|
998
|
+
return current.task;
|
|
999
|
+
},
|
|
1000
|
+
/** Detaches this handler's observers, never cancels work held by runs. */
|
|
1001
|
+
async close() {
|
|
1002
|
+
stopped.abort();
|
|
1003
|
+
await Promise.all(watchers.values());
|
|
1004
|
+
},
|
|
1005
|
+
async fetch(request) {
|
|
1006
|
+
const path = new URL(request.url).pathname;
|
|
1007
|
+
let d = {
|
|
1008
|
+
version: "0.3",
|
|
1009
|
+
binding: path === rpcUrl.pathname ? "JSONRPC" : "HTTP+JSON",
|
|
1010
|
+
};
|
|
1011
|
+
let rpcId = null;
|
|
1012
|
+
try {
|
|
1013
|
+
// No body read, version parsing, store query or model work before authentication.
|
|
1014
|
+
const p = await principal(request);
|
|
1015
|
+
const publicCard = options.publicCard && path === cardPath && request.method === "GET";
|
|
1016
|
+
if (!p && !publicCard)
|
|
1017
|
+
return Response.json({ error: "Authentication is required." }, { status: 401, headers: { "WWW-Authenticate": "Bearer", "cache-control": "no-store" } });
|
|
1018
|
+
d = { ...d, version: parseA2AVersion(request.headers.get("A2A-Version")) };
|
|
1019
|
+
if (path === cardPath && request.method === "GET") {
|
|
1020
|
+
if (p)
|
|
1021
|
+
await access(scope(p), "AgentCard", undefined, request);
|
|
1022
|
+
return Response.json((await card(d.version)).document, {
|
|
1023
|
+
headers: { Vary: "A2A-Version", "cache-control": "no-store" },
|
|
1024
|
+
});
|
|
1025
|
+
}
|
|
1026
|
+
if (!p)
|
|
1027
|
+
protocol(-32001);
|
|
1028
|
+
const extensions = request.headers
|
|
1029
|
+
.get("A2A-Extensions")
|
|
1030
|
+
?.split(",")
|
|
1031
|
+
.map((v) => v.trim()) ?? [];
|
|
1032
|
+
if (options.card.extensions?.some((ext) => ext.required === true &&
|
|
1033
|
+
(typeof ext.uri !== "string" || !extensions.includes(ext.uri))))
|
|
1034
|
+
protocol(-32008);
|
|
1035
|
+
// Empty REST cancellations are valid protocol requests, but still need a JSON media
|
|
1036
|
+
// type here. Otherwise a cross-site form can reach a cookie-authenticated command.
|
|
1037
|
+
const mediaType = request.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
|
|
1038
|
+
if (request.method === "POST" &&
|
|
1039
|
+
mediaType !== "application/json" &&
|
|
1040
|
+
mediaType !== "application/a2a+json")
|
|
1041
|
+
throw new A2AError("protocol", { code: -32005, status: 415 });
|
|
1042
|
+
let decoded;
|
|
1043
|
+
if (d.binding === "JSONRPC") {
|
|
1044
|
+
if (request.method !== "POST")
|
|
1045
|
+
throw new A2AError("invalid", { status: 405 });
|
|
1046
|
+
const value = await readA2AJson(request, { limits });
|
|
1047
|
+
// Keep a valid correlation id even when decoding the operation fails.
|
|
1048
|
+
if (value &&
|
|
1049
|
+
typeof value === "object" &&
|
|
1050
|
+
!Array.isArray(value) &&
|
|
1051
|
+
(typeof value.id === "string" || typeof value.id === "number"))
|
|
1052
|
+
rpcId = value.id;
|
|
1053
|
+
const rpc = decodeA2ARpcRequest(value, d.version, limits);
|
|
1054
|
+
rpcId = rpc.id;
|
|
1055
|
+
decoded = rpc.request;
|
|
1056
|
+
}
|
|
1057
|
+
else
|
|
1058
|
+
decoded = await decodeA2AHttpRequest(request, {
|
|
1059
|
+
baseUrl: restUrl.href,
|
|
1060
|
+
version: d.version,
|
|
1061
|
+
tenant: options.tenant,
|
|
1062
|
+
limits,
|
|
1063
|
+
});
|
|
1064
|
+
const result = await operation(scope(p), decoded, request, d, rpcId);
|
|
1065
|
+
if (result instanceof Response)
|
|
1066
|
+
return result;
|
|
1067
|
+
await access(scope(p), decoded.method, undefined, request);
|
|
1068
|
+
const encoded = encodeA2AResult(result, d);
|
|
1069
|
+
return Response.json(d.binding === "JSONRPC" ? { jsonrpc: "2.0", id: rpcId, result: encoded } : encoded, { headers: { "cache-control": "no-store", "A2A-Version": d.version } });
|
|
1070
|
+
}
|
|
1071
|
+
catch (error) {
|
|
1072
|
+
const encoded = encodeA2AError(error instanceof A2AError
|
|
1073
|
+
? (error.code ?? (error.kind === "invalid" || error.kind === "limit" ? -32602 : -32603))
|
|
1074
|
+
: -32603, d, rpcId);
|
|
1075
|
+
return Response.json(encoded.body, {
|
|
1076
|
+
status: error instanceof A2AError && [413, 415, 405].includes(error.status ?? 0)
|
|
1077
|
+
? error.status
|
|
1078
|
+
: encoded.status,
|
|
1079
|
+
headers: { "cache-control": "no-store" },
|
|
1080
|
+
});
|
|
1081
|
+
}
|
|
1082
|
+
},
|
|
1083
|
+
};
|
|
1084
|
+
}
|
|
1085
|
+
/** Gate A2A evidence before handing it to the real host resolver/claim. Does not grant
|
|
1086
|
+
* approvals, invent scopes, consume requests or replace the host's lease checks. */
|
|
1087
|
+
export function a2aPolicy(policy, options) {
|
|
1088
|
+
async function evidence(requestId, value) {
|
|
1089
|
+
if (!isRecord(value) ||
|
|
1090
|
+
value.via !== "a2a" ||
|
|
1091
|
+
value.owner !== options.scope.owner ||
|
|
1092
|
+
value.actorId !== options.scope.actorId ||
|
|
1093
|
+
value.tenant !== options.scope.tenant ||
|
|
1094
|
+
value.taskId !== options.context.runId ||
|
|
1095
|
+
value.requestId !== requestId ||
|
|
1096
|
+
typeof value.messageId !== "string")
|
|
1097
|
+
throw new A2AError("invalid");
|
|
1098
|
+
const task = await options.tasks.get(options.scope, options.context.runId);
|
|
1099
|
+
const message = task?.messages.find((m) => m.id === value.messageId && m.kind === "resume");
|
|
1100
|
+
if (!message ||
|
|
1101
|
+
message.source !== options.context.continuation?.sourceId ||
|
|
1102
|
+
!equalData(message.answers?.[requestId], value))
|
|
1103
|
+
throw new A2AError("invalid");
|
|
1104
|
+
return message;
|
|
1105
|
+
}
|
|
1106
|
+
return {
|
|
1107
|
+
...policy,
|
|
1108
|
+
async claimContinuation(snapshot, continuation) {
|
|
1109
|
+
const messages = new Map();
|
|
1110
|
+
for (const [id, value] of Object.entries(continuation.answers)) {
|
|
1111
|
+
if (!isRecord(value) || value.via !== "a2a")
|
|
1112
|
+
continue;
|
|
1113
|
+
const message = await evidence(id, value);
|
|
1114
|
+
if (!Object.entries(message.answers ?? {}).every(([requestId, answer]) => equalData(continuation.answers[requestId], answer)))
|
|
1115
|
+
throw new A2AError("invalid");
|
|
1116
|
+
messages.set(message.id, message);
|
|
1117
|
+
}
|
|
1118
|
+
// Scheduled wakes and explicit cancellations are checked by the binding and claimed by
|
|
1119
|
+
// the real host. A cancellation contains no answers and grants no pending request.
|
|
1120
|
+
await policy.claimContinuation(snapshot, continuation);
|
|
1121
|
+
// The host's exact claim and physical segment establish acceptance even if resume's
|
|
1122
|
+
// acknowledgement was lost. A later message may continue, but this one is never replayed.
|
|
1123
|
+
for (const message of messages.values())
|
|
1124
|
+
await receipt(options.tasks, options.scope, options.context.runId, message.id, "accepted", options.context.segmentId);
|
|
1125
|
+
},
|
|
1126
|
+
async resolveRequest(request, value) {
|
|
1127
|
+
if (!isRecord(value) || value.via !== "a2a")
|
|
1128
|
+
return policy.resolveRequest(request, value);
|
|
1129
|
+
await evidence(request.id, value);
|
|
1130
|
+
if (request.scope.actorId !== options.scope.actorId ||
|
|
1131
|
+
request.scope.expiresAt <= Date.now() ||
|
|
1132
|
+
(request.ask.type === "approval" && !options.remoteApprovals) ||
|
|
1133
|
+
(request.ask.type === "client" && !options.remoteClientTools))
|
|
1134
|
+
return { type: "pending" };
|
|
1135
|
+
return policy.resolveRequest(request, value);
|
|
1136
|
+
},
|
|
1137
|
+
};
|
|
1138
|
+
}
|
|
1139
|
+
//# sourceMappingURL=server.js.map
|