osborn 0.9.274 → 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/.claude/skills/meetings/SKILL.md +1 -1
- package/dist/claude-auth.d.ts +93 -6
- package/dist/claude-auth.js +241 -27
- package/dist/claude-llm.d.ts +31 -1
- package/dist/claude-llm.js +147 -10
- package/dist/data-sender-auth.d.ts +1 -0
- package/dist/data-sender-auth.js +4 -0
- package/dist/duck.d.ts +8 -0
- package/dist/duck.js +59 -0
- package/dist/index.js +468 -123
- package/dist/lib/safe-artifact-path.d.ts +17 -0
- package/dist/lib/safe-artifact-path.js +129 -0
- package/dist/meeting-tts.d.ts +35 -0
- package/dist/meeting-tts.js +161 -0
- package/dist/pipeline-direct-llm.d.ts +36 -1
- package/dist/pipeline-direct-llm.js +110 -24
- package/dist/pipeline-fastbrain.d.ts +14 -0
- package/dist/pipeline-fastbrain.js +5 -3
- package/dist/prompts/direct-mode-research.md +2 -0
- package/dist/prompts.d.ts +1 -1
- package/dist/prompts.js +3 -0
- package/dist/session-switch.d.ts +151 -0
- package/dist/session-switch.js +188 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -35,12 +35,14 @@ const __filename = fileURLToPath(import.meta.url);
|
|
|
35
35
|
const __dirname = dirname(__filename);
|
|
36
36
|
import { createPatch } from 'diff';
|
|
37
37
|
import { loadConfig, getMcpServers, getEnabledMcpServerNames, getVoiceMode, getDirectConfig, listSessions, listAllClaudeSessions, invalidateSessionListCache, getMostRecentSessionId, sessionExists, getSessionSummary, getConversationHistory, ensureSessionWorkspace, getMcpServerStatusList, buildMcpServersForKeys, listWorkspaceArtifacts } from './config.js';
|
|
38
|
+
import { isSafeArtifactPath } from './lib/safe-artifact-path.js';
|
|
38
39
|
import { cleanupHousekeeping } from './housekeeping.js';
|
|
39
40
|
import { createSTT, createTTS } from './voice-io.js';
|
|
40
|
-
import { createClaudeLLM, NAMED_AGENTS, applyTurbo } from './claude-llm.js';
|
|
41
|
+
import { createClaudeLLM, NAMED_AGENTS, applyTurbo, requestAuthRestart } from './claude-llm.js';
|
|
41
42
|
import { clearPipelineFastBrainSession, prewarmBM25Index } from './pipeline-fastbrain.js';
|
|
42
|
-
import { ensureClaudeAuth, applyAuthFallback, replayInFlightAuth } from './claude-auth.js';
|
|
43
|
+
import { ensureClaudeAuth, applyAuthFallback, replayInFlightAuth, startClaudeAuthOnDemand, isOnDemandAuthInFlight } from './claude-auth.js';
|
|
43
44
|
import { statusManager } from './status-manager.js';
|
|
45
|
+
import { decideNextSession, planSwitch, resolveSessionCwd, keepNonConversationItems, recoverySessionId as pickRecoverySessionId, warmParkKey, sessionMessagesDir, createSwitchGuard, scanSlugCwd } from './session-switch.js';
|
|
44
46
|
import { createSmitheryProxy, destroySmitheryProxy, parseSmitheryUrl, isSmitheryUrl, SmitheryAuthorizationError } from './smithery-proxy.js';
|
|
45
47
|
import { DIRECT_MODE_PROMPT } from './prompts.js';
|
|
46
48
|
import { MCP_CATALOG } from './config.js';
|
|
@@ -48,11 +50,13 @@ import { storeExists, openStore, recentRows } from './session-store.js';
|
|
|
48
50
|
import { readCompactionMarkers } from './compaction-log.js';
|
|
49
51
|
import { sessionListEntry, cleanHistoryRows, userEchoText, TypedEchoTracker, ClientNoteQueue, parseFavoriteChanged, parseLegacyFavoriteNotice } from './transcript-wiring.js';
|
|
50
52
|
import { getRecallClient } from './recall-client.js';
|
|
53
|
+
import { synthMeetingAudio, selectMeetingTtsProviders } from './meeting-tts.js';
|
|
51
54
|
import { MeetingTranscriptPoller } from './meeting-transcript-poller.js';
|
|
52
55
|
import { missingRequiredEnv } from './env-keys.js';
|
|
53
56
|
import { armPermissionPush, handleWatchAck, setWatchResultHandler } from './pushover.js';
|
|
54
57
|
import { startWatchGateway } from './watch-gateway.js';
|
|
55
58
|
import { noiseGate } from './noise-gate.js';
|
|
59
|
+
import { installDuck, DUCK_LEVEL } from './duck.js';
|
|
56
60
|
import { meetingAddressing, isRoutableTarget } from './meeting-addressing.js';
|
|
57
61
|
import { listSecretStatus, setSecrets, deleteSecret } from './secrets-store.js';
|
|
58
62
|
import { AGENT_SELF_IDENTITY, checkControlSender, resolveJoin, userIdFromMetadata } from './data-sender-auth.js';
|
|
@@ -255,6 +259,9 @@ const livekitState = {
|
|
|
255
259
|
// stopped). The hooks below are populated by main() (which owns `room` and the
|
|
256
260
|
// connect-with-retry loop) so the module-level HTTP server can drive them.
|
|
257
261
|
let intentionalLeave = false;
|
|
262
|
+
// Native barge-in duck on the live session's audio output (see duck.ts)
|
|
263
|
+
let currentDuck = null;
|
|
264
|
+
let duckRestoreTimer = null;
|
|
258
265
|
let connectRoomHook = null;
|
|
259
266
|
// Mints a LISTEN-ONLY LiveKit token for the meeting canvas so it can join the
|
|
260
267
|
// agent's room and play the agent's REAL TTS audio track — bit-identical to
|
|
@@ -469,39 +476,12 @@ function interruptMeetingSpeech(reason) {
|
|
|
469
476
|
void recall.stopOutputAudio(botId);
|
|
470
477
|
console.log(`✋ meeting speech interrupted (${reason}) — queue cleared + output_audio stopped`);
|
|
471
478
|
}
|
|
472
|
-
// Synthesize speech as MP3
|
|
473
|
-
//
|
|
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.
|
|
474
482
|
async function synthMp3(text) {
|
|
475
|
-
const
|
|
476
|
-
|
|
477
|
-
if (!oa) {
|
|
478
|
-
console.warn('⚠️ synthMp3: no OPENAI_API_KEY — meeting has no voice');
|
|
479
|
-
return null;
|
|
480
|
-
}
|
|
481
|
-
// Meeting audio is always OpenAI TTS (HTTP MP3 required for Recall output_audio).
|
|
482
|
-
// Reads OSBORN_TTS_* env vars — same source as getDirectConfig — so voice is
|
|
483
|
-
// consistent between the pipeline and meeting canvas when TTS provider is openai.
|
|
484
|
-
const model = process.env.OSBORN_TTS_PROVIDER === 'openai' ? (process.env.OSBORN_TTS_MODEL || 'tts-1-hd') : 'tts-1-hd';
|
|
485
|
-
const voice = process.env.OSBORN_TTS_PROVIDER === 'openai' ? (process.env.OSBORN_TTS_VOICE || 'fable') : 'fable';
|
|
486
|
-
try {
|
|
487
|
-
const r = await fetch('https://api.openai.com/v1/audio/speech', {
|
|
488
|
-
method: 'POST',
|
|
489
|
-
headers: { 'Authorization': `Bearer ${oa}`, 'Content-Type': 'application/json' },
|
|
490
|
-
body: JSON.stringify({ model, voice, input: text.slice(0, 4000), response_format: 'mp3' }),
|
|
491
|
-
signal: AbortSignal.timeout(20000),
|
|
492
|
-
});
|
|
493
|
-
if (r.ok) {
|
|
494
|
-
const buf = Buffer.from(await r.arrayBuffer());
|
|
495
|
-
console.log(`🗣️ synthMp3 openai ${model}/${voice} ${buf.length}b in ${Date.now() - t0}ms`);
|
|
496
|
-
return buf;
|
|
497
|
-
}
|
|
498
|
-
const e = await r.text().catch(() => '');
|
|
499
|
-
console.warn(`⚠️ synthMp3 openai ${r.status}: ${e.slice(0, 120)}`);
|
|
500
|
-
}
|
|
501
|
-
catch (e) {
|
|
502
|
-
console.warn(`⚠️ synthMp3 openai: ${e.message}`);
|
|
503
|
-
}
|
|
504
|
-
return null;
|
|
483
|
+
const r = await synthMeetingAudio(text);
|
|
484
|
+
return r ? r.audio : null;
|
|
505
485
|
}
|
|
506
486
|
// THE speak path for meetings (2026-08-01): Recall native output_audio FIRST
|
|
507
487
|
// (direct, loud, no canvas capture chain), canvas Web-Audio say as FALLBACK.
|
|
@@ -649,8 +629,11 @@ function startApiServer(workingDir, port) {
|
|
|
649
629
|
// Durable compaction markers (sidecar, not the derived store) so a
|
|
650
630
|
// resumed transcript rebuilds every past "Conversation compacted" row at
|
|
651
631
|
// its real position — the store rebuild can't wipe these.
|
|
652
|
-
|
|
653
|
-
|
|
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);
|
|
654
637
|
if (!dbPath) {
|
|
655
638
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
656
639
|
res.end(JSON.stringify({ sessionId, messages: [], compactions }));
|
|
@@ -984,9 +967,10 @@ function startApiServer(workingDir, port) {
|
|
|
984
967
|
return;
|
|
985
968
|
}
|
|
986
969
|
// ── Meeting canvas: TTS audio for speaking INTO the meeting ──────────────
|
|
987
|
-
// GET /tts?text=... → mp3 (
|
|
988
|
-
//
|
|
989
|
-
//
|
|
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.
|
|
990
974
|
if (req.method === 'GET' && url.pathname === '/tts') {
|
|
991
975
|
const text = (url.searchParams.get('text') || '').slice(0, 4000);
|
|
992
976
|
if (!text) {
|
|
@@ -995,32 +979,21 @@ function startApiServer(workingDir, port) {
|
|
|
995
979
|
return;
|
|
996
980
|
}
|
|
997
981
|
const t0 = Date.now();
|
|
998
|
-
|
|
999
|
-
// Reads OSBORN_TTS_* env vars so voice stays in sync with pipeline when provider is openai.
|
|
1000
|
-
const key = process.env.OPENAI_API_KEY;
|
|
1001
|
-
if (!key) {
|
|
982
|
+
if (selectMeetingTtsProviders().length === 0) {
|
|
1002
983
|
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
1003
|
-
res.end(JSON.stringify({ error: 'no OPENAI_API_KEY' }));
|
|
984
|
+
res.end(JSON.stringify({ error: 'no SONIOX_API_KEY or OPENAI_API_KEY' }));
|
|
1004
985
|
return;
|
|
1005
986
|
}
|
|
1006
|
-
const model = process.env.OSBORN_TTS_PROVIDER === 'openai' ? (process.env.OSBORN_TTS_MODEL || 'tts-1-hd') : 'tts-1-hd';
|
|
1007
|
-
const voice = url.searchParams.get('voice') || (process.env.OSBORN_TTS_PROVIDER === 'openai' ? (process.env.OSBORN_TTS_VOICE || 'fable') : 'fable');
|
|
1008
987
|
try {
|
|
1009
|
-
const
|
|
1010
|
-
|
|
1011
|
-
headers: { 'Authorization': `Bearer ${key}`, 'Content-Type': 'application/json' },
|
|
1012
|
-
body: JSON.stringify({ model, voice, input: text, response_format: 'mp3' }),
|
|
1013
|
-
});
|
|
1014
|
-
if (!tts.ok) {
|
|
1015
|
-
const e = await tts.text().catch(() => '');
|
|
988
|
+
const out = await synthMeetingAudio(text, { voice: url.searchParams.get('voice') || undefined });
|
|
989
|
+
if (!out) {
|
|
1016
990
|
res.writeHead(502, { 'Content-Type': 'application/json' });
|
|
1017
|
-
res.end(JSON.stringify({ error:
|
|
991
|
+
res.end(JSON.stringify({ error: 'tts failed (all providers)' }));
|
|
1018
992
|
return;
|
|
1019
993
|
}
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
res.
|
|
1023
|
-
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);
|
|
1024
997
|
}
|
|
1025
998
|
catch (e) {
|
|
1026
999
|
res.writeHead(500, { 'Content-Type': 'application/json' });
|
|
@@ -2479,7 +2452,9 @@ async function main() {
|
|
|
2479
2452
|
const parkWarm = (reason) => {
|
|
2480
2453
|
if (!currentLLM)
|
|
2481
2454
|
return;
|
|
2482
|
-
|
|
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;
|
|
2483
2458
|
if (!sid) {
|
|
2484
2459
|
console.log(`🔥 [KEEP-WARM] no sessionId to key re-attach — aborting instead (${reason})`);
|
|
2485
2460
|
killCurrentLLM(reason + '_no_sessionid');
|
|
@@ -2965,6 +2940,7 @@ async function main() {
|
|
|
2965
2940
|
if (!botId)
|
|
2966
2941
|
return;
|
|
2967
2942
|
console.log(`🏁 Meeting ended (${reason}) — bot ${botId}`);
|
|
2943
|
+
cancelPendingSwitch('meeting_ended');
|
|
2968
2944
|
// Stop inputs FIRST so no more chunks land mid-teardown.
|
|
2969
2945
|
stopMeetingFlush();
|
|
2970
2946
|
if (activeMeetingPoller) {
|
|
@@ -3711,6 +3687,311 @@ async function main() {
|
|
|
3711
3687
|
}
|
|
3712
3688
|
function startProactiveLoop(_task, _sessionId) { }
|
|
3713
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
|
+
}
|
|
3714
3995
|
// Helper to send data to frontend (with size limit handling)
|
|
3715
3996
|
//
|
|
3716
3997
|
// WebRTC SCTP data channel max message size is ~256KB. Sending larger
|
|
@@ -3965,6 +4246,24 @@ async function main() {
|
|
|
3965
4246
|
prewarmBM25Index(sessionId, workingDir).catch(() => { });
|
|
3966
4247
|
}
|
|
3967
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
|
+
});
|
|
3968
4267
|
// Also pre-warm for resumed sessions (sessionId already known)
|
|
3969
4268
|
if (resumeSessionId && currentVoiceMode === 'pipeline') {
|
|
3970
4269
|
prewarmBM25Index(resumeSessionId, workingDir).catch(() => { });
|
|
@@ -3989,7 +4288,9 @@ async function main() {
|
|
|
3989
4288
|
// Detect research artifact writes (session workspace or legacy research dir)
|
|
3990
4289
|
if ((data.name === 'Write' || data.name === 'Edit') && data.input?.file_path) {
|
|
3991
4290
|
const fp = data.input.file_path;
|
|
3992
|
-
|
|
4291
|
+
// Robust root check (not a substring) — parity with the read gate so a
|
|
4292
|
+
// traversal path can't spoof a "research_artifact_updated" notification.
|
|
4293
|
+
if (isSafeArtifactPath(fp)) {
|
|
3993
4294
|
sendToFrontend({
|
|
3994
4295
|
type: 'research_artifact_updated',
|
|
3995
4296
|
filePath: fp,
|
|
@@ -5024,6 +5325,14 @@ async function main() {
|
|
|
5024
5325
|
agentState = ev.newState;
|
|
5025
5326
|
// Clear processing guard when model transitions to any new state
|
|
5026
5327
|
isProcessingQueue = false;
|
|
5328
|
+
// Native duck: never leave the next utterance quiet
|
|
5329
|
+
if (ev.newState !== 'speaking') {
|
|
5330
|
+
if (duckRestoreTimer) {
|
|
5331
|
+
clearTimeout(duckRestoreTimer);
|
|
5332
|
+
duckRestoreTimer = null;
|
|
5333
|
+
}
|
|
5334
|
+
currentDuck?.setDuck(1, 'agent ' + ev.newState);
|
|
5335
|
+
}
|
|
5027
5336
|
console.log(`🤖 State: ${ev.newState}`);
|
|
5028
5337
|
sendToFrontend({ type: 'agent_state', state: ev.newState });
|
|
5029
5338
|
// When the model becomes available (listening), process any queued voice injections
|
|
@@ -5043,6 +5352,24 @@ async function main() {
|
|
|
5043
5352
|
const prev = userState;
|
|
5044
5353
|
userState = ev.newState;
|
|
5045
5354
|
console.log(`👤 User state: ${prev} → ${ev.newState} (agent: ${agentState})`);
|
|
5355
|
+
// Native duck: drop agent TTS to DUCK_LEVEL while the user talks over it;
|
|
5356
|
+
// restore 250ms after they go quiet (cancelled if they speak again).
|
|
5357
|
+
if (ev.newState === 'speaking') {
|
|
5358
|
+
if (duckRestoreTimer) {
|
|
5359
|
+
clearTimeout(duckRestoreTimer);
|
|
5360
|
+
duckRestoreTimer = null;
|
|
5361
|
+
}
|
|
5362
|
+
if (agentState === 'speaking')
|
|
5363
|
+
currentDuck?.setDuck(DUCK_LEVEL, 'user speaking');
|
|
5364
|
+
}
|
|
5365
|
+
else {
|
|
5366
|
+
if (duckRestoreTimer)
|
|
5367
|
+
clearTimeout(duckRestoreTimer);
|
|
5368
|
+
duckRestoreTimer = setTimeout(() => {
|
|
5369
|
+
duckRestoreTimer = null;
|
|
5370
|
+
currentDuck?.setDuck(1, 'user quiet');
|
|
5371
|
+
}, 250);
|
|
5372
|
+
}
|
|
5046
5373
|
if (ev.newState === 'speaking' && agentState === 'speaking') {
|
|
5047
5374
|
// 0.9.67: action commented out, condition + debug kept.
|
|
5048
5375
|
//
|
|
@@ -5149,6 +5476,8 @@ async function main() {
|
|
|
5149
5476
|
// Whatever else SDK provides — dump it all for now
|
|
5150
5477
|
fields: Object.keys(ev),
|
|
5151
5478
|
}));
|
|
5479
|
+
if (ev.isInterruption === false)
|
|
5480
|
+
currentDuck?.setDuck(1, 'overlap not interruption');
|
|
5152
5481
|
});
|
|
5153
5482
|
// agent_false_interruption — the SDK's "actually that was a false alarm,
|
|
5154
5483
|
// resuming TTS" event. Fires falseInterruptionTimeout after a pause.
|
|
@@ -5160,6 +5489,7 @@ async function main() {
|
|
|
5160
5489
|
resumed: ev.resumed,
|
|
5161
5490
|
createdAt: ev.createdAt,
|
|
5162
5491
|
}));
|
|
5492
|
+
currentDuck?.setDuck(1, 'false interruption');
|
|
5163
5493
|
});
|
|
5164
5494
|
// speech_created — every time TTS audio is queued. Lets us correlate
|
|
5165
5495
|
// a speech-handle id back to the transcript that triggered it.
|
|
@@ -5354,7 +5684,8 @@ async function main() {
|
|
|
5354
5684
|
}
|
|
5355
5685
|
try {
|
|
5356
5686
|
// Reuse existing session ID so Claude SDK resumes where it left off
|
|
5357
|
-
|
|
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 });
|
|
5358
5689
|
let result;
|
|
5359
5690
|
{
|
|
5360
5691
|
// Pipeline mode: recreate PipelineDirectLLM wrapper with fast brain
|
|
@@ -5396,6 +5727,7 @@ async function main() {
|
|
|
5396
5727
|
// Re-wire event listeners on the new session
|
|
5397
5728
|
wireSessionEvents(newSession, newAgent);
|
|
5398
5729
|
await newSession.start({ agent: newAgent, room: activeRoom });
|
|
5730
|
+
currentDuck = installDuck(newSession);
|
|
5399
5731
|
// Sync state
|
|
5400
5732
|
agentState = 'listening';
|
|
5401
5733
|
sendToFrontend({ type: 'agent_state', state: 'listening' });
|
|
@@ -5438,6 +5770,7 @@ async function main() {
|
|
|
5438
5770
|
console.log('🎬 Starting voice session...');
|
|
5439
5771
|
try {
|
|
5440
5772
|
await session.start({ agent, room: activeRoom });
|
|
5773
|
+
currentDuck = installDuck(session);
|
|
5441
5774
|
console.log('✅ Voice session started!');
|
|
5442
5775
|
console.log('🎤 Ready - speak to begin!\n');
|
|
5443
5776
|
// Workspace is created later in the session_id event handler (when SDK assigns real ID)
|
|
@@ -5493,6 +5826,7 @@ async function main() {
|
|
|
5493
5826
|
});
|
|
5494
5827
|
};
|
|
5495
5828
|
const readyInterval = setInterval(sendReady, 2000);
|
|
5829
|
+
stopReadyRetries = () => { readySent = true; clearInterval(readyInterval); };
|
|
5496
5830
|
// Fire immediately with the fast-scanned recent session (sessionsLoaded still false)
|
|
5497
5831
|
await sendReady();
|
|
5498
5832
|
setTimeout(() => {
|
|
@@ -5645,6 +5979,7 @@ async function main() {
|
|
|
5645
5979
|
console.log(`👋 User left: ${participant.identity}`);
|
|
5646
5980
|
if (participant.identity === controllingUserIdentity)
|
|
5647
5981
|
controllingUserIdentity = null;
|
|
5982
|
+
cancelPendingSwitch('participant_disconnected', false);
|
|
5648
5983
|
// Full cleanup — stop all background work to avoid accumulating API usage
|
|
5649
5984
|
voiceQueue.length = 0;
|
|
5650
5985
|
isProcessingQueue = false;
|
|
@@ -5761,6 +6096,40 @@ async function main() {
|
|
|
5761
6096
|
sendToFrontend({ type: 'claude_auth_submitting', message: 'Submitting code to Claude CLI...' });
|
|
5762
6097
|
pendingAuthSubmitCode(data.code);
|
|
5763
6098
|
}
|
|
6099
|
+
else if (data.type === 'claude_auth_start') {
|
|
6100
|
+
// On-demand Claude sign-in. When a fallback key exists the join path
|
|
6101
|
+
// skips the blocking OAuth (claude_auth_optional), so this is the only
|
|
6102
|
+
// way to start it. Owner-gated via CONTROL_MESSAGE_TYPES.
|
|
6103
|
+
const authSend = (type, payload) => {
|
|
6104
|
+
sendToFrontend({ type, ...payload });
|
|
6105
|
+
};
|
|
6106
|
+
if (pendingAuthSubmitCode && !isOnDemandAuthInFlight()) {
|
|
6107
|
+
// The join-path flow is already running — re-deliver its state.
|
|
6108
|
+
console.log('🔑 claude_auth_start: join-path flow in flight — replaying state');
|
|
6109
|
+
replayInFlightAuth(authSend);
|
|
6110
|
+
}
|
|
6111
|
+
else {
|
|
6112
|
+
// Not awaited: done only settles when the user finishes (or the 5-min
|
|
6113
|
+
// timeout), and this handler must stay responsive (claude_auth_code).
|
|
6114
|
+
const { started, result } = startClaudeAuthOnDemand(authSend, {
|
|
6115
|
+
get: () => pendingAuthSubmitCode,
|
|
6116
|
+
set: (fn) => { pendingAuthSubmitCode = fn; },
|
|
6117
|
+
});
|
|
6118
|
+
if (!started) {
|
|
6119
|
+
replayInFlightAuth(authSend);
|
|
6120
|
+
}
|
|
6121
|
+
else {
|
|
6122
|
+
console.log('🔑 claude_auth_start: starting on-demand Claude OAuth');
|
|
6123
|
+
void result.then(({ fallbackCleared }) => {
|
|
6124
|
+
// Only when a fallback redirect was actually active: live persistent
|
|
6125
|
+
// sessions restart BEFORE their next turn (deferred — a streaming
|
|
6126
|
+
// turn finishes normally), resuming the same sessionId on Claude.
|
|
6127
|
+
if (fallbackCleared)
|
|
6128
|
+
requestAuthRestart();
|
|
6129
|
+
});
|
|
6130
|
+
}
|
|
6131
|
+
}
|
|
6132
|
+
}
|
|
5764
6133
|
else if (data.type === 'permission_response') {
|
|
5765
6134
|
// Handle permission response for direct mode
|
|
5766
6135
|
if (currentLLM && currentLLM.hasPendingPermission?.()) {
|
|
@@ -5817,6 +6186,9 @@ async function main() {
|
|
|
5817
6186
|
// The session echoes this item as user_transcript; carry the frontend's
|
|
5818
6187
|
// clientMsgId (bubble dedupe) and the attachment blocks onto that echo.
|
|
5819
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?.();
|
|
5820
6192
|
// Skip interrupt for Gemini — disrupts state machine (hangs in speaking state)
|
|
5821
6193
|
if (true) { // always non-gemini in pipeline mode
|
|
5822
6194
|
currentSession.interrupt();
|
|
@@ -5857,7 +6229,11 @@ async function main() {
|
|
|
5857
6229
|
// Context injection (generateReply) happens in session_selected handler
|
|
5858
6230
|
// to avoid double generateReply calls that cause timeouts
|
|
5859
6231
|
const sessionId = data.sessionId;
|
|
5860
|
-
if (sessionId &&
|
|
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)) {
|
|
5861
6237
|
currentLLM.setResumeSessionId(sessionId);
|
|
5862
6238
|
currentResumeSessionId = sessionId;
|
|
5863
6239
|
console.log(`🔄 Will resume session: ${sessionId}`);
|
|
@@ -5940,7 +6316,10 @@ async function main() {
|
|
|
5940
6316
|
}
|
|
5941
6317
|
else if (data.type === 'continue_session' && currentLLM) {
|
|
5942
6318
|
const recentId = await getMostRecentSessionId(workingDir);
|
|
5943
|
-
if (recentId) {
|
|
6319
|
+
if (recentId && liveSwitchNeeded(recentId)) {
|
|
6320
|
+
await requestSessionSwitch(recentId, workingDir, { origin: 'continue_session' });
|
|
6321
|
+
}
|
|
6322
|
+
else if (recentId) {
|
|
5944
6323
|
currentLLM.setResumeSessionId(recentId);
|
|
5945
6324
|
currentResumeSessionId = recentId;
|
|
5946
6325
|
console.log(`🔄 Continuing most recent session: ${recentId}`);
|
|
@@ -5986,64 +6365,21 @@ async function main() {
|
|
|
5986
6365
|
}
|
|
5987
6366
|
}
|
|
5988
6367
|
else if (data.type === 'switch_session' && currentLLM) {
|
|
5989
|
-
// 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.
|
|
5990
6374
|
const sessionId = data.sessionId;
|
|
5991
|
-
|
|
5992
|
-
|
|
5993
|
-
|
|
5994
|
-
|
|
5995
|
-
|
|
5996
|
-
|
|
5997
|
-
|
|
5998
|
-
|
|
5999
|
-
clearPipelineFastBrainSession();
|
|
6000
|
-
clearPipelineFastBrainSession();
|
|
6001
|
-
console.log(`🔄 Switched to session: ${sessionId}`);
|
|
6002
|
-
// Step 3: Send full context to frontend (including conversation history)
|
|
6003
|
-
await sendToFrontend({
|
|
6004
|
-
type: 'session_switched',
|
|
6005
|
-
sessionId,
|
|
6006
|
-
success: true,
|
|
6007
|
-
summary,
|
|
6008
|
-
conversationHistory,
|
|
6009
|
-
});
|
|
6010
|
-
// Step 3.5: Send existing session artifacts to frontend (session-scoped)
|
|
6011
|
-
const switchArtifacts = listWorkspaceArtifacts(workingDir, sessionId);
|
|
6012
|
-
if (switchArtifacts.length > 0) {
|
|
6013
|
-
console.log(`📁 Sending ${switchArtifacts.length} session artifacts to frontend`);
|
|
6014
|
-
await sendToFrontend({
|
|
6015
|
-
type: 'session_artifacts',
|
|
6016
|
-
sessionId,
|
|
6017
|
-
artifacts: switchArtifacts.map(a => ({
|
|
6018
|
-
filePath: a.filePath,
|
|
6019
|
-
fileName: a.fileName,
|
|
6020
|
-
type: a.type,
|
|
6021
|
-
updatedAt: a.updatedAt,
|
|
6022
|
-
}))
|
|
6023
|
-
});
|
|
6024
|
-
}
|
|
6025
|
-
// Step 4: Voice agent acknowledges context — greet first, point to index after
|
|
6026
|
-
if (currentSession && summary) {
|
|
6027
|
-
try {
|
|
6028
|
-
const acknowledgment = summary.lastMessages.length > 0
|
|
6029
|
-
? `I've switched to your previous session. You were working on: ${summary.lastMessages[summary.lastMessages.length - 1]?.substring(0, 100)}`
|
|
6030
|
-
: `Switched to previous session with ${summary.messageCount} messages. What would you like to continue with?`;
|
|
6031
|
-
await currentSession.say(acknowledgment);
|
|
6032
|
-
}
|
|
6033
|
-
catch (err) {
|
|
6034
|
-
console.log('⚠️ Switch acknowledgment failed:', err);
|
|
6035
|
-
}
|
|
6036
|
-
injectSessionIndexIntoChatCtx(currentAgent, sessionId, workingDir);
|
|
6037
|
-
}
|
|
6038
|
-
}
|
|
6039
|
-
else {
|
|
6040
|
-
await sendToFrontend({
|
|
6041
|
-
type: 'session_switched',
|
|
6042
|
-
sessionId,
|
|
6043
|
-
success: false,
|
|
6044
|
-
error: 'Session not found',
|
|
6045
|
-
});
|
|
6046
|
-
}
|
|
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' });
|
|
6047
6383
|
}
|
|
6048
6384
|
else if (data.type === 'get_current_session' && currentLLM) {
|
|
6049
6385
|
// Get current session ID
|
|
@@ -6075,7 +6411,9 @@ async function main() {
|
|
|
6075
6411
|
// ============================================================
|
|
6076
6412
|
else if (data.type === 'get_plan_file') {
|
|
6077
6413
|
const filePath = data.filePath;
|
|
6078
|
-
|
|
6414
|
+
// SECURITY: same reachable read-only primitive as get_research_artifact —
|
|
6415
|
+
// gate the plan dir with a resolve+root-prefix check, not a substring.
|
|
6416
|
+
if (filePath && isSafeArtifactPath(filePath, ['plans'])) {
|
|
6079
6417
|
try {
|
|
6080
6418
|
const fs = await import('fs');
|
|
6081
6419
|
const content = fs.readFileSync(filePath, 'utf-8');
|
|
@@ -6088,7 +6426,10 @@ async function main() {
|
|
|
6088
6426
|
}
|
|
6089
6427
|
else if (data.type === 'get_research_artifact') {
|
|
6090
6428
|
const filePath = data.filePath;
|
|
6091
|
-
|
|
6429
|
+
// SECURITY: resolve + canonicalize + root-prefix check (NOT a substring
|
|
6430
|
+
// test). This handler is read-only and reachable by ANY room participant,
|
|
6431
|
+
// so a substring gate let `…/osb/../../../etc/passwd` be read + uploaded.
|
|
6432
|
+
if (filePath && isSafeArtifactPath(filePath)) {
|
|
6092
6433
|
try {
|
|
6093
6434
|
const fs = await import('fs');
|
|
6094
6435
|
const path = await import('path');
|
|
@@ -6635,7 +6976,10 @@ async function main() {
|
|
|
6635
6976
|
else if (data.type === 'session_selected') {
|
|
6636
6977
|
const sessionId = data.sessionId;
|
|
6637
6978
|
console.log(`🚪 Session gate completed: ${sessionId ? `resume ${sessionId}` : 'fresh start'}`);
|
|
6638
|
-
if (sessionId && currentLLM &&
|
|
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)) {
|
|
6639
6983
|
// Resume the selected session
|
|
6640
6984
|
currentLLM.setResumeSessionId(sessionId);
|
|
6641
6985
|
currentResumeSessionId = sessionId;
|
|
@@ -7019,6 +7363,7 @@ async function main() {
|
|
|
7019
7363
|
const destroyRoomSession = async (reason) => {
|
|
7020
7364
|
if (destroyingRoomSession)
|
|
7021
7365
|
return;
|
|
7366
|
+
cancelPendingSwitch('room_destroyed', false);
|
|
7022
7367
|
if (!activeRoom) {
|
|
7023
7368
|
// Already idle — still ensure billing backstop is armed.
|
|
7024
7369
|
livekitState.status = 'idle';
|