osborn 0.9.267 → 0.9.269
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/dist/bridge-llm.d.ts +22 -0
- package/dist/bridge-llm.js +39 -0
- package/dist/claude-auth.js +33 -4
- package/dist/claude-llm.js +22 -0
- package/dist/codex-handler.d.ts +38 -0
- package/dist/codex-handler.js +83 -0
- package/dist/codex-llm.d.ts +40 -0
- package/dist/codex-llm.js +144 -0
- package/dist/fast-brain.d.ts +176 -0
- package/dist/fast-brain.js +1887 -0
- package/dist/index-3-2-26-legacy.d.ts +1 -0
- package/dist/index-3-2-26-legacy.js +2233 -0
- package/dist/leagcyprompts2.d.ts +0 -0
- package/dist/leagcyprompts2.js +573 -0
- package/dist/pipeline-fastbrain.js +69 -6
- package/dist/prompts-2-25-26.d.ts +0 -0
- package/dist/prompts-2-25-26.js +518 -0
- package/dist/prompts-3-2-26.d.ts +78 -0
- package/dist/prompts-3-2-26.js +1319 -0
- package/dist/summary-index.d.ts +90 -0
- package/dist/summary-index.js +585 -0
- package/package.json +1 -1
|
@@ -0,0 +1,22 @@
|
|
|
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;
|
|
@@ -0,0 +1,39 @@
|
|
|
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
|
+
}
|
package/dist/claude-auth.js
CHANGED
|
@@ -177,7 +177,33 @@ export function applyAuthFallback() {
|
|
|
177
177
|
if (process.env.ANTHROPIC_API_KEY && process.env.ANTHROPIC_API_KEY.trim() !== '') {
|
|
178
178
|
return;
|
|
179
179
|
}
|
|
180
|
-
// Tier 3:
|
|
180
|
+
// Tier 3: HOUSE DEMO PASS - z.ai GLM coding subscription (flat/shared, not
|
|
181
|
+
// pay-per-use). Cline/opencode-style: unauthenticated demo users ride the
|
|
182
|
+
// house pass instead of raw API billing. The z.ai Anthropic-compatible
|
|
183
|
+
// endpoint (api.z.ai/api/anthropic) speaks native Messages - verified live
|
|
184
|
+
// 2026-10-24 (glm-4.7 returned a real response). Precedence: Z_AI_PERSONAL_API_KEY
|
|
185
|
+
// (verified working; ZAI_STANDARD_API_KEY in .env is expired).
|
|
186
|
+
const zaiKey = process.env.Z_AI_PERSONAL_API_KEY || process.env.ZAI_API_KEY;
|
|
187
|
+
if (zaiKey && zaiKey.trim() !== '') {
|
|
188
|
+
// Native Anthropic-Messages endpoint - no local translation proxy needed.
|
|
189
|
+
process.env.ANTHROPIC_BASE_URL = process.env.OSBORN_DEMO_BASE_URL || 'https://api.z.ai/api/anthropic';
|
|
190
|
+
process.env.ANTHROPIC_AUTH_TOKEN = zaiKey;
|
|
191
|
+
process.env.ANTHROPIC_API_KEY = ''; // required - a set key bypasses AUTH_TOKEN
|
|
192
|
+
const demoModel = process.env.OSBORN_DEMO_MODEL || 'glm-4.7';
|
|
193
|
+
process.env.ANTHROPIC_MODEL = demoModel;
|
|
194
|
+
process.env.ANTHROPIC_SMALL_FAST_MODEL = demoModel;
|
|
195
|
+
process.env.CLAUDE_CODE_SUBAGENT_MODEL = demoModel;
|
|
196
|
+
process.env.CLAUDE_CODE_SUBAGENT_MODEL_FORCE = demoModel;
|
|
197
|
+
// GLM-4.7 exposes a 200K window; pins the CLI's context-cap handling.
|
|
198
|
+
process.env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = process.env.OSBORN_DEMO_MAX_CONTEXT || '200000';
|
|
199
|
+
// Signal for the fast brain (pipeline-fastbrain reads this per call) so the
|
|
200
|
+
// WHOLE model layer - main agent AND fast brain - rides the same pass.
|
|
201
|
+
process.env.OSBORN_DEMO_PASS = 'zai';
|
|
202
|
+
fallbackTierActive = true;
|
|
203
|
+
console.log(`[auth-fallback] using house demo pass (z.ai), model=${demoModel}`);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
// Tier 4: central OpenRouter key (pay-per-use fallback of the fallback).
|
|
181
207
|
const openRouterKey = process.env.OPENROUTER_API_KEY;
|
|
182
208
|
if (openRouterKey && openRouterKey.trim() !== '') {
|
|
183
209
|
// Native Anthropic-Messages endpoint — no local translation proxy needed.
|
|
@@ -207,8 +233,8 @@ export function applyAuthFallback() {
|
|
|
207
233
|
console.log(`[auth-fallback] using central OpenRouter tier, model=${FALLBACK_MODEL}`);
|
|
208
234
|
return;
|
|
209
235
|
}
|
|
210
|
-
// Tier
|
|
211
|
-
console.warn('[auth-fallback] no Claude login, no ANTHROPIC_API_KEY, and no OPENROUTER_API_KEY — agent may be unauthenticated');
|
|
236
|
+
// Tier 4 fail: no fallback key at all — do NOT throw.
|
|
237
|
+
console.warn('[auth-fallback] no Claude login, no ANTHROPIC_API_KEY, no Z_AI key, and no OPENROUTER_API_KEY — agent may be unauthenticated');
|
|
212
238
|
}
|
|
213
239
|
/**
|
|
214
240
|
* Clear the OpenRouter fallback redirect — but ONLY if applyAuthFallback() set
|
|
@@ -229,8 +255,11 @@ function clearAuthFallbackIfActive() {
|
|
|
229
255
|
// must be unset so the per-agent sonnet/opus fields take effect again.
|
|
230
256
|
delete process.env.CLAUDE_CODE_SUBAGENT_MODEL;
|
|
231
257
|
delete process.env.CLAUDE_CODE_SUBAGENT_MODEL_FORCE;
|
|
258
|
+
// Demo-pass signal - without this a post-login fast brain would keep routing
|
|
259
|
+
// to the house z.ai pass instead of the user's own pay-per-use providers.
|
|
260
|
+
delete process.env.OSBORN_DEMO_PASS;
|
|
232
261
|
fallbackTierActive = false;
|
|
233
|
-
console.log('[auth-fallback] real Claude login completed — cleared
|
|
262
|
+
console.log('[auth-fallback] real Claude login completed — cleared fallback redirect');
|
|
234
263
|
}
|
|
235
264
|
/**
|
|
236
265
|
* Check auth via `claude auth status` (most reliable).
|
package/dist/claude-llm.js
CHANGED
|
@@ -373,6 +373,28 @@ process.env.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE = '75'; // auto-compact at 75% of 1M
|
|
|
373
373
|
if (!process.env.ANTHROPIC_SMALL_FAST_MODEL) {
|
|
374
374
|
process.env.ANTHROPIC_SMALL_FAST_MODEL = 'claude-haiku-4-5-20251001';
|
|
375
375
|
}
|
|
376
|
+
// RESUME-TURN 400 FIX: disable the Claude Code CLI's prompt-cache *diagnostics*
|
|
377
|
+
// on outbound /v1/messages. Recent CLI builds opt the request into the
|
|
378
|
+
// `diagnostics.previous_message_id` feature (the `msg_...` id of the client's
|
|
379
|
+
// previous response, so the server can report prompt-cache cache-miss reasons —
|
|
380
|
+
// pure telemetry we never read). On a FRESH session turn 1 sends
|
|
381
|
+
// `previous_message_id: null` (the valid "opt-in with no prior message" case),
|
|
382
|
+
// so it works. On a RESUMED session the CLI rebuilds conversation state from the
|
|
383
|
+
// replayed JSONL but has NO in-memory `msg_...` id for the last response (that id
|
|
384
|
+
// is never persisted to the transcript), so the first post-resume turn sends an
|
|
385
|
+
// invalid/empty/non-`msg_` value and the API 400s:
|
|
386
|
+
// diagnostics.previous_message_id: must be the `id` from a prior /v1/messages
|
|
387
|
+
// response (starts with `msg_`)
|
|
388
|
+
// — twice (the CLI's one turn retry), after which only the Fast Brain fallback
|
|
389
|
+
// answers. The diagnostics request-adornment is non-essential traffic, which the
|
|
390
|
+
// CLI suppresses entirely under this flag, so it never attaches
|
|
391
|
+
// `previous_message_id` — fixing resume with zero behavioral change beyond losing
|
|
392
|
+
// cache-miss telemetry. Set at module load (same lifecycle as ENABLE_1M_CONTEXT):
|
|
393
|
+
// the subprocess reads env once at cold-start, so a per-message write would be too
|
|
394
|
+
// late for the persistent query. Respect an explicit operator override.
|
|
395
|
+
if (process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC === undefined) {
|
|
396
|
+
process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = '1';
|
|
397
|
+
}
|
|
376
398
|
// Research mode tools — full research capabilities
|
|
377
399
|
// Named sub-agents — the orchestrator delegates to these specialists. Each has
|
|
378
400
|
// a specific role, model, and tool set. Module-level + exported so the HTTP
|
|
@@ -0,0 +1,38 @@
|
|
|
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 {};
|
|
@@ -0,0 +1,83 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
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;
|
|
@@ -0,0 +1,144 @@
|
|
|
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, shortuuid, DEFAULT_API_CONNECT_OPTIONS } from '@livekit/agents';
|
|
10
|
+
import { Codex } from '@openai/codex-sdk';
|
|
11
|
+
import { EventEmitter } from 'events';
|
|
12
|
+
/**
|
|
13
|
+
* Codex LLM - Wraps Codex Agent SDK for LiveKit
|
|
14
|
+
*/
|
|
15
|
+
export class CodexLLM extends llm.LLM {
|
|
16
|
+
#opts;
|
|
17
|
+
#codex;
|
|
18
|
+
#thread = null;
|
|
19
|
+
#eventEmitter;
|
|
20
|
+
constructor(opts = {}) {
|
|
21
|
+
super();
|
|
22
|
+
this.#opts = {
|
|
23
|
+
workingDirectory: opts.workingDirectory || process.cwd(),
|
|
24
|
+
skipGitRepoCheck: opts.skipGitRepoCheck ?? true,
|
|
25
|
+
};
|
|
26
|
+
this.#codex = new Codex();
|
|
27
|
+
this.#eventEmitter = opts.eventEmitter || new EventEmitter();
|
|
28
|
+
console.log('🟣 CodexLLM initialized (Codex Agent SDK)');
|
|
29
|
+
console.log(` 📁 Working dir: ${this.#opts.workingDirectory}`);
|
|
30
|
+
}
|
|
31
|
+
label() {
|
|
32
|
+
return 'codex.agent-sdk';
|
|
33
|
+
}
|
|
34
|
+
get model() {
|
|
35
|
+
return 'codex';
|
|
36
|
+
}
|
|
37
|
+
get events() {
|
|
38
|
+
return this.#eventEmitter;
|
|
39
|
+
}
|
|
40
|
+
get thread() {
|
|
41
|
+
return this.#thread;
|
|
42
|
+
}
|
|
43
|
+
chat({ chatCtx, toolCtx, connOptions = DEFAULT_API_CONNECT_OPTIONS, }) {
|
|
44
|
+
return new CodexLLMStream(this, {
|
|
45
|
+
chatCtx,
|
|
46
|
+
toolCtx,
|
|
47
|
+
connOptions,
|
|
48
|
+
opts: this.#opts,
|
|
49
|
+
codex: this.#codex,
|
|
50
|
+
thread: this.#thread,
|
|
51
|
+
onThread: (t) => { this.#thread = t; },
|
|
52
|
+
eventEmitter: this.#eventEmitter,
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Codex LLM Stream - Runs Codex Agent SDK and streams results
|
|
58
|
+
*/
|
|
59
|
+
class CodexLLMStream extends llm.LLMStream {
|
|
60
|
+
#opts;
|
|
61
|
+
#codex;
|
|
62
|
+
#thread;
|
|
63
|
+
#onThread;
|
|
64
|
+
#eventEmitter;
|
|
65
|
+
constructor(llmInstance, { chatCtx, toolCtx, connOptions, opts, codex, thread, onThread, eventEmitter, }) {
|
|
66
|
+
super(llmInstance, { chatCtx, toolCtx, connOptions });
|
|
67
|
+
this.#opts = opts;
|
|
68
|
+
this.#codex = codex;
|
|
69
|
+
this.#thread = thread;
|
|
70
|
+
this.#onThread = onThread;
|
|
71
|
+
this.#eventEmitter = eventEmitter;
|
|
72
|
+
}
|
|
73
|
+
async run() {
|
|
74
|
+
const requestId = `codex_${shortuuid()}`;
|
|
75
|
+
try {
|
|
76
|
+
// Extract user's message from chat context
|
|
77
|
+
// ChatContext has .items which are ChatItem[] (ChatMessage | FunctionCall | FunctionCallOutput)
|
|
78
|
+
const items = this.chatCtx.items;
|
|
79
|
+
// Find the last user message
|
|
80
|
+
let userText = '';
|
|
81
|
+
for (let i = items.length - 1; i >= 0; i--) {
|
|
82
|
+
const item = items[i];
|
|
83
|
+
if (item.type === 'message' && item.role === 'user') {
|
|
84
|
+
// Content is ChatContent[] = (ImageContent | AudioContent | string)[]
|
|
85
|
+
if (Array.isArray(item.content)) {
|
|
86
|
+
userText = item.content
|
|
87
|
+
.filter((c) => typeof c === 'string')
|
|
88
|
+
.join('\n');
|
|
89
|
+
}
|
|
90
|
+
break;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (!userText.trim()) {
|
|
94
|
+
this.queue.put({
|
|
95
|
+
id: requestId,
|
|
96
|
+
delta: { role: 'assistant', content: "I didn't catch that. Could you repeat?" },
|
|
97
|
+
});
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
console.log(`🎤 User (${userText.length} chars): "${userText}"`);
|
|
101
|
+
// Create or reuse thread
|
|
102
|
+
if (!this.#thread) {
|
|
103
|
+
console.log('🆕 Starting new Codex thread');
|
|
104
|
+
this.#thread = this.#codex.startThread({
|
|
105
|
+
workingDirectory: this.#opts.workingDirectory,
|
|
106
|
+
skipGitRepoCheck: this.#opts.skipGitRepoCheck,
|
|
107
|
+
});
|
|
108
|
+
this.#onThread(this.#thread);
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
console.log('🔄 Continuing Codex thread');
|
|
112
|
+
}
|
|
113
|
+
// Run Codex and get result
|
|
114
|
+
const turn = await this.#thread.run(userText);
|
|
115
|
+
// Emit tool usage events
|
|
116
|
+
if (turn.items && turn.items.length > 0) {
|
|
117
|
+
for (const item of turn.items) {
|
|
118
|
+
console.log(`🔧 Codex: ${item.type || 'action'}`);
|
|
119
|
+
this.#eventEmitter.emit('tool_use', item);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
// Send response to TTS
|
|
123
|
+
const result = turn.finalResponse || 'Done.';
|
|
124
|
+
this.queue.put({
|
|
125
|
+
id: requestId,
|
|
126
|
+
delta: { role: 'assistant', content: result },
|
|
127
|
+
});
|
|
128
|
+
console.log('✅ Codex response complete');
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
console.error('❌ Codex Agent SDK error:', error);
|
|
132
|
+
this.queue.put({
|
|
133
|
+
id: requestId,
|
|
134
|
+
delta: { role: 'assistant', content: 'Sorry, I encountered an error.' },
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Create a CodexLLM instance
|
|
141
|
+
*/
|
|
142
|
+
export function createCodexLLM(opts) {
|
|
143
|
+
return new CodexLLM(opts);
|
|
144
|
+
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fast Brain — Central Orchestrator for the Voice AI System
|
|
3
|
+
*
|
|
4
|
+
* The sole intelligence layer between the user and all backend capabilities.
|
|
5
|
+
* The realtime voice model is a thin teleprompter — it speaks what this module returns.
|
|
6
|
+
*
|
|
7
|
+
* Capabilities:
|
|
8
|
+
* - Read/write session files (spec.md)
|
|
9
|
+
* - Web search for quick factual lookups
|
|
10
|
+
* - Record user decisions and preferences into spec.md
|
|
11
|
+
* - Trigger deep research (via callbacks to index.ts)
|
|
12
|
+
* - Generate teleprompter scripts for ALL voice output
|
|
13
|
+
* - Post-research: synthesize findings from JSONL into spec.md + voice scripts
|
|
14
|
+
* - Generate visual documents (comparison, diagram, analysis, summary)
|
|
15
|
+
*
|
|
16
|
+
* Central function: askFastBrain() — ALL user questions route here.
|
|
17
|
+
* It returns a FastBrainResponse with a teleprompter script the voice model reads verbatim.
|
|
18
|
+
*
|
|
19
|
+
* Auth chain (tried in order):
|
|
20
|
+
* 1. ANTHROPIC_API_KEY env var → Anthropic SDK (Haiku)
|
|
21
|
+
* 2. ANTHROPIC_AUTH_TOKEN env var → Anthropic SDK (Haiku)
|
|
22
|
+
* 3. GOOGLE_API_KEY env var → Gemini Flash fallback
|
|
23
|
+
*/
|
|
24
|
+
/**
|
|
25
|
+
* Extract useful content snippets from tool responses, truncated by tool type.
|
|
26
|
+
* Returns null for tools with no useful content (Write confirmations, etc.)
|
|
27
|
+
*/
|
|
28
|
+
export declare function extractToolContent(toolName: string, toolInput: any, toolResponse: any): string | null;
|
|
29
|
+
/** A single voice conversation turn from the realtime LLM's chatCtx */
|
|
30
|
+
export interface ConversationTurn {
|
|
31
|
+
role: 'user' | 'assistant';
|
|
32
|
+
text: string;
|
|
33
|
+
}
|
|
34
|
+
/** Clear fast brain session state — call on disconnect/reconnect/session switch */
|
|
35
|
+
export declare function clearFastBrainSession(): void;
|
|
36
|
+
/** @deprecated Use clearFastBrainSession() instead */
|
|
37
|
+
export declare function clearFastBrainHistory(): void;
|
|
38
|
+
/**
|
|
39
|
+
* Ask the fast brain a question with access to session files and web search.
|
|
40
|
+
* Returns an answer or "NEEDS_DEEPER_RESEARCH: ..." for escalation.
|
|
41
|
+
*
|
|
42
|
+
* Auth chain: Anthropic (API key → auth token → Keychain OAuth) → Gemini Flash fallback
|
|
43
|
+
*
|
|
44
|
+
* @param researchContext - Optional snapshot of the live research log.
|
|
45
|
+
* ~2 second response time for most queries.
|
|
46
|
+
*/
|
|
47
|
+
export declare function askHaiku(workingDir: string, sessionId: string, question: string, researchContext?: string, chatHistory?: ConversationTurn[], sendToChat?: (text: string) => void, sessionBaseDir?: string): Promise<string>;
|
|
48
|
+
/** Callbacks for the fast brain to trigger side effects in index.ts */
|
|
49
|
+
export interface FastBrainCallbacks {
|
|
50
|
+
triggerResearch: (task: string) => void;
|
|
51
|
+
queueVoice: (script: string) => void;
|
|
52
|
+
sendToFrontend: (data: any) => void;
|
|
53
|
+
}
|
|
54
|
+
/** Structured response from the fast brain orchestrator */
|
|
55
|
+
export interface FastBrainResponse {
|
|
56
|
+
/** Teleprompter script for the voice model to speak */
|
|
57
|
+
script: string;
|
|
58
|
+
/** Response type for caller routing */
|
|
59
|
+
type: 'answer' | 'research_started' | 'recorded' | 'question';
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Central orchestrator — ALL user questions from the realtime model come here.
|
|
63
|
+
* Routes to: direct answer, research triggering, decision recording, or document generation.
|
|
64
|
+
* Returns a teleprompter script the voice model reads verbatim.
|
|
65
|
+
*/
|
|
66
|
+
export declare function askFastBrain(workingDir: string, sessionId: string, question: string, opts: {
|
|
67
|
+
chatHistory?: ConversationTurn[];
|
|
68
|
+
researchContext?: string;
|
|
69
|
+
callbacks: FastBrainCallbacks;
|
|
70
|
+
sessionBaseDir?: string;
|
|
71
|
+
}): Promise<FastBrainResponse>;
|
|
72
|
+
/**
|
|
73
|
+
* Process a batch of research content chunks through the fast brain.
|
|
74
|
+
* Updates spec.md incrementally during research.
|
|
75
|
+
*
|
|
76
|
+
* @param isRefinement - true for the final post-research consolidation pass (higher token budget)
|
|
77
|
+
*/
|
|
78
|
+
export declare function processResearchChunk(workingDir: string, sessionId: string, task: string, contentChunks: string[], isRefinement?: boolean, sessionBaseDir?: string): Promise<{
|
|
79
|
+
spec: string | null;
|
|
80
|
+
libraryFiles: string[];
|
|
81
|
+
} | null>;
|
|
82
|
+
/**
|
|
83
|
+
* Augment agent SDK research results with context from spec.md.
|
|
84
|
+
* Passes ALL specific details through verbatim — only ADDS context annotations.
|
|
85
|
+
* The voice model downstream handles summarization for speech.
|
|
86
|
+
*
|
|
87
|
+
* Falls back to returning the original result if the fast brain is unavailable.
|
|
88
|
+
*/
|
|
89
|
+
export declare function augmentResearchResult(workingDir: string, sessionId: string, task: string, agentResult: string): Promise<string>;
|
|
90
|
+
/**
|
|
91
|
+
* Update spec.md after research completes.
|
|
92
|
+
* Reads FULL untruncated data directly from Claude Agent SDK JSONL files
|
|
93
|
+
* instead of receiving pre-truncated content chunks.
|
|
94
|
+
*
|
|
95
|
+
* Data sources:
|
|
96
|
+
* - getRecentToolResults() — last 30 full tool results (Read, Bash, WebSearch, etc.)
|
|
97
|
+
* - readSessionHistory() — last 50 assistant messages (agent reasoning/analysis)
|
|
98
|
+
* - getSubagentTranscripts() — all sub-agent findings
|
|
99
|
+
*
|
|
100
|
+
* Returns { spec } or null if update failed.
|
|
101
|
+
*/
|
|
102
|
+
export declare function updateSpecFromJSONL(workingDir: string, sessionId: string, task: string, researchLog: string[], sessionBaseDir?: string): Promise<{
|
|
103
|
+
spec: string | null;
|
|
104
|
+
libraryFiles: string[];
|
|
105
|
+
} | null>;
|
|
106
|
+
/**
|
|
107
|
+
* Fire-and-forget: Write a user question to spec.md Open Questions > From User
|
|
108
|
+
* before the agent starts researching. Ensures every escalated question is tracked.
|
|
109
|
+
*
|
|
110
|
+
* Uses a simple LLM call to fuzzy-match existing questions and avoid duplicates.
|
|
111
|
+
* Skips if spec.md doesn't exist yet or no provider is available.
|
|
112
|
+
*/
|
|
113
|
+
export declare function writeQuestionToSpec(workingDir: string, sessionId: string, question: string): Promise<void>;
|
|
114
|
+
/**
|
|
115
|
+
* Fire-and-forget: Check if substantial agent output answers any open questions in spec.md.
|
|
116
|
+
* Debounced (3s) to prevent flooding during rapid tool_result sequences.
|
|
117
|
+
*
|
|
118
|
+
* When a question is answered, marks it with [x] and moves the answer to Findings.
|
|
119
|
+
*/
|
|
120
|
+
export declare function checkOutputAgainstQuestions(workingDir: string, sessionId: string, output: string, outputType: 'tool_result' | 'assistant_text'): Promise<void>;
|
|
121
|
+
/**
|
|
122
|
+
* Generate a natural, contextualized voice update from raw research events.
|
|
123
|
+
* Called by scheduleResearchBatch() instead of injecting raw events directly.
|
|
124
|
+
*
|
|
125
|
+
* Returns a natural 1-2 sentence update, or null if nothing interesting to say.
|
|
126
|
+
* 3-second timeout — returns null if the LLM is too slow.
|
|
127
|
+
*/
|
|
128
|
+
export declare function contextualizeResearchUpdate(workingDir: string, sessionId: string, task: string, batchEvents: string[], researchLog: string[], chatHistory?: ConversationTurn[], sessionBaseDir?: string): Promise<string | null>;
|
|
129
|
+
/**
|
|
130
|
+
* Generate a proactive conversational prompt to keep the user engaged during research.
|
|
131
|
+
* Called periodically (every 15s) during active research.
|
|
132
|
+
*
|
|
133
|
+
* Can ask open questions, discuss implications of findings, or give progress with depth.
|
|
134
|
+
* Returns null/NOTHING if nothing interesting to say.
|
|
135
|
+
* 3-second timeout.
|
|
136
|
+
*/
|
|
137
|
+
export declare function generateProactivePrompt(workingDir: string, sessionId: string, task: string, researchLog: string[], previousPrompts: string[], sessionBaseDir?: string): Promise<string | null>;
|
|
138
|
+
/**
|
|
139
|
+
* Generate a structured visual document (comparison table, Mermaid diagram,
|
|
140
|
+
* analysis, or summary) from research findings.
|
|
141
|
+
*
|
|
142
|
+
* Reads spec.md and JSONL results for context.
|
|
143
|
+
* Writes the result to workspace and returns the filename + content.
|
|
144
|
+
*/
|
|
145
|
+
export declare function generateVisualDocument(workingDir: string, sessionId: string, request: string, documentType: 'comparison' | 'diagram' | 'analysis' | 'summary', sessionBaseDir?: string): Promise<{
|
|
146
|
+
fileName: string;
|
|
147
|
+
content: string;
|
|
148
|
+
} | null>;
|
|
149
|
+
/**
|
|
150
|
+
* Generate a complete teleprompter script from research results.
|
|
151
|
+
* Replaces augmentResearchResult + extractPriorityContent.
|
|
152
|
+
* Reads full JSONL and produces a spoken monologue.
|
|
153
|
+
*/
|
|
154
|
+
export declare function processResearchCompletion(workingDir: string, sessionId: string, task: string, agentResult: string, chatHistory?: ConversationTurn[], sendToChat?: (text: string) => void, sessionBaseDir?: string): Promise<string>;
|
|
155
|
+
/**
|
|
156
|
+
* Process a batch of research events and decide whether to speak.
|
|
157
|
+
* Replaces contextualizeResearchUpdate — but usually returns null (silent).
|
|
158
|
+
* Only speaks when something genuinely critical is found.
|
|
159
|
+
*/
|
|
160
|
+
export declare function handleResearchBatch(workingDir: string, sessionId: string, task: string, batchEvents: string[], researchLog: string[], chatHistory?: ConversationTurn[], sessionBaseDir?: string): Promise<string | null>;
|
|
161
|
+
/**
|
|
162
|
+
* Generate a brief spoken script for session resume or switch.
|
|
163
|
+
* Replaces buildContextBriefing + getSpecForVoiceModel.
|
|
164
|
+
*/
|
|
165
|
+
export declare function prepareBriefingScript(workingDir: string, sessionId: string, conversationHistory?: {
|
|
166
|
+
role: string;
|
|
167
|
+
text: string;
|
|
168
|
+
}[], type?: 'resume' | 'switch' | 'default'): Promise<string>;
|
|
169
|
+
/**
|
|
170
|
+
* Generate a spoken script after Gemini auto-recovery.
|
|
171
|
+
* Replaces inline recovery logic in index.ts.
|
|
172
|
+
*/
|
|
173
|
+
export declare function prepareRecoveryScript(conversationHistory?: {
|
|
174
|
+
role: string;
|
|
175
|
+
text: string;
|
|
176
|
+
}[]): Promise<string>;
|