claude-code-session-manager 0.141.0 → 0.143.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 (223) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +76 -153
  3. package/bin/cli.cjs +11 -0
  4. package/dist/assets/AppSettings-BO4jDVGO.js +2 -0
  5. package/dist/assets/{History-DJMiuXyK.js → History-DTttbvPb.js} +1 -1
  6. package/dist/assets/HomeClaudeConfig-DADP5bfn.js +3 -0
  7. package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-B_D4Bg7L.js} +1 -1
  8. package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-DPnDJKcr.js} +7 -7
  9. package/dist/assets/Scheduler-CNLjn90m.js +16 -0
  10. package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-D1b2aiol.js} +1 -1
  11. package/dist/assets/{Skills-C1v91GEO.js → Skills-cfV7sgk6.js} +5 -5
  12. package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-DVXtEIVy.js} +1 -1
  13. package/dist/assets/Toggle-CYajnSdx.js +1 -0
  14. package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-DJ4gGRuE.js} +1 -1
  15. package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-D3MoHY2U.js} +1 -1
  16. package/dist/assets/index-CdTppjKR.js +3133 -0
  17. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  18. package/dist/index.html +2 -2
  19. package/dist-web/app.css +1 -1
  20. package/dist-web/app.js +496 -484
  21. package/package.json +6 -4
  22. package/plugins/AGENTS.md +4 -3
  23. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  24. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  25. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  26. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  27. package/plugins/session-manager-dev/skills/develop/SKILL.md +58 -18
  28. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  29. package/scripts/README.md +2 -0
  30. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  31. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  32. package/scripts/scheduler-mcp-server.cjs +1032 -112
  33. package/src/main/adminRouteRegistry.cjs +69 -0
  34. package/src/main/agentLibrary.cjs +72 -4
  35. package/src/main/agentsIpc.cjs +3 -2
  36. package/src/main/build-info.json +4 -4
  37. package/src/main/chatRunner.cjs +336 -23
  38. package/src/main/config.cjs +35 -1
  39. package/src/main/docEdit.cjs +4 -2
  40. package/src/main/health.cjs +129 -2
  41. package/src/main/index.cjs +110 -52
  42. package/src/main/ipcSchemas.cjs +172 -8
  43. package/src/main/lib/AGENTS.md +1 -1
  44. package/src/main/lib/chatBootRecovery.cjs +2 -0
  45. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  46. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  47. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  48. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  49. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  50. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  51. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  52. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  53. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  54. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  55. package/src/main/lib/demo-video-kit/cast.md +52 -0
  56. package/src/main/lib/demo-video-kit/character.cjs +778 -30
  57. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  58. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  59. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  60. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  61. package/src/main/lib/demo-video-kit/kind-tiktok.md +103 -0
  62. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  63. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  64. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  65. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  66. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  67. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  68. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  69. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  70. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  71. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  72. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  73. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  74. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  75. package/src/main/lib/epic/artifactRetention.cjs +356 -0
  76. package/src/main/lib/epic/artifactStore.cjs +435 -0
  77. package/src/main/lib/epic/delegationReadiness.cjs +83 -2
  78. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  79. package/src/main/lib/epic/epicEventLog.cjs +258 -0
  80. package/src/main/lib/epic/epicMint.cjs +43 -1
  81. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  82. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  83. package/src/main/lib/epic/epicPurge.cjs +347 -0
  84. package/src/main/lib/epic/epicReopen.cjs +5 -2
  85. package/src/main/lib/epic/epicSettle.cjs +4 -13
  86. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  87. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  88. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  89. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  90. package/src/main/lib/epic/epicValidationHook.cjs +94 -4
  91. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  92. package/src/main/lib/externalContract.cjs +48 -4
  93. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  94. package/src/main/lib/feedback-remote/crossProjectReply.cjs +478 -127
  95. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  96. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  97. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  98. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  99. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  100. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  101. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  102. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  103. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  104. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  105. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  106. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +32 -1
  107. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  108. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  109. package/src/main/lib/feedback-remote/pendingReplies.cjs +207 -0
  110. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +282 -14
  111. package/src/main/lib/feedback-remote/replyClaims.cjs +159 -0
  112. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  113. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  114. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  115. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  116. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  117. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  118. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  119. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  120. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  121. package/src/main/lib/git/gitWorktree.cjs +8 -0
  122. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  123. package/src/main/lib/git/worktreeDeps.cjs +182 -4
  124. package/src/main/lib/mcpToolCatalog.cjs +399 -29
  125. package/src/main/lib/opsOwnership.cjs +141 -28
  126. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  127. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  128. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  129. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  130. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  131. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  132. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  133. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +309 -0
  134. package/src/main/lib/phaseProjection.cjs +103 -0
  135. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  136. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  137. package/src/main/lib/prd/prdCreate.cjs +387 -228
  138. package/src/main/lib/prd/prdCriteria.cjs +228 -0
  139. package/src/main/lib/prd/prdFrontmatter.cjs +43 -3
  140. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  141. package/src/main/lib/prd/prdSizing.cjs +3 -1
  142. package/src/main/lib/process/cleanEnv.cjs +52 -1
  143. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  144. package/src/main/lib/process/memoryScope.cjs +31 -3
  145. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  146. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  147. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  148. package/src/main/lib/project-pages/videoScriptPress.cjs +260 -0
  149. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +351 -0
  150. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  151. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  152. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  153. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  154. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  155. package/src/main/lib/promptSessionSchema.cjs +6 -0
  156. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  157. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  158. package/src/main/lib/scheduler/criteriaChecks.cjs +313 -0
  159. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  160. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  161. package/src/main/lib/scheduler/jobMemoryStats.cjs +324 -0
  162. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  163. package/src/main/lib/scheduler/planRecordHarvest.cjs +152 -54
  164. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +191 -0
  165. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  166. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  167. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  168. package/src/main/lib/scheduler/scheduleJobSchema.cjs +18 -0
  169. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  170. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  171. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -3
  172. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  173. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  174. package/src/main/lib/scheduler/slotsRoute.cjs +251 -0
  175. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  176. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  177. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +152 -11
  178. package/src/main/lib/tasks/memoryConsolidation.cjs +312 -0
  179. package/src/main/lib/tasks/mitigationReview.cjs +314 -0
  180. package/src/main/lib/tasks/taskAdminRoutes.cjs +390 -25
  181. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  182. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  183. package/src/main/lib/tasks/taskRun.cjs +186 -17
  184. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  185. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  186. package/src/main/lib/telemetry/auditEvents.cjs +204 -6
  187. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  188. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  189. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  190. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  191. package/src/main/lib/toolUseClassify.cjs +181 -0
  192. package/src/main/lib/util/atomicFs.cjs +2 -2
  193. package/src/main/lib/util/smfileRange.cjs +77 -0
  194. package/src/main/projectPages.cjs +3 -1
  195. package/src/main/promptSessionEvents.cjs +21 -1
  196. package/src/main/pty.cjs +77 -0
  197. package/src/main/queueOps.cjs +33 -14
  198. package/src/main/runVerify.cjs +74 -9
  199. package/src/main/scheduler/AGENTS.md +1 -0
  200. package/src/main/scheduler/budget.cjs +6 -5
  201. package/src/main/scheduler/prdParser.cjs +46 -13
  202. package/src/main/scheduler/reviewLadder.cjs +9 -25
  203. package/src/main/scheduler/utilizationHold.cjs +191 -0
  204. package/src/main/scheduler.cjs +1932 -213
  205. package/src/main/templates/PRD_AUTHORING.md +11 -3
  206. package/src/main/webRemote.cjs +463 -6
  207. package/src/preload/api.d.ts +576 -39
  208. package/src/preload/apiSurface.json +223 -7
  209. package/src/preload/index.cjs +48 -1
  210. package/src/seed/agents/architect.md +6 -1
  211. package/src/seed/agents/blender-artist.md +2 -1
  212. package/src/seed/agents/competitive-analyst.md +3 -1
  213. package/src/seed/agents/competitive-researcher.md +2 -1
  214. package/src/seed/agents/demo-video-builder.md +98 -87
  215. package/src/seed/agents/dev-lead.md +3 -3
  216. package/src/seed/agents/project-home-builder.md +9 -31
  217. package/src/seed/agents/validator.md +23 -23
  218. package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
  219. package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
  220. package/dist/assets/Scheduler-cyr61UAC.js +0 -16
  221. package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
  222. package/dist/assets/index-B2TQz3nd.js +0 -3121
  223. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -0,0 +1,234 @@
1
+ // @ts-check
2
+ /**
3
+ * feedbackReport — the desktop's validator for a feedback widget Report v1 (the report.json part
4
+ * of the widget's multipart POST). Mirrors web/feedback-widget/schema/report.v1.json exactly:
5
+ * every limit, enum and closed object there is enforced here, and the parity test in
6
+ * __tests__/feedbackReport.test.cjs reads the JSON Schema and compares it with the constants below.
7
+ *
8
+ * Reports come from customers' browsers and are UNTRUSTED. parseReport never throws and its error
9
+ * names only the failing path and the zod issue code — never field contents.
10
+ */
11
+ 'use strict';
12
+
13
+ const { z } = require('zod');
14
+
15
+ const SCHEMA_VERSION = 1;
16
+ const REPORT_TYPES = /** @type {const} */ (['bug', 'feature', 'other']);
17
+ const MARK_COLORS = /** @type {const} */ (['#a83818', '#f4b942', '#2e5a3e', '#1a1612']);
18
+ const MARK_KINDS = /** @type {const} */ (['pin', 'box', 'element', 'arrow', 'draw', 'text']);
19
+ const CONSOLE_LEVELS = /** @type {const} */ (['error']);
20
+ const CLIENT_REPORT_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
21
+ const NETWORK_STATUS_STRINGS = /** @type {const} */ (['network-error', 'timeout']);
22
+
23
+ const MIN_TITLE = 3;
24
+ const MAX_TITLE = 120;
25
+ const MAX_DETAILS = 5000;
26
+ const MAX_NOTE = 1000;
27
+ const MIN_TEXT = 1;
28
+ const MAX_TEXT = 140;
29
+ const MIN_DRAW_POINTS = 3;
30
+ const MIN_BOX_EDGE = 8;
31
+ const MIN_MARK_N = 1;
32
+ const MAX_ELEMENT_TEXT = 80;
33
+ const MAX_CONSOLE = 20;
34
+ const MAX_NETWORK = 20;
35
+ const MAX_MESSAGE = 500;
36
+ const MAX_STACK = 2000;
37
+ const MIN_CONSOLE_COUNT = 1;
38
+ const MIN_ERROR_STATUS = 400;
39
+ const MAX_CAPTURE_ERROR = 200;
40
+
41
+ /** @type {Record<(typeof REPORT_TYPES)[number], 'bug' | 'feature' | 'discussion'>} */
42
+ const INBOX_TAG = { bug: 'bug', feature: 'feature', other: 'discussion' };
43
+
44
+ const int = () => z.number().int();
45
+ const dateTime = () => z.iso.datetime({ offset: true });
46
+ const color = z.enum(MARK_COLORS);
47
+ const note = z.string().trim().max(MAX_NOTE);
48
+ const markN = int().min(MIN_MARK_N);
49
+
50
+ // $defs
51
+ const pin = z.strictObject({ kind: z.literal('pin'), n: markN, x: z.number(), y: z.number(), color, note });
52
+ const box = z.strictObject({
53
+ kind: z.literal('box'), n: markN, x: z.number(), y: z.number(),
54
+ w: z.number().min(MIN_BOX_EDGE), h: z.number().min(MIN_BOX_EDGE), color, note,
55
+ });
56
+ const elementInfo = z.strictObject({
57
+ selector: z.string(),
58
+ label: z.string().optional(),
59
+ tag: z.string(),
60
+ id: z.string().optional(),
61
+ classes: z.array(z.string()).optional(),
62
+ text: z.string().max(MAX_ELEMENT_TEXT).optional(),
63
+ role: z.string().optional(),
64
+ ariaLabel: z.string().optional(),
65
+ xpath: z.string().optional(),
66
+ });
67
+ const element = z.strictObject({
68
+ kind: z.literal('element'), n: markN, x: z.number(), y: z.number(), w: z.number(), h: z.number(),
69
+ color, note, element: elementInfo,
70
+ });
71
+ const arrow = z.strictObject({
72
+ kind: z.literal('arrow'), x1: z.number(), y1: z.number(), x2: z.number(), y2: z.number(), color,
73
+ });
74
+ const draw = z.strictObject({
75
+ kind: z.literal('draw'),
76
+ points: z.array(z.tuple([z.number(), z.number()])).min(MIN_DRAW_POINTS),
77
+ color,
78
+ });
79
+ const text = z.strictObject({
80
+ kind: z.literal('text'), x: z.number(), y: z.number(), text: z.string().min(MIN_TEXT).max(MAX_TEXT), color,
81
+ });
82
+ const consoleEntry = z.strictObject({
83
+ level: z.enum(CONSOLE_LEVELS),
84
+ message: z.string().max(MAX_MESSAGE),
85
+ stack: z.string().max(MAX_STACK).optional(),
86
+ source: z.string().optional(),
87
+ timestamp: dateTime(),
88
+ count: int().min(MIN_CONSOLE_COUNT),
89
+ });
90
+ const networkEntry = z.strictObject({
91
+ method: z.string(),
92
+ url: z.string(),
93
+ status: z.union([int().min(MIN_ERROR_STATUS), z.literal(NETWORK_STATUS_STRINGS[0]), z.literal(NETWORK_STATUS_STRINGS[1])]),
94
+ durationMs: int(),
95
+ timestamp: dateTime(),
96
+ });
97
+
98
+ const mark = z.discriminatedUnion('kind', [pin, box, element, arrow, draw, text]);
99
+
100
+ const reportSchema = z.strictObject({
101
+ schemaVersion: z.literal(SCHEMA_VERSION),
102
+ // The host's rule (relay + relayBoxesMock UUID_RE): any 8-4-4-4-12 hex, case-insensitive, no
103
+ // version/variant check — so the desktop never rejects a report the host already accepted.
104
+ clientReportId: z.string().regex(CLIENT_REPORT_ID_RE),
105
+ project: z.string(),
106
+ type: z.enum(REPORT_TYPES),
107
+ title: z.string().trim().min(MIN_TITLE).max(MAX_TITLE),
108
+ details: z.string().trim().max(MAX_DETAILS),
109
+ createdAt: dateTime(),
110
+ page: z.strictObject({
111
+ url: z.string(),
112
+ title: z.string(),
113
+ viewport: z.strictObject({
114
+ width: int(), height: int(), devicePixelRatio: z.number(), scrollX: int(), scrollY: int(),
115
+ }),
116
+ }),
117
+ screenshot: z.strictObject({
118
+ part: z.literal('screenshot'),
119
+ annotatedPart: z.literal('annotated'),
120
+ width: int(),
121
+ height: int(),
122
+ scale: z.number(),
123
+ }),
124
+ marks: z.array(mark),
125
+ console: z.array(consoleEntry).max(MAX_CONSOLE).nullable(),
126
+ network: z.array(networkEntry).max(MAX_NETWORK).nullable(),
127
+ user: z.looseObject({ id: z.string(), name: z.string().optional(), email: z.string().optional() }).nullable(),
128
+ client: z.strictObject({
129
+ widgetVersion: z.string(),
130
+ captureError: z.string().max(MAX_CAPTURE_ERROR).optional(),
131
+ }),
132
+ });
133
+
134
+ /**
135
+ * @typedef {z.infer<typeof reportSchema>} Report
136
+ * @typedef {{ ok: true, report: Report } | { ok: false, error: string }} ParseResult
137
+ */
138
+
139
+ /**
140
+ * Validate an untrusted Report v1 value. Never throws.
141
+ * @param {unknown} value
142
+ * @returns {ParseResult}
143
+ */
144
+ function parseReport(value) {
145
+ const r = reportSchema.safeParse(value);
146
+ if (r.success) return { ok: true, report: r.data };
147
+ const issue = r.error.issues[0];
148
+ const where = issue && issue.path.length ? issue.path.map(String).join('.') : '(root)';
149
+ return { ok: false, error: `${where}: ${issue ? issue.code : 'invalid'}` };
150
+ }
151
+
152
+ const MAX_CONTEXT_BYTES = 262144;
153
+
154
+ /**
155
+ * The structured widget context the host stores opaquely (Bilko 76e88612: <= 262144 bytes of
156
+ * JSON, 413 above). Every part is optional; each part that is present obeys the Report v1 rules.
157
+ */
158
+ const contextSchema = z.strictObject({
159
+ page: reportSchema.shape.page.optional(),
160
+ marks: reportSchema.shape.marks.optional(),
161
+ console: reportSchema.shape.console.optional(),
162
+ network: reportSchema.shape.network.optional(),
163
+ client: z.strictObject({
164
+ widgetVersion: z.string().optional(),
165
+ captureError: z.string().max(MAX_CAPTURE_ERROR).optional(),
166
+ }).optional(),
167
+ });
168
+
169
+ /**
170
+ * @typedef {z.infer<typeof contextSchema>} FeedbackContext
171
+ * @typedef {{ ok: true, context: FeedbackContext } | { ok: false, error: string }} ContextResult
172
+ */
173
+
174
+ /**
175
+ * Validate an untrusted feedback context. Never throws; errors name only the path and issue code.
176
+ * @param {unknown} value
177
+ * @returns {ContextResult}
178
+ */
179
+ function parseContext(value) {
180
+ let bytes;
181
+ try {
182
+ const json = JSON.stringify(value);
183
+ bytes = typeof json === 'string' ? Buffer.byteLength(json, 'utf8') : 0;
184
+ } catch {
185
+ return { ok: false, error: 'context: not serializable' };
186
+ }
187
+ if (bytes > MAX_CONTEXT_BYTES) return { ok: false, error: `context: too_big (over ${MAX_CONTEXT_BYTES} bytes)` };
188
+ const r = contextSchema.safeParse(value);
189
+ if (r.success) return { ok: true, context: r.data };
190
+ const issue = r.error.issues[0];
191
+ const where = issue && issue.path.length ? `context.${issue.path.map(String).join('.')}` : 'context';
192
+ return { ok: false, error: `${where}: ${issue ? issue.code : 'invalid'}` };
193
+ }
194
+
195
+ /**
196
+ * Map a report type to the customer feedback inbox tag.
197
+ * @param {(typeof REPORT_TYPES)[number]} type
198
+ * @returns {'bug' | 'feature' | 'discussion'}
199
+ */
200
+ function toInboxTag(type) {
201
+ return INBOX_TAG[type] || 'discussion';
202
+ }
203
+
204
+ module.exports = {
205
+ parseReport,
206
+ parseContext,
207
+ toInboxTag,
208
+ reportSchema,
209
+ contextSchema,
210
+ MAX_CONTEXT_BYTES,
211
+ SCHEMA_VERSION,
212
+ REPORT_TYPES,
213
+ MARK_COLORS,
214
+ MARK_KINDS,
215
+ CONSOLE_LEVELS,
216
+ NETWORK_STATUS_STRINGS,
217
+ MIN_TITLE,
218
+ MAX_TITLE,
219
+ MAX_DETAILS,
220
+ MAX_NOTE,
221
+ MIN_TEXT,
222
+ MAX_TEXT,
223
+ MIN_DRAW_POINTS,
224
+ MIN_BOX_EDGE,
225
+ MIN_MARK_N,
226
+ MAX_ELEMENT_TEXT,
227
+ MAX_CONSOLE,
228
+ MAX_NETWORK,
229
+ MAX_MESSAGE,
230
+ MAX_STACK,
231
+ MIN_CONSOLE_COUNT,
232
+ MIN_ERROR_STATUS,
233
+ MAX_CAPTURE_ERROR,
234
+ };
@@ -0,0 +1,217 @@
1
+ // @ts-check
2
+ /**
3
+ * feedbackSeal — desktop half of the sealed feedback envelope (v1).
4
+ *
5
+ * A feedback box owns a P-256 key pair. A sender seals a payload to the box's
6
+ * public key with an ephemeral P-256 key; only the box's private key opens it.
7
+ *
8
+ * Envelope v1:
9
+ * 'SMF1' | uint16 BE header length (<= 1024) | UTF-8 header JSON
10
+ * { v:1, kid, epk, iv, ct } | AES-256-GCM ciphertext || 16-byte tag
11
+ * key = HKDF-SHA256(ECDH(ephemeral, box), salt = epk raw || box pub raw,
12
+ * info = 'sm-feedback/1|' + boxId, 32 bytes)
13
+ * AAD = magic || length || header bytes
14
+ *
15
+ * Test vectors: web/feedback-widget/schema/seal-vectors.v1.json (the browser
16
+ * implementation proves byte compatibility against the same file).
17
+ */
18
+ 'use strict';
19
+
20
+ const crypto = require('node:crypto');
21
+
22
+ const MAGIC = Buffer.from('SMF1', 'ascii');
23
+ const MAX_HEADER_LEN = 1024;
24
+ const IV_LEN = 12;
25
+ const TAG_LEN = 16;
26
+ const POINT_LEN = 65;
27
+ const INFO_PREFIX = 'sm-feedback/1|';
28
+
29
+ /** @param {string} code */
30
+ function fail(code) {
31
+ return new Error(code);
32
+ }
33
+
34
+ /**
35
+ * @param {crypto.KeyObject} keyObj public or private EC key
36
+ * @returns {Buffer} 65-byte uncompressed point 0x04||x||y
37
+ */
38
+ function rawPointOf(keyObj) {
39
+ const pub = keyObj.type === 'private' ? crypto.createPublicKey(keyObj) : keyObj;
40
+ const jwk = pub.export({ format: 'jwk' });
41
+ return pointFromXY(String(jwk.x), String(jwk.y));
42
+ }
43
+
44
+ /** @param {string} x @param {string} y */
45
+ function pointFromXY(x, y) {
46
+ const bx = Buffer.from(x, 'base64url');
47
+ const by = Buffer.from(y, 'base64url');
48
+ if (bx.length !== 32 || by.length !== 32) throw fail('bad_key');
49
+ return Buffer.concat([Buffer.from([0x04]), bx, by]);
50
+ }
51
+
52
+ /** @param {Buffer} raw 65-byte uncompressed point */
53
+ function publicKeyFromRaw(raw) {
54
+ if (raw.length !== POINT_LEN || raw[0] !== 0x04) throw fail('bad_key');
55
+ return crypto.createPublicKey({
56
+ key: {
57
+ kty: 'EC',
58
+ crv: 'P-256',
59
+ x: raw.subarray(1, 33).toString('base64url'),
60
+ y: raw.subarray(33, 65).toString('base64url'),
61
+ },
62
+ format: 'jwk',
63
+ });
64
+ }
65
+
66
+ /** @param {crypto.JsonWebKey} jwk */
67
+ function privateKeyFromJwk(jwk) {
68
+ return crypto.createPrivateKey({ key: jwk, format: 'jwk' });
69
+ }
70
+
71
+ /**
72
+ * @returns {{ publicKey: string, privateKeyJwk: crypto.JsonWebKey }}
73
+ */
74
+ function generateBoxKeypair() {
75
+ const { privateKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
76
+ return {
77
+ publicKey: rawPointOf(privateKey).toString('base64url'),
78
+ privateKeyJwk: privateKey.export({ format: 'jwk' }),
79
+ };
80
+ }
81
+
82
+ /**
83
+ * @param {string} publicKey base64url raw point
84
+ * @returns {string} first 22 chars of base64url(sha256(raw point))
85
+ */
86
+ function keyFingerprint(publicKey) {
87
+ const raw = Buffer.from(publicKey, 'base64url');
88
+ return crypto.createHash('sha256').update(raw).digest('base64url').slice(0, 22);
89
+ }
90
+
91
+ /**
92
+ * @param {crypto.KeyObject} priv
93
+ * @param {crypto.KeyObject} pub
94
+ * @param {Buffer} epkRaw
95
+ * @param {Buffer} boxRaw
96
+ * @param {string} boxId
97
+ */
98
+ function deriveKey(priv, pub, epkRaw, boxRaw, boxId) {
99
+ const shared = crypto.diffieHellman({ privateKey: priv, publicKey: pub });
100
+ const salt = Buffer.concat([epkRaw, boxRaw]);
101
+ const info = Buffer.from(INFO_PREFIX + boxId, 'utf8');
102
+ return Buffer.from(crypto.hkdfSync('sha256', shared, salt, info, 32));
103
+ }
104
+
105
+ /** @param {number} len */
106
+ function prefix(len) {
107
+ const b = Buffer.alloc(6);
108
+ MAGIC.copy(b, 0);
109
+ b.writeUInt16BE(len, 4);
110
+ return b;
111
+ }
112
+
113
+ /**
114
+ * @param {Buffer|Uint8Array|string} plaintext
115
+ * @param {string} contentType
116
+ * @param {string} publicKey base64url raw box point
117
+ * @param {string} boxId
118
+ * @param {{ ephemeralPrivateKeyJwk?: crypto.JsonWebKey, iv?: Buffer|Uint8Array|string }} [opts]
119
+ * test-vector-only overrides; production passes none.
120
+ * @returns {Buffer}
121
+ */
122
+ function sealEnvelope(plaintext, contentType, publicKey, boxId, opts) {
123
+ if (typeof contentType !== 'string' || !contentType) throw new TypeError('contentType required');
124
+ if (typeof boxId !== 'string' || !boxId) throw new TypeError('boxId required');
125
+ const boxRaw = Buffer.from(publicKey, 'base64url');
126
+ const boxPub = publicKeyFromRaw(boxRaw);
127
+ const ephPriv = opts && opts.ephemeralPrivateKeyJwk
128
+ ? privateKeyFromJwk(opts.ephemeralPrivateKeyJwk)
129
+ : crypto.generateKeyPairSync('ec', { namedCurve: 'prime256v1' }).privateKey;
130
+ const epkRaw = rawPointOf(ephPriv);
131
+ let iv;
132
+ if (opts && opts.iv != null) {
133
+ iv = typeof opts.iv === 'string' ? Buffer.from(opts.iv, 'base64url') : Buffer.from(opts.iv);
134
+ } else {
135
+ iv = crypto.randomBytes(IV_LEN);
136
+ }
137
+ if (iv.length !== IV_LEN) throw new TypeError('iv must be 12 bytes');
138
+
139
+ const header = Buffer.from(JSON.stringify({
140
+ v: 1,
141
+ kid: keyFingerprint(publicKey),
142
+ epk: epkRaw.toString('base64url'),
143
+ iv: iv.toString('base64url'),
144
+ ct: contentType,
145
+ }), 'utf8');
146
+ if (header.length > MAX_HEADER_LEN) throw new TypeError('header too large');
147
+ const aad = Buffer.concat([prefix(header.length), header]);
148
+
149
+ const key = deriveKey(ephPriv, boxPub, epkRaw, boxRaw, boxId);
150
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
151
+ cipher.setAAD(aad);
152
+ const body = typeof plaintext === 'string' ? Buffer.from(plaintext, 'utf8') : Buffer.from(plaintext);
153
+ const ct = Buffer.concat([cipher.update(body), cipher.final(), cipher.getAuthTag()]);
154
+ return Buffer.concat([aad, ct]);
155
+ }
156
+
157
+ /**
158
+ * @param {Buffer|Uint8Array} buf
159
+ * @param {crypto.JsonWebKey} privateKeyJwk
160
+ * @param {string} boxId
161
+ * @returns {{ contentType: string, body: Buffer }}
162
+ * @throws {Error} message 'bad_envelope' | 'decrypt_failed'
163
+ */
164
+ function openEnvelope(buf, privateKeyJwk, boxId) {
165
+ const b = Buffer.isBuffer(buf) ? buf : Buffer.from(buf || []);
166
+ if (b.length < 6 || !b.subarray(0, 4).equals(MAGIC)) throw fail('bad_envelope');
167
+ const hlen = b.readUInt16BE(4);
168
+ if (hlen === 0 || hlen > MAX_HEADER_LEN || b.length < 6 + hlen + TAG_LEN) throw fail('bad_envelope');
169
+ const aad = b.subarray(0, 6 + hlen);
170
+ /** @type {unknown} */
171
+ let parsed;
172
+ try {
173
+ parsed = JSON.parse(b.subarray(6, 6 + hlen).toString('utf8'));
174
+ } catch {
175
+ throw fail('bad_envelope');
176
+ }
177
+ const h = /** @type {Record<string, unknown>} */ (parsed && typeof parsed === 'object' ? parsed : {});
178
+ if (h.v !== 1 || typeof h.kid !== 'string' || typeof h.epk !== 'string'
179
+ || typeof h.iv !== 'string' || typeof h.ct !== 'string') {
180
+ throw fail('bad_envelope');
181
+ }
182
+ const kid = h.kid;
183
+ const contentType = h.ct;
184
+ const iv = Buffer.from(h.iv, 'base64url');
185
+ const epkRaw = Buffer.from(h.epk, 'base64url');
186
+ if (iv.length !== IV_LEN) throw fail('bad_envelope');
187
+ /** @type {crypto.KeyObject} */
188
+ let epk;
189
+ try {
190
+ epk = publicKeyFromRaw(epkRaw);
191
+ } catch {
192
+ throw fail('bad_envelope');
193
+ }
194
+
195
+ try {
196
+ const priv = privateKeyFromJwk(privateKeyJwk);
197
+ const boxRaw = rawPointOf(priv);
198
+ if (keyFingerprint(boxRaw.toString('base64url')) !== kid) throw fail('decrypt_failed');
199
+ const key = deriveKey(priv, epk, epkRaw, boxRaw, String(boxId));
200
+ const data = b.subarray(6 + hlen);
201
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
202
+ decipher.setAAD(aad);
203
+ decipher.setAuthTag(data.subarray(data.length - TAG_LEN));
204
+ const body = Buffer.concat([decipher.update(data.subarray(0, data.length - TAG_LEN)), decipher.final()]);
205
+ return { contentType, body };
206
+ } catch {
207
+ throw fail('decrypt_failed');
208
+ }
209
+ }
210
+
211
+ module.exports = {
212
+ generateBoxKeypair,
213
+ keyFingerprint,
214
+ sealEnvelope,
215
+ openEnvelope,
216
+ MAX_HEADER_LEN,
217
+ };
@@ -34,12 +34,14 @@
34
34
  const http = require('node:http');
35
35
  const path = require('node:path');
36
36
  const crypto = require('node:crypto');
37
+ const { Readable } = require('node:stream');
38
+ const { EventEmitter } = require('node:events');
37
39
  const fsp = require('node:fs/promises');
38
40
  const config = require('../../config.cjs');
39
41
  const schedulerPaths = require('../scheduler/schedulerPaths.cjs');
40
42
  // App + outside-contract version, reported on the health route, unknown-route
41
43
  // 404s and in the token file so outside callers never probe for a route.
42
- const { contractInfo } = require('../externalContract.cjs');
44
+ const { contractInfo, healthInfo } = require('../externalContract.cjs');
43
45
 
44
46
  /**
45
47
  * Mode-aware token file path, resolved fresh on every call (never cached at
@@ -134,6 +136,14 @@ function createAdminHttp() {
134
136
  sendJson(res, 401, { ok: false, error: 'unauthorized' });
135
137
  return;
136
138
  }
139
+ await dispatch(req, res);
140
+ }
141
+
142
+ /**
143
+ * Route dispatch shared by the HTTP server (after auth) and invoke() (no
144
+ * auth — in-process callers are already inside the main process).
145
+ */
146
+ async function dispatch(req, res) {
137
147
  // Route lookup is keyed by pathname only — req.url carries the raw query
138
148
  // string too, which would otherwise never match a registered route (every
139
149
  // route before PRD 1024 was query-free, so this was a latent gap, not a
@@ -142,7 +152,7 @@ function createAdminHttp() {
142
152
  // /admin/scheduler/prds?cwd=&epicId=&status=).
143
153
  const urlObj = new URL(req.url, 'http://127.0.0.1');
144
154
  if (req.method === 'GET' && urlObj.pathname === HEALTH_PATH) {
145
- sendJson(res, 200, { ok: true, ...contractInfo() });
155
+ sendJson(res, 200, { ok: true, ...healthInfo() });
146
156
  return;
147
157
  }
148
158
  try {
@@ -221,15 +231,111 @@ function createAdminHttp() {
221
231
  server = null;
222
232
  }
223
233
 
234
+ /**
235
+ * In-process call into a registered route — same handler, validation,
236
+ * idempotency and audit rows as the HTTP API, with no socket and no bearer
237
+ * token. `query` may be a plain object or URLSearchParams; it is merged
238
+ * onto any query already in `routePath`. `body` (any JSON value) is
239
+ * serialized and streamed to the handler like an HTTP request body.
240
+ * Resolves { status, json } (json null when the handler wrote non-JSON).
241
+ */
242
+ async function invoke(method, routePath, { body, query } = {}) {
243
+ const urlObj = new URL(routePath, 'http://127.0.0.1');
244
+ if (query) {
245
+ const params = query instanceof URLSearchParams ? query : new URLSearchParams(
246
+ Object.entries(query).filter(([, v]) => v !== undefined && v !== null).map(([k, v]) => [k, String(v)]),
247
+ );
248
+ for (const [k, v] of params) urlObj.searchParams.append(k, v);
249
+ }
250
+ const payload = body === undefined ? '' : JSON.stringify(body);
251
+ const req = createInMemoryRequest(String(method).toUpperCase(), `${urlObj.pathname}${urlObj.search}`, payload);
252
+ const res = createResponseShim();
253
+ try {
254
+ await dispatch(req, res);
255
+ } catch (e) {
256
+ if (!res.writableEnded) sendJson(res, 500, { ok: false, error: e?.message ?? 'internal error' });
257
+ }
258
+ return res.result();
259
+ }
260
+
224
261
  return {
225
262
  start,
226
263
  stop,
227
264
  registerRoute,
265
+ invoke,
228
266
  get token() { return token; },
229
267
  get server() { return server; },
230
268
  };
231
269
  }
232
270
 
271
+ /** In-memory IncomingMessage stand-in: a Readable carrying the JSON body. */
272
+ function createInMemoryRequest(method, url, payload) {
273
+ const buf = Buffer.from(payload, 'utf8');
274
+ const req = new Readable({ read() {} });
275
+ if (buf.length) req.push(buf);
276
+ req.push(null);
277
+ req.method = method;
278
+ req.url = url;
279
+ req.headers = buf.length
280
+ ? { 'content-type': 'application/json', 'content-length': String(buf.length) }
281
+ : {};
282
+ req.socket = null;
283
+ req.setTimeout = () => req;
284
+ return req;
285
+ }
286
+
287
+ /** ServerResponse stand-in capturing status, headers and the written body. */
288
+ function createResponseShim() {
289
+ const res = new EventEmitter();
290
+ const chunks = [];
291
+ const headers = {};
292
+ res.statusCode = 200;
293
+ res.headersSent = false;
294
+ res.writableEnded = false;
295
+ res.finished = false;
296
+ res.destroyed = false;
297
+ res.writableLength = 0;
298
+ res.setHeader = (name, value) => { headers[String(name).toLowerCase()] = value; return res; };
299
+ res.getHeader = (name) => headers[String(name).toLowerCase()];
300
+ res.removeHeader = (name) => { delete headers[String(name).toLowerCase()]; };
301
+ res.writeHead = (status, a, b) => {
302
+ res.statusCode = status;
303
+ const hdrs = typeof a === 'object' && a !== null ? a : b;
304
+ if (hdrs && typeof hdrs === 'object') for (const [k, v] of Object.entries(hdrs)) res.setHeader(k, v);
305
+ res.headersSent = true;
306
+ return res;
307
+ };
308
+ const toBuf = (chunk, enc) => (Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), typeof enc === 'string' ? enc : 'utf8'));
309
+ res.write = (chunk, enc, cb) => {
310
+ if (chunk !== undefined && chunk !== null) chunks.push(toBuf(chunk, enc));
311
+ res.headersSent = true;
312
+ const done = typeof enc === 'function' ? enc : cb;
313
+ if (typeof done === 'function') done();
314
+ return true;
315
+ };
316
+ res.end = (chunk, enc, cb) => {
317
+ if (res.writableEnded) return res;
318
+ if (typeof chunk === 'function') { cb = chunk; chunk = undefined; }
319
+ if (chunk !== undefined && chunk !== null) chunks.push(toBuf(chunk, enc));
320
+ res.headersSent = true;
321
+ res.writableEnded = true;
322
+ res.finished = true;
323
+ const done = typeof enc === 'function' ? enc : cb;
324
+ if (typeof done === 'function') done();
325
+ res.emit('finish');
326
+ res.emit('close');
327
+ return res;
328
+ };
329
+ res.destroy = () => { res.destroyed = true; res.emit('close'); return res; };
330
+ res.result = () => {
331
+ const text = Buffer.concat(chunks).toString('utf8');
332
+ let json = null;
333
+ try { json = text ? JSON.parse(text) : null; } catch { json = null; }
334
+ return { status: res.statusCode, json };
335
+ };
336
+ return res;
337
+ }
338
+
233
339
  module.exports = {
234
340
  createAdminHttp,
235
341
  resolveTokenPath,
@@ -3,7 +3,7 @@
3
3
  * the scheduler MCP) can list, create/update and delete a HOT KEYS macro
4
4
  * for its own project, through the existing macroLibrary.cjs store:
5
5
  * GET /admin/macros?cwd=… -> { ok, macros }
6
- * POST /admin/macros/save {cwd, id?, label, agentName, tag, prompt, inputs?, surface?, job?}
6
+ * POST /admin/macros/save {cwd, id?, label, agentName, tag, prompt, inputs?, surface?, job?, voiceId?}
7
7
  * POST /admin/macros/delete {cwd, id, originClaudeSessionId?}
8
8
  * -> { ok, deleted, macro }
9
9
  * delete removes the macro from THIS project through
@@ -63,6 +63,7 @@
63
63
  'use strict';
64
64
 
65
65
  const { readBody, sendJson } = require('./localAdminHttp.cjs');
66
+ const { usageHeldBody } = require('../scheduler/usageHoldRoute.cjs');
66
67
  const { resolveCwd } = require('./projectHomeAdminRoutes.cjs');
67
68
  const macroLibrary = require('../persona-macro/macroLibrary.cjs');
68
69
  const { appendAuditEvent } = require('../telemetry/auditLog.cjs');
@@ -180,6 +181,7 @@ function saveHandler(onChanged, libOpts, deps = {}) {
180
181
  inputs: body.inputs,
181
182
  surface: body.surface,
182
183
  job: body.job,
184
+ voiceId: body.voiceId,
183
185
  });
184
186
  } catch (e) {
185
187
  sendJson(res, 400, { ok: false, error: e?.issues?.[0]?.message ?? e?.message ?? 'invalid payload' });
@@ -407,6 +409,8 @@ function runHandler(deps, libOpts) {
407
409
  return;
408
410
  }
409
411
 
412
+ if (refusedByUsageHold(deps, res)) return;
413
+
410
414
  const payload = {
411
415
  cwd,
412
416
  agentName: macro.agentName,
@@ -450,6 +454,30 @@ function runHandler(deps, libOpts) {
450
454
  };
451
455
  }
452
456
 
457
+ const USAGE_HOLD_HINT =
458
+ "Usage is above 'pause above': script presses wait until the window resets or usage drops below it. "
459
+ + 'Retry after hold.resetsAt. GET /admin/usage-hold reads the hold.';
460
+
461
+ /**
462
+ * The usage hold ('pause above') gate in front of every script-press
463
+ * startExternalNewSession call. Replies 429 usage_held / 503 usage_hold_error
464
+ * and returns true when the press must not start; false when it may.
465
+ * Read lazily so scheduler.cjs never loads at module load.
466
+ */
467
+ function refusedByUsageHold(deps, res) {
468
+ const usageHold = deps.usageHold || (() => require('../../scheduler.cjs').currentUsageHold());
469
+ let hold;
470
+ try {
471
+ hold = usageHold();
472
+ } catch (e) {
473
+ sendJson(res, 503, { ok: false, error: 'usage_hold_error', details: e instanceof Error ? e.message : String(e) });
474
+ return true;
475
+ }
476
+ if (!hold) return false;
477
+ sendJson(res, 429, usageHeldBody(hold, USAGE_HOLD_HINT));
478
+ return true;
479
+ }
480
+
453
481
  /** 503 error text for a failed startExternalNewSession result. */
454
482
  function launchFailureError(result) {
455
483
  return result?.reason === 'timeout'
@@ -499,6 +527,8 @@ async function runWithExternalRef({ deps, res, cwd, macro, prompt, effort, exter
499
527
  recentRuns.delete(key);
500
528
  }
501
529
 
530
+ if (refusedByUsageHold(deps, res)) return;
531
+
502
532
  const payload = {
503
533
  cwd,
504
534
  agentName: macro.agentName,
@@ -558,6 +588,7 @@ async function runWithExternalRef({ deps, res, cwd, macro, prompt, effort, exter
558
588
  /**
559
589
  * @param {{ onChanged?: () => void, startExternalNewSession?: (p: object) => Promise<any>,
560
590
  * isTabBusy?: (tabId: string) => boolean, listPersonas?: () => Promise<Array<{name: string}>>,
591
+ * usageHold?: () => any,
561
592
  * checkProjectVideoToolRunnable?: (i: { cwd: string, agentName: string, job: object }) => Promise<{ ok: boolean, error?: string }> }} deps
562
593
  */
563
594
  function registerAdminRoute(adminHttp, deps = {}, opts = {}) {