osborn 0.9.274 → 0.9.276

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.
@@ -121,7 +121,7 @@ card replaced the stream).
121
121
 
122
122
  **Drive the engine** (one Bash call, needs `OSBORN_ENGINE_TOKEN` env):
123
123
  ```bash
124
- curl -sS -X POST "https://osborn-voice-e2e.fly.dev:8781/act" \
124
+ curl -sS -X POST "https://osborn-voice-e2e-n.fly.dev:8781/act" \
125
125
  -H "x-engine-token: $OSBORN_ENGINE_TOKEN" -H 'Content-Type: application/json' \
126
126
  -d '{"instruction":"go to youtube.com"}'
127
127
  ```
@@ -13,6 +13,20 @@
13
13
  * On Linux/Docker, credentials go to ~/.claude/.credentials.json (file-based, no keyring).
14
14
  * The Fly.io volume at /workspace/.claude is symlinked to ~/.claude for persistence.
15
15
  */
16
+ /**
17
+ * Strip ALL ANSI escape sequences from a string — CSI (including private
18
+ * prefixes like `?`), OSC (both BEL and ST terminators), and lone ESC bytes.
19
+ *
20
+ * This is a superset of the common `/\x1B\[[0-9;]*[A-Za-z]/g` pattern, which
21
+ * misses private-prefix modes like `\x1B[?2026h` and string terminators like
22
+ * `\x1B\\`. Claude's Ink UI uses these extensively and they leak into error
23
+ * messages and URLs when we only strip the basic CSI form.
24
+ */
25
+ /**
26
+ * Redact Claude tokens (sk-ant-oat01-…, sk-ant-api…) from CLI output before it
27
+ * is logged or forwarded — `claude setup-token` prints the token to the pty.
28
+ */
29
+ export declare function redactClaudeTokens(text: string): string;
16
30
  export interface ClaudeAuthCallbacks {
17
31
  onUrl: (url: string) => void;
18
32
  onWaitingForCode: () => void;
@@ -28,24 +42,65 @@ export interface ClaudeAuthHandle {
28
42
  * On Linux/Docker, Claude Code stores OAuth creds at ~/.claude/.credentials.json
29
43
  */
30
44
  export declare function isClaudeAuthenticated(): boolean;
45
+ export declare function consumeFallbackClearedByLogin(): boolean;
46
+ /** Trim whitespace and strip one layer of surrounding quotes from an env value. */
47
+ export declare function cleanEnvKey(value: string | undefined | null): string;
48
+ /** Env vars that give the agent a working model backend without a Claude login. */
49
+ export declare const FALLBACK_MODEL_KEY_VARS: readonly ["ANTHROPIC_API_KEY", "Z_AI_PERSONAL_API_KEY", "ZAI_API_KEY", "OPENROUTER_API_KEY"];
50
+ /**
51
+ * True when any fallback model key (Anthropic API key, z.ai, OpenRouter) has a
52
+ * non-empty value after trimming and quote-stripping.
53
+ */
54
+ export declare function hasFallbackModelKey(env?: NodeJS.ProcessEnv): boolean;
55
+ /**
56
+ * Pure decision for ensureClaudeAuth(): skip the blocking interactive OAuth when
57
+ * Claude is not authenticated but a fallback key exists — the session starts
58
+ * immediately on the fallback tier and Claude sign-in is offered as an optional
59
+ * upgrade. OSBORN_FORCE_CLAUDE_LOGIN=1 restores the old blocking behaviour.
60
+ */
61
+ export declare function shouldSkipBlockingOAuth(env: NodeJS.ProcessEnv, authed: boolean): boolean;
62
+ /**
63
+ * Pure decision for ensureClaudeAuth()'s in-flight branch (#71): should a new
64
+ * join wait on an OAuth flow that is already running? Only when the user
65
+ * explicitly asked to sign in (force) or there is no fallback model to run on.
66
+ * A fallback-key machine re-entering /chat must not be blocked by the optional
67
+ * sign-in it opened earlier.
68
+ */
69
+ export declare function inFlightAuthBlocksJoin(env: NodeJS.ProcessEnv, force?: boolean): boolean;
31
70
  /**
32
- * Additive third onboarding tier. Runs AFTER ensureClaudeAuth() and BEFORE
33
- * session creation. Resolves which auth backend the agent will use, in order:
71
+ * Additive onboarding tier resolution. Runs AFTER ensureClaudeAuth() and BEFORE
72
+ * session creation. Resolves which auth backend the agent will use, in order
73
+ * (Claude → ANTHROPIC_API_KEY → z.ai → OpenRouter):
34
74
  *
35
75
  * Tier 1 — real Claude login active (expiry-aware): use it, no-op.
36
76
  * Tier 2 — user's own ANTHROPIC_API_KEY is set: use it, no-op.
37
- * Tier 3 — central OPENROUTER_API_KEY present: redirect the SDK to
77
+ * Tier 3 — house demo pass, Z_AI_PERSONAL_API_KEY (or ZAI_API_KEY): redirect
78
+ * the SDK to z.ai's Anthropic-compatible endpoint (GLM model).
79
+ * Tier 4 — central OPENROUTER_API_KEY present: redirect the SDK to
38
80
  * OpenRouter's native Anthropic-Messages endpoint via env vars and
39
81
  * point every model slot at FALLBACK_MODEL. Proven end-to-end
40
82
  * env-var-only (no proxy) — the Claude Code tool loop completes.
41
- * Tier 3 fail — no OpenRouter key: warn and no-op (do NOT throw; the SDK
42
- * may still find creds we didn't detect).
83
+ * Tier 4 fail — no fallback key at all: warn and no-op (do NOT throw; the
84
+ * SDK may still find creds we didn't detect).
85
+ *
86
+ * Key values are trimmed and quote-stripped (cleanEnvKey) — a stray trailing
87
+ * space in a secret would otherwise be sent verbatim as the bearer token.
43
88
  *
44
89
  * Env vars MUST be set here, before the first query() spawn — the SDK
45
90
  * subprocess inherits process.env at spawn time and reads auth/model config
46
91
  * once at cold start.
47
92
  */
48
93
  export declare function applyAuthFallback(): void;
94
+ /**
95
+ * Clear the fallback redirect (z.ai house pass or OpenRouter) — but ONLY if
96
+ * applyAuthFallback() set it. Called from the auth onComplete path so a user who later finishes real
97
+ * Claude login mid-session (or on the next cold start) is not stuck routing to
98
+ * the fallback. A user-supplied ANTHROPIC_BASE_URL is left untouched.
99
+ *
100
+ * Returns true iff a fallback was active and has now been cleared — callers use
101
+ * this to decide whether a running session needs a (deferred) restart.
102
+ */
103
+ export declare function clearAuthFallbackIfActive(): boolean;
49
104
  /**
50
105
  * Check auth via `claude auth status` (most reliable).
51
106
  * Uses resolved path to avoid posix_spawnp PATH issues.
@@ -85,6 +140,9 @@ export declare function replayInFlightAuth(send: (type: string, payload: unknown
85
140
  * 1. CLAUDE_CODE_OAUTH_TOKEN env var
86
141
  * 2. ~/.claude/.credentials.json file
87
142
  * 3. `claude auth status --json`
143
+ * 3b. Fallback model key present (hasFallbackModelKey) → return immediately
144
+ * and emit `claude_auth_optional`; skipped when OSBORN_FORCE_CLAUDE_LOGIN=1
145
+ * or opts.force (user explicitly asked to sign in via `claude_auth_start`)
88
146
  * 4. Interactive OAuth flow (setup-token)
89
147
  *
90
148
  * Concurrency: if a previous call is still running its OAuth flow, new
@@ -93,7 +151,36 @@ export declare function replayInFlightAuth(send: (type: string, payload: unknown
93
151
  * microphone-permission error) retrigger ensureClaudeAuth and the user
94
152
  * sees two different URLs / two different code_challenges racing.
95
153
  */
96
- export declare function ensureClaudeAuth(sendToFrontend: (type: string, payload: unknown) => void): Promise<{
154
+ export declare function ensureClaudeAuth(sendToFrontend: (type: string, payload: unknown) => void, opts?: {
155
+ force?: boolean;
156
+ }): Promise<{
97
157
  submitCode?: (code: string) => void;
98
158
  done?: Promise<void>;
99
159
  }>;
160
+ /** True while a claude_auth_start-initiated flow is running. */
161
+ export declare function isOnDemandAuthInFlight(): boolean;
162
+ /**
163
+ * Start Claude OAuth on demand — the upgrade path after ensureClaudeAuth()
164
+ * skipped the blocking flow because a fallback key exists. Guarded: a second
165
+ * call while one is running does NOT start another flow (started=false, same
166
+ * result promise).
167
+ *
168
+ * `submitCode` get/set bind the caller's pendingAuthSubmitCode slot; on settle
169
+ * the slot is cleared only if it still holds THIS flow's submitCode.
170
+ *
171
+ * Resolves `{ fallbackCleared }` — true only when a fallback redirect was
172
+ * active and is now gone (the caller should then request a deferred session
173
+ * restart). Already-authenticated → no flow, fallbackCleared reflects only
174
+ * whether a stale fallback was active.
175
+ */
176
+ export declare function startClaudeAuthOnDemand(sendToFrontend: (type: string, payload: unknown) => void, submitCode: {
177
+ get: () => ((code: string) => void) | null;
178
+ set: (fn: ((code: string) => void) | null) => void;
179
+ }, deps?: {
180
+ ensure?: typeof ensureClaudeAuth;
181
+ }): {
182
+ started: boolean;
183
+ result: Promise<{
184
+ fallbackCleared: boolean;
185
+ }>;
186
+ };
@@ -84,6 +84,13 @@ const CREDENTIALS_PATH = join(homedir(), '.claude', '.credentials.json');
84
84
  * `\x1B\\`. Claude's Ink UI uses these extensively and they leak into error
85
85
  * messages and URLs when we only strip the basic CSI form.
86
86
  */
87
+ /**
88
+ * Redact Claude tokens (sk-ant-oat01-…, sk-ant-api…) from CLI output before it
89
+ * is logged or forwarded — `claude setup-token` prints the token to the pty.
90
+ */
91
+ export function redactClaudeTokens(text) {
92
+ return text.replace(/sk-ant-[A-Za-z0-9_-]+/g, 'sk-ant-[REDACTED]');
93
+ }
87
94
  function stripAnsi(text) {
88
95
  return text
89
96
  // Full CSI: ESC [ <intermediates 0x20–0x3F> <final 0x40–0x7E>
@@ -151,17 +158,108 @@ export function isClaudeAuthenticated() {
151
158
  */
152
159
  let fallbackTierActive = false;
153
160
  /**
154
- * Additive third onboarding tier. Runs AFTER ensureClaudeAuth() and BEFORE
155
- * session creation. Resolves which auth backend the agent will use, in order:
161
+ * Pre-fallback values of the model env vars applyAuthFallback() overwrites, so
162
+ * clearAuthFallbackIfActive() can RESTORE an operator-set value instead of
163
+ * deleting it. `undefined` means "was unset". Captured once, on the first
164
+ * activation (a second applyAuthFallback() must not snapshot its own values).
165
+ */
166
+ const RESTORABLE_MODEL_VARS = ['ANTHROPIC_MODEL', 'ANTHROPIC_SMALL_FAST_MODEL', 'CLAUDE_CODE_MAX_CONTEXT_TOKENS'];
167
+ let preFallbackModelEnv = null;
168
+ function snapshotModelEnv() {
169
+ if (fallbackTierActive || preFallbackModelEnv)
170
+ return;
171
+ preFallbackModelEnv = {};
172
+ for (const k of RESTORABLE_MODEL_VARS)
173
+ preFallbackModelEnv[k] = process.env[k];
174
+ }
175
+ function restoreModelEnv() {
176
+ for (const k of RESTORABLE_MODEL_VARS) {
177
+ const v = preFallbackModelEnv ? preFallbackModelEnv[k] : undefined;
178
+ if (v === undefined)
179
+ delete process.env[k];
180
+ else
181
+ process.env[k] = v;
182
+ }
183
+ preFallbackModelEnv = null;
184
+ }
185
+ /**
186
+ * Set when the OAuth onComplete path cleared an active fallback, so a caller that
187
+ * awaited the flow (claude_auth_start) still learns a restart is needed even
188
+ * though its own clearAuthFallbackIfActive() then finds nothing to clear.
189
+ */
190
+ let fallbackClearedByLogin = false;
191
+ export function consumeFallbackClearedByLogin() {
192
+ const v = fallbackClearedByLogin;
193
+ fallbackClearedByLogin = false;
194
+ return v;
195
+ }
196
+ /** Trim whitespace and strip one layer of surrounding quotes from an env value. */
197
+ export function cleanEnvKey(value) {
198
+ if (!value)
199
+ return '';
200
+ let v = value.trim();
201
+ if (v.length >= 2 && ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'")))) {
202
+ v = v.slice(1, -1).trim();
203
+ }
204
+ return v;
205
+ }
206
+ /** Env vars that give the agent a working model backend without a Claude login. */
207
+ export const FALLBACK_MODEL_KEY_VARS = [
208
+ 'ANTHROPIC_API_KEY',
209
+ 'Z_AI_PERSONAL_API_KEY',
210
+ 'ZAI_API_KEY',
211
+ 'OPENROUTER_API_KEY',
212
+ ];
213
+ /**
214
+ * True when any fallback model key (Anthropic API key, z.ai, OpenRouter) has a
215
+ * non-empty value after trimming and quote-stripping.
216
+ */
217
+ export function hasFallbackModelKey(env = process.env) {
218
+ return FALLBACK_MODEL_KEY_VARS.some((name) => cleanEnvKey(env[name]) !== '');
219
+ }
220
+ /**
221
+ * Pure decision for ensureClaudeAuth(): skip the blocking interactive OAuth when
222
+ * Claude is not authenticated but a fallback key exists — the session starts
223
+ * immediately on the fallback tier and Claude sign-in is offered as an optional
224
+ * upgrade. OSBORN_FORCE_CLAUDE_LOGIN=1 restores the old blocking behaviour.
225
+ */
226
+ export function shouldSkipBlockingOAuth(env, authed) {
227
+ if (authed)
228
+ return false;
229
+ if (env.OSBORN_FORCE_CLAUDE_LOGIN === '1')
230
+ return false;
231
+ return hasFallbackModelKey(env);
232
+ }
233
+ /**
234
+ * Pure decision for ensureClaudeAuth()'s in-flight branch (#71): should a new
235
+ * join wait on an OAuth flow that is already running? Only when the user
236
+ * explicitly asked to sign in (force) or there is no fallback model to run on.
237
+ * A fallback-key machine re-entering /chat must not be blocked by the optional
238
+ * sign-in it opened earlier.
239
+ */
240
+ export function inFlightAuthBlocksJoin(env, force = false) {
241
+ if (force)
242
+ return true;
243
+ return !shouldSkipBlockingOAuth(env, false);
244
+ }
245
+ /**
246
+ * Additive onboarding tier resolution. Runs AFTER ensureClaudeAuth() and BEFORE
247
+ * session creation. Resolves which auth backend the agent will use, in order
248
+ * (Claude → ANTHROPIC_API_KEY → z.ai → OpenRouter):
156
249
  *
157
250
  * Tier 1 — real Claude login active (expiry-aware): use it, no-op.
158
251
  * Tier 2 — user's own ANTHROPIC_API_KEY is set: use it, no-op.
159
- * Tier 3 — central OPENROUTER_API_KEY present: redirect the SDK to
252
+ * Tier 3 — house demo pass, Z_AI_PERSONAL_API_KEY (or ZAI_API_KEY): redirect
253
+ * the SDK to z.ai's Anthropic-compatible endpoint (GLM model).
254
+ * Tier 4 — central OPENROUTER_API_KEY present: redirect the SDK to
160
255
  * OpenRouter's native Anthropic-Messages endpoint via env vars and
161
256
  * point every model slot at FALLBACK_MODEL. Proven end-to-end
162
257
  * env-var-only (no proxy) — the Claude Code tool loop completes.
163
- * Tier 3 fail — no OpenRouter key: warn and no-op (do NOT throw; the SDK
164
- * may still find creds we didn't detect).
258
+ * Tier 4 fail — no fallback key at all: warn and no-op (do NOT throw; the
259
+ * SDK may still find creds we didn't detect).
260
+ *
261
+ * Key values are trimmed and quote-stripped (cleanEnvKey) — a stray trailing
262
+ * space in a secret would otherwise be sent verbatim as the bearer token.
165
263
  *
166
264
  * Env vars MUST be set here, before the first query() spawn — the SDK
167
265
  * subprocess inherits process.env at spawn time and reads auth/model config
@@ -174,38 +272,46 @@ export function applyAuthFallback() {
174
272
  return;
175
273
  }
176
274
  // Tier 2: user's own Anthropic key.
177
- if (process.env.ANTHROPIC_API_KEY && process.env.ANTHROPIC_API_KEY.trim() !== '') {
275
+ const anthropicKey = cleanEnvKey(process.env.ANTHROPIC_API_KEY);
276
+ if (anthropicKey !== '') {
277
+ process.env.ANTHROPIC_API_KEY = anthropicKey;
178
278
  return;
179
279
  }
180
280
  // Tier 3: HOUSE DEMO PASS - z.ai GLM coding subscription (flat/shared, not
181
281
  // pay-per-use). Cline/opencode-style: unauthenticated demo users ride the
182
282
  // house pass instead of raw API billing. The z.ai Anthropic-compatible
183
283
  // 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() !== '') {
284
+ // 2026-10-24 (glm-4.7 returned a real response). Defaults moved to glm-5.3 /
285
+ // glm-5.3-flash 2026-11-10: the GLM Coding Plan now only lists GLM-5.3 and
286
+ // GLM-5.3-Flash (docs.z.ai/devpack/overview; glm-4.7 is silently routed to
287
+ // 5.3-Flash). Precedence: Z_AI_PERSONAL_API_KEY, then ZAI_API_KEY.
288
+ const zaiKey = cleanEnvKey(process.env.Z_AI_PERSONAL_API_KEY) || cleanEnvKey(process.env.ZAI_API_KEY);
289
+ if (zaiKey !== '') {
290
+ snapshotModelEnv();
188
291
  // Native Anthropic-Messages endpoint - no local translation proxy needed.
189
292
  process.env.ANTHROPIC_BASE_URL = process.env.OSBORN_DEMO_BASE_URL || 'https://api.z.ai/api/anthropic';
190
293
  process.env.ANTHROPIC_AUTH_TOKEN = zaiKey;
191
294
  process.env.ANTHROPIC_API_KEY = ''; // required - a set key bypasses AUTH_TOKEN
192
- const demoModel = process.env.OSBORN_DEMO_MODEL || 'glm-4.7';
295
+ const demoModel = process.env.OSBORN_DEMO_MODEL || 'glm-5.3';
296
+ const demoFastModel = process.env.OSBORN_DEMO_FAST_MODEL || 'glm-5.3-flash';
193
297
  process.env.ANTHROPIC_MODEL = demoModel;
194
- process.env.ANTHROPIC_SMALL_FAST_MODEL = demoModel;
298
+ process.env.ANTHROPIC_SMALL_FAST_MODEL = demoFastModel;
195
299
  process.env.CLAUDE_CODE_SUBAGENT_MODEL = demoModel;
196
300
  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';
301
+ // GLM-5.3 and GLM-5.3-Flash expose a 1M-token window (docs.z.ai/guides/llm/glm-5.3,
302
+ // verified 2026-11-10); pins the CLI's context-cap handling.
303
+ process.env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = process.env.OSBORN_DEMO_MAX_CONTEXT || '1000000';
199
304
  // Signal for the fast brain (pipeline-fastbrain reads this per call) so the
200
305
  // WHOLE model layer - main agent AND fast brain - rides the same pass.
201
306
  process.env.OSBORN_DEMO_PASS = 'zai';
202
307
  fallbackTierActive = true;
203
- console.log(`[auth-fallback] using house demo pass (z.ai), model=${demoModel}`);
308
+ console.log(`[auth-fallback] using house demo pass (z.ai), model=${demoModel}, fast=${demoFastModel}`);
204
309
  return;
205
310
  }
206
311
  // Tier 4: central OpenRouter key (pay-per-use fallback of the fallback).
207
- const openRouterKey = process.env.OPENROUTER_API_KEY;
208
- if (openRouterKey && openRouterKey.trim() !== '') {
312
+ const openRouterKey = cleanEnvKey(process.env.OPENROUTER_API_KEY);
313
+ if (openRouterKey !== '') {
314
+ snapshotModelEnv();
209
315
  // Native Anthropic-Messages endpoint — no local translation proxy needed.
210
316
  process.env.ANTHROPIC_BASE_URL = 'https://openrouter.ai/api';
211
317
  // Injected as raw `Authorization: Bearer <token>` by the SDK.
@@ -237,16 +343,23 @@ export function applyAuthFallback() {
237
343
  console.warn('[auth-fallback] no Claude login, no ANTHROPIC_API_KEY, no Z_AI key, and no OPENROUTER_API_KEY — agent may be unauthenticated');
238
344
  }
239
345
  /**
240
- * Clear the OpenRouter fallback redirect — but ONLY if applyAuthFallback() set
241
- * it. Called from the auth onComplete path so a user who later finishes real
346
+ * Clear the fallback redirect (z.ai house pass or OpenRouter) — but ONLY if
347
+ * applyAuthFallback() set it. Called from the auth onComplete path so a user who later finishes real
242
348
  * Claude login mid-session (or on the next cold start) is not stuck routing to
243
- * OpenRouter. A user-supplied ANTHROPIC_BASE_URL is left untouched.
349
+ * the fallback. A user-supplied ANTHROPIC_BASE_URL is left untouched.
350
+ *
351
+ * Returns true iff a fallback was active and has now been cleared — callers use
352
+ * this to decide whether a running session needs a (deferred) restart.
244
353
  */
245
- function clearAuthFallbackIfActive() {
354
+ export function clearAuthFallbackIfActive() {
246
355
  if (!fallbackTierActive)
247
- return;
356
+ return false;
248
357
  delete process.env.ANTHROPIC_BASE_URL;
249
358
  delete process.env.ANTHROPIC_AUTH_TOKEN;
359
+ // Model-slot overrides both tiers (z.ai + OpenRouter) set — restore the
360
+ // pre-fallback values (or unset) so the real Claude session isn't pinned onto
361
+ // glm-5.3 / FALLBACK_MODEL and the fallback's context cap.
362
+ restoreModelEnv();
250
363
  // Was forced to '' for the OpenRouter redirect; unset so the real OAuth
251
364
  // token path (CLAUDE_CODE_OAUTH_TOKEN) is used cleanly.
252
365
  delete process.env.ANTHROPIC_API_KEY;
@@ -260,6 +373,7 @@ function clearAuthFallbackIfActive() {
260
373
  delete process.env.OSBORN_DEMO_PASS;
261
374
  fallbackTierActive = false;
262
375
  console.log('[auth-fallback] real Claude login completed — cleared fallback redirect');
376
+ return true;
263
377
  }
264
378
  /**
265
379
  * Check auth via `claude auth status` (most reliable).
@@ -439,8 +553,9 @@ export function runClaudeAuthFlow(callbacks) {
439
553
  recentBuffer += clean;
440
554
  // Debug log (truncated)
441
555
  const logLine = clean.trim();
556
+ // Redact BEFORE truncating so a token can't survive as a cut-off prefix.
442
557
  if (logLine)
443
- console.log(`🔑 [claude-cli] ${logLine.substring(0, 200)}`);
558
+ console.log(`🔑 [claude-cli] ${redactClaudeTokens(logLine).substring(0, 200)}`);
444
559
  callbacks.onOutput?.(data);
445
560
  // Extract OAuth URL from accumulated output (claudebox whitespace-strip pattern)
446
561
  if (!urlSent) {
@@ -466,7 +581,7 @@ export function runClaudeAuthFlow(callbacks) {
466
581
  completed = true;
467
582
  clearTimeout(timeout);
468
583
  const token = tokenMatch[0];
469
- console.log(`✅ OAuth token captured (${token.length} chars, starts with ${token.substring(0, 20)}...)`);
584
+ console.log(`✅ OAuth token captured (${token.length} chars)`);
470
585
  // Set as env var so Claude Agent SDK picks it up immediately
471
586
  process.env.CLAUDE_CODE_OAUTH_TOKEN = token;
472
587
  // Persist to volume for future restarts
@@ -491,7 +606,7 @@ export function runClaudeAuthFlow(callbacks) {
491
606
  }
492
607
  // Detect errors
493
608
  if (/OAuth error|Invalid code|expired/i.test(recentBuffer)) {
494
- const errMsg = stripAnsi(recentBuffer).trim().substring(0, 200);
609
+ const errMsg = redactClaudeTokens(stripAnsi(recentBuffer).trim()).substring(0, 200);
495
610
  console.log('⚠️ Claude auth error:', errMsg);
496
611
  callbacks.onError(errMsg);
497
612
  recentBuffer = '';
@@ -551,6 +666,9 @@ export function replayInFlightAuth(send) {
551
666
  * 1. CLAUDE_CODE_OAUTH_TOKEN env var
552
667
  * 2. ~/.claude/.credentials.json file
553
668
  * 3. `claude auth status --json`
669
+ * 3b. Fallback model key present (hasFallbackModelKey) → return immediately
670
+ * and emit `claude_auth_optional`; skipped when OSBORN_FORCE_CLAUDE_LOGIN=1
671
+ * or opts.force (user explicitly asked to sign in via `claude_auth_start`)
554
672
  * 4. Interactive OAuth flow (setup-token)
555
673
  *
556
674
  * Concurrency: if a previous call is still running its OAuth flow, new
@@ -559,7 +677,25 @@ export function replayInFlightAuth(send) {
559
677
  * microphone-permission error) retrigger ensureClaudeAuth and the user
560
678
  * sees two different URLs / two different code_challenges racing.
561
679
  */
562
- export async function ensureClaudeAuth(sendToFrontend) {
680
+ export async function ensureClaudeAuth(sendToFrontend, opts = {}) {
681
+ // A flow is in flight but this machine already has a working model (a
682
+ // fallback key) and nobody explicitly asked to sign in: this is a re-entry
683
+ // (reload / back into /chat) while the optional on-demand sign-in is still
684
+ // open. Don't block the session on it or re-raise the blocking modal (#71) —
685
+ // run on the fallback and keep sign-in optional; the on-demand flow still
686
+ // owns the code paste (pendingAuthSubmitCode) and claude_auth_start replays it.
687
+ if (inFlightAuth && !inFlightAuthBlocksJoin(process.env, !!opts.force)) {
688
+ console.log('🔑 ensureClaudeAuth: OAuth in flight but a fallback model is available — not blocking this join');
689
+ try {
690
+ sendToFrontend('claude_auth_optional', {
691
+ message: 'Running on the fallback model. Sign in to Claude to upgrade.',
692
+ });
693
+ }
694
+ catch (err) {
695
+ console.warn('🔑 claude_auth_optional send failed:', err);
696
+ }
697
+ return {};
698
+ }
563
699
  // If an auth flow is already running, attach to it and replay any
564
700
  // state we've already captured (the URL, any waiting_code prompt).
565
701
  if (inFlightAuth) {
@@ -609,6 +745,23 @@ export async function ensureClaudeAuth(sendToFrontend) {
609
745
  console.log('✅ Claude authenticated (CLI status confirmed)');
610
746
  return {};
611
747
  }
748
+ // Check 3b: Fallback key present — don't block the session on interactive
749
+ // OAuth (which only ends on completion or a 5-minute timeout). Return the
750
+ // "no wait" shape so the caller proceeds straight to applyAuthFallback(),
751
+ // and tell the frontend Claude sign-in is an optional upgrade.
752
+ // opts.force (the on-demand `claude_auth_start` path) bypasses this check.
753
+ if (!opts.force && shouldSkipBlockingOAuth(process.env, false)) {
754
+ console.log('🔑 Claude not authenticated — fallback key present, skipping blocking OAuth');
755
+ try {
756
+ sendToFrontend('claude_auth_optional', {
757
+ message: 'Running on the fallback model. Sign in to Claude to upgrade.',
758
+ });
759
+ }
760
+ catch (err) {
761
+ console.warn('🔑 claude_auth_optional send failed:', err);
762
+ }
763
+ return {};
764
+ }
612
765
  // Check 4: Need interactive OAuth flow
613
766
  console.log('🔑 Claude not authenticated — starting OAuth flow');
614
767
  // Create the in-flight record BEFORE spawning, and fan-out every
@@ -651,7 +804,8 @@ export async function ensureClaudeAuth(sendToFrontend) {
651
804
  // the OpenRouter redirect env (only if the fallback set it) so this
652
805
  // session — and the next cold start — use the real OAuth token instead
653
806
  // of staying pinned to OpenRouter.
654
- clearAuthFallbackIfActive();
807
+ if (clearAuthFallbackIfActive())
808
+ fallbackClearedByLogin = true;
655
809
  // Include the captured token so the frontend can persist it to the
656
810
  // host-persistent layer via the Sprites API. Without this, credentials
657
811
  // written inside the service container's ephemeral overlay are lost on
@@ -681,3 +835,63 @@ export async function ensureClaudeAuth(sendToFrontend) {
681
835
  });
682
836
  return { submitCode: handle.submitCode, done };
683
837
  }
838
+ // ─────────────────────────────────────────
839
+ // On-demand Claude sign-in (claude_auth_start)
840
+ // ─────────────────────────────────────────
841
+ let onDemandAuth = null;
842
+ /** True while a claude_auth_start-initiated flow is running. */
843
+ export function isOnDemandAuthInFlight() {
844
+ return onDemandAuth !== null;
845
+ }
846
+ /**
847
+ * Start Claude OAuth on demand — the upgrade path after ensureClaudeAuth()
848
+ * skipped the blocking flow because a fallback key exists. Guarded: a second
849
+ * call while one is running does NOT start another flow (started=false, same
850
+ * result promise).
851
+ *
852
+ * `submitCode` get/set bind the caller's pendingAuthSubmitCode slot; on settle
853
+ * the slot is cleared only if it still holds THIS flow's submitCode.
854
+ *
855
+ * Resolves `{ fallbackCleared }` — true only when a fallback redirect was
856
+ * active and is now gone (the caller should then request a deferred session
857
+ * restart). Already-authenticated → no flow, fallbackCleared reflects only
858
+ * whether a stale fallback was active.
859
+ */
860
+ export function startClaudeAuthOnDemand(sendToFrontend, submitCode, deps = {}) {
861
+ if (onDemandAuth) {
862
+ console.log('🔑 claude_auth_start: on-demand flow already in flight — not starting another');
863
+ return { started: false, result: onDemandAuth };
864
+ }
865
+ const ensure = deps.ensure ?? ensureClaudeAuth;
866
+ const run = async () => {
867
+ try {
868
+ const authResult = await ensure(sendToFrontend, { force: true });
869
+ if (authResult.submitCode && authResult.done) {
870
+ const mine = authResult.submitCode;
871
+ submitCode.set(mine);
872
+ try {
873
+ await authResult.done;
874
+ }
875
+ finally {
876
+ if (submitCode.get() === mine)
877
+ submitCode.set(null);
878
+ }
879
+ }
880
+ else {
881
+ sendToFrontend('claude_auth_complete', { message: 'Claude is already authenticated.' });
882
+ }
883
+ // onComplete may already have cleared it — consume that signal too.
884
+ const cleared = clearAuthFallbackIfActive();
885
+ const clearedByLogin = consumeFallbackClearedByLogin();
886
+ return { fallbackCleared: cleared || clearedByLogin };
887
+ }
888
+ catch (err) {
889
+ console.error('❌ On-demand Claude authentication failed:', err?.message);
890
+ sendToFrontend('claude_auth_error', { message: err?.message || 'Authentication failed' });
891
+ return { fallbackCleared: false };
892
+ }
893
+ };
894
+ const p = run().finally(() => { onDemandAuth = null; });
895
+ onDemandAuth = p;
896
+ return { started: true, result: p };
897
+ }
@@ -7,7 +7,7 @@
7
7
  * Flow: User speaks → STT → ClaudeLLM (Agent SDK) → TTS → User hears
8
8
  */
9
9
  import { llm, type APIConnectOptions } from '@livekit/agents';
10
- import { type Options, type McpServerConfig } from '@anthropic-ai/claude-agent-sdk';
10
+ import { query, type Options, type McpServerConfig } from '@anthropic-ai/claude-agent-sdk';
11
11
  import { EventEmitter } from 'events';
12
12
  export interface ClaudeLLMOptions {
13
13
  workingDirectory?: string;
@@ -43,6 +43,9 @@ export interface ClaudeLLMOptions {
43
43
  tools?: string[];
44
44
  model?: string;
45
45
  }>;
46
+ /** Test seam: replaces the SDK `query()` for the persistent session (cold start
47
+ * + primeResume). Production never sets it. */
48
+ queryFn?: typeof query;
46
49
  }
47
50
  export declare const NAMED_AGENTS: {
48
51
  researcher: {
@@ -88,6 +91,14 @@ export declare const NAMED_AGENTS: {
88
91
  };
89
92
  export declare const FAST_MODEL = "haiku";
90
93
  export declare const FALLBACK_MODEL = "minimax/minimax-m3";
94
+ export declare function requestAuthRestart(): number;
95
+ export declare function getAuthEnvGeneration(): number;
96
+ /**
97
+ * Pure decision: restart a live persistent subprocess before pushing the next
98
+ * message? Only when it was spawned under an older auth generation AND it is
99
+ * idle (no turn streaming, no interrupt settling).
100
+ */
101
+ export declare function shouldRestartForAuth(spawnGen: number, currentGen: number, turnsInFlight: number, interruptPending: boolean): boolean;
91
102
  /**
92
103
  * Apply turbo override to an agents roster.
93
104
  * When turbo is true returns a DEEP COPY with every agent's model set to
@@ -130,6 +141,8 @@ export declare const VERIFIER_CHAIN: Record<string, {
130
141
  }>;
131
142
  export declare class ClaudeLLM extends llm.LLM {
132
143
  #private;
144
+ /** True when the live subprocess predates the latest auth-backend change. */
145
+ get authRestartPending(): boolean;
133
146
  constructor(opts?: ClaudeLLMOptions);
134
147
  /**
135
148
  * Respond to a pending permission request
@@ -205,6 +218,7 @@ export declare class ClaudeLLM extends llm.LLM {
205
218
  * Call this when resuming a session from a different project slug
206
219
  */
207
220
  setWorkingDirectory(path: string): void;
221
+ get workingDirectory(): string | undefined;
208
222
  /**
209
223
  * Reset state for mid-conversation session switch
210
224
  * Clears pending permissions and resets conversation tracking
@@ -313,6 +327,22 @@ export declare class ClaudeLLM extends llm.LLM {
313
327
  description?: string;
314
328
  status: string;
315
329
  }>;
330
+ /** `resume` id the live persistent query was spawned with (null = fresh / none). */
331
+ get spawnedResumeId(): string | null;
332
+ /**
333
+ * What the live session is doing right now (#74). A session switch is only
334
+ * executed when `idle`: a turn awaiting its result, SDK tasks (sub-agents
335
+ * outlive their turn), compaction, an in-flight interrupt or a permission
336
+ * prompt all mean closing the query would lose work.
337
+ */
338
+ busyState(): {
339
+ turnInFlight: boolean;
340
+ runningTasks: number;
341
+ compacting: boolean;
342
+ interruptPending: boolean;
343
+ permissionPending: boolean;
344
+ idle: boolean;
345
+ };
316
346
  /** Whether a persistent session is alive and consuming messages */
317
347
  hasSession(): boolean;
318
348
  /**