osborn 0.9.277 → 0.9.278

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.
@@ -90,7 +90,14 @@ export declare function inFlightAuthBlocksJoin(env: NodeJS.ProcessEnv, force?: b
90
90
  * subprocess inherits process.env at spawn time and reads auth/model config
91
91
  * once at cold start.
92
92
  */
93
- export declare function applyAuthFallback(): void;
93
+ export declare function applyAuthFallback(): ActiveProvider;
94
+ /**
95
+ * The model backend the agent is actually answering on, as returned by
96
+ * applyAuthFallback() (single source of truth — the tier is known at decision
97
+ * time). Drives agent_ready.provider so the model badge names what is really
98
+ * answering instead of the old hardcoded 'claude' (issue #87).
99
+ */
100
+ export type ActiveProvider = 'claude' | 'anthropic' | 'zai' | 'openrouter' | 'none';
94
101
  /**
95
102
  * Clear the fallback redirect (z.ai house pass or OpenRouter) — but ONLY if
96
103
  * applyAuthFallback() set it. Called from the auth onComplete path so a user who later finishes real
@@ -269,13 +269,13 @@ export function applyAuthFallback() {
269
269
  // Tier 1: real Claude login (expiry-aware — NOT hasOAuthTokenEnv, which
270
270
  // would treat an expired token as active and let the SDK fail downstream).
271
271
  if (isClaudeAuthenticated()) {
272
- return;
272
+ return 'claude';
273
273
  }
274
274
  // Tier 2: user's own Anthropic key.
275
275
  const anthropicKey = cleanEnvKey(process.env.ANTHROPIC_API_KEY);
276
276
  if (anthropicKey !== '') {
277
277
  process.env.ANTHROPIC_API_KEY = anthropicKey;
278
- return;
278
+ return 'anthropic';
279
279
  }
280
280
  // Tier 3: HOUSE DEMO PASS - z.ai GLM coding subscription (flat/shared, not
281
281
  // pay-per-use). Cline/opencode-style: unauthenticated demo users ride the
@@ -306,7 +306,7 @@ export function applyAuthFallback() {
306
306
  process.env.OSBORN_DEMO_PASS = 'zai';
307
307
  fallbackTierActive = true;
308
308
  console.log(`[auth-fallback] using house demo pass (z.ai), model=${demoModel}, fast=${demoFastModel}`);
309
- return;
309
+ return 'zai';
310
310
  }
311
311
  // Tier 4: central OpenRouter key (pay-per-use fallback of the fallback).
312
312
  const openRouterKey = cleanEnvKey(process.env.OPENROUTER_API_KEY);
@@ -337,10 +337,17 @@ export function applyAuthFallback() {
337
337
  process.env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = '131072';
338
338
  fallbackTierActive = true;
339
339
  console.log(`[auth-fallback] using central OpenRouter tier, model=${FALLBACK_MODEL}`);
340
- return;
340
+ return 'openrouter';
341
+ }
342
+ // A user's own Anthropic-compatible gateway (ANTHROPIC_AUTH_TOKEN + their own
343
+ // ANTHROPIC_BASE_URL) is left untouched above and still answers — label it as
344
+ // their own (anthropic) rather than a dead end.
345
+ if (cleanEnvKey(process.env.ANTHROPIC_AUTH_TOKEN) !== '') {
346
+ return 'anthropic';
341
347
  }
342
348
  // Tier 4 fail: no fallback key at all — do NOT throw.
343
349
  console.warn('[auth-fallback] no Claude login, no ANTHROPIC_API_KEY, no Z_AI key, and no OPENROUTER_API_KEY — agent may be unauthenticated');
350
+ return 'none';
344
351
  }
345
352
  /**
346
353
  * Clear the fallback redirect (z.ai house pass or OpenRouter) — but ONLY if
package/dist/index.js CHANGED
@@ -41,6 +41,7 @@ import { createSTT, createTTS } from './voice-io.js';
41
41
  import { createClaudeLLM, NAMED_AGENTS, applyTurbo, requestAuthRestart } from './claude-llm.js';
42
42
  import { clearPipelineFastBrainSession, prewarmBM25Index } from './pipeline-fastbrain.js';
43
43
  import { ensureClaudeAuth, applyAuthFallback, replayInFlightAuth, startClaudeAuthOnDemand, isOnDemandAuthInFlight } from './claude-auth.js';
44
+ import { probeActiveProviderKey } from './key-health.js';
44
45
  import { statusManager } from './status-manager.js';
45
46
  import { decideNextSession, planSwitch, resolveSessionCwd, keepNonConversationItems, recoverySessionId as pickRecoverySessionId, warmParkKey, sessionMessagesDir, createSwitchGuard, scanSlugCwd, pickConnectWorkingDir } from './session-switch.js';
46
47
  import { createSmitheryProxy, destroySmitheryProxy, parseSmitheryUrl, isSmitheryUrl, SmitheryAuthorizationError } from './smithery-proxy.js';
@@ -281,6 +282,13 @@ let bugReportHook = null;
281
282
  // closure. The /editor route in startApiServer() calls this to start the IDE
282
283
  // in the background without depending on main()'s closure directly.
283
284
  let codeServerStartHook = null;
285
+ // ── Model-provider health (module scope — shared between startApiServer + main) ──
286
+ // #87: the per-key self-test result for the ACTIVE fallback provider, written by
287
+ // main()'s connect path (probeActiveProviderKey) and read by startApiServer's
288
+ // GET /health so a dead/expired key surfaces as "No working model" instead of a
289
+ // silent non-reply. Null until the async probe lands (or never, on the Claude
290
+ // path / an ambiguous result) — never a fabricated verdict.
291
+ let agentKeyHealth = null;
284
292
  // ── IDE reverse-proxy (module scope — shared between startApiServer + main) ──
285
293
  // code-server runs on 127.0.0.1:8300; the agent proxies it through its own
286
294
  // public HTTP server so no Cloudflare tunnel is needed.
@@ -755,6 +763,10 @@ function startApiServer(workingDir, port) {
755
763
  },
756
764
  // Whole-machine memory — what the OOM killer watches. All values in MB.
757
765
  memory: { totalMb, usedMb, availableMb, usedPct, processRssMb },
766
+ // #87: per-key self-test for the active fallback provider. Absent until
767
+ // the async probe lands (and omitted entirely on the Claude path); the
768
+ // frontend surfaces "No working model" when every entry failed/expired.
769
+ ...(agentKeyHealth ? { keyHealth: agentKeyHealth } : {}),
758
770
  }));
759
771
  return;
760
772
  }
@@ -5169,7 +5181,35 @@ async function main() {
5169
5181
  // BEFORE session creation so the OpenRouter redirect env vars (tier 3) are
5170
5182
  // set before the first query() spawn inherits process.env. No-op for
5171
5183
  // tier-1 (real Claude login) and tier-2 (user's own ANTHROPIC_API_KEY).
5172
- applyAuthFallback();
5184
+ // #87: it also RETURNS the provider it selected (claude / zai / openrouter /
5185
+ // anthropic / none) — the single source of truth, since the tier is known at
5186
+ // decision time. Drives agent_ready.provider so the model badge names the
5187
+ // real model instead of the old hardcoded 'claude'.
5188
+ const activeProvider = applyAuthFallback();
5189
+ console.log(`🧭 Active model provider: ${activeProvider}`);
5190
+ // #87: HOUSE-tier key self-test. Presence of a key ≠ validity (the test
5191
+ // account's z.ai key failed and its OpenRouter key had expired, yet the
5192
+ // session showed "Listening" and never replied — the #70 symptom). Fire ONE
5193
+ // tiny real request, fire-and-forget, AFTER the session starts below, so it
5194
+ // adds ZERO latency to the connect path. Scoped to the house fallback tiers
5195
+ // (zai / openrouter) — a user's OWN Anthropic key is their concern and the
5196
+ // SDK surfaces its failures directly; we never ping it per connect. The
5197
+ // result rides GET /health; a definitive failure surfaces "No working model"
5198
+ // instead of a silent non-reply.
5199
+ agentKeyHealth = null;
5200
+ if (activeProvider === 'zai' || activeProvider === 'openrouter') {
5201
+ void probeActiveProviderKey(activeProvider)
5202
+ .then((entry) => {
5203
+ if (!entry)
5204
+ return;
5205
+ agentKeyHealth = [entry];
5206
+ if (entry.status === 'ok')
5207
+ console.log(`✅ [key-health] ${entry.provider} self-test: ok`);
5208
+ else
5209
+ console.warn(`⚠️ [key-health] ${entry.provider} self-test: ${entry.status}`);
5210
+ })
5211
+ .catch(() => { });
5212
+ }
5173
5213
  // Create session based on voice mode (from frontend or config)
5174
5214
  let session;
5175
5215
  let agent;
@@ -5823,7 +5863,12 @@ async function main() {
5823
5863
  return;
5824
5864
  await sendToFrontend({
5825
5865
  type: 'agent_ready',
5826
- provider: 'claude',
5866
+ // #87: the REAL active provider (claude / zai / openrouter / anthropic),
5867
+ // not a hardcoded 'claude' — so the model badge is honest on a fallback
5868
+ // session. 'none' (no model configured at all) is emitted as null so the
5869
+ // badge stays neutral instead of rendering a literal "none" pill; that
5870
+ // dead-end is surfaced by the Claude sign-in flow, not the badge.
5871
+ provider: activeProvider === 'none' ? null : activeProvider,
5827
5872
  voiceMode: sessionVoiceMode,
5828
5873
  hasRecentSession,
5829
5874
  recentSessionId,
@@ -0,0 +1,56 @@
1
+ /**
2
+ * key-health.ts — a tiny, REAL "can this provider actually answer?" self-test for
3
+ * the no-Claude fallback tiers (issue #87, gap 5).
4
+ *
5
+ * The bug this surfaces: applyAuthFallback() picks a tier because a key is
6
+ * PRESENT, but presence is not validity — the observed test account had a z.ai
7
+ * key that failed and an OpenRouter key that had expired, and nothing said so;
8
+ * the session showed "Listening" and silently never replied (the #70 symptom).
9
+ *
10
+ * This fires ONE minimal /v1/messages request against the ACTIVE provider's
11
+ * endpoint (the exact env applyAuthFallback already set) to confirm the
12
+ * configured key can really answer. The result rides GET /health, so a dead key
13
+ * becomes a visible "No working model" instead of a silent non-reply.
14
+ *
15
+ * Design rules (adversarial review of #87):
16
+ * - NEVER on the Claude path (tier 1) and never on the connect critical path:
17
+ * the caller runs it fire-and-forget AFTER the session starts, fallback-only,
18
+ * so it adds zero boot latency to a normal Claude session.
19
+ * - Conservative classification: only a DEFINITIVE auth/billing failure
20
+ * (401/403/402) becomes a negative verdict. A 4xx that could be an endpoint
21
+ * quirk (400/404), any 5xx, a timeout or a network error yields NO verdict
22
+ * (null) — a transient blip must never fabricate "No working model".
23
+ *
24
+ * Shape mirrors the frontend's KeyHealthEntry (frontend/src/lib/agent-health.ts)
25
+ * so resolveAgentHealth consumes it unchanged.
26
+ */
27
+ /** One fallback key's self-test result. Mirrors the frontend KeyHealthEntry. */
28
+ export interface KeyHealthEntry {
29
+ /** Provider key, e.g. 'zai' | 'openrouter' | 'anthropic'. */
30
+ provider: string;
31
+ /** Outcome of the tiny real request. */
32
+ status: 'ok' | 'failed' | 'expired';
33
+ /** ISO timestamp of the test. */
34
+ checkedAt?: string;
35
+ }
36
+ /**
37
+ * Classify a /v1/messages probe's HTTP status into a key-health verdict, or null
38
+ * when the outcome is ambiguous (no honest verdict — see module header).
39
+ * 2xx → ok (the key answered)
40
+ * 429 → ok (valid key, just rate-limited)
41
+ * 401, 403 → expired (bad / expired credential)
42
+ * 402 → failed (billing / credit depleted)
43
+ * anything else → null (endpoint quirk / 5xx / unknown — no verdict)
44
+ */
45
+ export declare function classifyProbeStatus(httpStatus: number): 'ok' | 'failed' | 'expired' | null;
46
+ /**
47
+ * Fire ONE minimal request against the ACTIVE provider endpoint to confirm the
48
+ * configured key can really answer. Reads the env applyAuthFallback() already
49
+ * set (ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN / ANTHROPIC_API_KEY /
50
+ * ANTHROPIC_MODEL), so it tests exactly what query() will use. All fallback
51
+ * tiers speak native Anthropic Messages, so one request shape covers them.
52
+ *
53
+ * Returns the verdict entry, or null when there was nothing to test or the
54
+ * outcome was ambiguous (never a fabricated failure).
55
+ */
56
+ export declare function probeActiveProviderKey(provider: string, env?: NodeJS.ProcessEnv, timeoutMs?: number): Promise<KeyHealthEntry | null>;
@@ -0,0 +1,93 @@
1
+ /**
2
+ * key-health.ts — a tiny, REAL "can this provider actually answer?" self-test for
3
+ * the no-Claude fallback tiers (issue #87, gap 5).
4
+ *
5
+ * The bug this surfaces: applyAuthFallback() picks a tier because a key is
6
+ * PRESENT, but presence is not validity — the observed test account had a z.ai
7
+ * key that failed and an OpenRouter key that had expired, and nothing said so;
8
+ * the session showed "Listening" and silently never replied (the #70 symptom).
9
+ *
10
+ * This fires ONE minimal /v1/messages request against the ACTIVE provider's
11
+ * endpoint (the exact env applyAuthFallback already set) to confirm the
12
+ * configured key can really answer. The result rides GET /health, so a dead key
13
+ * becomes a visible "No working model" instead of a silent non-reply.
14
+ *
15
+ * Design rules (adversarial review of #87):
16
+ * - NEVER on the Claude path (tier 1) and never on the connect critical path:
17
+ * the caller runs it fire-and-forget AFTER the session starts, fallback-only,
18
+ * so it adds zero boot latency to a normal Claude session.
19
+ * - Conservative classification: only a DEFINITIVE auth/billing failure
20
+ * (401/403/402) becomes a negative verdict. A 4xx that could be an endpoint
21
+ * quirk (400/404), any 5xx, a timeout or a network error yields NO verdict
22
+ * (null) — a transient blip must never fabricate "No working model".
23
+ *
24
+ * Shape mirrors the frontend's KeyHealthEntry (frontend/src/lib/agent-health.ts)
25
+ * so resolveAgentHealth consumes it unchanged.
26
+ */
27
+ import { cleanEnvKey } from './claude-auth.js';
28
+ /**
29
+ * Classify a /v1/messages probe's HTTP status into a key-health verdict, or null
30
+ * when the outcome is ambiguous (no honest verdict — see module header).
31
+ * 2xx → ok (the key answered)
32
+ * 429 → ok (valid key, just rate-limited)
33
+ * 401, 403 → expired (bad / expired credential)
34
+ * 402 → failed (billing / credit depleted)
35
+ * anything else → null (endpoint quirk / 5xx / unknown — no verdict)
36
+ */
37
+ export function classifyProbeStatus(httpStatus) {
38
+ if (httpStatus >= 200 && httpStatus < 300)
39
+ return 'ok';
40
+ if (httpStatus === 429)
41
+ return 'ok';
42
+ if (httpStatus === 401 || httpStatus === 403)
43
+ return 'expired';
44
+ if (httpStatus === 402)
45
+ return 'failed';
46
+ return null;
47
+ }
48
+ /**
49
+ * Fire ONE minimal request against the ACTIVE provider endpoint to confirm the
50
+ * configured key can really answer. Reads the env applyAuthFallback() already
51
+ * set (ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN / ANTHROPIC_API_KEY /
52
+ * ANTHROPIC_MODEL), so it tests exactly what query() will use. All fallback
53
+ * tiers speak native Anthropic Messages, so one request shape covers them.
54
+ *
55
+ * Returns the verdict entry, or null when there was nothing to test or the
56
+ * outcome was ambiguous (never a fabricated failure).
57
+ */
58
+ export async function probeActiveProviderKey(provider, env = process.env, timeoutMs = 8000) {
59
+ const base = (cleanEnvKey(env.ANTHROPIC_BASE_URL) || 'https://api.anthropic.com').replace(/\/$/, '');
60
+ const authToken = cleanEnvKey(env.ANTHROPIC_AUTH_TOKEN);
61
+ const apiKey = cleanEnvKey(env.ANTHROPIC_API_KEY);
62
+ const model = cleanEnvKey(env.ANTHROPIC_MODEL) || 'claude-3-5-haiku-latest';
63
+ // Nothing to test — no credential configured for the active endpoint.
64
+ if (!authToken && !apiKey)
65
+ return null;
66
+ const headers = {
67
+ 'content-type': 'application/json',
68
+ 'anthropic-version': '2023-06-01',
69
+ };
70
+ // Fallback redirects (z.ai / OpenRouter) authenticate with a bearer AUTH_TOKEN;
71
+ // a user's own Anthropic key uses x-api-key. applyAuthFallback sets exactly one.
72
+ if (authToken)
73
+ headers['authorization'] = `Bearer ${authToken}`;
74
+ else
75
+ headers['x-api-key'] = apiKey;
76
+ const body = JSON.stringify({ model, max_tokens: 1, messages: [{ role: 'user', content: 'hi' }] });
77
+ try {
78
+ const r = await fetch(`${base}/v1/messages`, {
79
+ method: 'POST',
80
+ headers,
81
+ body,
82
+ signal: AbortSignal.timeout(timeoutMs),
83
+ });
84
+ const verdict = classifyProbeStatus(r.status);
85
+ if (!verdict)
86
+ return null;
87
+ return { provider, status: verdict, checkedAt: new Date().toISOString() };
88
+ }
89
+ catch {
90
+ // Network error / timeout — ambiguous, never a fabricated verdict.
91
+ return null;
92
+ }
93
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osborn",
3
- "version": "0.9.277",
3
+ "version": "0.9.278",
4
4
  "description": "Voice AI coding assistant - local agent that connects to Osborn frontend",
5
5
  "type": "module",
6
6
  "bin": {