osborn 0.9.279 → 0.9.281

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 (40) hide show
  1. package/dist/agent-store.d.ts +162 -0
  2. package/dist/agent-store.js +300 -0
  3. package/dist/claude-llm.d.ts +13 -8
  4. package/dist/claude-llm.js +89 -73
  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 +6 -3
  16. package/dist/index.js +241 -158
  17. package/dist/meeting-addressing.d.ts +1 -1
  18. package/dist/meeting-addressing.js +1 -0
  19. package/dist/pipeline-direct-llm.d.ts +1 -1
  20. package/dist/pipeline-direct-llm.js +1 -1
  21. package/dist/prompts/chain-after-planner.md +1 -0
  22. package/dist/prompts/chain-after-researcher.md +1 -0
  23. package/dist/prompts/chain-after-writer.md +1 -0
  24. package/dist/prompts/direct-mode-research.md +5 -4
  25. package/dist/prompts/steward.md +131 -0
  26. package/dist/prompts.d.ts +6 -0
  27. package/dist/prompts.js +20 -3
  28. package/dist/pushover.d.ts +2 -0
  29. package/dist/pushover.js +4 -2
  30. package/dist/steward-gate.d.ts +18 -0
  31. package/dist/steward-gate.js +299 -0
  32. package/dist/steward-verdict.d.ts +23 -0
  33. package/dist/steward-verdict.js +97 -0
  34. package/dist/stopwords.d.ts +1 -0
  35. package/dist/stopwords.js +6 -0
  36. package/dist/store-catalog.d.ts +101 -0
  37. package/dist/store-catalog.js +336 -0
  38. package/dist/store-name.d.ts +1 -0
  39. package/dist/store-name.js +3 -0
  40. 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, 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 } 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,35 @@ 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
+ // Routes that change the machine's skills (guarded by storeWriteRefused).
135
+ const STORE_WRITE_PATHS = new Set(['/skills/fork', '/skills/remove', '/store/install']);
136
+ // Skills shipped with the package (core: maintained by Voice Native).
137
+ const PKG_SKILLS_DIR = join(__dirname, '..', '.claude', 'skills');
138
+ const homeSkillsDir = () => join(homedir(), '.claude', 'skills');
125
139
  function loadSkillsList(agentDir) {
126
140
  const skillsDir = join(agentDir, '.claude', 'skills');
127
141
  if (!existsSync(skillsDir))
128
142
  return [];
143
+ const core = coreSkillNames(PKG_SKILLS_DIR);
129
144
  const skills = [];
130
145
  try {
131
146
  for (const skillName of readdirSync(skillsDir)) {
132
147
  const skillFile = join(skillsDir, skillName, 'SKILL.md');
133
148
  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);
149
+ const { meta, body } = parseFrontMatter(readFileSync(skillFile, 'utf-8'));
150
+ // Display name: the first # heading (else the folder); description: front matter, else the paragraph after the heading
151
+ const titleMatch = body.match(/^#\s+(?:Skill:\s*)?(.+)/m);
137
152
  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 });
153
+ const descMatch = body.match(/^#[^\n]+\n+([^\n#]+)/m);
154
+ const description = typeof meta.description === 'string' && meta.description ? meta.description : descMatch ? descMatch[1].trim() : '';
155
+ const forkedFrom = skillForkedFrom(skillsDir, skillName);
156
+ const installedFrom = skillProvenance(skillsDir, skillName);
157
+ skills.push({ name, description, folder: skillName, core: core.has(skillName), ...(forkedFrom ? { forkedFrom } : {}), ...(installedFrom ? { installedFrom } : {}) });
142
158
  }
143
159
  }
144
160
  }
@@ -147,6 +163,21 @@ function loadSkillsList(agentDir) {
147
163
  }
148
164
  return skills;
149
165
  }
166
+ /** Adds, forks or removes a user skill (agent-store.ts rules). The one entry point for the
167
+ * chat's skill_* data messages (the connected agent) and Settings' /skills/* routes (no room). */
168
+ function changeSkill(op, name, arg) {
169
+ let out;
170
+ try {
171
+ out = op === 'add' ? addUserSkill(homeSkillsDir(), PKG_SKILLS_DIR, name, arg)
172
+ : op === 'fork' ? forkSkill(homeSkillsDir(), PKG_SKILLS_DIR, name, arg)
173
+ : removeUserSkill(homeSkillsDir(), PKG_SKILLS_DIR, name);
174
+ }
175
+ catch (err) {
176
+ out = { error: err instanceof Error ? err.message : String(err) };
177
+ }
178
+ console.log(`📚 skill ${op} ${storeName(name)}: ${'ok' in out ? 'ok' : out.error}`);
179
+ return out;
180
+ }
150
181
  // Generate a short, user-friendly room code
151
182
  function generateRoomCode() {
152
183
  const chars = 'abcdefghjkmnpqrstuvwxyz23456789';
@@ -353,7 +384,7 @@ function parseDevSubdomainPort(req) {
353
384
  // Route prefixes that belong to the agent itself. The proxy fall-through checks
354
385
  // this list FIRST so it never intercepts an agent API path.
355
386
  const AGENT_ROUTE_PREFIXES = [
356
- '/health', '/sessions', '/skills', '/agents', '/canvas', '/canvas-token',
387
+ '/health', '/sessions', '/skills', '/agents', '/store', '/canvas', '/canvas-token',
357
388
  '/canvas-stream', '/events', '/room-code', '/connect-room', '/leave-room',
358
389
  '/report-bug', '/restart', '/tts', '/noise-cancel', '/webhook', '/sessions/export',
359
390
  '/sessions/import', '/sessions/manifest',
@@ -574,6 +605,17 @@ function startApiServer(workingDir, port) {
574
605
  // Authorization is required for /secrets (Bearer OSBORN_SYNC_TOKEN); without it in the
575
606
  // allow-list the browser preflight fails and the dashboard can't read/manage keys.
576
607
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
608
+ // Store writes never answer every site: only an allowed origin (agent-store.ts) is echoed,
609
+ // so another site's page can neither pass the preflight nor read the reply.
610
+ if (STORE_WRITE_PATHS.has((req.url || '/').split('?')[0])) {
611
+ const origin = req.headers.origin;
612
+ if (origin && storeWriteOriginAllowed(origin, osbornFrontendUrl())) {
613
+ res.setHeader('Access-Control-Allow-Origin', origin);
614
+ res.setHeader('Vary', 'Origin');
615
+ }
616
+ else
617
+ res.removeHeader('Access-Control-Allow-Origin');
618
+ }
577
619
  if (req.method === 'OPTIONS') {
578
620
  res.writeHead(204);
579
621
  res.end();
@@ -662,10 +704,11 @@ function startApiServer(workingDir, port) {
662
704
  // pass their own cwd; honoured only if the session really lives there.
663
705
  const readDir = sessionMessagesDir(sessionId, url.searchParams.get('workingDirectory'), workingDir, sessionExists);
664
706
  const compactions = readCompactionMarkers(sessionId, readDir);
707
+ const steward = readStewardVerdicts(sessionId, readDir);
665
708
  const dbPath = storeExists(sessionId, readDir);
666
709
  if (!dbPath) {
667
710
  res.writeHead(200, { 'Content-Type': 'application/json' });
668
- res.end(JSON.stringify({ sessionId, messages: [], compactions }));
711
+ res.end(JSON.stringify({ sessionId, messages: [], compactions, steward }));
669
712
  return;
670
713
  }
671
714
  const db = openStore(dbPath, { readonly: true });
@@ -674,7 +717,7 @@ function startApiServer(workingDir, port) {
674
717
  // (notices, injected blocks) don't shrink the page (L2b).
675
718
  const messages = cleanHistoryRows(n => recentRows(db, n, ['user', 'assistant']), limit, 1200);
676
719
  res.writeHead(200, { 'Content-Type': 'application/json' });
677
- res.end(JSON.stringify({ sessionId, messages, compactions }));
720
+ res.end(JSON.stringify({ sessionId, messages, compactions, steward }));
678
721
  }
679
722
  finally {
680
723
  try {
@@ -713,20 +756,98 @@ function startApiServer(workingDir, port) {
713
756
  res.end(JSON.stringify({ skills: loadSkillsList(homedir()) }));
714
757
  return;
715
758
  }
759
+ // Agent & skill store routes: the chat and Settings both use them (through the
760
+ // authenticated /api/agent proxy in the cloud). JSON in and out.
761
+ const reply = (status, body) => { res.writeHead(status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(body)); };
762
+ // Store writes change the machine. Called past the token gate (unauthorized()); the
763
+ // rules for a machine with no sync token are agent-store.ts storeWriteRefusal.
764
+ const storeWriteRefused = () => {
765
+ const refusal = storeWriteRefusal({
766
+ hasToken: !!syncToken,
767
+ publicDeploy: !!process.env.FLY_APP_NAME || !!process.env.OSBORN_PUBLIC_HOST,
768
+ forwarded: !!(req.headers['x-forwarded-for'] || req.headers['x-forwarded-host']),
769
+ host: req.headers.host, remote: req.socket.remoteAddress, origin: req.headers.origin,
770
+ contentType: String(req.headers['content-type'] || ''), frontendUrl: osbornFrontendUrl(),
771
+ });
772
+ if (refusal)
773
+ reply(refusal.status, { error: refusal.error });
774
+ return !!refusal;
775
+ };
776
+ if (url.pathname === '/skills/content' || (url.pathname.startsWith('/skills/') && STORE_WRITE_PATHS.has(url.pathname))) {
777
+ if (unauthorized())
778
+ return;
779
+ const name = url.searchParams.get('name');
780
+ if (req.method === 'GET' && url.pathname === '/skills/content') {
781
+ const out = readUserSkill(homeSkillsDir(), name);
782
+ return reply('error' in out ? 404 : 200, out);
783
+ }
784
+ if (req.method !== 'POST' || url.pathname === '/skills/content')
785
+ return reply(405, { error: 'method not allowed' });
786
+ if (storeWriteRefused())
787
+ return;
788
+ const out = changeSkill(url.pathname === '/skills/fork' ? 'fork' : 'remove', name, url.searchParams.get('to'));
789
+ return reply('ok' in out ? 200 : 400, { ...out, skills: loadSkillsList(homedir()) });
790
+ }
791
+ if (url.pathname.startsWith('/store/')) {
792
+ // Catalog browse/install for the store (same gate as /skills/*). GitHub is
793
+ // read here, never by the browser; installs only take entries from the
794
+ // agent's own cached catalog, by id.
795
+ if (unauthorized())
796
+ return;
797
+ try {
798
+ if (req.method === 'GET' && url.pathname === '/store/catalog') {
799
+ const src = url.searchParams.get('source');
800
+ const caches = await loadCatalog(src && src !== 'all' ? src.split(',') : null, { refresh: url.searchParams.get('refresh') === '1' });
801
+ const entries = caches.flatMap((c) => c.entries);
802
+ const skills = loadSkillsList(homedir());
803
+ const myAgents = (url.searchParams.get('agents') || '').split(',').map(storeName).filter(Boolean).slice(0, 50);
804
+ const installed = installedIds(entries, new Set(skills.map((s) => s.folder)), url.searchParams.getAll('origin').slice(0, 50));
805
+ const signals = [
806
+ ...skills.map((s) => ({ text: `${s.folder} ${s.name} ${s.description}`, reason: `because you use the ${s.folder} skill` })),
807
+ ...myAgents.map((n) => ({ text: n, reason: `because you have the ${n} agent` })),
808
+ ...(await listAllClaudeSessions(40)).filter((s) => s.title).map((s) => ({ text: s.title, reason: 'related to your recent sessions' })),
809
+ ];
810
+ return reply(200, {
811
+ sources: caches.map((c) => {
812
+ const s = SOURCES.find((x) => x.id === c.source);
813
+ 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 } : {}) };
814
+ }),
815
+ entries,
816
+ installed: [...installed],
817
+ recommended: recommend(entries, signals, installed),
818
+ });
819
+ }
820
+ if (req.method === 'GET' && url.pathname === '/store/entry') {
821
+ const found = await findEntry(url.searchParams.get('id') || '');
822
+ if (!found)
823
+ return reply(404, { error: 'not in the catalog' });
824
+ // An agent's detail carries the draft it would install as (its starting role included).
825
+ return reply(200, { entry: found.entry, content: found.body, ...(found.entry.kind === 'agent' ? { draft: agentDraft(found.entry, found.body) } : {}) });
826
+ }
827
+ if (req.method === 'POST' && url.pathname === '/store/install') {
828
+ if (storeWriteRefused())
829
+ return;
830
+ const found = await findEntry(url.searchParams.get('id') || '');
831
+ if (!found)
832
+ return reply(404, { error: 'not in the catalog' });
833
+ if (found.entry.kind === 'agent')
834
+ return reply(200, { draft: agentDraft(found.entry, found.body) });
835
+ const out = await installSkill(found.entry, homeSkillsDir(), coreSkillNames(PKG_SKILLS_DIR));
836
+ return reply('ok' in out ? 200 : 400, { ...out, skills: loadSkillsList(homedir()) });
837
+ }
838
+ return reply(404, { error: 'not found' });
839
+ }
840
+ catch (e) {
841
+ return reply(502, { error: e instanceof Error ? e.message : 'store request failed' });
842
+ }
843
+ }
716
844
  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;
845
+ // Core sub-agents from claude-llm.ts NAMED_AGENTS (the same object the SDK
846
+ // query uses), with prompts so the store can show and fork them — so gated
847
+ // like the other store routes (the chat and Settings go through /api/agent).
848
+ if (unauthorized())
849
+ return;
850
+ return reply(200, { agents: describeAgents(NAMED_AGENTS, null, {}, true), ...describeRoles() });
730
851
  }
731
852
  if (req.method === 'GET' && url.pathname === '/health') {
732
853
  // Include osborn version — primary signal used by machines.readInstalledOsbornVersion()
@@ -767,6 +888,13 @@ function startApiServer(workingDir, port) {
767
888
  status: 'ok',
768
889
  workingDir,
769
890
  version,
891
+ // Library: is it on, can it call the model, does it reach /library (no values, 8-char session id).
892
+ library: {
893
+ enabled: isContentLensEnabled(),
894
+ modelKey: !!(process.env.OPENROUTER_API_KEY || '').trim(),
895
+ ingest: (() => { const c = resolveIngestConfig(); return 'reason' in c ? (c.reason === 'no-key' ? 'no-anon-key' : c.reason) : 'on'; })(),
896
+ lastRun: lastLibraryRun(),
897
+ },
770
898
  // WHERE this machine physically runs — Fly sets FLY_REGION (e.g. 'ord').
771
899
  // The dashboard maps it to a city ("Chicago") so the user always knows
772
900
  // the machine's location, not just their own clock. Null in local dev.
@@ -1915,6 +2043,14 @@ function startApiServer(workingDir, port) {
1915
2043
  });
1916
2044
  const host = process.env.HOST || '0.0.0.0';
1917
2045
  server.requestTimeout = 0; // no timeout — large uploads can take minutes
2046
+ {
2047
+ const c = resolveIngestConfig();
2048
+ const why = 'reason' in c ? c.reason : null;
2049
+ if (!(process.env.OPENROUTER_API_KEY || '').trim())
2050
+ console.warn('⚠️ library: OPENROUTER_API_KEY is not set: no Library pages will be written');
2051
+ else if (why && why !== 'disabled')
2052
+ console.warn(`⚠️ library: pages stay on this machine, nothing reaches /library (${why})`);
2053
+ }
1918
2054
  server.listen(port, host, () => {
1919
2055
  console.log(`🌐 API server listening on http://${host}:${port}`);
1920
2056
  console.log(` Sessions: http://${host}:${port}/sessions`);
@@ -2424,7 +2560,7 @@ async function main() {
2424
2560
  'session_id', 'mcp_servers_changed', 'tool_use', 'tool_result',
2425
2561
  'assistant_text', 'assistant_result', 'tts_chunks', 'permission_request',
2426
2562
  'tts_say', 'session_resume_failed', 'checkpoint_captured',
2427
- 'dispatch_rejected', 'task_completed', 'agent_started',
2563
+ 'dispatch_rejected', 'task_completed', 'agent_started', 'steward_verdict', 'steward_gate',
2428
2564
  ];
2429
2565
  // Abort + clear the parked brain. Clears BOTH timers so grace/watchdog can't
2430
2566
  // double-fire. Used on grace expiry, watchdog, and session mismatch.
@@ -2448,6 +2584,9 @@ async function main() {
2448
2584
  catch (err) {
2449
2585
  console.error(`❌ killWarm(${reason}) abort failed:`, err instanceof Error ? err.message : err);
2450
2586
  }
2587
+ finally {
2588
+ launchLibraryOnSessionEnd(warmSessionId, warmLLM?.workingDirectory || workingDir, `warm_${reason}`);
2589
+ }
2451
2590
  }
2452
2591
  if (warmLLM)
2453
2592
  console.log(`🧊 [KEEP-WARM] freed warm slot (${reason})`);
@@ -2654,6 +2793,9 @@ async function main() {
2654
2793
  catch (err) {
2655
2794
  console.error(`❌ killCurrentLLM(${reason}) failed:`, err instanceof Error ? err.message : err);
2656
2795
  }
2796
+ finally {
2797
+ launchLibraryOnSessionEnd(currentLLM?.sessionId, currentLLM?.workingDirectory || workingDir, reason);
2798
+ }
2657
2799
  }
2658
2800
  // ============================================================
2659
2801
  // SLICE 1: spawnBackgroundSession
@@ -2803,17 +2945,23 @@ async function main() {
2803
2945
  let currentUserId = '';
2804
2946
  // Per-user named agents (DB-backed) — sent by the frontend via set_agents
2805
2947
  // 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).
2948
+ // switch/resume) reuse them without waiting for a frontend resend. Added
2949
+ // beside the core NAMED_AGENTS, which they can never override or remove.
2808
2950
  let userNamedAgents = null;
2951
+ let userAgentRoles = {};
2952
+ let userAgentOrigins = {};
2953
+ const loggedDroppedAgents = new Set();
2809
2954
  // Turbo mode — read from set_agents handshake (data.turbo). When true every
2810
2955
  // agent (main + sub-agents) runs on FAST_MODEL. Default false = perfect no-op.
2811
2956
  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 = [];
2957
+ // The per-user agents for the voice session's LLMs (direct, pipeline and recovery),
2958
+ // so a session switch or rebuild keeps them (headless background slots run the built-ins). applyTurbo runs after the
2959
+ // merge so custom models are overridden too. With no custom agents, undefined lets
2960
+ // ClaudeLLM use NAMED_AGENTS directly (turbo then applies inside ClaudeLLMStream).
2961
+ const userAgentOptions = () => ({
2962
+ agents: userNamedAgents ? applyTurbo(mergeAgents(NAMED_AGENTS, userNamedAgents), turboMode) : undefined,
2963
+ agentRoles: userAgentRoles,
2964
+ });
2817
2965
  let activeMeetingBotId = null; // Recall.ai bot ID if in a meeting
2818
2966
  // While set (Date.now() < value), the agent's streaming tts_say output is
2819
2967
  // REDIRECTED into the meeting canvas instead of suppressed — the regular
@@ -3940,6 +4088,7 @@ async function main() {
3940
4088
  statusManager.upsertDispatch(d.id, { dispatchState: 'failed' });
3941
4089
  }
3942
4090
  // 4. Close the old query (idle, or forced) and clear its resume state.
4091
+ launchLibraryOnSessionEnd(llmAny.sessionId, llmAny.workingDirectory || workingDir, 'session_switch');
3943
4092
  currentLLM.resetForSessionSwitch();
3944
4093
  // 5. Cross-project: the SDK cwd, fast brain and session tail move together.
3945
4094
  if (cwd !== workingDir) {
@@ -4062,10 +4211,12 @@ async function main() {
4062
4211
  }
4063
4212
  catch { }
4064
4213
  });
4065
- async function sendToFrontend(data) {
4214
+ /** Publishes to the frontend (to one participant when `to` is given). Resolves false
4215
+ * when nothing was sent (no room, over the hard size cap, or a publish error). */
4216
+ async function sendToFrontend(data, to) {
4066
4217
  if (!localParticipant) {
4067
4218
  console.log('⚠️ sendToFrontend: no localParticipant!');
4068
- return;
4219
+ return false;
4069
4220
  }
4070
4221
  try {
4071
4222
  const encoder = new TextEncoder();
@@ -4098,16 +4249,19 @@ async function main() {
4098
4249
  const payload = encoder.encode(jsonData);
4099
4250
  if (payload.length > HARD_MAX_MESSAGE_SIZE) {
4100
4251
  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;
4252
+ return false;
4102
4253
  }
4103
4254
  await localParticipant.publishData(payload, {
4104
4255
  reliable: true,
4105
4256
  topic: 'osborn-updates',
4257
+ ...(to ? { destinationIdentities: [to] } : {}),
4106
4258
  });
4107
4259
  console.log(`📤 Sent to frontend: ${data.type} (${payload.length} bytes)`);
4260
+ return true;
4108
4261
  }
4109
4262
  catch (err) {
4110
4263
  console.error('❌ sendToFrontend error:', err);
4264
+ return false;
4111
4265
  }
4112
4266
  }
4113
4267
  // ── Phase B — meeting addressing/mute state → frontend (over the EXISTING
@@ -4216,18 +4370,7 @@ async function main() {
4216
4370
  voiceMode: 'direct',
4217
4371
  skipTTSQueue: true,
4218
4372
  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,
4373
+ ...userAgentOptions(),
4231
4374
  });
4232
4375
  // Apply turbo to the freshly created LLM so the main model also picks it up.
4233
4376
  // PipelineDirectLLM (llmOverride path) wraps its own ClaudeLLM and may not expose setTurbo.
@@ -4688,6 +4831,9 @@ async function main() {
4688
4831
  agent_id: d.agent_id,
4689
4832
  last_assistant_message: d.last_assistant_message,
4690
4833
  }));
4834
+ // Steward verdict card + sign-off gate note (#221) → chat
4835
+ directLLM.events.on('steward_verdict', (v) => sendToFrontend({ type: 'steward_verdict', ...v }));
4836
+ directLLM.events.on('steward_gate', (d) => sendToFrontend({ type: 'steward_gate', decision: d.decision, message: d.message }));
4691
4837
  // Dispatcher v1 — sub-agent started → frontend stop-key signal (Feature A2)
4692
4838
  directLLM.events.on('agent_started', (d) => sendToFrontend({
4693
4839
  type: 'agent_started',
@@ -5242,6 +5388,7 @@ async function main() {
5242
5388
  resumeSessionId,
5243
5389
  voiceMode: 'direct',
5244
5390
  skipTTSQueue: true,
5391
+ ...userAgentOptions(),
5245
5392
  // PipelineDirectOptions extends ClaudeLLMOptions; passing this through
5246
5393
  // forwards it into the inner `new ClaudeLLM(opts)`. Without this,
5247
5394
  // pipeline mode silently drops every PreCompact/PostCompact event
@@ -5748,6 +5895,7 @@ async function main() {
5748
5895
  resumeSessionId: recoverySessionId,
5749
5896
  voiceMode: 'direct',
5750
5897
  skipTTSQueue: true,
5898
+ ...userAgentOptions(),
5751
5899
  getChatHistory: () => getChatHistory(20).map(t => ({ role: t.role, content: t.text })),
5752
5900
  getResearchContext: () => {
5753
5901
  if (activeResearch?.researchLog.length) {
@@ -5876,9 +6024,8 @@ async function main() {
5876
6024
  enabledMcpServers: enabledMcpNames,
5877
6025
  workingDirectory: workingDir,
5878
6026
  skills: loadSkillsList(homedir()),
5879
- namedAgents: Object.entries(NAMED_AGENTS).map(([name, a]) => ({
5880
- name, description: a.description, model: a.model, tools: a.tools,
5881
- })),
6027
+ namedAgents: describeAgents(NAMED_AGENTS, userNamedAgents, userAgentRoles, false, userAgentOrigins),
6028
+ ...describeRoles(),
5882
6029
  });
5883
6030
  };
5884
6031
  const readyInterval = setInterval(sendReady, 2000);
@@ -5962,8 +6109,10 @@ async function main() {
5962
6109
  // Durable compaction markers ride the same push so the resumed
5963
6110
  // transcript rebuilds its "Conversation compacted" rows too.
5964
6111
  const compactions = readCompactionMarkers(preSelectedSessionId, workingDir);
6112
+ // Last few cards, without the full return text, so the push stays under the packet limit.
6113
+ const steward = readStewardVerdicts(preSelectedSessionId, workingDir).slice(-10).map(({ raw, ...v }) => v);
5965
6114
  if (priorMessages.length > 0) {
5966
- await sendToFrontend({ type: 'prior_messages', sessionId: preSelectedSessionId, messages: priorMessages, compactions });
6115
+ await sendToFrontend({ type: 'prior_messages', sessionId: preSelectedSessionId, messages: priorMessages, compactions, steward });
5967
6116
  console.log(`💬 Sent ${priorMessages.length} prior messages (+${compactions.length} compaction markers) from DB for optimistic UI`);
5968
6117
  }
5969
6118
  }
@@ -6145,6 +6294,10 @@ async function main() {
6145
6294
  const senderCheck = checkControlSender(String(data.type), participant?.identity, controllingUserIdentity);
6146
6295
  if (!senderCheck.ok) {
6147
6296
  console.warn(`🚫 Dropped ${data.type}: ${senderCheck.reason}`);
6297
+ // A store request waits for its reply (the chat's askAgent): answer the sender now.
6298
+ if (Object.hasOwn(STORE_REPLY_TYPES, data.type) && participant?.identity) {
6299
+ await sendToFrontend({ type: STORE_REPLY_TYPES[data.type], success: false, error: 'Another device controls this session' }, participant.identity);
6300
+ }
6148
6301
  return;
6149
6302
  }
6150
6303
  if (data.type === 'claude_auth_code' && pendingAuthSubmitCode) {
@@ -6692,116 +6845,50 @@ async function main() {
6692
6845
  skills: loadSkillsList(homedir()),
6693
6846
  });
6694
6847
  }
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
6848
  else if (data.type === 'set_agents') {
6711
6849
  // Per-user named agents from the DB (frontend fetches its user_agents
6712
6850
  // rows and sends them here after agent_ready, and again after edits).
6713
- // Validated + merged over built-ins, applied via setAgents(). SDK
6851
+ // Added beside the core agents, applied via setAgents(). SDK
6714
6852
  // constraint: takes effect at the next query cold start — a live
6715
6853
  // 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)
6724
- continue;
6725
- if (prompt.length > 6000) {
6726
- console.warn(`🤖 set_agents: '${name}' prompt >6KB — skipped`);
6854
+ const parsed = parseUserAgents(data.agents, NAMED_AGENTS);
6855
+ for (const d of parsed.dropped) {
6856
+ const key = `${d.name}: ${d.reason}`;
6857
+ if (loggedDroppedAgents.has(key))
6727
6858
  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
- };
6859
+ loggedDroppedAgents.add(key);
6860
+ console.warn(`🤖 set_agents: '${d.name}' dropped — ${d.reason}`);
6735
6861
  }
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) : [];
6862
+ userNamedAgents = Object.keys(parsed.agents).length ? parsed.agents : null;
6863
+ userAgentRoles = parsed.roles;
6864
+ userAgentOrigins = parsed.origins;
6739
6865
  // Turbo preference from the frontend (sourced from user_settings DB row).
6740
6866
  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;
6867
+ // applyTurbo wraps AFTER the merge so custom models also get overridden.
6868
+ const merged = applyTurbo(mergeAgents(NAMED_AGENTS, userNamedAgents), turboMode);
6747
6869
  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
- }
6870
+ currentLLM?.setAgents?.(userNamedAgents || turboMode ? merged : undefined, userAgentRoles);
6871
+ console.log(`🤖 set_agents: ${Object.keys(parsed.agents).length} user agent(s) → effective [${Object.keys(merged).join(', ')}]`);
6872
+ await sendToFrontend({ type: 'agents_status', agents: describeAgents(NAMED_AGENTS, userNamedAgents, userAgentRoles, false, userAgentOrigins), ...describeRoles() });
6778
6873
  }
6874
+ // The chat's skill actions go to the agent it is connected to (LAN, tunnel or cloud);
6875
+ // Settings, which has no room, uses the /skills/* routes. Both call changeSkill.
6779
6876
  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
- }
6877
+ const out = readUserSkill(homeSkillsDir(), data.name);
6878
+ await sendToFrontend({ type: STORE_REPLY_TYPES.skill_get, ...('error' in out ? { name: storeName(data.name), error: out.error } : out) });
6879
+ }
6880
+ else if (data.type === 'skill_add' || data.type === 'skill_fork' || data.type === 'skill_remove') {
6881
+ const op = data.type === 'skill_add' ? 'add' : data.type === 'skill_fork' ? 'fork' : 'remove';
6882
+ const out = changeSkill(op, data.name, op === 'add' ? data.content : data.to);
6883
+ const result = { type: STORE_REPLY_TYPES[data.type], success: 'ok' in out, ...('error' in out ? { error: out.error } : {}) };
6884
+ // A skill list over the data-channel cap is dropped: the result still goes out without it.
6885
+ if (!await sendToFrontend({ ...result, skills: loadSkillsList(homedir()) }))
6886
+ await sendToFrontend(result);
6887
+ }
6888
+ else if (data.type === 'get_agent_prompt') {
6889
+ // A built-in agent's prompt for View / Fork in the chat (the listing never carries prompts).
6890
+ const name = String(data.name || '');
6891
+ await sendToFrontend({ type: STORE_REPLY_TYPES.get_agent_prompt, name, prompt: coreRole(name, NAMED_AGENTS) ? NAMED_AGENTS[name].prompt : null });
6805
6892
  }
6806
6893
  // Noise cancellation (noise gate) — UI toggle. Meeting chunks auto-engage
6807
6894
  // it pipeline-side; this is the explicit button next to mute.
@@ -6892,9 +6979,8 @@ async function main() {
6892
6979
  // was showing). speakIntoMeeting routes voice→output_audio +
6893
6980
  // caption→canvas (no audio), so no double-audio. The canvas page's
6894
6981
  // 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
6982
  const canvasUrl = /^https:\/\//.test(webhookBase)
6897
- ? `${frontendUrl}/meeting-canvas?agent=${encodeURIComponent(webhookBase)}`
6983
+ ? `${osbornFrontendUrl()}/meeting-canvas?agent=${encodeURIComponent(webhookBase)}`
6898
6984
  : undefined;
6899
6985
  const castUrl = data.castUrl || process.env.OSBORN_MEETING_CAST_URL || canvasUrl;
6900
6986
  const botId = await recallJoin.joinMeeting(meetingUrl, webhookBase, { castUrl });
@@ -6903,15 +6989,12 @@ async function main() {
6903
6989
  activeMeetingBotId = botId;
6904
6990
  await sendToFrontend({ type: 'meeting_joined', botId, message: 'Osborn has joined the meeting' });
6905
6991
  // 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
6992
+ // agent set (core agents plus per-user agents),
6993
+ // same effective set set_agents computes, with the
6908
6994
  // orchestrator ('osborn') first. Flag-gated: a no-op (no roster
6909
6995
  // change, no emit) when OSBORN_MEETING_ADDRESSING is unset.
6910
6996
  if (meetingAddressing.enabled) {
6911
- const base = { ...NAMED_AGENTS };
6912
- for (const r of userRemovedAgents)
6913
- delete base[r];
6914
- const effective = { ...base, ...(userNamedAgents || {}) };
6997
+ const effective = mergeAgents(NAMED_AGENTS, userNamedAgents);
6915
6998
  meetingAddressing.setRoster(['osborn', ...Object.keys(effective)]);
6916
6999
  console.log(`🎛️ [meeting-addr] roster → [${meetingAddressing.rosterIds.join(', ')}]`);
6917
7000
  emitMeetingState();