osborn 0.9.277 → 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
  }
@@ -90,7 +90,36 @@ 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';
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>;
94
123
  /**
95
124
  * Clear the fallback redirect (z.ai house pass or OpenRouter) — but ONLY if
96
125
  * 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,80 @@ 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';
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
+ }
344
414
  }
345
415
  /**
346
416
  * Clear the fallback redirect (z.ai house pass or OpenRouter) — but ONLY if
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,15 +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';
43
+ import { ensureClaudeAuth, applyAuthFallback, replayInFlightAuth, startClaudeAuthOnDemand, isOnDemandAuthInFlight, probeActiveProviderKey } from './claude-auth.js';
44
44
  import { statusManager } from './status-manager.js';
45
- 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';
46
46
  import { createSmitheryProxy, destroySmitheryProxy, parseSmitheryUrl, isSmitheryUrl, SmitheryAuthorizationError } from './smithery-proxy.js';
47
47
  import { DIRECT_MODE_PROMPT } from './prompts.js';
48
48
  import { MCP_CATALOG } from './config.js';
@@ -281,6 +281,35 @@ let bugReportHook = null;
281
281
  // closure. The /editor route in startApiServer() calls this to start the IDE
282
282
  // in the background without depending on main()'s closure directly.
283
283
  let codeServerStartHook = null;
284
+ // ── Model-provider health (module scope — shared between startApiServer + main) ──
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;
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
+ }
284
313
  // ── IDE reverse-proxy (module scope — shared between startApiServer + main) ──
285
314
  // code-server runs on 127.0.0.1:8300; the agent proxies it through its own
286
315
  // public HTTP server so no Cloudflare tunnel is needed.
@@ -755,6 +784,11 @@ function startApiServer(workingDir, port) {
755
784
  },
756
785
  // Whole-machine memory — what the OOM killer watches. All values in MB.
757
786
  memory: { totalMb, usedMb, availableMb, usedPct, processRssMb },
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 } : {}),
791
+ ...(agentKeyHealth ? { keyHealth: agentKeyHealth } : {}),
758
792
  }));
759
793
  return;
760
794
  }
@@ -3701,11 +3735,14 @@ async function main() {
3701
3735
  // Set by the agent_ready retry loop; a switch must stop it so a late
3702
3736
  // agent_ready (preSelectedSessionId = A) doesn't reset the UI back to A.
3703
3737
  let stopReadyRetries = null;
3738
+ // Connect AWAITS this, so keep every lookup cheap: no listAllClaudeSessions().
3704
3739
  function resolveCwdForSession(sessionId, hint) {
3705
3740
  return resolveSessionCwd(sessionId, hint, workingDir, {
3706
3741
  exists: (id, wd) => sessionExists(id, wd),
3707
- listCwd: async (id) => (await listAllClaudeSessions()).find(s => s.sessionId === id)?.cwd ?? null,
3708
- 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
+ }),
3709
3746
  });
3710
3747
  }
3711
3748
  function findSlotKey(sessionId) {
@@ -5095,18 +5132,13 @@ async function main() {
5095
5132
  if (Number.isFinite(c) && c > 0)
5096
5133
  connectTiming.clickTs = c;
5097
5134
  }
5098
- // Working directory for this connection (resume-mismatch fix, #112).
5099
- //
5100
- // The client's workingDirectory is only a HINT. When a session is pre-
5101
- // selected, the agent is AUTHORITATIVE about where that session lives:
5102
- // resolve its real project dir (the only dir whose slug holds the
5103
- // session's JSONL) and boot there, so `--resume <id>` finds it instead of
5104
- // coming up in /workspace root — or silently as a different session —
5105
- // when the hint is stale or empty (e.g. a switch rewrote the URL without
5106
- // a cwd). resolveCwdForSession returns null only when the JSONL exists
5107
- // nowhere yet (fresh sprite / brand-new project), in which case the hint
5108
- // is honoured and created so the SDK spawn still has a valid cwd.
5109
- 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)
5110
5142
  ? metadata.workingDirectory
5111
5143
  : null;
5112
5144
  let resolvedConnectCwd = null;
@@ -5116,19 +5148,17 @@ async function main() {
5116
5148
  }
5117
5149
  catch (e) {
5118
5150
  console.warn('⚠️ connect cwd resolve failed:', e instanceof Error ? e.message : e);
5119
- resolvedConnectCwd = null;
5120
5151
  }
5121
5152
  }
5122
- const connectWd = pickConnectWorkingDir({ preSelectedSessionId, resolved: resolvedConnectCwd, hint: wdHint, defaultDir: defaultWorkingDir });
5123
- // Recursive mkdirSync is a no-op when the dir already exists; only the
5124
- // hint path (new project / fresh sprite) needs creating — the resolved
5125
- // dir exists by construction, the default is the agent's own boot dir.
5126
- if (connectWd.createIfMissing && !existsSync(connectWd.dir)) {
5127
- mkdirSync(connectWd.dir, { recursive: true });
5128
- 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}`);
5129
5160
  }
5130
- workingDir = connectWd.dir;
5131
- console.log(`📂 Working directory (${connectWd.source}): ${workingDir}`);
5161
+ console.log(`📂 Working directory: ${workingDir}`);
5132
5162
  }
5133
5163
  catch (err) {
5134
5164
  console.log('⚠️ Could not parse participant metadata, using config voiceMode:', voiceMode);
@@ -5169,7 +5199,11 @@ async function main() {
5169
5199
  // BEFORE session creation so the OpenRouter redirect env vars (tier 3) are
5170
5200
  // set before the first query() spawn inherits process.env. No-op for
5171
5201
  // tier-1 (real Claude login) and tier-2 (user's own ANTHROPIC_API_KEY).
5172
- applyAuthFallback();
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.
5204
+ const activeProvider = applyAuthFallback();
5205
+ agentActiveProvider = activeProvider === 'none' ? null : activeProvider;
5206
+ console.log(`🧭 Active model provider: ${activeProvider}`);
5173
5207
  // Create session based on voice mode (from frontend or config)
5174
5208
  let session;
5175
5209
  let agent;
@@ -5246,6 +5280,8 @@ async function main() {
5246
5280
  }
5247
5281
  currentSession = session;
5248
5282
  currentAgent = agent; // Store for updateChatCtx() context injection
5283
+ // #87: the session is live — NOW run the house-tier key self-test.
5284
+ startKeyHealthProbe();
5249
5285
  // CLICK-TIME OVERLAP (default-ON; OSBORN_CONNECT_OVERLAP=off): for a resumed
5250
5286
  // session, kick the JSONL replay NOW (fire-and-forget) so it overlaps the
5251
5287
  // user getting situated + speaking — instead of paying it serially on the
@@ -5823,7 +5859,13 @@ async function main() {
5823
5859
  return;
5824
5860
  await sendToFrontend({
5825
5861
  type: 'agent_ready',
5826
- provider: 'claude',
5862
+ // #87: the REAL active provider (claude / zai / openrouter / anthropic),
5863
+ // not a hardcoded 'claude' — so the model badge is honest on a fallback
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,
5827
5869
  voiceMode: sessionVoiceMode,
5828
5870
  hasRecentSession,
5829
5871
  recentSessionId,
@@ -6138,8 +6180,17 @@ async function main() {
6138
6180
  // Only when a fallback redirect was actually active: live persistent
6139
6181
  // sessions restart BEFORE their next turn (deferred — a streaming
6140
6182
  // turn finishes normally), resuming the same sessionId on Claude.
6141
- if (fallbackCleared)
6142
- 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();
6143
6194
  });
6144
6195
  }
6145
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.277",
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": {