osborn 0.9.271 → 0.9.274

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 (55) hide show
  1. package/.claude/skills/browser-apply/SKILL.md +82 -30
  2. package/.claude/skills/browser-apply/candidate.example.env +16 -0
  3. package/.claude/skills/browser-apply/fill.mjs +294 -0
  4. package/Dockerfile +1 -1
  5. package/dist/claude-llm.d.ts +3 -0
  6. package/dist/claude-llm.js +100 -17
  7. package/dist/compaction-log.d.ts +67 -0
  8. package/dist/compaction-log.js +195 -0
  9. package/dist/config.d.ts +18 -0
  10. package/dist/config.js +122 -65
  11. package/dist/content/transcript-sanitizer.d.ts +20 -6
  12. package/dist/content/transcript-sanitizer.js +66 -11
  13. package/dist/data-sender-auth.d.ts +90 -0
  14. package/dist/data-sender-auth.js +157 -0
  15. package/dist/env-keys.js +11 -0
  16. package/dist/index.js +411 -92
  17. package/dist/meeting-addressing.d.ts +176 -0
  18. package/dist/meeting-addressing.js +288 -0
  19. package/dist/pipeline-direct-llm.d.ts +27 -0
  20. package/dist/pipeline-direct-llm.js +117 -37
  21. package/dist/prompts/direct-mode-fallback.md +1 -1
  22. package/dist/prompts/direct-mode-research.md +2 -2
  23. package/dist/prompts.d.ts +1 -1
  24. package/dist/prompts.js +3 -3
  25. package/dist/pushover.d.ts +77 -0
  26. package/dist/pushover.js +276 -0
  27. package/dist/recall-client.js +21 -2
  28. package/dist/session-store.d.ts +15 -5
  29. package/dist/session-store.js +37 -10
  30. package/dist/transcript-wiring.d.ts +121 -0
  31. package/dist/transcript-wiring.js +252 -0
  32. package/dist/voice-io.d.ts +0 -9
  33. package/dist/voice-io.js +5 -19
  34. package/dist/watch-gateway.d.ts +38 -0
  35. package/dist/watch-gateway.js +205 -0
  36. package/package.json +1 -1
  37. package/scripts/review.ts +1 -1
  38. package/dist/bridge-llm.d.ts +0 -22
  39. package/dist/bridge-llm.js +0 -39
  40. package/dist/codex-handler.d.ts +0 -38
  41. package/dist/codex-handler.js +0 -83
  42. package/dist/codex-llm.d.ts +0 -40
  43. package/dist/codex-llm.js +0 -144
  44. package/dist/fast-brain.d.ts +0 -176
  45. package/dist/fast-brain.js +0 -1887
  46. package/dist/index-3-2-26-legacy.d.ts +0 -1
  47. package/dist/index-3-2-26-legacy.js +0 -2233
  48. package/dist/leagcyprompts2.d.ts +0 -0
  49. package/dist/leagcyprompts2.js +0 -573
  50. package/dist/prompts-2-25-26.d.ts +0 -0
  51. package/dist/prompts-2-25-26.js +0 -518
  52. package/dist/prompts-3-2-26.d.ts +0 -78
  53. package/dist/prompts-3-2-26.js +0 -1319
  54. package/dist/summary-index.d.ts +0 -90
  55. package/dist/summary-index.js +0 -585
@@ -0,0 +1,252 @@
1
+ /**
2
+ * transcript-wiring.ts — pure helpers for the transcript paths in index.ts
3
+ * (lane L2b, agent side). Kept out of index.ts so they are unit-testable
4
+ * without booting the agent.
5
+ *
6
+ * - sessionListEntry: one mapping for `/sessions` and `sessions_list`
7
+ * (carries title / firstTs / lastActivityAt).
8
+ * - cleanHistoryRows: `/session-messages` + `prior_messages`: sanitize
9
+ * with cleanTurnText BEFORE truncating, over-fetch so
10
+ * rows dropped by the sanitizer do not shrink the page.
11
+ * - userEchoText: the user_transcript echo text, sanitized.
12
+ * - TypedEchoTracker: carries a typed message's clientMsgId onto its echo.
13
+ * - ClientNoteQueue: out-of-band client notices (favorite_changed) that
14
+ * ride the NEXT real user turn as hidden context
15
+ * instead of becoming a user turn themselves.
16
+ */
17
+ import { cleanTurnText } from './content/transcript-sanitizer.js';
18
+ /** The preview fields the dashboard / session browser receive per session. */
19
+ export function sessionListEntry(s) {
20
+ return {
21
+ sessionId: s.sessionId,
22
+ projectSlug: s.projectSlug,
23
+ projectPath: s.projectPath,
24
+ cwd: s.cwd,
25
+ timestamp: s.timestamp.toISOString(),
26
+ lastMessage: s.lastMessage,
27
+ title: s.title,
28
+ messageCount: s.messageCount,
29
+ firstTs: s.firstTs,
30
+ lastActivityAt: s.lastActivityAt,
31
+ fileSize: s.fileSize,
32
+ };
33
+ }
34
+ /** Upper bound on rows read while topping up a page (sanitizer drops). */
35
+ export const HISTORY_MAX_FETCH = 2000;
36
+ /**
37
+ * Read up to `limit` clean messages, chronological. `fetchRows(n)` returns the
38
+ * newest `n` rows NEWEST-FIRST (recentRows' contract). Each row is sanitized
39
+ * with cleanTurnText first, then truncated to `maxChars`; dropped rows (pure
40
+ * notices, injected blocks, [SYSTEM] lines) are replaced by fetching more,
41
+ * starting at 3x and doubling, until the page is full, the store is exhausted
42
+ * (fewer rows than asked), or HISTORY_MAX_FETCH is reached.
43
+ */
44
+ export function cleanHistoryRows(fetchRows, limit, maxChars) {
45
+ const want = Math.max(1, Math.floor(limit) || 1);
46
+ let n = Math.min(want * 3, HISTORY_MAX_FETCH);
47
+ for (;;) {
48
+ const rows = fetchRows(n);
49
+ const kept = [];
50
+ for (const r of rows) {
51
+ const role = r.msgType === 'assistant' ? 'assistant' : 'user';
52
+ const clean = cleanTurnText(r.text || '', role);
53
+ if (!clean)
54
+ continue;
55
+ kept.push({ role, content: clean.slice(0, maxChars), ts: r.ts || null });
56
+ if (kept.length >= want)
57
+ break;
58
+ }
59
+ const exhausted = rows.length < n || n >= HISTORY_MAX_FETCH;
60
+ if (kept.length >= want || exhausted)
61
+ return kept.reverse(); // newest-first → chronological
62
+ n = Math.min(n * 2, HISTORY_MAX_FETCH);
63
+ }
64
+ }
65
+ // ── user_transcript echo ───────────────────────────────────────────────────
66
+ /** Injected-block tags whose UNCLOSED open tag must not reach the echo. */
67
+ const ECHO_INJECTED_TAGS = ['system-reminder', 'session_tail', 'task-notification', 'recalled_context', 'user-prompt-submit-hook'];
68
+ /**
69
+ * Echo-only guard: an injected open tag with no matching close after it is cut,
70
+ * together with everything after it to the end of the string. The shared
71
+ * sanitizer deliberately keeps an inline unterminated tag (a person can say
72
+ * "the <system-reminder> tag is noisy"), so this lives here, not in
73
+ * cleanTurnText: the echo is shown to everyone in the room and must never carry
74
+ * a half-injected block. Closed blocks are left for cleanTurnText.
75
+ */
76
+ export function cutUnclosedInjected(text) {
77
+ let out = text;
78
+ for (let changed = true; changed;) {
79
+ changed = false;
80
+ for (const tag of ECHO_INJECTED_TAGS) {
81
+ const open = new RegExp(`<${tag}\\b[^>]*>`, 'gi');
82
+ let last = null;
83
+ for (let m = open.exec(out); m; m = open.exec(out))
84
+ last = m;
85
+ if (!last)
86
+ continue;
87
+ const rest = out.slice(last.index + last[0].length);
88
+ if (new RegExp(`</${tag}\\s*>`, 'i').test(rest))
89
+ continue;
90
+ out = out.slice(0, last.index);
91
+ changed = true;
92
+ }
93
+ }
94
+ return out;
95
+ }
96
+ /**
97
+ * The text to echo as `user_transcript`, or null to send nothing. Runs the
98
+ * shared sanitizer (drops [time:] tags, <session_tail>, [favorited] /
99
+ * [welcome-back] / [SCRIPT] / [PROACTIVE] / [NOTIFICATION] / [SYSTEM] notices,
100
+ * unwraps [INTERRUPTED]/[CONTEXT]), then the echo's own noise filters.
101
+ */
102
+ export function userEchoText(raw, attachments = '') {
103
+ if (!raw || typeof raw !== 'string')
104
+ return null;
105
+ let clean = cleanTurnText(cutUnclosedInjected(raw), 'user');
106
+ if (clean) {
107
+ const normalized = clean.replace(/\s+/g, ' ');
108
+ if (clean.length < 3 || normalized === '<noise>' || normalized.toLowerCase() === 'thank you')
109
+ clean = null;
110
+ }
111
+ // A typed message keeps its attachment blocks (the chat renders them).
112
+ const att = attachments.trim();
113
+ if (att)
114
+ return clean ? `${clean}\n\n${att}` : att;
115
+ return clean;
116
+ }
117
+ /** Valid clientMsgId or undefined (string, 1..200 chars). */
118
+ export function validClientMsgId(v) {
119
+ return typeof v === 'string' && v.length > 0 && v.length <= 200 ? v : undefined;
120
+ }
121
+ /**
122
+ * Remembers typed messages (user_text) by their raw content so the session's
123
+ * echo of the same item (conversation_item_added → user_transcript) can carry
124
+ * the frontend's clientMsgId and keep its attachment blocks (the sanitizer
125
+ * strips trailing [File:]/[Image:] blocks, which the chat renders). Matches on
126
+ * the exact raw text first, then on the sanitized text. Entries expire after
127
+ * `ttlMs`; at most `max` are kept.
128
+ */
129
+ export class TypedEchoTracker {
130
+ ttlMs;
131
+ max;
132
+ #items = [];
133
+ constructor(ttlMs = 60_000, max = 20) {
134
+ this.ttlMs = ttlMs;
135
+ this.max = max;
136
+ }
137
+ register(rawContent, clientMsgId, attachments = '', now = Date.now()) {
138
+ const id = validClientMsgId(clientMsgId);
139
+ if (!id && !attachments.trim())
140
+ return;
141
+ this.#prune(now);
142
+ this.#items.push({
143
+ raw: rawContent,
144
+ clean: cleanTurnText(rawContent, 'user'),
145
+ echo: { ...(id ? { clientMsgId: id } : {}), attachments: attachments.trim() },
146
+ at: now,
147
+ });
148
+ if (this.#items.length > this.max)
149
+ this.#items.splice(0, this.#items.length - this.max);
150
+ }
151
+ /** Consume and return the typed-message info for this echoed text, if any. */
152
+ take(rawEcho, now = Date.now()) {
153
+ this.#prune(now);
154
+ let i = this.#items.findIndex((e) => e.raw === rawEcho);
155
+ if (i < 0) {
156
+ const clean = cleanTurnText(rawEcho, 'user');
157
+ if (clean)
158
+ i = this.#items.findIndex((e) => e.clean === clean);
159
+ }
160
+ if (i < 0)
161
+ return undefined;
162
+ const [hit] = this.#items.splice(i, 1);
163
+ return hit.echo;
164
+ }
165
+ clear() { this.#items = []; }
166
+ get size() { return this.#items.length; }
167
+ #prune(now) {
168
+ this.#items = this.#items.filter((e) => now - e.at <= this.ttlMs);
169
+ }
170
+ }
171
+ /** Validate a favorite_changed payload; null when unusable. */
172
+ export function parseFavoriteChanged(data) {
173
+ if (!data || typeof data !== 'object')
174
+ return null;
175
+ const fileName = typeof data.fileName === 'string' ? data.fileName.trim().slice(0, 300) : '';
176
+ const filePath = typeof data.filePath === 'string' ? data.filePath.trim().slice(0, 1000) : '';
177
+ if (!fileName && !filePath)
178
+ return null;
179
+ if (typeof data.favorited !== 'boolean')
180
+ return null;
181
+ return { filePath: filePath || fileName, fileName: fileName || filePath.split('/').pop() || filePath, favorited: data.favorited };
182
+ }
183
+ /**
184
+ * Backward compatibility: an older frontend sends the favorite as
185
+ * `user_text` "[time: …] [favorited] The user favorited the file NAME."
186
+ * Returns the change when `content` is exactly that notice, else null.
187
+ */
188
+ export function parseLegacyFavoriteNotice(content) {
189
+ if (typeof content !== 'string')
190
+ return null;
191
+ const body = content.replace(/^\s*\[time:[^\]]*\]\s*/, '');
192
+ const m = body.match(/^\[favorited\]\s*The user favorited the file (.+?)\.?\s*$/s);
193
+ if (!m)
194
+ return null;
195
+ const name = m[1].trim();
196
+ if (!name || name.includes('\n'))
197
+ return null;
198
+ return { filePath: name, fileName: name, favorited: true };
199
+ }
200
+ /** A client string made safe to sit inside a <system-reminder> line: no `<`, `>`, CR or LF. */
201
+ function noteSafe(s) {
202
+ return typeof s === 'string' ? s.replace(/[<>\r\n]/g, '').trim() : '';
203
+ }
204
+ /**
205
+ * Pending client notices for the agent, delivered as hidden context on the next
206
+ * real user turn (never as a user turn). Keyed by file path so a favorite then
207
+ * an unfavorite of the same file cancels out. The drained block is a
208
+ * <system-reminder>, which the shared sanitizer (lens-strip) removes from
209
+ * history, titles and echoes while keeping the user's own words.
210
+ */
211
+ export class ClientNoteQueue {
212
+ max;
213
+ #favorites = new Map();
214
+ constructor(max = 20) {
215
+ this.max = max;
216
+ }
217
+ favoriteChanged(raw) {
218
+ // Client-supplied names land inside a <system-reminder> block: strip
219
+ // anything that could close/open a tag or start a new line.
220
+ const fileName = noteSafe(raw.fileName);
221
+ const filePath = noteSafe(raw.filePath) || fileName;
222
+ if (!filePath)
223
+ return;
224
+ const change = { filePath, fileName: fileName || filePath, favorited: raw.favorited };
225
+ this.#favorites.delete(change.filePath);
226
+ // Un-favoriting stays silent (as before): it only cancels a pending note.
227
+ if (!change.favorited)
228
+ return;
229
+ this.#favorites.set(change.filePath, change);
230
+ while (this.#favorites.size > this.max) {
231
+ const oldest = this.#favorites.keys().next().value;
232
+ if (oldest === undefined)
233
+ break;
234
+ this.#favorites.delete(oldest);
235
+ }
236
+ }
237
+ get size() { return this.#favorites.size; }
238
+ clear() { this.#favorites.clear(); }
239
+ /** Return the pending notes as one hidden-context block and clear them; '' when none. */
240
+ drain() {
241
+ if (this.#favorites.size === 0)
242
+ return '';
243
+ const lines = [...this.#favorites.values()].map((f) => `[favorited] The user favorited the file ${f.fileName}${f.filePath !== f.fileName ? ` (${f.filePath})` : ''}.`);
244
+ this.#favorites.clear();
245
+ return [
246
+ '<system-reminder>',
247
+ 'Client notices since the last turn (UI actions, not something the user said; no reply needed unless relevant):',
248
+ ...lines,
249
+ '</system-reminder>',
250
+ ].join('\n');
251
+ }
252
+ }
@@ -32,12 +32,3 @@ export declare function createSTT(config: STTConfig): soniox.STT | deepgram.STT
32
32
  * Create TTS (Text-to-Speech) instance based on config
33
33
  */
34
34
  export declare function createTTS(config: TTSConfig): any;
35
- /**
36
- * Create VAD (Voice Activity Detection) for turn detection
37
- *
38
- * Tuned to prevent:
39
- * - "Audio file is too short" errors from STT (OpenAI requires >= 0.1s)
40
- * - Split sentences when user pauses briefly mid-speech
41
- * - False triggers from ambient noise
42
- */
43
- export declare function createVAD(): Promise<import("@livekit/agents").VAD>;
package/dist/voice-io.js CHANGED
@@ -6,7 +6,6 @@ import * as deepgram from '@livekit/agents-plugin-deepgram';
6
6
  import * as fishaudio from '@livekit/agents-plugin-fishaudio';
7
7
  import * as openai from '@livekit/agents-plugin-openai';
8
8
  import * as rime from '@livekit/agents-plugin-rime';
9
- import * as silero from '@livekit/agents-plugin-silero';
10
9
  import * as soniox from '@livekit/agents-plugin-soniox';
11
10
  /**
12
11
  * Create STT (Speech-to-Text) instance based on config
@@ -136,21 +135,8 @@ export function createTTS(config) {
136
135
  }
137
136
  return tts;
138
137
  }
139
- /**
140
- * Create VAD (Voice Activity Detection) for turn detection
141
- *
142
- * Tuned to prevent:
143
- * - "Audio file is too short" errors from STT (OpenAI requires >= 0.1s)
144
- * - Split sentences when user pauses briefly mid-speech
145
- * - False triggers from ambient noise
146
- */
147
- export async function createVAD() {
148
- // VAD now only handles interruption detection — turn detection moved to Deepgram STT (server-side).
149
- // Lighter settings = less local CPU from ONNX inference.
150
- return silero.VAD.load({
151
- minSpeechDuration: 0.4, // 400ms — quick interruption detection
152
- minSilenceDuration: 1.2, // 1200ms — responsive
153
- prefixPaddingDuration: 0.1,
154
- activationThreshold: 0.85, // default — balanced for interruptions only
155
- });
156
- }
138
+ // createVAD (Silero ONNX) removed 2026-11-07 — it was DEAD CODE: zero call sites.
139
+ // The live website path uses Deepgram STT endpointing for turn detection AND
140
+ // interruption (see index.ts: "VAD (Silero ONNX) removed — caused 2-5s inference
141
+ // lag"); the meeting path uses the Recall speech webhook. The @livekit/agents-
142
+ // plugin-silero dep is kept only for the runtime version snapshot in index.ts.
@@ -0,0 +1,38 @@
1
+ /**
2
+ * watch-gateway.ts — Track 2 watch bridge (native watchOS app ↔ LiveKit room).
3
+ *
4
+ * watchOS has no WKWebView and LiveKit's Swift SDK will not target it
5
+ * (client-sdk-swift #288), so the native watch app (frontend/native/watchos/)
6
+ * speaks a tiny WebSocket protocol to THIS gateway running on the user's own
7
+ * machine, which bridges into their LiveKit room via @livekit/rtc-node:
8
+ *
9
+ * watch ──WS JSON (control)──► gateway ──RTC data channel──► room
10
+ * watch ──WS binary (Int16LE PCM 24kHz mono)──► gateway ──resample 48k──► published mic track
11
+ * watch ◄──WS binary (Int16LE PCM 24kHz mono)── gateway ◄──decode+resample── subscribed agent track
12
+ *
13
+ * Protocol (see also GatewayLink.swift — the two must stay in sync):
14
+ * C→S text {"type":"hello","watchId":string} — first message; joins the ACTIVE room
15
+ * {"type":"answer","qid":string,"allow":boolean} — question sheet response
16
+ * {"type":"ping"}
17
+ * C→S bin raw Int16LE mono PCM frames @24kHz (no header)
18
+ * S→C text {"type":"state","agent":"idle|listening|thinking|speaking","room":string}
19
+ * {"type":"question","qid":string,"text":string}
20
+ * {"type":"joined","room":string} / {"type":"error","message":string} / {"type":"pong"}
21
+ * S→C bin raw Int16LE mono PCM frames @24kHz (announced by {"type":"audio","rate":24000})
22
+ *
23
+ * One watch connection = one rtc-node Room. The gateway is dormant unless
24
+ * started (index.ts gates on WATCH_GATEWAY=1).
25
+ */
26
+ import { WebSocketServer } from 'ws';
27
+ export interface WatchGatewayOptions {
28
+ port: number;
29
+ livekitUrl: string;
30
+ /** Returns the room the user's session is currently joined to (null = none). */
31
+ getActiveRoom: () => string | null;
32
+ /** Mints a LiveKit JWT for the given room (publish+subscribe+data). */
33
+ mintToken: (room: string) => Promise<string>;
34
+ }
35
+ export declare function startWatchGateway(opts: WatchGatewayOptions): {
36
+ wss: WebSocketServer;
37
+ close: () => void;
38
+ };
@@ -0,0 +1,205 @@
1
+ /**
2
+ * watch-gateway.ts — Track 2 watch bridge (native watchOS app ↔ LiveKit room).
3
+ *
4
+ * watchOS has no WKWebView and LiveKit's Swift SDK will not target it
5
+ * (client-sdk-swift #288), so the native watch app (frontend/native/watchos/)
6
+ * speaks a tiny WebSocket protocol to THIS gateway running on the user's own
7
+ * machine, which bridges into their LiveKit room via @livekit/rtc-node:
8
+ *
9
+ * watch ──WS JSON (control)──► gateway ──RTC data channel──► room
10
+ * watch ──WS binary (Int16LE PCM 24kHz mono)──► gateway ──resample 48k──► published mic track
11
+ * watch ◄──WS binary (Int16LE PCM 24kHz mono)── gateway ◄──decode+resample── subscribed agent track
12
+ *
13
+ * Protocol (see also GatewayLink.swift — the two must stay in sync):
14
+ * C→S text {"type":"hello","watchId":string} — first message; joins the ACTIVE room
15
+ * {"type":"answer","qid":string,"allow":boolean} — question sheet response
16
+ * {"type":"ping"}
17
+ * C→S bin raw Int16LE mono PCM frames @24kHz (no header)
18
+ * S→C text {"type":"state","agent":"idle|listening|thinking|speaking","room":string}
19
+ * {"type":"question","qid":string,"text":string}
20
+ * {"type":"joined","room":string} / {"type":"error","message":string} / {"type":"pong"}
21
+ * S→C bin raw Int16LE mono PCM frames @24kHz (announced by {"type":"audio","rate":24000})
22
+ *
23
+ * One watch connection = one rtc-node Room. The gateway is dormant unless
24
+ * started (index.ts gates on WATCH_GATEWAY=1).
25
+ */
26
+ import { WebSocketServer, WebSocket } from 'ws';
27
+ import { Room, RoomEvent, AudioSource, AudioResampler, AudioStream, AudioFrame, LocalAudioTrack, TrackKind, TrackSource, TrackPublishOptions, } from '@livekit/rtc-node';
28
+ const WATCH_PCM_RATE = 24_000;
29
+ const ROOM_RATE = 48_000;
30
+ function wsSendJson(ws, obj) {
31
+ if (ws.readyState === WebSocket.OPEN)
32
+ ws.send(JSON.stringify(obj));
33
+ }
34
+ export function startWatchGateway(opts) {
35
+ const wss = new WebSocketServer({ port: opts.port });
36
+ const sessions = new Set();
37
+ console.log(`⌚️ Watch gateway listening on :${opts.port} (bridging to ${opts.livekitUrl})`);
38
+ wss.on('connection', (ws) => {
39
+ let session = null;
40
+ let helloDone = false;
41
+ ws.on('message', (data, isBinary) => {
42
+ if (isBinary) {
43
+ // Raw Int16LE PCM @24kHz from the watch mic → resample → publish.
44
+ if (!session)
45
+ return;
46
+ const pcm = new Int16Array(data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength));
47
+ const frame = new AudioFrame(pcm, WATCH_PCM_RATE, 1, pcm.length);
48
+ for (const out of session.upResampler.push(frame)) {
49
+ void session.upSource.captureFrame(out).catch(() => { });
50
+ }
51
+ return;
52
+ }
53
+ let msg;
54
+ try {
55
+ msg = JSON.parse(data.toString());
56
+ }
57
+ catch {
58
+ return;
59
+ }
60
+ if (msg.type === 'ping') {
61
+ wsSendJson(ws, { type: 'pong' });
62
+ return;
63
+ }
64
+ if (!helloDone) {
65
+ if (msg.type !== 'hello') {
66
+ wsSendJson(ws, { type: 'error', message: 'expected hello first' });
67
+ return;
68
+ }
69
+ helloDone = true;
70
+ void handleHello(ws, String(msg.watchId || 'watch'), sessions).then((s) => {
71
+ session = s;
72
+ });
73
+ return;
74
+ }
75
+ // Answers from the watch question sheet ride the room data channel with
76
+ // the same shape the web UI sends, so the agent needs no new handling.
77
+ if (msg.type === 'answer' && session) {
78
+ const payload = JSON.stringify({
79
+ type: 'permission_response',
80
+ response: msg.allow ? 'allow' : 'deny',
81
+ source: 'watch',
82
+ qid: msg.qid,
83
+ });
84
+ void session.room.localParticipant
85
+ ?.publishData(new TextEncoder().encode(payload), { reliable: true })
86
+ .catch(() => { });
87
+ }
88
+ });
89
+ ws.on('close', () => void teardown(session));
90
+ ws.on('error', () => void teardown(session));
91
+ async function teardown(s) {
92
+ if (!s)
93
+ return;
94
+ session = null;
95
+ sessions.delete(s);
96
+ s.downReader?.cancel().catch(() => { });
97
+ try {
98
+ await s.upTrack.close();
99
+ }
100
+ catch { /* already closed */ }
101
+ s.upResampler.close();
102
+ s.downResampler.close();
103
+ try {
104
+ await s.room.disconnect();
105
+ }
106
+ catch { /* already disconnected */ }
107
+ }
108
+ async function handleHello(ws, watchId, activeSessions) {
109
+ const activeRoom = opts.getActiveRoom();
110
+ if (!activeRoom) {
111
+ wsSendJson(ws, { type: 'error', message: 'no active session room — connect from the dashboard first' });
112
+ ws.close();
113
+ return null;
114
+ }
115
+ const room = new Room();
116
+ const upSource = new AudioSource(ROOM_RATE, 1);
117
+ const upTrack = LocalAudioTrack.createAudioTrack(`watch-${watchId}-mic`, upSource);
118
+ const s = {
119
+ ws,
120
+ room,
121
+ upSource,
122
+ upTrack,
123
+ upResampler: new AudioResampler(WATCH_PCM_RATE, ROOM_RATE, 1),
124
+ downResampler: new AudioResampler(ROOM_RATE, WATCH_PCM_RATE, 1),
125
+ };
126
+ room
127
+ .on(RoomEvent.DataReceived, (payload) => {
128
+ // Room data (agent state, permission_request, …) → watch as JSON text.
129
+ try {
130
+ const text = new TextDecoder().decode(payload);
131
+ const parsed = JSON.parse(text);
132
+ if (parsed?.type === 'permission_request') {
133
+ // The watch shows a yes/no sheet for blocking questions.
134
+ wsSendJson(ws, {
135
+ type: 'question',
136
+ qid: parsed.toolUseId ?? parsed.toolName ?? 'perm',
137
+ text: parsed.description ?? `Use ${parsed.toolName}?`,
138
+ });
139
+ }
140
+ else if (parsed?.type === 'agent_state' || parsed?.type === 'state') {
141
+ wsSendJson(ws, { type: 'state', agent: parsed.state ?? parsed.agent ?? 'idle', room: activeRoom });
142
+ }
143
+ }
144
+ catch { /* non-JSON or non-object data — ignore */ }
145
+ })
146
+ .on(RoomEvent.TrackSubscribed, (track, publication, participant) => {
147
+ if (track.kind !== TrackKind.KIND_AUDIO)
148
+ return;
149
+ console.log(`⌚️ Watch gateway: subscribing agent audio (${publication.source}, ${participant.identity})`);
150
+ // Decode agent audio at room rate, resample down to 24k, ship to watch.
151
+ const stream = new AudioStream(track, ROOM_RATE, 1);
152
+ s.downStream = stream;
153
+ const reader = stream.getReader();
154
+ s.downReader = reader;
155
+ wsSendJson(ws, { type: 'audio', rate: WATCH_PCM_RATE });
156
+ void (async () => {
157
+ try {
158
+ for (;;) {
159
+ const { done, value } = await reader.read();
160
+ if (done)
161
+ break;
162
+ if (ws.readyState !== WebSocket.OPEN)
163
+ break;
164
+ for (const out of s.downResampler.push(value)) {
165
+ if (ws.readyState !== WebSocket.OPEN)
166
+ break;
167
+ ws.send(Buffer.from(out.data.buffer));
168
+ }
169
+ }
170
+ }
171
+ catch { /* reader cancelled or stream ended */ }
172
+ })();
173
+ })
174
+ .on(RoomEvent.Disconnected, () => {
175
+ wsSendJson(ws, { type: 'error', message: 'room disconnected' });
176
+ void teardown(s);
177
+ });
178
+ try {
179
+ await room.connect(opts.livekitUrl, await opts.mintToken(activeRoom), {
180
+ autoSubscribe: true,
181
+ dynacast: false,
182
+ });
183
+ await room.localParticipant.publishTrack(upTrack, new TrackPublishOptions({ source: TrackSource.SOURCE_MICROPHONE }));
184
+ }
185
+ catch (e) {
186
+ console.log('⌚️ Watch gateway: room connect failed:', e instanceof Error ? e.message : e);
187
+ wsSendJson(ws, { type: 'error', message: 'room connect failed' });
188
+ void teardown(s);
189
+ return null;
190
+ }
191
+ activeSessions.add(s);
192
+ console.log(`⌚️ Watch gateway: watch ${watchId} joined room ${activeRoom}`);
193
+ wsSendJson(ws, { type: 'joined', room: activeRoom });
194
+ return s;
195
+ }
196
+ });
197
+ return {
198
+ wss,
199
+ close: () => {
200
+ for (const ws of wss.clients)
201
+ ws.terminate();
202
+ wss.close();
203
+ },
204
+ };
205
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osborn",
3
- "version": "0.9.271",
3
+ "version": "0.9.274",
4
4
  "description": "Voice AI coding assistant - local agent that connects to Osborn frontend",
5
5
  "type": "module",
6
6
  "bin": {
package/scripts/review.ts CHANGED
@@ -244,7 +244,7 @@ const brief = `# Osborn Prompt Review
244
244
 
245
245
  ## Raw session log
246
246
 
247
- The following is the full untruncated terminal output from an \`npm run dev:logged\` session with Osborn, a voice AI research assistant. Pattern guide:
247
+ The following is the full untruncated terminal output from an \`npm run dev:logged\` session with Osborn, a voice AI engineer and thinking partner. Pattern guide:
248
248
 
249
249
  - \`📝 User (conv_item, N chars): "..."\` / \`📝 Text (N chars): "..."\` — what the user said (voice) or typed (data channel)
250
250
  - \`📥 [pipeline] chat() call #N (chars): "..."\` — pipeline-mode user turn entering the Claude SDK
@@ -1,22 +0,0 @@
1
- /**
2
- * Bridge LLM Module - Creates LLM instances for pipelined voice sessions
3
- *
4
- * In pipelined mode, we use a separate LLM (Gemini or GPT-4o) as the
5
- * "conversation manager" that handles voice I/O and routes to Claude Code.
6
- */
7
- import * as google from '@livekit/agents-plugin-google';
8
- import * as openai from '@livekit/agents-plugin-openai';
9
- export interface BridgeLLMConfig {
10
- provider: 'gemini-pro' | 'gemini-flash' | 'gpt-4o' | 'gpt-4o-mini';
11
- model?: string;
12
- }
13
- /**
14
- * Create Bridge LLM instance for pipelined voice sessions
15
- *
16
- * Options:
17
- * - gemini-pro: Gemini 2.5 Pro (smart, good reasoning)
18
- * - gemini-flash: Gemini 2.0 Flash (faster, cheaper)
19
- * - gpt-4o: GPT-4o (alternative if OpenAI preferred)
20
- * - gpt-4o-mini: GPT-4o Mini (faster, cheaper)
21
- */
22
- export declare function createBridgeLLM(config: BridgeLLMConfig): google.LLM | openai.LLM;
@@ -1,39 +0,0 @@
1
- /**
2
- * Bridge LLM Module - Creates LLM instances for pipelined voice sessions
3
- *
4
- * In pipelined mode, we use a separate LLM (Gemini or GPT-4o) as the
5
- * "conversation manager" that handles voice I/O and routes to Claude Code.
6
- */
7
- import * as google from '@livekit/agents-plugin-google';
8
- import * as openai from '@livekit/agents-plugin-openai';
9
- /**
10
- * Create Bridge LLM instance for pipelined voice sessions
11
- *
12
- * Options:
13
- * - gemini-pro: Gemini 2.5 Pro (smart, good reasoning)
14
- * - gemini-flash: Gemini 2.0 Flash (faster, cheaper)
15
- * - gpt-4o: GPT-4o (alternative if OpenAI preferred)
16
- * - gpt-4o-mini: GPT-4o Mini (faster, cheaper)
17
- */
18
- export function createBridgeLLM(config) {
19
- switch (config.provider) {
20
- case 'gemini-pro':
21
- return new google.LLM({
22
- model: config.model || 'gemini-2.5-pro',
23
- });
24
- case 'gemini-flash':
25
- return new google.LLM({
26
- model: config.model || 'gemini-2.0-flash',
27
- });
28
- case 'gpt-4o':
29
- return new openai.LLM({
30
- model: config.model || 'gpt-4o',
31
- });
32
- case 'gpt-4o-mini':
33
- return new openai.LLM({
34
- model: config.model || 'gpt-4o-mini',
35
- });
36
- default:
37
- throw new Error(`Unknown Bridge LLM provider: ${config.provider}`);
38
- }
39
- }
@@ -1,38 +0,0 @@
1
- import { EventEmitter } from 'events';
2
- type SandboxMode = 'workspace-write' | 'danger-full-access';
3
- type ApprovalPolicy = 'on-failure' | 'on-request' | 'never';
4
- interface CodexHandlerOptions {
5
- workingDirectory?: string;
6
- skipGitRepoCheck?: boolean;
7
- sandboxMode?: SandboxMode;
8
- approvalPolicy?: ApprovalPolicy;
9
- }
10
- /**
11
- * Codex Handler using the official OpenAI Codex SDK
12
- *
13
- * Features:
14
- * - Thread persistence (reuses same thread for context)
15
- * - Built-in coding tools (file operations, terminal commands)
16
- * - Hooks for observability
17
- *
18
- * Requirements:
19
- * - Codex CLI must be installed (npm install -g @openai/codex or use npx)
20
- * - Must be authenticated via: codex login (ChatGPT) or OPENAI_API_KEY env var
21
- *
22
- * Sandbox/Approval modes are configured via:
23
- * - ~/.codex/config.yaml for global settings
24
- * - CLI flags: --sandbox, --approval-policy
25
- *
26
- * Note: The SDK spawns the CLI binary, so authentication must be done beforehand.
27
- */
28
- export declare class CodexHandler extends EventEmitter {
29
- private codex;
30
- private thread;
31
- private options;
32
- constructor(options?: CodexHandlerOptions);
33
- run(prompt: string): Promise<string>;
34
- getThreadId(): string | null;
35
- clearThread(): void;
36
- }
37
- export declare function askCodex(prompt: string, cwd?: string): Promise<string>;
38
- export {};