claude-code-session-manager 0.140.0 → 0.142.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 (204) hide show
  1. package/README.md +80 -70
  2. package/bin/cli.cjs +11 -0
  3. package/dist/assets/AppSettings-BcZgIvvY.js +2 -0
  4. package/dist/assets/{History--JwsFnbn.js → History-DpZuJXi1.js} +1 -1
  5. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
  6. package/dist/assets/{Panel-CALyU0pe.js → Panel-BjdJjhqt.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-sdlA-fUb.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
  8. package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-CxAuwhNN.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
  10. package/dist/assets/{Skills-DtRzghn5.js → Skills-vv0noNVI.js} +5 -5
  11. package/dist/assets/{TiptapBody-DApeu7x8.js → TiptapBody-CXi8Pvut.js} +1 -1
  12. package/dist/assets/Toggle-CiYCWLjh.js +1 -0
  13. package/dist/assets/{VoiceButton-DtStfv1H.js → VoiceButton-4NKKd1sC.js} +1 -1
  14. package/dist/assets/{historyTotals-ydfnwepc.js → historyTotals-DDunb8Ch.js} +1 -1
  15. package/dist/assets/index-Cn5E9958.js +3133 -0
  16. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +496 -484
  20. package/package.json +4 -2
  21. package/plugins/AGENTS.md +4 -3
  22. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  23. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  24. package/plugins/session-manager-dev/skills/builder/SKILL.md +4 -2
  25. package/plugins/session-manager-dev/skills/develop/SKILL.md +55 -18
  26. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  27. package/scripts/README.md +1 -0
  28. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  29. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  30. package/scripts/scheduler-mcp-server.cjs +737 -110
  31. package/src/main/adminRouteRegistry.cjs +59 -0
  32. package/src/main/agentLibrary.cjs +72 -4
  33. package/src/main/agentsIpc.cjs +3 -2
  34. package/src/main/build-info.json +4 -4
  35. package/src/main/chatRunner.cjs +231 -16
  36. package/src/main/config.cjs +30 -0
  37. package/src/main/docEdit.cjs +4 -2
  38. package/src/main/health.cjs +91 -0
  39. package/src/main/index.cjs +98 -48
  40. package/src/main/ipcSchemas.cjs +171 -8
  41. package/src/main/lib/AGENTS.md +1 -1
  42. package/src/main/lib/chatBootRecovery.cjs +2 -0
  43. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  44. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  45. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  46. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  47. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  48. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  49. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  50. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  51. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  52. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  53. package/src/main/lib/demo-video-kit/cast.md +43 -0
  54. package/src/main/lib/demo-video-kit/character.cjs +722 -30
  55. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  56. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  57. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  58. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  59. package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
  60. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  61. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  62. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  63. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  64. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  65. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  66. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  67. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  68. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  69. package/src/main/lib/epic/artifactRetention.cjs +310 -0
  70. package/src/main/lib/epic/artifactStore.cjs +392 -0
  71. package/src/main/lib/epic/delegationReadiness.cjs +76 -2
  72. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  73. package/src/main/lib/epic/epicEventLog.cjs +214 -0
  74. package/src/main/lib/epic/epicMint.cjs +43 -1
  75. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  76. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  77. package/src/main/lib/epic/epicPurge.cjs +347 -0
  78. package/src/main/lib/epic/epicReopen.cjs +5 -2
  79. package/src/main/lib/epic/epicSettle.cjs +4 -13
  80. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  81. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  82. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  83. package/src/main/lib/epic/epicValidationHook.cjs +81 -2
  84. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  85. package/src/main/lib/externalContract.cjs +37 -4
  86. package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
  87. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  88. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  89. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  90. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  91. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  92. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  93. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  94. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  95. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  96. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  97. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  98. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
  99. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  100. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  101. package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
  102. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
  103. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  104. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  105. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  106. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  107. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  108. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  109. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  110. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  111. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  112. package/src/main/lib/git/worktreeDeps.cjs +77 -2
  113. package/src/main/lib/mcpToolCatalog.cjs +315 -30
  114. package/src/main/lib/opsOwnership.cjs +29 -1
  115. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  116. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  117. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  118. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  119. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  120. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  121. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  122. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
  123. package/src/main/lib/phaseProjection.cjs +103 -0
  124. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  125. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  126. package/src/main/lib/prd/prdCreate.cjs +67 -5
  127. package/src/main/lib/prd/prdCriteria.cjs +225 -0
  128. package/src/main/lib/prd/prdFrontmatter.cjs +68 -3
  129. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  130. package/src/main/lib/prd/prdSizing.cjs +3 -1
  131. package/src/main/lib/process/cleanEnv.cjs +52 -1
  132. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  133. package/src/main/lib/process/memoryScope.cjs +31 -3
  134. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  135. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  136. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  137. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  138. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  139. package/src/main/lib/promptSessionSchema.cjs +6 -0
  140. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  141. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  142. package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
  143. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  144. package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
  145. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  146. package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
  147. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
  148. package/src/main/lib/scheduler/preflightCheck.cjs +97 -0
  149. package/src/main/lib/scheduler/reviewNotice.cjs +39 -0
  150. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  151. package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
  152. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  153. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  154. package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
  155. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  156. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  157. package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
  158. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  159. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
  160. package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
  161. package/src/main/lib/tasks/mitigationReview.cjs +294 -0
  162. package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
  163. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  164. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  165. package/src/main/lib/tasks/taskRun.cjs +186 -17
  166. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  167. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  168. package/src/main/lib/telemetry/auditEvents.cjs +207 -6
  169. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  170. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  171. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  172. package/src/main/lib/toolUseClassify.cjs +181 -0
  173. package/src/main/lib/util/smfileRange.cjs +77 -0
  174. package/src/main/projectPages.cjs +3 -1
  175. package/src/main/promptSessionEvents.cjs +5 -0
  176. package/src/main/pty.cjs +68 -0
  177. package/src/main/queueOps.cjs +32 -13
  178. package/src/main/runVerify.cjs +74 -9
  179. package/src/main/scheduler/AGENTS.md +1 -0
  180. package/src/main/scheduler/budget.cjs +6 -5
  181. package/src/main/scheduler/prdParser.cjs +62 -14
  182. package/src/main/scheduler/reviewLadder.cjs +45 -28
  183. package/src/main/scheduler/starvation.cjs +69 -0
  184. package/src/main/scheduler/utilizationHold.cjs +101 -0
  185. package/src/main/scheduler.cjs +1745 -210
  186. package/src/main/templates/PRD_AUTHORING.md +13 -2
  187. package/src/main/webRemote.cjs +463 -6
  188. package/src/preload/api.d.ts +529 -38
  189. package/src/preload/apiSurface.json +209 -7
  190. package/src/preload/index.cjs +46 -1
  191. package/src/seed/agents/architect.md +6 -1
  192. package/src/seed/agents/blender-artist.md +2 -1
  193. package/src/seed/agents/competitive-analyst.md +3 -1
  194. package/src/seed/agents/competitive-researcher.md +2 -1
  195. package/src/seed/agents/demo-video-builder.md +87 -83
  196. package/src/seed/agents/dev-lead.md +3 -3
  197. package/src/seed/agents/project-home-builder.md +9 -31
  198. package/src/seed/agents/validator.md +9 -10
  199. package/dist/assets/AppSettings-CMFEM68R.js +0 -2
  200. package/dist/assets/HomeClaudeConfig-ijEXs--3.js +0 -3
  201. package/dist/assets/Scheduler-YT3j8SUa.js +0 -16
  202. package/dist/assets/ViewTabs-B7qLXRAH.js +0 -1
  203. package/dist/assets/index-CtxruO1L.js +0 -3121
  204. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -54,42 +54,92 @@ function buildPersonaToolScope(tools, { disallowed = [], structuredOutput = fals
54
54
  return { tools: out };
55
55
  }
56
56
 
57
+ /** Server name of an mcp__<server>__<tool> entry ('' when malformed). */
58
+ function mcpServerOf(tool) {
59
+ return String(tool).slice(5).split('__')[0];
60
+ }
61
+
62
+ const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
63
+
57
64
  /**
58
- * @param {{ tools: string[] }|null} scope result of buildPersonaToolScope
59
- * @param {{ mcpServers?: Record<string, object> }} [opts] known MCP server
60
- * definitions by name. When EVERY mcp__ tool in scope names a server here,
61
- * only those servers are passed (--mcp-config <json> --strict-mcp-config).
62
- * @returns {string[]} argv fragment ([] when unscoped)
65
+ * The argv that loads EXACTLY a job's MCP servers, fail-closed.
66
+ *
67
+ * Always pushes --strict-mcp-config (the CLI then ignores the user/project
68
+ * MCP config). The server set = the persona's declared `mcpServers:` plus the
69
+ * servers named by its mcp__<server>__<tool> tools; each must resolve in the
70
+ * known map, and only those are passed via --mcp-config. Any name that does
71
+ * not resolve — and any declared pack not in `knownPacks` — is a refusal
72
+ * { code: 'capability_unknown', name } (first one found); the caller parks
73
+ * the job naming it. There is no widening branch: an unknown server never
74
+ * loads every server.
75
+ *
76
+ * @param {{ tools: string[] }|null} scope result of buildPersonaToolScope (null = unscoped tools)
77
+ * @param {{ mcpServers?: Record<string, object>, declaredServers?: readonly string[], packs?: readonly string[], knownPacks?: readonly string[] }} [opts]
78
+ * mcpServers: known server definitions by name. declaredServers: the
79
+ * persona's `mcpServers:`. packs / knownPacks: the job's packs and those the
80
+ * catalog resolves.
81
+ * @returns {{ args: string[], refusal: null|{ code: 'capability_unknown', name: string } }}
63
82
  */
64
- function personaToolScopeArgs(scope, { mcpServers } = {}) {
65
- if (!scope) return [];
66
- const def = {
67
- description: 'Headless run with a scheduler-enforced tool scope.',
68
- prompt: 'Tool scope is enforced by the scheduler.',
69
- tools: scope.tools,
70
- };
71
- const args = [
72
- '--agents', JSON.stringify({ [HEADLESS_SCOPE_AGENT_NAME]: def }),
73
- '--agent', HEADLESS_SCOPE_AGENT_NAME,
74
- ];
75
- // A scope naming no MCP tool never uses a server: with --strict-mcp-config and
76
- // no --mcp-config (variadic; would swallow later args) the CLI boots none.
77
- const mcpTools = scope.tools.map(String).filter((t) => t.startsWith('mcp__'));
78
- if (mcpTools.length === 0) {
79
- args.push('--strict-mcp-config');
80
- return args;
83
+ function personaToolScopeArgs(scope, { mcpServers, declaredServers = [], packs = [], knownPacks = [] } = {}) {
84
+ /** @type {string[]} */
85
+ const args = [];
86
+ if (scope) {
87
+ const def = {
88
+ description: 'Headless run with a scheduler-enforced tool scope.',
89
+ prompt: 'Tool scope is enforced by the scheduler.',
90
+ tools: scope.tools,
91
+ };
92
+ args.push('--agents', JSON.stringify({ [HEADLESS_SCOPE_AGENT_NAME]: def }), '--agent', HEADLESS_SCOPE_AGENT_NAME);
81
93
  }
82
- // Server name = the segment between `mcp__` and the next `__`.
83
- const named = new Set(mcpTools.map((t) => t.slice(5).split('__')[0]));
94
+ /** @type {null|{ code: 'capability_unknown', name: string }} */
95
+ let refusal = null;
96
+ const refuse = (name) => { if (!refusal) refusal = { code: 'capability_unknown', name }; };
84
97
  const known = mcpServers || {};
85
- const allKnown = [...named].every((n) => n && Object.prototype.hasOwnProperty.call(known, n));
86
- if (allKnown) {
87
- const picked = {};
88
- for (const n of named) picked[n] = known[n];
89
- // --mcp-config is variadic: the caller must keep a `--flag` right after.
90
- args.push('--mcp-config', JSON.stringify({ mcpServers: picked }), '--strict-mcp-config');
98
+ /** @type {string[]} */
99
+ const named = [];
100
+ for (const d of Array.isArray(declaredServers) ? declaredServers : []) {
101
+ const n = String(d).trim();
102
+ if (n && !named.includes(n)) named.push(n);
103
+ }
104
+ const mcpTools = scope ? scope.tools.map(String).filter((t) => t.startsWith('mcp__')) : [];
105
+ for (const t of mcpTools) {
106
+ const n = mcpServerOf(t);
107
+ if (!n) { refuse(t); continue; }
108
+ if (!named.includes(n)) named.push(n);
109
+ }
110
+ /** @type {Record<string, object>} */
111
+ const picked = {};
112
+ for (const n of named) {
113
+ if (hasOwn(known, n)) picked[n] = known[n];
114
+ else refuse(n);
115
+ }
116
+ const knownPackSet = new Set(Array.isArray(knownPacks) ? knownPacks.map(String) : []);
117
+ for (const p of Array.isArray(packs) ? packs : []) {
118
+ if (!knownPackSet.has(String(p))) refuse(String(p));
119
+ }
120
+ // --mcp-config is variadic: it is followed immediately by --strict-mcp-config.
121
+ // With no server, no --mcp-config at all — strict mode alone boots none.
122
+ if (Object.keys(picked).length) args.push('--mcp-config', JSON.stringify({ mcpServers: picked }));
123
+ args.push('--strict-mcp-config');
124
+ return { args, refusal };
125
+ }
126
+
127
+ /**
128
+ * The resolved MCP server set a job runs with: declared + tool-named, sorted,
129
+ * unique (the AgentSnapshot's `mcpServers`).
130
+ * @param {readonly string[]|null|undefined} tools
131
+ * @param {readonly string[]|null|undefined} declared
132
+ * @returns {string[]}
133
+ */
134
+ function resolvedMcpServerNames(tools, declared) {
135
+ const names = new Set();
136
+ for (const d of Array.isArray(declared) ? declared : []) { const n = String(d).trim(); if (n) names.add(n); }
137
+ for (const t of Array.isArray(tools) ? tools.map(String) : []) {
138
+ if (!t.startsWith('mcp__')) continue;
139
+ const n = mcpServerOf(t);
140
+ if (n) names.add(n);
91
141
  }
92
- return args;
142
+ return [...names].sort();
93
143
  }
94
144
 
95
145
  const JOB_MCP_TOOLS_ENV = 'SM_SCHEDULER_JOB_MCP_TOOLS';
@@ -115,4 +165,5 @@ module.exports = {
115
165
  HEADLESS_SCOPE_AGENT_NAME,
116
166
  buildPersonaToolScope,
117
167
  personaToolScopeArgs,
168
+ resolvedMcpServerNames,
118
169
  };
@@ -21,7 +21,7 @@ const { resolveClaudeBin, claudeSpawnTarget } = require('./claudeBin.cjs');
21
21
  const { headlessPermissionArgs, ensureCliCapsProbed } = require('./claudeCliCaps.cjs');
22
22
  const { buildJobSandboxSettings } = require('./jobSandboxPolicy.cjs');
23
23
  const { feedChildStdin } = require('../process/childStdin.cjs');
24
- const { withProcRole } = require('../process/cleanEnv.cjs');
24
+ const { withProcRole, assertNoCredentials } = require('../process/cleanEnv.cjs');
25
25
 
26
26
  const MAX_OUT_BYTES = 8 * 1024 * 1024;
27
27
 
@@ -44,7 +44,9 @@ async function runClaudeP(prompt, { model = 'sonnet', timeoutMs = 180_000, syste
44
44
  ];
45
45
  if (systemPrompt) args.push('--append-system-prompt', systemPrompt);
46
46
  const target = claudeSpawnTarget('aux', 'runclaudep', bin);
47
- const child = spawn(target.command, args, { env: withProcRole({ ...process.env, SM_KG_INTERNAL: '1' }, 'aux'), stdio: ['pipe', 'pipe', 'pipe'], ...(target.argv0 ? { argv0: target.argv0 } : {}) });
47
+ const childEnv = withProcRole({ ...process.env, SM_KG_INTERNAL: '1' }, 'aux');
48
+ assertNoCredentials(childEnv, { site: 'runClaudeP' }); // named exception: CREDENTIAL_EXCEPTIONS
49
+ const child = spawn(target.command, args, { env: childEnv, stdio: ['pipe', 'pipe', 'pipe'], ...(target.argv0 ? { argv0: target.argv0 } : {}) });
48
50
  feedChildStdin(child, prompt);
49
51
  let out = '';
50
52
  let err = '';
@@ -20,6 +20,10 @@
20
20
  * longer prefix > shorter prefix). A compound Bash command resolves each
21
21
  * simple command and returns a blocking result if any one blocks.
22
22
  *
23
+ * Marks: see MARKS. 'irreversible' / 'money' / 'public' block; 'confirm'
24
+ * refuses in a job and asks the owner through Needs you (argsDigest names
25
+ * the exact call).
26
+ *
23
27
  * Pure apart from readMarksLayer / writeMarksLayer. No side effects at
24
28
  * require time. readMarksLayer and resolveMark never throw.
25
29
  *
@@ -30,11 +34,21 @@
30
34
 
31
35
  const fs = require('node:fs');
32
36
  const path = require('node:path');
37
+ const crypto = require('node:crypto');
33
38
  const { writeJsonAtomic, readJsonOrSync } = require('../util/atomicFs.cjs');
34
39
 
35
- const MARKS = Object.freeze(['read', 'write', 'irreversible', 'money', 'public']);
40
+ // Order = riskiness (a compound Bash line resolves to its riskiest mark), so
41
+ // 'confirm' sits below the blocking marks: a line holding both is refused for
42
+ // the blocking one first.
43
+ const MARKS = Object.freeze(['read', 'write', 'confirm', 'irreversible', 'money', 'public']);
36
44
  const BLOCKING_MARKS = new Set(['irreversible', 'money', 'public']);
45
+ // 'confirm' = refuse in a headless job, but ask the owner (Needs you) instead
46
+ // of a silent deny. Not a BLOCKING_MARK: the guard handles it on its own path.
47
+ const CONFIRM_MARK = 'confirm';
37
48
  const MARK_SET = new Set(MARKS);
49
+ // Machine-level JSONL (under schedulerHome) the guard appends one
50
+ // confirmation request to; the main process drains it into Needs you.
51
+ const CONFIRMATION_REQUESTS_FILE = 'tool-confirmation-requests.jsonl';
38
52
 
39
53
  const FILE_NAME = 'tool-risk.json';
40
54
  const FORMAT_VERSION = 1;
@@ -59,6 +73,27 @@ function isPlainObject(v) {
59
73
  return v !== null && typeof v === 'object' && !Array.isArray(v);
60
74
  }
61
75
 
76
+ /** schedulerHome-relative path of the confirmation-requests JSONL. */
77
+ function confirmationRequestsPath(schedulerHomeDir) {
78
+ return path.join(schedulerHomeDir, CONFIRMATION_REQUESTS_FILE);
79
+ }
80
+
81
+ /** JSON with object keys sorted at every depth; undefined values dropped like JSON.stringify. */
82
+ function canonicalJson(value) {
83
+ if (Array.isArray(value)) return `[${value.map((v) => (v === undefined ? 'null' : canonicalJson(v))).join(',')}]`;
84
+ if (isPlainObject(value)) {
85
+ const keys = Object.keys(value).filter((k) => value[k] !== undefined && typeof value[k] !== 'function').sort();
86
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(',')}}`;
87
+ }
88
+ const out = JSON.stringify(value);
89
+ return out === undefined ? 'null' : out;
90
+ }
91
+
92
+ /** sha256 hex of the canonical JSON of a call's tool_input (absent input = {}). */
93
+ function argsDigest(toolInput) {
94
+ return crypto.createHash('sha256').update(canonicalJson(toolInput === undefined ? {} : toolInput)).digest('hex');
95
+ }
96
+
62
97
  // ── Bash parsing ────────────────────────────────────────────────────────────
63
98
 
64
99
  /** Quote-aware split on top-level `&&`, `||`, `;`, `|`, and newlines. */
@@ -362,6 +397,11 @@ function resolveMark(call, layersIn) {
362
397
  module.exports = {
363
398
  MARKS,
364
399
  BLOCKING_MARKS,
400
+ CONFIRM_MARK,
401
+ CONFIRMATION_REQUESTS_FILE,
402
+ confirmationRequestsPath,
403
+ canonicalJson,
404
+ argsDigest,
365
405
  systemMarksPath,
366
406
  projectMarksPath,
367
407
  parseRule,
@@ -53,44 +53,71 @@ function isResetFresh(iso, now) {
53
53
  /** Flat sibling window that mirrors a `limits[]` entry's `kind`, for resets_at backfill. */
54
54
  const FLAT_WINDOW_BY_KIND = { session: 'five_hour', weekly_all: 'seven_day' };
55
55
 
56
+ /** Unscoped flat windows usageWindows falls back to, in order, when limits[] has no usable entry. */
57
+ const FLAT_WINDOWS = ['five_hour', 'seven_day'];
58
+
56
59
  /** An entry's utilization: real `percent`, else the flat-shape `utilization`. */
57
60
  function entryPercent(l) {
58
61
  return Number.isFinite(l.percent) ? l.percent : l.utilization;
59
62
  }
60
63
 
61
64
  /**
62
- * Which window is actually binding dispatch. The real /api/oauth/usage
65
+ * Every window bindingWindow chooses among, in payload order, as
66
+ * `{ name, utilization, resets_at, is_active }`. The real /api/oauth/usage
63
67
  * `limits[]` entries carry `kind` / `group` / `percent` / `severity` /
64
68
  * `resets_at` / `scope` / `is_active` (percent is 0-100, may exceed 100).
65
- * Only UNSCOPED entries (`scope == null`) are candidates — a scoped entry
66
- * (e.g. `weekly_scoped` for one model) does not bind dispatch generally. Among
67
- * them the HIGHEST finite percent wins ("binding" = closest to blocking us);
68
- * `is_active` only breaks ties, because the API sets it on group precedence
69
- * and trusting it alone would pick weekly_all 64 over session 95. With no
70
- * usable unscoped entry, falls back to the flat `five_hour`. Pure, no I/O.
69
+ * Only UNSCOPED entries (`scope == null`) with a finite percent count — a
70
+ * scoped entry (e.g. `weekly_scoped` for one model) does not bind dispatch
71
+ * generally. A null `resets_at` backfills from the matching flat window. With
72
+ * no such entry, the flat windows are listed instead, in order `five_hour`
73
+ * (session) then `seven_day` (weekly, all models), each only when its
74
+ * utilization is finite — so a weekly 95 binds even when five_hour reads low.
75
+ * Model-scoped flat windows (`seven_day_opus`, `seven_day_sonnet`) are never
76
+ * listed. Nothing usable is []. Pure, no I/O.
71
77
  */
72
- function bindingWindow(payload) {
78
+ function usageWindows(payload) {
79
+ const out = [];
73
80
  if (payload && Array.isArray(payload.limits)) {
74
- let best = null;
75
- let bestPct = -Infinity;
76
81
  for (const l of payload.limits) {
77
82
  if (!l || l.scope != null) continue;
78
83
  const pct = entryPercent(l);
79
84
  if (!Number.isFinite(pct)) continue;
80
- if (pct > bestPct || (pct === bestPct && l.is_active === true && !(best && best.is_active === true))) {
81
- best = l;
82
- bestPct = pct;
83
- }
85
+ const flat = payload[FLAT_WINDOW_BY_KIND[l.kind]];
86
+ out.push({
87
+ name: l.kind || l.type || l.name || 'unknown',
88
+ utilization: pct,
89
+ resets_at: l.resets_at ?? (flat ? flat.resets_at ?? null : null),
90
+ is_active: l.is_active === true,
91
+ });
84
92
  }
85
- if (best) {
86
- const flat = payload[FLAT_WINDOW_BY_KIND[best.kind]];
87
- return {
88
- name: best.kind || best.type || best.name || 'unknown',
89
- utilization: bestPct,
90
- resets_at: best.resets_at ?? (flat ? flat.resets_at ?? null : null),
91
- };
93
+ }
94
+ if (out.length > 0) return out;
95
+ if (!payload) return out;
96
+ for (const name of FLAT_WINDOWS) {
97
+ const w = payload[name];
98
+ if (w && Number.isFinite(w.utilization)) {
99
+ out.push({ name, utilization: w.utilization, resets_at: w.resets_at ?? null, is_active: w.is_active === true });
100
+ }
101
+ }
102
+ return out;
103
+ }
104
+
105
+ /**
106
+ * Which window is actually binding dispatch, picked from usageWindows() so
107
+ * the two never disagree. The HIGHEST finite percent wins ("binding" =
108
+ * closest to blocking us); `is_active` only breaks ties, because the API sets
109
+ * it on group precedence and trusting it alone would pick weekly_all 64 over
110
+ * session 95. With no usable window, falls back to the flat `five_hour`
111
+ * (utilization possibly undefined). Pure, no I/O.
112
+ */
113
+ function bindingWindow(payload) {
114
+ let best = null;
115
+ for (const w of usageWindows(payload)) {
116
+ if (!best || w.utilization > best.utilization || (w.utilization === best.utilization && w.is_active && !best.is_active)) {
117
+ best = w;
92
118
  }
93
119
  }
120
+ if (best) return { name: best.name, utilization: best.utilization, resets_at: best.resets_at };
94
121
  const fh = payload && payload.five_hour;
95
122
  return {
96
123
  name: 'five_hour',
@@ -242,6 +269,7 @@ module.exports = {
242
269
  backoffWithJitter,
243
270
  isResetFresh,
244
271
  bindingWindow,
272
+ usageWindows,
245
273
  degradedBudget,
246
274
  meterFailureBudget,
247
275
  degradedConcurrencyCap,
@@ -0,0 +1,277 @@
1
+ 'use strict';
2
+ // @ts-check
3
+
4
+ /**
5
+ * vaultRefs.cjs — local credential references for environment profiles
6
+ * (Managed Agents' "vault" primitive, kept local).
7
+ *
8
+ * An environment may list `credentials: [{ ref, server, envVar }]`. Each ref
9
+ * names a secret in a LOCAL store — never a network one:
10
+ * keyring:<service>/<account> OS keyring (Linux `secret-tool lookup`,
11
+ * macOS `security find-generic-password -w`)
12
+ * file:<path>[#<KEY>] a file under one of VAULT_FILE_ROOTS (home-
13
+ * relative, or `~/`-prefixed). With #KEY the
14
+ * file is read as a JSON object or KEY=VALUE
15
+ * lines; without, its trimmed contents.
16
+ * Any other scheme (https:, vault:, …) is refused: 'vault_ref_invalid'.
17
+ *
18
+ * A resolved value goes ONLY into the spawn env of the MCP server / broker the
19
+ * credential names, and only when that server runs OUTSIDE the job (the caller
20
+ * says which servers do). It never enters the job env: jobEnvWithoutVault
21
+ * strips every credential envVar from a job env, and jobSandboxPolicy.cjs
22
+ * denies VAULT_FILE_ROOTS (plus each credential's file path) to the job.
23
+ *
24
+ * File stores are read only, never written. Self's secrets/README.md owns
25
+ * its store's format; this module only reads paths under it.
26
+ */
27
+
28
+ const path = require('node:path');
29
+
30
+ /** Home-relative roots a file: ref may point under (all job-denied). */
31
+ const VAULT_FILE_ROOTS = Object.freeze(['Self/secrets', '.config/session-manager/vault']);
32
+
33
+ const ENV_VAR_RE = /^[A-Z_][A-Z0-9_]*$/;
34
+ const KEYRING_PART_RE = /^[A-Za-z0-9._@+-]+$/;
35
+
36
+ class VaultRefError extends Error {
37
+ /** @param {string} code @param {string} message */
38
+ constructor(code, message) {
39
+ super(message);
40
+ this.name = 'VaultRefError';
41
+ this.code = code;
42
+ }
43
+ }
44
+
45
+ /**
46
+ * @typedef {{ kind: 'keyring', service: string, account: string }
47
+ * | { kind: 'file', path: string, key: string|null }} ParsedVaultRef
48
+ */
49
+
50
+ /**
51
+ * Parse a ref string. file: paths come back home-relative and normalized.
52
+ * @param {unknown} ref
53
+ * @returns {ParsedVaultRef}
54
+ */
55
+ function parseVaultRef(ref) {
56
+ if (typeof ref !== 'string' || !ref) throw new VaultRefError('vault_ref_invalid', 'vault ref must be a non-empty string');
57
+ const colon = ref.indexOf(':');
58
+ const scheme = colon === -1 ? '' : ref.slice(0, colon);
59
+ const body = colon === -1 ? '' : ref.slice(colon + 1);
60
+ if (scheme === 'keyring') {
61
+ const slash = body.indexOf('/');
62
+ const service = slash === -1 ? '' : body.slice(0, slash);
63
+ const account = slash === -1 ? '' : body.slice(slash + 1);
64
+ if (!KEYRING_PART_RE.test(service) || !KEYRING_PART_RE.test(account)) {
65
+ throw new VaultRefError('vault_ref_invalid', `keyring ref must be keyring:<service>/<account>: ${ref}`);
66
+ }
67
+ return { kind: 'keyring', service, account };
68
+ }
69
+ if (scheme === 'file') {
70
+ const hash = body.indexOf('#');
71
+ let p = hash === -1 ? body : body.slice(0, hash);
72
+ const key = hash === -1 ? null : body.slice(hash + 1);
73
+ if (key !== null && !key) throw new VaultRefError('vault_ref_invalid', `empty #key in ${ref}`);
74
+ if (p.startsWith('~/')) p = p.slice(2);
75
+ if (!p || path.isAbsolute(p) || p.split('/').includes('..')) {
76
+ throw new VaultRefError('vault_ref_invalid', `file ref path must be home-relative without '..': ${ref}`);
77
+ }
78
+ const rel = path.posix.normalize(p);
79
+ const under = VAULT_FILE_ROOTS.some((root) => rel === root || rel.startsWith(`${root}/`));
80
+ if (!under) {
81
+ throw new VaultRefError('vault_ref_invalid', `file ref must sit under ${VAULT_FILE_ROOTS.join(' or ')}: ${ref}`);
82
+ }
83
+ return { kind: 'file', path: rel, key };
84
+ }
85
+ throw new VaultRefError('vault_ref_invalid', `vault ref kind must be keyring: or file: (no network stores): ${ref}`);
86
+ }
87
+
88
+ /** True when `ref` parses. */
89
+ function isVaultRef(ref) {
90
+ try {
91
+ parseVaultRef(ref);
92
+ return true;
93
+ } catch {
94
+ return false;
95
+ }
96
+ }
97
+
98
+ /** Home-relative path of a file: ref, or null (keyring / invalid). */
99
+ function vaultFilePath(ref) {
100
+ try {
101
+ const p = parseVaultRef(ref);
102
+ return p.kind === 'file' ? p.path : null;
103
+ } catch {
104
+ return null;
105
+ }
106
+ }
107
+
108
+ /** @param {string} text @param {string} key */
109
+ function pickKey(text, key) {
110
+ const trimmed = text.trim();
111
+ if (trimmed.startsWith('{')) {
112
+ try {
113
+ const obj = JSON.parse(trimmed);
114
+ if (obj && typeof obj === 'object' && Object.prototype.hasOwnProperty.call(obj, key) && obj[key] != null) return String(obj[key]);
115
+ return null;
116
+ } catch {
117
+ /* fall through to KEY=VALUE */
118
+ }
119
+ }
120
+ for (const line of text.split(/\r?\n/)) {
121
+ const m = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(.*)$/);
122
+ if (m && m[1] === key) {
123
+ let v = m[2].trim();
124
+ if (v.length >= 2 && ((v[0] === '"' && v.endsWith('"')) || (v[0] === "'" && v.endsWith("'")))) v = v.slice(1, -1);
125
+ return v;
126
+ }
127
+ }
128
+ return null;
129
+ }
130
+
131
+ /**
132
+ * Resolve a ref from its local store. Never touches the network.
133
+ * @param {string} ref
134
+ * @param {{ homeDir?: string, platform?: string,
135
+ * exec?: (cmd: string, args: string[]) => string,
136
+ * readFile?: (absPath: string) => string }} [opts] stubs for tests
137
+ * @returns {string}
138
+ */
139
+ function resolveVaultRef(ref, opts = {}) {
140
+ const parsed = parseVaultRef(ref);
141
+ let value;
142
+ if (parsed.kind === 'keyring') {
143
+ const platform = opts.platform || process.platform;
144
+ const exec = opts.exec || ((cmd, args) => require('node:child_process').execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000 }));
145
+ let cmd;
146
+ let args;
147
+ if (platform === 'linux') {
148
+ cmd = 'secret-tool';
149
+ args = ['lookup', 'service', parsed.service, 'account', parsed.account];
150
+ } else if (platform === 'darwin') {
151
+ cmd = 'security';
152
+ args = ['find-generic-password', '-s', parsed.service, '-a', parsed.account, '-w'];
153
+ } else {
154
+ throw new VaultRefError('vault_ref_unsupported', `no OS keyring CLI on platform ${platform}`);
155
+ }
156
+ try {
157
+ value = String(exec(cmd, args));
158
+ } catch (e) {
159
+ throw new VaultRefError('vault_ref_unresolved', `${cmd} could not read ${ref}: ${e && /** @type {Error} */ (e).message}`);
160
+ }
161
+ value = value.replace(/\r?\n$/, '');
162
+ } else {
163
+ const homeDir = opts.homeDir || require('node:os').homedir();
164
+ const abs = path.join(homeDir, parsed.path);
165
+ const readFile = opts.readFile || ((p) => require('node:fs').readFileSync(p, 'utf8'));
166
+ let text;
167
+ try {
168
+ text = String(readFile(abs));
169
+ } catch (e) {
170
+ throw new VaultRefError('vault_ref_unresolved', `cannot read ${ref}: ${e && /** @type {Error} */ (e).message}`);
171
+ }
172
+ const picked = parsed.key === null ? text.trim() : pickKey(text, parsed.key);
173
+ if (picked === null) throw new VaultRefError('vault_ref_unresolved', `key ${parsed.key} not found in ${ref}`);
174
+ value = picked;
175
+ }
176
+ if (!value) throw new VaultRefError('vault_ref_empty', `vault ref resolved empty: ${ref}`);
177
+ return value;
178
+ }
179
+
180
+ /**
181
+ * @typedef {{ ref: string, server: string, envVar: string }} VaultCredential
182
+ */
183
+
184
+ /** The credentials list of a profile or resolved environment ({ profile }). */
185
+ function credentialsOf(environment) {
186
+ if (!environment || typeof environment !== 'object') return [];
187
+ const e = /** @type {any} */ (environment);
188
+ const profile = e.profile && typeof e.profile === 'object' ? e.profile : e;
189
+ return Array.isArray(profile.credentials) ? /** @type {VaultCredential[]} */ (profile.credentials) : [];
190
+ }
191
+
192
+ /** @param {Iterable<string>|Record<string, unknown>|null|undefined} s */
193
+ function toNameSet(s) {
194
+ if (!s) return new Set();
195
+ if (typeof (/** @type {any} */ (s))[Symbol.iterator] === 'function') return new Set(Array.from(/** @type {Iterable<string>} */ (s), String));
196
+ return new Set(Object.keys(s));
197
+ }
198
+
199
+ /**
200
+ * Refuse any credential not bound to an out-of-job MCP server / broker.
201
+ * Throws VaultRefError 'vault_ref_unbound' (no server, or a server that runs
202
+ * inside the job / is unknown), or 'vault_ref_invalid' (bad ref / envVar).
203
+ * @param {object|null|undefined} environment profile or resolved environment
204
+ * @param {{ outOfJobServers?: Iterable<string>|Record<string, unknown>|null }} [opts]
205
+ * @returns {VaultCredential[]} the checked credentials
206
+ */
207
+ function assertRefTargetsServer(environment, { outOfJobServers } = {}) {
208
+ const allowed = toNameSet(outOfJobServers);
209
+ const creds = credentialsOf(environment);
210
+ for (const c of creds) {
211
+ const ref = c && c.ref;
212
+ parseVaultRef(ref);
213
+ const server = c && typeof c.server === 'string' ? c.server.trim() : '';
214
+ if (!server) throw new VaultRefError('vault_ref_unbound', `vault ref ${ref} names no server — refs resolve only into an out-of-job MCP server`);
215
+ if (!allowed.has(server)) throw new VaultRefError('vault_ref_unbound', `vault ref ${ref} targets ${server}, which is not an out-of-job server`);
216
+ if (!c || typeof c.envVar !== 'string' || !ENV_VAR_RE.test(c.envVar)) throw new VaultRefError('vault_ref_invalid', `vault ref ${ref} needs an envVar like API_TOKEN`);
217
+ }
218
+ return creds;
219
+ }
220
+
221
+ /**
222
+ * The spawn env for one out-of-job MCP server: baseEnv plus the resolved
223
+ * values of the credentials bound to it (and no other server's).
224
+ * @param {object|null|undefined} environment
225
+ * @param {string} serverName
226
+ * @param {{ outOfJobServers?: Iterable<string>|Record<string, unknown>|null,
227
+ * baseEnv?: Record<string, string|undefined>,
228
+ * resolve?: (ref: string) => string }} [opts]
229
+ * @returns {Record<string, string|undefined>}
230
+ */
231
+ function serverSpawnEnv(environment, serverName, { outOfJobServers, baseEnv = {}, resolve = (r) => resolveVaultRef(r) } = {}) {
232
+ const creds = assertRefTargetsServer(environment, { outOfJobServers });
233
+ const env = { ...baseEnv };
234
+ for (const c of creds) {
235
+ if (c.server.trim() === serverName) env[c.envVar] = resolve(c.ref);
236
+ }
237
+ return env;
238
+ }
239
+
240
+ /**
241
+ * A job env with every credential envVar removed, so no vault value (or a
242
+ * same-named parent value) reaches the job.
243
+ * @param {object|null|undefined} environment
244
+ * @param {Record<string, string|undefined>} jobEnv
245
+ * @returns {Record<string, string|undefined>}
246
+ */
247
+ function jobEnvWithoutVault(environment, jobEnv) {
248
+ const env = { ...(jobEnv || {}) };
249
+ for (const c of credentialsOf(environment)) {
250
+ if (c && typeof c.envVar === 'string') delete env[c.envVar];
251
+ }
252
+ return env;
253
+ }
254
+
255
+ /** Home-relative file paths of an environment's file: credentials. */
256
+ function credentialFilePaths(environment) {
257
+ /** @type {string[]} */
258
+ const out = [];
259
+ for (const c of credentialsOf(environment)) {
260
+ const p = vaultFilePath(c && c.ref);
261
+ if (p && !out.includes(p)) out.push(p);
262
+ }
263
+ return out;
264
+ }
265
+
266
+ module.exports = {
267
+ VAULT_FILE_ROOTS,
268
+ VaultRefError,
269
+ parseVaultRef,
270
+ isVaultRef,
271
+ vaultFilePath,
272
+ resolveVaultRef,
273
+ assertRefTargetsServer,
274
+ serverSpawnEnv,
275
+ jobEnvWithoutVault,
276
+ credentialFilePaths,
277
+ };