@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,149 @@
1
+ /**
2
+ * Turning a finished internal worker into what the run hands back: the tool result for the model
3
+ * and the `SettleInput` for the run manager — covering success, a failure with output, a failure
4
+ * without any (which rejects), and the best-effort settle input for that rejecting path.
5
+ */
6
+ import { formatModelReference } from "../../models/reference.js";
7
+ import { RecoverableToolError } from "../../shared/recoverable-error.js";
8
+ import { extractAssistantText } from "../../shared/text-utils.js";
9
+ import { buildFailureText, buildStoppedText, createDetails, finalizeSubAgentOutput, formatStatus } from "../result.js";
10
+ import { resolveVerificationVerdict } from "../verification-outcome.js";
11
+ import { changedPathsSummary } from "../workspace-summary.js";
12
+ import { getLastAssistantMessage } from "./worker.js";
13
+ /**
14
+ * Assemble the result of a finished worker. Rejects only for the single fatal case (no assistant
15
+ * message at all) — every other outcome, including a budget abort or explicit cancel, is a normal
16
+ * (if failed) result.
17
+ */
18
+ export async function buildInternalOutcome(input) {
19
+ const { worker, config, runContext, state, mutatesNote, emitUpdate } = input;
20
+ const { usage } = state;
21
+ const lastAssistantMessage = getLastAssistantMessage(worker.state.messages);
22
+ const durationMs = Date.now() - state.startedAt;
23
+ const modelRef = state.fallbackNote ? formatModelReference(state.activeModel) : undefined;
24
+ const fallbackLine = state.fallbackNote ? `Note: this run ${state.fallbackNote}.\n\n` : "";
25
+ if (!lastAssistantMessage) {
26
+ state.failureReason = state.failureReason || "Sub-agent returned no assistant message";
27
+ emitUpdate(formatStatus(config.name, "failed"));
28
+ throw new Error(`Sub-agent ${config.name} failed: ${state.failureReason}`);
29
+ }
30
+ const finalText = extractAssistantText(lastAssistantMessage);
31
+ const effectiveFailureReason = state.failureReason ||
32
+ (lastAssistantMessage.stopReason === "error" || lastAssistantMessage.stopReason === "aborted"
33
+ ? lastAssistantMessage.errorMessage || `Sub-agent stopped with ${lastAssistantMessage.stopReason}`
34
+ : undefined);
35
+ // The pass/fail rule is shared with the external verify path (spec 042 D1): one place
36
+ // deciding what a verify run's own output proves. Spec 052, D6: it is the checker's declared
37
+ // verdict, recorded for the leader to weigh — not a runtime-enforced gate.
38
+ const verificationVerdict = runContext.purpose === "verify"
39
+ ? resolveVerificationVerdict({ finalText, runFailed: Boolean(effectiveFailureReason) })
40
+ : undefined;
41
+ // Internal runs always report full usage; cost is "unknown" only for the shape a
42
+ // free/local model produces (tokens spent, nothing billed) — external harnesses
43
+ // override both explicitly once they land (D4/D9).
44
+ const costKnown = usage.cost.total > 0 || usage.total === 0;
45
+ const baseSettleInput = {
46
+ usage,
47
+ usageKnown: true,
48
+ costKnown,
49
+ turns: state.assistantTurns,
50
+ toolCalls: state.toolCalls,
51
+ durationMs,
52
+ verificationVerdict,
53
+ model: modelRef,
54
+ };
55
+ if (effectiveFailureReason) {
56
+ if (!finalText.trim()) {
57
+ emitUpdate(formatStatus(config.name, "failed"));
58
+ // Settlement records the reason itself, not the next-step advice wrapped around it below.
59
+ state.failureReason = effectiveFailureReason;
60
+ // The delegating model can act on this alone — re-dispatch, narrow the task, or do the
61
+ // work itself — so it is not a user-facing error bubble.
62
+ throw new RecoverableToolError(`${fallbackLine}${buildFailureText(config, effectiveFailureReason, finalText)}\n` +
63
+ `Retry the delegation (narrower if it hit a budget), or do the work directly; subagent_run op=show runId=${runContext.runId} has the details.`);
64
+ }
65
+ emitUpdate(formatStatus(config.name, "stopped"));
66
+ const finalized = finalizeSubAgentOutput(runContext, finalText);
67
+ return {
68
+ toolResult: {
69
+ content: [
70
+ {
71
+ type: "text",
72
+ text: mutatesNote + fallbackLine + buildStoppedText(config, effectiveFailureReason, finalized.replyText),
73
+ },
74
+ ],
75
+ details: createDetails({
76
+ config,
77
+ runContext,
78
+ usage,
79
+ turns: state.assistantTurns,
80
+ toolCalls: state.toolCalls,
81
+ durationMs,
82
+ failed: true,
83
+ failureReason: effectiveFailureReason,
84
+ verificationVerdict,
85
+ resultTruncated: finalized.truncated,
86
+ modelOverride: modelRef,
87
+ }),
88
+ },
89
+ settleInput: {
90
+ ...baseSettleInput,
91
+ // An explicit cancel is not a failure (P1-1) — the model asked this run to
92
+ // stop, and it did.
93
+ status: state.externallyCancelled ? "cancelled" : "failed",
94
+ failureReason: effectiveFailureReason,
95
+ outputText: finalText,
96
+ },
97
+ };
98
+ }
99
+ // P2-2, same as an external write run: what this run changed, so the reader does not spend
100
+ // its first tool call finding out. Only a cleanly completed write run pays for it.
101
+ const workspaceSummary = config.mutates === "write"
102
+ ? await changedPathsSummary(runContext.workingDirectory, input.workspaceBaseline).catch(() => undefined)
103
+ : undefined;
104
+ const workspaceLine = workspaceSummary
105
+ ? `\n\nWorkspace after the run (git status --porcelain): ${workspaceSummary}`
106
+ : "";
107
+ const finalized = finalizeSubAgentOutput(runContext, finalText);
108
+ return {
109
+ toolResult: {
110
+ content: [
111
+ {
112
+ type: "text",
113
+ text: mutatesNote +
114
+ fallbackLine +
115
+ (finalized.replyText || `(Sub-agent ${config.name} completed with no text output)`) +
116
+ workspaceLine,
117
+ },
118
+ ],
119
+ details: createDetails({
120
+ config,
121
+ runContext,
122
+ usage,
123
+ turns: state.assistantTurns,
124
+ toolCalls: state.toolCalls,
125
+ durationMs,
126
+ verificationVerdict,
127
+ resultTruncated: finalized.truncated,
128
+ modelOverride: modelRef,
129
+ }),
130
+ },
131
+ settleInput: { ...baseSettleInput, status: "completed", outputText: finalText, workspaceSummary },
132
+ };
133
+ }
134
+ /** Best-effort settle input for the one fatal path that rejects instead of resolving. */
135
+ export function fatalSettleInput(state, error) {
136
+ const { usage } = state;
137
+ return {
138
+ status: state.externallyCancelled ? "cancelled" : "failed",
139
+ failureReason: state.failureReason || error.message,
140
+ usage,
141
+ usageKnown: true,
142
+ costKnown: usage.cost.total > 0 || usage.total === 0,
143
+ turns: state.assistantTurns,
144
+ toolCalls: state.toolCalls,
145
+ durationMs: Date.now() - state.startedAt,
146
+ outputText: "",
147
+ model: state.fallbackNote ? formatModelReference(state.activeModel) : undefined,
148
+ };
149
+ }
@@ -0,0 +1,19 @@
1
+ import { type ResolvedInternalSubAgentConfig } from "../discovery.js";
2
+ import type { SubAgentToolOptions, SubAgentWorker } from "../types.js";
3
+ import type { InternalRunState } from "./state.js";
4
+ /**
5
+ * A transcript ending in a provider error is retried in place (the error message removed, the
6
+ * loop continued from the last user/tool message): transient errors up to
7
+ * MAX_TRANSIENT_RETRIES times with backoff, then — for anything but a context overflow — one
8
+ * switch to the backup model, the same rule the main turn follows (`shouldFallback`). Budget
9
+ * aborts and explicit cancels are never retried.
10
+ */
11
+ export declare function recoverFromProviderErrors(input: {
12
+ worker: SubAgentWorker;
13
+ options: SubAgentToolOptions;
14
+ config: ResolvedInternalSubAgentConfig;
15
+ state: InternalRunState;
16
+ /** Wakes a retry backoff early when the run is cancelled or out of wall time. */
17
+ retryBackoff: AbortController;
18
+ emitUpdate: (text: string) => void;
19
+ }): Promise<void>;
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Provider-error recovery for an internal run: a transcript ending in a provider error is retried in
3
+ * place (transient errors, with backoff) and then, once, on the backup model — the same rule the
4
+ * main turn follows.
5
+ */
6
+ import { clampThinkingLevel, isRetryableAssistantError } from "@earendil-works/pi-ai/compat";
7
+ import { shouldFallback } from "../../models/fallback.js";
8
+ import { formatModelReference } from "../../models/reference.js";
9
+ import { sleepUnref } from "../../shared/with-timeout.js";
10
+ import { DEFAULT_THINKING_LEVEL } from "../discovery.js";
11
+ import { formatStatus } from "../result.js";
12
+ import { isAssistantMessage } from "./worker.js";
13
+ /**
14
+ * A provider error (429, overloaded, 5xx, dropped stream) used to fail an internal run outright —
15
+ * the main session retries those, a bare `Agent` does not. Retried in place with exponential
16
+ * backoff (2s, 4s, 8s) before falling back to the backup model; the wall-time budget still bounds
17
+ * the whole thing.
18
+ */
19
+ const MAX_TRANSIENT_RETRIES = 3;
20
+ const RETRY_BASE_DELAY_MS = 2_000;
21
+ /**
22
+ * A transcript ending in a provider error is retried in place (the error message removed, the
23
+ * loop continued from the last user/tool message): transient errors up to
24
+ * MAX_TRANSIENT_RETRIES times with backoff, then — for anything but a context overflow — one
25
+ * switch to the backup model, the same rule the main turn follows (`shouldFallback`). Budget
26
+ * aborts and explicit cancels are never retried.
27
+ */
28
+ export async function recoverFromProviderErrors(input) {
29
+ const { worker, options, config, state, retryBackoff, emitUpdate } = input;
30
+ const resume = worker.continue?.bind(worker);
31
+ if (!resume)
32
+ return;
33
+ let retries = 0;
34
+ let switched = false;
35
+ for (;;) {
36
+ if (state.budgetExceeded || state.externallyCancelled)
37
+ return;
38
+ const last = worker.state.messages.at(-1);
39
+ if (!last || !isAssistantMessage(last) || last.stopReason !== "error")
40
+ return;
41
+ // `shouldFallback` is false only for a context overflow, which no retry or model switch fixes.
42
+ if (!shouldFallback(last.errorMessage))
43
+ return;
44
+ if (retries < MAX_TRANSIENT_RETRIES && isRetryableAssistantError(last)) {
45
+ retries++;
46
+ emitUpdate(formatStatus(config.name, `provider error, retrying (${retries}/${MAX_TRANSIENT_RETRIES})`));
47
+ const delayMs = (options.retryBaseDelayMs ?? RETRY_BASE_DELAY_MS) * 2 ** (retries - 1);
48
+ await sleepUnref(delayMs, retryBackoff.signal);
49
+ if (state.budgetExceeded || state.externallyCancelled)
50
+ return;
51
+ }
52
+ else {
53
+ if (switched || !options.resolveFallbackModel)
54
+ return;
55
+ const candidate = await options.resolveFallbackModel().catch(() => null);
56
+ if (state.budgetExceeded || state.externallyCancelled)
57
+ return;
58
+ if (!candidate || formatModelReference(candidate) === formatModelReference(state.activeModel))
59
+ return;
60
+ let candidateKey;
61
+ try {
62
+ candidateKey = await options.resolveApiKey(candidate);
63
+ }
64
+ catch {
65
+ return;
66
+ }
67
+ if (state.budgetExceeded || state.externallyCancelled)
68
+ return;
69
+ switched = true;
70
+ retries = 0;
71
+ const fromRef = formatModelReference(state.activeModel);
72
+ state.activeModel = candidate;
73
+ state.apiKey = candidateKey;
74
+ worker.state.model = candidate;
75
+ worker.state.thinkingLevel = clampThinkingLevel(candidate, config.thinkingLevel ?? DEFAULT_THINKING_LEVEL);
76
+ state.fallbackNote = `switched from ${fromRef} to backup model ${formatModelReference(candidate)} after: ${last.errorMessage?.split("\n")[0]?.slice(0, 200) ?? "unknown error"}`;
77
+ emitUpdate(formatStatus(config.name, `switching to backup model ${formatModelReference(candidate)}`));
78
+ }
79
+ worker.state.messages = worker.state.messages.slice(0, -1);
80
+ await resume();
81
+ await worker.waitForIdle();
82
+ }
83
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The `runtime: internal` half of delegation dispatch (spec 046 D2.5): register the durable run
3
+ * record, start the worker, drive it to completion (with the D6 convergence turn), settle it, and
4
+ * return either its real result or — once the sync grace window elapses — a "[Dispatched]"
5
+ * placeholder while the run keeps going in the background.
6
+ *
7
+ * Orchestration only: the worker, provider retry and outcome assembly live in their own files. The
8
+ * lease release on every pre-registration failure, the cancel handle installed before any setup I/O,
9
+ * and the grace/detach split all stay here, in this order.
10
+ */
11
+ import type { Api, Model } from "@earendil-works/pi-ai";
12
+ import type { ResolvedInternalSubAgentConfig } from "../discovery.js";
13
+ import type { SubAgentRunManager } from "../runs.js";
14
+ import type { DelegationParams, DelegationResult, SubAgentRunContext, SubAgentToolOptions } from "../types.js";
15
+ import type { WorkspaceBaseline } from "../workspace-summary.js";
16
+ interface InternalRunInput {
17
+ options: SubAgentToolOptions;
18
+ currentModel: Model<Api>;
19
+ config: ResolvedInternalSubAgentConfig;
20
+ runLabel: string;
21
+ mutatesNote: string;
22
+ runContext: SubAgentRunContext;
23
+ leaseKey: string | undefined;
24
+ params: DelegationParams;
25
+ signal: AbortSignal | undefined;
26
+ onUpdate?: (update: DelegationResult) => void;
27
+ runManager: SubAgentRunManager;
28
+ workspaceBaseline: WorkspaceBaseline | undefined;
29
+ }
30
+ export declare function dispatchInternalRun(input: InternalRunInput): Promise<DelegationResult>;
31
+ export {};
@@ -0,0 +1,240 @@
1
+ import * as log from "../../log.js";
2
+ import { formatModelReference } from "../../models/reference.js";
3
+ import { errorMessage } from "../../shared/text-utils.js";
4
+ import { sleepUnref } from "../../shared/with-timeout.js";
5
+ import { graceDeadlineFor, resolveSyncGraceMs, watchAbort } from "../grace.js";
6
+ import { buildDispatchedText, createDetails, formatStatus } from "../result.js";
7
+ import { buildSubAgentTask, resolveContextualBlocks } from "../task-envelope.js";
8
+ import { releaseWorkspaceLease } from "../workspace-lease.js";
9
+ import { buildInternalOutcome, fatalSettleInput } from "./outcome.js";
10
+ import { recoverFromProviderErrors } from "./provider-retry.js";
11
+ import { createInternalRunState, createUpdateEmitter } from "./state.js";
12
+ import { DirectoryExecutor, startWorker } from "./worker.js";
13
+ /**
14
+ * Spec 032 D6: when a turn/tool/wall-time budget is hit, the sub-agent gets one more,
15
+ * tool-free turn to summarize what it already found instead of having its work discarded.
16
+ * This is a hard stop on that convergence turn itself, independent of maxWallTimeSec.
17
+ */
18
+ const CONVERGENCE_WALL_CLOCK_MS = 60_000;
19
+ const CONVERGENCE_PROMPT = "Your turn/tool-call/wall-time budget for this task is exhausted. Based only on the work you have already completed, respond now with your conclusions: confirmed facts, what remains unfinished, and suggested next steps. Do not call any more tools.";
20
+ export async function dispatchInternalRun(input) {
21
+ const { options, config, runLabel, mutatesNote, runContext, leaseKey, params, signal, onUpdate, runManager } = input;
22
+ const scopedExecutor = new DirectoryExecutor(options.executor, runContext.workingDirectory);
23
+ let apiKey;
24
+ try {
25
+ apiKey = await options.resolveApiKey(config.model);
26
+ }
27
+ catch (error) {
28
+ releaseWorkspaceLease(leaseKey, runContext.runId);
29
+ throw error;
30
+ }
31
+ const state = createInternalRunState(config.model, apiKey);
32
+ /** Wakes a retry backoff early when the run is cancelled or out of wall time. */
33
+ const retryBackoff = new AbortController();
34
+ const handle = {};
35
+ try {
36
+ await runManager.register({
37
+ runId: runContext.runId,
38
+ channelId: options.runtimeContext.channelId,
39
+ runtime: "internal",
40
+ agent: config.name,
41
+ label: runLabel,
42
+ source: config.source,
43
+ tools: [...config.tools],
44
+ model: formatModelReference(config.model),
45
+ purpose: runContext.purpose,
46
+ taskId: runContext.taskId,
47
+ item: runContext.item,
48
+ workingDirectory: runContext.workingDirectory,
49
+ artifactDir: runContext.artifactDir,
50
+ channelDir: options.channelDir,
51
+ leaseKey,
52
+ mutates: config.mutates,
53
+ workspaceBaseline: input.workspaceBaseline,
54
+ });
55
+ }
56
+ catch (error) {
57
+ // Until the durable running record exists, setup still owns the lease. A channel/host
58
+ // admission rejection or required persist failure must leave no invisible writer lock.
59
+ releaseWorkspaceLease(leaseKey, runContext.runId);
60
+ throw error;
61
+ }
62
+ // Install the cancel handle before any setup I/O (tool construction, Git snapshots, worker
63
+ // creation) can yield. Without this provisional handle, a cancel in that window was treated as
64
+ // an unreachable run: the manager released the lease and settled it while the worker could still
65
+ // start writing after the supposed cancellation (especially dangerous for a write verifier).
66
+ runManager.registerCancelHandle(runContext.runId, () => {
67
+ state.externallyCancelled = true;
68
+ retryBackoff.abort();
69
+ handle.worker?.abort();
70
+ });
71
+ const emitUpdate = createUpdateEmitter({ config, runContext, state, onUpdate });
72
+ try {
73
+ startWorker({ handle, options, config, runContext, scopedExecutor, state, retryBackoff, runManager, emitUpdate });
74
+ }
75
+ catch (error) {
76
+ await failSetup(error, handle, state, runManager, runContext);
77
+ }
78
+ const worker = handle.worker;
79
+ const unsubscribe = handle.unsubscribe;
80
+ const wallClockTimer = handle.wallClockTimer;
81
+ // D2: the tool call waits at most until this turn's shared grace deadline (never longer than
82
+ // the run's own wall clock budget) before degrading to a "still running" placeholder. It also
83
+ // stops waiting the moment the turn is aborted (`/stop`): the SDK awaits this call, so ignoring
84
+ // the signal held `/stop` until its force-end fallback — and a result that then arrived inside
85
+ // the grace window settled `announce: false` into a turn that no longer existed, so nobody
86
+ // ever saw it. The run itself keeps executing either way — only the *return* differs.
87
+ const now = Date.now();
88
+ const deadline = Math.min(graceDeadlineFor(signal, resolveSyncGraceMs(options.syncGraceMs), now), now + config.maxWallTimeSec * 1000);
89
+ const outcomePromise = runToCompletion({
90
+ options,
91
+ config,
92
+ runContext,
93
+ params,
94
+ state,
95
+ retryBackoff,
96
+ emitUpdate,
97
+ worker,
98
+ unsubscribe,
99
+ wallClockTimer,
100
+ mutatesNote,
101
+ workspaceBaseline: input.workspaceBaseline,
102
+ }).then((value) => ({ ok: true, value }), (error) => ({
103
+ ok: false,
104
+ error: error instanceof Error ? error : new Error(String(error)),
105
+ }));
106
+ const abortWatch = watchAbort(signal);
107
+ const raceResult = await Promise.race([
108
+ outcomePromise,
109
+ sleepUnref(Math.max(0, deadline - now)).then(() => "timed-out"),
110
+ abortWatch.aborted,
111
+ ]);
112
+ abortWatch.dispose();
113
+ if (raceResult !== "timed-out" && raceResult !== "aborted") {
114
+ runManager.clearCancelHandle(runContext.runId);
115
+ if (!raceResult.ok) {
116
+ await runManager.settle(runContext.runId, fatalSettleInput(state, raceResult.error), { announce: false });
117
+ throw raceResult.error;
118
+ }
119
+ await runManager.settle(runContext.runId, raceResult.value.settleInput, { announce: false });
120
+ return raceResult.value.toolResult;
121
+ }
122
+ // Grace window elapsed (or the turn was stopped): hand back a placeholder now and let the run
123
+ // keep going in the background. It settles and, this time, announces itself with a completion
124
+ // wake (D2/D7) — the same "runtime guarantees completion" contract background jobs already keep.
125
+ state.detached = true;
126
+ void outcomePromise.then(async (outcome) => {
127
+ runManager.clearCancelHandle(runContext.runId);
128
+ const settleInput = outcome.ok ? outcome.value.settleInput : fatalSettleInput(state, outcome.error);
129
+ await runManager.settle(runContext.runId, settleInput, { announce: true }).catch((error) => {
130
+ log.logWarn("subagent.settle.failed", "Detached run settlement failed", {
131
+ reason: errorMessage(error),
132
+ fields: { runId: runContext.runId },
133
+ });
134
+ });
135
+ });
136
+ return {
137
+ content: [
138
+ {
139
+ type: "text",
140
+ text: mutatesNote +
141
+ buildDispatchedText(runContext.runId, config.name, "internal, async", runContext.workingDirectory),
142
+ },
143
+ ],
144
+ details: createDetails({
145
+ config,
146
+ runContext,
147
+ usage: state.usage,
148
+ turns: state.assistantTurns,
149
+ toolCalls: state.toolCalls,
150
+ durationMs: Date.now() - state.startedAt,
151
+ dispatched: true,
152
+ }),
153
+ };
154
+ }
155
+ /**
156
+ * Runs the worker to completion, including the D6 convergence turn, and returns the
157
+ * tool result plus the data `runs.ts` needs to settle.
158
+ */
159
+ async function runToCompletion(ctx) {
160
+ const { options, config, runContext, params, state, retryBackoff, emitUpdate, worker } = ctx;
161
+ try {
162
+ const contextualBlocks = await resolveContextualBlocks(config, options);
163
+ if (state.externallyCancelled) {
164
+ state.failureReason = state.failureReason || "Cancelled by request.";
165
+ }
166
+ else {
167
+ await worker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext));
168
+ await worker.waitForIdle();
169
+ await recoverFromProviderErrors({ worker, options, config, state, retryBackoff, emitUpdate });
170
+ }
171
+ // D6: a self-inflicted budget abort gets one tool-free turn to converge on a
172
+ // conclusion instead of discarding the work outright. An explicit cancel skips
173
+ // this — the model asked this run to stop now, not to wrap up.
174
+ if (state.budgetExceeded && !state.externallyCancelled) {
175
+ clearTimeout(ctx.wallClockTimer);
176
+ emitUpdate(formatStatus(config.name, "converging on budget exhaustion"));
177
+ const preConvergenceMessageCount = worker.state.messages.length;
178
+ worker.state.tools = [];
179
+ let convergenceTimedOut = false;
180
+ const convergenceTimer = setTimeout(() => {
181
+ convergenceTimedOut = true;
182
+ worker.abort();
183
+ }, options.convergenceWallClockMs ?? CONVERGENCE_WALL_CLOCK_MS);
184
+ try {
185
+ await worker.prompt(CONVERGENCE_PROMPT);
186
+ await worker.waitForIdle();
187
+ }
188
+ catch {
189
+ // Best effort: fall through to whatever worker.state.messages holds.
190
+ }
191
+ finally {
192
+ clearTimeout(convergenceTimer);
193
+ }
194
+ if (convergenceTimedOut) {
195
+ // Revert to the pre-D6 behavior: drop the (aborted, possibly partial)
196
+ // convergence turn and fall back to whatever came before it.
197
+ worker.state.messages = worker.state.messages.slice(0, preConvergenceMessageCount);
198
+ }
199
+ }
200
+ }
201
+ finally {
202
+ ctx.unsubscribe();
203
+ clearTimeout(ctx.wallClockTimer);
204
+ }
205
+ return buildInternalOutcome({
206
+ worker,
207
+ config,
208
+ runContext,
209
+ state,
210
+ mutatesNote: ctx.mutatesNote,
211
+ workspaceBaseline: ctx.workspaceBaseline,
212
+ emitUpdate,
213
+ });
214
+ }
215
+ /** Setup threw after the run was registered: undo what was armed, settle it failed, rethrow. */
216
+ async function failSetup(error, handle, state, runManager, runContext) {
217
+ handle.unsubscribe?.();
218
+ if (handle.wallClockTimer)
219
+ clearTimeout(handle.wallClockTimer);
220
+ runManager.clearCancelHandle(runContext.runId);
221
+ try {
222
+ handle.worker?.abort();
223
+ }
224
+ catch {
225
+ // Preserve the setup error; settlement below is the lifecycle authority.
226
+ }
227
+ const setupError = error instanceof Error ? error : new Error(String(error));
228
+ await runManager.settle(runContext.runId, {
229
+ status: "failed",
230
+ failureReason: setupError.message,
231
+ usage: state.usage,
232
+ usageKnown: true,
233
+ costKnown: true,
234
+ turns: state.assistantTurns,
235
+ toolCalls: state.toolCalls,
236
+ durationMs: Date.now() - state.startedAt,
237
+ outputText: "",
238
+ }, { announce: false });
239
+ throw setupError;
240
+ }
@@ -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;