osborn 0.9.278 → 0.9.279

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.
@@ -29,7 +29,7 @@ This approach catches rendering issues, unexpected fields, and errors before the
29
29
 
30
30
  ## One-time setup (user does this once per machine)
31
31
 
32
- Secret fields (email, password, phone, address) are filled by the `fill.mjs` helper, not by the MCP tools. The helper and the Playwright MCP must drive the SAME browser, which means both attach to one Chrome over CDP on loopback.
32
+ Candidate values (email, password, phone, address, work history, education) are filled by the `fill.mjs` helper, not by the MCP tools. The helper and the Playwright MCP must drive the SAME browser, which means both attach to one Chrome over CDP on loopback.
33
33
 
34
34
  1. Secret file. The user creates it and types the values in their own editor (never ask for the values in chat, never write them yourself):
35
35
  ```bash
@@ -52,9 +52,9 @@ Secret fields (email, password, phone, address) are filled by the `fill.mjs` hel
52
52
  ## Step-by-Step Execution Pattern
53
53
 
54
54
  ### Step 0 — Check the helper, then open the browser
55
- Run `node ~/.claude/skills/browser-apply/fill.mjs check` first. It prints variable names and `cdp: reachable` or `cdp: unreachable`, never values.
55
+ Run `node ~/.claude/skills/browser-apply/fill.mjs check` first. It prints variable names (including an `extra:` line listing every other `CANDIDATE_*` key the user set — work history, education, anything else) and `cdp: reachable` or `cdp: unreachable`, never values.
56
56
  - File missing / refused: point the user at "One-time setup" step 1 and wait.
57
- - `cdp: unreachable`: you can still navigate and fill the non-secret fields with the MCP tools, but for every secret field (email, password, phone, address) ask the user to type it into the browser themselves.
57
+ - `cdp: unreachable`: you can still navigate and click with the MCP tools, but every value from the secret file — email, password, phone, address, and every work-history and education field — must be typed by the user themselves. You have no copy of any of them; do not reconstruct one.
58
58
 
59
59
  Use: `mcp__playwright__browser_navigate` with the applyManually URL
60
60
 
@@ -81,8 +81,11 @@ Fields to fill:
81
81
  - Sponsorship: No
82
82
 
83
83
  ### Step 4 — My Experience
84
- Snapshot → click Add for each job entry → fill title/company/dates/description → save each → screenshot.
85
- Then add education entries.
84
+ Snapshot → click Add for each job entry → fill title/company/dates/description
85
+ with the helper from `CANDIDATE_JOB_N_*` (see "Candidate Data") → save each →
86
+ screenshot. Then add education entries from `CANDIDATE_EDUCATION_N_*`.
87
+ Never type a job, employer, school or date you were not given by the helper; if
88
+ one is missing, ask the user rather than filling anything.
86
89
  Ask user before clicking Next.
87
90
 
88
91
  ### Step 5 — Application Questions
@@ -113,14 +116,30 @@ Personal values are NOT stored in this skill. They live in a local secret file t
113
116
  | Phone | `$CANDIDATE_PHONE` |
114
117
  | Address line 1 | `$CANDIDATE_ADDRESS_LINE1` |
115
118
  | City / State / Zip | `$CANDIDATE_CITY` / `$CANDIDATE_STATE` / `$CANDIDATE_ZIP` |
116
-
117
- Jobs:
118
- 1. Senior Engineer at Acme Corp — April 2024 to Present
119
- 2. Full Stack Developer, Freelance — January 2016 to Present
120
-
121
- Education:
122
- 1. A.S. Information Systems
123
- 2. B.S. Psychology
119
+ | Job N title / employer | `$CANDIDATE_JOB_N_TITLE` / `$CANDIDATE_JOB_N_COMPANY` |
120
+ | Job N dates | `$CANDIDATE_JOB_N_START` / `$CANDIDATE_JOB_N_END` |
121
+ | Job N description | `$CANDIDATE_JOB_N_DESCRIPTION` |
122
+ | Education N | `$CANDIDATE_EDUCATION_N_SCHOOL` / `$CANDIDATE_EDUCATION_N_DEGREE` / `$CANDIDATE_EDUCATION_N_FIELD` |
123
+
124
+ Work history and education go through the SAME mechanism as the fields above,
125
+ with `N` starting at 1 (`CANDIDATE_JOB_1_TITLE`, `CANDIDATE_JOB_2_TITLE`, …).
126
+ This skill ships NO employment or education values of its own (an earlier
127
+ version carried a literal list; it was removed because it made the skill submit
128
+ an employer that was not the user's), and you must never supply one:
129
+
130
+ - Run `fill.mjs check` and read its `extra:` line: that is exactly which
131
+ `CANDIDATE_JOB_*` / `CANDIDATE_EDUCATION_*` keys the user actually set. It
132
+ prints names only, never values.
133
+ - Fill every one of them with the helper, exactly like the other fields — never
134
+ by typing a value through `mcp__playwright__browser_type` / `browser_fill_form`.
135
+ - If a job or education entry the form asks for is not in the secret file, STOP
136
+ and ask the user to type that entry themselves or add the key. Do NOT invent,
137
+ infer, or carry over an employer, title, school, degree or date from anywhere
138
+ — not from the user's repo, résumé file, an earlier application, or your own
139
+ guess. A wrong employer on a submitted application is a false statement to
140
+ that employer.
141
+ - Numbers are not contiguous promises: stop at the first N with no
142
+ `CANDIDATE_JOB_N_TITLE`, and ask before adding more entries than the file has.
124
143
 
125
144
  ### Filling secret fields
126
145
  Use the helper `fill.mjs` next to this SKILL.md (normally `~/.claude/skills/browser-apply/fill.mjs`). It reads `~/.osborn/candidate.env` itself (regular file, owned by you, mode 600) and attaches to the loopback CDP browser from "One-time setup". It fills only on an https page whose host EXACTLY equals `--confirm-host`. Inside the page, right before each field, it checks again that the field's own frame is https on that host. The password goes only into an `<input type="password">`. It prints `about to fill NAME on HOST` before each field and `filled NAME -> selector` after, never a value.
@@ -157,9 +176,9 @@ Rules:
157
176
  | Address | `[data-automation-id="addressSection_addressLine1"]` | `CANDIDATE_ADDRESS_LINE1` (helper) |
158
177
  | City | `[data-automation-id="addressSection_city"]` | `CANDIDATE_CITY` (helper) |
159
178
  | Zip | `[data-automation-id="addressSection_postalCode"]` | `CANDIDATE_ZIP` (helper) |
160
- | Job title | `[data-automation-id="jobTitle"]` | Jobs list above |
161
- | Company | `[data-automation-id="company"]` | Jobs list above |
162
- | Description | `[data-automation-id="description"]` | Jobs list above |
179
+ | Job title | `[data-automation-id="jobTitle"]` | `CANDIDATE_JOB_N_TITLE` (helper) |
180
+ | Company | `[data-automation-id="company"]` | `CANDIDATE_JOB_N_COMPANY` (helper) |
181
+ | Description | `[data-automation-id="description"]` | `CANDIDATE_JOB_N_DESCRIPTION` (helper) |
163
182
  | Next button | `[data-automation-id="bottom-navigation-next-btn"]` | - |
164
183
  | Create Account | `[data-automation-id="click_filter"][aria-label="Create Account"]` | - |
165
184
 
@@ -12,5 +12,19 @@ CANDIDATE_CITY=YOUR_CITY
12
12
  CANDIDATE_STATE=YOUR_STATE
13
13
  CANDIDATE_ZIP=YOUR_ZIP
14
14
 
15
+ # Work history. The skill ships NO employment values: if a job is not here, the
16
+ # model must ask you instead of filling anything. Number the entries from 1 and
17
+ # add as many as you need (JOB_3, JOB_4, …); delete the ones you do not use.
18
+ CANDIDATE_JOB_1_TITLE=YOUR_JOB_TITLE
19
+ CANDIDATE_JOB_1_COMPANY=YOUR_EMPLOYER
20
+ CANDIDATE_JOB_1_START=YOUR_START_DATE
21
+ CANDIDATE_JOB_1_END=YOUR_END_DATE_OR_Present
22
+ CANDIDATE_JOB_1_DESCRIPTION=WHAT_YOU_DID
23
+
24
+ # Education, numbered the same way. Also ships empty on purpose.
25
+ CANDIDATE_EDUCATION_1_SCHOOL=YOUR_SCHOOL
26
+ CANDIDATE_EDUCATION_1_DEGREE=YOUR_DEGREE
27
+ CANDIDATE_EDUCATION_1_FIELD=YOUR_FIELD_OF_STUDY
28
+
15
29
  # Optional: loopback CDP endpoint of the shared browser (non-loopback hosts are refused).
16
30
  # CANDIDATE_CDP_URL=http://127.0.0.1:9222
@@ -269,8 +269,16 @@ export async function checkReport(path, fileEnv, fetchImpl = fetch) {
269
269
  const set = EXPECTED_VARS.filter(k => fileEnv[k])
270
270
  const missing = EXPECTED_VARS.filter(k => !fileEnv[k])
271
271
  const cdp = cdpFrom(fileEnv)
272
+ // Anything else the user put in the file: work history, education, and any
273
+ // key a future form needs. Per-entry and open-ended, so deliberately not in
274
+ // EXPECTED_VARS (one job and no degree must not read as "missing"); listed by
275
+ // NAME so the model can see what it may fill and never invents an employer.
276
+ const extra = Object.keys(fileEnv)
277
+ .filter(k => k.startsWith('CANDIDATE_') && fileEnv[k] && !EXPECTED_VARS.includes(k) && !CONFIG_KEYS.includes(k))
278
+ .sort()
272
279
  const lines = [`ok: ${path} is a regular file owned by you, mode 600`, `set: ${set.join(', ') || '(none)'}`]
273
280
  if (missing.length) lines.push(`missing: ${missing.join(', ')}`)
281
+ lines.push(`extra: ${extra.join(', ') || '(none — ask the user for any work history, education or other field the form needs)'}`)
274
282
  lines.push(`cdp: ${(await probeCdp(cdp, fetchImpl)) ? 'reachable' : 'unreachable'} (${cdp})`)
275
283
  return lines
276
284
  }
@@ -98,6 +98,28 @@ export declare function applyAuthFallback(): ActiveProvider;
98
98
  * answering instead of the old hardcoded 'claude' (issue #87).
99
99
  */
100
100
  export type ActiveProvider = 'claude' | 'anthropic' | 'zai' | 'openrouter' | 'none';
101
+ /** One fallback key's self-test result, as served on GET /health. */
102
+ export interface KeyHealthEntry {
103
+ provider: string;
104
+ status: 'ok' | 'failed' | 'expired';
105
+ }
106
+ /**
107
+ * A /v1/messages probe's HTTP status → key-health verdict, or null when the
108
+ * outcome is ambiguous: only a DEFINITIVE credential/billing failure earns a
109
+ * negative verdict, because a transient blip must never fabricate "No working
110
+ * model". 403 is deliberately ambiguous — a WAF/edge block or gateway throttle in
111
+ * front of api.z.ai or openrouter.ai answers 403 for a perfectly good key.
112
+ */
113
+ export declare function classifyProbeStatus(httpStatus: number): 'ok' | 'failed' | 'expired' | null;
114
+ /**
115
+ * Fire ONE minimal request against the ACTIVE provider endpoint to confirm the
116
+ * configured key can really answer (#87, gap 5) — applyAuthFallback() picks a tier
117
+ * on key PRESENCE, which is not validity. Reads the env that function just set, so
118
+ * it tests exactly what query() will use; every fallback tier speaks native
119
+ * Anthropic Messages, so one request shape covers them. Returns null when there
120
+ * was nothing to test or the outcome was ambiguous — never a fabricated failure.
121
+ */
122
+ export declare function probeActiveProviderKey(provider: string, env?: NodeJS.ProcessEnv, timeoutMs?: number): Promise<KeyHealthEntry | null>;
101
123
  /**
102
124
  * Clear the fallback redirect (z.ai house pass or OpenRouter) — but ONLY if
103
125
  * applyAuthFallback() set it. Called from the auth onComplete path so a user who later finishes real
@@ -349,6 +349,69 @@ export function applyAuthFallback() {
349
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
350
  return 'none';
351
351
  }
352
+ /**
353
+ * A /v1/messages probe's HTTP status → key-health verdict, or null when the
354
+ * outcome is ambiguous: only a DEFINITIVE credential/billing failure earns a
355
+ * negative verdict, because a transient blip must never fabricate "No working
356
+ * model". 403 is deliberately ambiguous — a WAF/edge block or gateway throttle in
357
+ * front of api.z.ai or openrouter.ai answers 403 for a perfectly good key.
358
+ */
359
+ export function classifyProbeStatus(httpStatus) {
360
+ if (httpStatus >= 200 && httpStatus < 300)
361
+ return 'ok';
362
+ if (httpStatus === 429)
363
+ return 'ok';
364
+ if (httpStatus === 401)
365
+ return 'expired';
366
+ if (httpStatus === 402)
367
+ return 'failed';
368
+ return null;
369
+ }
370
+ /**
371
+ * Fire ONE minimal request against the ACTIVE provider endpoint to confirm the
372
+ * configured key can really answer (#87, gap 5) — applyAuthFallback() picks a tier
373
+ * on key PRESENCE, which is not validity. Reads the env that function just set, so
374
+ * it tests exactly what query() will use; every fallback tier speaks native
375
+ * Anthropic Messages, so one request shape covers them. Returns null when there
376
+ * was nothing to test or the outcome was ambiguous — never a fabricated failure.
377
+ */
378
+ export async function probeActiveProviderKey(provider, env = process.env, timeoutMs = 8000) {
379
+ const base = (cleanEnvKey(env.ANTHROPIC_BASE_URL) || 'https://api.anthropic.com').replace(/\/$/, '');
380
+ const authToken = cleanEnvKey(env.ANTHROPIC_AUTH_TOKEN);
381
+ const apiKey = cleanEnvKey(env.ANTHROPIC_API_KEY);
382
+ // Nothing to test — no credential configured for the active endpoint.
383
+ if (!authToken && !apiKey)
384
+ return null;
385
+ const headers = {
386
+ 'content-type': 'application/json',
387
+ 'anthropic-version': '2023-06-01',
388
+ };
389
+ // Fallback redirects (z.ai / OpenRouter) authenticate with a bearer AUTH_TOKEN;
390
+ // a user's own Anthropic key uses x-api-key. applyAuthFallback sets exactly one.
391
+ if (authToken)
392
+ headers['authorization'] = `Bearer ${authToken}`;
393
+ else
394
+ headers['x-api-key'] = apiKey;
395
+ const body = JSON.stringify({
396
+ model: cleanEnvKey(env.ANTHROPIC_MODEL),
397
+ max_tokens: 1,
398
+ messages: [{ role: 'user', content: 'hi' }],
399
+ });
400
+ try {
401
+ const r = await fetch(`${base}/v1/messages`, {
402
+ method: 'POST',
403
+ headers,
404
+ body,
405
+ signal: AbortSignal.timeout(timeoutMs),
406
+ });
407
+ const verdict = classifyProbeStatus(r.status);
408
+ return verdict ? { provider, status: verdict } : null;
409
+ }
410
+ catch {
411
+ // Network error / timeout — ambiguous, never a fabricated verdict.
412
+ return null;
413
+ }
414
+ }
352
415
  /**
353
416
  * Clear the fallback redirect (z.ai house pass or OpenRouter) — but ONLY if
354
417
  * applyAuthFallback() set it. Called from the auth onComplete path so a user who later finishes real
package/dist/config.d.ts CHANGED
@@ -162,6 +162,41 @@ export interface ClaudeSessionEntry {
162
162
  filePath: string;
163
163
  fileSize: number;
164
164
  }
165
+ /**
166
+ * Reverse a project slug back to a path — LAST-RESORT fallback only.
167
+ *
168
+ * Claude's slug encoding (`/` → `-`, `.` → `-`) is LOSSY: you can't tell from a
169
+ * slug whether a given `-` was originally `/`, `.`, or a literal `-` inside a
170
+ * directory name like `pensive-bohr`. So this function cannot reliably
171
+ * round-trip an arbitrary path.
172
+ *
173
+ * Strategy: produce the naive guess (with a small `--` → `/.` improvement for
174
+ * dot-directories like `.claude`), then VALIDATE it with `existsSync`. If the
175
+ * guess doesn't exist, return empty string — that way the caller knows the
176
+ * reverse failed and can fall back cleanly instead of passing a broken path
177
+ * to `child_process.spawn` and crashing with ENOENT.
178
+ *
179
+ * The primary source of cwd is `extractCwd()` which reads the actual cwd from
180
+ * the JSONL file. This function is only reached when that fails.
181
+ */
182
+ export declare function slugToPath(slug: string): string;
183
+ /**
184
+ * Extract cwd from the first JSONL entry that carries a `cwd` field.
185
+ *
186
+ * Previously: read only the first 8KB and only accepted `type === 'user'`. That
187
+ * broke for sessions whose first JSONL entry was larger than 8KB — e.g. a
188
+ * `queue-operation` containing pasted email/page text. readline never emits the
189
+ * `line` event for an incomplete final chunk, so the scan finds nothing,
190
+ * `listAllClaudeSessions` falls through to the lossy `slugToPath` reverse, and
191
+ * the mangled path ends up as a `cwd` passed to `child_process.spawn`, producing
192
+ * the misleading "Claude Code executable not found" error (see MEMORY bug #11).
193
+ *
194
+ * Now: stream line-by-line with no byte cap, short-circuit on the first entry
195
+ * with a `cwd` field regardless of `type` (every `user` / `attachment` /
196
+ * `assistant` / `system` entry in a Claude JSONL session carries `cwd`, so the
197
+ * scan finishes in the first few KB of any normal session).
198
+ */
199
+ export declare function extractCwd(filePath: string): Promise<string>;
165
200
  export declare function invalidateSessionListCache(): void;
166
201
  /**
167
202
  * Scan ALL Claude Code projects for sessions.
package/dist/config.js CHANGED
@@ -561,8 +561,9 @@ function scanPreviewLines(text, skipFirstPartial) {
561
561
  * gate and (b) the LAST user message. So: small files are read whole (exact);
562
562
  * large files read a bounded HEAD (gate + density sample + first turn/title) +
563
563
  * TAIL (last user message, last activity), turning a hundreds-of-MB parse into
564
- * ~192KB. messageCount becomes an estimate for large files — it's display-only
565
- * and gated on ">2", which any large session clears from the head alone.
564
+ * ~192KB. messageCount becomes an estimate for large files — it's display-only,
565
+ * and is derived from BOTH samples because a compacted transcript can have no
566
+ * countable turn in the head at all.
566
567
  */
567
568
  async function getSessionPreview(filePath, fileSize) {
568
569
  const HEAD = 64 * 1024;
@@ -603,10 +604,10 @@ async function getSessionPreview(filePath, fileSize) {
603
604
  const head = scanPreviewLines(headBuf.toString('utf8', 0, hn), false);
604
605
  const tail = scanPreviewLines(tailBuf.toString('utf8', 0, tn), true);
605
606
  const lastMessage = tail.lastUser ?? head.lastUser;
606
- // Estimate total from head density (display-only). Gate ">2" is satisfied
607
- // by head.count alone for any real large session.
608
- const avg = head.count > 0 ? hn / head.count : hn;
609
- const messageCount = head.count >= 3 ? Math.max(3, Math.round(size / avg)) : head.count;
607
+ // Density from BOTH samples: a compacted transcript opens with a
608
+ // compact_boundary plus tool records, so head.count alone can be 0.
609
+ const sampled = head.count + tail.count;
610
+ const messageCount = sampled > 0 ? Math.max(3, Math.round(size * sampled / (hn + tn))) : 3;
610
611
  return {
611
612
  lastMessage,
612
613
  title: tail.aiTitle ?? head.aiTitle ?? head.firstUser,
@@ -656,7 +657,7 @@ export function sessionExists(sessionId, projectPath) {
656
657
  * The primary source of cwd is `extractCwd()` which reads the actual cwd from
657
658
  * the JSONL file. This function is only reached when that fails.
658
659
  */
659
- function slugToPath(slug) {
660
+ export function slugToPath(slug) {
660
661
  // Naive reverse: leading `-` → `/`, `--` → `/.`, remaining `-` → `/`.
661
662
  // The `--` → `/.` pass handles dot-prefixed directories like `.claude`.
662
663
  const guess = slug
@@ -683,7 +684,7 @@ const UUID_JSONL_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]
683
684
  * `assistant` / `system` entry in a Claude JSONL session carries `cwd`, so the
684
685
  * scan finishes in the first few KB of any normal session).
685
686
  */
686
- async function extractCwd(filePath) {
687
+ export async function extractCwd(filePath) {
687
688
  return new Promise((resolve) => {
688
689
  const fileStream = createReadStream(filePath);
689
690
  const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity });
@@ -726,9 +727,9 @@ const SESSION_LIST_TTL_MS = 300_000;
726
727
  export function invalidateSessionListCache() {
727
728
  _sessionListCache = null;
728
729
  }
729
- // v2: sanitized lastMessage, title, firstTs, lastActivityAt, corrected turn count.
730
- // A v1 manifest is discarded on load (its previews carry raw wrapper text).
731
- const SESSION_MANIFEST_VERSION = 2;
730
+ // Older manifests are discarded on load. v2: sanitized preview fields. v3: the
731
+ // large-file messageCount estimate changed, and unchanged files are never re-read.
732
+ const SESSION_MANIFEST_VERSION = 3;
732
733
  function sessionManifestPath() {
733
734
  return join(homedir(), '.claude', 'session-manifest.json');
734
735
  }
package/dist/index.js CHANGED
@@ -34,16 +34,15 @@ import { createGunzip } from 'node:zlib';
34
34
  const __filename = fileURLToPath(import.meta.url);
35
35
  const __dirname = dirname(__filename);
36
36
  import { createPatch } from 'diff';
37
- import { loadConfig, getMcpServers, getEnabledMcpServerNames, getVoiceMode, getDirectConfig, listSessions, listAllClaudeSessions, invalidateSessionListCache, getMostRecentSessionId, sessionExists, getSessionSummary, getConversationHistory, ensureSessionWorkspace, getMcpServerStatusList, buildMcpServersForKeys, listWorkspaceArtifacts } from './config.js';
37
+ import { loadConfig, getMcpServers, getEnabledMcpServerNames, getVoiceMode, getDirectConfig, listSessions, listAllClaudeSessions, extractCwd, slugToPath, getClaudeProjectsDir, invalidateSessionListCache, getMostRecentSessionId, sessionExists, getSessionSummary, getConversationHistory, ensureSessionWorkspace, getMcpServerStatusList, buildMcpServersForKeys, listWorkspaceArtifacts } from './config.js';
38
38
  import { isSafeArtifactPath } from './lib/safe-artifact-path.js';
39
39
  import { cleanupHousekeeping } from './housekeeping.js';
40
40
  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
- import { ensureClaudeAuth, applyAuthFallback, replayInFlightAuth, startClaudeAuthOnDemand, isOnDemandAuthInFlight } from './claude-auth.js';
44
- import { probeActiveProviderKey } from './key-health.js';
43
+ import { ensureClaudeAuth, applyAuthFallback, replayInFlightAuth, startClaudeAuthOnDemand, isOnDemandAuthInFlight, probeActiveProviderKey } from './claude-auth.js';
45
44
  import { statusManager } from './status-manager.js';
46
- import { decideNextSession, planSwitch, resolveSessionCwd, keepNonConversationItems, recoverySessionId as pickRecoverySessionId, warmParkKey, sessionMessagesDir, createSwitchGuard, scanSlugCwd, pickConnectWorkingDir } from './session-switch.js';
45
+ import { decideNextSession, planSwitch, resolveSessionCwd, keepNonConversationItems, recoverySessionId as pickRecoverySessionId, warmParkKey, sessionMessagesDir, createSwitchGuard, scanSlugCwd } from './session-switch.js';
47
46
  import { createSmitheryProxy, destroySmitheryProxy, parseSmitheryUrl, isSmitheryUrl, SmitheryAuthorizationError } from './smithery-proxy.js';
48
47
  import { DIRECT_MODE_PROMPT } from './prompts.js';
49
48
  import { MCP_CATALOG } from './config.js';
@@ -283,12 +282,34 @@ let bugReportHook = null;
283
282
  // in the background without depending on main()'s closure directly.
284
283
  let codeServerStartHook = null;
285
284
  // ── 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.
285
+ // #87: the tier the agent is really answering on + that tier's key self-test. Both
286
+ // ride GET /health, so the badge names the real model and a dead key surfaces as
287
+ // "No working model" instead of a silent non-reply. Null = not known yet (or an
288
+ // ambiguous probe) — never a fabricated verdict.
289
+ let agentActiveProvider = null;
291
290
  let agentKeyHealth = null;
291
+ /**
292
+ * House-tier key self-test (#87) for whichever tier is active, fire-and-forget so
293
+ * it costs the connect path nothing. A user's OWN Anthropic key is skipped — the
294
+ * SDK surfaces its failures directly. Always clears the previous tier's verdict
295
+ * first, so a tier swap cannot leave a stale "No working model" on screen.
296
+ */
297
+ function startKeyHealthProbe() {
298
+ const provider = agentActiveProvider;
299
+ agentKeyHealth = null;
300
+ if (provider !== 'zai' && provider !== 'openrouter')
301
+ return;
302
+ void probeActiveProviderKey(provider)
303
+ .then((entry) => {
304
+ // The tier may have changed while this 8s probe was in flight (a sign-in
305
+ // mid-session) — a late verdict for the tier we left is not news.
306
+ if (!entry || agentActiveProvider !== provider)
307
+ return;
308
+ agentKeyHealth = [entry];
309
+ console.log(`${entry.status === 'ok' ? '✅' : '⚠️'} [key-health] ${entry.provider} self-test: ${entry.status}`);
310
+ })
311
+ .catch(() => { });
312
+ }
292
313
  // ── IDE reverse-proxy (module scope — shared between startApiServer + main) ──
293
314
  // code-server runs on 127.0.0.1:8300; the agent proxies it through its own
294
315
  // public HTTP server so no Cloudflare tunnel is needed.
@@ -763,9 +784,10 @@ function startApiServer(workingDir, port) {
763
784
  },
764
785
  // Whole-machine memory — what the OOM killer watches. All values in MB.
765
786
  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.
787
+ // #87: the tier actually answering + its key self-test. `provider` is the
788
+ // LIVE reading — agent_ready fires once, so it goes stale the moment a
789
+ // mid-session sign-in swaps the tier.
790
+ ...(agentActiveProvider ? { provider: agentActiveProvider } : {}),
769
791
  ...(agentKeyHealth ? { keyHealth: agentKeyHealth } : {}),
770
792
  }));
771
793
  return;
@@ -3713,11 +3735,14 @@ async function main() {
3713
3735
  // Set by the agent_ready retry loop; a switch must stop it so a late
3714
3736
  // agent_ready (preSelectedSessionId = A) doesn't reset the UI back to A.
3715
3737
  let stopReadyRetries = null;
3738
+ // Connect AWAITS this, so keep every lookup cheap: no listAllClaudeSessions().
3716
3739
  function resolveCwdForSession(sessionId, hint) {
3717
3740
  return resolveSessionCwd(sessionId, hint, workingDir, {
3718
3741
  exists: (id, wd) => sessionExists(id, wd),
3719
- listCwd: async (id) => (await listAllClaudeSessions()).find(s => s.sessionId === id)?.cwd ?? null,
3720
- scanCwd: (id) => scanSlugCwd(id, join(homedir(), '.claude', 'projects'), { readdir: (d) => readdirSync(d), exists: (p) => existsSync(p) }),
3742
+ lookupCwd: (id) => scanSlugCwd(id, getClaudeProjectsDir(), {
3743
+ readdir: (d) => readdirSync(d), exists: (p) => existsSync(p),
3744
+ decodeSlug: (s) => slugToPath(s), readCwd: (p) => extractCwd(p),
3745
+ }),
3721
3746
  });
3722
3747
  }
3723
3748
  function findSlotKey(sessionId) {
@@ -5107,18 +5132,13 @@ async function main() {
5107
5132
  if (Number.isFinite(c) && c > 0)
5108
5133
  connectTiming.clickTs = c;
5109
5134
  }
5110
- // Working directory for this connection (resume-mismatch fix, #112).
5111
- //
5112
- // The client's workingDirectory is only a HINT. When a session is pre-
5113
- // selected, the agent is AUTHORITATIVE about where that session lives:
5114
- // resolve its real project dir (the only dir whose slug holds the
5115
- // session's JSONL) and boot there, so `--resume <id>` finds it instead of
5116
- // coming up in /workspace root — or silently as a different session —
5117
- // when the hint is stale or empty (e.g. a switch rewrote the URL without
5118
- // a cwd). resolveCwdForSession returns null only when the JSONL exists
5119
- // nowhere yet (fresh sprite / brand-new project), in which case the hint
5120
- // is honoured and created so the SDK spawn still has a valid cwd.
5121
- const wdHint = (metadata.workingDirectory && typeof metadata.workingDirectory === 'string' && metadata.workingDirectory.length > 0)
5135
+ // Working directory for this connection (resume-mismatch fix, #112). The
5136
+ // client's workingDirectory is only a HINT; for a pre-selected session the
5137
+ // agent is AUTHORITATIVE about where that session lives, so `--resume`
5138
+ // finds its JSONL instead of coming up in the workspace root — or as a
5139
+ // different session — on a stale or empty hint. null = the JSONL is
5140
+ // nowhere yet (fresh sprite / new project), so the hint stands.
5141
+ const wdHint = (typeof metadata.workingDirectory === 'string' && metadata.workingDirectory.length > 0)
5122
5142
  ? metadata.workingDirectory
5123
5143
  : null;
5124
5144
  let resolvedConnectCwd = null;
@@ -5128,19 +5148,17 @@ async function main() {
5128
5148
  }
5129
5149
  catch (e) {
5130
5150
  console.warn('⚠️ connect cwd resolve failed:', e instanceof Error ? e.message : e);
5131
- resolvedConnectCwd = null;
5132
5151
  }
5133
5152
  }
5134
- const connectWd = pickConnectWorkingDir({ preSelectedSessionId, resolved: resolvedConnectCwd, hint: wdHint, defaultDir: defaultWorkingDir });
5135
- // Recursive mkdirSync is a no-op when the dir already exists; only the
5136
- // hint path (new project / fresh sprite) needs creating — the resolved
5137
- // dir exists by construction, the default is the agent's own boot dir.
5138
- if (connectWd.createIfMissing && !existsSync(connectWd.dir)) {
5139
- mkdirSync(connectWd.dir, { recursive: true });
5140
- console.log(`📁 Created project directory: ${connectWd.dir}`);
5153
+ workingDir = resolvedConnectCwd || wdHint || defaultWorkingDir;
5154
+ // Only the HINT is ever created: a resolved cwd can come from an imported
5155
+ // session's JSONL and name another machine's path, and creating that tree
5156
+ // would boot the agent in an empty dir (scanSlugCwd won't either).
5157
+ if (workingDir === wdHint && !existsSync(workingDir)) {
5158
+ mkdirSync(workingDir, { recursive: true });
5159
+ console.log(`📁 Created project directory: ${workingDir}`);
5141
5160
  }
5142
- workingDir = connectWd.dir;
5143
- console.log(`📂 Working directory (${connectWd.source}): ${workingDir}`);
5161
+ console.log(`📂 Working directory: ${workingDir}`);
5144
5162
  }
5145
5163
  catch (err) {
5146
5164
  console.log('⚠️ Could not parse participant metadata, using config voiceMode:', voiceMode);
@@ -5181,35 +5199,11 @@ async function main() {
5181
5199
  // BEFORE session creation so the OpenRouter redirect env vars (tier 3) are
5182
5200
  // set before the first query() spawn inherits process.env. No-op for
5183
5201
  // tier-1 (real Claude login) and tier-2 (user's own ANTHROPIC_API_KEY).
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'.
5202
+ // #87: record WHICH tier it selected — that drives agent_ready.provider and
5203
+ // /health. The key self-test for it fires after session start.
5188
5204
  const activeProvider = applyAuthFallback();
5205
+ agentActiveProvider = activeProvider === 'none' ? null : activeProvider;
5189
5206
  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
- }
5213
5207
  // Create session based on voice mode (from frontend or config)
5214
5208
  let session;
5215
5209
  let agent;
@@ -5286,6 +5280,8 @@ async function main() {
5286
5280
  }
5287
5281
  currentSession = session;
5288
5282
  currentAgent = agent; // Store for updateChatCtx() context injection
5283
+ // #87: the session is live — NOW run the house-tier key self-test.
5284
+ startKeyHealthProbe();
5289
5285
  // CLICK-TIME OVERLAP (default-ON; OSBORN_CONNECT_OVERLAP=off): for a resumed
5290
5286
  // session, kick the JSONL replay NOW (fire-and-forget) so it overlaps the
5291
5287
  // user getting situated + speaking — instead of paying it serially on the
@@ -5865,10 +5861,11 @@ async function main() {
5865
5861
  type: 'agent_ready',
5866
5862
  // #87: the REAL active provider (claude / zai / openrouter / anthropic),
5867
5863
  // 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,
5864
+ // session. Null when no model is configured at all, so the badge stays
5865
+ // neutral instead of rendering a literal "none" pill; that dead-end is
5866
+ // surfaced by the Claude sign-in flow. /health re-serves this live, which
5867
+ // is what keeps it true after a sign-in (agent_ready fires only once).
5868
+ provider: agentActiveProvider,
5872
5869
  voiceMode: sessionVoiceMode,
5873
5870
  hasRecentSession,
5874
5871
  recentSessionId,
@@ -6183,8 +6180,17 @@ async function main() {
6183
6180
  // Only when a fallback redirect was actually active: live persistent
6184
6181
  // sessions restart BEFORE their next turn (deferred — a streaming
6185
6182
  // turn finishes normally), resuming the same sessionId on Claude.
6186
- if (fallbackCleared)
6187
- requestAuthRestart();
6183
+ if (!fallbackCleared)
6184
+ return;
6185
+ // Publish the new tier and drop the dead one's verdict BEFORE the
6186
+ // respawn, or /health keeps serving {provider:'zai', status:'expired'}
6187
+ // and the UI claims "The session can't answer" while Claude answers
6188
+ // fine. fallbackCleared is only reachable once Claude auth really
6189
+ // exists (every other outcome of the flow rejects), including the
6190
+ // CLI/Keychain case that isClaudeAuthenticated() cannot see.
6191
+ agentActiveProvider = 'claude';
6192
+ startKeyHealthProbe();
6193
+ requestAuthRestart();
6188
6194
  });
6189
6195
  }
6190
6196
  }
@@ -78,15 +78,13 @@ export declare function planSwitch(decision: SessionSwitchDecision, ctx: SwitchP
78
78
  export interface SessionCwdDeps {
79
79
  /** sessionExists(id, projectPath) from config.ts. */
80
80
  exists: (sessionId: string, cwd: string) => boolean;
81
- /** Routing cwd from listAllClaudeSessions() (slug-derived), or null. */
82
- listCwd: (sessionId: string) => Promise<string | null | undefined>;
83
- /** Last resort: find <id>.jsonl in any project slug and decode its cwd. */
84
- scanCwd: (sessionId: string) => Promise<string | null | undefined>;
81
+ /** Find ONE session's project dir (scanSlugCwd), or null. */
82
+ lookupCwd: (sessionId: string) => Promise<string | null | undefined>;
85
83
  }
86
84
  /**
87
85
  * The project directory a session's JSONL resolves under (what `--resume`
88
86
  * needs as cwd): the client's hint if the session really lives there, else
89
- * the current dir, else the session list's routing cwd, else a slug scan.
87
+ * the current dir, else a one-session scan of the project slugs.
90
88
  * null = the session does not exist ("Session not found"). A candidate is
91
89
  * only returned after `exists()` confirms it.
92
90
  */
@@ -122,38 +120,6 @@ export declare function warmParkKey(llm: {
122
120
  * otherwise the agent's boot dir (today's behaviour). Never trusts the param.
123
121
  */
124
122
  export declare function sessionMessagesDir(sessionId: string, requested: string | null | undefined, bootDir: string, exists: (sessionId: string, cwd: string) => boolean): string;
125
- /**
126
- * Working directory the agent boots a CONNECTION in (connect-time, #112).
127
- *
128
- * The resume mismatch bug: a client opens `/chat?session=A&workingDirectory=X`,
129
- * but X is stale/empty (a switch rewrote the URL without a cwd, or the hint was
130
- * never the session's real project). Trusting the raw hint booted the agent in
131
- * the wrong dir — often `/workspace` root — so `--resume A` never found A's
132
- * JSONL and the session silently came up as the wrong one with a generic
133
- * "Workspace" chip. The fix makes the agent AUTHORITATIVE about a pre-selected
134
- * session's cwd: its RESOLVED project dir wins over the client hint.
135
- *
136
- * `resolved` is resolveSessionCwd(preSelectedSessionId, hint, …) — the only dir
137
- * where A's JSONL actually exists (null = found nowhere yet). Pure: the caller
138
- * does the I/O (resolveSessionCwd) and the mkdir when `createIfMissing`.
139
- *
140
- * - pre-selected + resolved → the resolved dir (already exists, no mkdir).
141
- * - pre-selected + unresolved + hint → the hint, created (fresh sprite / new
142
- * project whose JSONL isn't on disk yet, so --resume can still attach there).
143
- * - pre-selected + nothing → the default boot dir.
144
- * - no pre-selected + hint → the hint, created (new project).
145
- * - no pre-selected + nothing → the default boot dir.
146
- */
147
- export declare function pickConnectWorkingDir(args: {
148
- preSelectedSessionId: string | null | undefined;
149
- resolved: string | null | undefined;
150
- hint: string | null | undefined;
151
- defaultDir: string;
152
- }): {
153
- dir: string;
154
- createIfMissing: boolean;
155
- source: 'resolved' | 'hint' | 'default';
156
- };
157
123
  /**
158
124
  * Single-flight guard for performSessionSwitch. Only the critical section
159
125
  * (teardown + arm + session_switched) holds the guard; `after` (the spoken
@@ -176,8 +142,16 @@ export declare function createSwitchGuard(): {
176
142
  * and decoding the slug (the same recovery resume_session has always used).
177
143
  * The decoding is lossy, so only a decoded path that EXISTS is returned — the
178
144
  * switch executor never creates directories for scan-derived paths.
145
+ *
146
+ * The `readCwd` fallback gets that same existence check, because an imported
147
+ * session's JSONL can record a cwd from another machine while sessionExists()
148
+ * only looks at the slug.
179
149
  */
180
150
  export declare function scanSlugCwd(sessionId: string, projectsDir: string, fsx: {
181
151
  readdir: (dir: string) => string[];
182
152
  exists: (path: string) => boolean;
153
+ /** slugToPath(slug) from config.ts: the lossy reverse, '' when it misses. */
154
+ decodeSlug: (slug: string) => string;
155
+ /** extractCwd(filePath) from config.ts: the cwd the JSONL itself records. */
156
+ readCwd: (filePath: string) => Promise<string | null | undefined>;
183
157
  }): Promise<string | null>;
@@ -67,7 +67,7 @@ export function planSwitch(decision, ctx) {
67
67
  /**
68
68
  * The project directory a session's JSONL resolves under (what `--resume`
69
69
  * needs as cwd): the client's hint if the session really lives there, else
70
- * the current dir, else the session list's routing cwd, else a slug scan.
70
+ * the current dir, else a one-session scan of the project slugs.
71
71
  * null = the session does not exist ("Session not found"). A candidate is
72
72
  * only returned after `exists()` confirms it.
73
73
  */
@@ -78,18 +78,14 @@ export async function resolveSessionCwd(sessionId, hint, currentDir, deps) {
78
78
  if (c && deps.exists(sessionId, c))
79
79
  return c;
80
80
  }
81
- for (const lookup of [deps.listCwd, deps.scanCwd]) {
82
- let c = null;
83
- try {
84
- c = await lookup(sessionId);
85
- }
86
- catch {
87
- c = null;
88
- }
89
- if (c && deps.exists(sessionId, c))
90
- return c;
81
+ let c = null;
82
+ try {
83
+ c = await deps.lookupCwd(sessionId);
91
84
  }
92
- return null;
85
+ catch {
86
+ c = null;
87
+ }
88
+ return c && deps.exists(sessionId, c) ? c : null;
93
89
  }
94
90
  /**
95
91
  * chatCtx rebuild on switch (4.13): keep the agent's non-conversation items
@@ -127,42 +123,6 @@ export function sessionMessagesDir(sessionId, requested, bootDir, exists) {
127
123
  }
128
124
  return bootDir;
129
125
  }
130
- /**
131
- * Working directory the agent boots a CONNECTION in (connect-time, #112).
132
- *
133
- * The resume mismatch bug: a client opens `/chat?session=A&workingDirectory=X`,
134
- * but X is stale/empty (a switch rewrote the URL without a cwd, or the hint was
135
- * never the session's real project). Trusting the raw hint booted the agent in
136
- * the wrong dir — often `/workspace` root — so `--resume A` never found A's
137
- * JSONL and the session silently came up as the wrong one with a generic
138
- * "Workspace" chip. The fix makes the agent AUTHORITATIVE about a pre-selected
139
- * session's cwd: its RESOLVED project dir wins over the client hint.
140
- *
141
- * `resolved` is resolveSessionCwd(preSelectedSessionId, hint, …) — the only dir
142
- * where A's JSONL actually exists (null = found nowhere yet). Pure: the caller
143
- * does the I/O (resolveSessionCwd) and the mkdir when `createIfMissing`.
144
- *
145
- * - pre-selected + resolved → the resolved dir (already exists, no mkdir).
146
- * - pre-selected + unresolved + hint → the hint, created (fresh sprite / new
147
- * project whose JSONL isn't on disk yet, so --resume can still attach there).
148
- * - pre-selected + nothing → the default boot dir.
149
- * - no pre-selected + hint → the hint, created (new project).
150
- * - no pre-selected + nothing → the default boot dir.
151
- */
152
- export function pickConnectWorkingDir(args) {
153
- const hint = norm(args.hint);
154
- if (norm(args.preSelectedSessionId)) {
155
- const resolved = norm(args.resolved);
156
- if (resolved)
157
- return { dir: resolved, createIfMissing: false, source: 'resolved' };
158
- if (hint)
159
- return { dir: hint, createIfMissing: true, source: 'hint' };
160
- return { dir: args.defaultDir, createIfMissing: false, source: 'default' };
161
- }
162
- if (hint)
163
- return { dir: hint, createIfMissing: true, source: 'hint' };
164
- return { dir: args.defaultDir, createIfMissing: false, source: 'default' };
165
- }
166
126
  // ── Review minors ────────────────────────────────────────────────────────────
167
127
  /**
168
128
  * Single-flight guard for performSessionSwitch. Only the critical section
@@ -202,6 +162,10 @@ export function createSwitchGuard() {
202
162
  * and decoding the slug (the same recovery resume_session has always used).
203
163
  * The decoding is lossy, so only a decoded path that EXISTS is returned — the
204
164
  * switch executor never creates directories for scan-derived paths.
165
+ *
166
+ * The `readCwd` fallback gets that same existence check, because an imported
167
+ * session's JSONL can record a cwd from another machine while sessionExists()
168
+ * only looks at the slug.
205
169
  */
206
170
  export async function scanSlugCwd(sessionId, projectsDir, fsx) {
207
171
  if (!sessionId || !fsx.exists(projectsDir))
@@ -213,12 +177,24 @@ export async function scanSlugCwd(sessionId, projectsDir, fsx) {
213
177
  catch {
214
178
  return null;
215
179
  }
180
+ let firstMatch = null;
216
181
  for (const slug of slugs) {
217
- if (!fsx.exists(`${projectsDir}/${slug}/${sessionId}.jsonl`))
182
+ const filePath = `${projectsDir}/${slug}/${sessionId}.jsonl`;
183
+ if (!fsx.exists(filePath))
218
184
  continue;
219
- const recovered = slug.replace(/^-/, '/').replace(/--/g, '/.').replace(/-/g, '/');
220
- if (recovered && recovered !== '/' && fsx.exists(recovered))
185
+ if (!firstMatch)
186
+ firstMatch = filePath;
187
+ const recovered = fsx.decodeSlug(slug);
188
+ if (recovered && recovered !== '/')
221
189
  return recovered;
222
190
  }
223
- return null;
191
+ if (!firstMatch)
192
+ return null;
193
+ try {
194
+ const recorded = await fsx.readCwd(firstMatch);
195
+ return recorded && fsx.exists(recorded) ? recorded : null;
196
+ }
197
+ catch {
198
+ return null;
199
+ }
224
200
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osborn",
3
- "version": "0.9.278",
3
+ "version": "0.9.279",
4
4
  "description": "Voice AI coding assistant - local agent that connects to Osborn frontend",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,56 +0,0 @@
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>;
@@ -1,93 +0,0 @@
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
- }