omp-superagent 0.0.0-stage → 0.1.2

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.
Files changed (97) hide show
  1. package/DESIGN.md +1502 -0
  2. package/LICENSE +21 -0
  3. package/README.ko.md +198 -0
  4. package/README.md +224 -2
  5. package/THIRD_PARTY_NOTICES.md +388 -0
  6. package/assets/architecture.mmd +24 -0
  7. package/assets/architecture.svg +126 -0
  8. package/assets/superagent-avatar.jpg +0 -0
  9. package/assets/superagent-mascot.webp +0 -0
  10. package/config.example.json +26 -0
  11. package/docs/OPERATIONS.md +1178 -0
  12. package/docs/discord-voice.md +96 -0
  13. package/docs/releases/0.1.0.md +222 -0
  14. package/docs/releases/0.1.1.md +60 -0
  15. package/docs/releases/0.1.2.md +53 -0
  16. package/package.json +65 -4
  17. package/scripts/ci.ts +33 -0
  18. package/scripts/prepare-ulw.ts +18 -0
  19. package/scripts/release.ts +58 -0
  20. package/scripts/setup.sh +25 -0
  21. package/scripts/test-omp.sh +36 -0
  22. package/skills/head/SKILL.md +100 -0
  23. package/skills/head/references/model-selection.md +83 -0
  24. package/skills/head/references/routing.md +181 -0
  25. package/skills/head/references/supervision.md +122 -0
  26. package/skills/lane/SKILL.md +66 -0
  27. package/skills/lane/references/workflow.md +95 -0
  28. package/src/autostart.ts +295 -0
  29. package/src/board-extension.ts +217 -0
  30. package/src/board.ts +396 -0
  31. package/src/cli.ts +253 -0
  32. package/src/codex-live-bridge.py +73 -0
  33. package/src/codex-live.ts +244 -0
  34. package/src/codex-voice-requirements.txt +5 -0
  35. package/src/codex_live_auth.py +192 -0
  36. package/src/codex_live_media.py +219 -0
  37. package/src/codex_live_provider.py +192 -0
  38. package/src/config.ts +266 -0
  39. package/src/contracts.ts +381 -0
  40. package/src/credentials.ts +172 -0
  41. package/src/decision-tool.ts +59 -0
  42. package/src/decisions.ts +143 -0
  43. package/src/delivery.ts +17 -0
  44. package/src/dialog.ts +73 -0
  45. package/src/discord-command-registration.ts +201 -0
  46. package/src/discord-commands.ts +29 -0
  47. package/src/discord-context.ts +118 -0
  48. package/src/discord-markdown.ts +172 -0
  49. package/src/discord-voice-draft.ts +124 -0
  50. package/src/discord-voice-link.ts +270 -0
  51. package/src/discord-voice.ts +150 -0
  52. package/src/discord.ts +1012 -0
  53. package/src/extension.ts +446 -0
  54. package/src/gateway-client.ts +229 -0
  55. package/src/gateway-protocol.ts +85 -0
  56. package/src/gateway-restart.ts +151 -0
  57. package/src/gateway-server.ts +440 -0
  58. package/src/gateway-store.ts +251 -0
  59. package/src/gateway.ts +654 -0
  60. package/src/head-recovery.ts +61 -0
  61. package/src/host-broker-services.ts +108 -0
  62. package/src/host-extension.ts +561 -0
  63. package/src/host-owner.ts +366 -0
  64. package/src/host-protocol.ts +144 -0
  65. package/src/host-services.ts +54 -0
  66. package/src/host.ts +415 -0
  67. package/src/installed-omp.ts +71 -0
  68. package/src/lane-extension.ts +184 -0
  69. package/src/lane-models.ts +75 -0
  70. package/src/lane-report.ts +70 -0
  71. package/src/lane-rows.ts +12 -0
  72. package/src/managed-ulw-probe.ts +172 -0
  73. package/src/managed-ulw.ts +471 -0
  74. package/src/message-order.ts +21 -0
  75. package/src/messenger-commands.ts +16 -0
  76. package/src/messengers.ts +143 -0
  77. package/src/native-presets.ts +370 -0
  78. package/src/native-sessions.ts +32 -0
  79. package/src/native-settings.ts +131 -0
  80. package/src/openai-live.ts +377 -0
  81. package/src/pr-github-schema.ts +110 -0
  82. package/src/pr-github.ts +170 -0
  83. package/src/pr-watch.ts +200 -0
  84. package/src/repository.ts +12 -0
  85. package/src/runtime.ts +4229 -0
  86. package/src/setup-judge.ts +34 -0
  87. package/src/setup-memory.ts +39 -0
  88. package/src/setup-profiles.ts +84 -0
  89. package/src/setup.ts +300 -0
  90. package/src/slack-command-registration.ts +217 -0
  91. package/src/slack-commands.ts +18 -0
  92. package/src/slack.ts +779 -0
  93. package/src/store.ts +862 -0
  94. package/src/telegram-command-registration.ts +155 -0
  95. package/src/telegram.ts +677 -0
  96. package/src/workflow.ts +94 -0
  97. package/upstream/ulw.json +9 -0
package/src/cli.ts ADDED
@@ -0,0 +1,253 @@
1
+ #!/usr/bin/env -S bun --no-env-file
2
+ import { Database } from "bun:sqlite";
3
+ import { existsSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { configuredPlatforms, credentialEnvNames, hostPaths, loadConfig, requireMessengerCredentials } from "./config";
6
+ import { inspectInstalledOmp } from "./installed-omp";
7
+ import { loadCredentials } from "./credentials";
8
+ import type { Lane } from "./contracts";
9
+ import { readLaneRows } from "./lane-rows";
10
+ import { setup } from "./setup";
11
+
12
+ // Lifecycle imports below must stay lazy: static Gateway/Host imports execute
13
+ // OMP's dotenv loader before setup/doctor/command registration select credential sources.
14
+ const HELP = `omp-sa — messenger-connected OMP head and independent topic sessions
15
+
16
+ Usage:
17
+ omp-sa --help (also: omp-sa help)
18
+ omp-sa setup --config FILE
19
+ omp-sa start --config FILE
20
+ omp-sa install --config FILE
21
+ omp-sa uninstall --config FILE
22
+ omp-sa status --config FILE
23
+ omp-sa stop [main|LANE_ID] --config FILE
24
+ omp-sa doctor --config FILE
25
+ omp-sa discord-commands --config FILE [--apply]
26
+ omp-sa telegram-commands --config FILE [--language CODE] [--apply]
27
+ omp-sa slack-commands --config FILE --manifest-token-env NAME [--apply]
28
+
29
+ Setup and service lifecycle:
30
+ setup creates FILE interactively, or preserves an existing FILE and prompts for its configured credentials.
31
+ It saves a private FILE.env and sets configured Discord/Telegram bot profile pictures through REST; it does not start bots.
32
+ On first setup only, you may opt into native Mnemopi memory. If no native Judge model is configured,
33
+ setup explains how to select one in ordinary OMP (/models > Roles > Judge); it does not choose a model for you.
34
+ doctor validates configuration, checks the installed OMP and reports credential presence, not successful login.
35
+ start launches a detached Gateway and one HEAD, activating ALL configured messengers. No autostart is installed.
36
+ start can return before HEAD can accept work. Check head.ready and head.initialization in the start response
37
+ (gateway.head in status); initial high/middle/low model presets must be verified before queued work runs.
38
+ status shows live Gateway/HEAD readiness when reachable, login launcher status, and saved lane IDs, models and states.
39
+ A saved lane state does not prove its Host is running or that the work completed.
40
+ stop main shuts down the Gateway and HEAD; a busy Host can refuse. Bare CLI stop also targets main.
41
+ stop LANE_ID requests shutdown of just that managed lane Host. It does not delete the lane or its session.
42
+ install enables macOS per-user startup at future login only; requires configured messenger credentials in private FILE.env
43
+ and native settings/authentication under the OS account home. No immediate start or shell environment capture.
44
+ uninstall removes only the owned login launcher; it does not stop an existing Gateway/head or remove credentials/state.
45
+
46
+ Add a messenger to an existing installation:
47
+ Edit FILE: keep existing blocks and add the desired top-level block with the fields below.
48
+ discord tokenEnv, ownerId, allowedGuildIds[], allowedChannelIds[]
49
+ telegram tokenEnv, ownerId, allowedChatIds[]
50
+ slack botTokenEnv, appTokenEnv, ownerId, teamId, allowedChannelIds[]
51
+ Copy the block shape from ${join(import.meta.dir, "../config.example.json")}.
52
+ Use string IDs for the same trusted owner on each platform. Credential fields name variables, never tokens.
53
+ Supply their values in the Gateway environment or private FILE.env (mode 0600). Run doctor before activation.
54
+ Editing FILE does not reload a running service. The next Gateway start activates all configured blocks.
55
+ Other FILE settings: command (stock OMP argv), headCwd, stateDir, maxHosts (includes HEAD),
56
+ maxSubagents (shared budget), idleMs (idle lane eviction), optional model (HEAD startup model).
57
+
58
+ Command registration:
59
+ discord-commands uses Discord REST only: dry-run by default, with no Gateway or native runtime activation.
60
+ --apply exclusively replaces this dedicated bot's GLOBAL commands with supported Superagent commands, deleting obsolete registrations (including Hermes). Guild commands are preserved; shadowing conflicts refuse apply.
61
+ telegram-commands configures owner-scoped Telegram command menus; --language selects an optional Telegram language code.
62
+ slack-commands configures /superagent-* commands through the app manifest; NAME identifies an app-configuration token environment variable, never a token argument.
63
+ All command registration is read-only by default and requires --apply to change remote configuration. No polling, Socket Mode, or native model session is started.
64
+ Running a Host requires an installed stock OMP with stdio RPC (rpc-ui), session resume, and extensions.
65
+ Same-process native TUI attach is not supported.
66
+
67
+ Owner controls in chat (not shell commands):
68
+ Send /help in Discord or Telegram. In Slack messages replace / with ! (e.g. !help, !status);
69
+ registered Slack commands use /superagent-* (e.g. /superagent-status).
70
+ /status, /context, /usage Inspect HEAD state, context or usage without starting a model turn.
71
+ /model [list|provider/id] Inspect or select the shared HEAD model; changes require an idle HEAD.
72
+ /model preset [list|NAME] Inspect or select a preset. Only NAME --global also saves future defaults.
73
+ /effort [LEVEL] Inspect or change HEAD thinking effort; existing lanes keep their settings.
74
+ /compact [instructions] Compact idle HEAD context, optionally with multiline instructions.
75
+ /new [request], /main Start a topic or return to the main topic in the owner's DM.
76
+ /stop [head|LANE_ID] Stop HEAD work or pause a lane, NOT the service. With no argument, pause
77
+ the lane bound to this chat, or stop HEAD work if there is no bound lane.
78
+ /resume Resume the lane bound to this chat, not HEAD.
79
+ /restart Safely replace Gateway and HEAD while preserving the session; no forced kill
80
+ or automatic prompt replay. Independent lane Hosts stay running.
81
+ /resolve [INPUT_ID] Close one uncertain HEAD input without retrying it. Use /status to find its ID;
82
+ the ID is required if several are held. This does not establish task success.
83
+
84
+ Capabilities to request from HEAD in chat (not CLI subcommands):
85
+ Lanes and threads: ask HEAD to start, inspect, steer, pause, resume or close an independent lane,
86
+ select its model/preset, or inspect and update its Discord thread or forum tags.
87
+ PR monitoring: give HEAD a GitHub PR URL and check interval to watch reviews and CI; ask to list or stop watches.
88
+ Requires gh with read access. A change notification does not authorize a merge or a new task.
89
+ Decisions: ask HEAD to request an owner decision, list pending decisions, inspect one or withdraw it.
90
+ Discord channel context: ask HEAD to inspect channel/thread context or set, list or clear a local purpose
91
+ note. Notes do not edit Discord's channel description or authorize work.
92
+ Shared board: registered HEAD and lane sessions can post, read and subscribe to informational updates
93
+ within this instance. Board posts are not commands or approvals.
94
+ Workflows: begin a request with ulw, ulw-plan, ulw-execute, ulw-loop, ulw-research or mass-ulw.
95
+ For batch judging against one rubric, begin with lowercase jevify (not /jevify).
96
+ Operations guide and native tool names: ${join(import.meta.dir, "../docs/OPERATIONS.md")}
97
+
98
+ Add Discord voice using a Codex subscription (optional; no API key or paid fallback):
99
+ In FILE, set discord.voice to the object below. Preserve the existing discord owner, token and allowlists.
100
+ Replace the IDs with Discord snowflakes (strings). Both channels must be in an allowed guild;
101
+ restrict the voice channel to the owner and bot, and include the text channel in discord.allowedChannelIds.
102
+ {"auth":"subscription","channelId":"VOICE_CHANNEL_ID","textChannelId":"TEXT_CHANNEL_ID","voice":"cove","maxSessionSeconds":300}
103
+ Do not include apiKeyEnv, model or backendModel in this object.
104
+
105
+ As the OS user running the Gateway (macOS/Linux):
106
+ codex login # Sign in with an eligible ChatGPT account, not an API key.
107
+ VENV="$HOME/.local/share/omp-superagent/codex-voice"
108
+ uv venv --python 3.12 "$VENV" # First-time setup only.
109
+ uv pip install --python "$VENV/bin/python" -r ${Bun.$.escape(join(import.meta.dir, "codex-voice-requirements.txt"))}
110
+ omp-sa doctor --config FILE # Checks config without connecting; does not verify voice entitlement.
111
+ The next Gateway start loads the change. Configuration alone does not start a call.
112
+
113
+ Alternative: Discord voice with separately billed OpenAI Live API (no Codex login or Python bridge):
114
+ Use the same channel allowlists. Set discord.voice to an API object instead of the subscription object:
115
+ {"auth":"api","channelId":"VOICE_CHANNEL_ID","textChannelId":"TEXT_CHANNEL_ID","voice":"marin","maxSessionSeconds":300,"model":"gpt-live-1","backendModel":"gpt-6-luna","apiKeyEnv":"SUPERAGENT_VOICE_OPENAI_KEY"}
116
+ Choose models and a voice available to your account. Put the key in the named environment variable or FILE.env,
117
+ not in JSON; never reuse a messenger token. Omitting auth selects the existing API mode, not subscription.
118
+
119
+ Owner commands are ordinary Discord messages in the configured text channel, not CLI or registered slash commands:
120
+ /voice start Join the configured voice channel first, then send this to open the call.
121
+ /voice share Subscription only: allow one draft to be posted here within one minute. API mode posts drafts directly.
122
+ /voice confirm Reply to the exact posted draft to submit it to HEAD. Separate approvals still apply.
123
+ /voice stop End the call.
124
+ Full guide: ${join(import.meta.dir, "../docs/discord-voice.md")}
125
+ `;
126
+
127
+ function laneRows(stateDir: string): Lane[] {
128
+ const path = join(stateDir, "coordination.sqlite");
129
+ if (!existsSync(path)) return [];
130
+ const db = new Database(path, { readonly: true });
131
+ try {
132
+ return readLaneRows(db);
133
+ } finally { db.close(); }
134
+ }
135
+
136
+ export async function main(args = process.argv.slice(2)): Promise<void> {
137
+ if (!args.length || args.includes("--help") || args[0] === "help") { console.log(HELP); return; }
138
+ const [command] = args;
139
+ if (!["setup", "start", "install", "uninstall", "status", "stop", "doctor", "discord-commands", "telegram-commands", "slack-commands"].includes(command!)) throw new Error(`Unknown command: ${command}`);
140
+ const configAt = args.indexOf("--config");
141
+ if (configAt < 0 || !args[configAt + 1]) throw new Error("--config FILE is required");
142
+ if (command === "install" || command === "uninstall") {
143
+ if (args.length !== 3 || configAt !== 1 || args[2]!.startsWith("-"))
144
+ throw new Error(`Usage: ${command} --config FILE`);
145
+ const config = await loadConfig(args[2]!);
146
+ const { installAutostart, uninstallAutostart } = await import("./autostart");
147
+ console.log(JSON.stringify(await (command === "install" ? installAutostart(config) : uninstallAutostart(config)), null, 2));
148
+ return;
149
+ }
150
+ if (command === "setup") { await setup(args[configAt + 1]!); return; }
151
+ if (command === "discord-commands" || command === "telegram-commands" || command === "slack-commands") {
152
+ const extra = command === "telegram-commands" ? " [--language CODE]"
153
+ : command === "slack-commands" ? " --manifest-token-env NAME" : "";
154
+ const usage = `Usage: ${command} --config FILE${extra} [--apply]`;
155
+ const valueFlags = new Set(["--config", ...(command === "telegram-commands" ? ["--language"]
156
+ : command === "slack-commands" ? ["--manifest-token-env"] : [])]);
157
+ const values = new Map<string, string>();
158
+ let apply = false;
159
+ for (let index = 1; index < args.length; index++) {
160
+ const flag = args[index]!;
161
+ if (flag === "--apply" && !apply) { apply = true; continue; }
162
+ const value = args[index + 1];
163
+ if (!valueFlags.has(flag) || values.has(flag) || !value || value.startsWith("-")) throw new Error(usage);
164
+ values.set(flag, value);
165
+ index++;
166
+ }
167
+ const configPath = values.get("--config");
168
+ const manifestTokenEnv = values.get("--manifest-token-env");
169
+ if (!configPath || command === "slack-commands" && !manifestTokenEnv) throw new Error(usage);
170
+ const config = await loadConfig(configPath);
171
+ let report: unknown;
172
+ if (command === "discord-commands") {
173
+ const { registerDiscordCommands } = await import("./discord-command-registration");
174
+ report = await registerDiscordCommands(config, { apply });
175
+ } else if (command === "telegram-commands") {
176
+ const { registerTelegramCommands } = await import("./telegram-command-registration");
177
+ report = await registerTelegramCommands(config, { apply, languageCode: values.get("--language") });
178
+ } else {
179
+ const { registerSlackCommands } = await import("./slack-command-registration");
180
+ report = await registerSlackCommands(config, { apply, manifestTokenEnv: manifestTokenEnv! });
181
+ }
182
+ console.log(JSON.stringify(report, null, 2));
183
+ if (report && typeof report === "object" && "status" in report && report.status === "blocked") process.exitCode = 1;
184
+ return;
185
+ }
186
+ const config = await loadConfig(args[configAt + 1]!);
187
+ const target = args[1] && !args[1]!.startsWith("-") ? args[1]! : "main";
188
+ const paths = hostPaths(config, target);
189
+ if (command === "doctor") {
190
+ loadCredentials(config);
191
+ const omp = await inspectInstalledOmp(config.command, credentialEnvNames(config));
192
+ console.log(JSON.stringify({
193
+ config: config.path, command: config.command, headCwd: config.headCwd,
194
+ omp, nativeTuiAttach: false,
195
+ maxHosts: config.maxHosts, maxSubagents: config.maxSubagents,
196
+ platforms: configuredPlatforms(config),
197
+ credentials: Object.fromEntries(credentialEnvNames(config).map(name => [name, Boolean(process.env[name])])),
198
+ messengersActivated: false,
199
+ }, null, 2));
200
+ return;
201
+ }
202
+ if (command === "status") {
203
+ const { gatewayStatus } = await import("./gateway-protocol");
204
+ const { autostartStatus } = await import("./autostart");
205
+ console.log(JSON.stringify({
206
+ gateway: await gatewayStatus(config),
207
+ autostart: await autostartStatus(config),
208
+ main: { socketPath: hostPaths(config, "main").socketPath },
209
+ lanes: laneRows(config.stateDir).map(l => ({
210
+ id: l.id, title: l.title, cwd: l.cwd, workState: l.workState,
211
+ model: l.model, modelReason: l.modelReason, modelPreset: l.modelPreset,
212
+ recordedRuntimeState: l.runtimeState, sessionId: l.sessionId, socketPath: l.socketPath,
213
+ })),
214
+ note: "Gateway/head readiness is live when the Gateway is reachable; lane records are not a completion guarantee.",
215
+ }, null, 2));
216
+ return;
217
+ }
218
+ if (target !== "main" && !laneRows(config.stateDir).some(l => l.id === target))
219
+ throw new Error("Unknown managed lane");
220
+ if (command === "stop") {
221
+ if (target === "main") {
222
+ const { stopGateway } = await import("./gateway");
223
+ await stopGateway(config);
224
+ console.log("Gateway and supervised main host accepted graceful shutdown.");
225
+ return;
226
+ }
227
+ const { connect } = await import("./host");
228
+ const host = await connect(paths.socketPath);
229
+ try {
230
+ const response = await host.request({ type: "shutdown_host" });
231
+ if (!response.success) throw new Error(response.error ?? "Host refused shutdown");
232
+ console.log(`Host ${target} accepted graceful shutdown.`);
233
+ } finally { await host.close(); }
234
+ return;
235
+ }
236
+ if (target !== "main") throw new Error("start only activates the Gateway/main service; lanes remain head-owned");
237
+ loadCredentials(config);
238
+ // Resolve required messenger credentials before native imports can populate env
239
+ // from their own project/provider configuration. Other native settings stay native.
240
+ requireMessengerCredentials(config);
241
+ const { gatewayPaths, launchGateway } = await import("./gateway");
242
+ const status = await launchGateway(config);
243
+ console.log(JSON.stringify({ ...status, gatewaySocketPath: gatewayPaths(config).socketPath,
244
+ gatewayLogPath: gatewayPaths(config).logPath,
245
+ note: "Gateway owns messenger transports. Explicit start may return while initialization is checking/running or blocked. head.ready requires verified native high/middle/low presets; head.initialization reports setup/recovery state separately from approval-reconciled intake readiness. Ordinary input remains durably queued until initialization completes." }, null, 2));
246
+ }
247
+
248
+ if (import.meta.main) {
249
+ await main().catch(error => {
250
+ console.error(error instanceof Error ? error.message : String(error));
251
+ process.exitCode = 1;
252
+ });
253
+ }
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env python3
2
+ # The Gateway runs this with the Python environment installed from codex-voice-requirements.txt.
3
+ # The Bun adapter owns the private stdin/stdout pipes; the bridge is not a CLI.
4
+
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import logging
9
+ import sys
10
+ from functools import partial
11
+ from typing import Final
12
+
13
+ import anyio
14
+ from anyio.abc import ObjectSendStream
15
+
16
+ from codex_live_auth import read_codex_login
17
+ from codex_live_media import COMMANDS, BridgeEvent, Command, run_peer
18
+ from codex_live_provider import VOICES, BridgeError, connect_subscription
19
+
20
+ MAX_LINE: Final = 65_536
21
+
22
+
23
+ def emit(event: BridgeEvent) -> None:
24
+ sys.stdout.write(json.dumps(event, ensure_ascii=True, separators=(",", ":")) + "\n")
25
+ sys.stdout.flush()
26
+
27
+
28
+ async def read_commands(send: ObjectSendStream[Command], scope: anyio.CancelScope) -> None:
29
+ async with send:
30
+ while True:
31
+ line = await anyio.to_thread.run_sync(sys.stdin.buffer.readline, MAX_LINE + 1, abandon_on_cancel=True)
32
+ if not line or line == b'{"type":"stop"}\n':
33
+ scope.cancel()
34
+ return
35
+ if len(line) > MAX_LINE or not line.endswith(b"\n"):
36
+ raise BridgeError("Invalid voice bridge command frame.")
37
+ await send.send(COMMANDS.validate_json(line))
38
+
39
+
40
+ async def run(voice: str) -> None:
41
+ if voice not in VOICES:
42
+ raise BridgeError("Unsupported Codex subscription voice.")
43
+ send, commands = anyio.create_memory_object_stream[Command](16)
44
+ async with commands, anyio.create_task_group() as tasks:
45
+ tasks.start_soon(read_commands, send, tasks.cancel_scope)
46
+ try:
47
+ login = await read_codex_login()
48
+ negotiate = partial(connect_subscription, voice=voice, login=login)
49
+ await run_peer(negotiate, (commands, emit), (login.token, login.account_id))
50
+ finally:
51
+ tasks.cancel_scope.cancel()
52
+
53
+
54
+ def main() -> None:
55
+ # Dependency exceptions can include response bodies, SDP or headers.
56
+ # The parent sees only this closed event or EOF, never raw diagnostics.
57
+ logging.disable(logging.CRITICAL)
58
+ exit_status = 0
59
+ try:
60
+ if len(sys.argv) != 2:
61
+ raise BridgeError("Codex voice needs a voice identifier.")
62
+ anyio.run(run, sys.argv[1])
63
+ except Exception: # Top-level subprocess trust boundary: fail closed without exposing wire data.
64
+ exit_status = 1
65
+ try:
66
+ emit({"type": "ended"})
67
+ except BrokenPipeError:
68
+ sys.exit(exit_status) # The parent already stopped reading.
69
+ sys.exit(exit_status)
70
+
71
+
72
+ if __name__ == "__main__":
73
+ main()
@@ -0,0 +1,244 @@
1
+ import { spawn } from "node:child_process";
2
+ import { homedir } from "node:os";
3
+ import { isAbsolute, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import type { openLive } from "./openai-live";
6
+
7
+ const BRIDGE = fileURLToPath(new URL("./codex-live-bridge.py", import.meta.url));
8
+ const START_TIMEOUT_MS = 45_000;
9
+ const FORWARD_TIMEOUT_MS = 10_000;
10
+ const MAX_INPUT_BYTES = 24_000; // Half a second of 24 kHz mono PCM16.
11
+ const MAX_LINE_CHARS = 64 * 1024;
12
+ const MAX_PIPE_BYTES = 64 * 1024;
13
+ const MAX_DRAFTS = 32;
14
+ const MAX_DRAFT_CHARS = 1_000;
15
+ const RECENT_SPEECH_MS = 20_000;
16
+ const SPEECH_GAP_MS = 200;
17
+ const VOICES = new Set(["arbor", "breeze", "cove", "ember", "juniper", "maple", "sol", "spruce", "vale"]);
18
+
19
+ type LiveHandlers = Parameters<typeof openLive>[1];
20
+ type LiveSession = Awaited<ReturnType<typeof openLive>>;
21
+ type BridgeCommand =
22
+ | { readonly type: "input"; readonly audio: string }
23
+ | { readonly type: "draft_result"; readonly id: string; readonly posted: boolean }
24
+ | { readonly type: "notify" }
25
+ | { readonly type: "stop" };
26
+
27
+ class CodexLiveError extends Error {
28
+ override readonly name = "CodexLiveError";
29
+ }
30
+
31
+ function record(value: unknown): value is Record<string, unknown> {
32
+ return value !== null && typeof value === "object" && !Array.isArray(value);
33
+ }
34
+
35
+ export async function openCodexLive(
36
+ options: { readonly voice: string }, handlers: LiveHandlers, signal: AbortSignal,
37
+ ): Promise<LiveSession> {
38
+ if (signal.aborted) throw new CodexLiveError("Codex voice startup was cancelled.");
39
+ if (!VOICES.has(options.voice)) throw new CodexLiveError("Unsupported Codex subscription voice.");
40
+ const home = homedir();
41
+ const python = process.env.OMP_SA_CODEX_VOICE_PYTHON ??
42
+ join(home, ".local", "share", "omp-superagent", "codex-voice",
43
+ ...(process.platform === "win32" ? ["Scripts", "python.exe"] : ["bin", "python"]));
44
+ if (!isAbsolute(python)) throw new CodexLiveError("Codex voice needs an absolute Python interpreter path.");
45
+
46
+ // Do not inherit Discord, Responses, FYI, Python injection, or proxy variables.
47
+ const env: NodeJS.ProcessEnv = { HOME: home };
48
+ const codexHome = process.env.CODEX_HOME;
49
+ if (codexHome !== undefined) {
50
+ if (!isAbsolute(codexHome)) throw new CodexLiveError("CODEX_HOME must be absolute when selecting a subscription profile.");
51
+ env.CODEX_HOME = codexHome;
52
+ }
53
+ for (const key of ["SYSTEMROOT", "USERPROFILE", "LOCALAPPDATA", "TMPDIR", "TEMP", "TMP"]) {
54
+ const value = process.env[key];
55
+ if (value && isAbsolute(value)) env[key] = value;
56
+ }
57
+ const processGroup = process.platform !== "win32";
58
+ const child = spawn(python, ["-E", "-s", "-B", "-u", BRIDGE, options.voice], {
59
+ cwd: home, env, stdio: ["pipe", "pipe", "ignore"], detached: processGroup, windowsHide: true,
60
+ });
61
+ const ready = Promise.withResolvers<LiveSession>();
62
+ let phase: "starting" | "active" | "closing" | "closed" = "starting";
63
+ let closeDeadline: ReturnType<typeof setTimeout> | undefined;
64
+ let draftDeadline: ReturnType<typeof setTimeout> | undefined;
65
+ let lastSpeech = -Infinity;
66
+ let utterance = 0;
67
+ let draftedUtterance = 0;
68
+ let pendingDraft: string | undefined;
69
+ const seen = new Set<string>();
70
+ let line = "";
71
+ const decoder = new TextDecoder("utf-8", { fatal: true });
72
+
73
+ function finish(reason: string): void {
74
+ if (phase === "closed") return;
75
+ const wasStarting = phase === "starting";
76
+ phase = "closed";
77
+ clearTimeout(startDeadline);
78
+ clearTimeout(draftDeadline);
79
+ signal.removeEventListener("abort", abort);
80
+ pendingDraft = undefined;
81
+ seen.clear();
82
+ line = "";
83
+ child.stdout.destroy();
84
+ child.stdin.end();
85
+ // EOF cancels the bridge task group, including a pending Codex auth probe.
86
+ closeDeadline = setTimeout(() => {
87
+ if (processGroup && child.pid && child.exitCode === null && child.signalCode === null) {
88
+ try {
89
+ process.kill(-child.pid, "SIGKILL");
90
+ } catch {
91
+ child.kill("SIGKILL");
92
+ }
93
+ } else child.kill("SIGKILL");
94
+ }, 3_000);
95
+ if (wasStarting) ready.reject(new CodexLiveError(reason));
96
+ else handlers.ended();
97
+ }
98
+
99
+ function send(command: BridgeCommand): boolean {
100
+ const payload = `${JSON.stringify(command)}\n`;
101
+ if (child.stdin.destroyed || child.stdin.writableLength + Buffer.byteLength(payload) > MAX_PIPE_BYTES) {
102
+ finish("Codex voice bridge input is unavailable or congested.");
103
+ return false;
104
+ }
105
+ child.stdin.write(payload);
106
+ return true;
107
+ }
108
+
109
+ function abort(): void {
110
+ if (phase === "starting") {
111
+ finish("Codex voice startup was cancelled.");
112
+ } else if (phase === "active") {
113
+ phase = "closing";
114
+ send({ type: "stop" });
115
+ finish("Codex voice stopped.");
116
+ }
117
+ }
118
+
119
+ const session: LiveSession = {
120
+ input(pcm) {
121
+ if (phase !== "active" || !pcm.length) return;
122
+ if (pcm.length > MAX_INPUT_BYTES || pcm.length % 2) {
123
+ finish("Invalid Codex voice PCM input.");
124
+ return;
125
+ }
126
+ let squares = 0;
127
+ for (let index = 0; index < pcm.length; index += 2) squares += pcm.readInt16LE(index) ** 2;
128
+ if (squares >= (pcm.length / 2) * 256 ** 2) {
129
+ const now = performance.now();
130
+ if (now - lastSpeech >= SPEECH_GAP_MS) {
131
+ utterance++;
132
+ try {
133
+ handlers.interrupt();
134
+ } catch {
135
+ finish("Codex voice interruption callback failed.");
136
+ return;
137
+ }
138
+ }
139
+ lastSpeech = now;
140
+ }
141
+ if (phase === "active") send({ type: "input", audio: pcm.toString("base64") });
142
+ },
143
+ notifyHeadReply() {
144
+ if (phase === "active") {
145
+ // A notification is never itself a new owner request. Do not reuse speech
146
+ // from before the notification if it prompts the model to delegate.
147
+ draftedUtterance = utterance;
148
+ send({ type: "notify" });
149
+ }
150
+ },
151
+ close: abort,
152
+ };
153
+
154
+ async function postDraft(id: string, text: string): Promise<void> {
155
+ pendingDraft = id;
156
+ draftedUtterance = utterance;
157
+ draftDeadline = setTimeout(() => finish("Codex voice draft forwarding timed out."), FORWARD_TIMEOUT_MS);
158
+ let posted = false;
159
+ try {
160
+ await handlers.forward(text);
161
+ posted = true;
162
+ } catch {
163
+ // A failed delivery may be ambiguous. Do not disclose details or retry it.
164
+ posted = false;
165
+ } finally {
166
+ clearTimeout(draftDeadline);
167
+ }
168
+ if (phase !== "active" || pendingDraft !== id) return;
169
+ pendingDraft = undefined;
170
+ send({ type: "draft_result", id, posted });
171
+ }
172
+
173
+ function handleEvent(frame: string): void {
174
+ const event: unknown = JSON.parse(frame);
175
+ if (!record(event)) throw new CodexLiveError("Invalid Codex voice bridge event.");
176
+ if (event.type === "ended") {
177
+ finish("Codex subscription voice is unavailable or ended.");
178
+ return;
179
+ }
180
+ if (event.type === "ready" && phase === "starting") {
181
+ clearTimeout(startDeadline);
182
+ phase = "active";
183
+ ready.resolve(session);
184
+ return;
185
+ }
186
+ if (phase !== "active") throw new CodexLiveError("Unexpected Codex voice bridge event before readiness.");
187
+ switch (event.type) {
188
+ case "audio": {
189
+ if (typeof event.audio !== "string") break;
190
+ const pcm = Buffer.from(event.audio, "base64");
191
+ if (pcm.length && pcm.length <= MAX_INPUT_BYTES && pcm.length % 2 === 0 &&
192
+ pcm.toString("base64") === event.audio) {
193
+ handlers.audio(pcm);
194
+ return;
195
+ }
196
+ break;
197
+ }
198
+ case "draft": {
199
+ const { id, text } = event;
200
+ if (typeof id !== "string" || !/^[A-Za-z0-9_-]{1,128}$/.test(id) || typeof text !== "string" ||
201
+ text !== text.trim() || !text || text.length > MAX_DRAFT_CHARS) break;
202
+ if (seen.has(id)) return;
203
+ if (seen.size >= MAX_DRAFTS) throw new CodexLiveError("Codex voice draft limit exceeded.");
204
+ seen.add(id);
205
+ if (pendingDraft || draftedUtterance === utterance || performance.now() - lastSpeech > RECENT_SPEECH_MS) {
206
+ send({ type: "draft_result", id, posted: false });
207
+ return;
208
+ }
209
+ void postDraft(id, text);
210
+ return;
211
+ }
212
+ }
213
+ throw new CodexLiveError("Invalid Codex voice bridge event.");
214
+ }
215
+
216
+ const startDeadline = setTimeout(() => finish("Codex voice startup timed out."), START_TIMEOUT_MS);
217
+ child.stdout.on("data", (chunk: Buffer) => {
218
+ if (child.stdout.destroyed || phase === "closed") return;
219
+ try {
220
+ line += decoder.decode(chunk, { stream: true });
221
+ let index: number;
222
+ while ((index = line.indexOf("\n")) >= 0) {
223
+ if (index > MAX_LINE_CHARS) throw new CodexLiveError("Codex voice bridge frame exceeded its limit.");
224
+ const frame = line.slice(0, index);
225
+ line = line.slice(index + 1);
226
+ handleEvent(frame);
227
+ if (child.stdout.destroyed) return;
228
+ }
229
+ if (line.length > MAX_LINE_CHARS) throw new CodexLiveError("Codex voice bridge frame exceeded its limit.");
230
+ } catch {
231
+ finish("Invalid Codex voice bridge event or callback failure.");
232
+ }
233
+ });
234
+ child.once("error", () => finish("Could not start the Codex voice bridge; install the optional runtime."));
235
+ child.stdin.on("error", () => finish("Codex voice bridge input closed."));
236
+ child.stdout.on("error", () => finish("Codex voice bridge output closed."));
237
+ child.once("close", () => {
238
+ finish("Codex voice bridge disconnected.");
239
+ clearTimeout(closeDeadline);
240
+ });
241
+ signal.addEventListener("abort", abort, { once: true });
242
+ if (signal.aborted) abort();
243
+ return ready.promise;
244
+ }
@@ -0,0 +1,5 @@
1
+ aiortc==1.16.0
2
+ anyio==4.16.0
3
+ httpx2[http2,brotli,zstd]==2.16.2
4
+ pydantic==2.14.3
5
+ websockets==17.4