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
@@ -6,38 +6,81 @@
6
6
  * cap, recorded in that project's Task ledger. Order:
7
7
  * 1. strict body schema (400 invalid_request), sessionId+resume /
8
8
  * resume+persistSession:false / missing mcpConfig file (400);
9
- * 2. the human switch 'Scripts may run Tasks' (403 tasks_disabled);
9
+ * 2. the held interactive slot is re-synced from the switch file
10
+ * (taskSwitch.syncInteractiveReserve; a throw is ignored), then the
11
+ * human switch 'Scripts may run Tasks' (403 tasks_disabled);
10
12
  * 3. persona → model + effort with the SPAWN-time resolvers
11
13
  * (agentModelResolve.cjs / agentEffortResolve.cjs — never
12
14
  * FALLBACK_MODEL, never effectiveModelInfo.cjs): 404 unknown_agent,
13
15
  * 422 model_unresolved, 422 effort_unresolved. The persona BODY is
14
16
  * never read into the prompt or argv;
15
17
  * 4. 409 session_busy when another running Task holds the session;
16
- * 5. ledger start line, THEN sessionSlots.waitForSlot by priority lane
18
+ * then buildTaskArgs (400);
19
+ * 5. the usage hold (scheduler.currentUsageHold — the same 'pause
20
+ * above' rule the PRD queue holds at): a hold → 429 usage_held
21
+ * { hold: { reason, window, percent, threshold, resetsAt }, detail,
22
+ * hint }, a throw → 503 usage_hold_error, both before any ledger
23
+ * line. No body key, priority or caller bypasses it — this loopback
24
+ * route cannot prove a human. One 'task_usage_held' audit event per
25
+ * project root per hold (holdIdentityKey), not per request;
26
+ * 6. ledger start line, THEN sessionSlots.waitForSlot by priority lane
17
27
  * (null → 'slot_timeout', too_many_waiting → 429);
18
- * 6. taskRun.runTask, token released in finally, ledger end line with
28
+ * 7. once the slot is granted the usage hold is read AGAIN: a hold or
29
+ * a throw releases the token and writes the end line status
30
+ * 'usage_held' + slotWaitMs; a hold replies 429 usage_held, a throw
31
+ * 503 usage_hold_error (both + taskId, slotWaitMs) — a Task that
32
+ * waited through the hold never spawns;
33
+ * 8. taskRun.runTask, token released in finally, ledger end line with
19
34
  * costUsd from modelPricing.costOfUsage;
20
- * 7. 200 { ok: true, taskId, status, stdout, envelope, usage, costUsd,
35
+ * 9. 200 { ok: true, taskId, status, stdout, envelope, usage, costUsd,
21
36
  * cliCostUsd, durationMs, slotWaitMs, exitCode, model, effort,
22
37
  * sessionId, quota }.
23
38
  * A req/res 'close' before the reply aborts the wait or the run
24
39
  * ('caller_gone'); the route disables the socket timeout (runs are long).
25
40
  *
41
+ * Stream mode (body stream: true): every refusal before the ledger start
42
+ * line keeps its status + JSON body. After the start line the route answers
43
+ * 200 application/x-ndjson, one JSON object per line:
44
+ * {type:'sm_task_started', taskId, model, effort, sessionId, startedAt}
45
+ * — written before the slot wait;
46
+ * {type:'sm_task_running', slotWaitMs} — once the slot is granted;
47
+ * each child stdout line as it arrives: as-is when it parses as a JSON
48
+ * object, else {type:'sm_task_stdout', text};
49
+ * {type:'sm_task_result', ...} — last: the non-stream 200 reply plus
50
+ * droppedLines, or the error object the JSON reply would carry
51
+ * (e.g. ok:false, error:'slot_timeout', taskId, slotWaitMs).
52
+ * A 'close' before the result line still aborts the wait or the run
53
+ * (caller_gone). While res.writableLength exceeds 8 MiB, output lines are
54
+ * skipped and counted in droppedLines, so a caller that stops reading
55
+ * cannot grow memory. The stream never carries stderr, env or argv.
56
+ *
26
57
  * GET /admin/tasks?cwd=&since=&until=&pipeline=&runId=&step=&agent=&status=&source=&limit=&offset=
27
58
  * → { ok, tasks, total, hasMore } from taskLedger.listTasks. Each task has
28
59
  * exactly TASK_FIELDS (no prompt/output text). Works whatever the switch.
29
- * GET /admin/task?cwd=&id=
60
+ * GET /admin/task?cwd=&id=&after=
30
61
  * → { ok, task } — TASK_FIELDS plus prompt, output, stderrTail, envelope
31
- * (and the truncation flags) from the body file; 404 unknown_task.
62
+ * (and the truncation flags) from the body file, plus live; 404 unknown_task.
63
+ * A Task this process is still running (the in-process live registry,
64
+ * filled from every POST run's stdout lines) answers status 'running',
65
+ * output = the captured lines from byte offset `after` (default 0), up to
66
+ * 1 MiB cut at a line boundary, outputTruncated when more remain, and
67
+ * live = { slotAcquired, outputEnd, outputCapped } (pass outputEnd as the
68
+ * next `after`). Any other Task: live null; `after` slices the stored
69
+ * output by bytes, rounded forward to a line boundary. GET /admin/tasks
70
+ * also reports a live Task as 'running', never 'interrupted'.
32
71
  * POST /admin/tasks/import (body ≤ 8 MiB)
33
72
  * { cwd, records: 1-100 } — direct `claude -p` calls a caller made while
34
- * Session Manager was down. 403 tasks_disabled when the switch is off.
73
+ * Session Manager was down. Re-syncs the held interactive slot from the
74
+ * switch file, then 403 tasks_disabled when the switch is off.
35
75
  * Each record is validated on its own and recorded with
36
76
  * taskLedger.appendImported (source 'direct'); a known (cwd, importId) is
37
77
  * skipped. costUsd is recomputed with costOfUsage when usage is present
38
78
  * (the caller's figure is kept as cliCostUsd).
39
79
  * → { ok, imported, alreadyImported, rejected: [{ index, error }] }.
40
80
  * Read and import routes take a cwd that must be a project root (400).
81
+ * POST /admin/tasks/switch (taskSwitchRoute.cjs, registered from here)
82
+ * The agent path for the switch: sets one project's switch only on a
83
+ * verified verbatim quote of the human's own chat prompt naming it.
41
84
  *
42
85
  * No caller environment variable ever reaches the child (buildTaskEnv adds
43
86
  * only the Task markers to process.env). Auth/loopback binding are the
@@ -51,18 +94,50 @@ const crypto = require('node:crypto');
51
94
  const { z } = require('zod');
52
95
  const { readBody, sendJson } = require('../feedback-remote/localAdminHttp.cjs');
53
96
  const { resolveProjectRoot } = require('../opsOwnership.cjs');
97
+ const { phaseOfTask } = require('../phaseProjection.cjs');
98
+ const { registerTaskSwitchRoute } = require('./taskSwitchRoute.cjs');
99
+ const { usageHeldBody } = require('../scheduler/usageHoldRoute.cjs');
54
100
 
55
101
  const MAX_BODY_BYTES = 4 * 1024 * 1024;
56
102
  const MAX_IMPORT_BODY_BYTES = 8 * 1024 * 1024;
57
103
  const MAX_IMPORT_RECORDS = 100;
58
104
  const MAX_SYSTEM_PROMPT_BYTES = 100 * 1024;
59
- const SWITCH_HINT = "Turn on 'Scripts may run Tasks' for this project on the Scheduler → Tasks page (a human-only switch).";
105
+ const SWITCH_HINT = "Turn on 'Scripts may run Tasks' for this project: a human flips it on the Scheduler → Tasks page, or an agent in a Session Manager chat calls task_switch_set with the human's own words asking for it.";
60
106
 
61
107
  function isAbsoluteDir(p) {
62
108
  if (typeof p !== 'string' || !path.isAbsolute(p)) return false;
63
109
  try { return fs.statSync(p).isDirectory(); } catch { return false; }
64
110
  }
65
111
 
112
+ const MAX_TOOL_RULES = 50;
113
+ const MAX_TOOL_RULE_CHARS = 500;
114
+
115
+ /**
116
+ * A permission rule the CLI's --disallowedTools list parser reads as ONE rule:
117
+ * trimmed-non-empty, <= 500 chars, no control characters, and when it has '('
118
+ * a tool name before it, a trailing ')' and balanced parentheses. An unbalanced
119
+ * '(' would make the CLI swallow later text into one broken rule — a deny that
120
+ * silently never applies — so it is refused, never passed on. The first
121
+ * character must be an ASCII letter (tool names and mcp__ rules all are), so a
122
+ * '-'-leading or space-leading value can never be read as a CLI flag.
123
+ * @param {unknown} s
124
+ */
125
+ function isValidToolRule(s) {
126
+ if (typeof s !== 'string') return false;
127
+ if (!/^[A-Za-z]/.test(s)) return false;
128
+ if (s.trim() === '' || s.length > MAX_TOOL_RULE_CHARS) return false;
129
+ if (/[\u0000-\u001f\u007f]/.test(s)) return false;
130
+ if (!s.includes('(') && !s.includes(')')) return true;
131
+ const open = s.indexOf('(');
132
+ if (open <= 0 || s.slice(0, open).trim() === '' || !s.endsWith(')')) return false;
133
+ let depth = 0;
134
+ for (const ch of s) {
135
+ if (ch === '(') depth += 1;
136
+ else if (ch === ')') { depth -= 1; if (depth < 0) return false; }
137
+ }
138
+ return depth === 0;
139
+ }
140
+
66
141
  const runtimeSchema = z.object({
67
142
  outputFormat: z.enum(['json', 'text', 'stream-json']).default('json'),
68
143
  settingSources: z.string().optional(),
@@ -75,6 +150,13 @@ const runtimeSchema = z.object({
75
150
  systemPrompt: z.string()
76
151
  .refine((s) => Buffer.byteLength(s, 'utf8') <= MAX_SYSTEM_PROMPT_BYTES, { message: `systemPrompt exceeds ${MAX_SYSTEM_PROMPT_BYTES} bytes` })
77
152
  .optional(),
153
+ appendSystemPrompt: z.string()
154
+ .refine((s) => Buffer.byteLength(s, 'utf8') <= MAX_SYSTEM_PROMPT_BYTES, { message: `appendSystemPrompt exceeds ${MAX_SYSTEM_PROMPT_BYTES} bytes` })
155
+ .optional(),
156
+ // Permission deny rules ('WebFetch(domain:localhost)'); each reaches the CLI as one
157
+ // '--disallowedTools=<rule>' element — after a bare variadic flag a '-'-leading value
158
+ // is parsed as a new flag, so the '=' form plus the leading-letter check stop injection.
159
+ disallowedTools: z.array(z.string().refine(isValidToolRule, { message: 'invalid tool rule' })).max(MAX_TOOL_RULES).optional(),
78
160
  skipPermissions: z.boolean().optional(),
79
161
  disableAutoMemory: z.boolean().optional(),
80
162
  sessionId: z.string().uuid().optional(),
@@ -98,8 +180,13 @@ const bodySchema = z.object({
98
180
  attempt: z.number().int().min(0).optional(),
99
181
  }).strict().default({}),
100
182
  runtime: runtimeSchema.default({ outputFormat: 'json' }),
183
+ // true → 200 application/x-ndjson after the ledger start line (see the header).
184
+ stream: z.boolean().optional(),
101
185
  }).strict();
102
186
 
187
+ /** Past this many unsent bytes in the response buffer, stream-mode output lines are dropped (and counted). */
188
+ const MAX_STREAM_BUFFER_BYTES = 8 * 1024 * 1024;
189
+
103
190
  /** Outcome statuses an imported record may carry: the ledger's end statuses (taskRun + route). */
104
191
  const IMPORT_STATUSES = /** @type {const} */ ([
105
192
  'ok', 'error', 'rate_limited', 'timeout', 'spawn_failed', 'caller_gone', 'slot_timeout', 'too_many_waiting', 'interrupted',
@@ -110,7 +197,7 @@ const TASK_FIELDS = Object.freeze([
110
197
  'taskId', 'source', 'importId', 'importedAt', 'agent', 'missionId', 'model', 'effort', 'priority', 'caller',
111
198
  'outputFormat', 'timeoutSec', 'slotWaitSec', 'sessionId', 'persisted', 'startedAt', 'endedAt', 'status',
112
199
  'exitCode', 'signal', 'durationMs', 'slotWaitMs', 'usage', 'costUsd', 'cliCostUsd', 'numTurns', 'quota',
113
- 'promptBytes', 'promptSha256', 'outputBytes', 'outputSha256',
200
+ 'promptBytes', 'promptSha256', 'outputBytes', 'outputSha256', 'phase',
114
201
  ]);
115
202
 
116
203
  /** @param {Record<string, any>} t a folded ledger Task → exactly TASK_FIELDS (missing → null). */
@@ -121,6 +208,7 @@ function publicTask(t) {
121
208
  if (!out.source) out.source = 'sm';
122
209
  if (out.caller == null) out.caller = {};
123
210
  out.persisted = t.persisted === true;
211
+ out.phase = phaseOfTask(t); // phaseProjection.cjs — never stored, derived from status
124
212
  return out;
125
213
  }
126
214
 
@@ -143,8 +231,90 @@ const listQuerySchema = z.object({
143
231
  const getQuerySchema = z.object({
144
232
  cwd: z.string().min(1),
145
233
  id: z.string().min(1).max(200),
234
+ // Byte offset into the Task's stdout to read from (a live Task's live.outputEnd).
235
+ after: z.string().regex(/^\d+$/).transform(Number).pipe(z.number().int().min(0)).optional(),
146
236
  }).strict();
147
237
 
238
+ /** Keys POST /admin/tasks accepts at the top level and under runtime, and GET /admin/task query keys (advertised on the health route via externalContract.cjs). */
239
+ const TASK_BODY_KEYS = Object.freeze(Object.keys(bodySchema.shape));
240
+ const TASK_RUNTIME_KEYS = Object.freeze(Object.keys(runtimeSchema.shape));
241
+ const TASK_GET_KEYS = Object.freeze(Object.keys(getQuerySchema.shape));
242
+
243
+ /** One GET /admin/task page of a live Task's captured output. */
244
+ const LIVE_PAGE_BYTES = 1024 * 1024;
245
+
246
+ /**
247
+ * A live Task's captured stdout: lines plus cumulative end byte offsets
248
+ * (ends[i] = bytes of lines[0..i] each counted with its '\n').
249
+ * @typedef {{ cwd: string, lines: string[], ends: number[], bytes: number,
250
+ * slotAcquired: boolean, outputCapped: boolean }} LiveTask
251
+ */
252
+
253
+ /** @param {number} cap @param {string} cwd @returns {LiveTask & { append: (line: string) => void }} */
254
+ function newLiveTask(cwd, cap) {
255
+ /** @type {any} */
256
+ const lt = { cwd, lines: [], ends: [], bytes: 0, slotAcquired: false, outputCapped: false };
257
+ lt.append = (/** @type {string} */ line) => {
258
+ if (lt.outputCapped) return;
259
+ const b = Buffer.byteLength(line + '\n', 'utf8');
260
+ if (lt.bytes + b > cap) { lt.outputCapped = true; return; }
261
+ lt.lines.push(line);
262
+ lt.bytes += b;
263
+ lt.ends.push(lt.bytes);
264
+ if (lt.bytes >= cap) lt.outputCapped = true;
265
+ };
266
+ return lt;
267
+ }
268
+
269
+ /**
270
+ * The page of a live Task's lines starting at byte offset `after`.
271
+ * Binary search for the first line whose START offset (ends[i-1], or 0) is
272
+ * >= after: O(log n) over n captured lines, then O(k) over the k lines taken
273
+ * (at most LIVE_PAGE_BYTES of them).
274
+ * @param {LiveTask} lt @param {number} after
275
+ * @returns {{ output: string, outputTruncated: boolean, outputEnd: number }}
276
+ */
277
+ function livePage(lt, after) {
278
+ const { lines, ends } = lt;
279
+ let lo = 0;
280
+ let hi = lines.length;
281
+ while (lo < hi) {
282
+ const mid = (lo + hi) >>> 1;
283
+ const start = mid === 0 ? 0 : ends[mid - 1];
284
+ if (start >= after) hi = mid; else lo = mid + 1;
285
+ }
286
+ const first = lo;
287
+ const pageStart = first === 0 ? 0 : ends[first - 1];
288
+ let i = first;
289
+ while (i < lines.length && ends[i] - pageStart <= LIVE_PAGE_BYTES) i += 1;
290
+ // A single line longer than a page is still delivered alone, so a reader always advances.
291
+ if (i === first && i < lines.length) i += 1;
292
+ const taken = lines.slice(first, i);
293
+ return {
294
+ output: taken.length ? taken.join('\n') + '\n' : '',
295
+ outputTruncated: i < lines.length,
296
+ outputEnd: i > first ? ends[i - 1] : after,
297
+ };
298
+ }
299
+
300
+ /**
301
+ * A finished Task's stored output from byte offset `after`, rounded forward to
302
+ * the next line boundary; an offset at or past the end gives ''. O(output bytes).
303
+ * @param {string} text @param {number} after
304
+ */
305
+ function sliceFromByte(text, after) {
306
+ if (!after) return text;
307
+ const buf = Buffer.from(text, 'utf8');
308
+ if (after >= buf.length) return '';
309
+ let start = after;
310
+ if (buf[start - 1] !== 0x0a) {
311
+ const nl = buf.indexOf(0x0a, start);
312
+ if (nl === -1) return '';
313
+ start = nl + 1;
314
+ }
315
+ return buf.subarray(start).toString('utf8');
316
+ }
317
+
148
318
  const callerSchema = z.object({
149
319
  pipeline: z.string().max(200).optional(),
150
320
  runId: z.string().max(200).optional(),
@@ -196,19 +366,27 @@ function issueText(/** @type {any} */ error) {
196
366
  * discarded here); model = persona `model` (overlay-aware) else the Settings
197
367
  * model — never agentModelResolve's FALLBACK_MODEL.
198
368
  * @param {{ cwd: string, agent: string }} a
199
- * @returns {Promise<{ personaFound: boolean, resolvedModelId: string|null, personaEffort: string|null }>}
369
+ * declaredMcpServers = the persona's `mcpServers:` (overlay-aware), the only
370
+ * MCP servers the strict Task spawn loads.
371
+ * @returns {Promise<{ personaFound: boolean, resolvedModelId: string|null, personaEffort: string|null, declaredMcpServers: string[] }>}
200
372
  */
201
373
  async function defaultResolveInfo({ cwd, agent }) {
202
- const { getPersonaBody } = require('../../agentLibrary.cjs');
374
+ const { getPersonaBody, parseCapabilityList } = require('../../agentLibrary.cjs');
203
375
  const persona = await getPersonaBody({ cwd, name: agent });
204
- if (!persona) return { personaFound: false, resolvedModelId: null, personaEffort: null };
376
+ if (!persona) return { personaFound: false, resolvedModelId: null, personaEffort: null, declaredMcpServers: [] };
205
377
  const { readOverlayAwarePersonaModel } = require('../claude/agentModelResolve.cjs');
206
378
  const { resolveEpicEffort } = require('../claude/agentEffortResolve.cjs');
207
379
  const { readSettingsModel } = require('../claude/modelCatalog.cjs');
208
380
  let model = readOverlayAwarePersonaModel(agent, { cwd });
209
381
  if (!model || model === 'inherit') model = readSettingsModel(cwd);
210
382
  const { effort } = resolveEpicEffort({ cwd, agentType: agent });
211
- return { personaFound: true, resolvedModelId: model || null, personaEffort: effort || null };
383
+ let declaredMcpServers = [];
384
+ try {
385
+ const { readOverlayAwarePersona } = require('../claude/agentModelResolve.cjs');
386
+ const p = readOverlayAwarePersona(agent, { cwd });
387
+ declaredMcpServers = parseCapabilityList(p && p.fm ? p.fm.mcpServers : undefined);
388
+ } catch { /* unreadable frontmatter → no declared servers (strict mode loads none) */ }
389
+ return { personaFound: true, resolvedModelId: model || null, personaEffort: effort || null, declaredMcpServers };
212
390
  }
213
391
 
214
392
  /** A real `--model` value: a non-empty string that is not the 'inherit' sentinel. */
@@ -237,13 +415,46 @@ function costFor(model, run, costOfUsage) {
237
415
  }
238
416
  }
239
417
 
418
+ /**
419
+ * The live registry (taskId → LiveTask) of the most recently registered
420
+ * POST /admin/tasks route. Production registers the route once; in tests the
421
+ * last registerAdminRoute call wins. null until a route is registered.
422
+ * @type {Map<string, { cwd: string }> | null}
423
+ */
424
+ let activeLiveTasks = null;
425
+
426
+ /**
427
+ * taskIds the most recently registered POST /admin/tasks route is running for
428
+ * project root `root` (path.resolve equality) — [] when none, or when no route
429
+ * is registered. The GET routes and the desktop Tasks IPC (taskIpc.cjs) pass
430
+ * these as liveTaskIds so every Task read folds a live run as running.
431
+ * Production registers the route once; in tests the last registration wins.
432
+ * @param {string} root
433
+ * @returns {string[]}
434
+ */
435
+ function liveTaskIdsFor(root) {
436
+ const ids = [];
437
+ if (!activeLiveTasks) return ids;
438
+ const want = path.resolve(root);
439
+ for (const [id, lt] of activeLiveTasks) if (path.resolve(lt.cwd) === want) ids.push(id);
440
+ return ids;
441
+ }
442
+
443
+ const USAGE_HOLD_HINT =
444
+ "Usage is above 'pause above': automatic Tasks wait until the window resets or usage drops below it. "
445
+ + 'Retry after hold.resetsAt; never run claude -p directly instead. GET /admin/usage-hold reads the hold.';
446
+
240
447
  /**
241
448
  * @param {{ registerRoute: Function }} adminHttp
242
449
  * @param {{ taskSwitch?: any, resolveInfo?: Function, sessionSlots?: any, runTask?: Function,
243
450
  * buildTaskArgs?: Function, buildTaskEnv?: Function, ledger?: any, costOfUsage?: Function,
244
- * now?: () => number, randomUUID?: () => string, resolveProjectRoot?: Function }} [deps]
451
+ * now?: () => number, randomUUID?: () => string, resolveProjectRoot?: Function,
452
+ * syncInteractiveReserve?: () => any, knownMcpServers?: () => Record<string, object>,
453
+ * usageHold?: () => any, appendAuditEvent?: (kind: string, fields: Record<string, any>) => void,
454
+ * switchRouteDeps?: Record<string, any> }} [deps]
245
455
  */
246
456
  function registerAdminRoute(adminHttp, deps = {}) {
457
+ registerTaskSwitchRoute(adminHttp, deps.switchRouteDeps || {});
247
458
  // Lazy defaults: agentLibrary / slots / spawn pull in heavy modules.
248
459
  const taskSwitch = () => deps.taskSwitch || require('./taskSwitch.cjs');
249
460
  const resolveInfo = deps.resolveInfo || defaultResolveInfo;
@@ -253,23 +464,83 @@ function registerAdminRoute(adminHttp, deps = {}) {
253
464
  const buildArgs = (/** @type {any} */ o) => (deps.buildTaskArgs || taskRun().buildTaskArgs)(o);
254
465
  const buildEnv = (/** @type {any} */ rt, /** @type {any} */ env) => (deps.buildTaskEnv || taskRun().buildTaskEnv)(rt, env);
255
466
  const ledger = () => deps.ledger || require('./taskLedger.cjs');
467
+ // The servers a declared `mcpServers:` name may resolve to — the scheduler's own set.
468
+ const knownMcpServers = deps.knownMcpServers || (() => {
469
+ const seed = require('../../seedSchedulerMcp.cjs');
470
+ return { [seed.SERVER_NAME]: seed.schedulerServerEntry() };
471
+ });
256
472
  const costOfUsage = (/** @type {any} */ m, /** @type {any} */ b) => (deps.costOfUsage || require('../claude/modelPricing.cjs').costOfUsage)(m, b);
257
473
  const now = deps.now || Date.now;
258
474
  const newId = deps.randomUUID || (() => crypto.randomUUID());
259
475
  const projectRoot = deps.resolveProjectRoot || resolveProjectRoot;
476
+ // The switch file can change outside the renderer IPC (e.g. a direct module
477
+ // call); re-sync the held interactive slot from it on every switch check.
478
+ // setInteractiveReserve is a no-op when unchanged, so this is cheap.
479
+ const syncReserve = deps.syncInteractiveReserve || (() => require('./taskSwitch.cjs').syncInteractiveReserve());
480
+ const safeSync = () => {
481
+ try { syncReserve(); } catch { /* a failed sync never changes the response */ }
482
+ };
483
+ // The usage hold ('pause above'): read lazily so scheduler.cjs never loads at module load.
484
+ const usageHold = deps.usageHold || (() => require('../../scheduler.cjs').currentUsageHold());
485
+ const audit = (/** @type {string} */ kind, /** @type {Record<string, any>} */ fields) =>
486
+ (deps.appendAuditEvent || require('../telemetry/auditLog.cjs').appendAuditEvent)(kind, fields);
487
+ /** project root → holdIdentityKey of the hold last audited for it; cleared when a read returns null. */
488
+ const heldAudited = new Map();
489
+ /** @param {string} root @param {any} hold */
490
+ const auditHold = (root, hold) => {
491
+ try {
492
+ const key = require('../../scheduler/utilizationHold.cjs').holdIdentityKey(hold);
493
+ if (heldAudited.get(root) === key) return;
494
+ heldAudited.set(root, key);
495
+ audit('task_usage_held', {
496
+ cwd: root, reason: hold.reason, window: hold.window, percent: hold.percent,
497
+ threshold: hold.threshold, resetsAt: hold.resetsAt,
498
+ });
499
+ } catch { /* an audit failure never changes the response */ }
500
+ };
501
+ /** @param {string} root @returns {any} the hold, or null; throws when the read throws. */
502
+ const readHold = (root) => {
503
+ const hold = usageHold();
504
+ if (!hold) { heldAudited.delete(root); return null; }
505
+ auditHold(root, hold);
506
+ return hold;
507
+ };
260
508
 
261
509
  /** sessionId → taskId for every Task currently between its start line and its end line. */
262
510
  const busySessions = new Map();
511
+ /**
512
+ * taskId → its live output for every POST /admin/tasks run between its
513
+ * ledger start line and the end of the handler (removed in finally, after
514
+ * the end line). In-process only: never persisted.
515
+ * @type {Map<string, LiveTask & { append: (line: string) => void }>}
516
+ */
517
+ const liveTasks = new Map();
518
+ const liveCap = () => Number(taskRun().MAX_STDOUT_BYTES) || 8 * 1024 * 1024;
519
+ /** @param {string} id @param {string} root */
520
+ const liveFor = (id, root) => {
521
+ const lt = liveTasks.get(id);
522
+ return lt && path.resolve(lt.cwd) === path.resolve(root) ? lt : null;
523
+ };
524
+ activeLiveTasks = liveTasks;
263
525
 
264
526
  adminHttp.registerRoute('POST', '/admin/tasks', async (/** @type {any} */ req, /** @type {any} */ res) => {
265
527
  try { if (typeof res.setTimeout === 'function') res.setTimeout(0); } catch { /* */ }
266
528
  try { if (typeof req.setTimeout === 'function') req.setTimeout(0); } catch { /* */ }
267
529
 
268
530
  let replied = false;
531
+ // Stream mode: set once the 200 NDJSON head is written (after the ledger start line).
532
+ let streaming = false;
533
+ const canWrite = () => !(res.writableEnded || res.destroyed);
534
+ const writeLine = (/** @type {any} */ obj) => { if (canWrite()) res.write(JSON.stringify(obj) + '\n'); };
269
535
  const reply = (/** @type {number} */ status, /** @type {any} */ obj) => {
270
536
  if (replied) return;
271
537
  replied = true;
272
- if (res.writableEnded || res.destroyed) return;
538
+ if (!canWrite()) return;
539
+ if (streaming) {
540
+ writeLine({ type: 'sm_task_result', ...obj });
541
+ res.end();
542
+ return;
543
+ }
273
544
  sendJson(res, status, obj);
274
545
  };
275
546
 
@@ -319,6 +590,7 @@ function registerAdminRoute(adminHttp, deps = {}) {
319
590
  }
320
591
  }
321
592
 
593
+ safeSync();
322
594
  if (!taskSwitch().isTaskSwitchOn(cwd)) {
323
595
  reply(403, { ok: false, error: 'tasks_disabled', hint: SWITCH_HINT });
324
596
  return;
@@ -358,13 +630,27 @@ function registerAdminRoute(adminHttp, deps = {}) {
358
630
 
359
631
  let args;
360
632
  try {
361
- args = buildArgs({ model, effort, runtime: argsRuntime, projectCwd: cwd });
633
+ const declaredMcpServers = Array.isArray(info.declaredMcpServers) ? info.declaredMcpServers : [];
634
+ args = buildArgs({ model, effort, runtime: argsRuntime, projectCwd: cwd, declaredMcpServers, knownMcpServers: knownMcpServers() });
362
635
  } catch (e) {
363
636
  reply(400, { ok: false, error: (e && /** @type {any} */ (e).code) || 'invalid_request', details: e instanceof Error ? e.message : String(e) });
364
637
  return;
365
638
  }
366
639
  const env = buildEnv(runtime, process.env);
367
640
 
641
+ // Last check before the ledger start line: the usage hold.
642
+ let heldNow;
643
+ try {
644
+ heldNow = readHold(cwd);
645
+ } catch (e) {
646
+ reply(503, { ok: false, error: 'usage_hold_error', details: e instanceof Error ? e.message : String(e) });
647
+ return;
648
+ }
649
+ if (heldNow) {
650
+ reply(429, usageHeldBody(heldNow, USAGE_HOLD_HINT));
651
+ return;
652
+ }
653
+
368
654
  const ac = new AbortController();
369
655
  const onClose = () => { if (!replied) ac.abort(); };
370
656
  req.on('close', onClose);
@@ -390,6 +676,14 @@ function registerAdminRoute(adminHttp, deps = {}) {
390
676
  persisted,
391
677
  prompt: input.prompt,
392
678
  });
679
+ const live = newLiveTask(cwd, liveCap());
680
+ liveTasks.set(taskId, live);
681
+
682
+ if (input.stream === true && canWrite()) {
683
+ res.writeHead(200, { 'Content-Type': 'application/x-ndjson', 'Cache-Control': 'no-store' });
684
+ streaming = true;
685
+ writeLine({ type: 'sm_task_started', taskId, model, effort, sessionId, startedAt });
686
+ }
393
687
 
394
688
  const end = (/** @type {Record<string, any>} */ row) => ledger().appendTaskEnd(cwd, {
395
689
  taskId,
@@ -408,8 +702,9 @@ function registerAdminRoute(adminHttp, deps = {}) {
408
702
  token = await slots().waitForSlot(`task:${taskId}`, { lane, timeoutMs: input.slotWaitSec * 1000, signal: ac.signal });
409
703
  } catch (e) {
410
704
  const code = (e && /** @type {any} */ (e).code) || 'slot_error';
411
- await end({ status: code, slotWaitMs: now() - waitStart });
412
- reply(code === 'too_many_waiting' ? 429 : 500, { ok: false, error: code, taskId });
705
+ const errWaitMs = now() - waitStart;
706
+ await end({ status: code, slotWaitMs: errWaitMs });
707
+ reply(code === 'too_many_waiting' ? 429 : 500, streaming ? { ok: false, error: code, taskId, slotWaitMs: errWaitMs } : { ok: false, error: code, taskId });
413
708
  return;
414
709
  }
415
710
  const slotWaitMs = now() - waitStart;
@@ -420,6 +715,44 @@ function registerAdminRoute(adminHttp, deps = {}) {
420
715
  return;
421
716
  }
422
717
 
718
+ // The hold may have engaged while this Task waited for its slot.
719
+ // A failed read is fail-closed but is not a hold: 503 usage_hold_error, never 429.
720
+ let heldLate;
721
+ try {
722
+ heldLate = readHold(cwd);
723
+ } catch (e) {
724
+ try { slots().release(token); } catch { /* */ }
725
+ await end({ status: 'usage_held', slotWaitMs });
726
+ reply(503, { ok: false, error: 'usage_hold_error', taskId, slotWaitMs, details: e instanceof Error ? e.message : String(e) });
727
+ return;
728
+ }
729
+ if (heldLate) {
730
+ try { slots().release(token); } catch { /* */ }
731
+ await end({ status: 'usage_held', slotWaitMs });
732
+ reply(429, { ...usageHeldBody(heldLate, USAGE_HOLD_HINT), taskId, slotWaitMs });
733
+ return;
734
+ }
735
+
736
+ live.slotAcquired = true;
737
+
738
+ let droppedLines = 0;
739
+ if (streaming) writeLine({ type: 'sm_task_running', slotWaitMs });
740
+ // One callback for every run: the live registry, and in stream mode the NDJSON line too.
741
+ const onStdoutLine = (/** @type {string} */ line) => {
742
+ live.append(line);
743
+ if (streaming) {
744
+ if (!canWrite()) return;
745
+ if ((res.writableLength || 0) > MAX_STREAM_BUFFER_BYTES) { droppedLines += 1; return; }
746
+ let isObject = false;
747
+ try {
748
+ const v = JSON.parse(line);
749
+ isObject = v !== null && typeof v === 'object' && !Array.isArray(v);
750
+ } catch { /* not JSON → wrapped */ }
751
+ if (isObject) res.write(line + '\n');
752
+ else writeLine({ type: 'sm_task_stdout', text: line });
753
+ }
754
+ };
755
+
423
756
  let run;
424
757
  try {
425
758
  run = await runTask({
@@ -430,6 +763,9 @@ function registerAdminRoute(adminHttp, deps = {}) {
430
763
  timeoutMs: input.timeoutSec * 1000,
431
764
  signal: ac.signal,
432
765
  onSpawn: (/** @type {number} */ pid) => { try { slots().stampPid(token, pid); } catch { /* */ } },
766
+ onStdoutLine,
767
+ taskId,
768
+ projectRoot: cwd,
433
769
  });
434
770
  } finally {
435
771
  try { slots().release(token); } catch { /* */ }
@@ -455,7 +791,7 @@ function registerAdminRoute(adminHttp, deps = {}) {
455
791
  });
456
792
 
457
793
  const { textStdoutFor } = taskRun();
458
- reply(200, {
794
+ const result = {
459
795
  ok: true,
460
796
  taskId,
461
797
  status: run.status,
@@ -471,9 +807,11 @@ function registerAdminRoute(adminHttp, deps = {}) {
471
807
  effort,
472
808
  sessionId: finalSessionId,
473
809
  quota: run.quota,
474
- });
810
+ };
811
+ reply(200, streaming ? { ...result, droppedLines } : result);
475
812
  } finally {
476
813
  if (sessionId && busySessions.get(sessionId) === taskId) busySessions.delete(sessionId);
814
+ liveTasks.delete(taskId);
477
815
  req.removeListener('close', onClose);
478
816
  res.removeListener('close', onClose);
479
817
  }
@@ -499,8 +837,10 @@ function registerAdminRoute(adminHttp, deps = {}) {
499
837
  return;
500
838
  }
501
839
  try {
502
- const r = await ledger().listTasks(cwd, { ...filters, now: now() });
503
- sendJson(res, 200, { ok: true, tasks: r.tasks.map(publicTask), total: r.total, hasMore: r.hasMore });
840
+ // A Task this app is still running folds 'running' in the ledger, before its status filter and paging.
841
+ const r = await ledger().listTasks(cwd, { ...filters, now: now(), liveTaskIds: liveTaskIdsFor(cwd) });
842
+ const tasks = r.tasks.map((/** @type {any} */ t) => publicTask(t));
843
+ sendJson(res, 200, { ok: true, tasks, total: r.total, hasMore: r.hasMore });
504
844
  } catch (e) {
505
845
  sendJson(res, 500, { ok: false, error: 'ledger_read_failed', details: e instanceof Error ? e.message : String(e) });
506
846
  }
@@ -519,7 +859,7 @@ function registerAdminRoute(adminHttp, deps = {}) {
519
859
  }
520
860
  let t;
521
861
  try {
522
- t = await ledger().getTask(cwd, parsed.data.id, { now: now() });
862
+ t = await ledger().getTask(cwd, parsed.data.id, { now: now(), liveTaskIds: liveTaskIdsFor(cwd) });
523
863
  } catch (e) {
524
864
  sendJson(res, 500, { ok: false, error: 'ledger_read_failed', details: e instanceof Error ? e.message : String(e) });
525
865
  return;
@@ -529,16 +869,37 @@ function registerAdminRoute(adminHttp, deps = {}) {
529
869
  return;
530
870
  }
531
871
  const body = t.body || {};
872
+ const after = parsed.data.after || 0;
873
+ const live = liveFor(parsed.data.id, cwd);
874
+ if (live) {
875
+ const page = livePage(live, after);
876
+ sendJson(res, 200, {
877
+ ok: true,
878
+ task: {
879
+ ...publicTask(t),
880
+ prompt: typeof body.prompt === 'string' ? body.prompt : null,
881
+ promptTruncated: body.promptTruncated === true,
882
+ output: page.output,
883
+ outputTruncated: page.outputTruncated,
884
+ stderrTail: null,
885
+ envelope: null,
886
+ live: { slotAcquired: live.slotAcquired, outputEnd: page.outputEnd, outputCapped: live.outputCapped },
887
+ },
888
+ });
889
+ return;
890
+ }
891
+ const storedOutput = typeof body.output === 'string' ? body.output : null;
532
892
  sendJson(res, 200, {
533
893
  ok: true,
534
894
  task: {
535
895
  ...publicTask(t),
536
896
  prompt: typeof body.prompt === 'string' ? body.prompt : null,
537
897
  promptTruncated: body.promptTruncated === true,
538
- output: typeof body.output === 'string' ? body.output : null,
898
+ output: storedOutput !== null && after > 0 ? sliceFromByte(storedOutput, after) : storedOutput,
539
899
  outputTruncated: body.outputTruncated === true,
540
900
  stderrTail: typeof body.stderrTail === 'string' ? body.stderrTail : null,
541
901
  envelope: body.envelope === undefined ? null : body.envelope,
902
+ live: null,
542
903
  },
543
904
  });
544
905
  });
@@ -569,6 +930,7 @@ function registerAdminRoute(adminHttp, deps = {}) {
569
930
  sendJson(res, 400, { ok: false, error: 'invalid_request', details: e instanceof Error ? e.message : String(e) });
570
931
  return;
571
932
  }
933
+ safeSync();
572
934
  if (!taskSwitch().isTaskSwitchOn(cwd)) {
573
935
  sendJson(res, 403, { ok: false, error: 'tasks_disabled', hint: SWITCH_HINT });
574
936
  return;
@@ -638,4 +1000,7 @@ function registerAdminRoute(adminHttp, deps = {}) {
638
1000
  });
639
1001
  }
640
1002
 
641
- module.exports = { registerAdminRoute, MAX_BODY_BYTES, MAX_IMPORT_BODY_BYTES, TASK_FIELDS, IMPORT_STATUSES };
1003
+ module.exports = {
1004
+ registerAdminRoute, liveTaskIdsFor, MAX_BODY_BYTES, MAX_IMPORT_BODY_BYTES, TASK_FIELDS, IMPORT_STATUSES,
1005
+ TASK_BODY_KEYS, TASK_RUNTIME_KEYS, TASK_GET_KEYS,
1006
+ };