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
@@ -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()
@@ -0,0 +1,219 @@
1
+ """Paced 24 kHz mono PCM16 over one aiortc peer and an ordered control stream."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import sys
7
+ from collections.abc import Callable
8
+ from contextlib import AbstractAsyncContextManager, AsyncExitStack
9
+ from fractions import Fraction
10
+ from typing import Final, Literal, NotRequired, Protocol, TypedDict, assert_never
11
+
12
+ import anyio
13
+ import av
14
+ from aiortc import AudioStreamTrack, MediaStreamTrack, RTCConfiguration, RTCPeerConnection, RTCSessionDescription
15
+ from aiortc.mediastreams import MediaStreamError
16
+ from anyio.abc import ObjectReceiveStream
17
+ from pydantic import BaseModel, ConfigDict, Field, SecretStr, TypeAdapter
18
+
19
+ from codex_live_provider import DRAFT_ID, BridgeError, SpeechSink, append_speech, delegation_event
20
+
21
+ PCM_HZ: Final = 24_000
22
+ FRAME_SAMPLES: Final = 480
23
+ FRAME_BYTES: Final = FRAME_SAMPLES * 2
24
+ MAX_PCM: Final = 24_000
25
+ MAX_DRAFTS: Final = 32
26
+ REPLY_NOTICE: Final = "A reply from HEAD is available in the Discord text channel."
27
+ POSTED: Final = "A draft was posted for written confirmation. Nothing was submitted or executed."
28
+ NOT_POSTED: Final = "The client did not confirm posting a draft. Do not retry; check the text channel. Nothing was submitted or executed."
29
+ NO_TEXT: Final = "No clear draft text was provided. If the owner explicitly requested a draft, ask them to restate it."
30
+
31
+
32
+ class Input(BaseModel):
33
+ model_config = ConfigDict(frozen=True, strict=True, extra="forbid")
34
+ type: Literal["input"]
35
+ audio: str = Field(min_length=4, max_length=32_000)
36
+
37
+
38
+ class DraftResult(BaseModel):
39
+ model_config = ConfigDict(frozen=True, strict=True, extra="forbid")
40
+ type: Literal["draft_result"]
41
+ id: str = Field(max_length=128)
42
+ posted: bool
43
+
44
+
45
+ class Notify(BaseModel):
46
+ model_config = ConfigDict(frozen=True, strict=True, extra="forbid")
47
+ type: Literal["notify"]
48
+
49
+
50
+ type Command = Input | DraftResult | Notify
51
+ COMMANDS: Final = TypeAdapter(Command)
52
+
53
+
54
+ class BridgeEvent(TypedDict):
55
+ type: Literal["ready", "audio", "draft", "ended"]
56
+ audio: NotRequired[str]
57
+ id: NotRequired[str]
58
+ text: NotRequired[str]
59
+
60
+
61
+ class Sideband(SpeechSink, Protocol):
62
+ async def recv(self) -> str | bytes: ...
63
+
64
+
65
+ type Negotiate = Callable[[str], AbstractAsyncContextManager[tuple[str, Sideband]]]
66
+ type Emit = Callable[[BridgeEvent], None]
67
+
68
+
69
+ class PcmInputTrack(AudioStreamTrack):
70
+ """Keep a bounded queue and emit one frame per 20 ms, including silence."""
71
+
72
+ def __init__(self) -> None:
73
+ super().__init__()
74
+ self.pending = bytearray()
75
+ self.pts = 0
76
+ self.deadline: float | None = None
77
+
78
+ def append(self, data: bytes) -> None:
79
+ if not data or len(data) % 2 or len(self.pending) + len(data) > MAX_PCM:
80
+ raise BridgeError("Invalid or congested voice PCM input.")
81
+ self.pending.extend(data)
82
+
83
+ async def recv(self) -> av.AudioFrame:
84
+ if self.readyState != "live":
85
+ raise MediaStreamError
86
+ deadline = self.deadline if self.deadline is not None else anyio.current_time()
87
+ await anyio.sleep_until(deadline)
88
+ if self.readyState != "live":
89
+ raise MediaStreamError
90
+ # Anchor to the audio clock. Adding 20 ms to each actual wake-up would
91
+ # accumulate scheduler jitter until continuous owner speech filled the queue.
92
+ self.deadline = max(deadline + FRAME_SAMPLES / PCM_HZ, anyio.current_time())
93
+ frame = av.AudioFrame(format="s16", layout="mono", samples=FRAME_SAMPLES)
94
+ plane = frame.planes[0]
95
+ count = min(FRAME_BYTES, len(self.pending))
96
+ plane.update(bytes(self.pending[:count]) + bytes(plane.buffer_size - count))
97
+ del self.pending[:count]
98
+ frame.sample_rate = PCM_HZ
99
+ frame.time_base = Fraction(1, PCM_HZ)
100
+ frame.pts = self.pts
101
+ self.pts += FRAME_SAMPLES
102
+ return frame
103
+
104
+ def stop(self) -> None:
105
+ self.pending.clear()
106
+ super().stop()
107
+
108
+
109
+ async def play_remote_audio(track: MediaStreamTrack, active: anyio.Event, emit: Emit) -> None:
110
+ output = av.AudioResampler(format="s16", layout="mono", rate=PCM_HZ)
111
+ await active.wait()
112
+ while True:
113
+ frame = await track.recv()
114
+ if not isinstance(frame, av.AudioFrame):
115
+ raise BridgeError("OpenAI returned an unexpected media frame.")
116
+ for chunk in output.resample(frame):
117
+ pcm = bytes(chunk.planes[0])[:chunk.samples * 2]
118
+ if pcm:
119
+ emit({"type": "audio", "audio": base64.b64encode(pcm).decode("ascii")})
120
+
121
+
122
+ async def run_peer(
123
+ negotiate: Negotiate, ports: tuple[ObjectReceiveStream[Command], Emit], secrets: tuple[SecretStr, ...],
124
+ ) -> None:
125
+ """Negotiate media, process only one local command surface and project safe events."""
126
+ commands, emit = ports
127
+ if sys.byteorder != "little":
128
+ raise BridgeError("Codex voice PCM requires a little-endian host.")
129
+ peer = RTCPeerConnection(RTCConfiguration(iceServers=[]))
130
+ track = PcmInputTrack()
131
+ peer.addTrack(track)
132
+ connected, remote_audio, started, active = anyio.Event(), anyio.Event(), anyio.Event(), anyio.Event()
133
+ seen: set[str] = set()
134
+ pending: set[str] = set()
135
+ stack = AsyncExitStack()
136
+ try:
137
+ async with anyio.create_task_group() as tasks:
138
+ @peer.on("connectionstatechange")
139
+ def connection_changed() -> None:
140
+ if peer.connectionState == "connected":
141
+ connected.set()
142
+ elif peer.connectionState in ("failed", "closed"):
143
+ tasks.cancel_scope.cancel()
144
+
145
+ @peer.on("track")
146
+ def track_received(remote: MediaStreamTrack) -> None:
147
+ if remote.kind != "audio" or remote_audio.is_set():
148
+ tasks.cancel_scope.cancel()
149
+ return
150
+ remote_audio.set()
151
+ tasks.start_soon(play_remote_audio, remote, active, emit)
152
+
153
+ async def receive_control(sideband: Sideband) -> None:
154
+ while True:
155
+ raw = await sideband.recv()
156
+ kind, item = delegation_event(raw)
157
+ if kind == "session.started":
158
+ started.set()
159
+ elif kind in ("error", "session.closed"):
160
+ tasks.cancel_scope.cancel()
161
+ return
162
+ if not item or item.type != "delegation" or item.target != "client":
163
+ continue
164
+ identifier = item.id
165
+ if not DRAFT_ID.fullmatch(identifier):
166
+ raise BridgeError("Malformed voice draft identifier.")
167
+ text = item.draft_text()
168
+ # The compact event can precede a rich delegation.created with the same ID.
169
+ if kind == "session.delegation.created" and not text:
170
+ continue
171
+ if identifier in seen:
172
+ continue
173
+ if len(seen) >= MAX_DRAFTS:
174
+ raise BridgeError("Codex voice draft limit exceeded.")
175
+ seen.add(identifier)
176
+ if (not active.is_set() or not text or len(text.encode("utf-16-le")) > 2_000
177
+ or any(secret.get_secret_value() in text for secret in secrets)):
178
+ await append_speech(sideband, NO_TEXT, identifier)
179
+ continue
180
+ pending.add(identifier)
181
+ emit({"type": "draft", "id": identifier, "text": text})
182
+
183
+ with anyio.fail_after(35):
184
+ await peer.setLocalDescription(await peer.createOffer())
185
+ offer = peer.localDescription
186
+ if offer is None:
187
+ raise BridgeError("No local Codex voice media offer.")
188
+ answer, sideband = await stack.enter_async_context(negotiate(offer.sdp))
189
+ tasks.start_soon(receive_control, sideband)
190
+ await peer.setRemoteDescription(RTCSessionDescription(sdp=answer, type="answer"))
191
+ await started.wait()
192
+ await connected.wait()
193
+ await remote_audio.wait()
194
+ if peer.connectionState != "connected":
195
+ raise BridgeError("Codex voice media disconnected during startup.")
196
+ emit({"type": "ready"})
197
+ active.set()
198
+ async for command in commands:
199
+ match command:
200
+ case Input(audio=audio):
201
+ pcm = base64.b64decode(audio, validate=True)
202
+ if base64.b64encode(pcm).decode("ascii") != audio:
203
+ raise BridgeError("Invalid Codex voice input encoding.")
204
+ track.append(pcm)
205
+ case DraftResult(id=identifier, posted=posted):
206
+ if identifier not in pending:
207
+ raise BridgeError("Uncorrelated voice draft result.")
208
+ pending.remove(identifier)
209
+ await append_speech(sideband, POSTED if posted else NOT_POSTED, identifier)
210
+ case Notify():
211
+ await append_speech(sideband, REPLY_NOTICE)
212
+ case _ as unreachable:
213
+ assert_never(unreachable)
214
+ tasks.cancel_scope.cancel()
215
+ finally:
216
+ track.stop()
217
+ with anyio.move_on_after(1.5, shield=True):
218
+ await peer.close()
219
+ await stack.aclose()
@@ -0,0 +1,192 @@
1
+ """Subscription-only Quicksilver WebRTC signaling and client-delegation vocabulary."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import socket
8
+ import uuid
9
+ from collections.abc import AsyncIterator
10
+ from contextlib import asynccontextmanager
11
+ from typing import Final, Protocol
12
+ from urllib.parse import urlsplit
13
+
14
+ import anyio
15
+ import httpx2
16
+ from pydantic import BaseModel, ConfigDict, Field
17
+ from websockets.asyncio.client import ClientConnection, connect
18
+
19
+ from codex_live_auth import CodexLogin
20
+
21
+ CALL_URL: Final = "https://chatgpt.com/backend-api/codex/realtime/calls?intent=quicksilver&architecture=avas"
22
+ CONTROL_URL: Final = "wss://api.openai.com/v1/live"
23
+ VOICES: Final = frozenset({"arbor", "breeze", "cove", "ember", "juniper", "maple", "sol", "spruce", "vale"})
24
+ MAX_SDP: Final = 256 * 1024
25
+ MAX_EVENT_BYTES: Final = 256 * 1024
26
+ CALL_ID: Final = re.compile(r"(?:rtc_[A-Za-z0-9_-]{1,128}|[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12})\Z")
27
+ DRAFT_ID: Final = re.compile(r"[A-Za-z0-9_-]{1,128}\Z")
28
+ INSTRUCTIONS: Final = (
29
+ "You are the owner's Discord voice assistant. Speak briefly in the owner's language. "
30
+ "Answer ordinary conversation directly and be honest about uncertainty. "
31
+ "Delegate only when the owner's fresh spoken request clearly asks to propose a task to HEAD. "
32
+ "Put one concise, self-contained draft in the client delegation input_text, in the owner's language. "
33
+ "Never derive a new delegation from your own speech, notices, or delegation results. "
34
+ "Client delegation can only post a draft for written confirmation. Voice never approves, submits, or executes work. "
35
+ "Before dictating a work draft, the owner must type /voice share in the bound Discord text channel to allow one draft to be posted there. "
36
+ "Never claim a draft was posted without an explicit client result saying so."
37
+ )
38
+
39
+
40
+ class BridgeError(RuntimeError):
41
+ """An unsafe or failed subscription voice operation."""
42
+
43
+
44
+ class NoRedirectConnection(connect):
45
+ """Do not transfer authorization or the account header to a redirected host."""
46
+
47
+ def process_redirect(self, exc: Exception) -> Exception:
48
+ return exc
49
+
50
+
51
+ class SpeechSink(Protocol):
52
+ async def send(self, message: str) -> None: ...
53
+
54
+
55
+ class ContentPart(BaseModel):
56
+ model_config = ConfigDict(frozen=True, strict=True)
57
+ type: str
58
+ text: str | None = Field(default=None, max_length=1_000)
59
+
60
+
61
+ class Delegation(BaseModel):
62
+ model_config = ConfigDict(frozen=True, strict=True)
63
+ id: str
64
+ type: str
65
+ target: str
66
+ content: tuple[ContentPart, ...] = Field(default=(), max_length=16)
67
+
68
+ def draft_text(self) -> str:
69
+ return "".join(part.text or "" for part in self.content if part.type == "input_text").strip()
70
+
71
+
72
+ class ProviderEvent(BaseModel):
73
+ model_config = ConfigDict(frozen=True, strict=True)
74
+ type: str
75
+
76
+
77
+ class DelegationEvent(ProviderEvent):
78
+ item: Delegation | None = None
79
+ delegation: Delegation | None = None
80
+
81
+
82
+ def valid_sdp(sdp: str) -> bool:
83
+ lines = sdp.splitlines()
84
+ return (
85
+ 0 < len(sdp.encode()) <= MAX_SDP and "\0" not in sdp and bool(lines)
86
+ and lines[0] == "v=0"
87
+ and len([line for line in lines if line.startswith("m=")]) == 1
88
+ and any(line.startswith("m=audio ") for line in lines)
89
+ )
90
+
91
+
92
+ def call_id(headers: httpx2.Headers) -> str:
93
+ candidate = headers.get("openai-session-id")
94
+ location = headers.get("location")
95
+ if location:
96
+ parsed = urlsplit(location)
97
+ if (
98
+ len(location) > 512 or parsed.scheme not in ("", "https") or parsed.query or parsed.fragment
99
+ or parsed.netloc not in ("", "api.openai.com", "chatgpt.com")
100
+ ):
101
+ raise BridgeError("Invalid OpenAI call location.")
102
+ location_id = parsed.path.rstrip("/").split("/")[-1]
103
+ if not CALL_ID.fullmatch(location_id) or (candidate and candidate != location_id):
104
+ raise BridgeError("Invalid OpenAI call identifier.")
105
+ candidate = location_id
106
+ if not candidate or not CALL_ID.fullmatch(candidate):
107
+ raise BridgeError("No OpenAI call identifier was provided.")
108
+ return candidate
109
+
110
+
111
+ @asynccontextmanager
112
+ async def connect_subscription(
113
+ offer: str, voice: str, login: CodexLogin,
114
+ ) -> AsyncIterator[tuple[str, ClientConnection]]:
115
+ if voice not in VOICES or not valid_sdp(offer):
116
+ raise BridgeError("Invalid Codex subscription voice offer.")
117
+ token, account = login.token.get_secret_value(), login.account_id.get_secret_value()
118
+ headers = {
119
+ "Authorization": f"Bearer {token}",
120
+ "chatgpt-account-id": account,
121
+ "OpenAI-Alpha": "quicksilver=v2", # Protocol selector, not a client identity or entitlement.
122
+ **{name: str(uuid.uuid4()) for name in ("session-id", "thread-id", "x-session-id")},
123
+ }
124
+ transport = httpx2.AsyncHTTPTransport(
125
+ http2=True, trust_env=False, retries=0,
126
+ socket_options=[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)],
127
+ limits=httpx2.Limits(max_connections=1, max_keepalive_connections=0),
128
+ )
129
+ async with httpx2.AsyncClient(
130
+ transport=transport, trust_env=False, follow_redirects=False,
131
+ timeout=httpx2.Timeout(connect=5, read=24, write=10, pool=5),
132
+ ) as client:
133
+ async with client.stream("POST", CALL_URL, headers={**headers, "Accept-Encoding": "identity"}, json={
134
+ "sdp": offer,
135
+ "session": {
136
+ "model": "gpt-live-1-codex",
137
+ "instructions": INSTRUCTIONS,
138
+ "audio": {"output": {"voice": voice}},
139
+ "delegation": {"type": "client"},
140
+ },
141
+ }) as response:
142
+ if response.status_code not in (200, 201):
143
+ raise BridgeError("OpenAI declined subscription voice access.")
144
+ identifier = call_id(response.headers)
145
+ data = bytearray()
146
+ async for chunk in response.aiter_raw():
147
+ if len(data) + len(chunk) > MAX_SDP:
148
+ raise BridgeError("OpenAI voice answer exceeded its size limit.")
149
+ data.extend(chunk)
150
+ answer = data.decode("utf-8")
151
+ if not valid_sdp(answer) or token in answer or account in answer:
152
+ raise BridgeError("Invalid OpenAI voice answer.")
153
+
154
+ connection = await NoRedirectConnection(
155
+ f"{CONTROL_URL}/{identifier}", additional_headers=headers, proxy=None,
156
+ open_timeout=8, close_timeout=0.5, ping_interval=15, ping_timeout=10,
157
+ max_size=MAX_EVENT_BYTES, max_queue=16, compression=None,
158
+ )
159
+ try:
160
+ yield answer, connection
161
+ finally:
162
+ with anyio.move_on_after(1, shield=True):
163
+ try:
164
+ if connection.state.name == "OPEN":
165
+ await connection.send('{"type":"session.close"}')
166
+ finally:
167
+ await connection.close()
168
+
169
+
170
+ async def append_speech(connection: SpeechSink, text: str, draft_id: str | None = None) -> None:
171
+ data = {
172
+ "type": "delegation.context.append" if draft_id else "session.context.append",
173
+ "channel": "speakable",
174
+ "content": [{"type": "input_text", "text": text}],
175
+ }
176
+ if draft_id:
177
+ data["delegation_item_id"] = draft_id
178
+ with anyio.fail_after(3):
179
+ await connection.send(json.dumps(data))
180
+
181
+
182
+ def delegation_event(raw: str | bytes) -> tuple[str, Delegation | None]:
183
+ # Most sideband events are not relevant, including large transcript events.
184
+ # Do not retain their text or relay raw provider frames to Bun.
185
+ kind = ProviderEvent.model_validate_json(raw).type
186
+ match kind:
187
+ case "delegation.created":
188
+ return kind, DelegationEvent.model_validate_json(raw).item
189
+ case "session.delegation.created":
190
+ return kind, DelegationEvent.model_validate_json(raw).delegation
191
+ case _:
192
+ return kind, None