osborn 0.9.271 → 0.9.275

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 (61) hide show
  1. package/.claude/skills/browser-apply/SKILL.md +82 -30
  2. package/.claude/skills/browser-apply/candidate.example.env +16 -0
  3. package/.claude/skills/browser-apply/fill.mjs +294 -0
  4. package/Dockerfile +1 -1
  5. package/dist/claude-auth.d.ts +85 -6
  6. package/dist/claude-auth.js +202 -22
  7. package/dist/claude-llm.d.ts +13 -0
  8. package/dist/claude-llm.js +171 -25
  9. package/dist/compaction-log.d.ts +67 -0
  10. package/dist/compaction-log.js +195 -0
  11. package/dist/config.d.ts +18 -0
  12. package/dist/config.js +122 -65
  13. package/dist/content/transcript-sanitizer.d.ts +20 -6
  14. package/dist/content/transcript-sanitizer.js +66 -11
  15. package/dist/data-sender-auth.d.ts +90 -0
  16. package/dist/data-sender-auth.js +158 -0
  17. package/dist/duck.d.ts +8 -0
  18. package/dist/duck.js +59 -0
  19. package/dist/env-keys.js +11 -0
  20. package/dist/index.js +493 -97
  21. package/dist/lib/safe-artifact-path.d.ts +17 -0
  22. package/dist/lib/safe-artifact-path.js +129 -0
  23. package/dist/meeting-addressing.d.ts +176 -0
  24. package/dist/meeting-addressing.js +288 -0
  25. package/dist/pipeline-direct-llm.d.ts +52 -1
  26. package/dist/pipeline-direct-llm.js +206 -61
  27. package/dist/prompts/direct-mode-fallback.md +1 -1
  28. package/dist/prompts/direct-mode-research.md +2 -2
  29. package/dist/prompts.d.ts +1 -1
  30. package/dist/prompts.js +3 -3
  31. package/dist/pushover.d.ts +77 -0
  32. package/dist/pushover.js +276 -0
  33. package/dist/recall-client.js +21 -2
  34. package/dist/session-store.d.ts +15 -5
  35. package/dist/session-store.js +37 -10
  36. package/dist/transcript-wiring.d.ts +121 -0
  37. package/dist/transcript-wiring.js +252 -0
  38. package/dist/voice-io.d.ts +0 -9
  39. package/dist/voice-io.js +5 -19
  40. package/dist/watch-gateway.d.ts +38 -0
  41. package/dist/watch-gateway.js +205 -0
  42. package/package.json +1 -1
  43. package/scripts/review.ts +1 -1
  44. package/dist/bridge-llm.d.ts +0 -22
  45. package/dist/bridge-llm.js +0 -39
  46. package/dist/codex-handler.d.ts +0 -38
  47. package/dist/codex-handler.js +0 -83
  48. package/dist/codex-llm.d.ts +0 -40
  49. package/dist/codex-llm.js +0 -144
  50. package/dist/fast-brain.d.ts +0 -176
  51. package/dist/fast-brain.js +0 -1887
  52. package/dist/index-3-2-26-legacy.d.ts +0 -1
  53. package/dist/index-3-2-26-legacy.js +0 -2233
  54. package/dist/leagcyprompts2.d.ts +0 -0
  55. package/dist/leagcyprompts2.js +0 -573
  56. package/dist/prompts-2-25-26.d.ts +0 -0
  57. package/dist/prompts-2-25-26.js +0 -518
  58. package/dist/prompts-3-2-26.d.ts +0 -78
  59. package/dist/prompts-3-2-26.js +0 -1319
  60. package/dist/summary-index.d.ts +0 -90
  61. package/dist/summary-index.js +0 -585
package/dist/index.js CHANGED
@@ -20,7 +20,7 @@ import { dirname, join } from 'node:path';
20
20
  import { fileURLToPath } from 'node:url';
21
21
  import { spawn } from 'node:child_process';
22
22
  import { getHeapStatistics } from 'node:v8';
23
- import { randomUUID, randomBytes } from 'node:crypto';
23
+ import { randomUUID, randomBytes, createHmac, timingSafeEqual } from 'node:crypto';
24
24
  import httpProxy from 'http-proxy';
25
25
  import { createRequire } from 'node:module';
26
26
  // 0.9.71: createRequire for resolving package.json versions inside ESM
@@ -35,21 +35,29 @@ const __filename = fileURLToPath(import.meta.url);
35
35
  const __dirname = dirname(__filename);
36
36
  import { createPatch } from 'diff';
37
37
  import { loadConfig, getMcpServers, getEnabledMcpServerNames, getVoiceMode, getDirectConfig, listSessions, listAllClaudeSessions, invalidateSessionListCache, getMostRecentSessionId, sessionExists, getSessionSummary, getConversationHistory, ensureSessionWorkspace, getMcpServerStatusList, buildMcpServersForKeys, listWorkspaceArtifacts } from './config.js';
38
+ import { isSafeArtifactPath } from './lib/safe-artifact-path.js';
38
39
  import { cleanupHousekeeping } from './housekeeping.js';
39
40
  import { createSTT, createTTS } from './voice-io.js';
40
- import { createClaudeLLM, NAMED_AGENTS, applyTurbo } from './claude-llm.js';
41
+ import { createClaudeLLM, NAMED_AGENTS, applyTurbo, requestAuthRestart } from './claude-llm.js';
41
42
  import { clearPipelineFastBrainSession, prewarmBM25Index } from './pipeline-fastbrain.js';
42
- import { ensureClaudeAuth, applyAuthFallback, replayInFlightAuth } from './claude-auth.js';
43
+ import { ensureClaudeAuth, applyAuthFallback, replayInFlightAuth, startClaudeAuthOnDemand, isOnDemandAuthInFlight } from './claude-auth.js';
43
44
  import { statusManager } from './status-manager.js';
44
45
  import { createSmitheryProxy, destroySmitheryProxy, parseSmitheryUrl, isSmitheryUrl, SmitheryAuthorizationError } from './smithery-proxy.js';
45
46
  import { DIRECT_MODE_PROMPT } from './prompts.js';
46
47
  import { MCP_CATALOG } from './config.js';
47
48
  import { storeExists, openStore, recentRows } from './session-store.js';
49
+ import { readCompactionMarkers } from './compaction-log.js';
50
+ import { sessionListEntry, cleanHistoryRows, userEchoText, TypedEchoTracker, ClientNoteQueue, parseFavoriteChanged, parseLegacyFavoriteNotice } from './transcript-wiring.js';
48
51
  import { getRecallClient } from './recall-client.js';
49
52
  import { MeetingTranscriptPoller } from './meeting-transcript-poller.js';
50
53
  import { missingRequiredEnv } from './env-keys.js';
54
+ import { armPermissionPush, handleWatchAck, setWatchResultHandler } from './pushover.js';
55
+ import { startWatchGateway } from './watch-gateway.js';
51
56
  import { noiseGate } from './noise-gate.js';
57
+ import { installDuck, DUCK_LEVEL } from './duck.js';
58
+ import { meetingAddressing, isRoutableTarget } from './meeting-addressing.js';
52
59
  import { listSecretStatus, setSecrets, deleteSecret } from './secrets-store.js';
60
+ import { AGENT_SELF_IDENTITY, checkControlSender, resolveJoin, userIdFromMetadata } from './data-sender-auth.js';
53
61
  import { llm } from '@livekit/agents';
54
62
  // ============================================================
55
63
  // PIPELINE MODE: STT (Deepgram) → Claude Agent SDK → TTS
@@ -249,6 +257,9 @@ const livekitState = {
249
257
  // stopped). The hooks below are populated by main() (which owns `room` and the
250
258
  // connect-with-retry loop) so the module-level HTTP server can drive them.
251
259
  let intentionalLeave = false;
260
+ // Native barge-in duck on the live session's audio output (see duck.ts)
261
+ let currentDuck = null;
262
+ let duckRestoreTimer = null;
252
263
  let connectRoomHook = null;
253
264
  // Mints a LISTEN-ONLY LiveKit token for the meeting canvas so it can join the
254
265
  // agent's room and play the agent's REAL TTS audio track — bit-identical to
@@ -340,6 +351,48 @@ wsProxy.on('error', (err, _req, socket) => {
340
351
  // valid cookie are forwarded, so a forgotten agent route can never be silently
341
352
  // swallowed by the IDE proxy. Cleared in stopIde().
342
353
  let ideSessionToken = null;
354
+ // ── /editor access token (closes the unauthenticated-RCE hole) ──────────────
355
+ // The agent's HTTP server is public (0.0.0.0:8741 via fly.toml). GET /editor
356
+ // used to mint the osborn_ide cookie with NO auth, and code-server runs
357
+ // --auth none — so anyone who knew a machine's fly.dev address could open the
358
+ // IDE/terminal = remote code execution on the paying owner's machine.
359
+ //
360
+ // Fix: /editor now requires a short-lived HMAC token. The token is minted with
361
+ // OSBORN_SYNC_TOKEN (the per-machine owner secret) and embedded in the ideUrl
362
+ // the agent hands back over the LiveKit data channel — which is already
363
+ // owner-gated (control commands bound to OSBORN_OWNER_USER_ID). So only the
364
+ // owner ever receives a valid token; a direct hit to /editor without it is
365
+ // refused. Local dev (no FLY_APP_NAME) is localhost-only and skips the gate.
366
+ const EDITOR_TOKEN_TTL_MS = 24 * 60 * 60 * 1000; // long-lived: the URL is owner-only; avoids breaking "open editor later"
367
+ function mintEditorToken() {
368
+ const secret = process.env.OSBORN_SYNC_TOKEN;
369
+ if (!secret)
370
+ return '';
371
+ const exp = Date.now() + EDITOR_TOKEN_TTL_MS;
372
+ const sig = createHmac('sha256', secret).update(`editor:${exp}`).digest('base64url');
373
+ return `${exp}.${sig}`;
374
+ }
375
+ function verifyEditorToken(tok) {
376
+ const secret = process.env.OSBORN_SYNC_TOKEN;
377
+ if (!secret || !tok)
378
+ return false; // cloud with no secret → fail CLOSED
379
+ const dot = tok.indexOf('.');
380
+ if (dot < 0)
381
+ return false;
382
+ const exp = Number(tok.slice(0, dot));
383
+ if (!Number.isFinite(exp) || exp < Date.now())
384
+ return false;
385
+ const expected = createHmac('sha256', secret).update(`editor:${exp}`).digest('base64url');
386
+ const got = tok.slice(dot + 1);
387
+ if (got.length !== expected.length)
388
+ return false;
389
+ try {
390
+ return timingSafeEqual(Buffer.from(got), Buffer.from(expected));
391
+ }
392
+ catch {
393
+ return false;
394
+ }
395
+ }
343
396
  // Cancellation-generation guard for startCodeServer(). Incremented by stopIde()
344
397
  // every time the IDE is torn down. startCodeServer() captures myGen at entry;
345
398
  // if ideStartGeneration !== myGen when the poll resolves, the start has been
@@ -524,7 +577,32 @@ function startApiServer(workingDir, port) {
524
577
  }
525
578
  const url = new URL(req.url || '/', `http://localhost:${port}`);
526
579
  const syncToken = process.env.OSBORN_SYNC_TOKEN;
580
+ // Fail-closed auth for the sensitive session/ops routes. Requires
581
+ // `Authorization: Bearer <OSBORN_SYNC_TOKEN>` whenever we're on a cloud
582
+ // machine (FLY_APP_NAME set) OR a sync token is configured. Local dev with
583
+ // no token stays open. Writes 401 and returns true when NOT authorized, so
584
+ // a caller does `if (unauthorized()) return`. This replaces the old
585
+ // fail-OPEN `if (syncToken) { ... }` pattern (which left these routes wide
586
+ // open on any machine that hadn't set a token).
587
+ const unauthorized = () => {
588
+ const requireAuth = !!process.env.FLY_APP_NAME || !!syncToken;
589
+ if (requireAuth && req.headers['authorization'] !== `Bearer ${syncToken}`) {
590
+ res.writeHead(401, { 'Content-Type': 'application/json' });
591
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
592
+ return true;
593
+ }
594
+ return false;
595
+ };
527
596
  if (req.method === 'GET' && url.pathname === '/sessions') {
597
+ // Fail-closed in cloud: session lists reach only the owner (via the
598
+ // authenticated /api/agent proxy, which forwards Bearer OSBORN_SYNC_TOKEN).
599
+ // A direct hit to the public fly.dev address is rejected. Local dev
600
+ // (no FLY_APP_NAME) is localhost-only and stays open.
601
+ if (process.env.FLY_APP_NAME && (!syncToken || req.headers['authorization'] !== `Bearer ${syncToken}`)) {
602
+ res.writeHead(401, { 'Content-Type': 'application/json' });
603
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
604
+ return;
605
+ }
528
606
  try {
529
607
  const limit = Math.min(parseInt(url.searchParams.get('limit') || '500', 10), 1000);
530
608
  const sessions = await listAllClaudeSessions(limit);
@@ -537,16 +615,9 @@ function startApiServer(workingDir, port) {
537
615
  // hardcoded base-path list — agent self-describes its base so
538
616
  // the UI doesn't have to keep a sync'd copy.
539
617
  baseCwd: workingDir,
540
- sessions: sessions.map(s => ({
541
- sessionId: s.sessionId,
542
- projectSlug: s.projectSlug,
543
- projectPath: s.projectPath,
544
- cwd: s.cwd,
545
- timestamp: s.timestamp.toISOString(),
546
- lastMessage: s.lastMessage,
547
- messageCount: s.messageCount,
548
- fileSize: s.fileSize,
549
- })),
618
+ // sessionListEntry carries the L2a preview fields too (title, firstTs,
619
+ // lastActivityAt) so the dashboard can stop deriving them itself.
620
+ sessions: sessions.map(sessionListEntry),
550
621
  total: sessions.length,
551
622
  };
552
623
  res.writeHead(200, { 'Content-Type': 'application/json' });
@@ -566,6 +637,12 @@ function startApiServer(workingDir, port) {
566
637
  // store directly (readonly, no JSONL replay) — same source as the
567
638
  // data-channel prior_messages push, which remains the fallback for older
568
639
  // frontends. Rows carry real timestamps so the UI can date-stamp them.
640
+ // Fail-closed in cloud (real transcript content; owner-only via proxy).
641
+ if (process.env.FLY_APP_NAME && (!syncToken || req.headers['authorization'] !== `Bearer ${syncToken}`)) {
642
+ res.writeHead(401, { 'Content-Type': 'application/json' });
643
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
644
+ return;
645
+ }
569
646
  try {
570
647
  const sessionId = url.searchParams.get('session') || '';
571
648
  const limit = Math.min(parseInt(url.searchParams.get('limit') || '50', 10), 200);
@@ -574,21 +651,23 @@ function startApiServer(workingDir, port) {
574
651
  res.end(JSON.stringify({ error: 'session required' }));
575
652
  return;
576
653
  }
654
+ // Durable compaction markers (sidecar, not the derived store) so a
655
+ // resumed transcript rebuilds every past "Conversation compacted" row at
656
+ // its real position — the store rebuild can't wipe these.
657
+ const compactions = readCompactionMarkers(sessionId, workingDir);
577
658
  const dbPath = storeExists(sessionId, workingDir);
578
659
  if (!dbPath) {
579
660
  res.writeHead(200, { 'Content-Type': 'application/json' });
580
- res.end(JSON.stringify({ sessionId, messages: [] }));
661
+ res.end(JSON.stringify({ sessionId, messages: [], compactions }));
581
662
  return;
582
663
  }
583
664
  const db = openStore(dbPath, { readonly: true });
584
665
  try {
585
- const rows = recentRows(db, limit, ['user', 'assistant']);
586
- const messages = rows
587
- .reverse() // newest-first → chronological
588
- .map(r => ({ role: r.msgType === 'assistant' ? 'assistant' : 'user', content: (r.text || '').slice(0, 1200), ts: r.ts || null }))
589
- .filter(m => m.content.trim().length > 0);
666
+ // Sanitize BEFORE truncating, over-fetching so rows the sanitizer drops
667
+ // (notices, injected blocks) don't shrink the page (L2b).
668
+ const messages = cleanHistoryRows(n => recentRows(db, n, ['user', 'assistant']), limit, 1200);
590
669
  res.writeHead(200, { 'Content-Type': 'application/json' });
591
- res.end(JSON.stringify({ sessionId, messages }));
670
+ res.end(JSON.stringify({ sessionId, messages, compactions }));
592
671
  }
593
672
  finally {
594
673
  try {
@@ -837,6 +916,8 @@ function startApiServer(workingDir, port) {
837
916
  }
838
917
  // POST /restart — graceful process restart (process manager will restart)
839
918
  if (req.method === 'POST' && url.pathname === '/restart') {
919
+ if (unauthorized())
920
+ return; // was unauthenticated: anyone with the address could kill the agent
840
921
  res.writeHead(200, { 'Content-Type': 'application/json' });
841
922
  res.end(JSON.stringify({ success: true, message: 'Agent restarting...' }));
842
923
  console.log('🔄 Restart requested via HTTP — exiting for process manager restart');
@@ -1005,6 +1086,31 @@ function startApiServer(workingDir, port) {
1005
1086
  });
1006
1087
  return;
1007
1088
  }
1089
+ // POST /watch/ack — landing for the Track 1 wrist bridge (Pushover ack OR
1090
+ // ntfy Approve/Deny buttons). The frontend /api/watch/ack/[qid] route
1091
+ // verifies the HMAC signature and forwards here; pushover.ts re-verifies
1092
+ // against its pending map before resolving the blocking permission.
1093
+ // Dormant unless a provider (PUSHOVER_*/NTFY_*) + WATCH_ACK_SECRET are set.
1094
+ if (req.method === 'POST' && url.pathname === '/watch/ack') {
1095
+ let body = '';
1096
+ req.on('data', (c) => { body += c; });
1097
+ req.on('end', () => {
1098
+ try {
1099
+ const { qid, receipt, allow } = JSON.parse(body || '{}');
1100
+ if (!qid)
1101
+ throw new Error('qid required');
1102
+ // allow defaults to true (Pushover ack = approve); ntfy's Deny button sends false.
1103
+ const ok = handleWatchAck(qid, receipt, allow !== false);
1104
+ res.writeHead(ok ? 200 : 404, { 'Content-Type': 'application/json' });
1105
+ res.end(JSON.stringify({ ok }));
1106
+ }
1107
+ catch (e) {
1108
+ res.writeHead(400, { 'Content-Type': 'application/json' });
1109
+ res.end(JSON.stringify({ error: e.message }));
1110
+ }
1111
+ });
1112
+ return;
1113
+ }
1008
1114
  // GET /sessions/export — stream a gzipped tar of ~/.claude/projects/ AND
1009
1115
  // ~/.claude/skills/ to the client. Both directories ship in one archive so
1010
1116
  // a sync covers conversations (projects/) and learned skills together —
@@ -1013,14 +1119,8 @@ function startApiServer(workingDir, port) {
1013
1119
  // Optional ?workDir= query param accepted for backwards compat but ignored
1014
1120
  // (full export is always returned).
1015
1121
  if (req.method === 'GET' && url.pathname === '/sessions/export') {
1016
- if (syncToken) {
1017
- const authHeader = req.headers['authorization'] ?? '';
1018
- if (authHeader !== `Bearer ${syncToken}`) {
1019
- res.writeHead(401, { 'Content-Type': 'application/json' });
1020
- res.end(JSON.stringify({ error: 'Unauthorized' }));
1021
- return;
1022
- }
1023
- }
1122
+ if (unauthorized())
1123
+ return; // fail-closed (was fail-open: no token set → open)
1024
1124
  const claudeDir = join(homedir(), '.claude');
1025
1125
  const projectsDir = join(claudeDir, 'projects');
1026
1126
  const skillsDir = join(claudeDir, 'skills');
@@ -1060,6 +1160,8 @@ function startApiServer(workingDir, port) {
1060
1160
  // for the MVP — a per-share access token is a follow-up (tracked in
1061
1161
  // shared_sessions). sessionId is regex-validated to block path traversal.
1062
1162
  if (req.method === 'GET' && url.pathname === '/sessions/export-one') {
1163
+ if (unauthorized())
1164
+ return; // fail-closed; the sharing export leg now goes through the authed /api/agent proxy
1063
1165
  const sessionId = (url.searchParams.get('sessionId') || '').trim();
1064
1166
  if (!sessionId || !/^[a-zA-Z0-9._-]+$/.test(sessionId)) {
1065
1167
  res.writeHead(400, { 'Content-Type': 'application/json' });
@@ -1287,6 +1389,8 @@ function startApiServer(workingDir, port) {
1287
1389
  return { filesWritten, remapped, skillsWritten };
1288
1390
  };
1289
1391
  if (req.method === 'GET' && url.pathname === '/sessions/manifest') {
1392
+ if (unauthorized())
1393
+ return; // was public/no-auth: leaked the full session+skill file tree
1290
1394
  // Walks BOTH ~/.claude/projects/ AND ~/.claude/skills/ — full tree per
1291
1395
  // top-level directory.
1292
1396
  // - projects/<slug>/<...> → session JSONLs, sub-agent transcripts, tool-results, osb/
@@ -1348,14 +1452,8 @@ function startApiServer(workingDir, port) {
1348
1452
  }
1349
1453
  // POST /sessions/import — accept a gzipped tar and extract into ~/.claude/projects/
1350
1454
  if (req.method === 'POST' && url.pathname === '/sessions/import') {
1351
- if (syncToken) {
1352
- const authHeader = req.headers['authorization'] ?? '';
1353
- if (authHeader !== `Bearer ${syncToken}`) {
1354
- res.writeHead(401, { 'Content-Type': 'application/json' });
1355
- res.end(JSON.stringify({ error: 'Unauthorized' }));
1356
- return;
1357
- }
1358
- }
1455
+ if (unauthorized())
1456
+ return; // fail-closed (was fail-open)
1359
1457
  // 0.9.74: default targetWorkDir to this machine's own working directory.
1360
1458
  // Stale sync clients that omit the param used to get source slugs written
1361
1459
  // verbatim — those sessions LIST fine (the scanner walks all slugs) but
@@ -1428,14 +1526,8 @@ function startApiServer(workingDir, port) {
1428
1526
  }
1429
1527
  // POST /sessions/import-chunk — accept a single chunk of a multi-part upload
1430
1528
  if (req.method === 'POST' && url.pathname === '/sessions/import-chunk') {
1431
- if (syncToken) {
1432
- const authHeader = req.headers['authorization'] ?? '';
1433
- if (authHeader !== `Bearer ${syncToken}`) {
1434
- res.writeHead(401, { 'Content-Type': 'application/json' });
1435
- res.end(JSON.stringify({ error: 'Unauthorized' }));
1436
- return;
1437
- }
1438
- }
1529
+ if (unauthorized())
1530
+ return; // fail-closed (was fail-open)
1439
1531
  const uploadId = url.searchParams.get('uploadId');
1440
1532
  const chunkIndex = parseInt(url.searchParams.get('chunk') || '0');
1441
1533
  if (!uploadId) {
@@ -1466,14 +1558,8 @@ function startApiServer(workingDir, port) {
1466
1558
  }
1467
1559
  // POST /sessions/import-finalize — reassemble chunks, extract, apply slug merge
1468
1560
  if (req.method === 'POST' && url.pathname === '/sessions/import-finalize') {
1469
- if (syncToken) {
1470
- const authHeader = req.headers['authorization'] ?? '';
1471
- if (authHeader !== `Bearer ${syncToken}`) {
1472
- res.writeHead(401, { 'Content-Type': 'application/json' });
1473
- res.end(JSON.stringify({ error: 'Unauthorized' }));
1474
- return;
1475
- }
1476
- }
1561
+ if (unauthorized())
1562
+ return; // fail-closed (was fail-open)
1477
1563
  const uploadId = url.searchParams.get('uploadId');
1478
1564
  const total = parseInt(url.searchParams.get('total') || '0');
1479
1565
  const targetWorkDir = url.searchParams.get('targetWorkDir') ?? undefined;
@@ -1554,14 +1640,8 @@ function startApiServer(workingDir, port) {
1554
1640
  // Deletes ~/.claude/projects/<slug>/ and ~/.claude/projects/osb/<slug>/
1555
1641
  // Used by the dashboard "delete project" button.
1556
1642
  if (req.method === 'DELETE' && url.pathname === '/sessions/project') {
1557
- if (syncToken) {
1558
- const authHeader = req.headers['authorization'] ?? '';
1559
- if (authHeader !== `Bearer ${syncToken}`) {
1560
- res.writeHead(401, { 'Content-Type': 'application/json' });
1561
- res.end(JSON.stringify({ error: 'Unauthorized' }));
1562
- return;
1563
- }
1564
- }
1643
+ if (unauthorized())
1644
+ return; // fail-closed (was fail-open) — this DELETES a project's sessions
1565
1645
  const slug = url.searchParams.get('slug');
1566
1646
  if (!slug || slug.includes('..') || slug.includes('/')) {
1567
1647
  res.writeHead(400, { 'Content-Type': 'application/json' });
@@ -1670,7 +1750,16 @@ function startApiServer(workingDir, port) {
1670
1750
  // self-refreshing "Starting…" page so the user naturally re-hits /editor every
1671
1751
  // 3 s until ready.
1672
1752
  if (url.pathname === '/editor' && req.method === 'GET') {
1673
- // AUTH GATE (future): validate key / signed session before minting the cookie
1753
+ // AUTH GATE: the editor URL is minted with an owner-only signed token (see
1754
+ // mintEditorToken) and delivered over the authenticated data channel. A
1755
+ // direct hit without a valid token is refused — this is what closes the
1756
+ // unauthenticated-RCE hole. Local dev (no FLY_APP_NAME) is localhost-only.
1757
+ const editorToken = url.searchParams.get('t');
1758
+ if (process.env.FLY_APP_NAME && !verifyEditorToken(editorToken)) {
1759
+ res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });
1760
+ res.end('Forbidden — open the editor from inside your Voice Native session.');
1761
+ return;
1762
+ }
1674
1763
  // Optional ?folder= param: must be an absolute path under /workspace with no
1675
1764
  // directory-traversal sequences. If absent or invalid, fall back to bare '/'.
1676
1765
  const rawFolder = url.searchParams.get('folder') ?? '';
@@ -1706,9 +1795,14 @@ function startApiServer(workingDir, port) {
1706
1795
  console.error('❌ startCodeServer() from /editor failed:', err);
1707
1796
  });
1708
1797
  }
1709
- const refreshTarget = folderParam
1710
- ? `/editor?folder=${encodeURIComponent(folderParam)}`
1711
- : '/editor';
1798
+ // Preserve BOTH folder and the access token across the 3s self-refresh,
1799
+ // or the poll loop would bounce to a tokenless /editor and 403.
1800
+ const refreshQs = new URLSearchParams();
1801
+ if (folderParam)
1802
+ refreshQs.set('folder', folderParam);
1803
+ if (editorToken)
1804
+ refreshQs.set('t', editorToken);
1805
+ const refreshTarget = refreshQs.toString() ? `/editor?${refreshQs.toString()}` : '/editor';
1712
1806
  res.writeHead(200, {
1713
1807
  'Content-Type': 'text/html; charset=utf-8',
1714
1808
  'Cache-Control': 'no-store, must-revalidate',
@@ -2083,11 +2177,41 @@ async function main() {
2083
2177
  // null while the agent is idle (between sessions).
2084
2178
  let activeRoom = null;
2085
2179
  let activeRoomName = null; // the temporary room name currently joined
2180
+ // Watch gateway (mobile Track 2): bridges the native watchOS app's WS audio
2181
+ // + JSON into the user's LiveKit room via rtc-node. Opt-in — dormant unless
2182
+ // WATCH_GATEWAY=1 (port WATCH_GATEWAY_PORT, default 8742).
2183
+ if (process.env.WATCH_GATEWAY === '1') {
2184
+ const livekitUrl = process.env.LIVEKIT_URL || '';
2185
+ if (livekitUrl) {
2186
+ startWatchGateway({
2187
+ port: parseInt(process.env.WATCH_GATEWAY_PORT || '8742', 10),
2188
+ livekitUrl,
2189
+ getActiveRoom: () => activeRoomName,
2190
+ mintToken: mintAgentToken,
2191
+ });
2192
+ }
2193
+ else {
2194
+ console.log('⌚️ Watch gateway: WATCH_GATEWAY=1 but LIVEKIT_URL unset — not starting');
2195
+ }
2196
+ }
2086
2197
  // Track state
2087
2198
  let pendingSessionClose = null; // Tracks async session close for reconnect safety
2088
2199
  let currentSession = null;
2089
2200
  // 0.9.81: callable handler reference — see registration site for why.
2090
2201
  let participantConnectedHandler = null;
2202
+ // Identity of the user participant the voice session was last built for.
2203
+ // Only it may send state-changing data messages (data-sender-auth.ts).
2204
+ let controllingUserIdentity = null;
2205
+ // Machine owner (Supabase user id), baked into machine env by the frontend
2206
+ // provisioning (platform-env.ts). Empty = single-tenant / local mode:
2207
+ // newest joiner becomes the controller. NOTE: machines provisioned before
2208
+ // this env existed lack it until their next create / update-osborn /
2209
+ // pool repoint re-bakes the env, and run in newest-joiner mode until then.
2210
+ const OWNER_USER_ID = (process.env.OSBORN_OWNER_USER_ID || '').trim();
2211
+ if (OWNER_USER_ID)
2212
+ console.log('🔐 Control bound to machine owner (OSBORN_OWNER_USER_ID set)');
2213
+ else
2214
+ console.log('🔓 OSBORN_OWNER_USER_ID unset: single-tenant mode, newest joiner controls the agent');
2091
2215
  let currentAgent = null; // For updateChatCtx() context injection
2092
2216
  let currentLLM = null;
2093
2217
  const slots = new Map();
@@ -2716,6 +2840,11 @@ async function main() {
2716
2840
  // ────────────────────────────────────────────────────────────────────────
2717
2841
  // LIVE meeting transcript → LLM (buffered webhook finals). See recall.on('transcript').
2718
2842
  const meetingTranscriptBuffer = [];
2843
+ // Phase C routing target: the Tier-2 worker the most recent addressed turn
2844
+ // named (@researcher …). Captured in recall.on('transcript') when addressing
2845
+ // is enabled, consumed (and cleared) by the next addressed flushMeetingBuffer,
2846
+ // which injects a Task-dispatch directive for it. Null = no pending routing.
2847
+ let meetingAddressedTarget = null;
2719
2848
  let meetingFlushTimer = null;
2720
2849
  // Flush the buffered meeting turns to the LLM. `addressed=true` (the agent was
2721
2850
  // called by name / asked directly) tags the message so the agent RESPONDS by
@@ -2751,9 +2880,36 @@ async function main() {
2751
2880
  // Prepend + consume any interruption context (bot was cut off mid-sentence).
2752
2881
  const interrupt = meetingInterruptContext ? `${meetingInterruptContext}\n` : '';
2753
2882
  meetingInterruptContext = '';
2883
+ // Phase C — route an addressed turn to a specific Tier-2 worker. When the
2884
+ // addressing layer is on and the last addressed utterance named a routable
2885
+ // worker (not the orchestrator), STEER THE SINGLE SDK SESSION by injecting a
2886
+ // directive so the orchestrator dispatches that named agent via its Task
2887
+ // tool (the existing noteTaskDispatch/claimTaskDispatch/statusManager
2888
+ // plumbing in claude-llm.ts handles the rest). No parallel query() is
2889
+ // spawned — currentLLM.chat() feeds the one persistent session. Gated on
2890
+ // live dispatch headroom (statusManager) so a busy room can't fan out
2891
+ // unboundedly. The directive goes AFTER the `[MEETING` prefix so the ambient
2892
+ // non-interrupting + suppressMeetingTTS keying on that prefix still hold.
2893
+ let routingDirective = '';
2894
+ const pendingTarget = meetingAddressedTarget;
2895
+ meetingAddressedTarget = null;
2896
+ if (addressed && meetingAddressing.enabled && isRoutableTarget(pendingTarget)) {
2897
+ const active = statusManager.getActiveDispatchIds().length;
2898
+ const cap = Math.max(1, Number(process.env.OSBORN_MEETING_MAX_DISPATCH) || 3);
2899
+ if (active < cap) {
2900
+ routingDirective =
2901
+ `[ROUTING] A participant addressed @${pendingTarget}. Dispatch the "${pendingTarget}" ` +
2902
+ `agent via the Task tool (subagent_type "${pendingTarget}") to handle this turn instead of ` +
2903
+ `answering yourself, then relay its result into the meeting.\n`;
2904
+ console.log(`🎯 [meeting-addr] routing addressed turn → @${pendingTarget} via Task directive (dispatches ${active}/${cap})`);
2905
+ }
2906
+ else {
2907
+ console.log(`🎯 [meeting-addr] @${pendingTarget} routing skipped — at concurrency cap (${active}/${cap}); orchestrator handles it`);
2908
+ }
2909
+ }
2754
2910
  try {
2755
2911
  const ctx = new llm.ChatContext();
2756
- ctx.addMessage({ role: 'user', content: `${interrupt}${header}\n${turns.join('\n')}` });
2912
+ ctx.addMessage({ role: 'user', content: `${interrupt}${header}\n${routingDirective}${turns.join('\n')}` });
2757
2913
  currentLLM.chat({ chatCtx: ctx });
2758
2914
  console.log(`📓 Flushed ${turns.length} meeting turn(s) to LLM${addressed ? ' (ADDRESSED — respond)' : ''}`);
2759
2915
  }
@@ -2831,6 +2987,8 @@ async function main() {
2831
2987
  activeMeetingBotId = null;
2832
2988
  meetingAddressedUntil = 0;
2833
2989
  meetingSpeakers.clear();
2990
+ meetingAddressedTarget = null;
2991
+ meetingAddressing.reset(); // inert when OSBORN_MEETING_ADDRESSING is unset (empty registry)
2834
2992
  // leaveBot=false when Recall itself reported the meeting over (bot already gone).
2835
2993
  if (opts.leaveBot !== false) {
2836
2994
  const recall = getRecallClient();
@@ -3194,12 +3352,42 @@ async function main() {
3194
3352
  recall.on('transcript', ({ botId, speaker, text, partial }) => {
3195
3353
  console.log(`📝 Meeting transcript [${speaker}]${partial ? ' (partial)' : ''}: ${text}`);
3196
3354
  if (!partial && text.trim()) {
3355
+ // Multi-agent meeting addressing/mute (OFF by default — set
3356
+ // OSBORN_MEETING_ADDRESSING=on to engage). When the flag is unset this
3357
+ // whole block is skipped: processUtterance() short-circuits and the
3358
+ // meeting path below behaves EXACTLY as before. When ON: a muted speaker
3359
+ // is dropped, a mute/unmute command updates the registry (and notifies
3360
+ // the frontend), and an addressed worker is captured for Phase-C routing
3361
+ // in the next addressed flush (see flushMeetingBuffer).
3362
+ if (meetingAddressing.enabled) {
3363
+ const verdict = meetingAddressing.processUtterance(speaker, text);
3364
+ if (verdict.muteChanged) {
3365
+ console.log(`🎛️ [meeting-addr] ${verdict.muteChanged.action} "${verdict.muteChanged.who}" — muted now: ${meetingAddressing.mutes.list().join(', ') || 'none'}`);
3366
+ emitMuteChanged(verdict.muteChanged.action, verdict.muteChanged.who);
3367
+ }
3368
+ if (verdict.drop) {
3369
+ console.log(`🔇 [meeting-addr] dropped utterance from muted speaker "${speaker}"`);
3370
+ return; // muted participant — do not buffer or forward to the LLM
3371
+ }
3372
+ if (verdict.target) {
3373
+ // Remember the addressed worker so the next addressed flush routes to
3374
+ // it (Phase C). Store regardless of routability so the UI can show the
3375
+ // chip; flushMeetingBuffer gates actual Task dispatch on isRoutableTarget.
3376
+ meetingAddressedTarget = verdict.target;
3377
+ console.log(`🎯 [meeting-addr] "${speaker}" addresses @${verdict.target}${isRoutableTarget(verdict.target) ? ' (will route to worker)' : ' (orchestrator — no worker dispatch)'}`);
3378
+ emitMeetingState(verdict.target);
3379
+ }
3380
+ }
3381
+ const isNewSpeaker = !meetingSpeakers.has(speaker);
3197
3382
  meetingTranscriptBuffer.push(`${speaker}: ${text.trim()}`);
3198
3383
  // Addressed by name → flush NOW (don't wait the 20s batch) and tag it so
3199
3384
  // the agent replies out loud into the meeting. This is the chat-mode path:
3200
3385
  // named/asked → prompt response. Un-addressed chunks stay in the silent
3201
3386
  // 20s batch for note-taking. That's the two-mode seam, mechanically.
3202
3387
  meetingSpeakers.add(speaker);
3388
+ // New participant → refresh the frontend's mute roster (flag-gated no-op).
3389
+ if (isNewSpeaker)
3390
+ emitMeetingState();
3203
3391
  // Fuzzy name match: meeting STT routinely mangles "Osborn" — observed
3204
3392
  // live 2026-08-01: "Osborn can you hear me" → "i was born can you hear
3205
3393
  // me" (name trigger missed, bot stayed silent). Accept common
@@ -3354,6 +3542,13 @@ async function main() {
3354
3542
  }
3355
3543
  console.log(`🤐 Suppressed text buffered (+${t.length} chars, total ${lastInterruption.suppressedText.length}): "${t.substring(0, 80)}${t.length > 80 ? '...' : ''}"`);
3356
3544
  }
3545
+ // L2b: client notices (favorite_changed) ride the next real user turn as
3546
+ // hidden context (PipelineDirectLLM getAndConsumeClientNotes), never as a
3547
+ // user_text turn. typedEchoes carries a typed message's clientMsgId onto its
3548
+ // user_transcript echo.
3549
+ const clientNotes = new ClientNoteQueue();
3550
+ const typedEchoes = new TypedEchoTracker();
3551
+ const getAndConsumeClientNotes = () => clientNotes.drain();
3357
3552
  /**
3358
3553
  * Callback for PipelineDirectLLM — returns pending interruption context and clears it.
3359
3554
  * Called in chat() when user's transcribed message arrives.
@@ -3602,6 +3797,31 @@ async function main() {
3602
3797
  console.error('❌ sendToFrontend error:', err);
3603
3798
  }
3604
3799
  }
3800
+ // ── Phase B — meeting addressing/mute state → frontend (over the EXISTING
3801
+ // 'osborn-updates' data channel). Both are NO-OPS when the flag is unset, so
3802
+ // an un-flagged meeting emits nothing new (zero behavior change). `meeting_state`
3803
+ // is the full snapshot (roster, known speakers, muted set, who was addressed);
3804
+ // `mute_changed` is the lightweight per-change delta. Function declarations so
3805
+ // they're reachable from the transcript handler + handleDataReceived above.
3806
+ function emitMeetingState(addressed = null) {
3807
+ if (!meetingAddressing.enabled)
3808
+ return;
3809
+ const st = meetingAddressing.state();
3810
+ void sendToFrontend({
3811
+ type: 'meeting_state',
3812
+ enabled: st.enabled,
3813
+ roster: st.roster,
3814
+ speakers: [...meetingSpeakers],
3815
+ muted: st.muted,
3816
+ addressed,
3817
+ });
3818
+ }
3819
+ function emitMuteChanged(action, who) {
3820
+ if (!meetingAddressing.enabled)
3821
+ return;
3822
+ void sendToFrontend({ type: 'mute_changed', action, who, muted: meetingAddressing.mutes.list() });
3823
+ emitMeetingState();
3824
+ }
3605
3825
  async function announceViaVoice(text) {
3606
3826
  if (!currentSession)
3607
3827
  return;
@@ -3700,6 +3920,19 @@ async function main() {
3700
3920
  // PipelineDirectLLM (llmOverride path) wraps its own ClaudeLLM and may not expose setTurbo.
3701
3921
  directLLM?.setTurbo?.(turboMode);
3702
3922
  currentLLM = directLLM;
3923
+ // Watch bridge (mobile Track 1): a wrist ack/expiry settles whatever
3924
+ // permission is currently pending. Re-registered per session — harmless,
3925
+ // the latest closure wins and they all resolve through currentLLM.
3926
+ setWatchResultHandler((allow, toolName) => {
3927
+ if (currentLLM?.hasPendingPermission?.()) {
3928
+ currentLLM.respondToPermission(allow);
3929
+ console.log(`⌚️ Watch bridge settled ${toolName}: ${allow ? 'approve' : 'deny'}`);
3930
+ }
3931
+ else {
3932
+ // Already answered via the web UI — a late ack/expiry is a no-op.
3933
+ console.log(`⌚️ Watch bridge ${allow ? 'ack' : 'expiry'} for ${toolName} — no pending permission, ignoring`);
3934
+ }
3935
+ });
3703
3936
  // P1 host-agent anchor: this dashboard-started session owns the room's env
3704
3937
  // and keeps it alive (agentsActive → true) so background dispatches survive.
3705
3938
  // Keep-alive keys off the hostActive boolean, NOT a session_id event;
@@ -3761,7 +3994,9 @@ async function main() {
3761
3994
  // Detect research artifact writes (session workspace or legacy research dir)
3762
3995
  if ((data.name === 'Write' || data.name === 'Edit') && data.input?.file_path) {
3763
3996
  const fp = data.input.file_path;
3764
- if (fp.includes('/osb/') || fp.includes('.osborn/sessions/') || fp.includes('.osborn/research/')) {
3997
+ // Robust root check (not a substring) — parity with the read gate so a
3998
+ // traversal path can't spoof a "research_artifact_updated" notification.
3999
+ if (isSafeArtifactPath(fp)) {
3765
4000
  sendToFrontend({
3766
4001
  type: 'research_artifact_updated',
3767
4002
  filePath: fp,
@@ -3897,6 +4132,10 @@ async function main() {
3897
4132
  agentRole: 'direct',
3898
4133
  diff: diffString,
3899
4134
  });
4135
+ // Watch bridge (mobile Track 1): mirror this blocking question to the
4136
+ // wrist via Pushover. Fire-and-forget — dormant unless PUSHOVER_* env is
4137
+ // configured; web-UI answers always win (late wrist acks are no-ops).
4138
+ void armPermissionPush({ toolName, description }).catch(() => { });
3900
4139
  // Speak the descriptive request so user knows to respond
3901
4140
  //do not delete!! Leave this section commented out
3902
4141
  // say permission, request permission, ask for permission with session.say
@@ -4458,6 +4697,28 @@ async function main() {
4458
4697
  console.log('📽️🔊 meeting-canvas joined the LiveKit room — native session.say relays to the meeting');
4459
4698
  return; // not a user; skip session setup for it
4460
4699
  }
4700
+ // Owner binding (data-sender-auth.ts resolveJoin): with OSBORN_OWNER_USER_ID
4701
+ // set (cloud machines), only a `user-*` participant whose SIGNED token
4702
+ // metadata userId is the owner takes the session and becomes the
4703
+ // controller; other users are ignored (no voice session, gated data
4704
+ // dropped). With no owner configured (single-tenant / local), the newest
4705
+ // `user-*` joiner wins, as before. The watch gateway (our own identity)
4706
+ // never becomes the controller, so the owner's commands keep working; it
4707
+ // may still send permission_response. It gets the voice session only when
4708
+ // no controller exists (watch voice alone); joining after the owner it is
4709
+ // not adopted, so the owner's session and currentUserId stay intact.
4710
+ const joinerUserId = userIdFromMetadata(participant.metadata);
4711
+ const join = resolveJoin(participant.identity, joinerUserId, OWNER_USER_ID, controllingUserIdentity);
4712
+ controllingUserIdentity = join.controller;
4713
+ if (!join.adoptSession) {
4714
+ if (participant.identity === AGENT_SELF_IDENTITY) {
4715
+ console.log(`⌚ ${participant.identity} joined while ${controllingUserIdentity} controls the session; keeping the owner's voice session`);
4716
+ }
4717
+ else {
4718
+ console.warn(`🚫 ${participant.identity} is not the machine owner (token userId=${joinerUserId ?? 'none'}); not adopting it as the voice user`);
4719
+ }
4720
+ return;
4721
+ }
4461
4722
  // A user (re)arriving cancels the meeting leave-grace — the bot stays.
4462
4723
  cancelMeetingLeaveGrace();
4463
4724
  // A user is present — cancel any pending agent-side "alone" leave.
@@ -4656,6 +4917,7 @@ async function main() {
4656
4917
  }
4657
4918
  },
4658
4919
  getAndConsumeInterruptionContext,
4920
+ getAndConsumeClientNotes,
4659
4921
  onFastBrainResult: (result) => {
4660
4922
  console.log(`🧠⚡ [FAST_BRAIN ${result.type.toUpperCase()} +${result.elapsedMs}ms]: "${result.answer.substring(0, 60)}"`);
4661
4923
  sendToFrontend({
@@ -4705,19 +4967,28 @@ async function main() {
4705
4967
  let lastSentUserTranscript = '';
4706
4968
  let lastSentAgentTranscript = '';
4707
4969
  function sendUserTranscript(transcript, source) {
4708
- if (!transcript || transcript.length < 3)
4709
- return;
4710
- const normalized = transcript.trim().replace(/\s+/g, ' ');
4711
- if (normalized === lastSentUserTranscript)
4970
+ if (!transcript)
4712
4971
  return;
4713
- if (normalized === '<noise>' || normalized.toLowerCase() === 'thank you')
4972
+ // A typed message (user_text) echoes back here with its frontend
4973
+ // clientMsgId so the UI can dedupe its optimistic bubble (L2b).
4974
+ const typed = typedEchoes.take(transcript);
4975
+ const clientMsgId = typed?.clientMsgId;
4976
+ // Shared sanitizer (L2b): drops the frontend [time:] tag, injected
4977
+ // blocks and client/voice-injection notices ([favorited],
4978
+ // [welcome-back], [SCRIPT]/[PROACTIVE]/[NOTIFICATION] — Gemini v1.0.51:
4979
+ // userInput in generateReply creates a user conversation item), plus
4980
+ // <noise> / "thank you". null = nothing the user said.
4981
+ const text = userEchoText(transcript, typed?.attachments);
4982
+ if (!text)
4714
4983
  return;
4715
- // Filter out voice injection content that appears as user transcript
4716
- // (Gemini v1.0.51: userInput in generateReply creates a user conversation item)
4717
- if (normalized.startsWith('[SCRIPT]') || normalized.startsWith('[PROACTIVE]') || normalized.startsWith('[NOTIFICATION]'))
4984
+ const normalized = text.replace(/\s+/g, ' ');
4985
+ // A distinct typed message may repeat the previous text on purpose.
4986
+ if (!clientMsgId && normalized === lastSentUserTranscript)
4718
4987
  return;
4719
4988
  console.log(`📝 User (${source}, ${transcript.length} chars): "${transcript}"`);
4720
- sendToFrontend({ type: 'user_transcript', text: transcript });
4989
+ sendToFrontend(clientMsgId
4990
+ ? { type: 'user_transcript', text, clientMsgId }
4991
+ : { type: 'user_transcript', text });
4721
4992
  lastSentUserTranscript = normalized;
4722
4993
  if (connectTiming && !connectTiming.sawUserMsg) {
4723
4994
  connectTiming.sawUserMsg = true;
@@ -4760,6 +5031,14 @@ async function main() {
4760
5031
  agentState = ev.newState;
4761
5032
  // Clear processing guard when model transitions to any new state
4762
5033
  isProcessingQueue = false;
5034
+ // Native duck: never leave the next utterance quiet
5035
+ if (ev.newState !== 'speaking') {
5036
+ if (duckRestoreTimer) {
5037
+ clearTimeout(duckRestoreTimer);
5038
+ duckRestoreTimer = null;
5039
+ }
5040
+ currentDuck?.setDuck(1, 'agent ' + ev.newState);
5041
+ }
4763
5042
  console.log(`🤖 State: ${ev.newState}`);
4764
5043
  sendToFrontend({ type: 'agent_state', state: ev.newState });
4765
5044
  // When the model becomes available (listening), process any queued voice injections
@@ -4779,6 +5058,24 @@ async function main() {
4779
5058
  const prev = userState;
4780
5059
  userState = ev.newState;
4781
5060
  console.log(`👤 User state: ${prev} → ${ev.newState} (agent: ${agentState})`);
5061
+ // Native duck: drop agent TTS to DUCK_LEVEL while the user talks over it;
5062
+ // restore 250ms after they go quiet (cancelled if they speak again).
5063
+ if (ev.newState === 'speaking') {
5064
+ if (duckRestoreTimer) {
5065
+ clearTimeout(duckRestoreTimer);
5066
+ duckRestoreTimer = null;
5067
+ }
5068
+ if (agentState === 'speaking')
5069
+ currentDuck?.setDuck(DUCK_LEVEL, 'user speaking');
5070
+ }
5071
+ else {
5072
+ if (duckRestoreTimer)
5073
+ clearTimeout(duckRestoreTimer);
5074
+ duckRestoreTimer = setTimeout(() => {
5075
+ duckRestoreTimer = null;
5076
+ currentDuck?.setDuck(1, 'user quiet');
5077
+ }, 250);
5078
+ }
4782
5079
  if (ev.newState === 'speaking' && agentState === 'speaking') {
4783
5080
  // 0.9.67: action commented out, condition + debug kept.
4784
5081
  //
@@ -4885,6 +5182,8 @@ async function main() {
4885
5182
  // Whatever else SDK provides — dump it all for now
4886
5183
  fields: Object.keys(ev),
4887
5184
  }));
5185
+ if (ev.isInterruption === false)
5186
+ currentDuck?.setDuck(1, 'overlap not interruption');
4888
5187
  });
4889
5188
  // agent_false_interruption — the SDK's "actually that was a false alarm,
4890
5189
  // resuming TTS" event. Fires falseInterruptionTimeout after a pause.
@@ -4896,6 +5195,7 @@ async function main() {
4896
5195
  resumed: ev.resumed,
4897
5196
  createdAt: ev.createdAt,
4898
5197
  }));
5198
+ currentDuck?.setDuck(1, 'false interruption');
4899
5199
  });
4900
5200
  // speech_created — every time TTS audio is queued. Lets us correlate
4901
5201
  // a speech-handle id back to the transcript that triggered it.
@@ -5113,6 +5413,7 @@ async function main() {
5113
5413
  }
5114
5414
  },
5115
5415
  getAndConsumeInterruptionContext,
5416
+ getAndConsumeClientNotes,
5116
5417
  onFastBrainResult: (r) => {
5117
5418
  console.log(`🧠⚡ [FAST_BRAIN ${r.type.toUpperCase()} +${r.elapsedMs}ms]: "${r.answer.substring(0, 60)}"`);
5118
5419
  sendToFrontend({
@@ -5131,6 +5432,7 @@ async function main() {
5131
5432
  // Re-wire event listeners on the new session
5132
5433
  wireSessionEvents(newSession, newAgent);
5133
5434
  await newSession.start({ agent: newAgent, room: activeRoom });
5435
+ currentDuck = installDuck(newSession);
5134
5436
  // Sync state
5135
5437
  agentState = 'listening';
5136
5438
  sendToFrontend({ type: 'agent_state', state: 'listening' });
@@ -5173,6 +5475,7 @@ async function main() {
5173
5475
  console.log('🎬 Starting voice session...');
5174
5476
  try {
5175
5477
  await session.start({ agent, room: activeRoom });
5478
+ currentDuck = installDuck(session);
5176
5479
  console.log('✅ Voice session started!');
5177
5480
  console.log('🎤 Ready - speak to begin!\n');
5178
5481
  // Workspace is created later in the session_id event handler (when SDK assigns real ID)
@@ -5302,14 +5605,14 @@ async function main() {
5302
5605
  if (dbPath) {
5303
5606
  const db = openStore(dbPath, { readonly: true });
5304
5607
  try {
5305
- const rows = recentRows(db, 20, ['user', 'assistant']); // newest-first
5306
- const priorMessages = rows
5307
- .reverse() // → chronological
5308
- .map(r => ({ role: r.msgType === 'assistant' ? 'assistant' : 'user', content: (r.text || '').slice(0, 800), ts: r.ts || null }))
5309
- .filter(m => m.content.trim().length > 0);
5608
+ // Sanitized before truncation, over-fetched, chronological (L2b).
5609
+ const priorMessages = cleanHistoryRows(n => recentRows(db, n, ['user', 'assistant']), 20, 800);
5610
+ // Durable compaction markers ride the same push so the resumed
5611
+ // transcript rebuilds its "Conversation compacted" rows too.
5612
+ const compactions = readCompactionMarkers(preSelectedSessionId, workingDir);
5310
5613
  if (priorMessages.length > 0) {
5311
- await sendToFrontend({ type: 'prior_messages', sessionId: preSelectedSessionId, messages: priorMessages });
5312
- console.log(`💬 Sent ${priorMessages.length} prior messages from DB for optimistic UI`);
5614
+ await sendToFrontend({ type: 'prior_messages', sessionId: preSelectedSessionId, messages: priorMessages, compactions });
5615
+ console.log(`💬 Sent ${priorMessages.length} prior messages (+${compactions.length} compaction markers) from DB for optimistic UI`);
5313
5616
  }
5314
5617
  }
5315
5618
  finally {
@@ -5378,6 +5681,8 @@ async function main() {
5378
5681
  // participantConnectedHandler above).
5379
5682
  const handleParticipantDisconnected = (participant) => {
5380
5683
  console.log(`👋 User left: ${participant.identity}`);
5684
+ if (participant.identity === controllingUserIdentity)
5685
+ controllingUserIdentity = null;
5381
5686
  // Full cleanup — stop all background work to avoid accumulating API usage
5382
5687
  voiceQueue.length = 0;
5383
5688
  isProcessingQueue = false;
@@ -5484,11 +5789,50 @@ async function main() {
5484
5789
  try {
5485
5790
  const data = JSON.parse(new TextDecoder().decode(payload));
5486
5791
  console.log('📨 Data:', data.type);
5792
+ const senderCheck = checkControlSender(String(data.type), participant?.identity, controllingUserIdentity);
5793
+ if (!senderCheck.ok) {
5794
+ console.warn(`🚫 Dropped ${data.type}: ${senderCheck.reason}`);
5795
+ return;
5796
+ }
5487
5797
  if (data.type === 'claude_auth_code' && pendingAuthSubmitCode) {
5488
5798
  console.log('🔑 Received auth code from frontend');
5489
5799
  sendToFrontend({ type: 'claude_auth_submitting', message: 'Submitting code to Claude CLI...' });
5490
5800
  pendingAuthSubmitCode(data.code);
5491
5801
  }
5802
+ else if (data.type === 'claude_auth_start') {
5803
+ // On-demand Claude sign-in. When a fallback key exists the join path
5804
+ // skips the blocking OAuth (claude_auth_optional), so this is the only
5805
+ // way to start it. Owner-gated via CONTROL_MESSAGE_TYPES.
5806
+ const authSend = (type, payload) => {
5807
+ sendToFrontend({ type, ...payload });
5808
+ };
5809
+ if (pendingAuthSubmitCode && !isOnDemandAuthInFlight()) {
5810
+ // The join-path flow is already running — re-deliver its state.
5811
+ console.log('🔑 claude_auth_start: join-path flow in flight — replaying state');
5812
+ replayInFlightAuth(authSend);
5813
+ }
5814
+ else {
5815
+ // Not awaited: done only settles when the user finishes (or the 5-min
5816
+ // timeout), and this handler must stay responsive (claude_auth_code).
5817
+ const { started, result } = startClaudeAuthOnDemand(authSend, {
5818
+ get: () => pendingAuthSubmitCode,
5819
+ set: (fn) => { pendingAuthSubmitCode = fn; },
5820
+ });
5821
+ if (!started) {
5822
+ replayInFlightAuth(authSend);
5823
+ }
5824
+ else {
5825
+ console.log('🔑 claude_auth_start: starting on-demand Claude OAuth');
5826
+ void result.then(({ fallbackCleared }) => {
5827
+ // Only when a fallback redirect was actually active: live persistent
5828
+ // sessions restart BEFORE their next turn (deferred — a streaming
5829
+ // turn finishes normally), resuming the same sessionId on Claude.
5830
+ if (fallbackCleared)
5831
+ requestAuthRestart();
5832
+ });
5833
+ }
5834
+ }
5835
+ }
5492
5836
  else if (data.type === 'permission_response') {
5493
5837
  // Handle permission response for direct mode
5494
5838
  if (currentLLM && currentLLM.hasPendingPermission?.()) {
@@ -5502,7 +5846,26 @@ async function main() {
5502
5846
  console.log(`✅ Permission: ${data.response}`);
5503
5847
  }
5504
5848
  }
5849
+ else if (data.type === 'favorite_changed') {
5850
+ // L2b (UI#21): a favorite is a UI action, not something the user said.
5851
+ // Queue it as hidden context for the next real user turn; no reply, no
5852
+ // user_transcript echo, no JSONL user turn of its own.
5853
+ const change = parseFavoriteChanged(data);
5854
+ if (change) {
5855
+ clientNotes.favoriteChanged(change);
5856
+ console.log(`⭐ favorite_changed: ${change.fileName} → ${change.favorited ? 'on' : 'off'} (queued as context)`);
5857
+ }
5858
+ }
5505
5859
  else if (data.type === 'user_text' && currentSession) {
5860
+ // Backward compat: older frontends send a favorite as user_text
5861
+ // "[time: …] [favorited] The user favorited the file X." — route it to
5862
+ // the same context queue instead of starting a user turn.
5863
+ const legacyFavorite = parseLegacyFavoriteNotice(String(data.content || ''));
5864
+ if (legacyFavorite && !(Array.isArray(data.files) && data.files.length)) {
5865
+ clientNotes.favoriteChanged(legacyFavorite);
5866
+ console.log(`⭐ legacy [favorited] user_text → context note: ${legacyFavorite.fileName}`);
5867
+ return;
5868
+ }
5506
5869
  // Build message content — include attached files (URLs, text content)
5507
5870
  let fullContent = String(data.content || '');
5508
5871
  const files = data.files;
@@ -5523,6 +5886,9 @@ async function main() {
5523
5886
  else {
5524
5887
  console.log(`📝 Text (${fullContent.length} chars): "${fullContent}"`);
5525
5888
  }
5889
+ // The session echoes this item as user_transcript; carry the frontend's
5890
+ // clientMsgId (bubble dedupe) and the attachment blocks onto that echo.
5891
+ typedEchoes.register(fullContent, data.clientMsgId, fullContent.slice(String(data.content || '').length));
5526
5892
  // Skip interrupt for Gemini — disrupts state machine (hangs in speaking state)
5527
5893
  if (true) { // always non-gemini in pipeline mode
5528
5894
  currentSession.interrupt();
@@ -5544,16 +5910,7 @@ async function main() {
5544
5910
  // Sent here too so the in-chat session list grouping stays
5545
5911
  // consistent with the dashboard's grouping.
5546
5912
  baseCwd: workingDir,
5547
- sessions: sessions.map(s => ({
5548
- sessionId: s.sessionId,
5549
- projectSlug: s.projectSlug,
5550
- projectPath: s.projectPath,
5551
- cwd: s.cwd,
5552
- timestamp: s.timestamp.toISOString(),
5553
- lastMessage: s.lastMessage,
5554
- messageCount: s.messageCount,
5555
- fileSize: s.fileSize,
5556
- })),
5913
+ sessions: sessions.map(sessionListEntry),
5557
5914
  count: sessions.length,
5558
5915
  });
5559
5916
  }
@@ -5790,7 +6147,9 @@ async function main() {
5790
6147
  // ============================================================
5791
6148
  else if (data.type === 'get_plan_file') {
5792
6149
  const filePath = data.filePath;
5793
- if (filePath && filePath.includes('.claude/plans/')) {
6150
+ // SECURITY: same reachable read-only primitive as get_research_artifact —
6151
+ // gate the plan dir with a resolve+root-prefix check, not a substring.
6152
+ if (filePath && isSafeArtifactPath(filePath, ['plans'])) {
5794
6153
  try {
5795
6154
  const fs = await import('fs');
5796
6155
  const content = fs.readFileSync(filePath, 'utf-8');
@@ -5803,7 +6162,10 @@ async function main() {
5803
6162
  }
5804
6163
  else if (data.type === 'get_research_artifact') {
5805
6164
  const filePath = data.filePath;
5806
- if (filePath && (filePath.includes('/osb/') || filePath.includes('.osborn/sessions/') || filePath.includes('.osborn/research/'))) {
6165
+ // SECURITY: resolve + canonicalize + root-prefix check (NOT a substring
6166
+ // test). This handler is read-only and reachable by ANY room participant,
6167
+ // so a substring gate let `…/osb/../../../etc/passwd` be read + uploaded.
6168
+ if (filePath && isSafeArtifactPath(filePath)) {
5807
6169
  try {
5808
6170
  const fs = await import('fs');
5809
6171
  const path = await import('path');
@@ -6211,6 +6573,20 @@ async function main() {
6211
6573
  recallJoin.registerBot(botId, sessionId);
6212
6574
  activeMeetingBotId = botId;
6213
6575
  await sendToFrontend({ type: 'meeting_joined', botId, message: 'Osborn has joined the meeting' });
6576
+ // Phase B — point the addressable roster at the REAL effective
6577
+ // agent set (built-ins minus user-removed, plus per-user agents),
6578
+ // same effective set get_agents/set_agents compute, with the
6579
+ // orchestrator ('osborn') first. Flag-gated: a no-op (no roster
6580
+ // change, no emit) when OSBORN_MEETING_ADDRESSING is unset.
6581
+ if (meetingAddressing.enabled) {
6582
+ const base = { ...NAMED_AGENTS };
6583
+ for (const r of userRemovedAgents)
6584
+ delete base[r];
6585
+ const effective = { ...base, ...(userNamedAgents || {}) };
6586
+ meetingAddressing.setRoster(['osborn', ...Object.keys(effective)]);
6587
+ console.log(`🎛️ [meeting-addr] roster → [${meetingAddressing.rosterIds.join(', ')}]`);
6588
+ emitMeetingState();
6589
+ }
6214
6590
  // Minimal awareness injection (user directive 2026-08-04): tell the
6215
6591
  // LLM it's in a meeting and how transcripts are tagged — nothing
6216
6592
  // more. NO "do NOT speak / silent observer" coaching (that fought
@@ -6287,6 +6663,22 @@ async function main() {
6287
6663
  await sendToFrontend({ type: 'meeting_error', message: err.message });
6288
6664
  }
6289
6665
  }
6666
+ // Phase B — authenticated frontend mute/unmute of a meeting participant.
6667
+ // Controller-only: checkControlSender fails CLOSED for any type not on the
6668
+ // read-only list, so this gated type already requires the controlling user.
6669
+ // Flag-gated: ignored entirely unless OSBORN_MEETING_ADDRESSING is on (the
6670
+ // MuteRegistry is only consulted by processUtterance when enabled anyway).
6671
+ else if (data.type === 'mute_participant') {
6672
+ if (meetingAddressing.enabled) {
6673
+ const action = data.action === 'unmute' ? 'unmute' : 'mute';
6674
+ const who = String(data.who || '').trim();
6675
+ const applied = who ? meetingAddressing.applyMuteControl(action, who) : null;
6676
+ if (applied) {
6677
+ console.log(`🎛️ [meeting-addr] ${applied.action} "${applied.who}" via control — muted now: ${meetingAddressing.mutes.list().join(', ') || 'none'}`);
6678
+ emitMuteChanged(applied.action, applied.who);
6679
+ }
6680
+ }
6681
+ }
6290
6682
  // ── IDE (code-server) handlers ──────────────────────────────────────
6291
6683
  else if (data.type === 'start_ide') {
6292
6684
  try {
@@ -6295,10 +6687,14 @@ async function main() {
6295
6687
  const flyAppHost = process.env.FLY_APP_NAME
6296
6688
  ? `${process.env.FLY_APP_NAME}.fly.dev`
6297
6689
  : (process.env.OSBORN_PUBLIC_HOST || `localhost:${apiPort}`);
6298
- const ideUrl = process.env.FLY_APP_NAME
6690
+ // Mint an owner-only access token into the URL. The frontend opens it
6691
+ // verbatim; a direct hit to /editor without it is refused (RCE fix).
6692
+ const editorTok = mintEditorToken();
6693
+ const tokQs = editorTok ? `?t=${encodeURIComponent(editorTok)}` : '';
6694
+ const ideUrl = (process.env.FLY_APP_NAME
6299
6695
  ? `https://${flyAppHost}/editor`
6300
- : `http://${flyAppHost}/editor`;
6301
- console.log(`✅ IDE proxy ready: ${ideUrl}`);
6696
+ : `http://${flyAppHost}/editor`) + tokQs;
6697
+ console.log(`✅ IDE proxy ready: ${process.env.FLY_APP_NAME ? `https://${flyAppHost}/editor` : ideUrl}${editorTok ? ' (token-gated)' : ''}`);
6302
6698
  await sendToFrontend({ type: 'ide_ready', url: ideUrl });
6303
6699
  }
6304
6700
  catch (err) {