@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.
package/README.md CHANGED
@@ -1,3 +1,622 @@
1
- # Temporary Holding Version
1
+ # @archboard/codex-realtime-voice
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ This package adds a realtime Codex voice agent to your own Bun project. A person talks to a voice coordinator in a browser page. The coordinator answers short questions itself. It hands sustained work to workhorses. A workhorse is a Codex thread that works in one checkout, which is a directory of code that your server admits.
4
+
5
+ The package runs one private Codex app-server process, which is the process that hosts the Codex threads. It keeps the history of each conversation. It relays approvals to the page. It also tells the page when it cannot know whether an action arrived. The package is for developers who want voice-driven Codex work inside their own tool, with their own page, on their own machine. [Concepts](#concepts) defines the terms that this page uses.
6
+
7
+ ## Requirements
8
+
9
+ - Bun 1.4.4 or newer.
10
+ - The `@openai/codex` package at exactly version 0.166.0. The package refuses every other version.
11
+ - Node.js on `PATH`, because `@openai/codex` starts Codex with a Node.js script. A server that you start with `bun run <script>` needs no Node.js: `bun run` puts its own `node` on `PATH`.
12
+ - Linux or macOS.
13
+ - A Codex account that supports realtime voice. The person signs in from the page.
14
+ - For voice: a browser with a microphone and speakers. Browsers give microphone access only to pages on `https` or on a local address such as `127.0.0.1`.
15
+ - For the React entry: React 19.2.8 or a newer React 19.
16
+ - For TypeScript: `@types/bun`, because the server types use Bun's own types.
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ bun add @archboard/codex-realtime-voice @openai/codex@0.166.0 react react-dom
22
+ bun add -d @types/bun @types/react @types/react-dom
23
+ ```
24
+
25
+ `@openai/codex` is a peer dependency, so you install it yourself. `react` is an optional peer dependency. You need it only for `@archboard/codex-realtime-voice/react`. `@types/bun` is an optional peer dependency too. You need it only for type checking.
26
+
27
+ ## Quickstart
28
+
29
+ The quickstart is two files in the root of your project: a server and a React page. The workhorse works in the directory where you start the server.
30
+
31
+ `server.ts` starts the agent and a `Bun.serve` server. `agent.bunHandlers` gives the server its `fetch` and `websocket` handlers: the page's socket on `/voice` goes to the agent, and every other request goes to your `fetch`, which serves the page. A host on `node:http`, such as Express, uses [`attach`](#a-nodehttp-server) instead.
32
+
33
+ <!-- checked: server.ts -->
34
+
35
+ ```ts
36
+ import { homedir } from "node:os";
37
+ import path from "node:path";
38
+ import { createVoiceAgent, resolveCodexExecutable } from "@archboard/codex-realtime-voice/server";
39
+
40
+ const agent = createVoiceAgent({
41
+ storage: { directory: path.join(homedir(), ".my-voice-agent") },
42
+ codex: { executablePath: resolveCodexExecutable() },
43
+ checkouts: [process.cwd()],
44
+ instructions: {
45
+ coordinator: "Answer short questions yourself. Give sustained work to the workhorse.",
46
+ workhorse: "Do the work the person asks for in this checkout.",
47
+ },
48
+ onFatal: (error) => {
49
+ console.error(error);
50
+ void stop();
51
+ },
52
+ });
53
+
54
+ const page = await Bun.build({ entrypoints: [path.join(import.meta.dir, "page.tsx")] });
55
+ const script = await page.outputs[0]!.text();
56
+ const html = `<!doctype html><title>Voice</title><div id="root"></div><script type="module" src="/page.js"></script>`;
57
+
58
+ const server = Bun.serve({
59
+ hostname: "127.0.0.1",
60
+ port: 4100,
61
+ ...agent.bunHandlers({
62
+ path: "/voice",
63
+ fetch: (request) =>
64
+ new URL(request.url).pathname === "/page.js"
65
+ ? new Response(script, { headers: { "Content-Type": "text/javascript" } })
66
+ : new Response(html, { headers: { "Content-Type": "text/html" } }),
67
+ }),
68
+ });
69
+
70
+ await agent.start();
71
+ console.log(`Open ${server.url}`);
72
+
73
+ async function stop(): Promise<void> {
74
+ await agent.shutdown();
75
+ await server.stop();
76
+ }
77
+ process.once("SIGINT", () => void stop());
78
+ process.once("SIGTERM", () => void stop());
79
+ ```
80
+
81
+ `page.tsx` connects to the socket and offers sign-in, text messages, voice, the two stops and command approvals:
82
+
83
+ <!-- checked: page.tsx -->
84
+
85
+ ```tsx
86
+ import { useState } from "react";
87
+ import { createRoot } from "react-dom/client";
88
+ import {
89
+ createVoiceClient,
90
+ type VoiceApproval,
91
+ type VoiceApprovalResponse,
92
+ } from "@archboard/codex-realtime-voice/browser";
93
+ import {
94
+ VoiceClientProvider,
95
+ useVoiceClient,
96
+ useVoiceState,
97
+ } from "@archboard/codex-realtime-voice/react";
98
+
99
+ function App() {
100
+ const client = useVoiceClient();
101
+ const failure = useVoiceState((state) => state.failure);
102
+ return (
103
+ <main>
104
+ {failure && <p role="alert">{failure.message}</p>}
105
+ {failure?.uncertain && <button onClick={() => void client.refresh()}>Refresh</button>}
106
+ <Conversation />
107
+ </main>
108
+ );
109
+ }
110
+
111
+ function Conversation() {
112
+ const client = useVoiceClient();
113
+ const state = useVoiceState();
114
+ if (state.connection !== "connected")
115
+ return <button onClick={() => void client.connect()}>Connect ({state.connection})</button>;
116
+ if (state.server?.account.state !== "ready") return <SignIn />;
117
+ const pending = state.server.approvals.filter(
118
+ (approval) => approval.lifecycle.state === "pending",
119
+ );
120
+ return (
121
+ <>
122
+ <Voice />
123
+ <Work />
124
+ {pending.map((approval) => (
125
+ <Approval key={String(approval.requestId)} approval={approval} />
126
+ ))}
127
+ </>
128
+ );
129
+ }
130
+
131
+ function SignIn() {
132
+ const client = useVoiceClient();
133
+ const login = useVoiceState((state) => state.server?.login);
134
+ if (login?.state !== "pending")
135
+ return <button onClick={() => void client.signIn()}>Sign in with ChatGPT</button>;
136
+ return (
137
+ <p>
138
+ {login.authUrl && (
139
+ <a href={login.authUrl} target="_blank" rel="noreferrer">
140
+ Continue sign-in
141
+ </a>
142
+ )}{" "}
143
+ <button onClick={() => void client.refresh()}>I signed in</button>
144
+ </p>
145
+ );
146
+ }
147
+
148
+ const LIVE = [
149
+ "requesting_permission",
150
+ "negotiating",
151
+ "listening",
152
+ "muted",
153
+ "processing",
154
+ "speaking",
155
+ ];
156
+
157
+ function Voice() {
158
+ const client = useVoiceClient();
159
+ const voice = useVoiceState((state) => state.voice);
160
+ const server = useVoiceState((state) => state.server);
161
+ const live = LIVE.includes(voice.phase);
162
+ return (
163
+ <section>
164
+ <h2>Voice: {voice.phase}</h2>
165
+ <button disabled={live || !voice.available} onClick={() => void client.startVoice()}>
166
+ Start voice
167
+ </button>
168
+ <button disabled={!live} onClick={() => void client.stopVoice()}>
169
+ Stop voice
170
+ </button>
171
+ {voice.problem && <p role="alert">{voice.problem}</p>}
172
+ {server?.voice.transcript.map((line) => (
173
+ <p key={line.itemId}>
174
+ {line.speaker}: {line.text}
175
+ </p>
176
+ ))}
177
+ </section>
178
+ );
179
+ }
180
+
181
+ function Work() {
182
+ const client = useVoiceClient();
183
+ const timeline = useVoiceState((state) => state.server?.timeline);
184
+ const [message, setMessage] = useState("");
185
+ const running = timeline?.turns.some((turn) => turn.status === "inProgress") ?? false;
186
+ const send = async () => {
187
+ if (await client.send(message)) setMessage("");
188
+ };
189
+ return (
190
+ <section>
191
+ <h2>Workhorse</h2>
192
+ {timeline?.turns.flatMap((turn) =>
193
+ turn.items.map((item) =>
194
+ item.media === "prompt" || item.media === "text" ? (
195
+ <p key={item.itemId}>{item.text}</p>
196
+ ) : null,
197
+ ),
198
+ )}
199
+ <textarea value={message} onChange={(event) => setMessage(event.target.value)} />
200
+ <button disabled={running || message.trim() === ""} onClick={() => void send()}>
201
+ Send
202
+ </button>
203
+ <button disabled={!running} onClick={() => void client.stopWork()}>
204
+ Stop work
205
+ </button>
206
+ </section>
207
+ );
208
+ }
209
+
210
+ function Approval({ approval }: { readonly approval: VoiceApproval }) {
211
+ const client = useVoiceClient();
212
+ const intent = useVoiceState((state) => state.intent);
213
+ const answer = (response: VoiceApprovalResponse) => {
214
+ if (intent) void client.answerApproval(approval, response, intent);
215
+ };
216
+ if (approval.approvalKind !== "command_execution")
217
+ return <p>Codex asks a {approval.approvalKind} question that this page does not answer.</p>;
218
+ return (
219
+ <section>
220
+ <h2>Run this command?</h2>
221
+ <pre>{approval.command}</pre>
222
+ {approval.availableDecisions.map((decision) =>
223
+ typeof decision === "string" ? (
224
+ <button
225
+ key={decision}
226
+ onClick={() => answer({ approvalKind: "command_execution", decision })}
227
+ >
228
+ {decision}
229
+ </button>
230
+ ) : null,
231
+ )}
232
+ </section>
233
+ );
234
+ }
235
+
236
+ const root = createRoot(document.getElementById("root")!);
237
+ function mount() {
238
+ const client = createVoiceClient({ socketPath: "/voice" });
239
+ void client.connect();
240
+ window.addEventListener("pagehide", () => void client.dispose(), { once: true });
241
+ root.render(
242
+ <VoiceClientProvider client={client}>
243
+ <App />
244
+ </VoiceClientProvider>,
245
+ );
246
+ }
247
+ mount();
248
+ window.addEventListener("pageshow", (event) => {
249
+ if (event.persisted) mount();
250
+ });
251
+ ```
252
+
253
+ Start the server from the directory that the workhorse works in:
254
+
255
+ ```bash
256
+ bun server.ts
257
+ ```
258
+
259
+ Then do these steps:
260
+
261
+ 1. Open `http://127.0.0.1:4100`. Use this exact address, because the socket accepts only the server's own origin, and `localhost` is another origin.
262
+ 2. Select "Sign in with ChatGPT", then "Continue sign-in", and finish the sign-in in that browser. Select "I signed in" when the page still shows the sign-in.
263
+ 3. Type a message to the workhorse and select "Send".
264
+ 4. Select "Start voice", allow the microphone, and talk to the coordinator.
265
+ 5. Press `Ctrl+C` in the terminal to stop the server and its Codex process.
266
+
267
+ Bun bundles `page.tsx` when the server starts, so the quickstart needs no build step. For type checking, your `tsconfig.json` needs `"jsx": "react-jsx"`, the `DOM` library and the `bun` types. The page answers command approvals only. A complete page answers each approval kind. The example host in the [repository](https://github.com/miklschmidt/archboard/tree/main/apps/workbench-example) shows one.
268
+
269
+ ### A page without React
270
+
271
+ `@archboard/codex-realtime-voice/browser` works with any framework or none. The React hooks are a thin reading of this client:
272
+
273
+ <!-- checked: plain.ts -->
274
+
275
+ ```ts
276
+ import { createVoiceClient } from "@archboard/codex-realtime-voice/browser";
277
+
278
+ const client = createVoiceClient({ socketPath: "/voice" });
279
+ const status = document.createElement("output");
280
+ const talk = document.createElement("button");
281
+ talk.textContent = "Start voice";
282
+ talk.addEventListener("click", () => void client.startVoice());
283
+ document.body.append(status, talk);
284
+
285
+ client.subscribe(() => {
286
+ const state = client.snapshot();
287
+ status.textContent = `${state.connection}, voice ${state.voice.phase}`;
288
+ talk.disabled = !state.voice.available;
289
+ });
290
+ await client.connect();
291
+ ```
292
+
293
+ `subscribe` calls the listener after each change, and `snapshot()` returns the current state. Each state is a new frozen object.
294
+
295
+ ## Concepts
296
+
297
+ The coordinator is the Codex thread that the person talks to. It speaks through the realtime voice model, answers short questions, uses ordinary Codex tools for quick looks, and decides what the voice says. It does not do sustained work. It runs in its own directory inside the state directory, and that directory is not a checkout.
298
+
299
+ A workhorse is the Codex thread that does sustained work in one checkout. The coordinator gives it work with its own tools: it delegates, inspects, steers, queues and stops. A workhorse keeps its own history and never sees the coordinator's history. A text message from the page goes straight to the workhorse of the page's checkout.
300
+
301
+ An admitted checkout is a directory that your server lets a workhorse work in. You list the checkouts, or give a function that admits a checkout by name. Each workhorse reads the repository instructions and the Codex configuration of its checkout.
302
+
303
+ A tab session is one browser tab's conversation: one coordinator, and one workhorse for each checkout that the tab works in. The browser client keeps the tab session id in `sessionStorage`, so a reload keeps the conversation and another tab gets its own. When 60 seconds pass after the last chat of a tab closes, the tab session ends. The package then settles its open approvals, stops its voice and lets Codex unload its threads. A tab that comes back after that starts a new conversation.
304
+
305
+ A chat is one place in your page that shows the conversation, such as a panel. A chat id names it. Each chat has one socket. A chat that connects again replaces its earlier socket. All chats of a tab show the same conversation.
306
+
307
+ An approval is a request from Codex that the person must answer, such as running a command. The page receives each open approval in the server state and answers it with `answerApproval`. The answer carries the `intent` of the state that showed the approval, so the server refuses an answer to a conversation that changed since.
308
+
309
+ A spoken approval is an answer given aloud. Only a command approval that offers exactly "accept" or "decline" and grants nothing broader can be answered by voice. The coordinator classifies what the person said and settles the approval once through its own tool. When the words are unclear, the approval stays on the page for the person to answer there.
310
+
311
+ An uncertain delivery is an action whose result the client cannot know, for example because the socket closed before the server answered. The client then publishes a failure with `uncertain: true` and does not try the action again, because a second try can do the work twice. Refresh the state and look before you act again. The coordinator and the workhorse follow the same rule for their own tools, and the coordinator tells the person what is uncertain.
312
+
313
+ The state directory is the directory that you give as `storage.directory`. It holds the private Codex home (`codex-home`, the `CODEX_HOME` of the Codex process), the Codex database (`sqlite-home`) and the process-owner records (`owner`). The sign-in of the agent lives in this Codex home, not in the Codex home of your own Codex client. One running server owns one state directory.
314
+
315
+ ## Configuration
316
+
317
+ ### `createVoiceAgent(options)`
318
+
319
+ `createVoiceAgent` creates the agent and starts nothing. It throws when a listed checkout is not a readable directory, when an instruction is empty, or when an `identity` value has the wrong shape.
320
+
321
+ | Field | Default | What it does |
322
+ | -------------------------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
323
+ | `storage.directory` | Required | The state directory. The package creates it with mode `0700`. An existing directory must have mode `0700`, belong to you, and not be a symbolic link. A link above it that you or root own, in directories no other user can change, such as `/tmp` on macOS, is resolved once. Keep it outside every checkout. |
324
+ | `storage.ownerDirectory` | `<directory>/owner` | Where the process-owner lock and records live. |
325
+ | `codex.executablePath` | Required | The absolute path of the Codex executable. Use `resolveCodexExecutable()`. |
326
+ | `codex.hostEnvironment` | None | Extra environment variables for the Codex process. They replace inherited values, but never `CODEX_HOME` or `CODEX_SQLITE_HOME`. |
327
+ | `codex.pathPrefixes` | None | Absolute directories that go first on the `PATH` of the Codex process, in order. |
328
+ | `codex.diagnosticSecrets` | None | Strings that the package removes from the Codex output it keeps for diagnostics. |
329
+ | `codex.onGroupOwned` | None | Receives the identity of the Codex process group before the process is ready, for a host that cleans up processes itself. |
330
+ | `checkouts` | Required | The admitted checkouts: a list of directories, or a function that returns the admitted path for a named checkout and `null` for a refused one. The package resolves each to its real path. |
331
+ | `instructions.coordinator` | Required | Your text for the coordinator. The package appends it to the built-in coordinator role. It must not be empty. |
332
+ | `instructions.workhorse` | Required | Your text for each workhorse, appended to the built-in workhorse role. It must not be empty. |
333
+ | `identity` | See the identity table below | How the agent names itself to Codex and to the person. See the next table. |
334
+ | `onFatal` | Required | Receives a fault that the agent cannot recover from. You decide whether to stop. |
335
+ | `extensions` | None | Your own context, voice behavior and tools. See [Advanced hosting](#advanced-hosting). |
336
+
337
+ The agent that `createVoiceAgent` returns has these members:
338
+
339
+ | Member | What it does |
340
+ | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
341
+ | `start()` | Starts the private Codex process and resolves with the status once it is ready. When Codex cannot start, it rejects with an error whose `code` is `startup_failed` and whose `cause` names the reason. Call it again after a failure or a shutdown to start a new process. A call while the process is ready, or during `shutdown()`, rejects. |
342
+ | `status()` | Reads the status without starting anything: `state` (`idle`, `starting`, `ready`, `stopping` or `failed`), `ready`, `failure` (a message or `null`), `childPid` and `generation`. |
343
+ | `bunHandlers(options)` | Returns the `fetch` and `websocket` handlers of a `Bun.serve` server that serves the page's sockets on one path. Spread them into the options of `Bun.serve`. See [A `Bun.serve` server](#a-bunserve-server). |
344
+ | `attach(server, options)` | Serves the page's sockets on one path of a `node:http` server. It returns a function that detaches: it stops accepting, closes those sockets and waits for their work. See [A `node:http` server](#a-nodehttp-server). |
345
+ | `shutdown()` | Closes the sockets of every `bunHandlers` and `attach` call, stops the Codex process and forgets every tab session. |
346
+ | `instructions` | The exact coordinator and workhorse profiles that the threads start with: identity, instruction text, tools and the SHA-256 of each. Record the digests to notice when a change of your instructions or tools reaches Codex. |
347
+ | `browser` | The browser connection port for a host that serves sockets itself. See [Advanced hosting](#advanced-hosting). |
348
+
349
+ `identity` names the agent. A field that you leave out takes its default. Keep every value once threads exist: a thread keeps the names that it started with, a stored record keeps its prefix, and the agent drives only threads with its own thread source.
350
+
351
+ | Field | Default | What it does |
352
+ | ---------------- | -------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
353
+ | `serviceName` | `"codex-realtime-voice"` | The client service name that Codex records on each thread. |
354
+ | `threadSource` | `"codex-realtime-voice"` | The thread source that Codex records on each thread and that the agent requires. |
355
+ | `productName` | `"Codex"` | What the person talks with, as the workhorse and the spoken-approval prompt are told. One line of 1 to 64 characters without quotes, backslashes or braces. |
356
+ | `toolNamespaces` | `{ workhorse: "voice_workhorse", voice: "voice_channel", coordinator: "voice_coordinator" }` | The Codex tool namespaces of the built-in tools: the coordinator's workhorse tools, its spoken-approval tool, and the tool that a workhorse uses to reach the coordinator. Give all three. Each matches `^[a-z][a-z0-9_]{0,63}$`, and no two are the same. |
357
+ | `recordPrefix` | `"voice"` | The first part of every id that the agent creates and stores, as in `voice:<kind>:<token>`. It matches `^[a-z][a-z0-9-]{0,15}$`. A stored record keeps the prefix that it was written with. |
358
+
359
+ #### A `Bun.serve` server
360
+
361
+ `bunHandlers` takes these options. It throws a `TypeError` when `path`, or an `origin` that you give, can never admit a socket.
362
+
363
+ | Field | Default | What it does |
364
+ | ----------- | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
365
+ | `path` | Required | The socket path, such as `/voice`. It must start with `/`. A request that is not a socket upgrade on this path goes to `fetch`. |
366
+ | `fetch` | Answers `404` | Your handler of every other request. It receives the request and the server, as the `fetch` of `Bun.serve` does, and it can upgrade sockets of its own. |
367
+ | `websocket` | None | Your handlers of the sockets that your `fetch` upgrades. Bun has one handler set for each server, so the package tells its own sockets apart by their `data` and gives every other socket to these handlers. Their options, such as `maxPayloadLength`, apply to every socket of the server. When `backpressureLimit` makes Bun drop a frame to the page, the package closes that socket and the page reconnects. |
368
+ | `origin` | The origin of `server.url` | The HTTP origin of your server exactly, such as `http://127.0.0.1:4100`, with no path and no trailing slash. The default names the `hostname` that you gave `Bun.serve`, or `localhost` when you gave none, so a server on port `0` needs none. Give it when browsers reach the server by another name, as for a server on `0.0.0.0`, on a unix socket or behind a proxy. See [Security](#security). |
369
+ | `checkout` | The only listed checkout | The admitted checkout that every socket on this path works in. You must name it when the agent admits more than one checkout, or admits them with a function. |
370
+
371
+ When `fetch` upgrades sockets of its own, name the type of their `data`, as in `agent.bunHandlers<{ room: string }>({ path, fetch, websocket })`.
372
+
373
+ A socket that arrives before `start()` is ready is closed with `1011`. After `shutdown()`, the server answers an upgrade on `path` with `503`. To serve sockets again after a new `start()`, call `bunHandlers` again and give the result to `server.reload`.
374
+
375
+ #### A `node:http` server
376
+
377
+ `attach(server, options)` serves the sockets on a `node:http` server, such as one that Express or Node's `http` module makes. It takes the same `path` and `checkout`, and its `origin` is required. It applies the same checks as `bunHandlers`. Upgrades to other paths stay with the other `upgrade` listeners of the server, so a server with no other listener must end them itself. It throws a `TypeError` when `path` or `origin` can never admit a socket.
378
+
379
+ ```ts
380
+ agent.attach(server, { path: "/voice", origin: "http://127.0.0.1:4100" });
381
+ ```
382
+
383
+ ### `resolveCodexExecutable(options)`
384
+
385
+ `resolveCodexExecutable` finds the Codex executable and proves it before anything runs it. It must be an absolute path to a regular, executable file that reports exactly `codex-cli 0.166.0`. It never looks on `PATH`. It returns the absolute path, and throws a `CodexExecutableError` with a `code` when the proof fails.
386
+
387
+ | Field | Default | What it does |
388
+ | ---------------- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
389
+ | `executablePath` | The installed `@openai/codex` package | An absolute path to prove in place of the installed package. |
390
+ | `installedIn` | None | Refuses an installed `@openai/codex` that is not in `<installedIn>/node_modules`, such as a global install. It does not apply to `executablePath`. |
391
+ | `releasedIn` | None | For a host's compiled release: the platform package whose `@openai/codex-<os>-<cpu>` dependency holds the native binary. It does not apply to `executablePath`. |
392
+
393
+ ### `createVoiceClient(options)`
394
+
395
+ `createVoiceClient` makes the client of one chat. It opens nothing until you call `connect()`.
396
+
397
+ | Field | Default | What it does |
398
+ | ------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
399
+ | `socketPath` | Required | The socket path of the server, or a full URL. A path resolves against the page address. `http:` becomes `ws:` and `https:` becomes `wss:`. |
400
+ | `chatId` | `"main"` | The chat that this client shows. Use letters, digits, `_` and `-`, at most 128 characters. |
401
+
402
+ Every action returns a promise that resolves to `true` when the action completed and to `false` when it failed. The reason is then in `failure` of the state. Only one action runs at a time: an action that you call while another runs resolves to `false` at once and changes nothing. `stopVoice` and `stopWork` also run while another action runs. After `dispose()`, every action resolves to `false`.
403
+
404
+ | Action | What it does |
405
+ | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
406
+ | `connect()` | Opens the socket, or opens it again. After an open socket closes, the client opens a new one by itself. A first `connect()` whose socket never opens is not repeated: call it again. |
407
+ | `refresh()` | Reads the server state again without repeating a command. |
408
+ | `signIn(login?)` | Starts a sign-in. The default is the ChatGPT sign-in. `{ type: "apiKey", apiKey }` signs in with an API key. |
409
+ | `cancelSignIn()` | Cancels the pending sign-in. |
410
+ | `signOut()` | Signs the account out. |
411
+ | `send(message)` | Sends a message to the workhorse, and creates the conversation on first use. |
412
+ | `startVoice()` | Starts the coordinator's voice, and creates the conversation on first use. |
413
+ | `stopVoice()` | Stops voice. The workhorse keeps working. |
414
+ | `setMuted(muted)` | Mutes or unmutes the microphone of the running voice. |
415
+ | `stopWork()` | Interrupts the running workhorse turn. Voice keeps running. |
416
+ | `answerApproval(approval, response, intent)` | Answers one approval that the page showed, with the `intent` of the state that showed it. |
417
+ | `snapshot()` | Returns the current state. |
418
+ | `subscribe(listener)` | Calls the listener after each change of the state. Returns the function that stops it. |
419
+ | `dispose()` | Stops voice, releases the socket and ends every subscription. |
420
+
421
+ The state has these fields:
422
+
423
+ | Field | What it holds |
424
+ | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
425
+ | `connection` | `connected`, `reconnecting` or `stopped`. |
426
+ | `server` | What the server published last: the account, the sign-in, the workhorse timeline, approvals, the queue and the voice transcript. `null` before the first publication. |
427
+ | `voice` | The voice run: `phase`, `available` (a new voice run can start) and `problem` (why voice cannot start or why the last run failed). |
428
+ | `busy` | An action is running. |
429
+ | `failure` | Why the last action failed: `message` and `uncertain`. The next action clears it when it starts. |
430
+ | `intent` | The value to pass with an approval answer, or `null` while no answer can be sent. |
431
+
432
+ ### React
433
+
434
+ `VoiceClientProvider` takes a `client` and offers it to the components inside it. You connect and dispose the client yourself. A disposed client never connects again, so create the client outside React, as the quickstart does, or create one for each mount. Dispose it on `pagehide`, so a hidden page holds no socket and no microphone. When `pageshow` has `persisted: true`, the browser restored the page from its back-forward cache: create and connect a new client. The tab session id stays in `sessionStorage`, so the new client continues the conversation when the page comes back within 60 seconds. `useVoiceClient()` returns the client for its actions. `useVoiceState()` returns the whole state and renders again on each change. `useVoiceState(select)` returns one part and renders again only when that part changes. The selector runs once for each change of the state. Return a part of the state or a primitive value: a new object counts as a change, so the component then renders again on each change.
435
+
436
+ ## Security
437
+
438
+ The agent can run commands and change files in the admitted checkouts. Anyone who can use its socket can ask it to.
439
+
440
+ - Your server owns the listener. The package opens no port. Bind to `127.0.0.1`, as the quickstart does, unless you put your own authentication in front of the socket.
441
+ - `bunHandlers` and `attach` refuse a socket upgrade with `403` when the `Host` header is not the host of `origin`, or when the `Origin` header is present and is not exactly `origin`. This stops other web sites from opening the socket from a browser. A client that sends no `Origin` header, such as a local script, passes this check, so every process that can reach the port can drive the agent.
442
+ - A workhorse works only in an admitted checkout. The browser never chooses the checkout: `bunHandlers` and `attach` fix it for each socket path. The coordinator can delegate to every admitted checkout.
443
+ - Codex runs with a private `CODEX_HOME` in the state directory, never your own `~/.codex`. The package fixes its policy, and no option changes it: commands run in the `workspace-write` sandbox with network access, approvals are on request, and the approvals reviewer is `auto_review`. With `auto_review`, Codex gives an action that the sandbox refuses to a reviewer agent, which approves or denies it instead of asking the person.
444
+ - The Codex process receives only a fixed list of environment variables from your server: the user and shell (`HOME`, `USER`, `LOGNAME`, `SHELL`, `PATH`), the locale and time zone, the terminal, the temporary and XDG directories, the proxy and certificate variables, and `SSH_AUTH_SOCK`. Other variables, such as API keys, reach Codex only when you pass them in `codex.hostEnvironment`.
445
+ - An approval answer carries the `intent` of the state that showed it. The server refuses the answer when the conversation changed since. Speech alone never settles an approval: a spoken answer is classified and settled once, and an unclear answer goes back to the page.
446
+
447
+ The package never looks up Codex on `PATH`, never uses your personal Codex sign-in, never lets the browser choose a checkout, and never repeats an action whose result is unknown. It writes only in the state directory and in `storage.ownerDirectory`. Codex writes in the admitted checkouts under its sandbox.
448
+
449
+ ## Advanced hosting
450
+
451
+ ### Extensions
452
+
453
+ A host without a domain of its own passes no `extensions`. These fields add your own domain to the agent:
454
+
455
+ | Field | What it does |
456
+ | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
457
+ | `context` | What the coordinator is told about your application, as text. `read()` returns the current text, and `subscribe(onChange, onError)` calls `onChange` when the text changes. The coordinator receives the text as data, never as a request. The default lists the admitted checkouts. |
458
+ | `voice` | How voice starts: `start(narrative)` returns the voice `prompt`, `suppressCoordinatorSpeech` and `delegationAckFiller`. The optional `subscribe` sends extra speech or quiet context to the voice. `narrative` is the one the session presents, or null. The default is plain live voice. |
459
+ | `tools.coordinator`, `tools.workhorse` | Extra Codex dynamic tools for each role, in the `dynamicTools` shape of the Codex `thread/start` request. The package adds them after its own coordination tools. A tool cannot use a namespace of `identity.toolNamespaces`. |
460
+ | `domainTools` | The handler of your tools: `registrations` lists each namespace with the SHA-256 of its manifest, and `install(scope)` returns the domain whose `dispatch(request)` answers each call and whose `dispose()` cleans up. The agent installs it for each Codex process. |
461
+ | `contextCodec` | How execution context is encoded into the text that a thread reads. |
462
+ | `checkoutLabel` | The name that the workhorse list shows for a checkout. The default is the name of the checkout's directory. |
463
+ | `narrative` | The narrative that a voice session starts to present: JSON whose meaning is yours, which the media owner's `start(narrative)` sends as `realtimeStart.narrative`. `validate` refuses it before a running session changes, `prepare` turns it into the narrative the session presents, `opened` and `forget` follow the session. `unattended` says that nobody listens to the session live: the coordinator then gets no workhorse outcome, and the state that the server publishes shows `server.voice.unattended` as `true`. |
464
+
465
+ The remaining fields (`coordinatorContextFor`, `voiceFor`, `contextForOperation`, `onGeneration`, `onBrowserGateway`, `browserCheckoutOf`, `installBrowserSessions` and `browserLeaseLedger`) replace the package's own owners. They are for a host that routes its sockets itself.
466
+
467
+ The extension types are not exported by name. Derive them from `VoiceAgentExtensions`. This context source tells the coordinator what the person selected:
468
+
469
+ <!-- checked: context.ts -->
470
+
471
+ ```ts
472
+ import type { VoiceAgentExtensions } from "@archboard/codex-realtime-voice/server";
473
+
474
+ type ContextSource = NonNullable<VoiceAgentExtensions["context"]>;
475
+
476
+ let selected = "nothing";
477
+ const listeners = new Set<() => void>();
478
+
479
+ export const context: ContextSource = {
480
+ read: () => `The person has selected ${selected}.`,
481
+ subscribe: (onChange) => {
482
+ listeners.add(onChange);
483
+ return () => listeners.delete(onChange);
484
+ },
485
+ };
486
+
487
+ export function select(next: string): void {
488
+ selected = next;
489
+ for (const listener of listeners) listener();
490
+ }
491
+ ```
492
+
493
+ Pass it as `extensions: { context }` to `createVoiceAgent`.
494
+
495
+ ### Announcing a change
496
+
497
+ When something changes that the agents must know about, call `agent.announce(change)`. Import its input type, `ContextChange`, from `@archboard/codex-realtime-voice/server`. TypeScript infers the receipt types from the returned promise. The promise from `announce` rejects with a `TypeError` when the change is malformed, for example when it names no audience. It rejects with an `Error` while `agent.status()` does not read `ready`. The change names its audience: `workhorse` for the workhorses of some checkouts, `coordinator`, `voice`, or any combination. Each audience gets its own `text`, or `withheld` with the reason that you tell it nothing.
498
+
499
+ A workhorse gets the text as a developer message that starts no turn, also while a turn runs. Its `payload` is your own JSON data, which the context codec encodes with the execution facts. A payload that holds a function, a symbol, a bigint, a number that is not finite, a class instance or a cycle makes the change malformed. The coordinator gets the text as a developer message. The voice gets it as quiet context, or with `speech: true` as speech that waits for the audio in progress. The coordinator and the voice get a change only while voice is live.
500
+
501
+ A workhorse hears one `feed` and `sequence` at most once, and refuses a sequence that does not pass the last one of its feed. The coordinator and the voice keep no such promise: they answer a repeat with its first receipt only while it is among the last 64 deliveries of the tab. Give the thread that made the change as `author`: nobody hears their own change. By default every live tab session hears the change. Name `tabSessions` to limit it. The change counts as fresh for 30 seconds from `capturedAtMs`, which defaults to now and cannot be later than now. A workhorse is not told a change that went stale. While a change for the coordinator or the voice waits, a later change with the same `feed` and `topic` replaces it. The audiences are told at the same time, in no fixed order.
502
+
503
+ <!-- checked: announce.ts -->
504
+
505
+ ```ts
506
+ import type { VoiceAgent } from "@archboard/codex-realtime-voice/server";
507
+
508
+ let sequence = 0;
509
+
510
+ export async function fileSaved(agent: VoiceAgent, checkout: string, file: string): Promise<void> {
511
+ const receipts = await agent.announce({
512
+ feed: "editor",
513
+ sequence: sequence++,
514
+ workhorse: { checkouts: [checkout], text: `The person saved ${file}.` },
515
+ voice: { text: `${file} is saved.` },
516
+ });
517
+ for (const receipt of receipts) {
518
+ if (receipt.outcome !== "delivered") console.info(receipt.audience, receipt.reason);
519
+ }
520
+ }
521
+ ```
522
+
523
+ `announce` resolves with one receipt for each tab session and audience, and for each checkout of a workhorse. A receipt with `outcome_unknown` means that the message possibly arrived. The agent never sends it again.
524
+
525
+ A receipt for an audience that you told nothing has the reason `withheld`, unless a reason that is checked first applies, such as `voice_inactive` or `no_workhorse`. The receipt does not hold your reason text. The page does: each entry of `voiceContext.entries` in the state from `./contract` has a `withheld` field. For the coordinator and the voice, it holds the text that you gave as `withheld`, and it is `null` for every entry that has another reason. The agent cuts the text at 256 UTF-8 bytes and replaces each NUL character, so a long reason never stops the page from showing its state.
526
+
527
+ ### A host that owns its sockets
528
+
529
+ `bunHandlers` covers a `Bun.serve` server and `attach` a `node:http` server. A host that serves sockets in another way uses `agent.browser` on the server instead: `accept` registers a socket with its chat, tab session and checkout, `handle` passes each parsed request, `close` ends a socket, and `drain` waits for accepted work. The two adapters in the package source are the reference uses.
530
+
531
+ In the browser, `@archboard/codex-realtime-voice/controllers` holds the parts under `createVoiceClient`. Use them to draw your own conversation UI over a socket that you open: the transport and the media owner, the conversation controllers of one chat (the conversation link and sign-in, the composer with queue and steer, the queue and the approvals), and the conversation projected from the server timelines.
532
+
533
+ ### Entry points
534
+
535
+ | Entry | What it holds |
536
+ | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
537
+ | `./server` | `createVoiceAgent`, `resolveCodexExecutable` and their types. The remaining exports are lower-level parts for a host that routes its own sockets. A host that uses `bunHandlers` or `attach` needs none of them. |
538
+ | `./browser` | `createVoiceClient` and its types. |
539
+ | `./react` | `VoiceClientProvider`, `useVoiceClient` and `useVoiceState`. |
540
+ | `./controllers` | The transport, media and conversation parts under the client. |
541
+ | `./contract` | The types of the state that the server publishes, such as `BrowserSnapshot`, `BrowserApproval` and `BrowserTimeline`. |
542
+ | `./schemas` | The schemas of that state, for a server that extends it and for tests. |
543
+ | `./realtime` | The phases and transitions of a voice run. |
544
+ | `./runtime` | Lower-level runtime parts, such as coordinator callbacks and the realtime adapter. |
545
+
546
+ ## Troubleshooting
547
+
548
+ ### Codex reports another version
549
+
550
+ `resolveCodexExecutable` throws `CodexExecutableError` with code `wrong_version` and the message "The configured Codex executable reported an unexpected version; expected codex-cli 0.166.0." The executable it found is not Codex 0.166.0.
551
+
552
+ 1. Run `bun add @openai/codex@0.166.0` in your project.
553
+ 2. If you pass `executablePath`, make sure that it names a Codex 0.166.0 executable.
554
+
555
+ ### The Codex executable is not found
556
+
557
+ `resolveCodexExecutable` throws `CodexExecutableError`. Code `missing` means that `@openai/codex` is not installed where the package can find it, or that `executablePath` names no file. Code `not_absolute` means that `executablePath` is a relative path or a bare name: the package never looks on `PATH`. Code `version_unavailable` means that the executable did not run. With the installed package, the usual cause is that no `node` is on `PATH`.
558
+
559
+ 1. Run `bun add @openai/codex@0.166.0` in the project that runs the server. Package managers that skip peer dependencies leave it out.
560
+ 2. If you pass `executablePath`, give an absolute path.
561
+ 3. For `version_unavailable`, start the server with `bun run <script>`, or install Node.js.
562
+
563
+ ### The page asks for a sign-in
564
+
565
+ `server.account.state` is `signed_out`. The agent has its own Codex home, so the sign-in of your own Codex client does not count.
566
+
567
+ 1. Call `client.signIn()` and open `server.login.authUrl`.
568
+ 2. Finish the sign-in in a browser on the machine that runs the server. The ChatGPT sign-in returns to `http://127.0.0.1:1455` on that machine.
569
+ 3. If the page still shows the sign-in, call `client.refresh()`.
570
+
571
+ To sign in with an API key, call `client.signIn({ type: "apiKey", apiKey })`.
572
+
573
+ ### The microphone is denied
574
+
575
+ `voice.available` is `false` and `voice.problem` is "Microphone permission was denied." The browser refused the microphone.
576
+
577
+ 1. Allow the microphone for the page address in the browser's site settings.
578
+ 2. Call `client.connect()` or reload the page, then start voice again. After every failed voice start, `voice.available` stays `false` until the next `connect()`.
579
+
580
+ If `voice.problem` is "This browser cannot install realtime microphone and audio support.", the page has no microphone and WebRTC support. This happens when you open the page over `http` on an address that is not local. Open the page on `127.0.0.1`, `localhost` or `https`.
581
+
582
+ ### The socket is refused
583
+
584
+ The page shows "The voice connection failed. Reconnect to try again." and `connection` stays `stopped`. The browser's network panel shows the socket upgrade answered with `403`. The page address is not the socket's origin: the `origin` that you gave to `attach` or `bunHandlers`, or, when you gave `bunHandlers` none, the origin of `server.url`. For example, you opened `http://localhost:4100` and the origin is `http://127.0.0.1:4100`.
585
+
586
+ 1. Open the page at exactly the address in `origin`. When `bunHandlers` has no `origin` and the server runs on `0.0.0.0`, on a unix socket or behind a proxy, give it the `origin` that the browser uses.
587
+ 2. Serve the page and the socket from the same server. A page from a development server on another port has another origin.
588
+
589
+ A `400` answer means that the socket URL has no valid `tabSessionId` or `chatId`. `createVoiceClient` always sends both, so look at a custom `chatId`. A socket that closes at once with code `1011` puts the reason the server closed it with in `failure`, such as "The voice agent is unavailable. Restart the server.". It reached the server before `start()` resolved, after Codex failed, or on a path whose `checkout` the agent does not admit. The client opens a new socket by itself, as after any open socket that closes.
590
+
591
+ ### The state directory is in use
592
+
593
+ `start()` rejects with code `startup_failed`. Its `cause` is "Another server owns this Codex state at `<directory>/owner`. Stop the other owner (pid `<pid>`) before retrying." Another process runs an agent on the same state directory.
594
+
595
+ 1. Stop the process with that pid, or give each process its own `storage.directory`.
596
+ 2. Start again. A lock whose owner has exited is set aside by the next start.
597
+
598
+ The same rejection also names a state directory that the package cannot use:
599
+
600
+ - "must have mode 0700, received 0755": run `chmod 700` on the directory, or let the package create it.
601
+ - "Refusing symlink-escaped Codex storage path component": the path has a symbolic link that the package does not follow. That is the state directory itself, a directory below it, or a link above it that another user owns or could replace. `createVoiceAgent` follows a link above the state directory only when you or root own it and no other user can change the directories that lead to it, so a directory in `/tmp` or `os.tmpdir()` on macOS works. Give the state directory's real path, not a link in a shared directory.
602
+
603
+ ### Other errors from `createVoiceAgent`, `bunHandlers` and `attach`
604
+
605
+ - "A workbench role requires domain instructions.": an instruction is empty. Give text for both roles.
606
+ - A `TypeError` that starts with "A voice agent": an `identity` value has the wrong shape. The message names the rule.
607
+ - "Name an absolute socket path" or "Name the listener's own origin": `bunHandlers` or `attach` received a `path` without a leading `/`, or an `origin` with a path, a trailing slash or another scheme than `http` or `https`.
608
+ - "The allowed checkout `<path>` is not a readable directory.": a listed checkout does not exist. Create it or remove it from `checkouts`.
609
+ - "Name the checkout these sockets work in: the agent admits more than one.": pass `checkout` to `bunHandlers` or `attach`.
610
+
611
+ ### The page stays on reconnecting
612
+
613
+ `connection` reads `reconnecting` after an open socket closed, for example because the server stopped. The client opens a new socket by itself, and tries again every 3 seconds until one opens. The attempts leave the failure of an action as it is, so the failure of an action that the lost socket ended, such as an uncertain delivery, stays on the page. An attempt that opens clears the failure of a `connect` that did not open. If the server speaks a contract that this browser cannot read, the attempts stop: `connection` reads `stopped`, and `failure` says why unless it already holds another failure. Build the page with the same package version as the server, then reload the page.
614
+
615
+ 1. Make sure that the server runs and that `start()` resolved.
616
+ 2. If the server logs no error, look at the attempts in the browser's network panel. A `403` or `400` answer has the causes in [The socket is refused](#the-socket-is-refused).
617
+
618
+ A first `connect()` whose socket never opens is not repeated. The quickstart's "Connect" button calls it again.
619
+
620
+ ## License
621
+
622
+ MIT. See [LICENSE](LICENSE).