@archboard/codex-realtime-voice 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1374 @@
1
+ import { A as ApprovalOwnerView, B as DynamicServerRequest, C as WorkbenchExecutionContext, G as SessionResponsePayloads, H as TransportServerRequest, K as SessionThreadItem, L as CODEX_SESSION_THREAD_SOURCE, M as CodexApprovalBroker, N as DeepReadonly, O as WorkbenchContextSource, P as ItemApprovalIdentity, R as CodexSession, S as WorkbenchContextCodec, T as CodexRealtimeAdapter, U as SessionQueuedSubmission, V as TransportServerNotification, W as SessionResponse, a as CodexWorkhorseOperations, c as CodexThreadLinkPort, d as ThreadLinkReasonCode, f as ThreadLinkSnapshot, g as CodexEpochStore, h as ValidDynamicToolResponseSchema, i as CoordinatorCallbacks, j as ApprovalState, k as WorkbenchVoicePolicy, l as ThreadLinkBindingSnapshot, m as UnknownDynamicToolResponseSchema, n as SpokenApprovalSnapshot, o as CodexWorkhorseQueue, p as ThreadLinkTarget, q as SessionTurn, r as CoordinatorCallbackDeliveryReason, s as CodexCoordinator, t as CodexSpokenApprovalGate, u as ThreadLinkCasToken, v as WorkbenchDynamicTools, w as WorkbenchOperation, x as VoiceAgentIdentity, y as WorkbenchInstructions, z as CodexTransport } from "./contract-CZDUvuVt.mjs";
2
+ import { B as ChildId, G as OperationId, J as ThreadId, M as IdentityAuthorities, P as LogicalToolCallCorrelation, R as BrowserCommandId, S as BrowserDynamicApproval, U as JsonRpcRequestId, Y as TurnId, _ as BrowserVoiceContext, a as BrowserContextDelivery, b as VoiceNarrative, c as BrowserOperationOutcome, d as BrowserSchemas, f as BrowserSettings, i as BrowserCommandLease, o as BrowserCoordinator, p as BrowserSnapshot, q as RealtimeSessionId, r as BrowserCommand, s as BrowserLogin, t as BrowserAccount, u as BrowserReadiness, v as BrowserWorkhorses, w as BrowserDynamicApprovalResponse, y as DeliveryOutcome, z as ChildEpoch } from "./snapshot-BCrCORmt.mjs";
3
+ import { i as CodexServerNotificationParamsByMethod, r as CodexResponseByMethod } from "./contract-qg6q9-vH.mjs";
4
+ import { f as RealtimeTranscriptRecord, t as AnswerSdp } from "./realtime-contract-wHmSyUIe.mjs";
5
+ import { a as BrowserGatewaySnapshotMessage, i as BrowserGatewayMessage, n as BrowserGatewayCommandResult, t as BrowserGatewayAccountReadResult } from "./gateway-envelope-Ch4BsYcK.mjs";
6
+ import { z } from "zod";
7
+ import fs from "node:fs";
8
+ import { Server } from "node:http";
9
+ import { execFileSync } from "node:child_process";
10
+ type CodexAmbientEnvironment = Readonly<Record<string, string | undefined>>;
11
+ type CodexChildEnvironment = Readonly<Record<string, string>>;
12
+ interface CodexChildEnvironmentInput {
13
+ /** The reviewed ambient environment; the current process environment when absent. */
14
+ readonly ambient?: CodexAmbientEnvironment;
15
+ /** The canonical private CODEX_HOME root. */
16
+ readonly codexHome: string;
17
+ /** The canonical private CODEX_SQLITE_HOME root. */
18
+ readonly sqliteHome: string;
19
+ /** Explicit host additions override retained ambient values, except the protected Codex roots. */
20
+ readonly hostEnvironment?: CodexChildEnvironment | undefined;
21
+ /** Absolute directories that lead the resulting PATH, in the supplied order. */
22
+ readonly pathPrefixes?: readonly string[] | undefined;
23
+ }
24
+ /** Which Codex executable `resolveCodexExecutable` proves. */
25
+ interface CodexExecutableOptions {
26
+ /** An absolute path to prove in place of the installed `@openai/codex` package. */
27
+ readonly executablePath?: string;
28
+ /**
29
+ * Refuse an installed `@openai/codex` outside `<installedIn>/node_modules`, such as a global
30
+ * install or the install of another project. It does not apply to `executablePath`.
31
+ */
32
+ readonly installedIn?: string;
33
+ /**
34
+ * The directory of a host's compiled release: its platform package. The Codex binary
35
+ * lies in the `@openai/codex-<os>-<cpu>` package that npm installed beside it or above it,
36
+ * and it starts without Node.js. It does not apply to `executablePath`.
37
+ */
38
+ readonly releasedIn?: string;
39
+ }
40
+ /**
41
+ * Find the Codex executable and prove it before anything runs it: an absolute, regular,
42
+ * executable file that reports exactly the pinned Codex version. PATH is never consulted.
43
+ * @param options - An explicit path, or where the installed package must be.
44
+ * @returns The absolute path of the proven executable.
45
+ * @throws {CodexExecutableError} When the executable is missing, outside `installedIn`, not
46
+ * executable, or reports another version.
47
+ */
48
+ declare function resolveCodexExecutable(options?: CodexExecutableOptions): string;
49
+ interface CodexProcessGroupIdentity {
50
+ readonly leaderPid: number;
51
+ readonly pgid: number;
52
+ readonly leaderStartTime: string;
53
+ }
54
+ interface CodexStorageInput {
55
+ readonly rootDirectory?: string;
56
+ readonly codexHome?: string;
57
+ readonly sqliteHome?: string;
58
+ /**
59
+ * The private directory one server owns exclusively, which holds the owner lock. Several
60
+ * servers may share one CODEX_HOME, since Codex takes several processes on one home; each
61
+ * names its own owner directory. The Codex home is the owner when none is named.
62
+ */
63
+ readonly ownerDirectory?: string;
64
+ }
65
+ type CodexProcessStorageInput = (CodexStorageInput & {
66
+ readonly rootDirectory: string;
67
+ }) | (CodexStorageInput & {
68
+ readonly rootDirectory?: never;
69
+ readonly codexHome: string;
70
+ readonly sqliteHome: string;
71
+ });
72
+ interface CodexProcessOptions extends Pick<CodexChildEnvironmentInput, "hostEnvironment" | "pathPrefixes"> {
73
+ readonly executablePath: string;
74
+ /** The directory the app-server child runs in: the coordinator's own, which is no checkout. */
75
+ readonly workingDirectory: string;
76
+ readonly storage: CodexProcessStorageInput;
77
+ /** Publish each exact group identity to an outer cleanup owner before readiness. */
78
+ readonly onGroupOwned?: (identity: CodexProcessGroupIdentity) => void;
79
+ /** Secrets supplied by a caller are redacted before process diagnostics are retained. */
80
+ readonly diagnosticSecrets?: readonly string[];
81
+ }
82
+ /** The schemas that project and parse the browser state. */
83
+ type BrowserProjectionModel = Pick<BrowserSchemas, "BrowserSnapshotSchema" | "BrowserSpokenApprovalSchema">;
84
+ interface CodexAccountProjectionInput {
85
+ readonly kind: "codex_account_response";
86
+ readonly response: CodexResponseByMethod["account/read"];
87
+ }
88
+ type BrowserAccountProjectionInput = CodexAccountProjectionInput | Extract<BrowserAccount, {
89
+ readonly state: "unknown" | "signed_out" | "login_pending" | "failed";
90
+ }>;
91
+ type CodexThreadSettings = CodexServerNotificationParamsByMethod["thread/settings/updated"]["threadSettings"];
92
+ interface CodexSettingsProjectionInput {
93
+ readonly kind: "codex_thread_settings";
94
+ readonly owner: BrowserSettings["owner"];
95
+ readonly settings: Pick<CodexThreadSettings, "model" | "effort" | "serviceTier" | "approvalPolicy" | "approvalsReviewer" | "sandboxPolicy" | "activePermissionProfile">;
96
+ }
97
+ /**
98
+ * One authoritative queued submission, with the operation that queued
99
+ * it when this workbench queued it.
100
+ *
101
+ * The queue port sets a submission's `clientUserMessageId` to the serialized
102
+ * OperationId on every add it makes, so the composition root can recover the
103
+ * operation from the authoritative list and hand it over here. A null operation
104
+ * is a submission this workbench did not queue, and this chat has no authority to
105
+ * reorder it.
106
+ */
107
+ interface CodexQueuedSubmissionProjectionInput extends Pick<SessionQueuedSubmission, "id" | "input"> {
108
+ readonly operationId: OperationId | null;
109
+ }
110
+ interface CodexQueueProjectionInput {
111
+ readonly kind: "codex_queue";
112
+ readonly submissions: readonly CodexQueuedSubmissionProjectionInput[] | null;
113
+ }
114
+ type SessionItem<Type extends SessionThreadItem["type"]> = Extract<SessionThreadItem, {
115
+ readonly type: Type;
116
+ }>;
117
+ type TimelineSessionItem<Type extends SessionThreadItem["type"], Field extends keyof SessionItem<Type>> = DeepReadonly<Pick<SessionItem<Type>, Field>> & Readonly<Record<string, unknown>>;
118
+ interface CodexTimelineUserMessageProjectionInput extends Readonly<Record<string, unknown>> {
119
+ readonly kind: "user_message";
120
+ readonly item: TimelineSessionItem<"userMessage", "type" | "id">;
121
+ /** What the person said, bounded, with each non-text input named in brackets. */
122
+ readonly text: string;
123
+ }
124
+ interface CodexTimelineAgentMessageProjectionInput extends Readonly<Record<string, unknown>> {
125
+ readonly kind: "agent_message";
126
+ readonly item: TimelineSessionItem<"agentMessage", "type" | "id" | "text">;
127
+ }
128
+ interface CodexTimelineToolProjectionInput extends Readonly<Record<string, unknown>> {
129
+ readonly kind: "tool_call";
130
+ readonly item: TimelineSessionItem<"mcpToolCall" | "dynamicToolCall", "type" | "id" | "tool" | "status" | "durationMs">;
131
+ /** The MCP server, or the dynamic tool's namespace. */
132
+ readonly server: string | null;
133
+ /** The call's arguments as bounded compact JSON. */
134
+ readonly arguments: string | null;
135
+ /** Why the call failed, when it reported a failure. */
136
+ readonly error: string | null;
137
+ }
138
+ interface CodexTimelineCommandProjectionInput extends Readonly<Record<string, unknown>> {
139
+ readonly kind: "command_execution";
140
+ readonly item: TimelineSessionItem<"commandExecution", "type" | "id" | "command" | "status" | "exitCode" | "durationMs">;
141
+ /** The working directory, bounded; null when Codex reported none. */
142
+ readonly cwd: string | null;
143
+ /** The bounded tail of the aggregated output, and whether anything before it was cut. */
144
+ readonly output: {
145
+ readonly tail: string | null;
146
+ readonly truncated: boolean;
147
+ };
148
+ }
149
+ type CodexPatchChangeKind = SessionItem<"fileChange">["changes"][number]["kind"]["type"];
150
+ /** One changed file, its diff reduced to line counts. */
151
+ interface CodexTimelineFileChangeEntry extends Readonly<Record<string, unknown>> {
152
+ readonly path: string;
153
+ readonly kind: CodexPatchChangeKind;
154
+ readonly movePath: string | null;
155
+ readonly added: number;
156
+ readonly removed: number;
157
+ }
158
+ interface CodexTimelineFileChangeProjectionInput extends Readonly<Record<string, unknown>> {
159
+ readonly kind: "file_change";
160
+ readonly item: TimelineSessionItem<"fileChange", "type" | "id" | "status">;
161
+ readonly changes: readonly CodexTimelineFileChangeEntry[];
162
+ readonly changesTruncated: boolean;
163
+ }
164
+ interface CodexTimelineWebSearchProjectionInput extends Readonly<Record<string, unknown>> {
165
+ readonly kind: "web_search";
166
+ readonly item: TimelineSessionItem<"webSearch", "type" | "id">;
167
+ /** The bounded query, or null while Codex has not said what it searched for. */
168
+ readonly query: string | null;
169
+ }
170
+ interface CodexTimelineCompactionProjectionInput extends Readonly<Record<string, unknown>> {
171
+ readonly kind: "context_compaction";
172
+ readonly item: TimelineSessionItem<"contextCompaction", "type" | "id">;
173
+ }
174
+ interface CodexTimelineReasoningProjectionInput extends Readonly<Record<string, unknown>> {
175
+ readonly kind: "reasoning_summary";
176
+ readonly item: TimelineSessionItem<"reasoning", "type" | "id">;
177
+ /** The future owner chooses the bounded reasoning presentation from generated arrays. */
178
+ readonly text: string;
179
+ }
180
+ interface CodexTimelinePlanProjectionInput extends Readonly<Record<string, unknown>> {
181
+ readonly kind: "plan";
182
+ readonly item: TimelineSessionItem<"plan", "type" | "id" | "text">;
183
+ }
184
+ type TimelineApprovalIdentity = DeepReadonly<Omit<ItemApprovalIdentity, "approvalId"> & {
185
+ readonly approvalId: NonNullable<ItemApprovalIdentity["approvalId"]>;
186
+ }> & Readonly<Record<string, unknown>>;
187
+ interface CodexTimelineApprovalProjectionInput extends Readonly<Record<string, unknown>> {
188
+ readonly kind: "approval_request";
189
+ readonly identity: TimelineApprovalIdentity;
190
+ readonly state: Extract<ApprovalState, "pending" | "settled" | "cancelled">;
191
+ }
192
+ /** Independent readonly owner presentation; the sole adapter chooses browser media arms. */
193
+ type CodexTimelineItemProjectionInput = CodexTimelineUserMessageProjectionInput | CodexTimelineAgentMessageProjectionInput | CodexTimelineToolProjectionInput | CodexTimelineCommandProjectionInput | CodexTimelineFileChangeProjectionInput | CodexTimelineReasoningProjectionInput | CodexTimelinePlanProjectionInput | CodexTimelineWebSearchProjectionInput | CodexTimelineCompactionProjectionInput | CodexTimelineApprovalProjectionInput;
194
+ interface CodexTimelineTurnPresentation extends Readonly<Record<string, unknown>> {
195
+ readonly summary: string;
196
+ readonly outputs: Readonly<{
197
+ included: boolean;
198
+ truncated: boolean;
199
+ }>;
200
+ }
201
+ type CodexTurnPlanUpdate = CodexServerNotificationParamsByMethod["turn/plan/updated"];
202
+ /** The latest plan Codex published for one turn, bounded by the owner that holds it. */
203
+ type CodexTimelinePlanInput = DeepReadonly<Pick<CodexTurnPlanUpdate, "explanation" | "plan">> & Readonly<Record<string, unknown>>;
204
+ /** Why a turn failed, bounded. */
205
+ interface CodexTimelineTurnErrorInput extends Readonly<Record<string, unknown>> {
206
+ readonly message: string;
207
+ readonly details: string | null;
208
+ }
209
+ interface CodexTimelineTurnProjectionInput extends Readonly<Record<string, unknown>> {
210
+ /** Codex's own turn fields; `startedAt` and `completedAt` are Unix seconds. */
211
+ readonly turn: DeepReadonly<Pick<SessionTurn, "id" | "status" | "startedAt" | "completedAt" | "durationMs">> & Readonly<Record<string, unknown>>;
212
+ readonly items: readonly CodexTimelineItemProjectionInput[];
213
+ readonly presentation: CodexTimelineTurnPresentation;
214
+ readonly error: CodexTimelineTurnErrorInput | null;
215
+ readonly plan: CodexTimelinePlanInput | null;
216
+ }
217
+ /** The thread's latest token usage, as Codex last reported it. */
218
+ type CodexTimelineUsageInput = DeepReadonly<CodexServerNotificationParamsByMethod["thread/tokenUsage/updated"]["tokenUsage"]> & Readonly<Record<string, unknown>>;
219
+ /** Readonly owner view of the timeline. */
220
+ interface CodexTimelineProjectionInput extends Readonly<Record<string, unknown>> {
221
+ readonly kind: "codex_timeline";
222
+ readonly threadId: ThreadId;
223
+ readonly turns: readonly CodexTimelineTurnProjectionInput[];
224
+ readonly cursor: SessionResponsePayloads["thread/timeline/list"]["nextCursor"];
225
+ readonly usage: CodexTimelineUsageInput | null;
226
+ }
227
+ interface CodexContextDeliveryProjectionInput {
228
+ readonly kind: "codex_context_delivery";
229
+ readonly outcome: {
230
+ readonly targetThreadId: BrowserContextDelivery["threadId"] | null;
231
+ readonly outcome: BrowserContextDelivery["delivery"];
232
+ readonly reason: string | null;
233
+ } | null;
234
+ readonly freshness: {
235
+ readonly capturedAtMs: number;
236
+ readonly freshUntilMs: number;
237
+ } | null;
238
+ }
239
+ interface CodexCoordinatorProjectionInput {
240
+ readonly kind: "codex_coordinator";
241
+ readonly state: BrowserCoordinator["state"] | "inspect_only";
242
+ readonly threadId: BrowserCoordinator["threadId"];
243
+ readonly configured: {
244
+ readonly model: string;
245
+ readonly effort: string | null;
246
+ } | null;
247
+ readonly effective: {
248
+ readonly model: string;
249
+ readonly effort: string | null;
250
+ readonly serviceTier: string | null;
251
+ } | null;
252
+ readonly reason: string | null;
253
+ }
254
+ interface CodexVoiceProjectionInput {
255
+ readonly kind: "codex_voice";
256
+ readonly mediaReady: boolean;
257
+ readonly generation: {
258
+ readonly browserSessionId: string;
259
+ } | null;
260
+ /** Whether nobody listens live to the session. */
261
+ readonly unattended: boolean;
262
+ readonly coordinatorState: CodexCoordinatorProjectionInput["state"];
263
+ readonly transcript: readonly Pick<RealtimeTranscriptRecord, "itemId" | "sequence" | "role" | "text" | "status">[];
264
+ }
265
+ interface BrowserProjectionInput {
266
+ readonly readiness: BrowserReadiness;
267
+ readonly account: BrowserAccountProjectionInput;
268
+ readonly login: BrowserLogin;
269
+ readonly threadLink: ThreadLinkSnapshot;
270
+ readonly timeline: CodexTimelineProjectionInput | null;
271
+ /** The voice coordinator's own turns, read the way the timeline is. */
272
+ readonly coordinatorTimeline?: CodexTimelineProjectionInput | null;
273
+ /** Which coordinator turn delegated each workhorse turn the server has been told of. */
274
+ readonly delegations?: ReadonlyMap<TurnId, TurnId>;
275
+ readonly queue: CodexQueueProjectionInput;
276
+ readonly settings: readonly CodexSettingsProjectionInput[];
277
+ readonly approvals: readonly ApprovalOwnerView[];
278
+ readonly dynamicApprovals: readonly BrowserDynamicApproval[];
279
+ readonly contextDelivery: CodexContextDeliveryProjectionInput;
280
+ readonly coordinator: CodexCoordinatorProjectionInput;
281
+ readonly voice: CodexVoiceProjectionInput;
282
+ readonly spokenApproval: SpokenApprovalSnapshot;
283
+ readonly voiceContext?: BrowserVoiceContext | null;
284
+ /** The tab session's workhorses and the one whose conversation it shows. */
285
+ readonly workhorses?: BrowserWorkhorses;
286
+ readonly lease: BrowserCommandLease | null;
287
+ readonly operation: BrowserOperationOutcome | null;
288
+ }
289
+ type BrowserProjectionResult = {
290
+ readonly tag: "projected";
291
+ readonly snapshot: BrowserSnapshot;
292
+ } | {
293
+ readonly tag: "refused";
294
+ readonly reason: "secret_input" | "invalid_projection";
295
+ readonly message: string;
296
+ };
297
+ /**
298
+ * The tab session a browser tab names on every chat socket: minted by the tab, kept
299
+ * in its sessionStorage, shared by every chat of the tab. Opaque to the server beyond its bounds.
300
+ */
301
+ declare const TabSessionIdSchema: z.core.$ZodBranded<z.ZodString, "TabSessionId", "out">;
302
+ type TabSessionId = z.infer<typeof TabSessionIdSchema>;
303
+ /**
304
+ * The tab session a socket named, when it named one the server accepts.
305
+ * @param value The `tabSession` query parameter as it arrived.
306
+ * @returns The id, or null when it is missing or out of bounds.
307
+ */
308
+ export declare function parseTabSessionId(value: unknown): TabSessionId | null;
309
+ /**
310
+ * The tab session and checkout a workhorse's link key names.
311
+ * @param key The key, as `workhorseLinkKey` made it.
312
+ * @returns Both, or null when the key is not a workhorse's.
313
+ */
314
+ export declare function parseWorkhorseLinkKey(key: string): {
315
+ readonly tabSessionId: TabSessionId;
316
+ readonly checkout: string;
317
+ } | null;
318
+ type BrowserConnectionId = string;
319
+ /** Exact process-local WebSocket ownership. Reusable browser ids never substitute for it. */
320
+ type BrowserConnectionInstance = object;
321
+ type BrowserUnsubscribe = () => void;
322
+ interface BrowserLeaseRecord {
323
+ readonly lease: BrowserCommandLease;
324
+ readonly binding: BrowserLeaseBinding;
325
+ readonly capturedLink: ThreadLinkBindingSnapshot;
326
+ }
327
+ /** One tab session's lease: the active record and the bounded history of ended ones. */
328
+ interface BrowserSessionLeaseLedger {
329
+ active: BrowserLeaseRecord | null;
330
+ readonly retired: Map<BrowserCommandId, BrowserLeaseRecord>;
331
+ }
332
+ /**
333
+ * Process-lifetime lease authority retained while a source generation is replaced: one lease
334
+ * per browser tab session, so two tabs never take the lease from each other.
335
+ */
336
+ interface BrowserLeaseLedger {
337
+ readonly sessions: Map<TabSessionId, BrowserSessionLeaseLedger>;
338
+ }
339
+ type BrowserThreadLinkCreateCommand = Extract<BrowserCommand, {
340
+ readonly command: "threadLinkCreate";
341
+ }>;
342
+ type BrowserRealtimeStartCommand = Extract<BrowserCommand, {
343
+ readonly command: "realtimeStart";
344
+ }>;
345
+ type BrowserRealtimeAppendTextCommand = Extract<BrowserCommand, {
346
+ readonly command: "realtimeAppendText";
347
+ }>;
348
+ type BrowserRealtimeStopCommand = Extract<BrowserCommand, {
349
+ readonly command: "realtimeStop";
350
+ }>;
351
+ interface BrowserLeaseBinding {
352
+ readonly browserId: BrowserConnectionId;
353
+ readonly connection: BrowserConnectionInstance;
354
+ readonly chatId: string;
355
+ /** The tab the socket belongs to, which every chat of that tab shares. */
356
+ readonly tabSessionId: TabSessionId;
357
+ /** The checkout the chat's tab shows, whose workhorse the command is for. */
358
+ readonly checkout: string;
359
+ readonly commandId: BrowserCommandId;
360
+ readonly childId: ChildId;
361
+ readonly epoch: ChildEpoch;
362
+ readonly link: ThreadLinkSnapshot;
363
+ readonly linkRevision: number;
364
+ }
365
+ interface BrowserActionContext extends BrowserLeaseBinding {}
366
+ type BrowserDisconnectReason = "browser_disconnected" | "child_disconnected" | "gateway_shutdown";
367
+ /**
368
+ * Browser-only server settlement. Typed Codex request and result values end at
369
+ * their session owner; the gateway never mirrors them into a second result.
370
+ */
371
+ type BrowserActionResult = void | {
372
+ readonly outcome: DeliveryOutcome;
373
+ readonly message?: string;
374
+ readonly turnId?: TurnId;
375
+ /** The browser applies this answer to its local peer and owns remote media attachment. */
376
+ readonly realtimeAnswer?: AnswerSdp;
377
+ /** Stable opaque handle returned by start and echoed by append/stop. */
378
+ readonly realtimeSessionHandle?: string;
379
+ };
380
+ interface BrowserThreadLinkActions {
381
+ readonly create: (command: BrowserThreadLinkCreateCommand, context: BrowserActionContext) => Promise<BrowserActionResult>;
382
+ }
383
+ interface BrowserRealtimeActions {
384
+ readonly start: (command: BrowserRealtimeStartCommand, context: BrowserActionContext) => Promise<BrowserActionResult>;
385
+ readonly appendText: (command: BrowserRealtimeAppendTextCommand, context: BrowserActionContext) => Promise<BrowserActionResult>;
386
+ readonly stop: (command: BrowserRealtimeStopCommand, context: BrowserActionContext) => Promise<BrowserActionResult>;
387
+ readonly onBrowserDisconnect?: (context: BrowserActionContext, reason: BrowserDisconnectReason) => Promise<void> | void;
388
+ }
389
+ interface BrowserDynamicApprovalActions {
390
+ readonly resolve: (command: BrowserDynamicApprovalResponse, context: BrowserActionContext) => Promise<BrowserActionResult>;
391
+ readonly onChange?: (listener: () => void) => BrowserUnsubscribe;
392
+ }
393
+ /** The exact browser payload whose transport send completed successfully. */
394
+ type BrowserPublishedPayload = BrowserGatewayMessage | BrowserSnapshot;
395
+ interface BrowserWorkbenchConnection {
396
+ readonly browserId: BrowserConnectionId;
397
+ readonly chatId: string;
398
+ readonly tabSessionId: TabSessionId;
399
+ readonly instance: BrowserConnectionInstance;
400
+ readonly snapshot: () => BrowserGatewaySnapshotMessage;
401
+ /** Re-read cached owner state, so the next `snapshot()` is a genuine read. */
402
+ readonly refreshProjection: () => Promise<void>;
403
+ /** Confirm this exact event or snapshot result only after its transport send succeeds. */
404
+ readonly confirmPublished: (payload: BrowserPublishedPayload) => void;
405
+ readonly claimLease: () => BrowserCommandLease;
406
+ readonly renewLease: () => BrowserCommandLease;
407
+ readonly releaseLease: () => BrowserCommandLease | null;
408
+ readonly setMediaReady: (ready: boolean) => BrowserGatewaySnapshotMessage;
409
+ readonly accountRead: () => Promise<BrowserGatewayAccountReadResult>;
410
+ readonly command: (command: unknown) => Promise<BrowserGatewayCommandResult>;
411
+ readonly subscribe: (listener: (message: BrowserGatewayMessage) => void) => BrowserUnsubscribe;
412
+ readonly close: () => Promise<void>;
413
+ }
414
+ interface CodexWorkbenchGateway {
415
+ readonly connect: (browserId: BrowserConnectionId, chatId: string, tabSessionId: TabSessionId, instance?: BrowserConnectionInstance) => BrowserWorkbenchConnection;
416
+ readonly snapshot: (browserId: BrowserConnectionId, chatId: string) => BrowserGatewaySnapshotMessage;
417
+ readonly claimLease: (browserId: BrowserConnectionId, chatId: string) => BrowserCommandLease;
418
+ readonly renewLease: (browserId: BrowserConnectionId, lease: Pick<BrowserCommandLease, "commandId" | "chatId" | "childId" | "epoch">) => BrowserCommandLease;
419
+ readonly releaseLease: (browserId: BrowserConnectionId, chatId: string, commandId?: BrowserCommandId) => BrowserCommandLease | null;
420
+ readonly accountRead: (browserId: BrowserConnectionId, chatId: string) => Promise<BrowserGatewayAccountReadResult>;
421
+ readonly command: (browserId: BrowserConnectionId, command: unknown) => Promise<BrowserGatewayCommandResult>;
422
+ readonly subscribe: (browserId: BrowserConnectionId, chatId: string, listener: (message: BrowserGatewayMessage) => void) => BrowserUnsubscribe;
423
+ readonly closeConnection: (browserId: BrowserConnectionId, chatId: string, instance: BrowserConnectionInstance) => Promise<void>;
424
+ readonly childExit: (childId: ChildId, epoch: ChildEpoch) => Promise<void>;
425
+ /** Forget a tab session that ended: its lease and everything kept about it. */
426
+ readonly endSession: (tabSessionId: TabSessionId) => void;
427
+ readonly dispose: () => Promise<void>;
428
+ }
429
+ /**
430
+ * Build one developer item from immutable host context without starting a turn.
431
+ * @param input The captured input and its operation identity.
432
+ * @param input.threadId The threadId value.
433
+ * @param input.context The context value.
434
+ * @param codec The host application key and wire encoder.
435
+ * @returns The immutable developer-item parameters.
436
+ */
437
+ declare function createWorkbenchThreadInjectItemsParams(input: {
438
+ readonly threadId: string;
439
+ readonly context: WorkbenchExecutionContext;
440
+ }, codec: WorkbenchContextCodec): {
441
+ threadId: string;
442
+ items: {
443
+ type: "message";
444
+ role: "developer";
445
+ content: {
446
+ type: "input_text";
447
+ text: string;
448
+ }[];
449
+ }[];
450
+ };
451
+ type ThreadInjectItemsParams = ReturnType<typeof createWorkbenchThreadInjectItemsParams>;
452
+ /** A durable target captured by the workbench; this port never selects a thread. */
453
+ type CodexThreadContextTarget = ThreadLinkTarget & {
454
+ readonly childId: ChildId;
455
+ readonly epoch: ChildEpoch;
456
+ readonly operationId: string;
457
+ };
458
+ type CodexThreadContextEventId = Readonly<{
459
+ readonly feedId: string;
460
+ readonly sequence: number;
461
+ }>;
462
+ /**
463
+ * One announced change as one workhorse is told it: the host's words and data, and the
464
+ * identities the agent read when the change was announced. The host supplies no identity.
465
+ */
466
+ interface WorkhorseContextEvent {
467
+ readonly feedId: string;
468
+ readonly sequence: number;
469
+ /** The thread that made the change, or null when nobody said. */
470
+ readonly author: string | null;
471
+ readonly capturedAtMs: number;
472
+ readonly freshUntilMs: number;
473
+ /** The words, or null when the host withheld them. */
474
+ readonly text: string | null;
475
+ /** Why the host withheld the words, or null. */
476
+ readonly withheld: string | null;
477
+ /** The host's own data, which the context codec encodes beside the execution facts. */
478
+ readonly payload: Readonly<Record<string, unknown>>;
479
+ readonly threadLink: WorkbenchExecutionContext["threadLink"];
480
+ readonly child: {
481
+ readonly id: ChildId | null;
482
+ readonly epoch: ChildEpoch | null;
483
+ };
484
+ readonly workhorse: {
485
+ readonly threadId: ThreadId | null;
486
+ };
487
+ readonly coordinator: {
488
+ readonly threadId: ThreadId | null;
489
+ readonly realtimeSessionId: RealtimeSessionId | null;
490
+ };
491
+ }
492
+ /** Stable reasons retained when a context change is refused or its response is lost. */
493
+ type CodexThreadContextDeliveryReason = ThreadLinkReasonCode | "child_exit" | "disposed" | "invalid_context" | "invalid_event" | "own_change" | "link_changed" | "response_lost" | "session_rejected" | "stale_cursor" | "stale_event" | "thread_revalidation_failed" | "unbound" |
494
+ /** The host told this workhorse nothing of the change. */
495
+ "withheld";
496
+ type CodexThreadContextDeliveryState = "delivered" | "not_delivered" | "outcome_unknown";
497
+ interface CodexThreadContextDeliveryOutcomeBase {
498
+ readonly kind: "thread_context_delivery";
499
+ readonly event: CodexThreadContextEventId;
500
+ readonly attempted: boolean;
501
+ readonly outcome: CodexThreadContextDeliveryState;
502
+ readonly reason: CodexThreadContextDeliveryReason | null;
503
+ /** The window in which the change was fresh. */
504
+ readonly freshness: {
505
+ readonly capturedAtMs: number;
506
+ readonly freshUntilMs: number;
507
+ };
508
+ /** The exact canonical body, when the body was built before refusal or attempt. */
509
+ readonly payload: ThreadInjectItemsParams | null;
510
+ }
511
+ /** The immutable record for one change identity. */
512
+ type CodexThreadContextDeliveryOutcome = (CodexThreadContextDeliveryOutcomeBase & {
513
+ readonly linkKey: string;
514
+ readonly targetThreadId: ThreadId;
515
+ readonly targetChildId: ChildId;
516
+ readonly targetEpoch: ChildEpoch;
517
+ readonly targetOperationId: string;
518
+ }) | (CodexThreadContextDeliveryOutcomeBase & {
519
+ readonly linkKey: null;
520
+ readonly targetThreadId: null;
521
+ readonly targetChildId: null;
522
+ readonly targetEpoch: null;
523
+ readonly targetOperationId: null;
524
+ readonly attempted: false;
525
+ readonly outcome: "not_delivered";
526
+ readonly reason: "unbound" | "disposed";
527
+ readonly payload: null;
528
+ });
529
+ interface CodexThreadContextDelivery {
530
+ /** Deliver a change once: the same change again answers with its first outcome. */
531
+ readonly deliver: (event: WorkhorseContextEvent) => Promise<CodexThreadContextDeliveryOutcome>;
532
+ /** Settled outcomes in first-seen order. */
533
+ readonly inspect: () => readonly CodexThreadContextDeliveryOutcome[];
534
+ readonly get: (event: CodexThreadContextEventId) => CodexThreadContextDeliveryOutcome | undefined;
535
+ readonly dispose: () => void;
536
+ }
537
+ interface CodexThreadContextBinding {
538
+ readonly linkKey: string;
539
+ readonly target: CodexThreadContextTarget;
540
+ /** Exact link CAS evidence captured by the target-selection action. */
541
+ readonly link: ThreadLinkBindingSnapshot;
542
+ }
543
+ interface CodexThreadContextBindingToken {
544
+ readonly revision: number;
545
+ }
546
+ interface CodexThreadContextBindingSnapshot {
547
+ readonly token: CodexThreadContextBindingToken;
548
+ readonly binding: CodexThreadContextBinding | null;
549
+ }
550
+ interface CodexThreadContextBindingTransition {
551
+ readonly expected: CodexThreadContextBindingToken;
552
+ readonly next: CodexThreadContextBinding | null;
553
+ }
554
+ /** One process-lifetime subscription and event ledger over replaceable exact bindings. */
555
+ interface CodexThreadContextController extends CodexThreadContextDelivery {
556
+ readonly snapshot: () => CodexThreadContextBindingSnapshot;
557
+ readonly compareAndSwap: (transition: CodexThreadContextBindingTransition) => CodexThreadContextBindingSnapshot;
558
+ /** Null execution first, then clear the matching epoch and dispose the owner. */
559
+ readonly childExit: (child: ChildId, epoch: ChildEpoch) => Promise<void>;
560
+ }
561
+ /** Who can be told a context change: a checkout's workhorse, the coordinator, or the live voice. */
562
+ type ContextAudience = "workhorse" | "coordinator" | "voice";
563
+ /**
564
+ * What one audience is told: the words, or why the host tells it nothing this time. A withheld
565
+ * audience is told nothing, and its receipt says `withheld`.
566
+ */
567
+ type ContextWords<Extra extends object = object> = (Extra & {
568
+ readonly text: string;
569
+ }) | {
570
+ readonly withheld: string;
571
+ };
572
+ /**
573
+ * One change a host announces. Name at least one audience. A workhorse hears one `feed` and
574
+ * `sequence` at most once. The coordinator and the voice keep no such promise: they answer a repeat
575
+ * with its first receipt only while it is among the tab's last 64 deliveries.
576
+ */
577
+ interface ContextChange {
578
+ /** The stream the change belongs to. */
579
+ readonly feed: string;
580
+ /**
581
+ * The change's place in its feed, a whole number from 0. A workhorse refuses a sequence that
582
+ * does not pass the last one of the same feed it was given, as `stale_cursor`.
583
+ */
584
+ readonly sequence: number;
585
+ /** The tab sessions the change is for. Default: every live one. */
586
+ readonly tabSessions?: readonly TabSessionId[];
587
+ /**
588
+ * The Codex thread that made the change, or null. Nobody is told their own change, and the
589
+ * receipt says `own_change`: a workhorse is not told a change that it or its tab's coordinator
590
+ * made, and the coordinator and the voice are not told one that any thread of their tab made.
591
+ */
592
+ readonly author?: string | null;
593
+ /**
594
+ * When the change happened, in milliseconds since the epoch, never later than now. Default: now.
595
+ * The change is fresh for a fixed window from then, and a workhorse is not told a change that
596
+ * went stale.
597
+ */
598
+ readonly capturedAtMs?: number;
599
+ /**
600
+ * What the change is about. While a change for the coordinator or the voice waits in its tab's
601
+ * queue, a later change of the same feed and topic replaces it. Without a topic, nothing
602
+ * replaces it.
603
+ */
604
+ readonly topic?: string;
605
+ /**
606
+ * The workhorses of these checkouts, told as a developer message that starts no turn, also while
607
+ * a turn runs. `payload` is your own JSON data: the context codec encodes it with the execution facts,
608
+ * and it cannot use their keys.
609
+ */
610
+ readonly workhorse?: {
611
+ readonly checkouts: readonly string[];
612
+ } & ContextWords<{
613
+ readonly payload?: Readonly<Record<string, unknown>>;
614
+ }>;
615
+ /** The coordinator, told as a developer message that starts no turn, only while voice is live. */
616
+ readonly coordinator?: ContextWords;
617
+ /**
618
+ * The live voice, told as quiet context, or as speech it answers once the audio in progress ends.
619
+ * Only while voice is live.
620
+ */
621
+ readonly voice?: ContextWords<{
622
+ readonly speech?: boolean;
623
+ }>;
624
+ }
625
+ /** Why an audience was not told a change, or why the outcome of telling it is unknown. */
626
+ type ContextReceiptReason = CodexThreadContextDeliveryReason | CoordinatorCallbackDeliveryReason |
627
+ /** The tab session has no workhorse in that checkout. */
628
+ "no_workhorse" |
629
+ /** No live tab session has that id. */
630
+ "no_tab_session";
631
+ /**
632
+ * What one audience of one tab session made of a change. `outcome_unknown` means the message may
633
+ * have arrived: the agent never sends it again.
634
+ */
635
+ interface ContextReceipt {
636
+ readonly tabSessionId: TabSessionId;
637
+ readonly audience: ContextAudience;
638
+ /** The workhorse's checkout; null for the coordinator and the voice. */
639
+ readonly checkout: string | null;
640
+ readonly outcome: "delivered" | "not_delivered" | "outcome_unknown";
641
+ readonly reason: ContextReceiptReason | null;
642
+ }
643
+ interface ServerCodexBrowserSocketSend {
644
+ readonly send: (message: unknown) => Promise<void>;
645
+ }
646
+ interface ServerCodexBrowserWebSocket {
647
+ readonly readyState: number;
648
+ /** A successful write passes no error: Bun 1.4.3's `ws` passes `undefined`, Bun 1.4.4's passes `null`. */
649
+ readonly send: (data: string, callback: (error?: Error | null) => void) => void;
650
+ }
651
+ /**
652
+ * Adapt the production callback-based WebSocket into an awaitable send
653
+ * boundary.
654
+ * @param socket The socket.
655
+ * @returns The send boundary.
656
+ */
657
+ declare function createServerCodexBrowserSocketSend(socket: ServerCodexBrowserWebSocket): ServerCodexBrowserSocketSend;
658
+ interface ServerCodexBrowserSocketOwnerOptions {
659
+ readonly gateway: CodexWorkbenchGateway;
660
+ /** Resolve the chat from server-owned socket registration, never request bytes. */
661
+ readonly chatForBrowser: (browserId: string) => string | null;
662
+ /** The tab session the browser's socket named when it connected, never request bytes. */
663
+ readonly tabSessionForBrowser: (browserId: string) => TabSessionId | null;
664
+ /** Open the conversation of a tab whose chat connects, once; a later chat finds it open. */
665
+ readonly openTabSession: (tabSessionId: TabSessionId) => void;
666
+ }
667
+ interface ServerCodexBrowserSocketOwner {
668
+ /**
669
+ * Establish replacement ownership at socket acceptance, before the retired
670
+ * instance can deliver its close event. A first-time chat may still defer
671
+ * connection until it has registered its chat id.
672
+ */
673
+ readonly accept: (instance: BrowserConnectionInstance, browserId: string) => void;
674
+ readonly handle: (instance: BrowserConnectionInstance, browserId: string, input: unknown, transport: ServerCodexBrowserSocketSend) => Promise<void>;
675
+ readonly close: (instance: BrowserConnectionInstance, browserId: string) => Promise<void>;
676
+ /** Wait for every event publication and close already owned by this generation. */
677
+ readonly drain: () => Promise<void>;
678
+ readonly dispose: () => void;
679
+ }
680
+ /**
681
+ * Own the public server WebSocket bridge for one installed gateway generation.
682
+ * @param options The gateway, and how a browser's chat is resolved.
683
+ * @returns The owner.
684
+ */
685
+ declare function createServerCodexBrowserSocketOwner(options: ServerCodexBrowserSocketOwnerOptions): ServerCodexBrowserSocketOwner;
686
+ /** Host-owned approvals that the workbench presents and answers. */
687
+ interface WorkbenchDomainApprovals {
688
+ readonly browser: BrowserDynamicApprovalActions;
689
+ readonly pending: (tabSessionId: TabSessionId) => readonly BrowserDynamicApproval[];
690
+ readonly bindLease: (tabSessionId: TabSessionId, chatId: string, commandId: BrowserCommandId) => void;
691
+ }
692
+ type WorkhorseStartResponse = SessionResponse<"thread/start">;
693
+ type WorkhorseApprovalPolicy = WorkhorseStartResponse["approvalPolicy"];
694
+ type WorkhorseApprovalsReviewer = WorkhorseStartResponse["approvalsReviewer"];
695
+ type WorkhorseSandboxPolicy = WorkhorseStartResponse["sandbox"];
696
+ type WorkhorsePermissionProfile = WorkhorseStartResponse["activePermissionProfile"];
697
+ interface WorkhorseStartInput {
698
+ readonly linkKey: string;
699
+ /** The caller's last link-binding CAS; null is valid only for an unbound link. */
700
+ readonly expected: ThreadLinkCasToken | null;
701
+ }
702
+ type WorkhorseLifecycleState = "unbound" | "starting" | "ready" | "inspect_only" | "failed";
703
+ type WorkhorseSettlementOutcome = "pending" | "delivered" | "not_delivered" | "outcome_unknown";
704
+ /** The reviewed values returned by thread/start and retained as server evidence. */
705
+ interface WorkhorseStartFacts {
706
+ readonly threadId: ThreadId;
707
+ readonly cwd: string;
708
+ readonly runtimeWorkspaceRoots: readonly string[];
709
+ readonly historyMode: "paginated";
710
+ readonly source: typeof CODEX_SESSION_THREAD_SOURCE;
711
+ readonly threadSource: string;
712
+ readonly model: string;
713
+ readonly modelProvider: string;
714
+ readonly serviceTier: string | null;
715
+ readonly approvalPolicy: WorkhorseApprovalPolicy;
716
+ readonly approvalsReviewer: WorkhorseApprovalsReviewer;
717
+ readonly sandbox: WorkhorseSandboxPolicy;
718
+ readonly activePermissionProfile: WorkhorsePermissionProfile;
719
+ readonly instructionHash: string;
720
+ readonly manifestHash: string;
721
+ }
722
+ interface WorkhorseCleanupFacts {
723
+ readonly operationId: OperationId;
724
+ readonly threadId: ThreadId;
725
+ readonly outcome: Exclude<WorkhorseSettlementOutcome, "pending">;
726
+ readonly reason: string | null;
727
+ }
728
+ interface WorkhorseSnapshot {
729
+ readonly kind: "codex_workhorse";
730
+ readonly state: WorkhorseLifecycleState;
731
+ readonly linkKey: string | null;
732
+ readonly childId: ChildId | null;
733
+ readonly epoch: ChildEpoch | null;
734
+ readonly threadId: ThreadId | null;
735
+ readonly operationId: OperationId | null;
736
+ readonly outcome: WorkhorseSettlementOutcome | null;
737
+ readonly start: WorkhorseStartFacts | null;
738
+ readonly binding: ThreadLinkBindingSnapshot | null;
739
+ readonly cleanup: WorkhorseCleanupFacts | null;
740
+ readonly reason: string | null;
741
+ }
742
+ interface CodexWorkhorseStart {
743
+ readonly start: (input: WorkhorseStartInput) => Promise<WorkhorseSnapshot>;
744
+ readonly snapshot: () => WorkhorseSnapshot;
745
+ }
746
+ /** The runtime owners one workhorse runs on. */
747
+ interface CodexWorkbenchWorkhorseComponents {
748
+ readonly workhorse: CodexWorkhorseStart;
749
+ readonly contextDelivery: CodexThreadContextController;
750
+ readonly queue: CodexWorkhorseQueue<OperationId>;
751
+ readonly operations: CodexWorkhorseOperations;
752
+ }
753
+ /** What starts a workhorse's conversation. */
754
+ interface CodexWorkbenchWorkhorseActions {
755
+ /** New conversation from a chat of the checkout: a fresh thread for this workhorse. */
756
+ readonly threadLinks: BrowserThreadLinkActions;
757
+ /** Start this workhorse's thread when it has none that can run turns, as delegation does. */
758
+ readonly ensureStarted: () => Promise<void>;
759
+ }
760
+ /** What the server remembers about one workhorse between the reads that fill it in. */
761
+ interface CodexWorkbenchWorkhorseState {
762
+ /** The last authoritative queue listing. */
763
+ queue: CodexQueueProjectionInput;
764
+ /** The workhorse thread that listing was read for. */
765
+ queueThreadId: ThreadId | null;
766
+ /** The turn running on the workhorse's thread, as Codex last said, or null while none runs. */
767
+ activeTurn: {
768
+ readonly threadId: ThreadId;
769
+ readonly turnId: TurnId;
770
+ } | null;
771
+ }
772
+ /** One workhorse of a tab session: the one for one checkout. */
773
+ interface CodexWorkbenchWorkhorse {
774
+ /** The directory it works in: a checkout the host admitted. */
775
+ readonly checkout: string;
776
+ /** Its thread-link key, which no other workhorse shares. */
777
+ readonly key: string;
778
+ readonly components: CodexWorkbenchWorkhorseComponents;
779
+ readonly actions: CodexWorkbenchWorkhorseActions;
780
+ readonly state: CodexWorkbenchWorkhorseState;
781
+ }
782
+ /** What one stop did to one workhorse. */
783
+ interface WorkhorseStop {
784
+ readonly checkout: string;
785
+ /** Interrupted names a turn that was running; idle says none was. */
786
+ readonly outcome: "interrupted" | "idle";
787
+ }
788
+ declare const COORDINATOR_TOOLS_OWNER: "codex-coordinator-tools";
789
+ type CoordinatorToolsServerRequest = DynamicServerRequest & {
790
+ readonly owner: typeof COORDINATOR_TOOLS_OWNER;
791
+ };
792
+ type DynamicToolResponse = z.infer<typeof ValidDynamicToolResponseSchema> | z.infer<typeof UnknownDynamicToolResponseSchema>;
793
+ interface CoordinatorToolDispatchResult {
794
+ readonly response: DynamicToolResponse;
795
+ readonly attempted: boolean;
796
+ }
797
+ interface CoordinatorReplayStateSnapshot {
798
+ readonly liveWireCount: number;
799
+ readonly retainedWireCount: number;
800
+ readonly liveLogicalCount: number;
801
+ readonly retainedLogicalCount: number;
802
+ readonly retainedFingerprintBytes: number;
803
+ }
804
+ type CoordinatorToolLifecycleCause = "call_cancelled" | "caller_turn_interrupted" | "server_shutdown" | "browser_disconnect" | "child_disconnect";
805
+ interface CoordinatorToolDispatcher {
806
+ readonly dispatch: (request: CoordinatorToolsServerRequest) => Promise<CoordinatorToolDispatchResult>;
807
+ /** Listener-compatible entry point for the transport's exhaustive request stream. */
808
+ readonly onServerRequest: (request: TransportServerRequest) => void;
809
+ /** Stop a not-yet-attempted call without starting a replacement operation. */
810
+ readonly cancel: (requestId: JsonRpcRequestId, cause: CoordinatorToolLifecycleCause) => void;
811
+ /** Child disconnect prevents any later wire response and any retry. */
812
+ readonly onChildExit: (exit: {
813
+ readonly child: ChildId;
814
+ readonly epoch: ChildEpoch;
815
+ }) => void;
816
+ /** Count-only replay ownership inspection. It never exposes calls, inputs, or responses. */
817
+ readonly replayState: () => CoordinatorReplayStateSnapshot;
818
+ readonly dispose: () => void;
819
+ }
820
+ /**
821
+ * Where one coordinator turn shows: the conversation the tab showed when it started, and
822
+ * the checkouts whose workhorses it gave work to.
823
+ */
824
+ interface CoordinatorTurnHome {
825
+ /** The checkout the tab showed when the turn started, or null when it showed none yet. */
826
+ shownAtStart: string | null;
827
+ /** The checkouts whose workhorses the turn delegated to, steered or queued work for. */
828
+ readonly gaveWorkTo: Set<string>;
829
+ }
830
+ /** One thing that happened during a voice start. */
831
+ interface VoiceStartTraceEntry {
832
+ /** Milliseconds since the attempt began. */
833
+ readonly atMs: number;
834
+ readonly stage: string;
835
+ readonly detail: Readonly<Record<string, string | number | boolean | null>>;
836
+ }
837
+ /** Says what happened during one attempt. */
838
+ type VoiceStartNote = (stage: string, detail?: VoiceStartTraceEntry["detail"]) => void;
839
+ /**
840
+ * One conversation's view of the trace: the attempt its latest voice start began, which what its
841
+ * voice does later is noted into. Before its first start, nothing is kept.
842
+ */
843
+ interface SessionVoiceStartTrace {
844
+ /**
845
+ * This conversation begins a voice start.
846
+ * @param chatId The chat voice is starting for.
847
+ */
848
+ readonly begin: (chatId: string) => void;
849
+ /** Note into this conversation's latest attempt. */
850
+ readonly note: VoiceStartNote;
851
+ }
852
+ /** The part of an HTTP response the trace answers through. An Express response has it. */
853
+ interface TraceResponse {
854
+ json(body: unknown): unknown;
855
+ }
856
+ /**
857
+ * The one method of an HTTP application the trace route needs. An Express application has it, so
858
+ * the published types name no Express package.
859
+ */
860
+ interface TraceRouteHost {
861
+ get(path: string, handler: (request: unknown, response: TraceResponse) => void): unknown;
862
+ }
863
+ /**
864
+ * Mount the route the trace is read through.
865
+ * @param app The HTTP application, such as an Express application.
866
+ */
867
+ declare function mountVoiceStartTraceRoute(app: TraceRouteHost): void;
868
+ /** The runtime owners a tab session's coordinator and voice run on. */
869
+ interface CodexWorkbenchSessionComponents {
870
+ readonly realtime: CodexRealtimeAdapter;
871
+ readonly coordinator: CodexCoordinator;
872
+ readonly spokenApproval: CodexSpokenApprovalGate;
873
+ readonly coordinatorTools: CoordinatorToolDispatcher;
874
+ readonly callbacks: CoordinatorCallbacks;
875
+ }
876
+ /** What a browser asks of one tab session's voice. */
877
+ interface CodexWorkbenchTabSessionActions {
878
+ readonly realtime: BrowserRealtimeActions;
879
+ }
880
+ /** What the server remembers about one tab session between the reads that fill it in. */
881
+ interface CodexWorkbenchTabSessionState {
882
+ /** Which coordinator turn delegated each workhorse turn, newest last; bounded. */
883
+ readonly delegations: Map<TurnId, TurnId>;
884
+ /** Which conversation each coordinator turn shows in, newest last; bounded. */
885
+ readonly coordinatorTurnHomes: Map<TurnId, CoordinatorTurnHome>;
886
+ /** The coordinator tool call running now, which every owner that asks sees the same. */
887
+ currentCoordinatorCall: LogicalToolCallCorrelation | null;
888
+ /** Every thread this tab started, its coordinator's and its workhorses', current and replaced. */
889
+ readonly threads: Set<ThreadId>;
890
+ /** The attempt this tab's latest voice start began, which its voice notes into. */
891
+ readonly voiceTrace: SessionVoiceStartTrace;
892
+ /**
893
+ * The checkout the tab showed when voice last started. Voice speaks for the whole tab, and its
894
+ * session is bound to that checkout's workhorse for as long as it runs; null before any start.
895
+ */
896
+ voiceCheckout: string | null;
897
+ /** Live while its tab may still use it; ending once the tab has gone, until its threads unload. */
898
+ phase: "live" | "ending";
899
+ }
900
+ /** One browser tab's conversation: its coordinator and voice, and a workhorse per checkout. */
901
+ interface CodexWorkbenchTabSession {
902
+ readonly id: TabSessionId;
903
+ readonly components: CodexWorkbenchSessionComponents;
904
+ readonly actions: CodexWorkbenchTabSessionActions;
905
+ readonly state: CodexWorkbenchTabSessionState;
906
+ /** Its workhorses, by checkout, in the order they were built. */
907
+ readonly workhorses: ReadonlyMap<string, CodexWorkbenchWorkhorse>;
908
+ /** The workhorse of one checkout, built the first time it is asked for while the tab is live. */
909
+ readonly workhorse: (checkout: string) => CodexWorkbenchWorkhorse;
910
+ /** The workhorse voice is bound to: the one of the checkout voice last started from. */
911
+ readonly voiceWorkhorse: () => CodexWorkbenchWorkhorse | null;
912
+ /**
913
+ * Stop the workhorse of one checkout, or every workhorse of the tab when the checkout is null.
914
+ * Each one that runs a turn has it interrupted; the others have nothing to stop.
915
+ */
916
+ readonly stopWork: (checkout: string | null) => Promise<readonly WorkhorseStop[]>;
917
+ }
918
+ interface CodexWorkbenchSessions {
919
+ /** The live session with this id, built the first time it is asked for or after it ended. */
920
+ readonly open: (id: TabSessionId) => CodexWorkbenchTabSession;
921
+ /** The live session with this id, refused when there is none. */
922
+ readonly require: (id: TabSessionId) => CodexWorkbenchTabSession;
923
+ /** Every live session, in the order they opened. */
924
+ readonly list: () => readonly CodexWorkbenchTabSession[];
925
+ /** The live session that started this thread, or null when none did or it is ending. */
926
+ readonly forThread: (threadId: ThreadId) => CodexWorkbenchTabSession | null;
927
+ /** The workhorse of a live session that started this thread, or null when none did. */
928
+ readonly workhorseForThread: (threadId: ThreadId) => CodexWorkbenchWorkhorse | null;
929
+ /** Hand one notification to the session its thread belongs to, or to every session. */
930
+ readonly onNotification: (event: TransportServerNotification) => void;
931
+ /** Hand a coordinator tool call to the calling thread's session, or refuse it. */
932
+ readonly routeCoordinatorTool: (request: DynamicServerRequest) => void;
933
+ /** Hand a workhorse's tell_coordinator call to the calling thread's session, or refuse it. */
934
+ readonly routeCallback: (request: DynamicServerRequest) => void;
935
+ /**
936
+ * End the live session with this id, because its tab has gone for good. Resolves once every
937
+ * thread it started was unloaded and the session was dropped; a session that is not live is
938
+ * left alone.
939
+ */
940
+ readonly end: (id: TabSessionId) => Promise<void>;
941
+ /** Settle what every session carried for a child that exited. */
942
+ readonly childExit: (child: ChildId, epoch: ChildEpoch) => Promise<void>;
943
+ /** Stop what every session runs: voice and the queues. */
944
+ readonly stop: () => Promise<void>;
945
+ /** Dispose every session's remaining owners and forget every session. */
946
+ readonly dispose: () => Promise<void>;
947
+ /** Hear when a session opens or ends, or gains a workhorse. */
948
+ readonly onChange: (listener: () => void) => () => void;
949
+ }
950
+ /** Capabilities granted to an installed domain. The core retains generation and process ownership. */
951
+ interface CodexWorkbenchDomainScope {
952
+ readonly identity: IdentityAuthorities;
953
+ readonly epoch: CodexEpochStore;
954
+ readonly transport: CodexTransport;
955
+ readonly session: CodexSession;
956
+ readonly threadLink: CodexThreadLinkPort;
957
+ readonly approvals: CodexApprovalBroker;
958
+ readonly sessions: Pick<CodexWorkbenchSessions, "open" | "list" | "require" | "forThread" | "workhorseForThread" | "end" | "onChange">;
959
+ readonly assertCurrent: () => void;
960
+ readonly shutdown: () => Promise<CodexWorkbenchSnapshot>;
961
+ readonly publish: () => void;
962
+ }
963
+ /** A host owns its domain tools, their visual approvals, and their cleanup together. */
964
+ interface CodexWorkbenchDomain {
965
+ readonly dispatch: (request: DynamicServerRequest) => Promise<unknown>;
966
+ readonly approvals?: WorkbenchDomainApprovals;
967
+ readonly onNotification?: (event: TransportServerNotification) => void;
968
+ readonly endSession?: (id: TabSessionId) => void;
969
+ readonly childExit?: (child: ChildId, epoch: ChildEpoch) => Promise<void> | void;
970
+ readonly shutdown?: (cause: "server_shutdown" | "child_disconnected") => Promise<void> | void;
971
+ readonly dispose: () => void;
972
+ }
973
+ interface CodexWorkbenchDomainTools {
974
+ readonly registrations: readonly {
975
+ readonly namespace: string;
976
+ readonly manifestHash: string;
977
+ }[];
978
+ readonly install: (scope: CodexWorkbenchDomainScope) => CodexWorkbenchDomain;
979
+ }
980
+ /** The one owner name every Codex workbench snapshot reports itself under. */
981
+ declare const CODEX_WORKBENCH_OWNER: "codex-realtime-voice-workbench";
982
+ /** Where the workbench owner is in its life. */
983
+ type CodexWorkbenchState = "idle" | "starting" | "ready" | "stopping" | "failed";
984
+ interface CodexWorkbenchSnapshot {
985
+ readonly owner: typeof CODEX_WORKBENCH_OWNER;
986
+ readonly state: CodexWorkbenchState;
987
+ readonly generation: number;
988
+ readonly childPid: number | null;
989
+ readonly ready: boolean;
990
+ readonly failure: string | null;
991
+ }
992
+ /**
993
+ * How a host checks, prepares, opens and forgets the narrative a voice session starts to present.
994
+ * The narrative's meaning is the host's; the package keeps the voice session's identity.
995
+ */
996
+ interface VoiceNarrativeAdapter {
997
+ /** Refuse a narrative before the start changes any running session. */
998
+ readonly validate?: (input: VoiceNarrative | null) => void;
999
+ /** Turn the browser's narrative into the one the session presents. */
1000
+ readonly prepare: (input: VoiceNarrative | null, browserId: string) => VoiceNarrative | Promise<VoiceNarrative>;
1001
+ /** Hear that the session presenting this narrative is open. */
1002
+ readonly opened?: (narrative: VoiceNarrative | null, browserId: string, trace: SessionVoiceStartTrace) => void;
1003
+ /** Release what a replaced session's narrative held for its browser. */
1004
+ readonly forget?: (browserId: string) => void;
1005
+ /**
1006
+ * Whether nobody listens live to a session that presents this prepared narrative. An unattended
1007
+ * session gives the coordinator no workhorse outcome, and the browser state says so. Default:
1008
+ * never.
1009
+ */
1010
+ readonly unattended?: (narrative: VoiceNarrative) => boolean;
1011
+ }
1012
+ /**
1013
+ * The policy the core runs a generation under. The agent builds a default for every member; a
1014
+ * host's extension replaces that member whole. The default `contextForOperation` reads the
1015
+ * generation that the default `onGeneration` installs, so a host that replaces `onGeneration`
1016
+ * replaces it too.
1017
+ */
1018
+ interface CodexWorkbenchHostPolicy {
1019
+ readonly instructions: WorkbenchInstructions;
1020
+ /** How an execution context becomes the bytes a thread reads. Default: canonical JSON. */
1021
+ readonly contextCodec: WorkbenchContextCodec;
1022
+ readonly resolveCheckout: (named: string) => string | null;
1023
+ /** What one tab's coordinator is told about the host page. Default: the `context` option. */
1024
+ readonly coordinatorContextFor: (id: TabSessionId) => WorkbenchContextSource;
1025
+ /** How one tab's voice starts. Default: the `voice` option. */
1026
+ readonly voiceFor: (id: TabSessionId) => WorkbenchVoicePolicy;
1027
+ /**
1028
+ * The context an operation runs under, captured before it runs. Default: the live workhorse of
1029
+ * the authority's checkout and the host text; throws when that workhorse changed meanwhile.
1030
+ */
1031
+ readonly contextForOperation: (authority: WorkbenchOperationAuthority, operation: PendingOperation) => WorkbenchExecutionContext;
1032
+ readonly shownCheckoutOf: (browserId: string) => string;
1033
+ readonly shownConversationOf: (id: TabSessionId) => string | null;
1034
+ readonly onShownChange: (listener: () => void) => () => void;
1035
+ /** The name the workhorse list shows for a checkout. Default: the checkout directory's name. */
1036
+ readonly checkoutLabel: (checkout: string) => string;
1037
+ /** Checks, prepares, opens and forgets the narrative a browser starts voice to present. */
1038
+ readonly narrative?: VoiceNarrativeAdapter;
1039
+ /** The host's own Codex dynamic tools, installed on each generation. */
1040
+ readonly domainTools?: CodexWorkbenchDomainTools;
1041
+ /** Install context and authority readers before browser work is accepted. Retirement removes them. */
1042
+ readonly onGeneration?: (scope: CodexWorkbenchDomainScope) => () => void;
1043
+ /** Install a host's own browser socket routing on each generation's gateway. */
1044
+ readonly onBrowserGateway?: (scope: {
1045
+ readonly gateway: CodexWorkbenchGateway;
1046
+ readonly sessions: Pick<CodexWorkbenchSessions, "open" | "end">;
1047
+ }) => () => void;
1048
+ readonly onFatal: (error: unknown) => void;
1049
+ }
1050
+ type PendingOperation = Omit<Exclude<WorkbenchOperation, {
1051
+ readonly id: null;
1052
+ }>, "outcome">;
1053
+ interface WorkbenchOperationAuthority {
1054
+ readonly tabSessionId: TabSessionId;
1055
+ readonly checkout: string;
1056
+ readonly clientId: string | null;
1057
+ readonly childId: LogicalToolCallCorrelation["child"];
1058
+ readonly epoch: LogicalToolCallCorrelation["epoch"];
1059
+ readonly threadId: LogicalToolCallCorrelation["threadId"];
1060
+ readonly linkRevision?: number;
1061
+ }
1062
+ /** The chats on screen by tab, and when each tab that has none left ends. */
1063
+ interface TabSessions {
1064
+ /** Remember which tab a chat belongs to, as its authoritative socket named it. */
1065
+ readonly note: (browserId: string, tabSessionId: TabSessionId | null) => void;
1066
+ /** The tab a chat belongs to, or null while its socket named none. */
1067
+ readonly of: (browserId: string) => TabSessionId | null;
1068
+ /** Forget the tab of a chat whose socket has gone; its tab's grace starts if it was the last. */
1069
+ readonly forget: (browserId: string) => void;
1070
+ /** Forget every chat and every grace, because the server is stopping. Nothing ends. */
1071
+ readonly forgetAll: () => void;
1072
+ /** Hear each tab session that ended, once the grace passed with no chat of it back. */
1073
+ readonly onEnded: (listener: (tabSessionId: TabSessionId) => void) => () => void;
1074
+ /**
1075
+ * The checkout whose conversation a tab shows. A tab that shows none yet is pinned to the
1076
+ * checkout the asker names.
1077
+ */
1078
+ readonly shown: (tabSessionId: TabSessionId, pin: () => string) => string;
1079
+ /** The checkout whose conversation a tab shows, or null before anything read it. */
1080
+ readonly current: (tabSessionId: TabSessionId) => string | null;
1081
+ /** Show a checkout's conversation in a tab, as the person activated it; true when it changed. */
1082
+ readonly show: (tabSessionId: TabSessionId, checkout: string) => boolean;
1083
+ /** Hear each tab whose shown conversation changed. */
1084
+ readonly onShownChange: (listener: (tabSessionId: TabSessionId) => void) => () => void;
1085
+ }
1086
+ interface BrowserRegistration {
1087
+ readonly instance: BrowserConnectionInstance;
1088
+ readonly chatId: string;
1089
+ readonly tabSessionId: TabSessionId;
1090
+ readonly checkout: string;
1091
+ }
1092
+ interface DefaultWorkbenchHostInput {
1093
+ readonly instructions: WorkbenchInstructions;
1094
+ readonly context?: WorkbenchContextSource;
1095
+ readonly voice?: WorkbenchVoicePolicy;
1096
+ readonly allowedCheckouts: readonly string[] | ((named: string) => string | null);
1097
+ readonly domainTools?: CodexWorkbenchDomainTools;
1098
+ readonly onFatal?: (error: unknown) => void;
1099
+ }
1100
+ interface CodexWorkbenchStorageInput {
1101
+ readonly rootDirectory: string;
1102
+ readonly ownerDirectory?: string;
1103
+ }
1104
+ /** An installation supplies private paths, the executable environment, and frozen domain policy. */
1105
+ interface CreateCodexWorkbenchOptions {
1106
+ readonly storage: CodexWorkbenchStorageInput;
1107
+ readonly process: Omit<CodexProcessOptions, "workingDirectory" | "storage">;
1108
+ readonly host: DefaultWorkbenchHostInput;
1109
+ readonly extensions?: CodexWorkbenchExtensions;
1110
+ readonly browserLeaseLedger?: BrowserLeaseLedger;
1111
+ }
1112
+ /** Optional application adapters install domain context and browser routing on the core lifecycle. */
1113
+ type CodexWorkbenchExtensions = Omit<Partial<CodexWorkbenchHostPolicy>, "instructions" | "resolveCheckout" | "shownCheckoutOf" | "shownConversationOf" | "onShownChange"> & {
1114
+ /** The checkout a browser's tab shows first. Default: the checkout its socket was accepted with. */
1115
+ readonly browserCheckoutOf?: (browserId: string) => string;
1116
+ /** Install the host's reading and activation of the tab registry on each generation's gateway. */
1117
+ readonly installBrowserSessions?: (tabs: TabSessions) => () => void;
1118
+ };
1119
+ /**
1120
+ * Build the complete Codex workbench from explicit installation and host inputs.
1121
+ * @param options The private storage, process environment, and host policy.
1122
+ * @returns Lifecycle, session, connection, and browser activation operations.
1123
+ */
1124
+ declare function createCodexWorkbench(options: CreateCodexWorkbenchOptions): Readonly<{
1125
+ start: () => Promise<CodexWorkbenchSnapshot>;
1126
+ /**
1127
+ * Stop the private workbench and release browser session state.
1128
+ */
1129
+ shutdown: () => Promise<void>;
1130
+ /**
1131
+ * Read the private process lifecycle without starting a child.
1132
+ * @returns The current lifecycle snapshot.
1133
+ */
1134
+ snapshot: () => CodexWorkbenchSnapshot;
1135
+ browser: Readonly<{
1136
+ accept: (instance: BrowserConnectionInstance, browserId: string, registration: Omit<BrowserRegistration, "instance">) => void;
1137
+ handle: (instance: BrowserConnectionInstance, browserId: string, input: unknown, transport: ServerCodexBrowserSocketSend) => Promise<void>;
1138
+ close: (instance: BrowserConnectionInstance, browserId: string) => Promise<void>;
1139
+ drain: () => Promise<void>;
1140
+ }>;
1141
+ instructions: WorkbenchInstructions;
1142
+ /**
1143
+ * Tell the agents of the live tab sessions about a context change.
1144
+ * @param change What changed, and who is told.
1145
+ * @returns One receipt per tab session and audience.
1146
+ */
1147
+ announce: (change: ContextChange) => Promise<readonly ContextReceipt[]>;
1148
+ }>;
1149
+ /** What an upgrade on this path names: its chat, its tab session and the browser id of both. */
1150
+ interface SocketSurface {
1151
+ readonly tabSessionId: NonNullable<ReturnType<typeof parseTabSessionId>>;
1152
+ readonly chatId: string;
1153
+ readonly browserId: string;
1154
+ }
1155
+ /** Where browser sockets connect, and the one origin they must come from. */
1156
+ interface VoiceAgentAttachOptions {
1157
+ /**
1158
+ * The absolute socket path, such as `/api/voice`. Upgrades to any other path are left to the
1159
+ * server's other listeners, so a server with no other listener must end those itself.
1160
+ */
1161
+ readonly path: string;
1162
+ /**
1163
+ * The listener's own HTTP origin exactly, such as `http://127.0.0.1:4100`, with no path or
1164
+ * trailing slash. A socket whose `Host` header names another host, or whose `Origin` header
1165
+ * names another origin, is refused with 403.
1166
+ */
1167
+ readonly origin: string;
1168
+ /**
1169
+ * The admitted checkout every socket on this path works in. The browser never selects it.
1170
+ * Optional when the agent admits exactly one listed checkout.
1171
+ */
1172
+ readonly checkout?: string;
1173
+ }
1174
+ /**
1175
+ * The `data` of a socket this adapter upgraded. The shared `websocket` handlers serve a socket
1176
+ * whose `data` is one of these and give every other socket to the host's own handlers.
1177
+ */
1178
+ declare class VoiceSocket {
1179
+ readonly surface: SocketSurface;
1180
+ /**
1181
+ * Keep the admitted surface for the socket's `open`.
1182
+ * @param surface The socket's chat, tab session and browser id.
1183
+ */
1184
+ constructor(surface: SocketSurface);
1185
+ }
1186
+ type Fetched = Response | undefined | Promise<Response | undefined>;
1187
+ /**
1188
+ * Where the agent's browser sockets connect on a `Bun.serve` server, and the host's own handlers
1189
+ * of everything else on it.
1190
+ */
1191
+ interface VoiceAgentBunOptions<HostData> extends Omit<VoiceAgentAttachOptions, "origin"> {
1192
+ /**
1193
+ * The server's own HTTP origin exactly, such as `http://127.0.0.1:4100`. Default: the origin of
1194
+ * the receiving server's `url`, so a server on port 0 needs none. That `url` names the
1195
+ * `hostname` the server was given, and `localhost` when it was given none: name the origin when
1196
+ * the browser reaches the server under another name, as for a server on `0.0.0.0`, on a unix
1197
+ * socket or behind a proxy. A default the browser does not match refuses it with 403.
1198
+ */
1199
+ readonly origin?: string;
1200
+ /**
1201
+ * The host's handler of every request that is not a socket upgrade on `path`. It may upgrade
1202
+ * sockets of its own with any other `data`. Default: answer 404.
1203
+ */
1204
+ readonly fetch?: (request: Request, server: Bun.Server<HostData | VoiceSocket>) => Fetched;
1205
+ /**
1206
+ * The host's handlers of its own sockets. Their options, such as `maxPayloadLength`, apply to
1207
+ * every socket of the server, because Bun has one handler set per server.
1208
+ */
1209
+ readonly websocket?: Bun.WebSocketHandler<HostData>;
1210
+ }
1211
+ /** The `fetch` and `websocket` of `Bun.serve` options, with the agent's sockets in them. */
1212
+ interface VoiceAgentBunHandlers<HostData> {
1213
+ readonly fetch: (request: Request, server: Bun.Server<HostData | VoiceSocket>) => Fetched;
1214
+ readonly websocket: Bun.WebSocketHandler<HostData | VoiceSocket>;
1215
+ }
1216
+ /**
1217
+ * Deliberate extension points for a host that adds its own domain to the agent: context sources,
1218
+ * domain tools, voice narratives and its own browser socket routing. A host without a domain
1219
+ * passes none.
1220
+ */
1221
+ type VoiceAgentExtensions = Omit<CodexWorkbenchExtensions, "onFatal"> & {
1222
+ /** What the coordinator is told about the host page. Default: the admitted checkouts, as data. */
1223
+ readonly context?: WorkbenchContextSource;
1224
+ /** How voice starts, for a narrative or an ordinary session. Default: plain live voice. */
1225
+ readonly voice?: WorkbenchVoicePolicy;
1226
+ /** Extra Codex dynamic tools per role, appended to the built-in coordination tools. */
1227
+ readonly tools?: {
1228
+ readonly coordinator?: WorkbenchDynamicTools;
1229
+ readonly workhorse?: WorkbenchDynamicTools;
1230
+ };
1231
+ /** A browser command-lease ledger the host shares with its own sockets. */
1232
+ readonly browserLeaseLedger?: BrowserLeaseLedger;
1233
+ };
1234
+ /** Everything a host supplies to run one realtime Codex voice agent. */
1235
+ interface VoiceAgentOptions {
1236
+ /**
1237
+ * The agent's private state: Codex home, SQLite home and process-owner records. Created with
1238
+ * mode 0700. Keep it outside every checkout. The directory and everything below it must not
1239
+ * be a symbolic link. A link above it that you or root own, in directories no other user can
1240
+ * change, such as `/tmp` on macOS, is resolved once, here; any other link is refused at start.
1241
+ */
1242
+ readonly storage: {
1243
+ readonly directory: string;
1244
+ /** Where process-owner records live. Default: `<directory>/owner`. */
1245
+ readonly ownerDirectory?: string;
1246
+ };
1247
+ /**
1248
+ * How to run Codex: the verified executable path, extra environment, PATH prefixes, secrets
1249
+ * to redact from diagnostics, and an optional callback that receives the process group. Read
1250
+ * once, when the agent is created.
1251
+ */
1252
+ readonly codex: CreateCodexWorkbenchOptions["process"];
1253
+ /**
1254
+ * The checkouts a workhorse may work in: absolute paths, or a function that returns the
1255
+ * admitted path for a named checkout and null for a refused one.
1256
+ */
1257
+ readonly checkouts: readonly string[] | ((named: string) => string | null);
1258
+ /**
1259
+ * The host's own instructions, appended to the built-in coordinator and workhorse roles. Both
1260
+ * must be non-empty: for an empty one, {@link createVoiceAgent} throws a `TypeError` with the
1261
+ * message "A workbench role requires domain instructions."
1262
+ */
1263
+ readonly instructions: {
1264
+ readonly coordinator: string;
1265
+ readonly workhorse: string;
1266
+ };
1267
+ /**
1268
+ * How the agent names itself to Codex, to the user and in its records. Each value left out is
1269
+ * that of `DEFAULT_VOICE_AGENT_IDENTITY`. Keep every value once threads exist: a thread
1270
+ * keeps the names it started with.
1271
+ */
1272
+ readonly identity?: Partial<VoiceAgentIdentity>;
1273
+ /** Receives a fault the agent cannot recover from. The host decides whether to stop. */
1274
+ readonly onFatal: (error: unknown) => void;
1275
+ /** Domain extensions; see {@link VoiceAgentExtensions}. */
1276
+ readonly extensions?: VoiceAgentExtensions;
1277
+ }
1278
+ type Workbench = ReturnType<typeof createCodexWorkbench>;
1279
+ /** The agent's private Codex process: idle, starting, ready, or failed, with its failure. */
1280
+ type VoiceAgentStatus = ReturnType<Workbench["snapshot"]>;
1281
+ /**
1282
+ * The browser connection port, for a host that serves the agent's browser messages on a socket
1283
+ * of its own instead of {@link VoiceAgent.attach} or {@link VoiceAgent.bunHandlers}: accept a
1284
+ * socket with its chat, tab session and checkout, hand it each parsed request, close it, and drain
1285
+ * accepted work.
1286
+ */
1287
+ type VoiceAgentBrowserPort = Workbench["browser"];
1288
+ /** One realtime Codex voice agent: a coordinator per browser tab and a workhorse per checkout. */
1289
+ interface VoiceAgent {
1290
+ /**
1291
+ * Start the private Codex process and wait for it. Start again after a failure or a shutdown
1292
+ * to replace the process.
1293
+ * @returns The status once the process is ready: `ready` is always `true`.
1294
+ * @throws {Error} When Codex cannot start, an error whose `code` is `startup_failed` and whose
1295
+ * `cause` names the reason; {@link VoiceAgent.status} then reads `failed`. A start during a
1296
+ * shutdown, or while the process already runs, also rejects.
1297
+ */
1298
+ readonly start: () => Promise<VoiceAgentStatus>;
1299
+ /** Read the process status without starting anything. */
1300
+ readonly status: () => VoiceAgentStatus;
1301
+ /**
1302
+ * Serve browser sockets on one path of a `node:http` server, which Bun runs. Attach once
1303
+ * {@link VoiceAgent.start} is ready: a socket that arrives while the process is not ready is
1304
+ * closed with 1011. A socket that sends a binary or non-JSON frame is closed with 1003.
1305
+ * @returns Detach: stops accepting, closes those sockets and waits for their work.
1306
+ * @throws {TypeError} When the path or origin could never admit a socket, or the agent admits
1307
+ * more than one checkout and the options name none.
1308
+ */
1309
+ readonly attach: (server: Server, options: VoiceAgentAttachOptions) => () => Promise<void>;
1310
+ /**
1311
+ * Serve browser sockets on one path of a `Bun.serve` server: spread the result into its
1312
+ * options, as `Bun.serve({ port, ...agent.bunHandlers({ path, fetch }) })`. The admission is
1313
+ * that of {@link VoiceAgent.attach}. A request that is not a socket upgrade on `path` goes to
1314
+ * `fetch`, and a socket that `fetch` upgrades itself goes to `websocket`, the host's own
1315
+ * handlers. Left out, `origin` is the origin of the receiving server's `url`. After
1316
+ * {@link VoiceAgent.shutdown}, an upgrade on `path` is refused with 503: after a later
1317
+ * {@link VoiceAgent.start}, call this again and pass the result to the server's `reload`.
1318
+ * @returns The `fetch` and `websocket` of `Bun.serve` options.
1319
+ * @throws {TypeError} When the path or a named origin could never admit a socket, or the agent
1320
+ * admits more than one checkout and the options name none.
1321
+ */
1322
+ readonly bunHandlers: <HostData = undefined>(options: VoiceAgentBunOptions<HostData>) => VoiceAgentBunHandlers<HostData>;
1323
+ /**
1324
+ * Close the sockets of every {@link VoiceAgent.attach} and {@link VoiceAgent.bunHandlers} call,
1325
+ * stop the Codex process and forget every browser tab. After a later {@link VoiceAgent.start},
1326
+ * attach again or reload the server with new Bun handlers to serve sockets.
1327
+ */
1328
+ readonly shutdown: () => Promise<void>;
1329
+ /** The browser connection port; see {@link VoiceAgentBrowserPort}. */
1330
+ readonly browser: VoiceAgentBrowserPort;
1331
+ /**
1332
+ * The exact coordinator and workhorse profiles the agent's threads start with: identity,
1333
+ * composed instruction text, dynamic tools, and the SHA-256 of each. A host can record these
1334
+ * digests to notice when a change of its instructions or tools would reach Codex.
1335
+ */
1336
+ readonly instructions: Workbench["instructions"];
1337
+ /**
1338
+ * Tell the agents of the browser tabs that something they should know about changed: the
1339
+ * workhorses of some checkouts, the coordinator, the live voice, or any combination. A
1340
+ * workhorse hears one `feed` and `sequence` at most once, and nothing starts a turn. The
1341
+ * audiences are told concurrently, so no audience waits for another, and no order between them
1342
+ * is promised.
1343
+ * @returns One receipt per tab session and audience, and per checkout for a workhorse.
1344
+ * @throws {TypeError} When the change is malformed, for example when it names no audience.
1345
+ * @throws {Error} While {@link VoiceAgent.status} does not read ready.
1346
+ */
1347
+ readonly announce: (change: ContextChange) => Promise<readonly ContextReceipt[]>;
1348
+ }
1349
+ /**
1350
+ * Create a realtime Codex voice agent. Nothing starts until {@link VoiceAgent.start}.
1351
+ * @param options The storage, Codex process, checkouts, instructions, identity and extensions.
1352
+ * @returns The agent's lifecycle and browser operations.
1353
+ */
1354
+ export declare function createVoiceAgent(options: VoiceAgentOptions): VoiceAgent;
1355
+ /**
1356
+ * Project the owners' state into one validated browser snapshot, refusing
1357
+ * input that carries a secret or that the browser contract cannot represent.
1358
+ * @param model The browser schema owner.
1359
+ * @param input The owners' state for one chat.
1360
+ * @returns The projected snapshot, or the refusal.
1361
+ */
1362
+ export declare function projectCodexBrowserState(model: BrowserProjectionModel, input: BrowserProjectionInput): BrowserProjectionResult;
1363
+ /**
1364
+ * The checkouts of a tab session's live workhorses: those that have a thread.
1365
+ * @param session The tab session.
1366
+ * @returns The checkouts, in the order the workhorses were built.
1367
+ */
1368
+ declare function liveWorkhorseCheckouts(session: Pick<CodexWorkbenchTabSession, "workhorses">): readonly string[];
1369
+ /**
1370
+ * An empty process-lifetime ledger: no tab session has held a lease yet.
1371
+ * @returns The ledger.
1372
+ */
1373
+ declare function createBrowserLeaseLedger(): BrowserLeaseLedger;
1374
+ export { type BrowserProjectionInput, type ContextChange, type TabSessionId, type VoiceAgent, type VoiceAgentBrowserPort, type VoiceAgentExtensions, type VoiceAgentOptions, createBrowserLeaseLedger, createServerCodexBrowserSocketOwner, createServerCodexBrowserSocketSend, liveWorkhorseCheckouts, mountVoiceStartTraceRoute, resolveCodexExecutable };