@archboard/codex-realtime-voice 0.0.0-stage → 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.
@@ -0,0 +1,2808 @@
1
+ import { a as CodexPatchChangeKindTypeSchema, c as CodexThreadStatusTypeSchema, d as CodexTurnStatusSchema, f as createCodexCommandExecutionApprovalDecisionSchema, i as CodexFileChangeApprovalDecisionSchema, l as CodexTokenUsageBreakdownSchema, u as CodexTurnPlanStepStatusSchema } from "./app-server-contract-D4E5bibD.mjs";
2
+ import { n as parseRealtimeItemId, r as parseRealtimeSessionId } from "./realtime-contract-DwkCluo2.mjs";
3
+ import { z } from "zod";
4
+ // ../codex-app-server/src/shared/constants/app-server-capacity.ts
5
+ /**
6
+ * The canonical non-duration capacity contract for one Codex app-server
7
+ * connection. Durations remain in `@archboard/timing`.
8
+ */
9
+ const CODEX_APP_SERVER_CAPACITY = Object.freeze({
10
+ frameBytes: 16777216,
11
+ partialFrameBytes: 16777216,
12
+ stderrRetainedBytes: 65536,
13
+ text: Object.freeze({ maxChars: 256 }),
14
+ outbound: Object.freeze({
15
+ pendingRequests: 128,
16
+ regularQueuedFrames: 128,
17
+ regularQueuedBytes: 16777216,
18
+ pendingReverseRequests: 128,
19
+ pendingReverseBytes: 16777216,
20
+ maxReverseResponseBytes: 524288,
21
+ responseReservedFrames: 128,
22
+ responseReservedBytes: 67108864
23
+ }),
24
+ retention: Object.freeze({
25
+ requestTombstones: 256,
26
+ completedReverseIds: 256,
27
+ lateResponses: 128,
28
+ lateResponseRecordBytes: 4096,
29
+ issues: 256,
30
+ issueRecordBytes: 2048
31
+ }),
32
+ listenersPerEvent: 1
33
+ });
34
+ // src/shared/browser/schemas/scalars.ts
35
+ const JsonValueSchema = z.json();
36
+ /**
37
+ * A non-empty string bounded in both characters and UTF-8 bytes, without NUL,
38
+ * so a browser payload can never exceed what its wire budget assumed.
39
+ * @param maximum - The limit, applied to both the length and the encoded byte size.
40
+ * @returns The string schema.
41
+ */
42
+ const boundedText = (maximum) => z.string().min(1).max(maximum).refine((value) => !value.includes("\0"), "NUL is not allowed").refine((value) => new TextEncoder().encode(value).byteLength <= maximum, `text exceeds ${maximum} UTF-8 bytes`);
43
+ /**
44
+ * Like {@link boundedText} but allows the empty string, for bodies that may
45
+ * legitimately be blank on the wire.
46
+ * @param maximum - The limit, applied to both the length and the encoded byte size.
47
+ * @returns The string schema.
48
+ */
49
+ const boundedWireText = (maximum) => z.string().max(maximum).refine((value) => !value.includes("\0"), "NUL is not allowed").refine((value) => new TextEncoder().encode(value).byteLength <= maximum, `text exceeds ${maximum} UTF-8 bytes`);
50
+ /**
51
+ * Bounded text that may be null or absent.
52
+ * @param maximum - The limit, applied to both the length and the encoded byte size.
53
+ * @returns The optional, nullable string schema.
54
+ */
55
+ const optionalNullableText = (maximum) => boundedText(maximum).nullable().optional();
56
+ const SafeUrlSchema = boundedText(2048).refine((value) => {
57
+ try {
58
+ const url = new URL(value);
59
+ return url.protocol === "http:" || url.protocol === "https:";
60
+ } catch {
61
+ return false;
62
+ }
63
+ }, "only http and https URLs are supported");
64
+ const NonNegativeIntegerSchema = z.number().int().nonnegative();
65
+ /**
66
+ * Wraps one authority parser as a zod schema, so a refusal from the identity
67
+ * authority surfaces as an ordinary validation issue instead of a throw.
68
+ * @param parse - The authority's parser for one identity domain.
69
+ * @returns A schema that yields the branded identity or an issue.
70
+ */
71
+ function authorityIdentity(parse) {
72
+ return z.unknown().transform((value, context) => {
73
+ try {
74
+ return parse(value);
75
+ } catch (error) {
76
+ context.addIssue({
77
+ code: "custom",
78
+ message: error instanceof Error ? error.message : "identity is not valid in this session"
79
+ });
80
+ return z.NEVER;
81
+ }
82
+ });
83
+ }
84
+ /**
85
+ * Builds one schema per identity domain over the session's authority. The
86
+ * operation schema refuses everything when no operation authority is supplied,
87
+ * because a browser context without one must never accept an operation id.
88
+ * @param context - The decoder and validator, plus the operation capability when present.
89
+ * @returns The per-domain schemas and a union that accepts any of them.
90
+ */
91
+ function createIdentitySchemas(context) {
92
+ const decoder = context.decoder;
93
+ const identities = {
94
+ ChildIdSchema: authorityIdentity(decoder.parseChildId),
95
+ ChildEpochSchema: authorityIdentity(decoder.parseChildEpoch),
96
+ BrowserCommandIdSchema: authorityIdentity(decoder.parseBrowserCommandId),
97
+ ThreadIdSchema: authorityIdentity(decoder.parseThreadId),
98
+ TurnIdSchema: authorityIdentity(decoder.parseTurnId),
99
+ ItemIdSchema: authorityIdentity(decoder.parseItemId),
100
+ QueuedSubmissionIdSchema: authorityIdentity(decoder.parseQueuedSubmissionId),
101
+ LoginIdSchema: authorityIdentity(decoder.parseLoginId),
102
+ JsonRpcRequestIdSchema: authorityIdentity(decoder.parseJsonRpcRequestId),
103
+ DynamicToolCallIdSchema: authorityIdentity(decoder.parseDynamicToolCallId),
104
+ RealtimeSessionIdSchema: authorityIdentity(decoder.parseRealtimeSessionId),
105
+ ApprovalIdSchema: authorityIdentity(decoder.parseApprovalId),
106
+ OperationIdSchema: context.operation ? authorityIdentity(context.operation.decoder.parseOperationId) : z.custom(() => false, "OperationId authority is not available")
107
+ };
108
+ return {
109
+ ...identities,
110
+ OpaqueIdentitySchema: z.union([
111
+ identities.ChildIdSchema,
112
+ identities.ChildEpochSchema,
113
+ identities.BrowserCommandIdSchema,
114
+ identities.ThreadIdSchema,
115
+ identities.TurnIdSchema,
116
+ identities.ItemIdSchema,
117
+ identities.QueuedSubmissionIdSchema,
118
+ identities.LoginIdSchema,
119
+ identities.JsonRpcRequestIdSchema,
120
+ identities.DynamicToolCallIdSchema,
121
+ identities.RealtimeSessionIdSchema,
122
+ identities.ApprovalIdSchema,
123
+ identities.OperationIdSchema
124
+ ])
125
+ };
126
+ }
127
+ /**
128
+ * Refuses a target addressed to another child or an earlier epoch.
129
+ * @param context - The validator that knows the current child and epoch.
130
+ * @param value - The target being addressed.
131
+ * @param value.childId - The child the target names.
132
+ * @param value.epoch - The epoch the target names.
133
+ */
134
+ function assertCurrentTarget(context, value) {
135
+ context.assertCurrentEpoch(value.childId, value.epoch);
136
+ }
137
+ // src/shared/browser/schemas/vocabulary.ts
138
+ const TimestampSchema = z.number().int().nonnegative();
139
+ const DeliveryOutcomeSchema = z.enum([
140
+ "delivered",
141
+ "not_delivered",
142
+ "outcome_unknown"
143
+ ]);
144
+ /**
145
+ * What one timeline value may carry, in UTF-8 bytes or entries. The server
146
+ * projection bounds each value to these before the schema checks them, so a
147
+ * long command output or a sprawling patch is cut, never refused.
148
+ */
149
+ const BROWSER_TIMELINE_LIMITS = Object.freeze({
150
+ /** A prompt, an assistant message, reasoning, a plan item or a command line. */
151
+ text: 16384,
152
+ /** A tool name, or the MCP server or dynamic namespace that owns it. */
153
+ toolName: 256,
154
+ /** A tool call's arguments, as compact JSON. */
155
+ toolArguments: 1024,
156
+ /** The tail of a command's aggregated output. */
157
+ outputTail: 4096,
158
+ /** A working directory or a changed file's path. */
159
+ path: 1024,
160
+ /** A web search query. */
161
+ query: 1024,
162
+ /** A tool or turn error message. */
163
+ errorMessage: 2048,
164
+ /** The additional details a failed turn carries. */
165
+ errorDetails: 4096,
166
+ /** How many changed files one file change item lists. */
167
+ fileChanges: 64,
168
+ /** A plan's explanation. */
169
+ planExplanation: 2048,
170
+ /** How many steps one plan lists. */
171
+ planSteps: 64,
172
+ /** One plan step. */
173
+ planStep: 512
174
+ });
175
+ /** Exact callback JSON is retained up to the callback encoder's wire contract. */
176
+ const BROWSER_VOICE_CONTEXT_BODY_MAX_UTF8_BYTES = 32768;
177
+ const BROWSER_VOICE_CONTEXT_BRIEF_MAX_UTF8_BYTES = 8192;
178
+ const BROWSER_PERMISSION_FILE_ACCESS = {
179
+ deny: "deny",
180
+ read: "read",
181
+ write: "write"
182
+ };
183
+ /**
184
+ * Records a refusal from the identity validator as a validation issue.
185
+ * @param context - The refinement context of the schema being checked.
186
+ * @param error - What the validator threw.
187
+ * @param path - Where in the value the issue sits.
188
+ */
189
+ function addContextIssue(context, error, path) {
190
+ context.addIssue({
191
+ code: "custom",
192
+ path,
193
+ message: error instanceof Error ? error.message : "identity is not current"
194
+ });
195
+ }
196
+ /**
197
+ * A `superRefine` callback that refuses a value whose child and epoch are not
198
+ * the session's current ones, reporting at `epoch`.
199
+ * @param context - The validator that knows the current child and epoch.
200
+ * @returns The refinement to attach to a schema carrying `childId` and `epoch`.
201
+ */
202
+ function refineCurrentTarget(context) {
203
+ return (value, refinementContext) => {
204
+ try {
205
+ assertCurrentTarget(context.validator, value);
206
+ } catch (error) {
207
+ addContextIssue(refinementContext, error, ["epoch"]);
208
+ }
209
+ };
210
+ }
211
+ // src/shared/browser/schemas/approvals.ts
212
+ /**
213
+ * Tells whether an optional lower and upper bound contradict each other.
214
+ * @param minimum - The lower bound, or null when unbounded.
215
+ * @param maximum - The upper bound, or null when unbounded.
216
+ * @returns True when both are set and the lower exceeds the upper.
217
+ */
218
+ function contradictoryBounds(minimum, maximum) {
219
+ return minimum !== null && maximum !== null && minimum > maximum;
220
+ }
221
+ /**
222
+ * Builds the approval schema.
223
+ * @param identity - The session's identity schemas.
224
+ * @param context - The validator that knows the current child and epoch.
225
+ * @returns The discriminated approval schema.
226
+ */
227
+ function createBrowserApprovalSchemas(identity, context) {
228
+ const { ApprovalIdSchema, ChildEpochSchema, ChildIdSchema, ItemIdSchema, JsonRpcRequestIdSchema, ThreadIdSchema, TurnIdSchema } = identity;
229
+ const NullableReasonSchema = optionalNullableText(512);
230
+ const ApprovalEnvelope = {
231
+ requestId: JsonRpcRequestIdSchema,
232
+ threadId: ThreadIdSchema,
233
+ turnId: TurnIdSchema.nullable(),
234
+ itemId: ItemIdSchema.nullable(),
235
+ approvalId: ApprovalIdSchema.nullable(),
236
+ expiresAtMs: TimestampSchema,
237
+ lifecycle: z.discriminatedUnion("state", [
238
+ z.object({
239
+ state: z.enum(["staged", "pending"]),
240
+ decision: z.null(),
241
+ outcome: z.null(),
242
+ reason: z.null()
243
+ }).strict(),
244
+ z.object({
245
+ state: z.literal("settled"),
246
+ decision: z.enum([
247
+ "approved",
248
+ "declined",
249
+ "cancelled"
250
+ ]),
251
+ outcome: z.enum(["delivered", "not_delivered"]).nullable(),
252
+ reason: boundedText(512)
253
+ }).strict(),
254
+ z.object({
255
+ state: z.enum([
256
+ "expired",
257
+ "cancelled",
258
+ "stale"
259
+ ]),
260
+ decision: z.literal("cancelled"),
261
+ outcome: z.enum(["delivered", "not_delivered"]).nullable(),
262
+ reason: boundedText(512)
263
+ }).strict(),
264
+ z.object({
265
+ state: z.literal("outcome_unknown"),
266
+ decision: z.enum([
267
+ "approved",
268
+ "declined",
269
+ "cancelled"
270
+ ]),
271
+ outcome: z.literal("outcome_unknown"),
272
+ reason: boundedText(512)
273
+ }).strict()
274
+ ]),
275
+ binding: z.object({
276
+ child: ChildIdSchema,
277
+ epoch: ChildEpochSchema,
278
+ link: boundedText(256).nullable(),
279
+ target: boundedText(512),
280
+ effect: boundedText(512)
281
+ }).strict(),
282
+ spoken: z.object({
283
+ eligible: z.boolean(),
284
+ reason: z.enum([
285
+ "eligible",
286
+ "not_pending",
287
+ "stale_ownership",
288
+ "secret",
289
+ "multi_question",
290
+ "form",
291
+ "url",
292
+ "permission_scope",
293
+ "coordinator_blocking",
294
+ "unsupported_schema",
295
+ "broader_grant",
296
+ "not_binary"
297
+ ])
298
+ }).strict()
299
+ };
300
+ const ApprovalReason = { reason: NullableReasonSchema };
301
+ const ApprovalDecisionSchema = createCodexCommandExecutionApprovalDecisionSchema({
302
+ text: boundedText(16384),
303
+ host: boundedText(2048)
304
+ });
305
+ const ElicitationFieldSchema = z.object({
306
+ name: boundedText(256),
307
+ type: z.enum([
308
+ "string",
309
+ "number",
310
+ "integer",
311
+ "boolean",
312
+ "enum"
313
+ ]),
314
+ required: z.boolean(),
315
+ secret: z.boolean(),
316
+ title: boundedText(512).nullable(),
317
+ description: boundedText(4096).nullable(),
318
+ format: z.enum([
319
+ "email",
320
+ "uri",
321
+ "date",
322
+ "date-time"
323
+ ]).nullable(),
324
+ minimum: z.number().nullable(),
325
+ maximum: z.number().nullable(),
326
+ minLength: z.number().int().nonnegative().nullable(),
327
+ maxLength: z.number().int().nonnegative().nullable(),
328
+ minimumItems: z.number().int().nonnegative().nullable(),
329
+ maximumItems: z.number().int().nonnegative().nullable(),
330
+ options: z.array(boundedText(2048)).nullable(),
331
+ defaultValue: JsonValueSchema.nullable()
332
+ }).strict().superRefine((field, refinementContext) => {
333
+ if (field.secret && field.defaultValue !== null) refinementContext.addIssue({
334
+ code: "custom",
335
+ path: ["defaultValue"],
336
+ message: "secret elicitation defaults are never projected"
337
+ });
338
+ if (contradictoryBounds(field.minLength, field.maxLength)) refinementContext.addIssue({
339
+ code: "custom",
340
+ path: ["maxLength"],
341
+ message: "elicitation text bounds are contradictory"
342
+ });
343
+ if (contradictoryBounds(field.minimumItems, field.maximumItems)) refinementContext.addIssue({
344
+ code: "custom",
345
+ path: ["maximumItems"],
346
+ message: "elicitation item bounds are contradictory"
347
+ });
348
+ });
349
+ const BrowserRequestedPermissionScopeSchema = z.object({
350
+ network: z.boolean().nullable(),
351
+ fileAccess: z.array(z.enum(Object.values(BROWSER_PERMISSION_FILE_ACCESS))).max(3)
352
+ }).strict();
353
+ return { BrowserApprovalSchema: z.discriminatedUnion("approvalKind", [
354
+ z.object({
355
+ kind: z.literal("approval"),
356
+ approvalKind: z.literal("command_execution"),
357
+ ...ApprovalEnvelope,
358
+ ...ApprovalReason,
359
+ command: boundedText(16384).nullable(),
360
+ availableDecisions: z.array(ApprovalDecisionSchema)
361
+ }).strict(),
362
+ z.object({
363
+ kind: z.literal("approval"),
364
+ approvalKind: z.literal("file_change"),
365
+ ...ApprovalEnvelope,
366
+ ...ApprovalReason,
367
+ availableDecisions: z.array(CodexFileChangeApprovalDecisionSchema)
368
+ }).strict(),
369
+ z.object({
370
+ kind: z.literal("approval"),
371
+ approvalKind: z.literal("user_input"),
372
+ ...ApprovalEnvelope,
373
+ questions: z.array(z.object({
374
+ id: boundedText(256),
375
+ header: boundedText(256),
376
+ question: boundedText(4096),
377
+ isOther: z.boolean(),
378
+ isSecret: z.boolean(),
379
+ options: z.array(z.object({
380
+ label: boundedText(256),
381
+ description: boundedText(2048)
382
+ }).strict()).nullable()
383
+ }).strict())
384
+ }).strict(),
385
+ z.object({
386
+ kind: z.literal("approval"),
387
+ approvalKind: z.literal("elicitation"),
388
+ ...ApprovalEnvelope,
389
+ serverName: boundedText(256),
390
+ mode: z.enum([
391
+ "form",
392
+ "openai/form",
393
+ "url"
394
+ ]),
395
+ message: boundedText(16384),
396
+ url: SafeUrlSchema.nullable(),
397
+ fields: z.array(ElicitationFieldSchema).nullable()
398
+ }).strict(),
399
+ z.object({
400
+ kind: z.literal("approval"),
401
+ approvalKind: z.literal("permissions"),
402
+ ...ApprovalEnvelope,
403
+ ...ApprovalReason,
404
+ requestedScope: BrowserRequestedPermissionScopeSchema
405
+ }).strict(),
406
+ z.object({
407
+ kind: z.literal("approval"),
408
+ approvalKind: z.literal("apply_patch"),
409
+ ...ApprovalEnvelope,
410
+ ...ApprovalReason,
411
+ fileCount: z.number().int().nonnegative()
412
+ }).strict(),
413
+ z.object({
414
+ kind: z.literal("approval"),
415
+ approvalKind: z.literal("exec_command"),
416
+ ...ApprovalEnvelope,
417
+ ...ApprovalReason,
418
+ command: z.array(boundedText(16384))
419
+ }).strict()
420
+ ]).superRefine((approval, refinementContext) => {
421
+ if (approval.lifecycle.state !== "pending" && approval.spoken.eligible) refinementContext.addIssue({
422
+ code: "custom",
423
+ path: ["spoken", "eligible"],
424
+ message: "only pending approvals may be spoken eligible"
425
+ });
426
+ try {
427
+ assertCurrentTarget(context.validator, {
428
+ childId: approval.binding.child,
429
+ epoch: approval.binding.epoch
430
+ });
431
+ } catch {
432
+ refinementContext.addIssue({
433
+ code: "custom",
434
+ path: ["binding"],
435
+ message: "approval binding is not from the current child epoch"
436
+ });
437
+ }
438
+ }) };
439
+ }
440
+ // src/shared/browser/schemas/commands.ts
441
+ /**
442
+ * Builds the text command, command lease, operation outcome and browser
443
+ * command schemas.
444
+ * @param identity - The session's identity schemas.
445
+ * @param context - The validator that knows the current child and epoch.
446
+ * @param DynamicApprovalResponseArm - The dynamic approval response command, one arm of the command union.
447
+ * @returns The four schemas.
448
+ */
449
+ function createBrowserCommandSchemas(identity, context, DynamicApprovalResponseArm) {
450
+ const { ApprovalIdSchema, BrowserCommandIdSchema, ChildEpochSchema, ChildIdSchema, JsonRpcRequestIdSchema, LoginIdSchema, QueuedSubmissionIdSchema, ThreadIdSchema, TurnIdSchema } = identity;
451
+ const NullableReasonSchema = optionalNullableText(512);
452
+ const ChatIdSchema = boundedText(128);
453
+ const currentTarget = refineCurrentTarget(context);
454
+ const TargetSchema = {
455
+ commandId: BrowserCommandIdSchema,
456
+ chatId: ChatIdSchema,
457
+ childId: ChildIdSchema,
458
+ epoch: ChildEpochSchema
459
+ };
460
+ const BrowserTextCommandSchema = z.discriminatedUnion("command", [
461
+ z.object({
462
+ kind: z.literal("text_command"),
463
+ command: z.literal("start"),
464
+ ...TargetSchema,
465
+ threadId: ThreadIdSchema,
466
+ prompt: boundedText(16384)
467
+ }).strict(),
468
+ z.object({
469
+ kind: z.literal("text_command"),
470
+ command: z.literal("steer"),
471
+ ...TargetSchema,
472
+ threadId: ThreadIdSchema,
473
+ turnId: TurnIdSchema,
474
+ prompt: boundedText(16384)
475
+ }).strict(),
476
+ z.object({
477
+ kind: z.literal("text_command"),
478
+ command: z.literal("interrupt"),
479
+ ...TargetSchema,
480
+ threadId: ThreadIdSchema,
481
+ turnId: TurnIdSchema
482
+ }).strict()
483
+ ]).superRefine(currentTarget);
484
+ const BrowserCommandLeaseSchema = z.object({
485
+ kind: z.literal("command_lease"),
486
+ ...TargetSchema,
487
+ state: z.enum([
488
+ "active",
489
+ "expired",
490
+ "released"
491
+ ]),
492
+ expiresAtMs: TimestampSchema
493
+ }).strict().superRefine(currentTarget);
494
+ const BrowserOperationOutcomeSchema = z.object({
495
+ kind: z.literal("operation_outcome"),
496
+ operationId: BrowserCommandIdSchema,
497
+ outcome: DeliveryOutcomeSchema,
498
+ message: NullableReasonSchema
499
+ }).strict();
500
+ const BrowserCommandBase = {
501
+ kind: z.literal("browser_command"),
502
+ ...TargetSchema
503
+ };
504
+ const CommandArms = [
505
+ z.object({
506
+ ...BrowserCommandBase,
507
+ command: z.literal("accountLogin"),
508
+ login: JsonValueSchema
509
+ }).strict(),
510
+ z.object({
511
+ ...BrowserCommandBase,
512
+ command: z.literal("accountLoginCancel"),
513
+ loginId: LoginIdSchema
514
+ }).strict(),
515
+ z.object({
516
+ ...BrowserCommandBase,
517
+ command: z.literal("accountLogout")
518
+ }).strict(),
519
+ z.object({
520
+ ...BrowserCommandBase,
521
+ command: z.literal("threadLinkCreate")
522
+ }).strict(),
523
+ z.object({
524
+ ...BrowserCommandBase,
525
+ command: z.literal("queueAdd"),
526
+ prompt: boundedText(16384)
527
+ }).strict(),
528
+ z.object({
529
+ ...BrowserCommandBase,
530
+ command: z.literal("queueUpdate"),
531
+ submissionId: QueuedSubmissionIdSchema,
532
+ prompt: boundedText(16384)
533
+ }).strict(),
534
+ z.object({
535
+ ...BrowserCommandBase,
536
+ command: z.literal("queueDelete"),
537
+ submissionId: QueuedSubmissionIdSchema
538
+ }).strict(),
539
+ z.object({
540
+ ...BrowserCommandBase,
541
+ command: z.literal("queueReorder"),
542
+ orderedSubmissionIds: z.array(QueuedSubmissionIdSchema).min(1).max(100)
543
+ }).strict(),
544
+ z.object({
545
+ ...BrowserCommandBase,
546
+ command: z.literal("queueStart"),
547
+ submissionId: QueuedSubmissionIdSchema
548
+ }).strict(),
549
+ z.object({
550
+ ...BrowserCommandBase,
551
+ command: z.literal("approvalRespond"),
552
+ requestId: JsonRpcRequestIdSchema,
553
+ approvalId: ApprovalIdSchema.nullable(),
554
+ response: JsonValueSchema
555
+ }).strict(),
556
+ z.object({
557
+ ...BrowserCommandBase,
558
+ command: z.literal("realtimeStart"),
559
+ threadId: ThreadIdSchema,
560
+ sdp: boundedText(16384),
561
+ /** The narrative the session presents: JSON whose meaning the host validates. */
562
+ narrative: JsonValueSchema.optional()
563
+ }).strict(),
564
+ z.object({
565
+ ...BrowserCommandBase,
566
+ command: z.literal("realtimeAppendText"),
567
+ threadId: ThreadIdSchema,
568
+ realtimeSessionHandle: BrowserCommandIdSchema,
569
+ text: boundedText(4096)
570
+ }).strict(),
571
+ z.object({
572
+ ...BrowserCommandBase,
573
+ command: z.literal("realtimeStop"),
574
+ threadId: ThreadIdSchema,
575
+ realtimeSessionHandle: BrowserCommandIdSchema
576
+ }).strict(),
577
+ z.object({
578
+ ...BrowserCommandBase,
579
+ command: z.literal("start"),
580
+ threadId: ThreadIdSchema,
581
+ prompt: boundedText(16384)
582
+ }).strict(),
583
+ z.object({
584
+ ...BrowserCommandBase,
585
+ command: z.literal("steer"),
586
+ threadId: ThreadIdSchema,
587
+ turnId: TurnIdSchema,
588
+ prompt: boundedText(16384)
589
+ }).strict(),
590
+ z.object({
591
+ ...BrowserCommandBase,
592
+ command: z.literal("interrupt"),
593
+ threadId: ThreadIdSchema,
594
+ turnId: TurnIdSchema
595
+ }).strict(),
596
+ DynamicApprovalResponseArm
597
+ ];
598
+ return {
599
+ BrowserTextCommandSchema,
600
+ BrowserCommandLeaseSchema,
601
+ BrowserOperationOutcomeSchema,
602
+ BrowserCommandSchema: z.discriminatedUnion("command", CommandArms).superRefine(currentTarget)
603
+ };
604
+ }
605
+ /** One workhorse of the tab session, as a host lists it. */
606
+ const BrowserWorkhorseSchema = z.object({
607
+ /** The checkout that the workhorse works in. */
608
+ checkout: boundedText(4096),
609
+ /** The name the host shows for the checkout. */
610
+ label: boundedText(512),
611
+ /** Whether the tab session has a workhorse here; false only for the shown checkout before its first message. */
612
+ live: z.boolean(),
613
+ /** Whether a turn of it is running. */
614
+ running: z.boolean(),
615
+ /** Whether it waits for the person to answer an approval. */
616
+ waitingForApproval: z.boolean(),
617
+ /** Whether it waits for the person to answer a question. */
618
+ waitingForUser: z.boolean()
619
+ }).strict();
620
+ /**
621
+ * The workhorses of the tab session and the checkout whose conversation the
622
+ * tab shows. Each checkout is listed once, and the shown one is always listed.
623
+ */
624
+ const BrowserWorkhorsesSchema = z.object({
625
+ kind: z.literal("codex_workhorses"),
626
+ /** The checkout whose conversation every chat of the tab shows. */
627
+ shown: boundedText(4096),
628
+ entries: z.array(BrowserWorkhorseSchema).max(32)
629
+ }).strict().superRefine((value, context) => {
630
+ const checkouts = value.entries.map((entry) => entry.checkout);
631
+ if (new Set(checkouts).size !== checkouts.length) context.addIssue({
632
+ code: "custom",
633
+ path: ["entries"],
634
+ message: "a checkout is listed twice"
635
+ });
636
+ if (!checkouts.includes(value.shown)) context.addIssue({
637
+ code: "custom",
638
+ path: ["shown"],
639
+ message: "the shown checkout is not listed"
640
+ });
641
+ });
642
+ /**
643
+ * Builds the readiness, account, login and settings schemas.
644
+ * @param identity - The session's identity schemas.
645
+ * @returns The four schemas.
646
+ */
647
+ function createBrowserSessionSchemas(identity) {
648
+ const { LoginIdSchema } = identity;
649
+ const BrowserReadinessSchema = z.union([
650
+ z.object({
651
+ kind: z.literal("readiness"),
652
+ state: z.literal("stopped"),
653
+ reason: boundedText(512)
654
+ }).strict(),
655
+ z.object({
656
+ kind: z.literal("readiness"),
657
+ state: z.literal("backoff"),
658
+ retryAtMs: TimestampSchema,
659
+ reason: boundedText(512)
660
+ }).strict(),
661
+ z.object({
662
+ kind: z.literal("readiness"),
663
+ state: z.literal("initialized")
664
+ }).strict(),
665
+ z.object({
666
+ kind: z.literal("readiness"),
667
+ state: z.literal("storage_mismatch"),
668
+ reason: boundedText(512)
669
+ }).strict(),
670
+ z.object({
671
+ kind: z.literal("readiness"),
672
+ state: z.literal("login_capable")
673
+ }).strict(),
674
+ z.object({
675
+ kind: z.literal("readiness"),
676
+ state: z.literal("signed_out")
677
+ }).strict(),
678
+ z.object({
679
+ kind: z.literal("readiness"),
680
+ state: z.literal("login_pending"),
681
+ loginId: LoginIdSchema
682
+ }).strict(),
683
+ z.object({
684
+ kind: z.literal("readiness"),
685
+ state: z.literal("thread_capable")
686
+ }).strict(),
687
+ z.object({
688
+ kind: z.literal("readiness"),
689
+ state: z.literal("reconnecting"),
690
+ reason: boundedText(512)
691
+ }).strict(),
692
+ z.object({
693
+ kind: z.literal("readiness"),
694
+ state: z.literal("incompatible_contract"),
695
+ reason: boundedText(512)
696
+ }).strict()
697
+ ]);
698
+ const SupportedLoginVariantSchema = z.enum([
699
+ "apiKey",
700
+ "chatgpt",
701
+ "amazonBedrock",
702
+ "amazonBedrockAccessKeys"
703
+ ]);
704
+ const CodexAccountTypeSchema = z.enum([
705
+ "apiKey",
706
+ "chatgpt",
707
+ "amazonBedrock",
708
+ "gcp"
709
+ ]);
710
+ const BrowserAccountSchema = z.union([
711
+ z.object({
712
+ kind: z.literal("account"),
713
+ state: z.literal("unknown"),
714
+ reason: boundedText(512)
715
+ }).strict(),
716
+ z.object({
717
+ kind: z.literal("account"),
718
+ state: z.literal("signed_out")
719
+ }).strict(),
720
+ z.object({
721
+ kind: z.literal("account"),
722
+ state: z.literal("login_pending"),
723
+ loginId: LoginIdSchema,
724
+ variant: SupportedLoginVariantSchema
725
+ }).strict(),
726
+ z.object({
727
+ kind: z.literal("account"),
728
+ state: z.literal("ready"),
729
+ accountType: CodexAccountTypeSchema
730
+ }).strict(),
731
+ z.object({
732
+ kind: z.literal("account"),
733
+ state: z.literal("failed"),
734
+ reason: boundedText(512)
735
+ }).strict()
736
+ ]);
737
+ const BrowserLoginSchema = z.union([
738
+ z.object({
739
+ kind: z.literal("login"),
740
+ state: z.literal("idle")
741
+ }).strict(),
742
+ z.object({
743
+ kind: z.literal("login"),
744
+ state: z.literal("pending"),
745
+ loginId: LoginIdSchema,
746
+ variant: SupportedLoginVariantSchema,
747
+ authUrl: SafeUrlSchema.refine((value) => URL.canParse(value) && new URL(value).protocol === "https:").nullable()
748
+ }).strict(),
749
+ z.object({
750
+ kind: z.literal("login"),
751
+ state: z.literal("completed"),
752
+ loginId: LoginIdSchema
753
+ }).strict(),
754
+ z.object({
755
+ kind: z.literal("login"),
756
+ state: z.literal("cancelled"),
757
+ loginId: LoginIdSchema
758
+ }).strict(),
759
+ z.object({
760
+ kind: z.literal("login"),
761
+ state: z.literal("failed"),
762
+ loginId: LoginIdSchema.nullable(),
763
+ reason: boundedText(512)
764
+ }).strict()
765
+ ]);
766
+ const BrowserSandboxSchema = z.object({
767
+ mode: z.enum([
768
+ "full_access",
769
+ "read_only",
770
+ "external",
771
+ "workspace_write"
772
+ ]),
773
+ network: z.enum([
774
+ "enabled",
775
+ "restricted",
776
+ "unspecified"
777
+ ])
778
+ }).strict();
779
+ const ActivePermissionProfileSchema = z.object({
780
+ id: boundedText(256),
781
+ extends: boundedText(256).nullable()
782
+ }).strict();
783
+ const ApprovalPolicySchema = z.union([z.enum([
784
+ "untrusted",
785
+ "on-request",
786
+ "never"
787
+ ]), z.object({ granular: z.object({
788
+ sandbox_approval: z.boolean(),
789
+ rules: z.boolean(),
790
+ skill_approval: z.boolean(),
791
+ request_permissions: z.boolean(),
792
+ mcp_elicitations: z.boolean()
793
+ }).strict() }).strict()]);
794
+ return {
795
+ BrowserReadinessSchema,
796
+ BrowserAccountSchema,
797
+ BrowserLoginSchema,
798
+ BrowserSettingsSchema: z.object({
799
+ kind: z.literal("settings"),
800
+ owner: z.enum(["workhorse", "coordinator"]),
801
+ model: boundedText(256),
802
+ effort: boundedText(64).nullable(),
803
+ serviceTier: boundedText(64).nullable(),
804
+ approvalPolicy: ApprovalPolicySchema,
805
+ approvalsReviewer: z.enum([
806
+ "user",
807
+ "auto_review",
808
+ "guardian_subagent"
809
+ ]),
810
+ sandbox: BrowserSandboxSchema,
811
+ activePermissionProfile: ActivePermissionProfileSchema.nullable()
812
+ }).strict(),
813
+ BrowserWorkhorsesSchema
814
+ };
815
+ }
816
+ // src/shared/browser/schemas/thread.ts
817
+ /**
818
+ * Builds the thread link, timeline and queue schemas.
819
+ * @param identity - The session's identity schemas.
820
+ * @param context - The validator that knows the current child and epoch.
821
+ * @returns The schemas.
822
+ */
823
+ function createBrowserThreadSchemas(identity, context) {
824
+ const { ApprovalIdSchema, ChildEpochSchema, ChildIdSchema, ItemIdSchema, OperationIdSchema, QueuedSubmissionIdSchema, ThreadIdSchema, TurnIdSchema } = identity;
825
+ const NullableReasonSchema = optionalNullableText(512);
826
+ const ThreadLinkStatusSchema = CodexThreadStatusTypeSchema;
827
+ const BrowserThreadLinkSourcePresentationSchema = z.enum([
828
+ "standard",
829
+ "subagent",
830
+ "custom",
831
+ "unknown"
832
+ ]);
833
+ const UnboundThreadLinkSchema = z.object({
834
+ kind: z.literal("thread_link"),
835
+ state: z.literal("unbound"),
836
+ childId: z.null(),
837
+ epoch: z.null(),
838
+ threadId: z.null(),
839
+ sourcePresentation: z.null(),
840
+ status: z.literal("notLoaded"),
841
+ loaded: z.literal(false),
842
+ canAcceptDirectInput: z.literal(false),
843
+ reason: NullableReasonSchema
844
+ }).strict();
845
+ const InspectOnlyThreadLinkSchema = z.object({
846
+ kind: z.literal("thread_link"),
847
+ state: z.literal("inspect_only"),
848
+ childId: z.null(),
849
+ epoch: z.null(),
850
+ threadId: ThreadIdSchema,
851
+ sourcePresentation: BrowserThreadLinkSourcePresentationSchema,
852
+ status: ThreadLinkStatusSchema,
853
+ loaded: z.boolean(),
854
+ canAcceptDirectInput: z.literal(false),
855
+ reason: NullableReasonSchema
856
+ }).strict();
857
+ const ExecutableThreadLinkSchema = z.object({
858
+ kind: z.literal("thread_link"),
859
+ state: z.literal("executable"),
860
+ childId: ChildIdSchema,
861
+ epoch: ChildEpochSchema,
862
+ threadId: ThreadIdSchema,
863
+ sourcePresentation: z.literal("standard"),
864
+ status: ThreadLinkStatusSchema.exclude(["notLoaded"]),
865
+ loaded: z.literal(true),
866
+ canAcceptDirectInput: z.literal(true),
867
+ reason: NullableReasonSchema
868
+ }).strict();
869
+ const currentTarget = refineCurrentTarget(context);
870
+ const BrowserThreadLinkSchema = z.union([
871
+ UnboundThreadLinkSchema,
872
+ InspectOnlyThreadLinkSchema,
873
+ ExecutableThreadLinkSchema
874
+ ]).superRefine((value, refinementContext) => {
875
+ if (value.state === "executable") currentTarget(value, refinementContext);
876
+ });
877
+ /** A duration or a point in time, in milliseconds, when Codex reported one. */
878
+ const MillisecondsSchema = z.number().nonnegative().nullable();
879
+ const LineCountSchema = z.number().int().nonnegative();
880
+ const BrowserTimelineFileChangeSchema = z.object({
881
+ path: boundedText(BROWSER_TIMELINE_LIMITS.path),
882
+ kind: CodexPatchChangeKindTypeSchema,
883
+ movePath: boundedText(BROWSER_TIMELINE_LIMITS.path).nullable(),
884
+ added: LineCountSchema,
885
+ removed: LineCountSchema
886
+ }).strict();
887
+ const BrowserTimelineItemSchema = z.discriminatedUnion("media", [
888
+ z.object({
889
+ media: z.literal("prompt"),
890
+ itemId: ItemIdSchema,
891
+ text: boundedText(BROWSER_TIMELINE_LIMITS.text)
892
+ }).strict(),
893
+ z.object({
894
+ media: z.literal("text"),
895
+ itemId: ItemIdSchema,
896
+ text: boundedText(BROWSER_TIMELINE_LIMITS.text)
897
+ }).strict(),
898
+ z.object({
899
+ media: z.literal("tool"),
900
+ itemId: ItemIdSchema,
901
+ name: boundedText(BROWSER_TIMELINE_LIMITS.toolName),
902
+ status: z.enum([
903
+ "inProgress",
904
+ "completed",
905
+ "failed"
906
+ ]),
907
+ server: boundedText(BROWSER_TIMELINE_LIMITS.toolName).nullable(),
908
+ arguments: boundedText(BROWSER_TIMELINE_LIMITS.toolArguments).nullable(),
909
+ durationMs: MillisecondsSchema,
910
+ error: boundedText(BROWSER_TIMELINE_LIMITS.errorMessage).nullable()
911
+ }).strict(),
912
+ z.object({
913
+ media: z.literal("command"),
914
+ itemId: ItemIdSchema,
915
+ command: boundedText(BROWSER_TIMELINE_LIMITS.text),
916
+ status: z.enum([
917
+ "inProgress",
918
+ "completed",
919
+ "failed",
920
+ "declined"
921
+ ]),
922
+ cwd: boundedText(BROWSER_TIMELINE_LIMITS.path).nullable(),
923
+ exitCode: z.number().int().nullable(),
924
+ durationMs: MillisecondsSchema,
925
+ output: boundedText(BROWSER_TIMELINE_LIMITS.outputTail).nullable(),
926
+ outputTruncated: z.boolean()
927
+ }).strict(),
928
+ z.object({
929
+ media: z.literal("fileChange"),
930
+ itemId: ItemIdSchema,
931
+ status: z.enum([
932
+ "inProgress",
933
+ "completed",
934
+ "failed",
935
+ "declined"
936
+ ]),
937
+ changes: z.array(BrowserTimelineFileChangeSchema).max(BROWSER_TIMELINE_LIMITS.fileChanges),
938
+ changesTruncated: z.boolean()
939
+ }).strict(),
940
+ z.object({
941
+ media: z.literal("reasoning"),
942
+ itemId: ItemIdSchema,
943
+ text: boundedText(BROWSER_TIMELINE_LIMITS.text)
944
+ }).strict(),
945
+ z.object({
946
+ media: z.literal("plan"),
947
+ itemId: ItemIdSchema,
948
+ text: boundedText(BROWSER_TIMELINE_LIMITS.text)
949
+ }).strict(),
950
+ z.object({
951
+ media: z.literal("search"),
952
+ itemId: ItemIdSchema,
953
+ query: boundedText(BROWSER_TIMELINE_LIMITS.query).nullable()
954
+ }).strict(),
955
+ z.object({
956
+ media: z.literal("compaction"),
957
+ itemId: ItemIdSchema
958
+ }).strict(),
959
+ z.object({
960
+ media: z.literal("approval"),
961
+ itemId: ItemIdSchema,
962
+ approvalId: ApprovalIdSchema,
963
+ status: z.enum([
964
+ "pending",
965
+ "resolved",
966
+ "cancelled"
967
+ ])
968
+ }).strict()
969
+ ]);
970
+ /** The latest plan Codex published for a turn, while the server holds it. */
971
+ const BrowserTimelinePlanSchema = z.object({
972
+ explanation: boundedText(BROWSER_TIMELINE_LIMITS.planExplanation).nullable(),
973
+ steps: z.array(z.object({
974
+ step: boundedText(BROWSER_TIMELINE_LIMITS.planStep),
975
+ status: CodexTurnPlanStepStatusSchema
976
+ }).strict()).max(BROWSER_TIMELINE_LIMITS.planSteps)
977
+ }).strict();
978
+ const BrowserTimelineTurnSchema = z.object({
979
+ turnId: TurnIdSchema,
980
+ status: CodexTurnStatusSchema,
981
+ items: z.array(BrowserTimelineItemSchema),
982
+ summary: boundedText(512),
983
+ outputsIncluded: z.boolean(),
984
+ outputsTruncated: z.boolean(),
985
+ startedAtMs: MillisecondsSchema,
986
+ completedAtMs: MillisecondsSchema,
987
+ durationMs: MillisecondsSchema,
988
+ error: z.object({
989
+ message: boundedText(BROWSER_TIMELINE_LIMITS.errorMessage),
990
+ details: boundedText(BROWSER_TIMELINE_LIMITS.errorDetails).nullable()
991
+ }).strict().nullable(),
992
+ plan: BrowserTimelinePlanSchema.nullable(),
993
+ /** The coordinator turn that delegated this workhorse turn, while the server knows it. */
994
+ delegatedBy: TurnIdSchema.nullable().optional()
995
+ }).strict();
996
+ /** The thread's latest token usage, and the context window it counts against. */
997
+ const BrowserTimelineUsageSchema = z.object({
998
+ total: CodexTokenUsageBreakdownSchema,
999
+ last: CodexTokenUsageBreakdownSchema,
1000
+ modelContextWindow: z.number().nonnegative().nullable()
1001
+ }).strict();
1002
+ const BrowserTimelineSchema = z.object({
1003
+ kind: z.literal("timeline"),
1004
+ threadId: ThreadIdSchema,
1005
+ turns: z.array(BrowserTimelineTurnSchema),
1006
+ nextCursor: boundedText(1024).nullable(),
1007
+ usage: BrowserTimelineUsageSchema.nullable()
1008
+ }).strict();
1009
+ const QueueStatusSchema = z.enum([
1010
+ "empty",
1011
+ "queued",
1012
+ "running",
1013
+ "interrupted",
1014
+ "approval_blocked",
1015
+ "failed",
1016
+ "completed",
1017
+ "stale",
1018
+ "reconnecting",
1019
+ "unavailable",
1020
+ "outcome_unknown"
1021
+ ]);
1022
+ return {
1023
+ BrowserThreadLinkSourcePresentationSchema,
1024
+ BrowserThreadLinkSchema,
1025
+ BrowserTimelineSchema,
1026
+ BrowserQueueSchema: z.object({
1027
+ kind: z.literal("queue"),
1028
+ status: QueueStatusSchema,
1029
+ entries: z.array(z.object({
1030
+ submissionId: QueuedSubmissionIdSchema,
1031
+ prompt: boundedText(16384),
1032
+ status: QueueStatusSchema,
1033
+ /**
1034
+ * The workbench operation that queued this submission, or null when
1035
+ * the workbench did not queue it. The server recovers it from the
1036
+ * submission's clientUserMessageId, which the queue port sets to the
1037
+ * serialized OperationId on every add it makes.
1038
+ */
1039
+ operationId: OperationIdSchema.nullable()
1040
+ }).strict())
1041
+ }).strict()
1042
+ };
1043
+ }
1044
+ // src/shared/browser/schemas/voice.ts
1045
+ /**
1046
+ * Builds the context delivery, coordinator, voice and voice context schemas.
1047
+ * @param identity - The session's identity schemas.
1048
+ * @returns The four schemas and the realtime session id schema they share.
1049
+ */
1050
+ function createBrowserVoiceSchemas(identity) {
1051
+ const { ItemIdSchema, ThreadIdSchema, TurnIdSchema } = identity;
1052
+ const NullableReasonSchema = optionalNullableText(512);
1053
+ const BrowserRealtimeSessionIdSchema = z.string().min(1).refine((value) => !value.includes("\0"), "NUL is not allowed").transform(parseRealtimeSessionId);
1054
+ const BrowserContextDeliverySchema = z.object({
1055
+ kind: z.literal("context_delivery"),
1056
+ threadId: ThreadIdSchema,
1057
+ delivery: DeliveryOutcomeSchema,
1058
+ capturedAtMs: TimestampSchema,
1059
+ freshUntilMs: TimestampSchema,
1060
+ reason: NullableReasonSchema
1061
+ }).strict();
1062
+ const BrowserCoordinatorSchema = z.object({
1063
+ kind: z.literal("coordinator"),
1064
+ state: z.enum([
1065
+ "unbound",
1066
+ "starting",
1067
+ "ready",
1068
+ "active",
1069
+ "reconnecting",
1070
+ "failed"
1071
+ ]),
1072
+ threadId: ThreadIdSchema.nullable(),
1073
+ activeTurnId: TurnIdSchema.nullable(),
1074
+ configuredModel: boundedText(256).nullable(),
1075
+ configuredEffort: boundedText(64).nullable(),
1076
+ model: boundedText(256).nullable(),
1077
+ effort: boundedText(64).nullable(),
1078
+ serviceTier: boundedText(64).nullable(),
1079
+ reason: NullableReasonSchema
1080
+ }).strict().superRefine((value, refinementContext) => {
1081
+ if (value.state === "unbound" && (value.threadId !== null || value.activeTurnId !== null)) refinementContext.addIssue({
1082
+ code: "custom",
1083
+ path: ["state"],
1084
+ message: "an unbound coordinator cannot publish thread or turn state"
1085
+ });
1086
+ if (value.activeTurnId !== null && value.threadId === null) refinementContext.addIssue({
1087
+ code: "custom",
1088
+ path: ["activeTurnId"],
1089
+ message: "an active coordinator turn requires a coordinator thread"
1090
+ });
1091
+ });
1092
+ const BrowserVoiceSchema = z.object({
1093
+ kind: z.literal("voice"),
1094
+ state: z.enum([
1095
+ "unavailable",
1096
+ "ready",
1097
+ "starting",
1098
+ "active",
1099
+ "recovering",
1100
+ "stopping",
1101
+ "failed"
1102
+ ]),
1103
+ realtimeSessionId: BrowserRealtimeSessionIdSchema.nullable(),
1104
+ /** Whether nobody listens live to the session, as the host's narrative says. */
1105
+ unattended: z.boolean().optional(),
1106
+ transcript: z.array(z.object({
1107
+ itemId: ItemIdSchema,
1108
+ sequence: z.number().int().nonnegative(),
1109
+ speaker: z.enum(["user", "assistant"]),
1110
+ text: boundedText(16384),
1111
+ final: z.boolean()
1112
+ }).strict()),
1113
+ delivery: DeliveryOutcomeSchema.nullable(),
1114
+ reason: NullableReasonSchema
1115
+ }).strict();
1116
+ const BrowserVoiceContextEntryBaseSchema = z.object({
1117
+ id: boundedText(2048),
1118
+ /** Who an announced context change was for, or `callback` for the agent's own news. */
1119
+ kind: z.enum([
1120
+ "voice",
1121
+ "coordinator",
1122
+ "callback"
1123
+ ]),
1124
+ /** What an announced context change is about, as its host named it. */
1125
+ topic: boundedText(256).nullable(),
1126
+ sourceOrder: z.number().int().nonnegative(),
1127
+ capturedAtMs: TimestampSchema,
1128
+ freshUntilMs: TimestampSchema,
1129
+ reason: boundedText(512).nullable(),
1130
+ /** The host's detail of why it told nothing; set only when `reason` is `withheld`. */
1131
+ withheld: boundedWireText(256).nullable(),
1132
+ body: boundedWireText(BROWSER_VOICE_CONTEXT_BODY_MAX_UTF8_BYTES)
1133
+ }).strict();
1134
+ const BrowserVoiceContextEntrySchema = z.discriminatedUnion("attempted", [BrowserVoiceContextEntryBaseSchema.extend({
1135
+ attempted: z.literal(false),
1136
+ attemptedAtMs: z.null(),
1137
+ outcome: z.literal("not_delivered")
1138
+ }), BrowserVoiceContextEntryBaseSchema.extend({
1139
+ attempted: z.literal(true),
1140
+ attemptedAtMs: TimestampSchema,
1141
+ outcome: DeliveryOutcomeSchema
1142
+ })]).superRefine((value, refinementContext) => {
1143
+ if (value.freshUntilMs < value.capturedAtMs) refinementContext.addIssue({
1144
+ code: "custom",
1145
+ path: ["freshUntilMs"],
1146
+ message: "freshness cannot end before capture"
1147
+ });
1148
+ if (value.attempted && value.attemptedAtMs < value.capturedAtMs) refinementContext.addIssue({
1149
+ code: "custom",
1150
+ path: ["attemptedAtMs"],
1151
+ message: "attempt timing and delivery outcome are incoherent"
1152
+ });
1153
+ });
1154
+ return {
1155
+ BrowserContextDeliverySchema,
1156
+ BrowserCoordinatorSchema,
1157
+ BrowserVoiceSchema,
1158
+ BrowserVoiceContextSchema: z.object({
1159
+ kind: z.literal("voice_context"),
1160
+ sessionId: BrowserRealtimeSessionIdSchema,
1161
+ ledgerId: boundedText(2048),
1162
+ canonicalBrief: boundedWireText(BROWSER_VOICE_CONTEXT_BRIEF_MAX_UTF8_BYTES),
1163
+ ownerEntriesTruncated: z.number().int().nonnegative(),
1164
+ entriesTruncated: z.number().int().nonnegative(),
1165
+ entries: z.array(BrowserVoiceContextEntrySchema).max(64)
1166
+ }).strict().superRefine((value, refinementContext) => {
1167
+ if (value.entriesTruncated < value.ownerEntriesTruncated) refinementContext.addIssue({
1168
+ code: "custom",
1169
+ path: ["entriesTruncated"],
1170
+ message: "transport omissions cannot be less than permanent owner omissions"
1171
+ });
1172
+ })
1173
+ };
1174
+ }
1175
+ // ../timing/src/shared/constants/durations.ts
1176
+ /**
1177
+ * Freeze one owner's group of durations. Each key is typed as a number, not as
1178
+ * today's value, so a caller's types never depend on how a duration is tuned,
1179
+ * and each key keeps the reason written beside it.
1180
+ * @param group The owner's durations in milliseconds, each with its reason.
1181
+ * @returns The same group, frozen.
1182
+ */
1183
+ function durations(group) {
1184
+ return Object.freeze(group);
1185
+ }
1186
+ // ../timing/src/shared/constants/codex.ts
1187
+ /** The `codex app-server` child: its restart backoff and its ordered shutdown. */
1188
+ const CODEX_PROCESS_MS = durations({
1189
+ /** Retry-delay classification. Pulls against the first restart attempt. */
1190
+ restartBase: 1e3,
1191
+ /** Retry-delay cap classification. Pulls against request settlement and the backoff ceiling. */
1192
+ restartMax: 3e4,
1193
+ /**
1194
+ * Stdin EOF grace lets the child consume drained frames before TERM and ends on closure.
1195
+ * Realtime stop, EOF and TERM leave one second of the composed cap for group absence proof.
1196
+ */
1197
+ stdinEofGrace: 1e3,
1198
+ /** TERM grace classification. Pulls against realtime stop before TERM-to-KILL escalation. */
1199
+ termGrace: 5e3,
1200
+ /**
1201
+ * How long KILL waits for the TERMed group to freeze. A group freezes in a few
1202
+ * observation polls, but a member in a killable kernel wait never reads as stopped
1203
+ * and still dies on KILL. Pulls against the absence-proof second the composed
1204
+ * shutdown cap keeps, so a freeze that cannot finish leaves time to prove the
1205
+ * killed group gone.
1206
+ */
1207
+ groupFreeze: 500,
1208
+ /** Composed-shutdown cap classification. Pulls against realtime stop, stdin EOF grace, and TERM grace. */
1209
+ composedShutdown: 1e4
1210
+ });
1211
+ /**
1212
+ * The delay before the next restart of a failed `codex app-server` child: the
1213
+ * base delay doubled once for every restart already attempted since the last
1214
+ * account-ready session, capped at the maximum.
1215
+ * @param restartAttempt Restarts already attempted since account readiness.
1216
+ * @returns The delay in milliseconds.
1217
+ */
1218
+ function codexRestartDelayMs(restartAttempt) {
1219
+ return Math.min(CODEX_PROCESS_MS.restartMax, CODEX_PROCESS_MS.restartBase * 2 ** Math.min(restartAttempt, 30));
1220
+ }
1221
+ /** Requests to the app-server session, and how often its thread state is read. */
1222
+ const CODEX_SESSION_MS = durations({
1223
+ /**
1224
+ * How long an explanation waits for the turn of a message that an idle thread took from the
1225
+ * queue by itself, before it tells the reader to look at the conversation.
1226
+ */
1227
+ explanationTurnStart: 15e3,
1228
+ /** How often an answer that Codex writes reaches the panel: a reader sees it arrive in steps. */
1229
+ explanationText: 150,
1230
+ /** Uncertainty-bound classification. Pulls against a lost non-idempotent response before `outcome_unknown`. */
1231
+ requestSettlement: 3e4,
1232
+ /**
1233
+ * Bounds dynamic wait detection latency against app-server thread status
1234
+ * reads. Request uncertainty must contain a whole number of polls so the last
1235
+ * observation cannot cross the settlement boundary.
1236
+ */
1237
+ waitTargetPoll: 250,
1238
+ /**
1239
+ * Read-amplification floor classification. Pulls against the wait-target poll
1240
+ * below and request settlement above.
1241
+ *
1242
+ * Serving a browser snapshot request re-reads the authoritative workhorse
1243
+ * queue, which is a paginated app-server call. A client is free to ask for a
1244
+ * snapshot as often as it likes, so the server coalesces concurrent re-reads and
1245
+ * will not start a new one inside this floor. It sits at or above one
1246
+ * wait-target poll, because a browser must not out-run the cadence the server
1247
+ * observes thread state at, and far below request settlement, so a person's
1248
+ * refresh still reads as immediate.
1249
+ */
1250
+ queueRereadFloor: 1e3
1251
+ });
1252
+ /**
1253
+ * The voice: its realtime start, stop, recovery and the freshness it needs, and how soon the
1254
+ * browser's voice client opens its socket again.
1255
+ */
1256
+ const CODEX_REALTIME_MS = durations({
1257
+ /** Realtime-readiness timeout classification. Pulls against permission-independent SDP/start readiness. */
1258
+ start: 15e3,
1259
+ /** Realtime-stop timeout classification. Pulls against TERM grace so realtime stops first. */
1260
+ stop: 3e3,
1261
+ /** Realtime-recovery window classification. Pulls against context freshness while reconnecting. */
1262
+ recovery: 45e3,
1263
+ /** How long an announced context change stays fresh enough to deliver. Pulls against realtime recovery. */
1264
+ contextFreshness: 3e4,
1265
+ /**
1266
+ * How long the voice client waits before opening its socket again after the
1267
+ * socket is lost, and between failed attempts after that. Pulls against the tab
1268
+ * session grace: a reload plus these redials must fit inside it, or the server
1269
+ * ends the conversation before the client is back. It is also the beat of a
1270
+ * retry, so a shorter value would hammer a server that is restarting.
1271
+ */
1272
+ clientReconnect: 3e3
1273
+ });
1274
+ /** A browser command an agent leases, and the approvals a person answers. */
1275
+ const CODEX_APPROVAL_MS = durations({
1276
+ /** Browser-command lease classification. Pulls against the public browser wait contract and approval expiry. */
1277
+ browserCommandLease: 15e4,
1278
+ /** Visual-approval expiry classification. Pulls against the browser-command lease. */
1279
+ expiry: 9e4,
1280
+ /** Spoken-approval gate expiry classification. Pulls against visual approval expiry. */
1281
+ spokenGate: 6e4
1282
+ });
1283
+ /**
1284
+ * How long a browser tab's conversation outlives its last browser socket. Pulls against a
1285
+ * reload plus CODEX_REALTIME_MS.clientReconnect redials, which it must outlast or a reload loses the
1286
+ * conversation, and CODEX_APPROVAL_MS.expiry, which it must stay under so a closed tab's approvals
1287
+ * end as "tab session ended" rather than expiring unanswered.
1288
+ */
1289
+ const TAB_SESSION_GRACE_MS = 6e4;
1290
+ // src/shared/dynamic-approval/schemas/effects.ts
1291
+ /**
1292
+ * The host domain namespace a dynamic approval belongs to. The host names it, and the server makes
1293
+ * an approval only for a call through a namespace the host registered. The namespace is part of
1294
+ * the approval identity a decision must match, so the browser checks only its shape.
1295
+ */
1296
+ const DynamicApprovalNamespaceSchema = z.string().regex(/^[a-z][a-z0-9_]{0,63}$/u);
1297
+ const DYNAMIC_APPROVAL_TOOLS = [
1298
+ "create_thread",
1299
+ "fork_thread",
1300
+ "send_message_to_thread"
1301
+ ];
1302
+ const DYNAMIC_APPROVAL_DECISIONS = ["approve", "decline"];
1303
+ const DYNAMIC_APPROVAL_STATES = [
1304
+ "pending",
1305
+ "approved",
1306
+ "declined",
1307
+ "expired",
1308
+ "cancelled",
1309
+ "disconnected",
1310
+ "stale",
1311
+ "delivered",
1312
+ "not_delivered",
1313
+ "outcome_unknown"
1314
+ ];
1315
+ const AuthorityTokenSchema = boundedText(4096);
1316
+ /**
1317
+ * Records one custom validation issue at a path.
1318
+ * @param context - The refinement context of the schema being checked.
1319
+ * @param path - Where in the value the issue sits.
1320
+ * @param message - What is wrong.
1321
+ */
1322
+ function addIssue$1(context, path, message) {
1323
+ context.addIssue({
1324
+ code: "custom",
1325
+ path,
1326
+ message
1327
+ });
1328
+ }
1329
+ /**
1330
+ * Checks that a fork starts a turn exactly when it carries a prompt, and that
1331
+ * the turn has an operation id of its own rather than reusing the mutation's.
1332
+ * @param effect - A fork effect, in either its canonical or browser form.
1333
+ * @param refinementContext - Where issues are recorded.
1334
+ */
1335
+ function validateForkInitialTurn(effect, refinementContext) {
1336
+ const prompted = effect.arguments.prompt !== null;
1337
+ if (prompted !== (effect.initialTurnOperationId !== null)) addIssue$1(refinementContext, ["initialTurnOperationId"], prompted ? "prompted fork requires an initial turn" : "unprompted fork cannot start a turn");
1338
+ if (effect.initialTurnOperationId !== null && effect.initialTurnOperationId === effect.mutationOperationId) addIssue$1(refinementContext, ["initialTurnOperationId"], "fork initial turn needs its own OperationId");
1339
+ }
1340
+ /**
1341
+ * Checks that a create effect's initial turn has an operation id of its own.
1342
+ * @param effect - An effect of any tool; only `create_thread` is checked.
1343
+ * @param refinementContext - Where issues are recorded.
1344
+ */
1345
+ function validateCreateInitialTurn(effect, refinementContext) {
1346
+ if (effect.tool === "create_thread" && effect.initialTurnOperationId === effect.mutationOperationId) addIssue$1(refinementContext, ["initialTurnOperationId"], "create initial turn needs its own OperationId");
1347
+ }
1348
+ /**
1349
+ * Checks that a browser effect's target echoes the thread its arguments name,
1350
+ * so the chat can never show one thread while the call acts on another.
1351
+ * @param effect - A fork or send effect in its browser form.
1352
+ * @param refinementContext - Where issues are recorded.
1353
+ */
1354
+ function validateTargetEcho(effect, refinementContext) {
1355
+ if (effect.target !== effect.arguments.threadId) addIssue$1(refinementContext, ["target"], `target must echo ${effect.tool === "fork_thread" ? "fork" : "send"} arguments.threadId`);
1356
+ }
1357
+ /**
1358
+ * Builds the identity and effect schemas of a dynamic approval: who is
1359
+ * calling, in which epoch and operation, and exactly what the tool would do,
1360
+ * in the canonical form the hash covers and the projected form the browser sees.
1361
+ * @param identity - The session's identity schemas.
1362
+ * @param context - The validator for the current epoch and, when present, operation ids.
1363
+ * @returns The identity schema and both effect schemas.
1364
+ */
1365
+ function createDynamicApprovalEffectSchemas(identity, context) {
1366
+ const { ChildEpochSchema, ChildIdSchema, DynamicToolCallIdSchema, OperationIdSchema, ThreadIdSchema, TurnIdSchema } = identity;
1367
+ const DynamicApprovalToolSchema = z.enum(DYNAMIC_APPROVAL_TOOLS);
1368
+ const DynamicApprovalIdentitySchema = z.object({
1369
+ child: ChildIdSchema,
1370
+ epoch: ChildEpochSchema,
1371
+ threadId: ThreadIdSchema,
1372
+ turnId: TurnIdSchema,
1373
+ callId: DynamicToolCallIdSchema,
1374
+ namespace: DynamicApprovalNamespaceSchema,
1375
+ tool: DynamicApprovalToolSchema,
1376
+ manifestHash: boundedText(256),
1377
+ operationId: OperationIdSchema
1378
+ }).strict().superRefine((value, refinementContext) => {
1379
+ try {
1380
+ context.validator.assertCurrentEpoch(value.child, value.epoch);
1381
+ } catch (error) {
1382
+ addIssue$1(refinementContext, ["epoch"], error instanceof Error ? error.message : "identity epoch is not current");
1383
+ }
1384
+ try {
1385
+ context.operation?.validator.assertCurrentOperationId(value.operationId);
1386
+ } catch (error) {
1387
+ addIssue$1(refinementContext, ["operationId"], error instanceof Error ? error.message : "identity OperationId is not current");
1388
+ }
1389
+ });
1390
+ const CreateArgumentsSchema = z.object({ prompt: boundedText(16384) }).strict();
1391
+ const ForkArgumentsSchema = z.object({
1392
+ threadId: ThreadIdSchema,
1393
+ beforeTurnId: TurnIdSchema.nullable(),
1394
+ prompt: boundedText(16384).nullable()
1395
+ }).strict();
1396
+ const SendArgumentsSchema = z.object({
1397
+ threadId: ThreadIdSchema,
1398
+ prompt: boundedText(16384)
1399
+ }).strict();
1400
+ const ForkBoundarySchema = z.union([z.object({
1401
+ relation: z.literal("self"),
1402
+ beforeTurnId: TurnIdSchema
1403
+ }).strict(), z.object({
1404
+ relation: z.literal("other"),
1405
+ beforeTurnId: TurnIdSchema.nullable()
1406
+ }).strict()]);
1407
+ return {
1408
+ DynamicApprovalIdentitySchema,
1409
+ DynamicApprovalEffectSchema: z.discriminatedUnion("tool", [
1410
+ z.object({
1411
+ tool: z.literal("create_thread"),
1412
+ arguments: CreateArgumentsSchema,
1413
+ callerAuthority: AuthorityTokenSchema,
1414
+ targetAuthority: z.null(),
1415
+ contextAuthority: AuthorityTokenSchema,
1416
+ effectiveBoundary: z.null(),
1417
+ mutationOperationId: OperationIdSchema,
1418
+ initialTurnOperationId: OperationIdSchema,
1419
+ visualSummary: boundedText(512)
1420
+ }).strict(),
1421
+ z.object({
1422
+ tool: z.literal("fork_thread"),
1423
+ arguments: ForkArgumentsSchema,
1424
+ callerAuthority: AuthorityTokenSchema,
1425
+ targetAuthority: AuthorityTokenSchema,
1426
+ contextAuthority: AuthorityTokenSchema,
1427
+ effectiveBoundary: ForkBoundarySchema,
1428
+ mutationOperationId: OperationIdSchema,
1429
+ initialTurnOperationId: OperationIdSchema.nullable(),
1430
+ visualSummary: boundedText(512)
1431
+ }).strict(),
1432
+ z.object({
1433
+ tool: z.literal("send_message_to_thread"),
1434
+ arguments: SendArgumentsSchema,
1435
+ callerAuthority: AuthorityTokenSchema,
1436
+ targetAuthority: AuthorityTokenSchema,
1437
+ contextAuthority: AuthorityTokenSchema,
1438
+ effectiveBoundary: z.null(),
1439
+ mutationOperationId: OperationIdSchema,
1440
+ initialTurnOperationId: z.null(),
1441
+ visualSummary: boundedText(512)
1442
+ }).strict()
1443
+ ]).superRefine((effect, refinementContext) => {
1444
+ validateCreateInitialTurn(effect, refinementContext);
1445
+ if (effect.tool === "fork_thread") validateForkInitialTurn(effect, refinementContext);
1446
+ }),
1447
+ BrowserDynamicApprovalEffectSchema: z.discriminatedUnion("tool", [
1448
+ z.object({
1449
+ tool: z.literal("create_thread"),
1450
+ arguments: CreateArgumentsSchema,
1451
+ target: z.null(),
1452
+ effectiveBoundary: z.null(),
1453
+ mutationOperationId: OperationIdSchema,
1454
+ initialTurnOperationId: OperationIdSchema,
1455
+ visualSummary: boundedText(512)
1456
+ }).strict(),
1457
+ z.object({
1458
+ tool: z.literal("fork_thread"),
1459
+ arguments: ForkArgumentsSchema,
1460
+ target: ThreadIdSchema,
1461
+ effectiveBoundary: ForkBoundarySchema,
1462
+ mutationOperationId: OperationIdSchema,
1463
+ initialTurnOperationId: OperationIdSchema.nullable(),
1464
+ visualSummary: boundedText(512)
1465
+ }).strict(),
1466
+ z.object({
1467
+ tool: z.literal("send_message_to_thread"),
1468
+ arguments: SendArgumentsSchema,
1469
+ target: ThreadIdSchema,
1470
+ effectiveBoundary: z.null(),
1471
+ mutationOperationId: OperationIdSchema,
1472
+ initialTurnOperationId: z.null(),
1473
+ visualSummary: boundedText(512)
1474
+ }).strict()
1475
+ ]).superRefine((effect, refinementContext) => {
1476
+ validateCreateInitialTurn(effect, refinementContext);
1477
+ if (effect.tool === "create_thread") return;
1478
+ validateTargetEcho(effect, refinementContext);
1479
+ if (effect.tool === "fork_thread") validateForkInitialTurn(effect, refinementContext);
1480
+ })
1481
+ };
1482
+ }
1483
+ // src/shared/rules/dynamic-approval-lifecycle.ts
1484
+ const APPROVAL_RELATIONS = {
1485
+ pending: [{
1486
+ decision: "none",
1487
+ cause: "none",
1488
+ delivery: "none",
1489
+ toolResult: "none",
1490
+ binding: "required",
1491
+ resumable: false
1492
+ }],
1493
+ approved: [{
1494
+ decision: "approved",
1495
+ cause: "person_approved",
1496
+ delivery: "none",
1497
+ toolResult: "none",
1498
+ binding: "none",
1499
+ resumable: false
1500
+ }],
1501
+ declined: [{
1502
+ decision: "declined",
1503
+ cause: "person_declined",
1504
+ delivery: "none",
1505
+ toolResult: "refused:approval_declined",
1506
+ binding: "none",
1507
+ resumable: false
1508
+ }],
1509
+ expired: [{
1510
+ decision: "expired",
1511
+ cause: "deadline_reached",
1512
+ delivery: "none",
1513
+ toolResult: "refused:expired",
1514
+ binding: "none",
1515
+ resumable: false
1516
+ }],
1517
+ cancelled: [
1518
+ {
1519
+ decision: "cancelled",
1520
+ cause: "call_cancelled",
1521
+ delivery: "none",
1522
+ toolResult: "approval_required",
1523
+ binding: "none",
1524
+ resumable: false
1525
+ },
1526
+ {
1527
+ decision: "cancelled",
1528
+ cause: "caller_turn_interrupted",
1529
+ delivery: "none",
1530
+ toolResult: "approval_required",
1531
+ binding: "none",
1532
+ resumable: false
1533
+ },
1534
+ {
1535
+ decision: "cancelled",
1536
+ cause: "server_shutdown",
1537
+ delivery: "none",
1538
+ toolResult: "approval_required",
1539
+ binding: "none",
1540
+ resumable: false
1541
+ }
1542
+ ],
1543
+ disconnected: [{
1544
+ decision: "disconnected",
1545
+ cause: "browser_disconnected",
1546
+ delivery: "none",
1547
+ toolResult: "approval_required",
1548
+ binding: "none",
1549
+ resumable: false
1550
+ }, {
1551
+ decision: "disconnected",
1552
+ cause: "child_disconnected",
1553
+ delivery: "not_delivered",
1554
+ toolResult: "transport_not_delivered",
1555
+ binding: "none",
1556
+ resumable: false
1557
+ }],
1558
+ stale: [
1559
+ "refused:expired",
1560
+ "refused:invalid_call",
1561
+ "refused:stale_child",
1562
+ "refused:prior_epoch",
1563
+ "refused:unknown_provenance",
1564
+ "refused:not_loaded",
1565
+ "refused:not_controllable",
1566
+ "refused:system_error",
1567
+ "refused:busy",
1568
+ "refused:cycle"
1569
+ ].map((toolResult) => ({
1570
+ decision: "approved",
1571
+ cause: "person_approved",
1572
+ delivery: "none",
1573
+ toolResult,
1574
+ binding: "none",
1575
+ resumable: false
1576
+ })),
1577
+ delivered: [{
1578
+ decision: "approved",
1579
+ cause: "person_approved",
1580
+ delivery: "delivered",
1581
+ toolResult: "none",
1582
+ binding: "none",
1583
+ resumable: false
1584
+ }],
1585
+ not_delivered: [{
1586
+ decision: "approved",
1587
+ cause: "person_approved",
1588
+ delivery: "not_delivered",
1589
+ toolResult: "transport_not_delivered",
1590
+ binding: "none",
1591
+ resumable: false
1592
+ }],
1593
+ outcome_unknown: [{
1594
+ decision: "approved",
1595
+ cause: "person_approved",
1596
+ delivery: "outcome_unknown",
1597
+ toolResult: "none",
1598
+ binding: "none",
1599
+ resumable: false
1600
+ }]
1601
+ };
1602
+ /** The relation facts, in the order they are compared. */
1603
+ const RELATION_FIELDS = [
1604
+ "decision",
1605
+ "cause",
1606
+ "delivery",
1607
+ "toolResult",
1608
+ "binding",
1609
+ "resumable"
1610
+ ];
1611
+ /**
1612
+ * Reads the decision outcome and cause an approval carries, `none` for an
1613
+ * approval that has no decision yet.
1614
+ * @param decision - The approval's decision, or null.
1615
+ * @returns The outcome and cause as relation facts.
1616
+ */
1617
+ function decisionFacts(decision) {
1618
+ return decision === null ? {
1619
+ decision: "none",
1620
+ cause: "none"
1621
+ } : {
1622
+ decision: decision.outcome,
1623
+ cause: decision.cause
1624
+ };
1625
+ }
1626
+ /**
1627
+ * Projects an approval onto the relation facts its state arm is described by.
1628
+ * @param approval - The approval record.
1629
+ * @returns The same fields an `ApprovalRelation` names, with absent values as `none`.
1630
+ */
1631
+ function relationOfApproval(approval) {
1632
+ return {
1633
+ ...decisionFacts(approval.decision),
1634
+ delivery: approval.delivery ?? "none",
1635
+ toolResult: approval.toolResult ?? "none",
1636
+ binding: approval.binding === null ? "none" : "required",
1637
+ resumable: approval.resumable
1638
+ };
1639
+ }
1640
+ /**
1641
+ * Tells whether an approval's fields match one arm of its state.
1642
+ * @param approval - The approval record.
1643
+ * @param relation - One allowed arm of the approval's state.
1644
+ * @returns True when every relation fact agrees.
1645
+ */
1646
+ function matchesApprovalRelation(approval, relation) {
1647
+ const actual = relationOfApproval(approval);
1648
+ return RELATION_FIELDS.every((field) => actual[field] === relation[field]);
1649
+ }
1650
+ /**
1651
+ * Refuses an approval whose decision, delivery, tool result, binding and
1652
+ * resumable flag do not form one of the arms its state allows.
1653
+ * @param approval - The approval record.
1654
+ * @param refinementContext - Where the issue is recorded.
1655
+ */
1656
+ function validateDynamicApprovalState(approval, refinementContext) {
1657
+ if (!APPROVAL_RELATIONS[approval.state].some((relation) => matchesApprovalRelation(approval, relation))) refinementContext.addIssue({
1658
+ code: "custom",
1659
+ path: ["state"],
1660
+ message: "decision, delivery, toolResult, binding, and resumable fields are not a valid state arm"
1661
+ });
1662
+ }
1663
+ // src/shared/dynamic-approval/schemas/browser.ts
1664
+ const EffectHashSchema$1 = z.string().regex(/^sha256:[0-9a-f]{64}$/u, "effect hash must be sha256 plus 64 lowercase hex characters");
1665
+ const ChatIdSchema = boundedText(128);
1666
+ /**
1667
+ * Records one custom validation issue at a path.
1668
+ * @param context - The refinement context of the schema being checked.
1669
+ * @param path - Where in the value the issue sits.
1670
+ * @param message - What is wrong.
1671
+ */
1672
+ function addIssue(context, path, message) {
1673
+ context.addIssue({
1674
+ code: "custom",
1675
+ path,
1676
+ message
1677
+ });
1678
+ }
1679
+ /** Every field of a dynamic approval identity; two identities are the same when all agree. */
1680
+ const IDENTITY_FIELDS = [
1681
+ "child",
1682
+ "epoch",
1683
+ "threadId",
1684
+ "turnId",
1685
+ "callId",
1686
+ "namespace",
1687
+ "tool",
1688
+ "manifestHash",
1689
+ "operationId"
1690
+ ];
1691
+ /**
1692
+ * Tells whether two approval identities name the same logical call.
1693
+ * @param left - One identity.
1694
+ * @param right - The other.
1695
+ * @returns True when every field agrees.
1696
+ */
1697
+ function sameIdentity(left, right) {
1698
+ return IDENTITY_FIELDS.every((field) => left[field] === right[field]);
1699
+ }
1700
+ /**
1701
+ * Tells whether two captured links name the same thread in the same child epoch.
1702
+ * @param left - One link.
1703
+ * @param right - The other.
1704
+ * @returns True when thread, child and epoch all agree.
1705
+ */
1706
+ function sameLink(left, right) {
1707
+ return left.threadId === right.threadId && left.childId === right.childId && left.epoch === right.epoch;
1708
+ }
1709
+ /**
1710
+ * Builds the browser-facing dynamic approval schemas: the approval record the
1711
+ * chat shows, the response command it sends back, and the pending-aware
1712
+ * response parser that refuses a response for any approval but the one it
1713
+ * was minted for.
1714
+ * @param identity - The session's identity schemas.
1715
+ * @param context - The validator that knows the current child and epoch.
1716
+ * @param effectSchemas - The effect and identity schemas the approval embeds.
1717
+ * @returns The schemas, under their canonical and coordination-era names.
1718
+ */
1719
+ function createDynamicApprovalBrowserSchemas(identity, context, effectSchemas) {
1720
+ const { BrowserDynamicApprovalEffectSchema, DynamicApprovalIdentitySchema } = effectSchemas;
1721
+ const { BrowserCommandIdSchema, ChildEpochSchema, ChildIdSchema, ThreadIdSchema } = identity;
1722
+ const DynamicApprovalStateSchema = z.enum(DYNAMIC_APPROVAL_STATES);
1723
+ const DynamicApprovalDecisionSchema = z.discriminatedUnion("outcome", [
1724
+ decision("approved", "person_approved"),
1725
+ decision("declined", "person_declined"),
1726
+ decision("expired", "deadline_reached"),
1727
+ z.object({
1728
+ outcome: z.literal("cancelled"),
1729
+ identity: DynamicApprovalIdentitySchema,
1730
+ effectHash: EffectHashSchema$1,
1731
+ decidedAtMs: NonNegativeIntegerSchema,
1732
+ cause: z.enum([
1733
+ "call_cancelled",
1734
+ "caller_turn_interrupted",
1735
+ "server_shutdown"
1736
+ ])
1737
+ }).strict(),
1738
+ z.object({
1739
+ outcome: z.literal("disconnected"),
1740
+ identity: DynamicApprovalIdentitySchema,
1741
+ effectHash: EffectHashSchema$1,
1742
+ decidedAtMs: NonNegativeIntegerSchema,
1743
+ cause: z.enum(["browser_disconnected", "child_disconnected"])
1744
+ }).strict()
1745
+ ]);
1746
+ const DynamicApprovalToolResultSchema = z.enum([
1747
+ "approval_required",
1748
+ "refused:approval_declined",
1749
+ "refused:expired",
1750
+ "refused:invalid_call",
1751
+ "refused:stale_child",
1752
+ "refused:prior_epoch",
1753
+ "refused:unknown_provenance",
1754
+ "refused:not_loaded",
1755
+ "refused:not_controllable",
1756
+ "refused:system_error",
1757
+ "refused:busy",
1758
+ "refused:cycle",
1759
+ "transport_not_delivered"
1760
+ ]);
1761
+ const DynamicApprovalLinkSchema = z.object({
1762
+ threadId: ThreadIdSchema,
1763
+ childId: ChildIdSchema,
1764
+ epoch: ChildEpochSchema
1765
+ }).strict();
1766
+ const DynamicApprovalBindingSchema = z.object({
1767
+ commandId: BrowserCommandIdSchema,
1768
+ chatId: ChatIdSchema,
1769
+ capturedLink: DynamicApprovalLinkSchema
1770
+ }).strict().superRefine((binding, refinementContext) => {
1771
+ try {
1772
+ assertCurrentTarget(context.validator, binding.capturedLink);
1773
+ } catch (error) {
1774
+ addIssue(refinementContext, ["capturedLink", "epoch"], error instanceof Error ? error.message : "captured link is not current");
1775
+ }
1776
+ });
1777
+ const BrowserDynamicApprovalSchema = z.object({
1778
+ kind: z.literal("dynamic_approval"),
1779
+ state: DynamicApprovalStateSchema,
1780
+ identity: DynamicApprovalIdentitySchema,
1781
+ effect: BrowserDynamicApprovalEffectSchema,
1782
+ effectHash: EffectHashSchema$1,
1783
+ createdAtMs: NonNegativeIntegerSchema,
1784
+ expiresAtMs: NonNegativeIntegerSchema,
1785
+ decision: DynamicApprovalDecisionSchema.nullable(),
1786
+ delivery: z.enum([
1787
+ "delivered",
1788
+ "not_delivered",
1789
+ "outcome_unknown"
1790
+ ]).nullable(),
1791
+ toolResult: DynamicApprovalToolResultSchema.nullable(),
1792
+ binding: DynamicApprovalBindingSchema.nullable(),
1793
+ resumable: z.literal(false)
1794
+ }).strict().superRefine((approval, refinementContext) => {
1795
+ validateIdentityAndBrowserEffect(approval.identity, approval.effect, refinementContext);
1796
+ const window = approval.expiresAtMs - approval.createdAtMs;
1797
+ if (window <= 0 || window > CODEX_APPROVAL_MS.expiry) addIssue(refinementContext, ["expiresAtMs"], `approval expiry must be after creation and at most ${CODEX_APPROVAL_MS.expiry}ms after it`);
1798
+ validateDecisionEcho(approval.identity, approval.effectHash, approval.decision, refinementContext);
1799
+ validateDynamicApprovalState(approval, refinementContext);
1800
+ });
1801
+ const BrowserDynamicApprovalResponseSchema = z.object({
1802
+ kind: z.literal("browser_command"),
1803
+ command: z.literal("dynamicApprovalRespond"),
1804
+ commandId: BrowserCommandIdSchema,
1805
+ chatId: ChatIdSchema,
1806
+ childId: ChildIdSchema,
1807
+ epoch: ChildEpochSchema,
1808
+ capturedLink: DynamicApprovalLinkSchema,
1809
+ identity: DynamicApprovalIdentitySchema,
1810
+ effectHash: EffectHashSchema$1,
1811
+ decision: z.enum(DYNAMIC_APPROVAL_DECISIONS)
1812
+ }).strict().superRefine((response, refinementContext) => {
1813
+ try {
1814
+ assertCurrentTarget(context.validator, response);
1815
+ } catch (error) {
1816
+ addIssue(refinementContext, ["epoch"], error instanceof Error ? error.message : "response target is not current");
1817
+ }
1818
+ validateResponseBinding(response, refinementContext);
1819
+ });
1820
+ /**
1821
+ * Builds the response schema for one pending approval, so a response is
1822
+ * accepted only when its lease, chat, link, identity and effect hash all
1823
+ * match the approval the chat was shown.
1824
+ * @param pending - The approval record, parsed again so a caller cannot hand in a forgery.
1825
+ * @returns The response schema narrowed to that approval.
1826
+ * @throws {Error} When the approval is not pending or has no binding.
1827
+ */
1828
+ const createDynamicApprovalResponseSchema = (pending) => {
1829
+ const pendingApproval = BrowserDynamicApprovalSchema.parse(pending);
1830
+ if (pendingApproval.state !== "pending" || pendingApproval.binding === null) throw new Error("dynamic approval response requires a pending approval with a binding");
1831
+ const { binding } = pendingApproval;
1832
+ return BrowserDynamicApprovalResponseSchema.superRefine((response, refinementContext) => {
1833
+ if (response.commandId !== binding.commandId) addIssue(refinementContext, ["commandId"], "response command lease does not match pending approval");
1834
+ if (response.chatId !== binding.chatId) addIssue(refinementContext, ["chatId"], "response chat does not match pending approval");
1835
+ if (!sameLink(response.capturedLink, binding.capturedLink)) addIssue(refinementContext, ["capturedLink"], "response link does not match pending approval");
1836
+ if (!sameIdentity(response.identity, pendingApproval.identity)) addIssue(refinementContext, ["identity"], "response identity does not match pending approval");
1837
+ if (response.effectHash !== pendingApproval.effectHash) addIssue(refinementContext, ["effectHash"], "response effectHash does not match pending approval");
1838
+ });
1839
+ };
1840
+ /**
1841
+ * Parses a response against the pending approval it answers.
1842
+ * @param pending - The approval record.
1843
+ * @param response - The untrusted response command.
1844
+ * @returns The validated response.
1845
+ */
1846
+ const parseDynamicApprovalResponse = (pending, response) => createDynamicApprovalResponseSchema(pending).parse(response);
1847
+ /**
1848
+ * Checks that a response's identity and captured link are bound to the
1849
+ * child epoch it names and that the link does not retarget the caller.
1850
+ * @param response - The parsed response command.
1851
+ * @param refinementContext - Where issues are recorded.
1852
+ */
1853
+ function validateResponseBinding(response, refinementContext) {
1854
+ if (response.identity.child !== response.childId || response.identity.epoch !== response.epoch) addIssue(refinementContext, ["identity"], "response identity does not match current child epoch");
1855
+ if (response.capturedLink.childId !== response.childId || response.capturedLink.epoch !== response.epoch) addIssue(refinementContext, ["capturedLink"], "captured link is not bound to current child epoch");
1856
+ if (response.capturedLink.threadId !== response.identity.threadId) addIssue(refinementContext, ["capturedLink", "threadId"], "captured link cannot retarget the caller");
1857
+ }
1858
+ /**
1859
+ * A terminal decision arm for one outcome and the single cause that produces it.
1860
+ * @param outcome - The decision outcome.
1861
+ * @param cause - The cause that outcome always carries.
1862
+ * @returns The strict decision schema.
1863
+ */
1864
+ function decision(outcome, cause) {
1865
+ return z.object({
1866
+ outcome: z.literal(outcome),
1867
+ identity: DynamicApprovalIdentitySchema,
1868
+ effectHash: EffectHashSchema$1,
1869
+ decidedAtMs: NonNegativeIntegerSchema,
1870
+ cause: z.literal(cause)
1871
+ }).strict();
1872
+ }
1873
+ /**
1874
+ * Checks that the effect the chat is shown belongs to the logical call in
1875
+ * the identity: same tool, same operation, and a target that echoes the
1876
+ * arguments rather than pointing somewhere else.
1877
+ * @param approvalIdentity - The logical call the approval is for.
1878
+ * @param approvalEffect - The effect as projected for the browser.
1879
+ * @param refinementContext - Where issues are recorded.
1880
+ */
1881
+ function validateIdentityAndBrowserEffect(approvalIdentity, approvalEffect, refinementContext) {
1882
+ if (approvalIdentity.tool !== approvalEffect.tool) addIssue(refinementContext, ["effect", "tool"], "effect tool does not match logical call tool");
1883
+ if (approvalIdentity.operationId !== approvalEffect.mutationOperationId) addIssue(refinementContext, ["effect", "mutationOperationId"], "mutation OperationId is not the call OperationId");
1884
+ if (approvalEffect.tool === "create_thread") return;
1885
+ if (approvalEffect.target !== approvalEffect.arguments.threadId) addIssue(refinementContext, ["effect", "target"], "target must echo effect arguments");
1886
+ if (approvalEffect.tool === "fork_thread") validateForkBoundary(approvalIdentity, approvalEffect, refinementContext);
1887
+ }
1888
+ /**
1889
+ * Checks a fork's effective boundary against its relation to the caller: a
1890
+ * self fork targets the caller at the caller's turn, any other fork targets
1891
+ * another thread at the turn its arguments named.
1892
+ * @param approvalIdentity - The logical call the approval is for.
1893
+ * @param approvalEffect - A fork effect.
1894
+ * @param refinementContext - Where issues are recorded.
1895
+ */
1896
+ function validateForkBoundary(approvalIdentity, approvalEffect, refinementContext) {
1897
+ if (approvalEffect.effectiveBoundary.relation === "self") {
1898
+ if (approvalEffect.arguments.threadId !== approvalIdentity.threadId) addIssue(refinementContext, [
1899
+ "effect",
1900
+ "arguments",
1901
+ "threadId"
1902
+ ], "self fork must target its caller");
1903
+ if (approvalEffect.effectiveBoundary.beforeTurnId !== approvalIdentity.turnId) addIssue(refinementContext, ["effect", "effectiveBoundary"], "self fork boundary must be caller turn");
1904
+ return;
1905
+ }
1906
+ if (approvalEffect.arguments.threadId === approvalIdentity.threadId) addIssue(refinementContext, ["effect", "effectiveBoundary"], "other fork cannot target its caller");
1907
+ if (approvalEffect.effectiveBoundary.beforeTurnId !== approvalEffect.arguments.beforeTurnId) addIssue(refinementContext, ["effect", "effectiveBoundary"], "fork boundary must echo beforeTurnId");
1908
+ }
1909
+ /**
1910
+ * Checks that a terminal decision echoes the approval it settles, so a
1911
+ * decision can never be replayed onto another approval.
1912
+ * @param approvalIdentity - The logical call the approval is for.
1913
+ * @param approvalEffectHash - The approval's effect hash.
1914
+ * @param decisionValue - The decision, or null while the approval is open.
1915
+ * @param refinementContext - Where issues are recorded.
1916
+ */
1917
+ function validateDecisionEcho(approvalIdentity, approvalEffectHash, decisionValue, refinementContext) {
1918
+ if (decisionValue === null) return;
1919
+ if (!sameIdentity(decisionValue.identity, approvalIdentity)) addIssue(refinementContext, ["decision", "identity"], "terminal decision must echo the full identity");
1920
+ if (decisionValue.effectHash !== approvalEffectHash) addIssue(refinementContext, ["decision", "effectHash"], "terminal decision must echo effectHash");
1921
+ }
1922
+ return {
1923
+ DynamicApprovalStateSchema,
1924
+ DynamicApprovalDecisionSchema,
1925
+ DynamicApprovalToolResultSchema,
1926
+ DynamicApprovalBindingSchema,
1927
+ DynamicApprovalLinkSchema,
1928
+ BrowserDynamicApprovalSchema,
1929
+ BrowserDynamicApprovalResponseSchema,
1930
+ createDynamicApprovalResponseSchema,
1931
+ parseDynamicApprovalResponse,
1932
+ createPendingDynamicApprovalResponseSchema: createDynamicApprovalResponseSchema,
1933
+ parsePendingDynamicApprovalResponse: parseDynamicApprovalResponse,
1934
+ DynamicApprovalResponseSchema: BrowserDynamicApprovalResponseSchema,
1935
+ BrowserDynamicApprovalResponseCommandSchema: BrowserDynamicApprovalResponseSchema,
1936
+ DynamicCoordinationApprovalStateSchema: DynamicApprovalStateSchema,
1937
+ DynamicCoordinationApprovalResponseSchema: BrowserDynamicApprovalResponseSchema,
1938
+ createDynamicCoordinationApprovalResponseSchema: createDynamicApprovalResponseSchema,
1939
+ parseDynamicCoordinationApprovalResponse: parseDynamicApprovalResponse,
1940
+ BrowserDynamicCoordinationApprovalSchema: BrowserDynamicApprovalSchema
1941
+ };
1942
+ }
1943
+ // src/shared/rules/dynamic-approval-hash.ts
1944
+ const ROUND_CONSTANTS = [
1945
+ 1116352408,
1946
+ 1899447441,
1947
+ 3049323471,
1948
+ 3921009573,
1949
+ 961987163,
1950
+ 1508970993,
1951
+ 2453635748,
1952
+ 2870763221,
1953
+ 3624381080,
1954
+ 310598401,
1955
+ 607225278,
1956
+ 1426881987,
1957
+ 1925078388,
1958
+ 2162078206,
1959
+ 2614888103,
1960
+ 3248222580,
1961
+ 3835390401,
1962
+ 4022224774,
1963
+ 264347078,
1964
+ 604807628,
1965
+ 770255983,
1966
+ 1249150122,
1967
+ 1555081692,
1968
+ 1996064986,
1969
+ 2554220882,
1970
+ 2821834349,
1971
+ 2952996808,
1972
+ 3210313671,
1973
+ 3336571891,
1974
+ 3584528711,
1975
+ 113926993,
1976
+ 338241895,
1977
+ 666307205,
1978
+ 773529912,
1979
+ 1294757372,
1980
+ 1396182291,
1981
+ 1695183700,
1982
+ 1986661051,
1983
+ 2177026350,
1984
+ 2456956037,
1985
+ 2730485921,
1986
+ 2820302411,
1987
+ 3259730800,
1988
+ 3345764771,
1989
+ 3516065817,
1990
+ 3600352804,
1991
+ 4094571909,
1992
+ 275423344,
1993
+ 430227734,
1994
+ 506948616,
1995
+ 659060556,
1996
+ 883997877,
1997
+ 958139571,
1998
+ 1322822218,
1999
+ 1537002063,
2000
+ 1747873779,
2001
+ 1955562222,
2002
+ 2024104815,
2003
+ 2227730452,
2004
+ 2361852424,
2005
+ 2428436474,
2006
+ 2756734187,
2007
+ 3204031479,
2008
+ 3329325298
2009
+ ];
2010
+ /**
2011
+ * Rotates a 32-bit word right, the SHA-256 primitive.
2012
+ * @param value - The word.
2013
+ * @param amount - How many bits to rotate by.
2014
+ * @returns The rotated word.
2015
+ */
2016
+ function rotateRight(value, amount) {
2017
+ return value >>> amount | value << 32 - amount;
2018
+ }
2019
+ /**
2020
+ * Hashes canonical compact JSON without making the shared browser model Node-only.
2021
+ * @param value - The text to hash, encoded as UTF-8.
2022
+ * @returns The digest as sixty-four lowercase hexadecimal characters.
2023
+ */
2024
+ function sha256(value) {
2025
+ const input = new TextEncoder().encode(value);
2026
+ const blockCount = Math.ceil((input.byteLength + 9) / 64);
2027
+ const padded = new Uint8Array(blockCount * 64);
2028
+ padded.set(input);
2029
+ padded[input.byteLength] = 128;
2030
+ const view = new DataView(padded.buffer);
2031
+ const bitLength = input.byteLength * 8;
2032
+ view.setUint32(padded.byteLength - 4, bitLength, false);
2033
+ let h0 = 1779033703;
2034
+ let h1 = 3144134277;
2035
+ let h2 = 1013904242;
2036
+ let h3 = 2773480762;
2037
+ let h4 = 1359893119;
2038
+ let h5 = 2600822924;
2039
+ let h6 = 528734635;
2040
+ let h7 = 1541459225;
2041
+ for (let offset = 0; offset < padded.byteLength; offset += 64) {
2042
+ const words = /* @__PURE__ */ new Uint32Array(64);
2043
+ for (let index = 0; index < 16; index++) words[index] = view.getUint32(offset + index * 4, false);
2044
+ for (let index = 16; index < 64; index++) {
2045
+ const first = words[index - 15];
2046
+ const second = words[index - 2];
2047
+ const smallSigma0 = rotateRight(first, 7) ^ rotateRight(first, 18) ^ first >>> 3;
2048
+ const smallSigma1 = rotateRight(second, 17) ^ rotateRight(second, 19) ^ second >>> 10;
2049
+ words[index] = words[index - 16] + smallSigma0 + words[index - 7] + smallSigma1 >>> 0;
2050
+ }
2051
+ let a = h0;
2052
+ let b = h1;
2053
+ let c = h2;
2054
+ let d = h3;
2055
+ let e = h4;
2056
+ let f = h5;
2057
+ let g = h6;
2058
+ let h = h7;
2059
+ for (let index = 0; index < 64; index++) {
2060
+ const bigSigma1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);
2061
+ const choice = e & f ^ ~e & g;
2062
+ const temporary1 = h + bigSigma1 + choice + ROUND_CONSTANTS[index] + words[index] >>> 0;
2063
+ const temporary2 = (rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
2064
+ h = g;
2065
+ g = f;
2066
+ f = e;
2067
+ e = d + temporary1 >>> 0;
2068
+ d = c;
2069
+ c = b;
2070
+ b = a;
2071
+ a = temporary1 + temporary2 >>> 0;
2072
+ }
2073
+ h0 = h0 + a >>> 0;
2074
+ h1 = h1 + b >>> 0;
2075
+ h2 = h2 + c >>> 0;
2076
+ h3 = h3 + d >>> 0;
2077
+ h4 = h4 + e >>> 0;
2078
+ h5 = h5 + f >>> 0;
2079
+ h6 = h6 + g >>> 0;
2080
+ h7 = h7 + h >>> 0;
2081
+ }
2082
+ return [
2083
+ h0,
2084
+ h1,
2085
+ h2,
2086
+ h3,
2087
+ h4,
2088
+ h5,
2089
+ h6,
2090
+ h7
2091
+ ].map((word) => word.toString(16).padStart(8, "0")).join("");
2092
+ }
2093
+ /**
2094
+ * Spells the effect hash of a canonical effect body.
2095
+ * @param value - The canonical compact JSON of the effect.
2096
+ * @returns The `sha256:`-prefixed digest.
2097
+ */
2098
+ function effectHashFor(value) {
2099
+ return `sha256:${sha256(value)}`;
2100
+ }
2101
+ // src/shared/dynamic-approval/schemas/approval.ts
2102
+ const EffectHashSchema = z.string().regex(/^sha256:[0-9a-f]{64}$/u, "effect hash must be sha256 plus 64 lowercase hex characters");
2103
+ /**
2104
+ * Hashes the canonical JSON of an approval, the value both server and browser
2105
+ * must agree on before a decision may be applied.
2106
+ * @param value - The canonical compact JSON.
2107
+ * @returns The `sha256:`-prefixed digest.
2108
+ */
2109
+ function dynamicApprovalHashForCanonicalJson(value) {
2110
+ return effectHashFor(value);
2111
+ }
2112
+ /**
2113
+ * Rebuilds a tool's arguments with only its known fields in a fixed order, so
2114
+ * the canonical JSON is the same however the input object was assembled.
2115
+ * @param argumentsValue - The arguments of any of the three tools.
2116
+ * @returns An equivalent object with the fields in canonical order.
2117
+ */
2118
+ function canonicalArguments(argumentsValue) {
2119
+ if ("beforeTurnId" in argumentsValue) return {
2120
+ threadId: argumentsValue.threadId,
2121
+ beforeTurnId: argumentsValue.beforeTurnId,
2122
+ prompt: argumentsValue.prompt
2123
+ };
2124
+ if ("threadId" in argumentsValue) return {
2125
+ threadId: argumentsValue.threadId,
2126
+ prompt: argumentsValue.prompt
2127
+ };
2128
+ return { prompt: argumentsValue.prompt };
2129
+ }
2130
+ /**
2131
+ * Rebuilds a fork boundary with its fields in canonical order.
2132
+ * @param boundary - The effective boundary, null for tools without one.
2133
+ * @returns An equivalent boundary, or null.
2134
+ */
2135
+ function canonicalBoundary(boundary) {
2136
+ if (boundary === null) return null;
2137
+ if (boundary.relation === "self") return {
2138
+ relation: "self",
2139
+ beforeTurnId: boundary.beforeTurnId
2140
+ };
2141
+ return {
2142
+ relation: "other",
2143
+ beforeTurnId: boundary.beforeTurnId
2144
+ };
2145
+ }
2146
+ /**
2147
+ * Checks that the canonical effect belongs to the logical call in the
2148
+ * identity: same tool, same operation, and for a fork a boundary that agrees
2149
+ * with its relation to the caller.
2150
+ * @param approvalIdentity - The logical call the approval is for.
2151
+ * @param approvalEffect - The canonical effect.
2152
+ * @param refinementContext - Where issues are recorded.
2153
+ */
2154
+ function validateIdentityAndEffect(approvalIdentity, approvalEffect, refinementContext) {
2155
+ if (approvalIdentity.tool !== approvalEffect.tool) refinementContext.addIssue({
2156
+ code: "custom",
2157
+ path: ["effect", "tool"],
2158
+ message: "effect tool does not match logical call tool"
2159
+ });
2160
+ if (approvalIdentity.operationId !== approvalEffect.mutationOperationId) refinementContext.addIssue({
2161
+ code: "custom",
2162
+ path: ["effect", "mutationOperationId"],
2163
+ message: "mutation OperationId must be the call OperationId"
2164
+ });
2165
+ if (approvalEffect.tool === "fork_thread") validateForkRelation(approvalIdentity, approvalEffect, refinementContext);
2166
+ }
2167
+ /**
2168
+ * Checks a fork's effective boundary against its relation to the caller: a
2169
+ * self fork targets the caller at the caller's turn, any other fork targets
2170
+ * another thread at the turn its arguments named.
2171
+ * @param approvalIdentity - The logical call the approval is for.
2172
+ * @param approvalEffect - A canonical fork effect.
2173
+ * @param refinementContext - Where issues are recorded.
2174
+ */
2175
+ function validateForkRelation(approvalIdentity, approvalEffect, refinementContext) {
2176
+ if (approvalEffect.effectiveBoundary.relation === "self") {
2177
+ if (approvalEffect.arguments.threadId !== approvalIdentity.threadId) refinementContext.addIssue({
2178
+ code: "custom",
2179
+ path: [
2180
+ "effect",
2181
+ "arguments",
2182
+ "threadId"
2183
+ ],
2184
+ message: "self fork must target its caller"
2185
+ });
2186
+ if (approvalEffect.effectiveBoundary.beforeTurnId !== approvalIdentity.turnId) refinementContext.addIssue({
2187
+ code: "custom",
2188
+ path: ["effect", "effectiveBoundary"],
2189
+ message: "self fork boundary must be caller turn"
2190
+ });
2191
+ } else {
2192
+ if (approvalEffect.arguments.threadId === approvalIdentity.threadId) refinementContext.addIssue({
2193
+ code: "custom",
2194
+ path: ["effect", "effectiveBoundary"],
2195
+ message: "other fork cannot target its caller"
2196
+ });
2197
+ if (approvalEffect.effectiveBoundary.beforeTurnId !== approvalEffect.arguments.beforeTurnId) refinementContext.addIssue({
2198
+ code: "custom",
2199
+ path: ["effect", "effectiveBoundary"],
2200
+ message: "fork boundary must echo beforeTurnId"
2201
+ });
2202
+ }
2203
+ }
2204
+ /**
2205
+ * Spells an approval's identity and effect as compact JSON with every field
2206
+ * in a fixed order, the text the effect hash is computed over.
2207
+ * @param input - The identity and canonical effect.
2208
+ * @returns The canonical JSON.
2209
+ */
2210
+ function canonicalDynamicApprovalJson(input) {
2211
+ const { identity: approvalIdentity, effect: approvalEffect } = input;
2212
+ return JSON.stringify({
2213
+ identity: {
2214
+ child: approvalIdentity.child,
2215
+ epoch: approvalIdentity.epoch,
2216
+ threadId: approvalIdentity.threadId,
2217
+ turnId: approvalIdentity.turnId,
2218
+ callId: approvalIdentity.callId,
2219
+ namespace: approvalIdentity.namespace,
2220
+ tool: approvalIdentity.tool,
2221
+ manifestHash: approvalIdentity.manifestHash,
2222
+ operationId: approvalIdentity.operationId
2223
+ },
2224
+ effect: {
2225
+ tool: approvalEffect.tool,
2226
+ arguments: canonicalArguments(approvalEffect.arguments),
2227
+ callerAuthority: approvalEffect.callerAuthority,
2228
+ targetAuthority: approvalEffect.targetAuthority,
2229
+ contextAuthority: approvalEffect.contextAuthority,
2230
+ effectiveBoundary: canonicalBoundary(approvalEffect.effectiveBoundary),
2231
+ mutationOperationId: approvalEffect.mutationOperationId,
2232
+ initialTurnOperationId: approvalEffect.initialTurnOperationId,
2233
+ visualSummary: approvalEffect.visualSummary
2234
+ }
2235
+ });
2236
+ }
2237
+ /**
2238
+ * The canonical JSON of a parsed identity and effect, ready to hash.
2239
+ * @param approvalIdentity - The parsed identity.
2240
+ * @param approvalEffect - The parsed canonical effect.
2241
+ * @returns The canonical JSON.
2242
+ */
2243
+ function canonicalHashInput(approvalIdentity, approvalEffect) {
2244
+ return canonicalDynamicApprovalJson({
2245
+ identity: approvalIdentity,
2246
+ effect: approvalEffect
2247
+ });
2248
+ }
2249
+ /**
2250
+ * Builds every dynamic approval schema: the canonical request the server
2251
+ * validates and hashes, the effect and identity schemas it embeds, and the
2252
+ * browser-facing record and response schemas.
2253
+ * @param identity - The session's identity schemas.
2254
+ * @param context - The validator for the current epoch and, when present, operation ids.
2255
+ * @returns The schemas plus the canonical JSON and hashing helpers.
2256
+ */
2257
+ function createDynamicApprovalSchemas(identity, context) {
2258
+ const effectSchemas = createDynamicApprovalEffectSchemas(identity, context);
2259
+ const { DynamicApprovalIdentitySchema, DynamicApprovalEffectSchema } = effectSchemas;
2260
+ const DynamicApprovalRequestSchema = z.object({
2261
+ kind: z.literal("dynamic_approval_request"),
2262
+ identity: DynamicApprovalIdentitySchema,
2263
+ effect: DynamicApprovalEffectSchema,
2264
+ effectHash: EffectHashSchema,
2265
+ createdAtMs: NonNegativeIntegerSchema,
2266
+ expiresAtMs: NonNegativeIntegerSchema
2267
+ }).strict().superRefine((request, refinementContext) => {
2268
+ validateIdentityAndEffect(request.identity, request.effect, refinementContext);
2269
+ const window = request.expiresAtMs - request.createdAtMs;
2270
+ if (window <= 0 || window > CODEX_APPROVAL_MS.expiry) refinementContext.addIssue({
2271
+ code: "custom",
2272
+ path: ["expiresAtMs"],
2273
+ message: `expiry must be after creation and at most ${CODEX_APPROVAL_MS.expiry}ms after it`
2274
+ });
2275
+ if (request.effectHash !== effectHashFor(canonicalHashInput(request.identity, request.effect))) refinementContext.addIssue({
2276
+ code: "custom",
2277
+ path: ["effectHash"],
2278
+ message: "effectHash does not match identity and effect"
2279
+ });
2280
+ });
2281
+ const browserSchemas = createDynamicApprovalBrowserSchemas(identity, context, effectSchemas);
2282
+ return {
2283
+ ...effectSchemas,
2284
+ ...browserSchemas,
2285
+ DynamicApprovalRequestSchema,
2286
+ DynamicCoordinationApprovalRequestSchema: DynamicApprovalRequestSchema,
2287
+ canonicalDynamicApprovalJson,
2288
+ dynamicApprovalHashForCanonicalJson,
2289
+ /**
2290
+ * Computes the effect hash a request must carry for this identity and effect.
2291
+ * @param input - The request being hashed.
2292
+ * @param input.identity - The parsed identity.
2293
+ * @param input.effect - The parsed canonical effect.
2294
+ * @returns The `sha256:`-prefixed digest.
2295
+ */
2296
+ effectHashForRequest: (input) => effectHashFor(canonicalHashInput(input.identity, input.effect))
2297
+ };
2298
+ }
2299
+ // src/shared/browser/schemas/spoken-approval.ts
2300
+ const BROWSER_SPOKEN_APPROVAL_STATES = Object.freeze([
2301
+ "idle",
2302
+ "armed",
2303
+ "resolving",
2304
+ "settled",
2305
+ "expired",
2306
+ "visual_fallback",
2307
+ "outcome_unknown",
2308
+ "stale_session"
2309
+ ]);
2310
+ const BROWSER_SPOKEN_APPROVAL_REASONS = Object.freeze([
2311
+ "approval_unavailable",
2312
+ "not_eligible",
2313
+ "coordinator_unavailable",
2314
+ "realtime_unavailable",
2315
+ "invalid_context",
2316
+ "invalid_effect_prompt",
2317
+ "user_already_spoke",
2318
+ "missing_user_final",
2319
+ "assistant_only",
2320
+ "ambiguous",
2321
+ "changed_effect",
2322
+ "stale_realtime_session",
2323
+ "stale_state",
2324
+ "timeout",
2325
+ "classifier_lost",
2326
+ "resolver_lost",
2327
+ "child_exit",
2328
+ "disposed"
2329
+ ]);
2330
+ const BROWSER_IDLE_SPOKEN_APPROVAL = Object.freeze({
2331
+ kind: "spoken_approval",
2332
+ state: "idle",
2333
+ approval: null,
2334
+ gate: null,
2335
+ capturedUserFinal: null,
2336
+ settlement: null,
2337
+ reason: null
2338
+ });
2339
+ /** The states that only exist for one exact approval and gate. */
2340
+ const CORE_STATES = /* @__PURE__ */ new Set([
2341
+ "armed",
2342
+ "resolving",
2343
+ "settled",
2344
+ "expired",
2345
+ "outcome_unknown"
2346
+ ]);
2347
+ /** The states that have already captured the user's final spoken item. */
2348
+ const CAPTURED_STATES = /* @__PURE__ */ new Set([
2349
+ "resolving",
2350
+ "settled",
2351
+ "outcome_unknown"
2352
+ ]);
2353
+ /** The states in which no fallback reason may be shown. */
2354
+ const LIVE_STATES = /* @__PURE__ */ new Set([
2355
+ "armed",
2356
+ "resolving",
2357
+ "settled"
2358
+ ]);
2359
+ /** The reasons that mean the spoken session no longer describes this approval. */
2360
+ const STALE_REASONS = /* @__PURE__ */ new Set([
2361
+ "changed_effect",
2362
+ "stale_realtime_session",
2363
+ "stale_state"
2364
+ ]);
2365
+ /**
2366
+ * Tells whether the resolver's outcome is unknown: no settlement, or one
2367
+ * whose delivery outcome is itself unknown.
2368
+ * @param value - The spoken approval.
2369
+ * @returns True when no settled outcome is known.
2370
+ */
2371
+ function resolverOutcomeUnknown(value) {
2372
+ return value.settlement === null || value.settlement.outcome === "outcome_unknown";
2373
+ }
2374
+ /**
2375
+ * Tells whether a state that requires the exact approval, gate and captured
2376
+ * user item lacks any of them.
2377
+ * @param value - The spoken approval.
2378
+ * @returns True when any of the three is missing.
2379
+ */
2380
+ function lacksResolverIdentity(value) {
2381
+ return value.approval === null || value.gate === null || value.capturedUserFinal === null;
2382
+ }
2383
+ /**
2384
+ * The rule an idle approval must satisfy: it retains nothing.
2385
+ * @param value - The spoken approval.
2386
+ * @returns True when any request state is still present.
2387
+ */
2388
+ function idleRetainsState(value) {
2389
+ return value.approval !== null || value.gate !== null || value.capturedUserFinal !== null || value.settlement !== null || value.reason !== null;
2390
+ }
2391
+ /** The rules a non-idle spoken approval must satisfy, in the order their issues are reported. */
2392
+ const SPOKEN_APPROVAL_RULES = [
2393
+ {
2394
+ /**
2395
+ * Broken when a core state lacks its approval or gate.
2396
+ * @param value - The spoken approval.
2397
+ * @returns True when a core state lacks its approval or gate.
2398
+ */
2399
+ broken: (value) => CORE_STATES.has(value.state) && (value.approval === null || value.gate === null),
2400
+ path: ["state"],
2401
+ message: "this spoken approval state requires an exact approval and gate identity"
2402
+ },
2403
+ {
2404
+ /**
2405
+ * Broken when a captured state has no captured user item.
2406
+ * @param value - The spoken approval.
2407
+ * @returns True when a captured state has no captured user item.
2408
+ */
2409
+ broken: (value) => CAPTURED_STATES.has(value.state) && value.capturedUserFinal === null,
2410
+ path: ["capturedUserFinal"],
2411
+ message: "this spoken approval state requires the exact captured final user item"
2412
+ },
2413
+ {
2414
+ /**
2415
+ * Broken when an armed approval already holds a captured user item.
2416
+ * @param value - The spoken approval.
2417
+ * @returns True when an armed approval already holds a captured user item.
2418
+ */
2419
+ broken: (value) => value.state === "armed" && value.capturedUserFinal !== null,
2420
+ path: ["capturedUserFinal"],
2421
+ message: "an armed spoken approval has not captured its user item yet"
2422
+ },
2423
+ {
2424
+ /**
2425
+ * Broken when a settled approval has no settlement.
2426
+ * @param value - The spoken approval.
2427
+ * @returns True when a settled approval has no settlement.
2428
+ */
2429
+ broken: (value) => value.state === "settled" && value.settlement === null,
2430
+ path: ["settlement"],
2431
+ message: "a settled spoken approval requires its ordinary approval settlement"
2432
+ },
2433
+ {
2434
+ /**
2435
+ * Broken when an expired approval has a reason other than the timeout.
2436
+ * @param value - The spoken approval.
2437
+ * @returns True when an expired approval has a reason other than the timeout.
2438
+ */
2439
+ broken: (value) => value.state === "expired" && value.reason !== "timeout",
2440
+ path: ["reason"],
2441
+ message: "only the runtime timeout reason produces an expired spoken approval"
2442
+ },
2443
+ {
2444
+ /**
2445
+ * Broken when an unknown outcome is not a lost resolver without a known settlement.
2446
+ * @param value - The spoken approval.
2447
+ * @returns True when an unknown outcome is not a lost resolver without a known settlement.
2448
+ */
2449
+ broken: (value) => value.state === "outcome_unknown" && (value.reason !== "resolver_lost" || !resolverOutcomeUnknown(value)),
2450
+ path: ["reason"],
2451
+ message: "only a lost resolver result without a known settlement produces an unknown spoken outcome"
2452
+ },
2453
+ {
2454
+ /**
2455
+ * Broken when a stale session has a reason that is not a mismatch.
2456
+ * @param value - The spoken approval.
2457
+ * @returns True when a stale session has a reason that is not a mismatch.
2458
+ */
2459
+ broken: (value) => value.state === "stale_session" && (value.reason === null || !STALE_REASONS.has(value.reason)),
2460
+ path: ["reason"],
2461
+ message: "a stale spoken approval requires an identity or realtime mismatch"
2462
+ },
2463
+ {
2464
+ /**
2465
+ * Broken when the timeout reason is shown in a state other than expired.
2466
+ * @param value - The spoken approval.
2467
+ * @returns True when the timeout reason is shown in a state other than expired.
2468
+ */
2469
+ broken: (value) => value.reason === "timeout" && value.state !== "expired",
2470
+ path: ["state"],
2471
+ message: "the runtime timeout reason must be presented as expired"
2472
+ },
2473
+ {
2474
+ /**
2475
+ * Broken when a lost resolver with no known settlement is not shown as outcome unknown.
2476
+ * @param value - The spoken approval.
2477
+ * @returns True when a lost resolver with no known settlement is not shown as outcome unknown.
2478
+ */
2479
+ broken: (value) => value.reason === "resolver_lost" && resolverOutcomeUnknown(value) && value.state !== "outcome_unknown",
2480
+ path: ["state"],
2481
+ message: "a lost resolver without a known settlement must be presented as outcome unknown"
2482
+ },
2483
+ {
2484
+ /**
2485
+ * Broken when a lost resolver with a known settlement is not shown as visual fallback.
2486
+ * @param value - The spoken approval.
2487
+ * @returns True when a lost resolver with a known settlement is not shown as visual fallback.
2488
+ */
2489
+ broken: (value) => value.reason === "resolver_lost" && !resolverOutcomeUnknown(value) && value.state !== "visual_fallback",
2490
+ path: ["state"],
2491
+ message: "a lost resolver with a known settlement must preserve that truth as visual fallback"
2492
+ },
2493
+ {
2494
+ /**
2495
+ * Broken when a lost resolver lacks its approval, gate or captured user item.
2496
+ * @param value - The spoken approval.
2497
+ * @returns True when a lost resolver lacks its approval, gate or captured user item.
2498
+ */
2499
+ broken: (value) => value.reason === "resolver_lost" && lacksResolverIdentity(value),
2500
+ path: ["reason"],
2501
+ message: "a lost resolver requires its exact approval, gate, and captured user item"
2502
+ },
2503
+ {
2504
+ /**
2505
+ * Broken when a mismatch reason is shown in a state other than stale.
2506
+ * @param value - The spoken approval.
2507
+ * @returns True when a mismatch reason is shown in a state other than stale.
2508
+ */
2509
+ broken: (value) => value.reason !== null && STALE_REASONS.has(value.reason) && value.state !== "stale_session",
2510
+ path: ["state"],
2511
+ message: "an identity or realtime mismatch must be presented as stale"
2512
+ },
2513
+ {
2514
+ /**
2515
+ * Broken when a visual fallback carries no reason.
2516
+ * @param value - The spoken approval.
2517
+ * @returns True when a visual fallback carries no reason.
2518
+ */
2519
+ broken: (value) => value.state === "visual_fallback" && value.reason === null,
2520
+ path: ["reason"],
2521
+ message: "a visual spoken fallback requires the runtime reason"
2522
+ },
2523
+ {
2524
+ /**
2525
+ * Broken when a live or settled approval carries a fallback reason.
2526
+ * @param value - The spoken approval.
2527
+ * @returns True when a live or settled approval carries a fallback reason.
2528
+ */
2529
+ broken: (value) => LIVE_STATES.has(value.state) && value.reason !== null,
2530
+ path: ["reason"],
2531
+ message: "a live or settled spoken approval cannot carry a fallback reason"
2532
+ }
2533
+ ];
2534
+ /**
2535
+ * Applies the consistency rules to a parsed spoken approval: an idle record
2536
+ * must be empty; any other must agree with the rule table.
2537
+ * @param value - The spoken approval.
2538
+ * @param context - Where issues are recorded.
2539
+ */
2540
+ function validateSpokenApproval(value, context) {
2541
+ if (value.state === "idle") {
2542
+ if (idleRetainsState(value)) context.addIssue({
2543
+ code: "custom",
2544
+ path: ["state"],
2545
+ message: "an idle spoken approval cannot retain request state"
2546
+ });
2547
+ return;
2548
+ }
2549
+ for (const rule of SPOKEN_APPROVAL_RULES) if (rule.broken(value)) context.addIssue({
2550
+ code: "custom",
2551
+ path: [...rule.path],
2552
+ message: rule.message
2553
+ });
2554
+ }
2555
+ /**
2556
+ * Wraps a realtime identity parser as a zod schema, so a refusal surfaces as
2557
+ * a validation issue instead of a throw.
2558
+ * @param parse - The parser for one realtime identity kind.
2559
+ * @returns A schema that yields the branded identity or an issue.
2560
+ */
2561
+ function realtimeIdentity(parse) {
2562
+ return z.unknown().transform((value, context) => {
2563
+ try {
2564
+ return parse(value);
2565
+ } catch (error) {
2566
+ context.addIssue({
2567
+ code: "custom",
2568
+ message: error instanceof Error ? error.message : "realtime identity is invalid"
2569
+ });
2570
+ return z.NEVER;
2571
+ }
2572
+ });
2573
+ }
2574
+ /**
2575
+ * Builds the schema of the spoken-approval record the chat shows: which
2576
+ * approval voice may settle, the gate that armed it, what the person said,
2577
+ * and how it settled, with the consistency rules between those parts.
2578
+ * @param identity - The session's identity schemas.
2579
+ * @returns The strict, rule-checked schema.
2580
+ */
2581
+ function createBrowserSpokenApprovalSchema(identity) {
2582
+ const { ApprovalIdSchema, ChildEpochSchema, ChildIdSchema, JsonRpcRequestIdSchema, ThreadIdSchema } = identity;
2583
+ const RealtimeItemIdSchema = realtimeIdentity(parseRealtimeItemId);
2584
+ const RealtimeSessionIdSchema = realtimeIdentity(parseRealtimeSessionId);
2585
+ const ReasonSchema = z.enum(BROWSER_SPOKEN_APPROVAL_REASONS);
2586
+ const ApprovalSchema = z.object({
2587
+ requestId: JsonRpcRequestIdSchema,
2588
+ approvalId: ApprovalIdSchema.nullable(),
2589
+ threadId: ThreadIdSchema,
2590
+ binding: z.object({
2591
+ child: ChildIdSchema,
2592
+ epoch: ChildEpochSchema,
2593
+ target: boundedText(512),
2594
+ effect: boundedText(512)
2595
+ }).strict()
2596
+ }).strict();
2597
+ const GateSchema = z.object({
2598
+ coordinatorThreadId: ThreadIdSchema,
2599
+ realtimeSessionId: RealtimeSessionIdSchema,
2600
+ effectSummary: boundedText(512),
2601
+ effectFingerprint: boundedText(512),
2602
+ effectPrompt: z.object({
2603
+ itemId: RealtimeItemIdSchema,
2604
+ sequence: z.number().int().nonnegative()
2605
+ }).strict(),
2606
+ expiresAtMs: z.number().int().nonnegative()
2607
+ }).strict();
2608
+ const CapturedUserFinalSchema = z.object({
2609
+ itemId: RealtimeItemIdSchema,
2610
+ sequence: z.number().int().nonnegative(),
2611
+ text: boundedText(16384)
2612
+ }).strict();
2613
+ const SettlementSchema = z.object({
2614
+ state: z.enum([
2615
+ "settled",
2616
+ "expired",
2617
+ "cancelled",
2618
+ "stale",
2619
+ "outcome_unknown"
2620
+ ]),
2621
+ outcome: z.enum([
2622
+ "delivered",
2623
+ "not_delivered",
2624
+ "outcome_unknown"
2625
+ ]),
2626
+ reason: boundedText(512)
2627
+ }).strict();
2628
+ return z.object({
2629
+ kind: z.literal("spoken_approval"),
2630
+ state: z.enum(BROWSER_SPOKEN_APPROVAL_STATES),
2631
+ approval: ApprovalSchema.nullable(),
2632
+ gate: GateSchema.nullable(),
2633
+ capturedUserFinal: CapturedUserFinalSchema.nullable(),
2634
+ settlement: SettlementSchema.nullable(),
2635
+ reason: ReasonSchema.nullable()
2636
+ }).strict().superRefine(validateSpokenApproval);
2637
+ }
2638
+ // src/shared/browser/schemas/snapshot.ts
2639
+ /**
2640
+ * Tells whether a thread-scoped field names a thread other than the linked one.
2641
+ * @param value - The snapshot fields.
2642
+ * @param scoped - The thread-scoped field, or null when absent.
2643
+ * @returns True when the field is present and its thread differs from the link's.
2644
+ */
2645
+ function contradictsThreadLink(value, scoped) {
2646
+ return scoped !== null && value.threadLink.threadId !== scoped.threadId;
2647
+ }
2648
+ /**
2649
+ * Tells whether an unbound link is accompanied by thread-scoped state.
2650
+ * @param value - The snapshot fields.
2651
+ * @returns True when the link is unbound yet a timeline or context delivery receipt is present.
2652
+ */
2653
+ function unboundLinkPublishesThreadState(value) {
2654
+ return value.threadLink.state === "unbound" && (value.timeline !== null || value.contextDelivery !== null);
2655
+ }
2656
+ /**
2657
+ * Tells whether the voice context names a session other than the active voice session.
2658
+ * @param value - The snapshot fields.
2659
+ * @returns True when a voice context is present and its session differs from voice's.
2660
+ */
2661
+ function voiceContextContradictsVoice(value) {
2662
+ const voiceContext = value.voiceContext ?? null;
2663
+ return voiceContext !== null && value.voice?.realtimeSessionId !== voiceContext.sessionId;
2664
+ }
2665
+ /**
2666
+ * Tells whether the coordinator's timeline names a thread other than the coordinator's own,
2667
+ * which includes a timeline beside a coordinator that is bound to no thread.
2668
+ * @param value - The snapshot fields.
2669
+ * @returns True when a coordinator timeline is present and its thread differs from the coordinator's.
2670
+ */
2671
+ function coordinatorTimelineContradictsCoordinator(value) {
2672
+ const timeline = value.coordinatorTimeline ?? null;
2673
+ return timeline !== null && value.coordinator.threadId !== timeline.threadId;
2674
+ }
2675
+ /**
2676
+ * Checks relationships between fields after each field has passed its own schema.
2677
+ * @param value - The snapshot fields the relationships are about.
2678
+ * @returns The issues found, empty when every relationship holds.
2679
+ */
2680
+ function browserSnapshotRelationshipIssues(value) {
2681
+ const issues = [];
2682
+ for (const [name, scoped] of [["timeline", value.timeline], ["contextDelivery", value.contextDelivery]]) if (contradictsThreadLink(value, scoped)) issues.push({
2683
+ path: [name, "threadId"],
2684
+ message: "thread identity contradicts the current thread link"
2685
+ });
2686
+ if (unboundLinkPublishesThreadState(value)) issues.push({
2687
+ path: ["threadLink", "state"],
2688
+ message: "an unbound link cannot publish thread-scoped state"
2689
+ });
2690
+ if (voiceContextContradictsVoice(value)) issues.push({
2691
+ path: ["voiceContext", "sessionId"],
2692
+ message: "voice context identity contradicts the active voice session"
2693
+ });
2694
+ if (coordinatorTimelineContradictsCoordinator(value)) issues.push({
2695
+ path: ["coordinatorTimeline", "threadId"],
2696
+ message: "coordinator timeline identity contradicts the coordinator's thread"
2697
+ });
2698
+ return issues;
2699
+ }
2700
+ /**
2701
+ * Builds every browser DTO schema bound to one identity authority, plus the
2702
+ * snapshot that composes them and the union the transport accepts.
2703
+ * @param identity - The session's identity schemas.
2704
+ * @param context - The validator that knows the current child and epoch.
2705
+ * @returns The DTO schemas, the snapshot and DTO union, and the dynamic approval schemas.
2706
+ */
2707
+ function createBrowserSchemas(identity, context) {
2708
+ const dynamic = createDynamicApprovalSchemas(identity, context);
2709
+ const BrowserSpokenApprovalSchema = createBrowserSpokenApprovalSchema(identity);
2710
+ const session = createBrowserSessionSchemas(identity);
2711
+ const thread = createBrowserThreadSchemas(identity, context);
2712
+ const { BrowserApprovalSchema } = createBrowserApprovalSchemas(identity, context);
2713
+ const voice = createBrowserVoiceSchemas(identity);
2714
+ const commands = createBrowserCommandSchemas(identity, context, dynamic.BrowserDynamicApprovalResponseSchema);
2715
+ const BrowserSnapshotSchema = z.object({
2716
+ kind: z.literal("snapshot"),
2717
+ version: z.literal(1),
2718
+ readiness: session.BrowserReadinessSchema,
2719
+ account: session.BrowserAccountSchema,
2720
+ login: session.BrowserLoginSchema,
2721
+ threadLink: thread.BrowserThreadLinkSchema,
2722
+ timeline: thread.BrowserTimelineSchema.nullable(),
2723
+ queue: thread.BrowserQueueSchema,
2724
+ settings: z.array(session.BrowserSettingsSchema),
2725
+ approvals: z.array(BrowserApprovalSchema),
2726
+ dynamicApprovals: z.array(dynamic.BrowserDynamicApprovalSchema),
2727
+ contextDelivery: voice.BrowserContextDeliverySchema.nullable(),
2728
+ coordinator: voice.BrowserCoordinatorSchema,
2729
+ voice: voice.BrowserVoiceSchema,
2730
+ spokenApproval: BrowserSpokenApprovalSchema,
2731
+ voiceContext: voice.BrowserVoiceContextSchema.nullable().optional(),
2732
+ /** The voice coordinator's own turns; absent from a server that predates them. */
2733
+ coordinatorTimeline: thread.BrowserTimelineSchema.nullable().optional(),
2734
+ /** The tab session's workhorses and the shown one; absent from a server that predates them. */
2735
+ workhorses: session.BrowserWorkhorsesSchema.optional(),
2736
+ lease: commands.BrowserCommandLeaseSchema.nullable(),
2737
+ operation: commands.BrowserOperationOutcomeSchema.nullable()
2738
+ }).strict().superRefine((value, refinementContext) => {
2739
+ for (const issue of browserSnapshotRelationshipIssues(value)) refinementContext.addIssue({
2740
+ code: "custom",
2741
+ path: [...issue.path],
2742
+ message: issue.message
2743
+ });
2744
+ });
2745
+ const BrowserDtoSchema = z.union([
2746
+ BrowserSnapshotSchema,
2747
+ session.BrowserReadinessSchema,
2748
+ session.BrowserAccountSchema,
2749
+ session.BrowserLoginSchema,
2750
+ thread.BrowserThreadLinkSchema,
2751
+ thread.BrowserTimelineSchema,
2752
+ thread.BrowserQueueSchema,
2753
+ session.BrowserSettingsSchema,
2754
+ BrowserApprovalSchema,
2755
+ dynamic.BrowserDynamicApprovalSchema,
2756
+ commands.BrowserTextCommandSchema,
2757
+ voice.BrowserContextDeliverySchema,
2758
+ voice.BrowserCoordinatorSchema,
2759
+ voice.BrowserVoiceSchema,
2760
+ BrowserSpokenApprovalSchema,
2761
+ commands.BrowserCommandLeaseSchema,
2762
+ commands.BrowserOperationOutcomeSchema
2763
+ ]);
2764
+ return {
2765
+ BrowserReadinessSchema: session.BrowserReadinessSchema,
2766
+ BrowserAccountSchema: session.BrowserAccountSchema,
2767
+ BrowserLoginSchema: session.BrowserLoginSchema,
2768
+ BrowserThreadLinkSourcePresentationSchema: thread.BrowserThreadLinkSourcePresentationSchema,
2769
+ BrowserThreadLinkSchema: thread.BrowserThreadLinkSchema,
2770
+ BrowserTimelineSchema: thread.BrowserTimelineSchema,
2771
+ BrowserQueueSchema: thread.BrowserQueueSchema,
2772
+ BrowserSettingsSchema: session.BrowserSettingsSchema,
2773
+ BrowserWorkhorsesSchema: session.BrowserWorkhorsesSchema,
2774
+ BrowserApprovalSchema,
2775
+ BrowserTextCommandSchema: commands.BrowserTextCommandSchema,
2776
+ BrowserContextDeliverySchema: voice.BrowserContextDeliverySchema,
2777
+ BrowserCoordinatorSchema: voice.BrowserCoordinatorSchema,
2778
+ BrowserVoiceSchema: voice.BrowserVoiceSchema,
2779
+ BrowserSpokenApprovalSchema,
2780
+ BrowserVoiceContextSchema: voice.BrowserVoiceContextSchema,
2781
+ BrowserCommandLeaseSchema: commands.BrowserCommandLeaseSchema,
2782
+ BrowserOperationOutcomeSchema: commands.BrowserOperationOutcomeSchema,
2783
+ BrowserCommandSchema: commands.BrowserCommandSchema,
2784
+ BrowserSnapshotSchema,
2785
+ BrowserDtoSchema,
2786
+ ...dynamic
2787
+ };
2788
+ }
2789
+ // src/shared/browser/schemas/model.ts
2790
+ /**
2791
+ * Builds the complete browser model, every identity and DTO schema, bound to
2792
+ * one identity authority so nothing the browser exchanges can name a child,
2793
+ * epoch or identity the session did not issue.
2794
+ * @param context - The identity authorities, or a decoder-and-validator context with an optional operation capability.
2795
+ * @returns The identity schemas together with the browser DTO and command schemas.
2796
+ */
2797
+ function createCodexBrowserModel(context) {
2798
+ const normalizedContext = "identity" in context ? {
2799
+ ...context.identity,
2800
+ operation: context.operation
2801
+ } : context;
2802
+ const identity = createIdentitySchemas(normalizedContext);
2803
+ return {
2804
+ ...identity,
2805
+ ...createBrowserSchemas(identity, normalizedContext)
2806
+ };
2807
+ }
2808
+ export { JsonValueSchema as _, dynamicApprovalHashForCanonicalJson as a, CODEX_APP_SERVER_CAPACITY as b, CODEX_REALTIME_MS as c, codexRestartDelayMs as d, BROWSER_PERMISSION_FILE_ACCESS as f, DeliveryOutcomeSchema as g, BROWSER_VOICE_CONTEXT_BRIEF_MAX_UTF8_BYTES as h, canonicalDynamicApprovalJson as i, CODEX_SESSION_MS as l, BROWSER_VOICE_CONTEXT_BODY_MAX_UTF8_BYTES as m, browserSnapshotRelationshipIssues as n, CODEX_APPROVAL_MS as o, BROWSER_TIMELINE_LIMITS as p, BROWSER_IDLE_SPOKEN_APPROVAL as r, CODEX_PROCESS_MS as s, createCodexBrowserModel as t, TAB_SESSION_GRACE_MS as u, boundedText as v, boundedWireText as y };