@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
@@ -1,65 +1,39 @@
1
- import { mkdir, writeFile } from "fs/promises";
2
- import { join, relative } from "path";
3
- import { createJobRuntime } from "../agent/job-manager.js";
1
+ /**
2
+ * The daemon's composition root: loads config and builds the bot, durable dispatch, jobs, delegation
3
+ * runs, the events, memory and task services, then wires the per-channel handler (`turn-handler.ts`)
4
+ * and the ordered shutdown (`shutdown.ts`).
5
+ */
6
+ import { join } from "path";
4
7
  import { loadDetachedMaintenanceContext } from "../agent/maintenance-context.js";
5
8
  import { createRunner } from "../agent/runner-factory.js";
6
- import { scanWorkspaceForInterruptedTurns } from "../agent/turn-recovery.js";
7
- import { prepareAppServices } from "../app-services.js";
8
- import { createFreshActiveSession } from "../channel/active-session-store.js";
9
- import { muteChannelContext } from "../channel/channel-context.js";
9
+ import { scanWorkspaceForInterruptedTurns } from "../agent/turn/turn-recovery.js";
10
+ import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, parseArgs, printBootstrapSummary, printFirstRunGuide, readCliVersion, } from "../app/home.js";
11
+ import { prepareAppServices } from "../app/services.js";
10
12
  import { createChannelIndex } from "../channel/channel-index.js";
11
13
  import { ensureChannelDir, getChannelDir } from "../channel/channel-paths.js";
12
- import { resolveProjectScope } from "../channel/project-scope-store.js";
13
14
  import { ChannelStore } from "../channel/store.js";
14
- import { BUILT_IN_COMMANDS, formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../commands/catalog.js";
15
- import { createEventsWatcher } from "../events/events.js";
15
+ import { PipiclawSettingsManager } from "../config/settings.js";
16
+ import { getToolsConfigPath, loadToolsConfig } from "../config/tools.js";
17
+ import { DingTalkBot } from "../dingtalk/bot.js";
18
+ import { loadConfig } from "../dingtalk/config.js";
19
+ import { createEventsWatcher } from "../events/watcher.js";
16
20
  import { createExecutor } from "../executor.js";
21
+ import { createJobRuntime } from "../jobs/manager.js";
17
22
  import * as log from "../log.js";
18
23
  import { MemoryMaintenanceScheduler } from "../memory/scheduler.js";
19
- import { defaultModel } from "../models/utils.js";
24
+ import { defaultModel } from "../models/runtime.js";
20
25
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
21
- import { flushSecurityLogs } from "../security/logger.js";
22
- import { resolveProjectAccessPolicy } from "../security/project-scope.js";
23
- import { PipiclawSettingsManager } from "../settings.js";
24
26
  import { fileStamp } from "../shared/format.js";
25
- import { localStampForFilename } from "../shared/local-time.js";
26
27
  import { errorMessage } from "../shared/text-utils.js";
27
- import { sleepUnref } from "../shared/with-timeout.js";
28
- import { createSubAgentRuntime } from "../subagents/runs.js";
29
- import { buildTaskStepBrief } from "../tasks/brief.js";
30
- import { readActiveTasks } from "../tasks/ledger.js";
31
- import { consumeTaskNotice } from "../tasks/steer.js";
32
- import { pauseTask as pauseStoredTask } from "../tasks/store.js";
33
- import { getToolsConfigPath, loadToolsConfig } from "../tools/config.js";
28
+ import { renderRunNotice } from "../subagents/commands.js";
29
+ import { createSubAgentRuntime } from "../subagents/run-registry.js";
34
30
  import { getUsageLedger } from "../usage/ledger.js";
35
- import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, loadConfig, parseArgs, printBootstrapSummary, readCliVersion, } from "./app-home.js";
36
- import { createDingTalkContext } from "./delivery.js";
37
- import { DingTalkBot, } from "./dingtalk.js";
38
- import { DurableDispatchService } from "./durable-dispatch.js";
39
- import { extensionForMimeType } from "./inbound-media.js";
40
- import { runReportCommand } from "./report-commands.js";
41
- import { renderRunNotice } from "./subagent-commands.js";
42
- import { createTaskDriverEvent, parseDriverTaskId, TaskDriver } from "./task-driver.js";
31
+ import { DurableDispatchService, renderDispatchExhaustedNotice } from "./durable-dispatch.js";
32
+ import { createShutdown } from "./shutdown.js";
33
+ import { TaskDriver } from "./task-driver.js";
43
34
  import { migrateTasksToV5 } from "./task-migration.js";
44
35
  import { createTaskSpawner } from "./task-spawn.js";
45
- import { claimVerifiedWake } from "./task-wake.js";
46
- const SHUTDOWN_WAIT_MS = 15000;
47
- const SHUTDOWN_FLUSH_WAIT_MS = 45000;
48
- const SHUTDOWN_ABORT_WAIT_MS = 5000;
49
- const SHUTDOWN_LOG_FLUSH_WAIT_MS = 10_000;
50
- function waitForTasks(tasks, timeoutMs) {
51
- if (tasks.length === 0) {
52
- return Promise.resolve(true);
53
- }
54
- return new Promise((resolve) => {
55
- const timer = setTimeout(() => resolve(false), timeoutMs);
56
- timer.unref?.();
57
- void Promise.allSettled(tasks).then(() => {
58
- clearTimeout(timer);
59
- resolve(true);
60
- });
61
- });
62
- }
36
+ import { createTurnHandler } from "./turn-handler.js";
63
37
  /**
64
38
  * Ceiling on cached runners per daemon process. A long-lived daemon otherwise accumulates one
65
39
  * `ChannelRunner` (session, subscriptions, memory state) per distinct channel it has ever heard
@@ -83,531 +57,13 @@ async function evictIdleRunnersOverCap(channelRunners) {
83
57
  continue;
84
58
  channelRunners.delete(channelId);
85
59
  await runner.dispose().catch((err) => {
86
- log.logWarning(`[${channelId}] Failed to dispose evicted runner`, errorMessage(err));
60
+ log.logWarn("runtime.runner.evict_dispose_failed", "Evicted runner dispose failed", {
61
+ channelId: channelId,
62
+ reason: errorMessage(err),
63
+ });
87
64
  });
88
65
  }
89
66
  }
90
- function isNoRunningTaskQueueError(err) {
91
- return err instanceof Error && err.message === "No task is currently running.";
92
- }
93
- /**
94
- * Absolute `InboundImage.path`s → paths relative to the channel directory, for
95
- * `LoggedMessage.images` (spec 049). `log.jsonl` already stores everything else channel-relative
96
- * (it lives inside the channel directory itself); an absolute path there would be dead on any
97
- * machine other than the one that wrote it, and `~/.pipiclaw` itself can move between backup and
98
- * restore.
99
- */
100
- function relativeImagePaths(workspaceDir, channelId, images) {
101
- if (!images || images.length === 0)
102
- return [];
103
- const channelDir = getChannelDir(workspaceDir, channelId);
104
- return images.map((image) => relative(channelDir, image.path));
105
- }
106
- /**
107
- * The `runRuntimeCommand` names usable on the idle-turn path — every `BUILT_IN_COMMANDS` entry
108
- * *not* marked `runnerHandled`, i.e. every stateless report. `context` is the one deliberate
109
- * exception even though it isn't runner-handled while busy (see the busy-path switch in
110
- * `dingtalk.ts`): idle answers it through the runner's ChannelContext-aware command path
111
- * (thread-reply, delete semantics) instead, so it is routed like the runner-handled built-ins
112
- * here and excluded from this stateless-report set.
113
- */
114
- const IDLE_RUNTIME_COMMAND_NAMES = new Set(BUILT_IN_COMMANDS.filter((command) => !command.runnerHandled).map((command) => command.name));
115
- function isIdleRuntimeCommandName(name) {
116
- return IDLE_RUNTIME_COMMAND_NAMES.has(name);
117
- }
118
- /**
119
- * How long `/stop` waits for the turn to actually end before force-releasing it.
120
- * `requestStop` + `abort` only reach the agent loop; a turn wedged in its
121
- * epilogue (delivery drain, session-resource reload, memory flush) ignores both
122
- * and would otherwise keep the channel reporting "已有回合在运行" indefinitely.
123
- */
124
- const STOP_FORCE_END_GRACE_MS = 15_000;
125
- const STOP_FORCE_END_POLL_MS = 250;
126
- /**
127
- * Watchdog for `/stop`: release the channel if the stopped turn has not ended
128
- * once the grace window elapses. Returns true when it had to force the release.
129
- */
130
- export async function forceEndStuckTurnAfterStop(input) {
131
- const graceMs = input.graceMs ?? STOP_FORCE_END_GRACE_MS;
132
- const pollMs = input.pollMs ?? STOP_FORCE_END_POLL_MS;
133
- const deadline = Date.now() + graceMs;
134
- while (input.runner.isBusy() && Date.now() < deadline) {
135
- await sleepUnref(Math.min(pollMs, Math.max(1, deadline - Date.now())));
136
- }
137
- if (!input.runner.forceEndTurn(`/stop did not take effect within ${graceMs}ms`)) {
138
- return false;
139
- }
140
- await input
141
- .notify?.(`⚠️ 上一个回合的收尾卡住了,已强制结束以释放会话(后台清理仍在继续)。现在可以正常发消息或使用 \`/new\`、\`/model\`。`)
142
- .catch(() => undefined);
143
- return true;
144
- }
145
- function createDingTalkHandler(deps) {
146
- const { options, store, channelRunners, sessionResetChains, activeTasks, stopWatchdogs, channelIndex, archiveIncomingMessage, getRunner, cliVersion, startedAt, isShuttingDown, getDurableDispatch, getJobs, getRuns, getTaskDriver, } = deps;
147
- /**
148
- * Turn a `[TASK_DRIVER:<id>]` dispatch into a task loop step: bind the runner to the task
149
- * cycle's own session and replace the wake text with the step brief. Returns `undefined` for
150
- * every other event, which then follows the unchanged chat path.
151
- *
152
- * Binding failures fall back to the chat path rather than dropping the wake — a task that
153
- * cannot open its session should still be visible, not silently skipped.
154
- */
155
- const prepareTaskStep = async (event, runner) => {
156
- const taskId = parseDriverTaskId(event.text) ?? event.internalWake?.taskId;
157
- if (!taskId)
158
- return undefined;
159
- const channelDir = ensureChannelDir(options.paths.workspaceDir, event.channelId);
160
- try {
161
- const brief = await buildTaskStepBrief({ channelDir, taskId });
162
- if (!brief)
163
- return undefined;
164
- await runner.bindTaskSession(taskId);
165
- return { taskId, brief };
166
- }
167
- catch (error) {
168
- log.logWarning(`[${event.channelId}] Could not start task step for ${taskId}`, errorMessage(error));
169
- return undefined;
170
- }
171
- };
172
- /** Deliver whatever the step asked to say, then hand the runner back to the chat session. */
173
- const finishTaskStep = async (channelId, taskId, bot) => {
174
- const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
175
- try {
176
- const notice = await consumeTaskNotice(channelDir, taskId);
177
- if (notice) {
178
- // runner.run closes its per-turn delivery context before returning. Sending through that
179
- // closed context silently dropped successful task_step_end notifications (T-run-01).
180
- const delivered = await bot.sendPlain(channelId, notice);
181
- if (delivered)
182
- await store.logBotResponse(channelId, notice, Date.now().toString());
183
- else
184
- log.logWarning(`[${channelId}] Failed to deliver task notice for ${taskId}`);
185
- }
186
- }
187
- catch (error) {
188
- log.logWarning(`[${channelId}] Could not deliver task notice for ${taskId}`, errorMessage(error));
189
- }
190
- await getRunner(channelId).bindChatSession();
191
- };
192
- const handler = {
193
- isRunning(channelId) {
194
- return channelRunners.get(channelId)?.isBusy() ?? false;
195
- },
196
- noteChannelActivity(observation) {
197
- if (isShuttingDown())
198
- return;
199
- channelIndex.note(observation);
200
- },
201
- async handleStop(channelId, _bot) {
202
- const runner = channelRunners.get(channelId);
203
- let pausedTaskId;
204
- if (runner?.isBusy()) {
205
- runner.requestStop();
206
- // Stopping a task step stops the task: otherwise the driver would queue the next step
207
- // straight away. The step may not be bound to its session yet, so fall back to the text.
208
- const taskId = runner.getTaskLoop()?.taskId ?? parseDriverTaskId(runner.getTurnStatus().taskText);
209
- if (taskId) {
210
- await pauseStoredTask(getChannelDir(options.paths.workspaceDir, channelId), taskId, {
211
- by: "user",
212
- reason: "用户 /stop 中止了该任务的当前步骤。",
213
- });
214
- pausedTaskId = taskId;
215
- log.logInfo(`[${channelId}] Paused task ${taskId} on /stop`);
216
- }
217
- _bot.discardCard(channelId);
218
- // Drop queued-but-not-started messages so a burst does not keep
219
- // running after the user asked to halt; abort the in-flight one.
220
- const dropped = _bot.clearPendingMessages(channelId);
221
- if (dropped > 0) {
222
- log.logInfo(`[${channelId}] Dropped ${dropped} queued message(s) on stop`);
223
- }
224
- void runner.abort().catch((err) => {
225
- log.logWarning(`[${channelId}] Failed to abort run`, errorMessage(err));
226
- });
227
- void getDurableDispatch()
228
- ?.cancelChannel(channelId)
229
- .then((canceled) => {
230
- if (canceled)
231
- log.logInfo(`[${channelId}] Reset ${canceled} durable-dispatch lease(s) on stop`);
232
- })
233
- .catch((err) => {
234
- log.logWarning(`[${channelId}] Failed to reset durable-dispatch leases on stop`, errorMessage(err));
235
- });
236
- log.logInfo(`[${channelId}] Stop requested`);
237
- if (!stopWatchdogs.has(channelId)) {
238
- stopWatchdogs.add(channelId);
239
- void forceEndStuckTurnAfterStop({
240
- channelId,
241
- runner,
242
- graceMs: options.stopForceEndGraceMs,
243
- notify: (text) => _bot.sendPlain(channelId, text),
244
- })
245
- .catch((err) => {
246
- log.logWarning(`[${channelId}] Stop watchdog failed`, errorMessage(err));
247
- })
248
- .finally(() => {
249
- stopWatchdogs.delete(channelId);
250
- });
251
- }
252
- }
253
- return { pausedTaskId };
254
- },
255
- async handleNewSession(event, _bot) {
256
- if (isShuttingDown())
257
- return;
258
- const previous = sessionResetChains.get(event.channelId) ?? Promise.resolve();
259
- const reset = previous
260
- .catch(() => undefined)
261
- .then(async () => {
262
- try {
263
- const channelDir = ensureChannelDir(options.paths.workspaceDir, event.channelId);
264
- const access = resolveProjectAccessPolicy(loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config, process.cwd());
265
- const scope = resolveProjectScope(channelDir, access);
266
- if (scope.kind === "blocked") {
267
- throw new Error(scope.reason);
268
- }
269
- // The empty session file and active pointer are committed before the old
270
- // generation is touched. A filesystem failure therefore leaves the live
271
- // session authoritative and retryable.
272
- const result = await createFreshActiveSession(channelDir, scope.scope.projectRoot);
273
- const oldRunner = channelRunners.get(event.channelId);
274
- if (oldRunner) {
275
- channelRunners.delete(event.channelId);
276
- try {
277
- oldRunner.retireForNewSession();
278
- }
279
- catch (error) {
280
- // The active pointer already names the new session. Retirement is
281
- // best-effort cleanup and must not misreport the committed reset as failed.
282
- log.logWarning(`[${event.channelId}] Old runner retirement failed after /new`, errorMessage(error));
283
- }
284
- }
285
- const dropped = _bot.resetChannelQueue(event.channelId);
286
- if (dropped > 0) {
287
- log.logInfo(`[${event.channelId}] /new discarded ${dropped} queued old-session message(s)`);
288
- }
289
- await _bot.sendPlain(event.channelId, `已开启新会话。\n\nSession ID: \`${result.sessionId}\``);
290
- void archiveIncomingMessage(event.channelId, {
291
- date: new Date().toISOString(),
292
- ts: event.ts,
293
- user: event.user,
294
- userName: event.userName,
295
- text: event.text,
296
- isBot: false,
297
- images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
298
- }, "/new command");
299
- }
300
- catch (error) {
301
- const message = errorMessage(error);
302
- log.logWarning(`[${event.channelId}] Failed to create a fresh session`, message);
303
- await _bot.sendPlain(event.channelId, `新会话创建失败:${message}\n\n旧会话仍保持不变;请重试 \`/new\`。`);
304
- }
305
- });
306
- sessionResetChains.set(event.channelId, reset);
307
- activeTasks.add(reset);
308
- try {
309
- await reset;
310
- }
311
- finally {
312
- activeTasks.delete(reset);
313
- if (sessionResetChains.get(event.channelId) === reset) {
314
- sessionResetChains.delete(event.channelId);
315
- }
316
- }
317
- },
318
- async runRuntimeCommand(event, name, args) {
319
- const { channelId } = event;
320
- return runReportCommand({
321
- channelId,
322
- paths: options.paths,
323
- actor: "dingtalk-command",
324
- version: cliVersion,
325
- startedAt,
326
- peekRunner: () => channelRunners.get(channelId),
327
- getRunner: () => getRunner(channelId),
328
- runManager: getRuns().get(channelId),
329
- runningJobLines: () => getJobs().runningLines(channelId),
330
- // D4.2: dispose the cached runner so the next access rebuilds it under the new scope.
331
- // The active-session ref is untouched — same session, new project root.
332
- onScopeChanged: async () => {
333
- const runner = channelRunners.get(channelId);
334
- channelRunners.delete(channelId);
335
- await runner?.dispose().catch((err) => {
336
- log.logWarning(`[${channelId}] Failed to dispose runner after /project`, errorMessage(err));
337
- });
338
- },
339
- dispatchTask: async (id) => {
340
- const channelDir = getChannelDir(options.paths.workspaceDir, channelId);
341
- const entry = (await readActiveTasks(join(channelDir, "tasks"))).find((candidate) => candidate.id === id);
342
- if (!entry)
343
- return false;
344
- // A human asking to run a task twice means twice, so this key is deliberately
345
- // unique per invocation rather than sharing the driver's occurrence key (D1).
346
- const now = Date.now();
347
- return ((await getDurableDispatch()?.dispatch({
348
- ...createTaskDriverEvent(channelId, entry, now),
349
- dispatchId: `task:${channelId}:${entry.id}:manual:${new Date(now).toISOString()}`,
350
- })) ?? false);
351
- },
352
- }, name, args);
353
- },
354
- async handleBusyMessage(event, bot, mode, queueText) {
355
- if (isShuttingDown()) {
356
- return { kind: "handled" };
357
- }
358
- const runner = getRunner(event.channelId);
359
- const trimmedQueueText = queueText.trim();
360
- if (!trimmedQueueText) {
361
- const commandName = mode === "followUp" ? "followup" : "steer";
362
- await bot.sendPlain(event.channelId, `无法排队:/${commandName} 需要带上消息内容。`);
363
- return { kind: "handled" };
364
- }
365
- // Compaction is maintenance, not user work. A new message cancels it and is
366
- // kept as a normal queued turn instead of trying to steer an agent loop that
367
- // is currently disconnected for summarization.
368
- if (runner.interruptCompaction()) {
369
- log.logInfo(`[${event.channelId}] Interrupted compaction for a new user message`);
370
- return { kind: "requeue", text: trimmedQueueText };
371
- }
372
- // A task step runs in the task's own session and is muted: a steer here would land in
373
- // the background task's context and its answer would never reach the user, while the
374
- // message itself is kept out of the chat session. Run it as the next chat turn instead.
375
- const taskLoop = runner.getTaskLoop();
376
- if (taskLoop) {
377
- await bot.sendPlain(event.channelId, `后台任务 \`${taskLoop.taskId}\` 正在执行一步,你的消息会在这一步结束后处理;要给该任务补充指示,用 \`/tasks steer ${taskLoop.taskId} <内容>\`。`);
378
- log.logEvent("info", "agent.turn.followup_queued", "Message deferred past a task step", {
379
- ctx: { channelId: event.channelId, userName: event.userName },
380
- fields: { messageLength: trimmedQueueText.length, taskId: taskLoop.taskId },
381
- });
382
- return { kind: "requeue", text: trimmedQueueText };
383
- }
384
- if (mode === "followUp") {
385
- log.logEvent("info", "agent.turn.followup_queued", "Follow-up queued", {
386
- ctx: { channelId: event.channelId, userName: event.userName },
387
- fields: { messageLength: trimmedQueueText.length },
388
- });
389
- return { kind: "requeue", text: trimmedQueueText };
390
- }
391
- try {
392
- await runner.queueSteer(trimmedQueueText, event.userName, event.images);
393
- await archiveIncomingMessage(event.channelId, {
394
- date: new Date().toISOString(),
395
- ts: event.ts,
396
- user: event.user,
397
- userName: event.userName,
398
- text: event.text,
399
- isBot: false,
400
- deliveryMode: mode,
401
- skipContextSync: true,
402
- images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
403
- }, `${mode} message`);
404
- const confirmation = event.text.trim().startsWith("/")
405
- ? "已作为 steer 排队,当前工具步骤结束后生效。"
406
- : "已作为 steer 排队,当前工具步骤结束后生效。想等整个回合结束再执行,用 `/followup <消息>`。";
407
- await bot.sendPlain(event.channelId, confirmation);
408
- log.logEvent("info", "agent.turn.steer_queued", "Steer queued", {
409
- ctx: { channelId: event.channelId, userName: event.userName },
410
- fields: { messageLength: trimmedQueueText.length },
411
- });
412
- return { kind: "handled" };
413
- }
414
- catch (err) {
415
- const errMsg = errorMessage(err);
416
- if (isNoRunningTaskQueueError(err)) {
417
- log.logInfo(`[${event.channelId}] Busy ${mode} window closed; requeueing as a normal message`);
418
- return { kind: "requeue", text: trimmedQueueText };
419
- }
420
- log.logWarning(`[${event.channelId}] Failed to queue ${mode}`, errMsg);
421
- await bot.sendPlain(event.channelId, `无法排队这条消息:${errMsg}`);
422
- return { kind: "handled" };
423
- }
424
- },
425
- /**
426
- * Persist one downloaded inbound image under the channel's `inbox/` (spec 049). Bootstrap
427
- * owns this, not the transport, because it holds the workspace root; see the doc comment
428
- * on `DingTalkHandler.persistInboundImage` for the full contract (`mimeType: null` case
429
- * included).
430
- */
431
- async persistInboundImage(channelId, image) {
432
- try {
433
- const dir = join(getChannelDir(options.paths.workspaceDir, channelId), "inbox");
434
- await mkdir(dir, { recursive: true });
435
- const extension = extensionForMimeType(image.mimeType);
436
- const path = join(dir, `image-${localStampForFilename()}-${Math.random().toString(36).slice(2, 8)}.${extension}`);
437
- await writeFile(path, image.data, { mode: 0o600 });
438
- return {
439
- path,
440
- mimeType: image.mimeType ?? "application/octet-stream",
441
- byteSize: image.data.byteLength,
442
- ...(image.mimeType === null ? { unsupportedFormat: true } : {}),
443
- };
444
- }
445
- catch (err) {
446
- log.logWarning(`[${channelId}] Failed to persist inbound image`, errorMessage(err));
447
- return null;
448
- }
449
- },
450
- reserveEvent(event) {
451
- // This must remain synchronous. DingTalkBot calls it before awaiting the queued
452
- // handler, making the busy state observable to another message in the same tick.
453
- getRunner(event.channelId).beginTurn(event.text);
454
- },
455
- async handleEvent(inboundEvent, bot, _isEvent) {
456
- let event = inboundEvent;
457
- if (isShuttingDown()) {
458
- log.logInfo(`[${event.channelId}] Ignoring event during shutdown`);
459
- return;
460
- }
461
- const runner = getRunner(event.channelId);
462
- await getDurableDispatch()?.markStarted(event.dispatchId);
463
- let structuredWakeFinalized = event.internalWake === undefined;
464
- const task = (async () => {
465
- let baseCtx;
466
- try {
467
- // Computed before archiving so a command's own text can be excluded from
468
- // memory-extraction input (review 2026-08-24 §1.2): it is control-plane
469
- // traffic, not conversation, and the history stays queryable via session_search.
470
- const builtInCommand = parseBuiltInCommand(event.text);
471
- await archiveIncomingMessage(event.channelId, {
472
- date: new Date().toISOString(),
473
- ts: event.ts,
474
- user: event.user,
475
- userName: event.userName,
476
- text: event.text,
477
- isBot: false,
478
- skipContextSync: Boolean(builtInCommand),
479
- images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
480
- }, "user message");
481
- // Background wakes deliver their result, not their process: no progress card, no
482
- // thinking stream, nothing to clean up when a check-in ends `[SILENT]`.
483
- // Awaited completions deliver their result too, without opening another progress card.
484
- const backgroundOnly = Boolean(_isEvent);
485
- // Spec 051, D3: a task-driver dispatch runs as a *task step* — in the task cycle's
486
- // own session, with a brief instead of the wake text, and silent unless the step
487
- // asked for a notify. Everything below (busy state, /stop, delivery) is unchanged;
488
- // only which session the turn is bound to, and what reaches the channel, differ.
489
- let taskStep;
490
- baseCtx = createDingTalkContext(event, bot, store, backgroundOnly ? "none" : undefined);
491
- let ctx = baseCtx;
492
- if (builtInCommand) {
493
- const commandStartedAt = Date.now();
494
- const logCtx = { channelId: event.channelId, userName: event.userName };
495
- log.logEvent("info", "runtime.command.started", "Executing command", {
496
- ctx: logCtx,
497
- fields: { command: builtInCommand.name },
498
- });
499
- try {
500
- if (isIdleRuntimeCommandName(builtInCommand.name)) {
501
- const response = await handler.runRuntimeCommand(event, builtInCommand.name, builtInCommand.args);
502
- const delivered = await bot.sendPlain(event.channelId, response, {
503
- title: `/${builtInCommand.name}`,
504
- markdown: true,
505
- });
506
- if (!delivered) {
507
- log.logWarning(`[${event.channelId}] Failed to deliver /${builtInCommand.name} reply`, `${response.length} chars`);
508
- }
509
- }
510
- else if (isRunnerBuiltInCommand(builtInCommand)) {
511
- await runner.handleBuiltinCommand(ctx, builtInCommand);
512
- }
513
- log.logEvent("info", "runtime.command.completed", "Command completed", {
514
- ctx: logCtx,
515
- fields: { command: builtInCommand.name, durationMs: Date.now() - commandStartedAt },
516
- });
517
- }
518
- catch (err) {
519
- log.logEvent("warn", "runtime.command.failed", "Command failed", {
520
- ctx: logCtx,
521
- fields: {
522
- command: builtInCommand.name,
523
- durationMs: Date.now() - commandStartedAt,
524
- error: errorMessage(err),
525
- },
526
- });
527
- throw err;
528
- }
529
- return;
530
- }
531
- // Reject an unknown slash command instead of spending a full LLM turn
532
- // letting the model guess what `/modle` meant. Session commands,
533
- // skills, and prompt templates are recognized by isKnownSlashCommand.
534
- if (event.text.trim().startsWith("/") && !runner.isKnownSlashCommand(event.text)) {
535
- const name = slashCommandName(event.text) ?? "";
536
- await bot.sendPlain(event.channelId, formatUnknownCommandMessage(name));
537
- return;
538
- }
539
- log.logEvent("info", "agent.turn.started", "Starting turn", {
540
- ctx: { channelId: event.channelId, userName: event.userName },
541
- fields: { messageLength: event.text.length, source: _isEvent ? "event" : "message" },
542
- });
543
- // A completion wake for a task's job or delegation: verified against the resource's own
544
- // record before it may reopen the task (see `claimVerifiedWake`). Plain "belongs to task"
545
- // text in a message never counts — only the producer-created `internalWake` envelope.
546
- if (event.internalWake) {
547
- const { kind, resourceId, taskId: wakeTaskId } = event.internalWake;
548
- const claimed = await claimVerifiedWake(event, options.paths.workspaceDir, kind === "job" ? getJobs().get(event.channelId) : getRuns().get(event.channelId), options.wakeTransitionHooks?.[kind]);
549
- if (!claimed) {
550
- log.logWarning(`[${event.channelId}] Ignored an unverifiable ${kind} wake for ${resourceId} claiming task ${wakeTaskId}`);
551
- structuredWakeFinalized = true;
552
- return;
553
- }
554
- await claimed.finish();
555
- structuredWakeFinalized = true;
556
- // Drop without a turn only when something else is still driving this task (a sibling
557
- // wake in the same fan-out already reopened it); in every other case nobody else will
558
- // look at this result, so it still reaches a normal turn.
559
- if (!claimed.activated && claimed.taskStillDriven)
560
- return;
561
- }
562
- // Verified job/run wakes that activate a task are task steps too. Verification must happen
563
- // first: routing directly from user-controlled wake text would grant task-only tools.
564
- taskStep = await prepareTaskStep(event, runner);
565
- if (taskStep) {
566
- await baseCtx.close();
567
- event = { ...event, text: taskStep.brief };
568
- baseCtx = createDingTalkContext(event, bot, store, "none");
569
- ctx = muteChannelContext(baseCtx);
570
- }
571
- if (!backgroundOnly && !taskStep)
572
- ctx.primeCard(1500);
573
- const result = await runner.run(ctx, store);
574
- if (taskStep)
575
- await finishTaskStep(event.channelId, taskStep.taskId, bot);
576
- if (result.stopReason === "aborted" && runner.getTurnStatus().stopRequested) {
577
- log.logInfo(`[${event.channelId}] Stopped`);
578
- }
579
- }
580
- catch (err) {
581
- log.logEvent("error", "agent.turn.failed", "Turn failed", {
582
- ctx: { channelId: event.channelId, userName: event.userName },
583
- fields: { error: errorMessage(err) },
584
- });
585
- }
586
- finally {
587
- await baseCtx?.close().catch((error) => {
588
- log.logWarning(`[${event.channelId}] Failed to close delivery`, errorMessage(error));
589
- });
590
- if (structuredWakeFinalized)
591
- await getDurableDispatch()?.markCompleted(event.dispatchId);
592
- else
593
- await getDurableDispatch()?.markRetryable(event.dispatchId);
594
- runner.endTurn();
595
- // A finished turn may have written task files; rescan now so `outcome: continue`
596
- // queues the next step immediately instead of waiting out the current sleep.
597
- getTaskDriver().nudge?.();
598
- }
599
- })();
600
- activeTasks.add(task);
601
- try {
602
- await task;
603
- }
604
- finally {
605
- activeTasks.delete(task);
606
- }
607
- },
608
- };
609
- return handler;
610
- }
611
67
  export async function createRuntimeContext(options) {
612
68
  const startServices = options.startServices ?? true;
613
69
  const registerSignalHandlers = options.registerSignalHandlers ?? true;
@@ -626,13 +82,16 @@ export async function createRuntimeContext(options) {
626
82
  const channelIndex = createChannelIndex({ workspaceDir: options.paths.workspaceDir });
627
83
  let durableDispatch;
628
84
  let shuttingDown = false;
629
- let shutdownPromise = null;
630
85
  const archiveIncomingMessage = async (channelId, message, contextLabel) => {
631
86
  try {
632
87
  await store.logMessage(channelId, message);
633
88
  }
634
89
  catch (err) {
635
- log.logWarning(`[${channelId}] Failed to archive ${contextLabel}`, errorMessage(err));
90
+ log.logWarn("channel.archive.write_failed", "Message archive failed", {
91
+ channelId: channelId,
92
+ reason: errorMessage(err),
93
+ fields: { label: contextLabel },
94
+ });
636
95
  }
637
96
  };
638
97
  const getRunner = (channelId) => {
@@ -671,7 +130,7 @@ export async function createRuntimeContext(options) {
671
130
  const getJobs = () => jobs;
672
131
  const getRuns = () => runs;
673
132
  const getTaskDriver = () => taskDriver;
674
- const handler = createDingTalkHandler({
133
+ const handler = createTurnHandler({
675
134
  options,
676
135
  store,
677
136
  channelRunners,
@@ -692,18 +151,21 @@ export async function createRuntimeContext(options) {
692
151
  const bot = options.createBot
693
152
  ? options.createBot(handler, options.dingtalkConfig)
694
153
  : new DingTalkBot(handler, options.dingtalkConfig);
154
+ const dispatchStateDir = join(options.paths.appHomeDir, "state", "dispatch");
695
155
  durableDispatch = new DurableDispatchService({
696
- stateDir: join(options.paths.appHomeDir, "state", "dispatch"),
156
+ stateDir: dispatchStateDir,
697
157
  bot,
698
158
  // A structured wake (job/subagent completion, task-driver) that keeps failing before it can
699
159
  // ever mark itself complete would otherwise redeliver forever (30s tick, no backoff prior to
700
160
  // this notice). Surface it once instead of looping silently; the record stays on disk for
701
161
  // inspection until a human clears it.
702
162
  onExhausted: async (record) => {
703
- log.logWarning(`[${record.event.channelId}] Dispatch ${record.id} exhausted after ${record.deliveries} deliveries`, record.event.text.slice(0, 500));
704
- await bot.sendPlain(record.event.channelId, `一个后台唤醒(${record.event.user})连续 ${record.deliveries} 次投递均未能完成,已停止自动重试:\n` +
705
- `${record.event.text.slice(0, 300)}\n` +
706
- `记录文件:state/dispatch/${record.id}.json(已保留,供排查)。`);
163
+ log.logEvent("warn", "dispatch.exhausted", "Dispatch exhausted", {
164
+ ctx: { channelId: record.event.channelId },
165
+ details: record.event.text.slice(0, 500),
166
+ fields: { dispatchId: record.id, deliveries: record.deliveries, producer: record.event.user },
167
+ });
168
+ await bot.sendPlain(record.event.channelId, renderDispatchExhaustedNotice(record, dispatchStateDir));
707
169
  },
708
170
  });
709
171
  const executor = options.executor ?? createExecutor();
@@ -727,7 +189,7 @@ export async function createRuntimeContext(options) {
727
189
  const level = runtimeSettingsManager.getDelegationSettings().notices;
728
190
  if (level === "off")
729
191
  return;
730
- if (level === "settled" && notice.kind !== "settled")
192
+ if (level === "settled" && notice.kind === "progress")
731
193
  return;
732
194
  const text = renderRunNotice(notice);
733
195
  if (text)
@@ -755,12 +217,18 @@ export async function createRuntimeContext(options) {
755
217
  model: defaultModel.id,
756
218
  });
757
219
  if (recoveryReport.repaired.length > 0) {
758
- log.logWarning("Repaired interrupted turns on restart", `${recoveryReport.repaired.length}/${recoveryReport.scanned} channel(s): ${recoveryReport.repaired
759
- .map((r) => r.channelDir)
760
- .join(", ")}`);
220
+ log.logWarn("runtime.recovery.repaired", "Interrupted turns repaired on restart", {
221
+ fields: {
222
+ repaired: recoveryReport.repaired.length,
223
+ scanned: recoveryReport.scanned,
224
+ channels: recoveryReport.repaired.map((r) => r.channelDir),
225
+ },
226
+ });
761
227
  }
762
228
  if (recoveryReport.blocked.length > 0) {
763
- log.logWarning("Some channels have an unrecoverable session and will refuse new turns", recoveryReport.blocked.map((b) => `${b.channelDir}: ${b.reason}`).join("; "));
229
+ log.logWarn("runtime.recovery.blocked", "Channels with an unrecoverable session will refuse new turns", {
230
+ reason: recoveryReport.blocked.map((b) => `${b.channelDir}: ${b.reason}`).join("; "),
231
+ });
764
232
  }
765
233
  const eventsWatcher = options.createEventsWatcher
766
234
  ? options.createEventsWatcher(options.paths.workspaceDir, bot, executor, options.paths.eventHistoryPath)
@@ -822,81 +290,22 @@ export async function createRuntimeContext(options) {
822
290
  notify: (receipt) => bot.sendPlain(receipt.channelId, receipt.text),
823
291
  isEnabled: tasksToolEnabled,
824
292
  });
825
- const shutdownWithReason = async (reason = "manual") => {
826
- if (shutdownPromise) {
827
- return shutdownPromise;
828
- }
829
- shutdownPromise = (async () => {
293
+ const shutdownWithReason = createShutdown({
294
+ taskDriver,
295
+ getDurableDispatch,
296
+ memoryMaintenanceScheduler,
297
+ eventsWatcher,
298
+ runs,
299
+ jobs,
300
+ bot,
301
+ store,
302
+ channelIndex,
303
+ channelRunners,
304
+ activeTasks,
305
+ markShuttingDown: () => {
830
306
  shuttingDown = true;
831
- log.logInfo(`Shutting down (${reason})...`);
832
- taskDriver.stop();
833
- durableDispatch?.stop();
834
- memoryMaintenanceScheduler.stop();
835
- eventsWatcher.stop();
836
- runs.stop();
837
- jobs.stop();
838
- await bot.stop();
839
- const runningTasks = Array.from(activeTasks);
840
- if (runningTasks.length > 0) {
841
- log.logInfo(`Waiting for ${runningTasks.length} active task(s) to finish`);
842
- const completed = await waitForTasks(runningTasks, SHUTDOWN_WAIT_MS);
843
- if (!completed) {
844
- log.logWarning(`Shutdown grace period exceeded ${SHUTDOWN_WAIT_MS}ms, aborting active runs`);
845
- const aborts = [];
846
- for (const [channelId, runner] of channelRunners) {
847
- if (!runner.isBusy())
848
- continue;
849
- runner.requestStop();
850
- log.logInfo(`[${channelId}] Aborting active run for shutdown`);
851
- aborts.push(runner.abort().catch((err) => {
852
- log.logWarning(`[${channelId}] Failed to abort run during shutdown`, errorMessage(err));
853
- }));
854
- }
855
- await Promise.allSettled(aborts);
856
- const remainingTasks = Array.from(activeTasks);
857
- if (remainingTasks.length > 0) {
858
- const abortedCompleted = await waitForTasks(remainingTasks, SHUTDOWN_ABORT_WAIT_MS);
859
- if (!abortedCompleted) {
860
- log.logWarning(`Shutdown forced exit with ${remainingTasks.length} task(s) still active`);
861
- }
862
- }
863
- }
864
- }
865
- // Idle runners are disposed (flush memory, unsubscribe, release the SDK session); a
866
- // still-busy one — its turn already aborted above — is just dropped from the cache and
867
- // left to unwind on its own as the process exits.
868
- const disposals = [];
869
- for (const [channelId, runner] of channelRunners) {
870
- if (runner.isBusy())
871
- continue;
872
- disposals.push(runner.dispose().catch((err) => {
873
- log.logWarning(`[${channelId}] Failed to dispose runner during shutdown`, errorMessage(err));
874
- }));
875
- }
876
- if (disposals.length > 0) {
877
- log.logInfo(`Disposing ${disposals.length} idle channel runner(s) before shutdown`);
878
- const disposed = await waitForTasks(disposals, SHUTDOWN_FLUSH_WAIT_MS);
879
- if (!disposed) {
880
- log.logWarning(`Shutdown runner disposal exceeded ${SHUTDOWN_FLUSH_WAIT_MS}ms`);
881
- }
882
- }
883
- channelRunners.clear();
884
- const storageFlushes = [
885
- store.close(),
886
- // Cancels the debounce timer and lands the last activity times.
887
- channelIndex.close(),
888
- getUsageLedger().flush?.() ?? Promise.resolve(),
889
- flushSecurityLogs(),
890
- ...(eventsWatcher.flush ? [eventsWatcher.flush()] : []),
891
- ];
892
- const storageFlushed = await waitForTasks(storageFlushes, SHUTDOWN_LOG_FLUSH_WAIT_MS);
893
- if (!storageFlushed) {
894
- log.logWarning(`Shutdown log flush exceeded ${SHUTDOWN_LOG_FLUSH_WAIT_MS}ms`);
895
- }
896
- await waitForTasks([log.flushLogging()], SHUTDOWN_LOG_FLUSH_WAIT_MS);
897
- })();
898
- return shutdownPromise;
899
- };
307
+ },
308
+ });
900
309
  if (registerSignalHandlers) {
901
310
  process.once("SIGINT", () => {
902
311
  void shutdownWithReason("SIGINT").finally(() => {
@@ -940,9 +349,11 @@ export async function bootstrap(argv, options = {}) {
940
349
  parseArgs(argv, paths, io);
941
350
  const bootstrapResult = bootstrapAppHome(paths);
942
351
  printBootstrapSummary(bootstrapResult, io, paths);
352
+ // A freshly written template is the expected first-run outcome, not a failure: guide and exit 0.
353
+ // A template that exists but is still unfilled is caught by `loadConfig` below and exits 1.
943
354
  if (bootstrapResult.channelTemplateCreated) {
944
- io.error(`Fill in ${paths.channelConfigPath} and run \`${paths.appName}\` again.`);
945
- throw new BootstrapExitError(1);
355
+ printFirstRunGuide(io, paths);
356
+ throw new BootstrapExitError(0);
946
357
  }
947
358
  const dingtalkConfig = loadConfig(paths, io);
948
359
  dingtalkConfig.stateDir = paths.workspaceDir;