@arnilo/prism-hosts 0.13.0 → 0.14.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/CHANGELOG.md +2 -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 +1308 -1367
- package/host-builder/data/errors.json +207 -181
- 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 +3 -3
- package/host-builder/data/examples/memory-system.ts +31 -18
- 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 +29 -26
- package/host-builder/data/examples/side-call.ts +9 -5
- 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 +15 -5
- 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/codec.ts
ADDED
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A2A 1.0 JSON-RPC codec: wire types, request validation, part ↔ content mapping, and the Prism
|
|
3
|
+
* decisions extension. No I/O and no agent access; `serve.ts` (and the client in Task 3) share it.
|
|
4
|
+
*/
|
|
5
|
+
import type { ApprovalOutcome, ContentBlock, Decision, JsonObject, JsonValue, Message, PendingDecision } from "@arnilo/prism";
|
|
6
|
+
import { A2AError } from "./errors.js";
|
|
7
|
+
|
|
8
|
+
export const A2A_PROTOCOL_VERSION = "1.0";
|
|
9
|
+
export const A2A_CARD_PATH = "/.well-known/agent-card.json";
|
|
10
|
+
/** Extension URI a message lists in `extensions` when one of its `data` parts carries `{ decisions }`. */
|
|
11
|
+
export const PRISM_DECISIONS_EXTENSION = "https://prism.arnilo.dev/a2a/extensions/decisions/v1";
|
|
12
|
+
|
|
13
|
+
export type A2ATaskState =
|
|
14
|
+
| "TASK_STATE_SUBMITTED"
|
|
15
|
+
| "TASK_STATE_WORKING"
|
|
16
|
+
| "TASK_STATE_INPUT_REQUIRED"
|
|
17
|
+
| "TASK_STATE_AUTH_REQUIRED"
|
|
18
|
+
| "TASK_STATE_COMPLETED"
|
|
19
|
+
| "TASK_STATE_FAILED"
|
|
20
|
+
| "TASK_STATE_CANCELED"
|
|
21
|
+
| "TASK_STATE_REJECTED";
|
|
22
|
+
|
|
23
|
+
export type A2ARole = "ROLE_USER" | "ROLE_AGENT";
|
|
24
|
+
|
|
25
|
+
/** Exactly one of `text`, `raw`, `url`, `data`. */
|
|
26
|
+
export interface A2APart {
|
|
27
|
+
readonly text?: string;
|
|
28
|
+
readonly raw?: string;
|
|
29
|
+
readonly url?: string;
|
|
30
|
+
readonly data?: JsonValue;
|
|
31
|
+
readonly mediaType?: string;
|
|
32
|
+
readonly filename?: string;
|
|
33
|
+
readonly metadata?: JsonObject;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface A2AMessage {
|
|
37
|
+
readonly messageId: string;
|
|
38
|
+
readonly role: A2ARole;
|
|
39
|
+
readonly parts: readonly A2APart[];
|
|
40
|
+
readonly contextId?: string;
|
|
41
|
+
readonly taskId?: string;
|
|
42
|
+
readonly extensions?: readonly string[];
|
|
43
|
+
readonly referenceTaskIds?: readonly string[];
|
|
44
|
+
readonly metadata?: JsonObject;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface A2ATaskStatus {
|
|
48
|
+
readonly state: A2ATaskState;
|
|
49
|
+
readonly message?: A2AMessage;
|
|
50
|
+
readonly timestamp: string;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface A2AArtifact {
|
|
54
|
+
readonly artifactId: string;
|
|
55
|
+
readonly name?: string;
|
|
56
|
+
readonly parts: readonly A2APart[];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface A2ATask {
|
|
60
|
+
readonly id: string;
|
|
61
|
+
readonly contextId: string;
|
|
62
|
+
readonly status: A2ATaskStatus;
|
|
63
|
+
readonly artifacts?: readonly A2AArtifact[];
|
|
64
|
+
readonly history?: readonly A2AMessage[];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface A2ATaskStatusUpdateEvent {
|
|
68
|
+
readonly taskId: string;
|
|
69
|
+
readonly contextId: string;
|
|
70
|
+
readonly status: A2ATaskStatus;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface A2ATaskArtifactUpdateEvent {
|
|
74
|
+
readonly taskId: string;
|
|
75
|
+
readonly contextId: string;
|
|
76
|
+
readonly artifact: A2AArtifact;
|
|
77
|
+
readonly append?: boolean;
|
|
78
|
+
readonly lastChunk?: boolean;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** One `SendStreamingMessage` / `SubscribeToTask` SSE frame result: exactly one member. */
|
|
82
|
+
export type A2AStreamResponse =
|
|
83
|
+
| { readonly task: A2ATask }
|
|
84
|
+
| { readonly message: A2AMessage }
|
|
85
|
+
| { readonly statusUpdate: A2ATaskStatusUpdateEvent }
|
|
86
|
+
| { readonly artifactUpdate: A2ATaskArtifactUpdateEvent };
|
|
87
|
+
|
|
88
|
+
export type JsonRpcId = string | number;
|
|
89
|
+
|
|
90
|
+
export interface JsonRpcRequest {
|
|
91
|
+
readonly id: JsonRpcId;
|
|
92
|
+
readonly method: string;
|
|
93
|
+
readonly params: Readonly<Record<string, unknown>>;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export interface SendMessageParams {
|
|
97
|
+
readonly message: A2AMessage;
|
|
98
|
+
readonly returnImmediately: boolean;
|
|
99
|
+
readonly historyLength?: number;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export const TERMINAL_STATES: ReadonlySet<A2ATaskState> = new Set([
|
|
103
|
+
"TASK_STATE_COMPLETED",
|
|
104
|
+
"TASK_STATE_FAILED",
|
|
105
|
+
"TASK_STATE_CANCELED",
|
|
106
|
+
"TASK_STATE_REJECTED",
|
|
107
|
+
]);
|
|
108
|
+
|
|
109
|
+
export const INTERRUPTED_STATES: ReadonlySet<A2ATaskState> = new Set(["TASK_STATE_INPUT_REQUIRED", "TASK_STATE_AUTH_REQUIRED"]);
|
|
110
|
+
|
|
111
|
+
const ID_PATTERN = /^[A-Za-z0-9._:~-]{1,128}$/;
|
|
112
|
+
const TASK_ID_PATTERN = /^[A-Za-z0-9._:~-]{1,1024}$/;
|
|
113
|
+
const OUTCOMES: ReadonlySet<string> = new Set(["allow_once", "allow_for_run", "reject_once", "reject_for_run"]);
|
|
114
|
+
const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
115
|
+
const MAX_TEXT_BYTES = 256 * 1024;
|
|
116
|
+
const MAX_DECISIONS = 128;
|
|
117
|
+
const MAX_DECISION_REASON_BYTES = 2 * 1024;
|
|
118
|
+
|
|
119
|
+
function invalidParams(message: string): A2AError {
|
|
120
|
+
return new A2AError("invalidParams", message);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
124
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** A protocol id (`contextId`, `taskId`, `messageId`): bounded and limited to URL-safe characters. */
|
|
128
|
+
export function isA2AId(value: unknown): value is string {
|
|
129
|
+
return typeof value === "string" && ID_PATTERN.test(value);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function isA2ATaskId(value: unknown): value is string {
|
|
133
|
+
return typeof value === "string" && TASK_ID_PATTERN.test(value);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Validates a JSON-RPC 2.0 request envelope. Notifications (no `id`) and batches are refused. */
|
|
137
|
+
export function parseJsonRpcRequest(value: unknown): JsonRpcRequest {
|
|
138
|
+
if (!isRecord(value) || value.jsonrpc !== "2.0" || typeof value.method !== "string" || value.method.length === 0) {
|
|
139
|
+
throw new A2AError("invalidRequest", "Invalid JSON-RPC request");
|
|
140
|
+
}
|
|
141
|
+
const id = value.id;
|
|
142
|
+
if (!((typeof id === "string" && id.length <= 256) || (typeof id === "number" && Number.isSafeInteger(id)))) {
|
|
143
|
+
throw new A2AError("invalidRequest", "JSON-RPC request id must be a string or an integer");
|
|
144
|
+
}
|
|
145
|
+
const params = value.params ?? {};
|
|
146
|
+
if (!isRecord(params)) throw invalidParams("params must be an object");
|
|
147
|
+
return { id, method: value.method, params };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Parses `SendMessageRequest` params. A push-notification config is refused with `-32003`. */
|
|
151
|
+
export function parseSendMessageParams(params: Readonly<Record<string, unknown>>, maxParts: number): SendMessageParams {
|
|
152
|
+
const configuration = params.configuration ?? {};
|
|
153
|
+
if (!isRecord(configuration)) throw invalidParams("configuration must be an object");
|
|
154
|
+
if (configuration.taskPushNotificationConfig !== undefined || configuration.pushNotificationConfig !== undefined) {
|
|
155
|
+
throw new A2AError("pushNotificationNotSupported", "Push notifications are not supported");
|
|
156
|
+
}
|
|
157
|
+
if (configuration.returnImmediately !== undefined && typeof configuration.returnImmediately !== "boolean") {
|
|
158
|
+
throw invalidParams("configuration.returnImmediately must be a boolean");
|
|
159
|
+
}
|
|
160
|
+
const historyLength = parseHistoryLength(configuration.historyLength);
|
|
161
|
+
return {
|
|
162
|
+
message: parseA2AMessage(params.message, maxParts, "ROLE_USER"),
|
|
163
|
+
returnImmediately: configuration.returnImmediately === true,
|
|
164
|
+
...(historyLength === undefined ? {} : { historyLength }),
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** `GetTask` / `CancelTask` / `SubscribeToTask` params: `{ id, historyLength? }`. */
|
|
169
|
+
export function parseTaskIdParams(params: Readonly<Record<string, unknown>>): { readonly id: string; readonly historyLength?: number } {
|
|
170
|
+
if (!isA2ATaskId(params.id)) throw invalidParams("id must be a task id");
|
|
171
|
+
const historyLength = parseHistoryLength(params.historyLength);
|
|
172
|
+
return { id: params.id, ...(historyLength === undefined ? {} : { historyLength }) };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function parseHistoryLength(value: unknown): number | undefined {
|
|
176
|
+
if (value === undefined || value === null) return undefined;
|
|
177
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0)
|
|
178
|
+
throw invalidParams("historyLength must be a non-negative integer");
|
|
179
|
+
return value;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function parseRole(value: unknown): A2ARole {
|
|
183
|
+
if (value === "ROLE_USER" || value === "user") return "ROLE_USER";
|
|
184
|
+
if (value === "ROLE_AGENT" || value === "agent") return "ROLE_AGENT";
|
|
185
|
+
throw invalidParams("message.role is invalid");
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Validates one `Message`. `expectRole` pins the sender (a server accepts only `ROLE_USER`). */
|
|
189
|
+
export function parseA2AMessage(value: unknown, maxParts: number, expectRole?: A2ARole): A2AMessage {
|
|
190
|
+
if (!isRecord(value)) throw invalidParams("message is required");
|
|
191
|
+
if (!isA2AId(value.messageId)) throw invalidParams("message.messageId is invalid");
|
|
192
|
+
const role = parseRole(value.role);
|
|
193
|
+
if (expectRole !== undefined && role !== expectRole) throw invalidParams("message.role is invalid");
|
|
194
|
+
if (!Array.isArray(value.parts) || value.parts.length === 0 || value.parts.length > maxParts) {
|
|
195
|
+
throw invalidParams("message.parts must be a non-empty bounded array");
|
|
196
|
+
}
|
|
197
|
+
if (value.contextId !== undefined && !isA2AId(value.contextId)) throw invalidParams("message.contextId is invalid");
|
|
198
|
+
if (value.taskId !== undefined && !isA2ATaskId(value.taskId)) throw invalidParams("message.taskId is invalid");
|
|
199
|
+
const extensions = value.extensions;
|
|
200
|
+
if (
|
|
201
|
+
extensions !== undefined &&
|
|
202
|
+
(!Array.isArray(extensions) || extensions.length > 32 || extensions.some((uri) => typeof uri !== "string" || uri.length > 512))
|
|
203
|
+
) {
|
|
204
|
+
throw invalidParams("message.extensions is invalid");
|
|
205
|
+
}
|
|
206
|
+
return {
|
|
207
|
+
messageId: value.messageId,
|
|
208
|
+
role,
|
|
209
|
+
parts: value.parts.map(parseA2APart),
|
|
210
|
+
...(typeof value.contextId === "string" ? { contextId: value.contextId } : {}),
|
|
211
|
+
...(typeof value.taskId === "string" ? { taskId: value.taskId } : {}),
|
|
212
|
+
...(extensions ? { extensions: extensions as string[] } : {}),
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Validates one `Part`: exactly one of `text`, `raw` (base64), `url`, `data`. */
|
|
217
|
+
export function parseA2APart(value: unknown): A2APart {
|
|
218
|
+
if (!isRecord(value)) throw invalidParams("part must be an object");
|
|
219
|
+
const present = (["text", "raw", "url", "data"] as const).filter((key) => value[key] !== undefined);
|
|
220
|
+
if (present.length !== 1) throw invalidParams("part must hold exactly one of text, raw, url, data");
|
|
221
|
+
const mediaType = value.mediaType;
|
|
222
|
+
if (mediaType !== undefined && (typeof mediaType !== "string" || mediaType.length > 255))
|
|
223
|
+
throw invalidParams("part.mediaType is invalid");
|
|
224
|
+
const filename = value.filename;
|
|
225
|
+
if (filename !== undefined && (typeof filename !== "string" || filename.length > 255)) throw invalidParams("part.filename is invalid");
|
|
226
|
+
const common = {
|
|
227
|
+
...(typeof mediaType === "string" ? { mediaType } : {}),
|
|
228
|
+
...(typeof filename === "string" ? { filename } : {}),
|
|
229
|
+
};
|
|
230
|
+
if (value.text !== undefined) {
|
|
231
|
+
if (typeof value.text !== "string" || Buffer.byteLength(value.text) > MAX_TEXT_BYTES) throw invalidParams("part.text is invalid");
|
|
232
|
+
return { text: value.text, ...common };
|
|
233
|
+
}
|
|
234
|
+
if (value.raw !== undefined) {
|
|
235
|
+
if (typeof value.raw !== "string" || value.raw.length === 0 || value.raw.length % 4 !== 0 || !BASE64.test(value.raw)) {
|
|
236
|
+
throw invalidParams("part.raw must be base64");
|
|
237
|
+
}
|
|
238
|
+
return { raw: value.raw, ...common };
|
|
239
|
+
}
|
|
240
|
+
if (value.url !== undefined) {
|
|
241
|
+
if (typeof value.url !== "string") throw invalidParams("part.url is invalid");
|
|
242
|
+
return { url: value.url, ...common };
|
|
243
|
+
}
|
|
244
|
+
return { data: value.data as JsonValue, ...common };
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** The decisions a message carries through {@link PRISM_DECISIONS_EXTENSION}, or `undefined` when it carries none. */
|
|
248
|
+
/** `maxDecisions` is the agent's `ceilings.pendingDecisions` (default 128), so a raised ceiling can still be answered. */
|
|
249
|
+
export function readDecisions(
|
|
250
|
+
message: A2AMessage,
|
|
251
|
+
allowModifiedArguments: boolean,
|
|
252
|
+
maxDecisions = MAX_DECISIONS,
|
|
253
|
+
): readonly Decision[] | undefined {
|
|
254
|
+
if (!message.extensions?.includes(PRISM_DECISIONS_EXTENSION)) return undefined;
|
|
255
|
+
const parts = message.parts.filter((part) => isRecord(part.data) && "decisions" in part.data);
|
|
256
|
+
if (parts.length === 0) return undefined;
|
|
257
|
+
if (parts.length > 1) throw invalidParams("Only one decisions part is allowed");
|
|
258
|
+
const raw = (parts[0]?.data as Record<string, unknown> | undefined)?.decisions;
|
|
259
|
+
if (!Array.isArray(raw) || raw.length === 0 || raw.length > maxDecisions)
|
|
260
|
+
throw invalidParams("decisions must be a non-empty bounded array");
|
|
261
|
+
return raw.map((entry): Decision => {
|
|
262
|
+
if (!isRecord(entry)) throw invalidParams("decision must be an object");
|
|
263
|
+
for (const key of Object.keys(entry)) {
|
|
264
|
+
if (!["approvalId", "outcome", "reason", "elicitation", "modifiedArguments"].includes(key))
|
|
265
|
+
throw invalidParams(`decision.${key} is not allowed`);
|
|
266
|
+
}
|
|
267
|
+
if (typeof entry.approvalId !== "string" || entry.approvalId.length === 0 || entry.approvalId.length > 512) {
|
|
268
|
+
throw invalidParams("decision.approvalId is invalid");
|
|
269
|
+
}
|
|
270
|
+
if (typeof entry.outcome !== "string" || !OUTCOMES.has(entry.outcome)) throw invalidParams("decision.outcome is invalid");
|
|
271
|
+
if (entry.reason !== undefined && (typeof entry.reason !== "string" || Buffer.byteLength(entry.reason) > MAX_DECISION_REASON_BYTES)) {
|
|
272
|
+
throw invalidParams("decision.reason is invalid");
|
|
273
|
+
}
|
|
274
|
+
if (entry.elicitation !== undefined && !isRecord(entry.elicitation)) throw invalidParams("decision.elicitation must be an object");
|
|
275
|
+
if (entry.modifiedArguments !== undefined) {
|
|
276
|
+
if (!allowModifiedArguments) throw invalidParams("decision.modifiedArguments is not allowed");
|
|
277
|
+
if (!isRecord(entry.modifiedArguments)) throw invalidParams("decision.modifiedArguments must be an object");
|
|
278
|
+
}
|
|
279
|
+
return {
|
|
280
|
+
approvalId: entry.approvalId,
|
|
281
|
+
outcome: entry.outcome as ApprovalOutcome,
|
|
282
|
+
...(typeof entry.reason === "string" ? { reason: entry.reason } : {}),
|
|
283
|
+
...(isRecord(entry.elicitation) ? { elicitation: entry.elicitation as JsonObject } : {}),
|
|
284
|
+
...(isRecord(entry.modifiedArguments) ? { modifiedArguments: entry.modifiedArguments as JsonObject } : {}),
|
|
285
|
+
};
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Builds the `data` part a client sends to answer `TASK_STATE_INPUT_REQUIRED`. */
|
|
290
|
+
export function decisionsMessage(messageId: string, taskId: string, contextId: string, decisions: readonly Decision[]): A2AMessage {
|
|
291
|
+
return {
|
|
292
|
+
messageId,
|
|
293
|
+
role: "ROLE_USER",
|
|
294
|
+
taskId,
|
|
295
|
+
contextId,
|
|
296
|
+
extensions: [PRISM_DECISIONS_EXTENSION],
|
|
297
|
+
parts: [{ data: { decisions: decisions as unknown as JsonValue }, mediaType: "application/json" }],
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Maps inbound parts to a user `Message` within the model's declared input kinds. A `url` part is never
|
|
303
|
+
* fetched and, like a kind the model does not declare, fails with `-32005`.
|
|
304
|
+
*/
|
|
305
|
+
export function partsToMessage(parts: readonly A2APart[], declaredInput: readonly string[] | undefined): Message {
|
|
306
|
+
const declared = new Set(declaredInput ?? ["text"]);
|
|
307
|
+
const content: ContentBlock[] = [];
|
|
308
|
+
for (const part of parts) {
|
|
309
|
+
if (part.text !== undefined) {
|
|
310
|
+
content.push({ type: "text", text: part.text });
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
if (part.url !== undefined) throw new A2AError("contentTypeNotSupported", "URL parts are not supported");
|
|
314
|
+
if (part.data !== undefined) {
|
|
315
|
+
content.push({ type: "text", text: canonicalJson(part.data) });
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
const mediaType = (part.mediaType ?? "application/octet-stream").toLowerCase();
|
|
319
|
+
const name = part.filename;
|
|
320
|
+
const kind = mediaKind(mediaType);
|
|
321
|
+
if (kind === "image" && declared.has("image")) {
|
|
322
|
+
content.push({ type: "image", mimeType: mediaType, data: part.raw as string, ...(name ? { name } : {}) });
|
|
323
|
+
} else if (kind === "audio" && declared.has("audio")) {
|
|
324
|
+
content.push({ type: "audio", mediaType, data: part.raw as string, ...(name ? { name } : {}) });
|
|
325
|
+
} else if (kind === "document" && declared.has("document")) {
|
|
326
|
+
content.push({ type: "document", mediaType, data: part.raw as string, ...(name ? { name } : {}) });
|
|
327
|
+
} else if (kind !== "image" && kind !== "audio" && declared.has("file")) {
|
|
328
|
+
content.push({ type: "file", mediaType, data: part.raw as string, ...(name ? { name } : {}) });
|
|
329
|
+
} else {
|
|
330
|
+
throw new A2AError("contentTypeNotSupported", "The agent does not accept this media type");
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
return { role: "user", content };
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function mediaKind(mediaType: string): "image" | "audio" | "document" | "file" {
|
|
337
|
+
if (mediaType.startsWith("image/")) return "image";
|
|
338
|
+
if (mediaType.startsWith("audio/")) return "audio";
|
|
339
|
+
if (mediaType === "application/pdf" || mediaType.startsWith("text/")) return "document";
|
|
340
|
+
return "file";
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Text parts of a stored message, for `GetTask` history. Tool and system messages are not history. */
|
|
344
|
+
export function messageToA2A(message: Message, index: number, contextId: string, taskId: string): A2AMessage | undefined {
|
|
345
|
+
if (message.role !== "user" && message.role !== "assistant") return undefined;
|
|
346
|
+
const parts: A2APart[] = [];
|
|
347
|
+
for (const block of message.content) if (block.type === "text" && block.text.length > 0) parts.push({ text: block.text });
|
|
348
|
+
if (parts.length === 0) return undefined;
|
|
349
|
+
return {
|
|
350
|
+
messageId: message.id ?? `history-${index}`,
|
|
351
|
+
role: message.role === "user" ? "ROLE_USER" : "ROLE_AGENT",
|
|
352
|
+
contextId,
|
|
353
|
+
taskId,
|
|
354
|
+
parts,
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** One `data` item per pending decision: approval id, kind, tool name, and the (already redacted) reason. */
|
|
359
|
+
export function pendingParts(pending: readonly PendingDecision[]): A2APart[] {
|
|
360
|
+
return pending.map((decision) => ({
|
|
361
|
+
mediaType: "application/json",
|
|
362
|
+
data: {
|
|
363
|
+
approvalId: decision.approvalId,
|
|
364
|
+
kind: decision.kind,
|
|
365
|
+
...(decision.scope.toolName ? { toolName: decision.scope.toolName } : {}),
|
|
366
|
+
reason: decision.reason,
|
|
367
|
+
...(decision.elicitationSchema ? { elicitationSchema: decision.elicitationSchema } : {}),
|
|
368
|
+
},
|
|
369
|
+
}));
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
const TASK_STATES: ReadonlySet<string> = new Set([
|
|
373
|
+
"TASK_STATE_SUBMITTED",
|
|
374
|
+
"TASK_STATE_WORKING",
|
|
375
|
+
"TASK_STATE_INPUT_REQUIRED",
|
|
376
|
+
"TASK_STATE_AUTH_REQUIRED",
|
|
377
|
+
"TASK_STATE_COMPLETED",
|
|
378
|
+
"TASK_STATE_FAILED",
|
|
379
|
+
"TASK_STATE_CANCELED",
|
|
380
|
+
"TASK_STATE_REJECTED",
|
|
381
|
+
]);
|
|
382
|
+
const MAX_ARTIFACTS = 64;
|
|
383
|
+
|
|
384
|
+
function badResponse(message: string): A2AError {
|
|
385
|
+
return new A2AError("invalidAgentResponse", message);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** Re-labels a validation failure of a peer's payload as `-32006` InvalidAgentResponse. */
|
|
389
|
+
function asPeer<T>(read: () => T): T {
|
|
390
|
+
try {
|
|
391
|
+
return read();
|
|
392
|
+
} catch (error) {
|
|
393
|
+
if (error instanceof A2AError && error.errorName === "invalidParams") throw badResponse(`Invalid agent response: ${error.message}`);
|
|
394
|
+
throw error;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
function parseStatus(value: unknown, maxParts: number): A2ATaskStatus {
|
|
399
|
+
if (!isRecord(value) || typeof value.state !== "string" || !TASK_STATES.has(value.state))
|
|
400
|
+
throw badResponse("Invalid agent response: task status");
|
|
401
|
+
return {
|
|
402
|
+
state: value.state as A2ATaskState,
|
|
403
|
+
...(value.message === undefined || value.message === null
|
|
404
|
+
? {}
|
|
405
|
+
: { message: asPeer(() => parseA2AMessage(value.message, maxParts, "ROLE_AGENT")) }),
|
|
406
|
+
timestamp: typeof value.timestamp === "string" ? value.timestamp : "",
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function parseArtifact(value: unknown, maxParts: number): A2AArtifact {
|
|
411
|
+
if (!isRecord(value) || typeof value.artifactId !== "string" || value.artifactId.length > 256)
|
|
412
|
+
throw badResponse("Invalid agent response: artifact");
|
|
413
|
+
if (!Array.isArray(value.parts) || value.parts.length > maxParts) throw badResponse("Invalid agent response: artifact parts");
|
|
414
|
+
return {
|
|
415
|
+
artifactId: value.artifactId,
|
|
416
|
+
...(typeof value.name === "string" ? { name: value.name } : {}),
|
|
417
|
+
parts: asPeer(() => (value.parts as unknown[]).map(parseA2APart)),
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** Validates a peer's `Task` (`GetTask` result, or the `task` member of a send or stream response). History is dropped. */
|
|
422
|
+
export function parseA2ATask(value: unknown, maxParts: number): A2ATask {
|
|
423
|
+
if (!isRecord(value) || !isA2ATaskId(value.id) || !isA2AId(value.contextId)) throw badResponse("Invalid agent response: task");
|
|
424
|
+
const artifacts = value.artifacts;
|
|
425
|
+
if (artifacts !== undefined && (!Array.isArray(artifacts) || artifacts.length > MAX_ARTIFACTS))
|
|
426
|
+
throw badResponse("Invalid agent response: artifacts");
|
|
427
|
+
return {
|
|
428
|
+
id: value.id,
|
|
429
|
+
contextId: value.contextId,
|
|
430
|
+
status: parseStatus(value.status, maxParts),
|
|
431
|
+
...(Array.isArray(artifacts) ? { artifacts: artifacts.map((artifact) => parseArtifact(artifact, maxParts)) } : {}),
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** Validates one `SendMessage` result or stream frame: exactly one of `task`, `message`, `statusUpdate`, `artifactUpdate`. */
|
|
436
|
+
export function parseA2AStreamResponse(value: unknown, maxParts: number): A2AStreamResponse {
|
|
437
|
+
if (!isRecord(value)) throw badResponse("Invalid agent response");
|
|
438
|
+
const present = (["task", "message", "statusUpdate", "artifactUpdate"] as const).filter((key) => value[key] !== undefined);
|
|
439
|
+
if (present.length !== 1) throw badResponse("Invalid agent response: expected one of task, message, statusUpdate, artifactUpdate");
|
|
440
|
+
if (value.task !== undefined) return { task: parseA2ATask(value.task, maxParts) };
|
|
441
|
+
if (value.message !== undefined) return { message: asPeer(() => parseA2AMessage(value.message, maxParts, "ROLE_AGENT")) };
|
|
442
|
+
const update = (value.statusUpdate ?? value.artifactUpdate) as unknown;
|
|
443
|
+
if (!isRecord(update) || !isA2ATaskId(update.taskId) || !isA2AId(update.contextId)) throw badResponse("Invalid agent response: update");
|
|
444
|
+
if (value.statusUpdate !== undefined) {
|
|
445
|
+
return { statusUpdate: { taskId: update.taskId, contextId: update.contextId, status: parseStatus(update.status, maxParts) } };
|
|
446
|
+
}
|
|
447
|
+
return {
|
|
448
|
+
artifactUpdate: {
|
|
449
|
+
taskId: update.taskId,
|
|
450
|
+
contextId: update.contextId,
|
|
451
|
+
artifact: parseArtifact(update.artifact, maxParts),
|
|
452
|
+
...(typeof update.append === "boolean" ? { append: update.append } : {}),
|
|
453
|
+
...(typeof update.lastChunk === "boolean" ? { lastChunk: update.lastChunk } : {}),
|
|
454
|
+
},
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* The pending decisions a `TASK_STATE_INPUT_REQUIRED` status message lists (the `data` items {@link pendingParts}
|
|
460
|
+
* writes). Items that do not have that shape are skipped.
|
|
461
|
+
*/
|
|
462
|
+
export function readPendingParts(message: A2AMessage | undefined): PendingDecision[] {
|
|
463
|
+
const out: PendingDecision[] = [];
|
|
464
|
+
for (const part of message?.parts ?? []) {
|
|
465
|
+
const data = part.data;
|
|
466
|
+
if (!isRecord(data) || typeof data.approvalId !== "string" || data.approvalId.length === 0 || data.approvalId.length > 512) continue;
|
|
467
|
+
if (data.kind !== "tool_approval" && data.kind !== "elicitation") continue;
|
|
468
|
+
out.push({
|
|
469
|
+
approvalId: data.approvalId,
|
|
470
|
+
kind: data.kind,
|
|
471
|
+
scope: typeof data.toolName === "string" ? { toolName: data.toolName } : {},
|
|
472
|
+
reason: typeof data.reason === "string" ? data.reason.slice(0, MAX_DECISION_REASON_BYTES) : "",
|
|
473
|
+
...(isRecord(data.elicitationSchema) ? { elicitationSchema: data.elicitationSchema as JsonObject } : {}),
|
|
474
|
+
});
|
|
475
|
+
if (out.length >= MAX_DECISIONS) break;
|
|
476
|
+
}
|
|
477
|
+
return out;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/** Text of `text` parts, and canonical JSON of `data` parts, joined. */
|
|
481
|
+
export function partsText(parts: readonly A2APart[]): string {
|
|
482
|
+
return parts.map((part) => (part.text !== undefined ? part.text : part.data !== undefined ? canonicalJson(part.data) : "")).join("");
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
export function jsonRpcResult(id: JsonRpcId | null, result: unknown): string {
|
|
486
|
+
return JSON.stringify({ jsonrpc: "2.0", id, result });
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
export function jsonRpcError(id: JsonRpcId | null, error: A2AError): string {
|
|
490
|
+
return JSON.stringify({ jsonrpc: "2.0", id, error: { code: error.code, message: error.message } });
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/** RFC 8785 (JCS) canonical JSON: sorted keys by UTF-16 code unit, ECMAScript number and string forms. */
|
|
494
|
+
export function canonicalJson(value: unknown): string {
|
|
495
|
+
if (value === null || typeof value === "boolean" || typeof value === "string") return JSON.stringify(value);
|
|
496
|
+
if (typeof value === "number") {
|
|
497
|
+
if (!Number.isFinite(value)) throw invalidParams("Non-finite number");
|
|
498
|
+
return JSON.stringify(value);
|
|
499
|
+
}
|
|
500
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
501
|
+
if (isRecord(value)) {
|
|
502
|
+
return `{${Object.keys(value)
|
|
503
|
+
.filter((key) => value[key] !== undefined)
|
|
504
|
+
.sort()
|
|
505
|
+
.map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`)
|
|
506
|
+
.join(",")}}`;
|
|
507
|
+
}
|
|
508
|
+
throw invalidParams("Value is not JSON");
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/** Server-issued task id. It names the context and the run, so a suspended task can be found again after a restart. */
|
|
512
|
+
export function encodeTaskId(contextId: string, runId: string): string {
|
|
513
|
+
return `${Buffer.from(contextId).toString("base64url")}.${Buffer.from(runId).toString("base64url")}`;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
export function decodeTaskId(taskId: string): { readonly contextId: string; readonly runId: string } | undefined {
|
|
517
|
+
const [context, run, extra] = taskId.split(".");
|
|
518
|
+
if (!context || !run || extra !== undefined) return undefined;
|
|
519
|
+
const contextId = Buffer.from(context, "base64url").toString();
|
|
520
|
+
const runId = Buffer.from(run, "base64url").toString();
|
|
521
|
+
if (!isA2AId(contextId) || runId.length === 0 || runId.length > 256 || encodeTaskId(contextId, runId) !== taskId) return undefined;
|
|
522
|
+
return { contextId, runId };
|
|
523
|
+
}
|