@arnilo/prism-hosts 0.13.1 → 0.14.1
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/CHANGELOG.md +6 -0
- package/a2a/README.md +195 -0
- package/a2a/src/card.ts +208 -0
- package/a2a/src/codec.ts +523 -0
- package/a2a/src/connect.ts +415 -0
- package/a2a/src/errors.ts +87 -0
- package/a2a/src/index.ts +40 -0
- package/a2a/src/limits.ts +43 -0
- package/a2a/src/pending.ts +28 -0
- package/a2a/src/proxy.ts +526 -0
- package/a2a/src/serve.ts +886 -0
- package/acp/README.md +3 -1
- package/acp/src/limits.ts +3 -16
- package/acp/src/mapper.ts +26 -5
- package/acp/src/serve.ts +6 -5
- package/ag-ui/README.md +2 -1
- package/ag-ui/src/a2ui.ts +8 -31
- package/ag-ui/src/ag-ui-mapper.ts +27 -1
- package/ag-ui/src/encrypted-value.ts +3 -3
- package/ag-ui/src/handler.ts +4 -4
- package/ag-ui/src/index.ts +0 -33
- package/ag-ui/src/limits.ts +5 -88
- package/ag-ui/src/projectors.ts +8 -6
- package/ag-ui/src/renderer/bind.ts +2 -1
- package/channels/README.md +61 -5
- package/channels/src/discord-gateway.ts +354 -0
- package/channels/src/discord.ts +873 -0
- package/channels/src/index.ts +4 -2
- package/channels/src/limits.ts +3 -19
- package/channels/src/pairing.ts +1 -2
- package/channels/src/runtime-turn.ts +10 -2
- package/channels/src/signal.ts +11 -19
- package/channels/src/slack.ts +854 -0
- package/channels/src/telegram.ts +22 -44
- package/channels/src/types.ts +5 -2
- package/devtools/README.md +1 -1
- package/driver-process/src/driver.ts +3 -1
- package/driver-process/src/testing.ts +1 -1
- package/driver-process/src/turn.ts +5 -1
- package/evals/README.md +11 -7
- package/evals/src/calibration.ts +5 -13
- package/evals/src/compare-experiments.ts +1 -2
- package/evals/src/comparison.ts +7 -25
- package/evals/src/curate.ts +3 -9
- package/evals/src/dataset.ts +0 -2
- package/evals/src/index.ts +3 -20
- package/evals/src/injection.ts +33 -6
- package/evals/src/judge.ts +9 -13
- package/evals/src/limits.ts +0 -17
- package/evals/src/rubric-judge.ts +5 -10
- package/evals/src/scenario-runner.ts +8 -4
- package/evals/src/scenarios.ts +5 -5
- package/evals/src/score.ts +3 -5
- package/evals/src/stats.ts +0 -2
- package/evals/src/threshold.ts +3 -3
- package/evals/src/toolless-session.ts +7 -3
- package/evals/src/trace.ts +8 -14
- package/evals/src/trajectory.ts +45 -11
- package/evals/src/types.ts +2 -2
- package/evals/src/user-simulator.ts +1 -7
- package/evals/src/util.ts +3 -9
- package/headless/README.md +20 -1
- package/headless/src/authority.ts +14 -1
- package/headless/src/errors.ts +3 -1
- package/headless/src/index.ts +10 -1
- package/headless/src/limits.ts +2 -2
- package/headless/src/pending.ts +4 -3
- package/headless/src/recover.ts +126 -0
- package/headless/src/resume.ts +1 -1
- package/host-builder/data/api.json +1276 -1365
- package/host-builder/data/errors.json +199 -185
- package/host-builder/data/examples/a2a-client.ts +125 -0
- package/host-builder/data/examples/a2a-server.ts +133 -0
- package/host-builder/data/examples/autonomous-coding-loop.ts +1 -1
- package/host-builder/data/examples/build-workflow.ts +2 -2
- package/host-builder/data/examples/caveman-ponytail.ts +1 -1
- package/host-builder/data/examples/channel-discord.ts +176 -0
- package/host-builder/data/examples/channel-slack.ts +146 -0
- package/host-builder/data/examples/continue-after-failure.ts +80 -0
- package/host-builder/data/examples/custom-adapter.ts +1 -1
- package/host-builder/data/examples/decision-models.ts +1 -1
- package/host-builder/data/examples/define-package.ts +1 -1
- package/host-builder/data/examples/delegate.ts +74 -9
- package/host-builder/data/examples/durable-loops-and-approvals.ts +11 -10
- package/host-builder/data/examples/governance-deny.ts +1 -1
- package/host-builder/data/examples/guardrail-content.ts +126 -0
- package/host-builder/data/examples/headless-host.ts +1 -1
- package/host-builder/data/examples/long-running-job.ts +129 -0
- package/host-builder/data/examples/long-term-memory.ts +1 -1
- package/host-builder/data/examples/mcp-oauth.ts +197 -0
- package/host-builder/data/examples/mcp-trust.ts +1 -1
- package/host-builder/data/examples/memory-and-wiki.ts +2 -2
- package/host-builder/data/examples/memory-system.ts +19 -9
- package/host-builder/data/examples/model-router-aggregate-budgets.ts +1 -1
- package/host-builder/data/examples/parallel-tools.ts +70 -0
- package/host-builder/data/examples/remote-agent.ts +1 -1
- package/host-builder/data/examples/serve-tools.ts +1 -1
- package/host-builder/data/examples/session-memory.ts +18 -16
- package/host-builder/data/examples/side-call.ts +1 -1
- package/host-builder/data/examples/sqlite-resume.ts +1 -1
- package/host-builder/data/examples/structured-output.ts +57 -0
- package/host-builder/data/examples.json +14 -4
- package/host-builder/skills/prism-host-builder/SKILL.md +1 -1
- package/host-builder/skills/prism-host-builder/references/choosing.md +14 -10
- package/host-builder/skills/prism-host-builder/references/pitfalls.md +5 -3
- package/host-builder/skills/prism-host-builder/references/recipes.md +5 -5
- package/host-builder/skills/prism-host-builder/references/verification.md +1 -1
- package/host-builder/src/check/runner.ts +2 -3
- package/host-builder/src/server.ts +2 -2
- package/mcp-server/README.md +3 -3
- package/mcp-server/src/bounds.ts +3 -3
- package/mcp-server/src/serve-tools.ts +2 -9
- package/mcp-server/src/serve.ts +2 -4
- package/mcp-server/src/server.ts +10 -20
- package/package.json +12 -6
- package/remote/README.md +7 -4
- package/remote/src/channel.ts +6 -2
- package/remote/src/connect.ts +9 -3
- package/remote/src/errors.ts +3 -1
- package/remote/src/limits.ts +3 -13
- package/remote/src/mirror.ts +2 -1
- package/remote/src/pending.ts +4 -3
- package/remote/src/protocol.ts +3 -0
- package/remote/src/serve.ts +43 -5
- package/remote/src/session-proxy.ts +28 -5
- package/remote/src/testing.ts +3 -1
- package/remote/src/wire.ts +74 -14
package/a2a/src/serve.ts
ADDED
|
@@ -0,0 +1,886 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
type Agent,
|
|
4
|
+
resolveCeilings,
|
|
5
|
+
type AgentEvent,
|
|
6
|
+
type CredentialResolver,
|
|
7
|
+
createEnvRefCredentialResolver,
|
|
8
|
+
type Decision,
|
|
9
|
+
isSessionNotFound,
|
|
10
|
+
type Message,
|
|
11
|
+
type OwnershipScope,
|
|
12
|
+
OwnershipScopeError,
|
|
13
|
+
type PendingDecision,
|
|
14
|
+
type Principal,
|
|
15
|
+
type SecretRedactor,
|
|
16
|
+
type Session,
|
|
17
|
+
} from "@arnilo/prism";
|
|
18
|
+
import { type A2AAgentCard, buildServedCard, endpointPathOf, signAgentCard } from "./card.js";
|
|
19
|
+
import {
|
|
20
|
+
A2A_CARD_PATH,
|
|
21
|
+
A2A_PROTOCOL_VERSION,
|
|
22
|
+
type A2AArtifact,
|
|
23
|
+
type A2AMessage,
|
|
24
|
+
type A2AStreamResponse,
|
|
25
|
+
type A2ATask,
|
|
26
|
+
type A2ATaskState,
|
|
27
|
+
decodeTaskId,
|
|
28
|
+
encodeTaskId,
|
|
29
|
+
INTERRUPTED_STATES,
|
|
30
|
+
isA2AId,
|
|
31
|
+
type JsonRpcId,
|
|
32
|
+
type JsonRpcRequest,
|
|
33
|
+
jsonRpcError,
|
|
34
|
+
jsonRpcResult,
|
|
35
|
+
messageToA2A,
|
|
36
|
+
parseJsonRpcRequest,
|
|
37
|
+
parseSendMessageParams,
|
|
38
|
+
parseTaskIdParams,
|
|
39
|
+
partsToMessage,
|
|
40
|
+
pendingParts,
|
|
41
|
+
readDecisions,
|
|
42
|
+
TERMINAL_STATES,
|
|
43
|
+
} from "./codec.js";
|
|
44
|
+
import { A2AConfigError, A2AError, A2ALiteralSecretError } from "./errors.js";
|
|
45
|
+
import { type A2ALimitOptions, type ResolvedA2ALimits, resolveA2ALimits } from "./limits.js";
|
|
46
|
+
import { suspensionOf } from "./pending.js";
|
|
47
|
+
|
|
48
|
+
export interface A2AAuthorizeInput {
|
|
49
|
+
readonly request: Request;
|
|
50
|
+
/** The JSON-RPC method being called. */
|
|
51
|
+
readonly method: string;
|
|
52
|
+
readonly signal: AbortSignal;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Who is calling and which ownership scope their contexts live in. */
|
|
56
|
+
export interface A2AAuthorization {
|
|
57
|
+
readonly principal: Principal;
|
|
58
|
+
/** Session ownership for this caller. When absent, `ownershipFor(principal)` is used, else sessions are unscoped. */
|
|
59
|
+
readonly ownership?: OwnershipScope;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface ServeA2AOptions {
|
|
63
|
+
/** The Agent Card to serve. `capabilities` is filled from what `serveA2A` implements. */
|
|
64
|
+
readonly card: A2AAgentCard;
|
|
65
|
+
/**
|
|
66
|
+
* Verifies whatever the card's `securitySchemes` declare (Bearer, API key, OAuth, mTLS) and returns the
|
|
67
|
+
* caller, or `false`. Required: without it every call is refused.
|
|
68
|
+
*/
|
|
69
|
+
readonly authorize: (input: A2AAuthorizeInput) => A2AAuthorization | false | Promise<A2AAuthorization | false>;
|
|
70
|
+
readonly ownershipFor?: (principal: Principal) => OwnershipScope;
|
|
71
|
+
/** Signs the served card (ES256). `key` is an `env:` / `keyring:` ref to a PKCS#8 P-256 PEM; a literal throws. */
|
|
72
|
+
readonly signing?: { readonly key: string; readonly keyId: string };
|
|
73
|
+
/** Resolves `signing.key`. Defaults to the agent's credentials slot, else the kernel `env:` resolver. */
|
|
74
|
+
readonly credentials?: CredentialResolver;
|
|
75
|
+
/** Accept `modifiedArguments` in decisions (re-gated by the kernel). Defaults to `false`. */
|
|
76
|
+
readonly allowModifiedArguments?: boolean;
|
|
77
|
+
readonly redactor?: SecretRedactor;
|
|
78
|
+
readonly limits?: A2ALimitOptions;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface A2AHandler {
|
|
82
|
+
(request: Request): Promise<Response>;
|
|
83
|
+
/** The card as served, before signing. */
|
|
84
|
+
readonly card: A2AAgentCard;
|
|
85
|
+
/** Aborts working tasks and closes every open session. */
|
|
86
|
+
close(): Promise<void>;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
type Listener = (frame: A2AStreamResponse, end: boolean) => void;
|
|
90
|
+
|
|
91
|
+
interface ContextEntry {
|
|
92
|
+
readonly id: string;
|
|
93
|
+
readonly principalKey: string;
|
|
94
|
+
readonly session: Session;
|
|
95
|
+
/** Set while a task of this context is starting or working; one run per session at a time. */
|
|
96
|
+
busy: boolean;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
interface TaskRecord {
|
|
100
|
+
readonly id: string;
|
|
101
|
+
readonly contextId: string;
|
|
102
|
+
readonly runId: string;
|
|
103
|
+
readonly principalKey: string;
|
|
104
|
+
state: A2ATaskState;
|
|
105
|
+
statusMessage?: A2AMessage;
|
|
106
|
+
timestamp: string;
|
|
107
|
+
pending: readonly PendingDecision[];
|
|
108
|
+
readonly artifacts: A2AArtifact[];
|
|
109
|
+
current?: { readonly artifactId: string; text: string };
|
|
110
|
+
artifactSeq: number;
|
|
111
|
+
readonly listeners: Set<Listener>;
|
|
112
|
+
segment: Promise<void>;
|
|
113
|
+
settle?: () => void;
|
|
114
|
+
controller?: AbortController;
|
|
115
|
+
cancelRequested: boolean;
|
|
116
|
+
timedOut: boolean;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const JSON_HEADERS = { "content-type": "application/json; charset=utf-8", "a2a-version": A2A_PROTOCOL_VERSION };
|
|
120
|
+
const SSE_HEADERS = {
|
|
121
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
122
|
+
"cache-control": "no-cache, no-transform",
|
|
123
|
+
"a2a-version": A2A_PROTOCOL_VERSION,
|
|
124
|
+
};
|
|
125
|
+
const MAX_ARTIFACTS = 16;
|
|
126
|
+
const MAX_STATUS_TEXT_BYTES = 2 * 1024;
|
|
127
|
+
const VERSION_PATTERN = /^1\.0(?:\.\d+)?$/;
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Serves one `Agent` to A2A 1.0 peers over JSON-RPC: the Agent Card at `/.well-known/agent-card.json`, and
|
|
131
|
+
* `SendMessage`, `SendStreamingMessage`, `GetTask`, `CancelTask` and `SubscribeToTask` at the card's JSONRPC
|
|
132
|
+
* interface path. A context is one session; a task is one run plus the resumes that continue it. Every call
|
|
133
|
+
* goes through `session.stream` / `session.resume`, so approvals, hooks and limits apply.
|
|
134
|
+
*/
|
|
135
|
+
export function serveA2A(agent: Agent, options: ServeA2AOptions): A2AHandler {
|
|
136
|
+
const limits = resolveA2ALimits(options.limits);
|
|
137
|
+
const maxDecisions = resolveCeilings(agent.config?.ceilings).pendingDecisions;
|
|
138
|
+
const card = buildServedCard(options.card);
|
|
139
|
+
const endpointPath = endpointPathOf(card);
|
|
140
|
+
if (options.signing !== undefined) {
|
|
141
|
+
const { key, keyId } = options.signing;
|
|
142
|
+
if (typeof key !== "string" || !(key.startsWith("env:") || key.startsWith("keyring:"))) throw new A2ALiteralSecretError("signing.key");
|
|
143
|
+
if (typeof keyId !== "string" || keyId.trim().length === 0) throw new A2AConfigError("signing.keyId is required");
|
|
144
|
+
}
|
|
145
|
+
let servedCard: Promise<string> | undefined;
|
|
146
|
+
const cardBody = (): Promise<string> => {
|
|
147
|
+
servedCard ??= (async () => {
|
|
148
|
+
if (!options.signing) return JSON.stringify(card);
|
|
149
|
+
const resolver = options.credentials ?? resolverOf(agent);
|
|
150
|
+
const pem = (await resolver.resolve(options.signing.key, { package: "@arnilo/prism-hosts/a2a" }))?.value;
|
|
151
|
+
if (!pem) throw new A2AConfigError("signing.key reference is unavailable");
|
|
152
|
+
return JSON.stringify(signAgentCard(card, pem, options.signing.keyId));
|
|
153
|
+
})();
|
|
154
|
+
servedCard.catch(() => {
|
|
155
|
+
servedCard = undefined;
|
|
156
|
+
});
|
|
157
|
+
return servedCard;
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
const contexts = new Map<string, Promise<ContextEntry>>();
|
|
161
|
+
const tasks = new Map<string, TaskRecord>();
|
|
162
|
+
const working = new Map<string, number>();
|
|
163
|
+
const declaredInput = agent.config?.model?.capabilities?.input;
|
|
164
|
+
const redact = (text: string): string => boundedText(options.redactor ? options.redactor.redact(text) : text, MAX_STATUS_TEXT_BYTES);
|
|
165
|
+
|
|
166
|
+
// --- contexts --------------------------------------------------------------------------------
|
|
167
|
+
|
|
168
|
+
async function contextFor(
|
|
169
|
+
contextId: string,
|
|
170
|
+
principalKey: string,
|
|
171
|
+
ownership: OwnershipScope | undefined,
|
|
172
|
+
create: boolean,
|
|
173
|
+
): Promise<ContextEntry> {
|
|
174
|
+
const existing = contexts.get(contextId);
|
|
175
|
+
if (existing) {
|
|
176
|
+
const entry = await existing;
|
|
177
|
+
if (entry.principalKey !== principalKey) throw notFound();
|
|
178
|
+
contexts.delete(contextId);
|
|
179
|
+
contexts.set(contextId, existing); // most recently used last
|
|
180
|
+
return entry;
|
|
181
|
+
}
|
|
182
|
+
await evictContexts();
|
|
183
|
+
const opening = (async (): Promise<ContextEntry> => {
|
|
184
|
+
try {
|
|
185
|
+
const session = await agent.session({ id: contextId, create, ...(ownership ? { ownership } : {}) });
|
|
186
|
+
return { id: contextId, principalKey, session, busy: false };
|
|
187
|
+
} catch (error) {
|
|
188
|
+
if (isSessionNotFound(error) || error instanceof OwnershipScopeError || codeOf(error) === "ERR_PRISM_OWNERSHIP_WIDEN")
|
|
189
|
+
throw notFound();
|
|
190
|
+
throw error;
|
|
191
|
+
}
|
|
192
|
+
})();
|
|
193
|
+
contexts.set(contextId, opening);
|
|
194
|
+
opening.catch(() => {
|
|
195
|
+
if (contexts.get(contextId) === opening) contexts.delete(contextId);
|
|
196
|
+
});
|
|
197
|
+
return opening;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async function evictContexts(): Promise<void> {
|
|
201
|
+
if (contexts.size < limits.maxContexts) return;
|
|
202
|
+
for (const [id, promise] of contexts) {
|
|
203
|
+
const entry = await promise.catch(() => undefined);
|
|
204
|
+
if (entry?.busy) continue;
|
|
205
|
+
contexts.delete(id);
|
|
206
|
+
await entry?.session.close().catch(() => {});
|
|
207
|
+
if (contexts.size < limits.maxContexts) return;
|
|
208
|
+
}
|
|
209
|
+
throw new A2AError("overloaded", "Too many open contexts", 429);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// --- task registry -----------------------------------------------------------------------------
|
|
213
|
+
|
|
214
|
+
function register(record: TaskRecord): void {
|
|
215
|
+
if (tasks.size >= limits.maxTasks) {
|
|
216
|
+
for (const [id, candidate] of tasks) {
|
|
217
|
+
if (candidate.state === "TASK_STATE_WORKING") continue;
|
|
218
|
+
tasks.delete(id);
|
|
219
|
+
if (tasks.size < limits.maxTasks) break;
|
|
220
|
+
}
|
|
221
|
+
if (tasks.size >= limits.maxTasks) throw new A2AError("overloaded", "Too many tasks", 429);
|
|
222
|
+
}
|
|
223
|
+
tasks.set(record.id, record);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function newRecord(contextId: string, runId: string, principalKey: string, state: A2ATaskState): TaskRecord {
|
|
227
|
+
return {
|
|
228
|
+
id: encodeTaskId(contextId, runId),
|
|
229
|
+
contextId,
|
|
230
|
+
runId,
|
|
231
|
+
principalKey,
|
|
232
|
+
state,
|
|
233
|
+
timestamp: new Date().toISOString(),
|
|
234
|
+
pending: [],
|
|
235
|
+
artifacts: [],
|
|
236
|
+
artifactSeq: 0,
|
|
237
|
+
listeners: new Set(),
|
|
238
|
+
segment: Promise.resolve(),
|
|
239
|
+
cancelRequested: false,
|
|
240
|
+
timedOut: false,
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** A task the caller owns: from the registry, else recovered from its session when it is still suspended. */
|
|
245
|
+
async function lookup(taskId: string, principalKey: string, ownership: OwnershipScope | undefined): Promise<TaskRecord> {
|
|
246
|
+
const known = tasks.get(taskId);
|
|
247
|
+
if (known) {
|
|
248
|
+
if (known.principalKey !== principalKey) throw notFound();
|
|
249
|
+
return known;
|
|
250
|
+
}
|
|
251
|
+
const decoded = decodeTaskId(taskId);
|
|
252
|
+
if (!decoded) throw notFound();
|
|
253
|
+
const context = await contextFor(decoded.contextId, principalKey, ownership, false);
|
|
254
|
+
const suspension = suspensionOf(await context.session.entries());
|
|
255
|
+
if (!suspension || suspension.runId !== decoded.runId) throw notFound();
|
|
256
|
+
const record = newRecord(decoded.contextId, decoded.runId, principalKey, "TASK_STATE_INPUT_REQUIRED");
|
|
257
|
+
record.pending = suspension.pending;
|
|
258
|
+
record.statusMessage = statusMessage(record, pendingParts(suspension.pending));
|
|
259
|
+
register(record);
|
|
260
|
+
return record;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function statusMessage(record: TaskRecord, parts: A2AMessage["parts"]): A2AMessage {
|
|
264
|
+
return { messageId: randomUUID(), role: "ROLE_AGENT", contextId: record.contextId, taskId: record.id, parts };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function snapshot(record: TaskRecord, history?: readonly A2AMessage[]): A2ATask {
|
|
268
|
+
return {
|
|
269
|
+
id: record.id,
|
|
270
|
+
contextId: record.contextId,
|
|
271
|
+
status: {
|
|
272
|
+
state: record.state,
|
|
273
|
+
...(record.statusMessage ? { message: record.statusMessage } : {}),
|
|
274
|
+
timestamp: record.timestamp,
|
|
275
|
+
},
|
|
276
|
+
...(record.artifacts.length > 0 ? { artifacts: record.artifacts.map((artifact) => ({ ...artifact })) } : {}),
|
|
277
|
+
...(history ? { history } : {}),
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function emit(record: TaskRecord, frame: A2AStreamResponse, end = false): void {
|
|
282
|
+
for (const listener of record.listeners) listener(frame, end);
|
|
283
|
+
if (end) record.listeners.clear();
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function statusFrame(record: TaskRecord): A2AStreamResponse {
|
|
287
|
+
return {
|
|
288
|
+
statusUpdate: {
|
|
289
|
+
taskId: record.id,
|
|
290
|
+
contextId: record.contextId,
|
|
291
|
+
status: {
|
|
292
|
+
state: record.state,
|
|
293
|
+
...(record.statusMessage ? { message: record.statusMessage } : {}),
|
|
294
|
+
timestamp: record.timestamp,
|
|
295
|
+
},
|
|
296
|
+
},
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function setState(record: TaskRecord, state: A2ATaskState, message?: A2AMessage): void {
|
|
301
|
+
record.state = state;
|
|
302
|
+
record.statusMessage = message;
|
|
303
|
+
record.timestamp = new Date().toISOString();
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// --- running -----------------------------------------------------------------------------------
|
|
307
|
+
|
|
308
|
+
/** Reads events until `run.started`, so a run that cannot start is a JSON-RPC error, not a task. */
|
|
309
|
+
async function untilStarted(iterator: AsyncIterator<AgentEvent>): Promise<string> {
|
|
310
|
+
while (true) {
|
|
311
|
+
let next: IteratorResult<AgentEvent>;
|
|
312
|
+
try {
|
|
313
|
+
next = await iterator.next();
|
|
314
|
+
} catch (error) {
|
|
315
|
+
if (nameOf(error) === "AgentDecisionError") throw new A2AError("invalidParams", "Decisions do not match the pending task");
|
|
316
|
+
if (nameOf(error) === "AgentBusyError" || codeOf(error) === "session_busy")
|
|
317
|
+
throw new A2AError("invalidParams", "The context has a run in progress");
|
|
318
|
+
throw error;
|
|
319
|
+
}
|
|
320
|
+
if (next.done) throw new A2AError("internalError", "The run could not start");
|
|
321
|
+
const event = next.value;
|
|
322
|
+
if (event.type === "run.started") return event.runId;
|
|
323
|
+
if (event.type === "run.failed") throw new A2AError("internalError", "The run could not start");
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function arm(record: TaskRecord, controller: AbortController, context: ContextEntry): () => void {
|
|
328
|
+
record.controller = controller;
|
|
329
|
+
record.cancelRequested = false;
|
|
330
|
+
record.timedOut = false;
|
|
331
|
+
let settle!: () => void;
|
|
332
|
+
record.segment = new Promise<void>((resolve) => {
|
|
333
|
+
settle = resolve;
|
|
334
|
+
});
|
|
335
|
+
const timer = setTimeout(() => {
|
|
336
|
+
record.timedOut = true;
|
|
337
|
+
controller.abort(new Error("A2A task timed out"));
|
|
338
|
+
}, limits.taskTimeoutMs);
|
|
339
|
+
record.settle = () => {
|
|
340
|
+
clearTimeout(timer);
|
|
341
|
+
record.controller = undefined;
|
|
342
|
+
context.busy = false;
|
|
343
|
+
working.set(record.principalKey, Math.max(0, (working.get(record.principalKey) ?? 1) - 1));
|
|
344
|
+
settle();
|
|
345
|
+
};
|
|
346
|
+
return () => record.settle?.();
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function finish(record: TaskRecord, state: A2ATaskState, message?: A2AMessage): void {
|
|
350
|
+
if (record.state !== "TASK_STATE_WORKING") return;
|
|
351
|
+
if (record.current) closeArtifact(record);
|
|
352
|
+
setState(record, state, message);
|
|
353
|
+
const settle = record.settle;
|
|
354
|
+
record.settle = undefined;
|
|
355
|
+
emit(record, statusFrame(record), true);
|
|
356
|
+
settle?.();
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function closeArtifact(record: TaskRecord): void {
|
|
360
|
+
const current = record.current;
|
|
361
|
+
record.current = undefined;
|
|
362
|
+
if (!current || current.text.length === 0) return;
|
|
363
|
+
record.artifacts.push({ artifactId: current.artifactId, name: "response", parts: [{ text: current.text }] });
|
|
364
|
+
if (record.artifacts.length > MAX_ARTIFACTS) record.artifacts.splice(0, record.artifacts.length - MAX_ARTIFACTS);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function appendText(record: TaskRecord, text: string): void {
|
|
368
|
+
if (text.length === 0) return;
|
|
369
|
+
const append = record.current !== undefined;
|
|
370
|
+
if (!record.current) record.current = { artifactId: `response-${++record.artifactSeq}`, text: "" };
|
|
371
|
+
if (record.current.text.length + text.length <= limits.maxResponseBytes) record.current.text += text;
|
|
372
|
+
emit(record, {
|
|
373
|
+
artifactUpdate: {
|
|
374
|
+
taskId: record.id,
|
|
375
|
+
contextId: record.contextId,
|
|
376
|
+
artifact: { artifactId: record.current.artifactId, name: "response", parts: [{ text }] },
|
|
377
|
+
append,
|
|
378
|
+
},
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function apply(record: TaskRecord, event: AgentEvent): void {
|
|
383
|
+
switch (event.type) {
|
|
384
|
+
case "message.delta":
|
|
385
|
+
if (event.content.type === "text") appendText(record, event.content.text);
|
|
386
|
+
return;
|
|
387
|
+
case "message.completed": {
|
|
388
|
+
if (event.message.role !== "assistant") return;
|
|
389
|
+
if (!record.current) {
|
|
390
|
+
const text = event.message.content.map((block) => (block.type === "text" ? block.text : "")).join("");
|
|
391
|
+
appendText(record, text);
|
|
392
|
+
}
|
|
393
|
+
closeArtifact(record);
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
case "run.suspended": {
|
|
397
|
+
const interruption = options.redactor?.redact(event.interruption) ?? event.interruption;
|
|
398
|
+
const pending: readonly PendingDecision[] =
|
|
399
|
+
interruption.pendingDecisions ??
|
|
400
|
+
(interruption.toolCallId || interruption.toolName
|
|
401
|
+
? [
|
|
402
|
+
{
|
|
403
|
+
approvalId: event.runId,
|
|
404
|
+
kind: interruption.kind === "elicitation" ? "elicitation" : "tool_approval",
|
|
405
|
+
toolCallId: interruption.toolCallId,
|
|
406
|
+
scope: interruption.toolName ? { toolName: interruption.toolName } : {},
|
|
407
|
+
reason: interruption.reason,
|
|
408
|
+
},
|
|
409
|
+
]
|
|
410
|
+
: []);
|
|
411
|
+
if (pending.length === 0) {
|
|
412
|
+
finish(record, "TASK_STATE_FAILED", statusMessage(record, [{ text: "The run suspended with no decision to answer" }]));
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
record.pending = pending;
|
|
416
|
+
finish(record, "TASK_STATE_INPUT_REQUIRED", statusMessage(record, pendingParts(pending)));
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
case "run.completed":
|
|
420
|
+
finish(record, event.status === "stopped" && event.stopReason === "denied" ? "TASK_STATE_REJECTED" : "TASK_STATE_COMPLETED");
|
|
421
|
+
return;
|
|
422
|
+
case "run.failed":
|
|
423
|
+
if (record.cancelRequested) finish(record, "TASK_STATE_CANCELED");
|
|
424
|
+
else if (record.timedOut) finish(record, "TASK_STATE_FAILED", statusMessage(record, [{ text: "The task timed out" }]));
|
|
425
|
+
else finish(record, "TASK_STATE_FAILED", statusMessage(record, [{ text: redact(event.error.message || "The run failed") }]));
|
|
426
|
+
return;
|
|
427
|
+
default:
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
async function pump(record: TaskRecord, iterator: AsyncIterator<AgentEvent>, release: () => void): Promise<void> {
|
|
433
|
+
try {
|
|
434
|
+
while (record.state === "TASK_STATE_WORKING") {
|
|
435
|
+
const next = await iterator.next();
|
|
436
|
+
if (next.done) break;
|
|
437
|
+
apply(record, next.value);
|
|
438
|
+
}
|
|
439
|
+
} catch {
|
|
440
|
+
// A throwing iterator ends the task below; its error text is never forwarded.
|
|
441
|
+
} finally {
|
|
442
|
+
if (record.state === "TASK_STATE_WORKING") {
|
|
443
|
+
finish(record, record.cancelRequested ? "TASK_STATE_CANCELED" : "TASK_STATE_FAILED");
|
|
444
|
+
}
|
|
445
|
+
release();
|
|
446
|
+
await iterator.return?.().catch(() => {});
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function reserve(principalKey: string, context: ContextEntry): void {
|
|
451
|
+
if (context.busy) throw new A2AError("invalidParams", "The context has a task in progress");
|
|
452
|
+
const count = working.get(principalKey) ?? 0;
|
|
453
|
+
if (count >= limits.maxConcurrentTasks) throw new A2AError("overloaded", "Too many concurrent tasks", 429);
|
|
454
|
+
working.set(principalKey, count + 1);
|
|
455
|
+
context.busy = true;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function unreserve(principalKey: string, context: ContextEntry): void {
|
|
459
|
+
working.set(principalKey, Math.max(0, (working.get(principalKey) ?? 1) - 1));
|
|
460
|
+
context.busy = false;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
async function startTask(context: ContextEntry, caller: Caller, input: Message, listener?: Listener): Promise<TaskRecord> {
|
|
464
|
+
reserve(caller.principalKey, context);
|
|
465
|
+
const controller = new AbortController();
|
|
466
|
+
let iterator: AsyncIterator<AgentEvent>;
|
|
467
|
+
let runId: string;
|
|
468
|
+
try {
|
|
469
|
+
iterator = context.session
|
|
470
|
+
.stream(input, {
|
|
471
|
+
...(caller.ownership ? { ownership: caller.ownership } : {}),
|
|
472
|
+
principal: caller.principal,
|
|
473
|
+
signal: controller.signal,
|
|
474
|
+
interactive: false,
|
|
475
|
+
...(options.redactor ? { redactor: options.redactor } : {}),
|
|
476
|
+
overflow: "coalesce",
|
|
477
|
+
})
|
|
478
|
+
[Symbol.asyncIterator]();
|
|
479
|
+
runId = await untilStarted(iterator);
|
|
480
|
+
} catch (error) {
|
|
481
|
+
unreserve(caller.principalKey, context);
|
|
482
|
+
throw error;
|
|
483
|
+
}
|
|
484
|
+
const record = newRecord(context.id, runId, caller.principalKey, "TASK_STATE_WORKING");
|
|
485
|
+
try {
|
|
486
|
+
register(record);
|
|
487
|
+
} catch (error) {
|
|
488
|
+
context.session.abort("A2A registry full");
|
|
489
|
+
unreserve(caller.principalKey, context);
|
|
490
|
+
await iterator.return?.().catch(() => {});
|
|
491
|
+
throw error;
|
|
492
|
+
}
|
|
493
|
+
const release = arm(record, controller, context);
|
|
494
|
+
if (listener) {
|
|
495
|
+
record.listeners.add(listener);
|
|
496
|
+
listener({ task: snapshot(record) }, false);
|
|
497
|
+
}
|
|
498
|
+
void pump(record, iterator, release);
|
|
499
|
+
return record;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
async function resumeTask(
|
|
503
|
+
record: TaskRecord,
|
|
504
|
+
context: ContextEntry,
|
|
505
|
+
caller: Caller,
|
|
506
|
+
decisions: readonly Decision[],
|
|
507
|
+
listener?: Listener,
|
|
508
|
+
): Promise<void> {
|
|
509
|
+
const known = new Set(record.pending.map((decision) => decision.approvalId));
|
|
510
|
+
if (decisions.some((decision) => !known.has(decision.approvalId))) {
|
|
511
|
+
throw new A2AError("invalidParams", "Decisions do not match the pending task");
|
|
512
|
+
}
|
|
513
|
+
reserve(caller.principalKey, context);
|
|
514
|
+
const controller = new AbortController();
|
|
515
|
+
let iterator: AsyncIterator<AgentEvent>;
|
|
516
|
+
try {
|
|
517
|
+
iterator = context.session
|
|
518
|
+
.resume(decisions, {
|
|
519
|
+
...(caller.ownership ? { ownership: caller.ownership } : {}),
|
|
520
|
+
principal: caller.principal,
|
|
521
|
+
signal: controller.signal,
|
|
522
|
+
interactive: false,
|
|
523
|
+
...(options.redactor ? { redactor: options.redactor } : {}),
|
|
524
|
+
overflow: "coalesce",
|
|
525
|
+
})
|
|
526
|
+
[Symbol.asyncIterator]();
|
|
527
|
+
const runId = await untilStarted(iterator);
|
|
528
|
+
if (runId !== record.runId) throw new A2AError("internalError", "The resumed run does not match the task");
|
|
529
|
+
} catch (error) {
|
|
530
|
+
unreserve(caller.principalKey, context);
|
|
531
|
+
throw error;
|
|
532
|
+
}
|
|
533
|
+
const release = arm(record, controller, context);
|
|
534
|
+
record.pending = [];
|
|
535
|
+
setState(record, "TASK_STATE_WORKING");
|
|
536
|
+
if (listener) {
|
|
537
|
+
record.listeners.add(listener);
|
|
538
|
+
listener({ task: snapshot(record) }, false);
|
|
539
|
+
}
|
|
540
|
+
emit(record, statusFrame(record));
|
|
541
|
+
void pump(record, iterator, release);
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
async function history(record: TaskRecord, length: number | undefined): Promise<readonly A2AMessage[] | undefined> {
|
|
545
|
+
if (!length) return undefined;
|
|
546
|
+
const context = await contexts.get(record.contextId)?.catch(() => undefined);
|
|
547
|
+
if (!context) return undefined;
|
|
548
|
+
const messages = await context.session.messages();
|
|
549
|
+
const out: A2AMessage[] = [];
|
|
550
|
+
for (let index = messages.length - 1; index >= 0 && out.length < Math.min(length, limits.maxHistory); index -= 1) {
|
|
551
|
+
const message = messages[index];
|
|
552
|
+
const mapped = message ? messageToA2A(message, index, record.contextId, record.id) : undefined;
|
|
553
|
+
if (mapped) out.unshift(mapped);
|
|
554
|
+
}
|
|
555
|
+
return out;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
// --- methods -----------------------------------------------------------------------------------
|
|
559
|
+
|
|
560
|
+
async function sendMessage(rpc: JsonRpcRequest, caller: Caller, stream: SseStream | undefined): Promise<Response> {
|
|
561
|
+
const params = parseSendMessageParams(rpc.params, limits.maxParts);
|
|
562
|
+
const decisions = readDecisions(params.message, options.allowModifiedArguments === true, maxDecisions);
|
|
563
|
+
let record: TaskRecord;
|
|
564
|
+
if (params.message.taskId !== undefined) {
|
|
565
|
+
record = await lookup(params.message.taskId, caller.principalKey, caller.ownership);
|
|
566
|
+
if (params.message.contextId !== undefined && params.message.contextId !== record.contextId) {
|
|
567
|
+
throw new A2AError("invalidParams", "message.contextId does not match the task");
|
|
568
|
+
}
|
|
569
|
+
if (TERMINAL_STATES.has(record.state)) throw new A2AError("unsupportedOperation", "The task is in a terminal state");
|
|
570
|
+
if (record.state !== "TASK_STATE_INPUT_REQUIRED") throw new A2AError("invalidParams", "The task is still working");
|
|
571
|
+
if (!decisions) throw new A2AError("invalidParams", "The task is waiting for decisions");
|
|
572
|
+
const context = await contextFor(record.contextId, caller.principalKey, caller.ownership, false);
|
|
573
|
+
await resumeTask(record, context, caller, decisions, stream?.listener);
|
|
574
|
+
} else {
|
|
575
|
+
if (decisions) throw new A2AError("invalidParams", "Decisions need the taskId they answer");
|
|
576
|
+
const input = partsToMessage(params.message.parts, declaredInput);
|
|
577
|
+
const contextId = params.message.contextId ?? randomUUID();
|
|
578
|
+
if (!isA2AId(contextId)) throw new A2AError("invalidParams", "message.contextId is invalid");
|
|
579
|
+
const context = await contextFor(contextId, caller.principalKey, caller.ownership, true);
|
|
580
|
+
if (!context.busy && suspensionOf(await context.session.entries())) {
|
|
581
|
+
throw new A2AError("invalidParams", "The context has a task waiting for decisions");
|
|
582
|
+
}
|
|
583
|
+
record = await startTask(context, caller, input, stream?.listener);
|
|
584
|
+
}
|
|
585
|
+
if (stream) {
|
|
586
|
+
if (record.state !== "TASK_STATE_WORKING") stream.end();
|
|
587
|
+
return stream.response(rpc.id);
|
|
588
|
+
}
|
|
589
|
+
if (!params.returnImmediately) await record.segment;
|
|
590
|
+
return json(rpc.id, { task: snapshot(record, await history(record, params.historyLength)) });
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
async function getTask(rpc: JsonRpcRequest, caller: Caller): Promise<Response> {
|
|
594
|
+
const params = parseTaskIdParams(rpc.params);
|
|
595
|
+
const record = await lookup(params.id, caller.principalKey, caller.ownership);
|
|
596
|
+
if (params.historyLength) await contextFor(record.contextId, caller.principalKey, caller.ownership, false);
|
|
597
|
+
return json(rpc.id, snapshot(record, await history(record, params.historyLength)));
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
async function cancelTask(rpc: JsonRpcRequest, caller: Caller): Promise<Response> {
|
|
601
|
+
const params = parseTaskIdParams(rpc.params);
|
|
602
|
+
const record = await lookup(params.id, caller.principalKey, caller.ownership);
|
|
603
|
+
if (record.state !== "TASK_STATE_WORKING") throw new A2AError("taskNotCancelable", "The task cannot be canceled in its current state");
|
|
604
|
+
record.cancelRequested = true;
|
|
605
|
+
const context = await contexts.get(record.contextId);
|
|
606
|
+
context?.session.abort("A2A CancelTask");
|
|
607
|
+
record.controller?.abort(new Error("A2A CancelTask"));
|
|
608
|
+
await record.segment;
|
|
609
|
+
return json(rpc.id, snapshot(record));
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
async function subscribeToTask(rpc: JsonRpcRequest, caller: Caller, stream: SseStream): Promise<Response> {
|
|
613
|
+
const params = parseTaskIdParams(rpc.params);
|
|
614
|
+
const record = await lookup(params.id, caller.principalKey, caller.ownership);
|
|
615
|
+
if (TERMINAL_STATES.has(record.state)) throw new A2AError("unsupportedOperation", "The task is in a terminal state");
|
|
616
|
+
stream.listener({ task: snapshot(record) }, INTERRUPTED_STATES.has(record.state));
|
|
617
|
+
if (record.state === "TASK_STATE_WORKING") record.listeners.add(stream.listener);
|
|
618
|
+
return stream.response(rpc.id);
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
async function dispatch(rpc: JsonRpcRequest, caller: Caller): Promise<Response> {
|
|
622
|
+
switch (rpc.method) {
|
|
623
|
+
case "SendMessage":
|
|
624
|
+
return sendMessage(rpc, caller, undefined);
|
|
625
|
+
case "SendStreamingMessage": {
|
|
626
|
+
const stream = sseStream(limits);
|
|
627
|
+
try {
|
|
628
|
+
return await sendMessage(rpc, caller, stream);
|
|
629
|
+
} catch (error) {
|
|
630
|
+
stream.discard();
|
|
631
|
+
throw error;
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
case "GetTask":
|
|
635
|
+
return getTask(rpc, caller);
|
|
636
|
+
case "CancelTask":
|
|
637
|
+
return cancelTask(rpc, caller);
|
|
638
|
+
case "SubscribeToTask": {
|
|
639
|
+
const stream = sseStream(limits);
|
|
640
|
+
try {
|
|
641
|
+
return await subscribeToTask(rpc, caller, stream);
|
|
642
|
+
} catch (error) {
|
|
643
|
+
stream.discard();
|
|
644
|
+
throw error;
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
case "ListTasks":
|
|
648
|
+
throw new A2AError("unsupportedOperation", "ListTasks is not supported");
|
|
649
|
+
case "CreateTaskPushNotificationConfig":
|
|
650
|
+
case "GetTaskPushNotificationConfig":
|
|
651
|
+
case "ListTaskPushNotificationConfig":
|
|
652
|
+
case "ListTaskPushNotificationConfigs":
|
|
653
|
+
case "DeleteTaskPushNotificationConfig":
|
|
654
|
+
throw new A2AError("pushNotificationNotSupported", "Push notifications are not supported");
|
|
655
|
+
case "GetExtendedAgentCard":
|
|
656
|
+
throw new A2AError("extendedAgentCardNotConfigured", "No extended Agent Card is configured");
|
|
657
|
+
default:
|
|
658
|
+
throw new A2AError("methodNotFound", "Method not found");
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
function json(id: JsonRpcId, result: unknown): Response {
|
|
663
|
+
const body = jsonRpcResult(id, result);
|
|
664
|
+
if (Buffer.byteLength(body) > limits.maxResponseBytes) {
|
|
665
|
+
return new Response(jsonRpcError(id, new A2AError("internalError", "Response exceeds maxResponseBytes")), { headers: JSON_HEADERS });
|
|
666
|
+
}
|
|
667
|
+
return new Response(body, { headers: JSON_HEADERS });
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
const handler = async (request: Request): Promise<Response> => {
|
|
671
|
+
const url = new URL(request.url);
|
|
672
|
+
if (url.pathname === A2A_CARD_PATH) {
|
|
673
|
+
if (request.method !== "GET" && request.method !== "HEAD")
|
|
674
|
+
return new Response(null, { status: 405, headers: { allow: "GET, HEAD" } });
|
|
675
|
+
try {
|
|
676
|
+
return new Response(await cardBody(), {
|
|
677
|
+
headers: { "content-type": "application/json; charset=utf-8", "cache-control": "public, max-age=300" },
|
|
678
|
+
});
|
|
679
|
+
} catch {
|
|
680
|
+
return new Response(JSON.stringify({ error: "Agent Card unavailable" }), {
|
|
681
|
+
status: 503,
|
|
682
|
+
headers: { "content-type": "application/json" },
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
if (url.pathname !== endpointPath) return new Response(null, { status: 404 });
|
|
687
|
+
if (request.method !== "POST") return new Response(null, { status: 405, headers: { allow: "POST" } });
|
|
688
|
+
let rpcId: JsonRpcId | null = null;
|
|
689
|
+
try {
|
|
690
|
+
const version = request.headers.get("a2a-version") ?? url.searchParams.get("A2A-Version") ?? "";
|
|
691
|
+
// An empty or missing version means 0.3 (spec §3.6.2), which this server does not serve.
|
|
692
|
+
if (!VERSION_PATTERN.test(version.trim())) throw new A2AError("versionNotSupported", "A2A version not supported");
|
|
693
|
+
const contentType = request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
|
|
694
|
+
if (contentType !== "application/json" && contentType !== "application/a2a+json") {
|
|
695
|
+
throw new A2AError("invalidRequest", "Content-Type must be application/json", 415);
|
|
696
|
+
}
|
|
697
|
+
const rpc = parseJsonRpcRequest(await readJson(request, limits.maxRequestBytes));
|
|
698
|
+
rpcId = rpc.id;
|
|
699
|
+
const caller = await authorizeCall(request, rpc.method);
|
|
700
|
+
return await dispatch(rpc, caller);
|
|
701
|
+
} catch (error) {
|
|
702
|
+
const known = error instanceof A2AError ? error : new A2AError("internalError", "Internal error");
|
|
703
|
+
return new Response(jsonRpcError(rpcId, known), { status: known.status, headers: JSON_HEADERS });
|
|
704
|
+
}
|
|
705
|
+
};
|
|
706
|
+
|
|
707
|
+
async function authorizeCall(request: Request, method: string): Promise<Caller> {
|
|
708
|
+
if (typeof options.authorize !== "function") throw new A2AError("invalidRequest", "Unauthorized", 401);
|
|
709
|
+
let result: A2AAuthorization | false;
|
|
710
|
+
try {
|
|
711
|
+
result = await options.authorize({ request, method, signal: request.signal });
|
|
712
|
+
} catch {
|
|
713
|
+
throw new A2AError("invalidRequest", "Unauthorized", 401);
|
|
714
|
+
}
|
|
715
|
+
const principal = result ? result.principal : undefined;
|
|
716
|
+
if (!result || !principal || typeof principal.kind !== "string" || typeof principal.id !== "string" || principal.id.length === 0) {
|
|
717
|
+
throw new A2AError("invalidRequest", "Unauthorized", 401);
|
|
718
|
+
}
|
|
719
|
+
const ownership = result.ownership ?? options.ownershipFor?.(principal);
|
|
720
|
+
return { principal, ownership, principalKey: `${principal.kind.length}:${principal.kind}:${principal.id}` };
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
async function close(): Promise<void> {
|
|
724
|
+
const segments: Promise<void>[] = [];
|
|
725
|
+
for (const record of tasks.values()) {
|
|
726
|
+
if (record.state !== "TASK_STATE_WORKING") continue;
|
|
727
|
+
record.cancelRequested = true;
|
|
728
|
+
record.controller?.abort(new Error("A2A handler closed"));
|
|
729
|
+
segments.push(record.segment);
|
|
730
|
+
}
|
|
731
|
+
for (const promise of contexts.values()) (await promise.catch(() => undefined))?.session.abort("A2A handler closed");
|
|
732
|
+
await Promise.all(segments);
|
|
733
|
+
for (const promise of contexts.values()) await (await promise.catch(() => undefined))?.session.close().catch(() => {});
|
|
734
|
+
contexts.clear();
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
return Object.assign(handler, { card, close });
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
interface Caller {
|
|
741
|
+
readonly principal: Principal;
|
|
742
|
+
readonly ownership: OwnershipScope | undefined;
|
|
743
|
+
readonly principalKey: string;
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
interface SseStream {
|
|
747
|
+
readonly listener: Listener;
|
|
748
|
+
end(): void;
|
|
749
|
+
discard(): void;
|
|
750
|
+
response(id: JsonRpcId): Response;
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
/**
|
|
754
|
+
* One SSE response fed by a task listener. It closes at a terminal or interrupted state, at a stream limit,
|
|
755
|
+
* or when the client goes away; the task itself keeps running and can be resubscribed.
|
|
756
|
+
*/
|
|
757
|
+
function sseStream(limits: ResolvedA2ALimits): SseStream {
|
|
758
|
+
const queue: { frame: A2AStreamResponse; end: boolean }[] = [];
|
|
759
|
+
let wake: (() => void) | undefined;
|
|
760
|
+
let ended = false;
|
|
761
|
+
let detached = false;
|
|
762
|
+
const listener: Listener = (frame, end) => {
|
|
763
|
+
if (detached) return;
|
|
764
|
+
queue.push({ frame, end });
|
|
765
|
+
wake?.();
|
|
766
|
+
};
|
|
767
|
+
return {
|
|
768
|
+
listener,
|
|
769
|
+
end() {
|
|
770
|
+
ended = true;
|
|
771
|
+
wake?.();
|
|
772
|
+
},
|
|
773
|
+
discard() {
|
|
774
|
+
detached = true;
|
|
775
|
+
},
|
|
776
|
+
response(id) {
|
|
777
|
+
const encoder = new TextEncoder();
|
|
778
|
+
let count = 0;
|
|
779
|
+
let bytes = 0;
|
|
780
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
781
|
+
let timedOut = false;
|
|
782
|
+
const stop = () => {
|
|
783
|
+
detached = true;
|
|
784
|
+
if (timer) clearTimeout(timer);
|
|
785
|
+
};
|
|
786
|
+
return new Response(
|
|
787
|
+
new ReadableStream<Uint8Array>({
|
|
788
|
+
start() {
|
|
789
|
+
timer = setTimeout(() => {
|
|
790
|
+
timedOut = true;
|
|
791
|
+
wake?.();
|
|
792
|
+
}, limits.maxStreamMs);
|
|
793
|
+
},
|
|
794
|
+
async pull(controller) {
|
|
795
|
+
while (queue.length === 0 && !ended && !timedOut) {
|
|
796
|
+
await new Promise<void>((resolve) => {
|
|
797
|
+
wake = resolve;
|
|
798
|
+
});
|
|
799
|
+
wake = undefined;
|
|
800
|
+
}
|
|
801
|
+
const next = queue.shift();
|
|
802
|
+
if (!next) {
|
|
803
|
+
stop();
|
|
804
|
+
controller.close();
|
|
805
|
+
return;
|
|
806
|
+
}
|
|
807
|
+
const chunk = encoder.encode(`data: ${jsonRpcResult(id, next.frame)}\n\n`);
|
|
808
|
+
count += 1;
|
|
809
|
+
bytes += chunk.byteLength;
|
|
810
|
+
if (count > limits.maxStreamEvents || bytes > limits.maxStreamBytes) {
|
|
811
|
+
controller.enqueue(encoder.encode(`data: ${jsonRpcError(id, new A2AError("internalError", "Stream limit exceeded"))}\n\n`));
|
|
812
|
+
stop();
|
|
813
|
+
controller.close();
|
|
814
|
+
return;
|
|
815
|
+
}
|
|
816
|
+
controller.enqueue(chunk);
|
|
817
|
+
if (next.end) {
|
|
818
|
+
ended = true;
|
|
819
|
+
if (queue.length === 0) {
|
|
820
|
+
stop();
|
|
821
|
+
controller.close();
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
},
|
|
825
|
+
cancel: stop,
|
|
826
|
+
}),
|
|
827
|
+
{ status: 200, headers: SSE_HEADERS },
|
|
828
|
+
);
|
|
829
|
+
},
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
async function readJson(request: Request, maxBytes: number): Promise<unknown> {
|
|
834
|
+
const declared = Number(request.headers.get("content-length") ?? "0");
|
|
835
|
+
if (Number.isFinite(declared) && declared > maxBytes) throw new A2AError("invalidRequest", "Request exceeds maxRequestBytes", 413);
|
|
836
|
+
if (!request.body) throw new A2AError("invalidRequest", "Request body is required");
|
|
837
|
+
const reader = request.body.getReader();
|
|
838
|
+
const chunks: Uint8Array[] = [];
|
|
839
|
+
let bytes = 0;
|
|
840
|
+
try {
|
|
841
|
+
while (true) {
|
|
842
|
+
const next = await reader.read();
|
|
843
|
+
if (next.done) break;
|
|
844
|
+
bytes += next.value.byteLength;
|
|
845
|
+
if (bytes > maxBytes) throw new A2AError("invalidRequest", "Request exceeds maxRequestBytes", 413);
|
|
846
|
+
chunks.push(next.value);
|
|
847
|
+
}
|
|
848
|
+
} finally {
|
|
849
|
+
reader.releaseLock();
|
|
850
|
+
}
|
|
851
|
+
try {
|
|
852
|
+
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)));
|
|
853
|
+
} catch {
|
|
854
|
+
throw new A2AError("parseError", "Invalid JSON");
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
function resolverOf(agent: Agent): CredentialResolver {
|
|
859
|
+
const assigned = agent.config?.slots?.credentials;
|
|
860
|
+
return typeof assigned === "object" ? assigned : createEnvRefCredentialResolver();
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
function notFound(): A2AError {
|
|
864
|
+
return new A2AError("taskNotFound", "Task not found");
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
function nameOf(error: unknown): string | undefined {
|
|
868
|
+
return error instanceof Error ? error.name : undefined;
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
function codeOf(error: unknown): unknown {
|
|
872
|
+
return error instanceof Error ? (error as { code?: unknown }).code : undefined;
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
function boundedText(value: string, maxBytes: number): string {
|
|
876
|
+
if (Buffer.byteLength(value) <= maxBytes) return value;
|
|
877
|
+
let out = "";
|
|
878
|
+
let bytes = 0;
|
|
879
|
+
for (const char of value) {
|
|
880
|
+
const size = Buffer.byteLength(char);
|
|
881
|
+
if (bytes + size > maxBytes - 3) break;
|
|
882
|
+
bytes += size;
|
|
883
|
+
out += char;
|
|
884
|
+
}
|
|
885
|
+
return `${out}…`;
|
|
886
|
+
}
|