osborn 0.9.290 → 0.9.292

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.
Files changed (86) hide show
  1. package/.claude/skills/browser-apply/SKILL.md +5 -4
  2. package/.claude/skills/browser-apply/candidate.example.env +4 -1
  3. package/.claude/skills/browser-apply/fill.mjs +13 -2
  4. package/.claude/skills/meetings/SKILL.md +26 -7
  5. package/.env.example +6 -0
  6. package/dist/agent-store.d.ts +6 -0
  7. package/dist/agent-store.js +36 -6
  8. package/dist/approval-policy.d.ts +99 -0
  9. package/dist/approval-policy.js +196 -0
  10. package/dist/claude-llm.d.ts +6 -2
  11. package/dist/claude-llm.js +68 -20
  12. package/dist/config.d.ts +12 -16
  13. package/dist/config.js +75 -21
  14. package/dist/content/compaction-lens-worker.d.ts +5 -0
  15. package/dist/content/compaction-lens-worker.js +78 -7
  16. package/dist/content/content-llm.d.ts +14 -3
  17. package/dist/content/content-llm.js +33 -142
  18. package/dist/content/lens-db.d.ts +16 -5
  19. package/dist/content/lens-db.js +58 -11
  20. package/dist/content/lens-ingest.d.ts +1 -0
  21. package/dist/content/lens-ingest.js +1 -1
  22. package/dist/content/lens-launch.d.ts +42 -1
  23. package/dist/content/lens-launch.js +202 -40
  24. package/dist/content/lens-library-digest.d.ts +85 -0
  25. package/dist/content/lens-library-digest.js +305 -0
  26. package/dist/content/lens-library-index.d.ts +14 -3
  27. package/dist/content/lens-library-index.js +35 -8
  28. package/dist/content/lens-library-select.d.ts +1 -1
  29. package/dist/content/lens-library-select.js +1 -1
  30. package/dist/content/lens-library-sweep.d.ts +36 -0
  31. package/dist/content/lens-library-sweep.js +331 -0
  32. package/dist/content/lens-library.d.ts +29 -0
  33. package/dist/content/lens-library.js +130 -20
  34. package/dist/content/lens-model.d.ts +4 -0
  35. package/dist/content/lens-model.js +5 -0
  36. package/dist/content/lens-paths.d.ts +72 -0
  37. package/dist/content/lens-paths.js +248 -5
  38. package/dist/content/period-run.js +2 -2
  39. package/dist/content/secret-rules.d.ts +51 -0
  40. package/dist/content/secret-rules.js +185 -0
  41. package/dist/content/transcript-sanitizer.d.ts +1 -41
  42. package/dist/content/transcript-sanitizer.js +4 -171
  43. package/dist/data-sender-auth.d.ts +112 -3
  44. package/dist/data-sender-auth.js +165 -39
  45. package/dist/env-keys.d.ts +10 -2
  46. package/dist/env-keys.js +26 -5
  47. package/dist/index.js +616 -109
  48. package/dist/phone-code.d.ts +76 -0
  49. package/dist/phone-code.js +124 -0
  50. package/dist/phone-voice-actions.d.ts +132 -0
  51. package/dist/phone-voice-actions.js +223 -0
  52. package/dist/pipeline-direct-llm.d.ts +8 -1
  53. package/dist/pipeline-direct-llm.js +13 -1
  54. package/dist/prompts/library-digest.md +11 -0
  55. package/dist/prompts.d.ts +4 -0
  56. package/dist/prompts.js +6 -2
  57. package/dist/pushover.d.ts +2 -1
  58. package/dist/pushover.js +7 -6
  59. package/dist/risk-tier.d.ts +14 -0
  60. package/dist/risk-tier.js +140 -0
  61. package/dist/session-store.d.ts +1 -0
  62. package/dist/session-store.js +3 -2
  63. package/dist/session-switch.d.ts +22 -7
  64. package/dist/session-switch.js +58 -24
  65. package/dist/steward-verdict.d.ts +16 -3
  66. package/dist/steward-verdict.js +37 -18
  67. package/dist/watch-gateway.js +3 -1
  68. package/package.json +1 -1
  69. package/dist/bridge-llm.d.ts +0 -22
  70. package/dist/bridge-llm.js +0 -39
  71. package/dist/codex-handler.d.ts +0 -38
  72. package/dist/codex-handler.js +0 -83
  73. package/dist/codex-llm.d.ts +0 -40
  74. package/dist/codex-llm.js +0 -144
  75. package/dist/fast-brain.d.ts +0 -176
  76. package/dist/fast-brain.js +0 -1887
  77. package/dist/index-3-2-26-legacy.d.ts +0 -1
  78. package/dist/index-3-2-26-legacy.js +0 -2233
  79. package/dist/leagcyprompts2.d.ts +0 -0
  80. package/dist/leagcyprompts2.js +0 -573
  81. package/dist/prompts-2-25-26.d.ts +0 -0
  82. package/dist/prompts-2-25-26.js +0 -518
  83. package/dist/prompts-3-2-26.d.ts +0 -78
  84. package/dist/prompts-3-2-26.js +0 -1319
  85. package/dist/summary-index.d.ts +0 -90
  86. package/dist/summary-index.js +0 -585
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ import 'dotenv/config';
6
6
  import './boot-secrets.js';
7
7
  import { voice, initializeLogger } from '@livekit/agents';
8
8
  import { CloudTurnDetector } from './turn-detector-shim.js';
9
- import { Room, RoomEvent, DisconnectReason, } from '@livekit/rtc-node';
9
+ import { Room, RoomEvent, DisconnectReason, ParticipantKind, } from '@livekit/rtc-node';
10
10
  import { AccessToken } from 'livekit-server-sdk';
11
11
  // Initialize logger before anything else
12
12
  initializeLogger({ pretty: true, level: 'info' });
@@ -34,25 +34,25 @@ import { createGunzip } from 'node:zlib';
34
34
  const __filename = fileURLToPath(import.meta.url);
35
35
  const __dirname = dirname(__filename);
36
36
  import { createPatch } from 'diff';
37
- import { loadConfig, getMcpServers, getEnabledMcpServerNames, getVoiceMode, getDirectConfig, listSessions, listAllClaudeSessions, extractCwd, slugToPath, getClaudeProjectsDir, invalidateSessionListCache, getMostRecentSessionId, sessionExists, getSessionSummary, getConversationHistory, ensureSessionWorkspace, getMcpServerStatusList, buildMcpServersForKeys, listWorkspaceArtifacts } from './config.js';
37
+ import { loadConfig, getMcpServers, getEnabledMcpServerNames, getVoiceMode, getDirectConfig, listSessions, listAllClaudeSessions, extractCwd, slugToPath, getClaudeProjectsDir, getSessionDir, invalidateSessionListCache, getMostRecentSessionId, sessionExists, getSessionSummary, getConversationHistory, ensureSessionWorkspace, getMcpServerStatusList, buildMcpServersForKeys, listWorkspaceArtifacts } from './config.js';
38
38
  import { isSafeArtifactPath } from './lib/safe-artifact-path.js';
39
39
  import { cleanupHousekeeping } from './housekeeping.js';
40
40
  import { createSTT, createTTS } from './voice-io.js';
41
41
  import { createClaudeLLM, NAMED_AGENTS, applyTurbo, requestAuthRestart } from './claude-llm.js';
42
42
  import { SOURCES, loadCatalog, findEntry, installSkill, agentDraft, recommend, skillProvenance, installedIds, findUpdates } from './store-catalog.js';
43
- import { parseUserAgents, mergeAgents, describeAgents, describeRoles, coreRole, AGENT_LIMITS, storeWriteRefusal, storeWriteOriginAllowed, coreSkillNames, skillForkedFrom, forkSkill, removeUserSkill, addUserSkill, readUserSkill, parseFrontMatter, storeName } from './agent-store.js';
43
+ import { parseUserAgents, mergeAgents, describeAgents, describeRoles, coreRole, AGENT_LIMITS, storeWriteRefusal, storeWriteOriginAllowed, coreSkillNames, skillForkedFrom, forkSkill, removeUserSkill, addUserSkill, readUserSkill, parseFrontMatter, skillHeading, storeName } from './agent-store.js';
44
44
  import { clearPipelineFastBrainSession, prewarmBM25Index } from './pipeline-fastbrain.js';
45
45
  import { ensureClaudeAuth, applyAuthFallback, replayInFlightAuth, startClaudeAuthOnDemand, isOnDemandAuthInFlight, probeActiveProviderKey } from './claude-auth.js';
46
46
  import { statusManager } from './status-manager.js';
47
- import { decideNextSession, planSwitch, resolveSessionCwd, keepNonConversationItems, recoverySessionId as pickRecoverySessionId, warmParkKey, sessionMessagesDir, createSwitchGuard, scanSlugCwd } from './session-switch.js';
47
+ import { decideNextSession, planSwitch, resolveSessionCwd, keepNonConversationItems, recoverySessionId as pickRecoverySessionId, warmParkKey, sessionMessagesDir, createSwitchGuard, scanSlugCwd, connectWorkingDir } from './session-switch.js';
48
48
  import { createSmitheryProxy, destroySmitheryProxy, parseSmitheryUrl, isSmitheryUrl, SmitheryAuthorizationError } from './smithery-proxy.js';
49
- import { DIRECT_MODE_PROMPT } from './prompts.js';
50
- import { MCP_CATALOG } from './config.js';
51
- import { launchLibraryOnSessionEnd, lastLibraryRun, isContentLensEnabled } from './content/lens-launch.js';
49
+ import { DIRECT_MODE_PROMPT, PHONE_PERMISSION_DENIED } from './prompts.js';
50
+ import { MCP_CATALOG, readApprovalMode, writeApprovalMode } from './config.js';
51
+ import { launchLibraryOnSessionEnd, launchLibrarySweep, librarySweepHealth, setLibraryLiveSessions, isContentLensEnabled } from './content/lens-launch.js';
52
52
  import { resolveIngestConfig } from './content/lens-ingest.js';
53
53
  import { storeExists, openStore, recentRows } from './session-store.js';
54
54
  import { readCompactionMarkers } from './compaction-log.js';
55
- import { readStewardVerdicts } from './steward-verdict.js';
55
+ import { readStewardRecords, stewardPushRecords } from './steward-verdict.js';
56
56
  import { sessionListEntry, cleanHistoryRows, userEchoText, TypedEchoTracker, ClientNoteQueue, parseFavoriteChanged, parseLegacyFavoriteNotice } from './transcript-wiring.js';
57
57
  import { getRecallClient } from './recall-client.js';
58
58
  import { synthMeetingAudio, selectMeetingTtsProviders } from './meeting-tts.js';
@@ -64,7 +64,10 @@ import { noiseGate } from './noise-gate.js';
64
64
  import { installDuck, DUCK_LEVEL } from './duck.js';
65
65
  import { meetingAddressing, isRoutableTarget } from './meeting-addressing.js';
66
66
  import { listSecretStatus, setSecrets, deleteSecret } from './secrets-store.js';
67
- import { AGENT_SELF_IDENTITY, checkControlSender, resolveJoin, userIdFromMetadata } from './data-sender-auth.js';
67
+ import { AGENT_SELF_IDENTITY, CONNECT_ROOM_MAX_BODY, PHONE_ACTION_TYPES, PHONE_KEYPAD_APPROVALS_ENABLED, PHONE_TOOLS_ENABLED, checkControlSender, handlePhoneKeypad, isPhoneCallLive, isPhoneRoomName, phoneAnswerAllowed, phoneRequestRoute, planConnectRoom, readBodyCapped, resolveJoin, userIdFromMetadata } from './data-sender-auth.js';
68
+ import { PHONE_CODE_HANGUP_GRACE_MS, PHONE_CODE_TIMEOUT_MS, addCodeDigit, checkPhoneCode, heldCode, isPhoneLinePlayer as isLinePlayer, offerPhoneCode, phoneCallerAdmission, phoneCodeAction, removePhoneCaller } from './phone-code.js';
69
+ import { alwaysScope, answerPending, answerPendingWithoutId, approvalModeAnnouncement, approvalModeLabel, autoApproval, describePermission, isAlwaysAllowed, isApprovalMode, newSessionAllows, phoneApprovalPrompt, speakablePermission } from './approval-policy.js';
70
+ import { matchVoiceAction, phoneMayChangeMode, promptHeard, sayBlocked, sayModeChanged, sayOutputs, saySessions, sayStatus, saySwitchOutcome } from './phone-voice-actions.js';
68
71
  import { llm } from '@livekit/agents';
69
72
  // ============================================================
70
73
  // PIPELINE MODE: STT (Deepgram) → Claude Agent SDK → TTS
@@ -126,6 +129,8 @@ function buildToolLogEvent(name, input, status, agentRole, agentId) {
126
129
  catch { /* diff is best-effort — omit on any failure */ }
127
130
  return ev;
128
131
  }
132
+ // Spoken through session.say when a session resumes; matched in sendAgentTranscript.
133
+ const RESUME_GREETING = 'Welcome back! Ready to continue our previous conversation.';
129
134
  // The reply each chat store request waits for (VoiceRoom askAgent).
130
135
  const STORE_REPLY_TYPES = {
131
136
  skill_get: 'skill_content', skill_add: 'skill_add_result', skill_fork: 'skill_fork_result',
@@ -149,11 +154,10 @@ function loadSkillsList(agentDir) {
149
154
  const skillFile = join(skillsDir, skillName, 'SKILL.md');
150
155
  if (existsSync(skillFile)) {
151
156
  const { meta, body } = parseFrontMatter(readFileSync(skillFile, 'utf-8'));
152
- // Display name: the first # heading (else the folder); description: front matter, else the paragraph after the heading
153
- const titleMatch = body.match(/^#\s+(?:Skill:\s*)?(.+)/m);
154
- const name = titleMatch ? titleMatch[1].trim() : skillName;
155
- const descMatch = body.match(/^#[^\n]+\n+([^\n#]+)/m);
156
- const description = typeof meta.description === 'string' && meta.description ? meta.description : descMatch ? descMatch[1].trim() : '';
157
+ // Display name: the first # heading outside code (else the folder); description: front matter, else the paragraph after the heading
158
+ const heading = skillHeading(body);
159
+ const name = heading.title || skillName;
160
+ const description = typeof meta.description === 'string' && meta.description ? meta.description : heading.paragraph || '';
157
161
  const forkedFrom = skillForkedFrom(skillsDir, skillName);
158
162
  const installedFrom = skillProvenance(skillsDir, skillName);
159
163
  skills.push({ name, description, folder: skillName, core: core.has(skillName), ...(forkedFrom ? { forkedFrom } : {}), ...(installedFrom ? { installedFrom } : {}) });
@@ -295,6 +299,7 @@ let intentionalLeave = false;
295
299
  // Native barge-in duck on the live session's audio output (see duck.ts)
296
300
  let currentDuck = null;
297
301
  let duckRestoreTimer = null;
302
+ // phoneRoom: join this caller's room (a phone call) instead of a fresh one.
298
303
  let connectRoomHook = null;
299
304
  // Mints a LISTEN-ONLY LiveKit token for the meeting canvas so it can join the
300
305
  // agent's room and play the agent's REAL TTS audio track — bit-identical to
@@ -705,7 +710,7 @@ function startApiServer(workingDir, port) {
705
710
  // pass their own cwd; honoured only if the session really lives there.
706
711
  const readDir = sessionMessagesDir(sessionId, url.searchParams.get('workingDirectory'), workingDir, sessionExists);
707
712
  const compactions = readCompactionMarkers(sessionId, readDir);
708
- const steward = readStewardVerdicts(sessionId, readDir);
713
+ const steward = readStewardRecords(sessionId, readDir);
709
714
  const dbPath = storeExists(sessionId, readDir);
710
715
  if (!dbPath) {
711
716
  res.writeHead(200, { 'Content-Type': 'application/json' });
@@ -911,12 +916,13 @@ function startApiServer(workingDir, port) {
911
916
  status: 'ok',
912
917
  workingDir,
913
918
  version,
914
- // Library: is it on, can it call the model, does it reach /library (no values, 8-char session id).
919
+ // Library: is it on, can it call the model, does it reach /library. Public: counts, times and codes only.
915
920
  library: {
916
921
  enabled: isContentLensEnabled(),
917
922
  modelKey: !!(process.env.OPENROUTER_API_KEY || '').trim(),
918
923
  ingest: (() => { const c = resolveIngestConfig(); return 'reason' in c ? (c.reason === 'no-key' ? 'no-anon-key' : c.reason) : 'on'; })(),
919
- lastRun: lastLibraryRun(),
924
+ // Last launches, the worker's step outcome, the sweep's backlog and result, the last worker failure.
925
+ ...librarySweepHealth(),
920
926
  },
921
927
  // WHERE this machine physically runs — Fly sets FLY_REGION (e.g. 'ord').
922
928
  // The dashboard maps it to a city ("Chicago") so the user always knows
@@ -986,18 +992,53 @@ function startApiServer(workingDir, port) {
986
992
  // directly (mint its LiveKit token for it) rather than fetching /room-code.
987
993
  // The agent is in the room by the time this responds, so the user's join
988
994
  // fires ParticipantConnected (or is caught by the adopt-sweep either way).
995
+ // Phone calls (#361): an optional JSON body { roomName } joins that caller's
996
+ // room instead of a fresh one. Only with the sync token, only a "call-" room;
997
+ // 409 { error: 'busy' } while a user is in another room. No body = as before,
998
+ // except during a live phone call: 409 busy (never the caller's room).
989
999
  if (req.method === 'POST' && url.pathname === '/connect-room') {
1000
+ // Stop reading past the cap without destroying the socket, so the 413 still goes out.
1001
+ const raw = await readBodyCapped(req.iterator({ destroyOnReturn: false }), CONNECT_ROOM_MAX_BODY);
1002
+ if (raw === null) {
1003
+ res.writeHead(413, { 'Content-Type': 'application/json', Connection: 'close' });
1004
+ res.end(JSON.stringify({ ok: false, error: 'body too large' }));
1005
+ return;
1006
+ }
1007
+ let phoneRoom;
1008
+ if (raw.trim()) {
1009
+ let parsed = {};
1010
+ try {
1011
+ parsed = JSON.parse(raw);
1012
+ }
1013
+ catch { }
1014
+ if (parsed.roomName !== undefined) {
1015
+ if (unauthorized())
1016
+ return;
1017
+ if (!isPhoneRoomName(parsed.roomName)) {
1018
+ res.writeHead(400, { 'Content-Type': 'application/json' });
1019
+ res.end(JSON.stringify({ ok: false, error: 'invalid roomName' }));
1020
+ return;
1021
+ }
1022
+ phoneRoom = parsed.roomName;
1023
+ }
1024
+ }
990
1025
  if (!connectRoomHook) {
991
1026
  res.writeHead(503, { 'Content-Type': 'application/json' });
992
1027
  res.end(JSON.stringify({ ok: false, error: 'agent not ready' }));
993
1028
  return;
994
1029
  }
995
- connectRoomHook()
1030
+ connectRoomHook(phoneRoom)
996
1031
  .then((roomName) => {
997
1032
  res.writeHead(200, { 'Content-Type': 'application/json' });
998
- res.end(JSON.stringify({ ok: true, roomName, status: livekitState.status }));
1033
+ // callCode: the frontend emails the code this caller must type (#362).
1034
+ res.end(JSON.stringify({ ok: true, roomName, status: livekitState.status, ...(offerPhoneCode(phoneRoom, !!process.env.OSBORN_SYNC_TOKEN) ? { callCode: true } : {}) }));
999
1035
  })
1000
1036
  .catch((e) => {
1037
+ if (e?.code === 'busy') {
1038
+ res.writeHead(409, { 'Content-Type': 'application/json' });
1039
+ res.end(JSON.stringify({ ok: false, error: 'busy', status: livekitState.status }));
1040
+ return;
1041
+ }
1001
1042
  console.error('❌ /connect-room hook failed:', e);
1002
1043
  res.writeHead(500, { 'Content-Type': 'application/json' });
1003
1044
  res.end(JSON.stringify({ ok: false, error: e instanceof Error ? e.message : String(e), status: livekitState.status }));
@@ -2198,16 +2239,6 @@ async function main() {
2198
2239
  console.error('\nSet these in your .env file or environment.');
2199
2240
  process.exit(1);
2200
2241
  }
2201
- // Non-fatal diagnostic: surface any OTHER expected-required keys that are
2202
- // missing (per the shared env-keys.ts manifest — mirror of the frontend's
2203
- // platform-env.ts injection spec). The LiveKit trio above is the only
2204
- // hard-fail; the rest degrade gracefully (a plugin falls back, a feature
2205
- // no-ops), so we log rather than exit — but a missing OPENAI/DEEPGRAM key is
2206
- // the usual root cause of "voice works but STT/realtime is dead", worth naming.
2207
- const missingEnv = missingRequiredEnv().filter((k) => !['LIVEKIT_URL', 'LIVEKIT_API_KEY', 'LIVEKIT_API_SECRET'].includes(k));
2208
- if (missingEnv.length > 0) {
2209
- console.warn(`⚠️ Missing expected env keys (non-fatal): ${missingEnv.join(', ')}`);
2210
- }
2211
2242
  // Parse CLI args
2212
2243
  const cliArgs = parseArgs();
2213
2244
  // Load configuration
@@ -2257,6 +2288,11 @@ async function main() {
2257
2288
  const voiceMode = getVoiceMode(config);
2258
2289
  const directConfig = getDirectConfig(config);
2259
2290
  console.log(`🎯 PIPELINE MODE: ${directConfig.stt.provider} STT → Claude Agent SDK + fast brain → ${directConfig.tts.provider} TTS`);
2291
+ // Non-fatal: the LiveKit trio above is the only hard-fail; the STT/TTS key follows the providers in use.
2292
+ const missingEnv = missingRequiredEnv(process.env, { stt: directConfig.stt.provider, tts: directConfig.tts.provider }).filter((k) => !['LIVEKIT_URL', 'LIVEKIT_API_KEY', 'LIVEKIT_API_SECRET'].includes(k));
2293
+ if (missingEnv.length > 0) {
2294
+ console.warn(`⚠️ Missing expected env keys (non-fatal): ${missingEnv.join(', ')}`);
2295
+ }
2260
2296
  // Determine room code. STABLE PER MACHINE, derived from identity we
2261
2297
  // already have: the Fly app name (one app per user). No new storage, no
2262
2298
  // rotation — the same user always lands in the same room, and the room
@@ -2338,6 +2374,104 @@ async function main() {
2338
2374
  // null while the agent is idle (between sessions).
2339
2375
  let activeRoom = null;
2340
2376
  let activeRoomName = null; // the temporary room name currently joined
2377
+ // The caller's room the last authorised phone connect asked for. A phone call
2378
+ // is live only while the agent is in that room AND a SIP participant is in it
2379
+ // (cleared when the caller leaves or the room session ends).
2380
+ let phoneRoomName = null;
2381
+ const inPhoneRoom = () => isPhoneCallLive(activeRoomName, phoneRoomName, !!activeRoom && [...activeRoom.remoteParticipants.values()].some((p) => p.kind === ParticipantKind.SIP));
2382
+ // Emailed code (#362, PHONE_EMAIL_CODE_ENABLED): the caller waiting to type it
2383
+ // (not adopted: no voice session, no voice actions, no tools), the digits so
2384
+ // far, and the room whose caller typed it correctly.
2385
+ let phoneCodeCaller = null;
2386
+ let phoneCodeBuffer = '';
2387
+ let phoneCodeChecking = false;
2388
+ let phoneCodeVerifiedRoom = null;
2389
+ let phoneCodeTimer = null;
2390
+ const clearPhoneCode = () => {
2391
+ phoneCodeCaller = null;
2392
+ phoneCodeBuffer = '';
2393
+ phoneCodeVerifiedRoom = null;
2394
+ phoneCodeChecking = false;
2395
+ if (phoneCodeTimer) {
2396
+ clearTimeout(phoneCodeTimer);
2397
+ phoneCodeTimer = null;
2398
+ }
2399
+ };
2400
+ // Line players (phone-code.ts isPhoneLinePlayer; also the #365 hold line, flag on or off).
2401
+ const isPhoneLinePlayer = (p) => isLinePlayer(p.kind === ParticipantKind.INGRESS, activeRoomName, phoneRoomName);
2402
+ // Ends a call still waiting for its code, if `caller` is still the one waiting:
2403
+ // removes the caller, else leaves the room.
2404
+ const endPhoneCodeCall = (caller, why) => {
2405
+ const room = activeRoomName;
2406
+ if (phoneCodeCaller !== caller || !room)
2407
+ return;
2408
+ console.log(`📞🔐 Ending the call in ${room}: ${why}`);
2409
+ removePhoneCaller(room, caller.identity).then((done) => {
2410
+ if (!done && phoneCodeCaller === caller)
2411
+ destroyRoomSession(`phone-code-${why}`).catch(() => { });
2412
+ });
2413
+ };
2414
+ // A participant leaving a phone room that was never adopted (a line player, or
2415
+ // anyone during the code step) ends nothing. True when the leave is handled here.
2416
+ const phoneCodeLeave = (p) => {
2417
+ if (isPhoneLinePlayer(p))
2418
+ return true;
2419
+ if (!phoneCodeCaller)
2420
+ return false;
2421
+ if (p.identity === phoneCodeCaller.identity) {
2422
+ clearPhoneCode();
2423
+ phoneRoomName = null;
2424
+ console.log('📞🔐 Caller left before the code was accepted; nothing ran');
2425
+ armFastLeaveTimer();
2426
+ }
2427
+ return true;
2428
+ };
2429
+ // One try at the code. The frontend counts the tries and speaks the retry
2430
+ // and goodbye lines; the agent hangs up itself after a used-up code in case
2431
+ // the frontend cannot. Digits typed meanwhile are held for the next try.
2432
+ const submitPhoneCode = (code) => {
2433
+ const caller = phoneCodeCaller;
2434
+ const room = activeRoomName;
2435
+ if (!caller || !room)
2436
+ return;
2437
+ phoneCodeChecking = true;
2438
+ checkPhoneCode(osbornFrontendUrl(), process.env.OSBORN_SYNC_TOKEN, room, code).then((result) => {
2439
+ console.log(`📞🔐 Phone code for ${room}: ${result}`);
2440
+ // A check that outlived its call must not touch the next call's state (#397).
2441
+ if (phoneCodeCaller !== caller || activeRoomName !== room)
2442
+ return;
2443
+ phoneCodeChecking = false;
2444
+ const action = phoneCodeAction(result);
2445
+ if (action === 'adopt') {
2446
+ if (phoneCodeTimer) {
2447
+ clearTimeout(phoneCodeTimer);
2448
+ phoneCodeTimer = null;
2449
+ }
2450
+ phoneCodeVerifiedRoom = room;
2451
+ phoneCodeCaller = null;
2452
+ participantConnectedHandler?.(caller).catch((e) => console.error('📞 adopt after code failed:', e instanceof Error ? e.message : e));
2453
+ }
2454
+ else if (action === 'hang-up') {
2455
+ phoneCodeBuffer = '';
2456
+ setTimeout(() => endPhoneCodeCall(caller, result), PHONE_CODE_HANGUP_GRACE_MS);
2457
+ }
2458
+ else {
2459
+ const held = heldCode(phoneCodeBuffer);
2460
+ phoneCodeBuffer = held.buffer;
2461
+ if (held.submit)
2462
+ submitPhoneCode(held.submit);
2463
+ }
2464
+ });
2465
+ };
2466
+ // One keypad press during the code step: six digits make a try.
2467
+ const onPhoneCodeDigit = (digit) => {
2468
+ if (!phoneCodeCaller || !activeRoomName)
2469
+ return;
2470
+ const step = addCodeDigit(phoneCodeBuffer, digit, phoneCodeChecking);
2471
+ phoneCodeBuffer = step.buffer;
2472
+ if (step.submit)
2473
+ submitPhoneCode(step.submit);
2474
+ };
2341
2475
  // Watch gateway (mobile Track 2): bridges the native watchOS app's WS audio
2342
2476
  // + JSON into the user's LiveKit room via rtc-node. Opt-in — dormant unless
2343
2477
  // WATCH_GATEWAY=1 (port WATCH_GATEWAY_PORT, default 8742).
@@ -2579,6 +2713,15 @@ async function main() {
2579
2713
  let warmGraceTimer = null;
2580
2714
  let warmWatchdog = null;
2581
2715
  const warmStats = { starts: 0, reattachHits: 0, wastedTimeouts: 0, watchdogKills: 0, mismatchKills: 0 };
2716
+ // Library catch-up sweep: never touches a session that is still running (focused, parked or background).
2717
+ const liveSessionIds = () => [warmParkKey(currentLLM), warmSessionId, ...[...slots.values()].map(s => warmParkKey(s.llm))].filter((id) => !!id);
2718
+ setLibraryLiveSessions(liveSessionIds);
2719
+ setTimeout(() => {
2720
+ try {
2721
+ launchLibrarySweep(liveSessionIds(), 'startup');
2722
+ }
2723
+ catch { /* fail-open */ }
2724
+ }, 120_000).unref();
2582
2725
  // The outbound events createDirectSession() OWNS the wiring for. Stripped on
2583
2726
  // every (re-)wire so a re-attached subprocess ends up with exactly one
2584
2727
  // listener per event — no double TTS, no stacked handlers. Only OUR event
@@ -2883,9 +3026,20 @@ async function main() {
2883
3026
  console.error(`❌ killCurrentLLM(${reason}) failed:`, err instanceof Error ? err.message : err);
2884
3027
  }
2885
3028
  finally {
2886
- launchLibraryOnSessionEnd(currentLLM?.sessionId, currentLLM?.workingDirectory || workingDir, reason);
3029
+ launchLibraryOnSessionEnd(warmParkKey(currentLLM), currentLLM?.workingDirectory || workingDir, reason);
2887
3030
  }
2888
3031
  }
3032
+ // Steward verdict card + sign-off gate line (#221) → chat. A background slot sends only a one-line
3033
+ // background_steward (#255): its card lives in that session's own sidecar, and an older frontend
3034
+ // ignores the unknown type instead of painting the slot's card into the focused chat.
3035
+ function forwardStewardEvents(events, slotId) {
3036
+ events.on('steward_verdict', (v) => {
3037
+ sendToFrontend(slotId ? { type: 'background_steward', slotId, verdict: v.verdict, summary: v.summary } : { type: 'steward_verdict', ...v }).catch(() => { });
3038
+ });
3039
+ events.on('steward_gate', (d) => {
3040
+ sendToFrontend({ type: slotId ? 'background_steward' : 'steward_gate', ...(slotId ? { slotId, gate: d.decision } : { decision: d.decision }), message: d.message }).catch(() => { });
3041
+ });
3042
+ }
2889
3043
  // ============================================================
2890
3044
  // SLICE 1: spawnBackgroundSession
2891
3045
  // Creates a fully headless ClaudeLLM subprocess that resumes an
@@ -2972,6 +3126,7 @@ async function main() {
2972
3126
  // Wire up the LLM's internal EventEmitter so hook-emitted events also flow.
2973
3127
  bgLLM.events.on('session_id', (data) => bgEmitter.emit('session_id', data));
2974
3128
  bgLLM.events.on('tool_blocked', (data) => bgEmitter.emit('tool_blocked', data));
3129
+ forwardStewardEvents(bgLLM.events, slotId);
2975
3130
  // Build minimal sdkOptions for the headless cold start.
2976
3131
  // resume: sessionId brings up real prior context from JSONL.
2977
3132
  // env: CLAUDE_CODE_DISABLE_AUTO_MEMORY prevents concurrent subprocesses
@@ -3023,8 +3178,20 @@ async function main() {
3023
3178
  }
3024
3179
  let localParticipant = null;
3025
3180
  let agentState = 'initializing';
3026
- // Session-level always-allow list: paths the user has approved for this session without prompting
3027
- let sessionAlwaysAllowPaths = new Set();
3181
+ // Session-level always-allow list ("Always" in the browser, keypad 3 on a call): approved without prompting
3182
+ let sessionAllows = newSessionAllows();
3183
+ // The request a phone caller last heard read out: the keypad and a spoken yes/no answer only that one.
3184
+ let phonePromptedRequestId = null;
3185
+ // Sessions a call's "switch to …" picks from: loaded when the call starts, refreshed by "recent sessions".
3186
+ let phoneSessions = [];
3187
+ // "Switch to <title>?" asked on a call: switched only on a yes in the next turn.
3188
+ let phoneSwitchProposal = null;
3189
+ // A brain parked after "keep working" on a call: its requests keep the phone
3190
+ // policy (denied, or left pending) until a browser or app session re-attaches it.
3191
+ let phoneParkedBrain = null;
3192
+ // Tool approval mode (#364): saved in config.yaml, set from the app, applied
3193
+ // to every permission request (browser and phone calls).
3194
+ let approvalMode = readApprovalMode();
3028
3195
  let userState = 'listening'; // Track user speech state for queue safety
3029
3196
  let currentVoiceMode = voiceMode; // Track active voice mode for data handlers
3030
3197
  // Authenticated Supabase userId from participant metadata. Used to scope
@@ -3976,6 +4143,8 @@ async function main() {
3976
4143
  function resolveCwdForSession(sessionId, hint) {
3977
4144
  return resolveSessionCwd(sessionId, hint, workingDir, {
3978
4145
  exists: (id, wd) => sessionExists(id, wd),
4146
+ recordedCwd: (id, wd) => extractCwd(join(getSessionDir(wd), `${id}.jsonl`)),
4147
+ dirExists: (p) => existsSync(p),
3979
4148
  lookupCwd: (id) => scanSlugCwd(id, getClaudeProjectsDir(), {
3980
4149
  readdir: (d) => readdirSync(d), exists: (p) => existsSync(p),
3981
4150
  decodeSlug: (s) => slugToPath(s), readCwd: (p) => extractCwd(p),
@@ -3997,7 +4166,8 @@ async function main() {
3997
4166
  const b = slot.llm.busyState?.();
3998
4167
  return b && !b.idle ? 'busy' : 'idle';
3999
4168
  }
4000
- function cancelPendingSwitch(reason, notify = true) {
4169
+ // `reply`: where the cancel notice goes (default the room; a voice switch passes its own so it can speak it).
4170
+ function cancelPendingSwitch(reason, notify = true, reply = publishToRoom) {
4001
4171
  if (!pendingSwitch)
4002
4172
  return;
4003
4173
  const { target, timer } = pendingSwitch;
@@ -4005,7 +4175,7 @@ async function main() {
4005
4175
  pendingSwitch = null;
4006
4176
  console.log(`↩️ Pending switch to ${target.slice(0, 8)} cancelled (${reason})`);
4007
4177
  if (notify)
4008
- void sendToFrontend({ type: 'session_switch_cancelled', sessionId: target, reason });
4178
+ void reply({ type: 'session_switch_cancelled', sessionId: target, reason });
4009
4179
  }
4010
4180
  const SWITCH_REJECT_COPY = {
4011
4181
  meeting_active: 'Leave the meeting first — the meeting is attached to this session.',
@@ -4038,6 +4208,8 @@ async function main() {
4038
4208
  }).action === 'switch';
4039
4209
  }
4040
4210
  async function requestSessionSwitch(target, cwdHint, opts) {
4211
+ // Replies go to the room, or through the caller's `reply` (a call's voice switch reads them back).
4212
+ const sendToFrontend = opts.reply ?? publishToRoom;
4041
4213
  if (!currentLLM || !target)
4042
4214
  return 'reject';
4043
4215
  const cwd = await resolveCwdForSession(target, cwdHint);
@@ -4065,7 +4237,7 @@ async function main() {
4065
4237
  console.log(`🔀 Switch request (${opts.origin}) → ${target.slice(0, 8)}: ${decision.action}/${decision.leave} → ${plan.kind} (${plan.reason}) busy=${JSON.stringify(busy)}`);
4066
4238
  if (plan.kind === 'noop') {
4067
4239
  if (pendingSwitch)
4068
- cancelPendingSwitch('already_live');
4240
+ cancelPendingSwitch('already_live', true, sendToFrontend);
4069
4241
  else
4070
4242
  await sendToFrontend({ type: 'session_switch_cancelled', sessionId: target, reason: 'already_live' });
4071
4243
  return 'noop';
@@ -4118,10 +4290,12 @@ async function main() {
4118
4290
  });
4119
4291
  return 'defer';
4120
4292
  }
4121
- await performSessionSwitch(target, cwd, plan, opts.origin);
4293
+ await performSessionSwitch(target, cwd, plan, opts.origin, opts.reply);
4122
4294
  return 'execute';
4123
4295
  }
4124
- async function performSessionSwitch(target, cwd, plan, origin) {
4296
+ async function performSessionSwitch(target, cwd, plan, origin, reply) {
4297
+ // Replies go to the room, or through the caller's `reply` (a call's voice switch reads them back).
4298
+ const sendToFrontend = reply ?? publishToRoom;
4125
4299
  if (!currentLLM)
4126
4300
  return;
4127
4301
  // Single-flight: only the teardown/arm/notify section holds the guard; the
@@ -4177,7 +4351,7 @@ async function main() {
4177
4351
  statusManager.upsertDispatch(d.id, { dispatchState: 'failed' });
4178
4352
  }
4179
4353
  // 4. Close the old query (idle, or forced) and clear its resume state.
4180
- launchLibraryOnSessionEnd(llmAny.sessionId, llmAny.workingDirectory || workingDir, 'session_switch');
4354
+ launchLibraryOnSessionEnd(warmParkKey(llmAny), llmAny.workingDirectory || workingDir, 'session_switch', [...liveSessionIds(), target]);
4181
4355
  currentLLM.resetForSessionSwitch();
4182
4356
  // 5. Cross-project: the SDK cwd, fast brain and session tail move together.
4183
4357
  if (cwd !== workingDir) {
@@ -4195,7 +4369,7 @@ async function main() {
4195
4369
  hostWorkingDir = cwd;
4196
4370
  }
4197
4371
  // 7. Per-session permission grants don't carry over.
4198
- sessionAlwaysAllowPaths = new Set();
4372
+ sessionAllows = newSessionAllows();
4199
4373
  // 8. Workspace + caches.
4200
4374
  ensureSessionWorkspace(cwd, target);
4201
4375
  invalidateSessionListCache();
@@ -4474,14 +4648,15 @@ async function main() {
4474
4648
  // Apply turbo to the freshly created LLM so the main model also picks it up.
4475
4649
  // PipelineDirectLLM (llmOverride path) wraps its own ClaudeLLM and may not expose setTurbo.
4476
4650
  directLLM?.setTurbo?.(turboMode);
4651
+ // Phone call: talk-only, every tool denied (PHONE_TOOLS_ENABLED). Recomputed on
4652
+ // each session, so a re-attached brain follows whoever holds it now.
4653
+ directLLM?.setPhoneCall?.(inPhoneRoom());
4477
4654
  currentLLM = directLLM;
4478
- // Watch bridge (mobile Track 1): a wrist ack/expiry settles whatever
4479
- // permission is currently pending. Re-registered per session — harmless,
4480
- // the latest closure wins and they all resolve through currentLLM.
4481
- setWatchResultHandler((allow, toolName) => {
4482
- const target = currentLLM?.hasPendingPermission?.() ? currentLLM : warmLLM?.hasPendingPermission?.() ? warmLLM : null;
4483
- if (target) {
4484
- target.respondToPermission(allow);
4655
+ // Watch bridge (mobile Track 1): a wrist ack/expiry settles the request
4656
+ // its push was armed for (requestId), never a newer one. Re-registered per
4657
+ // session — harmless, the latest closure wins.
4658
+ setWatchResultHandler((allow, toolName, requestId) => {
4659
+ if (settlePendingPermission(allow ? 'allow' : 'deny', requestId)) {
4485
4660
  console.log(`⌚️ Watch bridge settled ${toolName}: ${allow ? 'approve' : 'deny'}`);
4486
4661
  }
4487
4662
  else {
@@ -4499,7 +4674,7 @@ async function main() {
4499
4674
  if (resumeSessionId)
4500
4675
  hostSessionId = resumeSessionId;
4501
4676
  // Reset the session always-allow list for each new direct session
4502
- sessionAlwaysAllowPaths = new Set();
4677
+ sessionAllows = newSessionAllows();
4503
4678
  // For resumed sessions, eagerly create workspace (we know the real ID)
4504
4679
  if (resumeSessionId) {
4505
4680
  const workspace = ensureSessionWorkspace(workingDir, resumeSessionId);
@@ -4616,30 +4791,28 @@ async function main() {
4616
4791
  console.log(`⚠️ Permission needed: ${data.toolName}`);
4617
4792
  const toolName = data.toolName;
4618
4793
  const input = data.input || {};
4619
- // Check session always-allow list before showing dialog
4620
- if (toolName === 'Write' || toolName === 'Edit' || toolName === 'MultiEdit') {
4621
- const filePath = String(input?.file_path || '');
4622
- if (filePath && sessionAlwaysAllowPaths.has(filePath)) {
4623
- console.log(`✅ Session always-allow: ${filePath}`);
4624
- directLLM.respondToPermission(true);
4625
- return;
4626
- }
4627
- }
4628
- // Build descriptive message based on tool type
4629
- let description = `I need permission to use ${toolName}.`;
4630
- if (toolName === 'Bash' && input.command) {
4631
- const cmd = String(input.command).substring(0, 60);
4632
- description = `I want to run the command: ${cmd}${String(input.command).length > 60 ? '...' : ''}`;
4633
- }
4634
- else if (toolName === 'Write' && input.file_path) {
4635
- description = `I want to create or overwrite the file: ${input.file_path}`;
4636
- }
4637
- else if (toolName === 'Edit' && input.file_path) {
4638
- description = `I want to edit the file: ${input.file_path}`;
4794
+ // Every answer names this id (settlePendingPermission); a late one never settles a newer request.
4795
+ const requestId = data.requestId;
4796
+ // A phone caller cannot approve tools until PHONE_KEYPAD_APPROVALS_ENABLED is on:
4797
+ // deny straight away. That holds for a brain parked after "keep working" on a
4798
+ // call too, until a browser or app session re-attaches it ('hold' = it waits
4799
+ // for a person; the saved mode and always-allow list never answer it).
4800
+ const phoneRoute = phoneRequestRoute({ liveCall: inPhoneRoom(), parkedFromCall: directLLM === phoneParkedBrain });
4801
+ if (phoneRoute === 'deny') {
4802
+ console.log(`📞 Phone call: denied ${toolName} (keypad approvals are off)`);
4803
+ directLLM.respondToPermission(false, PHONE_PERMISSION_DENIED, requestId);
4804
+ return;
4639
4805
  }
4640
- else if (toolName === 'WebFetch' && input.url) {
4641
- description = `I want to fetch content from: ${input.url}`;
4806
+ const holdForPerson = phoneRoute === 'hold';
4807
+ // Check session always-allow list before showing dialog
4808
+ if (!holdForPerson && isAlwaysAllowed(sessionAllows, toolName, input)) {
4809
+ console.log(`✅ Session always-allow: ${toolName} ${input?.file_path || ''}`);
4810
+ directLLM.respondToPermission(true, undefined, requestId);
4811
+ return;
4642
4812
  }
4813
+ const description = describePermission(toolName, input);
4814
+ // What "Always" covers for this request (the button and the phone prompt say it).
4815
+ const always = alwaysScope(toolName, input).label;
4643
4816
  // Generate diff for Write/Edit/MultiEdit tools
4644
4817
  let diffString;
4645
4818
  if (toolName === 'Write' || toolName === 'Edit' || toolName === 'MultiEdit') {
@@ -4697,19 +4870,46 @@ async function main() {
4697
4870
  diffString = undefined;
4698
4871
  }
4699
4872
  }
4873
+ // The saved approval mode (#364) answers here, for the browser and phone
4874
+ // calls alike; the browser only shows what was approved.
4875
+ const auto = autoApproval(approvalMode, toolName, input, workingDir);
4876
+ if (auto.approve && !holdForPerson) {
4877
+ console.log(`⚡ Auto-approved (${approvalMode}, ${auto.tier}): ${toolName}`);
4878
+ directLLM.respondToPermission(true, undefined, requestId);
4879
+ sendToFrontend({ type: 'permission_auto_approved', requestId, toolName, input: data.input, description, diff: diffString, mode: approvalMode, tier: auto.tier });
4880
+ return;
4881
+ }
4882
+ // Phone call (keypad approvals on): read the request out; the keypad
4883
+ // answers it through settlePendingPermission, never the model (#363).
4884
+ // The keypad and a spoken yes/no answer it only once the caller has heard
4885
+ // the whole prompt (playout finished); a press before then answers nothing.
4886
+ if (inPhoneRoom()) {
4887
+ phonePromptedRequestId = null;
4888
+ phoneSwitchProposal = null; // a "yes" now must never be read as confirming a switch
4889
+ void Promise.resolve(currentSession?.say?.(phoneApprovalPrompt(toolName, input)))
4890
+ .then((handle) => promptHeard(handle))
4891
+ .then((heard) => {
4892
+ // Talked over (interrupted) = not heard: the keypad and "yes" stay inert for it.
4893
+ if (heard && pendingPermissionHolder()?.getPendingPermission?.()?.requestId === requestId)
4894
+ phonePromptedRequestId = requestId;
4895
+ })
4896
+ .catch(() => { });
4897
+ }
4700
4898
  console.log(`🔍 perm payload: diff=${diffString ? `✅ ${diffString.length} chars` : '❌ NONE'} toolName=${toolName}`);
4701
4899
  sendToFrontend({
4702
4900
  type: 'permission_request',
4901
+ requestId,
4703
4902
  toolName: data.toolName,
4704
4903
  input: data.input,
4705
4904
  description,
4905
+ always,
4706
4906
  agentRole: 'direct',
4707
4907
  diff: diffString,
4708
4908
  });
4709
4909
  // Watch bridge (mobile Track 1): mirror this blocking question to the
4710
4910
  // wrist via Pushover. Fire-and-forget — dormant unless PUSHOVER_* env is
4711
4911
  // configured; web-UI answers always win (late wrist acks are no-ops).
4712
- void armPermissionPush({ toolName, description }).catch(() => { });
4912
+ void armPermissionPush({ toolName, description, requestId }).catch(() => { });
4713
4913
  // Speak the descriptive request so user knows to respond
4714
4914
  //do not delete!! Leave this section commented out
4715
4915
  // say permission, request permission, ask for permission with session.say
@@ -4932,8 +5132,7 @@ async function main() {
4932
5132
  last_assistant_message: d.last_assistant_message,
4933
5133
  }));
4934
5134
  // Steward verdict card + sign-off gate note (#221) → chat
4935
- directLLM.events.on('steward_verdict', (v) => sendToFrontend({ type: 'steward_verdict', ...v }));
4936
- directLLM.events.on('steward_gate', (d) => sendToFrontend({ type: 'steward_gate', decision: d.decision, message: d.message }));
5135
+ forwardStewardEvents(directLLM.events);
4937
5136
  directLLM.events.on('tool_blocked', (d) => sendToFrontend({ type: 'tool_blocked', ...d }));
4938
5137
  // Dispatcher v1 — sub-agent started → frontend stop-key signal (Feature A2)
4939
5138
  directLLM.events.on('agent_started', (d) => sendToFrontend({
@@ -5198,6 +5397,19 @@ async function main() {
5198
5397
  livekitState.error = err instanceof Error ? err.message : String(err);
5199
5398
  });
5200
5399
  };
5400
+ /** The LLM holding a pending permission (live session first, then a parked warm brain). */
5401
+ function pendingPermissionHolder() {
5402
+ return currentLLM?.hasPendingPermission?.() ? currentLLM : warmLLM?.hasPendingPermission?.() ? warmLLM : null;
5403
+ }
5404
+ // Settles the ONE request the answer was for (its requestId), on the live
5405
+ // session or a parked warm brain. The one answer path for the browser card,
5406
+ // the watch bridge, the phone keypad and a spoken yes/no. A late answer whose
5407
+ // request is gone settles nothing, never a newer request. 'always_allow' also
5408
+ // adds that request's scope (alwaysScope) to the session's always-allow list.
5409
+ // False when that request is not pending (already answered elsewhere).
5410
+ function settlePendingPermission(answer, requestId) {
5411
+ return answerPending(pendingPermissionHolder(), answer, requestId, sessionAllows);
5412
+ }
5201
5413
  // wireRoomHandlers(room): register EVERY room.on(...) listener onto a fresh
5202
5414
  // Room instance. Called once per session from createRoomSession(). The bodies
5203
5415
  // close over main()-scope state; `room` is the fresh instance passed in.
@@ -5260,6 +5472,19 @@ async function main() {
5260
5472
  room.on(RoomEvent.ParticipantConnected, (p) => { participantConnectedHandler?.(p); });
5261
5473
  room.on(RoomEvent.ParticipantDisconnected, handleParticipantDisconnected);
5262
5474
  room.on(RoomEvent.DataReceived, handleDataReceived);
5475
+ // Phone calls: keypad 2 denies the pending approval; 1 allows only once
5476
+ // PHONE_KEYPAD_APPROVALS_ENABLED is on. Only from the caller in an authorised phone room.
5477
+ // While the emailed code is awaited (#362), every press goes to the code, never to approvals.
5478
+ room.on(RoomEvent.DtmfReceived, (_code, digit, participant) => {
5479
+ if (phoneCodeCaller) {
5480
+ if (participant?.kind === ParticipantKind.SIP && inPhoneRoom() && participant.identity === phoneCodeCaller?.identity)
5481
+ onPhoneCodeDigit(digit);
5482
+ return;
5483
+ }
5484
+ const outcome = handlePhoneKeypad({ sip: participant?.kind === ParticipantKind.SIP, inPhoneRoom: inPhoneRoom(), digit }, (answer) => settlePendingPermission(answer, phonePromptedRequestId));
5485
+ if (outcome !== 'ignored')
5486
+ console.log(`📞 Keypad ${digit}: ${outcome}`);
5487
+ });
5263
5488
  };
5264
5489
  // 0.9.83: handler kept as a named reference so createRoomSession's adopt-sweep
5265
5490
  // can CALL it directly for participants already in the room at join time
@@ -5287,10 +5512,21 @@ async function main() {
5287
5512
  // no controller exists (watch voice alone); joining after the owner it is
5288
5513
  // not adopted, so the owner's session and currentUserId stay intact.
5289
5514
  const joinerUserId = userIdFromMetadata(participant.metadata);
5290
- const join = resolveJoin(participant.identity, joinerUserId, OWNER_USER_ID, controllingUserIdentity);
5515
+ // A phone caller (SIP) is adopted only in a room an authorised phone connect
5516
+ // asked for, and never becomes the controller (it has no data channel).
5517
+ const isPhoneCaller = participant.kind === ParticipantKind.SIP;
5518
+ // While a caller is typing the emailed code (#362) nobody else is adopted.
5519
+ if (isPhoneLinePlayer(participant) || (phoneCodeCaller && participant.identity !== phoneCodeCaller.identity)) {
5520
+ console.log(`📞🔐 ${participant.identity} joined during the code step; not adopting it`);
5521
+ return;
5522
+ }
5523
+ const join = resolveJoin(participant.identity, joinerUserId, OWNER_USER_ID, controllingUserIdentity, { sip: isPhoneCaller, phoneRoom: inPhoneRoom() });
5291
5524
  controllingUserIdentity = join.controller;
5292
5525
  if (!join.adoptSession) {
5293
- if (participant.identity === AGENT_SELF_IDENTITY) {
5526
+ if (isPhoneCaller) {
5527
+ console.warn(`🚫 phone caller ${participant.identity} is not in an authorised phone room; not adopting it`);
5528
+ }
5529
+ else if (participant.identity === AGENT_SELF_IDENTITY) {
5294
5530
  console.log(`⌚ ${participant.identity} joined while ${controllingUserIdentity} controls the session; keeping the owner's voice session`);
5295
5531
  }
5296
5532
  else {
@@ -5298,6 +5534,28 @@ async function main() {
5298
5534
  }
5299
5535
  return;
5300
5536
  }
5537
+ // Emailed code (#362): the caller types it before anything is built for them.
5538
+ const admission = isPhoneCaller
5539
+ ? phoneCallerAdmission({ verifiedRoom: phoneCodeVerifiedRoom, room: activeRoomName, hasSyncToken: !!process.env.OSBORN_SYNC_TOKEN })
5540
+ : 'adopt';
5541
+ if (admission === 'refuse') {
5542
+ // The code is required but this machine cannot check one (no sync token): end the call.
5543
+ console.warn('📞🔐 Emailed code required but OSBORN_SYNC_TOKEN is unset; hanging up');
5544
+ phoneCodeCaller = participant;
5545
+ endPhoneCodeCall(participant, 'no-sync-token');
5546
+ return;
5547
+ }
5548
+ if (admission === 'code') {
5549
+ phoneCodeCaller = participant;
5550
+ phoneCodeBuffer = '';
5551
+ // Ends the call if no code has matched by the end of the window, even if the frontend is gone.
5552
+ if (phoneCodeTimer)
5553
+ clearTimeout(phoneCodeTimer);
5554
+ phoneCodeTimer = setTimeout(() => endPhoneCodeCall(participant, 'timeout'), PHONE_CODE_TIMEOUT_MS);
5555
+ cancelIdleExitTimer();
5556
+ console.log(`📞🔐 Phone caller ${participant.identity} must type the emailed code first; not adopted yet`);
5557
+ return;
5558
+ }
5301
5559
  // A user (re)arriving cancels the meeting leave-grace — the bot stays.
5302
5560
  cancelMeetingLeaveGrace();
5303
5561
  // A user is present — cancel any pending agent-side "alone" leave.
@@ -5384,8 +5642,9 @@ async function main() {
5384
5642
  // client's workingDirectory is only a HINT; for a pre-selected session the
5385
5643
  // agent is AUTHORITATIVE about where that session lives, so `--resume`
5386
5644
  // finds its JSONL instead of coming up in the workspace root — or as a
5387
- // different session — on a stale or empty hint. null = the JSONL is
5388
- // nowhere yet (fresh sprite / new project), so the hint stands.
5645
+ // different session — on a stale or empty hint. Unresolved: an existing
5646
+ // hint is used; a missing one is created only for a new chat
5647
+ // (connectWorkingDir), else the default.
5389
5648
  const wdHint = (typeof metadata.workingDirectory === 'string' && metadata.workingDirectory.length > 0)
5390
5649
  ? metadata.workingDirectory
5391
5650
  : null;
@@ -5398,19 +5657,39 @@ async function main() {
5398
5657
  console.warn('⚠️ connect cwd resolve failed:', e instanceof Error ? e.message : e);
5399
5658
  }
5400
5659
  }
5401
- workingDir = resolvedConnectCwd || wdHint || defaultWorkingDir;
5402
- // Only the HINT is ever created: a resolved cwd can come from an imported
5403
- // session's JSONL and name another machine's path, and creating that tree
5404
- // would boot the agent in an empty dir (scanSlugCwd won't either).
5405
- if (workingDir === wdHint && !existsSync(workingDir)) {
5660
+ const connectDir = connectWorkingDir(resolvedConnectCwd, wdHint, preSelectedSessionId, defaultWorkingDir, existsSync);
5661
+ workingDir = connectDir.dir;
5662
+ if (connectDir.create) {
5406
5663
  mkdirSync(workingDir, { recursive: true });
5407
5664
  console.log(`📁 Created project directory: ${workingDir}`);
5408
5665
  }
5666
+ else if (wdHint && !resolvedConnectCwd && workingDir !== wdHint) {
5667
+ console.warn(`⚠️ Project folder not found, not created: ${wdHint}`);
5668
+ }
5409
5669
  console.log(`📂 Working directory: ${workingDir}`);
5410
5670
  }
5411
5671
  catch (err) {
5412
5672
  console.log('⚠️ Could not parse participant metadata, using config voiceMode:', voiceMode);
5413
5673
  }
5674
+ // A phone call carries no token metadata and has no session picker: it runs
5675
+ // as the machine owner and resumes the most recent session (none = a new one).
5676
+ if (isPhoneCaller) {
5677
+ currentUserId = OWNER_USER_ID;
5678
+ // The sessions a spoken "switch to …" can pick from (the match must be decided before the model turn).
5679
+ listAllClaudeSessions(50).then((all) => { phoneSessions = all.map(sessionListEntry); }).catch(() => { });
5680
+ try {
5681
+ const [latest] = await listAllClaudeSessions(1);
5682
+ const cwd = latest ? await resolveCwdForSession(latest.sessionId, latest.cwd) : null;
5683
+ if (latest && cwd) {
5684
+ preSelectedSessionId = latest.sessionId;
5685
+ workingDir = cwd;
5686
+ }
5687
+ }
5688
+ catch (e) {
5689
+ console.warn('⚠️ phone call: latest session lookup failed:', e instanceof Error ? e.message : e);
5690
+ }
5691
+ console.log(`📞 Phone call: ${preSelectedSessionId ? `resuming ${preSelectedSessionId}` : 'new session'} in ${workingDir}`);
5692
+ }
5414
5693
  ctMark('participant joined + metadata parsed');
5415
5694
  // Sync to outer scope so DataReceived handler can use it
5416
5695
  currentVoiceMode = sessionVoiceMode;
@@ -5464,6 +5743,9 @@ async function main() {
5464
5743
  if (KEEP_WARM && warmLLM && warmSessionId && resumeSessionId && warmSessionId === resumeSessionId && Date.now() < warmExpiry) {
5465
5744
  console.log(`🔥 [KEEP-WARM] re-attaching session ${warmSessionId.slice(0, 8)} — zero replay`);
5466
5745
  const reused = claimWarm();
5746
+ // Re-attached: its requests follow whoever holds it now (a browser or app, or a new call).
5747
+ if (reused === phoneParkedBrain)
5748
+ phoneParkedBrain = null;
5467
5749
  if (pendingSessionClose) {
5468
5750
  try {
5469
5751
  await pendingSessionClose;
@@ -5514,6 +5796,7 @@ async function main() {
5514
5796
  getAndConsumeInterruptionContext,
5515
5797
  getAndConsumeClientNotes,
5516
5798
  onFastBrainResult: onPipelineFastBrainResult,
5799
+ takeVoiceAction: takePhoneVoiceAction,
5517
5800
  });
5518
5801
  // Pass pipelineLLM to createDirectSession so it uses it instead of creating a new ClaudeLLM
5519
5802
  const result = await createDirectSession(resumeSessionId, pipelineLLM);
@@ -5588,7 +5871,10 @@ async function main() {
5588
5871
  if (normalized === lastSentAgentTranscript)
5589
5872
  return;
5590
5873
  console.log(`💬 Agent (${source}, ${text.length} chars): "${text}"`);
5591
- sendToFrontend({ type: 'assistant_response', text });
5874
+ // The resume greeting is spoken, never stored: flagged so the chat cache skips it.
5875
+ sendToFrontend(normalized === RESUME_GREETING
5876
+ ? { type: 'assistant_response', text, greeting: true }
5877
+ : { type: 'assistant_response', text });
5592
5878
  lastSentAgentTranscript = normalized;
5593
5879
  }
5594
5880
  // PRIMARY: conversation_item_added is the authoritative source
@@ -6003,6 +6289,7 @@ async function main() {
6003
6289
  getAndConsumeInterruptionContext,
6004
6290
  getAndConsumeClientNotes,
6005
6291
  onFastBrainResult: onPipelineFastBrainResult,
6292
+ takeVoiceAction: takePhoneVoiceAction,
6006
6293
  });
6007
6294
  result = await createDirectSession(recoverySessionId, pipelineLLM);
6008
6295
  }
@@ -6115,6 +6402,7 @@ async function main() {
6115
6402
  namedAgents: describeAgents(NAMED_AGENTS, userNamedAgents, userAgentRoles, false, userAgentOrigins),
6116
6403
  ...describeRoles(),
6117
6404
  keepWorking: true,
6405
+ approvalMode,
6118
6406
  });
6119
6407
  };
6120
6408
  const readyInterval = setInterval(sendReady, 2000);
@@ -6173,7 +6461,7 @@ async function main() {
6173
6461
  // screen connected (measured). Now the first words play at session-
6174
6462
  // ready (~2s); the prep runs in the background and never blocks voice.
6175
6463
  try {
6176
- await session.say("Welcome back! Ready to continue our previous conversation.");
6464
+ await session.say(RESUME_GREETING);
6177
6465
  }
6178
6466
  catch (err) {
6179
6467
  console.log('⚠️ Pre-selected session greeting failed:', err);
@@ -6199,7 +6487,7 @@ async function main() {
6199
6487
  // transcript rebuilds its "Conversation compacted" rows too.
6200
6488
  const compactions = readCompactionMarkers(preSelectedSessionId, workingDir);
6201
6489
  // Last few cards, without the full return text, so the push stays under the packet limit.
6202
- const steward = readStewardVerdicts(preSelectedSessionId, workingDir).slice(-10).map(({ raw, ...v }) => v);
6490
+ const steward = stewardPushRecords(readStewardRecords(preSelectedSessionId, workingDir));
6203
6491
  if (priorMessages.length > 0) {
6204
6492
  await sendToFrontend({ type: 'prior_messages', sessionId: preSelectedSessionId, messages: priorMessages, compactions, steward });
6205
6493
  console.log(`💬 Sent ${priorMessages.length} prior messages (+${compactions.length} compaction markers) from DB for optimistic UI`);
@@ -6247,8 +6535,8 @@ async function main() {
6247
6535
  })();
6248
6536
  }
6249
6537
  }
6250
- else if (!preSelectedSessionId && hasRecentSession) {
6251
- // No pre-selected session but sessions exist — defer greeting for session gate
6538
+ else if (!preSelectedSessionId && hasRecentSession && !isPhoneCaller) {
6539
+ // No pre-selected session but sessions exist — defer greeting for session gate (a phone call has none)
6252
6540
  console.log('⏳ Deferring greeting until session gate is completed');
6253
6541
  }
6254
6542
  else {
@@ -6262,6 +6550,9 @@ async function main() {
6262
6550
  console.log('⚠️ Greeting failed:', err);
6263
6551
  }
6264
6552
  }
6553
+ // A call has no approvals picker on screen: say which mode is on (#364).
6554
+ if (isPhoneCaller)
6555
+ await greetViaVoice(approvalModeAnnouncement(approvalMode, { toolsOn: PHONE_TOOLS_ENABLED, keypadOn: PHONE_KEYPAD_APPROVALS_ENABLED }));
6265
6556
  }
6266
6557
  catch (err) {
6267
6558
  console.error('❌ Failed to start session:', err);
@@ -6271,6 +6562,16 @@ async function main() {
6271
6562
  // participantConnectedHandler above).
6272
6563
  const handleParticipantDisconnected = (participant) => {
6273
6564
  console.log(`👋 User left: ${participant.identity}`);
6565
+ if (phoneCodeLeave(participant))
6566
+ return;
6567
+ // The caller hung up: the call is over (inPhoneRoom() is false from here, so the
6568
+ // next session gets tools back). Its brain is killed below, not parked, so nothing
6569
+ // it was asked on the call runs after hang-up with tools on.
6570
+ const phoneCallerLeft = participant.kind === ParticipantKind.SIP;
6571
+ if (phoneCallerLeft)
6572
+ phoneRoomName = null;
6573
+ if (phoneCallerLeft)
6574
+ clearPhoneCode();
6274
6575
  if (participant.identity === controllingUserIdentity)
6275
6576
  controllingUserIdentity = null;
6276
6577
  cancelPendingSwitch('participant_disconnected', false);
@@ -6330,17 +6631,22 @@ async function main() {
6330
6631
  // participantConnectedHandler owns continuation (re-attach or, on a
6331
6632
  // mismatch, it frees the warm slot). The warm watchdog is the backstop.
6332
6633
  console.log('🔀 [KEEP-WARM] duplicate-identity eviction — device handoff; parking brain, keeping room');
6634
+ // A call's brain parked here keeps the phone policy too, until re-attached.
6635
+ phoneParkedBrain = phoneCallerLeft ? currentLLM : null;
6333
6636
  parkWarm('duplicate_identity');
6334
6637
  clearPipelineFastBrainSession();
6335
6638
  clearPipelineFastBrainSession();
6336
6639
  }
6337
- else if (KEEP_WARM && currentLLM && currentLLM.sessionId) {
6640
+ else if (KEEP_WARM && currentLLM && warmParkKey(currentLLM) && (!phoneCallerLeft || (keepWorkingRequested && PHONE_TOOLS_ENABLED))) {
6641
+ // (A call parks only for "keep working after I hang up", and only once phone tools are on, #367.)
6338
6642
  // KEEP-WARM network/tab-close drop: park the subprocess instead of killing
6339
6643
  // it so a reconnect within the grace re-attaches with ZERO replay. We
6340
6644
  // STILL run the normal room teardown below — the parked brain is
6341
6645
  // independent of the room (no longer currentLLM, not in slots, so
6342
6646
  // agentsActive() is false), so releaseAgents + fast-leave free the empty
6343
6647
  // room with no billing burn. The warm grace/watchdog free the parked brain.
6648
+ // Parked from a call: its requests keep the phone policy until a browser or app re-attaches.
6649
+ phoneParkedBrain = phoneCallerLeft ? currentLLM : null;
6344
6650
  parkWarm('participant_disconnected');
6345
6651
  clearPipelineFastBrainSession();
6346
6652
  clearPipelineFastBrainSession();
@@ -6392,8 +6698,28 @@ async function main() {
6392
6698
  if (Object.hasOwn(STORE_REPLY_TYPES, data.type) && participant?.identity) {
6393
6699
  await sendToFrontend({ type: STORE_REPLY_TYPES[data.type], success: false, error: 'Another device controls this session' }, participant.identity);
6394
6700
  }
6701
+ // A refused mode change: that tab's picker shows the mode that is really on.
6702
+ if (data.type === 'set_approval_mode' && participant?.identity) {
6703
+ await sendToFrontend({ type: 'approval_mode', mode: approvalMode, error: 'Another device controls this session' }, participant.identity);
6704
+ }
6395
6705
  return;
6396
6706
  }
6707
+ await dispatchAction(data, { sender: participant?.identity });
6708
+ }
6709
+ catch { }
6710
+ };
6711
+ // The room publish, under a name dispatchAction's `reply` can shadow.
6712
+ const publishToRoom = sendToFrontend;
6713
+ /**
6714
+ * Runs one app command (a data-channel message whose sender already passed
6715
+ * checkControlSender). A phone call's voice actions (#367) run
6716
+ * the same code through here, restricted to PHONE_ACTION_TYPES. `reply`
6717
+ * receives what would go to the frontend (default: the room), so a call can
6718
+ * speak the result.
6719
+ */
6720
+ const dispatchAction = async (data, opts = {}) => {
6721
+ const sendToFrontend = opts.reply ?? publishToRoom;
6722
+ try {
6397
6723
  if (data.type === 'claude_auth_code' && pendingAuthSubmitCode) {
6398
6724
  console.log('🔑 Received auth code from frontend');
6399
6725
  sendToFrontend({ type: 'claude_auth_submitting', message: 'Submitting code to Claude CLI...' });
@@ -6443,17 +6769,31 @@ async function main() {
6443
6769
  }
6444
6770
  }
6445
6771
  else if (data.type === 'permission_response') {
6446
- // Handle permission response for direct mode
6447
- if (currentLLM && currentLLM.hasPendingPermission?.()) {
6448
- const allow = data.response === 'allow' || data.response === 'always_allow';
6449
- // Track always_allow paths for this session so future requests auto-approve
6450
- if (data.response === 'always_allow' && data.filePath) {
6451
- sessionAlwaysAllowPaths.add(String(data.filePath));
6452
- console.log(`🔒 Always-allow added for session: ${data.filePath}`);
6453
- }
6454
- currentLLM.respondToPermission(allow);
6455
- console.log(`✅ Permission: ${data.response}`);
6772
+ // Settles only the request the click was for (requestId); the always-allow
6773
+ // scope comes from that pending request, not from anything the client sent.
6774
+ // A client older than request ids sends none: answerPendingWithoutId (live
6775
+ // session's sole pending request only, Always as allow-once).
6776
+ const answer = data.response;
6777
+ const known = answer === 'allow' || answer === 'deny' || answer === 'always_allow';
6778
+ const settled = known && (data.requestId === undefined
6779
+ ? answerPendingWithoutId(currentLLM, warmLLM, answer)
6780
+ : settlePendingPermission(answer, data.requestId));
6781
+ if (settled) {
6782
+ console.log(`✅ Permission: ${answer}${data.requestId === undefined ? ' (no request id: live request, once)' : ''}`);
6783
+ }
6784
+ else {
6785
+ console.log(`🚫 Permission ${answer} ignored: request ${String(data.requestId ?? 'unnamed')} is not pending`);
6786
+ }
6787
+ }
6788
+ else if (data.type === 'set_approval_mode') {
6789
+ // The app's approvals picker (#364). Saved on the agent, so phone calls and
6790
+ // the next browser session use it too. Echoed so every client shows it.
6791
+ if (isApprovalMode(data.mode)) {
6792
+ approvalMode = data.mode;
6793
+ const saved = writeApprovalMode(data.mode);
6794
+ console.log(`🛡️ Approval mode: ${data.mode}${saved ? '' : ' (not saved: config.yaml unreadable)'}`);
6456
6795
  }
6796
+ sendToFrontend({ type: 'approval_mode', mode: approvalMode });
6457
6797
  }
6458
6798
  else if (data.type === 'favorite_changed') {
6459
6799
  // L2b (UI#21): a favorite is a UI action, not something the user said.
@@ -6685,15 +7025,15 @@ async function main() {
6685
7025
  // session_switch_cancelled.
6686
7026
  const sessionId = data.sessionId;
6687
7027
  const hint = typeof data.workingDirectory === 'string' ? data.workingDirectory : undefined;
6688
- await requestSessionSwitch(sessionId, hint, { force: !!data.force, origin: 'switch_session' });
7028
+ await requestSessionSwitch(sessionId, hint, { force: !!data.force, origin: 'switch_session', reply: sendToFrontend });
6689
7029
  }
6690
7030
  else if (data.type === 'get_busy') {
6691
7031
  // End asks before hanging up: a busy agent may keep working (keep_working).
6692
7032
  // Offered only when the hang-up will park the brain (the KEEP_WARM branch of
6693
7033
  // the disconnect handler) and it is working, not just waiting on an approval.
6694
7034
  const busy = currentLLM?.busyState?.();
6695
- const parks = KEEP_WARM && !activeMeetingBotId && !!currentLLM?.sessionId;
6696
- await sendToFrontend({ type: 'busy_state', idle: (busy?.idle ?? true) || !!busy?.permissionPending, capMin: parks ? IDLE_EXIT_GRACE_MS / 60000 : 0, phone: isWatchBridgeEnabled() }, participant?.identity);
7035
+ const parks = KEEP_WARM && !activeMeetingBotId && !!warmParkKey(currentLLM);
7036
+ await sendToFrontend({ type: 'busy_state', idle: (busy?.idle ?? true) || !!busy?.permissionPending, capMin: parks ? IDLE_EXIT_GRACE_MS / 60000 : 0, phone: isWatchBridgeEnabled() }, opts.sender);
6697
7037
  }
6698
7038
  else if (data.type === 'keep_working') {
6699
7039
  keepWorkingRequested = true;
@@ -7278,7 +7618,7 @@ async function main() {
7278
7618
  // Greet immediately, then point agent to session index (no raw JSONL loading)
7279
7619
  if (currentSession && summary) {
7280
7620
  try {
7281
- await currentSession.say("Welcome back! Ready to continue our previous conversation.");
7621
+ await currentSession.say(RESUME_GREETING);
7282
7622
  }
7283
7623
  catch (err) {
7284
7624
  console.log('⚠️ Session gate greeting failed:', err);
@@ -7495,8 +7835,153 @@ async function main() {
7495
7835
  }
7496
7836
  }
7497
7837
  }
7498
- catch { }
7838
+ catch (err) {
7839
+ console.warn(`⚠️ action ${data?.type} failed:`, err instanceof Error ? err.message : err);
7840
+ }
7841
+ };
7842
+ /**
7843
+ * Runs one PHONE_ACTION_TYPES command for a call's voice action and returns
7844
+ * what it sent to the frontend; it still reaches the room, so an open app
7845
+ * stays in step. Only the SIP caller's speech reaches it (takePhoneVoiceAction):
7846
+ * there is no HTTP route, so the agent's own tools cannot change approvals.
7847
+ */
7848
+ const runAppAction = async (data) => {
7849
+ if (!PHONE_ACTION_TYPES.has(String(data?.type)))
7850
+ throw new Error(`not an allowed action: ${String(data?.type)}`);
7851
+ const replies = [];
7852
+ await dispatchAction(data, { reply: async (d, to) => { replies.push(d); return publishToRoom(d, to); } });
7853
+ return replies;
7499
7854
  };
7855
+ // Phone voice actions (#367): on a call, a short command ("stop that", "what
7856
+ // are you doing?", "switch to my billing project", a yes/no to a pending
7857
+ // approval) runs the app's own action instead of a model turn, and the result
7858
+ // is spoken. The model never answers an approval.
7859
+ function takePhoneVoiceAction(text) {
7860
+ if (!inPhoneRoom())
7861
+ return false;
7862
+ // A yes/no counts only for the request the caller heard read out.
7863
+ const heard = !!phonePromptedRequestId && pendingPermissionHolder()?.getPendingPermission?.()?.requestId === phonePromptedRequestId;
7864
+ // A proposed switch waits one turn for its yes/no (and a minute at most).
7865
+ const switchProposed = !!phoneSwitchProposal && Date.now() < phoneSwitchProposal.expires;
7866
+ const action = matchVoiceAction(text, {
7867
+ permissionPending: heard, anyPermissionPending: !!pendingPermissionHolder(), switchProposed, sessions: phoneSessions,
7868
+ });
7869
+ // Any other turn drops the proposal: only the very next yes switches.
7870
+ if (action?.kind !== 'confirm_switch' && action?.kind !== 'switch')
7871
+ phoneSwitchProposal = null;
7872
+ if (!action)
7873
+ return false;
7874
+ console.log(`📞 Voice action: ${JSON.stringify(action)}`);
7875
+ void runPhoneVoiceAction(action)
7876
+ .then((line) => currentSession?.say?.(line))
7877
+ .catch((e) => console.warn('⚠️ voice action failed:', e instanceof Error ? e.message : e));
7878
+ return true;
7879
+ }
7880
+ async function runPhoneVoiceAction(action) {
7881
+ const llmNow = currentLLM;
7882
+ switch (action.kind) {
7883
+ case 'answer': {
7884
+ if (!phoneAnswerAllowed(action.answer))
7885
+ return "I can't approve actions on a call yet. Approve it in the app, or say no to deny it.";
7886
+ const requestId = phonePromptedRequestId;
7887
+ if (!requestId || pendingPermissionHolder()?.getPendingPermission?.()?.requestId !== requestId)
7888
+ return 'That request is no longer waiting.';
7889
+ await runAppAction({ type: 'permission_response', response: action.answer, requestId });
7890
+ return action.answer === 'allow' ? 'Allowed.' : 'Denied.';
7891
+ }
7892
+ case 'mode': {
7893
+ if (!phoneMayChangeMode(approvalMode, action.mode, PHONE_KEYPAD_APPROVALS_ENABLED)) {
7894
+ return `${approvalModeLabel(approvalMode)} is on. On a call I can only make approvals stricter for now; change it in the app.`;
7895
+ }
7896
+ await runAppAction({ type: 'set_approval_mode', mode: action.mode });
7897
+ return sayModeChanged(approvalMode);
7898
+ }
7899
+ case 'status': {
7900
+ const busy = llmNow?.busyState?.() ?? { turnInFlight: false, compacting: false };
7901
+ const pending = pendingPermissionHolder()?.getPendingPermission?.();
7902
+ return sayStatus({
7903
+ turnInFlight: !!busy.turnInFlight, compacting: !!busy.compacting,
7904
+ tasks: llmNow?.getRunningTasks?.() ?? [],
7905
+ pending: pending ? speakablePermission(pending.toolName, pending.input) : null,
7906
+ keypad: PHONE_KEYPAD_APPROVALS_ENABLED,
7907
+ heard: !!pending && pending.requestId === phonePromptedRequestId,
7908
+ });
7909
+ }
7910
+ case 'stop': {
7911
+ if (action.agent) {
7912
+ const want = action.agent.replace(/\s+/g, '').toLowerCase();
7913
+ const d = statusManager.getActiveDispatches().find((x) => (x.subagentType || '').replace(/[\s_-]+/g, '').toLowerCase().includes(want));
7914
+ if (!d)
7915
+ return `No ${action.agent} agent is running.`;
7916
+ const replies = await runAppAction({ type: 'stop_dispatch', agentId: d.id });
7917
+ return replies.find((r) => r.type === 'agent_stopped')?.stopped ? `Stopped the ${d.subagentType} agent.` : `I couldn't stop the ${d.subagentType} agent.`;
7918
+ }
7919
+ // The main turn: the same graceful interrupt the fast brain uses (the subprocess stays up).
7920
+ const stopped = await (llmNow?.interruptAgent?.() ?? llmNow?.interruptQuery?.());
7921
+ return stopped === false ? "I wasn't doing anything to stop." : 'Stopped.';
7922
+ }
7923
+ case 'sessions': {
7924
+ const replies = await runAppAction({ type: 'list_sessions' });
7925
+ const sessions = replies.find((r) => r.type === 'sessions_list')?.sessions ?? [];
7926
+ phoneSessions = sessions;
7927
+ return saySessions(sessions);
7928
+ }
7929
+ case 'blocked': {
7930
+ if (action.what === 'switch')
7931
+ phoneSwitchProposal = null;
7932
+ const pending = pendingPermissionHolder()?.getPendingPermission?.();
7933
+ const heard = !!pending && pending.requestId === phonePromptedRequestId;
7934
+ return sayBlocked(action.what, pending ? speakablePermission(pending.toolName, pending.input) : null, PHONE_KEYPAD_APPROVALS_ENABLED, heard);
7935
+ }
7936
+ case 'switch': {
7937
+ // matchVoiceAction only returns a switch whose name picked a session by
7938
+ // title (pickSession). Nothing switches until the caller says yes.
7939
+ const target = action.target;
7940
+ const name = target.title || action.query;
7941
+ if (target.sessionId === llmNow?.sessionId) {
7942
+ phoneSwitchProposal = null;
7943
+ return `You're already in ${name}.`;
7944
+ }
7945
+ phoneSwitchProposal = { target, expires: Date.now() + 60_000 };
7946
+ return `Switch to ${name}?`;
7947
+ }
7948
+ case 'cancel_switch': {
7949
+ phoneSwitchProposal = null;
7950
+ return 'OK, staying here.';
7951
+ }
7952
+ case 'confirm_switch': {
7953
+ const target = phoneSwitchProposal?.target;
7954
+ phoneSwitchProposal = null;
7955
+ if (!target)
7956
+ return 'There is nothing to switch to.';
7957
+ const name = target.title || 'that session';
7958
+ // Speak what the switch really did (done, pending, or why it was refused).
7959
+ const replies = await runAppAction({ type: 'switch_session', sessionId: target.sessionId, workingDirectory: target.cwd });
7960
+ // Replies about this target, plus an already_live cancel (the target was live; a pending switch elsewhere was dropped).
7961
+ return saySwitchOutcome(replies.filter((r) => r?.sessionId === target.sessionId || (r?.type === 'session_switch_cancelled' && r?.reason === 'already_live')), name);
7962
+ }
7963
+ case 'outputs': {
7964
+ const sessionId = llmNow?.sessionId;
7965
+ if (!sessionId)
7966
+ return "This session hasn't made any files yet.";
7967
+ const replies = await runAppAction({ type: 'get_session_artifacts', sessionId });
7968
+ return sayOutputs(replies.find((r) => r.type === 'session_artifacts')?.artifacts ?? []);
7969
+ }
7970
+ case 'keep_working': {
7971
+ // A hang-up kills the call's brain unless phone tools are on (#362):
7972
+ // work started on a call must not run on with tools after it ends.
7973
+ if (!PHONE_TOOLS_ENABLED)
7974
+ return "On a call I can't keep working after you hang up yet. Use the app for that.";
7975
+ const busy = (await runAppAction({ type: 'get_busy' })).find((r) => r.type === 'busy_state');
7976
+ if (!busy || busy.idle)
7977
+ return "I'm not working on anything, so there's nothing to keep going.";
7978
+ if (!busy.capMin)
7979
+ return "I can't keep working after this call on this machine.";
7980
+ await runAppAction({ type: 'keep_working' });
7981
+ return `OK. Hang up whenever you like. I'll keep working for up to ${busy.capMin} minutes${busy.phone ? " and let you know when I'm done" : ''}.`;
7982
+ }
7983
+ }
7984
+ }
7500
7985
  // ============================================================
7501
7986
  // Room session lifecycle (0.9.83): fresh Room per user session
7502
7987
  // ============================================================
@@ -7630,6 +8115,8 @@ async function main() {
7630
8115
  // Drop the reference immediately so nothing (handlers, sweeps) touches it.
7631
8116
  activeRoom = null;
7632
8117
  activeRoomName = null;
8118
+ phoneRoomName = null;
8119
+ clearPhoneCode();
7633
8120
  if (aloneTimer) {
7634
8121
  clearTimeout(aloneTimer);
7635
8122
  aloneTimer = null;
@@ -7677,7 +8164,8 @@ async function main() {
7677
8164
  t.addGrant({ roomJoin: true, room: activeRoomName, canPublish: false, canSubscribe: true, canPublishData: false });
7678
8165
  return { token: await t.toJwt(), url: process.env.LIVEKIT_URL || '', room: activeRoomName };
7679
8166
  };
7680
- connectRoomHook = async () => {
8167
+ connectRoomHook = async (phoneRoom) => {
8168
+ const busy = () => Object.assign(new Error('busy: the agent is in another session'), { code: 'busy' });
7681
8169
  intentionalLeave = false;
7682
8170
  cancelIdleExitTimer();
7683
8171
  // CONNECT TIMING: stamp the server's request-incoming moment (the user asked
@@ -7687,17 +8175,36 @@ async function main() {
7687
8175
  // Idempotency: an active session with a user present is reused (return its
7688
8176
  // room name). An active-but-empty session (agent joined, user never showed,
7689
8177
  // or a stale race) is torn down and replaced with a fresh one.
8178
+ const plan = planConnectRoom({
8179
+ activeRoomName: activeRoom ? activeRoomName : null,
8180
+ occupied: !!activeRoom && activeRoom.remoteParticipants.size > 0,
8181
+ // A caller's room is never handed to a browser, even once the caller has left.
8182
+ phoneCallLive: inPhoneRoom() || isPhoneRoomName(activeRoomName),
8183
+ phoneRoom,
8184
+ });
8185
+ if (plan === 'busy') {
8186
+ console.log(`🔌 /connect-room — busy: ${phoneRoom ? 'a user is in another room' : 'a phone call is live'} (${activeRoomName})`);
8187
+ throw busy();
8188
+ }
8189
+ if (plan === 'reuse') {
8190
+ console.log(`🔌 /connect-room — already connected with a user present, reusing ${activeRoomName}`);
8191
+ return activeRoomName;
8192
+ }
7690
8193
  if (activeRoom && activeRoomName) {
7691
- if (activeRoom.remoteParticipants.size > 0) {
7692
- console.log(`🔌 /connect-room — already connected with a user present, reusing ${activeRoomName}`);
7693
- return activeRoomName;
7694
- }
7695
8194
  console.log('🔌 /connect-room — active room is empty; tearing down + creating fresh');
7696
8195
  await destroyRoomSession('connect-room replacing empty session');
7697
8196
  }
7698
- const targetRoomName = buildRoomName();
7699
- console.log(`🔌 /connect-room — creating fresh room session: ${targetRoomName}`);
8197
+ const targetRoomName = phoneRoom || buildRoomName();
8198
+ if (phoneRoom)
8199
+ phoneRoomName = phoneRoom;
8200
+ console.log(`🔌 /connect-room — creating fresh room session: ${targetRoomName}${phoneRoom ? ' (phone call)' : ''}`);
7700
8201
  await createRoomSession(targetRoomName);
8202
+ // A concurrent browser connect won the in-flight join: that room is not the caller's.
8203
+ if (phoneRoom && activeRoomName !== phoneRoom)
8204
+ throw busy();
8205
+ // A browser connect that awaited an in-flight phone join: never hand it the caller's room.
8206
+ if (!phoneRoom && isPhoneRoomName(activeRoomName))
8207
+ throw busy();
7701
8208
  // Return the room the agent actually joined. When a concurrent /connect-room
7702
8209
  // call awaited an in-flight session, activeRoomName is the first call's room
7703
8210
  // name — which differs from targetRoomName generated here. Always use the