@silverprotocol/core 0.1.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/src/agjson.ts ADDED
@@ -0,0 +1,1437 @@
1
+ import { z } from "zod";
2
+
3
+ // ─────────────────────────────────────────────────────────────────────────────
4
+ // AgJSON v1 — CORE + EXTENDED + ADVANCED profiles (spec §9). Input arms (§3) are
5
+ // added in a later TDD step. Authoritative schema: silverprotocol/SPEC.md.
6
+ // ─────────────────────────────────────────────────────────────────────────────
7
+
8
+ // Opaque JSON value (spec §0.1 "unknown" = any-JSON pass-through; NEVER `any`).
9
+ export type JsonValue = string | number | boolean | null | JsonValue[] | { [k: string]: JsonValue };
10
+ export const JsonValue: z.ZodType<JsonValue> = z.lazy(() =>
11
+ z.union([
12
+ z.string(),
13
+ z.number(),
14
+ z.boolean(),
15
+ z.null(),
16
+ z.array(JsonValue),
17
+ z.record(z.string(), JsonValue),
18
+ ]),
19
+ );
20
+
21
+ // Host-only namespaced side metadata (spec §0.4 `_meta`).
22
+ export const AgMeta = z.record(z.string(), JsonValue);
23
+ export type AgMeta = z.infer<typeof AgMeta>;
24
+
25
+ // Source union (spec §2): MCP base64 + the Anthropic/Gemini url/file superset.
26
+ export const AgSource = z.discriminatedUnion("type", [
27
+ z.object({ type: z.literal("base64"), mediaType: z.string(), data: z.string() }),
28
+ z.object({ type: z.literal("url"), url: z.string(), mediaType: z.string().optional() }),
29
+ z.object({ type: z.literal("file"), fileId: z.string(), mediaType: z.string().optional() }),
30
+ ]);
31
+ export type AgSource = z.infer<typeof AgSource>;
32
+
33
+ // Grounding-source payload union (spec §2/§4): the §4 `source` event's payload
34
+ // union, extracted here so it can be reused verbatim by BOTH the event arm and
35
+ // AgTurnRecord.sources[] — one definition, DRY, cast-free (audit M23).
36
+ export const AgSourcePayload = z.union([
37
+ AgSource,
38
+ z.object({ url: z.string(), title: z.string().optional() }),
39
+ z.object({
40
+ type: z.literal("document"),
41
+ mediaType: z.string().optional(),
42
+ title: z.string().optional(),
43
+ filename: z.string().optional(),
44
+ }),
45
+ ]);
46
+ export type AgSourcePayload = z.infer<typeof AgSourcePayload>;
47
+
48
+ // Finish-reason superset (spec §4).
49
+ export const AgFinishReason = z.enum([
50
+ "stop",
51
+ "token_limit",
52
+ "context_window_exceeded",
53
+ "tool_call",
54
+ "paused",
55
+ "pause_turn",
56
+ "refusal",
57
+ "safety_blocked",
58
+ "malformed_tool_call",
59
+ "unexpected_tool_call",
60
+ "rejected",
61
+ "other",
62
+ "unknown",
63
+ ]);
64
+ export type AgFinishReason = z.infer<typeof AgFinishReason>;
65
+
66
+ // Tool-result outcome (spec §2/§4): `denied` is its own outcome; `input_required` = MCP MRTR pause.
67
+ export const ToolOutcome = z.enum(["ok", "error", "denied", "input_required"]);
68
+ export type ToolOutcome = z.infer<typeof ToolOutcome>;
69
+
70
+ // ─── EXTENDED shared sub-types (spec §2 / §4) ────────────────────────────────
71
+
72
+ // Replay-load-bearing provider metadata (OpenAI itemId etc.). Spec §2 brands it
73
+ // nominally distinct from AgMeta; the brand is a compile-time-only phantom
74
+ // (`__brand`, never serialized — §0.4) so a provider-replay bag is never confused
75
+ // with host-only `_meta`. The provider-replay channel imposes NO key namespacing.
76
+ // Runtime validation == AgMeta; `.brand()` adds the zod-native nominal marker
77
+ // (the brand is type-level only, never on the wire).
78
+ export const AgProviderMeta = AgMeta.brand<"AgProviderMeta">();
79
+ export type AgProviderMeta = z.infer<typeof AgProviderMeta>;
80
+
81
+ // Opaque provider-bound reasoning blob (spec §2): signatures / encrypted /
82
+ // redacted reasoning, echoed back byte-identical or multi-turn reasoning breaks.
83
+ export const AgOpaqueKind = z.enum(["signature", "ciphertext", "encrypted", "redacted"]);
84
+ export type AgOpaqueKind = z.infer<typeof AgOpaqueKind>;
85
+ export const AgOpaque = z.object({
86
+ kind: AgOpaqueKind,
87
+ value: z.string(),
88
+ provider: z.string().optional(),
89
+ });
90
+ export type AgOpaque = z.infer<typeof AgOpaque>;
91
+
92
+ // MCP content-block annotations (MCP-frozen verbatim — spec §0.4 / §2). Carried
93
+ // through reduce() UNCHANGED.
94
+ export const AgAnnotations = z.object({
95
+ audience: z.array(z.enum(["user", "assistant"])).optional(),
96
+ priority: z.number().optional(),
97
+ lastModified: z.string().optional(),
98
+ });
99
+ export type AgAnnotations = z.infer<typeof AgAnnotations>;
100
+
101
+ // MCP embedded resource (spec §2). UI surfaces ride here (uri="ui://…").
102
+ export const AgEmbeddedResource = z.object({
103
+ uri: z.string(),
104
+ mimeType: z.string().optional(),
105
+ text: z.string().optional(),
106
+ blob: z.string().optional(),
107
+ _meta: AgMeta.optional(),
108
+ });
109
+ export type AgEmbeddedResource = z.infer<typeof AgEmbeddedResource>;
110
+
111
+ // Citation (spec §2): typed location union; index FRAME + UNIT explicit
112
+ // (Gemini grounding = UTF-8 BYTE offsets). Shared head + a kind-discriminated tail.
113
+ const AgCitationUnit = z.enum(["char", "byte", "utf16"]);
114
+ const AgCitationBounds = z.enum(["[start,end)", "[start,end]"]);
115
+ const citationHead = {
116
+ citedText: z.string(),
117
+ source: z.string().optional(),
118
+ title: z.string().optional(),
119
+ confidence: z.union([z.number(), z.array(z.number())]).optional(),
120
+ confidenceScores: z.array(z.number()).optional(),
121
+ encryptedIndex: z.string().optional(),
122
+ indexFrame: z.enum(["source", "response"]).optional(),
123
+ };
124
+ export const AgCitation = z.discriminatedUnion("kind", [
125
+ z.object({
126
+ ...citationHead,
127
+ kind: z.literal("char"),
128
+ documentIndex: z.number(),
129
+ startCharIndex: z.number(),
130
+ endCharIndex: z.number(),
131
+ unit: AgCitationUnit.optional(),
132
+ bounds: AgCitationBounds.optional(),
133
+ }),
134
+ z.object({
135
+ ...citationHead,
136
+ kind: z.literal("page"),
137
+ documentIndex: z.number(),
138
+ startPage: z.number(),
139
+ endPage: z.number(),
140
+ }),
141
+ z.object({
142
+ ...citationHead,
143
+ kind: z.literal("block"),
144
+ documentIndex: z.number(),
145
+ startBlockIndex: z.number(),
146
+ endBlockIndex: z.number(),
147
+ }),
148
+ z.object({
149
+ ...citationHead,
150
+ kind: z.literal("url"),
151
+ url: z.string(),
152
+ startIndex: z.number().optional(),
153
+ endIndex: z.number().optional(),
154
+ unit: AgCitationUnit.optional(),
155
+ bounds: AgCitationBounds.optional(),
156
+ }),
157
+ z.object({
158
+ ...citationHead,
159
+ kind: z.literal("offset"),
160
+ startIndex: z.number(),
161
+ endIndex: z.number(),
162
+ sourceIds: z.array(z.string()),
163
+ partIndex: z.number().optional(),
164
+ unit: AgCitationUnit,
165
+ bounds: AgCitationBounds,
166
+ }),
167
+ ]);
168
+ export type AgCitation = z.infer<typeof AgCitation>;
169
+
170
+ // Usage (spec §4). `cumulative:true` ⇒ must de-cumulate (Anthropic).
171
+ // Hand-written interface (required for self-recursive `byModel`; mirrors JsonValue / AgBlock pattern).
172
+ export interface AgUsage {
173
+ inputTokens?: number;
174
+ outputTokens?: number;
175
+ cacheReadTokens?: number;
176
+ cacheWriteTokens?: number;
177
+ reasoningTokens?: number;
178
+ toolUseInputTokens?: number;
179
+ totalTokens?: number;
180
+ costUsd?: number;
181
+ cumulative?: boolean;
182
+ byModel?: Record<string, AgUsage>; // per-model breakdown (self-recursive; A2-additive)
183
+ serverToolRequests?: number; // server-executed MCP tool-request count (A2-additive)
184
+ }
185
+ export const AgUsage: z.ZodType<AgUsage> = z.lazy(() =>
186
+ z.object({
187
+ inputTokens: z.number().optional(),
188
+ outputTokens: z.number().optional(),
189
+ cacheReadTokens: z.number().optional(),
190
+ cacheWriteTokens: z.number().optional(),
191
+ reasoningTokens: z.number().optional(),
192
+ toolUseInputTokens: z.number().optional(),
193
+ totalTokens: z.number().optional(),
194
+ costUsd: z.number().optional(),
195
+ cumulative: z.boolean().optional(),
196
+ byModel: z.record(z.string(), AgUsage).optional(),
197
+ serverToolRequests: z.number().optional(),
198
+ }),
199
+ );
200
+
201
+ // Safety signal (spec §4).
202
+ export const AgSafety = z.object({
203
+ category: z.string(),
204
+ score: z.number().optional(),
205
+ probability: z.string().optional(),
206
+ blocked: z.boolean().optional(),
207
+ });
208
+ export type AgSafety = z.infer<typeof AgSafety>;
209
+
210
+ // HITL choice / auth-config (spec §4 / §7). `AgChoice.value` is opaque.
211
+ export const AgChoice = z.object({
212
+ id: z.string(),
213
+ label: z.string(),
214
+ value: JsonValue.optional(),
215
+ });
216
+ export type AgChoice = z.infer<typeof AgChoice>;
217
+
218
+ export const AgAuthConfig = z.object({
219
+ scheme: z.string(),
220
+ scopes: z.array(z.string()).optional(),
221
+ authorizationUrl: z.string().optional(),
222
+ tokenUrl: z.string().optional(),
223
+ clientId: z.string().optional(),
224
+ audience: z.string().optional(),
225
+ });
226
+ export type AgAuthConfig = z.infer<typeof AgAuthConfig>;
227
+
228
+ // HITL ask kind enum (spec §4 / §7) — shared by hitl.ask and AgPausedAsk.
229
+ export const AgAskKind = z.enum(["approval", "form", "text", "choice", "auth", "url"]);
230
+ export type AgAskKind = z.infer<typeof AgAskKind>;
231
+
232
+ // A single paused ask entry (spec §4): shared between hitl.ask and
233
+ // AgOutcome.paused.asks[]. `schema` / `metadata.value` are opaque pass-through
234
+ // (LangGraph interrupt(value: Any) rides metadata, §7).
235
+ export const AgPausedAsk = z.object({
236
+ askId: z.string(),
237
+ kind: AgAskKind,
238
+ message: z.string().optional(),
239
+ toolCallId: z.string().optional(),
240
+ schema: JsonValue.optional(),
241
+ choices: z.array(AgChoice).optional(),
242
+ authConfig: AgAuthConfig.optional(),
243
+ url: z.string().optional(),
244
+ reason: z.string().optional(),
245
+ metadata: AgMeta.optional(),
246
+ requestState: z.string().optional(),
247
+ inputKey: z.string().optional(),
248
+ resumeBinding: z.enum(["id", "positional"]).optional(),
249
+ ordinal: z.number().optional(),
250
+ token: z.string().optional(),
251
+ expiresAt: z.string().optional(),
252
+ });
253
+ export type AgPausedAsk = z.infer<typeof AgPausedAsk>;
254
+
255
+ // HITL answer resume payload (spec §7), carried in AgInput.kind:"resume"
256
+ // answers[]. There is NO `hitl.answer` wire type — the answer flows INPUT-side.
257
+ export const AgHitlAnswer = z.object({
258
+ askId: z.string(),
259
+ status: z.enum(["resolved", "declined", "cancelled"]),
260
+ reply: JsonValue.optional(),
261
+ reason: z.string().optional(),
262
+ ordinal: z.number().optional(),
263
+ token: z.string().optional(),
264
+ requestState: z.string().optional(),
265
+ });
266
+ export type AgHitlAnswer = z.infer<typeof AgHitlAnswer>;
267
+
268
+ // MCP MRTR pending-input carrier (spec §2 / §7): rides `tool-result.pendingInput`
269
+ // (and `tool.done.pendingInput`) when `outcome==="input_required"`. `inputKeys`
270
+ // (plural) = the set of STILL-PENDING request keys (distinct from the singular
271
+ // `inputKey` an ask resolves — spec §7).
272
+ export const AgPendingInput = z.object({
273
+ requestState: z.string().optional(),
274
+ inputKeys: z.array(z.string()).optional(),
275
+ });
276
+ export type AgPendingInput = z.infer<typeof AgPendingInput>;
277
+
278
+ // AgBlock — the full object-form union (spec §2). The SAME union appears in
279
+ // both directions (input messages, output content, tool-result.content), so the
280
+ // `tool-result.content` arm is recursively `AgBlock[]` and the schema is `z.lazy`.
281
+ // CORE = text | image | tool-call | tool-result; EXTENDED adds reasoning,
282
+ // compaction, search-result, code, code-result, document, file, audio, data,
283
+ // provider-raw, resource, resource-link, plus citations on `text` (spec §9 —
284
+ // all 16 AgBlock kinds are CORE/EXTENDED; ADVANCED adds no additional kinds).
285
+ // Every EXTENDED arm carries the optional `annotations` / `_meta` side channels
286
+ // (and `providerMetadata` where the spec puts it).
287
+ type BlockMeta = {
288
+ providerMetadata?: AgProviderMeta;
289
+ annotations?: AgAnnotations;
290
+ _meta?: AgMeta;
291
+ };
292
+ export type AgBlock =
293
+ | ({ type: "text"; text: string; citations?: AgCitation[] } & BlockMeta)
294
+ | ({ type: "image"; source: AgSource } & BlockMeta)
295
+ | ({ type: "audio"; source: AgSource } & BlockMeta)
296
+ | ({ type: "file"; source: AgSource; filename?: string } & BlockMeta)
297
+ | ({ type: "document"; source: AgSource; title?: string } & BlockMeta)
298
+ | { type: "resource"; resource: AgEmbeddedResource; annotations?: AgAnnotations; _meta?: AgMeta }
299
+ | { type: "resource-link"; uri: string; mimeType?: string; annotations?: AgAnnotations; _meta?: AgMeta }
300
+ | { type: "code"; language: string; code: string; annotations?: AgAnnotations; _meta?: AgMeta }
301
+ | {
302
+ type: "code-result";
303
+ outcome: "ok" | "failed" | "deadline_exceeded";
304
+ output: string;
305
+ annotations?: AgAnnotations;
306
+ _meta?: AgMeta;
307
+ }
308
+ // ONE reasoning block (visible text + optional opaque provider-bound part).
309
+ // opaque/providerMetadata/itemId are REPLAY-LOAD-BEARING (round-trip byte-identical).
310
+ | ({
311
+ type: "reasoning";
312
+ text?: string;
313
+ opaque?: AgOpaque;
314
+ provider?: string;
315
+ providerDetails?: JsonValue;
316
+ itemId?: string;
317
+ } & BlockMeta)
318
+ // A provider-bound conversation summary (Pydantic CompactionPart); mirrors reasoning.
319
+ | { type: "compaction"; text?: string; opaque?: AgOpaque; provider?: string; annotations?: AgAnnotations; _meta?: AgMeta }
320
+ // A grounding/search result carrying an opaque per-result replay blob.
321
+ | {
322
+ type: "search-result";
323
+ url?: string;
324
+ title?: string;
325
+ opaque?: AgOpaque;
326
+ pageAge?: string;
327
+ annotations?: AgAnnotations;
328
+ _meta?: AgMeta;
329
+ }
330
+ | ({
331
+ type: "tool-call";
332
+ toolCallId: string;
333
+ name: string;
334
+ input: JsonValue;
335
+ serverName?: string;
336
+ providerExecuted?: boolean;
337
+ signature?: string; // Gemini thoughtSignature on the tool-call — echo or 400 (replay-load-bearing)
338
+ provider?: string;
339
+ title?: string; // provider/model-supplied tool title (Vercel)
340
+ toolMetadata?: AgMeta; // per-tool metadata bag (Vercel)
341
+ itemId?: string; // OpenAI Responses fc_ item id; DISTINCT from toolCallId (replay-load-bearing)
342
+ providerCallIndex?: number; // Gemini null-id parallel-call positional index (replay-load-bearing, §8)
343
+ uiVisibility?: ("model" | "app")[]; // MCP Apps access-control scope (from tool's _meta.ui.visibility)
344
+ } & BlockMeta)
345
+ | {
346
+ type: "tool-result";
347
+ toolCallId: string;
348
+ content: AgBlock[];
349
+ outcome?: ToolOutcome;
350
+ // ── ADVANCED tool-result channels (spec §2 / §2.1 / §9) — additive over CORE ──
351
+ structuredContent?: JsonValue; // MODEL-facing structured result (base MCP outputSchema; §2.1)
352
+ uiData?: JsonValue; // surface/view, MODEL-HIDDEN (MCP Apps structuredContent / OpenAI Apps component data; §2.1)
353
+ sideData?: JsonValue; // app-only side data (LangChain ToolMessage.artifact; §2.1)
354
+ errorText?: string; // free-form error message (Vercel tool-output-error); present iff outcome==="error"
355
+ errorCode?: string; // structured server-tool error code (Anthropic web_search_tool_result_error.error_code)
356
+ toolMetadata?: AgMeta; // per-tool metadata bag (Vercel)
357
+ dynamic?: boolean; // Vercel dynamic-vs-static tool distinction
358
+ pendingInput?: AgPendingInput; // MCP MRTR carrier when outcome==="input_required"
359
+ preliminary?: boolean; // set when the result is partial/kept-open (tool.done.more:true); cleared by the final tool.done (audit M20)
360
+ isError?: boolean; // MCP-frozen field, kept verbatim (derived: outcome==="error")
361
+ providerMetadata?: AgProviderMeta;
362
+ annotations?: AgAnnotations;
363
+ _meta?: AgMeta;
364
+ }
365
+ | { type: "data"; name: string; id?: string; data: JsonValue; transient?: boolean; annotations?: AgAnnotations; _meta?: AgMeta }
366
+ | { type: "provider-raw"; vendor: string; raw: JsonValue; annotations?: AgAnnotations; _meta?: AgMeta };
367
+
368
+ // Per-block optional side-channel fields, spread into each arm (spec §2).
369
+ const blockMeta = {
370
+ providerMetadata: AgProviderMeta.optional(),
371
+ annotations: AgAnnotations.optional(),
372
+ _meta: AgMeta.optional(),
373
+ };
374
+ // `resource` / `resource-link` / non-provider-bound blocks carry annotations + _meta
375
+ // only (no providerMetadata per spec §2).
376
+ const blockAnno = {
377
+ annotations: AgAnnotations.optional(),
378
+ _meta: AgMeta.optional(),
379
+ };
380
+
381
+ export const AgBlock: z.ZodType<AgBlock> = z.lazy(() =>
382
+ z.discriminatedUnion("type", [
383
+ z.object({
384
+ ...blockMeta,
385
+ type: z.literal("text"),
386
+ text: z.string(),
387
+ citations: z.array(AgCitation).optional(),
388
+ }),
389
+ z.object({ ...blockMeta, type: z.literal("image"), source: AgSource }),
390
+ z.object({ ...blockMeta, type: z.literal("audio"), source: AgSource }),
391
+ z.object({ ...blockMeta, type: z.literal("file"), source: AgSource, filename: z.string().optional() }),
392
+ z.object({ ...blockMeta, type: z.literal("document"), source: AgSource, title: z.string().optional() }),
393
+ z.object({ ...blockAnno, type: z.literal("resource"), resource: AgEmbeddedResource }),
394
+ z.object({ ...blockAnno, type: z.literal("resource-link"), uri: z.string(), mimeType: z.string().optional() }),
395
+ z.object({ ...blockAnno, type: z.literal("code"), language: z.string(), code: z.string() }),
396
+ z.object({
397
+ ...blockAnno,
398
+ type: z.literal("code-result"),
399
+ outcome: z.enum(["ok", "failed", "deadline_exceeded"]),
400
+ output: z.string(),
401
+ }),
402
+ z.object({
403
+ ...blockMeta,
404
+ type: z.literal("reasoning"),
405
+ text: z.string().optional(),
406
+ opaque: AgOpaque.optional(),
407
+ provider: z.string().optional(),
408
+ providerDetails: JsonValue.optional(),
409
+ itemId: z.string().optional(),
410
+ }),
411
+ z.object({
412
+ ...blockAnno,
413
+ type: z.literal("compaction"),
414
+ text: z.string().optional(),
415
+ opaque: AgOpaque.optional(),
416
+ provider: z.string().optional(),
417
+ }),
418
+ z.object({
419
+ ...blockAnno,
420
+ type: z.literal("search-result"),
421
+ url: z.string().optional(),
422
+ title: z.string().optional(),
423
+ opaque: AgOpaque.optional(),
424
+ pageAge: z.string().optional(),
425
+ }),
426
+ z.object({
427
+ ...blockMeta,
428
+ type: z.literal("tool-call"),
429
+ toolCallId: z.string(),
430
+ name: z.string(),
431
+ input: JsonValue,
432
+ serverName: z.string().optional(),
433
+ providerExecuted: z.boolean().optional(),
434
+ signature: z.string().optional(),
435
+ provider: z.string().optional(),
436
+ title: z.string().optional(),
437
+ toolMetadata: AgMeta.optional(),
438
+ itemId: z.string().optional(),
439
+ providerCallIndex: z.number().optional(),
440
+ uiVisibility: z.array(z.enum(["model", "app"])).optional(),
441
+ }),
442
+ z.object({
443
+ type: z.literal("tool-result"),
444
+ toolCallId: z.string(),
445
+ content: z.array(AgBlock),
446
+ outcome: ToolOutcome.optional(),
447
+ // ── ADVANCED tool-result channels (spec §2 / §2.1 / §9) — additive over CORE ──
448
+ structuredContent: JsonValue.optional(),
449
+ uiData: JsonValue.optional(),
450
+ sideData: JsonValue.optional(),
451
+ errorText: z.string().optional(),
452
+ errorCode: z.string().optional(),
453
+ toolMetadata: AgMeta.optional(),
454
+ dynamic: z.boolean().optional(),
455
+ pendingInput: AgPendingInput.optional(),
456
+ preliminary: z.boolean().optional(),
457
+ isError: z.boolean().optional(),
458
+ providerMetadata: AgProviderMeta.optional(),
459
+ annotations: AgAnnotations.optional(),
460
+ _meta: AgMeta.optional(),
461
+ }),
462
+ z.object({
463
+ ...blockAnno,
464
+ type: z.literal("data"),
465
+ name: z.string(),
466
+ id: z.string().optional(),
467
+ data: JsonValue,
468
+ transient: z.boolean().optional(),
469
+ }),
470
+ z.object({ ...blockAnno, type: z.literal("provider-raw"), vendor: z.string(), raw: JsonValue }),
471
+ ]),
472
+ );
473
+
474
+ // Outcome (spec §4). The within-run pause `{type:"paused", asks}` is the EXTENDED
475
+ // (HITL) arm: the turn parks on one or more asks; `result` MAY accompany a pause
476
+ // (a partial value emitted before parking). `{type:"aborted"}` is turn.abort's
477
+ // dedicated marker (symmetric with the error arm) — taskState is verbatim-A2A
478
+ // only and is NEVER reducer-invented (audit M29).
479
+ export const AgOutcome = z.discriminatedUnion("type", [
480
+ z.object({ type: z.literal("success"), result: JsonValue.optional() }),
481
+ z.object({ type: z.literal("error"), message: z.string(), code: z.string().optional() }),
482
+ z.object({ type: z.literal("rejected"), reason: z.string().optional() }),
483
+ z.object({ type: z.literal("aborted"), reason: z.string().optional() }),
484
+ z.object({ type: z.literal("paused"), asks: z.array(AgPausedAsk), result: JsonValue.optional() }),
485
+ ]);
486
+ export type AgOutcome = z.infer<typeof AgOutcome>;
487
+
488
+ export const AgRole = z.enum(["user", "assistant", "tool", "system"]);
489
+ export type AgRole = z.infer<typeof AgRole>;
490
+
491
+ // Sentinel for removing all messages in a turn (spec §4 message.remove / §5).
492
+ export const REMOVE_ALL = "*" as const;
493
+
494
+ // ─── ADVANCED helper types (spec §2 / §3 / §4 / §9) ──────────────────────────
495
+
496
+ // The unified message object (spec §3.2): one type, both directions. Input-only
497
+ // fields are optional. Carried by `messages.snapshot` and reconstructed into
498
+ // `AgReduceResult.messages` (§5). `messageMetadata` is an opaque app bag
499
+ // (Vercel usage accounting + the A2UI `a2uiClientDataModel` snapshot key, §11.1).
500
+ export const AgMessage = z.object({
501
+ id: z.string(),
502
+ role: AgRole,
503
+ content: z.array(AgBlock),
504
+ turnId: z.string().optional(),
505
+ threadId: z.string().optional(),
506
+ candidateIndex: z.number().optional(), // absent ⇒ candidate 0 (§5 partitioning)
507
+ referenceTurnIds: z.array(z.string()).optional(),
508
+ messageMetadata: JsonValue.optional(),
509
+ extensions: z.array(z.string()).optional(),
510
+ metadata: AgMeta.optional(),
511
+ agentId: z.string().optional(), // agent that produced this message (A2-additive)
512
+ agentName: z.string().optional(), // human-readable agent name (A2-additive)
513
+ agentRole: z.string().optional(), // role of the agent in the pipeline (A2-additive)
514
+ model: z.string().optional(), // model that produced this message (A2-additive)
515
+ usage: AgUsage.optional(), // per-message token usage (landed from message.end.usage; A2-additive)
516
+ });
517
+ export type AgMessage = z.infer<typeof AgMessage>;
518
+
519
+ // The A2A streamed-artifact ENTITY (spec §2 — the ONLY meaning of "artifact").
520
+ // Side-channel, NOT an AgBlock; reduce() lands these in
521
+ // `AgReduceResult.artifacts` (§5). `extensions` = foreign A2A active-extension URIs.
522
+ export const AgArtifact = z.object({
523
+ artifactId: z.string(),
524
+ turnId: z.string(),
525
+ threadId: z.string(),
526
+ name: z.string().optional(),
527
+ description: z.string().optional(),
528
+ parts: z.array(AgBlock),
529
+ extensions: z.array(z.string()).optional(),
530
+ _meta: AgMeta.optional(),
531
+ });
532
+ export type AgArtifact = z.infer<typeof AgArtifact>;
533
+
534
+ // Turn trigger descriptor (A2-additive; folded from turn.start.trigger onto AgTurnRecord.trigger).
535
+ export const AgTrigger = z.object({
536
+ kind: z.enum(["user", "resume", "schedule", "webhook", "email", "agent", "cron", "unknown"]),
537
+ ref: z.string().optional(),
538
+ });
539
+ export type AgTrigger = z.infer<typeof AgTrigger>;
540
+
541
+ // A folded handoff edge (spec §2 `AgTurnRecord.handoffs[]` / §4 handoff event).
542
+ export const AgHandoffRecord = z.object({
543
+ kind: z.enum(["transfer", "escalate"]).optional(),
544
+ fromAgentId: z.string().optional(),
545
+ toAgentId: z.string().optional(),
546
+ toAgentName: z.string().optional(),
547
+ });
548
+ export type AgHandoffRecord = z.infer<typeof AgHandoffRecord>;
549
+
550
+ // A ToS-must-render record (spec §2 `AgTurnRecord.displayRequired[]` / §4
551
+ // display.required event).
552
+ export const AgDisplayRequired = z.object({
553
+ provider: z.string(),
554
+ html: z.string(),
555
+ });
556
+ export type AgDisplayRequired = z.infer<typeof AgDisplayRequired>;
557
+
558
+ // Agent→client capabilities (spec §3 / §6 / §11.5) — the in-band other half of
559
+ // negotiation, an A2A AgentCard-compatible superset advertised on the first turn
560
+ // (carrier: the `agent.capabilities` event, §4). Defined here (before AgTurnRecord)
561
+ // so AgTurnRecord can reference it without z.lazy().
562
+ export const AgCapabilities = z.object({
563
+ streaming: z.object({ partialMessages: z.boolean().optional() }).optional(),
564
+ pushNotifications: z.boolean().optional(),
565
+ securitySchemes: z.array(AgAuthConfig).optional(),
566
+ extensions: z.array(z.string()).optional(), // foreign A2A active-extension URIs
567
+ uiCatalogs: z.array(z.string()).optional(),
568
+ profile: z.enum(["CORE", "EXTENDED", "ADVANCED"]).optional(),
569
+ });
570
+ export type AgCapabilities = z.infer<typeof AgCapabilities>;
571
+
572
+ // Per-turn folded record (spec §2): paused asks, prompt.blocked safety, handoffs,
573
+ // sources, lifecycle state. Part of AgReduceResult; restorable on snapshot resync (§5).
574
+ export const AgTurnRecord = z.object({
575
+ turnId: z.string(),
576
+ parentTurnId: z.string().optional(),
577
+ threadId: z.string(),
578
+ outcome: AgOutcome.optional(),
579
+ finishReason: AgFinishReason.optional(),
580
+ usage: AgUsage.optional(),
581
+ safety: z.array(AgSafety).optional(),
582
+ handoffs: z.array(AgHandoffRecord).optional(),
583
+ sourceIds: z.array(z.string()).optional(),
584
+ sources: z.array(z.object({
585
+ sourceId: z.string(),
586
+ source: AgSourcePayload, // the §4 source arm's payload union, landed verbatim (audit M23)
587
+ chunkIndex: z.number().optional(),
588
+ providerMetadata: AgProviderMeta.optional(),
589
+ })).optional(), // grounding sources folded from source events (audit M23); sourceIds stays as the derived index
590
+ promptBlocked: z.object({
591
+ reason: z.enum(["safety", "blocklist", "prohibited", "other"]), // mirrors the §4 prompt.blocked reason enum exactly
592
+ safety: z.array(AgSafety).optional(),
593
+ }).optional(), // audit M28
594
+ asks: z.array(AgPausedAsk).optional(),
595
+ taskState: z.string().optional(), // verbatim A2A TaskState (never reducer-invented — audit M29); no outcome-target mapping (A44)
596
+ displayRequired: z.array(AgDisplayRequired).optional(),
597
+ trigger: AgTrigger.optional(), // what triggered this turn (A2-additive)
598
+ guardrails: z.array(z.object({
599
+ target: z.enum(["input", "output", "tool"]),
600
+ passed: z.boolean(),
601
+ action: z.enum(["block", "retry", "rewrite", "override", "terminate"]).optional(),
602
+ reason: z.string().optional(),
603
+ guardrailName: z.string().optional(),
604
+ safety: z.array(AgSafety).optional(),
605
+ })).optional(), // guardrail evaluations folded from guardrail.result events (A2-additive)
606
+ capabilities: AgCapabilities.optional(), // agent's AgCapabilities folded from agent.capabilities (first-turn negotiation; spec §5)
607
+ });
608
+ export type AgTurnRecord = z.infer<typeof AgTurnRecord>;
609
+
610
+ // A folded memory write (spec §5) — the landing record for memory.write events,
611
+ // parallel to AgArtifact. Side-channel; NOT an AgBlock. scope="thread" records are
612
+ // bound to threadId and REPLACED by a messages.snapshot; scope="agent"/"user"/"skill"
613
+ // are a SEPARATE cross-thread persistence axis (durable, NOT bound by the §1.1 thread
614
+ // containment tree) and are untouched by a per-thread snapshot.
615
+ export const AgMemoryRecord = z.object({
616
+ scope: z.enum(["agent", "user", "skill", "thread"]),
617
+ key: z.string().optional(),
618
+ value: JsonValue, // required on the LANDED record (the fold seeds it)
619
+ reason: z.string().optional(),
620
+ durable: z.boolean().optional(),
621
+ turnId: z.string().optional(),
622
+ threadId: z.string().optional(),
623
+ });
624
+ export type AgMemoryRecord = z.infer<typeof AgMemoryRecord>;
625
+
626
+ // reduce() landing container (spec §2 / §5) — the well-typed return of the fold.
627
+ export const AgReduceResult = z.object({
628
+ messages: z.array(AgMessage),
629
+ artifacts: z.array(AgArtifact),
630
+ memory: z.array(AgMemoryRecord), // memory side-channel (parallel to artifacts; required)
631
+ turns: z.array(AgTurnRecord),
632
+ state: JsonValue.optional(), // shared-state working copy (opaque, §11.1)
633
+ });
634
+ export type AgReduceResult = z.infer<typeof AgReduceResult>;
635
+
636
+ // A client-advertised frontend tool (spec §3 `AgClientCapabilities.frontendTools[]`).
637
+ // `inputSchema` is an opaque JSON Schema (pass-through per §0.1).
638
+ export const AgFrontendTool = z.object({
639
+ name: z.string(),
640
+ description: z.string().optional(),
641
+ inputSchema: JsonValue,
642
+ });
643
+ export type AgFrontendTool = z.infer<typeof AgFrontendTool>;
644
+
645
+ // Client→agent capabilities (spec §3) — the inbound half of the in-band negotiation.
646
+ export const AgClientCapabilities = z.object({
647
+ frontendTools: z.array(AgFrontendTool).optional(),
648
+ hitl: z
649
+ .object({
650
+ ask: z.boolean().optional(),
651
+ approveWithEdits: z.boolean().optional(),
652
+ form: z.boolean().optional(),
653
+ auth: z.boolean().optional(),
654
+ })
655
+ .optional(),
656
+ streaming: z.object({ partialMessages: z.boolean().optional() }).optional(),
657
+ uiResources: z
658
+ .object({
659
+ catalogs: z.array(z.string()).optional(),
660
+ htmlResources: z.boolean().optional(),
661
+ })
662
+ .optional(),
663
+ state: z.object({ jsonPatch: z.boolean().optional() }).optional(),
664
+ });
665
+ export type AgClientCapabilities = z.infer<typeof AgClientCapabilities>;
666
+
667
+ // ─── INPUT (spec §3) ─────────────────────────────────────────────────────────
668
+
669
+ // Reasoning request knob (spec §3): neutral mapping over OpenAI o-series `effort`
670
+ // + Anthropic/Gemini thinking `budgetTokens`.
671
+ export const AgReasoningConfig = z.object({
672
+ mode: z.enum(["enabled", "disabled"]),
673
+ effort: z.enum(["minimal", "low", "medium", "high"]).optional(),
674
+ budgetTokens: z.number().optional(),
675
+ });
676
+ export type AgReasoningConfig = z.infer<typeof AgReasoningConfig>;
677
+
678
+ // A tool definition carried by `start.run.tools[]` (spec §3). `inputSchema` is an
679
+ // opaque JSON Schema (§0.1). `uiVisibility` = MCP Apps access-control scope
680
+ // (from the tool's `_meta.ui.visibility`): "model" = model-callable, "app" = app-only.
681
+ export const AgToolDef = z.object({
682
+ name: z.string(),
683
+ description: z.string().optional(),
684
+ inputSchema: JsonValue,
685
+ strict: z.boolean().optional(),
686
+ providerExecuted: z.boolean().optional(),
687
+ uiVisibility: z.array(z.enum(["model", "app"])).optional(),
688
+ source: z
689
+ .discriminatedUnion("type", [
690
+ z.object({ type: z.literal("mcp"), serverName: z.string() }),
691
+ z.object({ type: z.literal("function") }),
692
+ z.object({ type: z.literal("frontend") }),
693
+ ])
694
+ .optional(),
695
+ _meta: AgMeta.optional(),
696
+ });
697
+ export type AgToolDef = z.infer<typeof AgToolDef>;
698
+
699
+ // Run configuration carried by the `start` kind (spec §3). `system`/`context`
700
+ // revert faithfully to text or AgBlock[]; `responseFormat.schema` is opaque (§0.1).
701
+ export const AgRunConfig = z.object({
702
+ model: z.string().optional(),
703
+ system: z.union([z.string(), z.array(AgBlock)]).optional(),
704
+ tools: z.array(AgToolDef).optional(),
705
+ toolChoice: z
706
+ .union([
707
+ z.enum(["auto", "none", "required"]),
708
+ z.object({ type: z.literal("tool"), name: z.string() }),
709
+ ])
710
+ .optional(),
711
+ responseFormat: z
712
+ .object({
713
+ type: z.literal("json_schema"),
714
+ name: z.string().optional(),
715
+ schema: JsonValue,
716
+ strict: z.boolean().optional(),
717
+ })
718
+ .optional(),
719
+ reasoning: AgReasoningConfig.optional(),
720
+ maxTokens: z.number().optional(),
721
+ temperature: z.number().optional(),
722
+ topP: z.number().optional(),
723
+ stopSequences: z.array(z.string()).optional(),
724
+ context: z.array(AgBlock).optional(),
725
+ pushNotification: z
726
+ .object({
727
+ url: z.string(),
728
+ token: z.string().optional(),
729
+ auth: z.object({ scheme: z.string(), credentials: z.string().optional() }).optional(),
730
+ })
731
+ .optional(),
732
+ });
733
+ export type AgRunConfig = z.infer<typeof AgRunConfig>;
734
+
735
+ // The spec version this SDK implements (SPEC.md status line + §12). Consumers
736
+ // reject a MAJOR mismatch and accept any same-major version (§12 negotiation).
737
+ export const AGJSON_VERSION = "1.0.0-draft.1";
738
+
739
+ const agjsonWireVersion = z
740
+ .string()
741
+ .refine((v) => /^\d+\./.test(v) && v.split(".")[0] === AGJSON_VERSION.split(".")[0], {
742
+ message: `AgJSON major-version mismatch (this SDK implements ${AGJSON_VERSION})`,
743
+ });
744
+
745
+ // Shared envelope fields on EVERY AgInput variant (spec §3). `state` = shared-
746
+ // state echo (opaque, §11.1); `metadata` may carry namespaced runtime-replay
747
+ // handles (LangGraph `langgraph/threadId` / `langgraph/checkpointId`, A50).
748
+ export const AgInputEnvelope = z.object({
749
+ protocol: z.literal("agjson"),
750
+ version: agjsonWireVersion,
751
+ threadId: z.string(),
752
+ turnId: z.string(),
753
+ parentTurnId: z.string().optional(),
754
+ capabilities: AgClientCapabilities.optional(),
755
+ state: JsonValue.optional(),
756
+ metadata: AgMeta.optional(),
757
+ });
758
+ export type AgInputEnvelope = z.infer<typeof AgInputEnvelope>;
759
+ const inputEnvelope = {
760
+ protocol: z.literal("agjson"),
761
+ version: agjsonWireVersion,
762
+ threadId: z.string(),
763
+ turnId: z.string(),
764
+ parentTurnId: z.string().optional(),
765
+ capabilities: AgClientCapabilities.optional(),
766
+ state: JsonValue.optional(),
767
+ metadata: AgMeta.optional(),
768
+ };
769
+
770
+ // ─── SURFACE INTERACTION (spec §3 / §6 / §11.8 un-merge) ─────────────────────
771
+ // There is NO merged AgUiAction. A shared AgSurfaceEnvelope carries the
772
+ // correlation fields at the AgJSON layer (§1.3, §4 surface addressing) and five
773
+ // per-spec-faithful constructs (A2UI ×3, MCP Apps, OpenAI Apps) — each keeping
774
+ // its OWN frozen field names — form AgSurfaceInteraction.
775
+
776
+ // Shared correlation envelope for ALL surface interactions (spec §3).
777
+ export const AgSurfaceEnvelope = z.object({
778
+ surface: z.enum(["a2ui", "mcp-app", "openai-app"]),
779
+ surfaceId: z.string(),
780
+ toolCallId: z.string().optional(),
781
+ turnId: z.string().optional(),
782
+ threadId: z.string().optional(),
783
+ _meta: AgMeta.optional(),
784
+ });
785
+ export type AgSurfaceEnvelope = z.infer<typeof AgSurfaceEnvelope>;
786
+ // Envelope fields spread into each surface-interaction arm. The `surface`
787
+ // literal is overridden per-arm (the discriminant), so it is omitted here.
788
+ const surfaceEnvelope = {
789
+ surfaceId: z.string(),
790
+ toolCallId: z.string().optional(),
791
+ turnId: z.string().optional(),
792
+ threadId: z.string().optional(),
793
+ _meta: AgMeta.optional(),
794
+ };
795
+
796
+ // A2UI v1.0 client→server `action` (A2UI-frozen names VERBATIM, §0.4). `context`
797
+ // = the A2UI resolved data-bindings — the SOLE sanctioned Record<string, unknown>
798
+ // (map shape known: string keys; each value opaque per §0.1).
799
+ export const AgA2uiSurfaceAction = z.object({
800
+ ...surfaceEnvelope,
801
+ surface: z.literal("a2ui"),
802
+ a2uiMessage: z.literal("action"),
803
+ name: z.string(),
804
+ sourceComponentId: z.string(),
805
+ timestamp: z.string(),
806
+ context: z.record(z.string(), z.unknown()),
807
+ wantResponse: z.boolean().optional(),
808
+ actionId: z.string().optional(),
809
+ });
810
+ export type AgA2uiSurfaceAction = z.infer<typeof AgA2uiSurfaceAction>;
811
+
812
+ // A2UI v1.0 client→server `functionResponse` (inbound leg of the server
813
+ // callFunction RPC). `value` is the opaque return value (§0.1).
814
+ export const AgA2uiFunctionResponse = z.object({
815
+ ...surfaceEnvelope,
816
+ surface: z.literal("a2ui"),
817
+ a2uiMessage: z.literal("function-response"),
818
+ functionCallId: z.string(),
819
+ call: z.string(),
820
+ value: JsonValue,
821
+ });
822
+ export type AgA2uiFunctionResponse = z.infer<typeof AgA2uiFunctionResponse>;
823
+
824
+ // A2UI v1.0 client→server `error` (Generic Error, upstream-faithful): carries
825
+ // EXACTLY ONE of surfaceId (surface-scoped) | functionCallId (function-call
826
+ // failure). `path` = JSON-Pointer; REQUIRED when code === "VALIDATION_FAILED".
827
+ export const AgA2uiError = z
828
+ .object({
829
+ ...surfaceEnvelope,
830
+ surfaceId: z.string().optional(), // overrides the envelope: XOR with functionCallId
831
+ surface: z.literal("a2ui"),
832
+ a2uiMessage: z.literal("error"),
833
+ functionCallId: z.string().optional(),
834
+ code: z.string(),
835
+ message: z.string(),
836
+ path: z.string().optional(),
837
+ })
838
+ .superRefine((v, ctx) => {
839
+ if ((v.surfaceId === undefined) === (v.functionCallId === undefined)) {
840
+ ctx.addIssue({
841
+ code: "custom",
842
+ message:
843
+ "AgA2uiError carries exactly one of surfaceId | functionCallId (A2UI v1.0 Generic Error)",
844
+ path: ["surfaceId"],
845
+ });
846
+ }
847
+ if (v.code === "VALIDATION_FAILED" && v.path === undefined) {
848
+ ctx.addIssue({
849
+ code: "custom",
850
+ message: "VALIDATION_FAILED requires path (JSON-Pointer)",
851
+ path: ["path"],
852
+ });
853
+ }
854
+ });
855
+ export type AgA2uiError = z.infer<typeof AgA2uiError>;
856
+
857
+ // MCP Apps 2026-01-26 view→host RPCs (nested union on the verbatim JSON-RPC
858
+ // `method`). `content`/`structuredContent` kept VERBATIM (MCP-frozen, §0.4).
859
+ // ui/request-display-mode has NO modal mode (OpenAI-only).
860
+ // Core-MCP view→host plumbing (tools/call, resources/read, notifications/message) are host-mediated,
861
+ // never forwarded as AgMcpAppViewMessage; a view-initiated tools/call enters only as a client tool-result.
862
+ export const AgMcpAppViewMessage = z.discriminatedUnion("method", [
863
+ z.object({
864
+ ...surfaceEnvelope,
865
+ surface: z.literal("mcp-app"),
866
+ method: z.literal("ui/update-model-context"),
867
+ params: z.object({ content: z.array(AgBlock).optional(), structuredContent: JsonValue.optional() }),
868
+ }),
869
+ z.object({
870
+ ...surfaceEnvelope,
871
+ surface: z.literal("mcp-app"),
872
+ method: z.literal("ui/message"),
873
+ params: z.object({
874
+ role: z.literal("user"),
875
+ content: z.object({ type: z.literal("text"), text: z.string() }),
876
+ }),
877
+ }),
878
+ z.object({
879
+ ...surfaceEnvelope,
880
+ surface: z.literal("mcp-app"),
881
+ method: z.literal("ui/request-display-mode"),
882
+ params: z.object({ mode: z.enum(["inline", "fullscreen", "pip"]) }),
883
+ }),
884
+ z.object({
885
+ ...surfaceEnvelope,
886
+ surface: z.literal("mcp-app"),
887
+ method: z.literal("ui/open-link"),
888
+ params: z.object({ url: z.string() }),
889
+ }),
890
+ ]);
891
+ export type AgMcpAppViewMessage = z.infer<typeof AgMcpAppViewMessage>;
892
+
893
+ // OpenAI Apps SDK widget (window.openai) component→server RPCs (nested union on
894
+ // `method`). OpenAI-frozen names VERBATIM (§0.4). `callTool` is a SPEC-UNIQUE
895
+ // surface interaction, NOT the normalized tool-call. requestDisplayMode has NO
896
+ // modal mode. `toolResponseMetadata` is the OpenAI-only global echo (shared
897
+ // across all arms, so it is spread into each).
898
+ const openAiWidgetBase = {
899
+ ...surfaceEnvelope,
900
+ surface: z.literal("openai-app"),
901
+ toolResponseMetadata: JsonValue.optional(),
902
+ };
903
+ export const AgOpenAiWidgetAction = z.discriminatedUnion("method", [
904
+ z.object({ ...openAiWidgetBase, method: z.literal("setWidgetState"), widgetState: JsonValue }),
905
+ z.object({
906
+ ...openAiWidgetBase,
907
+ method: z.literal("callTool"),
908
+ name: z.string(),
909
+ args: JsonValue,
910
+ callId: z.string(),
911
+ }),
912
+ z.object({
913
+ ...openAiWidgetBase,
914
+ method: z.literal("sendFollowUpMessage"),
915
+ prompt: z.string(),
916
+ scrollToBottom: z.boolean().optional(),
917
+ }),
918
+ z.object({
919
+ ...openAiWidgetBase,
920
+ method: z.literal("requestDisplayMode"),
921
+ mode: z.enum(["inline", "pip", "fullscreen"]),
922
+ requestId: z.string(),
923
+ }),
924
+ ]);
925
+ export type AgOpenAiWidgetAction = z.infer<typeof AgOpenAiWidgetAction>;
926
+
927
+ // The surface-interaction union (spec §3 / §6). Element type of
928
+ // resume.uiActions[]. Discriminated on `surface`; the three A2UI legs narrow
929
+ // further on the inner `a2uiMessage` discriminant.
930
+ export const AgSurfaceInteraction = z.union([
931
+ AgA2uiSurfaceAction,
932
+ AgA2uiFunctionResponse,
933
+ AgA2uiError,
934
+ AgMcpAppViewMessage,
935
+ AgOpenAiWidgetAction,
936
+ ]);
937
+ export type AgSurfaceInteraction = z.infer<typeof AgSurfaceInteraction>;
938
+
939
+ // A single client-executed tool-result flowing back IN (spec §3 `tool-result`
940
+ // kind `results[]`). The INPUT-side counterpart of the tool-result block; carries
941
+ // the 4 channels (§2.1) + async flags (`willContinue`/`scheduling`).
942
+ export const AgInputToolResult = z.object({
943
+ toolCallId: z.string(),
944
+ content: z.array(AgBlock),
945
+ outcome: ToolOutcome.optional(),
946
+ structuredContent: JsonValue.optional(),
947
+ uiData: JsonValue.optional(),
948
+ sideData: JsonValue.optional(),
949
+ errorText: z.string().optional(),
950
+ errorCode: z.string().optional(),
951
+ providerMetadata: AgProviderMeta.optional(),
952
+ toolMetadata: AgMeta.optional(),
953
+ dynamic: z.boolean().optional(),
954
+ pendingInput: AgPendingInput.optional(),
955
+ isError: z.boolean().optional(),
956
+ willContinue: z.boolean().optional(),
957
+ scheduling: z.enum(["when_idle", "preempt", "silent"]).optional(),
958
+ annotations: AgAnnotations.optional(),
959
+ _meta: AgMeta.optional(),
960
+ });
961
+ export type AgInputToolResult = z.infer<typeof AgInputToolResult>;
962
+
963
+ // AgInput — the input envelope (spec §3): a discriminated union on `kind`
964
+ // (start | resume | tool-result) over the shared AgInputEnvelope.
965
+ export const AgInput = z.discriminatedUnion("kind", [
966
+ z.object({
967
+ ...inputEnvelope,
968
+ kind: z.literal("start"),
969
+ messages: z.array(AgMessage),
970
+ run: AgRunConfig.optional(),
971
+ }),
972
+ z.object({
973
+ ...inputEnvelope,
974
+ kind: z.literal("resume"),
975
+ answers: z.array(AgHitlAnswer).optional(),
976
+ uiActions: z.array(AgSurfaceInteraction).optional(),
977
+ }),
978
+ z.object({
979
+ ...inputEnvelope,
980
+ kind: z.literal("tool-result"),
981
+ results: z.array(AgInputToolResult),
982
+ }),
983
+ ]);
984
+ export type AgInput = z.infer<typeof AgInput>;
985
+
986
+ // Surface display-mode enum (spec §4 `ui.display-mode`). Upstream OpenAI Apps
987
+ // DisplayMode = pip | inline | fullscreen; MCP Apps ui/request-display-mode has
988
+ // the same set. There is NO modal display mode (OpenAI's modal is the separate
989
+ // requestModal API, not carried here).
990
+ export const AgDisplayMode = z.enum(["inline", "pip", "fullscreen"]);
991
+ export type AgDisplayMode = z.infer<typeof AgDisplayMode>;
992
+
993
+ // Surface-RPC error (spec §4 `ui.result` / `ui.action-result`): `path` =
994
+ // JSON-Pointer for an A2UI VALIDATION_FAILED reciprocal rejection.
995
+ export const AgSurfaceError = z.object({
996
+ code: z.string(),
997
+ message: z.string(),
998
+ path: z.string().optional(),
999
+ });
1000
+ export type AgSurfaceError = z.infer<typeof AgSurfaceError>;
1001
+
1002
+ // Event base (spec §4): `seq` = global monotonic ordinal; `turnId` names the owning turn;
1003
+ // `messageId` (when present) names the open message the event attaches to.
1004
+ // Spread FIRST in each arm so an arm's required field overrides the optional base field.
1005
+ const base = {
1006
+ seq: z.number(),
1007
+ id: z.string().optional(),
1008
+ turnId: z.string().optional(),
1009
+ messageId: z.string().optional(),
1010
+ parentId: z.string().optional(),
1011
+ _meta: AgMeta.optional(),
1012
+ };
1013
+
1014
+ // AgEvent — the CLOSED discriminated union of all dotted/bare-noun event types
1015
+ // (CORE + EXTENDED + ADVANCED, spec §9). The open `ext.<vendor>.<key>` vendor
1016
+ // extension (§4/§12) CANNOT live in a discriminatedUnion (its `type` is an open
1017
+ // template-literal, not a fixed literal), so it is a sibling `AgExtEvent` joined
1018
+ // via `.or()` below. Kept as a named const for clarity.
1019
+ export const AgClosedEvent = z.discriminatedUnion("type", [
1020
+ z.object({ ...base, type: z.literal("turn.start"), threadId: z.string(), turnId: z.string(), trigger: AgTrigger.optional() }),
1021
+ z.object({
1022
+ ...base,
1023
+ type: z.literal("turn.done"),
1024
+ turnId: z.string(),
1025
+ outcome: AgOutcome,
1026
+ finishReason: AgFinishReason,
1027
+ usage: AgUsage.optional(), // EXTENDED — per-turn usage (spec §4)
1028
+ safety: z.array(AgSafety).optional(), // EXTENDED — safety signals (spec §4)
1029
+ messageId: z.string().optional(),
1030
+ messageMetadata: JsonValue.optional(), // Vercel usage accounting / A2UI snapshot (§4 / §11.1)
1031
+ taskState: z.string().optional(), // verbatim A2A TaskState with no outcome target (§2)
1032
+ }),
1033
+ z.object({
1034
+ ...base,
1035
+ type: z.literal("turn.error"),
1036
+ message: z.string(),
1037
+ code: z.string().optional(),
1038
+ retriable: z.boolean().optional(),
1039
+ usage: AgUsage.optional(), // EXTENDED — accrued usage on an interrupted turn (A1)
1040
+ }),
1041
+ z.object({ ...base, type: z.literal("turn.abort"), reason: z.string().optional() }),
1042
+ z.object({
1043
+ ...base,
1044
+ type: z.literal("error"),
1045
+ message: z.string(),
1046
+ code: z.string().optional(),
1047
+ retriable: z.boolean().optional(),
1048
+ }), // non-terminal advisory (spec §0.3 bare-noun event)
1049
+ z.object({
1050
+ ...base,
1051
+ type: z.literal("message.start"),
1052
+ id: z.string(),
1053
+ role: AgRole,
1054
+ turnId: z.string(),
1055
+ threadId: z.string(),
1056
+ stepId: z.string().optional(),
1057
+ extensions: z.array(z.string()).optional(), // foreign A2A active-extension URIs (§0.5)
1058
+ candidateIndex: z.number().optional(), // absent ⇒ candidate 0 (§5 partitioning)
1059
+ agentId: z.string().optional(), // agent that produced this message (A2-additive)
1060
+ agentName: z.string().optional(), // human-readable agent name (A2-additive)
1061
+ agentRole: z.string().optional(), // role of the agent in the pipeline (A2-additive)
1062
+ model: z.string().optional(), // model that produced this message (A2-additive)
1063
+ }),
1064
+ z.object({ ...base, type: z.literal("message.end"), id: z.string(), usage: AgUsage.optional() }), // usage = per-message token carrier (review #4)
1065
+ z.object({
1066
+ ...base,
1067
+ type: z.literal("text.start"),
1068
+ id: z.string(),
1069
+ role: z.literal("assistant").optional(),
1070
+ index: z.number().optional(),
1071
+ previousPartKind: z.string().optional(),
1072
+ providerMetadata: AgProviderMeta.optional(),
1073
+ candidateIndex: z.number().optional(), // absent ⇒ candidate 0 (§5 partitioning)
1074
+ }),
1075
+ z.object({
1076
+ ...base,
1077
+ type: z.literal("text.delta"),
1078
+ id: z.string(),
1079
+ delta: z.string(),
1080
+ providerMetadata: AgProviderMeta.optional(),
1081
+ }),
1082
+ z.object({
1083
+ ...base,
1084
+ type: z.literal("text.end"),
1085
+ id: z.string(),
1086
+ providerMetadata: AgProviderMeta.optional(),
1087
+ // STREAMED-text citations carrier (audit M22): citations for a streamed text
1088
+ // block arrive here (not as a duplicate id-less supplement block) and attach
1089
+ // to the sealed block named by `id` (spec §5 text.end row).
1090
+ citations: z.array(AgCitation).optional(),
1091
+ }),
1092
+ z.object({
1093
+ ...base,
1094
+ type: z.literal("content.block"),
1095
+ block: AgBlock,
1096
+ transient: z.boolean().optional(),
1097
+ candidateIndex: z.number().optional(), // absent ⇒ candidate 0 (§5 partitioning)
1098
+ }),
1099
+ z.object({
1100
+ ...base,
1101
+ type: z.literal("tool.start"),
1102
+ toolCallId: z.string(),
1103
+ name: z.string(),
1104
+ index: z.number().optional(),
1105
+ dynamic: z.boolean().optional(),
1106
+ serverName: z.string().optional(),
1107
+ providerExecuted: z.boolean().optional(),
1108
+ requiresApproval: z.boolean().optional(),
1109
+ title: z.string().optional(),
1110
+ toolMetadata: AgMeta.optional(),
1111
+ uiVisibility: z.array(z.enum(["model", "app"])).optional(),
1112
+ itemId: z.string().optional(),
1113
+ providerMetadata: AgProviderMeta.optional(),
1114
+ candidateIndex: z.number().optional(), // absent ⇒ candidate 0 (§5 partitioning)
1115
+ longRunning: z.boolean().optional(), // hint: this tool call may take a long time (A2-additive)
1116
+ }),
1117
+ z.object({
1118
+ ...base,
1119
+ type: z.literal("tool.args.delta"),
1120
+ toolCallId: z.string(),
1121
+ delta: z.string(),
1122
+ }),
1123
+ z.object({
1124
+ ...base,
1125
+ type: z.literal("tool.args.assembled"),
1126
+ toolCallId: z.string(),
1127
+ input: JsonValue,
1128
+ signature: z.string().optional(), // Gemini tool-call signature rides here (replay-load-bearing)
1129
+ title: z.string().optional(),
1130
+ toolMetadata: AgMeta.optional(),
1131
+ providerMetadata: AgProviderMeta.optional(),
1132
+ }),
1133
+ z.object({
1134
+ ...base,
1135
+ type: z.literal("tool.done"),
1136
+ toolCallId: z.string(),
1137
+ messageId: z.string().optional(),
1138
+ content: z.array(AgBlock),
1139
+ outcome: ToolOutcome.optional(),
1140
+ isError: z.boolean().optional(),
1141
+ // ── ADVANCED tool-result channels (spec §2.1 / §4 / §9) — additive over CORE ──
1142
+ structuredContent: JsonValue.optional(),
1143
+ uiData: JsonValue.optional(),
1144
+ sideData: JsonValue.optional(),
1145
+ errorText: z.string().optional(),
1146
+ errorCode: z.string().optional(),
1147
+ providerMetadata: AgProviderMeta.optional(),
1148
+ toolMetadata: AgMeta.optional(),
1149
+ dynamic: z.boolean().optional(),
1150
+ pendingInput: AgPendingInput.optional(),
1151
+ skipSummarization: z.boolean().optional(), // output-only async flag (§2.2)
1152
+ more: z.boolean().optional(), // output-only async flag — more:true SETS preliminary (§2.2)
1153
+ preliminary: z.boolean().optional(), // vestigial; unread by reduce() — the block flag derives from `more` (§2.2)
1154
+ candidateIndex: z.number().optional(), // absent ⇒ candidate 0 (§5 partitioning)
1155
+ }),
1156
+
1157
+ // ─── EXTENDED events (spec §4 / §9) ────────────────────────────────────────
1158
+ // ── REASONING ──
1159
+ z.object({
1160
+ ...base,
1161
+ type: z.literal("reasoning.start"),
1162
+ id: z.string(),
1163
+ mode: z.enum(["summarized", "full"]).optional(),
1164
+ partIndex: z.number().optional(),
1165
+ previousPartKind: z.string().optional(),
1166
+ providerMetadata: AgProviderMeta.optional(),
1167
+ itemId: z.string().optional(),
1168
+ candidateIndex: z.number().optional(), // absent ⇒ candidate 0 (§5 partitioning)
1169
+ }),
1170
+ z.object({
1171
+ ...base,
1172
+ type: z.literal("reasoning.delta"),
1173
+ id: z.string(),
1174
+ delta: z.string(),
1175
+ partIndex: z.number().optional(),
1176
+ providerMetadata: AgProviderMeta.optional(),
1177
+ }),
1178
+ z.object({
1179
+ ...base,
1180
+ type: z.literal("reasoning.end"),
1181
+ id: z.string(),
1182
+ provider: z.string().optional(),
1183
+ providerMetadata: AgProviderMeta.optional(),
1184
+ }),
1185
+ // REPLACE — sets `opaque` on the reasoning block named by `id` (replay-load-bearing).
1186
+ z.object({
1187
+ ...base,
1188
+ type: z.literal("reasoning.opaque"),
1189
+ id: z.string(),
1190
+ kind: AgOpaqueKind,
1191
+ value: z.string(),
1192
+ provider: z.string().optional(),
1193
+ itemId: z.string().optional(),
1194
+ }),
1195
+ // APPENDS to a per-id signature scratch buffer (Pydantic signature_delta).
1196
+ z.object({ ...base, type: z.literal("reasoning.opaque.delta"), id: z.string(), delta: z.string() }),
1197
+ // ── STEP ──
1198
+ z.object({
1199
+ ...base,
1200
+ type: z.literal("step.start"),
1201
+ id: z.string(),
1202
+ stepName: z.string().optional(),
1203
+ turnId: z.string().optional(),
1204
+ }),
1205
+ z.object({
1206
+ ...base,
1207
+ type: z.literal("step.done"),
1208
+ id: z.string(),
1209
+ stepName: z.string().optional(),
1210
+ usage: AgUsage.optional(),
1211
+ }),
1212
+ // ── SUBAGENT / HANDOFF ── (subagent.start is the SOLE nested-turn opener)
1213
+ z.object({
1214
+ ...base,
1215
+ type: z.literal("subagent.start"),
1216
+ turnId: z.string(),
1217
+ parentTurnId: z.string(),
1218
+ agentId: z.string().optional(),
1219
+ agentName: z.string().optional(),
1220
+ }),
1221
+ z.object({ ...base, type: z.literal("subagent.done"), turnId: z.string(), parentTurnId: z.string() }),
1222
+ z.object({
1223
+ ...base,
1224
+ type: z.literal("handoff"), // bare-noun EVENT carve-out (spec §0.3)
1225
+ kind: z.enum(["transfer", "escalate"]).optional(),
1226
+ fromAgentId: z.string().optional(),
1227
+ toAgentId: z.string().optional(),
1228
+ toAgentName: z.string().optional(),
1229
+ }),
1230
+ // ── SOURCE ── (bare-noun EVENT carve-out, spec §0.3) — offset-citation bind target
1231
+ z.object({
1232
+ ...base,
1233
+ type: z.literal("source"),
1234
+ sourceId: z.string(),
1235
+ source: AgSourcePayload,
1236
+ chunkIndex: z.number().optional(),
1237
+ providerMetadata: AgProviderMeta.optional(),
1238
+ }),
1239
+ // ── PROMPT SAFETY ──
1240
+ z.object({
1241
+ ...base,
1242
+ type: z.literal("prompt.blocked"),
1243
+ reason: z.enum(["safety", "blocklist", "prohibited", "other"]),
1244
+ safety: z.array(AgSafety).optional(),
1245
+ }),
1246
+ // ── MESSAGE OPERATIONS ──
1247
+ // id="*" (REMOVE_ALL) requires turnId — enforced by superRefine on AgEvent (below).
1248
+ z.object({ ...base, type: z.literal("message.remove"),
1249
+ id: z.union([z.string(), z.literal("*")]), // "*" = REMOVE_ALL
1250
+ turnId: z.string().optional() }),
1251
+ // ── MEMORY SIDE-CHANNEL ──
1252
+ // value and patch are both optional here; exactly-one invariant enforced by superRefine on AgEvent.
1253
+ z.object({ ...base, type: z.literal("memory.write"),
1254
+ scope: z.enum(["agent", "user", "skill", "thread"]),
1255
+ key: z.string().optional(),
1256
+ value: JsonValue.optional(), patch: JsonValue.optional(), // exactly one — see superRefine
1257
+ reason: z.string().optional(), durable: z.boolean().optional() }),
1258
+ // ── GUARDRAIL EVALUATION (A2-additive; §0.3 closed set — `result` segment already reserved) ──
1259
+ z.object({
1260
+ ...base,
1261
+ type: z.literal("guardrail.result"),
1262
+ target: z.enum(["input", "output", "tool"]),
1263
+ passed: z.boolean(),
1264
+ action: z.enum(["block", "retry", "rewrite", "override", "terminate"]).optional(),
1265
+ reason: z.string().optional(),
1266
+ guardrailName: z.string().optional(),
1267
+ safety: z.array(AgSafety).optional(),
1268
+ }),
1269
+ // ── HITL (one family; spec §7) ──
1270
+ z.object({
1271
+ ...base,
1272
+ type: z.literal("hitl.ask"),
1273
+ askId: z.string(),
1274
+ kind: AgAskKind,
1275
+ message: z.string().optional(),
1276
+ schema: JsonValue.optional(),
1277
+ choices: z.array(AgChoice).optional(),
1278
+ authConfig: AgAuthConfig.optional(),
1279
+ url: z.string().optional(),
1280
+ toolCallId: z.string().optional(),
1281
+ continuation: z.enum(["resume", "turn"]).optional(),
1282
+ reason: z.string().optional(),
1283
+ metadata: AgMeta.optional(),
1284
+ requestState: z.string().optional(),
1285
+ inputKey: z.string().optional(),
1286
+ resumeBinding: z.enum(["id", "positional"]).optional(),
1287
+ ordinal: z.number().optional(),
1288
+ token: z.string().optional(),
1289
+ expiresAt: z.string().optional(),
1290
+ }),
1291
+
1292
+ // ─── ADVANCED events (spec §4 / §9) ────────────────────────────────────────
1293
+ // ── OPAQUE / ADVANCED STATE PASSTHROUGH (LangGraph values/updates) ──
1294
+ // `snapshot` = full graph-state dict ("values" stream mode); REPLACE on fold (§5).
1295
+ z.object({ ...base, type: z.literal("state.snapshot"), snapshot: JsonValue }),
1296
+ // `patch` = LangGraph "updates" ({node:{key:value}}) OR an RFC-6902 JSON Patch — both opaque.
1297
+ z.object({ ...base, type: z.literal("state.delta"), patch: JsonValue }),
1298
+ // ── STREAMED ARTIFACTS (A2A) — side-channel landing (§5) ──
1299
+ z.object({
1300
+ ...base,
1301
+ type: z.literal("artifact.start"),
1302
+ artifactId: z.string(),
1303
+ turnId: z.string(),
1304
+ threadId: z.string(),
1305
+ name: z.string().optional(),
1306
+ description: z.string().optional(),
1307
+ extensions: z.array(z.string()).optional(),
1308
+ }),
1309
+ z.object({
1310
+ ...base,
1311
+ type: z.literal("artifact.delta"),
1312
+ artifactId: z.string(),
1313
+ part: AgBlock,
1314
+ append: z.boolean(),
1315
+ }),
1316
+ z.object({ ...base, type: z.literal("artifact.end"), artifactId: z.string(), lastChunk: z.literal(true) }),
1317
+ // ── RECONNECT / RESYNC ── resync; REPLACE messages; turns/artifacts REPLACE per-container
1318
+ // conditionally — only when the snapshot carries them; omitted containers are PRESERVED (§5).
1319
+ // memory REPLACES ONLY scope="thread" records; cross-thread (agent/user/skill) are untouched.
1320
+ z.object({
1321
+ ...base,
1322
+ type: z.literal("messages.snapshot"),
1323
+ messages: z.array(AgMessage),
1324
+ turns: z.array(AgTurnRecord).optional(),
1325
+ artifacts: z.array(AgArtifact).optional(),
1326
+ memory: z.array(AgMemoryRecord).optional(),
1327
+ }),
1328
+ // ── HOST DISPLAY/RUNTIME HINT ── live-only; `capabilities` here = HOST surface render hint (A30).
1329
+ z.object({
1330
+ ...base,
1331
+ type: z.literal("host.context"),
1332
+ theme: JsonValue.optional(),
1333
+ capabilities: JsonValue.optional(),
1334
+ container: JsonValue.optional(),
1335
+ }),
1336
+ // ── CAPABILITY NEGOTIATION (agent→client, first turn) ──
1337
+ z.object({ ...base, type: z.literal("agent.capabilities"), capabilities: AgCapabilities }),
1338
+ // ── MESSAGE METADATA ── merge into the message named by messageId (open assistant message when absent).
1339
+ z.object({ ...base, type: z.literal("message.metadata"), messageId: z.string().optional(), metadata: AgMeta }),
1340
+ // ── MANDATORY DISPLAY (ToS) ── recorded on the turn, MUST NOT be dropped (§5).
1341
+ z.object({ ...base, type: z.literal("display.required"), provider: z.string(), html: z.string() }),
1342
+ // ── AGENT ↔ SURFACE RPC (A2UI v1.0 + OpenAI Apps SDK) — live-only / non-folding (§5) ──
1343
+ z.object({
1344
+ ...base,
1345
+ type: z.literal("ui.call"),
1346
+ surfaceId: z.string(),
1347
+ callId: z.string(),
1348
+ method: z.string(),
1349
+ args: JsonValue.optional(),
1350
+ wantResponse: z.boolean().optional(),
1351
+ callableFrom: z.enum(["clientOnly", "remoteOnly", "clientOrRemote"]).optional(),
1352
+ }),
1353
+ z.object({
1354
+ ...base,
1355
+ type: z.literal("ui.result"),
1356
+ surfaceId: z.string(),
1357
+ callId: z.string(),
1358
+ method: z.string().optional(),
1359
+ value: JsonValue.optional(),
1360
+ error: AgSurfaceError.optional(),
1361
+ }),
1362
+ z.object({
1363
+ ...base,
1364
+ type: z.literal("ui.action-result"),
1365
+ surfaceId: z.string(),
1366
+ actionId: z.string(),
1367
+ value: JsonValue.optional(),
1368
+ error: AgSurfaceError.optional(),
1369
+ }),
1370
+ // OpenAI Apps SDK window.openai.callTool reply leg — `result` is a string returned to the widget.
1371
+ z.object({ ...base, type: z.literal("ui.widget.result"), surfaceId: z.string(), callId: z.string(), result: z.string() }),
1372
+ z.object({
1373
+ ...base,
1374
+ type: z.literal("ui.display-mode"),
1375
+ mode: AgDisplayMode,
1376
+ granted: AgDisplayMode.optional(), // authoritative reply leg (A52)
1377
+ surfaceId: z.string().optional(),
1378
+ toolCallId: z.string().optional(),
1379
+ }),
1380
+ // ── A2UI SURFACE LIFECYCLE + DATA-MODEL PUSH (server→renderer; opaque) ──
1381
+ // catalogId carried BY REFERENCE; components/dataModel/surfaceProperties OPAQUE (zero component schema).
1382
+ z.object({
1383
+ ...base,
1384
+ type: z.literal("ui.surface.start"),
1385
+ surfaceId: z.string(),
1386
+ catalogId: z.string(),
1387
+ surfaceProperties: JsonValue.optional(),
1388
+ sendDataModel: z.boolean().optional(),
1389
+ components: JsonValue.optional(),
1390
+ dataModel: JsonValue.optional(),
1391
+ toolCallId: z.string().optional(),
1392
+ }),
1393
+ // A2UI updateComponents — the streamed adjacency-list passes through VERBATIM.
1394
+ z.object({ ...base, type: z.literal("ui.surface.update"), surfaceId: z.string(), components: JsonValue }),
1395
+ z.object({ ...base, type: z.literal("ui.surface.end"), surfaceId: z.string() }),
1396
+ // A2UI updateDataModel push; path = JSON-Pointer (default "/"); absent value = delete-at-path; value OPAQUE.
1397
+ z.object({
1398
+ ...base,
1399
+ type: z.literal("ui.data-model"),
1400
+ surfaceId: z.string(),
1401
+ path: z.string().optional(),
1402
+ value: JsonValue.optional(),
1403
+ }),
1404
+ ]);
1405
+
1406
+ // AgClosedEventType — the TypeScript-level discriminated union of all closed event
1407
+ // members. Exported for consumers (e.g. the reduce() fold) that must switch on
1408
+ // ev.type after ruling out the open AgExtEvent arm: the AgExtEvent catchall(JsonValue)
1409
+ // index signature widens every field on the AgEvent union, so callers that need proper
1410
+ // field narrowing should narrow (via a type guard) to AgClosedEventType after an ext-pattern guard.
1411
+ export type AgClosedEventType = z.infer<typeof AgClosedEvent>;
1412
+
1413
+ // Open namespaced vendor-extension event `ext.<vendor>.<key>` (spec §4 / §9 / §12,
1414
+ // RFC-6648: no `x-` prefix). A discriminatedUnion can't hold an open template-literal
1415
+ // discriminant, so this is a sibling object validated on the `type` regex, with the
1416
+ // extra `[k]: unknown` keys constrained to `JsonValue` via `.catchall`.
1417
+ export const AgExtEvent = z
1418
+ .object({
1419
+ ...base,
1420
+ type: z.string().regex(/^ext\.[^.]+\..+$/),
1421
+ })
1422
+ .catchall(JsonValue);
1423
+ export type AgExtEvent = z.infer<typeof AgExtEvent>;
1424
+
1425
+ // AgEvent = the closed discriminated union OR the open ext event. A bare unknown
1426
+ // `type` (e.g. {type:"nope"}) matches neither arm and still REJECTS.
1427
+ // Cross-field invariants live here (discriminatedUnion arms cannot carry .refine —
1428
+ // it would produce ZodEffects, breaking the discriminatedUnion):
1429
+ // (1) message.remove id="*" (REMOVE_ALL) requires turnId
1430
+ // (2) memory.write requires exactly one of value | patch
1431
+ export const AgEvent = AgClosedEvent.or(AgExtEvent).superRefine((ev, ctx) => {
1432
+ if (ev.type === "message.remove" && ev.id === "*" && ev.turnId === undefined)
1433
+ ctx.addIssue({ code: "custom", message: "message.remove id='*' (REMOVE_ALL) requires turnId" });
1434
+ if (ev.type === "memory.write" && (ev.value !== undefined) === (ev.patch !== undefined))
1435
+ ctx.addIssue({ code: "custom", message: "memory.write requires exactly one of value | patch" });
1436
+ });
1437
+ export type AgEvent = z.infer<typeof AgEvent>;