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.
- package/DESIGN.md +189 -48
- package/README.ko.md +30 -16
- package/README.md +39 -20
- package/THIRD_PARTY_NOTICES.md +81 -6
- package/docs/OPERATIONS.md +178 -30
- package/docs/discord-voice.md +96 -0
- package/docs/releases/0.1.2.md +53 -0
- package/package.json +13 -7
- package/scripts/ci.ts +10 -5
- package/scripts/release.ts +14 -6
- package/scripts/test-omp.sh +36 -0
- package/skills/head/SKILL.md +82 -241
- package/skills/head/references/model-selection.md +81 -261
- package/skills/head/references/routing.md +179 -354
- package/skills/head/references/supervision.md +120 -310
- package/skills/lane/SKILL.md +53 -175
- package/skills/lane/references/workflow.md +93 -347
- package/src/cli.ts +96 -10
- package/src/codex-live-bridge.py +73 -0
- package/src/codex-live.ts +244 -0
- package/src/codex-voice-requirements.txt +5 -0
- package/src/codex_live_auth.py +192 -0
- package/src/codex_live_media.py +219 -0
- package/src/codex_live_provider.py +192 -0
- package/src/config.ts +77 -2
- package/src/contracts.ts +70 -6
- package/src/decision-tool.ts +59 -0
- package/src/decisions.ts +143 -0
- package/src/delivery.ts +10 -0
- package/src/discord-context.ts +118 -0
- package/src/discord-voice-draft.ts +124 -0
- package/src/discord-voice-link.ts +270 -0
- package/src/discord-voice.ts +150 -0
- package/src/discord.ts +312 -45
- package/src/extension.ts +178 -21
- package/src/gateway-client.ts +11 -4
- package/src/gateway-server.ts +52 -4
- package/src/gateway-store.ts +16 -2
- package/src/gateway.ts +27 -11
- package/src/host-broker-services.ts +108 -0
- package/src/host-extension.ts +159 -47
- package/src/host-owner.ts +16 -0
- package/src/host-protocol.ts +9 -1
- package/src/host-services.ts +54 -0
- package/src/host.ts +3 -2
- package/src/installed-omp.ts +34 -26
- package/src/lane-extension.ts +5 -0
- package/src/lane-rows.ts +12 -0
- package/src/messengers.ts +38 -9
- package/src/native-presets.ts +91 -3
- package/src/native-settings.ts +3 -1
- package/src/openai-live.ts +377 -0
- package/src/pr-github-schema.ts +110 -0
- package/src/pr-github.ts +170 -0
- package/src/pr-watch.ts +200 -0
- package/src/runtime.ts +419 -54
- package/src/slack.ts +14 -11
- package/src/store.ts +86 -30
- package/src/telegram.ts +28 -12
- package/scripts/check-omp.ts +0 -4
|
@@ -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
|
package/src/config.ts
CHANGED
|
@@ -8,8 +8,31 @@ export interface DiscordConfig {
|
|
|
8
8
|
ownerId: string;
|
|
9
9
|
allowedGuildIds: string[];
|
|
10
10
|
allowedChannelIds: string[];
|
|
11
|
+
voice?: DiscordVoiceConfig;
|
|
11
12
|
}
|
|
12
13
|
|
|
14
|
+
type DiscordVoiceSessionConfig = {
|
|
15
|
+
readonly channelId: string;
|
|
16
|
+
readonly textChannelId: string;
|
|
17
|
+
readonly voice: string;
|
|
18
|
+
readonly maxSessionSeconds: number;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export type DiscordVoiceConfig = DiscordVoiceSessionConfig & (
|
|
22
|
+
| {
|
|
23
|
+
readonly auth?: "api";
|
|
24
|
+
readonly apiKeyEnv: string;
|
|
25
|
+
readonly model: string;
|
|
26
|
+
readonly backendModel: string;
|
|
27
|
+
}
|
|
28
|
+
| {
|
|
29
|
+
readonly auth: "subscription";
|
|
30
|
+
readonly apiKeyEnv?: never;
|
|
31
|
+
readonly model?: never;
|
|
32
|
+
readonly backendModel?: never;
|
|
33
|
+
}
|
|
34
|
+
);
|
|
35
|
+
|
|
13
36
|
export interface TelegramConfig {
|
|
14
37
|
tokenEnv: string;
|
|
15
38
|
ownerId: string;
|
|
@@ -72,16 +95,32 @@ export function configuredPlatforms(config: Config): Platform[] {
|
|
|
72
95
|
return (["discord", "telegram", "slack"] as const).filter(platform => config[platform] !== undefined);
|
|
73
96
|
}
|
|
74
97
|
|
|
98
|
+
export function voiceApiKeyEnv(config: Config): string | undefined {
|
|
99
|
+
const voice = config.discord?.voice;
|
|
100
|
+
switch (voice?.auth) {
|
|
101
|
+
case "api":
|
|
102
|
+
case undefined:
|
|
103
|
+
return voice?.apiKeyEnv;
|
|
104
|
+
case "subscription":
|
|
105
|
+
return undefined;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
75
109
|
export function credentialEnvNames(config: Config): string[] {
|
|
110
|
+
const voiceKey = voiceApiKeyEnv(config);
|
|
76
111
|
return [...new Set([
|
|
77
112
|
...(config.discord ? [config.discord.tokenEnv] : []),
|
|
113
|
+
...(voiceKey === undefined ? [] : [voiceKey]),
|
|
78
114
|
...(config.telegram ? [config.telegram.tokenEnv] : []),
|
|
79
115
|
...(config.slack ? [config.slack.botTokenEnv, config.slack.appTokenEnv] : []),
|
|
80
116
|
])];
|
|
81
117
|
}
|
|
82
118
|
|
|
83
119
|
export function requireMessengerCredentials(config: Config): void {
|
|
120
|
+
// Only an explicit API voice session needs its provider key, not text intake.
|
|
121
|
+
const voiceKey = voiceApiKeyEnv(config);
|
|
84
122
|
for (const name of credentialEnvNames(config)) {
|
|
123
|
+
if (name === voiceKey) continue;
|
|
85
124
|
if (!process.env[name]) throw new Error(`Missing messenger credential environment variable ${name}`);
|
|
86
125
|
}
|
|
87
126
|
}
|
|
@@ -137,9 +176,44 @@ export function parseConfig(value: unknown, path: string): Config {
|
|
|
137
176
|
throw new Error("command contains unsupported patched OMP arguments; configure an installed stock OMP executable");
|
|
138
177
|
const headCwd = realpathSync(pathValue(raw.headCwd, "headCwd"));
|
|
139
178
|
if (!lstatSync(headCwd).isDirectory()) throw new Error("headCwd must be a directory");
|
|
140
|
-
const command = resolveOmpCommand(raw.command as string[]);
|
|
179
|
+
const command = resolveOmpCommand(raw.command as string[], process.env.PATH, base);
|
|
141
180
|
const maxHosts = integer(raw.maxHosts, "maxHosts", 2);
|
|
142
181
|
const maxSubagents = integer(raw.maxSubagents, "maxSubagents", maxHosts);
|
|
182
|
+
const discordChannels = discord ? ids(discord.allowedChannelIds, "discord.allowedChannelIds") : [];
|
|
183
|
+
const voice = discord?.voice === undefined ? undefined : record(discord.voice, "discord.voice");
|
|
184
|
+
let voiceConfig: DiscordVoiceConfig | undefined;
|
|
185
|
+
if (voice) {
|
|
186
|
+
const channelId = id(voice.channelId, "discord.voice.channelId", /^\d+$/);
|
|
187
|
+
const textChannelId = id(voice.textChannelId, "discord.voice.textChannelId", /^\d+$/);
|
|
188
|
+
if (textChannelId === channelId || !discordChannels.includes(textChannelId))
|
|
189
|
+
throw new Error("discord.voice.textChannelId must be a separate, allowed text channel");
|
|
190
|
+
const maxSessionSeconds = integer(voice.maxSessionSeconds, "discord.voice.maxSessionSeconds", 1);
|
|
191
|
+
if (maxSessionSeconds * 1000 > 2 ** 31 - 1) throw new Error("discord.voice.maxSessionSeconds exceeds timer range");
|
|
192
|
+
const session = { channelId, textChannelId, voice: text(voice.voice, "discord.voice.voice"), maxSessionSeconds };
|
|
193
|
+
const auth = voice.auth;
|
|
194
|
+
switch (auth) {
|
|
195
|
+
case "subscription": {
|
|
196
|
+
const unsupported = Object.keys(voice).find(key => key !== "auth" && !Object.hasOwn(session, key));
|
|
197
|
+
if (unsupported !== undefined) throw new Error(`discord.voice.${unsupported} is not supported with subscription auth`);
|
|
198
|
+
voiceConfig = { ...session, auth: "subscription" };
|
|
199
|
+
break;
|
|
200
|
+
}
|
|
201
|
+
case "api":
|
|
202
|
+
case undefined: {
|
|
203
|
+
const apiKeyEnv = tokenEnv(voice.apiKeyEnv, "discord.voice.apiKeyEnv");
|
|
204
|
+
if ([discord?.tokenEnv, telegram?.tokenEnv, slack?.appTokenEnv, slack?.botTokenEnv].includes(apiKeyEnv))
|
|
205
|
+
throw new Error("discord.voice.apiKeyEnv must not name a messenger token");
|
|
206
|
+
voiceConfig = {
|
|
207
|
+
...session, ...(auth === undefined ? {} : { auth }), apiKeyEnv,
|
|
208
|
+
model: text(voice.model, "discord.voice.model"),
|
|
209
|
+
backendModel: text(voice.backendModel, "discord.voice.backendModel"),
|
|
210
|
+
};
|
|
211
|
+
break;
|
|
212
|
+
}
|
|
213
|
+
default:
|
|
214
|
+
throw new Error('discord.voice.auth must be "api" or "subscription"');
|
|
215
|
+
}
|
|
216
|
+
}
|
|
143
217
|
return {
|
|
144
218
|
path: absolute,
|
|
145
219
|
stateDir: pathValue(raw.stateDir, "stateDir"),
|
|
@@ -153,7 +227,8 @@ export function parseConfig(value: unknown, path: string): Config {
|
|
|
153
227
|
tokenEnv: tokenEnv(discord.tokenEnv, "discord.tokenEnv"),
|
|
154
228
|
ownerId: id(discord.ownerId, "discord.ownerId", /^\d+$/),
|
|
155
229
|
allowedGuildIds: ids(discord.allowedGuildIds, "discord.allowedGuildIds"),
|
|
156
|
-
allowedChannelIds:
|
|
230
|
+
allowedChannelIds: discordChannels,
|
|
231
|
+
...(voiceConfig ? { voice: voiceConfig } : {}),
|
|
157
232
|
} } : {}),
|
|
158
233
|
...(telegram ? { telegram: {
|
|
159
234
|
tokenEnv: tokenEnv(telegram.tokenEnv, "telegram.tokenEnv"),
|
package/src/contracts.ts
CHANGED
|
@@ -54,6 +54,31 @@ export interface ReplyContext {
|
|
|
54
54
|
quote?: string;
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
+
/** Untrusted observations, never instructions, authority, or automatic routing policy.
|
|
58
|
+
* For threads, channel describes the parent and thread describes the destination.
|
|
59
|
+
* Missing optional properties mean unavailable; a null topic is an observed empty topic.
|
|
60
|
+
*/
|
|
61
|
+
export interface DiscordContext {
|
|
62
|
+
readonly kind: "guild" | "dm";
|
|
63
|
+
readonly channel: {
|
|
64
|
+
readonly id: string;
|
|
65
|
+
readonly name?: string;
|
|
66
|
+
readonly topic?: string | null;
|
|
67
|
+
readonly purpose?: string;
|
|
68
|
+
};
|
|
69
|
+
readonly thread?: { readonly id: string; readonly parentId: string; readonly name?: string; readonly purpose?: string };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export type DiscordPurposeRequest = {
|
|
73
|
+
readonly sourceId: string;
|
|
74
|
+
readonly route: Route;
|
|
75
|
+
} & (
|
|
76
|
+
| { readonly action: "list" }
|
|
77
|
+
| { readonly action: "set"; readonly purpose: string }
|
|
78
|
+
| { readonly action: "clear" }
|
|
79
|
+
);
|
|
80
|
+
export interface DiscordPurposeNote { readonly route: Route; readonly purpose: string }
|
|
81
|
+
|
|
57
82
|
export interface Inbound {
|
|
58
83
|
id: string;
|
|
59
84
|
route: Route;
|
|
@@ -67,6 +92,7 @@ export interface Inbound {
|
|
|
67
92
|
receivedAt: number;
|
|
68
93
|
attachments: Attachment[];
|
|
69
94
|
reply?: ReplyContext;
|
|
95
|
+
discordContext?: DiscordContext;
|
|
70
96
|
}
|
|
71
97
|
|
|
72
98
|
/** A real platform message that can be fetched, reacted to, or used as a thread source. */
|
|
@@ -81,6 +107,11 @@ export interface LaneModel {
|
|
|
81
107
|
provider: string;
|
|
82
108
|
id: string;
|
|
83
109
|
}
|
|
110
|
+
export const HEAD_MODEL_CONTROL = "head:model-control";
|
|
111
|
+
export interface HeadModelChange {
|
|
112
|
+
readonly sourceId: string;
|
|
113
|
+
readonly model: LaneModel;
|
|
114
|
+
}
|
|
84
115
|
export const MODEL_PRESET_NAMES = ["high", "middle", "low"] as const;
|
|
85
116
|
export type ModelPreset = string;
|
|
86
117
|
export type LanePresetSnapshot = NativeModelPreset;
|
|
@@ -157,6 +188,8 @@ export interface OutputRecord {
|
|
|
157
188
|
id: string;
|
|
158
189
|
sourceId: string;
|
|
159
190
|
route: Route;
|
|
191
|
+
/** Durable original owner message, only in the same physical conversation. */
|
|
192
|
+
replyTo?: MessageReference;
|
|
160
193
|
text: string;
|
|
161
194
|
state: OutputState;
|
|
162
195
|
remoteId: string | null;
|
|
@@ -172,6 +205,14 @@ export interface Approval {
|
|
|
172
205
|
request: Record<string, unknown>;
|
|
173
206
|
state: "pending" | "answered" | "cancelled";
|
|
174
207
|
remoteId: string | null;
|
|
208
|
+
decision?: { id: string; sourceId: string | null; sessionId: string };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export interface ApprovalResolution {
|
|
212
|
+
response?: DialogResponse;
|
|
213
|
+
reason?: string;
|
|
214
|
+
sourceId?: string;
|
|
215
|
+
headSelection?: { readonly reviewId: string; readonly reason: string };
|
|
175
216
|
}
|
|
176
217
|
|
|
177
218
|
export interface HeadRecoveryDecision {
|
|
@@ -212,16 +253,19 @@ export interface HeadRecoveryEffect {
|
|
|
212
253
|
export interface StorePort {
|
|
213
254
|
receive(input: Inbound, target: string | null, metadata?: Readonly<Record<string, string>>, workflow?: WorkflowActivation | null): boolean;
|
|
214
255
|
input(id: string): InputRecord | null;
|
|
256
|
+
ownerSource(id: string): InputRecord | null;
|
|
215
257
|
inputs(target?: string): InputRecord[];
|
|
216
|
-
/**
|
|
217
|
-
|
|
258
|
+
/** The first authorized revision on the physical route, even after settlement. */
|
|
259
|
+
firstAdmittedMessage(route: Route, messageId: string): InputRecord | null;
|
|
260
|
+
/** Actual authorized message IDs in durable admission order; not invocation or edit IDs. */
|
|
261
|
+
admittedMessageIds(route: Route): Iterable<string>;
|
|
218
262
|
bindInput(id: string, target: string): void;
|
|
219
263
|
submit(id: string, requestId: string, generation: number): boolean;
|
|
220
264
|
/** Nonterminal native assistant observation; never settles or dispatches its owner. */
|
|
221
265
|
progress(id: string, generation: number, sessionId: string, eventId: string, text: string): boolean;
|
|
222
266
|
recordLaneReport(id: string, generation: number, sessionId: string, eventId: string, report: LaneReport, observedAt?: number): boolean;
|
|
223
267
|
resolveLaneWaiting(id: string, generation: number, sessionId: string, kind: "tool" | "approval", nativeId: string): boolean;
|
|
224
|
-
settle(id: string, state: "done" | "uncertain" | "cancelled", output?: { id: string; text: string }): boolean;
|
|
268
|
+
settle(id: string, state: "done" | "uncertain" | "cancelled", output?: { id: string; text: string }, headModel?: HeadModelChange): boolean;
|
|
225
269
|
headRecoveryEffects(inputId: string): HeadRecoveryEffect[];
|
|
226
270
|
prepareHeadRecovery(attempt: HeadRecoveryAttempt): boolean;
|
|
227
271
|
commitHeadRecovery(expected: HeadRecoveryAttempt, decided: HeadRecoveryAttempt): boolean;
|
|
@@ -244,7 +288,7 @@ export interface StorePort {
|
|
|
244
288
|
putApproval(approval: Approval): void;
|
|
245
289
|
approval(id: string): Approval | null;
|
|
246
290
|
approvals(target?: string): Approval[];
|
|
247
|
-
resolveApproval(id: string, generation: number, state: "answered" | "cancelled"): boolean;
|
|
291
|
+
resolveApproval(id: string, generation: number, state: "answered" | "cancelled", resolution?: ApprovalResolution): boolean;
|
|
248
292
|
setApprovalMessage(id: string, remoteId: string): void;
|
|
249
293
|
recoverDeliveries(): void;
|
|
250
294
|
getMeta(key: string): string | null;
|
|
@@ -289,6 +333,21 @@ export interface GatewayRestartNotice {
|
|
|
289
333
|
reason: string;
|
|
290
334
|
}
|
|
291
335
|
|
|
336
|
+
export interface ThreadInfo {
|
|
337
|
+
readonly route: Route;
|
|
338
|
+
readonly title: string;
|
|
339
|
+
readonly archived: boolean | null;
|
|
340
|
+
readonly requiresTag: boolean;
|
|
341
|
+
readonly availableTags: readonly { readonly id: string; readonly name: string; readonly moderated: boolean }[];
|
|
342
|
+
readonly appliedTags: readonly string[];
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
export interface ThreadUpdate {
|
|
346
|
+
readonly title?: string;
|
|
347
|
+
readonly appliedTags?: readonly string[];
|
|
348
|
+
readonly archived?: boolean;
|
|
349
|
+
}
|
|
350
|
+
|
|
292
351
|
export interface Messenger {
|
|
293
352
|
start(handlers: {
|
|
294
353
|
/** Authenticate first; do not consume inbound events until native approvals are reconciled. */
|
|
@@ -307,8 +366,13 @@ export interface Messenger {
|
|
|
307
366
|
showApproval(approval: Approval): Promise<string>;
|
|
308
367
|
dismissApproval(approval: Approval): Promise<void>;
|
|
309
368
|
/** Read-only authenticated capability probe; false is unsupported, not a failed creation. */
|
|
310
|
-
canCreateThread?(route: Route): Promise<boolean>;
|
|
311
|
-
createThread(route: Route, title: string, sourceMessageId?: string): Promise<Route>;
|
|
369
|
+
canCreateThread?(route: Route, appliedTags?: readonly string[]): Promise<boolean>;
|
|
370
|
+
createThread(route: Route, title: string, sourceMessageId?: string, appliedTags?: readonly string[]): Promise<Route>;
|
|
371
|
+
/** Optional native thread management; unsupported transports must not simulate it. */
|
|
372
|
+
inspectThread?(route: Route): Promise<ThreadInfo>;
|
|
373
|
+
updateThread?(route: Route, update: ThreadUpdate): Promise<ThreadInfo>;
|
|
374
|
+
inspectDiscordContext?(route: Route): Promise<DiscordContext>;
|
|
375
|
+
discordPurpose?(request: DiscordPurposeRequest): Promise<readonly DiscordPurposeNote[]>;
|
|
312
376
|
/** null explicitly means no history API; intake recovery belongs to the adapter. */
|
|
313
377
|
fetchAfter(route: Route, messageId: string): Promise<Inbound[] | null>;
|
|
314
378
|
/** Validate platform/auth destination before fetching. Never follow redirects with credentials. */
|