osborn 0.9.272 → 0.9.274

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -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
@@ -45,13 +45,17 @@ import { createSmitheryProxy, destroySmitheryProxy, parseSmitheryUrl, isSmithery
45
45
  import { DIRECT_MODE_PROMPT } from './prompts.js';
46
46
  import { MCP_CATALOG } from './config.js';
47
47
  import { storeExists, openStore, recentRows } from './session-store.js';
48
+ import { readCompactionMarkers } from './compaction-log.js';
49
+ import { sessionListEntry, cleanHistoryRows, userEchoText, TypedEchoTracker, ClientNoteQueue, parseFavoriteChanged, parseLegacyFavoriteNotice } from './transcript-wiring.js';
48
50
  import { getRecallClient } from './recall-client.js';
49
51
  import { MeetingTranscriptPoller } from './meeting-transcript-poller.js';
50
52
  import { missingRequiredEnv } from './env-keys.js';
51
53
  import { armPermissionPush, handleWatchAck, setWatchResultHandler } from './pushover.js';
52
54
  import { startWatchGateway } from './watch-gateway.js';
53
55
  import { noiseGate } from './noise-gate.js';
56
+ import { meetingAddressing, isRoutableTarget } from './meeting-addressing.js';
54
57
  import { listSecretStatus, setSecrets, deleteSecret } from './secrets-store.js';
58
+ import { AGENT_SELF_IDENTITY, checkControlSender, resolveJoin, userIdFromMetadata } from './data-sender-auth.js';
55
59
  import { llm } from '@livekit/agents';
56
60
  // ============================================================
57
61
  // PIPELINE MODE: STT (Deepgram) → Claude Agent SDK → TTS
@@ -342,6 +346,48 @@ wsProxy.on('error', (err, _req, socket) => {
342
346
  // valid cookie are forwarded, so a forgotten agent route can never be silently
343
347
  // swallowed by the IDE proxy. Cleared in stopIde().
344
348
  let ideSessionToken = null;
349
+ // ── /editor access token (closes the unauthenticated-RCE hole) ──────────────
350
+ // The agent's HTTP server is public (0.0.0.0:8741 via fly.toml). GET /editor
351
+ // used to mint the osborn_ide cookie with NO auth, and code-server runs
352
+ // --auth none — so anyone who knew a machine's fly.dev address could open the
353
+ // IDE/terminal = remote code execution on the paying owner's machine.
354
+ //
355
+ // Fix: /editor now requires a short-lived HMAC token. The token is minted with
356
+ // OSBORN_SYNC_TOKEN (the per-machine owner secret) and embedded in the ideUrl
357
+ // the agent hands back over the LiveKit data channel — which is already
358
+ // owner-gated (control commands bound to OSBORN_OWNER_USER_ID). So only the
359
+ // owner ever receives a valid token; a direct hit to /editor without it is
360
+ // refused. Local dev (no FLY_APP_NAME) is localhost-only and skips the gate.
361
+ const EDITOR_TOKEN_TTL_MS = 24 * 60 * 60 * 1000; // long-lived: the URL is owner-only; avoids breaking "open editor later"
362
+ function mintEditorToken() {
363
+ const secret = process.env.OSBORN_SYNC_TOKEN;
364
+ if (!secret)
365
+ return '';
366
+ const exp = Date.now() + EDITOR_TOKEN_TTL_MS;
367
+ const sig = createHmac('sha256', secret).update(`editor:${exp}`).digest('base64url');
368
+ return `${exp}.${sig}`;
369
+ }
370
+ function verifyEditorToken(tok) {
371
+ const secret = process.env.OSBORN_SYNC_TOKEN;
372
+ if (!secret || !tok)
373
+ return false; // cloud with no secret → fail CLOSED
374
+ const dot = tok.indexOf('.');
375
+ if (dot < 0)
376
+ return false;
377
+ const exp = Number(tok.slice(0, dot));
378
+ if (!Number.isFinite(exp) || exp < Date.now())
379
+ return false;
380
+ const expected = createHmac('sha256', secret).update(`editor:${exp}`).digest('base64url');
381
+ const got = tok.slice(dot + 1);
382
+ if (got.length !== expected.length)
383
+ return false;
384
+ try {
385
+ return timingSafeEqual(Buffer.from(got), Buffer.from(expected));
386
+ }
387
+ catch {
388
+ return false;
389
+ }
390
+ }
345
391
  // Cancellation-generation guard for startCodeServer(). Incremented by stopIde()
346
392
  // every time the IDE is torn down. startCodeServer() captures myGen at entry;
347
393
  // if ideStartGeneration !== myGen when the poll resolves, the start has been
@@ -526,7 +572,32 @@ function startApiServer(workingDir, port) {
526
572
  }
527
573
  const url = new URL(req.url || '/', `http://localhost:${port}`);
528
574
  const syncToken = process.env.OSBORN_SYNC_TOKEN;
575
+ // Fail-closed auth for the sensitive session/ops routes. Requires
576
+ // `Authorization: Bearer <OSBORN_SYNC_TOKEN>` whenever we're on a cloud
577
+ // machine (FLY_APP_NAME set) OR a sync token is configured. Local dev with
578
+ // no token stays open. Writes 401 and returns true when NOT authorized, so
579
+ // a caller does `if (unauthorized()) return`. This replaces the old
580
+ // fail-OPEN `if (syncToken) { ... }` pattern (which left these routes wide
581
+ // open on any machine that hadn't set a token).
582
+ const unauthorized = () => {
583
+ const requireAuth = !!process.env.FLY_APP_NAME || !!syncToken;
584
+ if (requireAuth && req.headers['authorization'] !== `Bearer ${syncToken}`) {
585
+ res.writeHead(401, { 'Content-Type': 'application/json' });
586
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
587
+ return true;
588
+ }
589
+ return false;
590
+ };
529
591
  if (req.method === 'GET' && url.pathname === '/sessions') {
592
+ // Fail-closed in cloud: session lists reach only the owner (via the
593
+ // authenticated /api/agent proxy, which forwards Bearer OSBORN_SYNC_TOKEN).
594
+ // A direct hit to the public fly.dev address is rejected. Local dev
595
+ // (no FLY_APP_NAME) is localhost-only and stays open.
596
+ if (process.env.FLY_APP_NAME && (!syncToken || req.headers['authorization'] !== `Bearer ${syncToken}`)) {
597
+ res.writeHead(401, { 'Content-Type': 'application/json' });
598
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
599
+ return;
600
+ }
530
601
  try {
531
602
  const limit = Math.min(parseInt(url.searchParams.get('limit') || '500', 10), 1000);
532
603
  const sessions = await listAllClaudeSessions(limit);
@@ -539,16 +610,9 @@ function startApiServer(workingDir, port) {
539
610
  // hardcoded base-path list — agent self-describes its base so
540
611
  // the UI doesn't have to keep a sync'd copy.
541
612
  baseCwd: workingDir,
542
- sessions: sessions.map(s => ({
543
- sessionId: s.sessionId,
544
- projectSlug: s.projectSlug,
545
- projectPath: s.projectPath,
546
- cwd: s.cwd,
547
- timestamp: s.timestamp.toISOString(),
548
- lastMessage: s.lastMessage,
549
- messageCount: s.messageCount,
550
- fileSize: s.fileSize,
551
- })),
613
+ // sessionListEntry carries the L2a preview fields too (title, firstTs,
614
+ // lastActivityAt) so the dashboard can stop deriving them itself.
615
+ sessions: sessions.map(sessionListEntry),
552
616
  total: sessions.length,
553
617
  };
554
618
  res.writeHead(200, { 'Content-Type': 'application/json' });
@@ -568,6 +632,12 @@ function startApiServer(workingDir, port) {
568
632
  // store directly (readonly, no JSONL replay) — same source as the
569
633
  // data-channel prior_messages push, which remains the fallback for older
570
634
  // frontends. Rows carry real timestamps so the UI can date-stamp them.
635
+ // Fail-closed in cloud (real transcript content; owner-only via proxy).
636
+ if (process.env.FLY_APP_NAME && (!syncToken || req.headers['authorization'] !== `Bearer ${syncToken}`)) {
637
+ res.writeHead(401, { 'Content-Type': 'application/json' });
638
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
639
+ return;
640
+ }
571
641
  try {
572
642
  const sessionId = url.searchParams.get('session') || '';
573
643
  const limit = Math.min(parseInt(url.searchParams.get('limit') || '50', 10), 200);
@@ -576,21 +646,23 @@ function startApiServer(workingDir, port) {
576
646
  res.end(JSON.stringify({ error: 'session required' }));
577
647
  return;
578
648
  }
649
+ // Durable compaction markers (sidecar, not the derived store) so a
650
+ // resumed transcript rebuilds every past "Conversation compacted" row at
651
+ // its real position — the store rebuild can't wipe these.
652
+ const compactions = readCompactionMarkers(sessionId, workingDir);
579
653
  const dbPath = storeExists(sessionId, workingDir);
580
654
  if (!dbPath) {
581
655
  res.writeHead(200, { 'Content-Type': 'application/json' });
582
- res.end(JSON.stringify({ sessionId, messages: [] }));
656
+ res.end(JSON.stringify({ sessionId, messages: [], compactions }));
583
657
  return;
584
658
  }
585
659
  const db = openStore(dbPath, { readonly: true });
586
660
  try {
587
- const rows = recentRows(db, limit, ['user', 'assistant']);
588
- const messages = rows
589
- .reverse() // newest-first → chronological
590
- .map(r => ({ role: r.msgType === 'assistant' ? 'assistant' : 'user', content: (r.text || '').slice(0, 1200), ts: r.ts || null }))
591
- .filter(m => m.content.trim().length > 0);
661
+ // Sanitize BEFORE truncating, over-fetching so rows the sanitizer drops
662
+ // (notices, injected blocks) don't shrink the page (L2b).
663
+ const messages = cleanHistoryRows(n => recentRows(db, n, ['user', 'assistant']), limit, 1200);
592
664
  res.writeHead(200, { 'Content-Type': 'application/json' });
593
- res.end(JSON.stringify({ sessionId, messages }));
665
+ res.end(JSON.stringify({ sessionId, messages, compactions }));
594
666
  }
595
667
  finally {
596
668
  try {
@@ -839,6 +911,8 @@ function startApiServer(workingDir, port) {
839
911
  }
840
912
  // POST /restart — graceful process restart (process manager will restart)
841
913
  if (req.method === 'POST' && url.pathname === '/restart') {
914
+ if (unauthorized())
915
+ return; // was unauthenticated: anyone with the address could kill the agent
842
916
  res.writeHead(200, { 'Content-Type': 'application/json' });
843
917
  res.end(JSON.stringify({ success: true, message: 'Agent restarting...' }));
844
918
  console.log('🔄 Restart requested via HTTP — exiting for process manager restart');
@@ -1040,14 +1114,8 @@ function startApiServer(workingDir, port) {
1040
1114
  // Optional ?workDir= query param accepted for backwards compat but ignored
1041
1115
  // (full export is always returned).
1042
1116
  if (req.method === 'GET' && url.pathname === '/sessions/export') {
1043
- if (syncToken) {
1044
- const authHeader = req.headers['authorization'] ?? '';
1045
- if (authHeader !== `Bearer ${syncToken}`) {
1046
- res.writeHead(401, { 'Content-Type': 'application/json' });
1047
- res.end(JSON.stringify({ error: 'Unauthorized' }));
1048
- return;
1049
- }
1050
- }
1117
+ if (unauthorized())
1118
+ return; // fail-closed (was fail-open: no token set → open)
1051
1119
  const claudeDir = join(homedir(), '.claude');
1052
1120
  const projectsDir = join(claudeDir, 'projects');
1053
1121
  const skillsDir = join(claudeDir, 'skills');
@@ -1087,6 +1155,8 @@ function startApiServer(workingDir, port) {
1087
1155
  // for the MVP — a per-share access token is a follow-up (tracked in
1088
1156
  // shared_sessions). sessionId is regex-validated to block path traversal.
1089
1157
  if (req.method === 'GET' && url.pathname === '/sessions/export-one') {
1158
+ if (unauthorized())
1159
+ return; // fail-closed; the sharing export leg now goes through the authed /api/agent proxy
1090
1160
  const sessionId = (url.searchParams.get('sessionId') || '').trim();
1091
1161
  if (!sessionId || !/^[a-zA-Z0-9._-]+$/.test(sessionId)) {
1092
1162
  res.writeHead(400, { 'Content-Type': 'application/json' });
@@ -1314,6 +1384,8 @@ function startApiServer(workingDir, port) {
1314
1384
  return { filesWritten, remapped, skillsWritten };
1315
1385
  };
1316
1386
  if (req.method === 'GET' && url.pathname === '/sessions/manifest') {
1387
+ if (unauthorized())
1388
+ return; // was public/no-auth: leaked the full session+skill file tree
1317
1389
  // Walks BOTH ~/.claude/projects/ AND ~/.claude/skills/ — full tree per
1318
1390
  // top-level directory.
1319
1391
  // - projects/<slug>/<...> → session JSONLs, sub-agent transcripts, tool-results, osb/
@@ -1375,14 +1447,8 @@ function startApiServer(workingDir, port) {
1375
1447
  }
1376
1448
  // POST /sessions/import — accept a gzipped tar and extract into ~/.claude/projects/
1377
1449
  if (req.method === 'POST' && url.pathname === '/sessions/import') {
1378
- if (syncToken) {
1379
- const authHeader = req.headers['authorization'] ?? '';
1380
- if (authHeader !== `Bearer ${syncToken}`) {
1381
- res.writeHead(401, { 'Content-Type': 'application/json' });
1382
- res.end(JSON.stringify({ error: 'Unauthorized' }));
1383
- return;
1384
- }
1385
- }
1450
+ if (unauthorized())
1451
+ return; // fail-closed (was fail-open)
1386
1452
  // 0.9.74: default targetWorkDir to this machine's own working directory.
1387
1453
  // Stale sync clients that omit the param used to get source slugs written
1388
1454
  // verbatim — those sessions LIST fine (the scanner walks all slugs) but
@@ -1455,14 +1521,8 @@ function startApiServer(workingDir, port) {
1455
1521
  }
1456
1522
  // POST /sessions/import-chunk — accept a single chunk of a multi-part upload
1457
1523
  if (req.method === 'POST' && url.pathname === '/sessions/import-chunk') {
1458
- if (syncToken) {
1459
- const authHeader = req.headers['authorization'] ?? '';
1460
- if (authHeader !== `Bearer ${syncToken}`) {
1461
- res.writeHead(401, { 'Content-Type': 'application/json' });
1462
- res.end(JSON.stringify({ error: 'Unauthorized' }));
1463
- return;
1464
- }
1465
- }
1524
+ if (unauthorized())
1525
+ return; // fail-closed (was fail-open)
1466
1526
  const uploadId = url.searchParams.get('uploadId');
1467
1527
  const chunkIndex = parseInt(url.searchParams.get('chunk') || '0');
1468
1528
  if (!uploadId) {
@@ -1493,14 +1553,8 @@ function startApiServer(workingDir, port) {
1493
1553
  }
1494
1554
  // POST /sessions/import-finalize — reassemble chunks, extract, apply slug merge
1495
1555
  if (req.method === 'POST' && url.pathname === '/sessions/import-finalize') {
1496
- if (syncToken) {
1497
- const authHeader = req.headers['authorization'] ?? '';
1498
- if (authHeader !== `Bearer ${syncToken}`) {
1499
- res.writeHead(401, { 'Content-Type': 'application/json' });
1500
- res.end(JSON.stringify({ error: 'Unauthorized' }));
1501
- return;
1502
- }
1503
- }
1556
+ if (unauthorized())
1557
+ return; // fail-closed (was fail-open)
1504
1558
  const uploadId = url.searchParams.get('uploadId');
1505
1559
  const total = parseInt(url.searchParams.get('total') || '0');
1506
1560
  const targetWorkDir = url.searchParams.get('targetWorkDir') ?? undefined;
@@ -1581,14 +1635,8 @@ function startApiServer(workingDir, port) {
1581
1635
  // Deletes ~/.claude/projects/<slug>/ and ~/.claude/projects/osb/<slug>/
1582
1636
  // Used by the dashboard "delete project" button.
1583
1637
  if (req.method === 'DELETE' && url.pathname === '/sessions/project') {
1584
- if (syncToken) {
1585
- const authHeader = req.headers['authorization'] ?? '';
1586
- if (authHeader !== `Bearer ${syncToken}`) {
1587
- res.writeHead(401, { 'Content-Type': 'application/json' });
1588
- res.end(JSON.stringify({ error: 'Unauthorized' }));
1589
- return;
1590
- }
1591
- }
1638
+ if (unauthorized())
1639
+ return; // fail-closed (was fail-open) — this DELETES a project's sessions
1592
1640
  const slug = url.searchParams.get('slug');
1593
1641
  if (!slug || slug.includes('..') || slug.includes('/')) {
1594
1642
  res.writeHead(400, { 'Content-Type': 'application/json' });
@@ -1697,7 +1745,16 @@ function startApiServer(workingDir, port) {
1697
1745
  // self-refreshing "Starting…" page so the user naturally re-hits /editor every
1698
1746
  // 3 s until ready.
1699
1747
  if (url.pathname === '/editor' && req.method === 'GET') {
1700
- // AUTH GATE (future): validate key / signed session before minting the cookie
1748
+ // AUTH GATE: the editor URL is minted with an owner-only signed token (see
1749
+ // mintEditorToken) and delivered over the authenticated data channel. A
1750
+ // direct hit without a valid token is refused — this is what closes the
1751
+ // unauthenticated-RCE hole. Local dev (no FLY_APP_NAME) is localhost-only.
1752
+ const editorToken = url.searchParams.get('t');
1753
+ if (process.env.FLY_APP_NAME && !verifyEditorToken(editorToken)) {
1754
+ res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });
1755
+ res.end('Forbidden — open the editor from inside your Voice Native session.');
1756
+ return;
1757
+ }
1701
1758
  // Optional ?folder= param: must be an absolute path under /workspace with no
1702
1759
  // directory-traversal sequences. If absent or invalid, fall back to bare '/'.
1703
1760
  const rawFolder = url.searchParams.get('folder') ?? '';
@@ -1733,9 +1790,14 @@ function startApiServer(workingDir, port) {
1733
1790
  console.error('❌ startCodeServer() from /editor failed:', err);
1734
1791
  });
1735
1792
  }
1736
- const refreshTarget = folderParam
1737
- ? `/editor?folder=${encodeURIComponent(folderParam)}`
1738
- : '/editor';
1793
+ // Preserve BOTH folder and the access token across the 3s self-refresh,
1794
+ // or the poll loop would bounce to a tokenless /editor and 403.
1795
+ const refreshQs = new URLSearchParams();
1796
+ if (folderParam)
1797
+ refreshQs.set('folder', folderParam);
1798
+ if (editorToken)
1799
+ refreshQs.set('t', editorToken);
1800
+ const refreshTarget = refreshQs.toString() ? `/editor?${refreshQs.toString()}` : '/editor';
1739
1801
  res.writeHead(200, {
1740
1802
  'Content-Type': 'text/html; charset=utf-8',
1741
1803
  'Cache-Control': 'no-store, must-revalidate',
@@ -2132,6 +2194,19 @@ async function main() {
2132
2194
  let currentSession = null;
2133
2195
  // 0.9.81: callable handler reference — see registration site for why.
2134
2196
  let participantConnectedHandler = null;
2197
+ // Identity of the user participant the voice session was last built for.
2198
+ // Only it may send state-changing data messages (data-sender-auth.ts).
2199
+ let controllingUserIdentity = null;
2200
+ // Machine owner (Supabase user id), baked into machine env by the frontend
2201
+ // provisioning (platform-env.ts). Empty = single-tenant / local mode:
2202
+ // newest joiner becomes the controller. NOTE: machines provisioned before
2203
+ // this env existed lack it until their next create / update-osborn /
2204
+ // pool repoint re-bakes the env, and run in newest-joiner mode until then.
2205
+ const OWNER_USER_ID = (process.env.OSBORN_OWNER_USER_ID || '').trim();
2206
+ if (OWNER_USER_ID)
2207
+ console.log('🔐 Control bound to machine owner (OSBORN_OWNER_USER_ID set)');
2208
+ else
2209
+ console.log('🔓 OSBORN_OWNER_USER_ID unset: single-tenant mode, newest joiner controls the agent');
2135
2210
  let currentAgent = null; // For updateChatCtx() context injection
2136
2211
  let currentLLM = null;
2137
2212
  const slots = new Map();
@@ -2760,6 +2835,11 @@ async function main() {
2760
2835
  // ────────────────────────────────────────────────────────────────────────
2761
2836
  // LIVE meeting transcript → LLM (buffered webhook finals). See recall.on('transcript').
2762
2837
  const meetingTranscriptBuffer = [];
2838
+ // Phase C routing target: the Tier-2 worker the most recent addressed turn
2839
+ // named (@researcher …). Captured in recall.on('transcript') when addressing
2840
+ // is enabled, consumed (and cleared) by the next addressed flushMeetingBuffer,
2841
+ // which injects a Task-dispatch directive for it. Null = no pending routing.
2842
+ let meetingAddressedTarget = null;
2763
2843
  let meetingFlushTimer = null;
2764
2844
  // Flush the buffered meeting turns to the LLM. `addressed=true` (the agent was
2765
2845
  // called by name / asked directly) tags the message so the agent RESPONDS by
@@ -2795,9 +2875,36 @@ async function main() {
2795
2875
  // Prepend + consume any interruption context (bot was cut off mid-sentence).
2796
2876
  const interrupt = meetingInterruptContext ? `${meetingInterruptContext}\n` : '';
2797
2877
  meetingInterruptContext = '';
2878
+ // Phase C — route an addressed turn to a specific Tier-2 worker. When the
2879
+ // addressing layer is on and the last addressed utterance named a routable
2880
+ // worker (not the orchestrator), STEER THE SINGLE SDK SESSION by injecting a
2881
+ // directive so the orchestrator dispatches that named agent via its Task
2882
+ // tool (the existing noteTaskDispatch/claimTaskDispatch/statusManager
2883
+ // plumbing in claude-llm.ts handles the rest). No parallel query() is
2884
+ // spawned — currentLLM.chat() feeds the one persistent session. Gated on
2885
+ // live dispatch headroom (statusManager) so a busy room can't fan out
2886
+ // unboundedly. The directive goes AFTER the `[MEETING` prefix so the ambient
2887
+ // non-interrupting + suppressMeetingTTS keying on that prefix still hold.
2888
+ let routingDirective = '';
2889
+ const pendingTarget = meetingAddressedTarget;
2890
+ meetingAddressedTarget = null;
2891
+ if (addressed && meetingAddressing.enabled && isRoutableTarget(pendingTarget)) {
2892
+ const active = statusManager.getActiveDispatchIds().length;
2893
+ const cap = Math.max(1, Number(process.env.OSBORN_MEETING_MAX_DISPATCH) || 3);
2894
+ if (active < cap) {
2895
+ routingDirective =
2896
+ `[ROUTING] A participant addressed @${pendingTarget}. Dispatch the "${pendingTarget}" ` +
2897
+ `agent via the Task tool (subagent_type "${pendingTarget}") to handle this turn instead of ` +
2898
+ `answering yourself, then relay its result into the meeting.\n`;
2899
+ console.log(`🎯 [meeting-addr] routing addressed turn → @${pendingTarget} via Task directive (dispatches ${active}/${cap})`);
2900
+ }
2901
+ else {
2902
+ console.log(`🎯 [meeting-addr] @${pendingTarget} routing skipped — at concurrency cap (${active}/${cap}); orchestrator handles it`);
2903
+ }
2904
+ }
2798
2905
  try {
2799
2906
  const ctx = new llm.ChatContext();
2800
- ctx.addMessage({ role: 'user', content: `${interrupt}${header}\n${turns.join('\n')}` });
2907
+ ctx.addMessage({ role: 'user', content: `${interrupt}${header}\n${routingDirective}${turns.join('\n')}` });
2801
2908
  currentLLM.chat({ chatCtx: ctx });
2802
2909
  console.log(`📓 Flushed ${turns.length} meeting turn(s) to LLM${addressed ? ' (ADDRESSED — respond)' : ''}`);
2803
2910
  }
@@ -2875,6 +2982,8 @@ async function main() {
2875
2982
  activeMeetingBotId = null;
2876
2983
  meetingAddressedUntil = 0;
2877
2984
  meetingSpeakers.clear();
2985
+ meetingAddressedTarget = null;
2986
+ meetingAddressing.reset(); // inert when OSBORN_MEETING_ADDRESSING is unset (empty registry)
2878
2987
  // leaveBot=false when Recall itself reported the meeting over (bot already gone).
2879
2988
  if (opts.leaveBot !== false) {
2880
2989
  const recall = getRecallClient();
@@ -3238,12 +3347,42 @@ async function main() {
3238
3347
  recall.on('transcript', ({ botId, speaker, text, partial }) => {
3239
3348
  console.log(`📝 Meeting transcript [${speaker}]${partial ? ' (partial)' : ''}: ${text}`);
3240
3349
  if (!partial && text.trim()) {
3350
+ // Multi-agent meeting addressing/mute (OFF by default — set
3351
+ // OSBORN_MEETING_ADDRESSING=on to engage). When the flag is unset this
3352
+ // whole block is skipped: processUtterance() short-circuits and the
3353
+ // meeting path below behaves EXACTLY as before. When ON: a muted speaker
3354
+ // is dropped, a mute/unmute command updates the registry (and notifies
3355
+ // the frontend), and an addressed worker is captured for Phase-C routing
3356
+ // in the next addressed flush (see flushMeetingBuffer).
3357
+ if (meetingAddressing.enabled) {
3358
+ const verdict = meetingAddressing.processUtterance(speaker, text);
3359
+ if (verdict.muteChanged) {
3360
+ console.log(`🎛️ [meeting-addr] ${verdict.muteChanged.action} "${verdict.muteChanged.who}" — muted now: ${meetingAddressing.mutes.list().join(', ') || 'none'}`);
3361
+ emitMuteChanged(verdict.muteChanged.action, verdict.muteChanged.who);
3362
+ }
3363
+ if (verdict.drop) {
3364
+ console.log(`🔇 [meeting-addr] dropped utterance from muted speaker "${speaker}"`);
3365
+ return; // muted participant — do not buffer or forward to the LLM
3366
+ }
3367
+ if (verdict.target) {
3368
+ // Remember the addressed worker so the next addressed flush routes to
3369
+ // it (Phase C). Store regardless of routability so the UI can show the
3370
+ // chip; flushMeetingBuffer gates actual Task dispatch on isRoutableTarget.
3371
+ meetingAddressedTarget = verdict.target;
3372
+ console.log(`🎯 [meeting-addr] "${speaker}" addresses @${verdict.target}${isRoutableTarget(verdict.target) ? ' (will route to worker)' : ' (orchestrator — no worker dispatch)'}`);
3373
+ emitMeetingState(verdict.target);
3374
+ }
3375
+ }
3376
+ const isNewSpeaker = !meetingSpeakers.has(speaker);
3241
3377
  meetingTranscriptBuffer.push(`${speaker}: ${text.trim()}`);
3242
3378
  // Addressed by name → flush NOW (don't wait the 20s batch) and tag it so
3243
3379
  // the agent replies out loud into the meeting. This is the chat-mode path:
3244
3380
  // named/asked → prompt response. Un-addressed chunks stay in the silent
3245
3381
  // 20s batch for note-taking. That's the two-mode seam, mechanically.
3246
3382
  meetingSpeakers.add(speaker);
3383
+ // New participant → refresh the frontend's mute roster (flag-gated no-op).
3384
+ if (isNewSpeaker)
3385
+ emitMeetingState();
3247
3386
  // Fuzzy name match: meeting STT routinely mangles "Osborn" — observed
3248
3387
  // live 2026-08-01: "Osborn can you hear me" → "i was born can you hear
3249
3388
  // me" (name trigger missed, bot stayed silent). Accept common
@@ -3398,6 +3537,13 @@ async function main() {
3398
3537
  }
3399
3538
  console.log(`🤐 Suppressed text buffered (+${t.length} chars, total ${lastInterruption.suppressedText.length}): "${t.substring(0, 80)}${t.length > 80 ? '...' : ''}"`);
3400
3539
  }
3540
+ // L2b: client notices (favorite_changed) ride the next real user turn as
3541
+ // hidden context (PipelineDirectLLM getAndConsumeClientNotes), never as a
3542
+ // user_text turn. typedEchoes carries a typed message's clientMsgId onto its
3543
+ // user_transcript echo.
3544
+ const clientNotes = new ClientNoteQueue();
3545
+ const typedEchoes = new TypedEchoTracker();
3546
+ const getAndConsumeClientNotes = () => clientNotes.drain();
3401
3547
  /**
3402
3548
  * Callback for PipelineDirectLLM — returns pending interruption context and clears it.
3403
3549
  * Called in chat() when user's transcribed message arrives.
@@ -3646,6 +3792,31 @@ async function main() {
3646
3792
  console.error('❌ sendToFrontend error:', err);
3647
3793
  }
3648
3794
  }
3795
+ // ── Phase B — meeting addressing/mute state → frontend (over the EXISTING
3796
+ // 'osborn-updates' data channel). Both are NO-OPS when the flag is unset, so
3797
+ // an un-flagged meeting emits nothing new (zero behavior change). `meeting_state`
3798
+ // is the full snapshot (roster, known speakers, muted set, who was addressed);
3799
+ // `mute_changed` is the lightweight per-change delta. Function declarations so
3800
+ // they're reachable from the transcript handler + handleDataReceived above.
3801
+ function emitMeetingState(addressed = null) {
3802
+ if (!meetingAddressing.enabled)
3803
+ return;
3804
+ const st = meetingAddressing.state();
3805
+ void sendToFrontend({
3806
+ type: 'meeting_state',
3807
+ enabled: st.enabled,
3808
+ roster: st.roster,
3809
+ speakers: [...meetingSpeakers],
3810
+ muted: st.muted,
3811
+ addressed,
3812
+ });
3813
+ }
3814
+ function emitMuteChanged(action, who) {
3815
+ if (!meetingAddressing.enabled)
3816
+ return;
3817
+ void sendToFrontend({ type: 'mute_changed', action, who, muted: meetingAddressing.mutes.list() });
3818
+ emitMeetingState();
3819
+ }
3649
3820
  async function announceViaVoice(text) {
3650
3821
  if (!currentSession)
3651
3822
  return;
@@ -4519,6 +4690,28 @@ async function main() {
4519
4690
  console.log('📽️🔊 meeting-canvas joined the LiveKit room — native session.say relays to the meeting');
4520
4691
  return; // not a user; skip session setup for it
4521
4692
  }
4693
+ // Owner binding (data-sender-auth.ts resolveJoin): with OSBORN_OWNER_USER_ID
4694
+ // set (cloud machines), only a `user-*` participant whose SIGNED token
4695
+ // metadata userId is the owner takes the session and becomes the
4696
+ // controller; other users are ignored (no voice session, gated data
4697
+ // dropped). With no owner configured (single-tenant / local), the newest
4698
+ // `user-*` joiner wins, as before. The watch gateway (our own identity)
4699
+ // never becomes the controller, so the owner's commands keep working; it
4700
+ // may still send permission_response. It gets the voice session only when
4701
+ // no controller exists (watch voice alone); joining after the owner it is
4702
+ // not adopted, so the owner's session and currentUserId stay intact.
4703
+ const joinerUserId = userIdFromMetadata(participant.metadata);
4704
+ const join = resolveJoin(participant.identity, joinerUserId, OWNER_USER_ID, controllingUserIdentity);
4705
+ controllingUserIdentity = join.controller;
4706
+ if (!join.adoptSession) {
4707
+ if (participant.identity === AGENT_SELF_IDENTITY) {
4708
+ console.log(`⌚ ${participant.identity} joined while ${controllingUserIdentity} controls the session; keeping the owner's voice session`);
4709
+ }
4710
+ else {
4711
+ console.warn(`🚫 ${participant.identity} is not the machine owner (token userId=${joinerUserId ?? 'none'}); not adopting it as the voice user`);
4712
+ }
4713
+ return;
4714
+ }
4522
4715
  // A user (re)arriving cancels the meeting leave-grace — the bot stays.
4523
4716
  cancelMeetingLeaveGrace();
4524
4717
  // A user is present — cancel any pending agent-side "alone" leave.
@@ -4717,6 +4910,7 @@ async function main() {
4717
4910
  }
4718
4911
  },
4719
4912
  getAndConsumeInterruptionContext,
4913
+ getAndConsumeClientNotes,
4720
4914
  onFastBrainResult: (result) => {
4721
4915
  console.log(`🧠⚡ [FAST_BRAIN ${result.type.toUpperCase()} +${result.elapsedMs}ms]: "${result.answer.substring(0, 60)}"`);
4722
4916
  sendToFrontend({
@@ -4766,19 +4960,28 @@ async function main() {
4766
4960
  let lastSentUserTranscript = '';
4767
4961
  let lastSentAgentTranscript = '';
4768
4962
  function sendUserTranscript(transcript, source) {
4769
- if (!transcript || transcript.length < 3)
4770
- return;
4771
- const normalized = transcript.trim().replace(/\s+/g, ' ');
4772
- if (normalized === lastSentUserTranscript)
4963
+ if (!transcript)
4773
4964
  return;
4774
- if (normalized === '<noise>' || normalized.toLowerCase() === 'thank you')
4965
+ // A typed message (user_text) echoes back here with its frontend
4966
+ // clientMsgId so the UI can dedupe its optimistic bubble (L2b).
4967
+ const typed = typedEchoes.take(transcript);
4968
+ const clientMsgId = typed?.clientMsgId;
4969
+ // Shared sanitizer (L2b): drops the frontend [time:] tag, injected
4970
+ // blocks and client/voice-injection notices ([favorited],
4971
+ // [welcome-back], [SCRIPT]/[PROACTIVE]/[NOTIFICATION] — Gemini v1.0.51:
4972
+ // userInput in generateReply creates a user conversation item), plus
4973
+ // <noise> / "thank you". null = nothing the user said.
4974
+ const text = userEchoText(transcript, typed?.attachments);
4975
+ if (!text)
4775
4976
  return;
4776
- // Filter out voice injection content that appears as user transcript
4777
- // (Gemini v1.0.51: userInput in generateReply creates a user conversation item)
4778
- if (normalized.startsWith('[SCRIPT]') || normalized.startsWith('[PROACTIVE]') || normalized.startsWith('[NOTIFICATION]'))
4977
+ const normalized = text.replace(/\s+/g, ' ');
4978
+ // A distinct typed message may repeat the previous text on purpose.
4979
+ if (!clientMsgId && normalized === lastSentUserTranscript)
4779
4980
  return;
4780
4981
  console.log(`📝 User (${source}, ${transcript.length} chars): "${transcript}"`);
4781
- sendToFrontend({ type: 'user_transcript', text: transcript });
4982
+ sendToFrontend(clientMsgId
4983
+ ? { type: 'user_transcript', text, clientMsgId }
4984
+ : { type: 'user_transcript', text });
4782
4985
  lastSentUserTranscript = normalized;
4783
4986
  if (connectTiming && !connectTiming.sawUserMsg) {
4784
4987
  connectTiming.sawUserMsg = true;
@@ -5174,6 +5377,7 @@ async function main() {
5174
5377
  }
5175
5378
  },
5176
5379
  getAndConsumeInterruptionContext,
5380
+ getAndConsumeClientNotes,
5177
5381
  onFastBrainResult: (r) => {
5178
5382
  console.log(`🧠⚡ [FAST_BRAIN ${r.type.toUpperCase()} +${r.elapsedMs}ms]: "${r.answer.substring(0, 60)}"`);
5179
5383
  sendToFrontend({
@@ -5363,14 +5567,14 @@ async function main() {
5363
5567
  if (dbPath) {
5364
5568
  const db = openStore(dbPath, { readonly: true });
5365
5569
  try {
5366
- const rows = recentRows(db, 20, ['user', 'assistant']); // newest-first
5367
- const priorMessages = rows
5368
- .reverse() // → chronological
5369
- .map(r => ({ role: r.msgType === 'assistant' ? 'assistant' : 'user', content: (r.text || '').slice(0, 800), ts: r.ts || null }))
5370
- .filter(m => m.content.trim().length > 0);
5570
+ // Sanitized before truncation, over-fetched, chronological (L2b).
5571
+ const priorMessages = cleanHistoryRows(n => recentRows(db, n, ['user', 'assistant']), 20, 800);
5572
+ // Durable compaction markers ride the same push so the resumed
5573
+ // transcript rebuilds its "Conversation compacted" rows too.
5574
+ const compactions = readCompactionMarkers(preSelectedSessionId, workingDir);
5371
5575
  if (priorMessages.length > 0) {
5372
- await sendToFrontend({ type: 'prior_messages', sessionId: preSelectedSessionId, messages: priorMessages });
5373
- console.log(`💬 Sent ${priorMessages.length} prior messages from DB for optimistic UI`);
5576
+ await sendToFrontend({ type: 'prior_messages', sessionId: preSelectedSessionId, messages: priorMessages, compactions });
5577
+ console.log(`💬 Sent ${priorMessages.length} prior messages (+${compactions.length} compaction markers) from DB for optimistic UI`);
5374
5578
  }
5375
5579
  }
5376
5580
  finally {
@@ -5439,6 +5643,8 @@ async function main() {
5439
5643
  // participantConnectedHandler above).
5440
5644
  const handleParticipantDisconnected = (participant) => {
5441
5645
  console.log(`👋 User left: ${participant.identity}`);
5646
+ if (participant.identity === controllingUserIdentity)
5647
+ controllingUserIdentity = null;
5442
5648
  // Full cleanup — stop all background work to avoid accumulating API usage
5443
5649
  voiceQueue.length = 0;
5444
5650
  isProcessingQueue = false;
@@ -5545,6 +5751,11 @@ async function main() {
5545
5751
  try {
5546
5752
  const data = JSON.parse(new TextDecoder().decode(payload));
5547
5753
  console.log('📨 Data:', data.type);
5754
+ const senderCheck = checkControlSender(String(data.type), participant?.identity, controllingUserIdentity);
5755
+ if (!senderCheck.ok) {
5756
+ console.warn(`🚫 Dropped ${data.type}: ${senderCheck.reason}`);
5757
+ return;
5758
+ }
5548
5759
  if (data.type === 'claude_auth_code' && pendingAuthSubmitCode) {
5549
5760
  console.log('🔑 Received auth code from frontend');
5550
5761
  sendToFrontend({ type: 'claude_auth_submitting', message: 'Submitting code to Claude CLI...' });
@@ -5563,7 +5774,26 @@ async function main() {
5563
5774
  console.log(`✅ Permission: ${data.response}`);
5564
5775
  }
5565
5776
  }
5777
+ else if (data.type === 'favorite_changed') {
5778
+ // L2b (UI#21): a favorite is a UI action, not something the user said.
5779
+ // Queue it as hidden context for the next real user turn; no reply, no
5780
+ // user_transcript echo, no JSONL user turn of its own.
5781
+ const change = parseFavoriteChanged(data);
5782
+ if (change) {
5783
+ clientNotes.favoriteChanged(change);
5784
+ console.log(`⭐ favorite_changed: ${change.fileName} → ${change.favorited ? 'on' : 'off'} (queued as context)`);
5785
+ }
5786
+ }
5566
5787
  else if (data.type === 'user_text' && currentSession) {
5788
+ // Backward compat: older frontends send a favorite as user_text
5789
+ // "[time: …] [favorited] The user favorited the file X." — route it to
5790
+ // the same context queue instead of starting a user turn.
5791
+ const legacyFavorite = parseLegacyFavoriteNotice(String(data.content || ''));
5792
+ if (legacyFavorite && !(Array.isArray(data.files) && data.files.length)) {
5793
+ clientNotes.favoriteChanged(legacyFavorite);
5794
+ console.log(`⭐ legacy [favorited] user_text → context note: ${legacyFavorite.fileName}`);
5795
+ return;
5796
+ }
5567
5797
  // Build message content — include attached files (URLs, text content)
5568
5798
  let fullContent = String(data.content || '');
5569
5799
  const files = data.files;
@@ -5584,6 +5814,9 @@ async function main() {
5584
5814
  else {
5585
5815
  console.log(`📝 Text (${fullContent.length} chars): "${fullContent}"`);
5586
5816
  }
5817
+ // The session echoes this item as user_transcript; carry the frontend's
5818
+ // clientMsgId (bubble dedupe) and the attachment blocks onto that echo.
5819
+ typedEchoes.register(fullContent, data.clientMsgId, fullContent.slice(String(data.content || '').length));
5587
5820
  // Skip interrupt for Gemini — disrupts state machine (hangs in speaking state)
5588
5821
  if (true) { // always non-gemini in pipeline mode
5589
5822
  currentSession.interrupt();
@@ -5605,16 +5838,7 @@ async function main() {
5605
5838
  // Sent here too so the in-chat session list grouping stays
5606
5839
  // consistent with the dashboard's grouping.
5607
5840
  baseCwd: workingDir,
5608
- sessions: sessions.map(s => ({
5609
- sessionId: s.sessionId,
5610
- projectSlug: s.projectSlug,
5611
- projectPath: s.projectPath,
5612
- cwd: s.cwd,
5613
- timestamp: s.timestamp.toISOString(),
5614
- lastMessage: s.lastMessage,
5615
- messageCount: s.messageCount,
5616
- fileSize: s.fileSize,
5617
- })),
5841
+ sessions: sessions.map(sessionListEntry),
5618
5842
  count: sessions.length,
5619
5843
  });
5620
5844
  }
@@ -6272,6 +6496,20 @@ async function main() {
6272
6496
  recallJoin.registerBot(botId, sessionId);
6273
6497
  activeMeetingBotId = botId;
6274
6498
  await sendToFrontend({ type: 'meeting_joined', botId, message: 'Osborn has joined the meeting' });
6499
+ // Phase B — point the addressable roster at the REAL effective
6500
+ // agent set (built-ins minus user-removed, plus per-user agents),
6501
+ // same effective set get_agents/set_agents compute, with the
6502
+ // orchestrator ('osborn') first. Flag-gated: a no-op (no roster
6503
+ // change, no emit) when OSBORN_MEETING_ADDRESSING is unset.
6504
+ if (meetingAddressing.enabled) {
6505
+ const base = { ...NAMED_AGENTS };
6506
+ for (const r of userRemovedAgents)
6507
+ delete base[r];
6508
+ const effective = { ...base, ...(userNamedAgents || {}) };
6509
+ meetingAddressing.setRoster(['osborn', ...Object.keys(effective)]);
6510
+ console.log(`🎛️ [meeting-addr] roster → [${meetingAddressing.rosterIds.join(', ')}]`);
6511
+ emitMeetingState();
6512
+ }
6275
6513
  // Minimal awareness injection (user directive 2026-08-04): tell the
6276
6514
  // LLM it's in a meeting and how transcripts are tagged — nothing
6277
6515
  // more. NO "do NOT speak / silent observer" coaching (that fought
@@ -6348,6 +6586,22 @@ async function main() {
6348
6586
  await sendToFrontend({ type: 'meeting_error', message: err.message });
6349
6587
  }
6350
6588
  }
6589
+ // Phase B — authenticated frontend mute/unmute of a meeting participant.
6590
+ // Controller-only: checkControlSender fails CLOSED for any type not on the
6591
+ // read-only list, so this gated type already requires the controlling user.
6592
+ // Flag-gated: ignored entirely unless OSBORN_MEETING_ADDRESSING is on (the
6593
+ // MuteRegistry is only consulted by processUtterance when enabled anyway).
6594
+ else if (data.type === 'mute_participant') {
6595
+ if (meetingAddressing.enabled) {
6596
+ const action = data.action === 'unmute' ? 'unmute' : 'mute';
6597
+ const who = String(data.who || '').trim();
6598
+ const applied = who ? meetingAddressing.applyMuteControl(action, who) : null;
6599
+ if (applied) {
6600
+ console.log(`🎛️ [meeting-addr] ${applied.action} "${applied.who}" via control — muted now: ${meetingAddressing.mutes.list().join(', ') || 'none'}`);
6601
+ emitMuteChanged(applied.action, applied.who);
6602
+ }
6603
+ }
6604
+ }
6351
6605
  // ── IDE (code-server) handlers ──────────────────────────────────────
6352
6606
  else if (data.type === 'start_ide') {
6353
6607
  try {
@@ -6356,10 +6610,14 @@ async function main() {
6356
6610
  const flyAppHost = process.env.FLY_APP_NAME
6357
6611
  ? `${process.env.FLY_APP_NAME}.fly.dev`
6358
6612
  : (process.env.OSBORN_PUBLIC_HOST || `localhost:${apiPort}`);
6359
- const ideUrl = process.env.FLY_APP_NAME
6613
+ // Mint an owner-only access token into the URL. The frontend opens it
6614
+ // verbatim; a direct hit to /editor without it is refused (RCE fix).
6615
+ const editorTok = mintEditorToken();
6616
+ const tokQs = editorTok ? `?t=${encodeURIComponent(editorTok)}` : '';
6617
+ const ideUrl = (process.env.FLY_APP_NAME
6360
6618
  ? `https://${flyAppHost}/editor`
6361
- : `http://${flyAppHost}/editor`;
6362
- console.log(`✅ IDE proxy ready: ${ideUrl}`);
6619
+ : `http://${flyAppHost}/editor`) + tokQs;
6620
+ console.log(`✅ IDE proxy ready: ${process.env.FLY_APP_NAME ? `https://${flyAppHost}/editor` : ideUrl}${editorTok ? ' (token-gated)' : ''}`);
6363
6621
  await sendToFrontend({ type: 'ide_ready', url: ideUrl });
6364
6622
  }
6365
6623
  catch (err) {