@0xmaxma/claude-gateway 2.0.19 → 2.0.21

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 (276) hide show
  1. package/README.md +1 -0
  2. package/config.template.json +3 -2
  3. package/dist/agent/builtin-commands.d.ts +4 -0
  4. package/dist/agent/builtin-commands.d.ts.map +1 -1
  5. package/dist/agent/builtin-commands.js +11 -4
  6. package/dist/agent/builtin-commands.js.map +1 -1
  7. package/dist/agent/command-help.d.ts +11 -2
  8. package/dist/agent/command-help.d.ts.map +1 -1
  9. package/dist/agent/command-help.js +27 -8
  10. package/dist/agent/command-help.js.map +1 -1
  11. package/dist/agent/model-registry.d.ts +48 -0
  12. package/dist/agent/model-registry.d.ts.map +1 -0
  13. package/dist/agent/model-registry.js +144 -0
  14. package/dist/agent/model-registry.js.map +1 -0
  15. package/dist/agent/runner.d.ts +63 -41
  16. package/dist/agent/runner.d.ts.map +1 -1
  17. package/dist/agent/runner.js +304 -113
  18. package/dist/agent/runner.js.map +1 -1
  19. package/dist/agent/session-confirmations.d.ts +1 -1
  20. package/dist/agent/session-confirmations.d.ts.map +1 -1
  21. package/dist/agent/session-confirmations.js +5 -3
  22. package/dist/agent/session-confirmations.js.map +1 -1
  23. package/dist/agent/skill-learning/reviewer.d.ts.map +1 -1
  24. package/dist/agent/skill-learning/reviewer.js +2 -1
  25. package/dist/agent/skill-learning/reviewer.js.map +1 -1
  26. package/dist/agent/turn-stream.d.ts +2 -1
  27. package/dist/agent/turn-stream.d.ts.map +1 -1
  28. package/dist/agent/turn-stream.js.map +1 -1
  29. package/dist/api/gateway-router.d.ts.map +1 -1
  30. package/dist/api/gateway-router.js +4 -0
  31. package/dist/api/gateway-router.js.map +1 -1
  32. package/dist/api/manifest-sources.d.ts.map +1 -1
  33. package/dist/api/manifest-sources.js +3 -0
  34. package/dist/api/manifest-sources.js.map +1 -1
  35. package/dist/api/pstack-router.d.ts +14 -0
  36. package/dist/api/pstack-router.d.ts.map +1 -0
  37. package/dist/api/pstack-router.js +93 -0
  38. package/dist/api/pstack-router.js.map +1 -0
  39. package/dist/api/router.d.ts.map +1 -1
  40. package/dist/api/router.js +29 -24
  41. package/dist/api/router.js.map +1 -1
  42. package/dist/automation/computer-use.d.ts +7 -0
  43. package/dist/automation/computer-use.d.ts.map +1 -1
  44. package/dist/automation/computer-use.js +29 -7
  45. package/dist/automation/computer-use.js.map +1 -1
  46. package/dist/automation/model-choice-evaluator.d.ts +62 -3
  47. package/dist/automation/model-choice-evaluator.d.ts.map +1 -1
  48. package/dist/automation/model-choice-evaluator.js +24 -4
  49. package/dist/automation/model-choice-evaluator.js.map +1 -1
  50. package/dist/automation/vision-decider.d.ts +215 -0
  51. package/dist/automation/vision-decider.d.ts.map +1 -0
  52. package/dist/automation/vision-decider.js +673 -0
  53. package/dist/automation/vision-decider.js.map +1 -0
  54. package/dist/build-provenance.json +4 -4
  55. package/dist/cli/commands.generated.d.ts.map +1 -1
  56. package/dist/cli/commands.generated.js +36 -1
  57. package/dist/cli/commands.generated.js.map +1 -1
  58. package/dist/config/loader.d.ts.map +1 -1
  59. package/dist/config/loader.js +7 -0
  60. package/dist/config/loader.js.map +1 -1
  61. package/dist/config/reload-policy.js +1 -1
  62. package/dist/config/reload-policy.js.map +1 -1
  63. package/dist/config/watcher.d.ts.map +1 -1
  64. package/dist/config/watcher.js +2 -0
  65. package/dist/config/watcher.js.map +1 -1
  66. package/dist/orchestration/agent-tool-schemas.js +1 -1
  67. package/dist/orchestration/agent-tool-schemas.js.map +1 -1
  68. package/dist/orchestration/bridge.d.ts +6 -2
  69. package/dist/orchestration/bridge.d.ts.map +1 -1
  70. package/dist/orchestration/bridge.js +120 -5
  71. package/dist/orchestration/bridge.js.map +1 -1
  72. package/dist/orchestration/capabilities.d.ts.map +1 -1
  73. package/dist/orchestration/capabilities.js +10 -3
  74. package/dist/orchestration/capabilities.js.map +1 -1
  75. package/dist/orchestration/capacity.d.ts +9 -2
  76. package/dist/orchestration/capacity.d.ts.map +1 -1
  77. package/dist/orchestration/capacity.js +18 -7
  78. package/dist/orchestration/capacity.js.map +1 -1
  79. package/dist/orchestration/cli-skills.d.ts.map +1 -1
  80. package/dist/orchestration/cli-skills.js +4 -2
  81. package/dist/orchestration/cli-skills.js.map +1 -1
  82. package/dist/orchestration/computer-decisions.d.ts +7 -0
  83. package/dist/orchestration/computer-decisions.d.ts.map +1 -1
  84. package/dist/orchestration/computer-decisions.js +39 -0
  85. package/dist/orchestration/computer-decisions.js.map +1 -1
  86. package/dist/orchestration/config.d.ts +17 -0
  87. package/dist/orchestration/config.d.ts.map +1 -1
  88. package/dist/orchestration/config.js +21 -1
  89. package/dist/orchestration/config.js.map +1 -1
  90. package/dist/orchestration/dashboard-reader-worker.js +5 -3
  91. package/dist/orchestration/dashboard-reader-worker.js.map +1 -1
  92. package/dist/orchestration/decisions.d.ts.map +1 -1
  93. package/dist/orchestration/decisions.js +4 -2
  94. package/dist/orchestration/decisions.js.map +1 -1
  95. package/dist/orchestration/delivery.d.ts.map +1 -1
  96. package/dist/orchestration/delivery.js +1 -0
  97. package/dist/orchestration/delivery.js.map +1 -1
  98. package/dist/orchestration/gateway-tasks/computer.d.ts +10 -0
  99. package/dist/orchestration/gateway-tasks/computer.d.ts.map +1 -1
  100. package/dist/orchestration/gateway-tasks/computer.js +144 -32
  101. package/dist/orchestration/gateway-tasks/computer.js.map +1 -1
  102. package/dist/orchestration/gateway-tasks/controller.d.ts +6 -6
  103. package/dist/orchestration/gateway-tasks/controller.d.ts.map +1 -1
  104. package/dist/orchestration/gateway-tasks/controller.js +2 -2
  105. package/dist/orchestration/gateway-tasks/controller.js.map +1 -1
  106. package/dist/orchestration/input-batch.d.ts +8 -2
  107. package/dist/orchestration/input-batch.d.ts.map +1 -1
  108. package/dist/orchestration/input-batch.js +28 -8
  109. package/dist/orchestration/input-batch.js.map +1 -1
  110. package/dist/orchestration/mutation-recovery.js +1 -1
  111. package/dist/orchestration/mutation-recovery.js.map +1 -1
  112. package/dist/orchestration/notification-mailbox.d.ts.map +1 -1
  113. package/dist/orchestration/notification-mailbox.js +16 -2
  114. package/dist/orchestration/notification-mailbox.js.map +1 -1
  115. package/dist/orchestration/process-turn.d.ts +6 -1
  116. package/dist/orchestration/process-turn.d.ts.map +1 -1
  117. package/dist/orchestration/process-turn.js +9 -5
  118. package/dist/orchestration/process-turn.js.map +1 -1
  119. package/dist/orchestration/recovery.d.ts.map +1 -1
  120. package/dist/orchestration/recovery.js +21 -0
  121. package/dist/orchestration/recovery.js.map +1 -1
  122. package/dist/orchestration/response-errors.d.ts +5 -0
  123. package/dist/orchestration/response-errors.d.ts.map +1 -1
  124. package/dist/orchestration/response-errors.js +25 -0
  125. package/dist/orchestration/response-errors.js.map +1 -1
  126. package/dist/orchestration/runtime.d.ts +15 -1
  127. package/dist/orchestration/runtime.d.ts.map +1 -1
  128. package/dist/orchestration/runtime.js +155 -29
  129. package/dist/orchestration/runtime.js.map +1 -1
  130. package/dist/orchestration/speech.d.ts +3 -0
  131. package/dist/orchestration/speech.d.ts.map +1 -1
  132. package/dist/orchestration/speech.js +4 -1
  133. package/dist/orchestration/speech.js.map +1 -1
  134. package/dist/orchestration/store.d.ts +5 -0
  135. package/dist/orchestration/store.d.ts.map +1 -1
  136. package/dist/orchestration/store.js +13 -5
  137. package/dist/orchestration/store.js.map +1 -1
  138. package/dist/orchestration/subagent-tool-schemas.d.ts +12 -0
  139. package/dist/orchestration/subagent-tool-schemas.d.ts.map +1 -0
  140. package/dist/orchestration/subagent-tool-schemas.js +23 -0
  141. package/dist/orchestration/subagent-tool-schemas.js.map +1 -0
  142. package/dist/orchestration/task-controls.d.ts.map +1 -1
  143. package/dist/orchestration/task-controls.js +6 -3
  144. package/dist/orchestration/task-controls.js.map +1 -1
  145. package/dist/orchestration/task-questions.d.ts.map +1 -1
  146. package/dist/orchestration/task-questions.js +3 -1
  147. package/dist/orchestration/task-questions.js.map +1 -1
  148. package/dist/orchestration/tasks/automation-session.d.ts +17 -0
  149. package/dist/orchestration/tasks/automation-session.d.ts.map +1 -1
  150. package/dist/orchestration/tasks/automation-session.js +36 -1
  151. package/dist/orchestration/tasks/automation-session.js.map +1 -1
  152. package/dist/orchestration/tasks/driver.d.ts.map +1 -1
  153. package/dist/orchestration/tasks/driver.js +54 -14
  154. package/dist/orchestration/tasks/driver.js.map +1 -1
  155. package/dist/orchestration/tasks/scheduler.d.ts.map +1 -1
  156. package/dist/orchestration/tasks/scheduler.js +17 -3
  157. package/dist/orchestration/tasks/scheduler.js.map +1 -1
  158. package/dist/orchestration/tasks/service.d.ts +110 -34
  159. package/dist/orchestration/tasks/service.d.ts.map +1 -1
  160. package/dist/orchestration/tasks/service.js +254 -24
  161. package/dist/orchestration/tasks/service.js.map +1 -1
  162. package/dist/orchestration/tasks/task-directive.d.ts.map +1 -1
  163. package/dist/orchestration/tasks/task-directive.js +5 -1
  164. package/dist/orchestration/tasks/task-directive.js.map +1 -1
  165. package/dist/orchestration/telegram-tool-status.d.ts +8 -1
  166. package/dist/orchestration/telegram-tool-status.d.ts.map +1 -1
  167. package/dist/orchestration/telegram-tool-status.js +57 -6
  168. package/dist/orchestration/telegram-tool-status.js.map +1 -1
  169. package/dist/orchestration/token-ledger.d.ts +14 -0
  170. package/dist/orchestration/token-ledger.d.ts.map +1 -1
  171. package/dist/orchestration/token-ledger.js +28 -2
  172. package/dist/orchestration/token-ledger.js.map +1 -1
  173. package/dist/orchestration/token-usage.d.ts +14 -0
  174. package/dist/orchestration/token-usage.d.ts.map +1 -1
  175. package/dist/orchestration/token-usage.js +16 -2
  176. package/dist/orchestration/token-usage.js.map +1 -1
  177. package/dist/orchestration/tool-name.d.ts.map +1 -1
  178. package/dist/orchestration/tool-name.js +5 -1
  179. package/dist/orchestration/tool-name.js.map +1 -1
  180. package/dist/orchestration/types.d.ts +34 -0
  181. package/dist/orchestration/types.d.ts.map +1 -1
  182. package/dist/orchestration/types.js +11 -0
  183. package/dist/orchestration/types.js.map +1 -1
  184. package/dist/orchestration/worker-harness.d.ts.map +1 -1
  185. package/dist/orchestration/worker-harness.js +5 -2
  186. package/dist/orchestration/worker-harness.js.map +1 -1
  187. package/dist/pstack/config.d.ts +48 -0
  188. package/dist/pstack/config.d.ts.map +1 -0
  189. package/dist/pstack/config.js +147 -0
  190. package/dist/pstack/config.js.map +1 -0
  191. package/dist/pstack/menu.d.ts +71 -0
  192. package/dist/pstack/menu.d.ts.map +1 -0
  193. package/dist/pstack/menu.js +286 -0
  194. package/dist/pstack/menu.js.map +1 -0
  195. package/dist/pstack/overlay.d.ts +30 -0
  196. package/dist/pstack/overlay.d.ts.map +1 -0
  197. package/dist/pstack/overlay.js +121 -0
  198. package/dist/pstack/overlay.js.map +1 -0
  199. package/dist/pstack/plugin-info.d.ts +36 -0
  200. package/dist/pstack/plugin-info.d.ts.map +1 -0
  201. package/dist/pstack/plugin-info.js +51 -0
  202. package/dist/pstack/plugin-info.js.map +1 -0
  203. package/dist/pstack/reflect.d.ts +14 -0
  204. package/dist/pstack/reflect.d.ts.map +1 -0
  205. package/dist/pstack/reflect.js +49 -0
  206. package/dist/pstack/reflect.js.map +1 -0
  207. package/dist/pstack/setup.d.ts +17 -0
  208. package/dist/pstack/setup.d.ts.map +1 -0
  209. package/dist/pstack/setup.js +47 -0
  210. package/dist/pstack/setup.js.map +1 -0
  211. package/dist/pstack/sheet.d.ts +19 -0
  212. package/dist/pstack/sheet.d.ts.map +1 -0
  213. package/dist/pstack/sheet.js +44 -0
  214. package/dist/pstack/sheet.js.map +1 -0
  215. package/dist/pstack/templates.d.ts +14 -0
  216. package/dist/pstack/templates.d.ts.map +1 -0
  217. package/dist/pstack/templates.js +41 -0
  218. package/dist/pstack/templates.js.map +1 -0
  219. package/dist/session/codex-process.d.ts +0 -3
  220. package/dist/session/codex-process.d.ts.map +1 -1
  221. package/dist/session/codex-process.js +8 -3
  222. package/dist/session/codex-process.js.map +1 -1
  223. package/dist/session/compactor.d.ts.map +1 -1
  224. package/dist/session/compactor.js +2 -1
  225. package/dist/session/compactor.js.map +1 -1
  226. package/dist/session/process-diagnostics.d.ts +3 -0
  227. package/dist/session/process-diagnostics.d.ts.map +1 -1
  228. package/dist/session/process-diagnostics.js +10 -0
  229. package/dist/session/process-diagnostics.js.map +1 -1
  230. package/dist/session/process.d.ts.map +1 -1
  231. package/dist/session/process.js +9 -4
  232. package/dist/session/process.js.map +1 -1
  233. package/dist/session/provider-refusal.d.ts +36 -0
  234. package/dist/session/provider-refusal.d.ts.map +1 -0
  235. package/dist/session/provider-refusal.js +109 -0
  236. package/dist/session/provider-refusal.js.map +1 -0
  237. package/dist/session/runtime-profile.d.ts +13 -2
  238. package/dist/session/runtime-profile.d.ts.map +1 -1
  239. package/dist/session/runtime-profile.js +35 -2
  240. package/dist/session/runtime-profile.js.map +1 -1
  241. package/dist/session/worker-extensions.d.ts +5 -2
  242. package/dist/session/worker-extensions.d.ts.map +1 -1
  243. package/dist/session/worker-extensions.js +10 -5
  244. package/dist/session/worker-extensions.js.map +1 -1
  245. package/dist/types.d.ts +3 -0
  246. package/dist/types.d.ts.map +1 -1
  247. package/dist/ui/dashboard-client.d.ts.map +1 -1
  248. package/dist/ui/dashboard-client.js +14 -4
  249. package/dist/ui/dashboard-client.js.map +1 -1
  250. package/dist/ui/dashboard-presentation.d.ts +29 -0
  251. package/dist/ui/dashboard-presentation.d.ts.map +1 -1
  252. package/dist/ui/dashboard-presentation.js +26 -1
  253. package/dist/ui/dashboard-presentation.js.map +1 -1
  254. package/dist/ui/token-report.d.ts +3 -0
  255. package/dist/ui/token-report.d.ts.map +1 -1
  256. package/dist/ui/token-report.js +1 -1
  257. package/dist/ui/token-report.js.map +1 -1
  258. package/dist/voice/errors.d.ts +6 -1
  259. package/dist/voice/errors.d.ts.map +1 -1
  260. package/dist/voice/errors.js +8 -1
  261. package/dist/voice/errors.js.map +1 -1
  262. package/dist/voice/managed-quota.d.ts +29 -3
  263. package/dist/voice/managed-quota.d.ts.map +1 -1
  264. package/dist/voice/managed-quota.js +68 -23
  265. package/dist/voice/managed-quota.js.map +1 -1
  266. package/dist/voice/notes.d.ts +27 -3
  267. package/dist/voice/notes.d.ts.map +1 -1
  268. package/dist/voice/notes.js +59 -10
  269. package/dist/voice/notes.js.map +1 -1
  270. package/mcp/lazy-tools.ts +4 -2
  271. package/mcp/server.ts +6 -2
  272. package/mcp/tools/tasks/module.ts +3 -1
  273. package/mcp/tools/telegram/pstack-menu.ts +22 -0
  274. package/mcp/tools/telegram/pure.ts +40 -0
  275. package/mcp/tools/telegram/receiver-server.ts +63 -6
  276. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TaskService = exports.MAX_CONTEXT_REFS = exports.MAX_AGENT_CONTEXT_REFS = void 0;
3
+ exports.TaskService = exports.MAX_CONTEXT_REFS = exports.MAX_AGENT_CONTEXT_REFS = exports.RUNNING_PARENT = void 0;
4
4
  exports.assertAgentContextRefs = assertAgentContextRefs;
5
5
  exports.mergeContextRefs = mergeContextRefs;
6
6
  exports.handoffCommandId = handoffCommandId;
@@ -27,6 +27,9 @@ const store_1 = require("../store");
27
27
  const config_1 = require("../config");
28
28
  const conversation_intake_1 = require("../conversation-intake");
29
29
  const types_1 = require("../types");
30
+ const subagent_tool_schemas_1 = require("../subagent-tool-schemas");
31
+ /** Parent states a subagent runs under; any other parent can neither start nor wait for one. */
32
+ exports.RUNNING_PARENT = ['starting', 'running', 'interrupting'];
30
33
  /** Refs the agent may name itself; the gateway's own additions are bounded separately by MAX_INTAKE_INPUTS. */
31
34
  exports.MAX_AGENT_CONTEXT_REFS = 64;
32
35
  /** Safety net only: an agent list plus a full semantic-intake batch, so normal use cannot reach it. */
@@ -54,6 +57,13 @@ function handoffCommandId(inputId) {
54
57
  const h = (0, crypto_1.createHash)('sha256').update('agent-handoff:' + inputId).digest('hex');
55
58
  return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20, 32)}`;
56
59
  }
60
+ /** The live execution state an index row carries. The process sample, its timestamps and the
61
+ * quiet/activity status are refreshed every observation, so including them made an unchanged
62
+ * task look changed and resent it on every turn; task_status still returns all of them. */
63
+ function indexExecution(execution) {
64
+ const { phase, activeTools, lastTool, lastProgressAt, attemptId } = execution;
65
+ return { phase, activeTools, lastProgressAt, attemptId, ...(lastTool ? { lastTool: { name: lastTool.name, status: lastTool.status, ...(lastTool.exitCode !== undefined ? { exitCode: lastTool.exitCode } : {}) } } : {}) };
66
+ }
57
67
  /** One index row: identity, live state and how to fetch the rest — never a report body.
58
68
  * A finished task's progress, execution observation and workflow checkpoint/review history
59
69
  * are report bodies, so they are dropped here and read back via task_status when needed.
@@ -66,16 +76,36 @@ function taskIndexEntry(task) {
66
76
  createdAt: task.createdAt, updatedAt: task.updatedAt,
67
77
  workflow: terminal ? undefined : task.workflow,
68
78
  latestProgress: terminal ? undefined : task.latestProgress,
69
- execution: terminal ? undefined : task.execution,
79
+ execution: terminal || !task.execution ? undefined : indexExecution(task.execution),
70
80
  pendingQuestion: task.pendingQuestion, failure: task.failure,
71
81
  cancellation: task.cancellation, replacedByTaskId: task.replacedByTaskId,
72
82
  workstreamId: task.workstreamId, continueTaskId: task.continueTaskId, continuationPolicy: task.continuationPolicy,
83
+ model: task.model, effort: task.effort,
84
+ ...(task.parentTaskId ? { parentTaskId: task.parentTaskId, rootTaskId: task.rootTaskId } : {}),
73
85
  resultAvailable: Boolean(task.result),
74
86
  actionLog: task.actionLog,
75
87
  computerConnection: task.computerConnection, automationController: task.automationController ?? "agent", gatewayTarget: task.gatewayTarget, automationSession: (0, automation_session_1.automationSession)(task),
76
88
  details: { tool: 'task_status', task_id: task.taskId },
77
89
  };
78
90
  }
91
+ /** What a pstack run actually did, for the decision turn that reports it: the pstack skills its
92
+ * tree invoked (Skill calls, or the skill a skill-worker was assigned) and its subagents by model.
93
+ * Absent when it used neither, so every other task's status is unchanged. */
94
+ function pstackEvidence(store, task, assigned, tree) {
95
+ const skills = new Set(assigned?.startsWith('pstack:') ? [assigned] : []);
96
+ // One query for the whole tree, not one per subagent.
97
+ for (const row of store.all("SELECT DISTINCT json_extract(payload_json,'$.payload.input.skill') AS skill FROM conversation_events WHERE conversation_id=? AND type='tool.activity' AND json_extract(payload_json,'$.task_id') IN (SELECT value FROM json_each(?)) AND json_extract(payload_json,'$.payload.name')='Skill' AND json_extract(payload_json,'$.payload.type')='tool_use'", task.conversationId, JSON.stringify([task.taskId, ...tree.map(child => child.taskId)])))
98
+ if (typeof row.skill === 'string' && row.skill.startsWith('pstack:'))
99
+ skills.add(row.skill.slice(0, 256));
100
+ const subagentModels = {};
101
+ for (const child of tree) {
102
+ const key = [child.model ?? 'parent model', child.effort].filter(Boolean).join(' ');
103
+ subagentModels[key] = (subagentModels[key] ?? 0) + 1;
104
+ }
105
+ if (!skills.size && !tree.length)
106
+ return {};
107
+ return { pstackEvidence: { ...(skills.size ? { skills: [...skills].sort() } : {}), ...(tree.length ? { subagents: tree.length, subagentModels } : {}) } };
108
+ }
79
109
  const ACTION_LOG_MAX = 12;
80
110
  const CORRECTION_HEAD = 'Latest user correction (apply first; supersedes conflicting earlier requirements):\n';
81
111
  /** The round's own command for the log: a correction's latest text, never its preamble, and never typed field text. */
@@ -182,12 +212,28 @@ class TaskService {
182
212
  status(conversationId, principalId, taskId) {
183
213
  this.store.assertMember(conversationId, principalId);
184
214
  if (taskId) {
185
- const task = this.owned(taskId, conversationId);
186
- delete task.skill;
187
- return [this.withRecentTools(task)];
215
+ const task = this.owned(taskId, conversationId), assigned = task.skill?.name;
216
+ // Gateway-managed tasks (browser/computer verification paths) never run pstack: no tree, no evidence.
217
+ if (task.gatewayTarget)
218
+ return [(0, types_1.publicTask)(this.withRecentTools(task))];
219
+ // A root lists its whole subagent tree; each entry names its parent.
220
+ const tree = task.parentTaskId ? [] : this.store.all("SELECT snapshot_json FROM tasks WHERE conversation_id=? AND json_extract(snapshot_json,'$.rootTaskId')=? ORDER BY created_at,rowid", task.conversationId, task.taskId)
221
+ .map(row => JSON.parse(String(row.snapshot_json)));
222
+ // Each subagent's latest attempt, in one query.
223
+ const latest = new Map(tree.length ? this.store.all("SELECT a.task_id,a.payload_json FROM task_attempts a WHERE a.task_id IN (SELECT value FROM json_each(?)) AND a.generation=(SELECT MAX(b.generation) FROM task_attempts b WHERE b.task_id=a.task_id)", JSON.stringify(tree.map(child => child.taskId)))
224
+ .map(row => [String(row.task_id), JSON.parse(String(row.payload_json))]) : []);
225
+ const subagents = tree.map(child => {
226
+ const ran = latest.get(child.taskId);
227
+ // model · harness · effort · state · duration, for the root's final report.
228
+ return { taskId: child.taskId, parentTaskId: child.parentTaskId, title: child.title, state: child.state, model: child.model, harness: ran?.harness, effort: child.effort, subagentType: child.subagentType,
229
+ ...(ran?.startedAt ? { durationMs: (types_1.TERMINAL_TASK_STATES.has(child.state) ? child.updatedAt : Date.now()) - ran.startedAt } : {}),
230
+ ...(child.failure ? { failure: child.failure.code } : {}) };
231
+ });
232
+ return [(0, types_1.publicTask)({ ...this.withRecentTools(task), ...(subagents.length ? { subagents } : {}), ...pstackEvidence(this.store, task, assigned, tree) })];
188
233
  }
189
- return this.store.all(`SELECT snapshot_json FROM tasks WHERE conversation_id=? AND (state NOT IN ('completed','failed','cancelled') OR (json_extract(snapshot_json,'$.automationSession.status') IN ('idle','blocked') AND json_extract(snapshot_json,'$.automationSession.idleSince')+json_extract(snapshot_json,'$.automationSession.idleTimeoutMs')>${Date.now()}) OR id IN
190
- (SELECT id FROM tasks WHERE conversation_id=? AND state IN ('completed','failed','cancelled') ORDER BY created_at DESC,id DESC LIMIT 100))
234
+ // As in indexPage: a root's status lists its subagents.
235
+ return this.store.all(`SELECT snapshot_json FROM tasks WHERE conversation_id=? AND ${store_1.LISTED_TASK_SQL} AND (state NOT IN ('completed','failed','cancelled') OR (json_extract(snapshot_json,'$.automationSession.status') IN ('idle','blocked') AND json_extract(snapshot_json,'$.automationSession.idleSince')+json_extract(snapshot_json,'$.automationSession.idleTimeoutMs')>${Date.now()}) OR id IN
236
+ (SELECT id FROM tasks WHERE conversation_id=? AND ${store_1.LISTED_TASK_SQL} AND state IN ('completed','failed','cancelled') ORDER BY created_at DESC,id DESC LIMIT 100))
191
237
  ORDER BY CASE WHEN state IN ('completed','failed','cancelled') THEN 1 ELSE 0 END,created_at DESC,id DESC`, conversationId, conversationId).map(row => {
192
238
  const task = JSON.parse(String(row.snapshot_json));
193
239
  const waiting = task.state === 'queued' && this.store.get('SELECT waiting_json FROM provider_waits WHERE entity_id=?', task.taskId);
@@ -195,8 +241,7 @@ class TaskService {
195
241
  task.providerWaiting = JSON.parse(String(waiting.waiting_json));
196
242
  else
197
243
  delete task.providerWaiting;
198
- delete task.skill; // Installed skill bodies are worker-only execution context.
199
- return this.withRecentTools(task);
244
+ return (0, types_1.publicTask)(this.withRecentTools(task));
200
245
  });
201
246
  }
202
247
  /** Current reports are lossless. Other tasks are an index, never partial reports.
@@ -217,8 +262,10 @@ class TaskService {
217
262
  }
218
263
  /** Bounded recent-task page: every unfinished task, plus only the newest finished ones. */
219
264
  indexPage(conversationId) {
220
- return this.store.all(`SELECT snapshot_json FROM tasks WHERE conversation_id=? AND (state NOT IN ('completed','failed','cancelled') OR (json_extract(snapshot_json,'$.automationSession.status') IN ('idle','blocked') AND json_extract(snapshot_json,'$.automationSession.idleSince')+json_extract(snapshot_json,'$.automationSession.idleTimeoutMs')>${Date.now()}) OR id IN
221
- (SELECT id FROM tasks WHERE conversation_id=? AND state IN ('completed','failed','cancelled') ORDER BY created_at DESC,id DESC LIMIT ${INDEXED_FINISHED_TASKS}))
265
+ // Subagents are listed under their root (task_status with the root's task_id), not as separate work,
266
+ // unless one awaits reconciliation: then it needs its own Retry cleanup.
267
+ return this.store.all(`SELECT snapshot_json FROM tasks WHERE conversation_id=? AND ${store_1.LISTED_TASK_SQL} AND (state NOT IN ('completed','failed','cancelled') OR (json_extract(snapshot_json,'$.automationSession.status') IN ('idle','blocked') AND json_extract(snapshot_json,'$.automationSession.idleSince')+json_extract(snapshot_json,'$.automationSession.idleTimeoutMs')>${Date.now()}) OR id IN
268
+ (SELECT id FROM tasks WHERE conversation_id=? AND ${store_1.LISTED_TASK_SQL} AND state IN ('completed','failed','cancelled') ORDER BY created_at DESC,id DESC LIMIT ${INDEXED_FINISHED_TASKS}))
222
269
  ORDER BY CASE WHEN state IN ('completed','failed','cancelled') THEN 1 ELSE 0 END,created_at DESC,id DESC`, conversationId, conversationId).map(row => JSON.parse(String(row.snapshot_json)));
223
270
  }
224
271
  withRecentTools(task) {
@@ -234,6 +281,11 @@ class TaskService {
234
281
  .map(row => String(row.path).slice(0, 2048)),
235
282
  currentFilesystemVerified: false,
236
283
  };
284
+ // The harness is an attempt's execution choice (Codex can fall back to Claude), so report the latest one.
285
+ const attempt = this.store.get('SELECT payload_json FROM task_attempts WHERE task_id=? ORDER BY generation DESC LIMIT 1', task.taskId);
286
+ const harness = attempt ? JSON.parse(String(attempt.payload_json)).harness : undefined;
287
+ if (harness)
288
+ task.harness = harness;
237
289
  // Direct corrections bypass the parent inference turn. Hydrated status and
238
290
  // notifications must carry the current goal so verification cannot use stale memory.
239
291
  return ['browser', 'computer'].includes(task.gatewayTarget?.adapter ?? '')
@@ -270,7 +322,7 @@ class TaskService {
270
322
  throw new types_1.OrchestrationError('UNKNOWN_WORKER_PROFILE');
271
323
  if ((command.targetProfile === 'gateway-managed') !== Boolean(command.gatewayTarget))
272
324
  throw new types_1.OrchestrationError('INVALID_GATEWAY_TARGET');
273
- if (command.gatewayTarget && (command.workingDirectory || command.skill || command.contextRefs?.length))
325
+ if (command.gatewayTarget && (command.workingDirectory || command.skill || command.contextRefs?.length || command.model || command.effort))
274
326
  throw new types_1.OrchestrationError('INVALID_GATEWAY_TARGET');
275
327
  return this.command(context, 'spawn', command, true, () => {
276
328
  const conversation = this.store.get('SELECT * FROM conversations WHERE id=?', context.conversationId);
@@ -335,8 +387,17 @@ class TaskService {
335
387
  }
336
388
  if (command.skill)
337
389
  task.skill = command.skill;
338
- if (context.model && !command.gatewayTarget)
390
+ // A follow-up keeps the model and effort its predecessor was explicitly given, like its directory and worker session.
391
+ const requested = command.model ? command : prior?.requestedModel ? { model: prior.model, requestedModel: prior.requestedModel } : undefined;
392
+ if (requested?.model) {
393
+ task.model = requested.model;
394
+ task.requestedModel = requested.requestedModel ?? requested.model;
395
+ }
396
+ else if (context.model && !command.gatewayTarget)
339
397
  task.model = context.model;
398
+ const effort = command.effort ?? (command.model ? undefined : prior?.effort);
399
+ if (effort)
400
+ task.effort = effort;
340
401
  const projectRoot = command.workingDirectory || (this.config.tasks.workspaceMode === 'host' && prior?.resourceProfile?.mode === 'host' ? prior.resourceProfile.projectRoot : undefined) || this.config.tasks.projectRoot || this.defaultProjectRoot;
341
402
  if (projectRoot && !command.gatewayTarget)
342
403
  task.resourceProfile = { projectRoot, mode: this.config.tasks.workspaceMode };
@@ -654,12 +715,21 @@ class TaskService {
654
715
  throw new types_1.OrchestrationError('INVALID_REPLACEMENT');
655
716
  this.owned(replacedByTaskId, conversationId);
656
717
  }
657
- if (types_1.TERMINAL_TASK_STATES.has(task.state) && !(task.gatewayTarget?.adapter === 'computer' && task.gatewayDispatch && (0, automation_session_1.automationSession)(task)?.status !== 'closed')) {
658
- const session = (0, automation_session_1.automationSession)(task);
659
- if (session && session.status !== 'closed') {
718
+ // Ending a settled round, by the user or the agent, closes its session only:
719
+ // the round's completed/failed outcome is not rewritten as a cancellation.
720
+ if (types_1.TERMINAL_TASK_STATES.has(task.state)) {
721
+ const session = (0, automation_session_1.automationSession)(task), closes = Boolean(session && session.status !== 'closed');
722
+ if (closes) {
660
723
  task.automationSession = { ...session, status: 'closed', closedAt: Date.now(), closedReason: requestedBy };
661
- this.store.saveTask(task, task.stateVersion);
724
+ if (task.gatewayTarget?.adapter === 'computer' && task.gatewayDispatch)
725
+ task.computerRevocation = { requestId: task.gatewayDispatch.requestId, requestedAt: Date.now() };
662
726
  }
727
+ if (replacedByTaskId)
728
+ task.replacedByTaskId = replacedByTaskId;
729
+ if (closes || replacedByTaskId)
730
+ this.store.saveTask(task, task.stateVersion);
731
+ // A subagent whose stop was unconfirmed outlives its ended parent; this retries its cleanup.
732
+ this.cancelSubagents(task);
663
733
  return task;
664
734
  }
665
735
  if (task.state === 'cancel_requested') {
@@ -689,15 +759,25 @@ class TaskService {
689
759
  this.store.saveTask(task, version);
690
760
  if (task.state === 'cancelled')
691
761
  this.notify(task);
692
- else
762
+ else {
693
763
  this.store.enqueue('interrupt', `cancel:${taskId}:${task.stateVersion}`, { taskId });
764
+ this.cancelSubagents(task);
765
+ }
694
766
  return task;
695
767
  }
696
768
  /** A settled computer round still owns device access until explicit revocation. */
697
769
  finishIdleComputerCleanup(taskId, requestId) {
698
770
  this.store.transaction(() => {
699
771
  const task = this.store.task(taskId);
700
- if (!task || task.state !== 'cancel_requested' || task.activeAttemptId || task.gatewayTarget?.adapter !== 'computer' || task.gatewayDispatch?.requestId !== requestId)
772
+ if (!task || task.activeAttemptId || task.gatewayTarget?.adapter !== 'computer' || task.gatewayDispatch?.requestId !== requestId)
773
+ throw new types_1.OrchestrationError('STALE_ATTEMPT');
774
+ // A terminal round keeps its reported outcome; only the pending revocation is settled.
775
+ if (types_1.TERMINAL_TASK_STATES.has(task.state) && task.computerRevocation?.requestId === requestId) {
776
+ delete task.computerRevocation;
777
+ this.store.saveTask(task, task.stateVersion);
778
+ return;
779
+ }
780
+ if (task.state !== 'cancel_requested')
701
781
  throw new types_1.OrchestrationError('STALE_ATTEMPT');
702
782
  task.state = 'cancelled';
703
783
  task.latestProgress = { source: 'runtime', observedAt: Date.now(), text: 'Computer Use disconnected.' };
@@ -881,10 +961,25 @@ class TaskService {
881
961
  return undefined;
882
962
  }
883
963
  }
964
+ // A subagent's ancestors hold their slots while they wait for it. They are not counted
965
+ // against it, so a chain can always extend (no deadlock), while siblings still queue
966
+ // within the usual limits (no tree takes every worker process).
967
+ const ancestors = [];
968
+ for (let id = task.parentTaskId; id;) {
969
+ const parent = this.store.task(id);
970
+ if (!parent)
971
+ break;
972
+ ancestors.push(parent);
973
+ id = parent.parentTaskId;
974
+ }
975
+ // A subagent only runs for a parent that is running; after a restart its parent awaits reconciliation.
976
+ if (task.parentTaskId && !exports.RUNNING_PARENT.includes(ancestors[0]?.state ?? ''))
977
+ return undefined;
978
+ const holding = ancestors.filter(parent => parent.activeAttemptId).length;
884
979
  const active = this.store.all('SELECT conversation_id,COUNT(*) AS n FROM tasks WHERE active_attempt_id IS NOT NULL GROUP BY conversation_id');
885
- if (active.reduce((n, row) => n + Number(row.n), 0) >= this.config.tasks.maxConcurrentPerAgent || Number(active.find(row => row.conversation_id === task.conversationId)?.n ?? 0) >= this.config.tasks.maxConcurrentPerConversation)
980
+ if (active.reduce((n, row) => n + Number(row.n), 0) - holding >= this.config.tasks.maxConcurrentPerAgent || Number(active.find(row => row.conversation_id === task.conversationId)?.n ?? 0) - holding >= this.config.tasks.maxConcurrentPerConversation)
886
981
  return undefined;
887
- const worker = task.gatewayTarget ? { sessionId: task.gatewayTarget.sessionId, workerId: undefined } : this.pool.acquire(task, this.config.tasks.maxConcurrentPerAgent, this.config.tasks.workerIdleTtlMs);
982
+ const worker = task.gatewayTarget ? { sessionId: task.gatewayTarget.sessionId, workerId: undefined } : this.pool.acquire(task, this.config.tasks.maxConcurrentPerAgent + holding, this.config.tasks.workerIdleTtlMs);
888
983
  if (!worker)
889
984
  return undefined;
890
985
  task.workerId = worker.workerId;
@@ -974,13 +1069,16 @@ class TaskService {
974
1069
  const startedAt = attempt.startedAt ?? attempt.processIdentity?.startedAt ?? task.createdAt;
975
1070
  // Reviews alone never end a task (#557): past the limit without a new
976
1071
  // worker report, stop the attempt through the cancellation path.
977
- const reportedAt = Math.max(startedAt, task.latestProgress?.source === 'worker' ? task.latestProgress.observedAt : 0);
1072
+ let reportedAt = Math.max(startedAt, task.latestProgress?.source === 'worker' ? task.latestProgress.observedAt : 0);
978
1073
  const limit = this.config.tasks.progressStaleLimitMs;
1074
+ // A parent blocked in subagent_wait cannot report; its subagents' reports are its progress.
1075
+ if (limit && task.state === 'running' && observation.observedAt - reportedAt >= limit)
1076
+ reportedAt = Math.max(reportedAt, this.subtreeReportedAt(task.taskId));
979
1077
  if (limit && task.state === 'running' && observation.observedAt - reportedAt >= limit) {
980
1078
  this.stopStalled(task, observation.observedAt - reportedAt, observation);
981
1079
  return;
982
1080
  }
983
- if (observation.observedAt - startedAt >= this.config.tasks.progressStaleMs) {
1081
+ if (observation.observedAt - startedAt >= this.config.tasks.progressStaleMs && observation.observedAt - this.subtreeReportedAt(task.taskId, startedAt) >= this.config.tasks.progressStaleMs) {
984
1082
  if (observation.resultSeenAt !== undefined) {
985
1083
  this.supervise(task, 'result_seen_not_terminal', `The worker returned a final result ${Math.max(0, Math.round((observation.observedAt - observation.resultSeenAt) / 1000))}s ago, but ${observation.pendingBackground ?? 0} native background task(s) have not reported completion, so the task is not terminal yet. The result is accepted automatically once the background grace period passes without activity. Report what is still being awaited; stop background work that is no longer needed.`, observation.observedAt);
986
1084
  }
@@ -990,6 +1088,14 @@ class TaskService {
990
1088
  }
991
1089
  });
992
1090
  }
1091
+ /** The latest worker progress report, or finish, anywhere below a task; `floor` when there is none later. */
1092
+ subtreeReportedAt(taskId, floor = 0) {
1093
+ const row = this.store.get(`WITH RECURSIVE below(id) AS (SELECT id FROM tasks WHERE json_extract(snapshot_json,'$.parentTaskId')=?
1094
+ UNION SELECT t.id FROM tasks t JOIN below b ON json_extract(t.snapshot_json,'$.parentTaskId')=b.id)
1095
+ SELECT MAX(MAX(CASE WHEN json_extract(snapshot_json,'$.latestProgress.source')='worker' THEN json_extract(snapshot_json,'$.latestProgress.observedAt') ELSE 0 END),
1096
+ MAX(CASE WHEN state IN ('completed','failed','cancelled') THEN updated_at ELSE 0 END)) AS at FROM tasks WHERE id IN (SELECT id FROM below)`, taskId);
1097
+ return Math.max(floor, Number(row?.at ?? 0));
1098
+ }
993
1099
  stopStalled(task, quietMs, observation) {
994
1100
  const minutes = Math.round(quietMs / 60000);
995
1101
  const reason = `No new worker progress report for ${minutes} minute(s), past tasks.progressStaleLimitMs (${Math.round(this.config.tasks.progressStaleLimitMs / 60000)} minute(s)).` +
@@ -1000,6 +1106,7 @@ class TaskService {
1000
1106
  this.store.saveTask(task, task.stateVersion);
1001
1107
  this.store.appendEvent(task.conversationId, 'task.progress_stalled', { taskId: task.taskId, attemptId: observation.attemptId, quietMs, limitMs: this.config.tasks.progressStaleLimitMs, resultSeenAt: observation.resultSeenAt, pendingBackground: observation.pendingBackground }, task.taskId);
1002
1108
  this.store.enqueue('interrupt', `stalled:${task.taskId}:${task.stateVersion}`, { taskId: task.taskId });
1109
+ this.cancelSubagents(task);
1003
1110
  }
1004
1111
  /** A supervisor stop is a failure with its evidence, not a user/agent cancellation.
1005
1112
  * An unconfirmed stop keeps the cleanup code every other unconfirmed stop uses. */
@@ -1140,6 +1247,9 @@ class TaskService {
1140
1247
  return receipt.prior;
1141
1248
  if (task.state !== 'running' || task.revision !== attempt.revision)
1142
1249
  throw new types_1.OrchestrationError('SUPERSEDED_QUESTION');
1250
+ // As with a native subagent, only its parent reads its output and nothing could answer it here.
1251
+ if (task.parentTaskId)
1252
+ throw new types_1.OrchestrationError('SUBAGENT_INPUT_UNAVAILABLE', 'A subagent cannot ask questions. Finish now and put the open question, with what you found so far, in your final result; your parent decides.');
1143
1253
  if (computerReport && task.gatewayTarget?.adapter === 'computer')
1144
1254
  task.computerReport = computerReport;
1145
1255
  task.state = 'waiting_input';
@@ -1162,6 +1272,7 @@ class TaskService {
1162
1272
  if (outcome.result.artifactIds.length > 64 || outcome.result.artifactIds.some(id => typeof id !== 'string' || id.length > 1024))
1163
1273
  throw new types_1.OrchestrationError('INVALID_INPUT');
1164
1274
  }
1275
+ const refusals = outcome.type === 'completed' ? outcome.result.providerRefusals : outcome.failure?.providerRefusals ?? outcome.providerRefusals;
1165
1276
  return this.store.transaction(() => {
1166
1277
  const { task, attempt } = this.active(attemptId, generation);
1167
1278
  if (task.gatewayTarget?.adapter === 'computer' && outcome.computerReport)
@@ -1233,6 +1344,12 @@ class TaskService {
1233
1344
  task.failure = stalled;
1234
1345
  task.latestProgress = { source: 'runtime', observedAt: Date.now(), text: stalled.message };
1235
1346
  }
1347
+ // After every failure reassignment above, so a stop or stall reason cannot drop them.
1348
+ if (refusals?.length && attempt.failure && !attempt.failure.providerRefusals) {
1349
+ attempt.failure = { ...attempt.failure, providerRefusals: refusals };
1350
+ if (task.failure)
1351
+ task.failure = attempt.failure;
1352
+ }
1236
1353
  if (task.queuedCommands?.length)
1237
1354
  this.nextQueuedCommand(task, waitingForCommand || outcome.type === 'completed');
1238
1355
  if (task.state === 'cancelled') {
@@ -1242,13 +1359,15 @@ class TaskService {
1242
1359
  if (outcome.type === 'completed' && outcome.result.unresolvedBackground) {
1243
1360
  this.store.appendEvent(task.conversationId, 'task.background_unresolved', { attemptId, ...outcome.result.unresolvedBackground }, task.taskId);
1244
1361
  }
1362
+ if (refusals?.length)
1363
+ this.store.appendEvent(task.conversationId, 'task.provider_refusal', { attemptId, refusals }, task.taskId);
1245
1364
  if (outcome.type !== 'unknown')
1246
1365
  this.pool.release(task.taskId, outcome.type === 'completed' || outcome.type === 'paused');
1247
1366
  this.store.saveAttempt(attempt);
1248
1367
  this.store.saveTask(task, task.stateVersion);
1249
1368
  if (task.state === 'queued')
1250
1369
  this.store.enqueue('schedule', `schedule:${task.taskId}:${task.stateVersion}`, { taskId: task.taskId });
1251
- else if (types_1.TERMINAL_TASK_STATES.has(task.state) || task.state === 'needs_reconciliation' || (waitingForCommand && task.state === 'waiting_input' && task.automationController !== 'user' && task.executionControl?.phase !== 'paused'))
1370
+ else if (types_1.TERMINAL_TASK_STATES.has(task.state) || task.state === 'needs_reconciliation' || (waitingForCommand && task.state === 'waiting_input' && task.automationController !== 'user' && task.executionControl?.phase !== 'paused') || (waitingForCommand && (0, automation_session_1.agentStepRunEnded)(task)))
1252
1371
  this.notify(task);
1253
1372
  return task;
1254
1373
  });
@@ -1284,11 +1403,122 @@ class TaskService {
1284
1403
  task.latestProgress = { source: 'runtime', observedAt: Date.now(), text: [done, `Running queued command: ${JSON.stringify(next.text.slice(0, 120))}${rest.length ? ` (${rest.length} more waiting)` : ''}.`].filter(Boolean).join('\n').slice(0, 4096) };
1285
1404
  }
1286
1405
  notify(task) {
1406
+ // A native subagent dies with its parent session; a durable child would otherwise be orphaned.
1407
+ if (types_1.TERMINAL_TASK_STATES.has(task.state) || task.state === 'needs_reconciliation')
1408
+ this.cancelSubagents(task);
1409
+ // Subagents report to the parent worker (subagent_wait), never to the channel, except an
1410
+ // unconfirmed stop no running parent can see: it holds a slot until someone retries its cleanup.
1411
+ if (task.parentTaskId && !(task.state === 'needs_reconciliation' && !exports.RUNNING_PARENT.includes(this.store.task(task.parentTaskId)?.state ?? '')))
1412
+ return;
1287
1413
  const input = this.store.get('SELECT binding_id FROM conversation_inputs WHERE id=?', task.initiatingInputId);
1288
1414
  const notificationId = (0, crypto_1.randomUUID)();
1289
1415
  this.store.run(`INSERT INTO notifications(id,conversation_id,task_id,task_state_version,originating_binding_id) VALUES(?,?,?,?,?) ON CONFLICT(task_id,task_state_version) DO NOTHING`, notificationId, task.conversationId, task.taskId, task.stateVersion, input.binding_id);
1290
1416
  this.store.enqueue('notification', `notification:${task.taskId}:${task.stateVersion}`, { conversationId: task.conversationId, taskId: task.taskId, notificationId });
1291
1417
  }
1418
+ cancelSubagents(parent) {
1419
+ for (const row of this.store.all("SELECT snapshot_json FROM tasks WHERE json_extract(snapshot_json,'$.parentTaskId')=? AND state NOT IN ('completed','failed','cancelled')", parent.taskId)) {
1420
+ const child = JSON.parse(String(row.snapshot_json));
1421
+ // cancelOwned cascades below each child (at cancel_requested, or via notify once it ends).
1422
+ this.cancelOwned(child.conversationId, child.taskId);
1423
+ }
1424
+ }
1425
+ /**
1426
+ * subagent_spawn: a worker's subagent becomes a task in the same
1427
+ * conversation, with the worker's owner, capabilities and project, linked to
1428
+ * its parent. It is scheduled and admitted like any other task.
1429
+ */
1430
+ spawnSubagent(attemptId, generation, actionId, spec) {
1431
+ (0, store_1.boundedText)(spec.title, 512);
1432
+ (0, store_1.boundedText)(spec.instructions);
1433
+ return this.store.transaction(() => {
1434
+ const { task: parent } = this.active(attemptId, generation);
1435
+ const receipt = this.workerReceipt(attemptId, actionId, 'subagent_spawn', JSON.stringify(spec));
1436
+ if (receipt.prior)
1437
+ return receipt.prior;
1438
+ if (!['starting', 'running'].includes(parent.state))
1439
+ throw new types_1.OrchestrationError('STATE_CONFLICT', `This task is ${parent.state}; it cannot start subagents.`);
1440
+ const depth = (parent.depth ?? 0) + 1;
1441
+ if (depth > subagent_tool_schemas_1.SUBAGENT_MAX_DEPTH)
1442
+ throw new types_1.OrchestrationError('SUBAGENT_DEPTH_EXCEEDED', `Subagents nest at most ${subagent_tool_schemas_1.SUBAGENT_MAX_DEPTH} levels below the root worker. Do this work inline.`);
1443
+ // The same admission as task_spawn: no new work while the conversation drains, and both queue limits.
1444
+ if (this.store.get('SELECT status FROM conversations WHERE id=?', parent.conversationId)?.status !== 'active')
1445
+ throw new types_1.OrchestrationError('DRAINING');
1446
+ const queuedRows = this.store.all("SELECT conversation_id,COUNT(*) AS n FROM tasks WHERE state='queued' GROUP BY conversation_id");
1447
+ const queued = Number(queuedRows.find(row => row.conversation_id === parent.conversationId)?.n ?? 0);
1448
+ if (queued >= this.config.tasks.maxQueuedPerConversation || queuedRows.reduce((n, row) => n + Number(row.n), 0) >= this.config.tasks.maxQueuedPerAgent) {
1449
+ throw new types_1.OrchestrationError('QUEUE_FULL', `This agent already has the most queued tasks it allows. Wait for a subagent to finish (subagent_wait) or do this work inline.`);
1450
+ }
1451
+ const now = Date.now();
1452
+ const task = { taskId: (0, crypto_1.randomUUID)(), conversationId: parent.conversationId, agentId: parent.agentId, agentSessionId: parent.agentSessionId,
1453
+ ownerPrincipalId: parent.ownerPrincipalId, initiatingInputId: parent.initiatingInputId, title: spec.title, targetProfile: 'default-worker',
1454
+ state: 'queued', stateVersion: 1, revision: 1, appliedRevision: 0, timing: { phase: 'queued', since: now, measuredFrom: now, totals: {} },
1455
+ capabilities: parent.capabilities, createdAt: now, updatedAt: now,
1456
+ parentTaskId: parent.taskId, rootTaskId: parent.rootTaskId ?? parent.taskId, depth,
1457
+ // A read-only subagent cannot hand out write access to its own subagents.
1458
+ ...(spec.subagentType ? { subagentType: spec.subagentType } : {}), ...(spec.readonly || parent.readonly ? { readonly: true } : {}) };
1459
+ task.workstreamId = task.taskId;
1460
+ const model = spec.model ?? parent.model;
1461
+ if (model)
1462
+ task.model = model;
1463
+ const effort = spec.effort ?? parent.effort;
1464
+ if (effort)
1465
+ task.effort = effort;
1466
+ if (parent.resourceProfile)
1467
+ task.resourceProfile = parent.resourceProfile;
1468
+ this.store.run('INSERT INTO tasks VALUES(?,?,?,?,?,?,?,?,?)', task.taskId, task.conversationId, task.state, 1, 1, null, JSON.stringify(task), now, now);
1469
+ const revision = { taskId: task.taskId, revision: 1, instructions: spec.instructions, contextRefs: [], mode: 'when_ready', originatingInputId: parent.initiatingInputId };
1470
+ this.store.run('INSERT INTO task_revisions VALUES(?,?,?)', task.taskId, 1, JSON.stringify(revision));
1471
+ this.store.appendEvent(task.conversationId, 'task.created', task, task.taskId);
1472
+ this.store.enqueue('schedule', `schedule:${task.taskId}:1`, { taskId: task.taskId });
1473
+ this.saveWorkerReceipt(attemptId, actionId, 'subagent_spawn', receipt.hash, task);
1474
+ return task;
1475
+ });
1476
+ }
1477
+ /** A subagent's parent, grandparent and so on, nearest first; empty for a root task. */
1478
+ ancestorIds(taskId) {
1479
+ const ids = [];
1480
+ for (let id = this.store.task(taskId)?.parentTaskId; id && ids.length <= subagent_tool_schemas_1.SUBAGENT_MAX_DEPTH;) {
1481
+ ids.push(id);
1482
+ id = this.store.task(id)?.parentTaskId;
1483
+ }
1484
+ return ids;
1485
+ }
1486
+ /** The calling worker's own subagents among `taskIds`; anything else is denied. */
1487
+ subagents(attemptId, generation, taskIds) {
1488
+ const { task: parent } = this.active(attemptId, generation);
1489
+ if (!Array.isArray(taskIds) || !taskIds.length || taskIds.length > 32 || taskIds.some(id => typeof id !== 'string'))
1490
+ throw new types_1.OrchestrationError('INVALID_INPUT');
1491
+ return taskIds.map(id => {
1492
+ const child = this.store.task(id);
1493
+ if (!child || child.parentTaskId !== parent.taskId)
1494
+ throw new types_1.OrchestrationError('ACCESS_DENIED');
1495
+ return child;
1496
+ });
1497
+ }
1498
+ /** subagent_wait: results once every listed subagent has finished; undefined while any is still working. */
1499
+ subagentResults(attemptId, generation, taskIds) {
1500
+ const children = this.subagents(attemptId, generation, taskIds);
1501
+ if (children.some(child => !types_1.TERMINAL_TASK_STATES.has(child.state) && child.state !== 'needs_reconciliation'))
1502
+ return undefined;
1503
+ return children.map(child => ({ task_id: child.taskId, state: child.state, model: child.model, effort: child.effort,
1504
+ ...(child.result ? { result: child.result.summary } : {}),
1505
+ // Files it staged are delivered with the root's result; listed so the parent can refer to them.
1506
+ ...this.stagedFiles(child), ...(child.failure ? { failure: { code: child.failure.code, message: child.failure.message } } : {}),
1507
+ ...(child.state === 'needs_reconciliation' ? { note: 'Its process could not be confirmed stopped and may still be running. Cancel it with subagent_cancel before relying on files it touched.' } : {}) }));
1508
+ }
1509
+ stagedFiles(task) {
1510
+ if (task.state !== 'completed' || !task.result?.artifactIds.length)
1511
+ return {};
1512
+ const names = this.store.all("SELECT f.name FROM task_files f WHERE f.task_id=? AND f.id IN (SELECT value FROM json_each(?)) ORDER BY f.created_at,f.id", task.taskId, JSON.stringify(task.result.artifactIds)).map(row => String(row.name));
1513
+ return names.length ? { staged_files: names } : {};
1514
+ }
1515
+ /** subagent_cancel: cancel the calling worker's own subagents and everything below them. */
1516
+ cancelSubagentTasks(attemptId, generation, taskIds) {
1517
+ return this.store.transaction(() => this.subagents(attemptId, generation, taskIds).map(child => {
1518
+ const task = this.cancelOwned(child.conversationId, child.taskId);
1519
+ return { task_id: task.taskId, state: task.state };
1520
+ }));
1521
+ }
1292
1522
  /** Parent independently checks a fresh, scoped browser observation. Never clears an uncertain mutation. */
1293
1523
  verifyBrowser(context, taskId, revision, requestId, evidenceId, evidence, check) {
1294
1524
  (0, store_1.boundedText)(evidence, 4096);