osborn 0.9.265 → 0.9.267

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.
@@ -290,6 +290,17 @@ export declare class ClaudeLLM extends llm.LLM {
290
290
  noteTaskDispatch(toolUseId: string | undefined, subagentType: string | undefined): void;
291
291
  /** SubagentStart claim: pair this agent_id with the oldest unclaimed dispatch of its type. */
292
292
  claimTaskDispatch(agentId: string | undefined, subagentType: string | undefined): void;
293
+ /**
294
+ * Bounded-leak fix (0.9.264): drop a finished agent's pairing entries at
295
+ * SubagentStop. BOTH maps must go together — #resolveTaskId deliberately
296
+ * returns null when a pairing exists for an ended task (so a stale stop-click
297
+ * can never retarget a DIFFERENT live agent of the same type); with both
298
+ * entries deleted the resolve is null just the same, so behavior is unchanged
299
+ * while the maps stay bounded (they previously grew one entry per sub-agent
300
+ * for the life of the session, 200+ in heavy use). #dispatchedFor is NOT
301
+ * cleared here: it IS the double-fire dedup for the SubagentStop hook itself.
302
+ */
303
+ releaseAgentTracking(agentId: string | undefined): void;
293
304
  /** Background consumer feed: track SDK task lifecycle messages. */
294
305
  trackTaskMessage(msg: any): void;
295
306
  /** Live background tasks (for truthful status/UX). */
@@ -1411,6 +1411,14 @@ export class ClaudeLLM extends llm.LLM {
1411
1411
  captureCheckpoint(checkpointId) {
1412
1412
  this.#checkpoints.push(checkpointId);
1413
1413
  this.#latestCheckpoint = checkpointId;
1414
+ // Bounded-leak fix (0.9.264): a checkpoint lands on EVERY user-type SDK
1415
+ // message (tool results included) — thousands over a long session, never
1416
+ // pruned. Rewind only ever consumes the FIRST (getFirstCheckpoint →
1417
+ // session start) and the LATEST (#latestCheckpoint, kept separately), so
1418
+ // retain [0] + the most recent 500 and drop the middle.
1419
+ if (this.#checkpoints.length > 600) {
1420
+ this.#checkpoints.splice(1, this.#checkpoints.length - 501);
1421
+ }
1414
1422
  console.log(`📍 Checkpoint captured: ${checkpointId.substring(0, 8)}...`);
1415
1423
  this.#eventEmitter.emit('checkpoint_captured', { checkpointId });
1416
1424
  }
@@ -1670,6 +1678,22 @@ export class ClaudeLLM extends llm.LLM {
1670
1678
  this.#toolUseByAgentId.set(agentId, toolUse);
1671
1679
  }
1672
1680
  }
1681
+ /**
1682
+ * Bounded-leak fix (0.9.264): drop a finished agent's pairing entries at
1683
+ * SubagentStop. BOTH maps must go together — #resolveTaskId deliberately
1684
+ * returns null when a pairing exists for an ended task (so a stale stop-click
1685
+ * can never retarget a DIFFERENT live agent of the same type); with both
1686
+ * entries deleted the resolve is null just the same, so behavior is unchanged
1687
+ * while the maps stay bounded (they previously grew one entry per sub-agent
1688
+ * for the life of the session, 200+ in heavy use). #dispatchedFor is NOT
1689
+ * cleared here: it IS the double-fire dedup for the SubagentStop hook itself.
1690
+ */
1691
+ releaseAgentTracking(agentId) {
1692
+ if (!agentId)
1693
+ return;
1694
+ this.#toolUseByAgentId.delete(agentId);
1695
+ this.#typeByAgentId.delete(agentId);
1696
+ }
1673
1697
  /** Background consumer feed: track SDK task lifecycle messages. */
1674
1698
  trackTaskMessage(msg) {
1675
1699
  if (msg?.type !== 'system')
@@ -2771,6 +2795,10 @@ class ClaudeLLMStream extends llm.LLMStream {
2771
2795
  console.warn('Pattern#1 chain push failed:', e);
2772
2796
  }
2773
2797
  }
2798
+ // Bounded-leak fix (0.9.264): the agent is done — release its
2799
+ // pairing entries (after the chain logic above has run).
2800
+ if (input?.agent_id)
2801
+ this.#llmRef.releaseAgentTracking(input.agent_id);
2774
2802
  return {};
2775
2803
  }]
2776
2804
  }],
package/dist/index.js CHANGED
@@ -559,6 +559,51 @@ function startApiServer(workingDir, port) {
559
559
  }
560
560
  return;
561
561
  }
562
+ if (req.method === 'GET' && url.pathname === '/session-messages') {
563
+ // Prior-conversation hydration for the chat page. The browser calls this at
564
+ // MOUNT, in parallel with the LiveKit connect, so the resumed transcript
565
+ // paints before the voice handshake finishes. Reads the per-session recall
566
+ // store directly (readonly, no JSONL replay) — same source as the
567
+ // data-channel prior_messages push, which remains the fallback for older
568
+ // frontends. Rows carry real timestamps so the UI can date-stamp them.
569
+ try {
570
+ const sessionId = url.searchParams.get('session') || '';
571
+ const limit = Math.min(parseInt(url.searchParams.get('limit') || '50', 10), 200);
572
+ if (!sessionId) {
573
+ res.writeHead(400, { 'Content-Type': 'application/json' });
574
+ res.end(JSON.stringify({ error: 'session required' }));
575
+ return;
576
+ }
577
+ const dbPath = storeExists(sessionId, workingDir);
578
+ if (!dbPath) {
579
+ res.writeHead(200, { 'Content-Type': 'application/json' });
580
+ res.end(JSON.stringify({ sessionId, messages: [] }));
581
+ return;
582
+ }
583
+ const db = openStore(dbPath, { readonly: true });
584
+ try {
585
+ const rows = recentRows(db, limit, ['user', 'assistant']);
586
+ const messages = rows
587
+ .reverse() // newest-first → chronological
588
+ .map(r => ({ role: r.msgType === 'assistant' ? 'assistant' : 'user', content: (r.text || '').slice(0, 1200), ts: r.ts || null }))
589
+ .filter(m => m.content.trim().length > 0);
590
+ res.writeHead(200, { 'Content-Type': 'application/json' });
591
+ res.end(JSON.stringify({ sessionId, messages }));
592
+ }
593
+ finally {
594
+ try {
595
+ db.close();
596
+ }
597
+ catch { }
598
+ }
599
+ }
600
+ catch (err) {
601
+ console.error('API /session-messages error:', err);
602
+ res.writeHead(500, { 'Content-Type': 'application/json' });
603
+ res.end(JSON.stringify({ error: 'failed to read session messages' }));
604
+ }
605
+ return;
606
+ }
562
607
  if (req.method === 'GET' && url.pathname === '/canvas-token') {
563
608
  // Listen-only LiveKit credentials for the meeting canvas (see hook doc).
564
609
  const out = canvasTokenHook ? await canvasTokenHook() : null;
@@ -5260,7 +5305,7 @@ async function main() {
5260
5305
  const rows = recentRows(db, 20, ['user', 'assistant']); // newest-first
5261
5306
  const priorMessages = rows
5262
5307
  .reverse() // → chronological
5263
- .map(r => ({ role: r.msgType === 'assistant' ? 'assistant' : 'user', content: (r.text || '').slice(0, 800) }))
5308
+ .map(r => ({ role: r.msgType === 'assistant' ? 'assistant' : 'user', content: (r.text || '').slice(0, 800), ts: r.ts || null }))
5264
5309
  .filter(m => m.content.trim().length > 0);
5265
5310
  if (priorMessages.length > 0) {
5266
5311
  await sendToFrontend({ type: 'prior_messages', sessionId: preSelectedSessionId, messages: priorMessages });
@@ -6548,92 +6593,103 @@ async function main() {
6548
6593
  // attempts fail we surface status='failed' and rethrow so the caller sees it.
6549
6594
  // A single transient blip is absorbed; a persistent failure (quota/auth) is
6550
6595
  // reported promptly rather than hanging the connect flow.
6551
- let creatingRoomSession = false;
6596
+ // Tracks an in-flight createRoomSession so concurrent /connect-room calls
6597
+ // await the same underlying room.connect() rather than racing or triggering a
6598
+ // double-connect cycle (which previously doubled cold-path latency when the
6599
+ // sandbox route's 6s timeout fired before room.connect() finished).
6600
+ let createRoomSessionInflight = null;
6552
6601
  const createRoomSession = async (targetRoomName) => {
6553
- if (creatingRoomSession) {
6554
- console.log('⏳ createRoomSession already in progress — skipping duplicate');
6555
- return;
6602
+ if (createRoomSessionInflight) {
6603
+ console.log('⏳ createRoomSession already in progress — awaiting in-flight connect (idempotent)');
6604
+ return createRoomSessionInflight;
6556
6605
  }
6557
- creatingRoomSession = true;
6558
- try {
6559
- // Discard any prior (dead/stale) instance without reuse.
6560
- if (activeRoom) {
6561
- console.warn('⚠️ createRoomSession called with an existing activeRoom — discarding it (no reuse)');
6562
- activeRoom = null;
6563
- }
6564
- const room = new Room();
6565
- room.setMaxListeners(50); // Prevent MaxListenersExceeded warnings
6566
- wireRoomHandlers(room);
6567
- const backoffSchedule = [5_000, 10_000, 20_000];
6568
- let lastErr = null;
6569
- for (let attempt = 0; attempt < 3; attempt++) {
6570
- livekitState.status = livekitState.attemptCount === 0 ? 'connecting' : 'retrying';
6571
- livekitState.lastAttemptAt = Date.now();
6572
- livekitState.attemptCount += 1;
6573
- try {
6574
- const jwt = await mintAgentToken(targetRoomName);
6575
- await room.connect(livekitUrl, jwt, {
6576
- autoSubscribe: true,
6577
- dynacast: true,
6578
- });
6579
- // Success — adopt this instance as the active room.
6580
- activeRoom = room;
6581
- activeRoomName = targetRoomName;
6582
- currentRoomCode = targetRoomName; // legacy /room-code returns last-created NAME
6583
- localParticipant = room.localParticipant;
6584
- livekitState.status = 'connected';
6585
- livekitState.error = null;
6586
- livekitState.errorCode = null;
6587
- console.log('✅ Connected to room:', targetRoomName);
6588
- // Post-connect setup (re-homed from the dead RoomEvent.Connected handler).
6589
- postConnectSetup(room, targetRoomName);
6590
- // Adopt-sweep: ParticipantConnected only fires for participants who join
6591
- // AFTER us. Anyone already in the room at connect time is populated by
6592
- // rtc-node from the connect callback (no event) — invoke the handler
6593
- // directly so their voice session is created. Runs exactly once per
6594
- // connect (replaces the old adopt-poll + connectRoomHook adopt loop).
6595
- for (const p of room.remoteParticipants.values()) {
6596
- console.log(`👥 Participant already in room at join: ${p.identity} — adopting (invoking handler directly)`);
6597
- participantConnectedHandler?.(p).catch((e) => console.error('👥 adopt handler error:', e instanceof Error ? e.message : e));
6606
+ const run = async () => {
6607
+ try {
6608
+ // Discard any prior (dead/stale) instance without reuse.
6609
+ if (activeRoom) {
6610
+ console.warn('⚠️ createRoomSession called with an existing activeRoom — discarding it (no reuse)');
6611
+ activeRoom = null;
6612
+ }
6613
+ const room = new Room();
6614
+ room.setMaxListeners(50); // Prevent MaxListenersExceeded warnings
6615
+ wireRoomHandlers(room);
6616
+ const backoffSchedule = [5_000, 10_000, 20_000];
6617
+ let lastErr = null;
6618
+ for (let attempt = 0; attempt < 3; attempt++) {
6619
+ livekitState.status = livekitState.attemptCount === 0 ? 'connecting' : 'retrying';
6620
+ livekitState.lastAttemptAt = Date.now();
6621
+ livekitState.attemptCount += 1;
6622
+ try {
6623
+ const t0 = Date.now();
6624
+ const jwt = await mintAgentToken(targetRoomName);
6625
+ const t1 = Date.now();
6626
+ await room.connect(livekitUrl, jwt, {
6627
+ autoSubscribe: true,
6628
+ dynacast: true,
6629
+ });
6630
+ const t2 = Date.now();
6631
+ console.log(`⏱️ [room-connect] mintToken=${t1 - t0}ms connect=${t2 - t1}ms total=${t2 - t0}ms`);
6632
+ // Success — adopt this instance as the active room.
6633
+ activeRoom = room;
6634
+ activeRoomName = targetRoomName;
6635
+ currentRoomCode = targetRoomName; // legacy /room-code returns last-created NAME
6636
+ localParticipant = room.localParticipant;
6637
+ livekitState.status = 'connected';
6638
+ livekitState.error = null;
6639
+ livekitState.errorCode = null;
6640
+ console.log('✅ Connected to room:', targetRoomName);
6641
+ // Post-connect setup (re-homed from the dead RoomEvent.Connected handler).
6642
+ postConnectSetup(room, targetRoomName);
6643
+ // Adopt-sweep: ParticipantConnected only fires for participants who join
6644
+ // AFTER us. Anyone already in the room at connect time is populated by
6645
+ // rtc-node from the connect callback (no event) — invoke the handler
6646
+ // directly so their voice session is created. Runs exactly once per
6647
+ // connect (replaces the old adopt-poll + connectRoomHook adopt loop).
6648
+ for (const p of room.remoteParticipants.values()) {
6649
+ console.log(`👥 Participant already in room at join: ${p.identity} — adopting (invoking handler directly)`);
6650
+ participantConnectedHandler?.(p).catch((e) => console.error('👥 adopt handler error:', e instanceof Error ? e.message : e));
6651
+ }
6652
+ console.log('\n⏳ Waiting for user to connect...');
6653
+ console.log(` Room: ${targetRoomName}\n`);
6654
+ return;
6598
6655
  }
6599
- console.log('\n⏳ Waiting for user to connect...');
6600
- console.log(` Room: ${targetRoomName}\n`);
6601
- return;
6602
- }
6603
- catch (err) {
6604
- lastErr = err;
6605
- const msg = err instanceof Error ? err.message : String(err);
6606
- // Categorize the error so the frontend can show specific guidance.
6607
- let errorCode;
6608
- if (/429|connection minutes limit/i.test(msg))
6609
- errorCode = 'quota_exceeded';
6610
- else if (/401|403|unauthorized|invalid/i.test(msg))
6611
- errorCode = 'auth';
6612
- else if (/ENOTFOUND|ECONNREFUSED|ETIMEDOUT|network/i.test(msg))
6613
- errorCode = 'network';
6614
- else
6615
- errorCode = 'unknown';
6616
- livekitState.status = 'failed';
6617
- livekitState.error = msg;
6618
- livekitState.errorCode = errorCode;
6619
- console.error(`❌ LiveKit connect failed (${errorCode}, attempt ${attempt + 1}/3): ${msg.substring(0, 200)}`);
6620
- if (attempt < 2) {
6621
- const waitMs = backoffSchedule[attempt];
6622
- console.error(` Retrying in ${waitMs / 1000}s...`);
6623
- await new Promise(r => setTimeout(r, waitMs));
6656
+ catch (err) {
6657
+ lastErr = err;
6658
+ const msg = err instanceof Error ? err.message : String(err);
6659
+ // Categorize the error so the frontend can show specific guidance.
6660
+ let errorCode;
6661
+ if (/429|connection minutes limit/i.test(msg))
6662
+ errorCode = 'quota_exceeded';
6663
+ else if (/401|403|unauthorized|invalid/i.test(msg))
6664
+ errorCode = 'auth';
6665
+ else if (/ENOTFOUND|ECONNREFUSED|ETIMEDOUT|network/i.test(msg))
6666
+ errorCode = 'network';
6667
+ else
6668
+ errorCode = 'unknown';
6669
+ livekitState.status = 'failed';
6670
+ livekitState.error = msg;
6671
+ livekitState.errorCode = errorCode;
6672
+ console.error(`❌ LiveKit connect failed (${errorCode}, attempt ${attempt + 1}/3): ${msg.substring(0, 200)}`);
6673
+ if (attempt < 2) {
6674
+ const waitMs = backoffSchedule[attempt];
6675
+ console.error(` Retrying in ${waitMs / 1000}s...`);
6676
+ await new Promise(r => setTimeout(r, waitMs));
6677
+ }
6624
6678
  }
6625
6679
  }
6680
+ // All attempts failed. Drop the dead instance; leave status='failed' so
6681
+ // /health surfaces it and the frontend can retry /connect-room.
6682
+ activeRoom = null;
6683
+ activeRoomName = null;
6684
+ console.error('❌ createRoomSession: all 3 connect attempts failed — giving up (status=failed)');
6685
+ throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
6626
6686
  }
6627
- // All attempts failed. Drop the dead instance; leave status='failed' so
6628
- // /health surfaces it and the frontend can retry /connect-room.
6629
- activeRoom = null;
6630
- activeRoomName = null;
6631
- console.error('❌ createRoomSession: all 3 connect attempts failed — giving up (status=failed)');
6632
- throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
6633
- }
6634
- finally {
6635
- creatingRoomSession = false;
6636
- }
6687
+ finally {
6688
+ createRoomSessionInflight = null;
6689
+ }
6690
+ };
6691
+ createRoomSessionInflight = run();
6692
+ return createRoomSessionInflight;
6637
6693
  };
6638
6694
  // destroyRoomSession(reason): tear down the active room session and DISCARD
6639
6695
  // the Room instance (never reused). A hung rtc-node disconnect() (signal-less
@@ -6724,7 +6780,11 @@ async function main() {
6724
6780
  const targetRoomName = buildRoomName();
6725
6781
  console.log(`🔌 /connect-room — creating fresh room session: ${targetRoomName}`);
6726
6782
  await createRoomSession(targetRoomName);
6727
- return targetRoomName;
6783
+ // Return the room the agent actually joined. When a concurrent /connect-room
6784
+ // call awaited an in-flight session, activeRoomName is the first call's room
6785
+ // name — which differs from targetRoomName generated here. Always use the
6786
+ // actual active name so the client mints a token for the right room.
6787
+ return activeRoomName || targetRoomName;
6728
6788
  };
6729
6789
  leaveRoomHook = async (reason) => {
6730
6790
  if (aloneTimer) {
@@ -18,13 +18,15 @@
18
18
  // Model reads from env var (set by main process from getInferenceConfig) or DEFAULT_CONFIG default.
19
19
  // To switch model: update DEFAULT_CONFIG.inference.fastBrainModel in config.ts, or set OSBORN_FAST_BRAIN_MODEL env var.
20
20
  // Provider switch: Fireworks (OpenAI-compatible) when FIREWORKS_API_KEY is set, else
21
- // OpenRouter. Default Fireworks model: deepseek-v4p1-flash — v3p1 is deprecated off
22
- // Fireworks serverless (verified 2026-10-22 via the model page metadata); V4.1 Flash
23
- // is the live successor in the same fast/cheap DeepSeek class (262K ctx, tool calls).
21
+ // OpenRouter. Default Fireworks model: gpt-oss-120b — $0.15/M (docs.fireworks.ai/
22
+ // serverless/pricing, verified 2026-10-22), strictly cheaper than the old OpenRouter
23
+ // deepseek-chat ($0.257/M in, $1.029/M out) on BOTH input and output, with strong
24
+ // OpenAI-style function calling (the fast brain is a tool loop). Same-price alternate:
25
+ // accounts/fireworks/models/glm-5p3-flash ($0.15/M) via OSBORN_FAST_BRAIN_MODEL.
24
26
  const FIREWORKS = !!process.env.FIREWORKS_API_KEY;
25
27
  const PROVIDER_NAME = FIREWORKS ? 'Fireworks' : 'OpenRouter';
26
28
  const OPENROUTER_MODEL = process.env.OSBORN_FAST_BRAIN_MODEL ||
27
- (FIREWORKS ? 'accounts/fireworks/models/deepseek-v4p1-flash' : 'deepseek/deepseek-chat');
29
+ (FIREWORKS ? 'accounts/fireworks/models/gpt-oss-120b' : 'deepseek/deepseek-chat');
28
30
  const OPENROUTER_URL = FIREWORKS
29
31
  ? 'https://api.fireworks.ai/inference/v1/chat/completions'
30
32
  : 'https://openrouter.ai/api/v1/chat/completions';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osborn",
3
- "version": "0.9.265",
3
+ "version": "0.9.267",
4
4
  "description": "Voice AI coding assistant - local agent that connects to Osborn frontend",
5
5
  "type": "module",
6
6
  "bin": {
@@ -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 {};
@@ -1,83 +0,0 @@
1
- import { Codex } from '@openai/codex-sdk';
2
- import { EventEmitter } from 'events';
3
- /**
4
- * Codex Handler using the official OpenAI Codex SDK
5
- *
6
- * Features:
7
- * - Thread persistence (reuses same thread for context)
8
- * - Built-in coding tools (file operations, terminal commands)
9
- * - Hooks for observability
10
- *
11
- * Requirements:
12
- * - Codex CLI must be installed (npm install -g @openai/codex or use npx)
13
- * - Must be authenticated via: codex login (ChatGPT) or OPENAI_API_KEY env var
14
- *
15
- * Sandbox/Approval modes are configured via:
16
- * - ~/.codex/config.yaml for global settings
17
- * - CLI flags: --sandbox, --approval-policy
18
- *
19
- * Note: The SDK spawns the CLI binary, so authentication must be done beforehand.
20
- */
21
- export class CodexHandler extends EventEmitter {
22
- codex;
23
- thread = null;
24
- options;
25
- constructor(options = {}) {
26
- super();
27
- this.options = {
28
- workingDirectory: options.workingDirectory || process.cwd(),
29
- skipGitRepoCheck: options.skipGitRepoCheck ?? true,
30
- };
31
- // Initialize Codex (inherits process env by default)
32
- this.codex = new Codex();
33
- }
34
- async run(prompt) {
35
- try {
36
- // Create or reuse thread
37
- if (!this.thread) {
38
- console.log('🆕 Starting new Codex thread');
39
- this.thread = this.codex.startThread({
40
- workingDirectory: this.options.workingDirectory,
41
- skipGitRepoCheck: this.options.skipGitRepoCheck,
42
- });
43
- }
44
- else {
45
- console.log('🔄 Continuing Codex thread');
46
- }
47
- console.log(`📁 CWD: ${this.options.workingDirectory}`);
48
- this.emit('thinking', prompt);
49
- // Run the prompt and get the Turn result
50
- const turn = await this.thread.run(prompt);
51
- // Extract the final response text
52
- const result = turn.finalResponse || '';
53
- this.emit('result', result);
54
- console.log(`✅ Codex done. Length: ${result.length}`);
55
- // Log tool usage if any
56
- if (turn.items && turn.items.length > 0) {
57
- for (const item of turn.items) {
58
- this.emit('tool_use', item);
59
- }
60
- }
61
- return result || 'Task completed.';
62
- }
63
- catch (error) {
64
- console.error('❌ Codex SDK error:', error);
65
- this.emit('error', error);
66
- throw error;
67
- }
68
- }
69
- getThreadId() {
70
- // Codex threads have IDs but they may not be directly exposed
71
- // Check the thread object for an id property
72
- return this.thread?.id || null;
73
- }
74
- clearThread() {
75
- this.thread = null;
76
- console.log('🗑️ Codex thread cleared');
77
- }
78
- }
79
- // Quick utility for one-off queries
80
- export async function askCodex(prompt, cwd) {
81
- const handler = new CodexHandler({ workingDirectory: cwd });
82
- return handler.run(prompt);
83
- }
@@ -1,40 +0,0 @@
1
- /**
2
- * Codex LLM Wrapper for LiveKit Agents
3
- *
4
- * Wraps the Codex Agent SDK (@openai/codex-sdk) to work
5
- * with LiveKit's AgentSession as an LLM provider.
6
- *
7
- * Flow: User speaks → STT → CodexLLM (Agent SDK) → TTS → User hears
8
- */
9
- import { llm, type APIConnectOptions } from '@livekit/agents';
10
- import { Codex } from '@openai/codex-sdk';
11
- import { EventEmitter } from 'events';
12
- export interface CodexLLMOptions {
13
- workingDirectory?: string;
14
- skipGitRepoCheck?: boolean;
15
- /** Event emitter for tool_use, progress updates */
16
- eventEmitter?: EventEmitter;
17
- }
18
- /**
19
- * Codex LLM - Wraps Codex Agent SDK for LiveKit
20
- */
21
- export declare class CodexLLM extends llm.LLM {
22
- #private;
23
- constructor(opts?: CodexLLMOptions);
24
- label(): string;
25
- get model(): string;
26
- get events(): EventEmitter;
27
- get thread(): ReturnType<Codex['startThread']> | null;
28
- chat({ chatCtx, toolCtx, connOptions, }: {
29
- chatCtx: llm.ChatContext;
30
- toolCtx?: llm.ToolContext;
31
- connOptions?: APIConnectOptions;
32
- parallelToolCalls?: boolean;
33
- toolChoice?: llm.ToolChoice;
34
- extraKwargs?: Record<string, unknown>;
35
- }): llm.LLMStream;
36
- }
37
- /**
38
- * Create a CodexLLM instance
39
- */
40
- export declare function createCodexLLM(opts?: CodexLLMOptions): CodexLLM;