@clagentic/console 1.10.0-beta.1 → 1.10.0-beta.2

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 (68) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.js +10 -0
  3. package/lib/agent-dispatch-tool.js +20 -0
  4. package/lib/build-changes.js +79 -0
  5. package/lib/build-identity.js +192 -0
  6. package/lib/build-monitor.js +125 -0
  7. package/lib/build-sha.json +2 -2
  8. package/lib/build-update-offer.js +141 -0
  9. package/lib/build-update-restart.js +142 -0
  10. package/lib/build-update-standing.js +184 -0
  11. package/lib/cli/daemon-launch.js +8 -5
  12. package/lib/cli/ipc-subcommands.js +6 -0
  13. package/lib/cli/session-subcommands.js +122 -0
  14. package/lib/cli-sessions.js +8 -1
  15. package/lib/codex-defaults.js +8 -2
  16. package/lib/daemon-projects.js +19 -0
  17. package/lib/daemon.js +166 -127
  18. package/lib/memory-shed.js +13 -32
  19. package/lib/project-connection.js +14 -0
  20. package/lib/project-external-trigger.js +91 -123
  21. package/lib/project-loop.js +5 -4
  22. package/lib/project-prompt-responses.js +5 -4
  23. package/lib/project-sessions.js +43 -68
  24. package/lib/project-user-message.js +7 -20
  25. package/lib/project.js +23 -5
  26. package/lib/prompt-registry.js +7 -0
  27. package/lib/public/css/diagnostics.css +30 -0
  28. package/lib/public/modules/agent-dispatch-tool.js +9 -0
  29. package/lib/public/modules/app-messages.js +7 -2
  30. package/lib/public/modules/app-panels.js +0 -1
  31. package/lib/public/modules/build-update-detail.js +54 -0
  32. package/lib/public/modules/diagnostics.js +126 -20
  33. package/lib/public/modules/tools.js +14 -2
  34. package/lib/public/modules/vendor-picker.js +2 -2
  35. package/lib/public/modules/vendor-registry.js +11 -2
  36. package/lib/sdk-bridge.js +62 -15
  37. package/lib/sdk-message-processor.js +11 -20
  38. package/lib/sdk-skill-discovery.js +65 -60
  39. package/lib/server.js +15 -2
  40. package/lib/session-id.js +33 -0
  41. package/lib/session-input-ipc.js +32 -0
  42. package/lib/session-input.js +379 -0
  43. package/lib/session-reclaim.js +284 -0
  44. package/lib/session-resume.js +172 -0
  45. package/lib/sessions.js +16 -2
  46. package/lib/supervisor.js +39 -0
  47. package/lib/turn-initiator.js +108 -0
  48. package/lib/vendor-registry-message.js +1 -0
  49. package/lib/ws-schema.js +3 -1
  50. package/lib/yoke/adapters/claude-vendor.js +0 -1
  51. package/lib/yoke/adapters/claude-worker.js +6 -4
  52. package/lib/yoke/adapters/claude.js +34 -34
  53. package/lib/yoke/adapters/codex-capabilities.js +9 -6
  54. package/lib/yoke/adapters/codex-vendor.js +15 -15
  55. package/lib/yoke/adapters/codex.js +121 -61
  56. package/lib/yoke/auth-checks.js +8 -21
  57. package/lib/yoke/codex-app-server.js +27 -71
  58. package/lib/yoke/codex-binary.js +254 -0
  59. package/lib/yoke/codex-command.js +122 -0
  60. package/lib/yoke/codex-protocol.js +96 -0
  61. package/lib/yoke/codex-version.js +135 -0
  62. package/lib/yoke/index.js +20 -4
  63. package/lib/yoke/install-probe.js +21 -6
  64. package/lib/yoke/interface.js +11 -5
  65. package/lib/yoke/registry.js +41 -4
  66. package/package.json +1 -2
  67. package/scripts/verify-installed-build.js +59 -17
  68. package/lib/lore-attestation.js +0 -73
package/lib/sdk-bridge.js CHANGED
@@ -14,6 +14,8 @@ var { runPreflight } = require("./settings-preflight");
14
14
  var { promptsFor } = require("./prompt-registry");
15
15
  var { toolApprovalKind } = require("./prompt-kinds");
16
16
  var sessionActivity = require("./session-activity");
17
+ var sessionReclaim = require("./session-reclaim");
18
+ var { isAgentDispatchTool } = require("./agent-dispatch-tool");
17
19
  var { getNewWorkRefusal } = require("./new-work-gate");
18
20
  var runtimeEnv = require("./runtime-env");
19
21
  var mcpToolSchema = require("./mcp-tool-schema");
@@ -383,6 +385,9 @@ function createSDKBridge(opts) {
383
385
  var adapter = opts.adapter;
384
386
  var adapters = opts.adapters || {};
385
387
  var dangerouslySkipPermissions = opts.dangerouslySkipPermissions || false;
388
+ // Whether the daemon isolates users at the OS level. An agent that does not
389
+ // support that (Codex) is disabled then: never created, never started.
390
+ var osUsersMode = !!opts.osUsers;
386
391
  // mcpServers may be either a static object or a getter function. The
387
392
  // getter form lets callers gate individual servers at call time (e.g.
388
393
  // clay-browser is only exposed while the Chrome extension is connected).
@@ -596,10 +601,14 @@ function createSDKBridge(opts) {
596
601
  // no activity at all, or a leaked child registration would pin the
597
602
  // session (and its process) alive forever. Because that case was never
598
603
  // "live" at the moment of reap (no activity for the full timeout window),
599
- // it emits no notification here — only the pressure path in
600
- // lib/memory-shed.js, which can reclaim a still-progressing session as a
601
- // deliberate last resort, notifies both UI surfaces (see its
602
- // liveChildReclaims handling).
604
+ // it is reaped; the reap and the pressure path in lib/memory-shed.js both
605
+ // announce it through lib/session-reclaim.js.
606
+ //
607
+ // A session with ANY open operator prompt is never reaped (see the
608
+ // pendingCount check in startIdleReaper): a background agent blocked on a
609
+ // permission prompt emits nothing, so its silence is the operator's to
610
+ // break, not evidence that it died. When a silent child IS reaped, the
611
+ // operator is told which agents were interrupted.
603
612
  var IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
604
613
  var IDLE_CHECK_INTERVAL_MS = 60 * 1000; // check every 60 seconds
605
614
  // lr-5450ef: BACKSTOP staleness window for the activity registry's leak
@@ -656,11 +665,30 @@ function createSDKBridge(opts) {
656
665
  if (!session.queryInstance) return;
657
666
  if (session.singleTurn) return;
658
667
 
668
+ // A session with an open prompt (its own, or a background agent's) is
669
+ // waiting on the operator, not idle: an agent blocked on a prompt
670
+ // emits no stream events, so the activity clock cannot tell. Ending
671
+ // it would abort the pending tool call and destroy the agent's work.
672
+ // Memory pressure is handled by lib/memory-shed.js, not this timer.
673
+ if (promptsFor(sm).pendingCount(session) > 0) return;
674
+
659
675
  var lastActivity = session.lastActivityAt || 0;
660
676
  if (now - lastActivity > IDLE_TIMEOUT_MS) {
661
677
  console.log("[sdk-bridge] Reaping idle session " + session.localId +
662
678
  " (idle " + Math.round((now - lastActivity) / 60000) + "min)" +
663
679
  (session.title ? " title=" + JSON.stringify(session.title) : ""));
680
+ // Never silent when background agents are still registered: name
681
+ // them and mark the session as expected to resume.
682
+ sessionReclaim.announceLiveAgentReclaim({
683
+ session: session,
684
+ sm: sm,
685
+ send: send,
686
+ slug: slug,
687
+ reason: "idle_reap",
688
+ source: "idle-reap",
689
+ cause: "Clagentic: Console ended this session after " + Math.round(IDLE_TIMEOUT_MS / 60000)
690
+ + " minutes without activity.",
691
+ });
664
692
  // End the query so the for-await loop in processQueryStream
665
693
  // exits naturally, triggering the finally block cleanup.
666
694
  // Works for both in-process (messageQueue.end) and worker (handle.close) paths.
@@ -1124,10 +1152,17 @@ function createSDKBridge(opts) {
1124
1152
  // configurable) rather than copying the worker's blanket 30s.
1125
1153
  // The registry creates the notification and dismisses it when the
1126
1154
  // prompt settles.
1155
+ // A prompt raised by a background agent says so, on the card, the banner
1156
+ // and the push: otherwise it reads as the parent's own call and is easy
1157
+ // to miss while the parent sits idle.
1158
+ var agentLabel = sessionReclaim.ownerLabelOfTool(session, prompts, opts.toolUseID);
1159
+ var agentPrefix = agentLabel ? 'Background agent "' + agentLabel + '": ' : "";
1127
1160
  var opened = prompts.open(session, kind, {
1128
1161
  toolName: toolName,
1129
1162
  toolInput: input,
1130
- decisionReason: opts.decisionReason || "",
1163
+ decisionReason: agentLabel
1164
+ ? 'Requested by background agent "' + agentLabel + '". ' + (opts.decisionReason || "")
1165
+ : (opts.decisionReason || ""),
1131
1166
  vendor: session.vendor || (adapter && adapter.vendor) || "claude",
1132
1167
  suppressAlwaysAllowRule: opts.suppressAlwaysAllowRule,
1133
1168
  defaultToNo: opts.defaultToNo,
@@ -1136,7 +1171,7 @@ function createSDKBridge(opts) {
1136
1171
  toolUseId: opts.toolUseID,
1137
1172
  signal: opts.signal,
1138
1173
  notification: {
1139
- title: permissionPushTitle(toolName, input),
1174
+ title: agentPrefix + permissionPushTitle(toolName, input),
1140
1175
  body: permissionPushBody(toolName, input),
1141
1176
  slug: slug,
1142
1177
  sessionId: session.localId,
@@ -1152,7 +1187,7 @@ function createSDKBridge(opts) {
1152
1187
  type: "permission_request",
1153
1188
  slug: slug,
1154
1189
  requestId: opened.requestId,
1155
- title: permissionPushTitle(toolName, input),
1190
+ title: agentPrefix + permissionPushTitle(toolName, input),
1156
1191
  body: permissionPushBody(toolName, input),
1157
1192
  };
1158
1193
  // Route to session owner only — body carries tool name and input (may contain paths/code).
@@ -1615,7 +1650,10 @@ function createSDKBridge(opts) {
1615
1650
  return { sessionId: result.sessionId, useLocalHistory: false };
1616
1651
  }
1617
1652
 
1618
- async function startQuery(session, text, images, linuxUser) {
1653
+ // `initiator` (turn-initiator.js INITIATORS) is who started this turn. It is
1654
+ // per turn: it stamps the first message and decides the new process's
1655
+ // environment, and says nothing about later turns of the session.
1656
+ async function startQuery(session, text, images, linuxUser, initiator) {
1619
1657
  async function ensureVendorReady(vendor) {
1620
1658
  if (!vendor) return null;
1621
1659
  // What the adapter's live session advertises narrows its declaration; the
@@ -1633,6 +1671,7 @@ function createSDKBridge(opts) {
1633
1671
  // session's own server is started for it when its query begins.
1634
1672
  vendorAdapter = await yoke.lazyCreateAdapter(adapters, vendor, withRuntimeEnv({
1635
1673
  cwd: cwd,
1674
+ osUsers: osUsersMode,
1636
1675
  dangerouslySkipPermissions: dangerouslySkipPermissions,
1637
1676
  linuxUser: linuxUser || undefined,
1638
1677
  clayPort: clayPort,
@@ -1668,6 +1707,13 @@ function createSDKBridge(opts) {
1668
1707
  sendAndRecord(session, { type: "done", code: 1 });
1669
1708
  return;
1670
1709
  }
1710
+ // An agent that per-user OS isolation rules out is refused with its reason,
1711
+ // not offered a login, and nothing of it is started.
1712
+ if (session.vendor && yokeRegistry.disabledByOsUsers(session.vendor, osUsersMode)) {
1713
+ sendAndRecord(session, { type: "error", text: yokeRegistry.osUsersReasonFor(session.vendor) });
1714
+ sendAndRecord(session, { type: "done", code: 1 });
1715
+ return;
1716
+ }
1671
1717
  // If vendor is set but adapter not ready, try lazy creation (user may have logged in)
1672
1718
  if (session.vendor && !adapters[session.vendor]) {
1673
1719
  var lazyAdapter = await ensureVendorReady(session.vendor);
@@ -2109,6 +2155,7 @@ function createSDKBridge(opts) {
2109
2155
  var mergedMcpServers = mergeMcpServers(getMcpServers(), getRemoteMcpServers) || undefined;
2110
2156
  var queryOpts = {
2111
2157
  cwd: cwd,
2158
+ initiator: initiator,
2112
2159
  model: queryModel,
2113
2160
  effort: ls.effort || sm.currentEffort || undefined,
2114
2161
  toolServers: mergedMcpServers,
@@ -2198,7 +2245,7 @@ function createSDKBridge(opts) {
2198
2245
 
2199
2246
  // Push initial user message through the QueryHandle
2200
2247
  console.log("[sdk-bridge] pushing initial message via handle.pushMessage...");
2201
- handle.pushMessage(text, images);
2248
+ handle.pushMessage(text, images, initiator);
2202
2249
 
2203
2250
  // lr-b61b: Flush any messages that arrived between turns (after the previous
2204
2251
  // finally block nulled queryInstance and before this startQuery call).
@@ -2206,7 +2253,7 @@ function createSDKBridge(opts) {
2206
2253
  console.log("[sdk-bridge] startQuery: flushing " + session.pendingMessages.length + " buffered pending message(s) for session " + session.localId);
2207
2254
  for (var pi = 0; pi < session.pendingMessages.length; pi++) {
2208
2255
  var pm = session.pendingMessages[pi];
2209
- handle.pushMessage(pm.text, pm.images);
2256
+ handle.pushMessage(pm.text, pm.images, pm.initiator);
2210
2257
  }
2211
2258
  session.pendingMessages = [];
2212
2259
  }
@@ -2244,11 +2291,11 @@ function createSDKBridge(opts) {
2244
2291
  }
2245
2292
  }
2246
2293
 
2247
- function pushMessage(session, text, images) {
2294
+ function pushMessage(session, text, images, initiator) {
2248
2295
  session.lastActivityAt = Date.now();
2249
2296
  // Route through QueryHandle (works for both in-process and worker paths)
2250
2297
  if (session.queryInstance && typeof session.queryInstance.pushMessage === "function") {
2251
- session.queryInstance.pushMessage(text, images);
2298
+ session.queryInstance.pushMessage(text, images, initiator);
2252
2299
  } else {
2253
2300
  // lr-b61b: queryInstance is null between turns (finally block has run but
2254
2301
  // startQuery has not been called yet). Buffer the message so it is not
@@ -2264,7 +2311,7 @@ function createSDKBridge(opts) {
2264
2311
  // so any candidate cause that lands a message here is visible.
2265
2312
  var wasFull = session.pendingMessages.length >= MAX_PENDING_MESSAGES;
2266
2313
  if (wasFull) session.pendingMessages.shift();
2267
- session.pendingMessages.push({ text: text, images: images });
2314
+ session.pendingMessages.push({ text: text, images: images, initiator: initiator });
2268
2315
  console.log("[sdk-bridge] pushMessage: queryInstance null, buffered message for session " + session.localId + " (pending=" + session.pendingMessages.length + ")");
2269
2316
  sendAndRecord(session, {
2270
2317
  type: "diagnostic",
@@ -2280,6 +2327,7 @@ function createSDKBridge(opts) {
2280
2327
  function permissionPushTitle(toolName, input) {
2281
2328
  if (!input) return "Claude wants to use " + toolName;
2282
2329
  var file = input.file_path ? input.file_path.split(/[/\\]/).pop() : "";
2330
+ if (isAgentDispatchTool(toolName)) return "Claude wants to launch an agent";
2283
2331
  switch (toolName) {
2284
2332
  case "Bash": return "Claude wants to run a command";
2285
2333
  case "Edit": return "Claude wants to edit " + (file || "a file");
@@ -2289,7 +2337,6 @@ function createSDKBridge(opts) {
2289
2337
  case "Glob": return "Claude wants to find files";
2290
2338
  case "WebFetch": return "Claude wants to fetch a URL";
2291
2339
  case "WebSearch": return "Claude wants to search the web";
2292
- case "Task": return "Claude wants to launch an agent";
2293
2340
  default: return "Claude wants to use " + toolName;
2294
2341
  }
2295
2342
  }
@@ -2325,7 +2372,7 @@ function createSDKBridge(opts) {
2325
2372
  // a null user is the daemon's own account.
2326
2373
  function detectInstalledVendors(linuxUser) {
2327
2374
  // The registry owns the probes and the allowlist of executable names.
2328
- var state = require("./yoke").detectVendorInstallState(linuxUser || null);
2375
+ var state = require("./yoke").detectVendorInstallState(linuxUser || null, { osUsers: osUsersMode });
2329
2376
  recordInstallState(sm, linuxUser || null, state);
2330
2377
  return state.installed;
2331
2378
  }
@@ -3,9 +3,10 @@ var { discoverWorkflows } = require("./sdk-workflow-discovery");
3
3
  var { buildEnrichedSlashCommands } = require("./sdk-slash-enrichment");
4
4
  var { promptsFor } = require("./prompt-registry");
5
5
  var sessionActivity = require("./session-activity");
6
- var loreAttestation = require("./lore-attestation");
7
6
  var yokeRegistry = require("./yoke").registry;
8
7
  var { authRequiredFacts } = require("./vendor-auth");
8
+ var sessionReclaim = require("./session-reclaim");
9
+ var { isAgentDispatchTool } = require("./agent-dispatch-tool");
9
10
 
10
11
  // Source names of the activity tokens an agent with the activityTokens
11
12
  // trait holds for its own tool and thinking blocks.
@@ -155,7 +156,7 @@ function attachMessageProcessor(ctx) {
155
156
  if (name === "Glob" && input && input.pattern) return "Finding " + input.pattern;
156
157
  if (name === "WebSearch" && input && input.query) return "Searching: " + input.query;
157
158
  if (name === "WebFetch") return "Fetching URL...";
158
- if (name === "Task" && input && input.description) return input.description;
159
+ if (isAgentDispatchTool(name) && input && input.description) return input.description;
159
160
  return "Running " + name + "...";
160
161
  }
161
162
 
@@ -264,22 +265,6 @@ function attachMessageProcessor(ctx) {
264
265
  sm.saveSessionFile(session);
265
266
  if (_isNewSessionId) {
266
267
  sendAndRecord(session, { type: "session_id", cliSessionId: session.cliSessionId });
267
- // Declare human presence to LORE for a session of an agent with the
268
- // attestsHumanSessions trait (Codex) that the operator is driving
269
- // through the console, keyed on the rollout/thread id captured just
270
- // above (parsed.sessionId is that id — see
271
- // lib/yoke/adapters/codex.js's thread/start-and-resume handling).
272
- // Claude console sessions are already covered by LORE's own pulse hook
273
- // and are deliberately not duplicated here (see lib/lore-attestation.js
274
- // header). Gated on session.humanOriginated, set ONLY by the WS
275
- // "message"/"send_scheduled_now" handlers in project-user-message.js —
276
- // never true for a headless session (Ralph Loop, external trigger,
277
- // scheduler), so a scheduled/autonomous dispatch is never attested.
278
- // Fire-and-forget and fail-open by construction — see
279
- // attestHumanSession's own contract.
280
- if (sessionHasTrait(session, "attestsHumanSessions") && session.humanOriginated) {
281
- loreAttestation.attestHumanSession(session.cliSessionId);
282
- }
283
268
  }
284
269
  }
285
270
 
@@ -504,8 +489,10 @@ function attachMessageProcessor(ctx) {
504
489
 
505
490
  // Track active Task tools (activeTaskToolIds, written by the prompt
506
491
  // registry) for sub-agent done detection and prompt ownership.
507
- if (block.name === "Task") {
492
+ if (isAgentDispatchTool(block.name)) {
508
493
  promptsFor(sm).taskStarted(session, block.id);
494
+ // Names the agent in any notice about it (reap, shed, its prompts).
495
+ sessionReclaim.noteTaskLabel(session, block.id, input);
509
496
  }
510
497
 
511
498
  if (pushModule && block.name === "AskUserQuestion" && input.questions) {
@@ -584,6 +571,7 @@ function attachMessageProcessor(ctx) {
584
571
  });
585
572
  }
586
573
  resultPrompts.taskEnded(session, block.tool_use_id);
574
+ sessionReclaim.pruneTaskLabels(session);
587
575
  // lr-9bcd7b (widened lr-6e20f7): release the activity token
588
576
  // acquired at block_stop for this tool id, unconditionally --
589
577
  // NOT gated on activeTaskToolIds still containing the entry.
@@ -962,7 +950,10 @@ function attachMessageProcessor(ctx) {
962
950
  // The sub-agent is done. Its tracking and ownership records are
963
951
  // released, except for a prompt still awaiting the operator, which
964
952
  // keeps the Task in scope until it settles.
965
- if (parentId) notifiedPrompts.taskEnded(session, parentId);
953
+ if (parentId) {
954
+ notifiedPrompts.taskEnded(session, parentId);
955
+ sessionReclaim.pruneTaskLabels(session);
956
+ }
966
957
 
967
958
  } else if (parsed.yokeType === "rate_limit") {
968
959
  var info = parsed.rateLimitInfo;
@@ -203,6 +203,66 @@ function extractDescriptionFromContent(content) {
203
203
  return "";
204
204
  }
205
205
 
206
+ // Where skills live, lowest precedence first: each agent reads its own native
207
+ // location (Claude .claude/skills, Codex .agents/skills), and the console
208
+ // presents one list from all of them. A project's skill beats the user's of the
209
+ // same name, and within a level the directory of the agent the list is for beats
210
+ // the other's: .claude by default, .agents when preferAgentsDir is set (the list
211
+ // for a session of the agent that reads .agents/skills natively).
212
+ function skillRoots(cwd, globalHome, preferAgentsDir) {
213
+ var first = preferAgentsDir ? ".claude" : ".agents";
214
+ var second = preferAgentsDir ? ".agents" : ".claude";
215
+ var roots = [];
216
+ if (globalHome) {
217
+ roots.push(path.join(globalHome, first, "skills"));
218
+ roots.push(path.join(globalHome, second, "skills"));
219
+ }
220
+ if (cwd) {
221
+ roots.push(path.join(cwd, first, "skills"));
222
+ roots.push(path.join(cwd, second, "skills"));
223
+ }
224
+ return roots;
225
+ }
226
+
227
+ // A directory or file that is simply not there is the ordinary case (a user
228
+ // without a .agents directory) and stays quiet. Anything else (permissions, an
229
+ // I/O fault) hides skills the user has, so it is named in the log.
230
+ function warnUnlessAbsent(what, target, err) {
231
+ if (err && (err.code === "ENOENT" || err.code === "ENOTDIR")) return;
232
+ console.warn("[skills] could not read " + what + " " + target + ": " + (err && err.code ? err.code : (err && err.message) || err));
233
+ }
234
+
235
+ // name -> the skill's real directory, for every skill in every root. A name
236
+ // from a directory listing never indexes an ordinary object.
237
+ function collectSkillDirs(cwd, globalHome, preferAgentsDir) {
238
+ var byName = Object.create(null);
239
+ var roots = skillRoots(cwd, globalHome, preferAgentsDir);
240
+ for (var d = 0; d < roots.length; d++) {
241
+ var base = roots[d];
242
+ var entries;
243
+ try {
244
+ entries = fs.readdirSync(base, { withFileTypes: true });
245
+ } catch (e) {
246
+ warnUnlessAbsent("skills directory", base, e);
247
+ continue;
248
+ }
249
+ for (var i = 0; i < entries.length; i++) {
250
+ var entry = entries[i];
251
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
252
+ var skillDir = resolveContainedSkillDir(base, entry.name);
253
+ if (!skillDir) continue;
254
+ var skillMd = path.join(skillDir, "SKILL.md");
255
+ try {
256
+ fs.accessSync(skillMd, fs.constants.R_OK);
257
+ byName[entry.name] = skillDir;
258
+ } catch (e) {
259
+ warnUnlessAbsent("skill file", skillMd, e);
260
+ }
261
+ }
262
+ }
263
+ return byName;
264
+ }
265
+
206
266
  // Read SKILL.md for a skill directory and extract a short description string.
207
267
  // Delegates to extractDescriptionFromContent for the actual parsing logic.
208
268
  function extractSkillDescription(skillDir) {
@@ -226,36 +286,8 @@ function extractSkillDescription(skillDir) {
226
286
  // it here so the global skills dir is the invoking user's own ~/.claude/skills,
227
287
  // not the daemon process's REAL_HOME (lr-3ccc78). Falls back to REAL_HOME when
228
288
  // absent — the single-user / no-OS-isolation case, unchanged behavior.
229
- function discoverSkillsWithMeta(cwd, homeOverride) {
230
- var globalHome = homeOverride || require("./config").REAL_HOME;
231
- var dirs = [
232
- path.join(globalHome, ".claude", "skills"),
233
- path.join(cwd, ".claude", "skills"),
234
- ];
235
- // Ordered map so project skills override global skills
236
- var byName = {};
237
- for (var d = 0; d < dirs.length; d++) {
238
- var base = dirs[d];
239
- var entries;
240
- try {
241
- entries = fs.readdirSync(base, { withFileTypes: true });
242
- } catch (e) {
243
- continue;
244
- }
245
- for (var i = 0; i < entries.length; i++) {
246
- var entry = entries[i];
247
- if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
248
- var skillDir = resolveContainedSkillDir(base, entry.name);
249
- if (!skillDir) continue;
250
- var skillMdPath = path.join(skillDir, "SKILL.md");
251
- try {
252
- fs.accessSync(skillMdPath, fs.constants.R_OK);
253
- byName[entry.name] = skillDir;
254
- } catch (e) {
255
- // no SKILL.md, skip
256
- }
257
- }
258
- }
289
+ function discoverSkillsWithMeta(cwd, homeOverride, preferAgentsDir) {
290
+ var byName = collectSkillDirs(cwd, homeOverride || require("./config").REAL_HOME, preferAgentsDir);
259
291
  var result = [];
260
292
  var names = Object.keys(byName);
261
293
  for (var j = 0; j < names.length; j++) {
@@ -306,36 +338,7 @@ function attachSkillDiscovery(ctx) {
306
338
  // above) so a caller can resolve the session owner's home instead of the
307
339
  // daemon's REAL_HOME on a shared multi-user daemon (lr-3ccc78).
308
340
  function discoverSkillDirs(homeOverride) {
309
- var skills = {};
310
- var globalHome = homeOverride || require("./config").REAL_HOME;
311
- var dirs = [
312
- path.join(globalHome, ".claude", "skills"),
313
- path.join(cwd, ".claude", "skills"),
314
- ];
315
- for (var d = 0; d < dirs.length; d++) {
316
- var base = dirs[d];
317
- var entries;
318
- try {
319
- entries = fs.readdirSync(base, { withFileTypes: true });
320
- } catch (e) {
321
- continue; // directory doesn't exist
322
- }
323
- for (var i = 0; i < entries.length; i++) {
324
- var entry = entries[i];
325
- if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
326
- var skillDir = resolveContainedSkillDir(base, entry.name);
327
- if (!skillDir) continue;
328
- var skillMd = path.join(skillDir, "SKILL.md");
329
- try {
330
- fs.accessSync(skillMd, fs.constants.R_OK);
331
- // project skills override global skills with same name
332
- skills[entry.name] = skillDir;
333
- } catch (e) {
334
- // no SKILL.md, skip
335
- }
336
- }
337
- }
338
- return skills;
341
+ return collectSkillDirs(cwd, homeOverride || require("./config").REAL_HOME);
339
342
  }
340
343
 
341
344
  function mergeSkills(sdkSkills, fsSkills) {
@@ -366,4 +369,6 @@ module.exports = {
366
369
  // reuse the same two-stage (lexical + realpath) containment check instead
367
370
  // of approximating it — see the function's own doc comment.
368
371
  resolveContainedSkillDir: resolveContainedSkillDir,
372
+ collectSkillDirs: collectSkillDirs,
373
+ skillRoots: skillRoots,
369
374
  };
package/lib/server.js CHANGED
@@ -22,6 +22,7 @@ var { computeAllProjectSessions } = require("./server-hub-sessions");
22
22
  var { resolveEffectiveProtocol } = require("./effective-protocol");
23
23
  var { createProjectAccess } = require("./project-access");
24
24
  var { checkWsOrigin } = require("./ws-origin");
25
+ var sessionReclaim = require("./session-reclaim");
25
26
 
26
27
  var https = require("https");
27
28
  var pkg = require("../package.json");
@@ -289,6 +290,7 @@ function createServer(opts) {
289
290
  var onShutdown = opts.onShutdown || null;
290
291
  var onRestart = opts.onRestart || null;
291
292
  var onRestartForBuildUpdate = opts.onRestartForBuildUpdate || null;
293
+ var onGetBuildUpdateDiagnostic = opts.onGetBuildUpdateDiagnostic || null;
292
294
  var onSetUpdateChannel = opts.onSetUpdateChannel || null;
293
295
  var onSetProjectVisibility = opts.onSetProjectVisibility || null;
294
296
  var onSetProjectAllowedUsers = opts.onSetProjectAllowedUsers || null;
@@ -395,9 +397,15 @@ function createServer(opts) {
395
397
  // emitted — the trigger carries its own notification channel (e.g. ntfy).
396
398
  var { attachExternalTrigger } = require("./project-external-trigger");
397
399
  var { EXTERNAL_TRIGGERS_DIR } = require("./config");
400
+ // One implementation for the file drop and the daemon IPC verbs (open-session,
401
+ // send-input).
402
+ var _sessionInput = require("./session-input").createSessionInput({
403
+ getProject: function (slug) { return projects.get(slug) || null; },
404
+ });
398
405
  var _externalTrigger = attachExternalTrigger({
399
406
  triggersDir: EXTERNAL_TRIGGERS_DIR,
400
407
  getProject: function (slug) { return projects.get(slug) || null; },
408
+ sessionInput: _sessionInput,
401
409
  });
402
410
  _externalTrigger.startWatcher();
403
411
 
@@ -1483,6 +1491,7 @@ function createServer(opts) {
1483
1491
  onShutdown: onShutdown,
1484
1492
  onRestart: onRestart,
1485
1493
  onRestartForBuildUpdate: onRestartForBuildUpdate,
1494
+ onGetBuildUpdateDiagnostic: onGetBuildUpdateDiagnostic,
1486
1495
  onDmMessage: handleDmMessage,
1487
1496
  broadcastAll: broadcastAll,
1488
1497
  notificationsModule: _globalNotifications,
@@ -1518,7 +1527,8 @@ function createServer(opts) {
1518
1527
  function removeProject(slug) {
1519
1528
  var ctx = projects.get(slug);
1520
1529
  if (!ctx) return false;
1521
- var shutdownResult = ctx.destroy();
1530
+ // A deliberate removal: its sessions are not recorded as resumable.
1531
+ var shutdownResult = ctx.destroy({ reason: "project_removed" });
1522
1532
  projects.delete(slug);
1523
1533
  if (shutdownResult && typeof shutdownResult.catch === "function") {
1524
1534
  shutdownResult.catch(function(err) {
@@ -1742,9 +1752,10 @@ function createServer(opts) {
1742
1752
  function destroyAll() {
1743
1753
  _externalTrigger.stopWatcher();
1744
1754
  var shutdowns = [];
1755
+ var tally = sessionReclaim.createShutdownTally();
1745
1756
  projects.forEach(function (ctx, slug) {
1746
1757
  console.log("[server] Destroying project:", slug);
1747
- var result = ctx.destroy();
1758
+ var result = ctx.destroy({ reason: sessionReclaim.RESTART_REASON, tally: tally });
1748
1759
  if (result && typeof result.then === "function") {
1749
1760
  shutdowns.push(result.catch(function(err) {
1750
1761
  console.error("[server] Project destroy failed for " + slug + ":", err && err.message ? err.message : err);
@@ -1753,6 +1764,7 @@ function createServer(opts) {
1753
1764
  }
1754
1765
  });
1755
1766
  projects.clear();
1767
+ sessionReclaim.logShutdownSummary(tally);
1756
1768
  return Promise.all(shutdowns);
1757
1769
  }
1758
1770
 
@@ -1822,6 +1834,7 @@ function createServer(opts) {
1822
1834
  clearRecovery: auth.clearRecovery,
1823
1835
  broadcastAll: broadcastAll,
1824
1836
  forEachProject: forEachProject,
1837
+ sessionInput: _sessionInput,
1825
1838
  destroyProject: removeProject,
1826
1839
  destroyAll: destroyAll,
1827
1840
  // Drain controller injection (lr-6b30).
@@ -0,0 +1,33 @@
1
+ // session-id.js - the one place a session id is checked before it becomes part
2
+ // of a file path. An id arrives from outside (a browser message, an injected
3
+ // input), so it is validated before any filesystem use and every path built from
4
+ // it is checked to stay inside the directory it is meant for.
5
+
6
+ var path = require("path");
7
+
8
+ // Letters, digits, "_" and "-", not starting with a separator-like character.
9
+ var SAFE_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
10
+
11
+ function isSafeSessionId(id) {
12
+ return typeof id === "string" && SAFE_SESSION_ID.test(id);
13
+ }
14
+
15
+ // Returns <dir>/<id><ext>, throwing when the id is unsafe or the resolved path
16
+ // is not inside dir. The containment check is separate from the allowlist so a
17
+ // later loosening of the allowlist cannot reopen traversal.
18
+ function sessionPathWithin(dir, id, ext) {
19
+ if (!isSafeSessionId(id)) {
20
+ throw new Error("unsafe session id " + JSON.stringify(String(id).slice(0, 64)));
21
+ }
22
+ var root = path.resolve(dir);
23
+ var full = path.resolve(root, id + ext);
24
+ if (full.indexOf(root + path.sep) !== 0) {
25
+ throw new Error("session path escapes its directory: " + JSON.stringify(String(id).slice(0, 64)));
26
+ }
27
+ return full;
28
+ }
29
+
30
+ module.exports = {
31
+ isSafeSessionId: isSafeSessionId,
32
+ sessionPathWithin: sessionPathWithin,
33
+ };
@@ -0,0 +1,32 @@
1
+ // session-input-ipc.js - the daemon IPC side of open-session and send-input:
2
+ // which fields of an IPC message reach lib/session-input.js. Kept out of
3
+ // daemon.js so the handler a CLI call reaches can be exercised without booting
4
+ // the daemon.
5
+
6
+ // Handles one IPC message with a session-input instance. Returns the result
7
+ // (or a Promise of it), or undefined when msg.cmd is not a session command.
8
+ function handleSessionCommand(sessionInput, msg) {
9
+ if (msg.cmd === "open_session") {
10
+ return sessionInput.openSession({
11
+ projectSlug: msg.projectSlug,
12
+ prompt: msg.prompt,
13
+ contextNote: msg.contextNote,
14
+ vendor: msg.vendor,
15
+ agentName: msg.agentName,
16
+ sessionVisibility: msg.sessionVisibility,
17
+ initiator: msg.initiator,
18
+ });
19
+ }
20
+ if (msg.cmd === "send_session_input") {
21
+ return sessionInput.sendInput({
22
+ projectSlug: msg.projectSlug,
23
+ sessionId: msg.sessionId,
24
+ prompt: msg.prompt,
25
+ contextNote: msg.contextNote,
26
+ initiator: msg.initiator,
27
+ });
28
+ }
29
+ return undefined;
30
+ }
31
+
32
+ module.exports = { handleSessionCommand: handleSessionCommand };