@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,3 +1,7 @@
1
+ /**
2
+ * `/events`: list, show, delete and history of scheduled events, confined to `workspace/events/` and
3
+ * the event history.
4
+ */
1
5
  import { existsSync } from "fs";
2
6
  import { readdir, readFile, unlink } from "fs/promises";
3
7
  import { join } from "path";
@@ -5,7 +9,8 @@ import { renderSubcommandUsage } from "../commands/catalog.js";
5
9
  import { capReply } from "../commands/reply-limits.js";
6
10
  import { normalizeSafeId, resolveSafeIdPath } from "../shared/safe-id.js";
7
11
  import { errorMessage, eventNameFromFilename, clipText as sharedClipText } from "../shared/text-utils.js";
8
- import { describeEventPayload, parseScheduledEventContent, } from "./events.js";
12
+ import { describeEventPayload, parseScheduledEventContent } from "./parse.js";
13
+ import { EventDefinitionError, validateScheduledEvent } from "./validation.js";
9
14
  const EVENT_NAME_PATTERN = /^[A-Za-z0-9._-]+$/;
10
15
  const DEFAULT_HISTORY_LIMIT = 20;
11
16
  const TEXT_PREVIEW_MAX_CHARS = 100;
@@ -37,7 +42,7 @@ export function parseEventsCommand(args) {
37
42
  throw new Error("用法:/events history [name]");
38
43
  return name ? { action, name } : { action };
39
44
  }
40
- throw new Error(`未知的 /events 动作:${action}`);
45
+ throw new Error(`未知子命令 \`${action}\`。`);
41
46
  }
42
47
  function eventsDir(workspaceDir) {
43
48
  return join(workspaceDir, "events");
@@ -56,60 +61,91 @@ function clipText(text, maxChars = TEXT_PREVIEW_MAX_CHARS) {
56
61
  return sharedClipText(text, maxChars, { headRatio: 1, omitHint: "...", collapseWhitespace: true });
57
62
  }
58
63
  function formatEventSummary(name, event) {
59
- const lines = [`**${name}**`, `- 类型:${event.type}`, `- channelId:${event.channelId}`];
64
+ const lines = [`**${name}**`, `- 类型:${event.type}`, `- 频道(channelId):${event.channelId}`];
60
65
  if (event.type === "one-shot") {
61
66
  lines.push(`- 触发时间:${event.at}`);
62
67
  }
63
68
  if (event.type === "periodic") {
64
- lines.push(`- schedule:${event.schedule}`);
69
+ lines.push(`- 时间表(schedule):${event.schedule}`);
65
70
  }
66
71
  lines.push(`- 内容:${clipText(describeEventPayload(event))}`);
67
72
  return lines.join("\n");
68
73
  }
74
+ /**
75
+ * Why a definition is invalid, in the user's terms (spec 053, D2). The error's own message is
76
+ * English text for the model (`event_manage`), so it is never pasted here.
77
+ */
78
+ const PROBLEM_TEXT = {
79
+ malformed: "文件不是有效的 JSON",
80
+ "missing-field": "缺少必填字段(type、channelId、at 或 schedule,以及 text 或 task 之一)",
81
+ payload: "text 和 task 必须恰好填一个",
82
+ "task-template": "task 模板无效",
83
+ "pre-action": "preAction 配置无效",
84
+ immediate: "不再支持 immediate 类型",
85
+ "unknown-type": "未知的事件类型",
86
+ "one-shot-time": "at 不是有效的时间",
87
+ "one-shot-too-soon": "at 距现在不足 2 分钟",
88
+ "one-shot-too-far": "at 超过约 24.8 天,更远的时间请改用 periodic",
89
+ "cron-invalid": "schedule 不是有效的 cron 表达式",
90
+ "cadence-too-frequent": "触发过于频繁(没有 preAction 时至少间隔 30 分钟,有 preAction 时至少 5 分钟)",
91
+ "pre-action-blocked": "preAction 命令被安全策略拦截",
92
+ };
93
+ function describeEventProblem(error, name) {
94
+ if (error instanceof EventDefinitionError)
95
+ return PROBLEM_TEXT[error.kind];
96
+ return `定义无效,用 \`/events show ${name}\` 查看`;
97
+ }
98
+ const EMPTY_EVENTS = "暂无定时事件。\n在对话里告诉我要定时做什么,我会创建事件。";
69
99
  async function listEvents(workspaceDir) {
70
100
  const dir = eventsDir(workspaceDir);
71
- if (!existsSync(dir)) {
72
- return "**定时事件**\n\n没有找到 events 目录。";
73
- }
101
+ if (!existsSync(dir))
102
+ return EMPTY_EVENTS;
74
103
  const filenames = (await readdir(dir)).filter((filename) => filename.endsWith(".json")).sort();
75
- if (filenames.length === 0) {
76
- return "**定时事件**\n\n暂无事件文件。";
77
- }
104
+ if (filenames.length === 0)
105
+ return EMPTY_EVENTS;
78
106
  const blocks = [];
79
107
  for (const filename of filenames) {
80
108
  const eventPath = join(dir, filename);
81
109
  const name = eventNameFromFilename(filename);
82
110
  try {
83
111
  const event = parseScheduledEventContent(await readFile(eventPath, "utf-8"), filename);
112
+ // The same definition rules the watcher applies, so "listed as fine" means "will run".
113
+ // The lead-time rule is creation-only (an overdue one-shot is a legitimate recovery).
114
+ validateScheduledEvent(event, { enforceOneShotLead: false });
84
115
  blocks.push(formatEventSummary(name, event));
85
116
  }
86
117
  catch (error) {
87
- const message = errorMessage(error);
88
- blocks.push(`**${name}**\n- ⚠ 无效:${message}`);
118
+ blocks.push(`**${name}**\n- ⚠️ 无效:${describeEventProblem(error, name)}`);
89
119
  }
90
120
  }
91
121
  return capReply(`**定时事件**\n\n${blocks.join("\n\n")}`, {
92
122
  nextStepHint: "用 `/events show <name>` 查看单个事件",
93
123
  }).text;
94
124
  }
125
+ function eventNotFound(eventName) {
126
+ return `未找到事件 \`${eventName}\`。用 \`/events list\` 查看。`;
127
+ }
95
128
  async function showEvent(workspaceDir, name) {
96
129
  const { eventName, eventPath } = resolveEventPath(workspaceDir, name);
97
- if (!existsSync(eventPath)) {
98
- return `找不到事件:${eventName}`;
99
- }
130
+ if (!existsSync(eventPath))
131
+ return eventNotFound(eventName);
100
132
  const raw = await readFile(eventPath, "utf-8");
101
- const parsed = JSON.parse(raw);
102
- return `**事件 ${eventName}**
103
-
104
- \`\`\`json
105
- ${JSON.stringify(parsed, null, 2)}
106
- \`\`\``;
133
+ let body;
134
+ try {
135
+ body = JSON.stringify(JSON.parse(raw), null, 2);
136
+ }
137
+ catch {
138
+ // Show the bytes as they are: an unparseable file is exactly the case the user needs to see.
139
+ body = raw;
140
+ }
141
+ return capReply(`**事件 ${eventName}**\n\n\`\`\`json\n${body}\n\`\`\``, {
142
+ nextStepHint: `完整文件在 \`${eventPath}\``,
143
+ }).text;
107
144
  }
108
145
  async function deleteEvent(workspaceDir, name) {
109
146
  const { eventName, eventPath } = resolveEventPath(workspaceDir, name);
110
- if (!existsSync(eventPath)) {
111
- return `找不到事件:${eventName}`;
112
- }
147
+ if (!existsSync(eventPath))
148
+ return eventNotFound(eventName);
113
149
  // Read before deleting so the reply carries what was removed (review 2026-08-24 §3.4):
114
150
  // an accidental delete stays recoverable from chat history instead of a bare confirmation.
115
151
  let summary;
@@ -121,7 +157,7 @@ async function deleteEvent(workspaceDir, name) {
121
157
  // Unparseable content is still safe to delete; just skip the summary.
122
158
  }
123
159
  await unlink(eventPath);
124
- return summary ? `已删除事件:\n\n${summary}` : `已删除事件:${eventName}`;
160
+ return summary ? `已删除事件:\n\n${summary}` : `已删除事件 \`${eventName}\`。`;
125
161
  }
126
162
  function parseHistoryLine(line) {
127
163
  try {
@@ -135,28 +171,45 @@ function parseHistoryLine(line) {
135
171
  return null;
136
172
  }
137
173
  }
174
+ const HISTORY_ACTION = {
175
+ loaded: "已加载",
176
+ scheduled: "已排程",
177
+ triggered: "已触发",
178
+ skipped: "已跳过",
179
+ enqueued: "已送达频道",
180
+ queue_full: "频道队列已满",
181
+ deleted: "已删除",
182
+ invalid: "无效",
183
+ pre_action_started: "preAction 开始",
184
+ pre_action_passed: "preAction 通过",
185
+ pre_action_blocked: "preAction 未通过",
186
+ pre_action_failed: "preAction 出错",
187
+ cancelled: "已取消",
188
+ };
189
+ const HISTORY_RESULT = { ok: "成功", error: "失败", skipped: "跳过" };
190
+ /** `2026-10-11T14:02:33.000+08:00` → `10-11 14:02`. */
191
+ function minuteStamp(ts) {
192
+ const match = /^\d{4}-(\d{2}-\d{2})T(\d{2}:\d{2})/.exec(ts);
193
+ return match ? `${match[1]} ${match[2]}` : ts;
194
+ }
195
+ /** One flat bullet per record; the operator detail (`reason`) is quoted as-is, it is a log entry. */
138
196
  function formatHistoryRecord(record) {
139
- const details = [];
140
- if (record.channelId)
141
- details.push(`- channelId:${record.channelId}`);
142
- if (record.schedule)
143
- details.push(`- schedule:${record.schedule}`);
144
- if (record.at)
145
- details.push(`- 触发时间:${record.at}`);
197
+ const action = HISTORY_ACTION[record.action] ?? record.action;
198
+ const result = HISTORY_RESULT[record.result] ?? record.result;
199
+ const bits = [`${minuteStamp(record.ts)} ${record.eventName}`, `${action}(${result})`];
146
200
  if (record.nextRunAt)
147
- details.push(`- 下次运行:${record.nextRunAt}`);
201
+ bits.push(`下次 ${minuteStamp(record.nextRunAt)}`);
148
202
  if (record.reason)
149
- details.push(`- 原因:${record.reason}`);
150
- if (record.textPreview)
151
- details.push(`- 内容:${clipText(record.textPreview)}`);
152
- const header = `**${record.ts} ${record.eventName}** ${record.action} · ${record.result}`;
153
- return details.length > 0 ? `${header}\n${details.join("\n")}` : header;
203
+ bits.push(`详情:\`${clipText(record.reason.replace(/`/g, "'"))}\``);
204
+ return `- ${bits.join(" · ")}`;
154
205
  }
155
206
  async function showHistory(historyPath, name) {
156
207
  const eventName = name ? normalizeEventName(name) : undefined;
157
- if (!existsSync(historyPath)) {
158
- return "**事件历史**\n\n暂无事件历史。";
159
- }
208
+ const empty = eventName
209
+ ? `暂无事件 \`${eventName}\` 的触发记录。\n事件触发后会记录在这里。`
210
+ : "暂无事件触发记录。\n事件触发后会记录在这里。";
211
+ if (!existsSync(historyPath))
212
+ return empty;
160
213
  const raw = await readFile(historyPath, "utf-8");
161
214
  const records = raw
162
215
  .split("\n")
@@ -167,11 +220,12 @@ async function showHistory(historyPath, name) {
167
220
  .filter((record) => !eventName || record.eventName === eventName)
168
221
  .slice(-DEFAULT_HISTORY_LIMIT)
169
222
  .reverse();
170
- if (records.length === 0) {
171
- return eventName ? `**事件历史**\n\n未找到事件 ${eventName} 的历史。` : "**事件历史**\n\n暂无事件历史。";
172
- }
223
+ if (records.length === 0)
224
+ return empty;
173
225
  const suffix = eventName ? ` · ${eventName}` : "";
174
- return `**事件历史**${suffix}\n\n${records.map(formatHistoryRecord).join("\n\n")}`;
226
+ return capReply(`**事件历史**${suffix}(最近 ${records.length} 条)\n\n${records.map(formatHistoryRecord).join("\n")}`, {
227
+ nextStepHint: `用 \`/events history <name>\` 只看一个事件;完整记录在 \`${historyPath}\``,
228
+ }).text;
175
229
  }
176
230
  export async function handleEventsCommand(options) {
177
231
  let command;
@@ -0,0 +1,14 @@
1
+ import type { ScheduledEvent } from "./types.js";
2
+ /** The one-line description of what an event delivers, for history records and listings. */
3
+ export declare function describeEventPayload(event: Pick<ScheduledEvent, "text" | "task">): string;
4
+ export declare function parseScheduledEventContent(content: string, filename: string): ScheduledEvent;
5
+ /**
6
+ * Stable, provenance-derived dispatch id (spec 031, D1).
7
+ *
8
+ * The identity of a wake is its *occurrence*, never the moment it happened to be executed.
9
+ * A one-shot keyed on its own `at` therefore lands on the same durable record whether it
10
+ * arrives via the outbox retry or via the post-restart file recovery path, so the two
11
+ * independent retry systems can no longer deliver the same occurrence twice. A live periodic
12
+ * occurrence is keyed on Croner's callback start time, so its durable outbox retries collapse
13
+ * while the next callback produces a genuinely new record.
14
+ */
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Parsing a scheduled-event definition file into a `ScheduledEvent`: the payload (text or task
3
+ * template), the optional pre-action gate and the schedule. Pure — the watcher owns reading files.
4
+ */
5
+ import { errorMessage } from "../shared/text-utils.js";
6
+ import { isPlainObject } from "../shared/type-guards.js";
7
+ import { validateTaskContractInput } from "../tasks/contract-input.js";
8
+ import { EventDefinitionError } from "./validation.js";
9
+ /** The one-line description of what an event delivers, for history records and listings. */
10
+ export function describeEventPayload(event) {
11
+ return event.task ? `任务模板:${event.task.title}` : (event.text ?? "");
12
+ }
13
+ function readRequiredString(data, field, filename) {
14
+ const value = data[field];
15
+ if (typeof value !== "string" || value.trim().length === 0) {
16
+ throw new EventDefinitionError("missing-field", `Missing required fields (type, channelId, and text or task) in ${filename}`);
17
+ }
18
+ return value;
19
+ }
20
+ /** `text` xor `task`: a chat message, or a template for a task instance (spec 052, D2). */
21
+ function parsePayload(data, filename) {
22
+ const hasText = typeof data.text === "string" && data.text.trim().length > 0;
23
+ const hasTask = data.task !== undefined;
24
+ if (hasText === hasTask) {
25
+ throw new EventDefinitionError("payload", `An event needs exactly one of 'text' (a chat message) or 'task' (a task template) in ${filename}`);
26
+ }
27
+ if (hasText)
28
+ return { text: data.text };
29
+ try {
30
+ return { task: validateTaskContractInput(data.task) };
31
+ }
32
+ catch (error) {
33
+ throw new EventDefinitionError("task-template", `Invalid 'task' template in ${filename}: ${errorMessage(error)}`);
34
+ }
35
+ }
36
+ function parsePreAction(data, filename) {
37
+ if (!data.preAction)
38
+ return undefined;
39
+ if (!isPlainObject(data.preAction)) {
40
+ throw new EventDefinitionError("pre-action", `Invalid 'preAction' field in ${filename}, expected an object`);
41
+ }
42
+ const action = data.preAction;
43
+ if (action.type !== "bash") {
44
+ throw new EventDefinitionError("pre-action", `Unsupported preAction type '${String(action.type)}' in ${filename}, only 'bash' is supported`);
45
+ }
46
+ if (typeof action.command !== "string" || action.command.trim().length === 0) {
47
+ throw new EventDefinitionError("pre-action", `Missing or empty 'preAction.command' in ${filename}`);
48
+ }
49
+ if (action.timeout !== undefined) {
50
+ if (typeof action.timeout !== "number" || !Number.isFinite(action.timeout) || action.timeout <= 0) {
51
+ throw new EventDefinitionError("pre-action", `Invalid 'preAction.timeout' in ${filename}, expected a positive millisecond value`);
52
+ }
53
+ }
54
+ return {
55
+ type: "bash",
56
+ command: action.command,
57
+ ...(typeof action.timeout === "number" ? { timeout: action.timeout } : {}),
58
+ };
59
+ }
60
+ export function parseScheduledEventContent(content, filename) {
61
+ let data;
62
+ try {
63
+ data = JSON.parse(content);
64
+ }
65
+ catch (error) {
66
+ throw new EventDefinitionError("malformed", `Invalid JSON in ${filename}: ${errorMessage(error)}`);
67
+ }
68
+ if (!isPlainObject(data)) {
69
+ throw new EventDefinitionError("missing-field", `Missing required fields (type, channelId, and text or task) in ${filename}`);
70
+ }
71
+ const type = readRequiredString(data, "type", filename);
72
+ const channelId = readRequiredString(data, "channelId", filename);
73
+ const payload = parsePayload(data, filename);
74
+ const preAction = parsePreAction(data, filename);
75
+ switch (type) {
76
+ // Removed in spec 031 (D4): an event that fires the moment it is written is a
77
+ // self-triggering loop with no gate in front of it, and nothing in the runtime produced
78
+ // one. Rejecting it here — rather than only in `event_manage` — is what makes the guard
79
+ // enforced, since the events directory is agent-writable.
80
+ case "immediate":
81
+ throw new EventDefinitionError("immediate", `Immediate events are no longer supported (${filename}); do the work in the current turn, ` +
82
+ "or schedule a one-shot at least 2 minutes out via event_manage.");
83
+ case "one-shot": {
84
+ if (typeof data.at !== "string" || data.at.trim().length === 0) {
85
+ throw new EventDefinitionError("missing-field", `Missing 'at' field for one-shot event in ${filename}`);
86
+ }
87
+ return { type, channelId, ...payload, at: data.at, ...(preAction ? { preAction } : {}) };
88
+ }
89
+ case "periodic": {
90
+ if (typeof data.schedule !== "string" || data.schedule.trim().length === 0) {
91
+ throw new EventDefinitionError("missing-field", `Missing 'schedule' field for periodic event in ${filename}`);
92
+ }
93
+ return {
94
+ type,
95
+ channelId,
96
+ ...payload,
97
+ schedule: data.schedule,
98
+ ...(preAction ? { preAction } : {}),
99
+ };
100
+ }
101
+ default:
102
+ throw new EventDefinitionError("unknown-type", `Unknown event type '${type}' in ${filename}`);
103
+ }
104
+ }
105
+ /**
106
+ * Stable, provenance-derived dispatch id (spec 031, D1).
107
+ *
108
+ * The identity of a wake is its *occurrence*, never the moment it happened to be executed.
109
+ * A one-shot keyed on its own `at` therefore lands on the same durable record whether it
110
+ * arrives via the outbox retry or via the post-restart file recovery path, so the two
111
+ * independent retry systems can no longer deliver the same occurrence twice. A live periodic
112
+ * occurrence is keyed on Croner's callback start time, so its durable outbox retries collapse
113
+ * while the next callback produces a genuinely new record.
114
+ */
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Scheduled-event shapes: the on-disk definition, history records and the injected callbacks.
3
+ * Types only, shared by validation, parsing and the watcher without forming an import cycle.
4
+ */
5
+ import type { ChannelEvent } from "../channel/channel-event.js";
6
+ import type { TaskCreateInput } from "../tasks/contract-input.js";
7
+ export interface EventAction {
8
+ type: "bash";
9
+ command: string;
10
+ timeout?: number;
11
+ }
12
+ /**
13
+ * What an event delivers when it fires: a chat `text`, or a `task` template that spawns a fresh
14
+ * task instance (spec 052, D2). Exactly one is present — `parseScheduledEventContent` enforces it.
15
+ */
16
+ export interface EventPayload {
17
+ text?: string;
18
+ task?: TaskCreateInput;
19
+ }
20
+ export interface OneShotEvent extends EventPayload {
21
+ type: "one-shot";
22
+ channelId: string;
23
+ at: string;
24
+ preAction?: EventAction;
25
+ }
26
+ export interface PeriodicEvent extends EventPayload {
27
+ type: "periodic";
28
+ channelId: string;
29
+ schedule: string;
30
+ preAction?: EventAction;
31
+ }
32
+ export type ScheduledEvent = OneShotEvent | PeriodicEvent;
33
+ export type EventHistoryAction = "loaded" | "scheduled" | "triggered" | "skipped" | "enqueued" | "queue_full" | "deleted" | "invalid" | "pre_action_started" | "pre_action_passed" | "pre_action_blocked" | "pre_action_failed" | "cancelled";
34
+ export type EventHistoryResult = "ok" | "error" | "skipped";
35
+ export interface EventHistoryRecord {
36
+ ts: string;
37
+ eventName: string;
38
+ eventPath: string;
39
+ eventType: ScheduledEvent["type"] | "unknown";
40
+ channelId?: string;
41
+ action: EventHistoryAction;
42
+ result: EventHistoryResult;
43
+ reason?: string;
44
+ schedule?: string;
45
+ at?: string;
46
+ nextRunAt?: string;
47
+ textPreview?: string;
48
+ preAction?: {
49
+ type: "bash";
50
+ command: string;
51
+ timeoutMs: number;
52
+ exitCode?: number | null;
53
+ durationMs?: number;
54
+ };
55
+ queue?: {
56
+ accepted: boolean;
57
+ };
58
+ }
59
+ /** One occurrence of a template event asking for a task instance (spec 052, D2). */
60
+ export interface SpawnTaskRequest {
61
+ /** The event's name (filename without `.json`); becomes the instance's `origin`. */
62
+ eventName: string;
63
+ channelId: string;
64
+ template: TaskCreateInput;
65
+ /** The moment this occurrence was due — deterministic per occurrence, so a replay maps to the same instance. */
66
+ occurrence: Date;
67
+ }
68
+ export type SpawnTaskResult =
69
+ /** A new instance was created. */
70
+ {
71
+ outcome: "spawned";
72
+ id: string;
73
+ }
74
+ /** This occurrence's instance already exists: an idempotent replay. */
75
+ | {
76
+ outcome: "exists";
77
+ id: string;
78
+ }
79
+ /** Another instance of the same event is still running; the user was told. */
80
+ | {
81
+ outcome: "skipped";
82
+ id: string;
83
+ };
84
+ export interface EventsWatcherOptions {
85
+ historyPath?: string;
86
+ /**
87
+ * Creates the task instance a template event asks for. Injected by the runtime so the events
88
+ * subsystem never reads or writes task files (spec 052, INV-8).
89
+ */
90
+ spawnTask?: (request: SpawnTaskRequest) => Promise<SpawnTaskResult>;
91
+ /** Persist synthetic work before it enters the in-memory channel queue. */
92
+ dispatch?: (event: ChannelEvent) => boolean | Promise<boolean>;
93
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,5 +1,5 @@
1
1
  import type { SecurityConfig } from "../security/types.js";
2
- import type { ScheduledEvent } from "./events.js";
2
+ import type { ScheduledEvent } from "./types.js";
3
3
  /**
4
4
  * Admission rules for scheduled events (spec 031, D4).
5
5
  *
@@ -24,10 +24,21 @@ export declare const MIN_PERIODIC_INTERVAL_MS: number;
24
24
  export declare const MIN_PERIODIC_INTERVAL_WITH_PREACTION_MS: number;
25
25
  /** sanity cap on total scheduled events to keep the directory (and the scheduler) from being flooded. */
26
26
  export declare const MAX_EVENT_FILES = 50;
27
- export declare class EventValidationError extends Error {
27
+ /**
28
+ * What is wrong with an event definition, as data (spec 053, D2). The error `message` is English
29
+ * and written for the model (`event_manage` returns it as a recoverable rejection); `/events list`
30
+ * renders `kind` in the user's terms instead of pasting that text into the chat.
31
+ */
32
+ export type EventProblemKind = "malformed" | "missing-field" | "payload" | "task-template" | "pre-action" | "immediate" | "unknown-type" | "one-shot-time" | "one-shot-too-soon" | "one-shot-too-far" | "cron-invalid" | "cadence-too-frequent" | "pre-action-blocked";
33
+ /** A definition the file parser rejects. Kept distinct from `EventValidationError`, which the tool treats as model-fixable. */
34
+ export declare class EventDefinitionError extends Error {
35
+ readonly kind: EventProblemKind;
36
+ constructor(kind: EventProblemKind, message: string);
37
+ }
38
+ export declare class EventValidationError extends EventDefinitionError {
28
39
  /** Whether the model can usefully retry with a corrected definition. */
29
40
  readonly recoverable: boolean;
30
- constructor(message: string, recoverable?: boolean);
41
+ constructor(kind: EventProblemKind, message: string, recoverable?: boolean);
31
42
  }
32
43
  export declare function validateOneShotLead(event: ScheduledEvent & {
33
44
  type: "one-shot";
@@ -26,9 +26,17 @@ export const MIN_PERIODIC_INTERVAL_MS = 30 * 60 * 1000;
26
26
  export const MIN_PERIODIC_INTERVAL_WITH_PREACTION_MS = 5 * 60 * 1000;
27
27
  /** sanity cap on total scheduled events to keep the directory (and the scheduler) from being flooded. */
28
28
  export const MAX_EVENT_FILES = 50;
29
- export class EventValidationError extends Error {
30
- constructor(message, recoverable = true) {
29
+ /** A definition the file parser rejects. Kept distinct from `EventValidationError`, which the tool treats as model-fixable. */
30
+ export class EventDefinitionError extends Error {
31
+ constructor(kind, message) {
31
32
  super(message);
33
+ this.kind = kind;
34
+ this.name = "EventDefinitionError";
35
+ }
36
+ }
37
+ export class EventValidationError extends EventDefinitionError {
38
+ constructor(kind, message, recoverable = true) {
39
+ super(kind, message);
32
40
  this.name = "EventValidationError";
33
41
  this.recoverable = recoverable;
34
42
  }
@@ -36,19 +44,19 @@ export class EventValidationError extends Error {
36
44
  export function validateOneShotLead(event, now = Date.now()) {
37
45
  const atTime = parseLocalTime(event.at);
38
46
  if (atTime === undefined) {
39
- throw new EventValidationError(`one-shot 'at' is not a valid local time: ${event.at}`);
47
+ throw new EventValidationError("one-shot-time", `one-shot 'at' is not a valid local time: ${event.at}`);
40
48
  }
41
49
  if (atTime < now + MIN_ONE_SHOT_LEAD_MS) {
42
- throw new EventValidationError("one-shot 'at' must be at least 2 minutes in the future (self-triggering guard).");
50
+ throw new EventValidationError("one-shot-too-soon", "one-shot 'at' must be at least 2 minutes in the future (self-triggering guard).");
43
51
  }
44
52
  }
45
53
  function validateOneShotMaximumDelay(event, now = Date.now()) {
46
54
  const atTime = parseLocalTime(event.at);
47
55
  if (atTime === undefined) {
48
- throw new EventValidationError(`one-shot 'at' is not a valid local time: ${event.at}`);
56
+ throw new EventValidationError("one-shot-time", `one-shot 'at' is not a valid local time: ${event.at}`);
49
57
  }
50
58
  if (atTime - now > MAX_ONE_SHOT_DELAY_MS) {
51
- throw new EventValidationError("one-shot 'at' must be within about 24.8 days; use a periodic event for longer delays.");
59
+ throw new EventValidationError("one-shot-too-far", "one-shot 'at' must be within about 24.8 days; use a periodic event for longer delays.");
52
60
  }
53
61
  }
54
62
  export function validatePeriodicCadence(event) {
@@ -59,7 +67,7 @@ export function validatePeriodicCadence(event) {
59
67
  cron.stop();
60
68
  }
61
69
  catch (error) {
62
- throw new EventValidationError(`Invalid cron schedule "${event.schedule}": ${errorMessage(error)}`);
70
+ throw new EventValidationError("cron-invalid", `Invalid cron schedule "${event.schedule}": ${errorMessage(error)}`);
63
71
  }
64
72
  // A preAction gate makes a tighter cadence safe (the sensor keeps most fires silent);
65
73
  // without one, hold the 30-minute floor so a bare high-frequency cron can't burn tokens.
@@ -68,7 +76,7 @@ export function validatePeriodicCadence(event) {
68
76
  // Fewer than two upcoming runs means no meaningful cadence to rate-limit (e.g. a one-off cron); allow it.
69
77
  for (let i = 1; i < runs.length; i++) {
70
78
  if (runs[i].getTime() - runs[i - 1].getTime() < floorMs) {
71
- throw new EventValidationError(`periodic events must fire no more often than every ${floorMinutes} minutes` +
79
+ throw new EventValidationError("cadence-too-frequent", `periodic events must fire no more often than every ${floorMinutes} minutes` +
72
80
  `${event.preAction ? " (even with a preAction gate)" : "; for tighter checks add a preAction gate (min 5 minutes) instead of a high-frequency cron"}.`);
73
81
  }
74
82
  }
@@ -78,7 +86,7 @@ export function validatePreActionCommand(event, commandGuardConfig) {
78
86
  return;
79
87
  const result = guardCommand(event.preAction.command, commandGuardConfig);
80
88
  if (!result.allowed) {
81
- throw new EventValidationError(`preAction command blocked by guard: ${result.reason ?? "not allowed"}`, false);
89
+ throw new EventValidationError("pre-action-blocked", `preAction command blocked by guard: ${result.reason ?? "not allowed"}`, false);
82
90
  }
83
91
  }
84
92
  /** Apply every admission rule that depends only on the definition itself. */
@@ -0,0 +1,67 @@
1
+ import type { ChannelEventSink } from "../channel/channel-event.js";
2
+ import type { Executor } from "../executor.js";
3
+ import type { SecurityConfig } from "../security/types.js";
4
+ import type { EventsWatcherOptions } from "./types.js";
5
+ export declare class EventsWatcher {
6
+ private eventsDir;
7
+ private bot;
8
+ private executor;
9
+ private commandGuardConfig?;
10
+ private options;
11
+ private timers;
12
+ private crons;
13
+ private debounceTimers;
14
+ private startTime;
15
+ private watcher;
16
+ private started;
17
+ private knownFiles;
18
+ private readonly historyAppender?;
19
+ constructor(eventsDir: string, bot: ChannelEventSink, executor: Executor, commandGuardConfig?: SecurityConfig["commandGuard"] | undefined, options?: EventsWatcherOptions);
20
+ start(): void;
21
+ stop(): void;
22
+ flush(): Promise<void>;
23
+ private ensureHistoryFile;
24
+ private appendHistory;
25
+ private appendEventHistory;
26
+ private debounce;
27
+ private scanExisting;
28
+ private handleFileChange;
29
+ /**
30
+ * Watch callbacks are the top of their own stack, so a rejection here reaches nobody — and
31
+ * `handleFile` can reject: reloading a due one-shot dispatches it inline, and dispatch
32
+ * writes to disk. `scanExisting` already wraps its own calls; this is the same guard for
33
+ * the live path. One bad file must not take the watcher, or the process, down with it.
34
+ */
35
+ private handleFileSafely;
36
+ private handleDelete;
37
+ private cancelScheduled;
38
+ private handleFile;
39
+ private parseEvent;
40
+ /**
41
+ * The admission gate (spec 031, D4). `event_manage` applies the same rules first, but the
42
+ * events directory is agent-writable, so a file that arrived any other way is only ever
43
+ * stopped here. Returns the rejection reason, or undefined when the event may be scheduled.
44
+ */
45
+ private admissionFailure;
46
+ private wasWrittenAfterStart;
47
+ private handleOneShot;
48
+ private handlePeriodic;
49
+ private execute;
50
+ /**
51
+ * Deliver a template event: ask the runtime for a fresh task instance (spec 052, D2). The
52
+ * occurrence is the one this trigger was *due* for — a one-shot's `at`, a periodic's cron tick —
53
+ * so a post-restart replay of the same occurrence lands on the same instance instead of making a
54
+ * second one.
55
+ */
56
+ private spawnTaskInstance;
57
+ private runPreAction;
58
+ private deleteFile;
59
+ private getInvalidMarkerPath;
60
+ private markInvalid;
61
+ private clearInvalidMarker;
62
+ private sleep;
63
+ }
64
+ /**
65
+ * Create and start an events watcher.
66
+ */
67
+ export declare function createEventsWatcher(workspaceDir: string, bot: ChannelEventSink, executor: Executor, commandGuardConfig?: SecurityConfig["commandGuard"], historyPath?: string, dispatch?: EventsWatcherOptions["dispatch"], spawnTask?: EventsWatcherOptions["spawnTask"]): EventsWatcher;