osborn 0.9.281 → 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.
@@ -117,9 +117,10 @@ export declare function describeAgents(core: CoreAgents, user: Record<string, Ag
117
117
  * page, voice-native.com, or the frontend the agent is configured with. No Origin = not a
118
118
  * browser cross-site request. Also decides which origin the write routes' CORS echoes. */
119
119
  export declare function storeWriteOriginAllowed(origin: string | undefined, frontendUrl: string): boolean;
120
- /** Refusal for a store write, or null. With a token, unauthorized() has already checked it;
121
- * without one, only this machine's own pages may write, never a public or tunnelled
122
- * address, and every write must be JSON (no other site's form or text/plain POST). */
120
+ /** Refusal for a store request, or null. With a token, unauthorized() has already checked it;
121
+ * without one, only this machine's own pages may use the store (reads carry the core prompts
122
+ * and the user's skills), never a public or tunnelled address, and every write must be JSON
123
+ * (no other site's form or text/plain POST). */
123
124
  export declare function storeWriteRefusal(r: {
124
125
  hasToken: boolean;
125
126
  publicDeploy: boolean;
@@ -129,6 +130,7 @@ export declare function storeWriteRefusal(r: {
129
130
  origin?: string;
130
131
  contentType?: string;
131
132
  frontendUrl: string;
133
+ read?: boolean;
132
134
  }): {
133
135
  status: number;
134
136
  error: string;
@@ -71,7 +71,7 @@ function roleBehaviours(role, isCore) {
71
71
  return out;
72
72
  }
73
73
  // ── Definitions shared with the frontend and the user_agents SQL checks ───────
74
- // (migrations 004/015/016/017; agent/tests/user-agents-migrations.test.ts keeps them equal)
74
+ // (migrations 004/015/016/018; agent/tests/user-agents-migrations.test.ts keeps them equal)
75
75
  export const AGENT_MODELS = ['inherit', 'sonnet', 'opus', 'haiku', 'fable'];
76
76
  export const isAgentModel = (m) => typeof m === 'string' && (AGENT_MODELS.includes(m) || /^claude-/.test(m));
77
77
  export const AGENT_LIMITS = { name: 40, description: 500, prompt: 20000 };
@@ -126,7 +126,8 @@ export function parseUserAgents(rows, core) {
126
126
  // Only a built-in parent matters to the role and grounding; a catalog origin names none.
127
127
  const from = storeName(rawFrom);
128
128
  roles[name] = resolveRole({ role: r.role, forkedFrom: from }, core);
129
- const tools = Array.isArray(r.tools) && r.tools.length ? r.tools.map(String) : undefined;
129
+ const listed = Array.isArray(r.tools) ? r.tools.map((t) => String(t).trim()).filter(Boolean) : []; // ' Edit ' is Edit
130
+ const tools = listed.length ? listed : undefined;
130
131
  agents[name] = {
131
132
  description,
132
133
  prompt,
@@ -182,19 +183,20 @@ export function storeWriteOriginAllowed(origin, frontendUrl) {
182
183
  catch { /* none configured */ }
183
184
  return LOOPBACK_HOST.test(u.host) || /^https:\/\/(www\.)?voice-native\.com$/.test(u.origin) || u.origin === configured;
184
185
  }
185
- /** Refusal for a store write, or null. With a token, unauthorized() has already checked it;
186
- * without one, only this machine's own pages may write, never a public or tunnelled
187
- * address, and every write must be JSON (no other site's form or text/plain POST). */
186
+ /** Refusal for a store request, or null. With a token, unauthorized() has already checked it;
187
+ * without one, only this machine's own pages may use the store (reads carry the core prompts
188
+ * and the user's skills), never a public or tunnelled address, and every write must be JSON
189
+ * (no other site's form or text/plain POST). */
188
190
  export function storeWriteRefusal(r) {
189
191
  if (!r.hasToken) {
190
192
  if (r.publicDeploy || r.forwarded || !LOOPBACK_HOST.test(r.host || ''))
191
- return { status: 403, error: 'this machine is reachable from outside: set OSBORN_SYNC_TOKEN to change skills' };
193
+ return { status: 403, error: 'this machine is reachable from outside: set OSBORN_SYNC_TOKEN to use the store' };
192
194
  if (!LOOPBACK_ADDR.test(r.remote || ''))
193
- return { status: 403, error: 'store changes need the sync token or a request from this machine' };
195
+ return { status: 403, error: 'the store needs the sync token or a request from this machine' };
194
196
  if (!storeWriteOriginAllowed(r.origin, r.frontendUrl))
195
- return { status: 403, error: 'store changes are refused from this site' };
197
+ return { status: 403, error: 'the store is refused from this site' };
196
198
  }
197
- if (!/^application\/json\b/i.test(r.contentType || ''))
199
+ if (!r.read && !/^application\/json\b/i.test(r.contentType || ''))
198
200
  return { status: 415, error: 'send JSON (Content-Type: application/json)' };
199
201
  return null;
200
202
  }
@@ -1017,19 +1017,19 @@ export function decideWrite(role, filePath) {
1017
1017
  const rule = role ? ROLES[role].write : 'workspace';
1018
1018
  if (rule === 'anywhere')
1019
1019
  return { decision: 'defer' };
1020
+ // Fail closed for every limited role: an edit with no path is denied.
1021
+ if (!filePath)
1022
+ return { decision: 'deny', reason: 'Write denied: could not determine target file path. Failing closed.' };
1020
1023
  if (rule === 'workspace') {
1021
- if (filePath && !isWorkspacePath(filePath)) {
1024
+ if (!isWorkspacePath(filePath)) {
1022
1025
  return { decision: 'deny', reason: 'Research mode: writes restricted to session workspace.' };
1023
1026
  }
1024
1027
  return { decision: 'allow' };
1025
1028
  }
1026
- // Extension whitelist — fail closed (empty/unknown path denied).
1027
- const target = rule.matchBasename ? (filePath ? basename(resolve(filePath)) : '') : filePath;
1028
- if (!filePath || !rule.extensions.test(target)) {
1029
- const reason = filePath
1030
- ? `Write denied: ${filePath} is not a ${rule.label} file. This agent may only write ${rule.label} files.`
1031
- : 'Write denied: could not determine target file path. Failing closed.';
1032
- return { decision: 'deny', reason };
1029
+ // Extension whitelist.
1030
+ const target = rule.matchBasename ? basename(resolve(filePath)) : filePath;
1031
+ if (!rule.extensions.test(target)) {
1032
+ return { decision: 'deny', reason: `Write denied: ${filePath} is not a ${rule.label} file. This agent may only write ${rule.label} files.` };
1033
1033
  }
1034
1034
  return { decision: 'defer' };
1035
1035
  }
@@ -2546,7 +2546,6 @@ class ClaudeLLMStream extends llm.LLMStream {
2546
2546
  if (gate.decision !== 'allow')
2547
2547
  this.#eventEmitter.emit('steward_gate', { decision: gate.decision, message: gate.message });
2548
2548
  if (gate.decision === 'deny') {
2549
- this.#eventEmitter.emit('tool_blocked', { name: toolName, reason: gate.message });
2550
2549
  return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny' }, reason: gate.message };
2551
2550
  }
2552
2551
  if (gate.decision === 'advise')
@@ -2574,13 +2573,13 @@ class ClaudeLLMStream extends llm.LLMStream {
2574
2573
  `Then re-attempt this edit. (One-time reminder this turn; new files are exempt.)`,
2575
2574
  ].join('\n');
2576
2575
  console.log(`🏛️ Writer provenance reminder: nudging before ${base} (first edit of an existing file this turn)`);
2577
- this.#eventEmitter.emit('tool_blocked', { name: toolName, reason: `Review ${base}'s git history first (one-time provenance reminder).` });
2576
+ this.#eventEmitter.emit('tool_blocked', { name: toolName, reason: `Review ${base}'s git history first (one-time provenance reminder).`, kind: 'reminder' });
2578
2577
  return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny' }, reason: gateReason };
2579
2578
  }
2580
2579
  const { decision, reason } = decideWrite(role, filePath);
2581
2580
  console.log(`🔎 Write gate: agent=${agentType ?? 'main'} role=${role ?? '-'} path="${filePath || '(none)'}" → ${decision}`);
2582
2581
  if (decision === 'deny') {
2583
- this.#eventEmitter.emit('tool_blocked', { name: toolName, reason });
2582
+ this.#eventEmitter.emit('tool_blocked', { name: toolName, reason, agent: agentType ?? 'main', role, path: filePath });
2584
2583
  return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny' }, reason };
2585
2584
  }
2586
2585
  if (decision === 'defer') {
@@ -23,7 +23,7 @@
23
23
  * favorite_changed
24
24
  * Open (read-only, listed in READ_ONLY_MESSAGE_TYPES):
25
25
  * get_current_session, get_session_artifacts, get_plan_file,
26
- * get_research_artifact, get_mcp_status, get_skills, skill_get
26
+ * get_research_artifact, get_mcp_status, get_skills, skill_get, get_busy
27
27
  * list_sessions / list_slots / list_processes are read-only but return session
28
28
  * and process ids that the gated commands (dispatch_background etc.) take as
29
29
  * targets, so they are gated too.
@@ -23,7 +23,7 @@
23
23
  * favorite_changed
24
24
  * Open (read-only, listed in READ_ONLY_MESSAGE_TYPES):
25
25
  * get_current_session, get_session_artifacts, get_plan_file,
26
- * get_research_artifact, get_mcp_status, get_skills, skill_get
26
+ * get_research_artifact, get_mcp_status, get_skills, skill_get, get_busy
27
27
  * list_sessions / list_slots / list_processes are read-only but return session
28
28
  * and process ids that the gated commands (dispatch_background etc.) take as
29
29
  * targets, so they are gated too.
@@ -49,6 +49,8 @@ export const CONTROL_MESSAGE_TYPES = new Set([
49
49
  'switch_session',
50
50
  // Cancels a deferred switch (#74) — state-changing, controller-only.
51
51
  'cancel_session_switch',
52
+ // Keeps the agent working after the hang-up — state-changing, controller-only.
53
+ 'keep_working',
52
54
  'session_selected',
53
55
  'mcp_toggle',
54
56
  'set_agents',
@@ -82,6 +84,8 @@ export const READ_ONLY_MESSAGE_TYPES = new Set([
82
84
  'get_mcp_status',
83
85
  'get_skills',
84
86
  'skill_get',
87
+ // End asks whether the agent is mid-task before offering keep-working.
88
+ 'get_busy',
85
89
  ]);
86
90
  /** Identity prefix /api/token gives every user participant. */
87
91
  export const USER_IDENTITY_PREFIX = 'user-';
package/dist/index.js CHANGED
@@ -40,7 +40,7 @@ import { cleanupHousekeeping } from './housekeeping.js';
40
40
  import { createSTT, createTTS } from './voice-io.js';
41
41
  import { createClaudeLLM, NAMED_AGENTS, applyTurbo, requestAuthRestart } from './claude-llm.js';
42
42
  import { SOURCES, loadCatalog, findEntry, installSkill, agentDraft, recommend, skillProvenance, installedIds } 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';
43
+ import { parseUserAgents, mergeAgents, describeAgents, describeRoles, coreRole, AGENT_LIMITS, storeWriteRefusal, storeWriteOriginAllowed, coreSkillNames, skillForkedFrom, forkSkill, removeUserSkill, addUserSkill, readUserSkill, parseFrontMatter, storeName } from './agent-store.js';
44
44
  import { clearPipelineFastBrainSession, prewarmBM25Index } from './pipeline-fastbrain.js';
45
45
  import { ensureClaudeAuth, applyAuthFallback, replayInFlightAuth, startClaudeAuthOnDemand, isOnDemandAuthInFlight, probeActiveProviderKey } from './claude-auth.js';
46
46
  import { statusManager } from './status-manager.js';
@@ -58,7 +58,7 @@ import { getRecallClient } from './recall-client.js';
58
58
  import { synthMeetingAudio, selectMeetingTtsProviders } from './meeting-tts.js';
59
59
  import { MeetingTranscriptPoller } from './meeting-transcript-poller.js';
60
60
  import { missingRequiredEnv } from './env-keys.js';
61
- import { armPermissionPush, handleWatchAck, setWatchResultHandler, osbornFrontendUrl } from './pushover.js';
61
+ import { armPermissionPush, handleWatchAck, setWatchResultHandler, osbornFrontendUrl, notifyPhone, isWatchBridgeEnabled, phonePushPending } from './pushover.js';
62
62
  import { startWatchGateway } from './watch-gateway.js';
63
63
  import { noiseGate } from './noise-gate.js';
64
64
  import { installDuck, DUCK_LEVEL } from './duck.js';
@@ -131,8 +131,10 @@ const STORE_REPLY_TYPES = {
131
131
  skill_get: 'skill_content', skill_add: 'skill_add_result', skill_fork: 'skill_fork_result',
132
132
  skill_remove: 'skill_remove_result', get_agent_prompt: 'agent_prompt',
133
133
  };
134
- // Routes that change the machine's skills (guarded by storeWriteRefused).
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.
135
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']);
136
138
  // Skills shipped with the package (core: maintained by Voice Native).
137
139
  const PKG_SKILLS_DIR = join(__dirname, '..', '.claude', 'skills');
138
140
  const homeSkillsDir = () => join(homedir(), '.claude', 'skills');
@@ -605,9 +607,8 @@ function startApiServer(workingDir, port) {
605
607
  // Authorization is required for /secrets (Bearer OSBORN_SYNC_TOKEN); without it in the
606
608
  // allow-list the browser preflight fails and the dashboard can't read/manage keys.
607
609
  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])) {
610
+ // Store routes (STORE_PATHS) echo only an allowed origin, never '*'.
611
+ if (STORE_PATHS.has((req.url || '/').split('?')[0])) {
611
612
  const origin = req.headers.origin;
612
613
  if (origin && storeWriteOriginAllowed(origin, osbornFrontendUrl())) {
613
614
  res.setHeader('Access-Control-Allow-Origin', origin);
@@ -745,24 +746,13 @@ function startApiServer(workingDir, port) {
745
746
  res.end(JSON.stringify(out));
746
747
  return;
747
748
  }
748
- if (req.method === 'GET' && url.pathname === '/skills') {
749
- // Installed skills — same list the chat's get_skills data-channel message
750
- // returns, exposed over HTTP so the DASHBOARD (no LiveKit connection) can
751
- // render the skills manager too. Reads ~/.claude/skills (homedir) — the SINGLE
752
- // location the agent ingests from (loadAllSkills) and PostCompact writes to.
753
- // Previously used process.cwd()/.claude/skills, which the agent never read —
754
- // so UI-created skills were invisible to the agent (the "divergence").
755
- res.writeHead(200, { 'Content-Type': 'application/json' });
756
- res.end(JSON.stringify({ skills: loadSkillsList(homedir()) }));
757
- return;
758
- }
759
749
  // Agent & skill store routes: the chat and Settings both use them (through the
760
750
  // authenticated /api/agent proxy in the cloud). JSON in and out.
761
751
  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({
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,
766
756
  hasToken: !!syncToken,
767
757
  publicDeploy: !!process.env.FLY_APP_NAME || !!process.env.OSBORN_PUBLIC_HOST,
768
758
  forwarded: !!(req.headers['x-forwarded-for'] || req.headers['x-forwarded-host']),
@@ -773,17 +763,32 @@ function startApiServer(workingDir, port) {
773
763
  reply(refusal.status, { error: refusal.error });
774
764
  return !!refusal;
775
765
  };
766
+ if (req.method === 'GET' && url.pathname === '/skills') {
767
+ if (unauthorized() || storeRefused(true))
768
+ return;
769
+ // Installed skills — same list the chat's get_skills data-channel message
770
+ // returns, exposed over HTTP so the DASHBOARD (no LiveKit connection) can
771
+ // render the skills manager too. Reads ~/.claude/skills (homedir) — the SINGLE
772
+ // location the agent ingests from (loadAllSkills) and PostCompact writes to.
773
+ // Previously used process.cwd()/.claude/skills, which the agent never read —
774
+ // so UI-created skills were invisible to the agent (the "divergence").
775
+ res.writeHead(200, { 'Content-Type': 'application/json' });
776
+ res.end(JSON.stringify({ skills: loadSkillsList(homedir()) }));
777
+ return;
778
+ }
776
779
  if (url.pathname === '/skills/content' || (url.pathname.startsWith('/skills/') && STORE_WRITE_PATHS.has(url.pathname))) {
777
780
  if (unauthorized())
778
781
  return;
779
782
  const name = url.searchParams.get('name');
780
783
  if (req.method === 'GET' && url.pathname === '/skills/content') {
784
+ if (storeRefused(true))
785
+ return;
781
786
  const out = readUserSkill(homeSkillsDir(), name);
782
787
  return reply('error' in out ? 404 : 200, out);
783
788
  }
784
789
  if (req.method !== 'POST' || url.pathname === '/skills/content')
785
790
  return reply(405, { error: 'method not allowed' });
786
- if (storeWriteRefused())
791
+ if (storeRefused())
787
792
  return;
788
793
  const out = changeSkill(url.pathname === '/skills/fork' ? 'fork' : 'remove', name, url.searchParams.get('to'));
789
794
  return reply('ok' in out ? 200 : 400, { ...out, skills: loadSkillsList(homedir()) });
@@ -795,6 +800,8 @@ function startApiServer(workingDir, port) {
795
800
  if (unauthorized())
796
801
  return;
797
802
  try {
803
+ if (req.method === 'GET' && storeRefused(true))
804
+ return;
798
805
  if (req.method === 'GET' && url.pathname === '/store/catalog') {
799
806
  const src = url.searchParams.get('source');
800
807
  const caches = await loadCatalog(src && src !== 'all' ? src.split(',') : null, { refresh: url.searchParams.get('refresh') === '1' });
@@ -810,7 +817,7 @@ function startApiServer(workingDir, port) {
810
817
  return reply(200, {
811
818
  sources: caches.map((c) => {
812
819
  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 } : {}) };
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 } : {}) };
814
821
  }),
815
822
  entries,
816
823
  installed: [...installed],
@@ -825,11 +832,18 @@ function startApiServer(workingDir, port) {
825
832
  return reply(200, { entry: found.entry, content: found.body, ...(found.entry.kind === 'agent' ? { draft: agentDraft(found.entry, found.body) } : {}) });
826
833
  }
827
834
  if (req.method === 'POST' && url.pathname === '/store/install') {
828
- if (storeWriteRefused())
835
+ if (storeRefused())
829
836
  return;
830
837
  const found = await findEntry(url.searchParams.get('id') || '');
831
838
  if (!found)
832
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}` });
833
847
  if (found.entry.kind === 'agent')
834
848
  return reply(200, { draft: agentDraft(found.entry, found.body) });
835
849
  const out = await installSkill(found.entry, homeSkillsDir(), coreSkillNames(PKG_SKILLS_DIR));
@@ -845,7 +859,7 @@ function startApiServer(workingDir, port) {
845
859
  // Core sub-agents from claude-llm.ts NAMED_AGENTS (the same object the SDK
846
860
  // query uses), with prompts so the store can show and fork them — so gated
847
861
  // like the other store routes (the chat and Settings go through /api/agent).
848
- if (unauthorized())
862
+ if (unauthorized() || storeRefused(true))
849
863
  return;
850
864
  return reply(200, { agents: describeAgents(NAMED_AGENTS, null, {}, true), ...describeRoles() });
851
865
  }
@@ -2375,7 +2389,10 @@ async function main() {
2375
2389
  // P1: room stays alive while the host anchor is active or any background slot
2376
2390
  // is running. Teardown timers below early-return on this so a dashboard-started
2377
2391
  // session + its background dispatches aren't killed by the empty-room grace.
2378
- 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;
2379
2396
  // Release the host anchor + hard-kill background slots at a genuine session-end
2380
2397
  // boundary so the room can idle-exit (agentsActive → false). Idempotent. MUST be
2381
2398
  // called before arming idle-exit on EVERY path where the session ends, or the
@@ -2498,7 +2515,8 @@ async function main() {
2498
2515
  // fast-leave) — the parked brain does NOT hold the room (it's no longer
2499
2516
  // `currentLLM` nor in `slots`, so agentsActive() is false);
2500
2517
  // 2. a grace timer frees the parked brain if no reconnect arrives;
2501
- // 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).)
2502
2520
  // One-owner invariant: the subprocess is owned by exactly one of
2503
2521
  // {currentLLM, warmLLM}, or it's aborted — never two live, never orphaned.
2504
2522
  // DEFAULT-ON (user, 2026-10-21): the three backstops above — not the flag —
@@ -2560,11 +2578,33 @@ async function main() {
2560
2578
  'session_id', 'mcp_servers_changed', 'tool_use', 'tool_result',
2561
2579
  'assistant_text', 'assistant_result', 'tts_chunks', 'permission_request',
2562
2580
  'tts_say', 'session_resume_failed', 'checkpoint_captured',
2563
- 'dispatch_rejected', 'task_completed', 'agent_started', 'steward_verdict', 'steward_gate',
2581
+ 'dispatch_rejected', 'task_completed', 'agent_started', 'steward_verdict', 'steward_gate', 'tool_blocked',
2564
2582
  ];
2565
- // Abort + clear the parked brain. Clears BOTH timers so grace/watchdog can't
2566
- // double-fire. Used on grace expiry, watchdog, and session mismatch.
2567
- 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();
2568
2608
  if (warmGraceTimer) {
2569
2609
  clearTimeout(warmGraceTimer);
2570
2610
  warmGraceTimer = null;
@@ -2573,6 +2613,49 @@ async function main() {
2573
2613
  clearTimeout(warmWatchdog);
2574
2614
  warmWatchdog = null;
2575
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();
2576
2659
  if (warmLLM) {
2577
2660
  try {
2578
2661
  const llm = warmLLM;
@@ -2595,8 +2678,16 @@ async function main() {
2595
2678
  warmExpiry = 0;
2596
2679
  };
2597
2680
  // Grace timer (free memory if no reconnect) + INDEPENDENT watchdog ceiling.
2598
- // Both end in the SAME teardown: kill warm → releaseAgents → arm idle-exit, so
2599
- // 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
+ };
2600
2691
  const armWarmTimers = () => {
2601
2692
  if (warmGraceTimer)
2602
2693
  clearTimeout(warmGraceTimer);
@@ -2606,17 +2697,13 @@ async function main() {
2606
2697
  warmGraceTimer = null;
2607
2698
  warmStats.wastedTimeouts++;
2608
2699
  console.log('🧊 [KEEP-WARM] grace expired with no reconnect — freeing warm slot');
2609
- killWarm('grace_expired');
2610
- releaseAgents();
2611
- armIdleExitTimer('warm-grace-expired');
2700
+ freeWarm('grace_expired');
2612
2701
  }, REATTACH_GRACE_MS);
2613
2702
  warmWatchdog = setTimeout(() => {
2614
2703
  warmWatchdog = null;
2615
2704
  warmStats.watchdogKills++;
2616
2705
  console.warn('🧊 [KEEP-WARM] WATCHDOG ceiling hit — hard-freeing warm slot (backstop)');
2617
- killWarm('watchdog_ceiling');
2618
- releaseAgents();
2619
- armIdleExitTimer('warm-watchdog');
2706
+ freeWarm('watchdog_ceiling');
2620
2707
  }, WARM_HARD_CEILING_MS);
2621
2708
  };
2622
2709
  // Move currentLLM → warm slot WITHOUT aborting it (the park). If there's no
@@ -2650,14 +2737,7 @@ async function main() {
2650
2737
  // Detach the parked brain for reuse WITHOUT aborting it, cancelling its timers.
2651
2738
  // Caller takes ownership (becomes currentLLM via createDirectSession).
2652
2739
  const claimWarm = () => {
2653
- if (warmGraceTimer) {
2654
- clearTimeout(warmGraceTimer);
2655
- warmGraceTimer = null;
2656
- }
2657
- if (warmWatchdog) {
2658
- clearTimeout(warmWatchdog);
2659
- warmWatchdog = null;
2660
- }
2740
+ clearWarmTimers();
2661
2741
  const llm = warmLLM;
2662
2742
  warmLLM = null;
2663
2743
  warmSessionId = null;
@@ -4128,15 +4208,13 @@ async function main() {
4128
4208
  // 11. Tell the UI; it replaces the transcript with the target's history.
4129
4209
  const summary = await getSessionSummary(target, cwd);
4130
4210
  const conversationHistory = await getConversationHistory(target, cwd, 30);
4131
- await sendToFrontend({
4132
- type: 'session_switched',
4133
- sessionId: target,
4134
- workingDirectory: cwd,
4135
- success: true,
4136
- forced: plan.reason === 'forced',
4137
- summary,
4138
- conversationHistory,
4139
- });
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)`);
4140
4218
  const switchArtifacts = listWorkspaceArtifacts(cwd, target);
4141
4219
  if (switchArtifacts.length > 0) {
4142
4220
  await sendToFrontend({
@@ -4380,8 +4458,9 @@ async function main() {
4380
4458
  // permission is currently pending. Re-registered per session — harmless,
4381
4459
  // the latest closure wins and they all resolve through currentLLM.
4382
4460
  setWatchResultHandler((allow, toolName) => {
4383
- if (currentLLM?.hasPendingPermission?.()) {
4384
- currentLLM.respondToPermission(allow);
4461
+ const target = currentLLM?.hasPendingPermission?.() ? currentLLM : warmLLM?.hasPendingPermission?.() ? warmLLM : null;
4462
+ if (target) {
4463
+ target.respondToPermission(allow);
4385
4464
  console.log(`⌚️ Watch bridge settled ${toolName}: ${allow ? 'approve' : 'deny'}`);
4386
4465
  }
4387
4466
  else {
@@ -4834,6 +4913,7 @@ async function main() {
4834
4913
  // Steward verdict card + sign-off gate note (#221) → chat
4835
4914
  directLLM.events.on('steward_verdict', (v) => sendToFrontend({ type: 'steward_verdict', ...v }));
4836
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 }));
4837
4917
  // Dispatcher v1 — sub-agent started → frontend stop-key signal (Feature A2)
4838
4918
  directLLM.events.on('agent_started', (d) => sendToFrontend({
4839
4919
  type: 'agent_started',
@@ -5166,6 +5246,7 @@ async function main() {
5166
5246
  // connect callback, not via events).
5167
5247
  participantConnectedHandler = async (participant) => {
5168
5248
  console.log(`\n👤 User joined: ${participant.identity}`);
5249
+ keepWorkingRequested = false; // a request belongs to the hang-up it preceded
5169
5250
  // The meeting canvas joining as a listener = browser-parity audio path is
5170
5251
  // LIVE: the agent's normal session.say plays through the canvas into the
5171
5252
  // meeting, so tts_say suppression/redirect must stand down.
@@ -5372,6 +5453,10 @@ async function main() {
5372
5453
  session = result.session;
5373
5454
  agent = result.agent;
5374
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);
5375
5460
  }
5376
5461
  else if (warmLLM) {
5377
5462
  killWarm(warmSessionId && warmSessionId !== resumeSessionId ? 'reattach_session_mismatch' : 'reattach_expired');
@@ -6026,6 +6111,7 @@ async function main() {
6026
6111
  skills: loadSkillsList(homedir()),
6027
6112
  namedAgents: describeAgents(NAMED_AGENTS, userNamedAgents, userAgentRoles, false, userAgentOrigins),
6028
6113
  ...describeRoles(),
6114
+ keepWorking: true,
6029
6115
  });
6030
6116
  };
6031
6117
  const readyInterval = setInterval(sendReady, 2000);
@@ -6258,6 +6344,11 @@ async function main() {
6258
6344
  releaseAgents();
6259
6345
  armMeetingLeaveGrace();
6260
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
+ }
6261
6352
  }
6262
6353
  else {
6263
6354
  // Kill the Claude SDK subprocess BEFORE dropping the reference, otherwise the
@@ -6593,6 +6684,18 @@ async function main() {
6593
6684
  const hint = typeof data.workingDirectory === 'string' ? data.workingDirectory : undefined;
6594
6685
  await requestSessionSwitch(sessionId, hint, { force: !!data.force, origin: 'switch_session' });
6595
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
+ }
6596
6699
  else if (data.type === 'cancel_session_switch') {
6597
6700
  if (pendingSwitch)
6598
6701
  cancelPendingSwitch('user_cancelled');
@@ -38,6 +38,8 @@ interface AckPayload {
38
38
  t: number;
39
39
  e: number;
40
40
  }
41
+ /** An approval push went out and is still waiting for its answer. */
42
+ export declare const phonePushPending: () => boolean;
41
43
  export declare function setWatchResultHandler(fn: (allow: boolean, toolName: string) => void): void;
42
44
  /** The frontend this agent links to and accepts store writes from (OSBORN_FRONTEND_URL, default the live site). */
43
45
  export declare const osbornFrontendUrl: () => string;
@@ -60,6 +62,9 @@ interface NtfyConfig {
60
62
  }
61
63
  export declare function ntfyConfig(): NtfyConfig | null;
62
64
  export declare function isNtfyEnabled(): boolean;
65
+ /** A plain notice to the phone (Pushover and/or ntfy), e.g. "background work finished".
66
+ * False when neither provider is configured or every send failed. */
67
+ export declare function notifyPhone(message: string): Promise<boolean>;
63
68
  /**
64
69
  * Mirror a blocking permission request to the wrist. Fire-and-forget: any
65
70
  * failure (network, Pushover 4xx, missing env) just logs — the web UI remains
package/dist/pushover.js CHANGED
@@ -34,6 +34,8 @@ const EXPIRY_GRACE_MS = 5_000;
34
34
  /** Pending pushes by qid. The permission system is single-slot, so in practice
35
35
  * this holds at most one live record — a Map keeps ack matching O(1) anyway. */
36
36
  const pending = new Map();
37
+ /** An approval push went out and is still waiting for its answer. */
38
+ export const phonePushPending = () => [...pending.values()].some(p => !p.settled);
37
39
  /** Registered by index.ts: resolves the currently-pending permission. */
38
40
  let resultHandler = null;
39
41
  export function setWatchResultHandler(fn) {
@@ -95,6 +97,32 @@ export function ntfyConfig() {
95
97
  export function isNtfyEnabled() {
96
98
  return ntfyConfig() !== null;
97
99
  }
100
+ // One send per provider, shared by the permission push and plain notices.
101
+ const postPushover = (cfg, fields) => fetch(`${PUSH_API}/messages.json`, {
102
+ method: 'POST',
103
+ body: new URLSearchParams({ token: cfg.token, user: cfg.userKey, title: 'Voice Native', ...fields }),
104
+ });
105
+ const postNtfy = (ntfy, fields) => fetch(ntfy.url, {
106
+ method: 'POST',
107
+ headers: { 'Content-Type': 'application/json', ...(ntfy.token ? { Authorization: `Bearer ${ntfy.token}` } : {}) },
108
+ body: JSON.stringify({ topic: ntfy.topic, title: 'Voice Native', tags: ['computer'], click: `${osbornFrontendUrl()}/dashboard`, ...fields }),
109
+ });
110
+ /** A plain notice to the phone (Pushover and/or ntfy), e.g. "background work finished".
111
+ * False when neither provider is configured or every send failed. */
112
+ export async function notifyPhone(message) {
113
+ const cfg = pushoverConfig();
114
+ const ntfy = ntfyConfig();
115
+ const text = message.slice(0, 1000);
116
+ const sends = [];
117
+ if (cfg)
118
+ sends.push(postPushover(cfg, { message: text, url: `${osbornFrontendUrl()}/dashboard` }));
119
+ if (ntfy)
120
+ sends.push(postNtfy(ntfy, { message: text }));
121
+ const ok = (await Promise.allSettled(sends)).some((r) => r.status === 'fulfilled' && r.value.ok);
122
+ if (sends.length && !ok)
123
+ console.log('📱 notifyPhone: not delivered');
124
+ return ok;
125
+ }
98
126
  /**
99
127
  * Mirror a blocking permission request to the wrist. Fire-and-forget: any
100
128
  * failure (network, Pushover 4xx, missing env) just logs — the web UI remains
@@ -131,18 +159,12 @@ export async function armPermissionPush(opts) {
131
159
  };
132
160
  if (cfg) {
133
161
  try {
134
- const res = await fetch(`${PUSH_API}/messages.json`, {
135
- method: 'POST',
136
- body: new URLSearchParams({
137
- token: cfg.token,
138
- user: cfg.userKey,
139
- title: 'Voice Native',
140
- message: `${opts.description}\n\nTap to approve · ignore to deny`.slice(0, 1000),
141
- priority: '2',
142
- retry: String(RETRY_S),
143
- expire: String(EXPIRE_S),
144
- callback: `${frontendUrl}${ACK_PATH}/${qid}`,
145
- }),
162
+ const res = await postPushover(cfg, {
163
+ message: `${opts.description}\n\nTap to approve · ignore to deny`.slice(0, 1000),
164
+ priority: '2',
165
+ retry: String(RETRY_S),
166
+ expire: String(EXPIRE_S),
167
+ callback: `${frontendUrl}${ACK_PATH}/${qid}`,
146
168
  });
147
169
  const body = (await res.json().catch(() => ({})));
148
170
  if (!res.ok || !body.receipt) {
@@ -159,34 +181,13 @@ export async function armPermissionPush(opts) {
159
181
  if (ntfy) {
160
182
  // Approve/Deny buttons hit the SAME signed ack route with ?ans=1|0.
161
183
  try {
162
- const res = await fetch(ntfy.url, {
163
- method: 'POST',
164
- headers: {
165
- 'Content-Type': 'application/json',
166
- ...(ntfy.token ? { Authorization: `Bearer ${ntfy.token}` } : {}),
167
- },
168
- body: JSON.stringify({
169
- topic: ntfy.topic,
170
- title: 'Voice Native',
171
- message: opts.description.slice(0, 1000),
172
- priority: 4,
173
- tags: ['computer'],
174
- click: `${frontendUrl}/dashboard`,
175
- actions: [
176
- {
177
- action: 'http',
178
- label: 'Approve',
179
- method: 'GET',
180
- url: `${frontendUrl}${ACK_PATH}/${qid}?ans=1`,
181
- },
182
- {
183
- action: 'http',
184
- label: 'Deny',
185
- method: 'GET',
186
- url: `${frontendUrl}${ACK_PATH}/${qid}?ans=0`,
187
- },
188
- ],
189
- }),
184
+ const res = await postNtfy(ntfy, {
185
+ message: opts.description.slice(0, 1000),
186
+ priority: 4,
187
+ actions: [
188
+ { action: 'http', label: 'Approve', method: 'GET', url: `${frontendUrl}${ACK_PATH}/${qid}?ans=1` },
189
+ { action: 'http', label: 'Deny', method: 'GET', url: `${frontendUrl}${ACK_PATH}/${qid}?ans=0` },
190
+ ],
190
191
  });
191
192
  if (!res.ok)
192
193
  console.log(`⌚️ Watch bridge: ntfy rejected (${res.status})`);
@@ -23,6 +23,7 @@ export interface CatalogEntry {
23
23
  repo: string;
24
24
  path: string;
25
25
  sha: string;
26
+ rev: string;
26
27
  license: string;
27
28
  /** Files that can run (scripts/ or a script extension), shown before install. */
28
29
  scripts: string[];
@@ -40,7 +41,10 @@ export declare function normaliseSource(src: CatalogSource, snap: Snapshot, read
40
41
  entries: CatalogEntry[];
41
42
  bodies: Record<string, string>;
42
43
  failed: number;
44
+ tooLarge: number;
43
45
  }>;
46
+ export declare class TooLarge extends Error {
47
+ }
44
48
  interface SourceCache {
45
49
  source: string;
46
50
  repo: string;
@@ -49,6 +53,7 @@ interface SourceCache {
49
53
  entries: CatalogEntry[];
50
54
  bodies: Record<string, string>;
51
55
  error?: string;
56
+ note?: string;
52
57
  }
53
58
  export declare function loadCatalog(ids: string[] | null, opts?: {
54
59
  refresh?: boolean;
@@ -3,6 +3,7 @@
3
3
  // hour, pinned at the commit they were read at. MCP servers, hooks, bin and
4
4
  // monitors are out of scope: entries that need MCP are skipped.
5
5
  import { execFile } from 'node:child_process';
6
+ import { createHash } from 'node:crypto';
6
7
  import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, rmSync, mkdtempSync } from 'node:fs';
7
8
  import { homedir, tmpdir } from 'node:os';
8
9
  import { dirname, join, resolve, sep, posix } from 'node:path';
@@ -52,7 +53,7 @@ async function mapLimit(items, n, fn) {
52
53
  }
53
54
  /** Turns a repo snapshot into catalog entries (pure apart from `read`). Returns the bodies too. */
54
55
  export async function normaliseSource(src, snap, read) {
55
- let failed = 0;
56
+ let failed = 0, tooLarge = 0;
56
57
  const paths = snap.paths;
57
58
  const repoLicense = detectLicense(await read(paths.find((p) => /^LICEN[CS]E(\.md|\.txt)?$/i.test(p)) || 'LICENSE').catch(() => null));
58
59
  const market = {};
@@ -72,7 +73,10 @@ export async function normaliseSource(src, snap, read) {
72
73
  });
73
74
  const bodies = {};
74
75
  const entries = (await mapLimit(hits, 8, async (h) => {
75
- const md = await read(h.file).catch(() => { failed++; return null; });
76
+ const md = await read(h.file).catch((e) => { if (e instanceof TooLarge)
77
+ tooLarge++;
78
+ else
79
+ failed++; return null; });
76
80
  if (!md)
77
81
  return null;
78
82
  const { meta, body } = parseFrontMatter(md);
@@ -95,13 +99,14 @@ export async function normaliseSource(src, snap, read) {
95
99
  description: str(meta.description).slice(0, 600),
96
100
  tools, ...(str(meta.model) ? { model: str(meta.model) } : {}),
97
101
  files, repo: src.repo, path: dir, sha: snap.sha,
102
+ rev: createHash('sha256').update(md).update('\0' + files.join('\n')).digest('hex').slice(0, 16),
98
103
  license: ownLicense ? (/LICENSE/i.test(ownLicense) ? 'See LICENSE.txt' : ownLicense.slice(0, 40)) : (files.some((f) => /^LICEN[CS]E/i.test(f)) ? 'See LICENSE.txt' : repoLicense || 'Unknown'),
99
104
  scripts: files.filter((f) => f.startsWith('scripts/') || SCRIPT_EXT.test(f)),
100
105
  trust: src.trust,
101
106
  ...(h.plugin ? { plugin: h.plugin, ...(market[h.plugin]?.category ? { category: market[h.plugin].category } : {}) } : {}),
102
107
  };
103
108
  })).filter((e) => !!e);
104
- return { entries, bodies, failed };
109
+ return { entries, bodies, failed, tooLarge };
105
110
  }
106
111
  // ── Fetching ─────────────────────────────────────────────────────────────────
107
112
  const GH_API = 'https://api.github.com';
@@ -121,6 +126,8 @@ async function snapshotViaApi(repo) {
121
126
  if (!t.ok)
122
127
  throw new Error(`tree ${t.status}`);
123
128
  const tree = await t.json();
129
+ if (tree.truncated)
130
+ throw new Error('tree listing truncated'); // a partial listing would cache as complete; git lists it all
124
131
  return { sha, paths: (tree.tree || []).filter((n) => n.type === 'blob').map((n) => n.path) };
125
132
  }
126
133
  /** Fallback when the API is rate-limited or blocked: a blobless depth-1 clone, file names only. */
@@ -146,6 +153,8 @@ async function snapshot(repo) {
146
153
  }
147
154
  }
148
155
  const MAX_FILE_BYTES = 2 * 1024 * 1024;
156
+ export class TooLarge extends Error {
157
+ }
149
158
  async function rawBytes(repo, sha, path) {
150
159
  const r = await fetch(`${GH_RAW}/${repo}/${sha}/${path.split('/').map(encodeURIComponent).join('/')}`, { signal: AbortSignal.timeout(20000) });
151
160
  if (r.status === 404)
@@ -153,7 +162,9 @@ async function rawBytes(repo, sha, path) {
153
162
  if (!r.ok)
154
163
  throw new Error(`raw ${r.status}`); // rate limit / outage: a failure, not a missing file
155
164
  const buf = Buffer.from(await r.arrayBuffer());
156
- return buf.length > MAX_FILE_BYTES ? null : buf;
165
+ if (buf.length > MAX_FILE_BYTES)
166
+ throw new TooLarge(`${path} is larger than ${MAX_FILE_BYTES >> 20} MB`); // never read as a missing file
167
+ return buf;
157
168
  }
158
169
  const rawReader = (repo, sha) => async (p) => (await rawBytes(repo, sha, p))?.toString('utf-8') ?? null;
159
170
  // ── Cache ────────────────────────────────────────────────────────────────────
@@ -161,7 +172,7 @@ const TTL_MS = 60 * 60 * 1000;
161
172
  const cacheDir = () => join(homedir(), '.osborn', 'store-cache');
162
173
  const inflight = new Map();
163
174
  async function loadSource(src, opts = {}) {
164
- const file = join(opts.dir || cacheDir(), `${src.id}.v2.json`); // v2: entries carry scripts[]
175
+ const file = join(opts.dir || cacheDir(), `${src.id}.v3.json`); // v3: entries carry rev
165
176
  let cached = null;
166
177
  try {
167
178
  cached = JSON.parse(readFileSync(file, 'utf-8'));
@@ -174,8 +185,9 @@ async function loadSource(src, opts = {}) {
174
185
  const p = (async () => {
175
186
  try {
176
187
  const snap = await snapshot(src.repo);
177
- const { entries, bodies, failed } = await normaliseSource(src, snap, rawReader(src.repo, snap.sha));
178
- const fresh = { source: src.id, repo: src.repo, sha: snap.sha, fetchedAt: Date.now(), entries, bodies };
188
+ const { entries, bodies, failed, tooLarge } = await normaliseSource(src, snap, rawReader(src.repo, snap.sha));
189
+ // Oversize entries are left out on purpose; the source says so rather than looking complete.
190
+ const fresh = { source: src.id, repo: src.repo, sha: snap.sha, fetchedAt: Date.now(), entries, bodies, ...(tooLarge ? { note: `${tooLarge} entr${tooLarge === 1 ? 'y is' : 'ies are'} over ${MAX_FILE_BYTES >> 20} MB and not listed` } : {}) };
179
191
  // Some files could not be read: never cache a partial catalog over a good one.
180
192
  if (failed) {
181
193
  const error = `${failed} file(s) could not be read from GitHub`;
@@ -247,7 +259,15 @@ export async function installSkill(entry, skillsDir, coreSkills, fetchFile = (p)
247
259
  try {
248
260
  let total = 0;
249
261
  for (const f of entry.files) {
250
- const buf = await fetchFile(`${entry.path}/${f}`);
262
+ let buf;
263
+ try {
264
+ buf = await fetchFile(`${entry.path}/${f}`);
265
+ }
266
+ catch (e) {
267
+ if (e instanceof TooLarge)
268
+ return { error: e.message };
269
+ throw e;
270
+ }
251
271
  if (!buf)
252
272
  return { error: `could not fetch ${f}` };
253
273
  total += buf.length;
@@ -284,7 +304,7 @@ export function agentDraft(entry, body) {
284
304
  return {
285
305
  name: storeName(entry.name).slice(0, AGENT_LIMITS.name),
286
306
  description: (entry.description || entry.name).slice(0, AGENT_LIMITS.description),
287
- prompt: body.slice(0, AGENT_LIMITS.prompt),
307
+ prompt: body, // never cut: /store/install refuses one over AGENT_LIMITS.prompt
288
308
  model, tools, role: draftRole(tools),
289
309
  forked_from: catalogOrigin(entry),
290
310
  };
@@ -1,3 +1,7 @@
1
1
  // The name a user agent or skill is stored under. Dependency-free so the frontend's
2
2
  // copy (frontend/src/lib/agent-name.ts agentName) can be tested against it.
3
- export const storeName = (raw) => String(raw ?? '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-');
3
+ // A name with no letter or digit ('---') is no name: ''.
4
+ export const storeName = (raw) => {
5
+ const n = String(raw ?? '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-');
6
+ return /[a-z0-9]/.test(n) ? n : '';
7
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osborn",
3
- "version": "0.9.281",
3
+ "version": "0.9.282",
4
4
  "description": "Voice AI coding assistant - local agent that connects to Osborn frontend",
5
5
  "type": "module",
6
6
  "bin": {