osborn 0.9.280 → 0.9.282

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 (38) hide show
  1. package/dist/agent-store.d.ts +164 -0
  2. package/dist/agent-store.js +302 -0
  3. package/dist/claude-llm.d.ts +7 -8
  4. package/dist/claude-llm.js +75 -171
  5. package/dist/content/compaction-lens-worker.js +2 -1
  6. package/dist/content/content-run.js +9 -9
  7. package/dist/content/lens-clip-window.js +7 -6
  8. package/dist/content/lens-launch.d.ts +11 -0
  9. package/dist/content/lens-launch.js +11 -0
  10. package/dist/content/lens-library-select.d.ts +7 -5
  11. package/dist/content/lens-library-select.js +7 -6
  12. package/dist/content/lens-library.d.ts +7 -1
  13. package/dist/content/lens-library.js +29 -6
  14. package/dist/data-sender-auth.d.ts +3 -2
  15. package/dist/data-sender-auth.js +10 -3
  16. package/dist/index.js +376 -190
  17. package/dist/pipeline-direct-llm.d.ts +1 -1
  18. package/dist/pipeline-direct-llm.js +1 -1
  19. package/dist/prompts/chain-after-planner.md +1 -0
  20. package/dist/prompts/chain-after-researcher.md +1 -0
  21. package/dist/prompts/chain-after-writer.md +1 -0
  22. package/dist/prompts/direct-mode-research.md +2 -2
  23. package/dist/prompts/steward.md +131 -0
  24. package/dist/prompts.d.ts +6 -0
  25. package/dist/prompts.js +18 -1
  26. package/dist/pushover.d.ts +7 -0
  27. package/dist/pushover.js +45 -42
  28. package/dist/steward-gate.d.ts +6 -5
  29. package/dist/steward-gate.js +256 -32
  30. package/dist/steward-verdict.d.ts +23 -0
  31. package/dist/steward-verdict.js +97 -0
  32. package/dist/stopwords.d.ts +1 -0
  33. package/dist/stopwords.js +6 -0
  34. package/dist/store-catalog.d.ts +106 -0
  35. package/dist/store-catalog.js +356 -0
  36. package/dist/store-name.d.ts +1 -0
  37. package/dist/store-name.js +7 -0
  38. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -39,6 +39,8 @@ import { isSafeArtifactPath } from './lib/safe-artifact-path.js';
39
39
  import { cleanupHousekeeping } from './housekeeping.js';
40
40
  import { createSTT, createTTS } from './voice-io.js';
41
41
  import { createClaudeLLM, NAMED_AGENTS, applyTurbo, requestAuthRestart } from './claude-llm.js';
42
+ import { SOURCES, loadCatalog, findEntry, installSkill, agentDraft, recommend, skillProvenance, installedIds } from './store-catalog.js';
43
+ import { parseUserAgents, mergeAgents, describeAgents, describeRoles, coreRole, AGENT_LIMITS, storeWriteRefusal, storeWriteOriginAllowed, coreSkillNames, skillForkedFrom, forkSkill, removeUserSkill, addUserSkill, readUserSkill, parseFrontMatter, storeName } from './agent-store.js';
42
44
  import { clearPipelineFastBrainSession, prewarmBM25Index } from './pipeline-fastbrain.js';
43
45
  import { ensureClaudeAuth, applyAuthFallback, replayInFlightAuth, startClaudeAuthOnDemand, isOnDemandAuthInFlight, probeActiveProviderKey } from './claude-auth.js';
44
46
  import { statusManager } from './status-manager.js';
@@ -46,14 +48,17 @@ import { decideNextSession, planSwitch, resolveSessionCwd, keepNonConversationIt
46
48
  import { createSmitheryProxy, destroySmitheryProxy, parseSmitheryUrl, isSmitheryUrl, SmitheryAuthorizationError } from './smithery-proxy.js';
47
49
  import { DIRECT_MODE_PROMPT } from './prompts.js';
48
50
  import { MCP_CATALOG } from './config.js';
51
+ import { launchLibraryOnSessionEnd, lastLibraryRun, isContentLensEnabled } from './content/lens-launch.js';
52
+ import { resolveIngestConfig } from './content/lens-ingest.js';
49
53
  import { storeExists, openStore, recentRows } from './session-store.js';
50
54
  import { readCompactionMarkers } from './compaction-log.js';
55
+ import { readStewardVerdicts } from './steward-verdict.js';
51
56
  import { sessionListEntry, cleanHistoryRows, userEchoText, TypedEchoTracker, ClientNoteQueue, parseFavoriteChanged, parseLegacyFavoriteNotice } from './transcript-wiring.js';
52
57
  import { getRecallClient } from './recall-client.js';
53
58
  import { synthMeetingAudio, selectMeetingTtsProviders } from './meeting-tts.js';
54
59
  import { MeetingTranscriptPoller } from './meeting-transcript-poller.js';
55
60
  import { missingRequiredEnv } from './env-keys.js';
56
- import { armPermissionPush, handleWatchAck, setWatchResultHandler } from './pushover.js';
61
+ import { armPermissionPush, handleWatchAck, setWatchResultHandler, osbornFrontendUrl, notifyPhone, isWatchBridgeEnabled, phonePushPending } from './pushover.js';
57
62
  import { startWatchGateway } from './watch-gateway.js';
58
63
  import { noiseGate } from './noise-gate.js';
59
64
  import { installDuck, DUCK_LEVEL } from './duck.js';
@@ -121,24 +126,37 @@ function buildToolLogEvent(name, input, status, agentRole, agentId) {
121
126
  catch { /* diff is best-effort — omit on any failure */ }
122
127
  return ev;
123
128
  }
124
- // Load skills list with name + description for frontend display
129
+ // The reply each chat store request waits for (VoiceRoom askAgent).
130
+ const STORE_REPLY_TYPES = {
131
+ skill_get: 'skill_content', skill_add: 'skill_add_result', skill_fork: 'skill_fork_result',
132
+ skill_remove: 'skill_remove_result', get_agent_prompt: 'agent_prompt',
133
+ };
134
+ // Store routes, guarded by storeRefused: writes change the machine's skills; reads carry the
135
+ // core prompts, the user's skills and the catalog. Neither answers every site's CORS.
136
+ const STORE_WRITE_PATHS = new Set(['/skills/fork', '/skills/remove', '/store/install']);
137
+ const STORE_PATHS = new Set([...STORE_WRITE_PATHS, '/skills', '/skills/content', '/store/catalog', '/store/entry', '/agents']);
138
+ // Skills shipped with the package (core: maintained by Voice Native).
139
+ const PKG_SKILLS_DIR = join(__dirname, '..', '.claude', 'skills');
140
+ const homeSkillsDir = () => join(homedir(), '.claude', 'skills');
125
141
  function loadSkillsList(agentDir) {
126
142
  const skillsDir = join(agentDir, '.claude', 'skills');
127
143
  if (!existsSync(skillsDir))
128
144
  return [];
145
+ const core = coreSkillNames(PKG_SKILLS_DIR);
129
146
  const skills = [];
130
147
  try {
131
148
  for (const skillName of readdirSync(skillsDir)) {
132
149
  const skillFile = join(skillsDir, skillName, 'SKILL.md');
133
150
  if (existsSync(skillFile)) {
134
- const content = readFileSync(skillFile, 'utf-8');
135
- // Extract title from first # heading, or use folder name
136
- const titleMatch = content.match(/^#\s+(?:Skill:\s*)?(.+)/m);
151
+ const { meta, body } = parseFrontMatter(readFileSync(skillFile, 'utf-8'));
152
+ // Display name: the first # heading (else the folder); description: front matter, else the paragraph after the heading
153
+ const titleMatch = body.match(/^#\s+(?:Skill:\s*)?(.+)/m);
137
154
  const name = titleMatch ? titleMatch[1].trim() : skillName;
138
- // Extract description from first paragraph after heading
139
- const descMatch = content.match(/^#[^\n]+\n+([^\n#]+)/m);
140
- const description = descMatch ? descMatch[1].trim() : '';
141
- skills.push({ name, description, folder: skillName });
155
+ const descMatch = body.match(/^#[^\n]+\n+([^\n#]+)/m);
156
+ const description = typeof meta.description === 'string' && meta.description ? meta.description : descMatch ? descMatch[1].trim() : '';
157
+ const forkedFrom = skillForkedFrom(skillsDir, skillName);
158
+ const installedFrom = skillProvenance(skillsDir, skillName);
159
+ skills.push({ name, description, folder: skillName, core: core.has(skillName), ...(forkedFrom ? { forkedFrom } : {}), ...(installedFrom ? { installedFrom } : {}) });
142
160
  }
143
161
  }
144
162
  }
@@ -147,6 +165,21 @@ function loadSkillsList(agentDir) {
147
165
  }
148
166
  return skills;
149
167
  }
168
+ /** Adds, forks or removes a user skill (agent-store.ts rules). The one entry point for the
169
+ * chat's skill_* data messages (the connected agent) and Settings' /skills/* routes (no room). */
170
+ function changeSkill(op, name, arg) {
171
+ let out;
172
+ try {
173
+ out = op === 'add' ? addUserSkill(homeSkillsDir(), PKG_SKILLS_DIR, name, arg)
174
+ : op === 'fork' ? forkSkill(homeSkillsDir(), PKG_SKILLS_DIR, name, arg)
175
+ : removeUserSkill(homeSkillsDir(), PKG_SKILLS_DIR, name);
176
+ }
177
+ catch (err) {
178
+ out = { error: err instanceof Error ? err.message : String(err) };
179
+ }
180
+ console.log(`📚 skill ${op} ${storeName(name)}: ${'ok' in out ? 'ok' : out.error}`);
181
+ return out;
182
+ }
150
183
  // Generate a short, user-friendly room code
151
184
  function generateRoomCode() {
152
185
  const chars = 'abcdefghjkmnpqrstuvwxyz23456789';
@@ -353,7 +386,7 @@ function parseDevSubdomainPort(req) {
353
386
  // Route prefixes that belong to the agent itself. The proxy fall-through checks
354
387
  // this list FIRST so it never intercepts an agent API path.
355
388
  const AGENT_ROUTE_PREFIXES = [
356
- '/health', '/sessions', '/skills', '/agents', '/canvas', '/canvas-token',
389
+ '/health', '/sessions', '/skills', '/agents', '/store', '/canvas', '/canvas-token',
357
390
  '/canvas-stream', '/events', '/room-code', '/connect-room', '/leave-room',
358
391
  '/report-bug', '/restart', '/tts', '/noise-cancel', '/webhook', '/sessions/export',
359
392
  '/sessions/import', '/sessions/manifest',
@@ -574,6 +607,16 @@ function startApiServer(workingDir, port) {
574
607
  // Authorization is required for /secrets (Bearer OSBORN_SYNC_TOKEN); without it in the
575
608
  // allow-list the browser preflight fails and the dashboard can't read/manage keys.
576
609
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
610
+ // Store routes (STORE_PATHS) echo only an allowed origin, never '*'.
611
+ if (STORE_PATHS.has((req.url || '/').split('?')[0])) {
612
+ const origin = req.headers.origin;
613
+ if (origin && storeWriteOriginAllowed(origin, osbornFrontendUrl())) {
614
+ res.setHeader('Access-Control-Allow-Origin', origin);
615
+ res.setHeader('Vary', 'Origin');
616
+ }
617
+ else
618
+ res.removeHeader('Access-Control-Allow-Origin');
619
+ }
577
620
  if (req.method === 'OPTIONS') {
578
621
  res.writeHead(204);
579
622
  res.end();
@@ -662,10 +705,11 @@ function startApiServer(workingDir, port) {
662
705
  // pass their own cwd; honoured only if the session really lives there.
663
706
  const readDir = sessionMessagesDir(sessionId, url.searchParams.get('workingDirectory'), workingDir, sessionExists);
664
707
  const compactions = readCompactionMarkers(sessionId, readDir);
708
+ const steward = readStewardVerdicts(sessionId, readDir);
665
709
  const dbPath = storeExists(sessionId, readDir);
666
710
  if (!dbPath) {
667
711
  res.writeHead(200, { 'Content-Type': 'application/json' });
668
- res.end(JSON.stringify({ sessionId, messages: [], compactions }));
712
+ res.end(JSON.stringify({ sessionId, messages: [], compactions, steward }));
669
713
  return;
670
714
  }
671
715
  const db = openStore(dbPath, { readonly: true });
@@ -674,7 +718,7 @@ function startApiServer(workingDir, port) {
674
718
  // (notices, injected blocks) don't shrink the page (L2b).
675
719
  const messages = cleanHistoryRows(n => recentRows(db, n, ['user', 'assistant']), limit, 1200);
676
720
  res.writeHead(200, { 'Content-Type': 'application/json' });
677
- res.end(JSON.stringify({ sessionId, messages, compactions }));
721
+ res.end(JSON.stringify({ sessionId, messages, compactions, steward }));
678
722
  }
679
723
  finally {
680
724
  try {
@@ -702,7 +746,26 @@ function startApiServer(workingDir, port) {
702
746
  res.end(JSON.stringify(out));
703
747
  return;
704
748
  }
749
+ // Agent & skill store routes: the chat and Settings both use them (through the
750
+ // authenticated /api/agent proxy in the cloud). JSON in and out.
751
+ const reply = (status, body) => { res.writeHead(status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(body)); };
752
+ // Called past the token gate (unauthorized()); the rules for a machine with no sync token
753
+ // are agent-store.ts storeWriteRefusal (reads skip only the JSON check).
754
+ const storeRefused = (read = false) => {
755
+ const refusal = storeWriteRefusal({ read,
756
+ hasToken: !!syncToken,
757
+ publicDeploy: !!process.env.FLY_APP_NAME || !!process.env.OSBORN_PUBLIC_HOST,
758
+ forwarded: !!(req.headers['x-forwarded-for'] || req.headers['x-forwarded-host']),
759
+ host: req.headers.host, remote: req.socket.remoteAddress, origin: req.headers.origin,
760
+ contentType: String(req.headers['content-type'] || ''), frontendUrl: osbornFrontendUrl(),
761
+ });
762
+ if (refusal)
763
+ reply(refusal.status, { error: refusal.error });
764
+ return !!refusal;
765
+ };
705
766
  if (req.method === 'GET' && url.pathname === '/skills') {
767
+ if (unauthorized() || storeRefused(true))
768
+ return;
706
769
  // Installed skills — same list the chat's get_skills data-channel message
707
770
  // returns, exposed over HTTP so the DASHBOARD (no LiveKit connection) can
708
771
  // render the skills manager too. Reads ~/.claude/skills (homedir) — the SINGLE
@@ -713,20 +776,92 @@ function startApiServer(workingDir, port) {
713
776
  res.end(JSON.stringify({ skills: loadSkillsList(homedir()) }));
714
777
  return;
715
778
  }
779
+ if (url.pathname === '/skills/content' || (url.pathname.startsWith('/skills/') && STORE_WRITE_PATHS.has(url.pathname))) {
780
+ if (unauthorized())
781
+ return;
782
+ const name = url.searchParams.get('name');
783
+ if (req.method === 'GET' && url.pathname === '/skills/content') {
784
+ if (storeRefused(true))
785
+ return;
786
+ const out = readUserSkill(homeSkillsDir(), name);
787
+ return reply('error' in out ? 404 : 200, out);
788
+ }
789
+ if (req.method !== 'POST' || url.pathname === '/skills/content')
790
+ return reply(405, { error: 'method not allowed' });
791
+ if (storeRefused())
792
+ return;
793
+ const out = changeSkill(url.pathname === '/skills/fork' ? 'fork' : 'remove', name, url.searchParams.get('to'));
794
+ return reply('ok' in out ? 200 : 400, { ...out, skills: loadSkillsList(homedir()) });
795
+ }
796
+ if (url.pathname.startsWith('/store/')) {
797
+ // Catalog browse/install for the store (same gate as /skills/*). GitHub is
798
+ // read here, never by the browser; installs only take entries from the
799
+ // agent's own cached catalog, by id.
800
+ if (unauthorized())
801
+ return;
802
+ try {
803
+ if (req.method === 'GET' && storeRefused(true))
804
+ return;
805
+ if (req.method === 'GET' && url.pathname === '/store/catalog') {
806
+ const src = url.searchParams.get('source');
807
+ const caches = await loadCatalog(src && src !== 'all' ? src.split(',') : null, { refresh: url.searchParams.get('refresh') === '1' });
808
+ const entries = caches.flatMap((c) => c.entries);
809
+ const skills = loadSkillsList(homedir());
810
+ const myAgents = (url.searchParams.get('agents') || '').split(',').map(storeName).filter(Boolean).slice(0, 50);
811
+ const installed = installedIds(entries, new Set(skills.map((s) => s.folder)), url.searchParams.getAll('origin').slice(0, 50));
812
+ const signals = [
813
+ ...skills.map((s) => ({ text: `${s.folder} ${s.name} ${s.description}`, reason: `because you use the ${s.folder} skill` })),
814
+ ...myAgents.map((n) => ({ text: n, reason: `because you have the ${n} agent` })),
815
+ ...(await listAllClaudeSessions(40)).filter((s) => s.title).map((s) => ({ text: s.title, reason: 'related to your recent sessions' })),
816
+ ];
817
+ return reply(200, {
818
+ sources: caches.map((c) => {
819
+ const s = SOURCES.find((x) => x.id === c.source);
820
+ return { id: c.source, label: s.label, repo: c.repo, trust: s.trust, sha: c.sha, fetchedAt: c.fetchedAt, count: c.entries.length, ...(c.error ? { error: c.error } : {}), ...(c.note ? { note: c.note } : {}) };
821
+ }),
822
+ entries,
823
+ installed: [...installed],
824
+ recommended: recommend(entries, signals, installed),
825
+ });
826
+ }
827
+ if (req.method === 'GET' && url.pathname === '/store/entry') {
828
+ const found = await findEntry(url.searchParams.get('id') || '');
829
+ if (!found)
830
+ return reply(404, { error: 'not in the catalog' });
831
+ // An agent's detail carries the draft it would install as (its starting role included).
832
+ return reply(200, { entry: found.entry, content: found.body, ...(found.entry.kind === 'agent' ? { draft: agentDraft(found.entry, found.body) } : {}) });
833
+ }
834
+ if (req.method === 'POST' && url.pathname === '/store/install') {
835
+ if (storeRefused())
836
+ return;
837
+ const found = await findEntry(url.searchParams.get('id') || '');
838
+ if (!found)
839
+ return reply(404, { error: 'not in the catalog' });
840
+ // Install what was reviewed: the card carries the entry's rev (its text and file list).
841
+ const reviewed = url.searchParams.get('rev');
842
+ if (reviewed && reviewed !== found.entry.rev)
843
+ return reply(409, { error: 'This entry changed upstream since you viewed it. Refresh and review it again.' });
844
+ // An agent whose prompt is over the limit is refused, never cut: what was reviewed is what installs.
845
+ if (found.entry.kind === 'agent' && found.body.length > AGENT_LIMITS.prompt)
846
+ return reply(400, { error: `this agent's prompt is ${found.body.length} characters; the limit is ${AGENT_LIMITS.prompt}` });
847
+ if (found.entry.kind === 'agent')
848
+ return reply(200, { draft: agentDraft(found.entry, found.body) });
849
+ const out = await installSkill(found.entry, homeSkillsDir(), coreSkillNames(PKG_SKILLS_DIR));
850
+ return reply('ok' in out ? 200 : 400, { ...out, skills: loadSkillsList(homedir()) });
851
+ }
852
+ return reply(404, { error: 'not found' });
853
+ }
854
+ catch (e) {
855
+ return reply(502, { error: e instanceof Error ? e.message : 'store request failed' });
856
+ }
857
+ }
716
858
  if (req.method === 'GET' && url.pathname === '/agents') {
717
- // Named sub-agents (researcher/reasoner/writer) — definitions come from
718
- // claude-llm.ts NAMED_AGENTS (single source of truth, same object the SDK
719
- // query uses). Prompts are omitted: the UI manager needs role/model/tools,
720
- // not the full instruction text.
721
- const agents = Object.entries(NAMED_AGENTS).map(([name, a]) => ({
722
- name,
723
- description: a.description,
724
- model: a.model,
725
- tools: a.tools,
726
- }));
727
- res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
728
- res.end(JSON.stringify({ agents }));
729
- return;
859
+ // Core sub-agents from claude-llm.ts NAMED_AGENTS (the same object the SDK
860
+ // query uses), with prompts so the store can show and fork them — so gated
861
+ // like the other store routes (the chat and Settings go through /api/agent).
862
+ if (unauthorized() || storeRefused(true))
863
+ return;
864
+ return reply(200, { agents: describeAgents(NAMED_AGENTS, null, {}, true), ...describeRoles() });
730
865
  }
731
866
  if (req.method === 'GET' && url.pathname === '/health') {
732
867
  // Include osborn version — primary signal used by machines.readInstalledOsbornVersion()
@@ -767,6 +902,13 @@ function startApiServer(workingDir, port) {
767
902
  status: 'ok',
768
903
  workingDir,
769
904
  version,
905
+ // Library: is it on, can it call the model, does it reach /library (no values, 8-char session id).
906
+ library: {
907
+ enabled: isContentLensEnabled(),
908
+ modelKey: !!(process.env.OPENROUTER_API_KEY || '').trim(),
909
+ ingest: (() => { const c = resolveIngestConfig(); return 'reason' in c ? (c.reason === 'no-key' ? 'no-anon-key' : c.reason) : 'on'; })(),
910
+ lastRun: lastLibraryRun(),
911
+ },
770
912
  // WHERE this machine physically runs — Fly sets FLY_REGION (e.g. 'ord').
771
913
  // The dashboard maps it to a city ("Chicago") so the user always knows
772
914
  // the machine's location, not just their own clock. Null in local dev.
@@ -1915,6 +2057,14 @@ function startApiServer(workingDir, port) {
1915
2057
  });
1916
2058
  const host = process.env.HOST || '0.0.0.0';
1917
2059
  server.requestTimeout = 0; // no timeout — large uploads can take minutes
2060
+ {
2061
+ const c = resolveIngestConfig();
2062
+ const why = 'reason' in c ? c.reason : null;
2063
+ if (!(process.env.OPENROUTER_API_KEY || '').trim())
2064
+ console.warn('⚠️ library: OPENROUTER_API_KEY is not set: no Library pages will be written');
2065
+ else if (why && why !== 'disabled')
2066
+ console.warn(`⚠️ library: pages stay on this machine, nothing reaches /library (${why})`);
2067
+ }
1918
2068
  server.listen(port, host, () => {
1919
2069
  console.log(`🌐 API server listening on http://${host}:${port}`);
1920
2070
  console.log(` Sessions: http://${host}:${port}/sessions`);
@@ -2239,7 +2389,10 @@ async function main() {
2239
2389
  // P1: room stays alive while the host anchor is active or any background slot
2240
2390
  // is running. Teardown timers below early-return on this so a dashboard-started
2241
2391
  // session + its background dispatches aren't killed by the empty-room grace.
2242
- const agentsActive = () => hostActive || slots.size > 0;
2392
+ // Work the user left running when they hung up (keep-working, below) holds the
2393
+ // machine the same way, until it finishes or hits its cap.
2394
+ let keepWorkingActive = false;
2395
+ const agentsActive = () => hostActive || slots.size > 0 || keepWorkingActive;
2243
2396
  // Release the host anchor + hard-kill background slots at a genuine session-end
2244
2397
  // boundary so the room can idle-exit (agentsActive → false). Idempotent. MUST be
2245
2398
  // called before arming idle-exit on EVERY path where the session ends, or the
@@ -2362,7 +2515,8 @@ async function main() {
2362
2515
  // fast-leave) — the parked brain does NOT hold the room (it's no longer
2363
2516
  // `currentLLM` nor in `slots`, so agentsActive() is false);
2364
2517
  // 2. a grace timer frees the parked brain if no reconnect arrives;
2365
- // 3. an INDEPENDENT watchdog hard-kills it at a ceiling even if (2) is buggy.
2518
+ // 3. an INDEPENDENT watchdog hard-kills it at a ceiling even if (2) is buggy
2519
+ // (while keep-working runs, its cap timer replaces (2) and (3).)
2366
2520
  // One-owner invariant: the subprocess is owned by exactly one of
2367
2521
  // {currentLLM, warmLLM}, or it's aborted — never two live, never orphaned.
2368
2522
  // DEFAULT-ON (user, 2026-10-21): the three backstops above — not the flag —
@@ -2424,11 +2578,33 @@ async function main() {
2424
2578
  'session_id', 'mcp_servers_changed', 'tool_use', 'tool_result',
2425
2579
  'assistant_text', 'assistant_result', 'tts_chunks', 'permission_request',
2426
2580
  'tts_say', 'session_resume_failed', 'checkpoint_captured',
2427
- 'dispatch_rejected', 'task_completed', 'agent_started',
2581
+ 'dispatch_rejected', 'task_completed', 'agent_started', 'steward_verdict', 'steward_gate', 'tool_blocked',
2428
2582
  ];
2429
- // Abort + clear the parked brain. Clears BOTH timers so grace/watchdog can't
2430
- // double-fire. Used on grace expiry, watchdog, and session mismatch.
2431
- const killWarm = (reason) => {
2583
+ // ── KEEP WORKING AFTER HANG-UP ──
2584
+ // When the user ends the call while the agent is mid-task and chooses "Keep
2585
+ // working" (data message keep_working), the keep-warm park below drops its
2586
+ // short grace: the brain runs until its turn and tasks finish (then a phone
2587
+ // notice, and the normal re-attach grace), or until the machine's own idle
2588
+ // timeout (IDLE_EXIT_GRACE_MS, 15 min) has passed since the hang-up, when it
2589
+ // is stopped. keepWorkingActive holds the machine (idle-exit, recycle); the
2590
+ // room still tears down. A reconnect re-attaches through claimWarm.
2591
+ let keepWorkingRequested = false;
2592
+ let keepWorkingPoll = null;
2593
+ let keepWorkingCap = null;
2594
+ const stopKeepWorking = () => {
2595
+ if (keepWorkingPoll) {
2596
+ clearInterval(keepWorkingPoll);
2597
+ keepWorkingPoll = null;
2598
+ }
2599
+ if (keepWorkingCap) {
2600
+ clearTimeout(keepWorkingCap);
2601
+ keepWorkingCap = null;
2602
+ }
2603
+ keepWorkingActive = false;
2604
+ };
2605
+ // Every timer that can end or free the parked brain.
2606
+ const clearWarmTimers = () => {
2607
+ stopKeepWorking();
2432
2608
  if (warmGraceTimer) {
2433
2609
  clearTimeout(warmGraceTimer);
2434
2610
  warmGraceTimer = null;
@@ -2437,6 +2613,49 @@ async function main() {
2437
2613
  clearTimeout(warmWatchdog);
2438
2614
  warmWatchdog = null;
2439
2615
  }
2616
+ };
2617
+ // Called right after parkWarm, once the room teardown is armed.
2618
+ const keepWorkingAfterLeave = () => {
2619
+ if (!warmLLM)
2620
+ return;
2621
+ clearWarmTimers();
2622
+ const started = Date.now();
2623
+ warmExpiry = started + IDLE_EXIT_GRACE_MS; // a reconnect while it works re-attaches
2624
+ keepWorkingActive = true;
2625
+ console.log(`🏃 [KEEP-WORKING] user hung up mid-task — working on for up to ${IDLE_EXIT_GRACE_MS / 60000} min`);
2626
+ keepWorkingPoll = setInterval(() => {
2627
+ const busy = warmLLM?.busyState?.();
2628
+ if (busy?.permissionPending) {
2629
+ // Blocked on an approval. If a phone push is out, its answer reaches the
2630
+ // parked brain, so keep waiting (the cap still applies); otherwise nobody
2631
+ // can answer, so fall back to the grace.
2632
+ if (phonePushPending())
2633
+ return;
2634
+ stopKeepWorking();
2635
+ console.log('✋ [KEEP-WORKING] waiting on an approval no phone can answer — normal re-attach grace from here');
2636
+ warmExpiry = Date.now() + REATTACH_GRACE_MS;
2637
+ armWarmTimers();
2638
+ return;
2639
+ }
2640
+ if (!(busy?.idle ?? true))
2641
+ return;
2642
+ stopKeepWorking();
2643
+ const mins = Math.max(1, Math.round((Date.now() - started) / 60000));
2644
+ console.log(`🏁 [KEEP-WORKING] finished after ~${mins} min — normal re-attach grace from here`);
2645
+ void notifyPhone(`Osborn finished the work you left running (${mins} min). Open Voice Native to see the result.`);
2646
+ warmExpiry = Date.now() + REATTACH_GRACE_MS;
2647
+ armWarmTimers();
2648
+ }, 15_000);
2649
+ keepWorkingCap = setTimeout(() => {
2650
+ console.log(`⏱️ [KEEP-WORKING] cap reached (${IDLE_EXIT_GRACE_MS / 60000} min) — stopping`);
2651
+ freeWarm('keep_working_cap');
2652
+ void notifyPhone(`Osborn stopped the work you left running after ${IDLE_EXIT_GRACE_MS / 60000} minutes. Reconnect to continue it.`);
2653
+ }, IDLE_EXIT_GRACE_MS);
2654
+ };
2655
+ // Abort + clear the parked brain. Clears BOTH timers so grace/watchdog can't
2656
+ // double-fire. Used on grace expiry, watchdog, and session mismatch.
2657
+ const killWarm = (reason) => {
2658
+ clearWarmTimers();
2440
2659
  if (warmLLM) {
2441
2660
  try {
2442
2661
  const llm = warmLLM;
@@ -2448,6 +2667,9 @@ async function main() {
2448
2667
  catch (err) {
2449
2668
  console.error(`❌ killWarm(${reason}) abort failed:`, err instanceof Error ? err.message : err);
2450
2669
  }
2670
+ finally {
2671
+ launchLibraryOnSessionEnd(warmSessionId, warmLLM?.workingDirectory || workingDir, `warm_${reason}`);
2672
+ }
2451
2673
  }
2452
2674
  if (warmLLM)
2453
2675
  console.log(`🧊 [KEEP-WARM] freed warm slot (${reason})`);
@@ -2456,8 +2678,16 @@ async function main() {
2456
2678
  warmExpiry = 0;
2457
2679
  };
2458
2680
  // Grace timer (free memory if no reconnect) + INDEPENDENT watchdog ceiling.
2459
- // Both end in the SAME teardown: kill warm → releaseAgents → arm idle-exit, so
2460
- // the machine always self-stops within WARM_HARD_CEILING_MS + idle-grace.
2681
+ // Both end in the SAME teardown (freeWarm, also keep-working's cap): kill warm →
2682
+ // releaseAgents → fast-leave (a room the kept slots held) → arm idle-exit, so the
2683
+ // machine always self-stops within WARM_HARD_CEILING_MS + idle-grace (keep-working:
2684
+ // its cap + the re-attach grace + idle-grace).
2685
+ const freeWarm = (reason) => {
2686
+ killWarm(reason);
2687
+ releaseAgents();
2688
+ armFastLeaveTimer();
2689
+ armIdleExitTimer(`warm-${reason}`);
2690
+ };
2461
2691
  const armWarmTimers = () => {
2462
2692
  if (warmGraceTimer)
2463
2693
  clearTimeout(warmGraceTimer);
@@ -2467,17 +2697,13 @@ async function main() {
2467
2697
  warmGraceTimer = null;
2468
2698
  warmStats.wastedTimeouts++;
2469
2699
  console.log('🧊 [KEEP-WARM] grace expired with no reconnect — freeing warm slot');
2470
- killWarm('grace_expired');
2471
- releaseAgents();
2472
- armIdleExitTimer('warm-grace-expired');
2700
+ freeWarm('grace_expired');
2473
2701
  }, REATTACH_GRACE_MS);
2474
2702
  warmWatchdog = setTimeout(() => {
2475
2703
  warmWatchdog = null;
2476
2704
  warmStats.watchdogKills++;
2477
2705
  console.warn('🧊 [KEEP-WARM] WATCHDOG ceiling hit — hard-freeing warm slot (backstop)');
2478
- killWarm('watchdog_ceiling');
2479
- releaseAgents();
2480
- armIdleExitTimer('warm-watchdog');
2706
+ freeWarm('watchdog_ceiling');
2481
2707
  }, WARM_HARD_CEILING_MS);
2482
2708
  };
2483
2709
  // Move currentLLM → warm slot WITHOUT aborting it (the park). If there's no
@@ -2511,14 +2737,7 @@ async function main() {
2511
2737
  // Detach the parked brain for reuse WITHOUT aborting it, cancelling its timers.
2512
2738
  // Caller takes ownership (becomes currentLLM via createDirectSession).
2513
2739
  const claimWarm = () => {
2514
- if (warmGraceTimer) {
2515
- clearTimeout(warmGraceTimer);
2516
- warmGraceTimer = null;
2517
- }
2518
- if (warmWatchdog) {
2519
- clearTimeout(warmWatchdog);
2520
- warmWatchdog = null;
2521
- }
2740
+ clearWarmTimers();
2522
2741
  const llm = warmLLM;
2523
2742
  warmLLM = null;
2524
2743
  warmSessionId = null;
@@ -2654,6 +2873,9 @@ async function main() {
2654
2873
  catch (err) {
2655
2874
  console.error(`❌ killCurrentLLM(${reason}) failed:`, err instanceof Error ? err.message : err);
2656
2875
  }
2876
+ finally {
2877
+ launchLibraryOnSessionEnd(currentLLM?.sessionId, currentLLM?.workingDirectory || workingDir, reason);
2878
+ }
2657
2879
  }
2658
2880
  // ============================================================
2659
2881
  // SLICE 1: spawnBackgroundSession
@@ -2803,17 +3025,23 @@ async function main() {
2803
3025
  let currentUserId = '';
2804
3026
  // Per-user named agents (DB-backed) — sent by the frontend via set_agents
2805
3027
  // after agent_ready. Kept here so agent-side LLM recreations (session
2806
- // switch/resume) reuse them without waiting for a frontend resend. Merged
2807
- // OVER the built-in NAMED_AGENTS (same-name user rows shadow built-ins).
3028
+ // switch/resume) reuse them without waiting for a frontend resend. Added
3029
+ // beside the core NAMED_AGENTS, which they can never override or remove.
2808
3030
  let userNamedAgents = null;
3031
+ let userAgentRoles = {};
3032
+ let userAgentOrigins = {};
3033
+ const loggedDroppedAgents = new Set();
2809
3034
  // Turbo mode — read from set_agents handshake (data.turbo). When true every
2810
3035
  // agent (main + sub-agents) runs on FAST_MODEL. Default false = perfect no-op.
2811
3036
  let turboMode = false;
2812
- // Built-ins the user has removed (tombstoned in user_agents with enabled=false).
2813
- // A removed built-in disappears from the effective set but stays re-addable
2814
- // from the frontend's "Available to add" list — default agents are never
2815
- // gone forever, matching the skill-catalog pattern.
2816
- let userRemovedAgents = [];
3037
+ // The per-user agents for the voice session's LLMs (direct, pipeline and recovery),
3038
+ // so a session switch or rebuild keeps them (headless background slots run the built-ins). applyTurbo runs after the
3039
+ // merge so custom models are overridden too. With no custom agents, undefined lets
3040
+ // ClaudeLLM use NAMED_AGENTS directly (turbo then applies inside ClaudeLLMStream).
3041
+ const userAgentOptions = () => ({
3042
+ agents: userNamedAgents ? applyTurbo(mergeAgents(NAMED_AGENTS, userNamedAgents), turboMode) : undefined,
3043
+ agentRoles: userAgentRoles,
3044
+ });
2817
3045
  let activeMeetingBotId = null; // Recall.ai bot ID if in a meeting
2818
3046
  // While set (Date.now() < value), the agent's streaming tts_say output is
2819
3047
  // REDIRECTED into the meeting canvas instead of suppressed — the regular
@@ -3940,6 +4168,7 @@ async function main() {
3940
4168
  statusManager.upsertDispatch(d.id, { dispatchState: 'failed' });
3941
4169
  }
3942
4170
  // 4. Close the old query (idle, or forced) and clear its resume state.
4171
+ launchLibraryOnSessionEnd(llmAny.sessionId, llmAny.workingDirectory || workingDir, 'session_switch');
3943
4172
  currentLLM.resetForSessionSwitch();
3944
4173
  // 5. Cross-project: the SDK cwd, fast brain and session tail move together.
3945
4174
  if (cwd !== workingDir) {
@@ -3979,15 +4208,13 @@ async function main() {
3979
4208
  // 11. Tell the UI; it replaces the transcript with the target's history.
3980
4209
  const summary = await getSessionSummary(target, cwd);
3981
4210
  const conversationHistory = await getConversationHistory(target, cwd, 30);
3982
- await sendToFrontend({
3983
- type: 'session_switched',
3984
- sessionId: target,
3985
- workingDirectory: cwd,
3986
- success: true,
3987
- forced: plan.reason === 'forced',
3988
- summary,
3989
- conversationHistory,
3990
- });
4211
+ const switched = { type: 'session_switched', sessionId: target, workingDirectory: cwd, success: true, forced: plan.reason === 'forced' };
4212
+ // The history is only the UI's fallback (it reads /session-messages first); when it pushes the
4213
+ // message past the size cap, send the switch without it so the rail and URL still move.
4214
+ const told = await sendToFrontend({ ...switched, summary, conversationHistory })
4215
+ || await sendToFrontend(switched);
4216
+ if (!told)
4217
+ console.warn(`⚠️ Switch to ${target.slice(0, 8)}: the UI was not told (no room or publish failed)`);
3991
4218
  const switchArtifacts = listWorkspaceArtifacts(cwd, target);
3992
4219
  if (switchArtifacts.length > 0) {
3993
4220
  await sendToFrontend({
@@ -4062,10 +4289,12 @@ async function main() {
4062
4289
  }
4063
4290
  catch { }
4064
4291
  });
4065
- async function sendToFrontend(data) {
4292
+ /** Publishes to the frontend (to one participant when `to` is given). Resolves false
4293
+ * when nothing was sent (no room, over the hard size cap, or a publish error). */
4294
+ async function sendToFrontend(data, to) {
4066
4295
  if (!localParticipant) {
4067
4296
  console.log('⚠️ sendToFrontend: no localParticipant!');
4068
- return;
4297
+ return false;
4069
4298
  }
4070
4299
  try {
4071
4300
  const encoder = new TextEncoder();
@@ -4098,16 +4327,19 @@ async function main() {
4098
4327
  const payload = encoder.encode(jsonData);
4099
4328
  if (payload.length > HARD_MAX_MESSAGE_SIZE) {
4100
4329
  console.error(`❌ sendToFrontend: dropping message (${(payload.length / 1024).toFixed(0)}KB > ${(HARD_MAX_MESSAGE_SIZE / 1024).toFixed(0)}KB hard limit) — type: ${data.type}`);
4101
- return;
4330
+ return false;
4102
4331
  }
4103
4332
  await localParticipant.publishData(payload, {
4104
4333
  reliable: true,
4105
4334
  topic: 'osborn-updates',
4335
+ ...(to ? { destinationIdentities: [to] } : {}),
4106
4336
  });
4107
4337
  console.log(`📤 Sent to frontend: ${data.type} (${payload.length} bytes)`);
4338
+ return true;
4108
4339
  }
4109
4340
  catch (err) {
4110
4341
  console.error('❌ sendToFrontend error:', err);
4342
+ return false;
4111
4343
  }
4112
4344
  }
4113
4345
  // ── Phase B — meeting addressing/mute state → frontend (over the EXISTING
@@ -4216,18 +4448,7 @@ async function main() {
4216
4448
  voiceMode: 'direct',
4217
4449
  skipTTSQueue: true,
4218
4450
  onCompactionEvent: buildOnCompactionEvent(),
4219
- // Per-user named agents survive LLM recreations (session switch/resume).
4220
- // applyTurbo runs post-merge so custom models are also overridden when turbo is on.
4221
- // When neither custom agents nor turbo are active, pass undefined so the
4222
- // ClaudeLLM cold-start uses NAMED_AGENTS directly (the ?? NAMED_AGENTS path).
4223
- // When turbo IS on with no custom agents, undefined would skip the override —
4224
- // ClaudeLLM handles that internally via the turbo bypass in ClaudeLLMStream.
4225
- agents: (userNamedAgents || userRemovedAgents.length) ? (() => {
4226
- const base = { ...NAMED_AGENTS };
4227
- for (const r of userRemovedAgents)
4228
- delete base[r];
4229
- return applyTurbo({ ...base, ...(userNamedAgents || {}) }, turboMode);
4230
- })() : undefined,
4451
+ ...userAgentOptions(),
4231
4452
  });
4232
4453
  // Apply turbo to the freshly created LLM so the main model also picks it up.
4233
4454
  // PipelineDirectLLM (llmOverride path) wraps its own ClaudeLLM and may not expose setTurbo.
@@ -4237,8 +4458,9 @@ async function main() {
4237
4458
  // permission is currently pending. Re-registered per session — harmless,
4238
4459
  // the latest closure wins and they all resolve through currentLLM.
4239
4460
  setWatchResultHandler((allow, toolName) => {
4240
- if (currentLLM?.hasPendingPermission?.()) {
4241
- currentLLM.respondToPermission(allow);
4461
+ const target = currentLLM?.hasPendingPermission?.() ? currentLLM : warmLLM?.hasPendingPermission?.() ? warmLLM : null;
4462
+ if (target) {
4463
+ target.respondToPermission(allow);
4242
4464
  console.log(`⌚️ Watch bridge settled ${toolName}: ${allow ? 'approve' : 'deny'}`);
4243
4465
  }
4244
4466
  else {
@@ -4688,6 +4910,10 @@ async function main() {
4688
4910
  agent_id: d.agent_id,
4689
4911
  last_assistant_message: d.last_assistant_message,
4690
4912
  }));
4913
+ // Steward verdict card + sign-off gate note (#221) → chat
4914
+ directLLM.events.on('steward_verdict', (v) => sendToFrontend({ type: 'steward_verdict', ...v }));
4915
+ directLLM.events.on('steward_gate', (d) => sendToFrontend({ type: 'steward_gate', decision: d.decision, message: d.message }));
4916
+ directLLM.events.on('tool_blocked', (d) => sendToFrontend({ type: 'tool_blocked', ...d }));
4691
4917
  // Dispatcher v1 — sub-agent started → frontend stop-key signal (Feature A2)
4692
4918
  directLLM.events.on('agent_started', (d) => sendToFrontend({
4693
4919
  type: 'agent_started',
@@ -5020,6 +5246,7 @@ async function main() {
5020
5246
  // connect callback, not via events).
5021
5247
  participantConnectedHandler = async (participant) => {
5022
5248
  console.log(`\n👤 User joined: ${participant.identity}`);
5249
+ keepWorkingRequested = false; // a request belongs to the hang-up it preceded
5023
5250
  // The meeting canvas joining as a listener = browser-parity audio path is
5024
5251
  // LIVE: the agent's normal session.say plays through the canvas into the
5025
5252
  // meeting, so tts_say suppression/redirect must stand down.
@@ -5226,6 +5453,10 @@ async function main() {
5226
5453
  session = result.session;
5227
5454
  agent = result.agent;
5228
5455
  reattached = true;
5456
+ const pending = reused?.getPendingPermission?.();
5457
+ // Its prompt went to the old room: re-show it through the wired listener (diff included).
5458
+ if (pending)
5459
+ reused.events?.emit('permission_request', pending);
5229
5460
  }
5230
5461
  else if (warmLLM) {
5231
5462
  killWarm(warmSessionId && warmSessionId !== resumeSessionId ? 'reattach_session_mismatch' : 'reattach_expired');
@@ -5242,6 +5473,7 @@ async function main() {
5242
5473
  resumeSessionId,
5243
5474
  voiceMode: 'direct',
5244
5475
  skipTTSQueue: true,
5476
+ ...userAgentOptions(),
5245
5477
  // PipelineDirectOptions extends ClaudeLLMOptions; passing this through
5246
5478
  // forwards it into the inner `new ClaudeLLM(opts)`. Without this,
5247
5479
  // pipeline mode silently drops every PreCompact/PostCompact event
@@ -5748,6 +5980,7 @@ async function main() {
5748
5980
  resumeSessionId: recoverySessionId,
5749
5981
  voiceMode: 'direct',
5750
5982
  skipTTSQueue: true,
5983
+ ...userAgentOptions(),
5751
5984
  getChatHistory: () => getChatHistory(20).map(t => ({ role: t.role, content: t.text })),
5752
5985
  getResearchContext: () => {
5753
5986
  if (activeResearch?.researchLog.length) {
@@ -5876,9 +6109,9 @@ async function main() {
5876
6109
  enabledMcpServers: enabledMcpNames,
5877
6110
  workingDirectory: workingDir,
5878
6111
  skills: loadSkillsList(homedir()),
5879
- namedAgents: Object.entries(NAMED_AGENTS).map(([name, a]) => ({
5880
- name, description: a.description, model: a.model, tools: a.tools,
5881
- })),
6112
+ namedAgents: describeAgents(NAMED_AGENTS, userNamedAgents, userAgentRoles, false, userAgentOrigins),
6113
+ ...describeRoles(),
6114
+ keepWorking: true,
5882
6115
  });
5883
6116
  };
5884
6117
  const readyInterval = setInterval(sendReady, 2000);
@@ -5962,8 +6195,10 @@ async function main() {
5962
6195
  // Durable compaction markers ride the same push so the resumed
5963
6196
  // transcript rebuilds its "Conversation compacted" rows too.
5964
6197
  const compactions = readCompactionMarkers(preSelectedSessionId, workingDir);
6198
+ // Last few cards, without the full return text, so the push stays under the packet limit.
6199
+ const steward = readStewardVerdicts(preSelectedSessionId, workingDir).slice(-10).map(({ raw, ...v }) => v);
5965
6200
  if (priorMessages.length > 0) {
5966
- await sendToFrontend({ type: 'prior_messages', sessionId: preSelectedSessionId, messages: priorMessages, compactions });
6201
+ await sendToFrontend({ type: 'prior_messages', sessionId: preSelectedSessionId, messages: priorMessages, compactions, steward });
5967
6202
  console.log(`💬 Sent ${priorMessages.length} prior messages (+${compactions.length} compaction markers) from DB for optimistic UI`);
5968
6203
  }
5969
6204
  }
@@ -6109,6 +6344,11 @@ async function main() {
6109
6344
  releaseAgents();
6110
6345
  armMeetingLeaveGrace();
6111
6346
  armFastLeaveTimer();
6347
+ // "Keep working" chosen at End: after the teardown is armed (it checks agentsActive()).
6348
+ if (keepWorkingRequested) {
6349
+ keepWorkingRequested = false;
6350
+ keepWorkingAfterLeave();
6351
+ }
6112
6352
  }
6113
6353
  else {
6114
6354
  // Kill the Claude SDK subprocess BEFORE dropping the reference, otherwise the
@@ -6145,6 +6385,10 @@ async function main() {
6145
6385
  const senderCheck = checkControlSender(String(data.type), participant?.identity, controllingUserIdentity);
6146
6386
  if (!senderCheck.ok) {
6147
6387
  console.warn(`🚫 Dropped ${data.type}: ${senderCheck.reason}`);
6388
+ // A store request waits for its reply (the chat's askAgent): answer the sender now.
6389
+ if (Object.hasOwn(STORE_REPLY_TYPES, data.type) && participant?.identity) {
6390
+ await sendToFrontend({ type: STORE_REPLY_TYPES[data.type], success: false, error: 'Another device controls this session' }, participant.identity);
6391
+ }
6148
6392
  return;
6149
6393
  }
6150
6394
  if (data.type === 'claude_auth_code' && pendingAuthSubmitCode) {
@@ -6440,6 +6684,18 @@ async function main() {
6440
6684
  const hint = typeof data.workingDirectory === 'string' ? data.workingDirectory : undefined;
6441
6685
  await requestSessionSwitch(sessionId, hint, { force: !!data.force, origin: 'switch_session' });
6442
6686
  }
6687
+ else if (data.type === 'get_busy') {
6688
+ // End asks before hanging up: a busy agent may keep working (keep_working).
6689
+ // Offered only when the hang-up will park the brain (the KEEP_WARM branch of
6690
+ // the disconnect handler) and it is working, not just waiting on an approval.
6691
+ const busy = currentLLM?.busyState?.();
6692
+ const parks = KEEP_WARM && !activeMeetingBotId && !!currentLLM?.sessionId;
6693
+ await sendToFrontend({ type: 'busy_state', idle: (busy?.idle ?? true) || !!busy?.permissionPending, capMin: parks ? IDLE_EXIT_GRACE_MS / 60000 : 0, phone: isWatchBridgeEnabled() }, participant?.identity);
6694
+ }
6695
+ else if (data.type === 'keep_working') {
6696
+ keepWorkingRequested = true;
6697
+ console.log('🏃 [KEEP-WORKING] requested — the next hang-up keeps the agent working');
6698
+ }
6443
6699
  else if (data.type === 'cancel_session_switch') {
6444
6700
  if (pendingSwitch)
6445
6701
  cancelPendingSwitch('user_cancelled');
@@ -6692,116 +6948,50 @@ async function main() {
6692
6948
  skills: loadSkillsList(homedir()),
6693
6949
  });
6694
6950
  }
6695
- else if (data.type === 'get_agents') {
6696
- // Named sub-agents for the chat agents manager — built-ins (minus any
6697
- // user-removed) merged with per-user DB-backed definitions.
6698
- const effectiveBase = { ...NAMED_AGENTS };
6699
- for (const r of userRemovedAgents)
6700
- delete effectiveBase[r];
6701
- const effective = { ...effectiveBase, ...(userNamedAgents || {}) };
6702
- await sendToFrontend({
6703
- type: 'agents_status',
6704
- agents: Object.entries(effective).map(([name, a]) => ({
6705
- name, description: a.description, model: a.model, tools: a.tools,
6706
- custom: !!userNamedAgents && name in userNamedAgents,
6707
- })),
6708
- });
6709
- }
6710
6951
  else if (data.type === 'set_agents') {
6711
6952
  // Per-user named agents from the DB (frontend fetches its user_agents
6712
6953
  // rows and sends them here after agent_ready, and again after edits).
6713
- // Validated + merged over built-ins, applied via setAgents(). SDK
6954
+ // Added beside the core agents, applied via setAgents(). SDK
6714
6955
  // constraint: takes effect at the next query cold start — a live
6715
6956
  // subprocess keeps the agents it started with.
6716
- const MODELS = new Set(['sonnet', 'opus', 'haiku', 'fable', 'inherit']);
6717
- const rows = Array.isArray(data.agents) ? data.agents : [];
6718
- const validated = {};
6719
- for (const r of rows) {
6720
- const name = String(r?.name || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-');
6721
- const description = String(r?.description || '').trim();
6722
- const prompt = String(r?.prompt || '').trim();
6723
- if (!name || !description || !prompt)
6957
+ const parsed = parseUserAgents(data.agents, NAMED_AGENTS);
6958
+ for (const d of parsed.dropped) {
6959
+ const key = `${d.name}: ${d.reason}`;
6960
+ if (loggedDroppedAgents.has(key))
6724
6961
  continue;
6725
- if (prompt.length > 6000) {
6726
- console.warn(`🤖 set_agents: '${name}' prompt >6KB — skipped`);
6727
- continue;
6728
- }
6729
- validated[name] = {
6730
- description,
6731
- prompt,
6732
- ...(Array.isArray(r.tools) && r.tools.length ? { tools: r.tools.map(String) } : {}),
6733
- ...(r.model && (MODELS.has(r.model) || /^claude-/.test(r.model)) ? { model: String(r.model) } : {}),
6734
- };
6962
+ loggedDroppedAgents.add(key);
6963
+ console.warn(`🤖 set_agents: '${d.name}' dropped — ${d.reason}`);
6735
6964
  }
6736
- userNamedAgents = Object.keys(validated).length ? validated : null;
6737
- // Removed built-ins (tombstones) — excluded from the effective set.
6738
- userRemovedAgents = Array.isArray(data.removed) ? data.removed.map(String) : [];
6965
+ userNamedAgents = Object.keys(parsed.agents).length ? parsed.agents : null;
6966
+ userAgentRoles = parsed.roles;
6967
+ userAgentOrigins = parsed.origins;
6739
6968
  // Turbo preference from the frontend (sourced from user_settings DB row).
6740
6969
  turboMode = !!data.turbo;
6741
- const base = { ...NAMED_AGENTS };
6742
- for (const r of userRemovedAgents)
6743
- delete base[r];
6744
- // applyTurbo wraps AFTER the base+custom merge so custom models also get overridden.
6745
- const merged = applyTurbo({ ...base, ...(userNamedAgents || {}) }, turboMode);
6746
- const customized = !!userNamedAgents || userRemovedAgents.length > 0 || turboMode;
6970
+ // applyTurbo wraps AFTER the merge so custom models also get overridden.
6971
+ const merged = applyTurbo(mergeAgents(NAMED_AGENTS, userNamedAgents), turboMode);
6747
6972
  currentLLM?.setTurbo?.(turboMode);
6748
- currentLLM?.setAgents?.(customized ? merged : undefined);
6749
- console.log(`🤖 set_agents: ${Object.keys(validated).length} user agent(s), ${userRemovedAgents.length} removed → effective [${Object.keys(merged).join(', ')}]`);
6750
- await sendToFrontend({
6751
- type: 'agents_status',
6752
- agents: Object.entries(merged).map(([name, a]) => ({
6753
- name, description: a.description, model: a.model, tools: a.tools,
6754
- custom: !!userNamedAgents && name in userNamedAgents,
6755
- })),
6756
- });
6757
- }
6758
- else if (data.type === 'skill_add') {
6759
- const skillName = (data.name || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-');
6760
- const skillContent = (data.content || '').trim();
6761
- if (!skillName || !skillContent) {
6762
- await sendToFrontend({ type: 'skill_add_result', success: false, error: 'Name and content are required' });
6763
- }
6764
- else {
6765
- try {
6766
- const skillDir = join(homedir(), '.claude', 'skills', skillName);
6767
- mkdirSync(skillDir, { recursive: true });
6768
- writeFileSync(join(skillDir, 'SKILL.md'), skillContent, 'utf-8');
6769
- console.log(`📚 Skill added: ${skillName}`);
6770
- const skills = loadSkillsList(homedir());
6771
- await sendToFrontend({ type: 'skill_add_result', success: true, skills });
6772
- }
6773
- catch (err) {
6774
- console.error('❌ Failed to add skill:', err);
6775
- await sendToFrontend({ type: 'skill_add_result', success: false, error: String(err) });
6776
- }
6777
- }
6973
+ currentLLM?.setAgents?.(userNamedAgents || turboMode ? merged : undefined, userAgentRoles);
6974
+ console.log(`🤖 set_agents: ${Object.keys(parsed.agents).length} user agent(s) → effective [${Object.keys(merged).join(', ')}]`);
6975
+ await sendToFrontend({ type: 'agents_status', agents: describeAgents(NAMED_AGENTS, userNamedAgents, userAgentRoles, false, userAgentOrigins), ...describeRoles() });
6778
6976
  }
6977
+ // The chat's skill actions go to the agent it is connected to (LAN, tunnel or cloud);
6978
+ // Settings, which has no room, uses the /skills/* routes. Both call changeSkill.
6779
6979
  else if (data.type === 'skill_get') {
6780
- const folder = (data.name || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-');
6781
- const p = join(homedir(), '.claude', 'skills', folder, 'SKILL.md');
6782
- if (folder && existsSync(p)) {
6783
- await sendToFrontend({ type: 'skill_content', name: folder, content: readFileSync(p, 'utf-8') });
6784
- }
6785
- else {
6786
- await sendToFrontend({ type: 'skill_content', name: folder, error: 'skill not found' });
6787
- }
6788
- }
6789
- else if (data.type === 'skill_remove') {
6790
- const folder = (data.name || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-');
6791
- const dir = join(homedir(), '.claude', 'skills', folder);
6792
- if (!folder || !existsSync(dir)) {
6793
- await sendToFrontend({ type: 'skill_remove_result', success: false, error: 'skill not found' });
6794
- }
6795
- else {
6796
- try {
6797
- rmSync(dir, { recursive: true, force: true });
6798
- console.log(`🗑️ Skill removed: ${folder}`);
6799
- await sendToFrontend({ type: 'skill_remove_result', success: true, skills: loadSkillsList(homedir()) });
6800
- }
6801
- catch (err) {
6802
- await sendToFrontend({ type: 'skill_remove_result', success: false, error: String(err) });
6803
- }
6804
- }
6980
+ const out = readUserSkill(homeSkillsDir(), data.name);
6981
+ await sendToFrontend({ type: STORE_REPLY_TYPES.skill_get, ...('error' in out ? { name: storeName(data.name), error: out.error } : out) });
6982
+ }
6983
+ else if (data.type === 'skill_add' || data.type === 'skill_fork' || data.type === 'skill_remove') {
6984
+ const op = data.type === 'skill_add' ? 'add' : data.type === 'skill_fork' ? 'fork' : 'remove';
6985
+ const out = changeSkill(op, data.name, op === 'add' ? data.content : data.to);
6986
+ const result = { type: STORE_REPLY_TYPES[data.type], success: 'ok' in out, ...('error' in out ? { error: out.error } : {}) };
6987
+ // A skill list over the data-channel cap is dropped: the result still goes out without it.
6988
+ if (!await sendToFrontend({ ...result, skills: loadSkillsList(homedir()) }))
6989
+ await sendToFrontend(result);
6990
+ }
6991
+ else if (data.type === 'get_agent_prompt') {
6992
+ // A built-in agent's prompt for View / Fork in the chat (the listing never carries prompts).
6993
+ const name = String(data.name || '');
6994
+ await sendToFrontend({ type: STORE_REPLY_TYPES.get_agent_prompt, name, prompt: coreRole(name, NAMED_AGENTS) ? NAMED_AGENTS[name].prompt : null });
6805
6995
  }
6806
6996
  // Noise cancellation (noise gate) — UI toggle. Meeting chunks auto-engage
6807
6997
  // it pipeline-side; this is the explicit button next to mute.
@@ -6892,9 +7082,8 @@ async function main() {
6892
7082
  // was showing). speakIntoMeeting routes voice→output_audio +
6893
7083
  // caption→canvas (no audio), so no double-audio. The canvas page's
6894
7084
  // OWN Web Audio is NOT used for voice (it's suspended headless).
6895
- const frontendUrl = (process.env.OSBORN_FRONTEND_URL || 'https://www.voice-native.com').replace(/\/$/, '');
6896
7085
  const canvasUrl = /^https:\/\//.test(webhookBase)
6897
- ? `${frontendUrl}/meeting-canvas?agent=${encodeURIComponent(webhookBase)}`
7086
+ ? `${osbornFrontendUrl()}/meeting-canvas?agent=${encodeURIComponent(webhookBase)}`
6898
7087
  : undefined;
6899
7088
  const castUrl = data.castUrl || process.env.OSBORN_MEETING_CAST_URL || canvasUrl;
6900
7089
  const botId = await recallJoin.joinMeeting(meetingUrl, webhookBase, { castUrl });
@@ -6903,15 +7092,12 @@ async function main() {
6903
7092
  activeMeetingBotId = botId;
6904
7093
  await sendToFrontend({ type: 'meeting_joined', botId, message: 'Osborn has joined the meeting' });
6905
7094
  // Phase B — point the addressable roster at the REAL effective
6906
- // agent set (built-ins minus user-removed, plus per-user agents),
6907
- // same effective set get_agents/set_agents compute, with the
7095
+ // agent set (core agents plus per-user agents),
7096
+ // same effective set set_agents computes, with the
6908
7097
  // orchestrator ('osborn') first. Flag-gated: a no-op (no roster
6909
7098
  // change, no emit) when OSBORN_MEETING_ADDRESSING is unset.
6910
7099
  if (meetingAddressing.enabled) {
6911
- const base = { ...NAMED_AGENTS };
6912
- for (const r of userRemovedAgents)
6913
- delete base[r];
6914
- const effective = { ...base, ...(userNamedAgents || {}) };
7100
+ const effective = mergeAgents(NAMED_AGENTS, userNamedAgents);
6915
7101
  meetingAddressing.setRoster(['osborn', ...Object.keys(effective)]);
6916
7102
  console.log(`🎛️ [meeting-addr] roster → [${meetingAddressing.rosterIds.join(', ')}]`);
6917
7103
  emitMeetingState();