@oyasmi/pipiclaw 0.9.3 → 0.9.4-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (336) hide show
  1. package/dist/agent/builtin-commands.d.ts +19 -0
  2. package/dist/agent/builtin-commands.js +80 -0
  3. package/dist/agent/channel-runner.d.ts +20 -208
  4. package/dist/agent/channel-runner.js +167 -1188
  5. package/dist/agent/maintenance-context.d.ts +1 -1
  6. package/dist/agent/maintenance-context.js +1 -1
  7. package/dist/agent/prompt/manifest.d.ts +6 -1
  8. package/dist/agent/prompt/manifest.js +45 -64
  9. package/dist/agent/prompt/resources.d.ts +3 -0
  10. package/dist/agent/prompt/resources.js +11 -2
  11. package/dist/agent/runner-factory.d.ts +1 -43
  12. package/dist/agent/{command-extension.d.ts → session/command-extension.d.ts} +4 -0
  13. package/dist/agent/{command-extension.js → session/command-extension.js} +48 -35
  14. package/dist/agent/{type-guards.d.ts → session/event-guards.d.ts} +2 -2
  15. package/dist/agent/{type-guards.js → session/event-guards.js} +5 -1
  16. package/dist/agent/session/model-selection.d.ts +47 -0
  17. package/dist/agent/session/model-selection.js +99 -0
  18. package/dist/agent/{session-adapter.d.ts → session/session-adapter.d.ts} +21 -1
  19. package/dist/agent/session/session-adapter.js +159 -0
  20. package/dist/agent/{session-events.d.ts → session/session-events.d.ts} +9 -5
  21. package/dist/agent/{session-events.js → session/session-events.js} +24 -13
  22. package/dist/agent/session/session-host.d.ts +200 -0
  23. package/dist/agent/session/session-host.js +621 -0
  24. package/dist/agent/{session-resource-gate.js → session/session-resource-gate.js} +5 -3
  25. package/dist/agent/status-render.d.ts +0 -1
  26. package/dist/agent/status-render.js +4 -16
  27. package/dist/agent/{context-budget.js → turn/context-budget.js} +5 -1
  28. package/dist/agent/{progress-formatter.d.ts → turn/progress-formatter.d.ts} +4 -1
  29. package/dist/agent/{run-queue.d.ts → turn/run-queue.d.ts} +1 -1
  30. package/dist/agent/{run-queue.js → turn/run-queue.js} +10 -5
  31. package/dist/{memory → agent/turn}/task-digest.js +4 -4
  32. package/dist/agent/turn/turn-context.d.ts +14 -0
  33. package/dist/agent/turn/turn-context.js +64 -0
  34. package/dist/agent/turn/turn-error.d.ts +31 -0
  35. package/dist/agent/turn/turn-error.js +68 -0
  36. package/dist/agent/turn/turn-finish.d.ts +50 -0
  37. package/dist/agent/turn/turn-finish.js +188 -0
  38. package/dist/agent/turn/turn-input.d.ts +43 -0
  39. package/dist/agent/turn/turn-input.js +79 -0
  40. package/dist/agent/turn/turn-pipeline.d.ts +68 -0
  41. package/dist/agent/turn/turn-pipeline.js +257 -0
  42. package/dist/agent/{turn-prompt.d.ts → turn/turn-prompt.d.ts} +2 -2
  43. package/dist/agent/{turn-prompt.js → turn/turn-prompt.js} +6 -2
  44. package/dist/agent/{turn-recovery.js → turn/turn-recovery.js} +1 -1
  45. package/dist/agent/{turn-state.d.ts → turn/turn-state.d.ts} +1 -1
  46. package/dist/agent/types.d.ts +43 -2
  47. package/dist/agent/types.js +1 -1
  48. package/dist/{models/auth-cli.d.ts → app/auth-command.d.ts} +1 -1
  49. package/dist/{models/auth-cli.js → app/auth-command.js} +14 -10
  50. package/dist/{runtime/app-home.d.ts → app/home.d.ts} +6 -2
  51. package/dist/{runtime/app-home.js → app/home.js} +22 -75
  52. package/dist/{runtime → app}/proxy.js +4 -2
  53. package/dist/{app-services.d.ts → app/services.d.ts} +5 -5
  54. package/dist/{app-services.js → app/services.js} +17 -14
  55. package/dist/channel/channel-context.d.ts +12 -2
  56. package/dist/channel/channel-context.js +29 -2
  57. package/dist/channel/channel-event.d.ts +10 -2
  58. package/dist/channel/channel-event.js +1 -1
  59. package/dist/channel/channel-index.js +4 -1
  60. package/dist/{runtime/project-commands.d.ts → channel/commands.d.ts} +1 -1
  61. package/dist/{runtime/project-commands.js → channel/commands.js} +17 -16
  62. package/dist/channel/project-scope-store.js +1 -1
  63. package/dist/channel/store.js +4 -0
  64. package/dist/commands/catalog.d.ts +24 -7
  65. package/dist/commands/catalog.js +91 -44
  66. package/dist/commands/reply-limits.d.ts +6 -0
  67. package/dist/commands/reply-limits.js +24 -0
  68. package/dist/{runtime/report-commands.d.ts → commands/router.d.ts} +10 -3
  69. package/dist/{runtime/report-commands.js → commands/router.js} +6 -6
  70. package/dist/{settings.d.ts → config/settings.d.ts} +10 -10
  71. package/dist/{settings.js → config/settings.js} +11 -11
  72. package/dist/{tools/config.d.ts → config/tools.d.ts} +1 -2
  73. package/dist/{tools/config.js → config/tools.js} +5 -2
  74. package/dist/dingtalk/access-token.d.ts +12 -0
  75. package/dist/dingtalk/access-token.js +51 -0
  76. package/dist/dingtalk/api.d.ts +19 -0
  77. package/dist/dingtalk/api.js +67 -0
  78. package/dist/dingtalk/bot.d.ts +97 -0
  79. package/dist/dingtalk/bot.js +389 -0
  80. package/dist/dingtalk/cards.d.ts +56 -0
  81. package/dist/dingtalk/cards.js +318 -0
  82. package/dist/{runtime → dingtalk}/channel-queue.js +4 -1
  83. package/dist/dingtalk/config.d.ts +19 -0
  84. package/dist/dingtalk/config.js +95 -0
  85. package/dist/dingtalk/connection.d.ts +57 -0
  86. package/dist/dingtalk/connection.js +356 -0
  87. package/dist/dingtalk/conversation-meta.d.ts +16 -0
  88. package/dist/dingtalk/conversation-meta.js +77 -0
  89. package/dist/{runtime → dingtalk}/delivery.d.ts +6 -2
  90. package/dist/{runtime → dingtalk}/delivery.js +29 -15
  91. package/dist/dingtalk/handler.d.ts +90 -0
  92. package/dist/dingtalk/handler.js +1 -0
  93. package/dist/dingtalk/inbound.d.ts +66 -0
  94. package/dist/dingtalk/inbound.js +137 -0
  95. package/dist/dingtalk/media.d.ts +66 -0
  96. package/dist/dingtalk/media.js +214 -0
  97. package/dist/events/{event-commands.js → commands.js} +99 -45
  98. package/dist/events/parse.d.ts +14 -0
  99. package/dist/events/parse.js +114 -0
  100. package/dist/events/types.d.ts +93 -0
  101. package/dist/events/types.js +1 -0
  102. package/dist/events/{event-validation.d.ts → validation.d.ts} +14 -3
  103. package/dist/events/{event-validation.js → validation.js} +17 -9
  104. package/dist/events/watcher.d.ts +67 -0
  105. package/dist/events/{events.js → watcher.js} +63 -121
  106. package/dist/executor.js +2 -2
  107. package/dist/index.d.ts +6 -4
  108. package/dist/index.js +2 -2
  109. package/dist/jobs/launch.d.ts +42 -0
  110. package/dist/jobs/launch.js +118 -0
  111. package/dist/{agent/job-manager.d.ts → jobs/manager.d.ts} +1 -67
  112. package/dist/{agent/job-manager.js → jobs/manager.js} +34 -157
  113. package/dist/jobs/record.d.ts +55 -0
  114. package/dist/jobs/record.js +36 -0
  115. package/dist/log.d.ts +12 -2
  116. package/dist/log.js +26 -34
  117. package/dist/main.js +3 -3
  118. package/dist/memory/commands.js +29 -23
  119. package/dist/memory/lifecycle.js +26 -5
  120. package/dist/memory/maintenance-gates.d.ts +2 -2
  121. package/dist/memory/maintenance-state.js +4 -1
  122. package/dist/memory/maintenance-tuning.d.ts +15 -0
  123. package/dist/memory/maintenance-tuning.js +3 -0
  124. package/dist/memory/reflect-job.d.ts +2 -2
  125. package/dist/memory/reflect-job.js +4 -2
  126. package/dist/memory/scheduler.d.ts +3 -3
  127. package/dist/memory/scheduler.js +5 -2
  128. package/dist/memory/sidecar-worker.js +1 -1
  129. package/dist/memory/transcript.js +1 -1
  130. package/dist/{agent/model-fallback.d.ts → models/fallback.d.ts} +6 -6
  131. package/dist/{agent/model-fallback.js → models/fallback.js} +15 -28
  132. package/dist/models/login-identity.d.ts +2 -0
  133. package/dist/models/login-identity.js +83 -0
  134. package/dist/models/provider-login.d.ts +3 -1
  135. package/dist/models/provider-login.js +8 -2
  136. package/dist/models/reference.d.ts +20 -0
  137. package/dist/models/{utils.js → reference.js} +0 -48
  138. package/dist/models/{utils.d.ts → runtime.d.ts} +1 -16
  139. package/dist/models/runtime.js +52 -0
  140. package/dist/paths.d.ts +2 -0
  141. package/dist/paths.js +9 -0
  142. package/dist/playbooks/agent-delegation.md +2 -2
  143. package/dist/playbooks/catalog.d.ts +6 -2
  144. package/dist/playbooks/catalog.js +9 -6
  145. package/dist/runtime/bootstrap.d.ts +7 -17
  146. package/dist/runtime/bootstrap.js +70 -659
  147. package/dist/runtime/durable-dispatch.d.ts +43 -4
  148. package/dist/runtime/durable-dispatch.js +153 -3
  149. package/dist/runtime/inbound-images.d.ts +18 -0
  150. package/dist/runtime/inbound-images.js +51 -0
  151. package/dist/runtime/shutdown.d.ts +39 -0
  152. package/dist/runtime/shutdown.js +120 -0
  153. package/dist/runtime/stop-watchdog.d.ts +16 -0
  154. package/dist/runtime/stop-watchdog.js +32 -0
  155. package/dist/runtime/task-driver.d.ts +6 -4
  156. package/dist/runtime/task-driver.js +58 -23
  157. package/dist/runtime/task-migration.js +25 -8
  158. package/dist/runtime/task-spawn.d.ts +1 -1
  159. package/dist/runtime/task-spawn.js +13 -6
  160. package/dist/runtime/turn-handler.d.ts +47 -0
  161. package/dist/runtime/turn-handler.js +318 -0
  162. package/dist/runtime/turn-run.d.ts +52 -0
  163. package/dist/runtime/turn-run.js +318 -0
  164. package/dist/runtime/wake-coalescing.d.ts +18 -0
  165. package/dist/runtime/wake-coalescing.js +29 -0
  166. package/dist/security/block-message.d.ts +22 -1
  167. package/dist/security/block-message.js +66 -1
  168. package/dist/security/command-guard.js +4 -0
  169. package/dist/security/network.d.ts +2 -1
  170. package/dist/security/network.js +7 -2
  171. package/dist/security/path-guard-check.js +2 -2
  172. package/dist/security/path-guard.js +4 -0
  173. package/dist/security/types.d.ts +1 -2
  174. package/dist/security/types.js +1 -2
  175. package/dist/shared/exact-keys.d.ts +1 -1
  176. package/dist/shared/format.d.ts +12 -0
  177. package/dist/shared/format.js +37 -0
  178. package/dist/shared/host-process.js +16 -4
  179. package/dist/shared/wake-claim.d.ts +1 -1
  180. package/dist/shared/with-timeout.d.ts +3 -2
  181. package/dist/shared/with-timeout.js +14 -3
  182. package/dist/{runtime/skill-commands.d.ts → skills/commands.d.ts} +2 -2
  183. package/dist/{runtime/skill-commands.js → skills/commands.js} +18 -11
  184. package/dist/{agent/workspace-resources.js → skills/loader.js} +1 -1
  185. package/dist/{tools/skill-security.js → skills/validation.js} +4 -0
  186. package/dist/skills/workspace.d.ts +33 -0
  187. package/dist/skills/workspace.js +116 -0
  188. package/dist/{runtime/subagent-commands.d.ts → subagents/commands.d.ts} +9 -7
  189. package/dist/{runtime/subagent-commands.js → subagents/commands.js} +116 -77
  190. package/dist/subagents/completion-wake.d.ts +17 -0
  191. package/dist/subagents/completion-wake.js +76 -0
  192. package/dist/subagents/detached-discovery.js +1 -1
  193. package/dist/subagents/discovery.d.ts +1 -1
  194. package/dist/subagents/discovery.js +2 -2
  195. package/dist/subagents/dispatch.d.ts +33 -0
  196. package/dist/subagents/dispatch.js +190 -0
  197. package/dist/subagents/external/claude-code.js +23 -1
  198. package/dist/subagents/external/dispatch.d.ts +25 -0
  199. package/dist/subagents/external/dispatch.js +90 -0
  200. package/dist/subagents/external/harness.d.ts +1 -1
  201. package/dist/subagents/external/progress-tail.d.ts +18 -1
  202. package/dist/subagents/external/progress-tail.js +64 -17
  203. package/dist/subagents/external/run.d.ts +5 -1
  204. package/dist/subagents/external/run.js +23 -9
  205. package/dist/subagents/external/settlement.d.ts +4 -1
  206. package/dist/subagents/external/settlement.js +1 -1
  207. package/dist/subagents/format.d.ts +1 -1
  208. package/dist/subagents/grace.d.ts +24 -0
  209. package/dist/subagents/grace.js +57 -0
  210. package/dist/subagents/internal/outcome.d.ts +24 -0
  211. package/dist/subagents/internal/outcome.js +149 -0
  212. package/dist/subagents/internal/provider-retry.d.ts +19 -0
  213. package/dist/subagents/internal/provider-retry.js +83 -0
  214. package/dist/subagents/internal/run.d.ts +31 -0
  215. package/dist/subagents/internal/run.js +240 -0
  216. package/dist/subagents/internal/state.d.ts +43 -0
  217. package/dist/subagents/internal/state.js +48 -0
  218. package/dist/subagents/internal/worker.d.ts +51 -0
  219. package/dist/subagents/internal/worker.js +167 -0
  220. package/dist/subagents/result.d.ts +62 -0
  221. package/dist/subagents/result.js +103 -0
  222. package/dist/subagents/run-record.d.ts +222 -0
  223. package/dist/subagents/run-record.js +101 -0
  224. package/dist/subagents/run-registry.d.ts +9 -0
  225. package/dist/subagents/run-registry.js +125 -0
  226. package/dist/subagents/runs.d.ts +16 -232
  227. package/dist/subagents/runs.js +132 -310
  228. package/dist/subagents/task-envelope.d.ts +36 -0
  229. package/dist/subagents/task-envelope.js +168 -0
  230. package/dist/subagents/types.d.ts +154 -0
  231. package/dist/subagents/types.js +1 -0
  232. package/dist/subagents/verification-outcome.d.ts +1 -1
  233. package/dist/subagents/workspace-summary.d.ts +16 -4
  234. package/dist/subagents/workspace-summary.js +74 -18
  235. package/dist/tasks/board.d.ts +10 -3
  236. package/dist/tasks/board.js +38 -3
  237. package/dist/tasks/{work-log.d.ts → bound-work.d.ts} +1 -1
  238. package/dist/tasks/{work-log.js → bound-work.js} +1 -1
  239. package/dist/tasks/brief.js +1 -1
  240. package/dist/{runtime/task-commands.d.ts → tasks/commands.d.ts} +1 -1
  241. package/dist/{runtime/task-commands.js → tasks/commands.js} +117 -67
  242. package/dist/tasks/contract-input.d.ts +1 -1
  243. package/dist/tasks/contract-input.js +1 -1
  244. package/dist/tasks/create.js +1 -1
  245. package/dist/tasks/frontmatter.d.ts +5 -0
  246. package/dist/tasks/frontmatter.js +8 -0
  247. package/dist/tasks/{log.d.ts → loop-log.d.ts} +11 -1
  248. package/dist/tasks/{log.js → loop-log.js} +59 -3
  249. package/dist/tasks/mutation-lock.js +1 -1
  250. package/dist/tasks/session-path.js +1 -1
  251. package/dist/tasks/steer.js +1 -1
  252. package/dist/tasks/store.js +6 -4
  253. package/dist/tasks/ticket.d.ts +3 -1
  254. package/dist/tasks/ticket.js +19 -1
  255. package/dist/tools/bash.d.ts +1 -1
  256. package/dist/tools/bash.js +2 -2
  257. package/dist/tools/{tool-details.d.ts → contract/details.d.ts} +11 -3
  258. package/dist/tools/{tool-details.js → contract/details.js} +42 -5
  259. package/dist/tools/{presentation.js → contract/presentation.js} +3 -3
  260. package/dist/tools/event-manage.d.ts +1 -1
  261. package/dist/tools/event-manage.js +4 -4
  262. package/dist/tools/index.d.ts +5 -3
  263. package/dist/tools/index.js +8 -6
  264. package/dist/tools/job.d.ts +1 -1
  265. package/dist/tools/memory-manage.js +4 -1
  266. package/dist/tools/registry.d.ts +7 -7
  267. package/dist/tools/registry.js +6 -6
  268. package/dist/tools/session-search.d.ts +1 -1
  269. package/dist/tools/skill.d.ts +2 -34
  270. package/dist/tools/skill.js +8 -116
  271. package/dist/tools/subagent-manage.d.ts +1 -1
  272. package/dist/tools/subagent-manage.js +19 -13
  273. package/dist/tools/subagent.d.ts +46 -0
  274. package/dist/tools/subagent.js +127 -0
  275. package/dist/tools/{task-manage.d.ts → task-manage/factory.d.ts} +7 -3
  276. package/dist/tools/{task-manage.js → task-manage/factory.js} +7 -7
  277. package/dist/tools/task-manage/lifecycle.js +2 -2
  278. package/dist/tools/task-manage/log-view.js +2 -2
  279. package/dist/tools/task-manage/shared.js +3 -3
  280. package/dist/tools/task-manage/step-end.js +7 -4
  281. package/dist/tools/task-manage/types.d.ts +1 -1
  282. package/dist/tools/web-fetch.d.ts +1 -1
  283. package/dist/tools/web-search.d.ts +1 -1
  284. package/dist/tui/app.d.ts +1 -1
  285. package/dist/tui/app.js +6 -6
  286. package/dist/tui/cli.d.ts +1 -1
  287. package/dist/tui/cli.js +3 -3
  288. package/dist/tui/commands.js +4 -4
  289. package/dist/tui/frontend.d.ts +44 -0
  290. package/dist/tui/frontend.js +13 -0
  291. package/dist/tui/pitui-frontend.d.ts +1 -1
  292. package/dist/tui/pitui-frontend.js +1 -1
  293. package/dist/tui/plain-frontend.d.ts +1 -1
  294. package/dist/tui/renderer.d.ts +3 -42
  295. package/dist/tui/renderer.js +3 -2
  296. package/dist/tui/terminal-context.d.ts +2 -2
  297. package/dist/tui/terminal-media-sender.d.ts +1 -1
  298. package/dist/tui/turn-controller.d.ts +3 -1
  299. package/dist/tui/turn-controller.js +36 -21
  300. package/dist/usage/ledger.js +7 -1
  301. package/dist/usage/render.js +3 -1
  302. package/dist/{shared/types.d.ts → usage/totals.d.ts} +3 -0
  303. package/dist/web/client.d.ts +5 -1
  304. package/dist/web/client.js +4 -0
  305. package/dist/web/config.d.ts +1 -1
  306. package/dist/web/fetch.d.ts +1 -1
  307. package/dist/web/search-providers.d.ts +1 -1
  308. package/dist/web/search.d.ts +1 -1
  309. package/package.json +9 -7
  310. package/dist/agent/session-adapter.js +0 -77
  311. package/dist/events/events.d.ts +0 -159
  312. package/dist/runtime/dingtalk.d.ts +0 -272
  313. package/dist/runtime/dingtalk.js +0 -1416
  314. package/dist/subagents/tool.d.ts +0 -206
  315. package/dist/subagents/tool.js +0 -1088
  316. /package/dist/{runtime → agent/prompt}/workspace-templates.d.ts +0 -0
  317. /package/dist/{runtime → agent/prompt}/workspace-templates.js +0 -0
  318. /package/dist/agent/{session-resource-gate.d.ts → session/session-resource-gate.d.ts} +0 -0
  319. /package/dist/agent/{context-budget.d.ts → turn/context-budget.d.ts} +0 -0
  320. /package/dist/agent/{progress-formatter.js → turn/progress-formatter.js} +0 -0
  321. /package/dist/{memory → agent/turn}/task-digest.d.ts +0 -0
  322. /package/dist/agent/{turn-recovery.d.ts → turn/turn-recovery.d.ts} +0 -0
  323. /package/dist/agent/{turn-state.js → turn/turn-state.js} +0 -0
  324. /package/dist/{runtime → app}/proxy.d.ts +0 -0
  325. /package/dist/{runtime → dingtalk}/channel-queue.d.ts +0 -0
  326. /package/dist/{runtime → dingtalk}/inbound-media.d.ts +0 -0
  327. /package/dist/{runtime → dingtalk}/inbound-media.js +0 -0
  328. /package/dist/events/{event-commands.d.ts → commands.d.ts} +0 -0
  329. /package/dist/{agent/workspace-resources.d.ts → skills/loader.d.ts} +0 -0
  330. /package/dist/{tools/skill-security.d.ts → skills/validation.d.ts} +0 -0
  331. /package/dist/tasks/{ledger.d.ts → contract.d.ts} +0 -0
  332. /package/dist/tasks/{ledger.js → contract.js} +0 -0
  333. /package/dist/tools/{subagent-tool-names.d.ts → contract/names.d.ts} +0 -0
  334. /package/dist/tools/{subagent-tool-names.js → contract/names.js} +0 -0
  335. /package/dist/tools/{presentation.d.ts → contract/presentation.d.ts} +0 -0
  336. /package/dist/{shared/types.js → usage/totals.js} +0 -0
@@ -0,0 +1,318 @@
1
+ import { muteChannelContext } from "../channel/channel-context.js";
2
+ import { ensureChannelDir } from "../channel/channel-paths.js";
3
+ import { BUILT_IN_COMMANDS, formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../commands/catalog.js";
4
+ import { createDingTalkContext } from "../dingtalk/delivery.js";
5
+ import * as log from "../log.js";
6
+ import { errorMessage } from "../shared/text-utils.js";
7
+ import { buildTaskStepBrief } from "../tasks/brief.js";
8
+ import { consumeTaskNotice } from "../tasks/steer.js";
9
+ import { relativeImagePaths } from "./inbound-images.js";
10
+ import { parseDriverTaskId } from "./task-driver.js";
11
+ import { claimVerifiedWake } from "./task-wake.js";
12
+ import { isCoalescableWake, MAX_COALESCED_WAKES, mergeCompletionWakes } from "./wake-coalescing.js";
13
+ /**
14
+ * The `runRuntimeCommand` names usable on the idle-turn path — every `BUILT_IN_COMMANDS` entry
15
+ * *not* marked `runnerHandled`, i.e. every stateless report. `context` is the one deliberate
16
+ * exception even though it isn't runner-handled while busy (see the busy-path switch in
17
+ * `dingtalk/bot.ts`): idle answers it through the runner's ChannelContext-aware command path
18
+ * (thread-reply, delete semantics) instead, so it is routed like the runner-handled built-ins
19
+ * here and excluded from this stateless-report set.
20
+ */
21
+ const IDLE_RUNTIME_COMMAND_NAMES = new Set(BUILT_IN_COMMANDS.filter((command) => !command.runnerHandled).map((command) => command.name));
22
+ function isIdleRuntimeCommandName(name) {
23
+ return IDLE_RUNTIME_COMMAND_NAMES.has(name);
24
+ }
25
+ /**
26
+ * The turn pipeline behind `DingTalkHandler.handleEvent`: admit the dispatch, run commands or the
27
+ * agent (as a task step when the wake is one), and always settle the dispatch and release the turn.
28
+ */
29
+ export function createEventTurnRunner(deps) {
30
+ const { options, store, activeTasks, archiveIncomingMessage, getRunner, isShuttingDown, getDurableDispatch, getJobs, getRuns, getTaskDriver, } = deps;
31
+ /**
32
+ * Turn a `[TASK_DRIVER:<id>]` dispatch into a task loop step: bind the runner to the task
33
+ * cycle's own session and replace the wake text with the step brief. Returns `undefined` for
34
+ * every other event, which then follows the unchanged chat path.
35
+ *
36
+ * Binding failures fall back to the chat path rather than dropping the wake — a task that
37
+ * cannot open its session should still be visible, not silently skipped.
38
+ */
39
+ const prepareTaskStep = async (event, runner) => {
40
+ const taskId = parseDriverTaskId(event.text) ?? event.internalWake?.taskId;
41
+ if (!taskId)
42
+ return undefined;
43
+ const channelDir = ensureChannelDir(options.paths.workspaceDir, event.channelId);
44
+ try {
45
+ const brief = await buildTaskStepBrief({ channelDir, taskId });
46
+ if (!brief)
47
+ return undefined;
48
+ await runner.bindTaskSession(taskId);
49
+ return { taskId, brief };
50
+ }
51
+ catch (error) {
52
+ log.logWarn("taskdriver.step.start_failed", "Task step start failed", {
53
+ channelId: event.channelId,
54
+ reason: errorMessage(error),
55
+ fields: { taskId },
56
+ });
57
+ return undefined;
58
+ }
59
+ };
60
+ /** Deliver whatever the step asked to say, then hand the runner back to the chat session. */
61
+ const finishTaskStep = async (channelId, taskId, bot) => {
62
+ const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
63
+ try {
64
+ const notice = await consumeTaskNotice(channelDir, taskId);
65
+ if (notice) {
66
+ // runner.run closes its per-turn delivery context before returning. Sending through that
67
+ // closed context silently dropped successful task_step_end notifications (T-run-01).
68
+ const delivered = await bot.sendPlain(channelId, notice);
69
+ if (delivered)
70
+ await store.logBotResponse(channelId, notice, Date.now().toString());
71
+ else
72
+ log.logWarn("taskdriver.notice.delivery_failed", "Task notice delivery failed", {
73
+ channelId: channelId,
74
+ fields: { taskId },
75
+ });
76
+ }
77
+ }
78
+ catch (error) {
79
+ log.logWarn("taskdriver.notice.delivery_failed", "Task notice delivery failed", {
80
+ channelId: channelId,
81
+ reason: errorMessage(error),
82
+ fields: { taskId },
83
+ });
84
+ }
85
+ await getRunner(channelId).bindChatSession();
86
+ };
87
+ /**
88
+ * Dispatch admission: refuse a stale redelivery of a wake an earlier turn already handled (the
89
+ * turn is released), and fold other pending completion wakes into this one. `undefined` = skip.
90
+ */
91
+ const admitTurn = async (inboundEvent, runner) => {
92
+ let event = inboundEvent;
93
+ const durable = getDurableDispatch();
94
+ // Sampled synchronously, before any await: `/stop` after this point cleared the queued closures.
95
+ const stopEpoch = durable?.stopEpoch(inboundEvent.channelId) ?? 0;
96
+ if (durable && !(await durable.markStarted(event.dispatchId))) {
97
+ // A stale delivery of a wake an earlier turn already absorbed and handled.
98
+ runner.endTurn();
99
+ return undefined;
100
+ }
101
+ const structuredWakeFinalized = event.internalWake === undefined;
102
+ let absorbedDispatchIds = [];
103
+ if (durable && event.dispatchId && isCoalescableWake(event)) {
104
+ const absorbed = await durable
105
+ .absorbPending(event.channelId, event.dispatchId, isCoalescableWake, MAX_COALESCED_WAKES - 1, stopEpoch)
106
+ .catch((error) => {
107
+ log.logWarn("dispatch.wake.absorb_failed", "Wake coalescing failed", {
108
+ channelId: event.channelId,
109
+ reason: errorMessage(error),
110
+ });
111
+ return [];
112
+ });
113
+ if (absorbed.length > 0) {
114
+ event = mergeCompletionWakes(event, absorbed);
115
+ absorbedDispatchIds = absorbed.flatMap((absorbedEvent) => absorbedEvent.dispatchId ? [absorbedEvent.dispatchId] : []);
116
+ log.logInfoEvent("dispatch.wake.coalesced", "Completion wakes coalesced", {
117
+ channelId: event.channelId,
118
+ fields: { primary: event.dispatchId, absorbed: absorbedDispatchIds.length },
119
+ });
120
+ }
121
+ }
122
+ return { event, baseCtx: undefined, structuredWakeFinalized, absorbedDispatchIds, mergedWakesHandled: false };
123
+ };
124
+ /** A built-in slash command typed on an idle channel: stateless reports here, session commands on the runner. */
125
+ const runBuiltinCommand = async (turn, builtInCommand, runner, ctx, bot) => {
126
+ const { event } = turn;
127
+ const commandStartedAt = Date.now();
128
+ const logCtx = { channelId: event.channelId, userName: event.userName };
129
+ log.logEvent("info", "runtime.command.started", "Executing command", {
130
+ ctx: logCtx,
131
+ fields: { command: builtInCommand.name },
132
+ });
133
+ try {
134
+ if (isIdleRuntimeCommandName(builtInCommand.name)) {
135
+ const response = await deps.runRuntimeCommand(event, builtInCommand.name, builtInCommand.args);
136
+ const delivered = await bot.sendPlain(event.channelId, response, {
137
+ title: `/${builtInCommand.name}`,
138
+ markdown: true,
139
+ });
140
+ if (!delivered) {
141
+ log.logWarn("delivery.command_reply.failed", "Command reply delivery failed", {
142
+ channelId: event.channelId,
143
+ fields: { command: builtInCommand.name, chars: response.length },
144
+ });
145
+ }
146
+ }
147
+ else if (isRunnerBuiltInCommand(builtInCommand)) {
148
+ await runner.handleBuiltinCommand(ctx, builtInCommand);
149
+ }
150
+ log.logEvent("info", "runtime.command.completed", "Command completed", {
151
+ ctx: logCtx,
152
+ fields: { command: builtInCommand.name, durationMs: Date.now() - commandStartedAt },
153
+ });
154
+ }
155
+ catch (err) {
156
+ log.logEvent("warn", "runtime.command.failed", "Command failed", {
157
+ ctx: logCtx,
158
+ fields: {
159
+ command: builtInCommand.name,
160
+ durationMs: Date.now() - commandStartedAt,
161
+ error: errorMessage(err),
162
+ },
163
+ });
164
+ throw err;
165
+ }
166
+ };
167
+ /**
168
+ * A completion wake for a task's job or delegation: verified against the resource's own record
169
+ * before it may reopen the task (see `claimVerifiedWake`). Plain "belongs to task" text in a
170
+ * message never counts — only the producer-created `internalWake` envelope. Returns whether the
171
+ * turn should still run.
172
+ */
173
+ const verifyInternalWake = async (turn, internalWake) => {
174
+ const { event } = turn;
175
+ const { kind, resourceId, taskId: wakeTaskId } = internalWake;
176
+ const claimed = await claimVerifiedWake(event, options.paths.workspaceDir, kind === "job" ? getJobs().get(event.channelId) : getRuns().get(event.channelId), options.wakeTransitionHooks?.[kind]);
177
+ if (!claimed) {
178
+ log.logWarn("dispatch.wake.unverified", "Unverifiable wake ignored", {
179
+ channelId: event.channelId,
180
+ fields: { kind, resourceId, taskId: wakeTaskId },
181
+ });
182
+ turn.structuredWakeFinalized = true;
183
+ return false;
184
+ }
185
+ await claimed.finish();
186
+ turn.structuredWakeFinalized = true;
187
+ // Drop without a turn only when something else is still driving this task (a sibling
188
+ // wake in the same fan-out already reopened it); in every other case nobody else will
189
+ // look at this result, so it still reaches a normal turn.
190
+ return claimed.activated || !claimed.taskStillDriven;
191
+ };
192
+ /** The turn proper: archive, route commands, verify wakes, then run the agent (as a task step if one). */
193
+ const executeTurn = async (turn, runner, bot, backgroundOnly) => {
194
+ const { event } = turn;
195
+ // Computed before archiving so a command's own text can be excluded from
196
+ // memory-extraction input (review 2026-08-24 §1.2): it is control-plane
197
+ // traffic, not conversation, and the history stays queryable via session_search.
198
+ const builtInCommand = parseBuiltInCommand(event.text);
199
+ await archiveIncomingMessage(event.channelId, {
200
+ date: new Date().toISOString(),
201
+ ts: event.ts,
202
+ user: event.user,
203
+ userName: event.userName,
204
+ text: event.text,
205
+ isBot: false,
206
+ skipContextSync: Boolean(builtInCommand),
207
+ images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
208
+ }, "user message");
209
+ // Background wakes deliver their result, not their process: no progress card, no
210
+ // thinking stream, nothing to clean up when a check-in ends `[SILENT]`.
211
+ // Awaited completions deliver their result too, without opening another progress card.
212
+ // Spec 051, D3: a task-driver dispatch runs as a *task step* — in the task cycle's
213
+ // own session, with a brief instead of the wake text, and silent unless the step
214
+ // asked for a notify. Everything below (busy state, /stop, delivery) is unchanged;
215
+ // only which session the turn is bound to, and what reaches the channel, differ.
216
+ let baseCtx = createDingTalkContext(event, bot, store, backgroundOnly ? "none" : undefined);
217
+ turn.baseCtx = baseCtx;
218
+ let ctx = baseCtx;
219
+ if (builtInCommand) {
220
+ await runBuiltinCommand(turn, builtInCommand, runner, ctx, bot);
221
+ return;
222
+ }
223
+ // Reject an unknown slash command instead of spending a full LLM turn
224
+ // letting the model guess what `/modle` meant. Session commands,
225
+ // skills, and prompt templates are recognized by isKnownSlashCommand.
226
+ if (event.text.trim().startsWith("/") && !runner.isKnownSlashCommand(event.text)) {
227
+ const name = slashCommandName(event.text) ?? "";
228
+ await bot.sendPlain(event.channelId, formatUnknownCommandMessage(name));
229
+ return;
230
+ }
231
+ log.logEvent("info", "agent.turn.started", "Starting turn", {
232
+ ctx: { channelId: event.channelId, userName: event.userName },
233
+ fields: { messageLength: event.text.length, source: backgroundOnly ? "event" : "message" },
234
+ });
235
+ if (event.internalWake && !(await verifyInternalWake(turn, event.internalWake)))
236
+ return;
237
+ // Verified job/run wakes that activate a task are task steps too. Verification must happen
238
+ // first: routing directly from user-controlled wake text would grant task-only tools.
239
+ const taskStep = await prepareTaskStep(turn.event, runner);
240
+ if (taskStep) {
241
+ await baseCtx.close();
242
+ turn.event = { ...turn.event, text: taskStep.brief };
243
+ baseCtx = createDingTalkContext(turn.event, bot, store, "none");
244
+ turn.baseCtx = baseCtx;
245
+ ctx = muteChannelContext(baseCtx);
246
+ }
247
+ if (!backgroundOnly && !taskStep)
248
+ ctx.primeCard(1500);
249
+ const result = await runner.run(ctx, store);
250
+ turn.mergedWakesHandled = result.stopReason !== "aborted" && result.stopReason !== "error";
251
+ if (taskStep)
252
+ await finishTaskStep(turn.event.channelId, taskStep.taskId, bot);
253
+ if (result.stopReason === "aborted" && runner.getTurnStatus().stopRequested) {
254
+ log.logInfoEvent("agent.turn.stopped", "Turn stopped", { channelId: turn.event.channelId });
255
+ }
256
+ };
257
+ /** Always runs: close delivery, settle the dispatch records, release the turn, nudge the task driver. */
258
+ const finishTurn = async (turn, runner) => {
259
+ const { event } = turn;
260
+ await turn.baseCtx?.close().catch((error) => {
261
+ log.logWarn("delivery.close.failed", "Delivery close failed", {
262
+ channelId: event.channelId,
263
+ reason: errorMessage(error),
264
+ });
265
+ });
266
+ if (turn.structuredWakeFinalized)
267
+ await getDurableDispatch()?.markCompleted(event.dispatchId);
268
+ else
269
+ await getDurableDispatch()?.markRetryable(event.dispatchId);
270
+ // A stopped turn has not finished handling its merged notifications. Release their
271
+ // claims even if /stop's asynchronous cancelChannel reset raced admission or failed.
272
+ const stopped = !turn.mergedWakesHandled || runner.getTurnStatus().stopRequested;
273
+ for (const absorbedId of turn.absorbedDispatchIds) {
274
+ if (stopped)
275
+ await getDurableDispatch()?.markRetryable(absorbedId);
276
+ else
277
+ await getDurableDispatch()?.markCompleted(absorbedId);
278
+ }
279
+ runner.endTurn();
280
+ // A finished turn may have written task files; rescan now so `outcome: continue`
281
+ // queues the next step immediately instead of waiting out the current sleep.
282
+ getTaskDriver().nudge?.();
283
+ };
284
+ const runEventTurn = async (inboundEvent, bot, isEvent) => {
285
+ if (isShuttingDown()) {
286
+ log.logInfoEvent("runtime.shutdown.event_ignored", "Event ignored during shutdown", {
287
+ channelId: inboundEvent.channelId,
288
+ });
289
+ return;
290
+ }
291
+ const runner = getRunner(inboundEvent.channelId);
292
+ const turn = await admitTurn(inboundEvent, runner);
293
+ if (!turn)
294
+ return;
295
+ const task = (async () => {
296
+ try {
297
+ await executeTurn(turn, runner, bot, Boolean(isEvent));
298
+ }
299
+ catch (err) {
300
+ log.logEvent("error", "agent.turn.failed", "Turn failed", {
301
+ ctx: { channelId: turn.event.channelId, userName: turn.event.userName },
302
+ fields: { error: errorMessage(err) },
303
+ });
304
+ }
305
+ finally {
306
+ await finishTurn(turn, runner);
307
+ }
308
+ })();
309
+ activeTasks.add(task);
310
+ try {
311
+ await task;
312
+ }
313
+ finally {
314
+ activeTasks.delete(task);
315
+ }
316
+ };
317
+ return runEventTurn;
318
+ }
@@ -0,0 +1,18 @@
1
+ import type { ChannelEvent } from "../channel/channel-event.js";
2
+ /**
3
+ * Consumer-side merging of completion wakes. K parallel delegations (or background jobs) used to
4
+ * settle into K separate main-agent turns, each re-reading the whole session to handle one result
5
+ * — and with the event queue capped at a handful of items, the rest waited out a 30s+ retry. Now
6
+ * the turn that starts one completion wake also takes every other one still waiting for this
7
+ * channel, so results that arrive while the channel is busy are handled together in the next turn.
8
+ * Nothing is delayed to make that happen: the first result still wakes the channel immediately.
9
+ *
10
+ * Only chat-level wakes merge. A task-bound wake carries `internalWake` and goes through its own
11
+ * claim (`task-wake.ts`), which already lets sibling wakes of one fan-out drop out once the task
12
+ * is reopened.
13
+ */
14
+ /** The merged turn's prompt grows with every result's tail; past this many it is better split. */
15
+ export declare const MAX_COALESCED_WAKES = 6;
16
+ export declare function isCoalescableWake(event: ChannelEvent): boolean;
17
+ /** The primary wake keeps its own text (and `[KIND:id]` tag) first; the others follow it. */
18
+ export declare function mergeCompletionWakes(primary: ChannelEvent, others: ChannelEvent[]): ChannelEvent;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Consumer-side merging of completion wakes. K parallel delegations (or background jobs) used to
3
+ * settle into K separate main-agent turns, each re-reading the whole session to handle one result
4
+ * — and with the event queue capped at a handful of items, the rest waited out a 30s+ retry. Now
5
+ * the turn that starts one completion wake also takes every other one still waiting for this
6
+ * channel, so results that arrive while the channel is busy are handled together in the next turn.
7
+ * Nothing is delayed to make that happen: the first result still wakes the channel immediately.
8
+ *
9
+ * Only chat-level wakes merge. A task-bound wake carries `internalWake` and goes through its own
10
+ * claim (`task-wake.ts`), which already lets sibling wakes of one fan-out drop out once the task
11
+ * is reopened.
12
+ */
13
+ /** The merged turn's prompt grows with every result's tail; past this many it is better split. */
14
+ export const MAX_COALESCED_WAKES = 6;
15
+ const COMPLETION_WAKE_ID = /^(subagent|job):.+:done$/;
16
+ export function isCoalescableWake(event) {
17
+ return !event.internalWake && typeof event.dispatchId === "string" && COMPLETION_WAKE_ID.test(event.dispatchId);
18
+ }
19
+ /** The primary wake keeps its own text (and `[KIND:id]` tag) first; the others follow it. */
20
+ export function mergeCompletionWakes(primary, others) {
21
+ if (others.length === 0)
22
+ return primary;
23
+ const header = `[${others.length} more completion wake(s) arrived while this channel was busy and are delivered with the one above. ` +
24
+ "Handle all of them in this turn; reply with exactly [SILENT] only if none of them needs a follow-up.]";
25
+ return {
26
+ ...primary,
27
+ text: [primary.text, header, ...others.map((event) => event.text)].join("\n\n---\n\n"),
28
+ };
29
+ }
@@ -4,8 +4,29 @@ export interface BlockMessageDetail {
4
4
  value: string;
5
5
  }
6
6
  /**
7
- * Shared scaffold for a guard's user/model-facing block message: `"<Subject> blocked [category]"`
7
+ * Shared scaffold for a guard's model-facing block message: `"<Subject> blocked [category]"`
8
8
  * followed by one line per detail. Used by both the path guard and the command guard so their
9
9
  * wording does not drift line by line as each grows its own detail set.
10
10
  */
11
11
  export declare function formatBlockMessage(subject: string, category: string | undefined, details: BlockMessageDetail[]): string;
12
+ export type GuardKind = "path" | "command" | "network";
13
+ /** What a guard refused, in structured form — the user-facing rendering is built from this. */
14
+ export interface GuardBlock {
15
+ guard: GuardKind;
16
+ category?: string;
17
+ /** What was refused: the resolved path, the command, or the URL. */
18
+ target: string;
19
+ /** Path guard only. */
20
+ operation?: "read" | "write";
21
+ }
22
+ /**
23
+ * A guard refusal (spec 053, D5.2). Its `message` is the model-facing English text, unchanged —
24
+ * it steers the model to explain the intent to the user. `blocked` carries the same refusal as
25
+ * data, so the chat can show a short Chinese line instead of the model's text.
26
+ */
27
+ export declare class GuardBlockedError extends Error {
28
+ readonly blocked: GuardBlock;
29
+ constructor(message: string, blocked: GuardBlock);
30
+ }
31
+ /** The one chat line for a guard refusal, e.g. `已拦截:写入允许范围以外的路径 \`/x/y\`(…)`. */
32
+ export declare function renderGuardBlockForUser(block: GuardBlock): string;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Shared scaffold for a guard's user/model-facing block message: `"<Subject> blocked [category]"`
2
+ * Shared scaffold for a guard's model-facing block message: `"<Subject> blocked [category]"`
3
3
  * followed by one line per detail. Used by both the path guard and the command guard so their
4
4
  * wording does not drift line by line as each grows its own detail set.
5
5
  */
@@ -10,3 +10,68 @@ export function formatBlockMessage(subject, category, details) {
10
10
  }
11
11
  return lines.join("\n");
12
12
  }
13
+ /**
14
+ * A guard refusal (spec 053, D5.2). Its `message` is the model-facing English text, unchanged —
15
+ * it steers the model to explain the intent to the user. `blocked` carries the same refusal as
16
+ * data, so the chat can show a short Chinese line instead of the model's text.
17
+ */
18
+ export class GuardBlockedError extends Error {
19
+ constructor(message, blocked) {
20
+ super(message);
21
+ this.blocked = blocked;
22
+ this.name = "GuardBlockedError";
23
+ }
24
+ }
25
+ const PATH_BLOCK = {
26
+ "outside-allowed-roots": (op) => `${op}允许范围以外的路径`,
27
+ "system-path": (op) => `${op}系统路径`,
28
+ "sensitive-read-path": (op) => `${op}敏感路径`,
29
+ "sensitive-write-path": (op) => `${op}敏感路径`,
30
+ "symlink-write": () => "通过符号链接写入",
31
+ "configured-deny": (op) => `${op} security.json 禁止的路径`,
32
+ };
33
+ const COMMAND_BLOCK = {
34
+ "destructive-file-op": "属于破坏性文件操作",
35
+ "system-manipulation": "会修改系统配置",
36
+ "privilege-escalation": "涉及提权",
37
+ "process-manipulation": "会操作其他进程",
38
+ "network-abuse": "属于高风险网络操作",
39
+ "container-escape": "可能突破容器隔离",
40
+ obfuscation: "包含混淆或动态拼接的内容",
41
+ "configured-command-deny": "被 security.json 禁止",
42
+ };
43
+ /** Network refusals a deployer can lift in security.json; the rest are just unreachable URLs. */
44
+ const NETWORK_BLOCK = {
45
+ "private-address": { reason: "指向内网地址", adjustable: true },
46
+ "blocked-host": { reason: "是被禁止访问的主机", adjustable: true },
47
+ "dns-failure": { reason: "主机名无法解析", adjustable: false },
48
+ "invalid-url": { reason: "不是有效的网址", adjustable: false },
49
+ "unsupported-scheme": { reason: "使用了不支持的协议", adjustable: false },
50
+ "missing-host": { reason: "缺少主机名", adjustable: false },
51
+ };
52
+ function clipTarget(target, max) {
53
+ const flat = target.replace(/\s+/g, " ").trim();
54
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
55
+ }
56
+ const ADJUST_HINT = "(如需放行,由部署者调整 security.json)";
57
+ /** The one chat line for a guard refusal, e.g. `已拦截:写入允许范围以外的路径 \`/x/y\`(…)`. */
58
+ export function renderGuardBlockForUser(block) {
59
+ switch (block.guard) {
60
+ case "path": {
61
+ const op = block.operation === "write" ? "写入" : "读取";
62
+ const what = (block.category ? PATH_BLOCK[block.category] : undefined)?.(op) ?? `${op}受保护的路径`;
63
+ return `已拦截:${what} \`${clipTarget(block.target, 160)}\`${ADJUST_HINT}`;
64
+ }
65
+ case "command": {
66
+ const why = (block.category ? COMMAND_BLOCK[block.category] : undefined) ?? "属于高危操作";
67
+ return `已拦截:命令 \`${clipTarget(block.target, 80)}\` ${why}${ADJUST_HINT}`;
68
+ }
69
+ case "network": {
70
+ const known = block.category ? NETWORK_BLOCK[block.category] : undefined;
71
+ const url = `\`${clipTarget(block.target, 120)}\``;
72
+ if (known && !known.adjustable)
73
+ return `无法访问 ${url}:${known.reason}`;
74
+ return `已拦截:访问 ${url}${known ? ` ${known.reason}` : ""}${ADJUST_HINT}`;
75
+ }
76
+ }
77
+ }
@@ -1,3 +1,7 @@
1
+ /**
2
+ * The command guard: decides whether a shell command may run, against the configured allow/deny
3
+ * rules and a wrapper-aware scan of every place a command can start.
4
+ */
1
5
  import { basename } from "node:path";
2
6
  import { stripNullAndNormalize } from "../shared/text-utils.js";
3
7
  const WHITESPACE = /\s+/;
@@ -1,3 +1,4 @@
1
+ import { GuardBlockedError } from "./block-message.js";
1
2
  import type { SecurityConfig } from "./types.js";
2
3
  type ValidationStage = "request" | "redirect";
3
4
  export interface NetworkGuardContext {
@@ -8,7 +9,7 @@ export interface ValidatedNetworkTarget {
8
9
  hostname: string;
9
10
  resolvedAddress?: string;
10
11
  }
11
- export declare class NetworkGuardError extends Error {
12
+ export declare class NetworkGuardError extends GuardBlockedError {
12
13
  readonly url: string;
13
14
  readonly stage: ValidationStage;
14
15
  readonly category: string;
@@ -1,9 +1,14 @@
1
+ /**
2
+ * The network guard for the web tools: URL and redirect validation, and rejection of private,
3
+ * loopback and link-local targets (including IPv4-mapped IPv6).
4
+ */
1
5
  import { lookup } from "node:dns/promises";
2
6
  import { isIP } from "node:net";
3
7
  import { errorMessage } from "../shared/text-utils.js";
4
- export class NetworkGuardError extends Error {
8
+ import { GuardBlockedError } from "./block-message.js";
9
+ export class NetworkGuardError extends GuardBlockedError {
5
10
  constructor(options) {
6
- super(options.message);
11
+ super(options.message, { guard: "network", category: options.category, target: options.url });
7
12
  this.name = "NetworkGuardError";
8
13
  this.url = options.url;
9
14
  this.stage = options.stage;
@@ -1,4 +1,4 @@
1
- import { formatBlockMessage } from "./block-message.js";
1
+ import { formatBlockMessage, GuardBlockedError } from "./block-message.js";
2
2
  import { logSecurityEvent } from "./logger.js";
3
3
  import { guardPath } from "./path-guard.js";
4
4
  function formatPathBlockMessage(resolvedPath, category, reason) {
@@ -32,7 +32,7 @@ export async function checkPathGuard(rawPath, operation, securityConfig, securit
32
32
  category: guardResult.category,
33
33
  reason: guardResult.reason,
34
34
  });
35
- throw new Error(formatPathBlockMessage(guardResult.resolvedPath, guardResult.category, guardResult.reason));
35
+ throw new GuardBlockedError(formatPathBlockMessage(guardResult.resolvedPath, guardResult.category, guardResult.reason), { guard: "path", category: guardResult.category, target: guardResult.resolvedPath ?? rawPath, operation });
36
36
  }
37
37
  // `guardPath` always populates `resolvedPath` on an allowed result (see D1.1 above).
38
38
  return guardResult.resolvedPath;
@@ -1,3 +1,7 @@
1
+ /**
2
+ * The path guard: resolves a requested path once against the project scope and the read/write allow and
3
+ * deny lists, and returns the resolved path that file tools must then use.
4
+ */
1
5
  import { existsSync, lstatSync, realpathSync } from "node:fs";
2
6
  import { homedir, tmpdir } from "node:os";
3
7
  import { basename, dirname, isAbsolute, join, normalize, resolve } from "node:path";
@@ -37,8 +37,7 @@ export interface SecurityConfig {
37
37
  };
38
38
  }
39
39
  /**
40
- * Every top-level `security.json` key, read by `test/config-reference-coverage.test.ts` to check
41
- * that `docs/security.md` still mentions each one. Kept in sync with `SecurityConfig` by
40
+ * Every top-level `security.json` key. Kept in sync with `SecurityConfig` by
42
41
  * `satisfies` (rejects an extra/misspelled entry) and `AssertNoMissingKeys` (rejects a field with
43
42
  * no entry here) — both at `npm run typecheck`.
44
43
  */
@@ -1,6 +1,5 @@
1
1
  /**
2
- * Every top-level `security.json` key, read by `test/config-reference-coverage.test.ts` to check
3
- * that `docs/security.md` still mentions each one. Kept in sync with `SecurityConfig` by
2
+ * Every top-level `security.json` key. Kept in sync with `SecurityConfig` by
4
3
  * `satisfies` (rejects an extra/misspelled entry) and `AssertNoMissingKeys` (rejects a field with
5
4
  * no entry here) — both at `npm run typecheck`.
6
5
  */
@@ -3,7 +3,7 @@
3
3
  * the result to a `const` typed `true` (then `void` it to satisfy `noUnusedLocals`): if `K` is
4
4
  * missing any key of `T`, the check's type becomes `never` and the assignment fails to
5
5
  * typecheck. This is what keeps a documentation-coverage test's key list (e.g.
6
- * `SETTINGS_TOP_LEVEL_KEYS` in `settings.ts`) from silently drifting out of sync with the
6
+ * `SETTINGS_TOP_LEVEL_KEYS` in `config/settings.ts`) from silently drifting out of sync with the
7
7
  * interface it documents when a field is added — `npm run typecheck` catches it, not a human
8
8
  * remembering to update two places.
9
9
  *
@@ -1,5 +1,17 @@
1
1
  /** Render a millisecond duration as compact human text (`"42s"`, `"3m7s"`). */
2
2
  export declare function formatDuration(ms: number): string;
3
+ /**
4
+ * User-facing elapsed time in Chinese, two units at most (`42秒`, `1分02秒`, `3小时05分`, `2天3小时`) —
5
+ * for "how long did this take / has this been running" in replies, receipts and cards (spec 053,
6
+ * D4). Model-facing text keeps `formatDuration` above.
7
+ */
8
+ export declare function formatElapsedZh(ms: number): string;
9
+ /**
10
+ * A coarse, single-unit span in Chinese (`30 秒`, `12 分钟`, `3 小时`, `2 天`) — for "how far away is
11
+ * this deadline", where a second unit is noise. Rounds within a unit and promotes to the next unit
12
+ * when rounding reaches it, so the output never reads `60 分钟` or `24 小时`.
13
+ */
14
+ export declare function formatSpanZh(ms: number): string;
3
15
  /**
4
16
  * Coerce an untrusted numeric config/request value into an integer within `[minimum, maximum]`,
5
17
  * falling back to `fallback` for anything not a finite number or out of range. Shared by the
@@ -6,6 +6,43 @@ export function formatDuration(ms) {
6
6
  return `${seconds}s`;
7
7
  return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
8
8
  }
9
+ /**
10
+ * User-facing elapsed time in Chinese, two units at most (`42秒`, `1分02秒`, `3小时05分`, `2天3小时`) —
11
+ * for "how long did this take / has this been running" in replies, receipts and cards (spec 053,
12
+ * D4). Model-facing text keeps `formatDuration` above.
13
+ */
14
+ export function formatElapsedZh(ms) {
15
+ const totalSeconds = Math.max(0, Math.floor(ms / 1000));
16
+ if (totalSeconds < 60)
17
+ return `${totalSeconds}秒`;
18
+ const totalMinutes = Math.floor(totalSeconds / 60);
19
+ if (totalMinutes < 60)
20
+ return `${totalMinutes}分${String(totalSeconds % 60).padStart(2, "0")}秒`;
21
+ const totalHours = Math.floor(totalMinutes / 60);
22
+ if (totalHours < 24) {
23
+ const minutes = totalMinutes % 60;
24
+ return minutes > 0 ? `${totalHours}小时${String(minutes).padStart(2, "0")}分` : `${totalHours}小时`;
25
+ }
26
+ const hours = totalHours % 24;
27
+ return hours > 0 ? `${Math.floor(totalHours / 24)}天${hours}小时` : `${Math.floor(totalHours / 24)}天`;
28
+ }
29
+ /**
30
+ * A coarse, single-unit span in Chinese (`30 秒`, `12 分钟`, `3 小时`, `2 天`) — for "how far away is
31
+ * this deadline", where a second unit is noise. Rounds within a unit and promotes to the next unit
32
+ * when rounding reaches it, so the output never reads `60 分钟` or `24 小时`.
33
+ */
34
+ export function formatSpanZh(ms) {
35
+ const seconds = Math.max(0, Math.round(ms / 1000));
36
+ if (seconds < 60)
37
+ return `${seconds} 秒`;
38
+ const minutes = Math.round(ms / 60_000);
39
+ if (minutes < 60)
40
+ return `${minutes} 分钟`;
41
+ const hours = Math.round(ms / 3_600_000);
42
+ if (hours < 24)
43
+ return `${hours} 小时`;
44
+ return `${Math.round(ms / 86_400_000)} 天`;
45
+ }
9
46
  /**
10
47
  * Coerce an untrusted numeric config/request value into an integer within `[minimum, maximum]`,
11
48
  * falling back to `fallback` for anything not a finite number or out of range. Shared by the