@oyasmi/pipiclaw 0.9.4-beta.1 → 0.9.4

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 +10 -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,125 @@
1
+ /**
2
+ * The application's registry of per-channel run managers: lazy creation, the host-wide admission
3
+ * count, startup restore across every persisted channel, and the daily garbage-collection timer.
4
+ */
5
+ import { mkdir, readdir, readFile } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+ import { isChannelId } from "../channel/channel-paths.js";
8
+ import * as log from "../log.js";
9
+ import { errorMessage } from "../shared/text-utils.js";
10
+ import { parseRunRecord } from "./run-record.js";
11
+ import { SubAgentRunManager } from "./runs.js";
12
+ async function listRecordChannelIds(stateDir) {
13
+ const channelIds = [];
14
+ for (const entry of await readdir(stateDir, { withFileTypes: true })) {
15
+ if (!entry.isDirectory())
16
+ continue;
17
+ const dir = join(stateDir, entry.name);
18
+ let channelId;
19
+ try {
20
+ for (const filename of (await readdir(dir)).filter((name) => name.endsWith(".json"))) {
21
+ channelId = parseRunRecord(await readFile(join(dir, filename), "utf-8"))?.channelId;
22
+ if (channelId)
23
+ break;
24
+ }
25
+ }
26
+ catch {
27
+ channelId = undefined;
28
+ }
29
+ const resolved = channelId && isChannelId(channelId) ? channelId : entry.name;
30
+ if (isChannelId(resolved))
31
+ channelIds.push(resolved);
32
+ }
33
+ return channelIds;
34
+ }
35
+ /** Owns this application's channel managers and their maintenance timer. */
36
+ export function createSubAgentRuntime(options = {}) {
37
+ const config = { ...options };
38
+ const managers = new Map();
39
+ let stopped = false;
40
+ /** Host-wide running count for the D10.2 admission check, summed across every known channel. */
41
+ function totalRunningSubAgentRuns() {
42
+ let total = 0;
43
+ for (const manager of managers.values()) {
44
+ total += manager.runningCount();
45
+ }
46
+ return total;
47
+ }
48
+ const GARBAGE_COLLECTION_INTERVAL_MS = 24 * 60 * 60_000;
49
+ let garbageCollectionTimer;
50
+ let collectingGarbage = false;
51
+ async function collectGarbageAllChannels() {
52
+ if (collectingGarbage)
53
+ return;
54
+ collectingGarbage = true;
55
+ try {
56
+ for (const manager of managers.values()) {
57
+ await manager.collectGarbage().catch((error) => log.logWarn("subagent.gc.failed", "Run garbage collection pass failed", {
58
+ reason: errorMessage(error),
59
+ }));
60
+ }
61
+ }
62
+ finally {
63
+ collectingGarbage = false;
64
+ }
65
+ }
66
+ function startSubAgentGarbageCollector() {
67
+ if (stopped)
68
+ return;
69
+ if (garbageCollectionTimer)
70
+ clearInterval(garbageCollectionTimer);
71
+ garbageCollectionTimer = setInterval(() => void collectGarbageAllChannels(), GARBAGE_COLLECTION_INTERVAL_MS);
72
+ garbageCollectionTimer.unref?.();
73
+ }
74
+ /** Stop the host-wide daily garbage collector during shutdown or test teardown. */
75
+ function stop() {
76
+ stopped = true;
77
+ for (const manager of managers.values())
78
+ manager.stop();
79
+ if (garbageCollectionTimer) {
80
+ clearInterval(garbageCollectionTimer);
81
+ garbageCollectionTimer = undefined;
82
+ }
83
+ }
84
+ function get(channelId) {
85
+ let manager = managers.get(channelId);
86
+ if (!manager) {
87
+ manager = new SubAgentRunManager(channelId, { ...config, runningCount: totalRunningSubAgentRuns });
88
+ managers.set(channelId, manager);
89
+ if (stopped)
90
+ manager.stop();
91
+ }
92
+ return manager;
93
+ }
94
+ /**
95
+ * Re-adopt every channel's persisted runs at startup, settling any internal run still marked
96
+ * `running` as `lost` (D10.3). Channels are discovered from the state directory itself, exactly
97
+ * like `restoreChannelJobs` — but by reading the records rather than trusting directory names,
98
+ * so a channel is adopted under the id the rest of the runtime can act on.
99
+ */
100
+ async function restore() {
101
+ const stateDir = config.stateDir;
102
+ if (!stateDir)
103
+ return 0;
104
+ let channelIds;
105
+ try {
106
+ await mkdir(stateDir, { recursive: true });
107
+ channelIds = await listRecordChannelIds(stateDir);
108
+ }
109
+ catch (error) {
110
+ log.logWarn("subagent.scan.failed", "Persisted run scan failed", { reason: errorMessage(error) });
111
+ return 0;
112
+ }
113
+ let restored = 0;
114
+ for (const channelId of channelIds) {
115
+ restored += await get(channelId).restore();
116
+ }
117
+ // Reclaim stale runs once as a host-wide startup batch; subsequent batches run daily.
118
+ await collectGarbageAllChannels();
119
+ if (restored > 0) {
120
+ log.logInfoEvent("subagent.restore.done", "Sub-agent run records restored", { fields: { count: restored } });
121
+ }
122
+ return restored;
123
+ }
124
+ return { get, restore, start: startSubAgentGarbageCollector, stop };
125
+ }
@@ -1,239 +1,7 @@
1
1
  import type { ChannelEvent } from "../channel/channel-event.js";
2
2
  import type { ChannelStore } from "../channel/store.js";
3
- import { type UsageTotals } from "../shared/types.js";
4
3
  import type { UsageLedger } from "../usage/ledger.js";
5
- import type { WorkspaceBaseline } from "./workspace-summary.js";
6
- /**
7
- * The run: one abstraction level for delegation, whether it executes as an in-process sub-agent
8
- * or (from spec 040 phase 2 onward) a short-lived external CLI process. See
9
- * `docs/archive/specs/040-async-delegation-and-external-agents/design.md`, D1.
10
- *
11
- * State machine vocabulary is borrowed from `job-manager.ts`'s `JobStatus` rather than inventing
12
- * a second one. Only three facts are persisted as idempotent markers (D1/P5) because only three
13
- * side effects cannot be safely replayed: settling (writes output, frees a lease), recording
14
- * usage (a ledger write is a real charge), and enqueuing the completion wake (redelivery makes
15
- * the parent agent re-process the same result). Everything else — duration, tool counts, verdict
16
- * — is plain data that can be overwritten harmlessly.
17
- */
18
- export type RunStatus = "running" | "completed" | "failed" | "cancelled" | "lost";
19
- export type RunRuntime = "internal" | "external";
20
- export type RunHarness = "claude-code" | "codex-cli" | "exec";
21
- export type RunMutates = "read" | "write";
22
- /**
23
- * Longest a dispatching tool call waits for its run to settle before returning a "still running"
24
- * placeholder instead of the result (D2). A code constant, not a settings key, per CLAUDE.md's
25
- * rule for numeric thresholds.
26
- */
27
- export declare const SYNC_GRACE_MS = 120000;
28
- /**
29
- * Effective sync grace window. A test-only env override (`PIPICLAW_TEST_SUBAGENT_SYNC_GRACE_MS`)
30
- * lets the deterministic e2e layer exercise the detached-settlement + completion-wake path
31
- * (spec 048 A14/A15/A16) without a multi-minute wait; production always uses `SYNC_GRACE_MS`.
32
- */
33
- export declare function resolveSyncGraceMs(override?: number): number;
34
- /** D10.2: per-channel cap on concurrently running delegation runs. */
35
- export declare const MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL = 6;
36
- /** D10.2: host-wide cap across every channel. Bounds unbounded process/worker growth only —
37
- * not the full cross-subsystem (task/job/sidecar) admission scheme the design doc leaves open. */
38
- export declare const MAX_RUNNING_SUBAGENT_RUNS_PER_HOST = 20;
39
- /**
40
- * Human-typeable run ids (spec 041). Runs used to be identified by the dispatching tool call's
41
- * own id, which on some providers is a `call_<24 chars>|fc_<50 chars>` composite — useless in a
42
- * chat UI where a human has to read it back to cancel or inspect a run. `mintRunId()` on
43
- * `SubAgentRunManager` produces `run_` + 6 chars instead; the alphabet excludes 0/1/i/l/o/u
44
- * because those are the characters people misread on a phone screen or misspeak out loud.
45
- */
46
- export declare const RUN_ID_PREFIX = "run_";
47
- export type RunResolution = {
48
- kind: "found";
49
- record: RunRecord;
50
- } | {
51
- kind: "ambiguous";
52
- candidates: RunRecord[];
53
- } | {
54
- kind: "not_found";
55
- };
56
- export interface RunUsage {
57
- usage: UsageTotals;
58
- /** False only for harnesses that cannot report tokens at all (`exec`). */
59
- usageKnown: boolean;
60
- /** False for harnesses that omit a cost field (`codex-cli`, `exec`). */
61
- costKnown: boolean;
62
- }
63
- export interface RunRecord extends RunUsage {
64
- runId: string;
65
- channelId: string;
66
- runtime: RunRuntime;
67
- harness?: RunHarness;
68
- agent: string;
69
- label: string;
70
- source: "predefined" | "inline";
71
- tools: string[];
72
- model?: string;
73
- purpose: "work" | "verify";
74
- taskId?: string;
75
- /** The task's Work Items id this run was dispatched for (spec 052, D4). */
76
- item?: string;
77
- workingDirectory: string;
78
- artifactDir: string;
79
- status: RunStatus;
80
- startedAt: number;
81
- finishedAt?: number;
82
- durationMs?: number;
83
- failureReason?: string;
84
- turns?: number;
85
- toolCalls?: number;
86
- /** The checker's declared `VERDICT:` for a `purpose=verify` run (spec 052, D6): information for the leader, not a gate. */
87
- verificationVerdict?: "pass" | "fail";
88
- /** P2-2: `git status --porcelain` taken right after a `mutates: "write"` run finished, so the
89
- * wake's reader does not have to spend its own first tool call finding out what changed. */
90
- workspaceSummary?: string;
91
- /** A write run's dirty-path snapshot at dispatch, so the post-run summary reports only what this
92
- * run changed (see `workspace-summary.ts`). Persisted so restart reconciliation can use it too. */
93
- workspaceBaseline?: WorkspaceBaseline;
94
- /** Set once settlement (write output, free resources) has happened; guards against replay. */
95
- settledAt?: number;
96
- /**
97
- * Durable settlement intent. While this exists the public status remains `running` and the
98
- * lease is still held; it lets a restart finish a settlement that crashed after the intent was
99
- * recorded but before the terminal record was published.
100
- */
101
- settlementPending?: PendingSettlement;
102
- /** Set once this run's usage has been written to the ledger; guards against double billing. */
103
- usageRecorded?: boolean;
104
- /** Set once this run's cost has been credited to its task. Separate from `usageRecorded` so a
105
- * replayed settlement can never credit it twice. */
106
- taskAccounted?: boolean;
107
- /** Set once the completion wake has been hallmarked for delivery; guards against a duplicate wake. */
108
- wakeEnqueued?: boolean;
109
- /** Durable one-time relationship between the internally produced wake and task activation (T9). */
110
- wakeClaimDispatchId?: string;
111
- wakeConsumedAt?: number;
112
- pid?: number;
113
- /** `ps`'s `lstart` for `pid` at launch — the OS-verifiable identity check that tells this
114
- * process apart from an unrelated one that later reuses the same pid (D10.3). */
115
- pidStartedAt?: string;
116
- /** Wall-clock deadline (`setLaunched` time + `maxWallTimeSec`), so a restart can resume
117
- * enforcing it — an in-process timer dies with the process that set it. */
118
- deadlineAt?: number;
119
- /** Set before the kill signal is sent, so whichever code path eventually settles this run (the
120
- * live in-process watcher or the cross-restart deadline check) reports why, instead of guessing from
121
- * protocol output alone (P1-1). */
122
- terminationReason?: "timeout" | "cancelled";
123
- argv?: string[];
124
- sessionId?: string;
125
- leaseKey?: string;
126
- mutates?: RunMutates;
127
- /** Spec 042 D1: the role's wall-time budget, persisted so restart reconciliation can report an
128
- * accurate "budget exceeded (Ns)" reason instead of reverse-engineering it from `deadlineAt`. */
129
- maxWallTimeSec?: number;
130
- /** Spec 042 D1: the real process start time (`setLaunched` time), as opposed to `startedAt`
131
- * (registration time) — restart reconciliation's duration estimate is measured from here. */
132
- processStartedAt?: number;
133
- /** This run's channel directory, so settlement (including restart reconciliation) can reach the
134
- * owning task's log (spec 052, D4). */
135
- channelDir?: string;
136
- /** True when `durationMs` is a restart-reconciliation estimate rather than a measured process
137
- * lifetime (spec 042 D1) — display surfaces prefix it with "≈". */
138
- durationEstimated?: boolean;
139
- /** Spec 042 D10: non-fatal argv-assembly warnings (e.g. a dropped placeholder token) recorded
140
- * at launch, shown by `/subagents show`. */
141
- invocationWarnings?: string[];
142
- /** Spec 042 D7: fingerprint of the role's `command`/`externalModelRef`/`shell` at launch time
143
- * (external only) — `follow_up` refuses to resume under a role that has since changed one of
144
- * these instead of silently reinterpreting the old session under a new harness invocation. */
145
- roleFingerprint?: string;
146
- /** Spec 042 D12: the harness adapter's own schema version at launch — lets `/subagents show`
147
- * distinguish "the target CLI's own protocol changed under an adapter that hasn't caught up"
148
- * from "the agent itself failed". */
149
- parserVersion?: number;
150
- /** Spec 042 D12: best-effort `<executable> --version` output captured at launch (1s timeout,
151
- * `undefined` if the probe failed or timed out) — the other half of the same diagnosis. */
152
- cliVersion?: string;
153
- }
154
- export interface RegisterRunInput {
155
- runId: string;
156
- channelId: string;
157
- runtime: RunRuntime;
158
- harness?: RunHarness;
159
- agent: string;
160
- label: string;
161
- source: "predefined" | "inline";
162
- tools: string[];
163
- model?: string;
164
- purpose: "work" | "verify";
165
- taskId?: string;
166
- item?: string;
167
- workingDirectory: string;
168
- artifactDir: string;
169
- /** This run's channel directory — where its owning task lives. Set at registration for every
170
- * runtime, so settlement can credit the task whether the run was internal or external; the
171
- * external launch path re-persists it with the rest of its info. */
172
- channelDir?: string;
173
- /** Set only when the caller already holds a workspace write lease for this run (D10.1). */
174
- leaseKey?: string;
175
- mutates?: RunMutates;
176
- workspaceBaseline?: WorkspaceBaseline;
177
- }
178
- interface PendingSettlement {
179
- status: SettleInput["status"];
180
- failureReason?: string;
181
- usage: UsageTotals;
182
- usageKnown: boolean;
183
- costKnown: boolean;
184
- turns: number;
185
- toolCalls: number;
186
- durationMs: number;
187
- durationEstimated?: boolean;
188
- verificationVerdict?: "pass" | "fail";
189
- workspaceSummary?: string;
190
- sessionId?: string;
191
- model?: string;
192
- finishedAt: number;
193
- announce: boolean;
194
- }
195
- export interface SettleInput {
196
- status: "completed" | "failed" | "cancelled" | "lost";
197
- failureReason?: string;
198
- usage: UsageTotals;
199
- usageKnown: boolean;
200
- costKnown: boolean;
201
- turns: number;
202
- toolCalls: number;
203
- durationMs: number;
204
- /** True when `durationMs` is a restart-reconciliation estimate rather than a measured process
205
- * lifetime (spec 042 D1) — display surfaces prefix it with "≈". */
206
- durationEstimated?: boolean;
207
- /** Full reply text. Settlement saves it to `output.md`; only its tail goes in the wake. */
208
- outputText: string;
209
- verificationVerdict?: "pass" | "fail";
210
- /** P2-2: see `RunRecord.workspaceSummary`. */
211
- workspaceSummary?: string;
212
- /** The harness's own session/thread id, captured even on failure so a later resume can still use it. */
213
- sessionId?: string;
214
- /** The model that actually produced the result, when it differs from the one registered (an
215
- * internal run that switched to the backup model). Usage is billed against this one. */
216
- model?: string;
217
- }
218
- /**
219
- * A best-effort, out-of-band notice about a run — distinct from the completion wake (`dispatch`).
220
- * The wake is an LLM turn (its delivery latency is whatever the model takes to respond); a notice
221
- * is plain text rendered straight to the channel, so it reaches the user in roughly the time the
222
- * run itself takes to settle, not the wake turn's latency on top of that.
223
- */
224
- export interface RunNotice {
225
- kind: "settled" | "progress" | "stalled";
226
- runId: string;
227
- agent: string;
228
- /** Only set for `kind: "settled"`. */
229
- status?: RunStatus;
230
- durationMs: number;
231
- /** Only set for `kind: "progress"`: the harness's most recently observed step, already short. */
232
- step?: string;
233
- /** Only set for `kind: "stalled"`: how long the run has written no output. */
234
- silentMs?: number;
235
- }
236
- export type RunNotifier = (channelId: string, notice: RunNotice) => void | Promise<void>;
4
+ import { type RegisterRunInput, type RunNotifier, type RunRecord, type RunResolution, type RunStatus, type SettleInput } from "./run-record.js";
237
5
  export interface RunManagerOptions {
238
6
  /**
239
7
  * Root of the per-channel record directories (`<stateDir>/<escaped channelId>/`, escaped by
@@ -388,7 +156,7 @@ export declare class SubAgentRunManager {
388
156
  * Dispatch the completion wake. Durable-dispatch persists its own pending record before this
389
157
  * call can be interrupted (`DurableDispatchService.dispatch`), and `dispatch()` is idempotent on
390
158
  * `dispatchId`, so calling it again after a crash between here and marking `wakeEnqueued` is
391
- * harmless — this is the same fix as job-manager's `announce()` reordering (D7).
159
+ * harmless — this is the same fix as jobs/manager's `announce()` reordering (D7).
392
160
  */
393
161
  private announce;
394
162
  /** Explicit cancel (`subagent_run op=cancel`, spec 040 D6). Does not wake — it is the model's own decision. */
@@ -438,12 +206,8 @@ export declare class SubAgentRunManager {
438
206
  private collectGarbageIfExpired;
439
207
  collectGarbage(now?: number): Promise<void>;
440
208
  }
441
- /** Owns this application's channel managers and their maintenance timer. */
442
- export declare function createSubAgentRuntime(options?: RunManagerOptions): {
443
- get: (channelId: string) => SubAgentRunManager;
444
- restore: () => Promise<number>;
445
- start: () => void;
446
- stop: () => void;
447
- };
448
- export type SubAgentRuntime = ReturnType<typeof createSubAgentRuntime>;
449
- export {};
209
+ /**
210
+ * The channel each record directory belongs to. The id is read out of a record itself — the one
211
+ * lossless source, since a directory name is the *escaped* id and `__` cannot be turned back
212
+ * into `/` — with the directory name as the fallback for a directory without a readable record.
213
+ */