osborn 0.9.275 → 0.9.276

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -42,6 +42,7 @@ import { createClaudeLLM, NAMED_AGENTS, applyTurbo, requestAuthRestart } from '.
42
42
  import { clearPipelineFastBrainSession, prewarmBM25Index } from './pipeline-fastbrain.js';
43
43
  import { ensureClaudeAuth, applyAuthFallback, replayInFlightAuth, startClaudeAuthOnDemand, isOnDemandAuthInFlight } 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 } from './session-switch.js';
45
46
  import { createSmitheryProxy, destroySmitheryProxy, parseSmitheryUrl, isSmitheryUrl, SmitheryAuthorizationError } from './smithery-proxy.js';
46
47
  import { DIRECT_MODE_PROMPT } from './prompts.js';
47
48
  import { MCP_CATALOG } from './config.js';
@@ -49,6 +50,7 @@ import { storeExists, openStore, recentRows } from './session-store.js';
49
50
  import { readCompactionMarkers } from './compaction-log.js';
50
51
  import { sessionListEntry, cleanHistoryRows, userEchoText, TypedEchoTracker, ClientNoteQueue, parseFavoriteChanged, parseLegacyFavoriteNotice } from './transcript-wiring.js';
51
52
  import { getRecallClient } from './recall-client.js';
53
+ import { synthMeetingAudio, selectMeetingTtsProviders } from './meeting-tts.js';
52
54
  import { MeetingTranscriptPoller } from './meeting-transcript-poller.js';
53
55
  import { missingRequiredEnv } from './env-keys.js';
54
56
  import { armPermissionPush, handleWatchAck, setWatchResultHandler } from './pushover.js';
@@ -474,39 +476,12 @@ function interruptMeetingSpeech(reason) {
474
476
  void recall.stopOutputAudio(botId);
475
477
  console.log(`✋ meeting speech interrupted (${reason}) — queue cleared + output_audio stopped`);
476
478
  }
477
- // Synthesize speech as MP3 (Deepgram fast path, OpenAI fallback) — for
478
- // Recall native output_audio, which requires mp3.
479
+ // Synthesize speech as MP3 for Recall native output_audio (which requires mp3).
480
+ // Soniox REST first (same provider as the voice pipeline), OpenAI fallback only
481
+ // if OPENAI_API_KEY is set, else null. See meeting-tts.ts for provider order.
479
482
  async function synthMp3(text) {
480
- const t0 = Date.now();
481
- const oa = process.env.OPENAI_API_KEY;
482
- if (!oa) {
483
- console.warn('⚠️ synthMp3: no OPENAI_API_KEY — meeting has no voice');
484
- return null;
485
- }
486
- // Meeting audio is always OpenAI TTS (HTTP MP3 required for Recall output_audio).
487
- // Reads OSBORN_TTS_* env vars — same source as getDirectConfig — so voice is
488
- // consistent between the pipeline and meeting canvas when TTS provider is openai.
489
- const model = process.env.OSBORN_TTS_PROVIDER === 'openai' ? (process.env.OSBORN_TTS_MODEL || 'tts-1-hd') : 'tts-1-hd';
490
- const voice = process.env.OSBORN_TTS_PROVIDER === 'openai' ? (process.env.OSBORN_TTS_VOICE || 'fable') : 'fable';
491
- try {
492
- const r = await fetch('https://api.openai.com/v1/audio/speech', {
493
- method: 'POST',
494
- headers: { 'Authorization': `Bearer ${oa}`, 'Content-Type': 'application/json' },
495
- body: JSON.stringify({ model, voice, input: text.slice(0, 4000), response_format: 'mp3' }),
496
- signal: AbortSignal.timeout(20000),
497
- });
498
- if (r.ok) {
499
- const buf = Buffer.from(await r.arrayBuffer());
500
- console.log(`🗣️ synthMp3 openai ${model}/${voice} ${buf.length}b in ${Date.now() - t0}ms`);
501
- return buf;
502
- }
503
- const e = await r.text().catch(() => '');
504
- console.warn(`⚠️ synthMp3 openai ${r.status}: ${e.slice(0, 120)}`);
505
- }
506
- catch (e) {
507
- console.warn(`⚠️ synthMp3 openai: ${e.message}`);
508
- }
509
- return null;
483
+ const r = await synthMeetingAudio(text);
484
+ return r ? r.audio : null;
510
485
  }
511
486
  // THE speak path for meetings (2026-08-01): Recall native output_audio FIRST
512
487
  // (direct, loud, no canvas capture chain), canvas Web-Audio say as FALLBACK.
@@ -654,8 +629,11 @@ function startApiServer(workingDir, port) {
654
629
  // Durable compaction markers (sidecar, not the derived store) so a
655
630
  // resumed transcript rebuilds every past "Conversation compacted" row at
656
631
  // its real position — the store rebuild can't wipe these.
657
- const compactions = readCompactionMarkers(sessionId, workingDir);
658
- const dbPath = storeExists(sessionId, workingDir);
632
+ // Sessions outside the boot project (after a switch, or a reload of one)
633
+ // pass their own cwd; honoured only if the session really lives there.
634
+ const readDir = sessionMessagesDir(sessionId, url.searchParams.get('workingDirectory'), workingDir, sessionExists);
635
+ const compactions = readCompactionMarkers(sessionId, readDir);
636
+ const dbPath = storeExists(sessionId, readDir);
659
637
  if (!dbPath) {
660
638
  res.writeHead(200, { 'Content-Type': 'application/json' });
661
639
  res.end(JSON.stringify({ sessionId, messages: [], compactions }));
@@ -989,9 +967,10 @@ function startApiServer(workingDir, port) {
989
967
  return;
990
968
  }
991
969
  // ── Meeting canvas: TTS audio for speaking INTO the meeting ──────────────
992
- // GET /tts?text=... → mp3 (OpenAI TTS). The canvas plays this as a real
993
- // <audio> element so Recall's webpage output pipes it into the meeting —
994
- // speechSynthesis is NOT captured by Recall, a media element IS.
970
+ // GET /tts?text=... → mp3 (Soniox first, OpenAI fallback — meeting-tts.ts).
971
+ // The canvas decodes it with AudioContext.decodeAudioData so Recall's
972
+ // webpage output pipes it into the meeting — speechSynthesis is NOT
973
+ // captured by Recall, page audio IS.
995
974
  if (req.method === 'GET' && url.pathname === '/tts') {
996
975
  const text = (url.searchParams.get('text') || '').slice(0, 4000);
997
976
  if (!text) {
@@ -1000,32 +979,21 @@ function startApiServer(workingDir, port) {
1000
979
  return;
1001
980
  }
1002
981
  const t0 = Date.now();
1003
- // Meeting canvas TTS — always OpenAI HTTP (mp3 for <audio> element).
1004
- // Reads OSBORN_TTS_* env vars so voice stays in sync with pipeline when provider is openai.
1005
- const key = process.env.OPENAI_API_KEY;
1006
- if (!key) {
982
+ if (selectMeetingTtsProviders().length === 0) {
1007
983
  res.writeHead(400, { 'Content-Type': 'application/json' });
1008
- res.end(JSON.stringify({ error: 'no OPENAI_API_KEY' }));
984
+ res.end(JSON.stringify({ error: 'no SONIOX_API_KEY or OPENAI_API_KEY' }));
1009
985
  return;
1010
986
  }
1011
- const model = process.env.OSBORN_TTS_PROVIDER === 'openai' ? (process.env.OSBORN_TTS_MODEL || 'tts-1-hd') : 'tts-1-hd';
1012
- const voice = url.searchParams.get('voice') || (process.env.OSBORN_TTS_PROVIDER === 'openai' ? (process.env.OSBORN_TTS_VOICE || 'fable') : 'fable');
1013
987
  try {
1014
- const tts = await fetch('https://api.openai.com/v1/audio/speech', {
1015
- method: 'POST',
1016
- headers: { 'Authorization': `Bearer ${key}`, 'Content-Type': 'application/json' },
1017
- body: JSON.stringify({ model, voice, input: text, response_format: 'mp3' }),
1018
- });
1019
- if (!tts.ok) {
1020
- const e = await tts.text().catch(() => '');
988
+ const out = await synthMeetingAudio(text, { voice: url.searchParams.get('voice') || undefined });
989
+ if (!out) {
1021
990
  res.writeHead(502, { 'Content-Type': 'application/json' });
1022
- res.end(JSON.stringify({ error: `tts ${tts.status}`, detail: e.slice(0, 200) }));
991
+ res.end(JSON.stringify({ error: 'tts failed (all providers)' }));
1023
992
  return;
1024
993
  }
1025
- const buf = Buffer.from(await tts.arrayBuffer());
1026
- console.log(`🗣️ /tts openai ${model}/${voice} ${buf.length}b in ${Date.now() - t0}ms t=${new Date().toISOString()}`);
1027
- res.writeHead(200, { 'Content-Type': 'audio/mpeg', 'Cache-Control': 'no-store', 'Content-Length': buf.length });
1028
- res.end(buf);
994
+ console.log(`🗣️ /tts ${out.provider} ${out.audio.length}b in ${Date.now() - t0}ms t=${new Date().toISOString()}`);
995
+ res.writeHead(200, { 'Content-Type': out.contentType, 'Cache-Control': 'no-store', 'Content-Length': out.audio.length });
996
+ res.end(out.audio);
1029
997
  }
1030
998
  catch (e) {
1031
999
  res.writeHead(500, { 'Content-Type': 'application/json' });
@@ -2484,7 +2452,9 @@ async function main() {
2484
2452
  const parkWarm = (reason) => {
2485
2453
  if (!currentLLM)
2486
2454
  return;
2487
- const sid = currentLLM.sessionId;
2455
+ // Key by the init id, else the id the live query was spawned for (a primed /
2456
+ // just-switched session has no init id yet — killing it lost the warm brain).
2457
+ const sid = warmParkKey(currentLLM) || undefined;
2488
2458
  if (!sid) {
2489
2459
  console.log(`🔥 [KEEP-WARM] no sessionId to key re-attach — aborting instead (${reason})`);
2490
2460
  killCurrentLLM(reason + '_no_sessionid');
@@ -2970,6 +2940,7 @@ async function main() {
2970
2940
  if (!botId)
2971
2941
  return;
2972
2942
  console.log(`🏁 Meeting ended (${reason}) — bot ${botId}`);
2943
+ cancelPendingSwitch('meeting_ended');
2973
2944
  // Stop inputs FIRST so no more chunks land mid-teardown.
2974
2945
  stopMeetingFlush();
2975
2946
  if (activeMeetingPoller) {
@@ -3716,6 +3687,311 @@ async function main() {
3716
3687
  }
3717
3688
  function startProactiveLoop(_task, _sessionId) { }
3718
3689
  function stopProactiveLoop() { }
3690
+ // ============================================================
3691
+ // SESSION SWITCH EXECUTOR (#74)
3692
+ // One path for every in-place switch (switch_session, and resume_session /
3693
+ // continue_session / session_selected while a query is live). Decision +
3694
+ // plan are pure (session-switch.ts). Interim: FINISH-THEN-SWITCH — a busy
3695
+ // session is never closed unless the user forces it ("Switch now"); the
3696
+ // switch is deferred until it goes idle. demoteSupported:false until the
3697
+ // background-on-leave (swap) work ships.
3698
+ // ============================================================
3699
+ let pendingSwitch = null;
3700
+ const switchGuard = createSwitchGuard();
3701
+ // Set by the agent_ready retry loop; a switch must stop it so a late
3702
+ // agent_ready (preSelectedSessionId = A) doesn't reset the UI back to A.
3703
+ let stopReadyRetries = null;
3704
+ function resolveCwdForSession(sessionId, hint) {
3705
+ return resolveSessionCwd(sessionId, hint, workingDir, {
3706
+ 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) }),
3709
+ });
3710
+ }
3711
+ function findSlotKey(sessionId) {
3712
+ if (slots.has(sessionId))
3713
+ return sessionId;
3714
+ return [...slots.keys()].find(k => k.startsWith(sessionId) || sessionId.startsWith(k));
3715
+ }
3716
+ function targetSlotState(sessionId) {
3717
+ const key = findSlotKey(sessionId);
3718
+ if (!key)
3719
+ return 'none';
3720
+ const slot = slots.get(key);
3721
+ if (slot.dispatchInFlight || !slot.kickoffDone)
3722
+ return 'busy';
3723
+ const b = slot.llm.busyState?.();
3724
+ return b && !b.idle ? 'busy' : 'idle';
3725
+ }
3726
+ function cancelPendingSwitch(reason, notify = true) {
3727
+ if (!pendingSwitch)
3728
+ return;
3729
+ const { target, timer } = pendingSwitch;
3730
+ clearInterval(timer);
3731
+ pendingSwitch = null;
3732
+ console.log(`↩️ Pending switch to ${target.slice(0, 8)} cancelled (${reason})`);
3733
+ if (notify)
3734
+ void sendToFrontend({ type: 'session_switch_cancelled', sessionId: target, reason });
3735
+ }
3736
+ const SWITCH_REJECT_COPY = {
3737
+ meeting_active: 'Leave the meeting first — the meeting is attached to this session.',
3738
+ target_busy_in_background: 'That session is busy in the background. Wait for it to finish or stop it first.',
3739
+ needs_you: 'This session is waiting on your answer to a permission prompt. Answer it, or choose Switch now.',
3740
+ not_found: 'Session not found',
3741
+ };
3742
+ /**
3743
+ * Legacy entry points (resume_session / continue_session / session_selected)
3744
+ * only ARMED a resume id. With a live query that runs a different session,
3745
+ * that armed id was ignored and the next turn ran in the old session
3746
+ * (session_resume_failed {requested:B, actual:A}). True → route through the
3747
+ * executor. False → keep the legacy arm-only path: no live query yet, or the
3748
+ * live/primed query already runs this session (decider 'push').
3749
+ */
3750
+ function liveSwitchNeeded(target) {
3751
+ if (!currentLLM || !target)
3752
+ return false;
3753
+ const llmAny = currentLLM;
3754
+ if (!llmAny.hasSession?.())
3755
+ return false;
3756
+ const busy = llmAny.busyState?.() ?? { idle: true };
3757
+ return decideNextSession({
3758
+ liveSessionId: currentLLM.sessionId ?? null,
3759
+ queryResumeTarget: llmAny.spawnedResumeId ?? null,
3760
+ resumeTarget: currentResumeSessionId ?? null,
3761
+ requestedTarget: target,
3762
+ hasLiveQuery: true,
3763
+ turnInFlight: !busy.idle,
3764
+ }).action === 'switch';
3765
+ }
3766
+ async function requestSessionSwitch(target, cwdHint, opts) {
3767
+ if (!currentLLM || !target)
3768
+ return 'reject';
3769
+ const cwd = await resolveCwdForSession(target, cwdHint);
3770
+ if (!cwd) {
3771
+ await sendToFrontend({ type: 'session_switched', sessionId: target, success: false, error: SWITCH_REJECT_COPY.not_found, reason: 'not_found' });
3772
+ return 'reject';
3773
+ }
3774
+ const llmAny = currentLLM;
3775
+ const busy = llmAny.busyState?.() ?? { idle: true, permissionPending: false, runningTasks: 0, turnInFlight: false };
3776
+ const decision = decideNextSession({
3777
+ liveSessionId: currentLLM.sessionId ?? null,
3778
+ queryResumeTarget: llmAny.spawnedResumeId ?? null,
3779
+ resumeTarget: currentResumeSessionId ?? null,
3780
+ requestedTarget: target,
3781
+ hasLiveQuery: !!llmAny.hasSession?.(),
3782
+ turnInFlight: !busy.idle,
3783
+ });
3784
+ const plan = planSwitch(decision, {
3785
+ permissionPending: !!busy.permissionPending,
3786
+ meetingActive: !!activeMeetingBotId,
3787
+ targetSlot: targetSlotState(target),
3788
+ force: !!opts.force,
3789
+ demoteSupported: false,
3790
+ });
3791
+ console.log(`🔀 Switch request (${opts.origin}) → ${target.slice(0, 8)}: ${decision.action}/${decision.leave} → ${plan.kind} (${plan.reason}) busy=${JSON.stringify(busy)}`);
3792
+ if (plan.kind === 'noop') {
3793
+ if (pendingSwitch)
3794
+ cancelPendingSwitch('already_live');
3795
+ else
3796
+ await sendToFrontend({ type: 'session_switch_cancelled', sessionId: target, reason: 'already_live' });
3797
+ return 'noop';
3798
+ }
3799
+ if (plan.kind === 'reject') {
3800
+ await sendToFrontend({
3801
+ type: 'session_switched', sessionId: target, success: false, reason: plan.reason,
3802
+ error: SWITCH_REJECT_COPY[plan.reason] || 'Could not switch sessions',
3803
+ });
3804
+ return 'reject';
3805
+ }
3806
+ if (plan.kind === 'defer') {
3807
+ // Single pending switch: a newer request replaces the older one.
3808
+ if (pendingSwitch) {
3809
+ clearInterval(pendingSwitch.timer);
3810
+ pendingSwitch = null;
3811
+ }
3812
+ const since = Date.now();
3813
+ let lastLog = since;
3814
+ const timer = setInterval(() => {
3815
+ if (!pendingSwitch || pendingSwitch.timer !== timer) {
3816
+ clearInterval(timer);
3817
+ return;
3818
+ }
3819
+ if (!currentLLM) {
3820
+ cancelPendingSwitch('session_gone');
3821
+ return;
3822
+ }
3823
+ const b = currentLLM.busyState?.();
3824
+ const idle = !b || b.idle || !currentLLM.hasSession?.();
3825
+ if (!idle) {
3826
+ if (Date.now() - lastLog > 10_000) {
3827
+ lastLog = Date.now();
3828
+ console.log(`⏳ Switch to ${target.slice(0, 8)} waiting for idle (${Math.round((Date.now() - since) / 1000)}s): ${JSON.stringify(b)}`);
3829
+ }
3830
+ return;
3831
+ }
3832
+ const p = pendingSwitch;
3833
+ clearInterval(timer);
3834
+ pendingSwitch = null;
3835
+ void requestSessionSwitch(p.target, p.cwd, { origin: `deferred:${p.origin}` }).catch((err) => {
3836
+ console.error(`❌ Deferred switch to ${p.target.slice(0, 8)} failed:`, err instanceof Error ? err.message : err);
3837
+ void sendToFrontend({ type: 'session_switched', sessionId: p.target, success: false, reason: 'switch_failed', error: 'Could not switch sessions' });
3838
+ });
3839
+ }, 500);
3840
+ pendingSwitch = { target, cwd, origin: opts.origin, since, timer };
3841
+ await sendToFrontend({
3842
+ type: 'session_switch_pending', sessionId: target, workingDirectory: cwd, reason: plan.reason,
3843
+ runningTasks: busy.runningTasks ?? 0, turnInFlight: !!busy.turnInFlight,
3844
+ });
3845
+ return 'defer';
3846
+ }
3847
+ await performSessionSwitch(target, cwd, plan, opts.origin);
3848
+ return 'execute';
3849
+ }
3850
+ async function performSessionSwitch(target, cwd, plan, origin) {
3851
+ if (!currentLLM)
3852
+ return;
3853
+ // Single-flight: only the teardown/arm/notify section holds the guard; the
3854
+ // spoken acknowledgment runs after it is released (a say() that never
3855
+ // resolves must not wedge every later switch).
3856
+ const outcome = await switchGuard.run(async () => {
3857
+ if (pendingSwitch) {
3858
+ clearInterval(pendingSwitch.timer);
3859
+ pendingSwitch = null;
3860
+ }
3861
+ const llmAny = currentLLM;
3862
+ // 1. Target runs as an idle background slot → stop it (one process per JSONL).
3863
+ if (plan.stopSlotFirst) {
3864
+ const key = findSlotKey(target);
3865
+ if (key) {
3866
+ const slot = slots.get(key);
3867
+ try {
3868
+ slot.llm.abortQuery?.();
3869
+ slot.llm.abortAgent?.();
3870
+ }
3871
+ catch { }
3872
+ slots.delete(key);
3873
+ console.log(`🗑️ Stopped idle background slot ${key.slice(0, 8)} before switching to it`);
3874
+ await sendToFrontend({ type: 'background_session_stopped', slotId: key });
3875
+ }
3876
+ }
3877
+ // 2. Voice-side state of the session being left.
3878
+ try {
3879
+ currentSession?.interrupt();
3880
+ }
3881
+ catch { }
3882
+ voiceQueue.length = 0;
3883
+ isProcessingQueue = false;
3884
+ currentSpeechHandle = null;
3885
+ activeSpeechHandles.clear();
3886
+ lastInterruption = null;
3887
+ if (researchBatchTimer) {
3888
+ clearTimeout(researchBatchTimer);
3889
+ researchBatchTimer = null;
3890
+ }
3891
+ stopProactiveLoop();
3892
+ if (activeResearch) {
3893
+ try {
3894
+ activeResearch.abortController.abort();
3895
+ activeResearch.cleanup();
3896
+ }
3897
+ catch { }
3898
+ activeResearch = null;
3899
+ }
3900
+ lastCompletedResearch = null;
3901
+ // 3. Sub-agent rows of the closed session can't finish any more.
3902
+ for (const d of statusManager.getActiveDispatches()) {
3903
+ statusManager.upsertDispatch(d.id, { dispatchState: 'failed' });
3904
+ }
3905
+ // 4. Close the old query (idle, or forced) and clear its resume state.
3906
+ currentLLM.resetForSessionSwitch();
3907
+ // 5. Cross-project: the SDK cwd, fast brain and session tail move together.
3908
+ if (cwd !== workingDir) {
3909
+ if (!existsSync(cwd))
3910
+ mkdirSync(cwd, { recursive: true });
3911
+ workingDir = cwd;
3912
+ llmAny.setWorkingDirectory?.(cwd);
3913
+ console.log(`📂 Switch moved working directory to ${cwd}`);
3914
+ }
3915
+ // 6. Arm the target — the next turn cold-starts with resume: target.
3916
+ currentLLM.setResumeSessionId(target);
3917
+ currentResumeSessionId = target;
3918
+ if (hostActive) {
3919
+ hostSessionId = target;
3920
+ hostWorkingDir = cwd;
3921
+ }
3922
+ // 7. Per-session permission grants don't carry over.
3923
+ sessionAlwaysAllowPaths = new Set();
3924
+ // 8. Workspace + caches.
3925
+ ensureSessionWorkspace(cwd, target);
3926
+ invalidateSessionListCache();
3927
+ clearPipelineFastBrainSession();
3928
+ // 9. Drop the old session's voice turns from the agent context.
3929
+ if (currentAgent) {
3930
+ try {
3931
+ const c = currentAgent.chatCtx.copy();
3932
+ c.items = keepNonConversationItems(c.items);
3933
+ await currentAgent.updateChatCtx(c);
3934
+ }
3935
+ catch (err) {
3936
+ console.warn('⚠️ Switch: chatCtx rebuild failed:', err instanceof Error ? err.message : err);
3937
+ }
3938
+ }
3939
+ // 10. A late agent_ready (preSelectedSessionId = old) must not reset the UI.
3940
+ stopReadyRetries?.();
3941
+ console.log(`🔄 Switched to session ${target.slice(0, 8)} (${origin}, ${plan.reason})`);
3942
+ // 11. Tell the UI; it replaces the transcript with the target's history.
3943
+ const summary = await getSessionSummary(target, cwd);
3944
+ const conversationHistory = await getConversationHistory(target, cwd, 30);
3945
+ await sendToFrontend({
3946
+ type: 'session_switched',
3947
+ sessionId: target,
3948
+ workingDirectory: cwd,
3949
+ success: true,
3950
+ forced: plan.reason === 'forced',
3951
+ summary,
3952
+ conversationHistory,
3953
+ });
3954
+ const switchArtifacts = listWorkspaceArtifacts(cwd, target);
3955
+ if (switchArtifacts.length > 0) {
3956
+ await sendToFrontend({
3957
+ type: 'session_artifacts',
3958
+ sessionId: target,
3959
+ artifacts: switchArtifacts.map(a => ({ filePath: a.filePath, fileName: a.fileName, type: a.type, updatedAt: a.updatedAt })),
3960
+ });
3961
+ }
3962
+ if (plan.stopSlotFirst) {
3963
+ const bg = [...slots.values()].map(s => ({ id: s.id, isFocused: s.isFocused, workingDir: s.workingDir, hasSession: s.llm.hasSession?.() ?? false }));
3964
+ await sendToFrontend({ type: 'slots_list', slots: [{ id: target, isFocused: true, workingDir: cwd, hasSession: false }, ...bg] });
3965
+ }
3966
+ injectSessionIndexIntoChatCtx(currentAgent, target, cwd);
3967
+ // 12. Overlap the target's JSONL replay with the user's next utterance.
3968
+ if (CONNECT_OVERLAP) {
3969
+ try {
3970
+ llmAny.prewarmResume?.();
3971
+ }
3972
+ catch { }
3973
+ }
3974
+ if (!summary)
3975
+ return null;
3976
+ return summary.lastMessages.length > 0
3977
+ ? `I've switched to your previous session. You were working on: ${summary.lastMessages[summary.lastMessages.length - 1]?.substring(0, 100)}`
3978
+ : `Switched to previous session with ${summary.messageCount} messages. What would you like to continue with?`;
3979
+ }, (acknowledgment) => {
3980
+ // Fire-and-forget, outside the guard.
3981
+ if (!acknowledgment || !currentSession)
3982
+ return;
3983
+ return Promise.resolve()
3984
+ .then(() => currentSession?.say(acknowledgment))
3985
+ .catch((err) => console.log('⚠️ Switch acknowledgment failed:', err));
3986
+ });
3987
+ if (!outcome.ran) {
3988
+ console.warn(`⚠️ Switch to ${target.slice(0, 8)} dropped — another switch is executing`);
3989
+ await sendToFrontend({
3990
+ type: 'session_switched', sessionId: target, success: false, reason: 'switch_in_progress',
3991
+ error: 'Another session switch is still in progress — try again in a moment.',
3992
+ });
3993
+ }
3994
+ }
3719
3995
  // Helper to send data to frontend (with size limit handling)
3720
3996
  //
3721
3997
  // WebRTC SCTP data channel max message size is ~256KB. Sending larger
@@ -3970,6 +4246,24 @@ async function main() {
3970
4246
  prewarmBM25Index(sessionId, workingDir).catch(() => { });
3971
4247
  }
3972
4248
  });
4249
+ // #71: tell the frontend which session is actually live as soon as the SDK
4250
+ // reports it (a brand-new session included), so /chat can pin ?session= and
4251
+ // a reload resumes it instead of starting fresh. Fires once per fresh
4252
+ // session id (ClaudeLLM emits session_id only when it had none).
4253
+ directLLM.events.on('session_id', ({ sessionId }) => {
4254
+ if (!sessionId)
4255
+ return;
4256
+ // A fresh session becomes the "switched-to" id so recovery / reconnect
4257
+ // resume it (D7).
4258
+ if (!currentResumeSessionId)
4259
+ currentResumeSessionId = sessionId;
4260
+ sendToFrontend({
4261
+ type: 'current_session',
4262
+ sessionId,
4263
+ workingDirectory: workingDir,
4264
+ isResumingSession: currentLLM?.isResumingSession ?? false,
4265
+ });
4266
+ });
3973
4267
  // Also pre-warm for resumed sessions (sessionId already known)
3974
4268
  if (resumeSessionId && currentVoiceMode === 'pipeline') {
3975
4269
  prewarmBM25Index(resumeSessionId, workingDir).catch(() => { });
@@ -5390,7 +5684,8 @@ async function main() {
5390
5684
  }
5391
5685
  try {
5392
5686
  // Reuse existing session ID so Claude SDK resumes where it left off
5393
- const recoverySessionId = currentLLM?.sessionId || resumeSessionId;
5687
+ // D7: after a switch, B may have no live id yet — resume B, not the connect-time A.
5688
+ const recoverySessionId = pickRecoverySessionId({ liveSessionId: currentLLM?.sessionId, switchedTo: currentResumeSessionId, connectTime: resumeSessionId });
5394
5689
  let result;
5395
5690
  {
5396
5691
  // Pipeline mode: recreate PipelineDirectLLM wrapper with fast brain
@@ -5531,6 +5826,7 @@ async function main() {
5531
5826
  });
5532
5827
  };
5533
5828
  const readyInterval = setInterval(sendReady, 2000);
5829
+ stopReadyRetries = () => { readySent = true; clearInterval(readyInterval); };
5534
5830
  // Fire immediately with the fast-scanned recent session (sessionsLoaded still false)
5535
5831
  await sendReady();
5536
5832
  setTimeout(() => {
@@ -5683,6 +5979,7 @@ async function main() {
5683
5979
  console.log(`👋 User left: ${participant.identity}`);
5684
5980
  if (participant.identity === controllingUserIdentity)
5685
5981
  controllingUserIdentity = null;
5982
+ cancelPendingSwitch('participant_disconnected', false);
5686
5983
  // Full cleanup — stop all background work to avoid accumulating API usage
5687
5984
  voiceQueue.length = 0;
5688
5985
  isProcessingQueue = false;
@@ -5889,6 +6186,9 @@ async function main() {
5889
6186
  // The session echoes this item as user_transcript; carry the frontend's
5890
6187
  // clientMsgId (bubble dedupe) and the attachment blocks onto that echo.
5891
6188
  typedEchoes.register(fullContent, data.clientMsgId, fullContent.slice(String(data.content || '').length));
6189
+ // A typed turn means the UI is live — stop agent_ready retries (they
6190
+ // reset UI state every 2s and, after a switch, name the old session).
6191
+ stopReadyRetries?.();
5892
6192
  // Skip interrupt for Gemini — disrupts state machine (hangs in speaking state)
5893
6193
  if (true) { // always non-gemini in pipeline mode
5894
6194
  currentSession.interrupt();
@@ -5929,7 +6229,11 @@ async function main() {
5929
6229
  // Context injection (generateReply) happens in session_selected handler
5930
6230
  // to avoid double generateReply calls that cause timeouts
5931
6231
  const sessionId = data.sessionId;
5932
- if (sessionId && sessionExists(sessionId, workingDir)) {
6232
+ if (sessionId && liveSwitchNeeded(sessionId)) {
6233
+ // A live query runs another session: switch for real (#74).
6234
+ await requestSessionSwitch(sessionId, typeof data.workingDirectory === 'string' ? data.workingDirectory : undefined, { force: !!data.force, origin: 'resume_session' });
6235
+ }
6236
+ else if (sessionId && sessionExists(sessionId, workingDir)) {
5933
6237
  currentLLM.setResumeSessionId(sessionId);
5934
6238
  currentResumeSessionId = sessionId;
5935
6239
  console.log(`🔄 Will resume session: ${sessionId}`);
@@ -6012,7 +6316,10 @@ async function main() {
6012
6316
  }
6013
6317
  else if (data.type === 'continue_session' && currentLLM) {
6014
6318
  const recentId = await getMostRecentSessionId(workingDir);
6015
- if (recentId) {
6319
+ if (recentId && liveSwitchNeeded(recentId)) {
6320
+ await requestSessionSwitch(recentId, workingDir, { origin: 'continue_session' });
6321
+ }
6322
+ else if (recentId) {
6016
6323
  currentLLM.setResumeSessionId(recentId);
6017
6324
  currentResumeSessionId = recentId;
6018
6325
  console.log(`🔄 Continuing most recent session: ${recentId}`);
@@ -6058,64 +6365,21 @@ async function main() {
6058
6365
  }
6059
6366
  }
6060
6367
  else if (data.type === 'switch_session' && currentLLM) {
6061
- // Switch to a different session mid-conversation
6368
+ // Switch to a different session mid-conversation (#74). Single executor:
6369
+ // resolves the target's project dir, runs it now when idle, defers it
6370
+ // until the current turn finishes when busy (unless force), rejects in a
6371
+ // meeting / when the target is busy in the background / on a pending
6372
+ // permission. Replies: session_switched | session_switch_pending |
6373
+ // session_switch_cancelled.
6062
6374
  const sessionId = data.sessionId;
6063
- if (sessionId && sessionExists(sessionId, workingDir)) {
6064
- // Step 1: Get FULL context summary with conversation history
6065
- const summary = await getSessionSummary(sessionId, workingDir);
6066
- const conversationHistory = await getConversationHistory(sessionId, workingDir, 30);
6067
- // Step 2: Reset LLM state and configure for new session
6068
- currentLLM.resetForSessionSwitch();
6069
- currentLLM.setResumeSessionId(sessionId);
6070
- currentResumeSessionId = sessionId;
6071
- clearPipelineFastBrainSession();
6072
- clearPipelineFastBrainSession();
6073
- console.log(`🔄 Switched to session: ${sessionId}`);
6074
- // Step 3: Send full context to frontend (including conversation history)
6075
- await sendToFrontend({
6076
- type: 'session_switched',
6077
- sessionId,
6078
- success: true,
6079
- summary,
6080
- conversationHistory,
6081
- });
6082
- // Step 3.5: Send existing session artifacts to frontend (session-scoped)
6083
- const switchArtifacts = listWorkspaceArtifacts(workingDir, sessionId);
6084
- if (switchArtifacts.length > 0) {
6085
- console.log(`📁 Sending ${switchArtifacts.length} session artifacts to frontend`);
6086
- await sendToFrontend({
6087
- type: 'session_artifacts',
6088
- sessionId,
6089
- artifacts: switchArtifacts.map(a => ({
6090
- filePath: a.filePath,
6091
- fileName: a.fileName,
6092
- type: a.type,
6093
- updatedAt: a.updatedAt,
6094
- }))
6095
- });
6096
- }
6097
- // Step 4: Voice agent acknowledges context — greet first, point to index after
6098
- if (currentSession && summary) {
6099
- try {
6100
- const acknowledgment = summary.lastMessages.length > 0
6101
- ? `I've switched to your previous session. You were working on: ${summary.lastMessages[summary.lastMessages.length - 1]?.substring(0, 100)}`
6102
- : `Switched to previous session with ${summary.messageCount} messages. What would you like to continue with?`;
6103
- await currentSession.say(acknowledgment);
6104
- }
6105
- catch (err) {
6106
- console.log('⚠️ Switch acknowledgment failed:', err);
6107
- }
6108
- injectSessionIndexIntoChatCtx(currentAgent, sessionId, workingDir);
6109
- }
6110
- }
6111
- else {
6112
- await sendToFrontend({
6113
- type: 'session_switched',
6114
- sessionId,
6115
- success: false,
6116
- error: 'Session not found',
6117
- });
6118
- }
6375
+ const hint = typeof data.workingDirectory === 'string' ? data.workingDirectory : undefined;
6376
+ await requestSessionSwitch(sessionId, hint, { force: !!data.force, origin: 'switch_session' });
6377
+ }
6378
+ else if (data.type === 'cancel_session_switch') {
6379
+ if (pendingSwitch)
6380
+ cancelPendingSwitch('user_cancelled');
6381
+ else
6382
+ await sendToFrontend({ type: 'session_switch_cancelled', sessionId: data.sessionId || null, reason: 'nothing_pending' });
6119
6383
  }
6120
6384
  else if (data.type === 'get_current_session' && currentLLM) {
6121
6385
  // Get current session ID
@@ -6712,7 +6976,10 @@ async function main() {
6712
6976
  else if (data.type === 'session_selected') {
6713
6977
  const sessionId = data.sessionId;
6714
6978
  console.log(`🚪 Session gate completed: ${sessionId ? `resume ${sessionId}` : 'fresh start'}`);
6715
- if (sessionId && currentLLM && sessionExists(sessionId, workingDir)) {
6979
+ if (sessionId && currentLLM && liveSwitchNeeded(sessionId)) {
6980
+ await requestSessionSwitch(sessionId, typeof data.workingDirectory === 'string' ? data.workingDirectory : undefined, { force: !!data.force, origin: 'session_selected' });
6981
+ }
6982
+ else if (sessionId && currentLLM && sessionExists(sessionId, workingDir)) {
6716
6983
  // Resume the selected session
6717
6984
  currentLLM.setResumeSessionId(sessionId);
6718
6985
  currentResumeSessionId = sessionId;
@@ -7096,6 +7363,7 @@ async function main() {
7096
7363
  const destroyRoomSession = async (reason) => {
7097
7364
  if (destroyingRoomSession)
7098
7365
  return;
7366
+ cancelPendingSwitch('room_destroyed', false);
7099
7367
  if (!activeRoom) {
7100
7368
  // Already idle — still ensure billing backstop is armed.
7101
7369
  livekitState.status = 'idle';