@oyasmi/pipiclaw 0.9.5 → 0.9.6-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 (345) hide show
  1. package/README.en.md +300 -142
  2. package/README.md +295 -140
  3. package/dist/agent/builtin-commands.d.ts +1 -1
  4. package/dist/agent/builtin-commands.js +1 -1
  5. package/dist/agent/channel-runner.d.ts +4 -3
  6. package/dist/agent/channel-runner.js +17 -28
  7. package/dist/agent/maintenance-context.js +2 -2
  8. package/dist/agent/prompt/builder.d.ts +1 -1
  9. package/dist/agent/prompt/builder.js +1 -1
  10. package/dist/agent/prompt/extension.d.ts +1 -1
  11. package/dist/agent/prompt/extension.js +1 -1
  12. package/dist/agent/prompt/manifest.d.ts +6 -1
  13. package/dist/agent/prompt/manifest.js +12 -5
  14. package/dist/agent/prompt/resources.d.ts +0 -3
  15. package/dist/agent/prompt/resources.js +0 -6
  16. package/dist/agent/prompt/sections.d.ts +2 -2
  17. package/dist/agent/prompt/sections.js +36 -26
  18. package/dist/agent/prompt/types.d.ts +3 -2
  19. package/dist/agent/runner-factory.js +1 -1
  20. package/dist/agent/session/command-extension.js +3 -1
  21. package/dist/agent/session/compaction-summary.js +3 -6
  22. package/dist/agent/session/compaction.d.ts +2 -0
  23. package/dist/agent/session/compaction.js +22 -14
  24. package/dist/agent/session/event-guards.d.ts +2 -1
  25. package/dist/agent/session/event-guards.js +6 -0
  26. package/dist/agent/session/model-selection.d.ts +2 -1
  27. package/dist/agent/session/model-selection.js +5 -5
  28. package/dist/agent/session/session-events.js +31 -4
  29. package/dist/agent/session/session-host.d.ts +5 -3
  30. package/dist/agent/session/session-host.js +20 -16
  31. package/dist/agent/status-render.js +3 -0
  32. package/dist/agent/stop-watchdog.js +5 -1
  33. package/dist/agent/turn/task-digest.d.ts +2 -5
  34. package/dist/agent/turn/task-digest.js +25 -45
  35. package/dist/agent/turn/turn-context.js +4 -6
  36. package/dist/agent/turn/turn-error.d.ts +1 -1
  37. package/dist/agent/turn/turn-error.js +9 -0
  38. package/dist/agent/turn/turn-pipeline.d.ts +10 -5
  39. package/dist/agent/turn/turn-pipeline.js +36 -7
  40. package/dist/agent/turn/turn-prompt.d.ts +2 -0
  41. package/dist/agent/turn/turn-prompt.js +2 -1
  42. package/dist/agent/turn/turn-recovery.js +4 -1
  43. package/dist/agent/turn/turn-state.d.ts +2 -0
  44. package/dist/agent/turn/turn-state.js +2 -1
  45. package/dist/agent/types.d.ts +23 -3
  46. package/dist/agent/types.js +2 -0
  47. package/dist/app/auth-command.d.ts +25 -0
  48. package/dist/app/auth-command.js +200 -67
  49. package/dist/app/home.d.ts +7 -8
  50. package/dist/app/home.js +143 -56
  51. package/dist/channel/attachments.d.ts +4 -0
  52. package/dist/channel/attachments.js +4 -0
  53. package/dist/channel/channel-context.d.ts +6 -0
  54. package/dist/channel/config.d.ts +3 -0
  55. package/dist/channel/config.js +11 -5
  56. package/dist/channel/store.d.ts +1 -1
  57. package/dist/commands/catalog.js +42 -10
  58. package/dist/commands/router.js +5 -1
  59. package/dist/desk/commands.d.ts +44 -5
  60. package/dist/desk/commands.js +162 -28
  61. package/dist/desk/paths.d.ts +6 -0
  62. package/dist/desk/paths.js +21 -1
  63. package/dist/desk/registry.d.ts +17 -2
  64. package/dist/desk/registry.js +122 -12
  65. package/dist/desk/types.d.ts +83 -1
  66. package/dist/dingtalk/bot.d.ts +1 -1
  67. package/dist/dingtalk/bot.js +4 -3
  68. package/dist/dingtalk/config.js +10 -10
  69. package/dist/dingtalk/delivery.js +15 -8
  70. package/dist/dingtalk/inbound-media.d.ts +36 -14
  71. package/dist/dingtalk/inbound-media.js +71 -12
  72. package/dist/dingtalk/inbound.d.ts +9 -2
  73. package/dist/dingtalk/inbound.js +17 -2
  74. package/dist/dingtalk/media.d.ts +4 -10
  75. package/dist/dingtalk/media.js +58 -32
  76. package/dist/events/commands.d.ts +2 -0
  77. package/dist/events/commands.js +13 -8
  78. package/dist/events/history.d.ts +9 -0
  79. package/dist/events/history.js +66 -0
  80. package/dist/events/parse.js +7 -3
  81. package/dist/events/types.d.ts +3 -0
  82. package/dist/events/watcher.d.ts +4 -8
  83. package/dist/events/watcher.js +53 -58
  84. package/dist/jobs/kill.d.ts +23 -0
  85. package/dist/jobs/kill.js +65 -0
  86. package/dist/jobs/manager.d.ts +19 -18
  87. package/dist/jobs/manager.js +36 -103
  88. package/dist/main.js +15 -3
  89. package/dist/memory/boundary-work.d.ts +2 -1
  90. package/dist/memory/boundary-work.js +1 -1
  91. package/dist/memory/lifecycle.d.ts +2 -1
  92. package/dist/memory/lifecycle.js +2 -2
  93. package/dist/memory/reflect-job.d.ts +2 -1
  94. package/dist/memory/reflect-job.js +1 -1
  95. package/dist/memory/reflect.d.ts +2 -1
  96. package/dist/memory/reflect.js +25 -4
  97. package/dist/memory/scheduler.d.ts +2 -1
  98. package/dist/memory/scheduler.js +1 -1
  99. package/dist/memory/session-corpus.d.ts +1 -1
  100. package/dist/memory/session-corpus.js +76 -1
  101. package/dist/memory/session-search.d.ts +2 -1
  102. package/dist/memory/session-search.js +14 -12
  103. package/dist/memory/sidecar-worker.d.ts +2 -1
  104. package/dist/memory/sidecar-worker.js +2 -4
  105. package/dist/memory/store.d.ts +2 -0
  106. package/dist/memory/store.js +19 -9
  107. package/dist/models/credential-work.d.ts +7 -0
  108. package/dist/models/credential-work.js +36 -0
  109. package/dist/models/login-ui.js +4 -4
  110. package/dist/models/provider-login.js +7 -6
  111. package/dist/models/requests.d.ts +8 -0
  112. package/dist/models/requests.js +69 -0
  113. package/dist/models/runtime.d.ts +3 -1
  114. package/dist/models/runtime.js +9 -2
  115. package/dist/playbooks/agent-delegation.md +20 -45
  116. package/dist/playbooks/background-jobs.md +1 -1
  117. package/dist/playbooks/catalog.js +1 -1
  118. package/dist/playbooks/delegation-inline.md +25 -0
  119. package/dist/playbooks/delegation-recovery.md +28 -0
  120. package/dist/playbooks/event-scheduling.md +18 -37
  121. package/dist/playbooks/event-sensors.md +26 -0
  122. package/dist/playbooks/event-task-template.md +22 -0
  123. package/dist/playbooks/learning-and-skills.md +26 -0
  124. package/dist/playbooks/memory-operations.md +36 -0
  125. package/dist/playbooks/outbound-media.md +2 -2
  126. package/dist/playbooks/runtime-files.md +29 -0
  127. package/dist/playbooks/runtime-operations.md +25 -0
  128. package/dist/playbooks/runtime-orientation.md +18 -53
  129. package/dist/playbooks/task-lead.md +22 -68
  130. package/dist/playbooks/task-manage.md +38 -0
  131. package/dist/playbooks/task-recovery.md +24 -0
  132. package/dist/playbooks/task-verify.md +22 -0
  133. package/dist/runtime/bootstrap.d.ts +10 -0
  134. package/dist/runtime/bootstrap.js +93 -29
  135. package/dist/runtime/daemon-lock.js +3 -3
  136. package/dist/runtime/desk-runtime.d.ts +40 -7
  137. package/dist/runtime/desk-runtime.js +330 -44
  138. package/dist/runtime/durable-dispatch.d.ts +14 -2
  139. package/dist/runtime/durable-dispatch.js +207 -65
  140. package/dist/runtime/ingress-busy.js +17 -8
  141. package/dist/runtime/ingress-commands.js +24 -4
  142. package/dist/runtime/ingress-deps.d.ts +4 -1
  143. package/dist/runtime/ingress.js +6 -1
  144. package/dist/runtime/request-execution.js +7 -6
  145. package/dist/runtime/shutdown.d.ts +4 -1
  146. package/dist/runtime/shutdown.js +88 -35
  147. package/dist/runtime/task-close.d.ts +1 -1
  148. package/dist/runtime/task-close.js +6 -3
  149. package/dist/runtime/task-control.d.ts +2 -3
  150. package/dist/runtime/task-control.js +38 -11
  151. package/dist/runtime/task-input.js +1 -1
  152. package/dist/runtime/task-lane-types.d.ts +12 -2
  153. package/dist/runtime/task-lane-types.js +9 -0
  154. package/dist/runtime/task-lane.d.ts +2 -0
  155. package/dist/runtime/task-lane.js +38 -20
  156. package/dist/runtime/task-step.d.ts +3 -3
  157. package/dist/runtime/task-step.js +34 -16
  158. package/dist/runtime/transports.js +6 -5
  159. package/dist/runtime/turn-run.js +103 -66
  160. package/dist/security/command-guard.d.ts +1 -1
  161. package/dist/security/command-guard.js +259 -314
  162. package/dist/security/path-guard.js +48 -7
  163. package/dist/security/shell-parse.d.ts +10 -0
  164. package/dist/security/shell-parse.js +224 -0
  165. package/dist/security/types.d.ts +2 -0
  166. package/dist/subagents/commands.d.ts +1 -1
  167. package/dist/subagents/commands.js +14 -5
  168. package/dist/subagents/completion-wake.js +6 -0
  169. package/dist/subagents/detached-discovery.d.ts +1 -1
  170. package/dist/subagents/discovery.d.ts +18 -199
  171. package/dist/subagents/discovery.js +35 -289
  172. package/dist/subagents/dispatch.d.ts +1 -2
  173. package/dist/subagents/dispatch.js +50 -29
  174. package/dist/subagents/external/antigravity-cli.d.ts +2 -0
  175. package/dist/subagents/external/antigravity-cli.js +517 -0
  176. package/dist/subagents/external/claude-code.js +8 -17
  177. package/dist/subagents/external/codex-cli.js +8 -18
  178. package/dist/subagents/external/cursor-cli.js +34 -31
  179. package/dist/subagents/external/dispatch.d.ts +21 -7
  180. package/dist/subagents/external/dispatch.js +146 -12
  181. package/dist/subagents/external/exec.js +3 -0
  182. package/dist/subagents/external/harness.d.ts +57 -33
  183. package/dist/subagents/external/harness.js +69 -40
  184. package/dist/subagents/external/reconciliation.js +1 -0
  185. package/dist/subagents/external/registry.js +4 -1
  186. package/dist/subagents/external/role-warnings.d.ts +4 -13
  187. package/dist/subagents/external/role-warnings.js +4 -28
  188. package/dist/subagents/external/run.d.ts +1 -2
  189. package/dist/subagents/external/run.js +16 -26
  190. package/dist/subagents/external/settlement.d.ts +2 -0
  191. package/dist/subagents/external/settlement.js +13 -3
  192. package/dist/subagents/format.d.ts +1 -1
  193. package/dist/subagents/format.js +1 -1
  194. package/dist/subagents/internal/outcome.d.ts +1 -2
  195. package/dist/subagents/internal/outcome.js +19 -12
  196. package/dist/subagents/internal/provider-retry.d.ts +1 -2
  197. package/dist/subagents/internal/provider-retry.js +2 -4
  198. package/dist/subagents/internal/run.d.ts +2 -3
  199. package/dist/subagents/internal/run.js +27 -4
  200. package/dist/subagents/internal/state.d.ts +2 -5
  201. package/dist/subagents/internal/state.js +1 -2
  202. package/dist/subagents/internal/worker.d.ts +1 -2
  203. package/dist/subagents/internal/worker.js +20 -10
  204. package/dist/subagents/resolve.d.ts +56 -0
  205. package/dist/subagents/resolve.js +202 -0
  206. package/dist/subagents/result.d.ts +6 -4
  207. package/dist/subagents/result.js +39 -6
  208. package/dist/subagents/run-record.d.ts +54 -2
  209. package/dist/subagents/run-record.js +7 -0
  210. package/dist/subagents/runs.d.ts +6 -31
  211. package/dist/subagents/runs.js +26 -31
  212. package/dist/subagents/task-envelope.d.ts +1 -2
  213. package/dist/subagents/task-envelope.js +13 -4
  214. package/dist/subagents/task-settlement.js +1 -0
  215. package/dist/subagents/types.d.ts +105 -6
  216. package/dist/subagents/types.js +16 -1
  217. package/dist/subagents/workspace-lease.d.ts +41 -24
  218. package/dist/subagents/workspace-lease.js +159 -24
  219. package/dist/subagents/worktree.d.ts +52 -0
  220. package/dist/subagents/worktree.js +363 -0
  221. package/dist/tasks/archive.js +4 -0
  222. package/dist/tasks/brief.d.ts +5 -1
  223. package/dist/tasks/brief.js +19 -5
  224. package/dist/tasks/commands.d.ts +6 -1
  225. package/dist/tasks/commands.js +32 -7
  226. package/dist/tasks/control.d.ts +11 -0
  227. package/dist/tasks/delivery.d.ts +2 -0
  228. package/dist/tasks/delivery.js +141 -21
  229. package/dist/tasks/loop-log.d.ts +12 -0
  230. package/dist/tasks/loop-log.js +10 -1
  231. package/dist/tasks/receipts.d.ts +7 -3
  232. package/dist/tasks/receipts.js +34 -5
  233. package/dist/tools/bash.d.ts +3 -0
  234. package/dist/tools/bash.js +29 -15
  235. package/dist/tools/contract/presentation.js +7 -5
  236. package/dist/tools/edit-diff.d.ts +11 -0
  237. package/dist/tools/edit-diff.js +148 -0
  238. package/dist/tools/edit-match.d.ts +18 -0
  239. package/dist/tools/edit-match.js +242 -0
  240. package/dist/tools/edit.d.ts +10 -2
  241. package/dist/tools/edit.js +91 -361
  242. package/dist/tools/event-manage.d.ts +2 -1
  243. package/dist/tools/event-manage.js +46 -39
  244. package/dist/tools/file-observations.d.ts +9 -0
  245. package/dist/tools/file-observations.js +50 -0
  246. package/dist/tools/glob-match.d.ts +3 -1
  247. package/dist/tools/glob-match.js +40 -17
  248. package/dist/tools/glob.d.ts +1 -0
  249. package/dist/tools/glob.js +39 -19
  250. package/dist/tools/grep-command.d.ts +13 -0
  251. package/dist/tools/grep-command.js +77 -0
  252. package/dist/tools/grep.js +96 -201
  253. package/dist/tools/index.d.ts +6 -2
  254. package/dist/tools/index.js +9 -4
  255. package/dist/tools/job.js +12 -11
  256. package/dist/tools/read.d.ts +2 -0
  257. package/dist/tools/read.js +10 -2
  258. package/dist/tools/registry.d.ts +16 -11
  259. package/dist/tools/registry.js +32 -12
  260. package/dist/tools/send-media.js +9 -5
  261. package/dist/tools/session-search.d.ts +2 -1
  262. package/dist/tools/session-search.js +15 -5
  263. package/dist/tools/skill.js +13 -12
  264. package/dist/tools/subagent-manage.d.ts +1 -1
  265. package/dist/tools/subagent-manage.js +25 -152
  266. package/dist/tools/subagent.d.ts +24 -2
  267. package/dist/tools/subagent.js +24 -18
  268. package/dist/tools/task-manage/control-tools.js +1 -1
  269. package/dist/tools/task-manage/factory.d.ts +2 -2
  270. package/dist/tools/task-manage/factory.js +40 -4
  271. package/dist/tools/task-manage/lifecycle.d.ts +3 -3
  272. package/dist/tools/task-manage/lifecycle.js +56 -13
  273. package/dist/tools/task-manage/schema.d.ts +4 -1
  274. package/dist/tools/task-manage/schema.js +4 -1
  275. package/dist/tools/task-manage/shared.d.ts +1 -1
  276. package/dist/tools/task-manage/types.d.ts +5 -1
  277. package/dist/tools/write-content.d.ts +7 -1
  278. package/dist/tools/write-content.js +18 -6
  279. package/dist/tools/write.d.ts +3 -0
  280. package/dist/tools/write.js +6 -2
  281. package/dist/tui/cli.d.ts +6 -6
  282. package/dist/tui/cli.js +120 -28
  283. package/dist/tui/client.d.ts +7 -0
  284. package/dist/tui/client.js +67 -16
  285. package/dist/tui/frontend.d.ts +2 -0
  286. package/dist/tui/pitui-frontend.d.ts +4 -0
  287. package/dist/tui/pitui-frontend.js +27 -0
  288. package/dist/tui/render.d.ts +1 -0
  289. package/dist/tui/render.js +5 -0
  290. package/dist/tui/session.js +6 -0
  291. package/dist/usage/ledger.d.ts +1 -1
  292. package/dist/usage/render.js +1 -1
  293. package/dist/web/client.d.ts +1 -0
  294. package/dist/web/client.js +11 -0
  295. package/dist/web/fetch.js +6 -3
  296. package/dist/webapi/auth.d.ts +0 -3
  297. package/dist/webapi/auth.js +3 -7
  298. package/dist/webapi/config.js +17 -14
  299. package/dist/webapi/key-command.js +41 -41
  300. package/dist/webapi/response-state.d.ts +7 -1
  301. package/dist/webapi/response-state.js +166 -3
  302. package/dist/webapi/routes/websocket.js +24 -1
  303. package/dist/webapi/server.d.ts +3 -1
  304. package/dist/webapi/server.js +32 -1
  305. package/dist/webapi/service.js +8 -0
  306. package/dist/webapi/transport.d.ts +2 -0
  307. package/dist/webapi/transport.js +11 -1
  308. package/examples/sub-agents/README.md +43 -75
  309. package/examples/sub-agents/agy-main.md +21 -0
  310. package/examples/sub-agents/claude-high.md +21 -0
  311. package/examples/sub-agents/claude-main.md +21 -0
  312. package/examples/sub-agents/codex-flash.md +21 -0
  313. package/examples/sub-agents/codex-high.md +21 -0
  314. package/examples/sub-agents/codex-main.md +21 -0
  315. package/examples/sub-agents/codex-review.md +20 -0
  316. package/examples/sub-agents/cursor-high.md +20 -0
  317. package/examples/sub-agents/cursor-main.md +20 -0
  318. package/examples/sub-agents/glm-flash.md +21 -0
  319. package/examples/sub-agents/glm-high.md +21 -0
  320. package/examples/sub-agents/pi-scout.md +20 -0
  321. package/package.json +11 -12
  322. package/dist/agent/session/request-tools.d.ts +0 -3
  323. package/dist/agent/session/request-tools.js +0 -20
  324. package/dist/models/api-keys.d.ts +0 -11
  325. package/dist/models/api-keys.js +0 -22
  326. package/dist/playbooks/memory-and-learning.md +0 -55
  327. package/examples/sub-agents/agents/claude-high.md +0 -23
  328. package/examples/sub-agents/agents/claude-main.md +0 -23
  329. package/examples/sub-agents/agents/codex-flash.md +0 -23
  330. package/examples/sub-agents/agents/codex-high.md +0 -23
  331. package/examples/sub-agents/agents/codex-main.md +0 -23
  332. package/examples/sub-agents/agents/codex-review.md +0 -23
  333. package/examples/sub-agents/agents/cursor-high.md +0 -22
  334. package/examples/sub-agents/agents/cursor-main.md +0 -22
  335. package/examples/sub-agents/agents/glm-flash.md +0 -23
  336. package/examples/sub-agents/agents/glm-high.md +0 -23
  337. package/examples/sub-agents/agents/scout.md +0 -30
  338. package/examples/sub-agents/roles/builder-hard.md +0 -34
  339. package/examples/sub-agents/roles/builder.md +0 -34
  340. package/examples/sub-agents/roles/explorer.md +0 -39
  341. package/examples/sub-agents/roles/git-committer.md +0 -43
  342. package/examples/sub-agents/roles/planner.md +0 -33
  343. package/examples/sub-agents/roles/reviewer.md +0 -33
  344. package/examples/sub-agents/roles/verifier.md +0 -35
  345. package/examples/sub-agents/roles/worker.md +0 -34
@@ -0,0 +1,66 @@
1
+ import { chmodSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname } from "node:path";
4
+ import * as log from "../log.js";
5
+ import { createJsonlAppender } from "../shared/jsonl-appender.js";
6
+ export const EVENT_HISTORY_MAX_BYTES = 2 * 1024 * 1024;
7
+ const EVENT_HISTORY_ROTATIONS = 2;
8
+ /**
9
+ * Shared per-path appenders: every desk's `EventsWatcher` writes into the same app-level
10
+ * `events-history.jsonl`, so they must share one serialized queue and file-size cache for
11
+ * size-based rotation to stay race-free across desks.
12
+ */
13
+ const appenders = new Map();
14
+ export function getEventHistoryAppender(path, maxSizeBytes = EVENT_HISTORY_MAX_BYTES) {
15
+ const key = `${path}:${maxSizeBytes}`;
16
+ let appender = appenders.get(key);
17
+ if (!appender) {
18
+ appender = createJsonlAppender({
19
+ path,
20
+ maxSizeBytes,
21
+ maxRotations: EVENT_HISTORY_ROTATIONS,
22
+ maxPendingRecords: 4_000,
23
+ maxPendingBytes: 8 * 1024 * 1024,
24
+ });
25
+ appenders.set(key, appender);
26
+ }
27
+ return appender;
28
+ }
29
+ export function ensureEventHistoryFile(historyPath) {
30
+ try {
31
+ mkdirSync(dirname(historyPath), { recursive: true, mode: 0o700 });
32
+ writeFileSync(historyPath, "", { flag: "a", mode: 0o600 });
33
+ chmodSync(historyPath, 0o600);
34
+ }
35
+ catch (err) {
36
+ log.logWarn("events.history.init_failed", "Event history file init failed", { reason: String(err) });
37
+ }
38
+ }
39
+ /**
40
+ * Read retained history shards from oldest to newest (`.2` → `.1` → active file) so `/events history`
41
+ * remains continuous right across a rotation boundary.
42
+ */
43
+ export async function readEventHistoryLines(historyPath) {
44
+ const shards = [
45
+ ...Array.from({ length: EVENT_HISTORY_ROTATIONS }, (_, index) => `${historyPath}.${EVENT_HISTORY_ROTATIONS - index}`),
46
+ historyPath,
47
+ ];
48
+ const lines = [];
49
+ for (const shard of shards) {
50
+ if (!existsSync(shard))
51
+ continue;
52
+ try {
53
+ const raw = await readFile(shard, "utf-8");
54
+ for (const line of raw.split("\n")) {
55
+ const trimmed = line.trim();
56
+ if (trimmed)
57
+ lines.push(trimmed);
58
+ }
59
+ }
60
+ catch (error) {
61
+ if (error.code !== "ENOENT")
62
+ throw error;
63
+ }
64
+ }
65
+ return lines;
66
+ }
@@ -46,15 +46,19 @@ function parsePreAction(data, filename) {
46
46
  if (typeof action.command !== "string" || action.command.trim().length === 0) {
47
47
  throw new EventDefinitionError("pre-action", `Missing or empty 'preAction.command' in ${filename}`);
48
48
  }
49
- if (action.timeout !== undefined) {
50
- if (typeof action.timeout !== "number" || !Number.isFinite(action.timeout) || action.timeout <= 0) {
49
+ if (action.timeout !== undefined && action.timeoutMs !== undefined && action.timeout !== action.timeoutMs) {
50
+ throw new EventDefinitionError("pre-action", `Conflicting 'preAction.timeout' and 'preAction.timeoutMs' in ${filename}; specify timeoutMs only`);
51
+ }
52
+ const rawTimeout = action.timeout ?? action.timeoutMs;
53
+ if (rawTimeout !== undefined) {
54
+ if (typeof rawTimeout !== "number" || !Number.isFinite(rawTimeout) || rawTimeout <= 0) {
51
55
  throw new EventDefinitionError("pre-action", `Invalid 'preAction.timeout' in ${filename}, expected a positive millisecond value`);
52
56
  }
53
57
  }
54
58
  return {
55
59
  type: "bash",
56
60
  command: action.command,
57
- ...(typeof action.timeout === "number" ? { timeout: action.timeout } : {}),
61
+ ...(typeof rawTimeout === "number" ? { timeout: rawTimeout } : {}),
58
62
  };
59
63
  }
60
64
  export function parseScheduledEventContent(content, filename) {
@@ -90,6 +90,8 @@ export type SpawnTaskResult =
90
90
  export interface EventsWatcherOptions {
91
91
  /** The desk this watcher serves; stamped on every dispatch, history record and spawn request. */
92
92
  desk: string;
93
+ /** Working directory for `preAction` commands (`desk.json` `cwd` when set, else `deskDir`). */
94
+ cwd?: string;
93
95
  /**
94
96
  * Whether a delivery channel is still bound to this desk (spec 058, D7's producer-side check).
95
97
  * An occurrence whose channel is not bound is skipped, never redirected.
@@ -101,6 +103,7 @@ export interface EventsWatcherOptions {
101
103
  */
102
104
  isReachable: (channelId: string) => boolean;
103
105
  historyPath?: string;
106
+ historyMaxBytes?: number;
104
107
  /**
105
108
  * Creates the task instance a template event asks for. Injected by the runtime so the events
106
109
  * subsystem never reads or writes task files (spec 052, INV-8).
@@ -11,6 +11,7 @@ export declare class EventsWatcher {
11
11
  private timers;
12
12
  private crons;
13
13
  private debounceTimers;
14
+ private readonly fileQueue;
14
15
  private startTime;
15
16
  private watcher;
16
17
  private started;
@@ -28,16 +29,11 @@ export declare class EventsWatcher {
28
29
  private debounce;
29
30
  private scanExisting;
30
31
  private handleFileChange;
31
- /**
32
- * Watch callbacks are the top of their own stack, so a rejection here reaches nobody — and
33
- * `handleFile` can reject: reloading a due one-shot dispatches it inline, and dispatch
34
- * writes to disk. `scanExisting` already wraps its own calls; this is the same guard for
35
- * the live path. One bad file must not take the watcher, or the process, down with it.
36
- */
37
- private handleFileSafely;
38
32
  private handleDelete;
33
+ private stopScheduled;
39
34
  private cancelScheduled;
40
35
  private handleFile;
36
+ private loadFile;
41
37
  private parseEvent;
42
38
  /**
43
39
  * The admission gate (spec 031, D4). `event_manage` applies the same rules first, but the
@@ -49,7 +45,7 @@ export declare class EventsWatcher {
49
45
  private handleOneShot;
50
46
  private handlePeriodic;
51
47
  private execute;
52
- /** Whether the watcher may still act on an occurrence (desk active, channel bound); records a skip. */
48
+ /** Whether the watcher may still act on an occurrence (desk active; task templates need reachable transport, chat wakes also need channel bound); records a skip. */
53
49
  private admits;
54
50
  /**
55
51
  * Deliver a template event: ask the runtime for a fresh task instance (spec 052, D2). The
@@ -3,15 +3,16 @@
3
3
  * (cron, optional pre-action gate) and enqueues every occurrence through the injected event sink.
4
4
  */
5
5
  import { Cron } from "croner";
6
- import { chmodSync, existsSync, mkdirSync, readdirSync, statSync, unlinkSync, watch, writeFileSync, } from "fs";
6
+ import { existsSync, mkdirSync, readdirSync, statSync, unlinkSync, watch } from "fs";
7
7
  import { readFile } from "fs/promises";
8
- import { dirname, join, resolve } from "path";
8
+ import { join, resolve } from "path";
9
9
  import * as log from "../log.js";
10
10
  import { guardCommand } from "../security/command-guard.js";
11
11
  import { writeFileAtomicallySync } from "../shared/atomic-file.js";
12
- import { createJsonlAppender } from "../shared/jsonl-appender.js";
13
12
  import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
13
+ import { createSerialQueue } from "../shared/serial-queue.js";
14
14
  import { clipText, errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
15
+ import { ensureEventHistoryFile, getEventHistoryAppender } from "./history.js";
15
16
  import { describeEventPayload, parseScheduledEventContent } from "./parse.js";
16
17
  import { EventPreActionError } from "./pre-action-error.js";
17
18
  import { MAX_EVENT_FILES, MAX_ONE_SHOT_DELAY_MS, validateScheduledEvent } from "./validation.js";
@@ -42,6 +43,7 @@ export class EventsWatcher {
42
43
  this.timers = new Map();
43
44
  this.crons = new Map();
44
45
  this.debounceTimers = new Map();
46
+ this.fileQueue = createSerialQueue();
45
47
  this.watcher = null;
46
48
  this.started = false;
47
49
  /** Set once by `stop()` and never cleared: in-flight loads check it before scheduling anything. */
@@ -49,11 +51,7 @@ export class EventsWatcher {
49
51
  this.knownFiles = new Set();
50
52
  this.startTime = Date.now();
51
53
  this.historyAppender = options.historyPath
52
- ? createJsonlAppender({
53
- path: options.historyPath,
54
- maxPendingRecords: 4_000,
55
- maxPendingBytes: 8 * 1024 * 1024,
56
- })
54
+ ? getEventHistoryAppender(options.historyPath, options.historyMaxBytes)
57
55
  : undefined;
58
56
  }
59
57
  start() {
@@ -97,23 +95,12 @@ export class EventsWatcher {
97
95
  await this.historyAppender?.flush();
98
96
  }
99
97
  ensureHistoryFile() {
100
- if (!this.options.historyPath) {
101
- return;
102
- }
103
- try {
104
- const historyDir = dirname(this.options.historyPath);
105
- mkdirSync(historyDir, { recursive: true, mode: 0o700 });
106
- writeFileSync(this.options.historyPath, "", { flag: "a", mode: 0o600 });
107
- chmodSync(this.options.historyPath, 0o600);
108
- }
109
- catch (err) {
110
- log.logWarn("events.history.init_failed", "Event history file init failed", { reason: String(err) });
111
- }
98
+ if (this.options.historyPath)
99
+ ensureEventHistoryFile(this.options.historyPath);
112
100
  }
113
101
  appendHistory(record) {
114
- if (!this.options.historyPath) {
102
+ if (!this.options.historyPath)
115
103
  return;
116
- }
117
104
  const { filename, ...rest } = record;
118
105
  const fullRecord = {
119
106
  ts: formatLocalTime(),
@@ -173,26 +160,21 @@ export class EventsWatcher {
173
160
  }
174
161
  }
175
162
  handleFileChange(filename) {
176
- const filePath = join(this.eventsDir, filename);
177
- if (!existsSync(filePath)) {
178
- this.handleDelete(filename);
179
- }
180
- else if (this.knownFiles.has(filename)) {
181
- this.cancelScheduled(filename);
182
- this.handleFileSafely(filename);
183
- }
184
- else {
185
- this.handleFileSafely(filename);
186
- }
187
- }
188
- /**
189
- * Watch callbacks are the top of their own stack, so a rejection here reaches nobody — and
190
- * `handleFile` can reject: reloading a due one-shot dispatches it inline, and dispatch
191
- * writes to disk. `scanExisting` already wraps its own calls; this is the same guard for
192
- * the live path. One bad file must not take the watcher, or the process, down with it.
193
- */
194
- handleFileSafely(filename) {
195
- void this.handleFile(filename).catch((err) => {
163
+ // Serialize per filename with `scanExisting`/`handleFile` so an overlapping watch event
164
+ // cannot race an in-flight read and overwrite `this.crons`/`this.timers` without stopping the old one.
165
+ void this.fileQueue
166
+ .run(filename, async () => {
167
+ if (this.stopped)
168
+ return;
169
+ if (!existsSync(join(this.eventsDir, filename))) {
170
+ this.handleDelete(filename);
171
+ return;
172
+ }
173
+ if (this.knownFiles.has(filename))
174
+ this.cancelScheduled(filename);
175
+ await this.loadFile(filename);
176
+ })
177
+ .catch((err) => {
196
178
  log.logWarn("events.file.load_failed", "Event file load failed", {
197
179
  reason: errorMessage(err),
198
180
  fields: { file: filename },
@@ -200,33 +182,32 @@ export class EventsWatcher {
200
182
  });
201
183
  }
202
184
  handleDelete(filename) {
185
+ this.clearInvalidMarker(filename);
203
186
  if (!this.knownFiles.has(filename))
204
187
  return;
205
188
  log.logInfo(`Event file deleted: ${filename}`);
206
189
  this.cancelScheduled(filename);
207
190
  this.knownFiles.delete(filename);
208
- this.appendHistory({
209
- filename,
210
- eventType: "unknown",
211
- action: "deleted",
212
- result: "ok",
213
- });
191
+ this.appendHistory({ filename, eventType: "unknown", action: "deleted", result: "ok" });
214
192
  }
215
- cancelScheduled(filename) {
216
- let cancelled = false;
193
+ stopScheduled(filename) {
194
+ let stoppedAny = false;
217
195
  const timer = this.timers.get(filename);
218
196
  if (timer) {
219
197
  clearTimeout(timer);
220
198
  this.timers.delete(filename);
221
- cancelled = true;
199
+ stoppedAny = true;
222
200
  }
223
201
  const cron = this.crons.get(filename);
224
202
  if (cron) {
225
203
  cron.stop();
226
204
  this.crons.delete(filename);
227
- cancelled = true;
205
+ stoppedAny = true;
228
206
  }
229
- if (cancelled) {
207
+ return stoppedAny;
208
+ }
209
+ cancelScheduled(filename) {
210
+ if (this.stopScheduled(filename)) {
230
211
  this.appendHistory({
231
212
  filename,
232
213
  eventType: "unknown",
@@ -236,7 +217,10 @@ export class EventsWatcher {
236
217
  });
237
218
  }
238
219
  }
239
- async handleFile(filename) {
220
+ handleFile(filename) {
221
+ return this.fileQueue.run(filename, () => this.loadFile(filename));
222
+ }
223
+ async loadFile(filename) {
240
224
  const filePath = join(this.eventsDir, filename);
241
225
  let event = null;
242
226
  let lastError = null;
@@ -258,6 +242,9 @@ export class EventsWatcher {
258
242
  // or cron that nothing would ever stop.
259
243
  if (this.stopped)
260
244
  return;
245
+ // Stop any prior timer/cron before re-evaluating or re-scheduling this filename, so even two
246
+ // direct `handleFile` calls can never leave an orphan Cron or Timeout behind.
247
+ this.stopScheduled(filename);
261
248
  if (!event) {
262
249
  log.logWarn("events.file.parse_failed", "Event file parse failed", {
263
250
  reason: lastError?.message,
@@ -377,9 +364,11 @@ export class EventsWatcher {
377
364
  });
378
365
  }
379
366
  }, delay);
367
+ this.stopScheduled(filename);
380
368
  this.timers.set(filename, timer);
381
369
  }
382
370
  handlePeriodic(filename, event) {
371
+ this.stopScheduled(filename);
383
372
  try {
384
373
  const cron = new Cron(event.schedule, { protect: true, catch: true }, async () => {
385
374
  try {
@@ -515,11 +504,11 @@ export class EventsWatcher {
515
504
  this.markInvalid(filename, `Event queue was full at ${new Date().toISOString()}; this occurrence was not delivered.`);
516
505
  }
517
506
  }
518
- /** Whether the watcher may still act on an occurrence (desk active, channel bound); records a skip. */
507
+ /** Whether the watcher may still act on an occurrence (desk active; task templates need reachable transport, chat wakes also need channel bound); records a skip. */
519
508
  admits(filename, event, deleteAfter) {
520
509
  if (this.stopped)
521
510
  return false; // a load `stop()` could not cancel: the desk went dormant meanwhile
522
- const bound = this.options.isBound(event.channelId);
511
+ const bound = event.task ? true : this.options.isBound(event.channelId);
523
512
  if (bound && this.options.isReachable(event.channelId))
524
513
  return true;
525
514
  this.appendEventHistory(filename, event, "skipped", "skipped", {
@@ -592,7 +581,10 @@ export class EventsWatcher {
592
581
  const timeoutSeconds = Math.max(1, Math.ceil(timeoutMs / 1000));
593
582
  let result;
594
583
  try {
595
- result = await this.executor.exec(action.command, { timeout: timeoutSeconds });
584
+ result = await this.executor.exec(action.command, {
585
+ timeout: timeoutSeconds,
586
+ ...(this.options.cwd ? { cwd: this.options.cwd } : {}),
587
+ });
596
588
  }
597
589
  catch (err) {
598
590
  throw new EventPreActionError("failed", errorMessage(err), {
@@ -665,5 +657,8 @@ export class EventsWatcher {
665
657
  /** Create the events watcher of one desk: it watches `<deskDir>/events/` (spec 058, D14). */
666
658
  export function createEventsWatcher(input) {
667
659
  const { deskDir, sink, executor, commandGuardConfig, ...options } = input;
668
- return new EventsWatcher(join(deskDir, "events"), sink, executor, commandGuardConfig, options);
660
+ return new EventsWatcher(join(deskDir, "events"), sink, executor, commandGuardConfig, {
661
+ ...options,
662
+ cwd: options.cwd ?? deskDir,
663
+ });
669
664
  }
@@ -0,0 +1,23 @@
1
+ import type { Executor } from "../executor.js";
2
+ import type { JobRecord } from "./record.js";
3
+ /**
4
+ * The outcome of one kill attempt, decided from the kill script's own printed token plus the
5
+ * executor result — never from "the shell exited 0", which a failed `kill` inside `2>/dev/null`
6
+ * would still do.
7
+ * - `terminated` — we signalled the target and then confirmed the pid is gone.
8
+ * - `gone` — the target was already gone before we signalled (or its pgid became unroutable).
9
+ * - `identity-mismatch` — the pid now belongs to an unrelated process, so *our* process is gone.
10
+ * - `unconfirmed` — the kill ran but the pid is still alive afterwards.
11
+ * - `not-submitted` — the executor could not even run the kill.
12
+ * - `no-target` — there is no pid we can safely signal (pid <= 1 / not finite).
13
+ */
14
+ type KillOutcome = "terminated" | "gone" | "identity-mismatch" | "unconfirmed" | "not-submitted" | "no-target";
15
+ /** Outcomes that prove the job's process is gone — safe to apply a terminal status. */
16
+ export declare const KILL_CONFIRMED_GONE: ReadonlySet<KillOutcome>;
17
+ /**
18
+ * Run one kill attempt and classify it from the printed token plus the executor result — never
19
+ * from "the shell exited 0". Used by cancel, timeout, the persist-failure rollback and the
20
+ * interrupted-launch recovery; the last two pass no signal so an aborted caller cannot skip it.
21
+ */
22
+ export declare function killJob(executor: Executor, record: Pick<JobRecord, "pid" | "pgid" | "pidStartedAt">, signal?: AbortSignal): Promise<KillOutcome>;
23
+ export {};
@@ -0,0 +1,65 @@
1
+ import { shellEscape } from "../shared/os.js";
2
+ /** Outcomes that prove the job's process is gone — safe to apply a terminal status. */
3
+ export const KILL_CONFIRMED_GONE = new Set([
4
+ "terminated",
5
+ "gone",
6
+ "identity-mismatch",
7
+ "no-target",
8
+ ]);
9
+ /**
10
+ * The shell command that terminates `record`'s process and prints one token describing what
11
+ * happened (`TERMINATED` / `GONE` / `IDENTITY_MISMATCH` / `UNCONFIRMED`), or `undefined` when
12
+ * there is no pid we can safely signal.
13
+ *
14
+ * A negative-PGID target is used only when `setsid` gave the job pgid == pid (spec: everything
15
+ * the command spawned dies with it). When a start time was captured it is checked first: a
16
+ * recycled pid reads as `IDENTITY_MISMATCH` and is never signalled; a pid `ps` cannot see but
17
+ * that `kill -0` says is alive reads as `UNCONFIRMED` (do not signal what we cannot prove is
18
+ * ours). Legacy / nohup records have only `kill -0` liveness and a plain pid kill.
19
+ */
20
+ function buildKillCommand(record) {
21
+ const pid = record.pid;
22
+ if (!Number.isFinite(pid) || pid <= 1)
23
+ return undefined;
24
+ const groupSafe = record.pgid !== undefined && record.pgid === pid;
25
+ const target = groupSafe ? `"-${pid}"` : `${pid}`;
26
+ const gate = record.pidStartedAt
27
+ ? `__pc_cur="$(ps -o lstart= -p ${pid} 2>/dev/null)"; ` +
28
+ `if [ -z "$__pc_cur" ]; then ` +
29
+ `if kill -0 ${pid} 2>/dev/null; then printf 'UNCONFIRMED\\n'; exit 0; else printf 'GONE\\n'; exit 0; fi; fi; ` +
30
+ `if [ "$__pc_cur" != ${shellEscape(record.pidStartedAt)} ]; then printf 'IDENTITY_MISMATCH\\n'; exit 0; fi; `
31
+ : `if ! kill -0 ${pid} 2>/dev/null; then printf 'GONE\\n'; exit 0; fi; `;
32
+ return (gate +
33
+ `kill -TERM ${target} 2>/dev/null; sleep 0.2; kill -KILL ${target} 2>/dev/null; sleep 0.05; ` +
34
+ `if kill -0 ${pid} 2>/dev/null; then printf 'UNCONFIRMED\\n'; else printf 'TERMINATED\\n'; fi`);
35
+ }
36
+ /**
37
+ * Run one kill attempt and classify it from the printed token plus the executor result — never
38
+ * from "the shell exited 0". Used by cancel, timeout, the persist-failure rollback and the
39
+ * interrupted-launch recovery; the last two pass no signal so an aborted caller cannot skip it.
40
+ */
41
+ export async function killJob(executor, record, signal) {
42
+ const command = buildKillCommand(record);
43
+ if (!command)
44
+ return "no-target";
45
+ let result;
46
+ try {
47
+ result = await executor.exec(command, signal ? { signal } : {});
48
+ }
49
+ catch {
50
+ return "not-submitted";
51
+ }
52
+ const token = result.stdout.trim().split("\n").pop()?.trim() ?? "";
53
+ switch (token) {
54
+ case "TERMINATED":
55
+ return "terminated";
56
+ case "GONE":
57
+ return "gone";
58
+ case "IDENTITY_MISMATCH":
59
+ return "identity-mismatch";
60
+ case "UNCONFIRMED":
61
+ return "unconfirmed";
62
+ default:
63
+ return "not-submitted";
64
+ }
65
+ }
@@ -2,9 +2,27 @@ import type { WakeEvent } from "../channel/channel-event.js";
2
2
  import type { Executor } from "../executor.js";
3
3
  import { type FileStore } from "../file-store.js";
4
4
  import { type JobRecord, type JobSnapshot, type JobStatus } from "./record.js";
5
+ /**
6
+ * Per-desk manager for background bash jobs. A long command that ran synchronously would hold
7
+ * the channel's run queue for its whole duration, blocking `/steer`, `/followup`, and every other
8
+ * message. A background job instead returns immediately and the model can end its turn.
9
+ *
10
+ * Jobs live on the host, managed through shell commands (`setsid` to launch as its own process
11
+ * group with a startup handshake, a three-state identity probe, a confirmed kill) with no
12
+ * in-process child handles. Records
13
+ * are mirrored to `state/jobs/<desk>/<id>.json` so they survive a restart: a detached
14
+ * process outlives the daemon, and losing the record while the process kept running meant orphaned
15
+ * work, leaked slots, and unreachable output (spec 031, D6).
16
+ *
17
+ * A finished job wakes its channel by itself. Making the model predict a completion time and
18
+ * arrange its own callback was a judgement call it could not make correctly, so completion is a
19
+ * runtime guarantee instead.
20
+ */
5
21
  export interface JobStartOptions {
6
22
  /** The channel the job was started from: its completion wake goes back there (spec 058, D7). */
7
23
  channelId: string;
24
+ /** Working directory for the background process; falls back to the desk directory when omitted. */
25
+ cwd?: string;
8
26
  signal?: AbortSignal;
9
27
  notify?: boolean;
10
28
  /** The task whose step starts the job (spec 064, INV-8): its completion is recorded there instead of waking `channelId`. */
@@ -114,6 +132,7 @@ export declare class DeskJobManager {
114
132
  stop(): void;
115
133
  private stopSweeper;
116
134
  private sweep;
135
+ private refreshBatch;
117
136
  /**
118
137
  * Probe every given job in one shell invocation, returning
119
138
  * `id → EXIT:<code> | ALIVE | GONE | DIFFERENT | UNKNOWN`.
@@ -163,24 +182,6 @@ export declare class DeskJobManager {
163
182
  private announce;
164
183
  /** Same contract as `SubAgentRunManager.suppressWake`: drop the chat wake of a job whose channel left the desk. */
165
184
  private suppressWake;
166
- /**
167
- * The shell command that terminates `record`'s process and prints one token describing what
168
- * happened (`TERMINATED` / `GONE` / `IDENTITY_MISMATCH` / `UNCONFIRMED`), or `undefined` when
169
- * there is no pid we can safely signal.
170
- *
171
- * A negative-PGID target is used only when `setsid` gave the job pgid == pid (spec: everything
172
- * the command spawned dies with it). When a start time was captured it is checked first: a
173
- * recycled pid reads as `IDENTITY_MISMATCH` and is never signalled; a pid `ps` cannot see but
174
- * that `kill -0` says is alive reads as `UNCONFIRMED` (do not signal what we cannot prove is
175
- * ours). Legacy / nohup records have only `kill -0` liveness and a plain pid kill.
176
- */
177
- private killCommand;
178
- /**
179
- * Run one kill attempt and classify it from the printed token plus the executor result — never
180
- * from "the shell exited 0". Used by cancel, timeout, the persist-failure rollback and the
181
- * interrupted-launch recovery; the last two pass no signal so an aborted caller cannot skip it.
182
- */
183
- private runKill;
184
185
  list(signal?: AbortSignal): Promise<JobSnapshot[]>;
185
186
  cancel(ids: string[], signal?: AbortSignal): Promise<Array<{
186
187
  id: string;