@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
+ * Watches `workspace/events/`, validates each definition, schedules one-shot and periodic events
3
+ * (cron, optional pre-action gate) and enqueues every occurrence through the injected event sink.
4
+ */
1
5
  import { Cron } from "croner";
2
6
  import { chmodSync, existsSync, mkdirSync, readdirSync, statSync, unlinkSync, watch, writeFileSync, } from "fs";
3
7
  import { readFile } from "fs/promises";
@@ -8,9 +12,8 @@ import { writeFileAtomicallySync } from "../shared/atomic-file.js";
8
12
  import { createJsonlAppender } from "../shared/jsonl-appender.js";
9
13
  import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
10
14
  import { clipText, errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
11
- import { isPlainObject } from "../shared/type-guards.js";
12
- import { validateTaskContractInput } from "../tasks/contract-input.js";
13
- import { MAX_EVENT_FILES, MAX_ONE_SHOT_DELAY_MS, validateScheduledEvent } from "./event-validation.js";
15
+ import { describeEventPayload, parseScheduledEventContent } from "./parse.js";
16
+ import { MAX_EVENT_FILES, MAX_ONE_SHOT_DELAY_MS, validateScheduledEvent } from "./validation.js";
14
17
  // ============================================================================
15
18
  // EventsWatcher
16
19
  // ============================================================================
@@ -20,109 +23,9 @@ const RETRY_BASE_MS = 100;
20
23
  const SCAN_CONCURRENCY = 4;
21
24
  const DEFAULT_PRE_ACTION_TIMEOUT_MS = 10_000;
22
25
  const TEXT_PREVIEW_MAX_CHARS = 160;
23
- /** The one-line description of what an event delivers, for history records and listings. */
24
- export function describeEventPayload(event) {
25
- return event.task ? `任务模板:${event.task.title}` : (event.text ?? "");
26
- }
27
26
  function truncateTextPreview(text) {
28
27
  return clipText(text, TEXT_PREVIEW_MAX_CHARS, { headRatio: 1, omitHint: "…", collapseWhitespace: true });
29
28
  }
30
- function readRequiredString(data, field, filename) {
31
- const value = data[field];
32
- if (typeof value !== "string" || value.trim().length === 0) {
33
- throw new Error(`Missing required fields (type, channelId, and text or task) in ${filename}`);
34
- }
35
- return value;
36
- }
37
- /** `text` xor `task`: a chat message, or a template for a task instance (spec 052, D2). */
38
- function parsePayload(data, filename) {
39
- const hasText = typeof data.text === "string" && data.text.trim().length > 0;
40
- const hasTask = data.task !== undefined;
41
- if (hasText === hasTask) {
42
- throw new Error(`An event needs exactly one of 'text' (a chat message) or 'task' (a task template) in ${filename}`);
43
- }
44
- if (hasText)
45
- return { text: data.text };
46
- try {
47
- return { task: validateTaskContractInput(data.task) };
48
- }
49
- catch (error) {
50
- throw new Error(`Invalid 'task' template in ${filename}: ${errorMessage(error)}`);
51
- }
52
- }
53
- function parsePreAction(data, filename) {
54
- if (!data.preAction)
55
- return undefined;
56
- if (!isPlainObject(data.preAction)) {
57
- throw new Error(`Invalid 'preAction' field in ${filename}, expected an object`);
58
- }
59
- const action = data.preAction;
60
- if (action.type !== "bash") {
61
- throw new Error(`Unsupported preAction type '${String(action.type)}' in ${filename}, only 'bash' is supported`);
62
- }
63
- if (typeof action.command !== "string" || action.command.trim().length === 0) {
64
- throw new Error(`Missing or empty 'preAction.command' in ${filename}`);
65
- }
66
- if (action.timeout !== undefined) {
67
- if (typeof action.timeout !== "number" || !Number.isFinite(action.timeout) || action.timeout <= 0) {
68
- throw new Error(`Invalid 'preAction.timeout' in ${filename}, expected a positive millisecond value`);
69
- }
70
- }
71
- return {
72
- type: "bash",
73
- command: action.command,
74
- ...(typeof action.timeout === "number" ? { timeout: action.timeout } : {}),
75
- };
76
- }
77
- export function parseScheduledEventContent(content, filename) {
78
- const data = JSON.parse(content);
79
- if (!isPlainObject(data)) {
80
- throw new Error(`Missing required fields (type, channelId, and text or task) in ${filename}`);
81
- }
82
- const type = readRequiredString(data, "type", filename);
83
- const channelId = readRequiredString(data, "channelId", filename);
84
- const payload = parsePayload(data, filename);
85
- const preAction = parsePreAction(data, filename);
86
- switch (type) {
87
- // Removed in spec 031 (D4): an event that fires the moment it is written is a
88
- // self-triggering loop with no gate in front of it, and nothing in the runtime produced
89
- // one. Rejecting it here — rather than only in `event_manage` — is what makes the guard
90
- // enforced, since the events directory is agent-writable.
91
- case "immediate":
92
- throw new Error(`Immediate events are no longer supported (${filename}); do the work in the current turn, ` +
93
- "or schedule a one-shot at least 2 minutes out via event_manage.");
94
- case "one-shot": {
95
- if (typeof data.at !== "string" || data.at.trim().length === 0) {
96
- throw new Error(`Missing 'at' field for one-shot event in ${filename}`);
97
- }
98
- return { type, channelId, ...payload, at: data.at, ...(preAction ? { preAction } : {}) };
99
- }
100
- case "periodic": {
101
- if (typeof data.schedule !== "string" || data.schedule.trim().length === 0) {
102
- throw new Error(`Missing 'schedule' field for periodic event in ${filename}`);
103
- }
104
- return {
105
- type,
106
- channelId,
107
- ...payload,
108
- schedule: data.schedule,
109
- ...(preAction ? { preAction } : {}),
110
- };
111
- }
112
- default:
113
- throw new Error(`Unknown event type '${type}' in ${filename}`);
114
- }
115
- }
116
- /**
117
- * Stable, provenance-derived dispatch id (spec 031, D1).
118
- *
119
- * The identity of a wake is its *occurrence*, never the moment it happened to be executed.
120
- * A one-shot keyed on its own `at` therefore lands on the same durable record whether it
121
- * arrives via the outbox retry or via the post-restart file recovery path, so the two
122
- * independent retry systems can no longer deliver the same occurrence twice. A live periodic
123
- * occurrence is keyed on Croner's callback start time, so its durable outbox retries collapse
124
- * while the next callback produces a genuinely new record.
125
- */
126
29
  function eventDispatchId(filename, event, occurrence) {
127
30
  const name = eventNameFromFilename(filename);
128
31
  return event.type === "one-shot" ? `event:${name}:${event.at}` : `event:${name}:${occurrence.toISOString()}`;
@@ -208,7 +111,7 @@ export class EventsWatcher {
208
111
  chmodSync(this.options.historyPath, 0o600);
209
112
  }
210
113
  catch (err) {
211
- log.logWarning("Failed to initialize event history file", String(err));
114
+ log.logWarn("events.history.init_failed", "Event history file init failed", { reason: String(err) });
212
115
  }
213
116
  }
214
117
  appendHistory(record) {
@@ -223,7 +126,7 @@ export class EventsWatcher {
223
126
  ...rest,
224
127
  };
225
128
  if (!this.historyAppender?.tryAppend(fullRecord, "critical")) {
226
- log.logWarning("Failed to queue event history", "Retry after pending event history writes drain");
129
+ log.logWarn("events.history.queue_full", "Event history write dropped while earlier writes drain");
227
130
  }
228
131
  }
229
132
  appendEventHistory(filename, event, action, result, extra = {}) {
@@ -255,7 +158,7 @@ export class EventsWatcher {
255
158
  files = readdirSync(this.eventsDir).filter((f) => f.endsWith(".json"));
256
159
  }
257
160
  catch (err) {
258
- log.logWarning("Failed to read events directory", String(err));
161
+ log.logWarn("events.dir.read_failed", "Events directory read failed", { reason: String(err) });
259
162
  return;
260
163
  }
261
164
  for (let offset = 0; this.started && offset < files.length; offset += SCAN_CONCURRENCY) {
@@ -264,7 +167,10 @@ export class EventsWatcher {
264
167
  await this.handleFile(filename);
265
168
  }
266
169
  catch (err) {
267
- log.logWarning(`Failed to restore event file: ${filename}`, errorMessage(err));
170
+ log.logWarn("events.file.restore_failed", "Event file restore failed", {
171
+ reason: errorMessage(err),
172
+ fields: { file: filename },
173
+ });
268
174
  }
269
175
  }));
270
176
  }
@@ -290,7 +196,10 @@ export class EventsWatcher {
290
196
  */
291
197
  handleFileSafely(filename) {
292
198
  void this.handleFile(filename).catch((err) => {
293
- log.logWarning(`Failed to load event file: ${filename}`, errorMessage(err));
199
+ log.logWarn("events.file.load_failed", "Event file load failed", {
200
+ reason: errorMessage(err),
201
+ fields: { file: filename },
202
+ });
294
203
  });
295
204
  }
296
205
  handleDelete(filename) {
@@ -348,7 +257,10 @@ export class EventsWatcher {
348
257
  }
349
258
  }
350
259
  if (!event) {
351
- log.logWarning(`Failed to parse event file after ${MAX_RETRIES} retries: ${filename}`, lastError?.message);
260
+ log.logWarn("events.file.parse_failed", "Event file parse failed", {
261
+ reason: lastError?.message,
262
+ fields: { file: filename, attempts: MAX_RETRIES },
263
+ });
352
264
  this.appendHistory({
353
265
  filename,
354
266
  eventType: "unknown",
@@ -361,7 +273,7 @@ export class EventsWatcher {
361
273
  }
362
274
  const rejection = this.admissionFailure(filename, event);
363
275
  if (rejection) {
364
- log.logWarning(`Rejected event file: ${filename}`, rejection);
276
+ log.logWarn("events.file.rejected", "Event file rejected", { reason: rejection, fields: { file: filename } });
365
277
  this.appendEventHistory(filename, event, "invalid", "error", { reason: rejection });
366
278
  this.markInvalid(filename, rejection);
367
279
  return;
@@ -416,7 +328,9 @@ export class EventsWatcher {
416
328
  const atTime = parseLocalTime(event.at);
417
329
  const now = Date.now();
418
330
  if (atTime === undefined) {
419
- log.logWarning(`Invalid one-shot time for ${filename}: ${event.at}`);
331
+ log.logWarn("events.oneshot.invalid_time", "One-shot event time invalid", {
332
+ fields: { file: filename, at: event.at },
333
+ });
420
334
  this.appendEventHistory(filename, event, "invalid", "error", { reason: `Invalid one-shot time: ${event.at}` });
421
335
  this.markInvalid(filename, `Invalid one-shot time: ${event.at}`);
422
336
  return;
@@ -431,7 +345,9 @@ export class EventsWatcher {
431
345
  }
432
346
  const delay = atTime - now;
433
347
  if (delay > MAX_ONE_SHOT_DELAY_MS) {
434
- log.logWarning(`One-shot event exceeds maximum supported delay for ${filename}: ${event.at}. Use a periodic cron event instead.`);
348
+ log.logWarn("events.oneshot.too_far", "One-shot event exceeds the maximum delay; use a periodic event", {
349
+ fields: { file: filename, at: event.at },
350
+ });
435
351
  this.appendEventHistory(filename, event, "skipped", "skipped", {
436
352
  reason: `One-shot event exceeds maximum supported delay: ${event.at}`,
437
353
  });
@@ -450,7 +366,10 @@ export class EventsWatcher {
450
366
  await this.execute(filename, event);
451
367
  }
452
368
  catch (err) {
453
- log.logWarning(`One-shot event execution failed: ${filename}`, String(err));
369
+ log.logWarn("events.oneshot.failed", "One-shot event execution failed", {
370
+ reason: String(err),
371
+ fields: { file: filename },
372
+ });
454
373
  this.appendEventHistory(filename, event, "skipped", "error", {
455
374
  reason: errorMessage(err),
456
375
  });
@@ -468,7 +387,10 @@ export class EventsWatcher {
468
387
  await this.execute(filename, event, false, cron.currentRun() ?? new Date());
469
388
  }
470
389
  catch (err) {
471
- log.logWarning(`Periodic event execution failed: ${filename}`, String(err));
390
+ log.logWarn("events.periodic.failed", "Periodic event execution failed", {
391
+ reason: String(err),
392
+ fields: { file: filename },
393
+ });
472
394
  this.appendEventHistory(filename, event, "skipped", "error", {
473
395
  reason: errorMessage(err),
474
396
  });
@@ -480,7 +402,10 @@ export class EventsWatcher {
480
402
  this.appendEventHistory(filename, event, "scheduled", "ok", next ? { nextRunAt: formatLocalTime(next) } : {});
481
403
  }
482
404
  catch (err) {
483
- log.logWarning(`Invalid cron schedule for ${filename}: ${event.schedule}`, String(err));
405
+ log.logWarn("events.periodic.invalid_cron", "Periodic event cron invalid", {
406
+ reason: String(err),
407
+ fields: { file: filename, schedule: event.schedule },
408
+ });
484
409
  this.appendEventHistory(filename, event, "invalid", "error", {
485
410
  reason: `Invalid cron schedule: ${event.schedule}\n${String(err)}`,
486
411
  });
@@ -572,7 +497,9 @@ export class EventsWatcher {
572
497
  // next tick, so just warn. One-shot/immediate events would otherwise be
573
498
  // GC'd as "past" with no trace, so leave a visible error marker (and keep
574
499
  // the source file) making the loss auditable rather than a silent hole.
575
- log.logWarning(`Event queue full, could not enqueue: ${filename}`);
500
+ log.logWarn("events.enqueue.queue_full", "Event not enqueued: channel queue full", {
501
+ fields: { file: filename },
502
+ });
576
503
  this.appendEventHistory(filename, event, "queue_full", "error", {
577
504
  reason: "channel queue full",
578
505
  queue: { accepted: false },
@@ -612,7 +539,10 @@ export class EventsWatcher {
612
539
  }
613
540
  catch (err) {
614
541
  const reason = errorMessage(err);
615
- log.logWarning(`Could not spawn a task for event: ${filename}`, reason);
542
+ log.logWarn("events.task_spawn.failed", "Task spawn for event failed", {
543
+ reason: reason,
544
+ fields: { file: filename },
545
+ });
616
546
  this.appendEventHistory(filename, event, "skipped", "error", { reason });
617
547
  if (deleteAfter) {
618
548
  this.markInvalid(filename, `Could not create the task instance at ${new Date().toISOString()}: ${reason}`);
@@ -624,7 +554,10 @@ export class EventsWatcher {
624
554
  if (this.commandGuardConfig?.enabled) {
625
555
  const guardResult = guardCommand(action.command, this.commandGuardConfig);
626
556
  if (!guardResult.allowed) {
627
- log.logWarning(`Pre-action command blocked by guard for ${filename}: ${guardResult.reason}`);
557
+ log.logWarn("events.preaction.blocked", "Event pre-action blocked by guard", {
558
+ reason: guardResult.reason,
559
+ fields: { file: filename },
560
+ });
628
561
  throw new EventPreActionError("blocked", `guard: ${guardResult.reason}`, {
629
562
  durationMs: Date.now() - startedAt,
630
563
  });
@@ -656,7 +589,10 @@ export class EventsWatcher {
656
589
  }
657
590
  catch (err) {
658
591
  if (err instanceof Error && "code" in err && err.code !== "ENOENT") {
659
- log.logWarning(`Failed to delete event file: ${filename}`, String(err));
592
+ log.logWarn("events.file.delete_failed", "Event file delete failed", {
593
+ reason: String(err),
594
+ fields: { file: filename },
595
+ });
660
596
  }
661
597
  }
662
598
  this.clearInvalidMarker(filename);
@@ -676,7 +612,10 @@ export class EventsWatcher {
676
612
  writeFileAtomicallySync(this.getInvalidMarkerPath(filename), [`timestamp: ${formatLocalTime()}`, `file: ${filename}`, "", message.trim()].join("\n"));
677
613
  }
678
614
  catch (err) {
679
- log.logWarning(`Failed to write event error marker: ${filename}`, String(err));
615
+ log.logWarn("events.marker.write_failed", "Event error marker write failed", {
616
+ reason: String(err),
617
+ fields: { file: filename },
618
+ });
680
619
  }
681
620
  this.knownFiles.add(filename);
682
621
  }
@@ -687,7 +626,10 @@ export class EventsWatcher {
687
626
  }
688
627
  catch (err) {
689
628
  if (err instanceof Error && "code" in err && err.code !== "ENOENT") {
690
- log.logWarning(`Failed to delete event error marker: ${filename}`, String(err));
629
+ log.logWarn("events.marker.delete_failed", "Event error marker delete failed", {
630
+ reason: String(err),
631
+ fields: { file: filename },
632
+ });
691
633
  }
692
634
  }
693
635
  }
package/dist/executor.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createWriteStream, existsSync } from "node:fs";
2
2
  import { join as joinPath, delimiter as PATH_DELIMITER } from "node:path";
3
3
  import { spawn } from "child_process";
4
- import { logWarning } from "./log.js";
4
+ import * as log from "./log.js";
5
5
  /**
6
6
  * The `bash` tool's schema says "Bash command" and models write bash-only syntax (`[[ ]]`, arrays,
7
7
  * `set -o pipefail`, process substitution). `/bin/sh` is `dash` on many hosts, so those fail with a
@@ -24,7 +24,7 @@ function resolveShell() {
24
24
  }
25
25
  const RESOLVED_SHELL = resolveShell();
26
26
  if (!RESOLVED_SHELL.isBash) {
27
- logWarning("executor: no `bash` binary found on this host; the bash tool is running commands via POSIX /bin/sh");
27
+ log.logWarn("runtime.executor.no_bash", "No bash binary on this host; the bash tool runs commands via POSIX /bin/sh");
28
28
  }
29
29
  /** True when the executor found a real `bash`; `bash.ts` uses this to keep its description honest. */
30
30
  export const EXECUTOR_SHELL_IS_BASH = RESOLVED_SHELL.isBash;
package/dist/index.d.ts CHANGED
@@ -9,9 +9,11 @@
9
9
  * Keep this list small. Every name added here also becomes a knip blind spot,
10
10
  * because `src/index.ts` is a knip entry point.
11
11
  */
12
- export type { ChannelContext, FinalDelivery, ProgressStyle } from "./channel/channel-context.js";
12
+ export { type BootstrapPaths, type BootstrapResult, isBootstrapExitError } from "./app/home.js";
13
+ export type { ChannelContext, FinalDelivery, ProgressStyle, ResponseMode } from "./channel/channel-context.js";
14
+ export type { PipiclawSettings } from "./config/settings.js";
15
+ export { DingTalkBot } from "./dingtalk/bot.js";
16
+ export type { DingTalkConfig } from "./dingtalk/config.js";
17
+ export type { DingTalkEvent, DingTalkHandler } from "./dingtalk/handler.js";
13
18
  export { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "./paths.js";
14
- export { type BootstrapPaths, type BootstrapResult, isBootstrapExitError } from "./runtime/app-home.js";
15
19
  export { type AppContext, type BootstrapOptions, bootstrap } from "./runtime/bootstrap.js";
16
- export { DingTalkBot, type DingTalkConfig, type DingTalkEvent, type DingTalkHandler, type ResponseMode, } from "./runtime/dingtalk.js";
17
- export type { PipiclawSettings } from "./settings.js";
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@
9
9
  * Keep this list small. Every name added here also becomes a knip blind spot,
10
10
  * because `src/index.ts` is a knip entry point.
11
11
  */
12
+ export { isBootstrapExitError } from "./app/home.js";
13
+ export { DingTalkBot } from "./dingtalk/bot.js";
12
14
  export { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "./paths.js";
13
- export { isBootstrapExitError } from "./runtime/app-home.js";
14
15
  export { bootstrap } from "./runtime/bootstrap.js";
15
- export { DingTalkBot, } from "./runtime/dingtalk.js";
@@ -0,0 +1,42 @@
1
+ /** Every scratch file a single job owns, all derived from its spill path. */
2
+ export interface JobArtifacts {
3
+ spillFile: string;
4
+ exitFile: string;
5
+ exitTmp: string;
6
+ readyFile: string;
7
+ readyTmp: string;
8
+ metaFile: string;
9
+ metaTmp: string;
10
+ }
11
+ export declare function jobArtifacts(spillFile: string): JobArtifacts;
12
+ /**
13
+ * Build the wrapper shell that launches a background job with a verifiable startup handshake.
14
+ *
15
+ * The inner shell writes an atomic `ready` marker as its very first action — *before* the user
16
+ * command — so the parent can distinguish "wrapper live, spill writable, command about to run"
17
+ * from "launch silently failed" (a read-only spill dir, a `setsid`/`sh` that could not exec). The
18
+ * parent also writes a metadata file (pid, and under `setsid` the pgid/start-time) *before* it
19
+ * waits on the handshake, so an abort that lands mid-handshake still leaves a recoverable pid.
20
+ *
21
+ * `setsid` (when present) makes the job its own session/process-group leader (pgid == pid), so a
22
+ * later cancel/timeout can terminate the whole group. A host without it falls back to `nohup` —
23
+ * still detached and restart-safe, but single-pid, so pgid/identity are deliberately not claimed.
24
+ *
25
+ * On handshake success the parent prints `MODE`/`PID`(/`PGID`/`LSTART`) and exits 0. On failure it
26
+ * kills whatever it spawned, echoes the inner error, removes the scratch files, and exits 1.
27
+ */
28
+ export declare function buildLaunchScript(command: string, art: JobArtifacts): string;
29
+ /**
30
+ * Read the launch command's stdout: an optional `MODE setsid|nohup` line followed by `PID <n>`
31
+ * and — only in `setsid` mode — `PGID <n>` / `LSTART <...>`. A bare number on its own line is also
32
+ * accepted as the pid so older/simpler executor fakes keep working. `pgid` and `pidStartedAt` are
33
+ * returned only when the job was launched under `setsid` *and* `ps` actually reported them; the
34
+ * `nohup` fallback never yields them, and the caller must then treat identity as unprovable.
35
+ */
36
+ export declare function parseLaunchOutput(stdout: string): {
37
+ pid?: number;
38
+ pgid?: number;
39
+ pidStartedAt?: string;
40
+ mode?: "setsid" | "nohup";
41
+ handshakeFailed?: boolean;
42
+ };
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Launching a background job: the wrapper shell with its verifiable startup handshake, the scratch
3
+ * files it owns, and the parser for its stdout. Pure string building and parsing (spec 054 D11).
4
+ */
5
+ import { shellEscape } from "../shared/os.js";
6
+ export function jobArtifacts(spillFile) {
7
+ return {
8
+ spillFile,
9
+ exitFile: `${spillFile}.exit`,
10
+ exitTmp: `${spillFile}.exit.tmp`,
11
+ readyFile: `${spillFile}.ready`,
12
+ readyTmp: `${spillFile}.ready.tmp`,
13
+ metaFile: `${spillFile}.meta`,
14
+ metaTmp: `${spillFile}.meta.tmp`,
15
+ };
16
+ }
17
+ /** ~2s of readiness polling: 40 iterations of a 50ms sleep in the wrapper shell. */
18
+ const LAUNCH_HANDSHAKE_MAX_POLLS = 40;
19
+ /**
20
+ * Build the wrapper shell that launches a background job with a verifiable startup handshake.
21
+ *
22
+ * The inner shell writes an atomic `ready` marker as its very first action — *before* the user
23
+ * command — so the parent can distinguish "wrapper live, spill writable, command about to run"
24
+ * from "launch silently failed" (a read-only spill dir, a `setsid`/`sh` that could not exec). The
25
+ * parent also writes a metadata file (pid, and under `setsid` the pgid/start-time) *before* it
26
+ * waits on the handshake, so an abort that lands mid-handshake still leaves a recoverable pid.
27
+ *
28
+ * `setsid` (when present) makes the job its own session/process-group leader (pgid == pid), so a
29
+ * later cancel/timeout can terminate the whole group. A host without it falls back to `nohup` —
30
+ * still detached and restart-safe, but single-pid, so pgid/identity are deliberately not claimed.
31
+ *
32
+ * On handshake success the parent prints `MODE`/`PID`(/`PGID`/`LSTART`) and exits 0. On failure it
33
+ * kills whatever it spawned, echoes the inner error, removes the scratch files, and exits 1.
34
+ */
35
+ export function buildLaunchScript(command, art) {
36
+ const spill = shellEscape(art.spillFile);
37
+ const exitFile = shellEscape(art.exitFile);
38
+ const exitTmp = shellEscape(art.exitTmp);
39
+ const ready = shellEscape(art.readyFile);
40
+ const readyTmp = shellEscape(art.readyTmp);
41
+ const meta = shellEscape(art.metaFile);
42
+ const metaTmp = shellEscape(art.metaTmp);
43
+ // Subshell around the user command so its own `exit N` only leaves the subshell and the
44
+ // exit-capture still runs; the exit code is written temp-then-renamed so a probe never reads a
45
+ // half-written `.exit`.
46
+ const inner = `printf 'ready\\n' > ${readyTmp} && mv -f ${readyTmp} ${ready} || exit 127; ` +
47
+ `( ${command} )\n__pc_rc=$?; ` +
48
+ `printf '%s\\n' "$__pc_rc" > ${exitTmp} && mv -f ${exitTmp} ${exitFile}`;
49
+ const escInner = shellEscape(inner);
50
+ // `ps` can momentarily miss a just-forked process on a loaded host: one short retry.
51
+ const psField = (field) => `"$(ps -o ${field}= -p "$__pc_pid" 2>/dev/null || { sleep 0.1; ps -o ${field}= -p "$__pc_pid" 2>/dev/null; })"`;
52
+ const handshake = (killExpr) => `__pc_i=0; while [ ! -s ${ready} ] && [ "$__pc_i" -lt ${LAUNCH_HANDSHAKE_MAX_POLLS} ]; do ` +
53
+ `sleep 0.05; __pc_i=$((__pc_i+1)); done; ` +
54
+ `if [ ! -s ${ready} ]; then ${killExpr}printf 'HANDSHAKE failed\\n'; cat ${spill} 2>/dev/null; ` +
55
+ `rm -f ${ready} ${readyTmp} ${meta} ${metaTmp} ${exitFile} ${exitTmp} ${spill}; exit 1; fi`;
56
+ const setsidKill = `kill -TERM "-$__pc_pid" 2>/dev/null; kill -TERM "$__pc_pid" 2>/dev/null; sleep 0.1; ` +
57
+ `kill -KILL "-$__pc_pid" 2>/dev/null; `;
58
+ const nohupKill = `kill -TERM "$__pc_pid" 2>/dev/null; sleep 0.1; kill -KILL "$__pc_pid" 2>/dev/null; `;
59
+ const setsidBranch = `setsid sh -c ${escInner} > ${spill} 2>&1 & __pc_pid=$!; ` +
60
+ `__pc_pgid=$(printf '%s' ${psField("pgid")} | tr -d ' '); __pc_lstart=${psField("lstart")}; ` +
61
+ `printf 'MODE setsid\\nPID %s\\nPGID %s\\nLSTART %s\\n' "$__pc_pid" "$__pc_pgid" "$__pc_lstart" ` +
62
+ `> ${metaTmp} && mv -f ${metaTmp} ${meta}; ` +
63
+ `${handshake(setsidKill)}; ` +
64
+ `printf 'MODE setsid\\nPID %s\\nPGID %s\\nLSTART %s\\n' "$__pc_pid" "$__pc_pgid" "$__pc_lstart"`;
65
+ const nohupBranch = `nohup sh -c ${escInner} > ${spill} 2>&1 & __pc_pid=$!; ` +
66
+ `printf 'MODE nohup\\nPID %s\\n' "$__pc_pid" > ${metaTmp} && mv -f ${metaTmp} ${meta}; ` +
67
+ `${handshake(nohupKill)}; ` +
68
+ `printf 'MODE nohup\\nPID %s\\n' "$__pc_pid"`;
69
+ // `umask 077`: the spill holds whatever the command printed (routinely credentials) in a
70
+ // world-readable /tmp; set the mask rather than chmod afterwards so there is no readable window.
71
+ return (`umask 077; rm -f ${exitFile} ${exitTmp} ${ready} ${readyTmp} ${meta} ${metaTmp}; ` +
72
+ `if command -v setsid >/dev/null 2>&1; then ${setsidBranch}; else ${nohupBranch}; fi`);
73
+ }
74
+ /**
75
+ * Read the launch command's stdout: an optional `MODE setsid|nohup` line followed by `PID <n>`
76
+ * and — only in `setsid` mode — `PGID <n>` / `LSTART <...>`. A bare number on its own line is also
77
+ * accepted as the pid so older/simpler executor fakes keep working. `pgid` and `pidStartedAt` are
78
+ * returned only when the job was launched under `setsid` *and* `ps` actually reported them; the
79
+ * `nohup` fallback never yields them, and the caller must then treat identity as unprovable.
80
+ */
81
+ export function parseLaunchOutput(stdout) {
82
+ let pid;
83
+ let pgid;
84
+ let pidStartedAt;
85
+ let mode;
86
+ let handshakeFailed = false;
87
+ for (const raw of stdout.split("\n")) {
88
+ const line = raw.trim();
89
+ if (!line)
90
+ continue;
91
+ if (line === "HANDSHAKE failed") {
92
+ handshakeFailed = true;
93
+ continue;
94
+ }
95
+ if (/^\d+$/.test(line)) {
96
+ pid ??= Number.parseInt(line, 10);
97
+ continue;
98
+ }
99
+ const match = line.match(/^(MODE|PID|PGID|LSTART)\s+(.*)$/);
100
+ if (!match)
101
+ continue;
102
+ const [, key, value] = match;
103
+ if (key === "MODE" && (value === "setsid" || value === "nohup"))
104
+ mode = value;
105
+ else if (key === "PID" && /^\d+$/.test(value))
106
+ pid = Number.parseInt(value, 10);
107
+ else if (key === "PGID" && /^\d+$/.test(value))
108
+ pgid = Number.parseInt(value, 10);
109
+ else if (key === "LSTART" && value)
110
+ pidStartedAt = value;
111
+ }
112
+ // The nohup fallback cannot capture these reliably; drop them even if something printed them.
113
+ if (mode === "nohup") {
114
+ pgid = undefined;
115
+ pidStartedAt = undefined;
116
+ }
117
+ return { pid, pgid, pidStartedAt, mode, handshakeFailed };
118
+ }
@@ -1,73 +1,7 @@
1
1
  import type { ChannelEvent } from "../channel/channel-event.js";
2
2
  import type { Executor } from "../executor.js";
3
3
  import { type FileStore } from "../file-store.js";
4
- /**
5
- * Per-channel manager for background bash jobs. A long command that ran synchronously would hold
6
- * the channel's run queue for its whole duration, blocking `/steer`, `/followup`, and every other
7
- * message. A background job instead returns immediately and the model can end its turn.
8
- *
9
- * Jobs live on the host, managed through shell commands (`setsid` to launch as its own process
10
- * group with a startup handshake, a three-state identity probe, a confirmed kill) with no
11
- * in-process child handles. Records
12
- * are mirrored to `state/jobs/<channelId>/<id>.json` so they survive a restart: a detached
13
- * process outlives the daemon, and losing the record while the process kept running meant orphaned
14
- * work, leaked slots, and unreachable output (spec 031, D6).
15
- *
16
- * A finished job wakes its channel by itself. Making the model predict a completion time and
17
- * arrange its own callback was a judgement call it could not make correctly, so completion is a
18
- * runtime guarantee instead.
19
- */
20
- export type JobStatus = "running" | "completed" | "failed" | "cancelled" | "lost";
21
- export interface JobSnapshot {
22
- id: string;
23
- label: string;
24
- command: string;
25
- status: JobStatus;
26
- startedAt: number;
27
- durationMs: number;
28
- exitCode?: number;
29
- /** The job's own wall-clock limit; a task's `work` ticket derives its backstop from it. */
30
- timeoutSeconds: number;
31
- /** The task this job's completion wake belongs to, if any — lets a caller verify that a
32
- * `[JOB:<id>] ... belongs to task <taskId>.` wake actually names the job it claims to (T9). */
33
- taskId?: string;
34
- }
35
- /** What should happen when the job finishes. */
36
- export interface JobWakeContract {
37
- /** Wake the channel on completion. Defaults to true — that is the point of the mechanism. */
38
- notify: boolean;
39
- /** The task this job is advancing, surfaced in the wake so the model lands in context. */
40
- taskId?: string;
41
- }
42
- interface JobRecord extends JobSnapshot {
43
- pid: number;
44
- /** Process-group id of the launched job, as `ps` reported it right after spawn. `setsid` makes
45
- * the job its own session/group leader, so this normally equals `pid` — the precondition for a
46
- * safe negative-PGID kill. Absent on records written before this was captured. */
47
- pgid?: number;
48
- /** `ps -o lstart=` for `pid` at launch: the only OS-verifiable way to tell the still-running
49
- * job apart from an unrelated process that later reused its pid. Absent on older records and
50
- * whenever `ps` was unavailable at launch — callers must then treat identity as unprovable. */
51
- pidStartedAt?: string;
52
- spillFile: string;
53
- exitFile: string;
54
- timeoutSeconds: number;
55
- contract: JobWakeContract;
56
- /** When the job reached a terminal status; drives retention of the record and spill file. */
57
- finishedAt?: number;
58
- /** Set once the completion wake has been dispatched, so a restart cannot re-announce it. */
59
- notified?: boolean;
60
- /** Set once the owning task's log has this job's settlement (spec 052, D4); guards against a second record. */
61
- taskLogged?: boolean;
62
- /**
63
- * A cancel or timeout whose kill could not be *confirmed* yet: the job stays `running` and
64
- * manageable, and every sweep re-attempts the kill until the process is proven gone, at which
65
- * point this terminal status is applied. Internal only — never surfaced in a `JobSnapshot`.
66
- */
67
- pendingKill?: "cancelled" | "failed";
68
- wakeClaimDispatchId?: string;
69
- wakeConsumedAt?: number;
70
- }
4
+ import { type JobRecord, type JobSnapshot, type JobStatus } from "./record.js";
71
5
  export interface JobStartOptions {
72
6
  signal?: AbortSignal;
73
7
  notify?: boolean;