@oyasmi/pipiclaw 0.9.3 → 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 (336) 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 +167 -1188
  5. package/dist/agent/maintenance-context.d.ts +1 -1
  6. package/dist/agent/maintenance-context.js +1 -1
  7. package/dist/agent/prompt/manifest.d.ts +6 -1
  8. package/dist/agent/prompt/manifest.js +45 -64
  9. package/dist/agent/prompt/resources.d.ts +3 -0
  10. package/dist/agent/prompt/resources.js +11 -2
  11. package/dist/agent/runner-factory.d.ts +1 -43
  12. package/dist/agent/{command-extension.d.ts → session/command-extension.d.ts} +4 -0
  13. package/dist/agent/{command-extension.js → session/command-extension.js} +48 -35
  14. package/dist/agent/{type-guards.d.ts → session/event-guards.d.ts} +2 -2
  15. package/dist/agent/{type-guards.js → session/event-guards.js} +5 -1
  16. package/dist/agent/session/model-selection.d.ts +47 -0
  17. package/dist/agent/session/model-selection.js +99 -0
  18. package/dist/agent/{session-adapter.d.ts → session/session-adapter.d.ts} +21 -1
  19. package/dist/agent/session/session-adapter.js +159 -0
  20. package/dist/agent/{session-events.d.ts → session/session-events.d.ts} +9 -5
  21. package/dist/agent/{session-events.js → session/session-events.js} +24 -13
  22. package/dist/agent/session/session-host.d.ts +200 -0
  23. package/dist/agent/session/session-host.js +621 -0
  24. package/dist/agent/{session-resource-gate.js → session/session-resource-gate.js} +5 -3
  25. package/dist/agent/status-render.d.ts +0 -1
  26. package/dist/agent/status-render.js +4 -16
  27. package/dist/agent/{context-budget.js → turn/context-budget.js} +5 -1
  28. package/dist/agent/{progress-formatter.d.ts → turn/progress-formatter.d.ts} +4 -1
  29. package/dist/agent/{run-queue.d.ts → turn/run-queue.d.ts} +1 -1
  30. package/dist/agent/{run-queue.js → turn/run-queue.js} +10 -5
  31. package/dist/{memory → agent/turn}/task-digest.js +4 -4
  32. package/dist/agent/turn/turn-context.d.ts +14 -0
  33. package/dist/agent/turn/turn-context.js +64 -0
  34. package/dist/agent/turn/turn-error.d.ts +31 -0
  35. package/dist/agent/turn/turn-error.js +68 -0
  36. package/dist/agent/turn/turn-finish.d.ts +50 -0
  37. package/dist/agent/turn/turn-finish.js +188 -0
  38. package/dist/agent/turn/turn-input.d.ts +43 -0
  39. package/dist/agent/turn/turn-input.js +79 -0
  40. package/dist/agent/turn/turn-pipeline.d.ts +68 -0
  41. package/dist/agent/turn/turn-pipeline.js +257 -0
  42. package/dist/agent/{turn-prompt.d.ts → turn/turn-prompt.d.ts} +2 -2
  43. package/dist/agent/{turn-prompt.js → turn/turn-prompt.js} +6 -2
  44. package/dist/agent/{turn-recovery.js → turn/turn-recovery.js} +1 -1
  45. package/dist/agent/{turn-state.d.ts → turn/turn-state.d.ts} +1 -1
  46. package/dist/agent/types.d.ts +43 -2
  47. package/dist/agent/types.js +1 -1
  48. package/dist/{models/auth-cli.d.ts → app/auth-command.d.ts} +1 -1
  49. package/dist/{models/auth-cli.js → app/auth-command.js} +14 -10
  50. package/dist/{runtime/app-home.d.ts → app/home.d.ts} +6 -2
  51. package/dist/{runtime/app-home.js → app/home.js} +22 -75
  52. package/dist/{runtime → app}/proxy.js +4 -2
  53. package/dist/{app-services.d.ts → app/services.d.ts} +5 -5
  54. package/dist/{app-services.js → app/services.js} +17 -14
  55. package/dist/channel/channel-context.d.ts +12 -2
  56. package/dist/channel/channel-context.js +29 -2
  57. package/dist/channel/channel-event.d.ts +10 -2
  58. package/dist/channel/channel-event.js +1 -1
  59. package/dist/channel/channel-index.js +4 -1
  60. package/dist/{runtime/project-commands.d.ts → channel/commands.d.ts} +1 -1
  61. package/dist/{runtime/project-commands.js → channel/commands.js} +17 -16
  62. package/dist/channel/project-scope-store.js +1 -1
  63. package/dist/channel/store.js +4 -0
  64. package/dist/commands/catalog.d.ts +24 -7
  65. package/dist/commands/catalog.js +91 -44
  66. package/dist/commands/reply-limits.d.ts +6 -0
  67. package/dist/commands/reply-limits.js +24 -0
  68. package/dist/{runtime/report-commands.d.ts → commands/router.d.ts} +10 -3
  69. package/dist/{runtime/report-commands.js → commands/router.js} +6 -6
  70. package/dist/{settings.d.ts → config/settings.d.ts} +10 -10
  71. package/dist/{settings.js → config/settings.js} +11 -11
  72. package/dist/{tools/config.d.ts → config/tools.d.ts} +1 -2
  73. package/dist/{tools/config.js → config/tools.js} +5 -2
  74. package/dist/dingtalk/access-token.d.ts +12 -0
  75. package/dist/dingtalk/access-token.js +51 -0
  76. package/dist/dingtalk/api.d.ts +19 -0
  77. package/dist/dingtalk/api.js +67 -0
  78. package/dist/dingtalk/bot.d.ts +97 -0
  79. package/dist/dingtalk/bot.js +389 -0
  80. package/dist/dingtalk/cards.d.ts +56 -0
  81. package/dist/dingtalk/cards.js +318 -0
  82. package/dist/{runtime → dingtalk}/channel-queue.js +4 -1
  83. package/dist/dingtalk/config.d.ts +19 -0
  84. package/dist/dingtalk/config.js +95 -0
  85. package/dist/dingtalk/connection.d.ts +57 -0
  86. package/dist/dingtalk/connection.js +356 -0
  87. package/dist/dingtalk/conversation-meta.d.ts +16 -0
  88. package/dist/dingtalk/conversation-meta.js +77 -0
  89. package/dist/{runtime → dingtalk}/delivery.d.ts +6 -2
  90. package/dist/{runtime → dingtalk}/delivery.js +29 -15
  91. package/dist/dingtalk/handler.d.ts +90 -0
  92. package/dist/dingtalk/handler.js +1 -0
  93. package/dist/dingtalk/inbound.d.ts +66 -0
  94. package/dist/dingtalk/inbound.js +137 -0
  95. package/dist/dingtalk/media.d.ts +66 -0
  96. package/dist/dingtalk/media.js +214 -0
  97. package/dist/events/{event-commands.js → commands.js} +99 -45
  98. package/dist/events/parse.d.ts +14 -0
  99. package/dist/events/parse.js +114 -0
  100. package/dist/events/types.d.ts +93 -0
  101. package/dist/events/types.js +1 -0
  102. package/dist/events/{event-validation.d.ts → validation.d.ts} +14 -3
  103. package/dist/events/{event-validation.js → validation.js} +17 -9
  104. package/dist/events/watcher.d.ts +67 -0
  105. package/dist/events/{events.js → watcher.js} +63 -121
  106. package/dist/executor.js +2 -2
  107. package/dist/index.d.ts +6 -4
  108. package/dist/index.js +2 -2
  109. package/dist/jobs/launch.d.ts +42 -0
  110. package/dist/jobs/launch.js +118 -0
  111. package/dist/{agent/job-manager.d.ts → jobs/manager.d.ts} +1 -67
  112. package/dist/{agent/job-manager.js → jobs/manager.js} +34 -157
  113. package/dist/jobs/record.d.ts +55 -0
  114. package/dist/jobs/record.js +36 -0
  115. package/dist/log.d.ts +12 -2
  116. package/dist/log.js +26 -34
  117. package/dist/main.js +3 -3
  118. package/dist/memory/commands.js +29 -23
  119. package/dist/memory/lifecycle.js +26 -5
  120. package/dist/memory/maintenance-gates.d.ts +2 -2
  121. package/dist/memory/maintenance-state.js +4 -1
  122. package/dist/memory/maintenance-tuning.d.ts +15 -0
  123. package/dist/memory/maintenance-tuning.js +3 -0
  124. package/dist/memory/reflect-job.d.ts +2 -2
  125. package/dist/memory/reflect-job.js +4 -2
  126. package/dist/memory/scheduler.d.ts +3 -3
  127. package/dist/memory/scheduler.js +5 -2
  128. package/dist/memory/sidecar-worker.js +1 -1
  129. package/dist/memory/transcript.js +1 -1
  130. package/dist/{agent/model-fallback.d.ts → models/fallback.d.ts} +6 -6
  131. package/dist/{agent/model-fallback.js → models/fallback.js} +15 -28
  132. package/dist/models/login-identity.d.ts +2 -0
  133. package/dist/models/login-identity.js +83 -0
  134. package/dist/models/provider-login.d.ts +3 -1
  135. package/dist/models/provider-login.js +8 -2
  136. package/dist/models/reference.d.ts +20 -0
  137. package/dist/models/{utils.js → reference.js} +0 -48
  138. package/dist/models/{utils.d.ts → runtime.d.ts} +1 -16
  139. package/dist/models/runtime.js +52 -0
  140. package/dist/paths.d.ts +2 -0
  141. package/dist/paths.js +9 -0
  142. package/dist/playbooks/agent-delegation.md +2 -2
  143. package/dist/playbooks/catalog.d.ts +6 -2
  144. package/dist/playbooks/catalog.js +9 -6
  145. package/dist/runtime/bootstrap.d.ts +7 -17
  146. package/dist/runtime/bootstrap.js +70 -659
  147. package/dist/runtime/durable-dispatch.d.ts +43 -4
  148. package/dist/runtime/durable-dispatch.js +153 -3
  149. package/dist/runtime/inbound-images.d.ts +18 -0
  150. package/dist/runtime/inbound-images.js +51 -0
  151. package/dist/runtime/shutdown.d.ts +39 -0
  152. package/dist/runtime/shutdown.js +120 -0
  153. package/dist/runtime/stop-watchdog.d.ts +16 -0
  154. package/dist/runtime/stop-watchdog.js +32 -0
  155. package/dist/runtime/task-driver.d.ts +6 -4
  156. package/dist/runtime/task-driver.js +58 -23
  157. package/dist/runtime/task-migration.js +25 -8
  158. package/dist/runtime/task-spawn.d.ts +1 -1
  159. package/dist/runtime/task-spawn.js +13 -6
  160. package/dist/runtime/turn-handler.d.ts +47 -0
  161. package/dist/runtime/turn-handler.js +318 -0
  162. package/dist/runtime/turn-run.d.ts +52 -0
  163. package/dist/runtime/turn-run.js +318 -0
  164. package/dist/runtime/wake-coalescing.d.ts +18 -0
  165. package/dist/runtime/wake-coalescing.js +29 -0
  166. package/dist/security/block-message.d.ts +22 -1
  167. package/dist/security/block-message.js +66 -1
  168. package/dist/security/command-guard.js +4 -0
  169. package/dist/security/network.d.ts +2 -1
  170. package/dist/security/network.js +7 -2
  171. package/dist/security/path-guard-check.js +2 -2
  172. package/dist/security/path-guard.js +4 -0
  173. package/dist/security/types.d.ts +1 -2
  174. package/dist/security/types.js +1 -2
  175. package/dist/shared/exact-keys.d.ts +1 -1
  176. package/dist/shared/format.d.ts +12 -0
  177. package/dist/shared/format.js +37 -0
  178. package/dist/shared/host-process.js +16 -4
  179. package/dist/shared/wake-claim.d.ts +1 -1
  180. package/dist/shared/with-timeout.d.ts +3 -2
  181. package/dist/shared/with-timeout.js +14 -3
  182. package/dist/{runtime/skill-commands.d.ts → skills/commands.d.ts} +2 -2
  183. package/dist/{runtime/skill-commands.js → skills/commands.js} +18 -11
  184. package/dist/{agent/workspace-resources.js → skills/loader.js} +1 -1
  185. package/dist/{tools/skill-security.js → skills/validation.js} +4 -0
  186. package/dist/skills/workspace.d.ts +33 -0
  187. package/dist/skills/workspace.js +116 -0
  188. package/dist/{runtime/subagent-commands.d.ts → subagents/commands.d.ts} +9 -7
  189. package/dist/{runtime/subagent-commands.js → subagents/commands.js} +116 -77
  190. package/dist/subagents/completion-wake.d.ts +17 -0
  191. package/dist/subagents/completion-wake.js +76 -0
  192. package/dist/subagents/detached-discovery.js +1 -1
  193. package/dist/subagents/discovery.d.ts +1 -1
  194. package/dist/subagents/discovery.js +2 -2
  195. package/dist/subagents/dispatch.d.ts +33 -0
  196. package/dist/subagents/dispatch.js +190 -0
  197. package/dist/subagents/external/claude-code.js +23 -1
  198. package/dist/subagents/external/dispatch.d.ts +25 -0
  199. package/dist/subagents/external/dispatch.js +90 -0
  200. package/dist/subagents/external/harness.d.ts +1 -1
  201. package/dist/subagents/external/progress-tail.d.ts +18 -1
  202. package/dist/subagents/external/progress-tail.js +64 -17
  203. package/dist/subagents/external/run.d.ts +5 -1
  204. package/dist/subagents/external/run.js +23 -9
  205. package/dist/subagents/external/settlement.d.ts +4 -1
  206. package/dist/subagents/external/settlement.js +1 -1
  207. package/dist/subagents/format.d.ts +1 -1
  208. package/dist/subagents/grace.d.ts +24 -0
  209. package/dist/subagents/grace.js +57 -0
  210. package/dist/subagents/internal/outcome.d.ts +24 -0
  211. package/dist/subagents/internal/outcome.js +149 -0
  212. package/dist/subagents/internal/provider-retry.d.ts +19 -0
  213. package/dist/subagents/internal/provider-retry.js +83 -0
  214. package/dist/subagents/internal/run.d.ts +31 -0
  215. package/dist/subagents/internal/run.js +240 -0
  216. package/dist/subagents/internal/state.d.ts +43 -0
  217. package/dist/subagents/internal/state.js +48 -0
  218. package/dist/subagents/internal/worker.d.ts +51 -0
  219. package/dist/subagents/internal/worker.js +167 -0
  220. package/dist/subagents/result.d.ts +62 -0
  221. package/dist/subagents/result.js +103 -0
  222. package/dist/subagents/run-record.d.ts +222 -0
  223. package/dist/subagents/run-record.js +101 -0
  224. package/dist/subagents/run-registry.d.ts +9 -0
  225. package/dist/subagents/run-registry.js +125 -0
  226. package/dist/subagents/runs.d.ts +16 -232
  227. package/dist/subagents/runs.js +132 -310
  228. package/dist/subagents/task-envelope.d.ts +36 -0
  229. package/dist/subagents/task-envelope.js +168 -0
  230. package/dist/subagents/types.d.ts +154 -0
  231. package/dist/subagents/types.js +1 -0
  232. package/dist/subagents/verification-outcome.d.ts +1 -1
  233. package/dist/subagents/workspace-summary.d.ts +16 -4
  234. package/dist/subagents/workspace-summary.js +74 -18
  235. package/dist/tasks/board.d.ts +10 -3
  236. package/dist/tasks/board.js +38 -3
  237. package/dist/tasks/{work-log.d.ts → bound-work.d.ts} +1 -1
  238. package/dist/tasks/{work-log.js → bound-work.js} +1 -1
  239. package/dist/tasks/brief.js +1 -1
  240. package/dist/{runtime/task-commands.d.ts → tasks/commands.d.ts} +1 -1
  241. package/dist/{runtime/task-commands.js → tasks/commands.js} +117 -67
  242. package/dist/tasks/contract-input.d.ts +1 -1
  243. package/dist/tasks/contract-input.js +1 -1
  244. package/dist/tasks/create.js +1 -1
  245. package/dist/tasks/frontmatter.d.ts +5 -0
  246. package/dist/tasks/frontmatter.js +8 -0
  247. package/dist/tasks/{log.d.ts → loop-log.d.ts} +11 -1
  248. package/dist/tasks/{log.js → loop-log.js} +59 -3
  249. package/dist/tasks/mutation-lock.js +1 -1
  250. package/dist/tasks/session-path.js +1 -1
  251. package/dist/tasks/steer.js +1 -1
  252. package/dist/tasks/store.js +6 -4
  253. package/dist/tasks/ticket.d.ts +3 -1
  254. package/dist/tasks/ticket.js +19 -1
  255. package/dist/tools/bash.d.ts +1 -1
  256. package/dist/tools/bash.js +2 -2
  257. package/dist/tools/{tool-details.d.ts → contract/details.d.ts} +11 -3
  258. package/dist/tools/{tool-details.js → contract/details.js} +42 -5
  259. package/dist/tools/{presentation.js → contract/presentation.js} +3 -3
  260. package/dist/tools/event-manage.d.ts +1 -1
  261. package/dist/tools/event-manage.js +4 -4
  262. package/dist/tools/index.d.ts +5 -3
  263. package/dist/tools/index.js +8 -6
  264. package/dist/tools/job.d.ts +1 -1
  265. package/dist/tools/memory-manage.js +4 -1
  266. package/dist/tools/registry.d.ts +7 -7
  267. package/dist/tools/registry.js +6 -6
  268. package/dist/tools/session-search.d.ts +1 -1
  269. package/dist/tools/skill.d.ts +2 -34
  270. package/dist/tools/skill.js +8 -116
  271. package/dist/tools/subagent-manage.d.ts +1 -1
  272. package/dist/tools/subagent-manage.js +19 -13
  273. package/dist/tools/subagent.d.ts +46 -0
  274. package/dist/tools/subagent.js +127 -0
  275. package/dist/tools/{task-manage.d.ts → task-manage/factory.d.ts} +7 -3
  276. package/dist/tools/{task-manage.js → task-manage/factory.js} +7 -7
  277. package/dist/tools/task-manage/lifecycle.js +2 -2
  278. package/dist/tools/task-manage/log-view.js +2 -2
  279. package/dist/tools/task-manage/shared.js +3 -3
  280. package/dist/tools/task-manage/step-end.js +7 -4
  281. package/dist/tools/task-manage/types.d.ts +1 -1
  282. package/dist/tools/web-fetch.d.ts +1 -1
  283. package/dist/tools/web-search.d.ts +1 -1
  284. package/dist/tui/app.d.ts +1 -1
  285. package/dist/tui/app.js +6 -6
  286. package/dist/tui/cli.d.ts +1 -1
  287. package/dist/tui/cli.js +3 -3
  288. package/dist/tui/commands.js +4 -4
  289. package/dist/tui/frontend.d.ts +44 -0
  290. package/dist/tui/frontend.js +13 -0
  291. package/dist/tui/pitui-frontend.d.ts +1 -1
  292. package/dist/tui/pitui-frontend.js +1 -1
  293. package/dist/tui/plain-frontend.d.ts +1 -1
  294. package/dist/tui/renderer.d.ts +3 -42
  295. package/dist/tui/renderer.js +3 -2
  296. package/dist/tui/terminal-context.d.ts +2 -2
  297. package/dist/tui/terminal-media-sender.d.ts +1 -1
  298. package/dist/tui/turn-controller.d.ts +3 -1
  299. package/dist/tui/turn-controller.js +36 -21
  300. package/dist/usage/ledger.js +7 -1
  301. package/dist/usage/render.js +3 -1
  302. package/dist/{shared/types.d.ts → usage/totals.d.ts} +3 -0
  303. package/dist/web/client.d.ts +5 -1
  304. package/dist/web/client.js +4 -0
  305. package/dist/web/config.d.ts +1 -1
  306. package/dist/web/fetch.d.ts +1 -1
  307. package/dist/web/search-providers.d.ts +1 -1
  308. package/dist/web/search.d.ts +1 -1
  309. package/package.json +9 -7
  310. package/dist/agent/session-adapter.js +0 -77
  311. package/dist/events/events.d.ts +0 -159
  312. package/dist/runtime/dingtalk.d.ts +0 -272
  313. package/dist/runtime/dingtalk.js +0 -1416
  314. package/dist/subagents/tool.d.ts +0 -206
  315. package/dist/subagents/tool.js +0 -1088
  316. /package/dist/{runtime → agent/prompt}/workspace-templates.d.ts +0 -0
  317. /package/dist/{runtime → agent/prompt}/workspace-templates.js +0 -0
  318. /package/dist/agent/{session-resource-gate.d.ts → session/session-resource-gate.d.ts} +0 -0
  319. /package/dist/agent/{context-budget.d.ts → turn/context-budget.d.ts} +0 -0
  320. /package/dist/agent/{progress-formatter.js → turn/progress-formatter.js} +0 -0
  321. /package/dist/{memory → agent/turn}/task-digest.d.ts +0 -0
  322. /package/dist/agent/{turn-recovery.d.ts → turn/turn-recovery.d.ts} +0 -0
  323. /package/dist/agent/{turn-state.js → turn/turn-state.js} +0 -0
  324. /package/dist/{runtime → app}/proxy.d.ts +0 -0
  325. /package/dist/{runtime → dingtalk}/channel-queue.d.ts +0 -0
  326. /package/dist/{runtime → dingtalk}/inbound-media.d.ts +0 -0
  327. /package/dist/{runtime → dingtalk}/inbound-media.js +0 -0
  328. /package/dist/events/{event-commands.d.ts → commands.d.ts} +0 -0
  329. /package/dist/{agent/workspace-resources.d.ts → skills/loader.d.ts} +0 -0
  330. /package/dist/{tools/skill-security.d.ts → skills/validation.d.ts} +0 -0
  331. /package/dist/tasks/{ledger.d.ts → contract.d.ts} +0 -0
  332. /package/dist/tasks/{ledger.js → contract.js} +0 -0
  333. /package/dist/tools/{subagent-tool-names.d.ts → contract/names.d.ts} +0 -0
  334. /package/dist/tools/{subagent-tool-names.js → contract/names.js} +0 -0
  335. /package/dist/tools/{presentation.d.ts → contract/presentation.d.ts} +0 -0
  336. /package/dist/{shared/types.js → usage/totals.js} +0 -0
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Mutable facts about one internal run, shared by the worker watcher, provider-retry recovery and
3
+ * outcome assembly. One object instead of a dozen closure variables, so each of those can live in
4
+ * its own file while still observing the same live values.
5
+ */
6
+ import type { Api, Model } from "@earendil-works/pi-ai";
7
+ import { type UsageTotals } from "../../usage/totals.js";
8
+ import type { ResolvedInternalSubAgentConfig } from "../discovery.js";
9
+ import type { SubAgentRunContext, SubAgentToolFields } from "../types.js";
10
+ export interface InternalRunState {
11
+ readonly startedAt: number;
12
+ readonly usage: UsageTotals;
13
+ assistantTurns: number;
14
+ toolCalls: number;
15
+ failureReason: string | undefined;
16
+ /** Set alongside failureReason only for the three self-inflicted budget aborts, distinct from an explicit cancel. */
17
+ budgetExceeded: boolean;
18
+ /** Set only by the `subagent_run op=cancel` handle registered as soon as the run is durable. */
19
+ externallyCancelled: boolean;
20
+ /** True once the sync grace window has elapsed and a "still running" placeholder has been returned. */
21
+ detached: boolean;
22
+ lastUpdateText: string;
23
+ /** The model actually answering; differs from `config.model` once a backup-model switch happened. */
24
+ activeModel: Model<Api>;
25
+ /** Set when the run switched to the backup model, for the reply and the record. */
26
+ fallbackNote: string | undefined;
27
+ /** Read on every provider request, so a backup-model switch only has to replace the key. */
28
+ apiKey: string;
29
+ }
30
+ export declare function createInternalRunState(model: Model<Api>, apiKey: string): InternalRunState;
31
+ /** Progress sink: forwards a status line to the dispatching tool call until the run detaches. */
32
+ export declare function createUpdateEmitter(input: {
33
+ config: ResolvedInternalSubAgentConfig;
34
+ runContext: SubAgentRunContext;
35
+ state: InternalRunState;
36
+ onUpdate?: (update: {
37
+ content: Array<{
38
+ type: "text";
39
+ text: string;
40
+ }>;
41
+ details: SubAgentToolFields;
42
+ }) => void;
43
+ }): (text: string) => void;
@@ -0,0 +1,48 @@
1
+ import { formatModelReference } from "../../models/reference.js";
2
+ import { createEmptyUsageTotals } from "../../usage/totals.js";
3
+ import { createDetails } from "../result.js";
4
+ export function createInternalRunState(model, apiKey) {
5
+ return {
6
+ startedAt: Date.now(),
7
+ usage: createEmptyUsageTotals(),
8
+ assistantTurns: 0,
9
+ toolCalls: 0,
10
+ failureReason: undefined,
11
+ budgetExceeded: false,
12
+ externallyCancelled: false,
13
+ detached: false,
14
+ lastUpdateText: "",
15
+ activeModel: model,
16
+ fallbackNote: undefined,
17
+ apiKey,
18
+ };
19
+ }
20
+ /** Progress sink: forwards a status line to the dispatching tool call until the run detaches. */
21
+ export function createUpdateEmitter(input) {
22
+ const { config, runContext, state, onUpdate } = input;
23
+ return (text) => {
24
+ // Once detached, execute() has already returned to the SDK; nothing is listening
25
+ // for further progress on this (from its view, finished) tool call.
26
+ if (state.detached)
27
+ return;
28
+ const nextText = text.trim();
29
+ if (!nextText || nextText === state.lastUpdateText) {
30
+ return;
31
+ }
32
+ state.lastUpdateText = nextText;
33
+ onUpdate?.({
34
+ content: [{ type: "text", text: nextText }],
35
+ details: createDetails({
36
+ config,
37
+ runContext,
38
+ usage: state.usage,
39
+ turns: state.assistantTurns,
40
+ toolCalls: state.toolCalls,
41
+ durationMs: Date.now() - state.startedAt,
42
+ failed: Boolean(state.failureReason),
43
+ failureReason: state.failureReason,
44
+ modelOverride: state.fallbackNote ? formatModelReference(state.activeModel) : undefined,
45
+ }),
46
+ });
47
+ };
48
+ }
@@ -0,0 +1,51 @@
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 { type AgentMessage, type AgentTool } from "@earendil-works/pi-agent-core";
6
+ import type { AssistantMessage } from "@earendil-works/pi-ai";
7
+ import type { ExecOptions, ExecResult, Executor } from "../../executor.js";
8
+ import { type ResolvedInternalSubAgentConfig } from "../discovery.js";
9
+ import type { SubAgentRunManager } from "../runs.js";
10
+ import type { SubAgentRunContext, SubAgentToolOptions, SubAgentWorker } from "../types.js";
11
+ import type { InternalRunState } from "./state.js";
12
+ /**
13
+ * Pins every command a run issues to the run's working directory. It sets the child's real `cwd`
14
+ * rather than prefixing `cd <dir> &&`: the prefix silently produced a *different* command than the
15
+ * guard inspected, and a directory that cannot be entered surfaced as a shell error inside an
16
+ * otherwise successful command line.
17
+ */
18
+ export declare class DirectoryExecutor implements Executor {
19
+ private readonly base;
20
+ private readonly directory;
21
+ constructor(base: Executor, directory: string);
22
+ exec(command: string, options?: ExecOptions): Promise<ExecResult>;
23
+ }
24
+ export declare function isAssistantMessage(message: AgentMessage): message is AssistantMessage;
25
+ export declare function getLastAssistantMessage(messages: AgentMessage[]): AssistantMessage | null;
26
+ /**
27
+ * Build a sub-agent's tool set through the injected `buildWorkerTools` (the registry's sub-agent
28
+ * whitelist: files + web), with its own security context and per-invocation bash timeout.
29
+ */
30
+ export declare function buildSubagentTools(executor: Executor, bashTimeoutSec: number, options: SubAgentToolOptions, runContext: SubAgentRunContext): AgentTool<any>[];
31
+ /** What `startWorker` fills in as it goes, so a failure part-way still leaves the cleanup its handles. */
32
+ export interface WorkerHandle {
33
+ worker?: SubAgentWorker;
34
+ unsubscribe?: () => void;
35
+ wallClockTimer?: ReturnType<typeof setTimeout>;
36
+ }
37
+ /**
38
+ * Build the scoped tool set, create the worker, arm the wall-clock budget and subscribe to its
39
+ * events. Everything is recorded on `handle` immediately, before the next step can throw.
40
+ */
41
+ export declare function startWorker(input: {
42
+ handle: WorkerHandle;
43
+ options: SubAgentToolOptions;
44
+ config: ResolvedInternalSubAgentConfig;
45
+ runContext: SubAgentRunContext;
46
+ scopedExecutor: Executor;
47
+ state: InternalRunState;
48
+ retryBackoff: AbortController;
49
+ runManager: SubAgentRunManager;
50
+ emitUpdate: (text: string) => void;
51
+ }): void;
@@ -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
+ }