@oyasmi/pipiclaw 0.9.4-beta.1 → 0.9.4-beta.2

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 (291) hide show
  1. package/dist/agent/builtin-commands.d.ts +19 -0
  2. package/dist/agent/builtin-commands.js +80 -0
  3. package/dist/agent/channel-runner.d.ts +20 -208
  4. package/dist/agent/channel-runner.js +148 -1245
  5. package/dist/agent/maintenance-context.d.ts +1 -1
  6. package/dist/agent/maintenance-context.js +1 -1
  7. package/dist/agent/prompt/resources.d.ts +3 -0
  8. package/dist/agent/prompt/resources.js +7 -1
  9. package/dist/agent/runner-factory.d.ts +1 -43
  10. package/dist/agent/{command-extension.d.ts → session/command-extension.d.ts} +4 -0
  11. package/dist/agent/{command-extension.js → session/command-extension.js} +5 -5
  12. package/dist/agent/{type-guards.d.ts → session/event-guards.d.ts} +2 -2
  13. package/dist/agent/{type-guards.js → session/event-guards.js} +5 -1
  14. package/dist/agent/session/model-selection.d.ts +47 -0
  15. package/dist/agent/session/model-selection.js +99 -0
  16. package/dist/agent/{session-adapter.d.ts → session/session-adapter.d.ts} +21 -1
  17. package/dist/agent/{session-adapter.js → session/session-adapter.js} +83 -1
  18. package/dist/agent/{session-events.d.ts → session/session-events.d.ts} +9 -5
  19. package/dist/agent/{session-events.js → session/session-events.js} +10 -10
  20. package/dist/agent/session/session-host.d.ts +200 -0
  21. package/dist/agent/session/session-host.js +621 -0
  22. package/dist/agent/{session-resource-gate.js → session/session-resource-gate.js} +2 -2
  23. package/dist/agent/{context-budget.js → turn/context-budget.js} +5 -1
  24. package/dist/agent/{progress-formatter.d.ts → turn/progress-formatter.d.ts} +4 -1
  25. package/dist/agent/{run-queue.d.ts → turn/run-queue.d.ts} +1 -1
  26. package/dist/agent/{run-queue.js → turn/run-queue.js} +3 -3
  27. package/dist/{memory → agent/turn}/task-digest.js +4 -4
  28. package/dist/agent/turn/turn-context.d.ts +14 -0
  29. package/dist/agent/turn/turn-context.js +64 -0
  30. package/dist/agent/turn/turn-finish.d.ts +50 -0
  31. package/dist/agent/turn/turn-finish.js +188 -0
  32. package/dist/agent/turn/turn-input.d.ts +43 -0
  33. package/dist/agent/turn/turn-input.js +79 -0
  34. package/dist/agent/turn/turn-pipeline.d.ts +68 -0
  35. package/dist/agent/turn/turn-pipeline.js +257 -0
  36. package/dist/agent/{turn-prompt.d.ts → turn/turn-prompt.d.ts} +2 -2
  37. package/dist/agent/{turn-prompt.js → turn/turn-prompt.js} +6 -2
  38. package/dist/agent/{turn-recovery.js → turn/turn-recovery.js} +1 -1
  39. package/dist/agent/{turn-state.d.ts → turn/turn-state.d.ts} +1 -1
  40. package/dist/agent/types.d.ts +43 -2
  41. package/dist/agent/types.js +1 -1
  42. package/dist/{models/auth-cli.d.ts → app/auth-command.d.ts} +1 -1
  43. package/dist/{models/auth-cli.js → app/auth-command.js} +11 -8
  44. package/dist/{runtime/app-home.d.ts → app/home.d.ts} +0 -2
  45. package/dist/{runtime/app-home.js → app/home.js} +4 -75
  46. package/dist/{app-services.d.ts → app/services.d.ts} +5 -5
  47. package/dist/{app-services.js → app/services.js} +10 -10
  48. package/dist/channel/channel-context.d.ts +12 -2
  49. package/dist/channel/channel-context.js +29 -2
  50. package/dist/channel/channel-event.d.ts +10 -2
  51. package/dist/channel/channel-event.js +1 -1
  52. package/dist/{runtime/project-commands.d.ts → channel/commands.d.ts} +1 -1
  53. package/dist/{runtime/project-commands.js → channel/commands.js} +1 -1
  54. package/dist/channel/store.js +4 -0
  55. package/dist/commands/catalog.d.ts +3 -3
  56. package/dist/commands/catalog.js +3 -3
  57. package/dist/{runtime/report-commands.d.ts → commands/router.d.ts} +10 -3
  58. package/dist/{runtime/report-commands.js → commands/router.js} +5 -5
  59. package/dist/{settings.d.ts → config/settings.d.ts} +7 -8
  60. package/dist/{settings.js → config/settings.js} +7 -10
  61. package/dist/{tools/config.d.ts → config/tools.d.ts} +1 -2
  62. package/dist/{tools/config.js → config/tools.js} +5 -2
  63. package/dist/dingtalk/access-token.d.ts +12 -0
  64. package/dist/dingtalk/access-token.js +51 -0
  65. package/dist/dingtalk/api.d.ts +19 -0
  66. package/dist/dingtalk/api.js +67 -0
  67. package/dist/dingtalk/bot.d.ts +97 -0
  68. package/dist/dingtalk/bot.js +389 -0
  69. package/dist/dingtalk/cards.d.ts +56 -0
  70. package/dist/dingtalk/cards.js +318 -0
  71. package/dist/{runtime → dingtalk}/channel-queue.js +3 -0
  72. package/dist/dingtalk/config.d.ts +19 -0
  73. package/dist/dingtalk/config.js +95 -0
  74. package/dist/dingtalk/connection.d.ts +57 -0
  75. package/dist/dingtalk/connection.js +356 -0
  76. package/dist/dingtalk/conversation-meta.d.ts +16 -0
  77. package/dist/dingtalk/conversation-meta.js +77 -0
  78. package/dist/{runtime → dingtalk}/delivery.d.ts +6 -2
  79. package/dist/dingtalk/handler.d.ts +90 -0
  80. package/dist/dingtalk/handler.js +1 -0
  81. package/dist/dingtalk/inbound.d.ts +66 -0
  82. package/dist/dingtalk/inbound.js +137 -0
  83. package/dist/dingtalk/media.d.ts +66 -0
  84. package/dist/dingtalk/media.js +214 -0
  85. package/dist/events/{event-commands.js → commands.js} +6 -2
  86. package/dist/events/parse.d.ts +14 -0
  87. package/dist/events/parse.js +114 -0
  88. package/dist/events/types.d.ts +93 -0
  89. package/dist/events/types.js +1 -0
  90. package/dist/events/{event-validation.d.ts → validation.d.ts} +1 -1
  91. package/dist/events/watcher.d.ts +67 -0
  92. package/dist/events/{events.js → watcher.js} +6 -109
  93. package/dist/index.d.ts +6 -4
  94. package/dist/index.js +2 -2
  95. package/dist/jobs/launch.d.ts +42 -0
  96. package/dist/jobs/launch.js +118 -0
  97. package/dist/{agent/job-manager.d.ts → jobs/manager.d.ts} +1 -67
  98. package/dist/{agent/job-manager.js → jobs/manager.js} +3 -146
  99. package/dist/jobs/record.d.ts +55 -0
  100. package/dist/jobs/record.js +36 -0
  101. package/dist/main.js +2 -2
  102. package/dist/memory/maintenance-gates.d.ts +2 -2
  103. package/dist/memory/maintenance-tuning.d.ts +15 -0
  104. package/dist/memory/maintenance-tuning.js +3 -0
  105. package/dist/memory/reflect-job.d.ts +2 -2
  106. package/dist/memory/reflect-job.js +4 -2
  107. package/dist/memory/scheduler.d.ts +3 -3
  108. package/dist/memory/scheduler.js +2 -1
  109. package/dist/memory/sidecar-worker.js +1 -1
  110. package/dist/memory/transcript.js +1 -1
  111. package/dist/{agent/model-fallback.d.ts → models/fallback.d.ts} +6 -6
  112. package/dist/{agent/model-fallback.js → models/fallback.js} +15 -28
  113. package/dist/models/login-identity.d.ts +2 -0
  114. package/dist/models/login-identity.js +83 -0
  115. package/dist/models/provider-login.d.ts +3 -1
  116. package/dist/models/provider-login.js +8 -2
  117. package/dist/models/reference.d.ts +20 -0
  118. package/dist/models/{utils.js → reference.js} +0 -48
  119. package/dist/models/{utils.d.ts → runtime.d.ts} +1 -16
  120. package/dist/models/runtime.js +52 -0
  121. package/dist/playbooks/catalog.d.ts +6 -2
  122. package/dist/playbooks/catalog.js +9 -6
  123. package/dist/runtime/bootstrap.d.ts +7 -17
  124. package/dist/runtime/bootstrap.js +37 -755
  125. package/dist/runtime/durable-dispatch.d.ts +17 -4
  126. package/dist/runtime/durable-dispatch.js +60 -18
  127. package/dist/runtime/inbound-images.d.ts +18 -0
  128. package/dist/runtime/inbound-images.js +51 -0
  129. package/dist/runtime/shutdown.d.ts +39 -0
  130. package/dist/runtime/shutdown.js +120 -0
  131. package/dist/runtime/stop-watchdog.d.ts +16 -0
  132. package/dist/runtime/stop-watchdog.js +32 -0
  133. package/dist/runtime/task-driver.d.ts +2 -2
  134. package/dist/runtime/task-driver.js +3 -3
  135. package/dist/runtime/task-migration.js +2 -2
  136. package/dist/runtime/task-spawn.d.ts +1 -1
  137. package/dist/runtime/task-spawn.js +1 -1
  138. package/dist/runtime/turn-handler.d.ts +47 -0
  139. package/dist/runtime/turn-handler.js +318 -0
  140. package/dist/runtime/turn-run.d.ts +52 -0
  141. package/dist/runtime/turn-run.js +318 -0
  142. package/dist/security/command-guard.js +4 -0
  143. package/dist/security/network.js +4 -0
  144. package/dist/security/path-guard.js +4 -0
  145. package/dist/security/types.d.ts +1 -2
  146. package/dist/security/types.js +1 -2
  147. package/dist/shared/exact-keys.d.ts +1 -1
  148. package/dist/shared/host-process.js +1 -1
  149. package/dist/shared/wake-claim.d.ts +1 -1
  150. package/dist/{runtime/skill-commands.d.ts → skills/commands.d.ts} +2 -2
  151. package/dist/{runtime/skill-commands.js → skills/commands.js} +1 -1
  152. package/dist/{agent/workspace-resources.js → skills/loader.js} +1 -1
  153. package/dist/{tools/skill-security.js → skills/validation.js} +4 -0
  154. package/dist/skills/workspace.d.ts +33 -0
  155. package/dist/skills/workspace.js +116 -0
  156. package/dist/{runtime/subagent-commands.d.ts → subagents/commands.d.ts} +4 -3
  157. package/dist/{runtime/subagent-commands.js → subagents/commands.js} +2 -2
  158. package/dist/subagents/completion-wake.d.ts +17 -0
  159. package/dist/subagents/completion-wake.js +76 -0
  160. package/dist/subagents/detached-discovery.js +1 -1
  161. package/dist/subagents/discovery.d.ts +1 -1
  162. package/dist/subagents/discovery.js +2 -2
  163. package/dist/subagents/dispatch.d.ts +33 -0
  164. package/dist/subagents/dispatch.js +190 -0
  165. package/dist/subagents/external/dispatch.d.ts +25 -0
  166. package/dist/subagents/external/dispatch.js +90 -0
  167. package/dist/subagents/external/harness.d.ts +1 -1
  168. package/dist/subagents/external/progress-tail.d.ts +1 -1
  169. package/dist/subagents/external/run.d.ts +2 -1
  170. package/dist/subagents/external/run.js +2 -2
  171. package/dist/subagents/external/settlement.d.ts +1 -1
  172. package/dist/subagents/format.d.ts +1 -1
  173. package/dist/subagents/grace.d.ts +24 -0
  174. package/dist/subagents/grace.js +57 -0
  175. package/dist/subagents/internal/outcome.d.ts +24 -0
  176. package/dist/subagents/internal/outcome.js +149 -0
  177. package/dist/subagents/internal/provider-retry.d.ts +19 -0
  178. package/dist/subagents/internal/provider-retry.js +83 -0
  179. package/dist/subagents/internal/run.d.ts +31 -0
  180. package/dist/subagents/internal/run.js +240 -0
  181. package/dist/subagents/internal/state.d.ts +43 -0
  182. package/dist/subagents/internal/state.js +48 -0
  183. package/dist/subagents/internal/worker.d.ts +51 -0
  184. package/dist/subagents/internal/worker.js +167 -0
  185. package/dist/subagents/result.d.ts +62 -0
  186. package/dist/subagents/result.js +103 -0
  187. package/dist/subagents/run-record.d.ts +222 -0
  188. package/dist/subagents/run-record.js +101 -0
  189. package/dist/subagents/run-registry.d.ts +9 -0
  190. package/dist/subagents/run-registry.js +125 -0
  191. package/dist/subagents/runs.d.ts +7 -243
  192. package/dist/subagents/runs.js +8 -291
  193. package/dist/subagents/task-envelope.d.ts +36 -0
  194. package/dist/subagents/task-envelope.js +168 -0
  195. package/dist/subagents/types.d.ts +154 -0
  196. package/dist/subagents/types.js +1 -0
  197. package/dist/subagents/verification-outcome.d.ts +1 -1
  198. package/dist/tasks/board.d.ts +2 -2
  199. package/dist/tasks/board.js +2 -2
  200. package/dist/tasks/{work-log.d.ts → bound-work.d.ts} +1 -1
  201. package/dist/tasks/{work-log.js → bound-work.js} +1 -1
  202. package/dist/tasks/brief.js +1 -1
  203. package/dist/{runtime/task-commands.d.ts → tasks/commands.d.ts} +1 -1
  204. package/dist/{runtime/task-commands.js → tasks/commands.js} +12 -8
  205. package/dist/tasks/contract-input.d.ts +1 -1
  206. package/dist/tasks/contract-input.js +1 -1
  207. package/dist/tasks/create.js +1 -1
  208. package/dist/tasks/{log.js → loop-log.js} +1 -1
  209. package/dist/tasks/mutation-lock.js +1 -1
  210. package/dist/tasks/session-path.js +1 -1
  211. package/dist/tasks/steer.js +1 -1
  212. package/dist/tasks/store.js +2 -2
  213. package/dist/tools/bash.d.ts +1 -1
  214. package/dist/tools/{tool-details.d.ts → contract/details.d.ts} +2 -2
  215. package/dist/tools/{tool-details.js → contract/details.js} +4 -4
  216. package/dist/tools/{presentation.js → contract/presentation.js} +3 -3
  217. package/dist/tools/event-manage.d.ts +1 -1
  218. package/dist/tools/event-manage.js +4 -4
  219. package/dist/tools/index.d.ts +3 -3
  220. package/dist/tools/index.js +7 -6
  221. package/dist/tools/job.d.ts +1 -1
  222. package/dist/tools/registry.d.ts +7 -7
  223. package/dist/tools/registry.js +6 -6
  224. package/dist/tools/session-search.d.ts +1 -1
  225. package/dist/tools/skill.d.ts +2 -34
  226. package/dist/tools/skill.js +8 -116
  227. package/dist/tools/subagent-manage.js +4 -3
  228. package/dist/tools/subagent.d.ts +46 -0
  229. package/dist/tools/subagent.js +127 -0
  230. package/dist/tools/{task-manage.d.ts → task-manage/factory.d.ts} +7 -3
  231. package/dist/tools/{task-manage.js → task-manage/factory.js} +7 -7
  232. package/dist/tools/task-manage/lifecycle.js +2 -2
  233. package/dist/tools/task-manage/log-view.js +2 -2
  234. package/dist/tools/task-manage/shared.js +3 -3
  235. package/dist/tools/task-manage/step-end.js +3 -3
  236. package/dist/tools/task-manage/types.d.ts +1 -1
  237. package/dist/tools/web-fetch.d.ts +1 -1
  238. package/dist/tools/web-search.d.ts +1 -1
  239. package/dist/tui/app.d.ts +1 -1
  240. package/dist/tui/app.js +6 -6
  241. package/dist/tui/cli.d.ts +1 -1
  242. package/dist/tui/cli.js +1 -1
  243. package/dist/tui/frontend.d.ts +44 -0
  244. package/dist/tui/frontend.js +13 -0
  245. package/dist/tui/pitui-frontend.d.ts +1 -1
  246. package/dist/tui/plain-frontend.d.ts +1 -1
  247. package/dist/tui/renderer.d.ts +3 -42
  248. package/dist/tui/terminal-context.d.ts +2 -2
  249. package/dist/tui/terminal-media-sender.d.ts +1 -1
  250. package/dist/tui/turn-controller.d.ts +1 -1
  251. package/dist/usage/ledger.js +4 -0
  252. package/dist/{shared/types.d.ts → usage/totals.d.ts} +3 -0
  253. package/dist/web/client.d.ts +5 -1
  254. package/dist/web/client.js +4 -0
  255. package/dist/web/config.d.ts +1 -1
  256. package/dist/web/fetch.d.ts +1 -1
  257. package/dist/web/search-providers.d.ts +1 -1
  258. package/dist/web/search.d.ts +1 -1
  259. package/package.json +9 -7
  260. package/dist/events/events.d.ts +0 -159
  261. package/dist/runtime/dingtalk.d.ts +0 -272
  262. package/dist/runtime/dingtalk.js +0 -1470
  263. package/dist/subagents/tool.d.ts +0 -213
  264. package/dist/subagents/tool.js +0 -1282
  265. /package/dist/{runtime → agent/prompt}/workspace-templates.d.ts +0 -0
  266. /package/dist/{runtime → agent/prompt}/workspace-templates.js +0 -0
  267. /package/dist/agent/{session-resource-gate.d.ts → session/session-resource-gate.d.ts} +0 -0
  268. /package/dist/agent/{context-budget.d.ts → turn/context-budget.d.ts} +0 -0
  269. /package/dist/agent/{progress-formatter.js → turn/progress-formatter.js} +0 -0
  270. /package/dist/{memory → agent/turn}/task-digest.d.ts +0 -0
  271. /package/dist/agent/{turn-error.d.ts → turn/turn-error.d.ts} +0 -0
  272. /package/dist/agent/{turn-error.js → turn/turn-error.js} +0 -0
  273. /package/dist/agent/{turn-recovery.d.ts → turn/turn-recovery.d.ts} +0 -0
  274. /package/dist/agent/{turn-state.js → turn/turn-state.js} +0 -0
  275. /package/dist/{runtime → app}/proxy.d.ts +0 -0
  276. /package/dist/{runtime → app}/proxy.js +0 -0
  277. /package/dist/{runtime → dingtalk}/channel-queue.d.ts +0 -0
  278. /package/dist/{runtime → dingtalk}/delivery.js +0 -0
  279. /package/dist/{runtime → dingtalk}/inbound-media.d.ts +0 -0
  280. /package/dist/{runtime → dingtalk}/inbound-media.js +0 -0
  281. /package/dist/events/{event-commands.d.ts → commands.d.ts} +0 -0
  282. /package/dist/events/{event-validation.js → validation.js} +0 -0
  283. /package/dist/{agent/workspace-resources.d.ts → skills/loader.d.ts} +0 -0
  284. /package/dist/{tools/skill-security.d.ts → skills/validation.d.ts} +0 -0
  285. /package/dist/tasks/{ledger.d.ts → contract.d.ts} +0 -0
  286. /package/dist/tasks/{ledger.js → contract.js} +0 -0
  287. /package/dist/tasks/{log.d.ts → loop-log.d.ts} +0 -0
  288. /package/dist/tools/{subagent-tool-names.d.ts → contract/names.d.ts} +0 -0
  289. /package/dist/tools/{subagent-tool-names.js → contract/names.js} +0 -0
  290. /package/dist/tools/{presentation.d.ts → contract/presentation.d.ts} +0 -0
  291. /package/dist/{shared/types.js → usage/totals.js} +0 -0
@@ -0,0 +1,167 @@
1
+ /**
2
+ * The worker of an internal run: its directory-pinned executor, its scoped tool set, creation of the
3
+ * SDK agent, and the event subscription that counts turns and tool calls and enforces the budgets.
4
+ */
5
+ import { Agent } from "@earendil-works/pi-agent-core";
6
+ import { clampThinkingLevel, streamSimple } from "@earendil-works/pi-ai/compat";
7
+ import { convertToLlm } from "@earendil-works/pi-coding-agent";
8
+ import { getJournalDir } from "../../memory/journal.js";
9
+ import { getChannelMemoryDir, getChannelMemoryIndexPath } from "../../memory/store.js";
10
+ import { DEFAULT_SECURITY_CONFIG } from "../../security/config.js";
11
+ import { describeToolCall } from "../../tools/contract/presentation.js";
12
+ import { addUsage } from "../../usage/totals.js";
13
+ import { DEFAULT_THINKING_LEVEL, withSubAgentsDirWriteDeny, } from "../discovery.js";
14
+ import { formatStatus } from "../result.js";
15
+ /**
16
+ * Pins every command a run issues to the run's working directory. It sets the child's real `cwd`
17
+ * rather than prefixing `cd <dir> &&`: the prefix silently produced a *different* command than the
18
+ * guard inspected, and a directory that cannot be entered surfaced as a shell error inside an
19
+ * otherwise successful command line.
20
+ */
21
+ export class DirectoryExecutor {
22
+ constructor(base, directory) {
23
+ this.base = base;
24
+ this.directory = directory;
25
+ }
26
+ exec(command, options) {
27
+ return this.base.exec(command, { ...options, cwd: this.directory });
28
+ }
29
+ }
30
+ export function isAssistantMessage(message) {
31
+ return typeof message === "object" && message !== null && "role" in message && message.role === "assistant";
32
+ }
33
+ export function getLastAssistantMessage(messages) {
34
+ for (let i = messages.length - 1; i >= 0; i--) {
35
+ const message = messages[i];
36
+ if (isAssistantMessage(message)) {
37
+ return message;
38
+ }
39
+ }
40
+ return null;
41
+ }
42
+ /**
43
+ * Sub-agents share the main agent's `write`/`edit` tools but only receive the runtime
44
+ * context (task text), never the "the MEMORY.md index is generated, write memory only through
45
+ * memory_save" rule the main agent gets in its system prompt (the memory tools themselves are
46
+ * withheld from sub-agents). Denying these paths at the path-guard level closes that gap
47
+ * structurally instead of relying on a sub-agent to infer an instruction it never received — a
48
+ * stray write/edit here would race the shared memory serial queue (channel-maintenance-queue)
49
+ * and silently corrupt durable memory.
50
+ */
51
+ function withSubagentMemoryWriteDeny(securityConfig, channelDir, workspaceDir) {
52
+ const protectedPaths = [
53
+ getChannelMemoryDir(channelDir),
54
+ getJournalDir(channelDir),
55
+ getChannelMemoryIndexPath(channelDir),
56
+ ];
57
+ // The role directory gets the same structural denial (spec 040, D8.1): a sub-agent's write/edit
58
+ // tools are exactly as capable of writing a self-authorizing `runtime: external` role file as
59
+ // the main agent's are.
60
+ return withSubAgentsDirWriteDeny({
61
+ ...securityConfig,
62
+ pathGuard: {
63
+ ...securityConfig.pathGuard,
64
+ writeDeny: [...securityConfig.pathGuard.writeDeny, ...protectedPaths],
65
+ },
66
+ }, workspaceDir);
67
+ }
68
+ /**
69
+ * Build a sub-agent's tool set through the injected `buildWorkerTools` (the registry's sub-agent
70
+ * whitelist: files + web), with its own security context and per-invocation bash timeout.
71
+ */
72
+ export function buildSubagentTools(executor, bashTimeoutSec, options, runContext) {
73
+ const securityConfig = withSubagentMemoryWriteDeny(options.securityConfig ?? DEFAULT_SECURITY_CONFIG, options.channelDir, options.workspaceDir);
74
+ return options
75
+ .buildWorkerTools({
76
+ executor,
77
+ fileStore: options.fileStore,
78
+ securityConfig,
79
+ securityContext: {
80
+ // No `channelDir`: a sub-agent receives channel state through its injected context
81
+ // blocks, not by reading the channel's own files, so it does not inherit the parent's
82
+ // channel-directory exception (see security/types.ts).
83
+ agentWorkspaceDir: options.workspaceDir,
84
+ projectRoot: runContext.workingDirectory,
85
+ boundary: options.projectBoundary,
86
+ },
87
+ channelId: options.runtimeContext.channelId,
88
+ channelDir: options.channelDir,
89
+ workspaceDir: options.workspaceDir,
90
+ webConfig: options.webConfig,
91
+ rtkEnabled: options.rtkEnabled,
92
+ bashDefaultTimeoutSeconds: bashTimeoutSec,
93
+ })
94
+ .filter((tool) => runContext.purpose !== "verify" || (tool.name !== "write" && tool.name !== "edit"));
95
+ }
96
+ function filterToolsByName(allTools, names) {
97
+ const allowed = new Set(names);
98
+ return allTools.filter((tool) => allowed.has(tool.name));
99
+ }
100
+ /**
101
+ * Build the scoped tool set, create the worker, arm the wall-clock budget and subscribe to its
102
+ * events. Everything is recorded on `handle` immediately, before the next step can throw.
103
+ */
104
+ export function startWorker(input) {
105
+ const { handle, options, config, runContext, scopedExecutor, state, retryBackoff, runManager, emitUpdate } = input;
106
+ const availableTools = (options.buildTools ?? buildSubagentTools)(scopedExecutor, config.bashTimeoutSec, options, runContext);
107
+ handle.worker =
108
+ options.createWorker?.({
109
+ subAgent: config,
110
+ apiKey: state.apiKey,
111
+ tools: filterToolsByName(availableTools, config.tools),
112
+ }) ??
113
+ new Agent({
114
+ initialState: {
115
+ systemPrompt: config.systemPrompt,
116
+ model: config.model,
117
+ // Same clamp the main agent applies (channel-runner.ts) before setting a model's
118
+ // thinkingLevel: a model with `reasoning: false` gets "off", an unsupported tier
119
+ // snaps to the nearest one, instead of a raw unsupported value reaching the provider.
120
+ // The internal path's resolved config always fills thinkingLevel; the fallback
121
+ // here only closes the type.
122
+ thinkingLevel: clampThinkingLevel(config.model, config.thinkingLevel ?? DEFAULT_THINKING_LEVEL),
123
+ tools: filterToolsByName(availableTools, config.tools),
124
+ },
125
+ convertToLlm,
126
+ // Read on every request, so a backup-model switch only has to replace the key.
127
+ getApiKey: async () => state.apiKey,
128
+ streamFn: streamSimple,
129
+ });
130
+ handle.wallClockTimer = setTimeout(() => {
131
+ state.failureReason = `Wall time budget exceeded (${config.maxWallTimeSec}s)`;
132
+ state.budgetExceeded = true;
133
+ retryBackoff.abort();
134
+ handle.worker?.abort();
135
+ }, config.maxWallTimeSec * 1000);
136
+ handle.unsubscribe = handle.worker.subscribe((event) => {
137
+ if (event.type === "message_end" && isAssistantMessage(event.message)) {
138
+ state.assistantTurns++;
139
+ addUsage(state.usage, event.message.usage);
140
+ }
141
+ if (event.type === "tool_execution_start") {
142
+ state.toolCalls++;
143
+ const label = describeToolCall(event.toolName, event.args);
144
+ emitUpdate(formatStatus(config.name, label));
145
+ // After detaching, the step goes out as a paced run notice instead, like an external
146
+ // run's progress tail — otherwise an async internal run is silent until it settles.
147
+ if (state.detached)
148
+ runManager.noteProgress(runContext.runId, label);
149
+ if (state.toolCalls > config.maxToolCalls) {
150
+ state.failureReason = `Tool call budget exceeded (${config.maxToolCalls})`;
151
+ state.budgetExceeded = true;
152
+ emitUpdate(formatStatus(config.name, "tool budget reached"));
153
+ handle.worker?.abort();
154
+ }
155
+ }
156
+ if (event.type === "turn_end" &&
157
+ isAssistantMessage(event.message) &&
158
+ event.toolResults.length > 0 &&
159
+ state.assistantTurns >= config.maxTurns) {
160
+ state.failureReason = `Turn budget exceeded (${config.maxTurns})`;
161
+ state.budgetExceeded = true;
162
+ emitUpdate(formatStatus(config.name, "turn budget reached"));
163
+ handle.worker?.abort();
164
+ }
165
+ });
166
+ emitUpdate(formatStatus(config.name, "started"));
167
+ }
@@ -0,0 +1,62 @@
1
+ import type { UsageTotals } from "../usage/totals.js";
2
+ import type { ResolvedSubAgentConfig, SubAgentConfig } from "./discovery.js";
3
+ import type { SubAgentRunContext, SubAgentToolFields } from "./types.js";
4
+ /**
5
+ * Reply budget for what a sub-agent hands back to its parent (spec 032 D4), measured in the
6
+ * same prompt-unit currency as the system prompt budget (shared/prompt-units.ts). The full
7
+ * output always lands on disk under the artifact directory regardless of this budget — this
8
+ * only caps what gets echoed into the parent's context.
9
+ */
10
+ export declare const MAX_SUBAGENT_RESULT_UNITS = 1200;
11
+ /**
12
+ * Character ceiling paired with the unit ceiling. `prompt-units.ts` notes that a long
13
+ * separator-free run of letters/digits counts as a single unit, so a units-only budget can still
14
+ * pass through an unbounded blob — every budget must bound units *and* chars (fix plan §2.4).
15
+ */
16
+ export declare const MAX_SUBAGENT_RESULT_CHARS = 12000;
17
+ export declare function formatStatus(agentName: string, text: string): string;
18
+ /**
19
+ * The "still running, don't wait or re-dispatch" reply shared by every dispatch path that hands
20
+ * back a placeholder instead of the run's own result: external always takes this path (D2); an
21
+ * internal run takes it once the sync grace window elapses (D2/D7). Only the runtime label
22
+ * (`external, <harness>` vs `internal, async`) differs between the two.
23
+ */
24
+ export declare function buildDispatchedText(runId: string, agentName: string, runtimeLabel: string, workingDirectory: string): string;
25
+ export declare function buildFailureText(config: SubAgentConfig, reason: string, lastAssistantText: string): string;
26
+ export declare function buildStoppedText(config: SubAgentConfig, reason: string, finalText: string): string;
27
+ export interface FinalizedSubAgentOutput {
28
+ replyText: string;
29
+ truncated: boolean;
30
+ }
31
+ /**
32
+ * Spec 032 D4: the full text always lands on disk, independent of whether it fits the reply
33
+ * budget. What comes back to the parent is capped at MAX_SUBAGENT_RESULT_UNITS; a reply over
34
+ * budget is truncated with a pointer to the file a chatty sub-agent can no longer blow out the
35
+ * parent's context.
36
+ *
37
+ * The file itself is written by `SubAgentRunManager.settle()` — the one settlement point both
38
+ * runtimes share (spec 040 D1) — which always runs before this call's reply reaches the parent.
39
+ * This function only needs the path, to point at it.
40
+ *
41
+ * Spec 046 D2.2 removed `returns: "artifact"` and the ARTIFACT marker protocol: a caller that
42
+ * needs a specific output file states the path in the task text instead, the path external roles
43
+ * already had to follow.
44
+ */
45
+ export declare function finalizeSubAgentOutput(runContext: SubAgentRunContext, finalText: string): FinalizedSubAgentOutput;
46
+ export declare function createDetails(input: {
47
+ config: ResolvedSubAgentConfig;
48
+ runContext: SubAgentRunContext;
49
+ usage: UsageTotals;
50
+ turns: number;
51
+ toolCalls: number;
52
+ durationMs: number;
53
+ failed?: boolean;
54
+ failureReason?: string;
55
+ verificationVerdict?: "pass" | "fail";
56
+ resultTruncated?: boolean;
57
+ /** Set for the "[Dispatched]" placeholder returned instead of waiting on the run (D2). */
58
+ dispatched?: boolean;
59
+ /** External roles report their harness's own model string, never `formatModelReference`. */
60
+ modelOverride?: string;
61
+ toolsOverride?: string[];
62
+ }): SubAgentToolFields;
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Shaping what a delegation hands back: status lines, the "[Dispatched]" placeholder, failure and
3
+ * stopped text, the reply-size budget, and the structured `details` payload.
4
+ */
5
+ import { join } from "node:path";
6
+ import { formatModelReference } from "../models/reference.js";
7
+ import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
8
+ /**
9
+ * Reply budget for what a sub-agent hands back to its parent (spec 032 D4), measured in the
10
+ * same prompt-unit currency as the system prompt budget (shared/prompt-units.ts). The full
11
+ * output always lands on disk under the artifact directory regardless of this budget — this
12
+ * only caps what gets echoed into the parent's context.
13
+ */
14
+ export const MAX_SUBAGENT_RESULT_UNITS = 1_200;
15
+ /**
16
+ * Character ceiling paired with the unit ceiling. `prompt-units.ts` notes that a long
17
+ * separator-free run of letters/digits counts as a single unit, so a units-only budget can still
18
+ * pass through an unbounded blob — every budget must bound units *and* chars (fix plan §2.4).
19
+ */
20
+ export const MAX_SUBAGENT_RESULT_CHARS = 12_000;
21
+ const RESULT_TRUNCATION_HEAD_RATIO = 1;
22
+ export function formatStatus(agentName, text) {
23
+ return `Subagent ${agentName}: ${text}`;
24
+ }
25
+ /**
26
+ * The "still running, don't wait or re-dispatch" reply shared by every dispatch path that hands
27
+ * back a placeholder instead of the run's own result: external always takes this path (D2); an
28
+ * internal run takes it once the sync grace window elapses (D2/D7). Only the runtime label
29
+ * (`external, <harness>` vs `internal, async`) differs between the two.
30
+ */
31
+ export function buildDispatchedText(runId, agentName, runtimeLabel, workingDirectory) {
32
+ return (`[Dispatched] runId=${runId}, agent ${agentName} (${runtimeLabel}), working directory ${workingDirectory}.\n` +
33
+ "Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
34
+ "Finish independent work and dispatches, then end the turn when only waiting remains; do not re-dispatch or poll to wait. " +
35
+ 'Inside a task step, use task_step_end outcome=park with ticket {"kind":"work"}.');
36
+ }
37
+ export function buildFailureText(config, reason, lastAssistantText) {
38
+ const trimmedLastText = lastAssistantText.trim();
39
+ if (!trimmedLastText) {
40
+ return `Sub-agent ${config.name} failed: ${reason}`;
41
+ }
42
+ return `Sub-agent ${config.name} failed: ${reason}\n\nLast output:\n${trimmedLastText}`;
43
+ }
44
+ export function buildStoppedText(config, reason, finalText) {
45
+ const trimmedFinalText = finalText.trim();
46
+ if (!trimmedFinalText) {
47
+ return `Sub-agent ${config.name} stopped: ${reason}`;
48
+ }
49
+ return `[Sub-agent ${config.name} stopped: ${reason}]\n\n${trimmedFinalText}`;
50
+ }
51
+ /**
52
+ * Spec 032 D4: the full text always lands on disk, independent of whether it fits the reply
53
+ * budget. What comes back to the parent is capped at MAX_SUBAGENT_RESULT_UNITS; a reply over
54
+ * budget is truncated with a pointer to the file a chatty sub-agent can no longer blow out the
55
+ * parent's context.
56
+ *
57
+ * The file itself is written by `SubAgentRunManager.settle()` — the one settlement point both
58
+ * runtimes share (spec 040 D1) — which always runs before this call's reply reaches the parent.
59
+ * This function only needs the path, to point at it.
60
+ *
61
+ * Spec 046 D2.2 removed `returns: "artifact"` and the ARTIFACT marker protocol: a caller that
62
+ * needs a specific output file states the path in the task text instead, the path external roles
63
+ * already had to follow.
64
+ */
65
+ export function finalizeSubAgentOutput(runContext, finalText) {
66
+ const outputPath = join(runContext.artifactDir, "output.md");
67
+ if (countPromptUnits(finalText) <= MAX_SUBAGENT_RESULT_UNITS && finalText.length <= MAX_SUBAGENT_RESULT_CHARS) {
68
+ return { replyText: finalText, truncated: false };
69
+ }
70
+ const clipped = clipTextByPromptUnits(finalText, MAX_SUBAGENT_RESULT_UNITS, {
71
+ headRatio: RESULT_TRUNCATION_HEAD_RATIO,
72
+ maxChars: MAX_SUBAGENT_RESULT_CHARS,
73
+ marker: `\n\n[... truncated; full output saved at ${outputPath} ...]\n\n`,
74
+ });
75
+ return { replyText: clipped.text, truncated: true };
76
+ }
77
+ export function createDetails(input) {
78
+ return {
79
+ agent: input.config.name,
80
+ source: input.config.source,
81
+ model: input.modelOverride ??
82
+ (input.config.runtime === "external"
83
+ ? (input.config.externalModelRef ?? "default")
84
+ : formatModelReference(input.config.model)),
85
+ tools: input.toolsOverride ?? [...input.config.tools],
86
+ turns: input.turns,
87
+ toolCalls: input.toolCalls,
88
+ durationMs: input.durationMs,
89
+ failed: input.failed ?? false,
90
+ failureReason: input.failureReason,
91
+ usage: {
92
+ ...input.usage,
93
+ cost: { ...input.usage.cost },
94
+ },
95
+ runId: input.runContext.runId,
96
+ purpose: input.runContext.purpose,
97
+ taskId: input.runContext.taskId,
98
+ verificationVerdict: input.verificationVerdict,
99
+ artifactDir: input.runContext.artifactDir,
100
+ resultTruncated: input.resultTruncated ?? false,
101
+ dispatched: input.dispatched,
102
+ };
103
+ }
@@ -0,0 +1,222 @@
1
+ import type { UsageTotals } from "../usage/totals.js";
2
+ import type { WorkspaceBaseline } from "./workspace-summary.js";
3
+ export type RunStatus = "running" | "completed" | "failed" | "cancelled" | "lost";
4
+ export type RunRuntime = "internal" | "external";
5
+ export type RunHarness = "claude-code" | "codex-cli" | "exec";
6
+ export type RunMutates = "read" | "write";
7
+ export type RunResolution = {
8
+ kind: "found";
9
+ record: RunRecord;
10
+ } | {
11
+ kind: "ambiguous";
12
+ candidates: RunRecord[];
13
+ } | {
14
+ kind: "not_found";
15
+ };
16
+ /** The settlement intent persisted before a run's terminal record is published. */
17
+ export interface PendingSettlement {
18
+ status: SettleInput["status"];
19
+ failureReason?: string;
20
+ usage: UsageTotals;
21
+ usageKnown: boolean;
22
+ costKnown: boolean;
23
+ turns: number;
24
+ toolCalls: number;
25
+ durationMs: number;
26
+ durationEstimated?: boolean;
27
+ verificationVerdict?: "pass" | "fail";
28
+ workspaceSummary?: string;
29
+ sessionId?: string;
30
+ model?: string;
31
+ finishedAt: number;
32
+ announce: boolean;
33
+ }
34
+ export interface RunUsage {
35
+ usage: UsageTotals;
36
+ /** False only for harnesses that cannot report tokens at all (`exec`). */
37
+ usageKnown: boolean;
38
+ /** False for harnesses that omit a cost field (`codex-cli`, `exec`). */
39
+ costKnown: boolean;
40
+ }
41
+ export interface RunRecord extends RunUsage {
42
+ runId: string;
43
+ channelId: string;
44
+ runtime: RunRuntime;
45
+ harness?: RunHarness;
46
+ agent: string;
47
+ label: string;
48
+ source: "predefined" | "inline";
49
+ tools: string[];
50
+ model?: string;
51
+ purpose: "work" | "verify";
52
+ taskId?: string;
53
+ /** The task's Work Items id this run was dispatched for (spec 052, D4). */
54
+ item?: string;
55
+ workingDirectory: string;
56
+ artifactDir: string;
57
+ status: RunStatus;
58
+ startedAt: number;
59
+ finishedAt?: number;
60
+ durationMs?: number;
61
+ failureReason?: string;
62
+ turns?: number;
63
+ toolCalls?: number;
64
+ /** The checker's declared `VERDICT:` for a `purpose=verify` run (spec 052, D6): information for the leader, not a gate. */
65
+ verificationVerdict?: "pass" | "fail";
66
+ /** P2-2: `git status --porcelain` taken right after a `mutates: "write"` run finished, so the
67
+ * wake's reader does not have to spend its own first tool call finding out what changed. */
68
+ workspaceSummary?: string;
69
+ /** A write run's dirty-path snapshot at dispatch, so the post-run summary reports only what this
70
+ * run changed (see `workspace-summary.ts`). Persisted so restart reconciliation can use it too. */
71
+ workspaceBaseline?: WorkspaceBaseline;
72
+ /** Set once settlement (write output, free resources) has happened; guards against replay. */
73
+ settledAt?: number;
74
+ /**
75
+ * Durable settlement intent. While this exists the public status remains `running` and the
76
+ * lease is still held; it lets a restart finish a settlement that crashed after the intent was
77
+ * recorded but before the terminal record was published.
78
+ */
79
+ settlementPending?: PendingSettlement;
80
+ /** Set once this run's usage has been written to the ledger; guards against double billing. */
81
+ usageRecorded?: boolean;
82
+ /** Set once this run's cost has been credited to its task. Separate from `usageRecorded` so a
83
+ * replayed settlement can never credit it twice. */
84
+ taskAccounted?: boolean;
85
+ /** Set once the completion wake has been hallmarked for delivery; guards against a duplicate wake. */
86
+ wakeEnqueued?: boolean;
87
+ /** Durable one-time relationship between the internally produced wake and task activation (T9). */
88
+ wakeClaimDispatchId?: string;
89
+ wakeConsumedAt?: number;
90
+ pid?: number;
91
+ /** `ps`'s `lstart` for `pid` at launch — the OS-verifiable identity check that tells this
92
+ * process apart from an unrelated one that later reuses the same pid (D10.3). */
93
+ pidStartedAt?: string;
94
+ /** Wall-clock deadline (`setLaunched` time + `maxWallTimeSec`), so a restart can resume
95
+ * enforcing it — an in-process timer dies with the process that set it. */
96
+ deadlineAt?: number;
97
+ /** Set before the kill signal is sent, so whichever code path eventually settles this run (the
98
+ * live in-process watcher or the cross-restart deadline check) reports why, instead of guessing from
99
+ * protocol output alone (P1-1). */
100
+ terminationReason?: "timeout" | "cancelled";
101
+ argv?: string[];
102
+ sessionId?: string;
103
+ leaseKey?: string;
104
+ mutates?: RunMutates;
105
+ /** Spec 042 D1: the role's wall-time budget, persisted so restart reconciliation can report an
106
+ * accurate "budget exceeded (Ns)" reason instead of reverse-engineering it from `deadlineAt`. */
107
+ maxWallTimeSec?: number;
108
+ /** Spec 042 D1: the real process start time (`setLaunched` time), as opposed to `startedAt`
109
+ * (registration time) — restart reconciliation's duration estimate is measured from here. */
110
+ processStartedAt?: number;
111
+ /** This run's channel directory, so settlement (including restart reconciliation) can reach the
112
+ * owning task's log (spec 052, D4). */
113
+ channelDir?: string;
114
+ /** True when `durationMs` is a restart-reconciliation estimate rather than a measured process
115
+ * lifetime (spec 042 D1) — display surfaces prefix it with "≈". */
116
+ durationEstimated?: boolean;
117
+ /** Spec 042 D10: non-fatal argv-assembly warnings (e.g. a dropped placeholder token) recorded
118
+ * at launch, shown by `/subagents show`. */
119
+ invocationWarnings?: string[];
120
+ /** Spec 042 D7: fingerprint of the role's `command`/`externalModelRef`/`shell` at launch time
121
+ * (external only) — `follow_up` refuses to resume under a role that has since changed one of
122
+ * these instead of silently reinterpreting the old session under a new harness invocation. */
123
+ roleFingerprint?: string;
124
+ /** Spec 042 D12: the harness adapter's own schema version at launch — lets `/subagents show`
125
+ * distinguish "the target CLI's own protocol changed under an adapter that hasn't caught up"
126
+ * from "the agent itself failed". */
127
+ parserVersion?: number;
128
+ /** Spec 042 D12: best-effort `<executable> --version` output captured at launch (1s timeout,
129
+ * `undefined` if the probe failed or timed out) — the other half of the same diagnosis. */
130
+ cliVersion?: string;
131
+ }
132
+ export interface RegisterRunInput {
133
+ runId: string;
134
+ channelId: string;
135
+ runtime: RunRuntime;
136
+ harness?: RunHarness;
137
+ agent: string;
138
+ label: string;
139
+ source: "predefined" | "inline";
140
+ tools: string[];
141
+ model?: string;
142
+ purpose: "work" | "verify";
143
+ taskId?: string;
144
+ item?: string;
145
+ workingDirectory: string;
146
+ artifactDir: string;
147
+ /** This run's channel directory — where its owning task lives. Set at registration for every
148
+ * runtime, so settlement can credit the task whether the run was internal or external; the
149
+ * external launch path re-persists it with the rest of its info. */
150
+ channelDir?: string;
151
+ /** Set only when the caller already holds a workspace write lease for this run (D10.1). */
152
+ leaseKey?: string;
153
+ mutates?: RunMutates;
154
+ workspaceBaseline?: WorkspaceBaseline;
155
+ }
156
+ export interface SettleInput {
157
+ status: "completed" | "failed" | "cancelled" | "lost";
158
+ failureReason?: string;
159
+ usage: UsageTotals;
160
+ usageKnown: boolean;
161
+ costKnown: boolean;
162
+ turns: number;
163
+ toolCalls: number;
164
+ durationMs: number;
165
+ /** True when `durationMs` is a restart-reconciliation estimate rather than a measured process
166
+ * lifetime (spec 042 D1) — display surfaces prefix it with "≈". */
167
+ durationEstimated?: boolean;
168
+ /** Full reply text. Settlement saves it to `output.md`; only its tail goes in the wake. */
169
+ outputText: string;
170
+ verificationVerdict?: "pass" | "fail";
171
+ /** P2-2: see `RunRecord.workspaceSummary`. */
172
+ workspaceSummary?: string;
173
+ /** The harness's own session/thread id, captured even on failure so a later resume can still use it. */
174
+ sessionId?: string;
175
+ /** The model that actually produced the result, when it differs from the one registered (an
176
+ * internal run that switched to the backup model). Usage is billed against this one. */
177
+ model?: string;
178
+ }
179
+ /**
180
+ * A best-effort, out-of-band notice about a run — distinct from the completion wake (`dispatch`).
181
+ * The wake is an LLM turn (its delivery latency is whatever the model takes to respond); a notice
182
+ * is plain text rendered straight to the channel, so it reaches the user in roughly the time the
183
+ * run itself takes to settle, not the wake turn's latency on top of that.
184
+ */
185
+ export interface RunNotice {
186
+ kind: "settled" | "progress" | "stalled";
187
+ runId: string;
188
+ agent: string;
189
+ /** Only set for `kind: "settled"`. */
190
+ status?: RunStatus;
191
+ durationMs: number;
192
+ /** Only set for `kind: "progress"`: the harness's most recently observed step, already short. */
193
+ step?: string;
194
+ /** Only set for `kind: "stalled"`: how long the run has written no output. */
195
+ silentMs?: number;
196
+ }
197
+ export type RunNotifier = (channelId: string, notice: RunNotice) => void | Promise<void>;
198
+ /** D10.2: per-channel cap on concurrently running delegation runs. */
199
+ export declare const MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL = 6;
200
+ /** D10.2: host-wide cap across every channel. Bounds unbounded process/worker growth only —
201
+ * not the full cross-subsystem (task/job/sidecar) admission scheme the design doc leaves open. */
202
+ export declare const MAX_RUNNING_SUBAGENT_RUNS_PER_HOST = 20;
203
+ /**
204
+ * Human-typeable run ids (spec 041). Runs used to be identified by the dispatching tool call's
205
+ * own id, which on some providers is a `call_<24 chars>|fc_<50 chars>` composite — useless in a
206
+ * chat UI where a human has to read it back to cancel or inspect a run. `mintRunId()` on
207
+ * `SubAgentRunManager` produces `run_` + 6 chars instead; the alphabet excludes 0/1/i/l/o/u
208
+ * because those are the characters people misread on a phone screen or misspeak out loud.
209
+ */
210
+ export declare const RUN_ID_PREFIX = "run_";
211
+ export declare function randomRunIdSuffix(): string;
212
+ /** Strips a leading `run_` (case-insensitive) so `show a1b2c3` and `show run_a1b2c3` resolve
213
+ * the same way — nobody should have to remember whether the prefix is required. */
214
+ export declare function normalizeRunIdQuery(query: string): string;
215
+ /** Settled runs and every runtime-managed artifact are retained together for one week. GC runs
216
+ * daily, so an item can remain for up to one additional sweep interval after this age. */
217
+ export declare const RUN_RETENTION_MS: number;
218
+ export declare const RUN_ARTIFACT_FILENAMES: readonly ["prompt.txt", "system-prompt.txt", "events.jsonl", "stderr.log", "output.md"];
219
+ export declare function isTerminal(status: RunStatus): boolean;
220
+ export declare function createPendingSettlement(input: SettleInput, finishedAt: number, announce: boolean): PendingSettlement;
221
+ export declare function applyPendingSettlement(record: RunRecord, pending: PendingSettlement): void;
222
+ export declare function parseRunRecord(raw: string): RunRecord | undefined;
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Run vocabulary and its pure helpers: the record, registration and settlement shapes, run-id
3
+ * minting and matching, the pending-settlement transform and the record parser. No state and no I/O,
4
+ * so the run manager and the external-run helpers can share it without an import cycle (spec 054 D9/D12).
5
+ */
6
+ import { isRecord } from "../shared/type-guards.js";
7
+ /** D10.2: per-channel cap on concurrently running delegation runs. */
8
+ export const MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL = 6;
9
+ /** D10.2: host-wide cap across every channel. Bounds unbounded process/worker growth only —
10
+ * not the full cross-subsystem (task/job/sidecar) admission scheme the design doc leaves open. */
11
+ export const MAX_RUNNING_SUBAGENT_RUNS_PER_HOST = 20;
12
+ /**
13
+ * Human-typeable run ids (spec 041). Runs used to be identified by the dispatching tool call's
14
+ * own id, which on some providers is a `call_<24 chars>|fc_<50 chars>` composite — useless in a
15
+ * chat UI where a human has to read it back to cancel or inspect a run. `mintRunId()` on
16
+ * `SubAgentRunManager` produces `run_` + 6 chars instead; the alphabet excludes 0/1/i/l/o/u
17
+ * because those are the characters people misread on a phone screen or misspeak out loud.
18
+ */
19
+ export const RUN_ID_PREFIX = "run_";
20
+ const RUN_ID_ALPHABET = "23456789abcdefghjkmnpqrstvwxyz";
21
+ const RUN_ID_SUFFIX_LEN = 6;
22
+ export function randomRunIdSuffix() {
23
+ let suffix = "";
24
+ for (let i = 0; i < RUN_ID_SUFFIX_LEN; i++) {
25
+ suffix += RUN_ID_ALPHABET[Math.floor(Math.random() * RUN_ID_ALPHABET.length)];
26
+ }
27
+ return suffix;
28
+ }
29
+ /** Strips a leading `run_` (case-insensitive) so `show a1b2c3` and `show run_a1b2c3` resolve
30
+ * the same way — nobody should have to remember whether the prefix is required. */
31
+ export function normalizeRunIdQuery(query) {
32
+ const lower = query.trim().toLowerCase();
33
+ return lower.startsWith(RUN_ID_PREFIX) ? lower.slice(RUN_ID_PREFIX.length) : lower;
34
+ }
35
+ /** Settled runs and every runtime-managed artifact are retained together for one week. GC runs
36
+ * daily, so an item can remain for up to one additional sweep interval after this age. */
37
+ export const RUN_RETENTION_MS = 7 * 24 * 60 * 60_000;
38
+ export const RUN_ARTIFACT_FILENAMES = [
39
+ "prompt.txt",
40
+ "system-prompt.txt",
41
+ "events.jsonl",
42
+ "stderr.log",
43
+ "output.md",
44
+ ];
45
+ export function isTerminal(status) {
46
+ return status !== "running";
47
+ }
48
+ export function createPendingSettlement(input, finishedAt, announce) {
49
+ return {
50
+ status: input.status,
51
+ failureReason: input.failureReason,
52
+ usage: input.usage,
53
+ usageKnown: input.usageKnown,
54
+ costKnown: input.costKnown,
55
+ turns: input.turns,
56
+ toolCalls: input.toolCalls,
57
+ durationMs: input.durationMs,
58
+ durationEstimated: input.durationEstimated,
59
+ verificationVerdict: input.verificationVerdict,
60
+ workspaceSummary: input.workspaceSummary,
61
+ sessionId: input.sessionId,
62
+ model: input.model,
63
+ finishedAt,
64
+ announce,
65
+ };
66
+ }
67
+ export function applyPendingSettlement(record, pending) {
68
+ record.status = pending.status;
69
+ record.failureReason = pending.failureReason;
70
+ record.usage = pending.usage;
71
+ record.usageKnown = pending.usageKnown;
72
+ record.costKnown = pending.costKnown;
73
+ record.turns = pending.turns;
74
+ record.toolCalls = pending.toolCalls;
75
+ record.durationMs = pending.durationMs;
76
+ record.durationEstimated = pending.durationEstimated;
77
+ record.verificationVerdict = pending.verificationVerdict;
78
+ record.workspaceSummary = pending.workspaceSummary;
79
+ if (pending.sessionId)
80
+ record.sessionId = pending.sessionId;
81
+ if (pending.model)
82
+ record.model = pending.model;
83
+ record.finishedAt = pending.finishedAt;
84
+ record.settledAt = pending.finishedAt;
85
+ record.settlementPending = undefined;
86
+ }
87
+ export function parseRunRecord(raw) {
88
+ const value = JSON.parse(raw);
89
+ if (!isRecord(value) ||
90
+ typeof value.runId !== "string" ||
91
+ typeof value.channelId !== "string" ||
92
+ (value.runtime !== "internal" && value.runtime !== "external") ||
93
+ typeof value.agent !== "string" ||
94
+ typeof value.workingDirectory !== "string" ||
95
+ typeof value.artifactDir !== "string" ||
96
+ typeof value.status !== "string" ||
97
+ typeof value.startedAt !== "number") {
98
+ return undefined;
99
+ }
100
+ return value;
101
+ }
@@ -0,0 +1,9 @@
1
+ import { type RunManagerOptions, SubAgentRunManager } from "./runs.js";
2
+ /** Owns this application's channel managers and their maintenance timer. */
3
+ export declare function createSubAgentRuntime(options?: RunManagerOptions): {
4
+ get: (channelId: string) => SubAgentRunManager;
5
+ restore: () => Promise<number>;
6
+ start: () => void;
7
+ stop: () => void;
8
+ };
9
+ export type SubAgentRuntime = ReturnType<typeof createSubAgentRuntime>;