osborn 0.9.291 → 0.9.293
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/browser-apply/SKILL.md +5 -4
- package/.claude/skills/browser-apply/candidate.example.env +4 -1
- package/.claude/skills/browser-apply/fill.mjs +13 -2
- package/.claude/skills/meetings/SKILL.md +26 -7
- package/.env.example +6 -0
- package/dist/agent-store.d.ts +6 -0
- package/dist/agent-store.js +36 -6
- package/dist/approval-policy.d.ts +99 -0
- package/dist/approval-policy.js +196 -0
- package/dist/claude-llm.d.ts +3 -2
- package/dist/claude-llm.js +49 -19
- package/dist/config.d.ts +12 -16
- package/dist/config.js +80 -22
- package/dist/content/compaction-lens-worker.d.ts +5 -0
- package/dist/content/compaction-lens-worker.js +78 -7
- package/dist/content/content-llm.d.ts +14 -3
- package/dist/content/content-llm.js +33 -142
- package/dist/content/lens-db.d.ts +16 -5
- package/dist/content/lens-db.js +58 -11
- package/dist/content/lens-ingest.d.ts +1 -0
- package/dist/content/lens-ingest.js +1 -1
- package/dist/content/lens-launch.d.ts +42 -1
- package/dist/content/lens-launch.js +202 -40
- package/dist/content/lens-library-digest.d.ts +85 -0
- package/dist/content/lens-library-digest.js +305 -0
- package/dist/content/lens-library-index.d.ts +14 -3
- package/dist/content/lens-library-index.js +35 -8
- package/dist/content/lens-library-select.d.ts +1 -1
- package/dist/content/lens-library-select.js +1 -1
- package/dist/content/lens-library-sweep.d.ts +36 -0
- package/dist/content/lens-library-sweep.js +331 -0
- package/dist/content/lens-library.d.ts +29 -0
- package/dist/content/lens-library.js +130 -20
- package/dist/content/lens-model.d.ts +4 -0
- package/dist/content/lens-model.js +5 -0
- package/dist/content/lens-paths.d.ts +72 -0
- package/dist/content/lens-paths.js +248 -5
- package/dist/content/period-run.js +2 -2
- package/dist/content/secret-rules.d.ts +51 -0
- package/dist/content/secret-rules.js +185 -0
- package/dist/content/transcript-sanitizer.d.ts +1 -41
- package/dist/content/transcript-sanitizer.js +4 -171
- package/dist/data-sender-auth.d.ts +43 -6
- package/dist/data-sender-auth.js +61 -45
- package/dist/env-keys.d.ts +10 -2
- package/dist/env-keys.js +26 -5
- package/dist/index.js +499 -106
- package/dist/phone-code.d.ts +76 -0
- package/dist/phone-code.js +124 -0
- package/dist/phone-voice-actions.d.ts +132 -0
- package/dist/phone-voice-actions.js +223 -0
- package/dist/pipeline-direct-llm.d.ts +7 -1
- package/dist/pipeline-direct-llm.js +12 -1
- package/dist/prompts/library-digest.md +11 -0
- package/dist/prompts.js +2 -2
- package/dist/pushover.d.ts +2 -1
- package/dist/pushover.js +7 -6
- package/dist/risk-tier.d.ts +14 -0
- package/dist/risk-tier.js +140 -0
- package/dist/session-store.d.ts +1 -0
- package/dist/session-store.js +3 -2
- package/dist/session-switch.d.ts +22 -7
- package/dist/session-switch.js +58 -24
- package/dist/steward-verdict.d.ts +16 -3
- package/dist/steward-verdict.js +37 -18
- package/dist/watch-gateway.js +3 -1
- package/package.json +1 -1
- package/dist/bridge-llm.d.ts +0 -22
- package/dist/bridge-llm.js +0 -39
- package/dist/codex-handler.d.ts +0 -38
- package/dist/codex-handler.js +0 -83
- package/dist/codex-llm.d.ts +0 -40
- package/dist/codex-llm.js +0 -144
- package/dist/fast-brain.d.ts +0 -176
- package/dist/fast-brain.js +0 -1887
- package/dist/index-3-2-26-legacy.d.ts +0 -1
- package/dist/index-3-2-26-legacy.js +0 -2233
- package/dist/leagcyprompts2.d.ts +0 -0
- package/dist/leagcyprompts2.js +0 -573
- package/dist/prompts-2-25-26.d.ts +0 -0
- package/dist/prompts-2-25-26.js +0 -518
- package/dist/prompts-3-2-26.d.ts +0 -78
- package/dist/prompts-3-2-26.js +0 -1319
- package/dist/summary-index.d.ts +0 -90
- package/dist/summary-index.js +0 -585
package/dist/index.js
CHANGED
|
@@ -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
49
|
import { DIRECT_MODE_PROMPT, PHONE_PERMISSION_DENIED } from './prompts.js';
|
|
50
|
-
import { MCP_CATALOG } from './config.js';
|
|
51
|
-
import { launchLibraryOnSessionEnd,
|
|
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 {
|
|
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, CONNECT_ROOM_MAX_BODY, checkControlSender, handlePhoneKeypad, isPhoneCallLive, isPhoneRoomName,
|
|
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
|
|
154
|
-
const name =
|
|
155
|
-
const
|
|
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 } : {}) });
|
|
@@ -706,7 +710,7 @@ function startApiServer(workingDir, port) {
|
|
|
706
710
|
// pass their own cwd; honoured only if the session really lives there.
|
|
707
711
|
const readDir = sessionMessagesDir(sessionId, url.searchParams.get('workingDirectory'), workingDir, sessionExists);
|
|
708
712
|
const compactions = readCompactionMarkers(sessionId, readDir);
|
|
709
|
-
const steward =
|
|
713
|
+
const steward = readStewardRecords(sessionId, readDir);
|
|
710
714
|
const dbPath = storeExists(sessionId, readDir);
|
|
711
715
|
if (!dbPath) {
|
|
712
716
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
@@ -912,12 +916,13 @@ function startApiServer(workingDir, port) {
|
|
|
912
916
|
status: 'ok',
|
|
913
917
|
workingDir,
|
|
914
918
|
version,
|
|
915
|
-
// Library: is it on, can it call the model, does it reach /library
|
|
919
|
+
// Library: is it on, can it call the model, does it reach /library. Public: counts, times and codes only.
|
|
916
920
|
library: {
|
|
917
921
|
enabled: isContentLensEnabled(),
|
|
918
922
|
modelKey: !!(process.env.OPENROUTER_API_KEY || '').trim(),
|
|
919
923
|
ingest: (() => { const c = resolveIngestConfig(); return 'reason' in c ? (c.reason === 'no-key' ? 'no-anon-key' : c.reason) : 'on'; })(),
|
|
920
|
-
|
|
924
|
+
// Last launches, the worker's step outcome, the sweep's backlog and result, the last worker failure.
|
|
925
|
+
...librarySweepHealth(),
|
|
921
926
|
},
|
|
922
927
|
// WHERE this machine physically runs — Fly sets FLY_REGION (e.g. 'ord').
|
|
923
928
|
// The dashboard maps it to a city ("Chicago") so the user always knows
|
|
@@ -1025,7 +1030,8 @@ function startApiServer(workingDir, port) {
|
|
|
1025
1030
|
connectRoomHook(phoneRoom)
|
|
1026
1031
|
.then((roomName) => {
|
|
1027
1032
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1028
|
-
|
|
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 } : {}) }));
|
|
1029
1035
|
})
|
|
1030
1036
|
.catch((e) => {
|
|
1031
1037
|
if (e?.code === 'busy') {
|
|
@@ -2233,16 +2239,6 @@ async function main() {
|
|
|
2233
2239
|
console.error('\nSet these in your .env file or environment.');
|
|
2234
2240
|
process.exit(1);
|
|
2235
2241
|
}
|
|
2236
|
-
// Non-fatal diagnostic: surface any OTHER expected-required keys that are
|
|
2237
|
-
// missing (per the shared env-keys.ts manifest — mirror of the frontend's
|
|
2238
|
-
// platform-env.ts injection spec). The LiveKit trio above is the only
|
|
2239
|
-
// hard-fail; the rest degrade gracefully (a plugin falls back, a feature
|
|
2240
|
-
// no-ops), so we log rather than exit — but a missing OPENAI/DEEPGRAM key is
|
|
2241
|
-
// the usual root cause of "voice works but STT/realtime is dead", worth naming.
|
|
2242
|
-
const missingEnv = missingRequiredEnv().filter((k) => !['LIVEKIT_URL', 'LIVEKIT_API_KEY', 'LIVEKIT_API_SECRET'].includes(k));
|
|
2243
|
-
if (missingEnv.length > 0) {
|
|
2244
|
-
console.warn(`⚠️ Missing expected env keys (non-fatal): ${missingEnv.join(', ')}`);
|
|
2245
|
-
}
|
|
2246
2242
|
// Parse CLI args
|
|
2247
2243
|
const cliArgs = parseArgs();
|
|
2248
2244
|
// Load configuration
|
|
@@ -2292,6 +2288,11 @@ async function main() {
|
|
|
2292
2288
|
const voiceMode = getVoiceMode(config);
|
|
2293
2289
|
const directConfig = getDirectConfig(config);
|
|
2294
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
|
+
}
|
|
2295
2296
|
// Determine room code. STABLE PER MACHINE, derived from identity we
|
|
2296
2297
|
// already have: the Fly app name (one app per user). No new storage, no
|
|
2297
2298
|
// rotation — the same user always lands in the same room, and the room
|
|
@@ -2378,6 +2379,99 @@ async function main() {
|
|
|
2378
2379
|
// (cleared when the caller leaves or the room session ends).
|
|
2379
2380
|
let phoneRoomName = null;
|
|
2380
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
|
+
};
|
|
2381
2475
|
// Watch gateway (mobile Track 2): bridges the native watchOS app's WS audio
|
|
2382
2476
|
// + JSON into the user's LiveKit room via rtc-node. Opt-in — dormant unless
|
|
2383
2477
|
// WATCH_GATEWAY=1 (port WATCH_GATEWAY_PORT, default 8742).
|
|
@@ -2619,6 +2713,15 @@ async function main() {
|
|
|
2619
2713
|
let warmGraceTimer = null;
|
|
2620
2714
|
let warmWatchdog = null;
|
|
2621
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();
|
|
2622
2725
|
// The outbound events createDirectSession() OWNS the wiring for. Stripped on
|
|
2623
2726
|
// every (re-)wire so a re-attached subprocess ends up with exactly one
|
|
2624
2727
|
// listener per event — no double TTS, no stacked handlers. Only OUR event
|
|
@@ -2923,9 +3026,20 @@ async function main() {
|
|
|
2923
3026
|
console.error(`❌ killCurrentLLM(${reason}) failed:`, err instanceof Error ? err.message : err);
|
|
2924
3027
|
}
|
|
2925
3028
|
finally {
|
|
2926
|
-
launchLibraryOnSessionEnd(currentLLM
|
|
3029
|
+
launchLibraryOnSessionEnd(warmParkKey(currentLLM), currentLLM?.workingDirectory || workingDir, reason);
|
|
2927
3030
|
}
|
|
2928
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
|
+
}
|
|
2929
3043
|
// ============================================================
|
|
2930
3044
|
// SLICE 1: spawnBackgroundSession
|
|
2931
3045
|
// Creates a fully headless ClaudeLLM subprocess that resumes an
|
|
@@ -3012,6 +3126,7 @@ async function main() {
|
|
|
3012
3126
|
// Wire up the LLM's internal EventEmitter so hook-emitted events also flow.
|
|
3013
3127
|
bgLLM.events.on('session_id', (data) => bgEmitter.emit('session_id', data));
|
|
3014
3128
|
bgLLM.events.on('tool_blocked', (data) => bgEmitter.emit('tool_blocked', data));
|
|
3129
|
+
forwardStewardEvents(bgLLM.events, slotId);
|
|
3015
3130
|
// Build minimal sdkOptions for the headless cold start.
|
|
3016
3131
|
// resume: sessionId brings up real prior context from JSONL.
|
|
3017
3132
|
// env: CLAUDE_CODE_DISABLE_AUTO_MEMORY prevents concurrent subprocesses
|
|
@@ -3063,8 +3178,20 @@ async function main() {
|
|
|
3063
3178
|
}
|
|
3064
3179
|
let localParticipant = null;
|
|
3065
3180
|
let agentState = 'initializing';
|
|
3066
|
-
// Session-level always-allow list
|
|
3067
|
-
let
|
|
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();
|
|
3068
3195
|
let userState = 'listening'; // Track user speech state for queue safety
|
|
3069
3196
|
let currentVoiceMode = voiceMode; // Track active voice mode for data handlers
|
|
3070
3197
|
// Authenticated Supabase userId from participant metadata. Used to scope
|
|
@@ -4016,6 +4143,8 @@ async function main() {
|
|
|
4016
4143
|
function resolveCwdForSession(sessionId, hint) {
|
|
4017
4144
|
return resolveSessionCwd(sessionId, hint, workingDir, {
|
|
4018
4145
|
exists: (id, wd) => sessionExists(id, wd),
|
|
4146
|
+
recordedCwd: (id, wd) => extractCwd(join(getSessionDir(wd), `${id}.jsonl`)),
|
|
4147
|
+
dirExists: (p) => existsSync(p),
|
|
4019
4148
|
lookupCwd: (id) => scanSlugCwd(id, getClaudeProjectsDir(), {
|
|
4020
4149
|
readdir: (d) => readdirSync(d), exists: (p) => existsSync(p),
|
|
4021
4150
|
decodeSlug: (s) => slugToPath(s), readCwd: (p) => extractCwd(p),
|
|
@@ -4037,7 +4166,8 @@ async function main() {
|
|
|
4037
4166
|
const b = slot.llm.busyState?.();
|
|
4038
4167
|
return b && !b.idle ? 'busy' : 'idle';
|
|
4039
4168
|
}
|
|
4040
|
-
|
|
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) {
|
|
4041
4171
|
if (!pendingSwitch)
|
|
4042
4172
|
return;
|
|
4043
4173
|
const { target, timer } = pendingSwitch;
|
|
@@ -4045,7 +4175,7 @@ async function main() {
|
|
|
4045
4175
|
pendingSwitch = null;
|
|
4046
4176
|
console.log(`↩️ Pending switch to ${target.slice(0, 8)} cancelled (${reason})`);
|
|
4047
4177
|
if (notify)
|
|
4048
|
-
void
|
|
4178
|
+
void reply({ type: 'session_switch_cancelled', sessionId: target, reason });
|
|
4049
4179
|
}
|
|
4050
4180
|
const SWITCH_REJECT_COPY = {
|
|
4051
4181
|
meeting_active: 'Leave the meeting first — the meeting is attached to this session.',
|
|
@@ -4078,6 +4208,8 @@ async function main() {
|
|
|
4078
4208
|
}).action === 'switch';
|
|
4079
4209
|
}
|
|
4080
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;
|
|
4081
4213
|
if (!currentLLM || !target)
|
|
4082
4214
|
return 'reject';
|
|
4083
4215
|
const cwd = await resolveCwdForSession(target, cwdHint);
|
|
@@ -4105,7 +4237,7 @@ async function main() {
|
|
|
4105
4237
|
console.log(`🔀 Switch request (${opts.origin}) → ${target.slice(0, 8)}: ${decision.action}/${decision.leave} → ${plan.kind} (${plan.reason}) busy=${JSON.stringify(busy)}`);
|
|
4106
4238
|
if (plan.kind === 'noop') {
|
|
4107
4239
|
if (pendingSwitch)
|
|
4108
|
-
cancelPendingSwitch('already_live');
|
|
4240
|
+
cancelPendingSwitch('already_live', true, sendToFrontend);
|
|
4109
4241
|
else
|
|
4110
4242
|
await sendToFrontend({ type: 'session_switch_cancelled', sessionId: target, reason: 'already_live' });
|
|
4111
4243
|
return 'noop';
|
|
@@ -4158,10 +4290,12 @@ async function main() {
|
|
|
4158
4290
|
});
|
|
4159
4291
|
return 'defer';
|
|
4160
4292
|
}
|
|
4161
|
-
await performSessionSwitch(target, cwd, plan, opts.origin);
|
|
4293
|
+
await performSessionSwitch(target, cwd, plan, opts.origin, opts.reply);
|
|
4162
4294
|
return 'execute';
|
|
4163
4295
|
}
|
|
4164
|
-
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;
|
|
4165
4299
|
if (!currentLLM)
|
|
4166
4300
|
return;
|
|
4167
4301
|
// Single-flight: only the teardown/arm/notify section holds the guard; the
|
|
@@ -4217,7 +4351,7 @@ async function main() {
|
|
|
4217
4351
|
statusManager.upsertDispatch(d.id, { dispatchState: 'failed' });
|
|
4218
4352
|
}
|
|
4219
4353
|
// 4. Close the old query (idle, or forced) and clear its resume state.
|
|
4220
|
-
launchLibraryOnSessionEnd(llmAny
|
|
4354
|
+
launchLibraryOnSessionEnd(warmParkKey(llmAny), llmAny.workingDirectory || workingDir, 'session_switch', [...liveSessionIds(), target]);
|
|
4221
4355
|
currentLLM.resetForSessionSwitch();
|
|
4222
4356
|
// 5. Cross-project: the SDK cwd, fast brain and session tail move together.
|
|
4223
4357
|
if (cwd !== workingDir) {
|
|
@@ -4235,7 +4369,7 @@ async function main() {
|
|
|
4235
4369
|
hostWorkingDir = cwd;
|
|
4236
4370
|
}
|
|
4237
4371
|
// 7. Per-session permission grants don't carry over.
|
|
4238
|
-
|
|
4372
|
+
sessionAllows = newSessionAllows();
|
|
4239
4373
|
// 8. Workspace + caches.
|
|
4240
4374
|
ensureSessionWorkspace(cwd, target);
|
|
4241
4375
|
invalidateSessionListCache();
|
|
@@ -4518,11 +4652,11 @@ async function main() {
|
|
|
4518
4652
|
// each session, so a re-attached brain follows whoever holds it now.
|
|
4519
4653
|
directLLM?.setPhoneCall?.(inPhoneRoom());
|
|
4520
4654
|
currentLLM = directLLM;
|
|
4521
|
-
// Watch bridge (mobile Track 1): a wrist ack/expiry settles
|
|
4522
|
-
//
|
|
4523
|
-
// the latest closure wins
|
|
4524
|
-
setWatchResultHandler((allow, toolName) => {
|
|
4525
|
-
if (settlePendingPermission(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)) {
|
|
4526
4660
|
console.log(`⌚️ Watch bridge settled ${toolName}: ${allow ? 'approve' : 'deny'}`);
|
|
4527
4661
|
}
|
|
4528
4662
|
else {
|
|
@@ -4540,7 +4674,7 @@ async function main() {
|
|
|
4540
4674
|
if (resumeSessionId)
|
|
4541
4675
|
hostSessionId = resumeSessionId;
|
|
4542
4676
|
// Reset the session always-allow list for each new direct session
|
|
4543
|
-
|
|
4677
|
+
sessionAllows = newSessionAllows();
|
|
4544
4678
|
// For resumed sessions, eagerly create workspace (we know the real ID)
|
|
4545
4679
|
if (resumeSessionId) {
|
|
4546
4680
|
const workspace = ensureSessionWorkspace(workingDir, resumeSessionId);
|
|
@@ -4657,36 +4791,28 @@ async function main() {
|
|
|
4657
4791
|
console.log(`⚠️ Permission needed: ${data.toolName}`);
|
|
4658
4792
|
const toolName = data.toolName;
|
|
4659
4793
|
const input = data.input || {};
|
|
4660
|
-
//
|
|
4661
|
-
|
|
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') {
|
|
4662
4802
|
console.log(`📞 Phone call: denied ${toolName} (keypad approvals are off)`);
|
|
4663
|
-
directLLM.respondToPermission(false, PHONE_PERMISSION_DENIED);
|
|
4803
|
+
directLLM.respondToPermission(false, PHONE_PERMISSION_DENIED, requestId);
|
|
4664
4804
|
return;
|
|
4665
4805
|
}
|
|
4806
|
+
const holdForPerson = phoneRoute === 'hold';
|
|
4666
4807
|
// Check session always-allow list before showing dialog
|
|
4667
|
-
if (
|
|
4668
|
-
|
|
4669
|
-
|
|
4670
|
-
|
|
4671
|
-
directLLM.respondToPermission(true);
|
|
4672
|
-
return;
|
|
4673
|
-
}
|
|
4674
|
-
}
|
|
4675
|
-
// Build descriptive message based on tool type
|
|
4676
|
-
let description = `I need permission to use ${toolName}.`;
|
|
4677
|
-
if (toolName === 'Bash' && input.command) {
|
|
4678
|
-
const cmd = String(input.command).substring(0, 60);
|
|
4679
|
-
description = `I want to run the command: ${cmd}${String(input.command).length > 60 ? '...' : ''}`;
|
|
4680
|
-
}
|
|
4681
|
-
else if (toolName === 'Write' && input.file_path) {
|
|
4682
|
-
description = `I want to create or overwrite the file: ${input.file_path}`;
|
|
4683
|
-
}
|
|
4684
|
-
else if (toolName === 'Edit' && input.file_path) {
|
|
4685
|
-
description = `I want to edit the file: ${input.file_path}`;
|
|
4686
|
-
}
|
|
4687
|
-
else if (toolName === 'WebFetch' && input.url) {
|
|
4688
|
-
description = `I want to fetch content from: ${input.url}`;
|
|
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;
|
|
4689
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;
|
|
4690
4816
|
// Generate diff for Write/Edit/MultiEdit tools
|
|
4691
4817
|
let diffString;
|
|
4692
4818
|
if (toolName === 'Write' || toolName === 'Edit' || toolName === 'MultiEdit') {
|
|
@@ -4744,19 +4870,46 @@ async function main() {
|
|
|
4744
4870
|
diffString = undefined;
|
|
4745
4871
|
}
|
|
4746
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
|
+
}
|
|
4747
4898
|
console.log(`🔍 perm payload: diff=${diffString ? `✅ ${diffString.length} chars` : '❌ NONE'} toolName=${toolName}`);
|
|
4748
4899
|
sendToFrontend({
|
|
4749
4900
|
type: 'permission_request',
|
|
4901
|
+
requestId,
|
|
4750
4902
|
toolName: data.toolName,
|
|
4751
4903
|
input: data.input,
|
|
4752
4904
|
description,
|
|
4905
|
+
always,
|
|
4753
4906
|
agentRole: 'direct',
|
|
4754
4907
|
diff: diffString,
|
|
4755
4908
|
});
|
|
4756
4909
|
// Watch bridge (mobile Track 1): mirror this blocking question to the
|
|
4757
4910
|
// wrist via Pushover. Fire-and-forget — dormant unless PUSHOVER_* env is
|
|
4758
4911
|
// configured; web-UI answers always win (late wrist acks are no-ops).
|
|
4759
|
-
void armPermissionPush({ toolName, description }).catch(() => { });
|
|
4912
|
+
void armPermissionPush({ toolName, description, requestId }).catch(() => { });
|
|
4760
4913
|
// Speak the descriptive request so user knows to respond
|
|
4761
4914
|
//do not delete!! Leave this section commented out
|
|
4762
4915
|
// say permission, request permission, ask for permission with session.say
|
|
@@ -4979,8 +5132,7 @@ async function main() {
|
|
|
4979
5132
|
last_assistant_message: d.last_assistant_message,
|
|
4980
5133
|
}));
|
|
4981
5134
|
// Steward verdict card + sign-off gate note (#221) → chat
|
|
4982
|
-
directLLM.events
|
|
4983
|
-
directLLM.events.on('steward_gate', (d) => sendToFrontend({ type: 'steward_gate', decision: d.decision, message: d.message }));
|
|
5135
|
+
forwardStewardEvents(directLLM.events);
|
|
4984
5136
|
directLLM.events.on('tool_blocked', (d) => sendToFrontend({ type: 'tool_blocked', ...d }));
|
|
4985
5137
|
// Dispatcher v1 — sub-agent started → frontend stop-key signal (Feature A2)
|
|
4986
5138
|
directLLM.events.on('agent_started', (d) => sendToFrontend({
|
|
@@ -5245,15 +5397,18 @@ async function main() {
|
|
|
5245
5397
|
livekitState.error = err instanceof Error ? err.message : String(err);
|
|
5246
5398
|
});
|
|
5247
5399
|
};
|
|
5248
|
-
|
|
5249
|
-
|
|
5250
|
-
|
|
5251
|
-
|
|
5252
|
-
|
|
5253
|
-
|
|
5254
|
-
|
|
5255
|
-
|
|
5256
|
-
|
|
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);
|
|
5257
5412
|
}
|
|
5258
5413
|
// wireRoomHandlers(room): register EVERY room.on(...) listener onto a fresh
|
|
5259
5414
|
// Room instance. Called once per session from createRoomSession(). The bodies
|
|
@@ -5319,8 +5474,14 @@ async function main() {
|
|
|
5319
5474
|
room.on(RoomEvent.DataReceived, handleDataReceived);
|
|
5320
5475
|
// Phone calls: keypad 2 denies the pending approval; 1 allows only once
|
|
5321
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.
|
|
5322
5478
|
room.on(RoomEvent.DtmfReceived, (_code, digit, participant) => {
|
|
5323
|
-
|
|
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));
|
|
5324
5485
|
if (outcome !== 'ignored')
|
|
5325
5486
|
console.log(`📞 Keypad ${digit}: ${outcome}`);
|
|
5326
5487
|
});
|
|
@@ -5354,6 +5515,11 @@ async function main() {
|
|
|
5354
5515
|
// A phone caller (SIP) is adopted only in a room an authorised phone connect
|
|
5355
5516
|
// asked for, and never becomes the controller (it has no data channel).
|
|
5356
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
|
+
}
|
|
5357
5523
|
const join = resolveJoin(participant.identity, joinerUserId, OWNER_USER_ID, controllingUserIdentity, { sip: isPhoneCaller, phoneRoom: inPhoneRoom() });
|
|
5358
5524
|
controllingUserIdentity = join.controller;
|
|
5359
5525
|
if (!join.adoptSession) {
|
|
@@ -5368,6 +5534,28 @@ async function main() {
|
|
|
5368
5534
|
}
|
|
5369
5535
|
return;
|
|
5370
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
|
+
}
|
|
5371
5559
|
// A user (re)arriving cancels the meeting leave-grace — the bot stays.
|
|
5372
5560
|
cancelMeetingLeaveGrace();
|
|
5373
5561
|
// A user is present — cancel any pending agent-side "alone" leave.
|
|
@@ -5454,8 +5642,9 @@ async function main() {
|
|
|
5454
5642
|
// client's workingDirectory is only a HINT; for a pre-selected session the
|
|
5455
5643
|
// agent is AUTHORITATIVE about where that session lives, so `--resume`
|
|
5456
5644
|
// finds its JSONL instead of coming up in the workspace root — or as a
|
|
5457
|
-
// different session — on a stale or empty hint.
|
|
5458
|
-
//
|
|
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.
|
|
5459
5648
|
const wdHint = (typeof metadata.workingDirectory === 'string' && metadata.workingDirectory.length > 0)
|
|
5460
5649
|
? metadata.workingDirectory
|
|
5461
5650
|
: null;
|
|
@@ -5468,14 +5657,15 @@ async function main() {
|
|
|
5468
5657
|
console.warn('⚠️ connect cwd resolve failed:', e instanceof Error ? e.message : e);
|
|
5469
5658
|
}
|
|
5470
5659
|
}
|
|
5471
|
-
|
|
5472
|
-
|
|
5473
|
-
|
|
5474
|
-
// would boot the agent in an empty dir (scanSlugCwd won't either).
|
|
5475
|
-
if (workingDir === wdHint && !existsSync(workingDir)) {
|
|
5660
|
+
const connectDir = connectWorkingDir(resolvedConnectCwd, wdHint, preSelectedSessionId, defaultWorkingDir, existsSync);
|
|
5661
|
+
workingDir = connectDir.dir;
|
|
5662
|
+
if (connectDir.create) {
|
|
5476
5663
|
mkdirSync(workingDir, { recursive: true });
|
|
5477
5664
|
console.log(`📁 Created project directory: ${workingDir}`);
|
|
5478
5665
|
}
|
|
5666
|
+
else if (wdHint && !resolvedConnectCwd && workingDir !== wdHint) {
|
|
5667
|
+
console.warn(`⚠️ Project folder not found, not created: ${wdHint}`);
|
|
5668
|
+
}
|
|
5479
5669
|
console.log(`📂 Working directory: ${workingDir}`);
|
|
5480
5670
|
}
|
|
5481
5671
|
catch (err) {
|
|
@@ -5485,6 +5675,8 @@ async function main() {
|
|
|
5485
5675
|
// as the machine owner and resumes the most recent session (none = a new one).
|
|
5486
5676
|
if (isPhoneCaller) {
|
|
5487
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(() => { });
|
|
5488
5680
|
try {
|
|
5489
5681
|
const [latest] = await listAllClaudeSessions(1);
|
|
5490
5682
|
const cwd = latest ? await resolveCwdForSession(latest.sessionId, latest.cwd) : null;
|
|
@@ -5551,6 +5743,9 @@ async function main() {
|
|
|
5551
5743
|
if (KEEP_WARM && warmLLM && warmSessionId && resumeSessionId && warmSessionId === resumeSessionId && Date.now() < warmExpiry) {
|
|
5552
5744
|
console.log(`🔥 [KEEP-WARM] re-attaching session ${warmSessionId.slice(0, 8)} — zero replay`);
|
|
5553
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;
|
|
5554
5749
|
if (pendingSessionClose) {
|
|
5555
5750
|
try {
|
|
5556
5751
|
await pendingSessionClose;
|
|
@@ -5601,6 +5796,7 @@ async function main() {
|
|
|
5601
5796
|
getAndConsumeInterruptionContext,
|
|
5602
5797
|
getAndConsumeClientNotes,
|
|
5603
5798
|
onFastBrainResult: onPipelineFastBrainResult,
|
|
5799
|
+
takeVoiceAction: takePhoneVoiceAction,
|
|
5604
5800
|
});
|
|
5605
5801
|
// Pass pipelineLLM to createDirectSession so it uses it instead of creating a new ClaudeLLM
|
|
5606
5802
|
const result = await createDirectSession(resumeSessionId, pipelineLLM);
|
|
@@ -5675,7 +5871,10 @@ async function main() {
|
|
|
5675
5871
|
if (normalized === lastSentAgentTranscript)
|
|
5676
5872
|
return;
|
|
5677
5873
|
console.log(`💬 Agent (${source}, ${text.length} chars): "${text}"`);
|
|
5678
|
-
|
|
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 });
|
|
5679
5878
|
lastSentAgentTranscript = normalized;
|
|
5680
5879
|
}
|
|
5681
5880
|
// PRIMARY: conversation_item_added is the authoritative source
|
|
@@ -6090,6 +6289,7 @@ async function main() {
|
|
|
6090
6289
|
getAndConsumeInterruptionContext,
|
|
6091
6290
|
getAndConsumeClientNotes,
|
|
6092
6291
|
onFastBrainResult: onPipelineFastBrainResult,
|
|
6292
|
+
takeVoiceAction: takePhoneVoiceAction,
|
|
6093
6293
|
});
|
|
6094
6294
|
result = await createDirectSession(recoverySessionId, pipelineLLM);
|
|
6095
6295
|
}
|
|
@@ -6202,6 +6402,7 @@ async function main() {
|
|
|
6202
6402
|
namedAgents: describeAgents(NAMED_AGENTS, userNamedAgents, userAgentRoles, false, userAgentOrigins),
|
|
6203
6403
|
...describeRoles(),
|
|
6204
6404
|
keepWorking: true,
|
|
6405
|
+
approvalMode,
|
|
6205
6406
|
});
|
|
6206
6407
|
};
|
|
6207
6408
|
const readyInterval = setInterval(sendReady, 2000);
|
|
@@ -6260,7 +6461,7 @@ async function main() {
|
|
|
6260
6461
|
// screen connected (measured). Now the first words play at session-
|
|
6261
6462
|
// ready (~2s); the prep runs in the background and never blocks voice.
|
|
6262
6463
|
try {
|
|
6263
|
-
await session.say(
|
|
6464
|
+
await session.say(RESUME_GREETING);
|
|
6264
6465
|
}
|
|
6265
6466
|
catch (err) {
|
|
6266
6467
|
console.log('⚠️ Pre-selected session greeting failed:', err);
|
|
@@ -6286,7 +6487,7 @@ async function main() {
|
|
|
6286
6487
|
// transcript rebuilds its "Conversation compacted" rows too.
|
|
6287
6488
|
const compactions = readCompactionMarkers(preSelectedSessionId, workingDir);
|
|
6288
6489
|
// Last few cards, without the full return text, so the push stays under the packet limit.
|
|
6289
|
-
const steward =
|
|
6490
|
+
const steward = stewardPushRecords(readStewardRecords(preSelectedSessionId, workingDir));
|
|
6290
6491
|
if (priorMessages.length > 0) {
|
|
6291
6492
|
await sendToFrontend({ type: 'prior_messages', sessionId: preSelectedSessionId, messages: priorMessages, compactions, steward });
|
|
6292
6493
|
console.log(`💬 Sent ${priorMessages.length} prior messages (+${compactions.length} compaction markers) from DB for optimistic UI`);
|
|
@@ -6349,6 +6550,9 @@ async function main() {
|
|
|
6349
6550
|
console.log('⚠️ Greeting failed:', err);
|
|
6350
6551
|
}
|
|
6351
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 }));
|
|
6352
6556
|
}
|
|
6353
6557
|
catch (err) {
|
|
6354
6558
|
console.error('❌ Failed to start session:', err);
|
|
@@ -6358,12 +6562,16 @@ async function main() {
|
|
|
6358
6562
|
// participantConnectedHandler above).
|
|
6359
6563
|
const handleParticipantDisconnected = (participant) => {
|
|
6360
6564
|
console.log(`👋 User left: ${participant.identity}`);
|
|
6565
|
+
if (phoneCodeLeave(participant))
|
|
6566
|
+
return;
|
|
6361
6567
|
// The caller hung up: the call is over (inPhoneRoom() is false from here, so the
|
|
6362
6568
|
// next session gets tools back). Its brain is killed below, not parked, so nothing
|
|
6363
6569
|
// it was asked on the call runs after hang-up with tools on.
|
|
6364
6570
|
const phoneCallerLeft = participant.kind === ParticipantKind.SIP;
|
|
6365
6571
|
if (phoneCallerLeft)
|
|
6366
6572
|
phoneRoomName = null;
|
|
6573
|
+
if (phoneCallerLeft)
|
|
6574
|
+
clearPhoneCode();
|
|
6367
6575
|
if (participant.identity === controllingUserIdentity)
|
|
6368
6576
|
controllingUserIdentity = null;
|
|
6369
6577
|
cancelPendingSwitch('participant_disconnected', false);
|
|
@@ -6423,17 +6631,22 @@ async function main() {
|
|
|
6423
6631
|
// participantConnectedHandler owns continuation (re-attach or, on a
|
|
6424
6632
|
// mismatch, it frees the warm slot). The warm watchdog is the backstop.
|
|
6425
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;
|
|
6426
6636
|
parkWarm('duplicate_identity');
|
|
6427
6637
|
clearPipelineFastBrainSession();
|
|
6428
6638
|
clearPipelineFastBrainSession();
|
|
6429
6639
|
}
|
|
6430
|
-
else if (KEEP_WARM && currentLLM && currentLLM
|
|
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.)
|
|
6431
6642
|
// KEEP-WARM network/tab-close drop: park the subprocess instead of killing
|
|
6432
6643
|
// it so a reconnect within the grace re-attaches with ZERO replay. We
|
|
6433
6644
|
// STILL run the normal room teardown below — the parked brain is
|
|
6434
6645
|
// independent of the room (no longer currentLLM, not in slots, so
|
|
6435
6646
|
// agentsActive() is false), so releaseAgents + fast-leave free the empty
|
|
6436
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;
|
|
6437
6650
|
parkWarm('participant_disconnected');
|
|
6438
6651
|
clearPipelineFastBrainSession();
|
|
6439
6652
|
clearPipelineFastBrainSession();
|
|
@@ -6485,8 +6698,28 @@ async function main() {
|
|
|
6485
6698
|
if (Object.hasOwn(STORE_REPLY_TYPES, data.type) && participant?.identity) {
|
|
6486
6699
|
await sendToFrontend({ type: STORE_REPLY_TYPES[data.type], success: false, error: 'Another device controls this session' }, participant.identity);
|
|
6487
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
|
+
}
|
|
6488
6705
|
return;
|
|
6489
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 {
|
|
6490
6723
|
if (data.type === 'claude_auth_code' && pendingAuthSubmitCode) {
|
|
6491
6724
|
console.log('🔑 Received auth code from frontend');
|
|
6492
6725
|
sendToFrontend({ type: 'claude_auth_submitting', message: 'Submitting code to Claude CLI...' });
|
|
@@ -6536,18 +6769,32 @@ async function main() {
|
|
|
6536
6769
|
}
|
|
6537
6770
|
}
|
|
6538
6771
|
else if (data.type === 'permission_response') {
|
|
6539
|
-
//
|
|
6540
|
-
|
|
6541
|
-
|
|
6542
|
-
|
|
6543
|
-
|
|
6544
|
-
|
|
6545
|
-
|
|
6546
|
-
|
|
6547
|
-
|
|
6548
|
-
|
|
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`);
|
|
6549
6786
|
}
|
|
6550
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)'}`);
|
|
6795
|
+
}
|
|
6796
|
+
sendToFrontend({ type: 'approval_mode', mode: approvalMode });
|
|
6797
|
+
}
|
|
6551
6798
|
else if (data.type === 'favorite_changed') {
|
|
6552
6799
|
// L2b (UI#21): a favorite is a UI action, not something the user said.
|
|
6553
6800
|
// Queue it as hidden context for the next real user turn; no reply, no
|
|
@@ -6778,15 +7025,15 @@ async function main() {
|
|
|
6778
7025
|
// session_switch_cancelled.
|
|
6779
7026
|
const sessionId = data.sessionId;
|
|
6780
7027
|
const hint = typeof data.workingDirectory === 'string' ? data.workingDirectory : undefined;
|
|
6781
|
-
await requestSessionSwitch(sessionId, hint, { force: !!data.force, origin: 'switch_session' });
|
|
7028
|
+
await requestSessionSwitch(sessionId, hint, { force: !!data.force, origin: 'switch_session', reply: sendToFrontend });
|
|
6782
7029
|
}
|
|
6783
7030
|
else if (data.type === 'get_busy') {
|
|
6784
7031
|
// End asks before hanging up: a busy agent may keep working (keep_working).
|
|
6785
7032
|
// Offered only when the hang-up will park the brain (the KEEP_WARM branch of
|
|
6786
7033
|
// the disconnect handler) and it is working, not just waiting on an approval.
|
|
6787
7034
|
const busy = currentLLM?.busyState?.();
|
|
6788
|
-
const parks = KEEP_WARM && !activeMeetingBotId && !!currentLLM
|
|
6789
|
-
await sendToFrontend({ type: 'busy_state', idle: (busy?.idle ?? true) || !!busy?.permissionPending, capMin: parks ? IDLE_EXIT_GRACE_MS / 60000 : 0, phone: isWatchBridgeEnabled() },
|
|
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);
|
|
6790
7037
|
}
|
|
6791
7038
|
else if (data.type === 'keep_working') {
|
|
6792
7039
|
keepWorkingRequested = true;
|
|
@@ -7371,7 +7618,7 @@ async function main() {
|
|
|
7371
7618
|
// Greet immediately, then point agent to session index (no raw JSONL loading)
|
|
7372
7619
|
if (currentSession && summary) {
|
|
7373
7620
|
try {
|
|
7374
|
-
await currentSession.say(
|
|
7621
|
+
await currentSession.say(RESUME_GREETING);
|
|
7375
7622
|
}
|
|
7376
7623
|
catch (err) {
|
|
7377
7624
|
console.log('⚠️ Session gate greeting failed:', err);
|
|
@@ -7588,8 +7835,153 @@ async function main() {
|
|
|
7588
7835
|
}
|
|
7589
7836
|
}
|
|
7590
7837
|
}
|
|
7591
|
-
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;
|
|
7592
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
|
+
}
|
|
7593
7985
|
// ============================================================
|
|
7594
7986
|
// Room session lifecycle (0.9.83): fresh Room per user session
|
|
7595
7987
|
// ============================================================
|
|
@@ -7724,6 +8116,7 @@ async function main() {
|
|
|
7724
8116
|
activeRoom = null;
|
|
7725
8117
|
activeRoomName = null;
|
|
7726
8118
|
phoneRoomName = null;
|
|
8119
|
+
clearPhoneCode();
|
|
7727
8120
|
if (aloneTimer) {
|
|
7728
8121
|
clearTimeout(aloneTimer);
|
|
7729
8122
|
aloneTimer = null;
|