claude-code-session-manager 0.138.0 → 0.140.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 (194) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +352 -79
  3. package/dist/assets/AppSettings-CMFEM68R.js +2 -0
  4. package/dist/assets/History--JwsFnbn.js +2 -0
  5. package/dist/assets/HomeClaudeConfig-ijEXs--3.js +3 -0
  6. package/dist/assets/{Panel-CeDiyuNn.js → Panel-CALyU0pe.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-sdlA-fUb.js +26 -0
  8. package/dist/assets/Scheduler-YT3j8SUa.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-CFMK8NJh.js → SkillReferenceGraph-CxAuwhNN.js} +1 -1
  10. package/dist/assets/Skills-DtRzghn5.js +67 -0
  11. package/dist/assets/{TiptapBody-D1kTj-tn.js → TiptapBody-DApeu7x8.js} +60 -54
  12. package/dist/assets/ViewTabs-B7qLXRAH.js +1 -0
  13. package/dist/assets/{VoiceButton-CZeyPM31.js → VoiceButton-DtStfv1H.js} +1 -1
  14. package/dist/assets/{historyTotals-B00l64Jw.js → historyTotals-ydfnwepc.js} +1 -1
  15. package/dist/assets/index-CtxruO1L.js +3121 -0
  16. package/dist/assets/{index-62tyjEQB.css → index-DKXdXfka.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +467 -451
  20. package/package.json +17 -6
  21. package/plugins/AGENTS.md +60 -0
  22. package/plugins/CLAUDE.md +1 -60
  23. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  24. package/plugins/session-manager-dev/skills/builder/SKILL.md +12 -4
  25. package/plugins/session-manager-dev/skills/builder/scripts/publish-preflight.cjs +255 -0
  26. package/plugins/session-manager-dev/skills/develop/SKILL.md +36 -22
  27. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
  28. package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
  29. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
  30. package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
  31. package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
  32. package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
  33. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
  34. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
  35. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
  36. package/scripts/README.md +2 -0
  37. package/scripts/hooks/guard-tool-risk.cjs +91 -0
  38. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
  39. package/scripts/ops-sweep.cjs +53 -23
  40. package/scripts/scheduler-mcp-server.cjs +360 -35
  41. package/src/main/build-info.json +4 -4
  42. package/src/main/chatRunner.cjs +2 -2
  43. package/src/main/config.cjs +112 -8
  44. package/src/main/docEdit.cjs +6 -1
  45. package/src/main/exchanges.cjs +70 -5
  46. package/src/main/files.cjs +7 -27
  47. package/src/main/health.cjs +48 -15
  48. package/src/main/historyAggregator.cjs +172 -63
  49. package/src/main/historyDashboard.cjs +87 -17
  50. package/src/main/index.cjs +78 -4
  51. package/src/main/ipcSchemas.cjs +233 -20
  52. package/src/main/lib/AGENTS.md +54 -0
  53. package/src/main/lib/CLAUDE.md +1 -54
  54. package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
  55. package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
  56. package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
  57. package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
  58. package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
  59. package/src/main/lib/claude/effectiveModelInfo.cjs +92 -22
  60. package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
  61. package/src/main/lib/claude/modelPricing.cjs +148 -0
  62. package/src/main/lib/claude/personaToolScope.cjs +12 -6
  63. package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
  64. package/src/main/lib/claude/runClaudeP.cjs +6 -1
  65. package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
  66. package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
  67. package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
  68. package/src/main/lib/ephemeralCwd.cjs +37 -2
  69. package/src/main/lib/epic/delegationReadiness.cjs +42 -9
  70. package/src/main/lib/epic/epicAdminRoutes.cjs +121 -0
  71. package/src/main/lib/epic/epicJobReceipt.cjs +87 -0
  72. package/src/main/lib/epic/epicOutsideRead.cjs +423 -0
  73. package/src/main/lib/epic/epicOutsideState.cjs +233 -0
  74. package/src/main/lib/epic/epicSettle.cjs +1 -1
  75. package/src/main/lib/epic/epicStateWatcher.cjs +157 -0
  76. package/src/main/lib/epic/epicSweepValidator.cjs +7 -2
  77. package/src/main/lib/epic/epicValidationHook.cjs +24 -4
  78. package/src/main/lib/epic/externalRef.cjs +37 -0
  79. package/src/main/lib/epic/externalRefIndex.cjs +136 -0
  80. package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
  81. package/src/main/lib/epic/restorableSessions.cjs +151 -17
  82. package/src/main/lib/epic/transcriptUsage.cjs +197 -0
  83. package/src/main/lib/externalContract.cjs +137 -0
  84. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +176 -5
  85. package/src/main/lib/feedback-remote/crossProjectReply.cjs +186 -9
  86. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -6
  87. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +50 -8
  88. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +218 -4
  89. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +19 -3
  90. package/src/main/lib/feedback-remote/feedbackImages.cjs +171 -0
  91. package/src/main/lib/feedback-remote/localAdminHttp.cjs +11 -10
  92. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +167 -21
  93. package/src/main/lib/feedback-remote/needsYouAdminRoutes.cjs +133 -0
  94. package/src/main/lib/feedback-remote/needsYouIpc.cjs +50 -0
  95. package/src/main/lib/feedback-remote/needsYouStore.cjs +285 -0
  96. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
  97. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
  98. package/src/main/lib/git/branchSweep.cjs +209 -4
  99. package/src/main/lib/git/gitWorktree.cjs +41 -5
  100. package/src/main/lib/guardShims.cjs +1 -1
  101. package/src/main/lib/historyRollup.cjs +58 -5
  102. package/src/main/lib/insideHome.cjs +27 -1
  103. package/src/main/lib/mcpToolCatalog.cjs +232 -25
  104. package/src/main/lib/mdDocCensus.cjs +59 -78
  105. package/src/main/lib/mdDocRefs.cjs +71 -93
  106. package/src/main/lib/mdNetworkScan.cjs +245 -250
  107. package/src/main/lib/mdReviewRecord.cjs +22 -9
  108. package/src/main/lib/memoryMdNetwork.cjs +5 -12
  109. package/src/main/lib/opsOwnership.cjs +18 -2
  110. package/src/main/lib/opsRetentionSettings.cjs +28 -4
  111. package/src/main/lib/persona-macro/agentAdminRoutes.cjs +121 -0
  112. package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
  113. package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
  114. package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
  115. package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
  116. package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
  117. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
  118. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  119. package/src/main/lib/prd/depSlugResolve.cjs +104 -4
  120. package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
  121. package/src/main/lib/prd/prdCreate.cjs +351 -23
  122. package/src/main/lib/prd/prdDisposition.cjs +11 -2
  123. package/src/main/lib/prd/prdFrontmatter.cjs +96 -3
  124. package/src/main/lib/process/loginItem.cjs +171 -0
  125. package/src/main/lib/process/loginItemPlan.cjs +193 -0
  126. package/src/main/lib/project-pages/playerBridge.cjs +4 -0
  127. package/src/main/lib/project-pages/videoReview.cjs +268 -0
  128. package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
  129. package/src/main/lib/promptSessionSchema.cjs +4 -0
  130. package/src/main/lib/remoteTranscriptTail.cjs +32 -1
  131. package/src/main/lib/scheduler/cpuSample.cjs +131 -4
  132. package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
  133. package/src/main/lib/scheduler/loadGate.cjs +24 -6
  134. package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
  135. package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
  136. package/src/main/lib/scheduler/queueStore.cjs +7 -0
  137. package/src/main/lib/scheduler/rcaReport.cjs +21 -1
  138. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
  139. package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
  140. package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
  141. package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
  142. package/src/main/lib/scheduler/schedulerPaths.cjs +12 -0
  143. package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
  144. package/src/main/lib/scheduler/validationQuality.cjs +282 -0
  145. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
  146. package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
  147. package/src/main/lib/tasks/taskIpc.cjs +80 -0
  148. package/src/main/lib/tasks/taskLedger.cjs +502 -0
  149. package/src/main/lib/tasks/taskRun.cjs +313 -0
  150. package/src/main/lib/tasks/taskSwitch.cjs +120 -0
  151. package/src/main/lib/telemetry/auditEvents.cjs +176 -0
  152. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +45 -0
  153. package/src/main/loginItemIpc.cjs +35 -0
  154. package/src/main/loopEfficiencyHandlers.cjs +11 -2
  155. package/src/main/projectPages.cjs +6 -15
  156. package/src/main/promptSessionEvents.cjs +9 -1
  157. package/src/main/queueOps.cjs +260 -3
  158. package/src/main/runVerify.cjs +53 -25
  159. package/src/main/scheduler/AGENTS.md +26 -0
  160. package/src/main/scheduler/CLAUDE.md +1 -26
  161. package/src/main/scheduler/budget.cjs +239 -9
  162. package/src/main/scheduler/cancelDependents.cjs +154 -0
  163. package/src/main/scheduler/prdParser.cjs +4 -1
  164. package/src/main/scheduler/starvation.cjs +20 -18
  165. package/src/main/scheduler.cjs +774 -64
  166. package/src/main/supervisor.cjs +5 -1
  167. package/src/main/templates/PRD_AUTHORING.md +7 -1
  168. package/src/main/transcripts.cjs +62 -7
  169. package/src/main/validationQualityHandlers.cjs +199 -0
  170. package/src/main/webRemote.cjs +132 -20
  171. package/src/preload/api.d.ts +434 -28
  172. package/src/preload/apiSurface.cjs +7 -0
  173. package/src/preload/apiSurface.json +485 -81
  174. package/src/preload/index.cjs +38 -5
  175. package/src/seed/agents/validator.md +19 -8
  176. package/dist/assets/AgentLibrary-C1d_D7uQ.js +0 -2
  177. package/dist/assets/AppSettings-CgDhqrsU.js +0 -2
  178. package/dist/assets/Button-Bk23rEnZ.js +0 -1
  179. package/dist/assets/DocumentEditorPane-BqY5Nq6W.js +0 -1
  180. package/dist/assets/Extensions-CXem-uwI.js +0 -2
  181. package/dist/assets/History-BwO3coo4.js +0 -2
  182. package/dist/assets/Library-BDV69fSe.js +0 -32
  183. package/dist/assets/ListDetail-CD-Fm6mh.js +0 -1
  184. package/dist/assets/ProjectClaudeConfig-NjdKdwe8.js +0 -25
  185. package/dist/assets/ProvenanceBadge-Bu8NmI_R.js +0 -1
  186. package/dist/assets/Scheduler-CkhTvG7C.js +0 -16
  187. package/dist/assets/Settings-COT34hBF.js +0 -2
  188. package/dist/assets/Skills-BgexoUkQ.js +0 -29
  189. package/dist/assets/SourceChip-BXjcdeb1.js +0 -1
  190. package/dist/assets/SystemPrompt-CeeH3EeW.js +0 -1
  191. package/dist/assets/Toggle-CENi19iK.js +0 -1
  192. package/dist/assets/ViewTabs-DDBb0x96.js +0 -1
  193. package/dist/assets/claude-settings-schema-COigsajx.js +0 -3
  194. package/dist/assets/index-CgCxpunJ.js +0 -3116
@@ -0,0 +1,202 @@
1
+ 'use strict';
2
+ // @ts-check
3
+
4
+ /**
5
+ * jobSandboxPolicy.cjs — turns a headless PRD job's persona and paths into the
6
+ * claude CLI flags that confine it.
7
+ *
8
+ * Two levels:
9
+ * - 'tool-rules' (every persona): keeps --dangerously-skip-permissions but
10
+ * passes --settings with permissions.deny Read/Edit rules over the secret
11
+ * files below. Probed on CLI 2.1.325: these rules ARE enforced under the
12
+ * bypass flag for the Read/Write tools and plain Bash cat/redirect, but
13
+ * `python3 -c open(...)` or `sh -c 'cat $1'` still read the file — tool
14
+ * rules are not containment.
15
+ * - 'os-sandbox' (validator, dev-lead, when bwrap+socat / sandbox-exec are
16
+ * present): drops the bypass flag, runs under a --permission-mode, and turns
17
+ * on the CLI's OS sandbox (Bash only — in-process tools stay governed by the
18
+ * permission rules): writes only in the worktree plus declared roots, secret
19
+ * files unreadable, Bash network limited to the profile's allowlist.
20
+ *
21
+ * Rule paths: a leading `//` is absolute; a single `/` is relative to the
22
+ * settings file — so every rule here is `//` + the absolute path sans its `/`.
23
+ *
24
+ * Pure: no fs, child_process, os or clock. The caller probes dependencies via
25
+ * sandboxDependencies({ platform, which }) and passes the result in.
26
+ */
27
+
28
+ const path = require('node:path');
29
+
30
+ /** Home-relative paths whose contents no job tool may read or write. */
31
+ const SANDBOX_SECRET_PATHS = Object.freeze([
32
+ '.npmrc',
33
+ '.netrc',
34
+ '.ssh',
35
+ '.gnupg',
36
+ 'Self/secrets',
37
+ '.claude/.credentials.json',
38
+ '.config/gh',
39
+ '.google_workspace_mcp',
40
+ '.config/google-workspace-mcp',
41
+ '.aws',
42
+ '.docker/config.json',
43
+ ]);
44
+
45
+ /**
46
+ * @typedef {{ readonly permissionMode: string, readonly network: readonly string[] }} SandboxProfile
47
+ */
48
+
49
+ /** @type {Readonly<Record<string, SandboxProfile>>} */
50
+ const SANDBOX_PROFILES = Object.freeze({
51
+ validator: Object.freeze({ permissionMode: 'default', network: Object.freeze([]) }),
52
+ 'dev-lead': Object.freeze({ permissionMode: 'acceptEdits', network: Object.freeze(['registry.npmjs.org']) }),
53
+ });
54
+
55
+ /** @type {Readonly<Record<string, readonly string[]>>} */
56
+ const PLATFORM_DEPS = Object.freeze({
57
+ linux: Object.freeze(['bwrap', 'socat']),
58
+ darwin: Object.freeze(['sandbox-exec']),
59
+ });
60
+
61
+ /**
62
+ * @param {{ platform: string, which: (name: string) => string|null }} args
63
+ * @returns {{ available: boolean, missing: string[] }}
64
+ */
65
+ function sandboxDependencies({ platform, which }) {
66
+ const needed = Object.prototype.hasOwnProperty.call(PLATFORM_DEPS, platform) ? PLATFORM_DEPS[platform] : null;
67
+ if (!needed) return { available: false, missing: [`unsupported platform: ${platform}`] };
68
+ const missing = needed.filter((name) => !which(name));
69
+ return { available: missing.length === 0, missing };
70
+ }
71
+
72
+ /** @param {string} abs */
73
+ function denyRulesFor(abs) {
74
+ const p = `/${abs.replace(/^\/+/, '')}`;
75
+ return [`Read(/${p})`, `Read(/${p}/**)`, `Edit(/${p})`, `Edit(/${p}/**)`];
76
+ }
77
+
78
+ /**
79
+ * @param {Record<string, unknown>} args
80
+ * @param {string} field
81
+ * @returns {string}
82
+ */
83
+ function requireAbs(args, field) {
84
+ const v = args[field];
85
+ if (typeof v !== 'string' || v.length === 0 || !path.isAbsolute(v)) {
86
+ throw new TypeError(`buildJobSandboxSettings: ${field} must be an absolute path (got ${JSON.stringify(v)})`);
87
+ }
88
+ return v;
89
+ }
90
+
91
+ /**
92
+ * @typedef {{
93
+ * level: 'os-sandbox'|'tool-rules',
94
+ * argv: string[],
95
+ * settings: Record<string, unknown>,
96
+ * summary: { level: 'os-sandbox'|'tool-rules', profile: string|null, network: string[]|null, reason: string|null },
97
+ * }} JobSandboxResult
98
+ */
99
+
100
+ /**
101
+ * @param {{
102
+ * agentType?: string|null,
103
+ * worktreeDir: string,
104
+ * projectRoot: string,
105
+ * homeDir: string,
106
+ * tmpDir: string,
107
+ * deps?: { available: boolean, missing?: string[] }|null,
108
+ * }} args
109
+ * @returns {JobSandboxResult}
110
+ */
111
+ function buildJobSandboxSettings(args) {
112
+ const raw = /** @type {Record<string, unknown>} */ (/** @type {unknown} */ (args || {}));
113
+ const worktreeDir = requireAbs(raw, 'worktreeDir');
114
+ const projectRoot = requireAbs(raw, 'projectRoot');
115
+ const homeDir = requireAbs(raw, 'homeDir');
116
+ const tmpDir = requireAbs(raw, 'tmpDir');
117
+ const agentType = typeof args.agentType === 'string' && args.agentType ? args.agentType : null;
118
+ const deps = args.deps;
119
+
120
+ const secretAbs = SANDBOX_SECRET_PATHS.map((p) => path.join(homeDir, p));
121
+ const deny = secretAbs.flatMap(denyRulesFor);
122
+
123
+ const profile =
124
+ agentType && Object.prototype.hasOwnProperty.call(SANDBOX_PROFILES, agentType) ? SANDBOX_PROFILES[agentType] : null;
125
+
126
+ /** @type {string|null} */
127
+ let reason = null;
128
+ if (!profile) {
129
+ reason = `no sandbox profile for persona ${agentType ?? '(none)'}`;
130
+ } else if (!deps || deps.available !== true) {
131
+ const missing = deps && Array.isArray(deps.missing) && deps.missing.length ? deps.missing : ['unknown'];
132
+ reason = `OS sandbox unavailable, missing: ${missing.join(', ')}`;
133
+ }
134
+
135
+ if (!profile || reason) {
136
+ const settings = { permissions: { deny } };
137
+ return {
138
+ level: 'tool-rules',
139
+ argv: ['--dangerously-skip-permissions', '--settings', JSON.stringify(settings)],
140
+ settings,
141
+ summary: { level: 'tool-rules', profile: agentType, network: null, reason },
142
+ };
143
+ }
144
+
145
+ const settings = {
146
+ permissions: {
147
+ allow: ['Read(//**)', 'Glob', 'Grep', 'Bash', 'Skill', 'Agent', 'ToolSearch', 'TodoWrite'],
148
+ deny: [...deny, 'WebFetch', 'WebSearch'],
149
+ },
150
+ sandbox: {
151
+ enabled: true,
152
+ failIfUnavailable: true,
153
+ allowUnsandboxedCommands: false,
154
+ autoAllowBashIfSandboxed: true,
155
+ filesystem: {
156
+ // .git: a job worktree commits into the main checkout's .git (objects,
157
+ // refs, worktrees/<name>); the CLI sandbox keeps .git/hooks and
158
+ // .git/config read-only itself.
159
+ allowWrite: [
160
+ worktreeDir,
161
+ path.join(projectRoot, '.git'),
162
+ tmpDir,
163
+ path.join(homeDir, '.npm'),
164
+ path.join(homeDir, '.cache'),
165
+ path.join(projectRoot, 'node_modules', '.vite'),
166
+ path.join(projectRoot, 'node_modules', '.vitest'),
167
+ ],
168
+ denyRead: secretAbs,
169
+ },
170
+ credentials: { files: secretAbs.map((p) => ({ path: p, mode: 'deny' })) },
171
+ network: { allowedDomains: [...profile.network], strictAllowlist: true },
172
+ },
173
+ };
174
+ return {
175
+ level: 'os-sandbox',
176
+ argv: ['--permission-mode', profile.permissionMode, '--settings', JSON.stringify(settings)],
177
+ settings,
178
+ summary: { level: 'os-sandbox', profile: agentType, network: [...profile.network], reason: null },
179
+ };
180
+ }
181
+
182
+ /**
183
+ * Env vars a job's child process needs for its sandbox level. An os-sandbox
184
+ * job gets TMPDIR/TMP/TEMP pointed at its private temp dir (the only tmp
185
+ * write root its settings declare); tool-rules jobs get no env change.
186
+ *
187
+ * @param {{ level?: string }|null|undefined} policy
188
+ * @param {string} tmpDir
189
+ * @returns {Record<string, string>}
190
+ */
191
+ function sandboxChildEnv(policy, tmpDir) {
192
+ if (!policy || policy.level !== 'os-sandbox') return {};
193
+ return { TMPDIR: tmpDir, TMP: tmpDir, TEMP: tmpDir };
194
+ }
195
+
196
+ module.exports = {
197
+ SANDBOX_SECRET_PATHS,
198
+ SANDBOX_PROFILES,
199
+ sandboxDependencies,
200
+ buildJobSandboxSettings,
201
+ sandboxChildEnv,
202
+ };
@@ -0,0 +1,148 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * modelPricing.cjs — the current price of each Claude model id, and the dollar cost of one
5
+ * usage bucket. Pure: no I/O, no imports, never throws.
6
+ *
7
+ * Source: the `claude-api` skill's model and prompt-caching reference, cached 2026-11-03,
8
+ * read on 2026-11-21. Prices are dollars per million tokens.
9
+ *
10
+ * Cache writes cost CACHE_WRITE_5M_MULTIPLIER × input for the 5-minute cache and
11
+ * CACHE_WRITE_1H_MULTIPLIER × input for the 1-hour cache, on every model. Cache writes whose split
12
+ * is unknown (cacheCreationUnknownTokens, or all of them when cacheCreation1hTokens is absent) are
13
+ * charged at the 1-hour rate and the result is marked estimated: on 2026-11-21 this machine's last 48 hours of transcripts had 93.5% of
14
+ * cache-write tokens as 1-hour writes.
15
+ *
16
+ * Known limits, deliberately NOT modeled (on 2026-11-21 the last 48 hours of transcripts had no
17
+ * such call):
18
+ * 1. Claude Haiku 5.5 prompts over 100K tokens cost 0.50 / 2.50 (input / output), not the base rate.
19
+ * 2. Fast mode costs more than the rates below.
20
+ */
21
+
22
+ /** @typedef {{ input: number, output: number, cacheRead: number }} ModelPrice */
23
+
24
+ const row = (input, output, cacheRead) => Object.freeze({ input, output, cacheRead });
25
+
26
+ // cacheRead is stated outright by the reference for Fable 5.2, Fable 5.1, Fable 5, Opus 5.5 and
27
+ // Sonnet 5.5 (and their Mythos twins). Every other row's cacheRead is derived from the general
28
+ // rule, 0.1 × input: opus-5, opus-4-8, opus-4-7, opus-4-6, sonnet-5, sonnet-4-6, haiku-5-5, haiku-4-5.
29
+ const MODEL_PRICES = Object.freeze({
30
+ 'claude-fable-5-2': row(8, 40, 0.20),
31
+ 'claude-mythos-5-2': row(8, 40, 0.20),
32
+ 'claude-fable-5-1': row(10, 50, 0.25),
33
+ 'claude-mythos-5-1': row(10, 50, 0.25),
34
+ 'claude-fable-5': row(10, 50, 1.00),
35
+ 'claude-mythos-5': row(10, 50, 1.00),
36
+ 'claude-opus-5-5': row(4, 20, 0.20),
37
+ 'claude-opus-5': row(5, 25, 0.50),
38
+ 'claude-opus-4-8': row(5, 25, 0.50),
39
+ 'claude-opus-4-7': row(5, 25, 0.50),
40
+ 'claude-opus-4-6': row(5, 25, 0.50),
41
+ 'claude-sonnet-5-5': row(2, 10, 0.10),
42
+ 'claude-sonnet-5': row(2, 10, 0.20),
43
+ 'claude-sonnet-4-6': row(3, 15, 0.30),
44
+ 'claude-haiku-5-5': row(0.10, 0.50, 0.01),
45
+ 'claude-haiku-4-5': row(1, 5, 0.10),
46
+ });
47
+
48
+ const CACHE_WRITE_5M_MULTIPLIER = 1.25;
49
+ const CACHE_WRITE_1H_MULTIPLIER = 2;
50
+
51
+ // Newest row per family, used to price an id that matches no row. Order matters only in that the
52
+ // first family word found wins.
53
+ const FAMILY_FALLBACK = Object.freeze([
54
+ ['fable', 'claude-fable-5-2'],
55
+ ['mythos', 'claude-mythos-5-2'],
56
+ ['opus', 'claude-opus-5-5'],
57
+ ['sonnet', 'claude-sonnet-5-5'],
58
+ ['haiku', 'claude-haiku-5-5'],
59
+ ]);
60
+ const DEFAULT_ID = 'claude-sonnet-5-5';
61
+
62
+ // Bedrock-style provider prefixes: `anthropic.`, `us.anthropic.`, `global.anthropic.`, …
63
+ const PROVIDER_PREFIX_RE = /^(?:[a-z0-9-]+\.)*anthropic\./;
64
+ // What may follow a row id: a -YYYYMMDD date, a `[1m]`-style context tag, or a Vertex `@` version.
65
+ const ROW_CONTINUATION_RE = /^(?:-\d{8}(?!\d)|\[|@)/;
66
+
67
+ /**
68
+ * @param {string} rowId
69
+ * @param {boolean} estimated
70
+ */
71
+ function priced(rowId, estimated) {
72
+ const p = MODEL_PRICES[/** @type {keyof typeof MODEL_PRICES} */ (rowId)];
73
+ return { id: rowId, input: p.input, output: p.output, cacheRead: p.cacheRead, estimated };
74
+ }
75
+
76
+ /**
77
+ * @param {unknown} modelId
78
+ * @returns {{ id: string, input: number, output: number, cacheRead: number, estimated: boolean }}
79
+ */
80
+ function priceForModel(modelId) {
81
+ const id = typeof modelId === 'string' ? modelId.toLowerCase().replace(PROVIDER_PREFIX_RE, '') : '';
82
+ if (id) {
83
+ for (const rowId of Object.keys(MODEL_PRICES)) {
84
+ if (id === rowId) return priced(rowId, false);
85
+ if (id.startsWith(rowId) && ROW_CONTINUATION_RE.test(id.slice(rowId.length))) return priced(rowId, false);
86
+ }
87
+ for (const [family, rowId] of FAMILY_FALLBACK) {
88
+ if (id.includes(family)) return priced(rowId, true);
89
+ }
90
+ }
91
+ return priced(DEFAULT_ID, true);
92
+ }
93
+
94
+ /** @param {unknown} v */
95
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
96
+
97
+ /**
98
+ * Cache writes split three ways:
99
+ * - cacheCreationUnknownTokens: cache-write tokens whose 5-minute / 1-hour split was not
100
+ * recorded. Clamped to [0, cacheCreationTokens], charged at the 1-hour rate, and they mark
101
+ * the result estimated when above zero. It is a plain number so buckets that mix lines with
102
+ * and without a recorded split still sum correctly.
103
+ * - cacheCreation1hTokens: recorded 1-hour writes, clamped to what is left after the unknown part.
104
+ * - the rest is 5-minute writes.
105
+ * When cacheCreation1hTokens is not a number at all, every cache write counts as unknown.
106
+ *
107
+ * @param {unknown} modelId
108
+ * @param {unknown} bucket { inputTokens, outputTokens, cacheReadTokens, cacheCreationTokens, cacheCreation1hTokens?, cacheCreationUnknownTokens? }
109
+ * @returns {{ costUsd: number, cacheSavingsUsd: number, estimated: boolean }}
110
+ */
111
+ function costOfUsage(modelId, bucket) {
112
+ const price = priceForModel(modelId);
113
+ /** @type {Record<string, unknown>} */
114
+ const b = bucket && typeof bucket === 'object' ? /** @type {Record<string, unknown>} */ (bucket) : {};
115
+ const input = num(b.inputTokens);
116
+ const output = num(b.outputTokens);
117
+ const cacheRead = num(b.cacheReadTokens);
118
+ const cacheWrite = Math.max(0, num(b.cacheCreationTokens));
119
+ let estimated = price.estimated;
120
+ let writeUnknown;
121
+ let write1h;
122
+ if (typeof b.cacheCreation1hTokens === 'number' && Number.isFinite(b.cacheCreation1hTokens)) {
123
+ writeUnknown = Math.min(Math.max(0, num(b.cacheCreationUnknownTokens)), cacheWrite);
124
+ write1h = Math.min(Math.max(0, b.cacheCreation1hTokens), cacheWrite - writeUnknown);
125
+ } else {
126
+ writeUnknown = cacheWrite;
127
+ write1h = 0;
128
+ }
129
+ if (writeUnknown > 0) estimated = true;
130
+ const write5m = cacheWrite - writeUnknown - write1h;
131
+ const costUsd = (
132
+ input * price.input +
133
+ output * price.output +
134
+ cacheRead * price.cacheRead +
135
+ write5m * price.input * CACHE_WRITE_5M_MULTIPLIER +
136
+ (writeUnknown + write1h) * price.input * CACHE_WRITE_1H_MULTIPLIER
137
+ ) / 1e6;
138
+ const cacheSavingsUsd = cacheRead * (price.input - price.cacheRead) / 1e6;
139
+ return { costUsd, cacheSavingsUsd, estimated };
140
+ }
141
+
142
+ module.exports = {
143
+ MODEL_PRICES,
144
+ CACHE_WRITE_5M_MULTIPLIER,
145
+ CACHE_WRITE_1H_MULTIPLIER,
146
+ priceForModel,
147
+ costOfUsage,
148
+ };
@@ -12,9 +12,11 @@
12
12
  * working.
13
13
  *
14
14
  * Scoping is focus, not containment: the scope decides which tools a job is
15
- * offered. Every headless job runs as the owner's OS user with
16
- * --dangerously-skip-permissions, so a job with Bash can still start an MCP
17
- * server or call the admin API itself.
15
+ * offered. Every headless job runs as the owner's OS user. Sandboxed personas
16
+ * (validator, dev-lead when the OS sandbox is available) no longer run with
17
+ * --dangerously-skip-permissions; every other job still does, under secret-path
18
+ * deny rules — see jobSandboxPolicy.cjs. Either way a job with Bash can still
19
+ * start an MCP server or call the admin API itself.
18
20
  *
19
21
  * Pure: no fs, and no require of scheduler.cjs (cycle) — the caller passes its
20
22
  * HEADLESS_DISALLOWED_TOOLS list in.
@@ -29,10 +31,13 @@ const HEADLESS_SCOPE_AGENT_NAME = 'sm-headless-scoped';
29
31
 
30
32
  /**
31
33
  * @param {readonly string[]|null|undefined} tools persona `tools:` list
32
- * @param {{ disallowed?: readonly string[] }} [opts]
34
+ * @param {{ disallowed?: readonly string[], structuredOutput?: boolean }} [opts]
35
+ * structuredOutput: also grant the CLI's StructuredOutput tool (a --json-schema
36
+ * run). Probe 2026-11-22 (CLI 2.1.325): a scoped run without it ends
37
+ * 'success' with structured_output null — the schema is silently skipped.
33
38
  * @returns {{ tools: string[] }|null} null = persona declares no restriction
34
39
  */
35
- function buildPersonaToolScope(tools, { disallowed = [] } = {}) {
40
+ function buildPersonaToolScope(tools, { disallowed = [], structuredOutput = false } = {}) {
36
41
  if (!Array.isArray(tools) || tools.length === 0) return null;
37
42
  const names = tools
38
43
  .filter((t) => typeof t === 'string')
@@ -41,7 +46,8 @@ function buildPersonaToolScope(tools, { disallowed = [] } = {}) {
41
46
  if (names.length === 0 || names.includes('*')) return null;
42
47
  const blocked = new Set(disallowed);
43
48
  const out = [];
44
- for (const name of [...names, ...HEADLESS_TOOL_FLOOR]) {
49
+ const extra = structuredOutput === true ? ['StructuredOutput'] : [];
50
+ for (const name of [...names, ...HEADLESS_TOOL_FLOOR, ...extra]) {
45
51
  if (blocked.has(name) || out.includes(name)) continue;
46
52
  out.push(name);
47
53
  }
@@ -27,7 +27,18 @@ const { readTail } = require('../util/fileTail.cjs');
27
27
  * pause at 58% weekly). Tool output may also mention 429 or "rate limit". */
28
28
  function detectRateLimitInLog(logPath) {
29
29
  try {
30
- const text = readTail(logPath, 16384);
30
+ return detectRateLimitInText(readTail(logPath, 16384));
31
+ } catch {
32
+ return false;
33
+ }
34
+ }
35
+
36
+ /** Same detection over already-captured text (e.g. a captured stdout tail).
37
+ * Only the last 16 KB is scanned, matching the log-tail variant. Never throws. */
38
+ function detectRateLimitInText(rawText) {
39
+ try {
40
+ const all = typeof rawText === 'string' ? rawText : '';
41
+ const text = all.length > 16384 ? all.slice(-16384) : all;
31
42
  if (!text) return false;
32
43
  for (const line of text.split('\n')) {
33
44
  const t = line.trim();
@@ -51,4 +62,4 @@ function detectRateLimitInLog(logPath) {
51
62
  }
52
63
  }
53
64
 
54
- module.exports = { detectRateLimitInLog };
65
+ module.exports = { detectRateLimitInLog, detectRateLimitInText };
@@ -16,8 +16,10 @@
16
16
  */
17
17
 
18
18
  const { spawn } = require('node:child_process');
19
+ const os = require('node:os');
19
20
  const { resolveClaudeBin, claudeSpawnTarget } = require('./claudeBin.cjs');
20
21
  const { headlessPermissionArgs, ensureCliCapsProbed } = require('./claudeCliCaps.cjs');
22
+ const { buildJobSandboxSettings } = require('./jobSandboxPolicy.cjs');
21
23
  const { feedChildStdin } = require('../process/childStdin.cjs');
22
24
  const { withProcRole } = require('../process/cleanEnv.cjs');
23
25
 
@@ -29,10 +31,13 @@ async function runClaudeP(prompt, { model = 'sonnet', timeoutMs = 180_000, syste
29
31
  return new Promise((resolve) => {
30
32
  let bin;
31
33
  try { bin = resolveClaudeBin(); } catch (e) { resolve({ ok: false, error: `claude not found: ${e?.message}` }); return; }
34
+ // No spawn cwd is set, so the child inherits process.cwd() — the sandbox roots there.
35
+ const sandboxDir = process.cwd();
36
+ const sandbox = buildJobSandboxSettings({ agentType: 'aux', worktreeDir: sandboxDir, projectRoot: sandboxDir, homeDir: os.homedir(), tmpDir: os.tmpdir(), deps: { available: false, missing: [] } });
32
37
  const args = [
33
38
  '-p',
34
39
  '--model', model,
35
- '--dangerously-skip-permissions',
40
+ ...sandbox.argv,
36
41
  ...headlessPermissionArgs(),
37
42
  '--strict-mcp-config',
38
43
  '--output-format', 'text',
@@ -0,0 +1,177 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * toolRiskIpc.cjs — the one main-process API for tool-risk marks:
5
+ *
6
+ * toolRisk:read ({ scope, cwd? }) -> { ok, path, exists, marks, interactive, error? }
7
+ * toolRisk:write ({ scope, cwd?, marks, interactive? }) -> { ok, path, error? }
8
+ *
9
+ * scope 'user' = System ~/.claude/tool-risk.json
10
+ * scope 'project' = Project <cwd>/.claude/tool-risk.json
11
+ *
12
+ * Every read/validate/write goes through toolRiskMarks.cjs (readMarksLayer /
13
+ * validateMarksFile / writeMarksLayer). `interactive` is a Project-only opt-in:
14
+ * turning it on installs guard-tool-risk into <cwd>/.claude/settings.json's
15
+ * PreToolUse hooks via its stable shim (delegationReadiness.cjs installGuard —
16
+ * the same merge/repair path the sanctioned guards use, with a local def, NOT a
17
+ * GUARD_DEFS entry, so the readiness banner never auto-installs it); turning it
18
+ * off removes exactly that hook.
19
+ */
20
+
21
+ const fs = require('node:fs');
22
+ const os = require('node:os');
23
+ const path = require('node:path');
24
+ const {
25
+ systemMarksPath,
26
+ projectMarksPath,
27
+ readMarksLayer,
28
+ validateMarksFile,
29
+ writeMarksLayer,
30
+ } = require('./toolRiskMarks.cjs');
31
+
32
+ const TOOL_RISK_GUARD_MATCHER = 'Bash|Write|Edit|NotebookEdit|mcp__.*';
33
+ const TOOL_RISK_GUARD_SCRIPT = path.resolve(__dirname, '..', '..', '..', '..', 'scripts', 'hooks', 'guard-tool-risk.cjs');
34
+ const TOOL_RISK_GUARD_DEF = Object.freeze({
35
+ id: 'tool-risk-guard',
36
+ label: 'Tool-risk guard hook installed',
37
+ guardName: 'guard-tool-risk',
38
+ scriptBasename: 'guard-tool-risk.cjs',
39
+ script: TOOL_RISK_GUARD_SCRIPT,
40
+ matcher: TOOL_RISK_GUARD_MATCHER,
41
+ fixActionId: null,
42
+ nudge: false,
43
+ });
44
+
45
+ function errMsg(e) {
46
+ return e && e.message ? e.message : String(e);
47
+ }
48
+
49
+ /** @returns {{ok:true, path:string} | {ok:false, path:string|null, error:string}} */
50
+ function layerPath({ scope, cwd }, homeDir) {
51
+ if (scope === 'user') return { ok: true, path: systemMarksPath(homeDir) };
52
+ if (scope === 'project') {
53
+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) {
54
+ return { ok: false, path: null, error: 'scope "project" needs an absolute cwd' };
55
+ }
56
+ return { ok: true, path: projectMarksPath(cwd) };
57
+ }
58
+ return { ok: false, path: null, error: `unknown scope ${JSON.stringify(scope)}` };
59
+ }
60
+
61
+ async function readToolRisk(payload, { homeDir = os.homedir() } = {}) {
62
+ const p = layerPath(payload || {}, homeDir);
63
+ if (!p.ok) return { ok: false, path: p.path, exists: false, marks: {}, interactive: false, error: p.error };
64
+ const r = readMarksLayer(p.path);
65
+ if (!r.ok) return { ok: false, path: p.path, exists: r.exists === true, marks: {}, interactive: false, error: r.error };
66
+ return { ok: true, path: p.path, exists: r.exists, marks: r.marks, interactive: r.interactive };
67
+ }
68
+
69
+ /** Remove every guard-tool-risk hook from <cwd>/.claude/settings.json; drop an emptied entry. */
70
+ async function removeToolRiskGuard({ cwd }) {
71
+ const { readJsonOrSync } = require('../util/atomicFs.cjs');
72
+ const { writeJson, addAllowedRoot } = require('../../config.cjs');
73
+ const settingsPath = path.join(cwd, '.claude', 'settings.json');
74
+ if (!fs.existsSync(settingsPath)) return { ok: true, action: 'not-installed', settingsPath };
75
+ const settings = readJsonOrSync(settingsPath, undefined);
76
+ if (settings === undefined || !settings || typeof settings !== 'object' || Array.isArray(settings)) {
77
+ return { ok: false, action: 'error', error: `${settingsPath} is not valid JSON — fix it by hand before removing the guard` };
78
+ }
79
+ const hooks = (settings.hooks && typeof settings.hooks === 'object') ? settings.hooks : null;
80
+ if (!hooks || !Array.isArray(hooks.PreToolUse)) return { ok: true, action: 'not-installed', settingsPath };
81
+
82
+ const isOurs = (h) => typeof h?.command === 'string' && h.command.includes(TOOL_RISK_GUARD_DEF.guardName);
83
+ let removed = false;
84
+ const preToolUse = [];
85
+ for (const entry of hooks.PreToolUse) {
86
+ if (!Array.isArray(entry?.hooks) || !entry.hooks.some(isOurs)) { preToolUse.push(entry); continue; }
87
+ removed = true;
88
+ const kept = entry.hooks.filter((h) => !isOurs(h));
89
+ if (kept.length > 0) preToolUse.push({ ...entry, hooks: kept });
90
+ }
91
+ if (!removed) return { ok: true, action: 'not-installed', settingsPath };
92
+
93
+ const nextHooks = { ...hooks };
94
+ if (preToolUse.length > 0) nextHooks.PreToolUse = preToolUse;
95
+ else delete nextHooks.PreToolUse;
96
+ const next = { ...settings };
97
+ if (Object.keys(nextHooks).length > 0) next.hooks = nextHooks;
98
+ else delete next.hooks;
99
+ addAllowedRoot(cwd);
100
+ await writeJson(settingsPath, next);
101
+ return { ok: true, action: 'removed', settingsPath };
102
+ }
103
+
104
+ async function installToolRiskGuard({ cwd, homeDir }) {
105
+ const { installGuard } = require('../epic/delegationReadiness.cjs');
106
+ return installGuard(TOOL_RISK_GUARD_DEF, { cwd, homeDir });
107
+ }
108
+
109
+ async function writeToolRisk(payload, { homeDir = os.homedir() } = {}) {
110
+ const { scope, cwd, marks, interactive } = payload || {};
111
+ const p = layerPath({ scope, cwd }, homeDir);
112
+ if (!p.ok) return { ok: false, path: p.path, error: p.error };
113
+ if (scope === 'user' && interactive !== undefined) {
114
+ return { ok: false, path: p.path, error: '"interactive" is a Project-only opt-in; it cannot be set on the System (user) layer' };
115
+ }
116
+
117
+ // Omitted `interactive` on a Project write keeps the file's current value.
118
+ let nextInteractive = interactive;
119
+ if (scope === 'project' && nextInteractive === undefined) {
120
+ const prev = readMarksLayer(p.path);
121
+ if (prev.ok && prev.exists && prev.interactive) nextInteractive = true;
122
+ }
123
+ const obj = { version: 1, marks };
124
+ if (nextInteractive !== undefined) obj.interactive = nextInteractive;
125
+
126
+ const v = validateMarksFile(obj);
127
+ if (!v.ok) return { ok: false, path: p.path, error: v.error };
128
+
129
+ try {
130
+ const w = await writeMarksLayer(p.path, obj);
131
+ if (!w.ok) return { ok: false, path: p.path, error: w.error };
132
+ } catch (e) {
133
+ return { ok: false, path: p.path, error: errMsg(e) };
134
+ }
135
+
136
+ if (scope === 'project' && interactive !== undefined) {
137
+ let hook;
138
+ try {
139
+ hook = interactive
140
+ ? await installToolRiskGuard({ cwd, homeDir })
141
+ : await removeToolRiskGuard({ cwd });
142
+ } catch (e) {
143
+ hook = { ok: false, error: errMsg(e) };
144
+ }
145
+ if (!hook.ok) return { ok: false, path: p.path, error: `marks saved, but the guard hook could not be ${interactive ? 'installed' : 'removed'}: ${hook.error}` };
146
+ }
147
+ return { ok: true, path: p.path };
148
+ }
149
+
150
+ /**
151
+ * @param {import('electron').IpcMain} ipcMain
152
+ * @param {{ schemas: any, validated: Function, validatePath?: (p:string)=>string, homeDir?: string,
153
+ * onChanged?: (info:{path:string}) => void }} deps
154
+ */
155
+ function registerToolRiskIpc(ipcMain, deps) {
156
+ const { schemas, validated, validatePath, onChanged } = deps;
157
+ const opts = () => ({ homeDir: deps.homeDir || os.homedir() });
158
+ ipcMain.handle('toolRisk:read', validated(schemas.toolRiskRead, async (p) => {
159
+ if (p.cwd && validatePath) validatePath(p.cwd);
160
+ return readToolRisk(p, opts());
161
+ }));
162
+ ipcMain.handle('toolRisk:write', validated(schemas.toolRiskWrite, async (p) => {
163
+ if (p.cwd && validatePath) validatePath(p.cwd);
164
+ const result = await writeToolRisk(p, opts());
165
+ if (result.ok && onChanged) onChanged({ path: result.path });
166
+ return result;
167
+ }));
168
+ }
169
+
170
+ module.exports = {
171
+ TOOL_RISK_GUARD_MATCHER,
172
+ TOOL_RISK_GUARD_DEF,
173
+ readToolRisk,
174
+ writeToolRisk,
175
+ removeToolRiskGuard,
176
+ registerToolRiskIpc,
177
+ };