omp-superagent 0.1.1 → 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 (60) hide show
  1. package/DESIGN.md +189 -48
  2. package/README.ko.md +30 -16
  3. package/README.md +39 -20
  4. package/THIRD_PARTY_NOTICES.md +81 -6
  5. package/docs/OPERATIONS.md +178 -30
  6. package/docs/discord-voice.md +96 -0
  7. package/docs/releases/0.1.2.md +53 -0
  8. package/package.json +13 -7
  9. package/scripts/ci.ts +10 -5
  10. package/scripts/release.ts +14 -6
  11. package/scripts/test-omp.sh +36 -0
  12. package/skills/head/SKILL.md +82 -241
  13. package/skills/head/references/model-selection.md +81 -261
  14. package/skills/head/references/routing.md +179 -354
  15. package/skills/head/references/supervision.md +120 -310
  16. package/skills/lane/SKILL.md +53 -175
  17. package/skills/lane/references/workflow.md +93 -347
  18. package/src/cli.ts +96 -10
  19. package/src/codex-live-bridge.py +73 -0
  20. package/src/codex-live.ts +244 -0
  21. package/src/codex-voice-requirements.txt +5 -0
  22. package/src/codex_live_auth.py +192 -0
  23. package/src/codex_live_media.py +219 -0
  24. package/src/codex_live_provider.py +192 -0
  25. package/src/config.ts +77 -2
  26. package/src/contracts.ts +70 -6
  27. package/src/decision-tool.ts +59 -0
  28. package/src/decisions.ts +143 -0
  29. package/src/delivery.ts +10 -0
  30. package/src/discord-context.ts +118 -0
  31. package/src/discord-voice-draft.ts +124 -0
  32. package/src/discord-voice-link.ts +270 -0
  33. package/src/discord-voice.ts +150 -0
  34. package/src/discord.ts +312 -45
  35. package/src/extension.ts +178 -21
  36. package/src/gateway-client.ts +11 -4
  37. package/src/gateway-server.ts +52 -4
  38. package/src/gateway-store.ts +16 -2
  39. package/src/gateway.ts +27 -11
  40. package/src/host-broker-services.ts +108 -0
  41. package/src/host-extension.ts +159 -47
  42. package/src/host-owner.ts +16 -0
  43. package/src/host-protocol.ts +9 -1
  44. package/src/host-services.ts +54 -0
  45. package/src/host.ts +3 -2
  46. package/src/installed-omp.ts +34 -26
  47. package/src/lane-extension.ts +5 -0
  48. package/src/lane-rows.ts +12 -0
  49. package/src/messengers.ts +38 -9
  50. package/src/native-presets.ts +91 -3
  51. package/src/native-settings.ts +3 -1
  52. package/src/openai-live.ts +377 -0
  53. package/src/pr-github-schema.ts +110 -0
  54. package/src/pr-github.ts +170 -0
  55. package/src/pr-watch.ts +200 -0
  56. package/src/runtime.ts +419 -54
  57. package/src/slack.ts +14 -11
  58. package/src/store.ts +86 -30
  59. package/src/telegram.ts +28 -12
  60. package/scripts/check-omp.ts +0 -4
@@ -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
@@ -0,0 +1,192 @@
1
+ """Local Codex managed-login RPC. No thread, turn, login, or tool request is sent."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import json
7
+ import os
8
+ import re
9
+ import shutil
10
+ import tempfile
11
+ import time
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from subprocess import DEVNULL, PIPE
15
+ from typing import Final, Literal
16
+ from urllib.parse import urlsplit
17
+
18
+ import anyio
19
+ from anyio.abc import ByteSendStream
20
+ from anyio.streams.buffered import BufferedByteReceiveStream
21
+ from pydantic import BaseModel, ConfigDict, Field, SecretStr
22
+
23
+ MAX_RPC_BYTES: Final = 256 * 1024
24
+ JWT: Final = re.compile(r"[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\Z")
25
+ ACCOUNT_ID: Final = re.compile(r"[A-Za-z0-9_-]{1,128}\Z")
26
+ SUBSCRIPTION_PLANS: Final = frozenset({
27
+ "go", "plus", "pro", "prolite", "promax", "team", "business", "enterprise",
28
+ "edu", "edu_plus", "edu_pro", "ent26", "self_serve_business_prolite",
29
+ "self_serve_business_usage_based", "enterprise_cbp_automation",
30
+ "enterprise_cbp_usage_based", "sci", "sci_plus",
31
+ })
32
+
33
+
34
+ class CodexLoginError(RuntimeError):
35
+ """A managed subscription login could not be safely resolved."""
36
+
37
+
38
+ class ManagedAccount(BaseModel):
39
+ model_config = ConfigDict(frozen=True, strict=True)
40
+ type: Literal["chatgpt"]
41
+ plan_type: str = Field(alias="planType")
42
+ email: str | None
43
+ workspace_name: str | None = Field(default=None, alias="workspaceName")
44
+
45
+
46
+ class WorkspaceRouting(BaseModel):
47
+ model_config = ConfigDict(frozen=True, strict=True)
48
+ backend_origin: str = Field(alias="backendOrigin")
49
+ account_routing_override: Literal["NO_CONSTRAINT"] | None = Field(default=None, alias="accountRoutingOverride")
50
+ chatgpt_account_id: str = Field(alias="chatgptAccountId")
51
+
52
+
53
+ class AccountResponse(BaseModel):
54
+ model_config = ConfigDict(frozen=True, strict=True)
55
+ account: ManagedAccount
56
+ requires_openai_auth: Literal[True] = Field(alias="requiresOpenaiAuth")
57
+ workspace_routing: WorkspaceRouting | None = Field(default=None, alias="workspaceRouting")
58
+ user_id: str | None = Field(default=None, alias="userId")
59
+
60
+
61
+ class AuthStatus(BaseModel):
62
+ model_config = ConfigDict(frozen=True, strict=True)
63
+ auth_method: Literal["chatgpt"] = Field(alias="authMethod")
64
+ auth_token: SecretStr = Field(alias="authToken")
65
+ requires_openai_auth: Literal[True] = Field(alias="requiresOpenaiAuth")
66
+
67
+
68
+ class AccountClaim(BaseModel):
69
+ model_config = ConfigDict(frozen=True, strict=True)
70
+ chatgpt_account_id: str = Field(min_length=1, max_length=128)
71
+ chatgpt_user_id: str | None = None
72
+
73
+
74
+ class ProfileClaim(BaseModel):
75
+ model_config = ConfigDict(frozen=True, strict=True)
76
+ email: str | None = None
77
+
78
+
79
+ class JwtClaims(BaseModel):
80
+ model_config = ConfigDict(frozen=True, strict=True)
81
+ exp: int
82
+ auth: AccountClaim = Field(alias="https://api.openai.com/auth")
83
+ profile: ProfileClaim | None = Field(default=None, alias="https://api.openai.com/profile")
84
+
85
+
86
+ @dataclass(frozen=True, slots=True)
87
+ class CodexLogin:
88
+ token: SecretStr
89
+ account_id: SecretStr
90
+
91
+
92
+ class RpcMessage(BaseModel):
93
+ model_config = ConfigDict(frozen=True, strict=True)
94
+ id: int | str | None = None
95
+ method: str | None = None
96
+ result: dict[str, str | int | bool | dict[str, str | int | bool | None] | None] | None = None
97
+
98
+
99
+ type RpcParams = dict[str, str | bool | dict[str, str]]
100
+
101
+
102
+ async def rpc(
103
+ streams: tuple[ByteSendStream, BufferedByteReceiveStream],
104
+ request_id: int,
105
+ message: tuple[str, RpcParams],
106
+ ) -> RpcMessage:
107
+ send, receive = streams
108
+ method, params = message
109
+ await send.send((json.dumps({"id": request_id, "method": method, "params": params}) + "\n").encode())
110
+ for _ in range(64):
111
+ frame = await receive.receive_until(b"\n", MAX_RPC_BYTES)
112
+ reply = RpcMessage.model_validate_json(frame)
113
+ if reply.id is None and reply.method is not None:
114
+ continue # Unsolicited notifications have no effect.
115
+ if reply.id == request_id and reply.method is None and reply.result is not None:
116
+ return reply
117
+ break # No server-initiated requests or raw error payloads.
118
+ raise CodexLoginError("Unexpected Codex managed-login response.")
119
+
120
+
121
+ async def read_codex_login() -> CodexLogin:
122
+ # Never resolve the auth broker (or a wrapper's interpreter) from a project
123
+ # PATH, including absolute node_modules/.bin entries injected by Bun.
124
+ paths = [str(Path.home() / ".local" / "bin"), "/opt/homebrew/bin", "/usr/local/bin",
125
+ *[entry for entry in os.defpath.split(os.pathsep) if os.path.isabs(entry)]]
126
+ executable = next((match for path in paths if (match := shutil.which(str(Path(path) / "codex")))), None)
127
+ if not executable:
128
+ raise CodexLoginError("Codex CLI is not installed.")
129
+ env = {
130
+ key: value for key in (
131
+ "HOME", "CODEX_HOME", "SYSTEMROOT", "USERPROFILE", "LOCALAPPDATA", "TMPDIR", "TEMP", "TMP",
132
+ ) if (value := os.environ.get(key))
133
+ }
134
+ env["PATH"] = os.pathsep.join(paths)
135
+ env["RUST_LOG"] = "off"
136
+ # Avoid project configuration and do not start/resume a Codex thread. The CLI
137
+ # still owns its usual login/keyring and any managed organization policy.
138
+ with tempfile.TemporaryDirectory(prefix="omp-codex-voice-") as empty_directory:
139
+ process = await anyio.open_process(
140
+ [executable, "app-server", "--listen", "stdio://",
141
+ "-c", "analytics.enabled=false"],
142
+ cwd=empty_directory, env=env, stdin=PIPE, stdout=PIPE, stderr=DEVNULL,
143
+ )
144
+ try:
145
+ if process.stdin is None or process.stdout is None:
146
+ raise CodexLoginError("Codex local authentication pipes are unavailable.")
147
+ streams = process.stdin, BufferedByteReceiveStream(process.stdout)
148
+ with anyio.fail_after(8):
149
+ await rpc(streams, 1, ("initialize", {
150
+ "clientInfo": {"name": "omp-superagent-voice", "version": "1"},
151
+ }))
152
+ await process.stdin.send(b'{"method":"initialized"}\n')
153
+ request = ("account/read", {"refreshToken": False})
154
+ account = AccountResponse.model_validate((await rpc(streams, 2, request)).result)
155
+ if account.account.plan_type not in SUBSCRIPTION_PLANS:
156
+ raise CodexLoginError("A ChatGPT subscription is required.")
157
+ route = account.workspace_routing
158
+ if route:
159
+ origin = urlsplit(route.backend_origin)
160
+ if (origin.scheme != "https" or origin.netloc != "chatgpt.com"
161
+ or origin.path not in ("", "/") or origin.query or origin.fragment):
162
+ raise CodexLoginError("The Codex workspace requires a different backend origin.")
163
+ status = AuthStatus.model_validate((await rpc(streams, 3, ("getAuthStatus", {
164
+ "includeToken": True, "refreshToken": False,
165
+ }))).result)
166
+ confirmed = AccountResponse.model_validate((await rpc(streams, 4, request)).result)
167
+ if confirmed != account:
168
+ raise CodexLoginError("The active Codex account changed during voice startup.")
169
+ token = status.auth_token.get_secret_value()
170
+ if len(token) > 32_768 or not JWT.fullmatch(token):
171
+ raise CodexLoginError("Invalid Codex managed login.")
172
+ payload = token.split(".")[1]
173
+ claims = JwtClaims.model_validate_json(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
174
+ identity = claims.auth.chatgpt_account_id
175
+ email = account.account.email
176
+ if (claims.exp <= time.time() or not ACCOUNT_ID.fullmatch(identity)
177
+ or (route and route.chatgpt_account_id != identity)
178
+ or (account.user_id and claims.auth.chatgpt_user_id and account.user_id != claims.auth.chatgpt_user_id)
179
+ or (email and claims.profile and claims.profile.email and email.casefold() != claims.profile.email.casefold())):
180
+ raise CodexLoginError("The Codex managed login is expired or does not match the active account.")
181
+ # The provider verifies the JWT and determines the account's actual voice entitlement.
182
+ return CodexLogin(status.auth_token, SecretStr(identity))
183
+ finally:
184
+ with anyio.CancelScope(shield=True):
185
+ if process.returncode is None:
186
+ if process.stdin is not None:
187
+ await process.stdin.aclose()
188
+ with anyio.move_on_after(0.5):
189
+ await process.wait()
190
+ if process.returncode is None:
191
+ process.kill()
192
+ await process.aclose()