osborn 0.9.276 → 0.9.278

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -115,7 +115,7 @@ Personal values are NOT stored in this skill. They live in a local secret file t
115
115
  | City / State / Zip | `$CANDIDATE_CITY` / `$CANDIDATE_STATE` / `$CANDIDATE_ZIP` |
116
116
 
117
117
  Jobs:
118
- 1. Meta API Consultant at Prehype / Audos — April 2024 to Present
118
+ 1. Senior Engineer at Acme Corp — April 2024 to Present
119
119
  2. Full Stack Developer, Freelance — January 2016 to Present
120
120
 
121
121
  Education:
@@ -90,7 +90,14 @@ export declare function inFlightAuthBlocksJoin(env: NodeJS.ProcessEnv, force?: b
90
90
  * subprocess inherits process.env at spawn time and reads auth/model config
91
91
  * once at cold start.
92
92
  */
93
- export declare function applyAuthFallback(): void;
93
+ export declare function applyAuthFallback(): ActiveProvider;
94
+ /**
95
+ * The model backend the agent is actually answering on, as returned by
96
+ * applyAuthFallback() (single source of truth — the tier is known at decision
97
+ * time). Drives agent_ready.provider so the model badge names what is really
98
+ * answering instead of the old hardcoded 'claude' (issue #87).
99
+ */
100
+ export type ActiveProvider = 'claude' | 'anthropic' | 'zai' | 'openrouter' | 'none';
94
101
  /**
95
102
  * Clear the fallback redirect (z.ai house pass or OpenRouter) — but ONLY if
96
103
  * applyAuthFallback() set it. Called from the auth onComplete path so a user who later finishes real
@@ -269,13 +269,13 @@ export function applyAuthFallback() {
269
269
  // Tier 1: real Claude login (expiry-aware — NOT hasOAuthTokenEnv, which
270
270
  // would treat an expired token as active and let the SDK fail downstream).
271
271
  if (isClaudeAuthenticated()) {
272
- return;
272
+ return 'claude';
273
273
  }
274
274
  // Tier 2: user's own Anthropic key.
275
275
  const anthropicKey = cleanEnvKey(process.env.ANTHROPIC_API_KEY);
276
276
  if (anthropicKey !== '') {
277
277
  process.env.ANTHROPIC_API_KEY = anthropicKey;
278
- return;
278
+ return 'anthropic';
279
279
  }
280
280
  // Tier 3: HOUSE DEMO PASS - z.ai GLM coding subscription (flat/shared, not
281
281
  // pay-per-use). Cline/opencode-style: unauthenticated demo users ride the
@@ -306,7 +306,7 @@ export function applyAuthFallback() {
306
306
  process.env.OSBORN_DEMO_PASS = 'zai';
307
307
  fallbackTierActive = true;
308
308
  console.log(`[auth-fallback] using house demo pass (z.ai), model=${demoModel}, fast=${demoFastModel}`);
309
- return;
309
+ return 'zai';
310
310
  }
311
311
  // Tier 4: central OpenRouter key (pay-per-use fallback of the fallback).
312
312
  const openRouterKey = cleanEnvKey(process.env.OPENROUTER_API_KEY);
@@ -337,10 +337,17 @@ export function applyAuthFallback() {
337
337
  process.env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = '131072';
338
338
  fallbackTierActive = true;
339
339
  console.log(`[auth-fallback] using central OpenRouter tier, model=${FALLBACK_MODEL}`);
340
- return;
340
+ return 'openrouter';
341
+ }
342
+ // A user's own Anthropic-compatible gateway (ANTHROPIC_AUTH_TOKEN + their own
343
+ // ANTHROPIC_BASE_URL) is left untouched above and still answers — label it as
344
+ // their own (anthropic) rather than a dead end.
345
+ if (cleanEnvKey(process.env.ANTHROPIC_AUTH_TOKEN) !== '') {
346
+ return 'anthropic';
341
347
  }
342
348
  // Tier 4 fail: no fallback key at all — do NOT throw.
343
349
  console.warn('[auth-fallback] no Claude login, no ANTHROPIC_API_KEY, no Z_AI key, and no OPENROUTER_API_KEY — agent may be unauthenticated');
350
+ return 'none';
344
351
  }
345
352
  /**
346
353
  * Clear the fallback redirect (z.ai house pass or OpenRouter) — but ONLY if
@@ -34,7 +34,7 @@ export interface ClientRedactor {
34
34
  export interface RedactorOptions {
35
35
  /**
36
36
  * PER-PIECE opt-in un-redaction: denylisted terms to leave visible for ONE
37
- * named draft/render (e.g. reveal: ["Audos"]). Never used by extraction —
37
+ * named draft/render (e.g. reveal: ["Acme"]). Never used by extraction —
38
38
  * the profile and samples are always stored fully redacted. A renderer that
39
39
  * reveals re-pulls the quote rows from session.db by row # and redacts them
40
40
  * with this option, in memory, for that piece only.
package/dist/index.js CHANGED
@@ -41,8 +41,9 @@ import { createSTT, createTTS } from './voice-io.js';
41
41
  import { createClaudeLLM, NAMED_AGENTS, applyTurbo, requestAuthRestart } from './claude-llm.js';
42
42
  import { clearPipelineFastBrainSession, prewarmBM25Index } from './pipeline-fastbrain.js';
43
43
  import { ensureClaudeAuth, applyAuthFallback, replayInFlightAuth, startClaudeAuthOnDemand, isOnDemandAuthInFlight } from './claude-auth.js';
44
+ import { probeActiveProviderKey } from './key-health.js';
44
45
  import { statusManager } from './status-manager.js';
45
- import { decideNextSession, planSwitch, resolveSessionCwd, keepNonConversationItems, recoverySessionId as pickRecoverySessionId, warmParkKey, sessionMessagesDir, createSwitchGuard, scanSlugCwd } from './session-switch.js';
46
+ import { decideNextSession, planSwitch, resolveSessionCwd, keepNonConversationItems, recoverySessionId as pickRecoverySessionId, warmParkKey, sessionMessagesDir, createSwitchGuard, scanSlugCwd, pickConnectWorkingDir } from './session-switch.js';
46
47
  import { createSmitheryProxy, destroySmitheryProxy, parseSmitheryUrl, isSmitheryUrl, SmitheryAuthorizationError } from './smithery-proxy.js';
47
48
  import { DIRECT_MODE_PROMPT } from './prompts.js';
48
49
  import { MCP_CATALOG } from './config.js';
@@ -281,6 +282,13 @@ let bugReportHook = null;
281
282
  // closure. The /editor route in startApiServer() calls this to start the IDE
282
283
  // in the background without depending on main()'s closure directly.
283
284
  let codeServerStartHook = null;
285
+ // ── Model-provider health (module scope — shared between startApiServer + main) ──
286
+ // #87: the per-key self-test result for the ACTIVE fallback provider, written by
287
+ // main()'s connect path (probeActiveProviderKey) and read by startApiServer's
288
+ // GET /health so a dead/expired key surfaces as "No working model" instead of a
289
+ // silent non-reply. Null until the async probe lands (or never, on the Claude
290
+ // path / an ambiguous result) — never a fabricated verdict.
291
+ let agentKeyHealth = null;
284
292
  // ── IDE reverse-proxy (module scope — shared between startApiServer + main) ──
285
293
  // code-server runs on 127.0.0.1:8300; the agent proxies it through its own
286
294
  // public HTTP server so no Cloudflare tunnel is needed.
@@ -755,6 +763,10 @@ function startApiServer(workingDir, port) {
755
763
  },
756
764
  // Whole-machine memory — what the OOM killer watches. All values in MB.
757
765
  memory: { totalMb, usedMb, availableMb, usedPct, processRssMb },
766
+ // #87: per-key self-test for the active fallback provider. Absent until
767
+ // the async probe lands (and omitted entirely on the Claude path); the
768
+ // frontend surfaces "No working model" when every entry failed/expired.
769
+ ...(agentKeyHealth ? { keyHealth: agentKeyHealth } : {}),
758
770
  }));
759
771
  return;
760
772
  }
@@ -5095,26 +5107,40 @@ async function main() {
5095
5107
  if (Number.isFinite(c) && c > 0)
5096
5108
  connectTiming.clickTs = c;
5097
5109
  }
5098
- // Read working directory override from frontend.
5110
+ // Working directory for this connection (resume-mismatch fix, #112).
5099
5111
  //
5100
- // If the path doesn't exist yet (new project on first use, or freshly
5101
- // imported sessions on a new sprite), create it with mkdirSync so the
5102
- // agent can accept it. This is safe: recursive mkdirSync is a no-op when
5103
- // the directory already exists, and project paths always live under the
5104
- // workspace root. The Claude SDK child_process.spawn requires the cwd to
5105
- // exist — mkdirSync satisfies that requirement without silently falling back.
5106
- if (metadata.workingDirectory && typeof metadata.workingDirectory === 'string' && metadata.workingDirectory.length > 0) {
5107
- if (!existsSync(metadata.workingDirectory)) {
5108
- mkdirSync(metadata.workingDirectory, { recursive: true });
5109
- console.log(`📁 Created project directory: ${metadata.workingDirectory}`);
5110
- }
5111
- workingDir = metadata.workingDirectory;
5112
- console.log(`📂 Working directory from frontend: ${workingDir}`);
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)
5122
+ ? metadata.workingDirectory
5123
+ : null;
5124
+ let resolvedConnectCwd = null;
5125
+ if (preSelectedSessionId) {
5126
+ try {
5127
+ resolvedConnectCwd = await resolveCwdForSession(preSelectedSessionId, wdHint);
5128
+ }
5129
+ catch (e) {
5130
+ console.warn('⚠️ connect cwd resolve failed:', e instanceof Error ? e.message : e);
5131
+ resolvedConnectCwd = null;
5132
+ }
5113
5133
  }
5114
- else {
5115
- // Reset to default for new connections (in case previous session changed it)
5116
- workingDir = defaultWorkingDir;
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}`);
5117
5141
  }
5142
+ workingDir = connectWd.dir;
5143
+ console.log(`📂 Working directory (${connectWd.source}): ${workingDir}`);
5118
5144
  }
5119
5145
  catch (err) {
5120
5146
  console.log('⚠️ Could not parse participant metadata, using config voiceMode:', voiceMode);
@@ -5155,7 +5181,35 @@ async function main() {
5155
5181
  // BEFORE session creation so the OpenRouter redirect env vars (tier 3) are
5156
5182
  // set before the first query() spawn inherits process.env. No-op for
5157
5183
  // tier-1 (real Claude login) and tier-2 (user's own ANTHROPIC_API_KEY).
5158
- applyAuthFallback();
5184
+ // #87: it also RETURNS the provider it selected (claude / zai / openrouter /
5185
+ // anthropic / none) — the single source of truth, since the tier is known at
5186
+ // decision time. Drives agent_ready.provider so the model badge names the
5187
+ // real model instead of the old hardcoded 'claude'.
5188
+ const activeProvider = applyAuthFallback();
5189
+ console.log(`🧭 Active model provider: ${activeProvider}`);
5190
+ // #87: HOUSE-tier key self-test. Presence of a key ≠ validity (the test
5191
+ // account's z.ai key failed and its OpenRouter key had expired, yet the
5192
+ // session showed "Listening" and never replied — the #70 symptom). Fire ONE
5193
+ // tiny real request, fire-and-forget, AFTER the session starts below, so it
5194
+ // adds ZERO latency to the connect path. Scoped to the house fallback tiers
5195
+ // (zai / openrouter) — a user's OWN Anthropic key is their concern and the
5196
+ // SDK surfaces its failures directly; we never ping it per connect. The
5197
+ // result rides GET /health; a definitive failure surfaces "No working model"
5198
+ // instead of a silent non-reply.
5199
+ agentKeyHealth = null;
5200
+ if (activeProvider === 'zai' || activeProvider === 'openrouter') {
5201
+ void probeActiveProviderKey(activeProvider)
5202
+ .then((entry) => {
5203
+ if (!entry)
5204
+ return;
5205
+ agentKeyHealth = [entry];
5206
+ if (entry.status === 'ok')
5207
+ console.log(`✅ [key-health] ${entry.provider} self-test: ok`);
5208
+ else
5209
+ console.warn(`⚠️ [key-health] ${entry.provider} self-test: ${entry.status}`);
5210
+ })
5211
+ .catch(() => { });
5212
+ }
5159
5213
  // Create session based on voice mode (from frontend or config)
5160
5214
  let session;
5161
5215
  let agent;
@@ -5809,7 +5863,12 @@ async function main() {
5809
5863
  return;
5810
5864
  await sendToFrontend({
5811
5865
  type: 'agent_ready',
5812
- provider: 'claude',
5866
+ // #87: the REAL active provider (claude / zai / openrouter / anthropic),
5867
+ // not a hardcoded 'claude' — so the model badge is honest on a fallback
5868
+ // session. 'none' (no model configured at all) is emitted as null so the
5869
+ // badge stays neutral instead of rendering a literal "none" pill; that
5870
+ // dead-end is surfaced by the Claude sign-in flow, not the badge.
5871
+ provider: activeProvider === 'none' ? null : activeProvider,
5813
5872
  voiceMode: sessionVoiceMode,
5814
5873
  hasRecentSession,
5815
5874
  recentSessionId,
@@ -0,0 +1,56 @@
1
+ /**
2
+ * key-health.ts — a tiny, REAL "can this provider actually answer?" self-test for
3
+ * the no-Claude fallback tiers (issue #87, gap 5).
4
+ *
5
+ * The bug this surfaces: applyAuthFallback() picks a tier because a key is
6
+ * PRESENT, but presence is not validity — the observed test account had a z.ai
7
+ * key that failed and an OpenRouter key that had expired, and nothing said so;
8
+ * the session showed "Listening" and silently never replied (the #70 symptom).
9
+ *
10
+ * This fires ONE minimal /v1/messages request against the ACTIVE provider's
11
+ * endpoint (the exact env applyAuthFallback already set) to confirm the
12
+ * configured key can really answer. The result rides GET /health, so a dead key
13
+ * becomes a visible "No working model" instead of a silent non-reply.
14
+ *
15
+ * Design rules (adversarial review of #87):
16
+ * - NEVER on the Claude path (tier 1) and never on the connect critical path:
17
+ * the caller runs it fire-and-forget AFTER the session starts, fallback-only,
18
+ * so it adds zero boot latency to a normal Claude session.
19
+ * - Conservative classification: only a DEFINITIVE auth/billing failure
20
+ * (401/403/402) becomes a negative verdict. A 4xx that could be an endpoint
21
+ * quirk (400/404), any 5xx, a timeout or a network error yields NO verdict
22
+ * (null) — a transient blip must never fabricate "No working model".
23
+ *
24
+ * Shape mirrors the frontend's KeyHealthEntry (frontend/src/lib/agent-health.ts)
25
+ * so resolveAgentHealth consumes it unchanged.
26
+ */
27
+ /** One fallback key's self-test result. Mirrors the frontend KeyHealthEntry. */
28
+ export interface KeyHealthEntry {
29
+ /** Provider key, e.g. 'zai' | 'openrouter' | 'anthropic'. */
30
+ provider: string;
31
+ /** Outcome of the tiny real request. */
32
+ status: 'ok' | 'failed' | 'expired';
33
+ /** ISO timestamp of the test. */
34
+ checkedAt?: string;
35
+ }
36
+ /**
37
+ * Classify a /v1/messages probe's HTTP status into a key-health verdict, or null
38
+ * when the outcome is ambiguous (no honest verdict — see module header).
39
+ * 2xx → ok (the key answered)
40
+ * 429 → ok (valid key, just rate-limited)
41
+ * 401, 403 → expired (bad / expired credential)
42
+ * 402 → failed (billing / credit depleted)
43
+ * anything else → null (endpoint quirk / 5xx / unknown — no verdict)
44
+ */
45
+ export declare function classifyProbeStatus(httpStatus: number): 'ok' | 'failed' | 'expired' | null;
46
+ /**
47
+ * Fire ONE minimal request against the ACTIVE provider endpoint to confirm the
48
+ * configured key can really answer. Reads the env applyAuthFallback() already
49
+ * set (ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN / ANTHROPIC_API_KEY /
50
+ * ANTHROPIC_MODEL), so it tests exactly what query() will use. All fallback
51
+ * tiers speak native Anthropic Messages, so one request shape covers them.
52
+ *
53
+ * Returns the verdict entry, or null when there was nothing to test or the
54
+ * outcome was ambiguous (never a fabricated failure).
55
+ */
56
+ export declare function probeActiveProviderKey(provider: string, env?: NodeJS.ProcessEnv, timeoutMs?: number): Promise<KeyHealthEntry | null>;
@@ -0,0 +1,93 @@
1
+ /**
2
+ * key-health.ts — a tiny, REAL "can this provider actually answer?" self-test for
3
+ * the no-Claude fallback tiers (issue #87, gap 5).
4
+ *
5
+ * The bug this surfaces: applyAuthFallback() picks a tier because a key is
6
+ * PRESENT, but presence is not validity — the observed test account had a z.ai
7
+ * key that failed and an OpenRouter key that had expired, and nothing said so;
8
+ * the session showed "Listening" and silently never replied (the #70 symptom).
9
+ *
10
+ * This fires ONE minimal /v1/messages request against the ACTIVE provider's
11
+ * endpoint (the exact env applyAuthFallback already set) to confirm the
12
+ * configured key can really answer. The result rides GET /health, so a dead key
13
+ * becomes a visible "No working model" instead of a silent non-reply.
14
+ *
15
+ * Design rules (adversarial review of #87):
16
+ * - NEVER on the Claude path (tier 1) and never on the connect critical path:
17
+ * the caller runs it fire-and-forget AFTER the session starts, fallback-only,
18
+ * so it adds zero boot latency to a normal Claude session.
19
+ * - Conservative classification: only a DEFINITIVE auth/billing failure
20
+ * (401/403/402) becomes a negative verdict. A 4xx that could be an endpoint
21
+ * quirk (400/404), any 5xx, a timeout or a network error yields NO verdict
22
+ * (null) — a transient blip must never fabricate "No working model".
23
+ *
24
+ * Shape mirrors the frontend's KeyHealthEntry (frontend/src/lib/agent-health.ts)
25
+ * so resolveAgentHealth consumes it unchanged.
26
+ */
27
+ import { cleanEnvKey } from './claude-auth.js';
28
+ /**
29
+ * Classify a /v1/messages probe's HTTP status into a key-health verdict, or null
30
+ * when the outcome is ambiguous (no honest verdict — see module header).
31
+ * 2xx → ok (the key answered)
32
+ * 429 → ok (valid key, just rate-limited)
33
+ * 401, 403 → expired (bad / expired credential)
34
+ * 402 → failed (billing / credit depleted)
35
+ * anything else → null (endpoint quirk / 5xx / unknown — no verdict)
36
+ */
37
+ export function classifyProbeStatus(httpStatus) {
38
+ if (httpStatus >= 200 && httpStatus < 300)
39
+ return 'ok';
40
+ if (httpStatus === 429)
41
+ return 'ok';
42
+ if (httpStatus === 401 || httpStatus === 403)
43
+ return 'expired';
44
+ if (httpStatus === 402)
45
+ return 'failed';
46
+ return null;
47
+ }
48
+ /**
49
+ * Fire ONE minimal request against the ACTIVE provider endpoint to confirm the
50
+ * configured key can really answer. Reads the env applyAuthFallback() already
51
+ * set (ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN / ANTHROPIC_API_KEY /
52
+ * ANTHROPIC_MODEL), so it tests exactly what query() will use. All fallback
53
+ * tiers speak native Anthropic Messages, so one request shape covers them.
54
+ *
55
+ * Returns the verdict entry, or null when there was nothing to test or the
56
+ * outcome was ambiguous (never a fabricated failure).
57
+ */
58
+ export async function probeActiveProviderKey(provider, env = process.env, timeoutMs = 8000) {
59
+ const base = (cleanEnvKey(env.ANTHROPIC_BASE_URL) || 'https://api.anthropic.com').replace(/\/$/, '');
60
+ const authToken = cleanEnvKey(env.ANTHROPIC_AUTH_TOKEN);
61
+ const apiKey = cleanEnvKey(env.ANTHROPIC_API_KEY);
62
+ const model = cleanEnvKey(env.ANTHROPIC_MODEL) || 'claude-3-5-haiku-latest';
63
+ // Nothing to test — no credential configured for the active endpoint.
64
+ if (!authToken && !apiKey)
65
+ return null;
66
+ const headers = {
67
+ 'content-type': 'application/json',
68
+ 'anthropic-version': '2023-06-01',
69
+ };
70
+ // Fallback redirects (z.ai / OpenRouter) authenticate with a bearer AUTH_TOKEN;
71
+ // a user's own Anthropic key uses x-api-key. applyAuthFallback sets exactly one.
72
+ if (authToken)
73
+ headers['authorization'] = `Bearer ${authToken}`;
74
+ else
75
+ headers['x-api-key'] = apiKey;
76
+ const body = JSON.stringify({ model, max_tokens: 1, messages: [{ role: 'user', content: 'hi' }] });
77
+ try {
78
+ const r = await fetch(`${base}/v1/messages`, {
79
+ method: 'POST',
80
+ headers,
81
+ body,
82
+ signal: AbortSignal.timeout(timeoutMs),
83
+ });
84
+ const verdict = classifyProbeStatus(r.status);
85
+ if (!verdict)
86
+ return null;
87
+ return { provider, status: verdict, checkedAt: new Date().toISOString() };
88
+ }
89
+ catch {
90
+ // Network error / timeout — ambiguous, never a fabricated verdict.
91
+ return null;
92
+ }
93
+ }
@@ -122,6 +122,38 @@ export declare function warmParkKey(llm: {
122
122
  * otherwise the agent's boot dir (today's behaviour). Never trusts the param.
123
123
  */
124
124
  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
+ };
125
157
  /**
126
158
  * Single-flight guard for performSessionSwitch. Only the critical section
127
159
  * (teardown + arm + session_switched) holds the guard; `after` (the spoken
@@ -127,6 +127,42 @@ export function sessionMessagesDir(sessionId, requested, bootDir, exists) {
127
127
  }
128
128
  return bootDir;
129
129
  }
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
+ }
130
166
  // ── Review minors ────────────────────────────────────────────────────────────
131
167
  /**
132
168
  * Single-flight guard for performSessionSwitch. Only the critical section
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osborn",
3
- "version": "0.9.276",
3
+ "version": "0.9.278",
4
4
  "description": "Voice AI coding assistant - local agent that connects to Osborn frontend",
5
5
  "type": "module",
6
6
  "bin": {