claude-code-session-manager 0.142.0 → 0.144.0

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 (162) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +22 -107
  3. package/dist/assets/AppSettings-Z68gQiVE.js +2 -0
  4. package/dist/assets/{History-DpZuJXi1.js → History-C3E6y_7t.js} +2 -2
  5. package/dist/assets/HomeClaudeConfig-Yd1vXzBn.js +5 -0
  6. package/dist/assets/{Panel-BjdJjhqt.js → Panel-CnfWs46Z.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-CP0Wsg-H.js +26 -0
  8. package/dist/assets/Scheduler-D8un7N3B.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-Cqyu4mef.js → SkillReferenceGraph-DRtZV1Al.js} +1 -1
  10. package/dist/assets/{Skills-vv0noNVI.js → Skills-Bg5O2Hyn.js} +23 -23
  11. package/dist/assets/{TiptapBody-CXi8Pvut.js → TiptapBody-BdzoBmqu.js} +27 -27
  12. package/dist/assets/{Toggle-CiYCWLjh.js → Toggle-Dt5K1OXt.js} +1 -1
  13. package/dist/assets/{VoiceButton-4NKKd1sC.js → VoiceButton-CTLyRgdF.js} +1 -1
  14. package/dist/assets/{historyTotals-DDunb8Ch.js → historyTotals-B2_KWBga.js} +1 -1
  15. package/dist/assets/{index-Cn5E9958.js → index-446b69rr.js} +715 -714
  16. package/dist/assets/{index-DVHIHoJf.css → index-BJ5TJvmz.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +438 -435
  20. package/package.json +6 -4
  21. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  23. package/plugins/session-manager-dev/skills/develop/SKILL.md +23 -16
  24. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +16 -2
  25. package/plugins/session-manager-dev/skills/maintaining-md-network/weekly-consolidation.md +87 -0
  26. package/scripts/README.md +1 -0
  27. package/scripts/scheduler-mcp-server.cjs +381 -6
  28. package/src/main/adminRouteRegistry.cjs +16 -0
  29. package/src/main/agentLibrary.cjs +60 -11
  30. package/src/main/agentsIpc.cjs +19 -0
  31. package/src/main/build-info.json +4 -4
  32. package/src/main/chatRunner.cjs +214 -7
  33. package/src/main/config.cjs +5 -1
  34. package/src/main/health.cjs +92 -14
  35. package/src/main/index.cjs +16 -4
  36. package/src/main/ipcSchemas.cjs +61 -1
  37. package/src/main/lib/claude/agentArmory.cjs +128 -0
  38. package/src/main/lib/claude/agentModelResolve.cjs +3 -2
  39. package/src/main/lib/claude/agentSnapshot.cjs +24 -3
  40. package/src/main/lib/claude/builtinTools.cjs +110 -0
  41. package/src/main/lib/claude/environmentProfiles.cjs +1 -1
  42. package/src/main/lib/claude/headlessMcpServers.cjs +138 -0
  43. package/src/main/lib/claude/jobSandboxPolicy.cjs +8 -2
  44. package/src/main/lib/claude/personaToolScope.cjs +77 -6
  45. package/src/main/lib/demo-video-kit/cast.md +10 -1
  46. package/src/main/lib/demo-video-kit/character.cjs +77 -21
  47. package/src/main/lib/demo-video-kit/kind-tiktok.md +5 -1
  48. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  49. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  50. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  51. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  52. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  53. package/src/main/lib/epic/artifactRetention.cjs +55 -9
  54. package/src/main/lib/epic/artifactStore.cjs +78 -35
  55. package/src/main/lib/epic/delegationReadiness.cjs +10 -3
  56. package/src/main/lib/epic/epicDepsSync.cjs +66 -0
  57. package/src/main/lib/epic/epicEventLog.cjs +45 -1
  58. package/src/main/lib/epic/epicOutsideRead.cjs +38 -1
  59. package/src/main/lib/epic/epicSettle.cjs +48 -4
  60. package/src/main/lib/epic/epicSpawnPlan.cjs +3 -1
  61. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  62. package/src/main/lib/epic/epicValidationHook.cjs +22 -3
  63. package/src/main/lib/epic/planReviewInput.cjs +123 -0
  64. package/src/main/lib/epic/restorableSessions.cjs +1 -0
  65. package/src/main/lib/epic/scriptStartedBy.cjs +71 -0
  66. package/src/main/lib/externalContract.cjs +24 -1
  67. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  68. package/src/main/lib/feedback-remote/createdProjects.cjs +291 -0
  69. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +24 -2
  70. package/src/main/lib/feedback-remote/crossProjectReply.cjs +96 -8
  71. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +54 -3
  72. package/src/main/lib/feedback-remote/pendingReplies.cjs +22 -0
  73. package/src/main/lib/feedback-remote/projectCreate.cjs +415 -0
  74. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +94 -4
  75. package/src/main/lib/feedback-remote/replyClaims.cjs +168 -0
  76. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +29 -1
  77. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +43 -2
  78. package/src/main/lib/feedback-remote/servicePairLocalRoutes.cjs +91 -0
  79. package/src/main/lib/feedback-remote/servicePairings.cjs +47 -7
  80. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +99 -1
  81. package/src/main/lib/git/gitWorktree.cjs +8 -0
  82. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  83. package/src/main/lib/git/worktreeDeps.cjs +119 -10
  84. package/src/main/lib/mcpToolCatalog.cjs +144 -12
  85. package/src/main/lib/mcpToolsProbe.cjs +19 -2
  86. package/src/main/lib/opsOwnership.cjs +113 -28
  87. package/src/main/lib/packs/packCatalog.cjs +98 -5
  88. package/src/main/lib/persona-macro/agentPersonaSchema.cjs +6 -0
  89. package/src/main/lib/persona-macro/builtinMacros.cjs +6 -4
  90. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +9 -0
  91. package/src/main/lib/persona-macro/personaLoadout.cjs +58 -0
  92. package/src/main/lib/persona-macro/personaMerge.cjs +11 -3
  93. package/src/main/lib/persona-macro/personaUpgrade.cjs +96 -0
  94. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +1 -1
  95. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +140 -0
  96. package/src/main/lib/prd/prdCreate.cjs +395 -229
  97. package/src/main/lib/prd/prdCriteria.cjs +7 -4
  98. package/src/main/lib/prd/prdFrontmatter.cjs +5 -2
  99. package/src/main/lib/prd/prdMcpReachWarnings.cjs +44 -0
  100. package/src/main/lib/prd/prdSandboxWarnings.cjs +49 -0
  101. package/src/main/lib/process/peerChatSession.cjs +165 -0
  102. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  103. package/src/main/lib/project-pages/videoScriptPress.cjs +266 -0
  104. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +371 -0
  105. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  106. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  107. package/src/main/lib/promptSessionSchema.cjs +2 -0
  108. package/src/main/lib/scheduler/baselineGate.cjs +31 -2
  109. package/src/main/lib/scheduler/criteriaChecks.cjs +164 -20
  110. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  111. package/src/main/lib/scheduler/jobMemoryStats.cjs +13 -2
  112. package/src/main/lib/scheduler/planRecordHarvest.cjs +215 -55
  113. package/src/main/lib/scheduler/planReleaseRoute.cjs +110 -0
  114. package/src/main/lib/scheduler/planReviewSchema.cjs +182 -0
  115. package/src/main/lib/scheduler/planReviewStats.cjs +63 -0
  116. package/src/main/lib/scheduler/planReviewStore.cjs +128 -0
  117. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +60 -2
  118. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  119. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  120. package/src/main/lib/scheduler/sandboxEnvironmentLimit.cjs +141 -0
  121. package/src/main/lib/scheduler/scheduleJobSchema.cjs +15 -0
  122. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  123. package/src/main/lib/scheduler/slotsRoute.cjs +101 -87
  124. package/src/main/lib/scheduler/upgradeDrain.cjs +32 -5
  125. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  126. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +28 -7
  127. package/src/main/lib/tasks/memoryConsolidation.cjs +123 -39
  128. package/src/main/lib/tasks/mitigationReview.cjs +21 -1
  129. package/src/main/lib/tasks/taskAdminRoutes.cjs +104 -17
  130. package/src/main/lib/tasks/taskLedger.cjs +2 -2
  131. package/src/main/lib/tasks/taskRun.cjs +3 -1
  132. package/src/main/lib/tasks/weeklyConsolidationInputs.cjs +178 -0
  133. package/src/main/lib/telemetry/auditEvents.cjs +21 -24
  134. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  135. package/src/main/lib/util/atomicFs.cjs +2 -2
  136. package/src/main/projectPages.cjs +22 -14
  137. package/src/main/promptSessionEvents.cjs +16 -1
  138. package/src/main/pty.cjs +14 -2
  139. package/src/main/queueOps.cjs +1 -1
  140. package/src/main/runVerify.cjs +4 -3
  141. package/src/main/scheduler/planReviewHold.cjs +140 -0
  142. package/src/main/scheduler/prdParser.cjs +1 -0
  143. package/src/main/scheduler/reviewLadder.cjs +2 -0
  144. package/src/main/scheduler/utilizationHold.cjs +101 -6
  145. package/src/main/scheduler.cjs +1055 -107
  146. package/src/main/seedAgentPersonas.cjs +11 -6
  147. package/src/main/seedStatus.cjs +1 -1
  148. package/src/main/templates/PRD_AUTHORING.md +22 -2
  149. package/src/main/webRemote.cjs +47 -7
  150. package/src/preload/api.d.ts +118 -2
  151. package/src/preload/apiSurface.json +42 -0
  152. package/src/preload/index.cjs +11 -0
  153. package/src/seed/agents/architect.md +28 -43
  154. package/src/seed/agents/demo-video-builder.md +15 -8
  155. package/src/seed/agents/dev-lead.md +3 -1
  156. package/src/seed/agents/md-network-curator.md +27 -0
  157. package/src/seed/agents/plan-reviewer.md +47 -0
  158. package/src/seed/agents/validator.md +21 -19
  159. package/dist/assets/AppSettings-BcZgIvvY.js +0 -2
  160. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +0 -3
  161. package/dist/assets/ProjectClaudeConfig-BTClYV6i.js +0 -26
  162. package/dist/assets/Scheduler-DPobKx1Z.js +0 -16
@@ -22,11 +22,12 @@ const { evaluateDispatchLiveness } = require('./lib/scheduler/watchdogHelpers.cj
22
22
  const { computeStallSummary, computeDepHistorySatisfaction, FAILURE_STREAK_ESCALATION_MS } = require('./scheduler/budget.cjs');
23
23
  const { classifyQueueStarvation, launchBlockedSlugs, STARVE_ESCALATION_MS } = require('./scheduler/starvation.cjs');
24
24
  const { REVERIFY_INTERVAL_MS } = require('./scheduler/reviewLadder.cjs');
25
+ const { proRatedThreshold } = require('./scheduler/utilizationHold.cjs');
25
26
  const { makeDepResolver } = require('./lib/prd/depSlugResolve.cjs');
26
27
  const { findStarvedProjects, findUnresolvableDepRoots, DEFAULT_PROJECT_CWD, DEP_HISTORY_FAIL_OPEN } = require('./lib/scheduler/schedulerBatch.cjs');
27
28
  const { auditLogPath, readTail } = require('./lib/telemetry/auditLog.cjs');
28
29
  const { checkMainDependencyHealth } = require('./lib/git/depHealth.cjs');
29
- const { findTrackedRuntimeState } = require('./lib/git/runtimeStateUntrack.cjs');
30
+ const { findTrackedRuntimeState, findVisibleRuntimeState } = require('./lib/git/runtimeStateUntrack.cjs');
30
31
  const { resolveBuildIdentity } = require('./lib/buildIdentity.cjs');
31
32
  const { computeReport, isRetentionEnabled, liveKeysFromJobs, resolveRetentionConfig } = require('./lib/scheduler/runLogRetention.cjs');
32
33
  const { allProjectCwds } = require('./lib/activeSessions.cjs');
@@ -154,7 +155,16 @@ function evaluateTickLiveness(queueState, heartbeat, now, runningCount) {
154
155
  oldestPendingSlug: pending[0]?.slug,
155
156
  };
156
157
  }
157
- if (typeof heartbeat.utilization === 'number' && heartbeat.utilization >= config.utilizationThreshold) {
158
+ // Same pro-rated 'pause above' the scheduler's own hold reads
159
+ // (scheduler/utilizationHold.cjs) — a flat cap here would call a
160
+ // dispatching queue held, or a held one stalled.
161
+ const effectiveThreshold = proRatedThreshold({
162
+ base: config.utilizationThreshold,
163
+ window: heartbeat.utilizationWindow,
164
+ resetsAt: heartbeat.nextReset,
165
+ now,
166
+ });
167
+ if (typeof heartbeat.utilization === 'number' && heartbeat.utilization >= effectiveThreshold) {
158
168
  // A hold on the binding window is benign only if it self-heals soon
159
169
  // (reset within 5h). A weekly hold, or an unknown reset horizon, can
160
170
  // last days — surface it rather than reading GREEN.
@@ -816,6 +826,71 @@ function evaluateMainDepLinks(results = []) {
816
826
  return { component: { ok: true, checked: list.length, broken }, issues };
817
827
  }
818
828
 
829
+ /**
830
+ * evaluateVisibleRuntimeState(results) → { component, issues }
831
+ *
832
+ * Pure over `Array<{ cwd, count }>` (count = findVisibleRuntimeState(cwd).length).
833
+ * One warn issue per project whose runtime files git can see — a namespace
834
+ * missing its self-ignore. Non-critical: component.ok is always true.
835
+ */
836
+ function evaluateVisibleRuntimeState(results = []) {
837
+ const list = Array.isArray(results) ? results : [];
838
+ const projects = list
839
+ .filter((r) => r && Number.isFinite(r.count) && r.count > 0)
840
+ .map(({ cwd, count }) => ({ cwd, count }));
841
+ if (projects.length === 0) return { component: { ok: true }, issues: [] };
842
+ return {
843
+ component: { ok: true, warn: true, projects },
844
+ issues: projects.map((p) => `warn: ${p.cwd} has ${p.count} Session Manager runtime file(s) git can see (missing self-ignore)`),
845
+ };
846
+ }
847
+
848
+ /**
849
+ * collectRuntimeStateHealth(roots, { findTracked, findVisible })
850
+ * → Promise<{ components: { tracked_runtime_state, visible_runtime_state }, issues }>
851
+ *
852
+ * Runs both runtime-state checks over `roots` (sequentially). Each side has its
853
+ * own failure handling: a throw on one side sets only that component to
854
+ * { ok: true, error } and adds no issues for it — the other side still reports.
855
+ * Non-critical: neither component ever sets ok=false.
856
+ */
857
+ async function collectRuntimeStateHealth(roots = [], { findTracked, findVisible } = {}) {
858
+ const list = Array.isArray(roots) ? roots : [];
859
+ const components = {};
860
+ const visibleIssues = [];
861
+ const trackedIssues = [];
862
+
863
+ try {
864
+ const visible = [];
865
+ for (const cwd of list) {
866
+ visible.push({ cwd, count: (await findVisible(cwd)).length });
867
+ }
868
+ const visibleEval = evaluateVisibleRuntimeState(visible);
869
+ components.visible_runtime_state = visibleEval.component;
870
+ visibleIssues.push(...visibleEval.issues);
871
+ } catch (e) {
872
+ components.visible_runtime_state = { ok: true, error: e && e.message };
873
+ }
874
+
875
+ try {
876
+ const hits = [];
877
+ for (const cwd of list) {
878
+ const n = (await findTracked(cwd)).length;
879
+ if (n > 0) hits.push({ cwd, count: n });
880
+ }
881
+ components.tracked_runtime_state = hits.length === 0
882
+ ? { ok: true }
883
+ : { ok: true, warn: true, projects: hits };
884
+ for (const h of hits) {
885
+ trackedIssues.push(`warn: ${h.cwd} tracks ${h.count} Session Manager runtime-state file(s) in git — untrack from its main checkout`);
886
+ }
887
+ } catch (e) {
888
+ components.tracked_runtime_state = { ok: true, error: e && e.message };
889
+ }
890
+
891
+ return { components, issues: [...visibleIssues, ...trackedIssues] };
892
+ }
893
+
819
894
  /**
820
895
  * evaluateCredentialHealth({ credState, now }) → { component, issues }
821
896
  *
@@ -1486,21 +1561,22 @@ async function check(opts = {}) {
1486
1561
  // 6.76. Tracked runtime state: projects that committed Session Manager
1487
1562
  // runtime namespaces. Warning only (never flips ok) — untrack via
1488
1563
  // runtimeStateUntrack.untrackRuntimeState from the project's main checkout.
1564
+ // Each check fails on its own inside collectRuntimeStateHealth; only a
1565
+ // failure computing the roots blanks both.
1566
+ let runtimeRoots = null;
1489
1567
  try {
1490
- const roots = [...new Set(allProjectCwds())].slice(0, 100).filter((cwd) => fs.existsSync(cwd));
1491
- const hits = [];
1492
- for (const cwd of roots) {
1493
- const n = (await findTrackedRuntimeState(cwd)).length;
1494
- if (n > 0) hits.push({ cwd, count: n });
1495
- }
1496
- status.components.tracked_runtime_state = hits.length === 0
1497
- ? { ok: true }
1498
- : { ok: true, warn: true, projects: hits };
1499
- for (const h of hits) {
1500
- status.issues.push(`warn: ${h.cwd} tracks ${h.count} Session Manager runtime-state file(s) in git — untrack from its main checkout`);
1501
- }
1568
+ runtimeRoots = [...new Set(allProjectCwds())].slice(0, 100).filter((cwd) => fs.existsSync(cwd));
1502
1569
  } catch (e) {
1503
1570
  status.components.tracked_runtime_state = { ok: true, error: e.message };
1571
+ status.components.visible_runtime_state = { ok: true, error: e.message };
1572
+ }
1573
+ if (runtimeRoots) {
1574
+ const runtime = await collectRuntimeStateHealth(runtimeRoots, {
1575
+ findTracked: findTrackedRuntimeState,
1576
+ findVisible: findVisibleRuntimeState,
1577
+ });
1578
+ Object.assign(status.components, runtime.components);
1579
+ status.issues.push(...runtime.issues);
1504
1580
  }
1505
1581
 
1506
1582
  // 6.8. Credential health (informational-but-loud): is the Claude OAuth token
@@ -1595,6 +1671,8 @@ module.exports = {
1595
1671
  evaluateStarveEscalationHealth,
1596
1672
  evaluateBuildFreshness,
1597
1673
  evaluateMainDepLinks,
1674
+ evaluateVisibleRuntimeState,
1675
+ collectRuntimeStateHealth,
1598
1676
  WORKTREE_SAFETY_PATHS,
1599
1677
  latestStarveEscalationReasons,
1600
1678
  DISPATCH_STALL_THRESHOLD_MS,
@@ -68,9 +68,6 @@ const voiceHotkey = require('./voiceHotkey.cjs');
68
68
  const scheduler = require('./scheduler.cjs');
69
69
  const { createAdminHttp } = require('./lib/feedback-remote/localAdminHttp.cjs');
70
70
  const prdCreate = require('./lib/prd/prdCreate.cjs');
71
- const prdAdminRoutes = require('./lib/prd/prdAdminRoutes.cjs');
72
- const projectHomeAdminRoutes = require('./lib/feedback-remote/projectHomeAdminRoutes.cjs');
73
- const macroAdminRoutes = require('./lib/feedback-remote/macroAdminRoutes.cjs');
74
71
  const { smfileResponseHeaders, shouldBlockFrameNavigation, smfileUrlToPath } = require('./lib/smfileHeaders.cjs');
75
72
  const { buildMediaResponse } = require('./lib/util/smfileRange.cjs');
76
73
  const { appendAuditEvent } = require('./lib/telemetry/auditLog.cjs');
@@ -92,12 +89,18 @@ const { resolveProjectContext } = require('./lib/projectRootResolve.cjs');
92
89
  const upgradeDrain = require('./lib/scheduler/upgradeDrain.cjs');
93
90
  const { writeGuardShims } = require('./lib/guardShims.cjs');
94
91
  const { sendIfAlive } = require('./lib/sendToRenderer.cjs');
95
- const crossProjectFeedback = require('./lib/feedback-remote/crossProjectFeedback.cjs');
96
92
  const adminHttp = createAdminHttp();
97
93
  require('./adminRouteRegistry.cjs').registerAppAdminRoutes(adminHttp, {
98
94
  onMacrosChanged: () => broadcastMacrosChanged(),
99
95
  onNeedsYouChanged: broadcastNeedsYouChanged,
100
96
  });
97
+ // Event-driven epic_state_changed (lib/epic/epicStateEmitter.cjs): chat turns poke it,
98
+ // and its job rows wait for any in-flight queue write before a recompute reads them.
99
+ {
100
+ const epicStateEmitter = require('./lib/epic/epicStateEmitter.cjs');
101
+ epicStateEmitter.configureEpicStateEmitter({ isTabBusy: chatRunner.isTabBusy, listJobs: () => scheduler.remote.listJobRowsSettled() });
102
+ epicStateEmitter.startEpicStateEmitter();
103
+ }
101
104
  // Outside apps' "Needs you" items (lib/feedback-remote/needsYouStore.cjs); changes broadcast `needsYou:changed`.
102
105
  function broadcastNeedsYouChanged() {
103
106
  sendIfAlive(mainWindow, 'needsYou:changed', {});
@@ -390,6 +393,10 @@ function relaunchViaNpx() {
390
393
  async function rebootApp({ force = false } = {}) {
391
394
  if (force) {
392
395
  logReboot('force reboot requested — immediate, not draining');
396
+ // This reboot IS the restart any pending request asked for; never leave one
397
+ // behind for the next boot to drain and restart a second time.
398
+ const retired = upgradeDrain.retireRestartRequestBestEffort();
399
+ if (!retired.ok) logReboot(`could not retire restart request (continuing): ${retired.error}`);
393
400
  return performReboot();
394
401
  }
395
402
  const request = upgradeDrain.requestRestart({ reason: 'user-reboot', requestedBy: 'user' });
@@ -629,6 +636,11 @@ require('./lib/persona-macro/macroJobIpc.cjs').registerMacroJobIpc(ipcMain, macr
629
636
  // Project Video review step: list + human decide (approve / ask for changes). Same deps
630
637
  // as macroJobIpc — a decision dispatches through runToolJob. Renderer IPC only.
631
638
  require('./lib/project-pages/videoReviewIpc.cjs').registerVideoReviewIpc(ipcMain, macroJobIpcDeps);
639
+ // 'Scripts may run Demo Video' switch: get + the human-click set (by.via 'ui'). Renderer IPC only.
640
+ require('./lib/project-pages/videoScriptSwitchIpc.cjs').registerVideoScriptSwitchIpc(ipcMain, {
641
+ schemas,
642
+ validatePath: require('./config.cjs').validatePath,
643
+ });
632
644
  // Voices screen: list/preview + the ONLY writer of voice approvals and deletions.
633
645
  // Renderer IPC only — no admin route or MCP tool approves, changes or deletes a voice.
634
646
  require('./lib/project-pages/voicesIpc.cjs').registerVoicesIpc(ipcMain, {
@@ -838,8 +838,48 @@ const setSessionSlotsSchema = z.object({
838
838
  // only after a production incident (see scheduleJobSchema.cjs's header).
839
839
  // Full field-level rules live in lib/persona-macro/agentPersonaSchema.cjs, mirroring
840
840
  // AgentPersonaSaveInput (src/preload/api.d.ts) field-for-field.
841
- const agentsSavePersona = AgentPersonaSaveSchema;
841
+ // A project override (projectCwd set) may also carry the gear keys, validated with the persona
842
+ // frontmatter rules (saveOverlay re-checks the serialized lines). AgentPersonaSaveSchema is
843
+ // .strict(), so the gear keys are split off, validated here, and merged back.
844
+ const AgentOverlayGearSchema = z.object({
845
+ loadout: z.enum(['undecided', 'bare', 'equipped', 'unbound']).optional(),
846
+ mcpServers: z.array(z.string().trim().min(1).max(200)).max(64).optional(),
847
+ packs: z.array(z.string().trim().min(1).max(200)).max(64).optional(),
848
+ environment: z.string().trim().regex(/^[a-z0-9][a-z0-9-]*$/, 'environment must be a lowercase, hyphenated profile name').optional(),
849
+ }).strict();
850
+ const GEAR_KEYS = ['loadout', 'mcpServers', 'packs', 'environment'];
851
+ const agentsSavePersona = z.record(z.string(), z.unknown()).transform((raw, ctx) => {
852
+ /** @type {Record<string, unknown>} */
853
+ const gear = {};
854
+ const rest = { ...raw };
855
+ const hasCwd = rest.projectCwd !== undefined;
856
+ for (const k of GEAR_KEYS) {
857
+ if (k in rest) { gear[k] = rest[k]; delete rest[k]; }
858
+ }
859
+ // Global saves take the gear keys via AgentPersonaSaveSchema; 'undecided' is overlay-only.
860
+ if (!hasCwd && gear.loadout === 'undecided') {
861
+ ctx.addIssue({ code: 'custom', path: ['loadout'], message: "loadout 'undecided' is accepted only on a project override (projectCwd set)" });
862
+ return z.NEVER;
863
+ }
864
+ if (!hasCwd) {
865
+ const base = AgentPersonaSaveSchema.safeParse({ ...rest, ...gear });
866
+ if (!base.success) {
867
+ for (const i of base.error.issues) ctx.addIssue({ code: 'custom', path: i.path, message: i.message });
868
+ return z.NEVER;
869
+ }
870
+ return base.data;
871
+ }
872
+ const base = AgentPersonaSaveSchema.safeParse(rest);
873
+ const g = AgentOverlayGearSchema.safeParse(gear);
874
+ if (!base.success || !g.success) {
875
+ for (const r of [base, g]) if (!r.success) for (const i of r.error.issues) ctx.addIssue({ code: 'custom', path: i.path, message: i.message });
876
+ return z.NEVER;
877
+ }
878
+ return { ...base.data, ...g.data };
879
+ });
842
880
  // agents:remove-override — an OPEN project's override, keyed by its absolute cwd (never a folder name).
881
+ const agentsTakeBundledPersona = z.object({ name: PersonaNameSchema }).strict();
882
+ const agentsDismissPersonaUpgrade = z.object({ name: PersonaNameSchema, bundledVersion: z.number().int().min(1) }).strict();
843
883
  const agentsRemoveOverride = z.object({ name: PersonaNameSchema, projectCwd: ProjectCwdSchema }).strict();
844
884
  // agents:delete-persona — a kebab-case name only; `.strict()` also bars deletePersona's injectable `globalDir`.
845
885
  const agentsDeletePersona = z.object({ name: PersonaNameSchema }).strict();
@@ -1101,6 +1141,11 @@ const agentsResolveEpicModel = z.object({
1101
1141
  }).strict();
1102
1142
  const agentsResolveEpicEffort = agentsResolveEpicModel;
1103
1143
 
1144
+ // agents:armory — gear read model; cwd optional (global gear only when absent).
1145
+ const agentsArmory = z.object({
1146
+ cwd: z.string().min(1).max(4096).optional(),
1147
+ }).strict();
1148
+
1104
1149
  // ──────────────────────────────────────────── Project Pages (PRD 932)
1105
1150
  // Same validation split as projectBriefCwd above: real path validation is
1106
1151
  // config.cjs's validatePath at first fs access in projectPages.cjs.
@@ -1152,6 +1197,10 @@ const projectVideosReviewDecide = z.object({
1152
1197
  note: z.string().max(2000).optional(),
1153
1198
  }).strict();
1154
1199
  const projectVideosReviewRetry = z.object({ cwd: z.string().min(1).max(4096), entryId }).strict();
1200
+ // 'Scripts may run Demo Video' switch (project-pages/videoScriptSwitchIpc.cjs): renderer IPC only,
1201
+ // the human-click writer (by.via 'ui').
1202
+ const videosScriptSwitchGet = z.object({ cwd: z.string().min(1).max(4096) }).strict();
1203
+ const videosScriptSwitchSet = z.object({ cwd: z.string().min(1).max(4096), enabled: z.boolean() }).strict();
1155
1204
  // Voices screen (project-pages/voicesIpc.cjs): renderer IPC only — the sole writer of
1156
1205
  // voice approvals and deletions. voiceId follows voiceLibrary.VOICE_ID_RE (voiceLibraryId, declared
1157
1206
  // above macrosDispatchJob); text is TEXT_MAX (300).
@@ -1449,6 +1498,11 @@ const chatExternalNewSessionResult = z.object({
1449
1498
  ok: z.boolean(),
1450
1499
  epicId: z.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*$/).optional(),
1451
1500
  error: z.string().max(500).optional(),
1501
+ // The background build the renderer queued for a scripted job press
1502
+ // (Demo Video): its Project Home entry id, slug and stage.
1503
+ entryId: entryId.optional(),
1504
+ slug: z.string().min(1).max(200).optional(),
1505
+ stage: z.enum(['review', 'final']).nullable().optional(),
1452
1506
  }).strict();
1453
1507
 
1454
1508
  // Phone drill-down reads. cwd is re-checked against the open tabs in
@@ -1509,6 +1563,7 @@ const webRemoteServicePairStart = z.object({
1509
1563
  name: z.string().min(1).max(64).regex(/^[^\r\n]+$/),
1510
1564
  homeCwd: z.string().min(1).max(4096),
1511
1565
  scope: z.array(z.string().min(1).max(64)).min(1).max(16),
1566
+ projectRoot: z.string().min(1).max(4096).optional(),
1512
1567
  }).strict();
1513
1568
  const webRemoteServiceConfirmSas = z.object({
1514
1569
  pairingId: z.string().regex(WEB_REMOTE_UUID_RE),
@@ -1989,6 +2044,8 @@ module.exports = {
1989
2044
  exchangesList,
1990
2045
  agentsSavePersona,
1991
2046
  agentsRemoveOverride,
2047
+ agentsTakeBundledPersona,
2048
+ agentsDismissPersonaUpgrade,
1992
2049
  agentsDeletePersona,
1993
2050
  claudeConfigRead,
1994
2051
  claudeConfigPatch,
@@ -2004,6 +2061,8 @@ module.exports = {
2004
2061
  projectVideosReviewList,
2005
2062
  projectVideosReviewDecide,
2006
2063
  projectVideosReviewRetry,
2064
+ videosScriptSwitchGet,
2065
+ videosScriptSwitchSet,
2007
2066
  voicesList,
2008
2067
  voicesPreview,
2009
2068
  voicesApprove,
@@ -2017,6 +2076,7 @@ module.exports = {
2017
2076
  modelsCatalog,
2018
2077
  agentsResolveEpicModel,
2019
2078
  agentsResolveEpicEffort,
2079
+ agentsArmory,
2020
2080
  delegationReadinessCwd,
2021
2081
  appCreateProjectFolder,
2022
2082
  telemetrySetConfig,
@@ -0,0 +1,128 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * agentArmory.cjs — the Armory read model: one pure aggregate of catalogs that
5
+ * already exist (built-in tools + bundled skills, configured MCP servers with
6
+ * their last-known tools, packs + loose skills, tool-risk marks). No registry
7
+ * file, no probes run here. Every source is injected (`deps`); a source that
8
+ * throws adds a message to `errors` and leaves its group empty. Never throws.
9
+ *
10
+ * Deps (all optional, default to the real modules):
11
+ * - getBuiltinTools() -> { tools, skills }
12
+ * - listPacks() -> { packs, errors } ; listUnpackedSkills() -> string[]
13
+ * - listMcpServers({ cwd }) -> [{ name, scope }] (same config reader as mcpToolsProbe)
14
+ * - getMcpProbe({ name, scope, cwd }) -> { ok, tools: (string|{name})[] } | null (last result only)
15
+ * - loadMarks({ cwd }) -> { system, project } risk-mark layers
16
+ * - listEnvironments() -> { name, summary }[] (default: built-in profiles of environmentProfiles.cjs)
17
+ * - bannedTools: string[] (the scheduler's HEADLESS_DISALLOWED_TOOLS, passed by the caller)
18
+ */
19
+
20
+ const os = require('node:os');
21
+ const path = require('node:path');
22
+
23
+ /** @param {unknown} e */
24
+ const msg = (e) => String((e && /** @type {Error} */ (e).message) || e);
25
+
26
+ /** Default probe source: the last checkConfiguredMcpServer result held in memory. */
27
+ function defaultGetMcpProbe({ name, scope }) {
28
+ return require('../mcpToolsProbe.cjs').lastProbe(scope, name);
29
+ }
30
+
31
+ /** Real MCP config reader: user ~/.claude.json + <cwd>/.mcp.json via claudeConfig (as mcpToolsProbe). */
32
+ async function defaultListMcpServers({ cwd }) {
33
+ const claudeConfig = require('../claudeConfig.cjs');
34
+ const out = [];
35
+ const user = await claudeConfig.read({ fileId: 'claudeJson', scope: 'user', home: os.homedir() });
36
+ for (const name of Object.keys((user.data && user.data.mcpServers) || {})) out.push({ name, scope: 'user' });
37
+ if (typeof cwd === 'string' && path.isAbsolute(cwd)) {
38
+ const proj = await claudeConfig.read({ fileId: 'mcpJson', scope: 'project', cwd });
39
+ for (const name of Object.keys((proj.data && proj.data.mcpServers) || {})) out.push({ name, scope: 'project' });
40
+ }
41
+ // Plugin-provided servers have no config file here; they appear once checked.
42
+ for (const e of require('../mcpToolsProbe.cjs').probedServers('plugin')) out.push({ name: e.name, scope: 'plugin' });
43
+ return out;
44
+ }
45
+
46
+ function defaultListEnvironments() {
47
+ const { BUILTIN_ENVIRONMENTS } = require('./environmentProfiles.cjs');
48
+ return Object.entries(BUILTIN_ENVIRONMENTS).map(([name, p]) => ({ name, summary: p.description }));
49
+ }
50
+
51
+ function defaultLoadMarks({ cwd }) {
52
+ const m = require('./toolRiskMarks.cjs');
53
+ return {
54
+ system: m.readMarksLayer(m.systemMarksPath(os.homedir())),
55
+ project: typeof cwd === 'string' && cwd ? m.readMarksLayer(m.projectMarksPath(cwd)) : null,
56
+ };
57
+ }
58
+
59
+ /**
60
+ * @param {{ cwd?: string, deps?: Record<string, any> }} [opts]
61
+ */
62
+ async function buildArmory({ cwd, deps } = {}) {
63
+ const d = deps || {};
64
+ /** @type {string[]} */ const errors = [];
65
+ const out = { builtins: [], bundledSkills: [], mcpServers: [], packs: [], unpackedSkills: [], environments: [], errors };
66
+
67
+ /** Run one source; on failure record and return the fallback. */
68
+ const guard = async (label, fn, fallback) => {
69
+ try { return await fn(); } catch (e) { errors.push(`${label}: ${msg(e)}`); return fallback; }
70
+ };
71
+
72
+ const banned = new Set(Array.isArray(d.bannedTools) ? d.bannedTools : []);
73
+ let floor = [];
74
+ try { floor = require('./personaToolScope.cjs').HEADLESS_TOOL_FLOOR; } catch (e) { errors.push(`toolFloor: ${msg(e)}`); }
75
+ const floorSet = new Set(floor);
76
+
77
+ const marks = await guard('toolRiskMarks', async () => (d.loadMarks || defaultLoadMarks)({ cwd }), null);
78
+ const isRisky = (tool) => {
79
+ if (!marks) return false;
80
+ try { return !!require('./toolRiskMarks.cjs').resolveMark({ tool }, marks); } catch { return false; }
81
+ };
82
+ const badgesFor = (name, { floorable = true } = {}) => {
83
+ /** @type {('risky'|'banned'|'floor')[]} */ const b = [];
84
+ if (isRisky(name)) b.push('risky');
85
+ if (banned.has(name)) b.push('banned');
86
+ if (floorable && floorSet.has(name)) b.push('floor');
87
+ return b;
88
+ };
89
+ const item = (name, opts) => ({ id: name, label: name, badges: badgesFor(name, opts) });
90
+
91
+ const builtin = await guard('builtinTools', async () => (d.getBuiltinTools || require('./builtinTools.cjs').getBuiltinTools)(), null);
92
+ if (builtin) {
93
+ out.builtins = (builtin.tools || []).map((t) => item(t));
94
+ out.bundledSkills = (builtin.skills || []).map((s) => item(s, { floorable: false }));
95
+ }
96
+
97
+ const packRes = await guard('packs', async () => (d.listPacks || require('../packs/packCatalog.cjs').listPacks)(), null);
98
+ if (packRes) {
99
+ out.packs = (packRes.packs || []).map((p) => ({
100
+ id: p.id, label: p.label || p.id, badges: [], skills: [...(p.skills || [])], source: p.source,
101
+ }));
102
+ for (const e of packRes.errors || []) errors.push(`packs: ${e.dir}: ${e.error}`);
103
+ }
104
+ out.unpackedSkills = await guard('unpackedSkills', async () => [...(d.listUnpackedSkills || require('../packs/packCatalog.cjs').listUnpackedSkills)()], []);
105
+
106
+ const servers = await guard('mcpServers', async () => (d.listMcpServers || defaultListMcpServers)({ cwd }), []);
107
+ for (const s of servers) {
108
+ let status = 'not-checked';
109
+ let tools = [];
110
+ try {
111
+ const probe = await (d.getMcpProbe || defaultGetMcpProbe)({ name: s.name, scope: s.scope, cwd });
112
+ if (probe && probe.ok === false) status = 'failing';
113
+ else if (probe && Array.isArray(probe.tools)) {
114
+ status = 'checked';
115
+ tools = probe.tools
116
+ .map((t) => (typeof t === 'string' ? t : t && t.name))
117
+ .filter((n) => typeof n === 'string' && n)
118
+ .map((n) => ({ id: `mcp__${s.name}__${n}`, label: n, badges: badgesFor(`mcp__${s.name}__${n}`, { floorable: false }) }));
119
+ }
120
+ } catch (e) { errors.push(`mcpProbe ${s.name}: ${msg(e)}`); }
121
+ out.mcpServers.push({ id: s.name, label: s.name, badges: [], tools, status, scope: s.scope });
122
+ }
123
+
124
+ out.environments = await guard('environments', async () => (d.listEnvironments || defaultListEnvironments)(), []);
125
+ return out;
126
+ }
127
+
128
+ module.exports = { buildArmory };
@@ -257,7 +257,7 @@ const DEFAULT_PRD_AGENT_TYPE = 'dev-lead';
257
257
  * read) and this module's frontmatter-stripped-body cap.
258
258
  *
259
259
  * @param {{ cwd: string, agentType: string|null, deps?: object }} opts
260
- * @returns {Promise<{ model: string|null, systemPrompt: string|null, personaPath: string|null, tools: string[]|null, refusal: null|{ code: 'persona_missing'|'persona_invalid', detail: string } }>}
260
+ * @returns {Promise<{ model: string|null, systemPrompt: string|null, personaPath: string|null, tools: string[]|null, loadout?: 'undecided'|'bare'|'equipped'|'unbound', refusal: null|{ code: 'persona_missing'|'persona_invalid', detail: string } }>}
261
261
  */
262
262
  async function resolvePrdPersonaForSpawn({ cwd, agentType, deps = {} } = {}) {
263
263
  const name = agentType || DEFAULT_PRD_AGENT_TYPE;
@@ -295,7 +295,8 @@ async function resolvePrdPersonaForSpawn({ cwd, agentType, deps = {} } = {}) {
295
295
  const systemPrompt = buildPersonaBodyText(body, persona.path, { uncapped });
296
296
  const parseTools = deps.parseTools || require('../../agentLibrary.cjs').parseTools;
297
297
  const list = parseTools(typeof fm.tools === 'string' ? fm.tools : '');
298
- return { model, systemPrompt, personaPath: persona.path, tools: list.length ? list : null, refusal: null };
298
+ const { loadoutState } = require('../persona-macro/personaLoadout.cjs');
299
+ return { model, systemPrompt, personaPath: persona.path, tools: list.length ? list : null, loadout: loadoutState(fm), refusal: null };
299
300
  } catch (err) {
300
301
  const msg = err && err.message ? err.message : String(err);
301
302
  return refuse('persona_invalid', `agentType '${name}' persona ${persona.path || '(unknown path)'} could not be parsed: ${msg}`, persona.path || null);
@@ -5,7 +5,7 @@
5
5
  * agent), stored locally and content-addressed.
6
6
  *
7
7
  * A snapshot freezes exactly the agent definition a run used:
8
- * { name, bodySha256, body, model, effort, tools, mcpServers, packs, seedVersion, environment }
8
+ * { name, bodySha256, body, model, effort, tools, mcpServers, packs, seedVersion, environment, gearBindsChat, loadout }
9
9
  * Its id is the sha256 of its canonical JSON (keys sorted at every depth), so
10
10
  * equal definitions share one id and any edit (body, model, tools, ...) mints
11
11
  * a new one. A resume can therefore re-run precisely the definition it pinned.
@@ -36,6 +36,7 @@ const crypto = require('node:crypto');
36
36
  const fsp = require('node:fs/promises');
37
37
  const { opsPath, assertOpsWrite } = require('../opsOwnership.cjs');
38
38
  const atomicFs = require('../util/atomicFs.cjs');
39
+ const { loadoutState } = require('../persona-macro/personaLoadout.cjs');
39
40
 
40
41
  const WRITER = 'agents';
41
42
  const ID_RE = /^[0-9a-f]{64}$/;
@@ -107,6 +108,23 @@ async function buildAgentSnapshot({ cwd, agentType, packs, deps = {} } = {}) {
107
108
  return { id: null, snapshot: null, refusal: { code: env.code, detail } };
108
109
  }
109
110
 
111
+ // Persona-declared capabilities (`mcpServers:` / `packs:`) are part of the snapshot, so every
112
+ // caller (epicMint, epicAgentRefresh, scheduler) records the same resolved set.
113
+ let declaredServers = [];
114
+ let declaredPacks = [];
115
+ if (fm) {
116
+ try {
117
+ const { parseCapabilityList } = require('../../agentLibrary.cjs');
118
+ declaredServers = parseCapabilityList(fm.mcpServers);
119
+ declaredPacks = parseCapabilityList(fm.packs);
120
+ } catch { /* no declared capabilities */ }
121
+ }
122
+ const mergedPacks = [];
123
+ for (const p of [...declaredPacks, ...(Array.isArray(packs) ? packs : [])]) {
124
+ const id = String(p);
125
+ if (!mergedPacks.includes(id)) mergedPacks.push(id);
126
+ }
127
+
110
128
  const body = resolved.systemPrompt || '';
111
129
  const tools = Array.isArray(resolved.tools) ? resolved.tools.map(String) : null;
112
130
  const snapshot = {
@@ -116,10 +134,13 @@ async function buildAgentSnapshot({ cwd, agentType, packs, deps = {} } = {}) {
116
134
  model: resolved.model || null,
117
135
  effort: effort || null,
118
136
  tools,
119
- mcpServers: mcpServersFromTools(tools),
120
- packs: Array.isArray(packs) ? packs.map(String) : [],
137
+ mcpServers: [...new Set([...declaredServers.map((d) => String(d).trim()).filter(Boolean), ...mcpServersFromTools(tools)])].sort(),
138
+ packs: mergedPacks,
121
139
  seedVersion,
122
140
  environment: { id: env.id, hash: env.hash },
141
+ // Gear applies to chat turns only for snapshots stamped true; older snapshots lack the key (falsy).
142
+ gearBindsChat: true,
143
+ loadout: loadoutState(fm),
123
144
  };
124
145
  return { id: snapshotId(snapshot), snapshot, refusal: null };
125
146
  }
@@ -0,0 +1,110 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * builtinTools.cjs — learns the claude CLI's real built-in tool and bundled-skill
5
+ * names from the stream-json `system`/`init` event of a minimal run. The init
6
+ * event is emitted before the first API call, so the child is killed on init and
7
+ * no model tokens are spent. Cached in memory per CLI version; any failure
8
+ * returns FALLBACK_TOOLS (source 'fallback') and never throws.
9
+ */
10
+
11
+ const os = require('node:os');
12
+ const { resolveClaudeBin, probeClaudeVersion } = require('./claudeBin.cjs');
13
+ const { killTree, detachedSpawnOpts } = require('../process/killTree.cjs');
14
+ const { cleanChildEnv } = require('../process/cleanEnv.cjs');
15
+
16
+ const FALLBACK_TOOLS = ['Read', 'Grep', 'Glob', 'Bash', 'Write', 'Edit', 'WebFetch', 'WebSearch', 'Task', 'Agent', 'Skill', 'NotebookEdit', 'TodoWrite'];
17
+ const PROBE_TIMEOUT_MS = 20_000;
18
+ const OUTPUT_CAP_BYTES = 2 * 1024 * 1024;
19
+
20
+ /** @type {Map<string, { tools: string[], skills: string[], source: 'cli' | 'fallback', cliVersion: string | null }>} */
21
+ const cache = new Map();
22
+
23
+ const strings = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string' && x) : []);
24
+
25
+ /** Probe argv: pinned model, no user MCP, no user/project/local settings or plugins. */
26
+ function probeArgs() {
27
+ return ['--model', 'haiku', '-p', 'hi', '--output-format', 'stream-json', '--verbose', '--strict-mcp-config', '--setting-sources', 'project'];
28
+ }
29
+
30
+ /**
31
+ * Spawn the probe; resolve with the parsed init event or null. Never rejects.
32
+ * @returns {Promise<Record<string, any> | null>}
33
+ */
34
+ function runProbe(spawn, claudeBin) {
35
+ return new Promise((resolve) => {
36
+ let child = null;
37
+ let settled = false;
38
+ let buf = '';
39
+ let bytes = 0;
40
+ let timer = null;
41
+ const finish = (value) => {
42
+ if (settled) return;
43
+ settled = true;
44
+ if (timer) clearTimeout(timer);
45
+ if (child && child.pid) { try { killTree(child.pid, 'SIGKILL'); } catch { /* */ } }
46
+ else if (child && typeof child.kill === 'function') { try { child.kill('SIGKILL'); } catch { /* */ } }
47
+ resolve(value);
48
+ };
49
+ const feed = (chunk) => {
50
+ if (settled) return;
51
+ bytes += chunk.length;
52
+ buf += chunk.toString();
53
+ let nl;
54
+ while ((nl = buf.indexOf('\n')) >= 0) {
55
+ const line = buf.slice(0, nl).trim();
56
+ buf = buf.slice(nl + 1);
57
+ if (!line) continue;
58
+ let evt;
59
+ try { evt = JSON.parse(line); } catch { return finish(null); }
60
+ if (evt && evt.type === 'system' && evt.subtype === 'init') return finish(evt);
61
+ }
62
+ if (bytes > OUTPUT_CAP_BYTES) finish(null);
63
+ };
64
+ try {
65
+ child = spawn(claudeBin, probeArgs(), {
66
+ cwd: os.tmpdir(),
67
+ env: cleanChildEnv(),
68
+ stdio: ['ignore', 'pipe', 'ignore'],
69
+ windowsHide: true,
70
+ ...detachedSpawnOpts(),
71
+ });
72
+ timer = setTimeout(() => finish(null), PROBE_TIMEOUT_MS);
73
+ if (child.stdout) child.stdout.on('data', feed);
74
+ child.on('error', () => finish(null));
75
+ child.on('close', () => finish(null));
76
+ } catch {
77
+ finish(null);
78
+ }
79
+ });
80
+ }
81
+
82
+ /**
83
+ * @param {{ spawn?: Function, claudeBin?: string, cliVersion?: string | null }} [opts]
84
+ * @returns {Promise<{ tools: string[], skills: string[], source: 'cli' | 'fallback', cliVersion: string | null }>}
85
+ */
86
+ async function getBuiltinTools({ spawn, claudeBin, cliVersion } = {}) {
87
+ let version = cliVersion || null;
88
+ try {
89
+ if (!version) version = await probeClaudeVersion();
90
+ } catch { /* version stays null */ }
91
+ const key = version || 'unknown';
92
+ const hit = cache.get(key);
93
+ if (hit) return { ...hit, tools: [...hit.tools], skills: [...hit.skills] };
94
+ try {
95
+ const doSpawn = spawn || require('node:child_process').spawn;
96
+ const init = await runProbe(doSpawn, claudeBin || resolveClaudeBin());
97
+ const tools = init ? strings(init.tools).filter((t) => !t.startsWith('mcp__')) : [];
98
+ if (init && tools.length) {
99
+ const result = { tools, skills: strings(init.skills), source: /** @type {const} */ ('cli'), cliVersion: version };
100
+ cache.set(key, result);
101
+ return { ...result, tools: [...tools], skills: [...result.skills] };
102
+ }
103
+ } catch { /* fall through */ }
104
+ return { tools: [...FALLBACK_TOOLS], skills: [], source: 'fallback', cliVersion: version };
105
+ }
106
+
107
+ /** Test hook — forget cached probes. */
108
+ function __resetForTests() { cache.clear(); }
109
+
110
+ module.exports = { getBuiltinTools, FALLBACK_TOOLS, __resetForTests };
@@ -116,7 +116,7 @@ const BUILTIN_ENVIRONMENTS = deepFreeze({
116
116
  osSandboxRequired: true,
117
117
  permissionMode: 'acceptEdits',
118
118
  writeRoots: [...JOB_WRITE_ROOTS],
119
- network: { mode: 'allowlist', hosts: ['registry.npmjs.org'] },
119
+ network: { mode: 'allowlist', hosts: ['registry.npmjs.org', 'api.github.com'] },
120
120
  secretDenyPaths: [...SANDBOX_SECRET_PATHS],
121
121
  webFetch: false,
122
122
  webSearch: false,