@hosty-sdk/app 0.47.0 → 0.49.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.
@@ -0,0 +1,605 @@
1
+ import { AgentApiError, AGENT_EVENT_VERSION } from "./agent.js";
2
+ export const AGENT_COMMAND_MAX_BYTES = 1024 * 1024;
3
+ function fail(message, status = 400, code = "invalid_input") { throw new AgentApiError(code, message, status); }
4
+ const object = (value) => !!value && typeof value === "object" && !Array.isArray(value);
5
+ function shape(value, keys, label) {
6
+ if (!object(value) || Object.keys(value).some(key => !keys.includes(key)))
7
+ fail(`Invalid ${label}; unknown fields are not supported.`);
8
+ }
9
+ const bounded = (value, max = 256, empty = false) => typeof value === "string" && (empty || value.trim().length > 0) && Buffer.byteLength(value) <= max && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(value);
10
+ const opaque = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,256}$/.test(value);
11
+ const uuid = (value) => typeof value === "string" && /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(value);
12
+ const decimal = (value, zero = false) => typeof value === "string" && (zero ? /^(?:0|[1-9][0-9]{0,39})$/ : /^[1-9][0-9]{0,39}$/).test(value);
13
+ const digest = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
14
+ const integer = (value, min = 1, max = Number.MAX_SAFE_INTEGER) => Number.isSafeInteger(value) && Number(value) >= min && Number(value) <= max;
15
+ function array(value, max, label) { if (!Array.isArray(value) || value.length > max)
16
+ fail(`Invalid bounded ${label}.`); }
17
+ function strings(value, max = 128, width = 256) {
18
+ array(value, max, "string selection");
19
+ if (value.some(v => !bounded(v, width)) || new Set(value).size !== value.length)
20
+ fail("Selections require distinct bounded strings.");
21
+ }
22
+ function provider(value) {
23
+ shape(value, ["appId", "installationId", "key"], "provider reference");
24
+ if (![value.appId, value.installationId, value.key].every(v => bounded(v)))
25
+ fail("An installation-qualified provider reference is required.");
26
+ }
27
+ function qualified(value) { shape(value, ["provider", "id"], "qualified reference"); provider(value.provider); if (!opaque(value.id))
28
+ fail("A bounded resource ID is required."); }
29
+ function instructions(value) {
30
+ array(value, 16, "instructions");
31
+ const ids = new Set();
32
+ for (const item of value) {
33
+ shape(item, ["id", "text"], "instruction");
34
+ if (!bounded(item.id, 128) || !bounded(item.text, 256 * 1024, true) || ids.has(item.id))
35
+ fail("Instructions require distinct IDs and bounded text.");
36
+ ids.add(item.id);
37
+ }
38
+ }
39
+ const capabilityName = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)*$/;
40
+ function required(value) { if (value !== undefined) {
41
+ strings(value);
42
+ if (value.some(item => !capabilityName.test(item)))
43
+ fail("Use lowercase capability contract keys.");
44
+ } }
45
+ export function validateAgentMcpSelection(value) {
46
+ shape(value, ["targets", "connections"], "MCP selection");
47
+ if (value.targets !== undefined) {
48
+ array(value.targets, 16, "MCP targets");
49
+ const seen = new Set();
50
+ for (const item of value.targets) {
51
+ shape(item, ["target", "tools", "policy"], "MCP target selection");
52
+ if (!object(item.target))
53
+ fail("A logical MCP target is required.");
54
+ if (item.target.kind === "core")
55
+ shape(item.target, ["kind"], "Core MCP target");
56
+ else {
57
+ shape(item.target, ["kind", "appId", "installationId", "key"], "app MCP target");
58
+ if (item.target.kind !== "app")
59
+ fail("Unknown MCP target kind.");
60
+ provider({ appId: item.target.appId, installationId: item.target.installationId, key: item.target.key });
61
+ }
62
+ const key = item.target.kind === "core" ? "core" : JSON.stringify([item.target.appId, item.target.installationId, item.target.key]);
63
+ if (seen.has(key))
64
+ fail("Duplicate MCP target.");
65
+ seen.add(key);
66
+ if (item.tools !== undefined)
67
+ strings(item.tools, 512);
68
+ if (item.policy !== undefined) {
69
+ shape(item.policy, ["default", "autoAllowReadOnly", "tools"], "MCP execution policy");
70
+ if (!["ask", "run"].includes(String(item.policy.default)) || item.policy.autoAllowReadOnly !== undefined && typeof item.policy.autoAllowReadOnly !== "boolean")
71
+ fail("Invalid MCP execution policy.");
72
+ if (item.policy.tools !== undefined) {
73
+ if (!object(item.policy.tools) || Object.keys(item.policy.tools).length > 512)
74
+ fail("Invalid bounded tool policies.");
75
+ for (const [name, policy] of Object.entries(item.policy.tools)) {
76
+ shape(policy, ["mode", "definition"], "tool execution policy");
77
+ if (!bounded(name) || !["ask", "run", "disabled"].includes(String(policy.mode)) || (policy.mode === "run" ? !digest(policy.definition) : policy.definition !== undefined))
78
+ fail("Explicit run policy requires the exact tool definition digest.");
79
+ }
80
+ }
81
+ }
82
+ }
83
+ }
84
+ if (value.connections !== undefined) {
85
+ array(value.connections, 16, "external MCP connections");
86
+ const seen = new Set();
87
+ for (const connection of value.connections) {
88
+ shape(connection, ["id", "revision"], "external MCP connection");
89
+ if (!opaque(connection.id) || !decimal(connection.revision) || seen.has(connection.id))
90
+ fail("An exact external connection revision is required.");
91
+ seen.add(connection.id);
92
+ }
93
+ }
94
+ }
95
+ export function validateAgentConfiguration(value) {
96
+ shape(value, ["connection", "instructions", "systemPrompt", "skills", "nativeTools", "approvalMode", "predictions", "subagents"], "agent configuration");
97
+ shape(value.connection, ["id", "revision"], "connection");
98
+ if (!opaque(value.connection.id) || !decimal(value.connection.revision))
99
+ fail("An exact provider connection revision is required.");
100
+ if (value.instructions !== undefined)
101
+ instructions(value.instructions);
102
+ if (value.systemPrompt !== undefined) {
103
+ shape(value.systemPrompt, ["mode", "text"], "system prompt addition");
104
+ if (value.systemPrompt.mode !== "append" || !bounded(value.systemPrompt.text, 256 * 1024, true))
105
+ fail("Only a bounded append-mode system addition is supported.");
106
+ }
107
+ if (value.skills !== undefined) {
108
+ array(value.skills, 202, "skill selection");
109
+ const seen = new Set();
110
+ for (const item of value.skills) {
111
+ shape(item, ["skillId", "expectedDigest"], "skill reference");
112
+ if (!digest(item.skillId) || item.expectedDigest !== undefined && !digest(item.expectedDigest) || seen.has(item.skillId))
113
+ fail("Skills require distinct Core IDs and optional content digests.");
114
+ seen.add(item.skillId);
115
+ }
116
+ }
117
+ if (value.nativeTools !== undefined && !["provider_default", "none"].includes(String(value.nativeTools)))
118
+ fail("Unsupported native tool selection.");
119
+ if (value.approvalMode !== undefined && !["normal", "autonomous"].includes(String(value.approvalMode)))
120
+ fail("Unsupported approval mode.");
121
+ if (value.predictions !== undefined) {
122
+ shape(value.predictions, ["enabled"], "prediction configuration");
123
+ if (typeof value.predictions.enabled !== "boolean")
124
+ fail("Predictions require an explicit enabled flag.");
125
+ }
126
+ if (value.subagents !== undefined) {
127
+ shape(value.subagents, ["enabled", "maxConcurrency"], "native subagent selection");
128
+ if (typeof value.subagents.enabled !== "boolean" || value.subagents.maxConcurrency !== undefined && !integer(value.subagents.maxConcurrency, 1, 128))
129
+ fail("Invalid native subagent policy.");
130
+ }
131
+ }
132
+ export function validateAgentAttachmentChunk(value, index) {
133
+ shape(value, ["digest", "sizeBytes", "mediaType", "name", "count", "data"], "attachment chunk");
134
+ if (!digest(value.digest) || !integer(value.sizeBytes, 0, 25 * 1024 * 1024) || !bounded(value.mediaType, 128) || value.name !== undefined && !bounded(value.name)
135
+ || !integer(value.count, 1, 50) || value.count !== Math.max(1, Math.ceil(value.sizeBytes / (512 * 1024))) || typeof value.data !== "string"
136
+ || value.data.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(value.data))
137
+ fail("Invalid bounded attachment chunk.");
138
+ const bytes = Buffer.from(value.data, "base64");
139
+ if (bytes.byteLength > 512 * 1024 || bytes.toString("base64") !== value.data || index !== undefined && (!integer(index, 0, value.count - 1) || bytes.byteLength !== (index < value.count - 1 ? 512 * 1024 : value.sizeBytes - index * 512 * 1024)))
140
+ fail("Attachment chunk size/index does not match its immutable file.");
141
+ }
142
+ export function validateAgentSessionCreate(value) {
143
+ shape(value, ["configuration", "correlation", "requiredCapabilities"], "session creation");
144
+ validateAgentConfiguration(value.configuration);
145
+ required(value.requiredCapabilities);
146
+ if (value.correlation !== undefined) {
147
+ shape(value.correlation, ["conversation", "task"], "optional correlation");
148
+ if (value.correlation.conversation !== undefined)
149
+ qualified(value.correlation.conversation);
150
+ if (value.correlation.task !== undefined)
151
+ qualified(value.correlation.task);
152
+ }
153
+ }
154
+ export function validateAgentConfigurationCreate(value) {
155
+ shape(value, ["requestId", "expectedSessionRevision", "configuration", "requiredCapabilities"], "configuration change");
156
+ if (!uuid(value.requestId) || !decimal(value.expectedSessionRevision))
157
+ fail("A configuration change requires its stable UUID and expected session revision.");
158
+ validateAgentConfiguration(value.configuration);
159
+ required(value.requiredCapabilities);
160
+ }
161
+ export function validateAgentRunInput(value) {
162
+ shape(value, ["expectedSessionRevision", "configurationRevision", "continuation", "input", "context", "selection", "resources", "mcp", "requiredCapabilities", "limits"], "run input");
163
+ if (!decimal(value.expectedSessionRevision) || !decimal(value.configurationRevision) || !["start", "resume"].includes(String(value.continuation)))
164
+ fail("A run requires exact revisions and an explicit continuation mode.");
165
+ if (!object(value.input))
166
+ fail("Run input is required.");
167
+ if ("decisionResponseRef" in value.input) {
168
+ shape(value.input, ["decisionResponseRef"], "decision continuation input");
169
+ shape(value.input.decisionResponseRef, ["runId", "requestId"], "decision response reference");
170
+ if (value.continuation !== "resume" || !opaque(value.input.decisionResponseRef.runId) || !uuid(value.input.decisionResponseRef.requestId))
171
+ fail("A decision continuation requires the original response and resume mode.");
172
+ }
173
+ else {
174
+ shape(value.input, ["text", "attachments"], "new turn input");
175
+ if (!bounded(value.input.text, AGENT_COMMAND_MAX_BYTES))
176
+ fail("A nonempty bounded input is required.");
177
+ if (value.input.attachments !== undefined) {
178
+ array(value.input.attachments, 20, "attachments");
179
+ for (const item of value.input.attachments) {
180
+ shape(item, ["owner", "id", "digest", "sizeBytes", "mediaType", "name"], "immutable attachment reference");
181
+ provider(item.owner);
182
+ if (!opaque(item.id) || !digest(item.digest) || !integer(item.sizeBytes, 0) || !bounded(item.mediaType, 128) || item.name !== undefined && !bounded(item.name))
183
+ fail("An authorized immutable attachment reference is required.");
184
+ }
185
+ }
186
+ }
187
+ if (value.context !== undefined)
188
+ instructions(value.context);
189
+ if (value.selection !== undefined) {
190
+ shape(value.selection, ["model", "reasoningEffort"], "model selection");
191
+ if (![value.selection.model, value.selection.reasoningEffort].every(v => v === null || bounded(v)))
192
+ fail("Explicit model/effort values or null are required.");
193
+ }
194
+ if (value.resources !== undefined) {
195
+ array(value.resources, 16, "resource references");
196
+ for (const resource of value.resources) {
197
+ shape(resource, ["kind", "id", "revision", "provider"], "resource reference");
198
+ if (!bounded(resource.kind, 64) || !opaque(resource.id) || !bounded(resource.revision))
199
+ fail("A qualified revisioned context reference is required.");
200
+ if (resource.provider !== undefined)
201
+ provider(resource.provider);
202
+ }
203
+ }
204
+ if (value.mcp !== undefined)
205
+ validateAgentMcpSelection(value.mcp);
206
+ required(value.requiredCapabilities);
207
+ if (value.limits !== undefined) {
208
+ shape(value.limits, ["maxDurationMs", "maxOutputTokens", "maxToolCalls"], "execution limits");
209
+ if (Object.values(value.limits).some(v => !integer(v)))
210
+ fail("Execution limits must be positive safe integers.");
211
+ }
212
+ }
213
+ function controlBase(value) { if (!uuid(value.requestId) || !uuid(value.expectedGeneration) || !decimal(value.expectedRevision))
214
+ fail("Controls require a stable request UUID, exact attempt generation and revision."); }
215
+ export function validateAgentResponseInput(value) {
216
+ shape(value, ["requestId", "expectedGeneration", "expectedRevision", "decisionId", "decisionRevision", "response"], "pending response");
217
+ controlBase(value);
218
+ if (!opaque(value.decisionId) || !decimal(value.decisionRevision) || !object(value.response))
219
+ fail("Select one exact pending decision.");
220
+ decisionResponse(value.response);
221
+ }
222
+ function decisionResponse(value) {
223
+ if (!object(value))
224
+ fail("A decision response is required.");
225
+ if (value.kind === "approval") {
226
+ shape(value, ["kind", "decision", "message"], "approval response");
227
+ if (!["allow", "deny"].includes(String(value.decision)) || value.message !== undefined && !bounded(value.message, 65536, true))
228
+ fail("Invalid approval response.");
229
+ }
230
+ else {
231
+ shape(value, ["kind", "answers"], "question response");
232
+ if (value.kind !== "question" || !object(value.answers) || Object.keys(value.answers).length > 128)
233
+ fail("Answers must match bounded question IDs.");
234
+ for (const [id, answer] of Object.entries(value.answers)) {
235
+ if (!opaque(id))
236
+ fail("Invalid question ID.");
237
+ if (Array.isArray(answer)) {
238
+ if (answer.length > 128 || answer.some(v => !bounded(v, 65536, true)))
239
+ fail("Invalid question answers.");
240
+ }
241
+ else if (!bounded(answer, 65536, true))
242
+ fail("Invalid question answer.");
243
+ }
244
+ }
245
+ }
246
+ export function validateAgentCancelInput(value) {
247
+ shape(value, ["requestId", "expectedGeneration", "expectedRevision", "fenceIfNotAdmitted"], "cancellation");
248
+ if (!uuid(value.requestId))
249
+ fail("A cancellation request UUID is required.");
250
+ if (value.fenceIfNotAdmitted !== undefined) {
251
+ shape(value.fenceIfNotAdmitted, ["sessionId", "startDigest"], "delayed start fence");
252
+ if (!opaque(value.fenceIfNotAdmitted.sessionId) || !digest(value.fenceIfNotAdmitted.startDigest) || value.expectedRevision !== undefined || value.expectedGeneration !== undefined)
253
+ fail("A delayed-start fence requires only the exact intended session/digest.");
254
+ }
255
+ else
256
+ controlBase(value);
257
+ }
258
+ /** This validates an attestation's shape only. Providers must independently confirm actual native exit. */
259
+ export function validateAgentRunControlInput(value) {
260
+ if (!object(value))
261
+ fail("An execution control is required.");
262
+ const fields = { park: ["decisionId", "decisionRevision", "reason"], barrier: ["barrierId", "kind", "generation", "acknowledgedSequence", "snapshot"], reconcile: ["stopped", "evidence"], liveConfigure: ["mcp"], mcpPolicy: ["mcp"], predictions: ["enabled"] };
263
+ if (typeof value.command !== "string" || !fields[value.command])
264
+ fail("Unsupported execution control.", 422, "unsupported_capability");
265
+ shape(value, ["requestId", "expectedGeneration", "expectedRevision", "command", ...fields[value.command]], "execution control");
266
+ controlBase(value);
267
+ if (value.command === "park" && (!opaque(value.decisionId) || !decimal(value.decisionRevision) || value.reason !== undefined && !bounded(value.reason, 8192)))
268
+ fail("Parking requires the exact pending decision.");
269
+ if (value.command === "barrier" && (!opaque(value.barrierId) || !["task_adoption", "child_wait", "source_rebind", "limits", "human_input"].includes(String(value.kind)) || !decimal(value.generation) || !decimal(value.acknowledgedSequence, true) || value.snapshot !== undefined && !bounded(value.snapshot, 8192)))
270
+ fail("A barrier requires exact generation and acknowledged event sequence.");
271
+ if (value.command === "reconcile" && (value.stopped !== true || value.evidence !== undefined && !bounded(value.evidence, 8192)))
272
+ fail("Invalid stop-reconciliation attestation.");
273
+ if (value.command === "liveConfigure" || value.command === "mcpPolicy")
274
+ validateAgentMcpSelection(value.mcp);
275
+ if (value.command === "predictions" && typeof value.enabled !== "boolean")
276
+ fail("Invalid prediction control.");
277
+ }
278
+ /** Validate the actual relative path and bytes before Core introspection. Never trust body identity fields. */
279
+ export function validateAgentRequest(method, path, body, expectedOperation) {
280
+ if (!path.startsWith("/") || path.startsWith("//") || /[\\#\r\n]/.test(path) || /%(?:2f|5c|25)/i.test(path.split("?", 1)[0]))
281
+ fail("Use a declared relative agent route.");
282
+ if (Buffer.byteLength(body) > AGENT_COMMAND_MAX_BYTES)
283
+ fail("The command exceeds its byte allowance.", 413, "payload_budget");
284
+ const url = new URL(path, "http://agent.invalid"), route = url.pathname, query = {};
285
+ let operation, sessionId, runId, requestId, connectionId, attachmentId, chunkIndex;
286
+ const attachment = /^\/attachments\/([A-Za-z0-9_-]{1,256})\/chunks\/(0|[1-9][0-9]?)$/.exec(route);
287
+ const match = /^\/(sessions|runs|connections)(?:\/([A-Za-z0-9_-]{1,256}))?(?:\/(configurations|runs|events|responses|cancel|controls|models|usage))?(?:\/([A-Za-z0-9_-]{1,256}))?$/.exec(route);
288
+ if (route === "/capabilities" && method === "GET")
289
+ operation = "capabilities";
290
+ else if (attachment && method === "PUT") {
291
+ operation = "attachments.write";
292
+ attachmentId = attachment[1];
293
+ chunkIndex = Number(attachment[2]);
294
+ if (!uuid(attachmentId))
295
+ fail("An attachment upload UUID is required.");
296
+ }
297
+ else if (match) {
298
+ const [, root, id, sub, child] = match;
299
+ if (root === "sessions") {
300
+ sessionId = id;
301
+ if (!id && !sub && method === "GET")
302
+ operation = "sessions.list";
303
+ else if (id && !sub && method === "GET")
304
+ operation = "sessions.read";
305
+ else if (id && !sub && method === "PUT")
306
+ operation = "sessions.create";
307
+ else if (id && sub === "configurations" && child && method === "PUT") {
308
+ operation = "sessions.configure";
309
+ requestId = child;
310
+ }
311
+ else if (id && sub === "runs" && child && method === "PUT") {
312
+ operation = "runs.start";
313
+ runId = child;
314
+ }
315
+ }
316
+ else if (root === "runs" && id) {
317
+ runId = id;
318
+ if (!sub && method === "GET")
319
+ operation = "runs.read";
320
+ else if (sub === "events" && !child && method === "GET")
321
+ operation = "runs.events";
322
+ else if (sub === "responses" && !child && method === "POST")
323
+ operation = "runs.respond";
324
+ else if (sub === "cancel" && !child && method === "POST")
325
+ operation = "runs.cancel";
326
+ else if (sub === "controls" && !child && method === "POST")
327
+ operation = "runs.control";
328
+ else if (sub === "controls" && child && method === "GET") {
329
+ operation = "runs.controls.read";
330
+ requestId = child;
331
+ }
332
+ }
333
+ else if (root === "connections") {
334
+ connectionId = id;
335
+ if (!id && !sub && method === "GET")
336
+ operation = "connections.list";
337
+ else if (id && sub === "models" && !child && method === "GET")
338
+ operation = "connections.models";
339
+ else if (id && sub === "usage" && !child && method === "GET")
340
+ operation = "connections.usage";
341
+ }
342
+ }
343
+ if (!operation || expectedOperation !== undefined && expectedOperation !== operation)
344
+ fail("Use a declared agent v1 operation.", 422, "unsupported_operation");
345
+ const allowed = operation === "runs.events" ? ["after"] : ["sessions.list", "connections.list"].includes(operation) ? ["cursor", "limit"] : [];
346
+ for (const [key, value] of url.searchParams) {
347
+ if (!allowed.includes(key) || url.searchParams.getAll(key).length !== 1)
348
+ fail("Unsupported or repeated query field.");
349
+ if (key === "limit") {
350
+ if (!/^[1-9][0-9]*$/.test(value) || !integer(Number(value), 1, 100))
351
+ fail("Use a page limit between 1 and 100.");
352
+ query.limit = Number(value);
353
+ }
354
+ else {
355
+ if (!bounded(value, 8192) || /[\r\n]/.test(value))
356
+ fail("Invalid replay/page cursor.");
357
+ if (key === "after")
358
+ query.after = value;
359
+ else
360
+ query.cursor = value;
361
+ }
362
+ }
363
+ let input;
364
+ if (method === "GET") {
365
+ if (Buffer.byteLength(body))
366
+ fail("Agent reads have no command body.");
367
+ }
368
+ else {
369
+ try {
370
+ input = JSON.parse(typeof body === "string" ? body : new TextDecoder("utf-8", { fatal: true }).decode(body));
371
+ }
372
+ catch {
373
+ fail("A valid UTF-8 JSON command is required.");
374
+ }
375
+ if (["sessions.create", "sessions.configure", "runs.start"].includes(operation) && (!uuid(sessionId) || operation === "runs.start" && !uuid(runId)))
376
+ fail("Creation and submission IDs must be stable UUIDs.");
377
+ if (operation === "sessions.create")
378
+ validateAgentSessionCreate(input);
379
+ else if (operation === "sessions.configure") {
380
+ validateAgentConfigurationCreate(input);
381
+ if (input.requestId !== requestId)
382
+ fail("Configuration request ID must equal its path ID.");
383
+ }
384
+ else if (operation === "runs.start")
385
+ validateAgentRunInput(input);
386
+ else if (operation === "runs.respond")
387
+ validateAgentResponseInput(input);
388
+ else if (operation === "runs.cancel")
389
+ validateAgentCancelInput(input);
390
+ else if (operation === "runs.control")
391
+ validateAgentRunControlInput(input);
392
+ else if (operation === "attachments.write")
393
+ validateAgentAttachmentChunk(input, chunkIndex);
394
+ }
395
+ return { operation, method, path, input, sessionId, runId, requestId, connectionId, attachmentId, chunkIndex, query };
396
+ }
397
+ export function agentReplayCursor(after, lastEventId) {
398
+ if (after && lastEventId && after !== lastEventId)
399
+ fail("Conflicting replay cursors.");
400
+ const value = after || lastEventId || undefined;
401
+ if (value && (!bounded(value, 8192) || /[\r\n]/.test(value)))
402
+ fail("Invalid replay cursor.");
403
+ return value;
404
+ }
405
+ function responseProblem(message) { return fail(message, 502, "response_invalid"); }
406
+ function finiteJson(value, depth = 0, seen = new Set()) {
407
+ if (value === null || typeof value === "string" || typeof value === "boolean")
408
+ return true;
409
+ if (typeof value === "number")
410
+ return Number.isFinite(value);
411
+ if (typeof value !== "object" || depth > 64 || seen.has(value))
412
+ return false;
413
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)
414
+ return false;
415
+ seen.add(value);
416
+ const valid = (Array.isArray(value) ? value : Object.values(value)).every(item => finiteJson(item, depth + 1, seen));
417
+ seen.delete(value);
418
+ return valid;
419
+ }
420
+ function contextUsage(value) { return value === null || object(value) && finiteJson(value); }
421
+ function source(value) { if (!object(value) || !opaque(value.agentId) || value.parentAgentId !== undefined && !opaque(value.parentAgentId) || value.parentToolCallId !== undefined && (!opaque(value.parentToolCallId) || !opaque(value.parentAgentId)))
422
+ responseProblem("Invalid execution source."); }
423
+ export function validateAgentPendingDecision(value) {
424
+ if (!object(value) || !opaque(value.id) || !decimal(value.revision) || !["approval", "question"].includes(String(value.kind)) || !["continue_run", "next_turn"].includes(String(value.delivery)))
425
+ responseProblem("Invalid pending decision.");
426
+ if (value.source !== undefined)
427
+ source(value.source);
428
+ if (value.questions !== undefined) {
429
+ if (!Array.isArray(value.questions) || value.questions.length > 128)
430
+ responseProblem("Invalid question schema.");
431
+ for (const q of value.questions) {
432
+ if (!object(q) || !opaque(q.id) || !bounded(q.text, 65536) || q.options !== undefined && (!Array.isArray(q.options) || q.options.some(o => !object(o) || !opaque(o.id) || !bounded(o.label, 8192))))
433
+ responseProblem("Invalid question schema.");
434
+ }
435
+ }
436
+ }
437
+ export function validateAgentRunSnapshot(value) {
438
+ if (!object(value))
439
+ responseProblem("A run snapshot is required.");
440
+ qualified(value.ref);
441
+ if (!opaque(value.sessionId) || !uuid(value.generation) || !decimal(value.revision, true) || !decimal(value.configurationRevision) || !decimal(value.lastSequence, true)
442
+ || !["queued", "running", "waiting_for_input", "succeeded", "failed", "cancelled", "unknown"].includes(String(value.state))
443
+ || !["preparing", "executing", "waiting", "finalizing", "cancelling", "parked", "interrupted", "terminal"].includes(String(value.phase))
444
+ || typeof value.stopConfirmed !== "boolean" || !["current", "last_known", "unavailable"].includes(String(value.freshness)) || !bounded(value.observedAt) || !Number.isFinite(Date.parse(value.observedAt)) || !bounded(value.cursor, 8192)
445
+ || !Array.isArray(value.pending) || value.pending.length > 256 || !object(value.effects) || !["known", "unknown"].includes(String(value.effects.certainty)))
446
+ responseProblem("Invalid atomic run snapshot.");
447
+ for (const decision of value.pending)
448
+ validateAgentPendingDecision(decision);
449
+ strings(value.effects.unresolvedCallIds, 1024);
450
+ if (value.coverage !== undefined) {
451
+ shape(value.coverage, ["messages", "tools", "decisions"], "snapshot coverage");
452
+ if (![value.coverage.messages, value.coverage.tools].every(item => item === "complete" || item === "truncated") || value.coverage.decisions !== undefined && !["complete", "truncated"].includes(String(value.coverage.decisions)))
453
+ responseProblem("Invalid snapshot coverage.");
454
+ }
455
+ if (value.executionUsage !== undefined && (!object(value.executionUsage) || !decimal(value.executionUsage.sequence, true) || !integer(value.executionUsage.activeMs, 0) || typeof value.executionUsage.unknown !== "boolean"))
456
+ responseProblem("Invalid durable execution usage.");
457
+ if (value.latestContext !== undefined) {
458
+ const latest = value.latestContext;
459
+ if (!object(latest) || Object.keys(latest).some(key => !["sequence", "usage"].includes(key)) || !decimal(latest.sequence)
460
+ || BigInt(latest.sequence) > BigInt(value.lastSequence) || !Object.hasOwn(latest, "usage") || !contextUsage(latest.usage))
461
+ responseProblem("Invalid latest context observation or snapshot watermark.");
462
+ }
463
+ if (value.decisions !== undefined) {
464
+ array(value.decisions, 256, "decision history");
465
+ for (const item of value.decisions) {
466
+ if (!object(item) || !["pending", "resolved", "superseded", "unknown"].includes(String(item.state)))
467
+ responseProblem("Invalid retained decision state.");
468
+ validateAgentPendingDecision(item.decision);
469
+ if (item.response !== undefined) {
470
+ try {
471
+ decisionResponse(item.response);
472
+ }
473
+ catch {
474
+ responseProblem("Invalid retained decision response.");
475
+ }
476
+ }
477
+ }
478
+ }
479
+ if (value.pendingContinuations !== undefined) {
480
+ array(value.pendingContinuations, 256, "continuation references");
481
+ for (const item of value.pendingContinuations) {
482
+ if (!object(item) || !uuid(item.requestId) || !["pending", "awaiting_authorization", "admitted", "superseded"].includes(String(item.state)))
483
+ responseProblem("Invalid reserved continuation reference.");
484
+ qualified(item.run);
485
+ }
486
+ }
487
+ if (["succeeded", "failed", "cancelled"].includes(String(value.state)) && !value.stopConfirmed)
488
+ responseProblem("A final run requires confirmed native stop.");
489
+ if (value.messages !== undefined && (!Array.isArray(value.messages) || value.messages.length > 4096 || value.messages.some(m => !object(m) || !opaque(m.id) || typeof m.text !== "string")))
490
+ responseProblem("Invalid snapshot message identities.");
491
+ if (value.tools !== undefined && (!Array.isArray(value.tools) || value.tools.length > 4096 || value.tools.some(t => !object(t) || !opaque(t.id) || !bounded(t.name))))
492
+ responseProblem("Invalid snapshot tool identities.");
493
+ for (const message of (value.messages ?? [])) {
494
+ if (!["assistant", "user", "system"].includes(String(message.role)) || !["streaming", "complete", "interrupted"].includes(String(message.state)))
495
+ responseProblem("Invalid snapshot message state.");
496
+ if (message.source !== undefined)
497
+ source(message.source);
498
+ }
499
+ for (const tool of (value.tools ?? [])) {
500
+ if (!["running", "completed", "failed", "cancelled", "unknown"].includes(String(tool.state)))
501
+ responseProblem("Invalid snapshot tool state.");
502
+ if (tool.source !== undefined)
503
+ source(tool.source);
504
+ if (tool.command !== undefined) {
505
+ const command = tool.command;
506
+ if (!object(command) || !["completed", "failed", "cancelled", "unknown"].includes(String(command.status)) || command.exitCode !== undefined && !Number.isSafeInteger(command.exitCode) || command.durationMs !== undefined && !integer(command.durationMs, 0) || command.summary !== undefined && !bounded(command.summary, 65536, true))
507
+ responseProblem("Invalid retained command result.");
508
+ }
509
+ }
510
+ if (value.agents !== undefined) {
511
+ array(value.agents, 1024, "agent inventory");
512
+ for (const agent of value.agents) {
513
+ source(agent);
514
+ if (!object(agent) || !["queued", "running", "waiting_for_input", "succeeded", "failed", "cancelled", "unknown"].includes(String(agent.state)) || agent.stopConfirmed !== undefined && typeof agent.stopConfirmed !== "boolean")
515
+ responseProblem("Invalid retained child agent state.");
516
+ }
517
+ }
518
+ if (Buffer.byteLength(JSON.stringify(value)) > AGENT_COMMAND_MAX_BYTES)
519
+ responseProblem("Snapshot byte allowance exceeded.");
520
+ }
521
+ const eventTypes = ["run.updated", "session.bound", "selection.updated", "message.started", "message.delta", "message.completed", "tool.started", "tool.output", "tool.completed", "decision.requested", "decision.updated", "decision.resolved", "control.updated", "result.available", "usage.updated", "context.updated", "agent.updated", "warning", "extension"];
522
+ export function validateAgentEvent(value) {
523
+ if (!object(value) || value.schemaVersion !== AGENT_EVENT_VERSION || !opaque(value.runId) || !uuid(value.generation) || !decimal(value.sequence) || !decimal(value.revision, true)
524
+ || !bounded(value.occurredAt) || !Number.isFinite(Date.parse(value.occurredAt)) || !eventTypes.includes(String(value.type)) || !object(value.data))
525
+ responseProblem("Unsupported or invalid agent event envelope.");
526
+ source(value.source);
527
+ const data = value.data;
528
+ if (value.type === "run.updated") {
529
+ validateAgentRunSnapshot(data.snapshot);
530
+ if (data.snapshot.ref.id !== value.runId || data.snapshot.generation !== value.generation || data.snapshot.lastSequence !== value.sequence || data.snapshot.revision !== value.revision)
531
+ responseProblem("Run event snapshot does not match its atomic watermark.");
532
+ }
533
+ else if (String(value.type).startsWith("message.") && !opaque(data.messageId))
534
+ responseProblem("Message events require a stable message ID.");
535
+ else if (String(value.type).startsWith("tool.") && !opaque(data.toolCallId))
536
+ responseProblem("Tool events require a stable tool-call ID.");
537
+ else if (String(value.type).startsWith("decision.") && !opaque(data.decisionId))
538
+ responseProblem("Decision events require a stable decision ID.");
539
+ else if (value.type === "control.updated" && !uuid(data.requestId))
540
+ responseProblem("Control events require a stable request UUID.");
541
+ else if (value.type === "session.bound" && !opaque(data.sessionId))
542
+ responseProblem("Session events require a public session ID.");
543
+ else if (value.type === "context.updated" && (!Object.hasOwn(data, "usage") || !contextUsage(data.usage)))
544
+ responseProblem("Context events require nullable JSON observation data.");
545
+ else if (value.type === "extension" && (!bounded(data.namespace, 256) || data.required === true))
546
+ responseProblem("Extensions cannot carry required protocol semantics.");
547
+ if (data.decision !== undefined)
548
+ validateAgentPendingDecision(data.decision);
549
+ if (data.response !== undefined) {
550
+ try {
551
+ decisionResponse(data.response);
552
+ }
553
+ catch {
554
+ responseProblem("Invalid event decision response.");
555
+ }
556
+ }
557
+ if (value.type === "usage.updated" && data.execution !== undefined && (!object(data.execution) || !decimal(data.execution.sequence, true) || !integer(data.execution.activeMs, 0) || typeof data.execution.unknown !== "boolean"))
558
+ responseProblem("Invalid event execution usage.");
559
+ if (object(data.decision) && data.decision.id !== data.decisionId)
560
+ responseProblem("Decision event identity mismatch.");
561
+ if ((value.type === "message.delta" || value.type === "tool.output") && typeof (value.type === "message.delta" ? data.text : data.output) !== "string")
562
+ responseProblem("Streamed output requires bounded text.");
563
+ if (Buffer.byteLength(JSON.stringify(value)) > AGENT_COMMAND_MAX_BYTES)
564
+ responseProblem("Event byte allowance exceeded.");
565
+ }
566
+ export function validateAgentCapabilities(value) {
567
+ if (!object(value) || value.version !== 1 || !Array.isArray(value.eventVersions) || !value.eventVersions.includes(AGENT_EVENT_VERSION) || !object(value.limits) || !object(value.configuration))
568
+ responseProblem("Unsupported agent contract.");
569
+ strings(value.capabilities, 128);
570
+ strings(value.configuration.resumeCompatible, 32);
571
+ if (value.capabilities.some(item => !capabilityName.test(item)))
572
+ responseProblem("Invalid capability contract key.");
573
+ for (const key of ["maxCommandBytes", "maxEventBytes", "maxSnapshotBytes", "maxReplayBytes", "replayRetentionMs", "maxControls", "maxPageSize"])
574
+ if (!integer(value.limits[key]))
575
+ responseProblem("Invalid agent limits.");
576
+ }
577
+ export function validateAgentSession(value) {
578
+ if (!object(value))
579
+ responseProblem("A session is required.");
580
+ qualified(value.ref);
581
+ if (!decimal(value.revision) || !decimal(value.configurationRevision) || !digest(value.configurationDigest) || !["not_created", "available", "missing", "unavailable", "unknown"].includes(String(value.nativeState)) || !Array.isArray(value.resolvedSkills))
582
+ responseProblem("Invalid agent session.");
583
+ if (value.activeRun !== null)
584
+ qualified(value.activeRun);
585
+ for (const item of value.resolvedSkills)
586
+ if (!object(item) || !digest(item.skillId) || !digest(item.digest))
587
+ responseProblem("Invalid resolved skill digest.");
588
+ }
589
+ export function validateAgentControlReceipt(value) {
590
+ if (!object(value) || !uuid(value.requestId) || !["accepted", "applied", "rejected", "superseded", "unknown"].includes(String(value.state)) || !decimal(value.revision, true))
591
+ responseProblem("Invalid control receipt.");
592
+ qualified(value.run);
593
+ if (value.continuation !== undefined) {
594
+ if (!object(value.continuation) || !["pending", "awaiting_authorization", "admitted", "superseded"].includes(String(value.continuation.state)))
595
+ responseProblem("Invalid reserved continuation.");
596
+ qualified(value.continuation.run);
597
+ }
598
+ }
599
+ export function encodeAgentSseEvent(event, cursor) {
600
+ validateAgentEvent(event);
601
+ agentReplayCursor(cursor);
602
+ if (!cursor)
603
+ fail("A persisted replay cursor is required.");
604
+ return `id: ${cursor}\nevent: agent\ndata: ${JSON.stringify(event)}\n\n`;
605
+ }