@archboard/codex-realtime-voice 0.0.0-stage → 0.2.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,4754 @@
1
+ import { a as VOICE_OUTPUT_SPEAKING_LEVEL, i as browserAudioElements, n as BrowserWorkbenchTransportError, r as createBrowserWorkbenchMediaOwner, t as createBrowserWorkbenchTransport } from "./transport-CqOvXrAE.mjs";
2
+ import { t as BROWSER_GATEWAY_ERROR_CODES } from "./gateway-envelope-CODkg5rz.mjs";
3
+ // src/ui/approval-forms/rules/fields.ts
4
+ const QUESTION_PREFIX = "question:";
5
+ const ELICITATION_PREFIX = "field:";
6
+ const PERMISSION_NETWORK = "permission:network";
7
+ const PERMISSION_SCOPE = "permission:scope";
8
+ const PERMISSION_STRICT_REVIEW = "permission:strict_auto_review";
9
+ const DECLINE_REASON = "decline_reason";
10
+ const STRING_FORMATS = {
11
+ email: "email",
12
+ uri: "url",
13
+ date: "date",
14
+ "date-time": "date_time"
15
+ };
16
+ const TYPED_CONTROLS = {
17
+ boolean: "boolean",
18
+ number: "number",
19
+ integer: "integer"
20
+ };
21
+ const FIELD_DEFAULTS = {
22
+ description: null,
23
+ required: false,
24
+ secret: false,
25
+ options: null,
26
+ allowsOther: false,
27
+ minimum: null,
28
+ maximum: null,
29
+ minLength: null,
30
+ maxLength: null,
31
+ minimumItems: null,
32
+ maximumItems: null,
33
+ defaultValue: null
34
+ };
35
+ /**
36
+ * One reviewed field, frozen.
37
+ * @param seed The field's facts.
38
+ * @returns The field; a secret never carries a default.
39
+ */
40
+ function field(seed) {
41
+ const merged = {
42
+ ...FIELD_DEFAULTS,
43
+ ...seed
44
+ };
45
+ return Object.freeze({
46
+ ...merged,
47
+ defaultValue: merged.secret ? null : merged.defaultValue
48
+ });
49
+ }
50
+ /**
51
+ * A default value as text, when it can be shown.
52
+ * @param value The server's default.
53
+ * @returns The text, or null.
54
+ */
55
+ function jsonText(value) {
56
+ if (value === null || value === void 0) return null;
57
+ return typeof value === "string" ? value : JSON.stringify(value);
58
+ }
59
+ /**
60
+ * The options of one question.
61
+ * @param question The question.
62
+ * @returns The options, or null for free text.
63
+ */
64
+ function questionOptions(question) {
65
+ if (question.options === null) return null;
66
+ return question.options.map((option) => Object.freeze({
67
+ label: option.label,
68
+ description: option.description
69
+ }));
70
+ }
71
+ /**
72
+ * The control a question needs.
73
+ * @param question The question.
74
+ * @param options Its options, or null.
75
+ * @returns Secret, free text, or a multiple choice.
76
+ */
77
+ function questionControl(question, options) {
78
+ if (question.isSecret) return "secret";
79
+ return options === null ? "text" : "multi_enum";
80
+ }
81
+ /**
82
+ * The fields of a user-input request: one per question.
83
+ * @param approval The request.
84
+ * @returns The fields.
85
+ */
86
+ function questionFields(approval) {
87
+ return approval.questions.map((question) => {
88
+ const options = questionOptions(question);
89
+ return field({
90
+ name: `${QUESTION_PREFIX}${question.id}`,
91
+ label: question.header,
92
+ description: question.question,
93
+ control: questionControl(question, options),
94
+ required: true,
95
+ secret: question.isSecret,
96
+ options,
97
+ allowsOther: question.isOther
98
+ });
99
+ });
100
+ }
101
+ /**
102
+ * The control of a string-typed elicitation field.
103
+ * @param source The server's field.
104
+ * @returns A format control, multiline for long text, else text.
105
+ */
106
+ function stringControl(source) {
107
+ if (source.format !== null) return STRING_FORMATS[source.format];
108
+ return (source.maxLength ?? 0) > 512 ? "multiline" : "text";
109
+ }
110
+ /**
111
+ * The control an elicitation field needs.
112
+ * @param source The server's field.
113
+ * @returns The control.
114
+ */
115
+ function elicitationControl(source) {
116
+ if (source.secret) return "secret";
117
+ if (source.type === "boolean" || source.type === "number" || source.type === "integer") return TYPED_CONTROLS[source.type];
118
+ return source.options === null ? stringControl(source) : choiceControl(source);
119
+ }
120
+ /**
121
+ * The control of an enumerated elicitation field.
122
+ * @param source The server's field.
123
+ * @returns Multiple choice when more than one item may be chosen, else single.
124
+ */
125
+ function choiceControl(source) {
126
+ return (source.maximumItems ?? 1) > 1 ? "multi_enum" : "enum";
127
+ }
128
+ /**
129
+ * The options of an elicitation field.
130
+ * @param source The server's field.
131
+ * @returns The options, or null.
132
+ */
133
+ function elicitationOptions(source) {
134
+ if (source.options === null) return null;
135
+ return source.options.map((option) => Object.freeze({
136
+ label: option,
137
+ description: null
138
+ }));
139
+ }
140
+ /**
141
+ * The fields of a form-mode elicitation.
142
+ * @param approval The request.
143
+ * @returns The fields; none for URL mode or an unpublished form.
144
+ */
145
+ function elicitationFields(approval) {
146
+ if (approval.mode === "url" || approval.fields === null) return [];
147
+ return approval.fields.map((source) => field({
148
+ name: `${ELICITATION_PREFIX}${source.name}`,
149
+ label: source.title ?? source.name,
150
+ description: source.description,
151
+ control: elicitationControl(source),
152
+ required: source.required,
153
+ secret: source.secret,
154
+ options: elicitationOptions(source),
155
+ minimum: source.minimum,
156
+ maximum: source.maximum,
157
+ minLength: source.minLength,
158
+ maxLength: source.maxLength,
159
+ minimumItems: source.minimumItems,
160
+ maximumItems: source.maximumItems,
161
+ defaultValue: jsonText(source.defaultValue)
162
+ }));
163
+ }
164
+ /**
165
+ * The browser contract publishes which file-access modes were requested but
166
+ * no paths, and a granted path list is never invented here. Network access is
167
+ * the only permission this surface can actually grant, so a request that does
168
+ * not name it has nothing to review and nothing to submit.
169
+ * @param approval The request.
170
+ * @returns True when a grant can be composed.
171
+ */
172
+ function permissionsAreGrantable(approval) {
173
+ return approval.approvalKind === "permissions" && approval.requestedScope.network !== null;
174
+ }
175
+ /**
176
+ * The reviewed fields of a permissions request.
177
+ * @param approval The request.
178
+ * @returns Network access, grant scope and strict review; none when nothing is grantable.
179
+ */
180
+ function permissionFields(approval) {
181
+ if (!permissionsAreGrantable(approval)) return [];
182
+ const requested = approval.requestedScope.network === true;
183
+ return [
184
+ field({
185
+ name: PERMISSION_NETWORK,
186
+ label: "Grant network access",
187
+ description: requested ? "The agent asked for network access." : "The agent asked for network access to be withheld.",
188
+ control: "boolean",
189
+ defaultValue: requested ? "true" : "false"
190
+ }),
191
+ field({
192
+ name: PERMISSION_SCOPE,
193
+ label: "Grant scope",
194
+ description: "A session grant lasts beyond this turn and is never spoken-eligible.",
195
+ control: "enum",
196
+ required: true,
197
+ options: [Object.freeze({
198
+ label: "turn",
199
+ description: "This turn only."
200
+ }), Object.freeze({
201
+ label: "session",
202
+ description: "The rest of this session."
203
+ })],
204
+ defaultValue: "turn"
205
+ }),
206
+ field({
207
+ name: PERMISSION_STRICT_REVIEW,
208
+ label: "Review every later command in this turn",
209
+ description: "Every subsequent command is reviewed before normal sandboxed execution.",
210
+ control: "boolean",
211
+ defaultValue: "false"
212
+ })
213
+ ];
214
+ }
215
+ const DECLINE_REASON_FIELD = field({
216
+ name: DECLINE_REASON,
217
+ label: "Decline reason",
218
+ description: "Optional. Sent with a decline so the agent can read why.",
219
+ control: "text"
220
+ });
221
+ /**
222
+ * The reviewed fields a decision on this request reads.
223
+ * @param approval The request.
224
+ * @returns The fields; none for a command execution or file change.
225
+ */
226
+ function approvalFields(approval) {
227
+ switch (approval.approvalKind) {
228
+ case "user_input": return questionFields(approval);
229
+ case "elicitation": return elicitationFields(approval);
230
+ case "permissions": return permissionFields(approval);
231
+ case "apply_patch":
232
+ case "exec_command": return [DECLINE_REASON_FIELD];
233
+ default: return [];
234
+ }
235
+ }
236
+ // src/ui/approval-forms/rules/form.ts
237
+ /**
238
+ * The form seeded from the fields' published defaults.
239
+ * @param fields The reviewed fields.
240
+ * @returns The form; a secret is never seeded.
241
+ */
242
+ function initialApprovalForm(fields) {
243
+ const values = {};
244
+ const flags = {};
245
+ for (const item of fields) if (item.control === "boolean") flags[item.name] = item.defaultValue === "true";
246
+ else if (item.defaultValue !== null) values[item.name] = item.defaultValue;
247
+ return Object.freeze({
248
+ values: Object.freeze(values),
249
+ selections: Object.freeze({}),
250
+ flags: Object.freeze(flags)
251
+ });
252
+ }
253
+ /**
254
+ * The form after one event.
255
+ * @param state The form.
256
+ * @param event The change.
257
+ * @returns A new form; the others are untouched.
258
+ */
259
+ function applyApprovalFormEvent(state, event) {
260
+ if (event.kind === "value") return Object.freeze({
261
+ ...state,
262
+ values: Object.freeze({
263
+ ...state.values,
264
+ [event.name]: event.value
265
+ })
266
+ });
267
+ if (event.kind === "flag") return Object.freeze({
268
+ ...state,
269
+ flags: Object.freeze({
270
+ ...state.flags,
271
+ [event.name]: event.value
272
+ })
273
+ });
274
+ return Object.freeze({
275
+ ...state,
276
+ selections: Object.freeze({
277
+ ...state.selections,
278
+ [event.name]: Object.freeze([...event.value])
279
+ })
280
+ });
281
+ }
282
+ /**
283
+ * One text answer.
284
+ * @param state The form.
285
+ * @param name The field.
286
+ * @returns The value, or empty.
287
+ */
288
+ function formValue(state, name) {
289
+ return state.values[name] ?? "";
290
+ }
291
+ /**
292
+ * One boolean answer.
293
+ * @param state The form.
294
+ * @param name The field.
295
+ * @returns The flag, or false.
296
+ */
297
+ function formFlag(state, name) {
298
+ return state.flags[name] ?? false;
299
+ }
300
+ /**
301
+ * One multiple-choice answer.
302
+ * @param state The form.
303
+ * @param name The field.
304
+ * @returns The selection, or none.
305
+ */
306
+ function formSelection(state, name) {
307
+ return state.selections[name] ?? [];
308
+ }
309
+ // src/ui/approvals/rules/vocabulary.ts
310
+ const FAMILY_TITLES = {
311
+ command_execution: "Run a command",
312
+ file_change: "Change files",
313
+ permissions: "Widen permissions",
314
+ apply_patch: "Apply a patch",
315
+ exec_command: "Run a command (legacy request)",
316
+ user_input: "Answer the agent's questions",
317
+ elicitation: "Answer an MCP server"
318
+ };
319
+ const DYNAMIC_TITLES = {
320
+ create_thread: "Create a new Codex thread",
321
+ fork_thread: "Fork a Codex thread",
322
+ send_message_to_thread: "Send a message to another Codex thread"
323
+ };
324
+ const PHASE_LABELS = {
325
+ staged: "Staged",
326
+ pending: "Waiting for you",
327
+ approved: "Approved",
328
+ declined: "Declined",
329
+ cancelled: "Cancelled",
330
+ expired: "Expired",
331
+ stale: "Stale",
332
+ disconnected: "Disconnected",
333
+ delivered: "Delivered",
334
+ not_delivered: "Not delivered",
335
+ outcome_unknown: "Outcome unknown"
336
+ };
337
+ const TERMINAL_PHASES = /* @__PURE__ */ new Set([
338
+ "approved",
339
+ "declined",
340
+ "cancelled",
341
+ "expired",
342
+ "stale",
343
+ "disconnected",
344
+ "delivered",
345
+ "not_delivered",
346
+ "outcome_unknown"
347
+ ]);
348
+ /** The server's own spoken-eligibility vocabulary, said in human words. */
349
+ const SPOKEN_REASONS = {
350
+ eligible: "This is a plain accept or decline, so it may also be answered by voice.",
351
+ not_pending: "Visual only: this request is no longer waiting for a decision.",
352
+ stale_ownership: "Visual only: the request no longer belongs to the current child epoch.",
353
+ secret: "Visual only: this request carries a secret that must never be spoken.",
354
+ multi_question: "Visual only: this request asks more than one question.",
355
+ form: "Visual only: this request needs a form, not a spoken word.",
356
+ url: "Visual only: this request hands over a URL.",
357
+ permission_scope: "Visual only: this request asks for a scoped permission grant.",
358
+ coordinator_blocking: "Visual only: answering this would block the voice coordinator.",
359
+ unsupported_schema: "Visual only: the server could not reduce this request to a spoken effect.",
360
+ broader_grant: "Visual only: one of the offered decisions grants more than this one action.",
361
+ not_binary: "Visual only: this request is not a plain accept or decline."
362
+ };
363
+ const DYNAMIC_SPOKEN_DETAIL = "Visual only: a dynamic coordination approval is never spoken-eligible.";
364
+ const NO_RESUME_NOTICE = "This approval cannot be resumed. The agent must ask again if it still needs the effect.";
365
+ const IMMUTABLE_EFFECT_NOTICE = "The effect and its hash are fixed. Approving sends exactly this effect, or nothing.";
366
+ const TRANSPORT_REFUSALS$1 = /* @__PURE__ */ new Map([
367
+ ["approval_not_pending", "This approval is no longer pending for the target it was raised against."],
368
+ ["dynamic_approval_not_pending", "This dynamic approval is no longer pending for the target it was raised against."],
369
+ ["link_changed", "The workbench moved to another thread link after this decision was offered."],
370
+ ["link_required", "The decision did not name the workbench target it was composed against."],
371
+ ["lease_required", "This browser does not hold the workbench command lease."],
372
+ ["lease_expired", "The workbench command lease expired before the decision was sent."],
373
+ ["lease_released", "The workbench command lease was released before the decision was sent."],
374
+ ["not_ready", "The workbench cannot answer approvals in its current state."],
375
+ ["socket_unavailable", "The workbench lost its connection before the decision was sent."],
376
+ ["incompatible_contract", "The server answered with a workbench contract this browser cannot read."],
377
+ ["response_lost", "The server never answered, so the decision's outcome is unknown."]
378
+ ]);
379
+ const GENERIC_REFUSAL = "The server refused this decision.";
380
+ /**
381
+ * The words for a refusal code.
382
+ * @param code The transport or gateway code.
383
+ * @returns The refusal in human words.
384
+ */
385
+ function refusalMessage(code) {
386
+ return TRANSPORT_REFUSALS$1.get(code) ?? GENERIC_REFUSAL;
387
+ }
388
+ /**
389
+ * The words for the server's spoken-eligibility reason.
390
+ * @param reason The server's reason.
391
+ * @returns The detail.
392
+ */
393
+ function spokenDetail(reason) {
394
+ return SPOKEN_REASONS[reason];
395
+ }
396
+ // src/ui/approvals/rules/offers.ts
397
+ const DECISION_PREFIX = "decision:";
398
+ const OFFER_SUBMIT = "submit";
399
+ const OFFER_DECLINE = "decline";
400
+ const OFFER_CANCEL = "cancel";
401
+ const OFFER_APPROVE = "approve";
402
+ const OFFER_ABORT = "abort";
403
+ const PLAIN_DECISION_LABELS = {
404
+ accept: "Approve",
405
+ acceptForSession: "Approve for this session",
406
+ decline: "Decline",
407
+ cancel: "Cancel"
408
+ };
409
+ const PLAIN_DECISION_TONES = {
410
+ accept: "primary",
411
+ acceptForSession: "secondary",
412
+ decline: "secondary",
413
+ cancel: "quiet"
414
+ };
415
+ const PLAIN_DECISION_DESCRIPTIONS = {
416
+ accept: null,
417
+ acceptForSession: "A session grant also covers later commands in this session.",
418
+ decline: null,
419
+ cancel: null
420
+ };
421
+ /**
422
+ * One offer, frozen.
423
+ * @param seed The offer's facts.
424
+ * @returns The offer.
425
+ */
426
+ function offer(seed) {
427
+ return Object.freeze({
428
+ description: null,
429
+ submitsForm: false,
430
+ spokenEligible: false,
431
+ ...seed
432
+ });
433
+ }
434
+ /**
435
+ * The offer for a plain server-offered decision.
436
+ * @param id The offer id.
437
+ * @param decision The decision.
438
+ * @param spokenEligible Whether voice may answer it.
439
+ * @returns The offer.
440
+ */
441
+ function plainDecisionOffer(id, decision, spokenEligible) {
442
+ return offer({
443
+ id,
444
+ label: PLAIN_DECISION_LABELS[decision],
445
+ tone: PLAIN_DECISION_TONES[decision],
446
+ description: PLAIN_DECISION_DESCRIPTIONS[decision],
447
+ spokenEligible
448
+ });
449
+ }
450
+ /**
451
+ * The offer for one command execution decision, plain or amended.
452
+ * @param decision The server-offered decision.
453
+ * @param index Its position among the offered decisions.
454
+ * @param spoken Whether the request as a whole is spoken-eligible.
455
+ * @returns The offer.
456
+ */
457
+ function commandDecisionOffer(decision, index, spoken) {
458
+ const id = `${DECISION_PREFIX}${index}`;
459
+ if (typeof decision === "string") return plainDecisionOffer(id, decision, spoken && (decision === "accept" || decision === "decline"));
460
+ if ("acceptWithExecpolicyAmendment" in decision) return offer({
461
+ id,
462
+ label: "Approve with the proposed exec policy amendment",
463
+ tone: "secondary",
464
+ description: `The server proposed: ${decision.acceptWithExecpolicyAmendment.execpolicy_amendment.join(" · ")}`
465
+ });
466
+ const amendment = decision.applyNetworkPolicyAmendment.network_policy_amendment;
467
+ return offer({
468
+ id,
469
+ label: `${amendment.action === "allow" ? "Allow" : "Deny"} ${amendment.host} in the network policy`,
470
+ tone: "secondary",
471
+ description: "This changes the network policy beyond this one command."
472
+ });
473
+ }
474
+ /**
475
+ * The offers of a file change: the server-offered decisions, in order.
476
+ * @param approval The request.
477
+ * @returns The offers.
478
+ */
479
+ function fileChangeOffers(approval) {
480
+ return approval.availableDecisions.map((decision, index) => plainDecisionOffer(`${DECISION_PREFIX}${index}`, decision, false));
481
+ }
482
+ /**
483
+ * The offers of an elicitation: accept only when the server published what
484
+ * accepting needs.
485
+ * @param approval The request.
486
+ * @returns The offers.
487
+ */
488
+ function elicitationOffers(approval) {
489
+ const unsupported = approval.mode === "url" ? approval.url === null : approval.fields === null;
490
+ const accept = offer({
491
+ id: OFFER_SUBMIT,
492
+ label: approval.mode === "url" ? "Accept and open the URL" : "Send this form",
493
+ tone: "primary",
494
+ submitsForm: approval.mode !== "url"
495
+ });
496
+ const rest = [offer({
497
+ id: OFFER_DECLINE,
498
+ label: "Decline",
499
+ tone: "secondary"
500
+ }), offer({
501
+ id: OFFER_CANCEL,
502
+ label: "Cancel",
503
+ tone: "quiet"
504
+ })];
505
+ return unsupported ? rest : [accept, ...rest];
506
+ }
507
+ /**
508
+ * The offers of a permissions request. A request that names no grantable
509
+ * permission has nothing to submit: a "grant" would send the same empty
510
+ * profile as the decline.
511
+ * @param approval The request.
512
+ * @returns The offers.
513
+ */
514
+ function permissionsOffers(approval) {
515
+ if (!permissionsAreGrantable(approval)) return [offer({
516
+ id: OFFER_DECLINE,
517
+ label: "Grant nothing",
518
+ tone: "primary"
519
+ })];
520
+ return [offer({
521
+ id: OFFER_SUBMIT,
522
+ label: "Grant the reviewed permissions",
523
+ tone: "primary",
524
+ submitsForm: true
525
+ }), offer({
526
+ id: OFFER_DECLINE,
527
+ label: "Grant nothing",
528
+ tone: "secondary"
529
+ })];
530
+ }
531
+ const USER_INPUT_OFFERS = Object.freeze([offer({
532
+ id: OFFER_SUBMIT,
533
+ label: "Send answers",
534
+ tone: "primary",
535
+ submitsForm: true
536
+ }), offer({
537
+ id: OFFER_DECLINE,
538
+ label: "Answer nothing",
539
+ tone: "quiet"
540
+ })]);
541
+ const LEGACY_OFFERS = Object.freeze([
542
+ offer({
543
+ id: OFFER_APPROVE,
544
+ label: "Approve",
545
+ tone: "primary"
546
+ }),
547
+ offer({
548
+ id: OFFER_DECLINE,
549
+ label: "Decline",
550
+ tone: "secondary",
551
+ submitsForm: true
552
+ }),
553
+ offer({
554
+ id: OFFER_ABORT,
555
+ label: "Cancel",
556
+ tone: "quiet"
557
+ })
558
+ ]);
559
+ /**
560
+ * The offers of the families whose decisions the server enumerates.
561
+ * @param approval The request.
562
+ * @param spoken Whether the request is spoken-eligible.
563
+ * @returns The offers, in the server's order.
564
+ */
565
+ function enumeratedOffers(approval, spoken) {
566
+ if (approval.approvalKind === "file_change") return fileChangeOffers(approval);
567
+ return approval.availableDecisions.map((decision, index) => commandDecisionOffer(decision, index, spoken));
568
+ }
569
+ /**
570
+ * The offers of one ordinary request.
571
+ * @param approval The request.
572
+ * @param spoken Whether the request is spoken-eligible.
573
+ * @returns The offers.
574
+ */
575
+ function ordinaryOffers(approval, spoken) {
576
+ switch (approval.approvalKind) {
577
+ case "command_execution":
578
+ case "file_change": return enumeratedOffers(approval, spoken);
579
+ case "user_input": return USER_INPUT_OFFERS;
580
+ case "elicitation": return elicitationOffers(approval);
581
+ case "permissions": return permissionsOffers(approval);
582
+ default: return LEGACY_OFFERS;
583
+ }
584
+ }
585
+ /**
586
+ * A genuine ordinary binary approval is a command execution whose server-offered
587
+ * decision set is exactly accept and decline. Every other family, every
588
+ * broader grant, and every amendment stays visual-only whatever the server
589
+ * annotated.
590
+ * @param approval The request.
591
+ * @returns True for exactly accept and decline on a command execution.
592
+ */
593
+ function isGenuineBinaryApproval(approval) {
594
+ if (approval.approvalKind !== "command_execution") return false;
595
+ const decisions = approval.availableDecisions;
596
+ return decisions.length === 2 && decisions.includes("accept") && decisions.includes("decline");
597
+ }
598
+ /**
599
+ * Whether an ordinary request may be answered by voice, and why.
600
+ * @param approval The request.
601
+ * @param phase Its phase.
602
+ * @returns The spoken facts.
603
+ */
604
+ function ordinarySpoken(approval, phase) {
605
+ const published = approval.spoken;
606
+ if (published.eligible && published.reason === "eligible" && phase === "pending" && isGenuineBinaryApproval(approval)) return Object.freeze({
607
+ eligible: true,
608
+ label: "Spoken approval available",
609
+ detail: SPOKEN_REASONS.eligible
610
+ });
611
+ const detail = published.eligible ? "Visual only: this browser could not confirm a plain accept or decline." : spokenDetail(published.reason);
612
+ return Object.freeze({
613
+ eligible: false,
614
+ label: "Visual only",
615
+ detail
616
+ });
617
+ }
618
+ /**
619
+ * A dynamic coordination approval is never spoken-eligible.
620
+ * @returns The spoken facts.
621
+ */
622
+ function dynamicSpoken() {
623
+ return Object.freeze({
624
+ eligible: false,
625
+ label: "Visual only",
626
+ detail: DYNAMIC_SPOKEN_DETAIL
627
+ });
628
+ }
629
+ /**
630
+ * The offers of one ordinary request while it can still be decided.
631
+ * @param approval The request.
632
+ * @param phase Its phase.
633
+ * @param authority Whether this browser may decide it.
634
+ * @returns The offers; none unless pending with live authority.
635
+ */
636
+ function approvalOffers(approval, phase, authority) {
637
+ if (authority === "removed" || phase !== "pending") return Object.freeze([]);
638
+ return Object.freeze(ordinaryOffers(approval, ordinarySpoken(approval, phase).eligible));
639
+ }
640
+ /**
641
+ * A dynamic coordination approval offers one approve or decline decision
642
+ * only, and only while it is pending.
643
+ * @param phase Its phase.
644
+ * @param authority Whether this browser may decide it.
645
+ * @returns The offers.
646
+ */
647
+ function dynamicOffers(phase, authority) {
648
+ if (authority === "removed" || phase !== "pending") return Object.freeze([]);
649
+ return Object.freeze([offer({
650
+ id: OFFER_APPROVE,
651
+ label: "Approve this effect",
652
+ tone: "primary"
653
+ }), offer({
654
+ id: OFFER_DECLINE,
655
+ label: "Decline this effect",
656
+ tone: "secondary"
657
+ })]);
658
+ }
659
+ // src/ui/approvals/rules/choice.ts
660
+ /**
661
+ * Whether two server-offered decisions are the same decision.
662
+ * @param left One decision.
663
+ * @param right The other.
664
+ * @returns True when they spell the same decision.
665
+ */
666
+ function sameDecision(left, right) {
667
+ if (typeof left === "string" || typeof right === "string") return left === right;
668
+ return JSON.stringify(left) === JSON.stringify(right);
669
+ }
670
+ /**
671
+ * The offer id of a server-offered decision.
672
+ * @param decisions The server's decisions.
673
+ * @param decision The chosen one.
674
+ * @returns The offer id, or null when the server did not offer it.
675
+ */
676
+ function decisionOffer(decisions, decision) {
677
+ const index = decisions.findIndex((candidate) => sameDecision(candidate, decision));
678
+ return index < 0 ? null : `${DECISION_PREFIX}${index}`;
679
+ }
680
+ /**
681
+ * The form holding one answer to one question.
682
+ * @param card The card.
683
+ * @param questionId The question.
684
+ * @param answer The answer.
685
+ * @returns The form.
686
+ */
687
+ function answerForm(card, questionId, answer) {
688
+ const name = `${QUESTION_PREFIX}${questionId}`;
689
+ const offered = card.fields.find((candidate) => candidate.name === name)?.options?.some((option) => option.label === answer) ?? false;
690
+ return applyApprovalFormEvent(initialApprovalForm(card.fields), offered ? {
691
+ kind: "selection",
692
+ name,
693
+ value: [answer]
694
+ } : {
695
+ kind: "value",
696
+ name,
697
+ value: answer
698
+ });
699
+ }
700
+ /**
701
+ * The offer an ordinary "approve" resolves to.
702
+ * @param card The card.
703
+ * @returns The offer id, or null.
704
+ */
705
+ function ordinaryApprove(card) {
706
+ const { request } = card;
707
+ switch (request.approvalKind) {
708
+ case "command_execution":
709
+ case "file_change": return decisionOffer(request.availableDecisions, "accept");
710
+ case "apply_patch":
711
+ case "exec_command": return OFFER_APPROVE;
712
+ default: return OFFER_SUBMIT;
713
+ }
714
+ }
715
+ /**
716
+ * The offer an ordinary "decline" resolves to.
717
+ * @param card The card.
718
+ * @returns The offer id, or null.
719
+ */
720
+ function ordinaryDecline(card) {
721
+ const { request } = card;
722
+ if (request.approvalKind === "command_execution" || request.approvalKind === "file_change") return decisionOffer(request.availableDecisions, "decline");
723
+ return OFFER_DECLINE;
724
+ }
725
+ /**
726
+ * The offer and answers an ordinary choice resolves to.
727
+ * @param card The card.
728
+ * @param choice The panel's choice.
729
+ * @returns The resolution, or null when the server offers no such decision.
730
+ */
731
+ function resolveOrdinaryChoice(card, choice) {
732
+ const form = initialApprovalForm(card.fields);
733
+ const decisions = "availableDecisions" in card.request ? card.request.availableDecisions : [];
734
+ switch (choice.kind) {
735
+ case "command_decision":
736
+ case "file_change_decision": return withOffer(decisionOffer(decisions, choice.decision), form);
737
+ case "answer": return {
738
+ offerId: OFFER_SUBMIT,
739
+ form: answerForm(card, choice.questionId, choice.answer)
740
+ };
741
+ case "approve": return withOffer(ordinaryApprove(card), form);
742
+ default: return withOffer(ordinaryDecline(card), form);
743
+ }
744
+ }
745
+ /**
746
+ * A resolution, when an offer was found.
747
+ * @param offerId The offer id, or null.
748
+ * @param form The form.
749
+ * @returns The resolution, or null.
750
+ */
751
+ function withOffer(offerId, form) {
752
+ return offerId === null ? null : {
753
+ offerId,
754
+ form
755
+ };
756
+ }
757
+ /**
758
+ * The offer and answers a panel choice resolves to on one card.
759
+ * @param card The card.
760
+ * @param choice The panel's choice.
761
+ * @returns The resolution, or null when the server offers no such decision.
762
+ */
763
+ function resolveApprovalChoice(card, choice) {
764
+ if (card.kind === "ordinary") return resolveOrdinaryChoice(card, choice);
765
+ if (choice.kind === "approve" || choice.kind === "decline") return {
766
+ offerId: choice.kind === "approve" ? OFFER_APPROVE : OFFER_DECLINE,
767
+ form: initialApprovalForm([])
768
+ };
769
+ return null;
770
+ }
771
+ // src/ui/approvals/rules/safe-url.ts
772
+ const SAFE_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:"]);
773
+ /**
774
+ * A URL this surface may link to, or null.
775
+ * @param value The candidate.
776
+ * @returns The normalized href, or null for anything but http and https.
777
+ */
778
+ function safeHttpUrl(value) {
779
+ if (!URL.canParse(value)) return null;
780
+ const parsed = new URL(value);
781
+ return SAFE_PROTOCOLS.has(parsed.protocol) ? parsed.href : null;
782
+ }
783
+ // src/ui/approvals/rules/disclosure.ts
784
+ const NO_TURN = "The server published no turn identity for this request.";
785
+ const NO_ITEM = "The server published no item identity for this request.";
786
+ const NO_APPROVAL_ID = "The server issued no ApprovalId for this request.";
787
+ const NO_LINK = "The server published no link presentation for this request.";
788
+ const NO_REASON = "The server published no reason.";
789
+ const NO_COMMAND = "The server did not publish the command text.";
790
+ const NO_SAFE_URL = "The server published no safe http or https URL, so nothing here can be opened.";
791
+ const NO_FIELDS = "The server published no reviewed fields for this form, so it cannot be answered here.";
792
+ const SECRET_NOTICE = "A secret answer is never shown back, never defaulted, and never spoken.";
793
+ const NOTHING_GRANTABLE_NOTICE = "This request names no permission this browser can grant, so the only honest answer here is to grant nothing.";
794
+ const FILE_ACCESS_NOTICE = "The server published which file-access modes were asked for but no paths. This page never invents a path list, so only network access, grant scope, and strict auto review can be granted here.";
795
+ const NO_DECISIONS_NOTICE = "The server offered no decisions, so this request can only be read.";
796
+ /**
797
+ * One row.
798
+ * @param label The label.
799
+ * @param value The value.
800
+ * @param technical Whether the value is a technical token.
801
+ * @returns The row.
802
+ */
803
+ function row(label, value, technical = false) {
804
+ return Object.freeze({
805
+ label,
806
+ value,
807
+ technical
808
+ });
809
+ }
810
+ /**
811
+ * A technical row, or the words for its absence.
812
+ * @param label The label.
813
+ * @param value The value, or null.
814
+ * @param absent The words when the server published nothing.
815
+ * @returns The row.
816
+ */
817
+ function optionalRow(label, value, absent) {
818
+ return value === null ? row(label, absent) : row(label, value, true);
819
+ }
820
+ /**
821
+ * An instant as ISO text.
822
+ * @param value Milliseconds since the epoch.
823
+ * @returns The text.
824
+ */
825
+ function timestampText(value) {
826
+ return new Date(value).toISOString();
827
+ }
828
+ /**
829
+ * The request's own identity.
830
+ * @param approval The request.
831
+ * @returns The rows.
832
+ */
833
+ function ordinaryIdentityRows(approval) {
834
+ return Object.freeze([
835
+ row("Request id", String(approval.requestId), true),
836
+ row("Thread", approval.threadId, true),
837
+ optionalRow("Turn", approval.turnId, NO_TURN),
838
+ optionalRow("Item", approval.itemId, NO_ITEM),
839
+ optionalRow("Approval id", approval.approvalId, NO_APPROVAL_ID),
840
+ row("Expires", timestampText(approval.expiresAtMs), true)
841
+ ]);
842
+ }
843
+ /**
844
+ * The broker's own identity for this request, rendered on every ordinary card.
845
+ * @param approval The request.
846
+ * @returns The rows.
847
+ */
848
+ function brokerRows(approval) {
849
+ const binding = approval.binding;
850
+ return Object.freeze([
851
+ row("Broker child", binding.child, true),
852
+ row("Broker child epoch", binding.epoch, true),
853
+ optionalRow("Broker link", binding.link, NO_LINK),
854
+ row("Broker target", binding.target),
855
+ row("Broker effect", binding.effect)
856
+ ]);
857
+ }
858
+ /**
859
+ * The server's reason row.
860
+ * @param reason The reason, or null.
861
+ * @returns The row.
862
+ */
863
+ function reasonRow(reason) {
864
+ return row("Reason", reason ?? NO_REASON);
865
+ }
866
+ /**
867
+ * The words for a requested network scope.
868
+ * @param value The request's network flag.
869
+ * @returns The words.
870
+ */
871
+ function networkScopeText(value) {
872
+ if (value === null) return "The agent did not ask about network access.";
873
+ return value ? "Requested" : "Requested to stay closed";
874
+ }
875
+ /**
876
+ * The effect rows of a permissions request.
877
+ * @param approval The request.
878
+ * @returns The rows.
879
+ */
880
+ function permissionsRows(approval) {
881
+ const access = approval.requestedScope.fileAccess;
882
+ return [
883
+ row("Requested network access", networkScopeText(approval.requestedScope.network)),
884
+ row("Requested file access", access.length === 0 ? "None requested." : access.join(", ")),
885
+ reasonRow(approval.reason)
886
+ ];
887
+ }
888
+ /**
889
+ * The effect rows of an elicitation.
890
+ * @param approval The request.
891
+ * @returns The rows.
892
+ */
893
+ function elicitationRows(approval) {
894
+ const href = approval.url === null ? null : safeHttpUrl(approval.url);
895
+ return [
896
+ row("MCP server", approval.serverName, true),
897
+ row("Mode", approval.mode, true),
898
+ row("Message", approval.message),
899
+ href === null ? row("URL", NO_SAFE_URL) : row("URL", approval.url ?? href, true)
900
+ ];
901
+ }
902
+ /**
903
+ * The effect rows of a user-input request.
904
+ * @param approval The request.
905
+ * @returns The rows.
906
+ */
907
+ function userInputRows(approval) {
908
+ const secret = approval.questions.some((question) => question.isSecret);
909
+ return [row("Questions", String(approval.questions.length), true), row("Secret answers", secret ? "One or more answers are secret." : "None.")];
910
+ }
911
+ /**
912
+ * The effect rows of the families that gate an action.
913
+ * @param approval The request.
914
+ * @returns The rows.
915
+ */
916
+ function actionRows(approval) {
917
+ switch (approval.approvalKind) {
918
+ case "command_execution": return [optionalRow("Command", approval.command, NO_COMMAND), reasonRow(approval.reason)];
919
+ case "apply_patch": return [row("Files changed", String(approval.fileCount), true), reasonRow(approval.reason)];
920
+ case "exec_command": return [row("Command", approval.command.join(" "), true), reasonRow(approval.reason)];
921
+ default: return [reasonRow(approval.reason)];
922
+ }
923
+ }
924
+ /**
925
+ * The effect one ordinary request asks for.
926
+ * @param approval The request.
927
+ * @returns The rows.
928
+ */
929
+ function ordinaryEffectRows(approval) {
930
+ switch (approval.approvalKind) {
931
+ case "permissions": return Object.freeze(permissionsRows(approval));
932
+ case "user_input": return Object.freeze(userInputRows(approval));
933
+ case "elicitation": return Object.freeze(elicitationRows(approval));
934
+ default: return Object.freeze(actionRows(approval));
935
+ }
936
+ }
937
+ /**
938
+ * The safe links one ordinary request carries.
939
+ * @param approval The request.
940
+ * @returns The links; none unless an elicitation carries a safe URL.
941
+ */
942
+ function ordinaryLinks(approval) {
943
+ if (approval.approvalKind !== "elicitation" || approval.url === null) return Object.freeze([]);
944
+ const href = safeHttpUrl(approval.url);
945
+ return href === null ? Object.freeze([]) : Object.freeze([Object.freeze({
946
+ label: approval.url,
947
+ href
948
+ })]);
949
+ }
950
+ /**
951
+ * The notices of a permissions request. One unambiguous notice: a request
952
+ * this browser cannot grant at all does not also need the narrower reason for
953
+ * the file-access half of it.
954
+ * @param approval The request.
955
+ * @returns The notices.
956
+ */
957
+ function permissionsNotices(approval) {
958
+ if (!permissionsAreGrantable(approval)) return [NOTHING_GRANTABLE_NOTICE];
959
+ return approval.requestedScope.fileAccess.length > 0 ? [FILE_ACCESS_NOTICE] : [];
960
+ }
961
+ /**
962
+ * The notices of an elicitation.
963
+ * @param approval The request.
964
+ * @returns The notices.
965
+ */
966
+ function elicitationNotices(approval) {
967
+ const notices = [];
968
+ const missing = approval.mode === "url" ? missingUrlNotice(approval) : missingFieldsNotice(approval);
969
+ if (missing !== null) notices.push(missing);
970
+ if (approval.fields?.some((item) => item.secret) === true) notices.push(SECRET_NOTICE);
971
+ return notices;
972
+ }
973
+ /**
974
+ * The notice of a URL-mode elicitation without a safe URL.
975
+ * @param approval The request.
976
+ * @returns The notice, or null.
977
+ */
978
+ function missingUrlNotice(approval) {
979
+ return approval.url === null || safeHttpUrl(approval.url) === null ? NO_SAFE_URL : null;
980
+ }
981
+ /**
982
+ * The notice of a form-mode elicitation without published fields.
983
+ * @param approval The request.
984
+ * @returns The notice, or null.
985
+ */
986
+ function missingFieldsNotice(approval) {
987
+ return approval.fields === null ? NO_FIELDS : null;
988
+ }
989
+ /**
990
+ * The notices of a user-input request.
991
+ * @param approval The request.
992
+ * @returns The notices.
993
+ */
994
+ function userInputNotices(approval) {
995
+ return approval.questions.some((question) => question.isSecret) ? [SECRET_NOTICE] : [];
996
+ }
997
+ /**
998
+ * The notices of the families whose decisions the server enumerates.
999
+ * @param approval The request.
1000
+ * @returns The notices.
1001
+ */
1002
+ function enumeratedNotices(approval) {
1003
+ const notices = [];
1004
+ if (approval.approvalKind === "command_execution" && approval.command === null) notices.push(NO_COMMAND);
1005
+ if (approval.availableDecisions.length === 0) notices.push(NO_DECISIONS_NOTICE);
1006
+ return notices;
1007
+ }
1008
+ /**
1009
+ * What the server did not publish, or what this browser will not do.
1010
+ * @param approval The request.
1011
+ * @returns The notices.
1012
+ */
1013
+ function ordinaryNotices(approval) {
1014
+ switch (approval.approvalKind) {
1015
+ case "command_execution":
1016
+ case "file_change": return Object.freeze(enumeratedNotices(approval));
1017
+ case "permissions": return Object.freeze(permissionsNotices(approval));
1018
+ case "user_input": return Object.freeze(userInputNotices(approval));
1019
+ case "elicitation": return Object.freeze(elicitationNotices(approval));
1020
+ default: return Object.freeze([]);
1021
+ }
1022
+ }
1023
+ // src/ui/approvals/rules/disclosure-dynamic.ts
1024
+ /**
1025
+ * The identity of the call that raised the approval.
1026
+ * @param approval The request.
1027
+ * @returns The rows.
1028
+ */
1029
+ function dynamicIdentityRows(approval) {
1030
+ const identity = approval.identity;
1031
+ return Object.freeze([
1032
+ row("Calling thread", identity.threadId, true),
1033
+ row("Calling turn", identity.turnId, true),
1034
+ row("Dynamic call id", identity.callId, true),
1035
+ row("Tool namespace", identity.namespace, true),
1036
+ row("Tool", identity.tool, true),
1037
+ row("Manifest hash", identity.manifestHash, true),
1038
+ row("OperationId", identity.operationId, true),
1039
+ row("Child", identity.child, true),
1040
+ row("Child epoch", identity.epoch, true)
1041
+ ]);
1042
+ }
1043
+ /**
1044
+ * The words for a fork's effective boundary.
1045
+ * @param effect The effect.
1046
+ * @returns The words.
1047
+ */
1048
+ function boundaryText(effect) {
1049
+ if (effect.tool !== "fork_thread") return "Not applicable: this effect has no fork boundary.";
1050
+ const boundary = effect.effectiveBoundary;
1051
+ if (boundary.relation === "self") return `Self fork before the calling turn ${boundary.beforeTurnId}.`;
1052
+ return boundary.beforeTurnId === null ? "Fork of another thread from its current head." : `Fork of another thread before turn ${boundary.beforeTurnId}.`;
1053
+ }
1054
+ /**
1055
+ * The prompt an effect carries.
1056
+ * @param effect The effect.
1057
+ * @returns The prompt, or the words for a fork that starts no turn.
1058
+ */
1059
+ function promptText(effect) {
1060
+ if (effect.tool === "fork_thread") return effect.arguments.prompt ?? "No prompt: this fork starts no turn.";
1061
+ return effect.arguments.prompt;
1062
+ }
1063
+ /**
1064
+ * The effect exactly as the server published it.
1065
+ * @param approval The request.
1066
+ * @returns The rows.
1067
+ */
1068
+ function dynamicEffectRows(approval) {
1069
+ const effect = approval.effect;
1070
+ const initialTurn = effect.initialTurnOperationId;
1071
+ return Object.freeze([
1072
+ row("Target thread", effect.target ?? "A new thread that does not exist yet.", effect.target !== null),
1073
+ row("Prompt", promptText(effect)),
1074
+ row("Effective fork boundary", boundaryText(effect)),
1075
+ row("Mutation OperationId", effect.mutationOperationId, true),
1076
+ initialTurn === null ? row("Initial turn OperationId", "None: this effect starts no turn.") : row("Initial turn OperationId", initialTurn, true),
1077
+ row("Effect hash", approval.effectHash, true),
1078
+ row("Created", timestampText(approval.createdAtMs), true),
1079
+ row("Expires", timestampText(approval.expiresAtMs), true),
1080
+ row("Server summary", effect.visualSummary),
1081
+ approval.toolResult === null ? row("Tool result", "The server published no tool result yet.") : row("Tool result", approval.toolResult, true)
1082
+ ]);
1083
+ }
1084
+ // src/ui/approvals/rules/status.ts
1085
+ const RECOVERY = {
1086
+ staged: null,
1087
+ pending: null,
1088
+ approved: null,
1089
+ declined: null,
1090
+ cancelled: "The agent must raise the request again if it still needs the effect.",
1091
+ expired: "The agent must raise the request again if it still needs the effect.",
1092
+ stale: "Wait for the server to publish a fresh snapshot before acting on this.",
1093
+ disconnected: "Reconnect the workbench; the agent must raise the request again.",
1094
+ delivered: null,
1095
+ not_delivered: "The server never delivered the decision, so nothing was executed.",
1096
+ outcome_unknown: "The workbench never retries an unknown mutation. Read the thread before assuming either result."
1097
+ };
1098
+ const DECISION_WORDS = {
1099
+ approved: "You approved this request.",
1100
+ declined: "You declined this request.",
1101
+ cancelled: "The server cancelled this request."
1102
+ };
1103
+ const DEFAULT_DETAILS = {
1104
+ staged: "The server staged this request and has not opened it for a decision.",
1105
+ pending: "The server is waiting for your decision.",
1106
+ approved: "The server recorded your approval.",
1107
+ declined: "The server recorded your decline.",
1108
+ cancelled: "The server cancelled this request before it was answered.",
1109
+ expired: "This request passed its expiry before it was answered.",
1110
+ stale: "The request no longer belongs to the current child epoch.",
1111
+ disconnected: "The connection that owned this request was lost.",
1112
+ delivered: "The server delivered your decision.",
1113
+ not_delivered: "The server could not deliver your decision.",
1114
+ outcome_unknown: "The server lost the answer, so the outcome of your decision is unknown."
1115
+ };
1116
+ const CLOCK_EXPIRED_ORDINARY = "This request passed its expiry before you answered it. The server has not published its terminal record yet.";
1117
+ const CLOCK_EXPIRED_DYNAMIC = "This effect passed its expiry before you answered it. The server has not published its terminal record yet.";
1118
+ const DYNAMIC_CAUSES = {
1119
+ person_approved: "You approved this effect.",
1120
+ person_declined: "You declined this effect.",
1121
+ deadline_reached: "The approval deadline passed before you answered.",
1122
+ call_cancelled: "The agent cancelled its own call.",
1123
+ caller_turn_interrupted: "The calling turn was interrupted.",
1124
+ server_shutdown: "The server shut down before you answered.",
1125
+ browser_disconnected: "This browser lost the approval before you answered.",
1126
+ child_disconnected: "The Codex child disconnected before the decision reached it."
1127
+ };
1128
+ const DYNAMIC_DECISION_WORDS = {
1129
+ approved: "You approved this effect.",
1130
+ declined: "You declined this effect.",
1131
+ expired: null,
1132
+ cancelled: null,
1133
+ disconnected: null
1134
+ };
1135
+ /**
1136
+ * Why the connection removes authority, if it does.
1137
+ * @param context The authority context.
1138
+ * @returns The reason, or null.
1139
+ */
1140
+ function connectionRemoval(context) {
1141
+ if (context.connection === "stopped") return context.connectionReason ?? "The browser is not connected to the server.";
1142
+ if (context.connection === "reconnecting") return context.connectionReason ?? "The browser is reconnecting to the server.";
1143
+ return null;
1144
+ }
1145
+ /**
1146
+ * Why a decision cannot be sent, if it cannot.
1147
+ * @param phase The phase.
1148
+ * @param context The authority context.
1149
+ * @returns The reason, or null while authority is live.
1150
+ */
1151
+ function authorityRemoval(phase, context) {
1152
+ if (phase !== "pending") return "This request is no longer waiting for a decision.";
1153
+ const connection = connectionRemoval(context);
1154
+ if (connection !== null) return connection;
1155
+ if (context.staleSnapshot) return "This snapshot is behind the server, so a decision could name the wrong request.";
1156
+ if (!context.canCommand) return "This browser cannot answer approvals until it holds a usable workbench command lease.";
1157
+ return context.canRespond ? null : "The workbench no longer accepts a response for this request.";
1158
+ }
1159
+ /**
1160
+ * One status.
1161
+ * @param phase The phase.
1162
+ * @param detail The words for it.
1163
+ * @param decision What the server recorded, or null.
1164
+ * @param delivery The delivery outcome, or null.
1165
+ * @param context The authority context.
1166
+ * @returns The status.
1167
+ */
1168
+ function statusFor(phase, detail, decision, delivery, context) {
1169
+ const authorityReason = authorityRemoval(phase, context);
1170
+ return Object.freeze({
1171
+ phase,
1172
+ label: PHASE_LABELS[phase],
1173
+ detail,
1174
+ recovery: RECOVERY[phase],
1175
+ decision,
1176
+ delivery,
1177
+ terminal: TERMINAL_PHASES.has(phase),
1178
+ authority: authorityReason === null ? "live" : "removed",
1179
+ authorityReason,
1180
+ resumable: false
1181
+ });
1182
+ }
1183
+ /**
1184
+ * The phase of a settled ordinary lifecycle: its delivery when the server
1185
+ * published one, else its decision.
1186
+ * @param lifecycle The settled lifecycle.
1187
+ * @returns The phase.
1188
+ */
1189
+ function settledPhase(lifecycle) {
1190
+ if (lifecycle.outcome === "delivered") return "delivered";
1191
+ if (lifecycle.outcome === "not_delivered") return "not_delivered";
1192
+ return lifecycle.decision;
1193
+ }
1194
+ /**
1195
+ * The phase of one ordinary approval.
1196
+ * @param approval The request.
1197
+ * @param context The authority context.
1198
+ * @returns The phase; a pending request past its expiry is expired.
1199
+ */
1200
+ function ordinaryPhase(approval, context) {
1201
+ const lifecycle = approval.lifecycle;
1202
+ switch (lifecycle.state) {
1203
+ case "pending": return approval.expiresAtMs <= context.nowMs ? "expired" : "pending";
1204
+ case "settled": return settledPhase(lifecycle);
1205
+ default: return lifecycle.state;
1206
+ }
1207
+ }
1208
+ /**
1209
+ * The detail of one ordinary approval: the server's own reason once it
1210
+ * published one, the clock's expiry, else the phase's default.
1211
+ * @param approval The request.
1212
+ * @param phase The phase.
1213
+ * @returns The detail.
1214
+ */
1215
+ function ordinaryDetail(approval, phase) {
1216
+ const lifecycle = approval.lifecycle;
1217
+ if (lifecycle.state === "pending" && phase === "expired") return CLOCK_EXPIRED_ORDINARY;
1218
+ return (lifecycle.state === "pending" || lifecycle.state === "staged" ? null : lifecycle.reason) ?? DEFAULT_DETAILS[phase];
1219
+ }
1220
+ /**
1221
+ * The status of one ordinary approval.
1222
+ * @param approval The request.
1223
+ * @param context The authority context.
1224
+ * @returns The status.
1225
+ */
1226
+ function ordinaryApprovalStatus(approval, context) {
1227
+ const phase = ordinaryPhase(approval, context);
1228
+ const lifecycle = approval.lifecycle;
1229
+ const decision = lifecycle.decision === null ? null : DECISION_WORDS[lifecycle.decision];
1230
+ return statusFor(phase, ordinaryDetail(approval, phase), decision, lifecycle.outcome, context);
1231
+ }
1232
+ /**
1233
+ * The detail of one dynamic approval.
1234
+ * @param approval The request.
1235
+ * @param phase The phase.
1236
+ * @returns The detail.
1237
+ */
1238
+ function dynamicDetail(approval, phase) {
1239
+ if (approval.state === "pending" && phase === "expired") return CLOCK_EXPIRED_DYNAMIC;
1240
+ return approval.decision === null ? DEFAULT_DETAILS[phase] : DYNAMIC_CAUSES[approval.decision.cause];
1241
+ }
1242
+ /**
1243
+ * The status of one dynamic approval.
1244
+ * @param approval The request.
1245
+ * @param context The authority context.
1246
+ * @returns The status.
1247
+ */
1248
+ function dynamicApprovalStatus(approval, context) {
1249
+ const phase = approval.state === "pending" && approval.expiresAtMs <= context.nowMs ? "expired" : approval.state;
1250
+ const decision = approval.decision === null ? null : DYNAMIC_DECISION_WORDS[approval.decision.outcome];
1251
+ return statusFor(phase, dynamicDetail(approval, phase), decision, approval.delivery, context);
1252
+ }
1253
+ // src/ui/approvals/rules/projection.ts
1254
+ const SUMMARY_LIMIT = 240;
1255
+ const NO_REQUEST = "No Codex approval request is open.";
1256
+ /**
1257
+ * Text within the summary limit.
1258
+ * @param value The text.
1259
+ * @returns The text, cut with an ellipsis when long.
1260
+ */
1261
+ function bounded(value) {
1262
+ return value.length <= SUMMARY_LIMIT ? value : `${value.slice(0, SUMMARY_LIMIT)}…`;
1263
+ }
1264
+ /**
1265
+ * A count with its noun.
1266
+ * @param count The count.
1267
+ * @param noun The singular noun.
1268
+ * @returns The phrase.
1269
+ */
1270
+ function counted(count, noun) {
1271
+ return `${count} ${noun}${count === 1 ? "" : "s"}`;
1272
+ }
1273
+ /**
1274
+ * One sentence saying what an ordinary request asks for.
1275
+ * @param approval The request.
1276
+ * @returns The summary.
1277
+ */
1278
+ function ordinarySummary(approval) {
1279
+ switch (approval.approvalKind) {
1280
+ case "user_input": return `Answer ${counted(approval.questions.length, "question")} from a tool.`;
1281
+ case "elicitation": return bounded(`${approval.serverName} asks: ${approval.message}`);
1282
+ case "file_change":
1283
+ case "permissions": return STATIC_SUMMARIES[approval.approvalKind];
1284
+ default: return actionSummary(approval);
1285
+ }
1286
+ }
1287
+ const STATIC_SUMMARIES = {
1288
+ file_change: "Write the agent's proposed file changes.",
1289
+ permissions: "Widen the sandbox permissions for this agent."
1290
+ };
1291
+ /**
1292
+ * One sentence saying what an action-gating request asks to run or apply.
1293
+ * @param approval The request.
1294
+ * @returns The summary.
1295
+ */
1296
+ function actionSummary(approval) {
1297
+ switch (approval.approvalKind) {
1298
+ case "command_execution": return approval.command === null ? "Run a command the server did not publish." : bounded(`Run ${approval.command}`);
1299
+ case "exec_command": return bounded(`Run ${approval.command.join(" ")}`);
1300
+ default: return `Apply a patch across ${counted(approval.fileCount, "file")}.`;
1301
+ }
1302
+ }
1303
+ /**
1304
+ * One ordinary card.
1305
+ * @param approval The request.
1306
+ * @param context The authority context.
1307
+ * @returns The card.
1308
+ */
1309
+ function ordinaryCard(approval, context) {
1310
+ const status = ordinaryApprovalStatus(approval, context);
1311
+ return Object.freeze({
1312
+ kind: "ordinary",
1313
+ key: `ordinary:${String(approval.requestId)}`,
1314
+ family: approval.approvalKind,
1315
+ title: FAMILY_TITLES[approval.approvalKind],
1316
+ summary: ordinarySummary(approval),
1317
+ request: approval,
1318
+ identity: ordinaryIdentityRows(approval),
1319
+ broker: brokerRows(approval),
1320
+ effect: ordinaryEffectRows(approval),
1321
+ fields: approvalFields(approval),
1322
+ links: ordinaryLinks(approval),
1323
+ offers: approvalOffers(approval, status.phase, status.authority),
1324
+ spoken: ordinarySpoken(approval, status.phase),
1325
+ status,
1326
+ expiresAtMs: approval.expiresAtMs,
1327
+ notices: ordinaryNotices(approval)
1328
+ });
1329
+ }
1330
+ /**
1331
+ * One dynamic card.
1332
+ * @param approval The request.
1333
+ * @param context The authority context.
1334
+ * @returns The card.
1335
+ */
1336
+ function dynamicCard(approval, context) {
1337
+ const status = dynamicApprovalStatus(approval, context);
1338
+ return Object.freeze({
1339
+ kind: "dynamic",
1340
+ key: `dynamic:${approval.identity.callId}:${approval.effectHash}`,
1341
+ tool: approval.identity.tool,
1342
+ title: DYNAMIC_TITLES[approval.identity.tool],
1343
+ summary: bounded(approval.effect.visualSummary),
1344
+ request: approval,
1345
+ identity: dynamicIdentityRows(approval),
1346
+ effect: dynamicEffectRows(approval),
1347
+ offers: dynamicOffers(status.phase, status.authority),
1348
+ spoken: dynamicSpoken(),
1349
+ status,
1350
+ effectHash: approval.effectHash,
1351
+ toolResult: approval.toolResult,
1352
+ expiresAtMs: approval.expiresAtMs,
1353
+ notices: Object.freeze([IMMUTABLE_EFFECT_NOTICE, NO_RESUME_NOTICE])
1354
+ });
1355
+ }
1356
+ /**
1357
+ * The immutable target a card's request was raised against.
1358
+ * @param card The card.
1359
+ * @returns The target.
1360
+ */
1361
+ function approvalTarget(card) {
1362
+ if (card.kind === "ordinary") return card.request.binding.target;
1363
+ return card.request.effect.target ?? "a new thread that does not exist yet";
1364
+ }
1365
+ /**
1366
+ * The connection facts a transport state carries.
1367
+ * @param state The transport state.
1368
+ * @returns The connection word.
1369
+ */
1370
+ function connectionOf(state) {
1371
+ if (state.connection === "connected") return "connected";
1372
+ return state.connection === "reconnecting" ? "reconnecting" : "stopped";
1373
+ }
1374
+ /**
1375
+ * The authority context for one family.
1376
+ * @param input The projection input.
1377
+ * @param canRespond Whether the transport accepts that family's response.
1378
+ * @returns The context.
1379
+ */
1380
+ function authorityContext(input, canRespond) {
1381
+ const state = input.state;
1382
+ return Object.freeze({
1383
+ nowMs: input.nowMs,
1384
+ canCommand: input.canCommand,
1385
+ canRespond,
1386
+ connection: connectionOf(state),
1387
+ staleSnapshot: state.kind === "stream",
1388
+ connectionReason: "reason" in state ? state.reason : null
1389
+ });
1390
+ }
1391
+ /**
1392
+ * The beacon's announcement.
1393
+ * @param pending How many cards are pending.
1394
+ * @param total How many cards there are.
1395
+ * @returns The announcement.
1396
+ */
1397
+ function announcement(pending, total) {
1398
+ if (pending > 0) return `${counted(pending, "Codex approval")} waiting for you.`;
1399
+ return total === 0 ? NO_REQUEST : `No Codex approval is waiting. ${counted(total, "recorded request")}.`;
1400
+ }
1401
+ /**
1402
+ * The app-global beacon.
1403
+ * @param cards The cards.
1404
+ * @returns The beacon.
1405
+ */
1406
+ function beacon(cards) {
1407
+ const pending = cards.filter((card) => card.status.phase === "pending").length;
1408
+ const entries = cards.map((card) => Object.freeze({
1409
+ key: card.key,
1410
+ label: `${card.title}: ${card.status.label}`,
1411
+ phase: card.status.phase,
1412
+ target: approvalTarget(card)
1413
+ }));
1414
+ return Object.freeze({
1415
+ scope: "app_global",
1416
+ pending,
1417
+ total: cards.length,
1418
+ announcement: announcement(pending, cards.length),
1419
+ entries: Object.freeze(entries)
1420
+ });
1421
+ }
1422
+ const RECONCILIATION_LABELS = {
1423
+ delivered: "Decision delivered",
1424
+ not_delivered: "Decision not delivered",
1425
+ outcome_unknown: "Decision outcome unknown"
1426
+ };
1427
+ const RECONCILIATION_DETAILS = {
1428
+ delivered: "The server confirmed the workbench delivered this decision.",
1429
+ not_delivered: "The server confirmed nothing was delivered, so nothing was executed.",
1430
+ outcome_unknown: "The server lost the answer. The workbench never retries an unknown mutation; read the thread before assuming either result."
1431
+ };
1432
+ /**
1433
+ * The server's authoritative outcome for the last operation.
1434
+ * @param snapshot The snapshot.
1435
+ * @returns The reconciliation, or null when none was published.
1436
+ */
1437
+ function reconciliation(snapshot) {
1438
+ const operation = snapshot.operation;
1439
+ if (operation === null) return null;
1440
+ return Object.freeze({
1441
+ operationId: operation.operationId,
1442
+ outcome: operation.outcome,
1443
+ label: RECONCILIATION_LABELS[operation.outcome],
1444
+ detail: operation.message ?? RECONCILIATION_DETAILS[operation.outcome]
1445
+ });
1446
+ }
1447
+ /**
1448
+ * Every card, pending first by expiry, then the rest in the server's order.
1449
+ * @param snapshot The snapshot.
1450
+ * @param ordinaryContext The ordinary authority context.
1451
+ * @param dynamicContext The dynamic authority context.
1452
+ * @returns The cards.
1453
+ */
1454
+ function orderedCards(snapshot, ordinaryContext, dynamicContext) {
1455
+ const cards = [...snapshot.approvals.map((approval) => ordinaryCard(approval, ordinaryContext)), ...snapshot.dynamicApprovals.map((approval) => dynamicCard(approval, dynamicContext))];
1456
+ const pending = cards.filter((card) => card.status.phase === "pending");
1457
+ const settled = cards.filter((card) => card.status.phase !== "pending");
1458
+ return Object.freeze([...pending.toSorted((left, right) => left.expiresAtMs - right.expiresAtMs), ...settled]);
1459
+ }
1460
+ /**
1461
+ * Why no approval can be answered, if none can.
1462
+ * @param input The projection input.
1463
+ * @param context The ordinary authority context.
1464
+ * @returns The reason, or null while authority is live.
1465
+ */
1466
+ function surfaceAuthorityReason(input, context) {
1467
+ const connection = connectionAuthorityReason(input.state.snapshot === null, context);
1468
+ if (connection !== null) return connection;
1469
+ if (context.staleSnapshot) return "This snapshot is behind the server, so no decision can name the right request.";
1470
+ return input.canCommand ? null : "This browser cannot answer approvals until it holds a usable workbench command lease.";
1471
+ }
1472
+ /**
1473
+ * Why the connection removes every authority, if it does.
1474
+ * @param noSnapshot Whether the server has published no snapshot.
1475
+ * @param context The ordinary authority context.
1476
+ * @returns The reason, or null.
1477
+ */
1478
+ function connectionAuthorityReason(noSnapshot, context) {
1479
+ if (noSnapshot) return context.connectionReason ?? "The workbench has published no snapshot, so no approval can be answered.";
1480
+ if (context.connection !== "connected") return context.connectionReason ?? "The browser is not connected to the server.";
1481
+ return null;
1482
+ }
1483
+ /**
1484
+ * The surface.
1485
+ * @param input The projection input.
1486
+ * @returns The view.
1487
+ */
1488
+ function projectWorkbenchApprovals(input) {
1489
+ const context = authorityContext(input, input.canRespondOrdinary);
1490
+ const snapshot = input.state.snapshot;
1491
+ const cards = snapshot === null ? Object.freeze([]) : orderedCards(snapshot, context, authorityContext(input, input.canRespondDynamic));
1492
+ const authorityReason = surfaceAuthorityReason(input, context);
1493
+ return Object.freeze({
1494
+ beacon: beacon(cards),
1495
+ cards,
1496
+ reconciliation: snapshot === null ? null : reconciliation(snapshot),
1497
+ authority: authorityReason === null ? "live" : "removed",
1498
+ authorityReason,
1499
+ empty: cards.length === 0 ? NO_REQUEST : null
1500
+ });
1501
+ }
1502
+ /**
1503
+ * The projection input for one transport state. The transport already
1504
+ * answers whether it would take each response; asking it keeps an approval it
1505
+ * has stopped accepting from showing a live decision.
1506
+ * @param state The transport state.
1507
+ * @param nowMs The clock.
1508
+ * @param capabilities The transport capabilities.
1509
+ * @returns The input.
1510
+ */
1511
+ function workbenchApprovalsInput(state, nowMs, capabilities) {
1512
+ return Object.freeze({
1513
+ state,
1514
+ nowMs,
1515
+ canCommand: capabilities.canCommand,
1516
+ canRespondOrdinary: capabilities.supportsCommand("approvalRespond"),
1517
+ canRespondDynamic: capabilities.supportsCommand("dynamicApprovalRespond")
1518
+ });
1519
+ }
1520
+ // src/ui/approval-forms/rules/form-validation.ts
1521
+ const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/u;
1522
+ const EMAIL_PATTERN = /^[^\s@]+@[^\s@.]+(?:\.[^\s@.]+)+$/u;
1523
+ const FORMATS = {
1524
+ url: {
1525
+ /**
1526
+ * Only http and https.
1527
+ * @param raw The answer.
1528
+ * @returns True for a safe URL.
1529
+ */
1530
+ accepts: (raw) => safeHttpUrl(raw) !== null,
1531
+ message: "must be an http or https URL."
1532
+ },
1533
+ email: {
1534
+ /**
1535
+ * An address with a dotted domain.
1536
+ * @param raw The answer.
1537
+ * @returns True for an address.
1538
+ */
1539
+ accepts: (raw) => EMAIL_PATTERN.test(raw),
1540
+ message: "must be an email address."
1541
+ },
1542
+ date: {
1543
+ /**
1544
+ * A YYYY-MM-DD date.
1545
+ * @param raw The answer.
1546
+ * @returns True for a date.
1547
+ */
1548
+ accepts: (raw) => DATE_PATTERN.test(raw),
1549
+ message: "must be a YYYY-MM-DD date."
1550
+ },
1551
+ date_time: {
1552
+ /**
1553
+ * Anything the platform parses as a date and time.
1554
+ * @param raw The answer.
1555
+ * @returns True when it parses.
1556
+ */
1557
+ accepts: (raw) => !Number.isNaN(Date.parse(raw)),
1558
+ message: "must be a date and time."
1559
+ }
1560
+ };
1561
+ /**
1562
+ * One error.
1563
+ * @param item The field.
1564
+ * @param message What is wrong.
1565
+ * @returns The error list.
1566
+ */
1567
+ function failure(item, message) {
1568
+ return [{
1569
+ name: item.name,
1570
+ message: `${item.label} ${message}`
1571
+ }];
1572
+ }
1573
+ /**
1574
+ * The option labels a field offers.
1575
+ * @param item The field.
1576
+ * @returns The labels.
1577
+ */
1578
+ function optionLabels(item) {
1579
+ return new Set((item.options ?? []).map((option) => option.label));
1580
+ }
1581
+ /**
1582
+ * Whether a parsed number sits inside the field's bounds.
1583
+ * @param item The field.
1584
+ * @param parsed The number.
1585
+ * @returns The bound error, or none.
1586
+ */
1587
+ function rangeErrors(item, parsed) {
1588
+ if (item.minimum !== null && parsed < item.minimum) return failure(item, `must be at least ${item.minimum}.`);
1589
+ if (item.maximum !== null && parsed > item.maximum) return failure(item, `must be at most ${item.maximum}.`);
1590
+ return [];
1591
+ }
1592
+ /**
1593
+ * A number field's errors.
1594
+ * @param item The field.
1595
+ * @param raw The answer.
1596
+ * @returns The errors.
1597
+ */
1598
+ function numberErrors(item, raw) {
1599
+ const parsed = Number(raw);
1600
+ if (raw.trim().length === 0 || Number.isNaN(parsed)) return failure(item, "must be a number.");
1601
+ if (item.control === "integer" && !Number.isInteger(parsed)) return failure(item, "must be a whole number.");
1602
+ return rangeErrors(item, parsed);
1603
+ }
1604
+ /**
1605
+ * A text field's length errors.
1606
+ * @param item The field.
1607
+ * @param raw The answer.
1608
+ * @returns The errors.
1609
+ */
1610
+ function lengthErrors(item, raw) {
1611
+ if (item.minLength !== null && raw.length < item.minLength) return failure(item, `needs at least ${item.minLength} characters.`);
1612
+ if (item.maxLength !== null && raw.length > item.maxLength) return failure(item, `allows at most ${item.maxLength} characters.`);
1613
+ return [];
1614
+ }
1615
+ /**
1616
+ * A formatted text field's errors.
1617
+ * @param item The field.
1618
+ * @param raw The answer.
1619
+ * @returns The errors.
1620
+ */
1621
+ function formatErrors(item, raw) {
1622
+ const format = FORMATS[item.control];
1623
+ if (format === void 0 || format.accepts(raw)) return [];
1624
+ return failure(item, format.message);
1625
+ }
1626
+ /**
1627
+ * A text field's errors.
1628
+ * @param item The field.
1629
+ * @param raw The answer.
1630
+ * @returns The errors.
1631
+ */
1632
+ function textErrors(item, raw) {
1633
+ const length = lengthErrors(item, raw);
1634
+ return length.length > 0 ? length : formatErrors(item, raw);
1635
+ }
1636
+ /**
1637
+ * How many answers a multiple-choice field holds, counting a free-text other.
1638
+ * @param item The field.
1639
+ * @param selected The chosen options.
1640
+ * @param other The free text.
1641
+ * @returns The count.
1642
+ */
1643
+ function answerCount(item, selected, other) {
1644
+ const extra = item.allowsOther && other.trim().length > 0 ? 1 : 0;
1645
+ return selected.length + extra;
1646
+ }
1647
+ /**
1648
+ * A multiple-choice field's count errors.
1649
+ * @param item The field.
1650
+ * @param total How many answers it holds.
1651
+ * @returns The errors.
1652
+ */
1653
+ function countErrors(item, total) {
1654
+ if (item.minimumItems !== null && total < item.minimumItems) return failure(item, `needs at least ${item.minimumItems} answers.`);
1655
+ if (item.maximumItems !== null && total > item.maximumItems) return failure(item, `allows at most ${item.maximumItems} answers.`);
1656
+ return requiredError(item, total);
1657
+ }
1658
+ /**
1659
+ * The error of a required field with no answer.
1660
+ * @param item The field.
1661
+ * @param total How many answers it holds.
1662
+ * @returns The error, or none.
1663
+ */
1664
+ function requiredError(item, total) {
1665
+ return item.required && total === 0 ? failure(item, "needs an answer.") : [];
1666
+ }
1667
+ /**
1668
+ * A multiple-choice field's errors.
1669
+ * @param item The field.
1670
+ * @param selected The chosen options.
1671
+ * @param other The free text.
1672
+ * @returns The errors.
1673
+ */
1674
+ function selectionErrors(item, selected, other) {
1675
+ const offered = optionLabels(item);
1676
+ const unknown = selected.find((label) => !offered.has(label));
1677
+ if (unknown !== void 0) return failure(item, `does not offer "${unknown}".`);
1678
+ return countErrors(item, answerCount(item, selected, other));
1679
+ }
1680
+ /**
1681
+ * A single-choice field's errors.
1682
+ * @param item The field.
1683
+ * @param raw The answer.
1684
+ * @returns The errors.
1685
+ */
1686
+ function enumErrors(item, raw) {
1687
+ return optionLabels(item).has(raw) ? [] : failure(item, `does not offer "${raw}".`);
1688
+ }
1689
+ /**
1690
+ * A text-carrying field's errors, by control.
1691
+ * @param item The field.
1692
+ * @param raw The answer.
1693
+ * @returns The errors.
1694
+ */
1695
+ function valueErrors(item, raw) {
1696
+ if (item.control === "enum") return enumErrors(item, raw);
1697
+ if (item.control === "number" || item.control === "integer") return numberErrors(item, raw);
1698
+ return textErrors(item, raw);
1699
+ }
1700
+ /**
1701
+ * One field's errors.
1702
+ * @param item The field.
1703
+ * @param state The form.
1704
+ * @returns The errors.
1705
+ */
1706
+ function fieldErrors(item, state) {
1707
+ if (item.control === "boolean") return [];
1708
+ if (item.control === "multi_enum") return selectionErrors(item, formSelection(state, item.name), formValue(state, item.name));
1709
+ const raw = formValue(state, item.name);
1710
+ if (raw.length === 0) return item.required ? failure(item, "needs an answer.") : [];
1711
+ return valueErrors(item, raw);
1712
+ }
1713
+ /**
1714
+ * Every error across the reviewed fields.
1715
+ * @param fields The fields that were rendered.
1716
+ * @param state The form.
1717
+ * @returns The errors, in field order.
1718
+ */
1719
+ function validateApprovalForm(fields, state) {
1720
+ return Object.freeze(fields.flatMap((item) => fieldErrors(item, state)));
1721
+ }
1722
+ // src/ui/approval-forms/rules/response.ts
1723
+ const DEFAULT_DECLINE_REASON = "Declined at the workbench.";
1724
+ const UNKNOWN_OFFER = "That decision is not offered for this request.";
1725
+ /**
1726
+ * The index a decision offer names.
1727
+ * @param offerId The offer id.
1728
+ * @returns The index, or null for any other offer.
1729
+ */
1730
+ function decisionIndex(offerId) {
1731
+ if (!offerId.startsWith("decision:")) return null;
1732
+ const index = Number(offerId.slice(9));
1733
+ return Number.isInteger(index) && index >= 0 ? index : null;
1734
+ }
1735
+ /**
1736
+ * A refused draft.
1737
+ * @param message Why.
1738
+ * @returns The result.
1739
+ */
1740
+ function invalid(message) {
1741
+ return {
1742
+ ok: false,
1743
+ errors: Object.freeze([{
1744
+ name: "offer",
1745
+ message
1746
+ }])
1747
+ };
1748
+ }
1749
+ /**
1750
+ * The answers one question collected: its selection, and its free text when given.
1751
+ * @param question The question.
1752
+ * @param form The form.
1753
+ * @returns The answers.
1754
+ */
1755
+ function questionAnswer(question, form) {
1756
+ const name = `${QUESTION_PREFIX}${question.id}`;
1757
+ const other = formValue(form, name).trim();
1758
+ const selected = question.options === null ? [] : [...formSelection(form, name)];
1759
+ return other.length === 0 ? selected : [...selected, other];
1760
+ }
1761
+ /**
1762
+ * The answers of every question.
1763
+ * @param approval The request.
1764
+ * @param form The form.
1765
+ * @returns The answers by question id.
1766
+ */
1767
+ function questionAnswers(approval, form) {
1768
+ const answers = {};
1769
+ for (const question of approval.questions) answers[question.id] = { answers: questionAnswer(question, form) };
1770
+ return answers;
1771
+ }
1772
+ /**
1773
+ * One elicitation field's content value, when it holds one.
1774
+ * @param item The field.
1775
+ * @param form The form.
1776
+ * @returns The typed value, or undefined when nothing was answered.
1777
+ */
1778
+ function fieldContent(item, form) {
1779
+ if (item.control === "boolean") return formFlag(form, item.name);
1780
+ if (item.control === "multi_enum") {
1781
+ const selected = [...formSelection(form, item.name)];
1782
+ return selected.length > 0 ? selected : void 0;
1783
+ }
1784
+ return textContent(item, formValue(form, item.name));
1785
+ }
1786
+ /**
1787
+ * A text-carrying field's typed content value.
1788
+ * @param item The field.
1789
+ * @param raw The answer.
1790
+ * @returns A number for numeric controls, the text otherwise, or undefined when empty.
1791
+ */
1792
+ function textContent(item, raw) {
1793
+ if (raw.length === 0) return;
1794
+ return item.control === "number" || item.control === "integer" ? Number(raw) : raw;
1795
+ }
1796
+ /**
1797
+ * The content of an accepted form-mode elicitation.
1798
+ * @param approval The request.
1799
+ * @param fields The reviewed fields.
1800
+ * @param form The form.
1801
+ * @returns The content, or null for URL mode or an unpublished form.
1802
+ */
1803
+ function elicitationContent(approval, fields, form) {
1804
+ if (approval.mode === "url" || approval.fields === null) return null;
1805
+ const content = {};
1806
+ for (const item of fields) {
1807
+ const value = fieldContent(item, form);
1808
+ if (item.name.startsWith("field:") && value !== void 0) content[item.name.slice(6)] = value;
1809
+ }
1810
+ return content;
1811
+ }
1812
+ /**
1813
+ * The reviewed permissions grant. Only a request that names network access
1814
+ * offers this decision at all.
1815
+ * @param form The form.
1816
+ * @returns The response.
1817
+ */
1818
+ function permissionsGrant(form) {
1819
+ const scope = formValue(form, "permission:scope") === "session" ? "session" : "turn";
1820
+ const strict = formFlag(form, PERMISSION_STRICT_REVIEW);
1821
+ return {
1822
+ approvalKind: "permissions",
1823
+ permissions: { network: { enabled: formFlag(form, PERMISSION_NETWORK) } },
1824
+ scope,
1825
+ ...strict ? { strictAutoReview: true } : {}
1826
+ };
1827
+ }
1828
+ /**
1829
+ * The permissions response for one offer.
1830
+ * @param offerId The offer.
1831
+ * @param form The form.
1832
+ * @returns The response; a decline grants nothing for the turn.
1833
+ */
1834
+ function permissionsResponse(offerId, form) {
1835
+ if (offerId === "decline") return {
1836
+ approvalKind: "permissions",
1837
+ permissions: {},
1838
+ scope: "turn"
1839
+ };
1840
+ return permissionsGrant(form);
1841
+ }
1842
+ /**
1843
+ * A legacy review decision, with the person's decline reason.
1844
+ * @param offerId The offer.
1845
+ * @param form The form.
1846
+ * @returns The decision, or null for an unoffered decision.
1847
+ */
1848
+ function legacyDecision(offerId, form) {
1849
+ if (offerId === "approve") return "approved";
1850
+ if (offerId === "abort") return "abort";
1851
+ if (offerId !== "decline") return null;
1852
+ const reason = formValue(form, DECLINE_REASON).trim();
1853
+ return { denied: { rejection: reason.length === 0 ? DEFAULT_DECLINE_REASON : reason } };
1854
+ }
1855
+ /**
1856
+ * The response of a legacy family.
1857
+ * @param approval The request.
1858
+ * @param offerId The offer.
1859
+ * @param form The form.
1860
+ * @returns The response, or null.
1861
+ */
1862
+ function legacyResponse(approval, offerId, form) {
1863
+ const decision = legacyDecision(offerId, form);
1864
+ if (decision === null) return null;
1865
+ return approval.approvalKind === "apply_patch" ? {
1866
+ approvalKind: "apply_patch",
1867
+ decision
1868
+ } : {
1869
+ approvalKind: "exec_command",
1870
+ decision
1871
+ };
1872
+ }
1873
+ /**
1874
+ * The response of a family whose decisions the server enumerates: exactly the
1875
+ * server-offered decision the offer named.
1876
+ * @param approval The request.
1877
+ * @param offerId The offer.
1878
+ * @returns The response, or null for an unoffered decision.
1879
+ */
1880
+ function enumeratedResponse(approval, offerId) {
1881
+ const index = decisionIndex(offerId);
1882
+ if (index === null) return null;
1883
+ if (approval.approvalKind === "command_execution") {
1884
+ const decision = approval.availableDecisions[index];
1885
+ return decision === void 0 ? null : {
1886
+ approvalKind: "command_execution",
1887
+ decision
1888
+ };
1889
+ }
1890
+ const decision = approval.availableDecisions[index];
1891
+ return decision === void 0 ? null : {
1892
+ approvalKind: "file_change",
1893
+ decision
1894
+ };
1895
+ }
1896
+ /**
1897
+ * The response of an elicitation.
1898
+ * @param approval The request.
1899
+ * @param fields The reviewed fields.
1900
+ * @param offerId The offer.
1901
+ * @param form The form.
1902
+ * @returns The response.
1903
+ */
1904
+ function elicitationResponse(approval, fields, offerId, form) {
1905
+ if (offerId === "decline") return {
1906
+ approvalKind: "elicitation",
1907
+ action: "decline",
1908
+ content: null,
1909
+ _meta: null
1910
+ };
1911
+ if (offerId === "cancel") return {
1912
+ approvalKind: "elicitation",
1913
+ action: "cancel",
1914
+ content: null,
1915
+ _meta: null
1916
+ };
1917
+ return {
1918
+ approvalKind: "elicitation",
1919
+ action: "accept",
1920
+ content: elicitationContent(approval, fields, form),
1921
+ _meta: null
1922
+ };
1923
+ }
1924
+ /**
1925
+ * The response of a user-input request.
1926
+ * @param approval The request.
1927
+ * @param offerId The offer.
1928
+ * @param form The form.
1929
+ * @returns The response; a decline answers nothing.
1930
+ */
1931
+ function userInputResponse(approval, offerId, form) {
1932
+ if (offerId === "decline") return {
1933
+ approvalKind: "user_input",
1934
+ answers: {}
1935
+ };
1936
+ return {
1937
+ approvalKind: "user_input",
1938
+ answers: questionAnswers(approval, form)
1939
+ };
1940
+ }
1941
+ /**
1942
+ * The response of one ordinary request for one offer.
1943
+ * @param input The draft input.
1944
+ * @returns The response, or null for an unoffered decision.
1945
+ */
1946
+ function ordinaryResponse(input) {
1947
+ const { approval, fields, offerId, form } = input;
1948
+ switch (approval.approvalKind) {
1949
+ case "command_execution":
1950
+ case "file_change": return enumeratedResponse(approval, offerId);
1951
+ case "user_input": return userInputResponse(approval, offerId, form);
1952
+ case "elicitation": return elicitationResponse(approval, fields, offerId, form);
1953
+ case "permissions": return permissionsResponse(offerId, form);
1954
+ default: return legacyResponse(approval, offerId, form);
1955
+ }
1956
+ }
1957
+ /**
1958
+ * The wire draft for one ordinary decision.
1959
+ * @param input The draft input.
1960
+ * @returns The draft, or the errors that stop it.
1961
+ */
1962
+ function ordinaryApprovalDraft(input) {
1963
+ if (input.submitsForm) {
1964
+ const errors = validateApprovalForm(input.fields, input.form);
1965
+ if (errors.length > 0) return {
1966
+ ok: false,
1967
+ errors
1968
+ };
1969
+ }
1970
+ const response = ordinaryResponse(input);
1971
+ if (response === null) return invalid(UNKNOWN_OFFER);
1972
+ return {
1973
+ ok: true,
1974
+ draft: {
1975
+ command: "approvalRespond",
1976
+ requestId: input.approval.requestId,
1977
+ approvalId: input.approval.approvalId,
1978
+ response
1979
+ }
1980
+ };
1981
+ }
1982
+ /**
1983
+ * The wire draft for one dynamic decision. A dynamic approval offers a
1984
+ * decision only while it is pending, and the closed model gives every pending
1985
+ * approval its binding, so an absent binding and an unoffered decision are
1986
+ * the same one refusal.
1987
+ * @param input The request and the offer.
1988
+ * @returns The draft, or the refusal.
1989
+ */
1990
+ function dynamicApprovalDraft(input) {
1991
+ const binding = input.approval.binding;
1992
+ const offered = input.offerId === "approve" || input.offerId === "decline";
1993
+ if (binding === null || !offered) return invalid(UNKNOWN_OFFER);
1994
+ return {
1995
+ ok: true,
1996
+ draft: {
1997
+ command: "dynamicApprovalRespond",
1998
+ capturedLink: binding.capturedLink,
1999
+ identity: input.approval.identity,
2000
+ effectHash: input.approval.effectHash,
2001
+ decision: input.offerId === "approve" ? "approve" : "decline"
2002
+ }
2003
+ };
2004
+ }
2005
+ // src/ui/approvals/rules/transport-errors.ts
2006
+ const CODES$2 = /* @__PURE__ */ new Set([
2007
+ ...BROWSER_GATEWAY_ERROR_CODES,
2008
+ "gateway_error",
2009
+ "socket_unavailable",
2010
+ "response_lost",
2011
+ "replaced",
2012
+ "incompatible_contract"
2013
+ ]);
2014
+ const OUTCOMES$2 = /* @__PURE__ */ new Set([
2015
+ "delivered",
2016
+ "not_delivered",
2017
+ "outcome_unknown"
2018
+ ]);
2019
+ /**
2020
+ * Whether a value is a delivery outcome.
2021
+ * @param value The value.
2022
+ * @returns True for the three outcomes.
2023
+ */
2024
+ function isOutcome$2(value) {
2025
+ return typeof value === "string" && OUTCOMES$2.has(value);
2026
+ }
2027
+ /**
2028
+ * Whether a value is a code the transport can carry.
2029
+ * @param value The value.
2030
+ * @returns True for a known code.
2031
+ */
2032
+ function isCode$2(value) {
2033
+ return typeof value === "string" && CODES$2.has(value);
2034
+ }
2035
+ /**
2036
+ * The transport facts a thrown error carries, when it is a transport error.
2037
+ * @param error The thrown value.
2038
+ * @returns Its code, outcome and message, or null for any other error.
2039
+ */
2040
+ function transportErrorFacts$2(error) {
2041
+ if (!(error instanceof Error) || !("code" in error) || !("outcome" in error)) return null;
2042
+ const { code, outcome } = error;
2043
+ if (!isCode$2(code) || !isOutcome$2(outcome)) return null;
2044
+ return {
2045
+ code,
2046
+ outcome,
2047
+ message: error.message
2048
+ };
2049
+ }
2050
+ // src/ui/approvals/state/submit.ts
2051
+ const SENT_MESSAGES = {
2052
+ delivered: "The server delivered your decision.",
2053
+ not_delivered: "The server could not deliver your decision, so nothing was executed.",
2054
+ outcome_unknown: "The server lost the answer, so the outcome is unknown. The workbench never retries an unknown mutation."
2055
+ };
2056
+ const NO_TARGET = "This browser no longer holds the workbench target this decision was offered against.";
2057
+ const NOT_OFFERED$1 = "That decision is not offered for this request.";
2058
+ /**
2059
+ * A refusal.
2060
+ * @param code The transport or gateway code.
2061
+ * @param outcome What the transport could prove.
2062
+ * @param message The words, or null for the code's own.
2063
+ * @returns The result.
2064
+ */
2065
+ function refused(code, outcome, message) {
2066
+ return Object.freeze({
2067
+ status: "refused",
2068
+ code,
2069
+ outcome,
2070
+ message: message ?? refusalMessage(code)
2071
+ });
2072
+ }
2073
+ /**
2074
+ * The draft one submission sends.
2075
+ * @param input The submission.
2076
+ * @returns The draft, or the errors that stop it.
2077
+ */
2078
+ function draftFor(input) {
2079
+ if (input.card.kind === "dynamic") return dynamicApprovalDraft({
2080
+ approval: input.card.request,
2081
+ offerId: input.offerId
2082
+ });
2083
+ const offer = input.card.offers.find((candidate) => candidate.id === input.offerId);
2084
+ return ordinaryApprovalDraft({
2085
+ approval: input.card.request,
2086
+ fields: input.card.fields,
2087
+ offerId: input.offerId,
2088
+ submitsForm: offer?.submitsForm ?? false,
2089
+ form: input.form
2090
+ });
2091
+ }
2092
+ /**
2093
+ * Dispatch one draft. A dynamic decision goes under the exact lease it was
2094
+ * offered under; an ordinary decision acquires fresh authority for the
2095
+ * captured intent.
2096
+ * @param input The submission, with a captured target.
2097
+ * @param draft The draft.
2098
+ * @returns The transport's result.
2099
+ */
2100
+ function dispatch(input, draft) {
2101
+ if (input.card.kind !== "dynamic") return input.transport.executeCommand(draft, input.target ?? void 0);
2102
+ const authority = input.target?.authority ?? null;
2103
+ if (authority === null) return Promise.reject(new Error(NO_TARGET, { cause: "lease_required" }));
2104
+ return input.transport.command(draft, authority);
2105
+ }
2106
+ /**
2107
+ * The result of a dispatched draft.
2108
+ * @param result The transport's result.
2109
+ * @returns Sent with its outcome, or the gateway's refusal.
2110
+ */
2111
+ function settled(result) {
2112
+ if (result.code !== null) return refused(result.code, result.outcome, result.message);
2113
+ return Object.freeze({
2114
+ status: "sent",
2115
+ outcome: result.outcome,
2116
+ message: SENT_MESSAGES[result.outcome]
2117
+ });
2118
+ }
2119
+ /**
2120
+ * The result of a thrown dispatch.
2121
+ * @param error The thrown value.
2122
+ * @returns The refusal; an unknown failure is an unknown outcome.
2123
+ */
2124
+ function thrown(error) {
2125
+ const facts = transportErrorFacts$2(error);
2126
+ if (facts !== null) return refused(facts.code, facts.outcome, refusalMessage(facts.code));
2127
+ if (error instanceof Error && error.cause === "lease_required") return refused("lease_required", "not_delivered", NO_TARGET);
2128
+ return refused("gateway_error", "outcome_unknown", null);
2129
+ }
2130
+ /**
2131
+ * Send one decision.
2132
+ * @param input The submission.
2133
+ * @returns How it settled.
2134
+ */
2135
+ async function submitApprovalDecision(input) {
2136
+ if (!input.card.offers.some((candidate) => candidate.id === input.offerId)) return refused("not_offered", "not_delivered", NOT_OFFERED$1);
2137
+ const built = draftFor(input);
2138
+ if (!built.ok) return Object.freeze({
2139
+ status: "invalid",
2140
+ errors: built.errors
2141
+ });
2142
+ if (input.target === null) return refused("link_required", "not_delivered", NO_TARGET);
2143
+ try {
2144
+ return settled(await dispatch(input, built.draft));
2145
+ } catch (error) {
2146
+ return thrown(error);
2147
+ }
2148
+ }
2149
+ // src/ui/approvals/state/controller.ts
2150
+ const NOT_OFFERED = Object.freeze({
2151
+ status: "refused",
2152
+ code: "not_offered",
2153
+ outcome: "not_delivered",
2154
+ message: "That decision is not offered for this request."
2155
+ });
2156
+ const ALREADY_BUSY = Object.freeze({
2157
+ status: "refused",
2158
+ code: "decision_in_flight",
2159
+ outcome: "not_delivered",
2160
+ message: "A decision on this request is already on the wire."
2161
+ });
2162
+ /**
2163
+ * The target a decision is offered against, read when the decision is made.
2164
+ * Capturing is a transport call that can refuse; a refusal is a null target,
2165
+ * which the submission reports rather than guessing another.
2166
+ * @param transport The transport port.
2167
+ * @returns The captured intent, or null.
2168
+ */
2169
+ function captureTarget$1(transport) {
2170
+ try {
2171
+ return transport.captureCommandIntent();
2172
+ } catch {
2173
+ return null;
2174
+ }
2175
+ }
2176
+ /**
2177
+ * One approvals controller over one transport.
2178
+ * @param transport The transport port.
2179
+ * @param options The clock.
2180
+ * @returns The controller.
2181
+ */
2182
+ function createWorkbenchApprovalsController(transport, options = {}) {
2183
+ const now = options.now ?? Date.now;
2184
+ const listeners = /* @__PURE__ */ new Set();
2185
+ const busy = /* @__PURE__ */ new Set();
2186
+ const results = /* @__PURE__ */ new Map();
2187
+ /**
2188
+ * Tell every listener.
2189
+ */
2190
+ function publish() {
2191
+ for (const listener of listeners) listener();
2192
+ }
2193
+ /**
2194
+ * The projection input for the transport as it stands now.
2195
+ * @param nowMs The clock.
2196
+ * @returns The input.
2197
+ */
2198
+ function input(nowMs) {
2199
+ return workbenchApprovalsInput(transport.state(), nowMs, transport.capabilities());
2200
+ }
2201
+ /**
2202
+ * Send one resolved decision on one card, keyed for the panel.
2203
+ * @param key The busy key.
2204
+ * @param card The card.
2205
+ * @param choice The panel's choice.
2206
+ * @returns How it settled.
2207
+ */
2208
+ async function decide(key, card, choice) {
2209
+ if (busy.has(key)) return ALREADY_BUSY;
2210
+ const resolved = resolveApprovalChoice(card, choice);
2211
+ if (resolved === null) {
2212
+ results.set(key, NOT_OFFERED);
2213
+ publish();
2214
+ return NOT_OFFERED;
2215
+ }
2216
+ busy.add(key);
2217
+ publish();
2218
+ const result = await submitApprovalDecision({
2219
+ transport,
2220
+ card,
2221
+ offerId: resolved.offerId,
2222
+ form: resolved.form,
2223
+ target: captureTarget$1(transport)
2224
+ });
2225
+ busy.delete(key);
2226
+ results.set(key, result);
2227
+ publish();
2228
+ return result;
2229
+ }
2230
+ /**
2231
+ * Decide one ordinary approval.
2232
+ * @param approval The request.
2233
+ * @param choice The panel's choice.
2234
+ * @returns How it settled.
2235
+ */
2236
+ function respondToApproval(approval, choice) {
2237
+ const projection = input(now());
2238
+ const context = {
2239
+ nowMs: projection.nowMs,
2240
+ canCommand: projection.canCommand,
2241
+ canRespond: projection.canRespondOrdinary,
2242
+ connection: projection.state.connection,
2243
+ staleSnapshot: projection.state.kind === "stream",
2244
+ connectionReason: "reason" in projection.state ? projection.state.reason : null
2245
+ };
2246
+ return decide(String(approval.requestId), ordinaryCard(approval, context), choice);
2247
+ }
2248
+ /**
2249
+ * Decide one dynamic coordination approval.
2250
+ * @param approval The request.
2251
+ * @param verdict Approve or decline.
2252
+ * @returns How it settled.
2253
+ */
2254
+ function respondToDynamicApproval(approval, verdict) {
2255
+ const projection = input(now());
2256
+ const context = {
2257
+ nowMs: projection.nowMs,
2258
+ canCommand: projection.canCommand,
2259
+ canRespond: projection.canRespondDynamic,
2260
+ connection: projection.state.connection,
2261
+ staleSnapshot: projection.state.kind === "stream",
2262
+ connectionReason: "reason" in projection.state ? projection.state.reason : null
2263
+ };
2264
+ return decide(approval.identity.callId, dynamicCard(approval, context), { kind: verdict });
2265
+ }
2266
+ const panelActions = Object.freeze({
2267
+ /**
2268
+ * Decide one ordinary approval from the panel.
2269
+ * @param approval The request.
2270
+ * @param choice The panel's choice.
2271
+ */
2272
+ respondToApproval: (approval, choice) => {
2273
+ respondToApproval(approval, choice);
2274
+ },
2275
+ /**
2276
+ * Decide one dynamic approval from the panel.
2277
+ * @param approval The request.
2278
+ * @param verdict Approve or decline.
2279
+ */
2280
+ respondToDynamicApproval: (approval, verdict) => {
2281
+ respondToDynamicApproval(approval, verdict);
2282
+ }
2283
+ });
2284
+ return Object.freeze({
2285
+ /**
2286
+ * Follow the controller's decision state.
2287
+ * @param listener Notified on every change.
2288
+ * @returns Release the subscription.
2289
+ */
2290
+ subscribe: (listener) => {
2291
+ listeners.add(listener);
2292
+ return () => {
2293
+ listeners.delete(listener);
2294
+ };
2295
+ },
2296
+ /**
2297
+ * The decision state.
2298
+ * @returns The busy keys and the results.
2299
+ */
2300
+ decisionState: () => ({
2301
+ busyApprovals: Object.freeze([...busy]),
2302
+ results: new Map(results)
2303
+ }),
2304
+ /**
2305
+ * The surface for the transport as it stands now.
2306
+ * @param nowMs The clock.
2307
+ * @returns The view.
2308
+ */
2309
+ view: (nowMs) => projectWorkbenchApprovals(input(nowMs)),
2310
+ respondToApproval,
2311
+ respondToDynamicApproval,
2312
+ panelActions
2313
+ });
2314
+ }
2315
+ // src/ui/composer/rules/draft.ts
2316
+ const DISPOSITIONS = {
2317
+ delivered: "cleared",
2318
+ not_delivered: "restored",
2319
+ outcome_unknown: "retained"
2320
+ };
2321
+ /**
2322
+ * The disposition of the typed text for one settled outcome.
2323
+ * @param outcome The settled outcome.
2324
+ * @returns Cleared, restored or retained.
2325
+ */
2326
+ function composerDraftDisposition(outcome) {
2327
+ return DISPOSITIONS[outcome];
2328
+ }
2329
+ // src/ui/composer/rules/link.ts
2330
+ const INSPECT_ONLY = "This Codex history is inspect-only.";
2331
+ const UNBOUND = "This chat has no Codex workhorse yet.";
2332
+ /**
2333
+ * The authoritative in-progress turn. The server's own steer owner refuses
2334
+ * unless exactly one turn is `inProgress` and its id is the one the command
2335
+ * named; the composer reads the same fact from the published snapshot rather
2336
+ * than remembering a turn it once saw.
2337
+ * @param snapshot The published snapshot.
2338
+ * @returns Idle, the one active turn, or ambiguous.
2339
+ */
2340
+ function readComposerTurn(snapshot) {
2341
+ const active = snapshot.timeline?.turns.filter((turn) => turn.status === "inProgress") ?? [];
2342
+ const only = active[0];
2343
+ if (only === void 0) return Object.freeze({ kind: "idle" });
2344
+ if (active.length > 1) return Object.freeze({
2345
+ kind: "ambiguous",
2346
+ count: active.length
2347
+ });
2348
+ return Object.freeze({
2349
+ kind: "active",
2350
+ turnId: only.turnId
2351
+ });
2352
+ }
2353
+ /**
2354
+ * Why a workbench cannot take direct input.
2355
+ * @param state The transport state.
2356
+ * @returns The server's reason, or a sentence naming the readiness.
2357
+ */
2358
+ function unavailableReason(state) {
2359
+ if ("reason" in state) return state.reason;
2360
+ return `Codex is ${state.state.replaceAll("_", " ")}; the workhorse cannot accept direct input.`;
2361
+ }
2362
+ /**
2363
+ * What the composer may target right now. Only a connected, thread-capable
2364
+ * workbench whose thread link is `executable` can take a turn command; every
2365
+ * other reachable state is disabled with the server's own reason.
2366
+ * @param state The transport state.
2367
+ * @returns The link.
2368
+ */
2369
+ function readComposerLink(state) {
2370
+ if (state.kind !== "readiness" || state.state !== "thread_capable") return Object.freeze({
2371
+ kind: "unavailable",
2372
+ reason: unavailableReason(state)
2373
+ });
2374
+ return linkOf(state.snapshot);
2375
+ }
2376
+ /**
2377
+ * The composer link of a thread-capable snapshot. An unbound chat has nothing
2378
+ * to inspect and nothing to send to, which is a different sentence and a
2379
+ * different next action from a workhorse this browser may read but never write.
2380
+ * @param snapshot The snapshot.
2381
+ * @returns The link.
2382
+ */
2383
+ function linkOf(snapshot) {
2384
+ const link = snapshot.threadLink;
2385
+ if (link.state === "unbound") return Object.freeze({
2386
+ kind: "unbound",
2387
+ reason: link.reason ?? UNBOUND
2388
+ });
2389
+ if (link.state !== "executable") return Object.freeze({
2390
+ kind: "inspect_only",
2391
+ reason: link.reason ?? INSPECT_ONLY
2392
+ });
2393
+ return Object.freeze({
2394
+ kind: "executable",
2395
+ threadId: link.threadId,
2396
+ turn: readComposerTurn(snapshot)
2397
+ });
2398
+ }
2399
+ const REFUSAL_RECOVERIES = {
2400
+ unavailable: "Wait for Codex to become thread-capable, then send the message again.",
2401
+ unbound: "Create or attach a Codex workhorse for this chat, then send a message.",
2402
+ inspect_only: "Select a current executable workhorse before sending a message.",
2403
+ empty_prompt: "Type a message before sending.",
2404
+ prompt_too_long: `Shorten the message to at most ${String(16384)} UTF-8 bytes.`,
2405
+ prompt_invalid: "Remove the unsupported character, then send the message again.",
2406
+ ambiguous_turn: "Wait for Codex to publish one authoritative in-progress turn, then try again.",
2407
+ no_active_turn: "There is nothing to steer or interrupt; the workhorse is idle.",
2408
+ turn_changed: "Read the current turn, then interrupt that one.",
2409
+ command_pending: "Wait for the command already in flight to settle."
2410
+ };
2411
+ const REFUSAL_MESSAGES = {
2412
+ unavailable: "The Codex workbench cannot accept direct workhorse input.",
2413
+ unbound: "This chat has no Codex workhorse to send to.",
2414
+ inspect_only: "This chat's thread link is inspect-only, so it accepts no direct input.",
2415
+ empty_prompt: "The workhorse accepts a non-empty message only.",
2416
+ prompt_too_long: "The message is longer than the workbench accepts.",
2417
+ prompt_invalid: "The message contains a character the workbench contract refuses.",
2418
+ ambiguous_turn: "Codex is reporting more than one in-progress turn, so no turn is authoritative.",
2419
+ no_active_turn: "The workhorse has no in-progress turn.",
2420
+ turn_changed: "The in-progress turn changed after this interrupt was offered.",
2421
+ command_pending: "Another workbench command is already in flight from this composer."
2422
+ };
2423
+ /**
2424
+ * The transport's refusal codes, said in human words. Kept beside the composer
2425
+ * rather than shared, because each surface explains the same refusal in terms
2426
+ * of the action the person just took. `invalid_command` is the server refusing a
2427
+ * command that does not fit the workhorse's current state; the reachable case
2428
+ * is the authoritative in-progress guard on `turn/start`.
2429
+ */
2430
+ const TRANSPORT_REFUSALS = {
2431
+ link_changed: "The chat moved to another thread link after this message was composed.",
2432
+ link_required: "The command did not name the workbench target it was composed against.",
2433
+ lease_required: "This browser does not hold the workbench command lease.",
2434
+ lease_expired: "The workbench command lease expired before the command was sent.",
2435
+ lease_released: "The workbench command lease was released before the command was sent.",
2436
+ not_ready: "The workbench cannot send workhorse commands in its current state.",
2437
+ socket_unavailable: "The workbench lost its connection before the command was sent.",
2438
+ incompatible_contract: "The server answered with a workbench contract this browser cannot read.",
2439
+ response_lost: "The server never answered, so the command's outcome is unknown.",
2440
+ replaced: "Another workbench connection replaced this one before the command was sent.",
2441
+ invalid_command: "The server refused this command for the workhorse's current state. Read the timeline, then send again.",
2442
+ gateway_error: "The server refused this command."
2443
+ };
2444
+ const GENERIC_TRANSPORT_REFUSAL = "The server refused this workhorse command.";
2445
+ /**
2446
+ * A transport refusal code in the composer's words.
2447
+ * @param code The refusal code.
2448
+ * @returns The sentence.
2449
+ */
2450
+ function transportRefusalMessage(code) {
2451
+ return TRANSPORT_REFUSALS[code] ?? GENERIC_TRANSPORT_REFUSAL;
2452
+ }
2453
+ const OUTCOME_MESSAGES = {
2454
+ delivered: "Codex accepted the message and published its authoritative turn.",
2455
+ not_delivered: "The server delivered nothing, so the workhorse never saw this message.",
2456
+ outcome_unknown: "The server lost the answer, so the outcome is unknown. The workbench never retries an unknown mutation."
2457
+ };
2458
+ const QUEUED_MESSAGE = "Codex parked the message in the thread queue.";
2459
+ const OUTCOME_RECOVERIES = {
2460
+ delivered: null,
2461
+ not_delivered: "The draft was kept in the composer. Correct the problem and send it again.",
2462
+ outcome_unknown: "Read the workhorse timeline before deciding whether to send this message again. The text is kept below."
2463
+ };
2464
+ const PENDING_MESSAGES = {
2465
+ start: "Sending your message to the Codex workhorse.",
2466
+ steer: "Steering the current Codex turn.",
2467
+ interrupt: "Interrupting the current Codex turn.",
2468
+ queue: "Queueing your message for the Codex workhorse."
2469
+ };
2470
+ const LATE_RESULT_REASON = "The chat moved to another thread link before the server answered, so this result is not applied here.";
2471
+ // src/ui/composer/rules/intent.ts
2472
+ const encoder = new TextEncoder();
2473
+ /**
2474
+ * A refusal plan.
2475
+ * @param code Why.
2476
+ * @returns The plan.
2477
+ */
2478
+ function composerRefusal(code) {
2479
+ return Object.freeze({
2480
+ kind: "refuse",
2481
+ refusal: Object.freeze({
2482
+ code,
2483
+ message: REFUSAL_MESSAGES[code],
2484
+ recovery: REFUSAL_RECOVERIES[code]
2485
+ })
2486
+ });
2487
+ }
2488
+ /**
2489
+ * Each non-executable link keeps the server's own sentence and gains the next
2490
+ * action that belongs to it.
2491
+ * @param link The link.
2492
+ * @returns A refusal, or null for an executable link.
2493
+ */
2494
+ function linkRefusal(link) {
2495
+ if (link.kind === "executable") return null;
2496
+ return Object.freeze({
2497
+ kind: "refuse",
2498
+ refusal: Object.freeze({
2499
+ code: link.kind,
2500
+ message: link.reason,
2501
+ recovery: REFUSAL_RECOVERIES[link.kind]
2502
+ })
2503
+ });
2504
+ }
2505
+ /**
2506
+ * The executable link, or the refusal that stands in its place.
2507
+ * @param state The transport state.
2508
+ * @returns The link or a refusal plan.
2509
+ */
2510
+ function executableLinkOrRefusal(state) {
2511
+ const link = readComposerLink(state);
2512
+ return link.kind === "executable" ? link : linkRefusal(link) ?? composerRefusal("unavailable");
2513
+ }
2514
+ /**
2515
+ * The prompt the closed contract accepts: non-empty, NUL-free, and within the
2516
+ * body's UTF-8 bound. Checked here so a message the server would reject is
2517
+ * refused with the person's text still in front of them.
2518
+ * @param text The prompt.
2519
+ * @returns A refusal code, or null.
2520
+ */
2521
+ function promptRefusal(text) {
2522
+ if (text.trim().length === 0) return "empty_prompt";
2523
+ if (text.includes("\0")) return "prompt_invalid";
2524
+ return encoder.encode(text).byteLength > 16384 ? "prompt_too_long" : null;
2525
+ }
2526
+ /**
2527
+ * The literal `turn/start` body.
2528
+ * @param threadId The thread.
2529
+ * @param text The prompt.
2530
+ * @returns The plan.
2531
+ */
2532
+ function startPlan(threadId, text) {
2533
+ return Object.freeze({
2534
+ kind: "dispatch",
2535
+ action: "start",
2536
+ draft: Object.freeze({
2537
+ command: "start",
2538
+ threadId,
2539
+ prompt: text
2540
+ })
2541
+ });
2542
+ }
2543
+ /**
2544
+ * The literal `turn/steer` body against the authoritative turn.
2545
+ * @param threadId The thread.
2546
+ * @param turn The turn read.
2547
+ * @param text The prompt.
2548
+ * @returns The plan, or a refusal without one active turn.
2549
+ */
2550
+ function steerPlan(threadId, turn, text) {
2551
+ if (turn.kind === "ambiguous") return composerRefusal("ambiguous_turn");
2552
+ if (turn.kind === "idle") return composerRefusal("no_active_turn");
2553
+ return Object.freeze({
2554
+ kind: "dispatch",
2555
+ action: "steer",
2556
+ draft: Object.freeze({
2557
+ command: "steer",
2558
+ threadId,
2559
+ turnId: turn.turnId,
2560
+ prompt: text
2561
+ })
2562
+ });
2563
+ }
2564
+ /**
2565
+ * The plan for one delivery choice against an executable link.
2566
+ * @param link The link.
2567
+ * @param text The prompt.
2568
+ * @param delivery The delivery choice.
2569
+ * @returns The plan.
2570
+ */
2571
+ function deliveryPlan(link, text, delivery) {
2572
+ switch (delivery) {
2573
+ case "send": return startPlan(link.threadId, text);
2574
+ case "steer": return steerPlan(link.threadId, link.turn, text);
2575
+ case "queue": return Object.freeze({
2576
+ kind: "dispatch",
2577
+ action: "queue",
2578
+ draft: Object.freeze({
2579
+ command: "queueAdd",
2580
+ prompt: text
2581
+ })
2582
+ });
2583
+ default: return link.turn.kind === "idle" ? startPlan(link.threadId, text) : steerPlan(link.threadId, link.turn, text);
2584
+ }
2585
+ }
2586
+ /**
2587
+ * What a submit sends. With `auto`, an idle submit is the literal `turn/start`
2588
+ * body and a submit while a turn runs is the literal `turn/steer` body carrying
2589
+ * the authoritative turn id the server re-proves as `expectedTurnId`. Nothing
2590
+ * else is ever sent from the send path: the composer does not fork or retry.
2591
+ * @param state The transport state.
2592
+ * @param text The prompt.
2593
+ * @param delivery The delivery choice.
2594
+ * @returns The plan.
2595
+ */
2596
+ function planComposerSubmit(state, text, delivery = "auto") {
2597
+ const link = executableLinkOrRefusal(state);
2598
+ if (link.kind !== "executable") return link;
2599
+ const refusedPrompt = promptRefusal(text);
2600
+ if (refusedPrompt !== null) return composerRefusal(refusedPrompt);
2601
+ return deliveryPlan(link, text, delivery);
2602
+ }
2603
+ /**
2604
+ * Interrupt targets the turn that was captured when the control was offered.
2605
+ * A turn that has since finished or been replaced is refused rather than
2606
+ * retargeted, so the person never interrupts work they were not looking at.
2607
+ * @param state The transport state.
2608
+ * @param capturedTurnId The turn the control was offered for.
2609
+ * @returns The plan.
2610
+ */
2611
+ function planComposerInterrupt(state, capturedTurnId) {
2612
+ const link = executableLinkOrRefusal(state);
2613
+ if (link.kind !== "executable") return link;
2614
+ const { turn } = link;
2615
+ if (turn.kind === "idle") return composerRefusal("no_active_turn");
2616
+ if (turn.kind === "ambiguous") return composerRefusal("ambiguous_turn");
2617
+ if (turn.turnId !== capturedTurnId) return composerRefusal("turn_changed");
2618
+ return Object.freeze({
2619
+ kind: "dispatch",
2620
+ action: "interrupt",
2621
+ draft: Object.freeze({
2622
+ command: "interrupt",
2623
+ threadId: link.threadId,
2624
+ turnId: capturedTurnId
2625
+ })
2626
+ });
2627
+ }
2628
+ // src/ui/composer/state/controller.ts
2629
+ const NO_TURN_REASON = "Codex reported delivery without identifying the accepted turn.";
2630
+ /**
2631
+ * A status.
2632
+ * @param state The status state.
2633
+ * @param message The words.
2634
+ * @param recovery The next action, or null.
2635
+ * @returns The frozen status.
2636
+ */
2637
+ function status(state, message, recovery) {
2638
+ return Object.freeze({
2639
+ role: "status",
2640
+ label: "Codex composer status",
2641
+ state,
2642
+ message,
2643
+ recovery
2644
+ });
2645
+ }
2646
+ const IDLE_STATUS = status("idle", "The composer is ready.", null);
2647
+ /**
2648
+ * A settlement.
2649
+ * @param outcome The delivery outcome.
2650
+ * @param message The words.
2651
+ * @param turnId The accepted turn, or null.
2652
+ * @param queued Whether the message was parked rather than sent.
2653
+ * @returns The frozen settlement.
2654
+ */
2655
+ function settlement(outcome, message, turnId = null, queued = false) {
2656
+ return Object.freeze({
2657
+ outcome,
2658
+ message,
2659
+ turnId,
2660
+ queued
2661
+ });
2662
+ }
2663
+ /**
2664
+ * The settlement a thrown error means. The server's own message, when it sent
2665
+ * one, beats the composer's vocabulary: only the server knows which guard refused.
2666
+ * @param error The rejection.
2667
+ * @returns The settlement.
2668
+ */
2669
+ function refusalOf(error) {
2670
+ if (error instanceof BrowserWorkbenchTransportError) return settlement(error.outcome, transportRefusalMessage(error.code));
2671
+ return settlement("outcome_unknown", error instanceof Error ? error.message : "The command outcome is unknown.");
2672
+ }
2673
+ /**
2674
+ * Failing to capture an intent is always `not_delivered`, whatever the error
2675
+ * says: the capture happens before the command exists, so nothing reached the
2676
+ * server and the person's text is safe to send again.
2677
+ * @param error The rejection.
2678
+ * @returns The settlement.
2679
+ */
2680
+ function captureRefusal(error) {
2681
+ if (error instanceof BrowserWorkbenchTransportError) return settlement("not_delivered", transportRefusalMessage(error.code));
2682
+ return settlement("not_delivered", error instanceof Error ? error.message : "The workbench command target is unavailable.");
2683
+ }
2684
+ /**
2685
+ * The turn a delivered command may claim. A steer names the turn it steered;
2686
+ * a start has no id of its own, so its id comes from the accepted response; a
2687
+ * queued message has no turn at all.
2688
+ * @param plan The dispatched plan.
2689
+ * @param result The server's result.
2690
+ * @returns The settlement.
2691
+ */
2692
+ function deliveredSettlement$1(plan, result) {
2693
+ if (plan.action === "queue") return settlement("delivered", QUEUED_MESSAGE, null, true);
2694
+ if (plan.action !== "start") return settlement("delivered", OUTCOME_MESSAGES.delivered, plan.draft.turnId);
2695
+ if (result.turnId === void 0) return settlement("outcome_unknown", NO_TURN_REASON);
2696
+ return settlement("delivered", OUTCOME_MESSAGES.delivered, result.turnId);
2697
+ }
2698
+ /**
2699
+ * The settlement of a server result.
2700
+ * @param plan The dispatched plan.
2701
+ * @param result The server's result.
2702
+ * @returns The settlement.
2703
+ */
2704
+ function resultSettlement(plan, result) {
2705
+ if (result.code !== null) return settlement(result.outcome, result.message ?? transportRefusalMessage(result.code));
2706
+ if (result.outcome === "delivered") return deliveredSettlement$1(plan, result);
2707
+ return settlement(result.outcome, OUTCOME_MESSAGES[result.outcome]);
2708
+ }
2709
+ /**
2710
+ * The submission result a settlement becomes.
2711
+ * @param settled The settlement.
2712
+ * @returns The result the runtime reads.
2713
+ */
2714
+ function submissionResult(settled) {
2715
+ if (settled.outcome === "delivered" && settled.queued) return Object.freeze({ outcome: "queued" });
2716
+ if (settled.outcome === "delivered" && settled.turnId !== null) return Object.freeze({
2717
+ outcome: "delivered",
2718
+ turnId: settled.turnId
2719
+ });
2720
+ if (settled.outcome === "not_delivered") return Object.freeze({
2721
+ outcome: "not_delivered",
2722
+ reason: settled.message
2723
+ });
2724
+ return Object.freeze({
2725
+ outcome: "outcome_unknown",
2726
+ reason: settled.message
2727
+ });
2728
+ }
2729
+ /**
2730
+ * The refusal for a workbench that cannot take input.
2731
+ * @returns The refusal.
2732
+ */
2733
+ function unavailableRefusal() {
2734
+ return Object.freeze({
2735
+ code: "unavailable",
2736
+ message: REFUSAL_MESSAGES.unavailable,
2737
+ recovery: REFUSAL_RECOVERIES.unavailable
2738
+ });
2739
+ }
2740
+ /**
2741
+ * Create the composer's one state owner.
2742
+ * @param options The transport it sends through.
2743
+ * @returns The controller.
2744
+ */
2745
+ function createWorkbenchComposerController(options) {
2746
+ const { transport } = options;
2747
+ const listeners = /* @__PURE__ */ new Set();
2748
+ let state = Object.freeze({
2749
+ pending: null,
2750
+ status: IDLE_STATUS,
2751
+ retained: null,
2752
+ settled: 0
2753
+ });
2754
+ /**
2755
+ * Publish a partial state.
2756
+ * @param next The fields that changed.
2757
+ */
2758
+ function publish(next) {
2759
+ state = Object.freeze({
2760
+ ...state,
2761
+ ...next
2762
+ });
2763
+ for (const listener of listeners) listener();
2764
+ }
2765
+ /**
2766
+ * Publish a refusal the composer made itself.
2767
+ * @param refusal The refusal.
2768
+ */
2769
+ function refuse(refusal) {
2770
+ publish({ status: status("refused", refusal.message, refusal.recovery) });
2771
+ }
2772
+ /**
2773
+ * A retained copy stands until the person dismisses it, or until it is
2774
+ * replaced by a newer one. A later command settling does not clear it: the
2775
+ * copy exists precisely because nobody knows whether its message landed. The
2776
+ * one exception is a delivered send of the same text.
2777
+ * @param disposition The draft disposition.
2778
+ * @param text The text sent, or null for an interrupt.
2779
+ * @param threadId The thread it was sent to.
2780
+ * @param reason Why the copy is kept.
2781
+ * @returns The retained draft, or null.
2782
+ */
2783
+ function retainedAfter(disposition, text, threadId, reason) {
2784
+ if (disposition === "retained" && text !== null) return Object.freeze({
2785
+ text,
2786
+ threadId,
2787
+ reason
2788
+ });
2789
+ const standing = state.retained;
2790
+ if (standing === null || disposition === "cleared" && standing.text === text) return null;
2791
+ return standing;
2792
+ }
2793
+ /**
2794
+ * Whether a result arrived after the chat left the link it was sent against.
2795
+ * @param threadId The thread the command named.
2796
+ * @returns True when the result cannot be applied here.
2797
+ */
2798
+ function lateFor(threadId) {
2799
+ const link = readComposerLink(transport.state());
2800
+ return link.kind !== "executable" || link.threadId !== threadId;
2801
+ }
2802
+ /**
2803
+ * Send one plan and read what the server said.
2804
+ * @param plan The plan.
2805
+ * @returns The settlement.
2806
+ */
2807
+ async function sendPlan(plan) {
2808
+ let intent;
2809
+ try {
2810
+ intent = transport.captureCommandIntent();
2811
+ } catch (error) {
2812
+ return captureRefusal(error);
2813
+ }
2814
+ publish({
2815
+ pending: plan.action,
2816
+ status: status("pending", PENDING_MESSAGES[plan.action], null)
2817
+ });
2818
+ try {
2819
+ return resultSettlement(plan, await transport.executeCommand(plan.draft, intent));
2820
+ } catch (error) {
2821
+ return refusalOf(error);
2822
+ }
2823
+ }
2824
+ /**
2825
+ * Dispatch a plan and publish its settlement.
2826
+ * @param plan The plan.
2827
+ * @param threadId The thread it targets.
2828
+ * @param text The text sent, or null for an interrupt.
2829
+ * @returns The settlement.
2830
+ */
2831
+ async function dispatch(plan, threadId, text) {
2832
+ let settled = await sendPlan(plan);
2833
+ if (settled.outcome !== "not_delivered" && lateFor(threadId)) settled = settlement("outcome_unknown", LATE_RESULT_REASON);
2834
+ const recovery = OUTCOME_RECOVERIES[settled.outcome];
2835
+ publish({
2836
+ pending: null,
2837
+ settled: state.settled + 1,
2838
+ status: status(settled.outcome, settled.message, recovery),
2839
+ retained: retainedAfter(composerDraftDisposition(settled.outcome), text, threadId, settled.message)
2840
+ });
2841
+ return settled;
2842
+ }
2843
+ /**
2844
+ * A second activation while a command is in flight is refused here and
2845
+ * sends nothing. `not_delivered` is the honest answer: this activation
2846
+ * reached no server.
2847
+ * @returns The refusal result.
2848
+ */
2849
+ function refusePending() {
2850
+ const plan = composerRefusal("command_pending");
2851
+ if (plan.kind === "refuse") refuse(plan.refusal);
2852
+ return Object.freeze({
2853
+ outcome: "not_delivered",
2854
+ reason: REFUSAL_MESSAGES.command_pending
2855
+ });
2856
+ }
2857
+ /**
2858
+ * Publish a refusal and answer the submission with it.
2859
+ * @param refusal The refusal.
2860
+ * @returns The not-delivered result.
2861
+ */
2862
+ function refuseSubmission(refusal) {
2863
+ refuse(refusal);
2864
+ return Object.freeze({
2865
+ outcome: "not_delivered",
2866
+ reason: refusal.message
2867
+ });
2868
+ }
2869
+ /**
2870
+ * The thread a plan targets: the link's thread for a queued message.
2871
+ * @param plan The plan.
2872
+ * @returns The thread, or null when the link is not executable.
2873
+ */
2874
+ function planThread(plan) {
2875
+ if (plan.action !== "queue") return plan.draft.threadId;
2876
+ const link = readComposerLink(transport.state());
2877
+ return link.kind === "executable" ? link.threadId : null;
2878
+ }
2879
+ /**
2880
+ * Submit a message with the chosen delivery.
2881
+ * @param submission The text and delivery.
2882
+ * @returns The submission result.
2883
+ */
2884
+ async function submit(submission) {
2885
+ if (state.pending !== null) return Object.freeze({
2886
+ outcome: "not_delivered",
2887
+ reason: refusePending().reason
2888
+ });
2889
+ const plan = planComposerSubmit(transport.state(), submission.text, submission.delivery);
2890
+ if (plan.kind === "refuse") return refuseSubmission(plan.refusal);
2891
+ const threadId = planThread(plan);
2892
+ if (threadId === null) return refuseSubmission(unavailableRefusal());
2893
+ return submissionResult(await dispatch(plan, threadId, submission.text));
2894
+ }
2895
+ /**
2896
+ * Interrupt the turn the control was offered for.
2897
+ * @param turnId The captured turn.
2898
+ * @returns The command result.
2899
+ */
2900
+ async function interrupt(turnId) {
2901
+ if (state.pending !== null) return refusePending();
2902
+ const plan = planComposerInterrupt(transport.state(), turnId);
2903
+ if (plan.kind === "refuse") {
2904
+ refuse(plan.refusal);
2905
+ return Object.freeze({
2906
+ outcome: "not_delivered",
2907
+ reason: plan.refusal.message
2908
+ });
2909
+ }
2910
+ const threadId = planThread(plan);
2911
+ if (threadId === null) return refusePending();
2912
+ const settled = await dispatch(plan, threadId, null);
2913
+ return Object.freeze({
2914
+ outcome: settled.outcome,
2915
+ reason: settled.message
2916
+ });
2917
+ }
2918
+ /**
2919
+ * Hear every publication.
2920
+ * @param listener The listener.
2921
+ * @returns A function that stops listening.
2922
+ */
2923
+ function subscribe(listener) {
2924
+ listeners.add(listener);
2925
+ return () => listeners.delete(listener);
2926
+ }
2927
+ /** Drop the retained copy. */
2928
+ function dismissRetainedDraft() {
2929
+ if (state.retained !== null) publish({ retained: null });
2930
+ }
2931
+ /**
2932
+ * The state.
2933
+ * @returns The frozen state.
2934
+ */
2935
+ function getState() {
2936
+ return state;
2937
+ }
2938
+ return Object.freeze({
2939
+ submit,
2940
+ interrupt,
2941
+ getState,
2942
+ subscribe,
2943
+ dismissRetainedDraft
2944
+ });
2945
+ }
2946
+ // src/ui/queue/rules/transport-errors.ts
2947
+ const CODES$1 = /* @__PURE__ */ new Set([
2948
+ ...BROWSER_GATEWAY_ERROR_CODES,
2949
+ "gateway_error",
2950
+ "socket_unavailable",
2951
+ "response_lost",
2952
+ "replaced",
2953
+ "incompatible_contract"
2954
+ ]);
2955
+ const OUTCOMES$1 = /* @__PURE__ */ new Set([
2956
+ "delivered",
2957
+ "not_delivered",
2958
+ "outcome_unknown"
2959
+ ]);
2960
+ /**
2961
+ * Whether a value is a delivery outcome.
2962
+ * @param value The value.
2963
+ * @returns True for the three outcomes.
2964
+ */
2965
+ function isOutcome$1(value) {
2966
+ return typeof value === "string" && OUTCOMES$1.has(value);
2967
+ }
2968
+ /**
2969
+ * Whether a value is a code the transport can carry.
2970
+ * @param value The value.
2971
+ * @returns True for a known code.
2972
+ */
2973
+ function isCode$1(value) {
2974
+ return typeof value === "string" && CODES$1.has(value);
2975
+ }
2976
+ /**
2977
+ * The transport facts a thrown error carries, when it is a transport error.
2978
+ * @param error The thrown value.
2979
+ * @returns Its code, outcome and message, or null for any other error.
2980
+ */
2981
+ function transportErrorFacts$1(error) {
2982
+ if (!(error instanceof Error) || !("code" in error) || !("outcome" in error)) return null;
2983
+ const { code, outcome } = error;
2984
+ if (!isCode$1(code) || !isOutcome$1(outcome)) return null;
2985
+ return {
2986
+ code,
2987
+ outcome,
2988
+ message: error.message
2989
+ };
2990
+ }
2991
+ /**
2992
+ * The message of a thrown value, or a fallback for a non-error.
2993
+ * @param error The thrown value.
2994
+ * @param fallback The words when nothing was thrown as an error.
2995
+ * @returns The message.
2996
+ */
2997
+ function errorMessage$1(error, fallback) {
2998
+ return error instanceof Error ? error.message : fallback;
2999
+ }
3000
+ // src/ui/queue/state/actions.ts
3001
+ const DELIVERED_MESSAGES = {
3002
+ add: "The server queued the submission and republished the queue.",
3003
+ list: "The server re-read and republished the authoritative queue for this thread link.",
3004
+ edit: "The server updated the queued submission and republished the queue.",
3005
+ cancel: "The server deleted the queued submission and republished the queue.",
3006
+ reorder: "The server applied the submitted order and republished the queue.",
3007
+ start: "The server started the queued submission and republished the queue."
3008
+ };
3009
+ const UNKNOWN_MESSAGES = {
3010
+ add: "The add command's outcome was lost; the submission may or may not be queued.",
3011
+ list: "The snapshot read did not complete; the queue on screen is not proven current.",
3012
+ edit: "The edit command's outcome was lost; the queued prompt may or may not have changed.",
3013
+ cancel: "The cancel command's outcome was lost; the submission may or may not be gone.",
3014
+ reorder: "The reorder command's outcome was lost; the queue order is not proven.",
3015
+ start: "The start command's outcome was lost; the submission may or may not be running."
3016
+ };
3017
+ /**
3018
+ * One settlement, frozen.
3019
+ * @param fields The settlement fields.
3020
+ * @returns The frozen settlement.
3021
+ */
3022
+ function frozen(fields) {
3023
+ return Object.freeze(fields);
3024
+ }
3025
+ /**
3026
+ * Read a command result as a settlement. Success is read only from an
3027
+ * authoritative delivered result.
3028
+ * @param control The control that sent the command.
3029
+ * @param submissionId The submission it named, or null.
3030
+ * @param result The transport's answer.
3031
+ * @returns The settlement.
3032
+ */
3033
+ function settle(control, submissionId, result) {
3034
+ if (result.outcome === "delivered") return frozen({
3035
+ control,
3036
+ state: "reconciled",
3037
+ code: null,
3038
+ message: result.message ?? DELIVERED_MESSAGES[control],
3039
+ submissionId
3040
+ });
3041
+ if (result.outcome === "outcome_unknown") return frozen({
3042
+ control,
3043
+ state: "outcome_unknown",
3044
+ code: result.code,
3045
+ message: result.message ?? UNKNOWN_MESSAGES[control],
3046
+ submissionId
3047
+ });
3048
+ return frozen({
3049
+ control,
3050
+ state: "refused",
3051
+ code: result.code,
3052
+ message: result.message ?? "The server refused the queue command.",
3053
+ submissionId
3054
+ });
3055
+ }
3056
+ /**
3057
+ * A thrown command is never read as success. A transport error carries the
3058
+ * outcome the transport could prove: `outcome_unknown` keeps the person in
3059
+ * uncertainty rather than showing a refusal that may not have happened.
3060
+ * @param control The control that sent the command.
3061
+ * @param submissionId The submission it named, or null.
3062
+ * @param error The thrown value.
3063
+ * @returns The settlement.
3064
+ */
3065
+ function settleFailure(control, submissionId, error) {
3066
+ const facts = transportErrorFacts$1(error);
3067
+ if (facts !== null) return frozen({
3068
+ control,
3069
+ state: facts.outcome === "outcome_unknown" ? "outcome_unknown" : "refused",
3070
+ code: facts.code,
3071
+ message: facts.message,
3072
+ submissionId
3073
+ });
3074
+ return frozen({
3075
+ control,
3076
+ state: "refused",
3077
+ code: null,
3078
+ message: errorMessage$1(error, "The queue command could not be sent."),
3079
+ submissionId
3080
+ });
3081
+ }
3082
+ /**
3083
+ * Emit one queue command against its captured target.
3084
+ * @param transport The transport port.
3085
+ * @param control The control sending it.
3086
+ * @param submissionId The submission it names, or null.
3087
+ * @param draft The wire draft.
3088
+ * @param target The target captured when the control was offered.
3089
+ * @returns The settlement.
3090
+ */
3091
+ async function send(transport, control, submissionId, draft, target) {
3092
+ try {
3093
+ return settle(control, submissionId, await transport.executeCommand(draft, target));
3094
+ } catch (error) {
3095
+ return settleFailure(control, submissionId, error);
3096
+ }
3097
+ }
3098
+ /**
3099
+ * Refresh the authoritative snapshot. It is the recovery for every state where
3100
+ * the queue on screen is not proven: stale, reconnecting, restarted,
3101
+ * unavailable, and a lost outcome.
3102
+ * @param transport The transport port.
3103
+ * @returns The settlement.
3104
+ */
3105
+ async function list(transport) {
3106
+ try {
3107
+ await transport.refresh();
3108
+ return frozen({
3109
+ control: "list",
3110
+ state: "reconciled",
3111
+ code: null,
3112
+ message: DELIVERED_MESSAGES.list,
3113
+ submissionId: null
3114
+ });
3115
+ } catch (error) {
3116
+ return settleFailure("list", null, error);
3117
+ }
3118
+ }
3119
+ /**
3120
+ * The six queue operations over one transport.
3121
+ * @param transport The transport port.
3122
+ * @returns The commands.
3123
+ */
3124
+ function createWorkbenchQueueCommands(transport) {
3125
+ return Object.freeze({
3126
+ /**
3127
+ * Re-read the authoritative list.
3128
+ * @returns The settlement.
3129
+ */
3130
+ list: () => list(transport),
3131
+ /**
3132
+ * Queue one submission behind the current turn.
3133
+ * @param prompt The prompt.
3134
+ * @param target The captured target.
3135
+ * @returns The settlement.
3136
+ */
3137
+ add: (prompt, target) => send(transport, "add", null, {
3138
+ command: "queueAdd",
3139
+ prompt
3140
+ }, target),
3141
+ /**
3142
+ * Replace one queued prompt.
3143
+ * @param submissionId The submission.
3144
+ * @param prompt The new prompt.
3145
+ * @param target The captured target.
3146
+ * @returns The settlement.
3147
+ */
3148
+ edit: (submissionId, prompt, target) => send(transport, "edit", submissionId, {
3149
+ command: "queueUpdate",
3150
+ submissionId,
3151
+ prompt
3152
+ }, target),
3153
+ /**
3154
+ * Delete one queued submission.
3155
+ * @param submissionId The submission.
3156
+ * @param target The captured target.
3157
+ * @returns The settlement.
3158
+ */
3159
+ cancel: (submissionId, target) => send(transport, "cancel", submissionId, {
3160
+ command: "queueDelete",
3161
+ submissionId
3162
+ }, target),
3163
+ /**
3164
+ * Submit the complete order.
3165
+ * @param orderedSubmissionIds Every submission, in the requested order.
3166
+ * @param target The captured target.
3167
+ * @param submissionId The submission the person moved, or null.
3168
+ * @returns The settlement.
3169
+ */
3170
+ reorder: (orderedSubmissionIds, target, submissionId = null) => send(transport, "reorder", submissionId, {
3171
+ command: "queueReorder",
3172
+ orderedSubmissionIds: [...orderedSubmissionIds]
3173
+ }, target),
3174
+ /**
3175
+ * Start one queued submission now.
3176
+ * @param submissionId The submission.
3177
+ * @param target The captured target.
3178
+ * @returns The settlement.
3179
+ */
3180
+ start: (submissionId, target) => send(transport, "start", submissionId, {
3181
+ command: "queueStart",
3182
+ submissionId
3183
+ }, target)
3184
+ });
3185
+ }
3186
+ /**
3187
+ * Capture the command target for the queue being rendered. It fails when the
3188
+ * chat holds no usable snapshot, which is a disabled-control reason rather
3189
+ * than an error the person has to read as a failure.
3190
+ * @param transport The transport port.
3191
+ * @returns The captured target, or the reason none could be captured.
3192
+ */
3193
+ function captureWorkbenchQueueTarget(transport) {
3194
+ try {
3195
+ return Object.freeze({
3196
+ captured: true,
3197
+ target: transport.captureCommandIntent()
3198
+ });
3199
+ } catch (error) {
3200
+ return Object.freeze({
3201
+ captured: false,
3202
+ reason: transportErrorFacts$1(error)?.message ?? "The workbench has no command target for this queue."
3203
+ });
3204
+ }
3205
+ }
3206
+ // src/ui/queue/rules/words.ts
3207
+ const WORKBENCH_QUEUE_STATE_WORDS = {
3208
+ loading: {
3209
+ label: "Loading queue",
3210
+ detail: "The authoritative queue snapshot for this thread link has not arrived yet.",
3211
+ recovery: "Wait for the snapshot, or refresh the list to request it again."
3212
+ },
3213
+ empty: {
3214
+ label: "Queue empty",
3215
+ detail: "The linked workhorse is holding no queued submissions.",
3216
+ recovery: "Add a submission to queue work behind the current turn."
3217
+ },
3218
+ queued: {
3219
+ label: "Queued",
3220
+ detail: "The linked workhorse is holding queued submissions in this order.",
3221
+ recovery: "Edit, cancel, reorder, or start a submission the coordinator owns."
3222
+ },
3223
+ running: {
3224
+ label: "Running",
3225
+ detail: "The linked workhorse is busy, so this queue is waiting behind the current turn.",
3226
+ recovery: "Wait for the turn to settle, or interrupt it from the workhorse timeline."
3227
+ },
3228
+ interrupted_preserved: {
3229
+ label: "Interrupted, queue preserved",
3230
+ detail: "The workhorse turn was interrupted and the server preserved every queued submission.",
3231
+ recovery: "Start the next submission when the workhorse is idle, or cancel what is stale."
3232
+ },
3233
+ approval_blocked: {
3234
+ label: "Blocked on approval",
3235
+ detail: "The linked workhorse is waiting on an approval before it can drain this queue.",
3236
+ recovery: "Answer the pending approval request, then the queue continues."
3237
+ },
3238
+ failed: {
3239
+ label: "Failed",
3240
+ detail: "The server reported a failure for this queue on the linked workhorse.",
3241
+ recovery: "Refresh the list to read the authoritative queue, then retry or cancel."
3242
+ },
3243
+ restarted: {
3244
+ label: "Workhorse restarted",
3245
+ detail: "The Codex child that owned the queue on screen was replaced, so its execution proof is void.",
3246
+ recovery: "Refresh the list to read the new child's queue before commanding it."
3247
+ },
3248
+ completed: {
3249
+ label: "Completed",
3250
+ detail: "Every submission the server is reporting for this queue has completed.",
3251
+ recovery: "Add a submission, or refresh the list to read the authoritative queue."
3252
+ },
3253
+ stale: {
3254
+ label: "Stale snapshot",
3255
+ detail: "The workbench stream skipped a sequence, so the queue on screen may not be current.",
3256
+ recovery: "Refresh the list to replace it with an authoritative snapshot."
3257
+ },
3258
+ reconnecting: {
3259
+ label: "Reconnecting",
3260
+ detail: "The workbench is reconnecting, so the queue cannot be commanded.",
3261
+ recovery: "Wait for the connection, then refresh the list before commanding the queue."
3262
+ },
3263
+ disconnected: {
3264
+ label: "Disconnected",
3265
+ detail: "This chat has no workbench socket, so there is nothing to read a queue from.",
3266
+ recovery: "Reconnect the workbench; refreshing needs a socket and cannot recover this."
3267
+ },
3268
+ session_stopped: {
3269
+ label: "Codex session stopped",
3270
+ detail: "This chat is connected, but the server's Codex session is not running.",
3271
+ recovery: "Refresh the list once the server's Codex session is running again."
3272
+ },
3273
+ session_incompatible: {
3274
+ label: "Codex session incompatible",
3275
+ detail: "This chat is connected, but the server's Codex session reports a contract it cannot serve.",
3276
+ recovery: "Install the pinned Codex version and restart the server; refreshing will keep reporting this until then."
3277
+ },
3278
+ unavailable: {
3279
+ label: "Queue unavailable",
3280
+ detail: "The server is not publishing a queue for the thread link this chat is on.",
3281
+ recovery: "Choose an executable thread link, then refresh the list."
3282
+ },
3283
+ outcome_unknown: {
3284
+ label: "Outcome unknown",
3285
+ detail: "A queue mutation's outcome was lost, so nothing on screen may be read as settled.",
3286
+ recovery: "Refresh the list to read the authoritative queue before commanding it again."
3287
+ }
3288
+ };
3289
+ const WORKBENCH_QUEUE_ENTRY_STATUS_LABELS = {
3290
+ empty: "Empty",
3291
+ queued: "Queued",
3292
+ running: "Running",
3293
+ interrupted: "Interrupted, preserved",
3294
+ approval_blocked: "Blocked on approval",
3295
+ failed: "Failed",
3296
+ completed: "Completed",
3297
+ stale: "Stale",
3298
+ reconnecting: "Reconnecting",
3299
+ unavailable: "Unavailable",
3300
+ outcome_unknown: "Outcome unknown"
3301
+ };
3302
+ // src/ui/queue/rules/state.ts
3303
+ const QUEUE_STATUS_STATES = {
3304
+ empty: "empty",
3305
+ queued: "queued",
3306
+ running: "running",
3307
+ interrupted: "interrupted_preserved",
3308
+ approval_blocked: "approval_blocked",
3309
+ failed: "failed",
3310
+ completed: "completed",
3311
+ stale: "stale",
3312
+ reconnecting: "reconnecting",
3313
+ unavailable: "unavailable",
3314
+ outcome_unknown: "outcome_unknown"
3315
+ };
3316
+ /** Statuses whose submission the server is no longer holding as pending work. */
3317
+ const SETTLED_ENTRY_STATUSES = /* @__PURE__ */ new Set([
3318
+ "completed",
3319
+ "failed",
3320
+ "empty"
3321
+ ]);
3322
+ const STALE_STATES = /* @__PURE__ */ new Set([
3323
+ "stale",
3324
+ "reconnecting",
3325
+ "restarted",
3326
+ "outcome_unknown",
3327
+ "session_stopped",
3328
+ "session_incompatible",
3329
+ "loading"
3330
+ ]);
3331
+ /**
3332
+ * Every readiness arm the server can publish, and what it means for the queue.
3333
+ *
3334
+ * A readiness state always arrives over a live socket, so none of these arms
3335
+ * is `disconnected`: they say something about the server's Codex session, not
3336
+ * about this chat's connection. `null` hands the decision to the queue's own
3337
+ * status. The exhaustive map is the point: a new readiness arm fails
3338
+ * type-check here rather than falling through to an ordinary label.
3339
+ */
3340
+ const READINESS_STATES = {
3341
+ stopped: "session_stopped",
3342
+ storage_mismatch: "session_stopped",
3343
+ backoff: "reconnecting",
3344
+ reconnecting: "reconnecting",
3345
+ incompatible_contract: "session_incompatible",
3346
+ initialized: "unavailable",
3347
+ login_capable: "unavailable",
3348
+ signed_out: "unavailable",
3349
+ login_pending: "unavailable",
3350
+ thread_capable: null
3351
+ };
3352
+ /**
3353
+ * Whether the server no longer holds this entry as pending work.
3354
+ * @param status The entry status.
3355
+ * @returns True for completed, failed and empty.
3356
+ */
3357
+ function isSettledEntryStatus(status) {
3358
+ return SETTLED_ENTRY_STATUSES.has(status);
3359
+ }
3360
+ /**
3361
+ * The child identity a thread link names, when it names one.
3362
+ * @param link The published thread link, or null before a snapshot.
3363
+ * @returns The child and epoch, or null for an unbound or inspect-only link.
3364
+ */
3365
+ function childIdentityOf(link) {
3366
+ if (link?.state !== "executable") return null;
3367
+ return {
3368
+ childId: link.childId,
3369
+ epoch: link.epoch
3370
+ };
3371
+ }
3372
+ /**
3373
+ * Whether two child identities name the same child epoch.
3374
+ * @param left One identity, or null.
3375
+ * @param right The other identity, or null.
3376
+ * @returns True when both are null or both name the same child and epoch.
3377
+ */
3378
+ function sameChild(left, right) {
3379
+ if (left === null || right === null) return left === right;
3380
+ return left.childId === right.childId && left.epoch === right.epoch;
3381
+ }
3382
+ /**
3383
+ * A restart is the one state the wire cannot spell on its own: the queue looks
3384
+ * ordinary, but it belongs to a child that replaced the one the person was
3385
+ * reading. Comparing the presented child with the snapshot's is the only
3386
+ * authoritative way to see it.
3387
+ * @param presented The child the queue on screen was presented for.
3388
+ * @param current The child the snapshot names now.
3389
+ * @returns True when the child changed.
3390
+ */
3391
+ function isRestarted(presented, current) {
3392
+ if (presented === null || presented === void 0 || current === null) return false;
3393
+ return !sameChild(presented, current);
3394
+ }
3395
+ /**
3396
+ * The connection-owner state for a dropped or retrying socket.
3397
+ * @param state The connection state.
3398
+ * @returns Reconnecting while the socket retries, else disconnected.
3399
+ */
3400
+ function connectionOwnerState(state) {
3401
+ return state.state === "reconnecting" || state.state === "backoff" ? "reconnecting" : "disconnected";
3402
+ }
3403
+ /**
3404
+ * The transport state that outranks the queue's own status. The stream owner
3405
+ * reports a sequence gap as stale; the connection owner reports a dropped or
3406
+ * retrying socket, which is the only thing disconnected ever means; readiness
3407
+ * is the server telling the browser how far its Codex child has got over a
3408
+ * socket that is still up.
3409
+ * @param state The transport state.
3410
+ * @returns The governing state, or null when the queue's own status decides.
3411
+ */
3412
+ function connectionState(state) {
3413
+ if (state.kind === "stream") return "stale";
3414
+ if (state.kind === "connection") return connectionOwnerState(state);
3415
+ return READINESS_STATES[state.state];
3416
+ }
3417
+ /**
3418
+ * The state before any snapshot has arrived.
3419
+ * @param state The transport state, which carries no snapshot.
3420
+ * @returns Loading while the first connection is made, else the connection state.
3421
+ */
3422
+ function stateWithoutSnapshot(state) {
3423
+ if (state.kind === "connection" && state.state === "reconnecting") return "loading";
3424
+ return connectionState(state) ?? "loading";
3425
+ }
3426
+ /**
3427
+ * The state once nothing outranks the queue: an inexecutable link has no
3428
+ * queue, else the queue's own status decides.
3429
+ * @param state The transport state.
3430
+ * @param snapshot The published snapshot.
3431
+ * @returns The governing state.
3432
+ */
3433
+ function stateWithSnapshot(state, snapshot) {
3434
+ const connection = connectionState(state);
3435
+ if (connection !== null) return connection;
3436
+ if (snapshot.threadLink.state !== "executable") return "unavailable";
3437
+ return QUEUE_STATUS_STATES[snapshot.queue.status];
3438
+ }
3439
+ /**
3440
+ * Resolve the one state that governs the whole region.
3441
+ * @param input The projection input.
3442
+ * @returns The governing state.
3443
+ */
3444
+ function resolveWorkbenchQueueState(input) {
3445
+ const snapshot = input.state.snapshot;
3446
+ if (snapshot === null) return stateWithoutSnapshot(input.state);
3447
+ if (isRestarted(input.presentedChild, childIdentityOf(snapshot.threadLink))) return "restarted";
3448
+ if (input.settlement?.state === "outcome_unknown") return "outcome_unknown";
3449
+ return stateWithSnapshot(input.state, snapshot);
3450
+ }
3451
+ /**
3452
+ * Whether a state means the queue on screen has not been proven current.
3453
+ * @param state The governing state.
3454
+ * @returns True when nothing on screen may be treated as current.
3455
+ */
3456
+ function isStaleWorkbenchQueueState(state) {
3457
+ return STALE_STATES.has(state);
3458
+ }
3459
+ // src/ui/queue/rules/correlation.ts
3460
+ const ABSENT = Object.freeze({
3461
+ linkState: null,
3462
+ workhorseThreadId: null,
3463
+ workhorseThreadStatus: null,
3464
+ child: null,
3465
+ activeTurnId: null,
3466
+ activeTurnStatus: null,
3467
+ coordinatorThreadId: null,
3468
+ coordinatorState: null,
3469
+ blockingApprovals: 0,
3470
+ sequence: null
3471
+ });
3472
+ /**
3473
+ * The turn the workhorse is on: the last in-progress turn, else the last turn.
3474
+ * @param snapshot The published snapshot.
3475
+ * @returns The turn, or null when the timeline shows none.
3476
+ */
3477
+ function activeTurn(snapshot) {
3478
+ const turns = snapshot.timeline?.turns ?? [];
3479
+ return turns.findLast((turn) => turn.status === "inProgress") ?? turns.at(-1) ?? null;
3480
+ }
3481
+ /**
3482
+ * How many approvals are pending on the linked workhorse.
3483
+ * @param snapshot The published snapshot.
3484
+ * @returns The count.
3485
+ */
3486
+ function pendingApprovals(snapshot) {
3487
+ const threadId = snapshot.threadLink.threadId;
3488
+ return snapshot.approvals.filter((approval) => approval.threadId === threadId && approval.lifecycle.state === "pending").length;
3489
+ }
3490
+ /**
3491
+ * The words for the workhorse thread.
3492
+ * @param facts The correlation facts.
3493
+ * @returns A phrase.
3494
+ */
3495
+ function workhorseText(facts) {
3496
+ return facts.workhorseThreadId === null ? "no linked workhorse" : `workhorse thread ${facts.workhorseThreadId}`;
3497
+ }
3498
+ /**
3499
+ * The words for the active turn.
3500
+ * @param facts The correlation facts.
3501
+ * @returns A phrase.
3502
+ */
3503
+ function turnText(facts) {
3504
+ return facts.activeTurnId === null ? "no workhorse turn on record" : `turn ${facts.activeTurnId} (${facts.activeTurnStatus ?? "unknown"})`;
3505
+ }
3506
+ /**
3507
+ * One sentence naming the queue, its workhorse, and its coordinator.
3508
+ * @param state The governing state.
3509
+ * @param facts The correlation facts.
3510
+ * @param entryCount How many entries the server holds.
3511
+ * @returns The sentence.
3512
+ */
3513
+ function correlationSummary(state, facts, entryCount) {
3514
+ const coordinator = facts.coordinatorThreadId === null ? "no coordinator thread" : `coordinator thread ${facts.coordinatorThreadId}`;
3515
+ const submissions = entryCount === 1 ? "1 submission" : `${entryCount} submissions`;
3516
+ return `${WORKBENCH_QUEUE_STATE_WORDS[state].label}: ${submissions} on ${workhorseText(facts)}, ${turnText(facts)}, queued through ${coordinator}.`;
3517
+ }
3518
+ /**
3519
+ * The correlation facts a published snapshot carries.
3520
+ * @param snapshot The published snapshot.
3521
+ * @param sequence The transport sequence, or null.
3522
+ * @returns The facts.
3523
+ */
3524
+ function snapshotFacts(snapshot, sequence) {
3525
+ const turn = activeTurn(snapshot);
3526
+ return {
3527
+ linkState: snapshot.threadLink.state,
3528
+ workhorseThreadId: snapshot.threadLink.threadId,
3529
+ workhorseThreadStatus: snapshot.threadLink.status,
3530
+ child: childIdentityOf(snapshot.threadLink),
3531
+ activeTurnId: turn?.turnId ?? null,
3532
+ activeTurnStatus: turn?.status ?? null,
3533
+ coordinatorThreadId: snapshot.coordinator.threadId,
3534
+ coordinatorState: snapshot.coordinator.state,
3535
+ blockingApprovals: pendingApprovals(snapshot),
3536
+ sequence
3537
+ };
3538
+ }
3539
+ /**
3540
+ * The queue's correlation with its workhorse and coordinator.
3541
+ * @param state The governing state.
3542
+ * @param snapshot The published snapshot, or null.
3543
+ * @param sequence The transport sequence, or null.
3544
+ * @param entryCount How many entries the server holds.
3545
+ * @returns The correlation.
3546
+ */
3547
+ function projectCorrelation(state, snapshot, sequence, entryCount) {
3548
+ const facts = snapshot === null ? {
3549
+ ...ABSENT,
3550
+ sequence
3551
+ } : snapshotFacts(snapshot, sequence);
3552
+ return Object.freeze({
3553
+ ...facts,
3554
+ summary: correlationSummary(state, facts, entryCount)
3555
+ });
3556
+ }
3557
+ // src/ui/queue/rules/reorder.ts
3558
+ const NOT_IN_QUEUE = "That submission is not in the authoritative queue.";
3559
+ const FOREIGN$1 = "Only a submission this coordinator queued can be reordered.";
3560
+ const ALONE$1 = "There is no other coordinator-owned submission to move this one past.";
3561
+ const FIRST$1 = "This submission is already the first coordinator-owned entry.";
3562
+ const LAST$1 = "This submission is already the last coordinator-owned entry.";
3563
+ const SAME_PLACE = "This submission is already in that place.";
3564
+ /**
3565
+ * An entry carries the identity of the coordinator dynamic-tool call that
3566
+ * queued it. A null identity is a submission the coordinator did not
3567
+ * make, another client's or the workhorse's own, and this chat has no
3568
+ * authority to move it.
3569
+ * @param entry The queue entry.
3570
+ * @returns True when the coordinator queued it.
3571
+ */
3572
+ function isCoordinatorOwned(entry) {
3573
+ return entry.operationId !== null;
3574
+ }
3575
+ /**
3576
+ * The absolute slots the coordinator-owned entries occupy.
3577
+ * @param entries The authoritative entries.
3578
+ * @returns The slot indexes, in queue order.
3579
+ */
3580
+ function coordinatorSlots(entries) {
3581
+ const slots = [];
3582
+ for (const [index, entry] of entries.entries()) if (isCoordinatorOwned(entry)) slots.push(index);
3583
+ return slots;
3584
+ }
3585
+ /**
3586
+ * A refused plan.
3587
+ * @param reason Why nothing moves.
3588
+ * @returns The plan.
3589
+ */
3590
+ function refuse(reason) {
3591
+ return Object.freeze({
3592
+ moved: false,
3593
+ reason
3594
+ });
3595
+ }
3596
+ /**
3597
+ * Map a pointer drop onto a coordinator-owned slot. Dropping "before the entry
3598
+ * at absolute position p" is expressed among the coordinator-owned entries
3599
+ * alone, because foreign entries never leave their absolute slot. Removing the
3600
+ * dragged entry first shifts every later slot down by one, so a forward drop
3601
+ * is decremented.
3602
+ * @param ownedSlots The coordinator-owned slots.
3603
+ * @param fromOwnedIndex The dragged entry's index among them.
3604
+ * @param dropIndex The absolute 0-based index the drop lands before.
3605
+ * @returns The target index among the owned entries.
3606
+ */
3607
+ function ownedIndexForDrop(ownedSlots, fromOwnedIndex, dropIndex) {
3608
+ let target = ownedSlots.filter((slot) => slot < dropIndex).length;
3609
+ if (target > fromOwnedIndex) target -= 1;
3610
+ return Math.min(Math.max(target, 0), ownedSlots.length - 1);
3611
+ }
3612
+ /**
3613
+ * The owned index a move asks for.
3614
+ * @param ownedSlots The coordinator-owned slots.
3615
+ * @param fromOwnedIndex The moved entry's index among them.
3616
+ * @param move The requested move.
3617
+ * @returns The target owned index, possibly off either end for a step.
3618
+ */
3619
+ function targetOwnedIndex(ownedSlots, fromOwnedIndex, move) {
3620
+ if (move.kind === "step") return fromOwnedIndex + (move.direction === "earlier" ? -1 : 1);
3621
+ return ownedIndexForDrop(ownedSlots, fromOwnedIndex, move.position - 1);
3622
+ }
3623
+ /**
3624
+ * Why a target owned index cannot be used, if it cannot.
3625
+ * @param fromOwnedIndex The moved entry's owned index.
3626
+ * @param toOwnedIndex The requested owned index.
3627
+ * @param ownedCount How many coordinator-owned entries there are.
3628
+ * @returns The refusal, or null when the move is possible.
3629
+ */
3630
+ function targetRefusal(fromOwnedIndex, toOwnedIndex, ownedCount) {
3631
+ if (toOwnedIndex < 0) return FIRST$1;
3632
+ if (toOwnedIndex >= ownedCount) return LAST$1;
3633
+ return toOwnedIndex === fromOwnedIndex ? SAME_PLACE : null;
3634
+ }
3635
+ /**
3636
+ * Every submission id in the requested order: foreign entries in their slots,
3637
+ * coordinator-owned entries permuted among theirs.
3638
+ * @param entries The authoritative entries.
3639
+ * @param owned The coordinator-owned ids in their new order.
3640
+ * @returns The complete ordered id list.
3641
+ */
3642
+ function interleave(entries, owned) {
3643
+ let nextOwned = 0;
3644
+ const ordered = [];
3645
+ for (const entry of entries) {
3646
+ if (!isCoordinatorOwned(entry)) {
3647
+ ordered.push(entry.submissionId);
3648
+ continue;
3649
+ }
3650
+ const replacement = owned[nextOwned];
3651
+ nextOwned += 1;
3652
+ ordered.push(replacement ?? entry.submissionId);
3653
+ }
3654
+ return ordered;
3655
+ }
3656
+ /**
3657
+ * Why a submission cannot be the subject of a reorder, if it cannot.
3658
+ * @param subject The entry, or undefined when the queue does not hold it.
3659
+ * @param ownedCount How many coordinator-owned entries there are.
3660
+ * @returns The refusal, or null.
3661
+ */
3662
+ function subjectRefusal(subject, ownedCount) {
3663
+ if (subject === void 0) return NOT_IN_QUEUE;
3664
+ if (!isCoordinatorOwned(subject)) return FOREIGN$1;
3665
+ return ownedCount < 2 ? ALONE$1 : null;
3666
+ }
3667
+ /**
3668
+ * Produce the complete ordered submission-id array for one reorder.
3669
+ * @param entries The authoritative entries, never mutated.
3670
+ * @param submissionId The submission to move.
3671
+ * @param move Where to move it.
3672
+ * @returns The plan, or why nothing moves.
3673
+ */
3674
+ function planQueueReorder(entries, submissionId, move) {
3675
+ const fromIndex = entries.findIndex((entry) => entry.submissionId === submissionId);
3676
+ const ownedSlots = coordinatorSlots(entries);
3677
+ const subject = subjectRefusal(entries[fromIndex], ownedSlots.length);
3678
+ if (subject !== null) return refuse(subject);
3679
+ const fromOwnedIndex = ownedSlots.indexOf(fromIndex);
3680
+ const toOwnedIndex = targetOwnedIndex(ownedSlots, fromOwnedIndex, move);
3681
+ const target = targetRefusal(fromOwnedIndex, toOwnedIndex, ownedSlots.length);
3682
+ if (target !== null) return refuse(target);
3683
+ const owned = ownedSlots.map((slot) => entries[slot]?.submissionId ?? submissionId);
3684
+ const [carried] = owned.splice(fromOwnedIndex, 1);
3685
+ owned.splice(toOwnedIndex, 0, carried ?? submissionId);
3686
+ return Object.freeze({
3687
+ moved: true,
3688
+ submissionId,
3689
+ fromPosition: fromIndex + 1,
3690
+ toPosition: (ownedSlots[toOwnedIndex] ?? fromIndex) + 1,
3691
+ orderedSubmissionIds: Object.freeze(interleave(entries, owned))
3692
+ });
3693
+ }
3694
+ // src/ui/queue/rules/entry-projection.ts
3695
+ const ENABLED = Object.freeze({
3696
+ enabled: true,
3697
+ reason: null
3698
+ });
3699
+ const UNSUPPORTED = {
3700
+ queueAdd: "The server is not accepting queue add commands for this link.",
3701
+ queueUpdate: "The server is not accepting queue update commands for this link.",
3702
+ queueDelete: "The server is not accepting queue delete commands for this link.",
3703
+ queueReorder: "The server is not accepting queue reorder commands for this link.",
3704
+ queueStart: "The server is not accepting queue start commands for this link."
3705
+ };
3706
+ const FOREIGN = "Only a submission this coordinator queued can be reordered.";
3707
+ const ALONE = "There is no other coordinator-owned submission to move this one past.";
3708
+ const FIRST = "This submission is already the first coordinator-owned entry.";
3709
+ const LAST = "This submission is already the last coordinator-owned entry.";
3710
+ /**
3711
+ * A disabled control with its reason.
3712
+ * @param reason Why the control is unavailable.
3713
+ * @returns The availability.
3714
+ */
3715
+ function disabled(reason) {
3716
+ return Object.freeze({
3717
+ enabled: false,
3718
+ reason
3719
+ });
3720
+ }
3721
+ /**
3722
+ * Whether a command is offered: not while the region is blocked, and only
3723
+ * when the server accepts it for this link.
3724
+ * @param input The projection input.
3725
+ * @param block The region or entry block, or null.
3726
+ * @param command The gateway command.
3727
+ * @returns The availability.
3728
+ */
3729
+ function commandAvailability(input, block, command) {
3730
+ if (block !== null) return disabled(block);
3731
+ return input.capabilities.supportsCommand(command) ? ENABLED : disabled(UNSUPPORTED[command]);
3732
+ }
3733
+ /**
3734
+ * The prompt's first words, on one line.
3735
+ * @param prompt The queued prompt.
3736
+ * @returns At most 72 characters.
3737
+ */
3738
+ function summarize(prompt) {
3739
+ const collapsed = prompt.replaceAll(/\s+/gu, " ").trim();
3740
+ return collapsed.length > 72 ? `${collapsed.slice(0, 71)}…` : collapsed;
3741
+ }
3742
+ /**
3743
+ * How this entry relates to the linked workhorse right now.
3744
+ * @param entry The entry.
3745
+ * @param correlation The queue's correlation.
3746
+ * @returns A sentence.
3747
+ */
3748
+ function entryCorrelation(entry, correlation) {
3749
+ const workhorse = correlation.workhorseThreadId === null ? "no linked workhorse" : `workhorse ${correlation.workhorseThreadId}`;
3750
+ if (entry.status === "running") return `Running on ${workhorse} as ${correlation.activeTurnId ?? "an unnamed turn"}.`;
3751
+ if (entry.status === "approval_blocked") return `Held on ${workhorse} behind ${correlation.blockingApprovals} pending approval request(s).`;
3752
+ if (entry.operationId === null) return `Queued on ${workhorse} outside this coordinator. This chat can still edit, cancel or start it; only submissions this coordinator queued can be reordered.`;
3753
+ return `Queued on ${workhorse} by coordinator operation ${entry.operationId}. This chat can edit, cancel, start and reorder it.`;
3754
+ }
3755
+ /**
3756
+ * The reason an entry's own status disables its commands, if it does.
3757
+ * @param entry The entry.
3758
+ * @returns The reason, or null.
3759
+ */
3760
+ function entryBlock(entry) {
3761
+ if (entry.status === "running") return "This submission is already running on the linked workhorse.";
3762
+ if (isSettledEntryStatus(entry.status)) return "This submission already settled; it is history, not queued work.";
3763
+ return null;
3764
+ }
3765
+ /**
3766
+ * Whether a move in one direction is offered.
3767
+ * @param facts The move facts.
3768
+ * @returns The availability.
3769
+ */
3770
+ function moveAvailability(facts) {
3771
+ if (facts.block !== null) return disabled(facts.block);
3772
+ if (!facts.owned) return disabled(FOREIGN);
3773
+ if (facts.ownedCount < 2) return disabled(ALONE);
3774
+ if (facts.edge !== null) return disabled(facts.edge);
3775
+ return facts.supported ? ENABLED : disabled(UNSUPPORTED.queueReorder);
3776
+ }
3777
+ /**
3778
+ * One entry as the region renders it.
3779
+ * @param entry The entry.
3780
+ * @param index Its 0-based position.
3781
+ * @param context What every entry shares.
3782
+ * @returns The entry view.
3783
+ */
3784
+ function projectEntry(entry, index, context) {
3785
+ const owned = isCoordinatorOwned(entry);
3786
+ const block = context.block ?? entryBlock(entry);
3787
+ const ownershipLabel = owned ? "Coordinator" : "Foreign";
3788
+ const position = index + 1;
3789
+ const ownedIndex = context.ownedSlots.indexOf(index);
3790
+ const move = {
3791
+ block,
3792
+ owned,
3793
+ ownedCount: context.ownedSlots.length,
3794
+ supported: context.input.capabilities.supportsCommand("queueReorder")
3795
+ };
3796
+ return Object.freeze({
3797
+ submissionId: entry.submissionId,
3798
+ prompt: entry.prompt,
3799
+ status: entry.status,
3800
+ statusLabel: WORKBENCH_QUEUE_ENTRY_STATUS_LABELS[entry.status],
3801
+ position,
3802
+ total: context.total,
3803
+ ownership: owned ? "coordinator" : "foreign",
3804
+ ownershipLabel,
3805
+ coordinatorOperationId: entry.operationId,
3806
+ label: `${ownershipLabel} submission ${position} of ${context.total}: ${summarize(entry.prompt)}`,
3807
+ correlation: entryCorrelation(entry, context.correlation),
3808
+ edit: commandAvailability(context.input, block, "queueUpdate"),
3809
+ cancel: commandAvailability(context.input, block, "queueDelete"),
3810
+ start: commandAvailability(context.input, block, "queueStart"),
3811
+ moveEarlier: moveAvailability({
3812
+ ...move,
3813
+ edge: ownedIndex === 0 ? FIRST : null
3814
+ }),
3815
+ moveLater: moveAvailability({
3816
+ ...move,
3817
+ edge: ownedIndex === context.ownedSlots.length - 1 ? LAST : null
3818
+ })
3819
+ });
3820
+ }
3821
+ // src/ui/queue/rules/projection.ts
3822
+ /**
3823
+ * The reason the transport's capabilities cannot carry a queue command, if any.
3824
+ * @param capabilities The transport capabilities.
3825
+ * @returns The reason, or null.
3826
+ */
3827
+ function capabilityBlock(capabilities) {
3828
+ if (!capabilities.connected) return "The workbench socket is not connected.";
3829
+ if (capabilities.readiness !== "thread_capable") return "The workbench is not thread-capable yet, so it holds no command lease for this queue.";
3830
+ return null;
3831
+ }
3832
+ /**
3833
+ * The reason the transport cannot carry a queue command right now, if any.
3834
+ * @param input The projection input.
3835
+ * @returns The reason, or null.
3836
+ */
3837
+ function transportBlock(input) {
3838
+ if (input.targetBlock !== null && input.targetBlock !== void 0) return input.targetBlock;
3839
+ const capability = capabilityBlock(input.capabilities);
3840
+ if (capability !== null) return capability;
3841
+ if (input.pending !== null && input.pending !== void 0) return `A ${input.pending.control} command is in flight; its outcome is not settled yet.`;
3842
+ return null;
3843
+ }
3844
+ /**
3845
+ * The one reason that disables every queue command at once. It is
3846
+ * deliberately separate from a per-entry reason: a person reading "the queue
3847
+ * is stale" and a person reading "that submission is already running" need
3848
+ * different sentences.
3849
+ * @param input The projection input.
3850
+ * @param state The governing state.
3851
+ * @returns The reason, or null.
3852
+ */
3853
+ function regionBlock(input, state) {
3854
+ if (isStaleWorkbenchQueueState(state)) return WORKBENCH_QUEUE_STATE_WORDS[state].recovery;
3855
+ if (state === "unavailable") return WORKBENCH_QUEUE_STATE_WORDS.unavailable.recovery;
3856
+ return transportBlock(input);
3857
+ }
3858
+ /**
3859
+ * Whether the whole queue may be reordered.
3860
+ * @param context What every entry shares.
3861
+ * @returns The availability.
3862
+ */
3863
+ function reorderAvailability(context) {
3864
+ if (context.ownedSlots.length < 2) return disabled("There is no other coordinator-owned submission to move one past.");
3865
+ return commandAvailability(context.input, context.block, "queueReorder");
3866
+ }
3867
+ /**
3868
+ * Whether the authoritative list can be re-read. Refreshing is how every
3869
+ * unavailable, stale, reconnecting, restarted and unknown state recovers, so
3870
+ * it stays reachable whenever a socket exists.
3871
+ * @param input The projection input.
3872
+ * @returns The availability.
3873
+ */
3874
+ function listAvailability(input) {
3875
+ return input.state.connection === "stopped" ? disabled("The workbench has no socket to read an authoritative queue from.") : ENABLED;
3876
+ }
3877
+ /**
3878
+ * Everything the queue region renders.
3879
+ * @param input The projection input.
3880
+ * @returns The view.
3881
+ */
3882
+ function projectWorkbenchQueue(input) {
3883
+ const snapshot = input.state.snapshot;
3884
+ const state = resolveWorkbenchQueueState(input);
3885
+ const entries = snapshot?.queue.entries ?? [];
3886
+ const correlation = projectCorrelation(state, snapshot, input.state.sequence, entries.length);
3887
+ const ownedSlots = entries.flatMap((entry, index) => isCoordinatorOwned(entry) ? [index] : []);
3888
+ const context = {
3889
+ input,
3890
+ block: regionBlock(input, state),
3891
+ correlation,
3892
+ ownedSlots,
3893
+ total: entries.length
3894
+ };
3895
+ const words = WORKBENCH_QUEUE_STATE_WORDS[state];
3896
+ return Object.freeze({
3897
+ state,
3898
+ label: words.label,
3899
+ detail: words.detail,
3900
+ recovery: words.recovery,
3901
+ correlation,
3902
+ entries: Object.freeze(entries.map((entry, index) => projectEntry(entry, index, context))),
3903
+ coordinatorOwnedCount: ownedSlots.length,
3904
+ foreignCount: entries.length - ownedSlots.length,
3905
+ add: commandAvailability(input, context.block, "queueAdd"),
3906
+ list: listAvailability(input),
3907
+ reorder: reorderAvailability(context),
3908
+ stale: isStaleWorkbenchQueueState(state),
3909
+ pending: input.pending ?? null,
3910
+ settlement: input.settlement ?? null
3911
+ });
3912
+ }
3913
+ // src/ui/queue/state/store.ts
3914
+ /**
3915
+ * One observation store over one transport.
3916
+ * @param transport The transport port.
3917
+ * @returns The store.
3918
+ */
3919
+ function createWorkbenchQueueStore(transport) {
3920
+ const listeners = /* @__PURE__ */ new Set();
3921
+ let presentedChild = null;
3922
+ /**
3923
+ * The child the snapshot names now.
3924
+ * @returns The identity, or null.
3925
+ */
3926
+ const currentChild = () => childIdentityOf(transport.state().snapshot?.threadLink ?? null);
3927
+ /**
3928
+ * One fresh observation.
3929
+ * @returns The observation.
3930
+ */
3931
+ const read = () => {
3932
+ presentedChild ??= currentChild();
3933
+ return Object.freeze({
3934
+ state: transport.state(),
3935
+ capabilities: transport.capabilities(),
3936
+ target: captureWorkbenchQueueTarget(transport),
3937
+ presentedChild
3938
+ });
3939
+ };
3940
+ let cached = read();
3941
+ /**
3942
+ * Re-read and tell every listener.
3943
+ */
3944
+ const publish = () => {
3945
+ cached = read();
3946
+ for (const listener of listeners) listener();
3947
+ };
3948
+ return Object.freeze({
3949
+ /**
3950
+ * Follow the transport while subscribed.
3951
+ * @param listener Notified after each observation.
3952
+ * @returns Release the subscription.
3953
+ */
3954
+ subscribe: (listener) => {
3955
+ listeners.add(listener);
3956
+ const release = transport.subscribe(publish);
3957
+ cached = read();
3958
+ return () => {
3959
+ listeners.delete(listener);
3960
+ release();
3961
+ };
3962
+ },
3963
+ /**
3964
+ * The latest observation; a stable identity between notifications.
3965
+ * @returns The observation.
3966
+ */
3967
+ getSnapshot: () => cached,
3968
+ /**
3969
+ * Accept the current child as the one the queue is presented for.
3970
+ */
3971
+ acceptCurrentChild: () => {
3972
+ presentedChild = currentChild();
3973
+ publish();
3974
+ }
3975
+ });
3976
+ }
3977
+ // src/ui/queue/state/controller.ts
3978
+ const STEP_EARLIER = Object.freeze({
3979
+ kind: "step",
3980
+ direction: "earlier"
3981
+ });
3982
+ const STEP_LATER = Object.freeze({
3983
+ kind: "step",
3984
+ direction: "later"
3985
+ });
3986
+ /**
3987
+ * A refusal this module decided on its own, before the wire.
3988
+ * @param control The control.
3989
+ * @param submissionId The submission, or null.
3990
+ * @param message Why.
3991
+ * @returns The settlement.
3992
+ */
3993
+ function localRefusal(control, submissionId, message) {
3994
+ return Object.freeze({
3995
+ control,
3996
+ state: "refused",
3997
+ code: null,
3998
+ message,
3999
+ submissionId
4000
+ });
4001
+ }
4002
+ /**
4003
+ * One queue controller over one transport.
4004
+ * @param transport The transport port.
4005
+ * @returns The controller.
4006
+ */
4007
+ function createWorkbenchQueueController(transport) {
4008
+ const store = createWorkbenchQueueStore(transport);
4009
+ const commands = createWorkbenchQueueCommands(transport);
4010
+ const listeners = /* @__PURE__ */ new Set();
4011
+ let commandState = Object.freeze({
4012
+ pending: null,
4013
+ settlement: null
4014
+ });
4015
+ /**
4016
+ * Publish new command state.
4017
+ * @param next The state.
4018
+ */
4019
+ function publish(next) {
4020
+ commandState = Object.freeze(next);
4021
+ for (const listener of listeners) listener();
4022
+ }
4023
+ /**
4024
+ * Run one command against the target captured for the queue on screen.
4025
+ * @param control The control.
4026
+ * @param submissionId The submission, or null.
4027
+ * @param dispatch The command, given its target.
4028
+ * @returns The settlement.
4029
+ */
4030
+ async function run(control, submissionId, dispatch) {
4031
+ const capture = store.getSnapshot().target;
4032
+ if (!capture.captured) {
4033
+ const refused = localRefusal(control, submissionId, capture.reason);
4034
+ publish({
4035
+ pending: null,
4036
+ settlement: refused
4037
+ });
4038
+ return refused;
4039
+ }
4040
+ publish({
4041
+ pending: {
4042
+ control,
4043
+ submissionId
4044
+ },
4045
+ settlement: commandState.settlement
4046
+ });
4047
+ const settled = await dispatch(capture.target);
4048
+ publish({
4049
+ pending: null,
4050
+ settlement: settled
4051
+ });
4052
+ return settled;
4053
+ }
4054
+ /**
4055
+ * Refresh the list. Refreshing is how a person accepts a replaced child:
4056
+ * the authoritative queue that just arrived is the queue now presented.
4057
+ * @returns The settlement.
4058
+ */
4059
+ async function list() {
4060
+ publish({
4061
+ pending: {
4062
+ control: "list",
4063
+ submissionId: null
4064
+ },
4065
+ settlement: commandState.settlement
4066
+ });
4067
+ const settled = await commands.list();
4068
+ publish({
4069
+ pending: null,
4070
+ settlement: settled
4071
+ });
4072
+ if (settled.state === "reconciled") store.acceptCurrentChild();
4073
+ return settled;
4074
+ }
4075
+ /**
4076
+ * Queue one submission behind the current turn.
4077
+ * @param prompt The prompt.
4078
+ * @returns The settlement.
4079
+ */
4080
+ function add(prompt) {
4081
+ return run("add", null, (target) => commands.add(prompt, target));
4082
+ }
4083
+ /**
4084
+ * Replace one queued prompt.
4085
+ * @param submissionId The submission.
4086
+ * @param prompt The new prompt.
4087
+ * @returns The settlement.
4088
+ */
4089
+ function edit(submissionId, prompt) {
4090
+ return run("edit", submissionId, (target) => commands.edit(submissionId, prompt, target));
4091
+ }
4092
+ /**
4093
+ * Delete one queued submission.
4094
+ * @param submissionId The submission.
4095
+ * @returns The settlement.
4096
+ */
4097
+ function cancel(submissionId) {
4098
+ return run("cancel", submissionId, (target) => commands.cancel(submissionId, target));
4099
+ }
4100
+ /**
4101
+ * Start one queued submission now.
4102
+ * @param submissionId The submission.
4103
+ * @returns The settlement.
4104
+ */
4105
+ function start(submissionId) {
4106
+ return run("start", submissionId, (target) => commands.start(submissionId, target));
4107
+ }
4108
+ /**
4109
+ * Plan and send one reorder. A plan that moves nothing is refused here and
4110
+ * never reaches the wire.
4111
+ * @param submissionId The submission to move.
4112
+ * @param reorder Where to move it.
4113
+ * @returns The settlement.
4114
+ */
4115
+ function move(submissionId, reorder) {
4116
+ const plan = planQueueReorder(store.getSnapshot().state.snapshot?.queue.entries ?? [], submissionId, reorder);
4117
+ if (!plan.moved) {
4118
+ const refused = localRefusal("reorder", submissionId, plan.reason);
4119
+ publish({
4120
+ pending: null,
4121
+ settlement: refused
4122
+ });
4123
+ return Promise.resolve(refused);
4124
+ }
4125
+ return run("reorder", submissionId, (target) => commands.reorder(plan.orderedSubmissionIds, target, submissionId));
4126
+ }
4127
+ /**
4128
+ * Follow the transport and the command state.
4129
+ * @param listener Notified on every change.
4130
+ * @returns Release the subscription.
4131
+ */
4132
+ function subscribe(listener) {
4133
+ listeners.add(listener);
4134
+ const release = store.subscribe(listener);
4135
+ return () => {
4136
+ listeners.delete(listener);
4137
+ release();
4138
+ };
4139
+ }
4140
+ /**
4141
+ * The view for the current observation and command state.
4142
+ * @returns The view.
4143
+ */
4144
+ function view() {
4145
+ const observation = store.getSnapshot();
4146
+ return projectWorkbenchQueue({
4147
+ state: observation.state,
4148
+ capabilities: observation.capabilities,
4149
+ presentedChild: observation.presentedChild,
4150
+ targetBlock: observation.target.captured ? null : observation.target.reason,
4151
+ pending: commandState.pending,
4152
+ settlement: commandState.settlement
4153
+ });
4154
+ }
4155
+ /**
4156
+ * The panel names a submission as a plain string; the wire needs the
4157
+ * branded id the server published. Only an id the authoritative queue holds
4158
+ * resolves, so the panel can never name a submission the server has not.
4159
+ * @param control The control asking.
4160
+ * @param submissionId The panel's string.
4161
+ * @param dispatch The command, given the resolved id.
4162
+ */
4163
+ function fromPanel(control, submissionId, dispatch) {
4164
+ const entry = (store.getSnapshot().state.snapshot?.queue.entries ?? []).find((candidate) => candidate.submissionId === submissionId);
4165
+ if (entry === void 0) {
4166
+ publish({
4167
+ pending: null,
4168
+ settlement: localRefusal(control, null, "That submission is not in the authoritative queue.")
4169
+ });
4170
+ return;
4171
+ }
4172
+ dispatch(entry.submissionId);
4173
+ }
4174
+ const panelActions = Object.freeze({
4175
+ /**
4176
+ * Move one submission one coordinator slot earlier.
4177
+ * @param submissionId The submission.
4178
+ */
4179
+ moveUp: (submissionId) => {
4180
+ fromPanel("reorder", submissionId, (resolved) => move(resolved, STEP_EARLIER));
4181
+ },
4182
+ /**
4183
+ * Move one submission one coordinator slot later.
4184
+ * @param submissionId The submission.
4185
+ */
4186
+ moveDown: (submissionId) => {
4187
+ fromPanel("reorder", submissionId, (resolved) => move(resolved, STEP_LATER));
4188
+ },
4189
+ /**
4190
+ * Delete one queued submission.
4191
+ * @param submissionId The submission.
4192
+ */
4193
+ remove: (submissionId) => {
4194
+ fromPanel("cancel", submissionId, cancel);
4195
+ },
4196
+ /**
4197
+ * Start one queued submission now.
4198
+ * @param submissionId The submission.
4199
+ */
4200
+ sendNow: (submissionId) => {
4201
+ fromPanel("start", submissionId, start);
4202
+ }
4203
+ });
4204
+ return Object.freeze({
4205
+ subscribe,
4206
+ view,
4207
+ /**
4208
+ * The controller's own state.
4209
+ * @returns The pending command and the last settlement.
4210
+ */
4211
+ commandState: () => commandState,
4212
+ list,
4213
+ add,
4214
+ edit,
4215
+ cancel,
4216
+ start,
4217
+ move,
4218
+ panelActions
4219
+ });
4220
+ }
4221
+ // src/ui/thread-link/rules/settlement.ts
4222
+ /**
4223
+ * An action name in words.
4224
+ * @param action The action.
4225
+ * @returns The words.
4226
+ */
4227
+ function words(action) {
4228
+ return action.replaceAll("_", " ");
4229
+ }
4230
+ /**
4231
+ * How a login command settled: the server's account facts decide, and a start
4232
+ * ChatGPT only accepted is not a completed sign-in.
4233
+ * @param result The transport's result.
4234
+ * @returns The settlement.
4235
+ */
4236
+ function loginSettlement(result) {
4237
+ const account = result.snapshot.account;
4238
+ if (account.state === "failed") return {
4239
+ state: "failed",
4240
+ announcement: account.reason
4241
+ };
4242
+ if (account.state === "login_pending" || result.snapshot.login.state === "pending") return {
4243
+ state: "succeeded",
4244
+ announcement: "Sign-in started. Complete the sign-in to continue."
4245
+ };
4246
+ if (account.state === "ready") return {
4247
+ state: "succeeded",
4248
+ announcement: "Signed in."
4249
+ };
4250
+ return {
4251
+ state: "inspect_only",
4252
+ announcement: "Sign-in has not been confirmed. Check the account status before trying again."
4253
+ };
4254
+ }
4255
+ /**
4256
+ * How a create settled: only a confirmed executable link is a success.
4257
+ * @param result The transport's result.
4258
+ * @returns The settlement.
4259
+ */
4260
+ function createSettlement(result) {
4261
+ const link = result.snapshot.threadLink;
4262
+ if (link.state !== "executable") return {
4263
+ state: "inspect_only",
4264
+ announcement: `The create completed without a confirmed executable link, so this chat stays inspect-only. ${link.reason ?? "The server named no reason."}`
4265
+ };
4266
+ return {
4267
+ state: "succeeded",
4268
+ announcement: "Agent connected."
4269
+ };
4270
+ }
4271
+ /**
4272
+ * What a refusal says: a create whose coordinator could not start says why the
4273
+ * coordinator could not, which the server publishes with the refusal; anything
4274
+ * else says the refusal's own words.
4275
+ * @param action The action.
4276
+ * @param result The transport's result.
4277
+ * @param target The action's target.
4278
+ * @returns The announcement.
4279
+ */
4280
+ function refusalWords(action, result, target) {
4281
+ const coordinator = result.snapshot.coordinator;
4282
+ return (action === "create" && result.code === "command_failed" && coordinator.state === "failed" ? coordinator.reason : null) ?? result.message ?? `The workbench refused ${words(action)} for chat ${target.chatId}.`;
4283
+ }
4284
+ /**
4285
+ * How a delivered command settled, by action.
4286
+ * @param action The action.
4287
+ * @param result The transport's result.
4288
+ * @param target The action's target.
4289
+ * @returns The settlement.
4290
+ */
4291
+ function deliveredSettlement(action, result, target) {
4292
+ if (action === "login") return loginSettlement(result);
4293
+ if (action === "create") return createSettlement(result);
4294
+ return {
4295
+ state: "succeeded",
4296
+ announcement: `${words(action)} completed for chat ${target.chatId}.`
4297
+ };
4298
+ }
4299
+ /**
4300
+ * How one command settled.
4301
+ * @param action The action.
4302
+ * @param result The transport's result.
4303
+ * @param target The action's target.
4304
+ * @returns The settlement.
4305
+ */
4306
+ function classify(action, result, target) {
4307
+ if (result.outcome === "outcome_unknown") return {
4308
+ state: "inspect_only",
4309
+ announcement: `The ${words(action)} outcome is unknown. Inspect the current link before acting again; do not retry blind. ${result.message ?? ""}`.trim()
4310
+ };
4311
+ if (result.outcome === "not_delivered" || result.code !== null) return {
4312
+ state: "failed",
4313
+ announcement: refusalWords(action, result, target)
4314
+ };
4315
+ return deliveredSettlement(action, result, target);
4316
+ }
4317
+ // src/ui/thread-link/rules/transport-errors.ts
4318
+ const CODES = /* @__PURE__ */ new Set([
4319
+ ...BROWSER_GATEWAY_ERROR_CODES,
4320
+ "gateway_error",
4321
+ "socket_unavailable",
4322
+ "response_lost",
4323
+ "replaced",
4324
+ "incompatible_contract"
4325
+ ]);
4326
+ const OUTCOMES = /* @__PURE__ */ new Set([
4327
+ "delivered",
4328
+ "not_delivered",
4329
+ "outcome_unknown"
4330
+ ]);
4331
+ const UNCERTAIN_CODES = /* @__PURE__ */ new Set(["response_lost", "outcome_unknown"]);
4332
+ /**
4333
+ * Whether a value is a delivery outcome.
4334
+ * @param value The value.
4335
+ * @returns True for the three outcomes.
4336
+ */
4337
+ function isOutcome(value) {
4338
+ return typeof value === "string" && OUTCOMES.has(value);
4339
+ }
4340
+ /**
4341
+ * Whether a value is a code the transport can carry.
4342
+ * @param value The value.
4343
+ * @returns True for a known code.
4344
+ */
4345
+ function isCode(value) {
4346
+ return typeof value === "string" && CODES.has(value);
4347
+ }
4348
+ /**
4349
+ * The transport facts a thrown error carries, when it is a transport error.
4350
+ * @param error The thrown value.
4351
+ * @returns Its code, outcome and message, or null for any other error.
4352
+ */
4353
+ function transportErrorFacts(error) {
4354
+ if (!(error instanceof Error) || !("code" in error) || !("outcome" in error)) return null;
4355
+ const { code, outcome } = error;
4356
+ if (!isCode(code) || !isOutcome(outcome)) return null;
4357
+ return {
4358
+ code,
4359
+ outcome,
4360
+ message: error.message
4361
+ };
4362
+ }
4363
+ /**
4364
+ * The message of a thrown value.
4365
+ * @param error The thrown value.
4366
+ * @returns Its message, or the generic words for an unnamed failure.
4367
+ */
4368
+ function errorMessage(error) {
4369
+ return error instanceof Error && error.message.trim().length > 0 ? error.message : "The Codex workbench action failed.";
4370
+ }
4371
+ /**
4372
+ * Whether a thrown value leaves the outcome unknown.
4373
+ * @param error The thrown value.
4374
+ * @returns True for a lost response or an unknown outcome.
4375
+ */
4376
+ function uncertain(error) {
4377
+ const facts = transportErrorFacts(error);
4378
+ if (facts === null) return false;
4379
+ return UNCERTAIN_CODES.has(facts.code) || facts.outcome === "outcome_unknown";
4380
+ }
4381
+ // src/ui/thread-link/state/controller.ts
4382
+ /**
4383
+ * The target of an action, captured once.
4384
+ * @param chat The chat.
4385
+ * @param captured The captured intent.
4386
+ * @returns The target.
4387
+ */
4388
+ function captureTarget(chat, captured) {
4389
+ return Object.freeze({
4390
+ chatId: chat.chatId,
4391
+ childId: captured.authority?.childId ?? null,
4392
+ epoch: captured.authority?.epoch ?? null,
4393
+ commandId: null,
4394
+ capturedLinkState: captured.capturedThreadLink.state,
4395
+ capturedLinkThreadId: captured.capturedThreadLink.threadId
4396
+ });
4397
+ }
4398
+ /**
4399
+ * A target for an action the workbench refused to hand a target to.
4400
+ * @param chatId The chat.
4401
+ * @returns The target.
4402
+ */
4403
+ function bareTarget(chatId) {
4404
+ return Object.freeze({
4405
+ chatId,
4406
+ childId: null,
4407
+ epoch: null,
4408
+ commandId: null,
4409
+ capturedLinkState: null,
4410
+ capturedLinkThreadId: null
4411
+ });
4412
+ }
4413
+ /**
4414
+ * The announcement of a pending action.
4415
+ * @param action The action.
4416
+ * @param chatId The chat.
4417
+ * @returns The words.
4418
+ */
4419
+ function pendingWords(action, chatId) {
4420
+ return action === "login" ? "Starting sign-in…" : `${words(action)} started for chat ${chatId}.`;
4421
+ }
4422
+ /**
4423
+ * The thread-link action controller.
4424
+ * @param options How it reaches its chat.
4425
+ * @returns The controller.
4426
+ */
4427
+ function createThreadLinkController(options) {
4428
+ let revision = 0;
4429
+ let published = Object.freeze({
4430
+ state: "idle",
4431
+ revision
4432
+ });
4433
+ const listeners = /* @__PURE__ */ new Set();
4434
+ /**
4435
+ * Publish one snapshot. A rendering subscriber never changes settlement.
4436
+ * @param next The snapshot.
4437
+ */
4438
+ function publish(next) {
4439
+ published = Object.freeze(next);
4440
+ for (const listener of listeners) try {
4441
+ listener();
4442
+ } catch {}
4443
+ }
4444
+ /**
4445
+ * Settle one action, unless a later action superseded it.
4446
+ * @param operationRevision The action's revision.
4447
+ * @param next The settled snapshot.
4448
+ * @returns Whether the settlement was published.
4449
+ */
4450
+ function settle(operationRevision, next) {
4451
+ if (operationRevision !== revision) return Object.freeze({
4452
+ state: "ignored",
4453
+ revision: operationRevision
4454
+ });
4455
+ publish(next);
4456
+ return Object.freeze({
4457
+ state: "applied",
4458
+ revision: operationRevision
4459
+ });
4460
+ }
4461
+ /**
4462
+ * A fresh revision, superseding every earlier action.
4463
+ * @returns The revision.
4464
+ */
4465
+ function nextRevision() {
4466
+ revision += 1;
4467
+ return revision;
4468
+ }
4469
+ /**
4470
+ * Dispatch one captured command and classify its result.
4471
+ * @param chat The chat.
4472
+ * @param action The action.
4473
+ * @param draft The draft.
4474
+ * @param target The captured target.
4475
+ * @param captured The captured intent.
4476
+ * @returns The settled snapshot.
4477
+ */
4478
+ async function dispatch(chat, action, draft, target, captured) {
4479
+ if (!chat.transport.capabilities().supportsCommand(draft.command)) return {
4480
+ state: "failed",
4481
+ revision,
4482
+ action,
4483
+ target,
4484
+ announcement: `The workbench is not ready for ${draft.command}. It arrived before this chat reached the state that command needs.`
4485
+ };
4486
+ const result = await chat.transport.executeCommand(draft, captured);
4487
+ const settledTarget = Object.freeze({
4488
+ ...target,
4489
+ commandId: result.commandId
4490
+ });
4491
+ const settlement = classify(action, result, settledTarget);
4492
+ return {
4493
+ state: settlement.state,
4494
+ revision,
4495
+ action,
4496
+ target: settledTarget,
4497
+ announcement: settlement.announcement
4498
+ };
4499
+ }
4500
+ /**
4501
+ * The settled snapshot of a thrown command.
4502
+ * @param action The action.
4503
+ * @param target The target, as far as it was captured.
4504
+ * @param error The thrown value.
4505
+ * @returns The settled snapshot.
4506
+ */
4507
+ function thrown(action, target, error) {
4508
+ const unknown = uncertain(error);
4509
+ return {
4510
+ state: unknown ? "inspect_only" : "failed",
4511
+ revision,
4512
+ action,
4513
+ target,
4514
+ announcement: unknown ? `${errorMessage(error)} The outcome is unknown; inspect the current link and do not retry blind.` : errorMessage(error)
4515
+ };
4516
+ }
4517
+ /**
4518
+ * Run one command against the chat captured now.
4519
+ * @param action The action.
4520
+ * @param draft The draft.
4521
+ * @returns Whether the settlement was published.
4522
+ */
4523
+ async function run(action, draft) {
4524
+ const chat = options.captureChat();
4525
+ const operationRevision = nextRevision();
4526
+ let target = bareTarget(chat.chatId);
4527
+ try {
4528
+ const captured = chat.transport.captureCommandIntent();
4529
+ target = captureTarget(chat, captured);
4530
+ publish({
4531
+ state: "pending",
4532
+ revision: operationRevision,
4533
+ action,
4534
+ target,
4535
+ announcement: pendingWords(action, target.chatId)
4536
+ });
4537
+ return settle(operationRevision, {
4538
+ ...await dispatch(chat, action, draft, target, captured),
4539
+ revision: operationRevision
4540
+ });
4541
+ } catch (error) {
4542
+ return settle(operationRevision, {
4543
+ ...thrown(action, target, error),
4544
+ revision: operationRevision
4545
+ });
4546
+ }
4547
+ }
4548
+ return Object.freeze({
4549
+ /**
4550
+ * The published action.
4551
+ * @returns The snapshot.
4552
+ */
4553
+ snapshot: () => published,
4554
+ /**
4555
+ * Follow the published action.
4556
+ * @param listener Notified on every publish.
4557
+ * @returns Release the subscription.
4558
+ */
4559
+ subscribe: (listener) => {
4560
+ listeners.add(listener);
4561
+ return () => {
4562
+ listeners.delete(listener);
4563
+ };
4564
+ },
4565
+ /**
4566
+ * Create a fresh workhorse.
4567
+ * @returns Whether the settlement was published.
4568
+ */
4569
+ create: () => run("create", { command: "threadLinkCreate" }),
4570
+ /**
4571
+ * Start one sign-in.
4572
+ * @param login The vendor login value.
4573
+ * @returns Whether the settlement was published.
4574
+ */
4575
+ login: (login) => run("login", {
4576
+ command: "accountLogin",
4577
+ login
4578
+ }),
4579
+ /**
4580
+ * Cancel one pending sign-in.
4581
+ * @param loginId The sign-in.
4582
+ * @returns Whether the settlement was published.
4583
+ */
4584
+ cancelLogin: (loginId) => run("cancel_login", {
4585
+ command: "accountLoginCancel",
4586
+ loginId
4587
+ }),
4588
+ /**
4589
+ * Sign out.
4590
+ * @returns Whether the settlement was published.
4591
+ */
4592
+ logout: () => run("logout", { command: "accountLogout" })
4593
+ });
4594
+ }
4595
+ // src/ui/conversation/state/controllers.ts
4596
+ /**
4597
+ * Make the conversation controllers of one chat.
4598
+ * @param options The chat and its transport.
4599
+ * @returns The controllers.
4600
+ */
4601
+ function createConversationControllers(options) {
4602
+ const { chatId, transport } = options;
4603
+ return Object.freeze({
4604
+ threadLink: createThreadLinkController({
4605
+ /**
4606
+ * The chat an action is captured against.
4607
+ * @returns The capture.
4608
+ */
4609
+ captureChat: () => ({
4610
+ chatId,
4611
+ transport
4612
+ }) }),
4613
+ composer: createWorkbenchComposerController({ transport }),
4614
+ queue: createWorkbenchQueueController(transport),
4615
+ approvals: createWorkbenchApprovalsController(transport)
4616
+ });
4617
+ }
4618
+ // src/ui/timeline/rules/projection.ts
4619
+ /**
4620
+ * The stable id of one turn.
4621
+ * @param threadId The thread.
4622
+ * @param turnId The turn.
4623
+ * @returns The id.
4624
+ */
4625
+ function conversationTurnId(threadId, turnId) {
4626
+ return JSON.stringify([
4627
+ "turn",
4628
+ threadId,
4629
+ turnId
4630
+ ]);
4631
+ }
4632
+ /**
4633
+ * How a turn ended.
4634
+ * @param status The Codex status.
4635
+ * @returns The outcome.
4636
+ */
4637
+ function outcomeOf(status) {
4638
+ return status === "inProgress" ? "running" : status;
4639
+ }
4640
+ /**
4641
+ * Refuse an identity already seen.
4642
+ * @param seen The identities so far.
4643
+ * @param identity This one.
4644
+ * @param what What it identifies, for the refusal.
4645
+ */
4646
+ function claimIdentity(seen, identity, what) {
4647
+ if (seen.has(identity)) throw new Error(`Codex published the same ${what} twice: ${identity}`);
4648
+ seen.add(identity);
4649
+ }
4650
+ /**
4651
+ * What makes one item of a turn itself. An approval shares the item id of
4652
+ * the call it gates, and one call can be asked about more than once, so an
4653
+ * approval is itself by its own id.
4654
+ * @param turnId The turn.
4655
+ * @param item The item.
4656
+ * @returns The identity.
4657
+ */
4658
+ function itemIdentity(turnId, item) {
4659
+ const own = item.media === "approval" ? item.approvalId : item.itemId;
4660
+ return `${turnId}/${item.media}/${own}`;
4661
+ }
4662
+ /**
4663
+ * The conversation a timeline holds.
4664
+ * @param timeline The authoritative timeline.
4665
+ * @param owner Whose thread it is.
4666
+ * @returns One turn per Codex turn, in order.
4667
+ * @throws {Error} When a turn or an item is published twice.
4668
+ */
4669
+ function projectTimelineTurns(timeline, owner) {
4670
+ const turns = /* @__PURE__ */ new Set();
4671
+ const items = /* @__PURE__ */ new Set();
4672
+ return timeline.turns.map((turn) => {
4673
+ claimIdentity(turns, turn.turnId, "turn");
4674
+ for (const item of turn.items) claimIdentity(items, itemIdentity(turn.turnId, item), "item");
4675
+ return {
4676
+ id: conversationTurnId(timeline.threadId, turn.turnId),
4677
+ owner,
4678
+ threadId: timeline.threadId,
4679
+ turnId: turn.turnId,
4680
+ outcome: outcomeOf(turn.status),
4681
+ items: turn.items,
4682
+ startedAtMs: turn.startedAtMs,
4683
+ completedAtMs: turn.completedAtMs,
4684
+ durationMs: turn.durationMs,
4685
+ error: turn.error,
4686
+ plan: turn.plan,
4687
+ delegatedBy: turn.delegatedBy == null ? null : {
4688
+ turnId: turn.delegatedBy,
4689
+ shown: false
4690
+ }
4691
+ };
4692
+ });
4693
+ }
4694
+ /**
4695
+ * Each turn of one thread with the time it sorts by: when it started, and for
4696
+ * a turn that has no start, the time of the turn before it in its own thread.
4697
+ * A thread's own order never changes.
4698
+ * @param turns One thread's turns, in order.
4699
+ * @returns The turns with their keys, never decreasing.
4700
+ */
4701
+ function placed(turns) {
4702
+ let latest = Number.NEGATIVE_INFINITY;
4703
+ return turns.map((turn) => {
4704
+ latest = Math.max(latest, turn.startedAtMs ?? latest);
4705
+ return {
4706
+ turn,
4707
+ key: latest
4708
+ };
4709
+ });
4710
+ }
4711
+ /**
4712
+ * Compare two places by time.
4713
+ * @param left The first.
4714
+ * @param right The second.
4715
+ * @returns Negative when the first sorts first.
4716
+ */
4717
+ function byTime(left, right) {
4718
+ if (left.key === right.key) return 0;
4719
+ return left.key < right.key ? -1 : 1;
4720
+ }
4721
+ /**
4722
+ * A workhorse turn that says whether the coordinator turn which delegated it is
4723
+ * in the conversation.
4724
+ * @param turn The turn.
4725
+ * @param shown The coordinator turns in the conversation.
4726
+ * @returns The turn, as it was when nothing changes.
4727
+ */
4728
+ function withDelegationShown(turn, shown) {
4729
+ const { delegatedBy } = turn;
4730
+ if (delegatedBy === null) return turn;
4731
+ const isShown = shown.has(delegatedBy.turnId);
4732
+ if (isShown === delegatedBy.shown) return turn;
4733
+ return {
4734
+ ...turn,
4735
+ delegatedBy: {
4736
+ ...delegatedBy,
4737
+ shown: isShown
4738
+ }
4739
+ };
4740
+ }
4741
+ /**
4742
+ * The workhorse's turns and the voice coordinator's in one conversation, ordered
4743
+ * by when each started. Two turns that start together keep the coordinator's
4744
+ * first, since it is the one that hands work on.
4745
+ * @param workhorse The workhorse's turns, in order.
4746
+ * @param coordinator The voice coordinator's turns, in order.
4747
+ * @returns The turns, with each delegated one told whether its delegating turn is among them.
4748
+ */
4749
+ function mergeConversation(workhorse, coordinator) {
4750
+ if (coordinator.length === 0) return workhorse;
4751
+ const shown = new Set(coordinator.map((turn) => turn.turnId));
4752
+ return [...placed(coordinator), ...placed(workhorse)].toSorted(byTime).map(({ turn }) => withDelegationShown(turn, shown));
4753
+ }
4754
+ export { VOICE_OUTPUT_SPEAKING_LEVEL, browserAudioElements, createBrowserWorkbenchMediaOwner, createBrowserWorkbenchTransport, createConversationControllers, mergeConversation, projectTimelineTurns };