@oyasmi/pipiclaw 0.9.4-beta.1 → 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 (291) 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 +148 -1245
  5. package/dist/agent/maintenance-context.d.ts +1 -1
  6. package/dist/agent/maintenance-context.js +1 -1
  7. package/dist/agent/prompt/resources.d.ts +3 -0
  8. package/dist/agent/prompt/resources.js +7 -1
  9. package/dist/agent/runner-factory.d.ts +1 -43
  10. package/dist/agent/{command-extension.d.ts → session/command-extension.d.ts} +4 -0
  11. package/dist/agent/{command-extension.js → session/command-extension.js} +5 -5
  12. package/dist/agent/{type-guards.d.ts → session/event-guards.d.ts} +2 -2
  13. package/dist/agent/{type-guards.js → session/event-guards.js} +5 -1
  14. package/dist/agent/session/model-selection.d.ts +47 -0
  15. package/dist/agent/session/model-selection.js +99 -0
  16. package/dist/agent/{session-adapter.d.ts → session/session-adapter.d.ts} +21 -1
  17. package/dist/agent/{session-adapter.js → session/session-adapter.js} +83 -1
  18. package/dist/agent/{session-events.d.ts → session/session-events.d.ts} +9 -5
  19. package/dist/agent/{session-events.js → session/session-events.js} +10 -10
  20. package/dist/agent/session/session-host.d.ts +200 -0
  21. package/dist/agent/session/session-host.js +621 -0
  22. package/dist/agent/{session-resource-gate.js → session/session-resource-gate.js} +2 -2
  23. package/dist/agent/{context-budget.js → turn/context-budget.js} +5 -1
  24. package/dist/agent/{progress-formatter.d.ts → turn/progress-formatter.d.ts} +4 -1
  25. package/dist/agent/{run-queue.d.ts → turn/run-queue.d.ts} +1 -1
  26. package/dist/agent/{run-queue.js → turn/run-queue.js} +3 -3
  27. package/dist/{memory → agent/turn}/task-digest.js +4 -4
  28. package/dist/agent/turn/turn-context.d.ts +14 -0
  29. package/dist/agent/turn/turn-context.js +64 -0
  30. package/dist/agent/turn/turn-finish.d.ts +50 -0
  31. package/dist/agent/turn/turn-finish.js +188 -0
  32. package/dist/agent/turn/turn-input.d.ts +43 -0
  33. package/dist/agent/turn/turn-input.js +79 -0
  34. package/dist/agent/turn/turn-pipeline.d.ts +68 -0
  35. package/dist/agent/turn/turn-pipeline.js +257 -0
  36. package/dist/agent/{turn-prompt.d.ts → turn/turn-prompt.d.ts} +2 -2
  37. package/dist/agent/{turn-prompt.js → turn/turn-prompt.js} +6 -2
  38. package/dist/agent/{turn-recovery.js → turn/turn-recovery.js} +1 -1
  39. package/dist/agent/{turn-state.d.ts → turn/turn-state.d.ts} +1 -1
  40. package/dist/agent/types.d.ts +43 -2
  41. package/dist/agent/types.js +1 -1
  42. package/dist/{models/auth-cli.d.ts → app/auth-command.d.ts} +1 -1
  43. package/dist/{models/auth-cli.js → app/auth-command.js} +11 -8
  44. package/dist/{runtime/app-home.d.ts → app/home.d.ts} +0 -2
  45. package/dist/{runtime/app-home.js → app/home.js} +4 -75
  46. package/dist/{app-services.d.ts → app/services.d.ts} +5 -5
  47. package/dist/{app-services.js → app/services.js} +10 -10
  48. package/dist/channel/channel-context.d.ts +12 -2
  49. package/dist/channel/channel-context.js +29 -2
  50. package/dist/channel/channel-event.d.ts +10 -2
  51. package/dist/channel/channel-event.js +1 -1
  52. package/dist/{runtime/project-commands.d.ts → channel/commands.d.ts} +1 -1
  53. package/dist/{runtime/project-commands.js → channel/commands.js} +1 -1
  54. package/dist/channel/store.js +4 -0
  55. package/dist/commands/catalog.d.ts +3 -3
  56. package/dist/commands/catalog.js +3 -3
  57. package/dist/{runtime/report-commands.d.ts → commands/router.d.ts} +10 -3
  58. package/dist/{runtime/report-commands.js → commands/router.js} +5 -5
  59. package/dist/{settings.d.ts → config/settings.d.ts} +7 -8
  60. package/dist/{settings.js → config/settings.js} +7 -10
  61. package/dist/{tools/config.d.ts → config/tools.d.ts} +1 -2
  62. package/dist/{tools/config.js → config/tools.js} +5 -2
  63. package/dist/dingtalk/access-token.d.ts +12 -0
  64. package/dist/dingtalk/access-token.js +51 -0
  65. package/dist/dingtalk/api.d.ts +19 -0
  66. package/dist/dingtalk/api.js +67 -0
  67. package/dist/dingtalk/bot.d.ts +97 -0
  68. package/dist/dingtalk/bot.js +389 -0
  69. package/dist/dingtalk/cards.d.ts +56 -0
  70. package/dist/dingtalk/cards.js +318 -0
  71. package/dist/{runtime → dingtalk}/channel-queue.js +3 -0
  72. package/dist/dingtalk/config.d.ts +19 -0
  73. package/dist/dingtalk/config.js +95 -0
  74. package/dist/dingtalk/connection.d.ts +57 -0
  75. package/dist/dingtalk/connection.js +356 -0
  76. package/dist/dingtalk/conversation-meta.d.ts +16 -0
  77. package/dist/dingtalk/conversation-meta.js +77 -0
  78. package/dist/{runtime → dingtalk}/delivery.d.ts +6 -2
  79. package/dist/dingtalk/handler.d.ts +90 -0
  80. package/dist/dingtalk/handler.js +1 -0
  81. package/dist/dingtalk/inbound.d.ts +66 -0
  82. package/dist/dingtalk/inbound.js +137 -0
  83. package/dist/dingtalk/media.d.ts +66 -0
  84. package/dist/dingtalk/media.js +214 -0
  85. package/dist/events/{event-commands.js → commands.js} +6 -2
  86. package/dist/events/parse.d.ts +14 -0
  87. package/dist/events/parse.js +114 -0
  88. package/dist/events/types.d.ts +93 -0
  89. package/dist/events/types.js +1 -0
  90. package/dist/events/{event-validation.d.ts → validation.d.ts} +1 -1
  91. package/dist/events/watcher.d.ts +67 -0
  92. package/dist/events/{events.js → watcher.js} +6 -109
  93. package/dist/index.d.ts +6 -4
  94. package/dist/index.js +2 -2
  95. package/dist/jobs/launch.d.ts +42 -0
  96. package/dist/jobs/launch.js +118 -0
  97. package/dist/{agent/job-manager.d.ts → jobs/manager.d.ts} +1 -67
  98. package/dist/{agent/job-manager.js → jobs/manager.js} +3 -146
  99. package/dist/jobs/record.d.ts +55 -0
  100. package/dist/jobs/record.js +36 -0
  101. package/dist/main.js +2 -2
  102. package/dist/memory/maintenance-gates.d.ts +2 -2
  103. package/dist/memory/maintenance-tuning.d.ts +15 -0
  104. package/dist/memory/maintenance-tuning.js +3 -0
  105. package/dist/memory/reflect-job.d.ts +2 -2
  106. package/dist/memory/reflect-job.js +4 -2
  107. package/dist/memory/scheduler.d.ts +3 -3
  108. package/dist/memory/scheduler.js +2 -1
  109. package/dist/memory/sidecar-worker.js +1 -1
  110. package/dist/memory/transcript.js +1 -1
  111. package/dist/{agent/model-fallback.d.ts → models/fallback.d.ts} +6 -6
  112. package/dist/{agent/model-fallback.js → models/fallback.js} +15 -28
  113. package/dist/models/login-identity.d.ts +2 -0
  114. package/dist/models/login-identity.js +83 -0
  115. package/dist/models/provider-login.d.ts +3 -1
  116. package/dist/models/provider-login.js +8 -2
  117. package/dist/models/reference.d.ts +20 -0
  118. package/dist/models/{utils.js → reference.js} +0 -48
  119. package/dist/models/{utils.d.ts → runtime.d.ts} +1 -16
  120. package/dist/models/runtime.js +52 -0
  121. package/dist/playbooks/catalog.d.ts +6 -2
  122. package/dist/playbooks/catalog.js +9 -6
  123. package/dist/runtime/bootstrap.d.ts +7 -17
  124. package/dist/runtime/bootstrap.js +37 -755
  125. package/dist/runtime/durable-dispatch.d.ts +17 -4
  126. package/dist/runtime/durable-dispatch.js +60 -18
  127. package/dist/runtime/inbound-images.d.ts +18 -0
  128. package/dist/runtime/inbound-images.js +51 -0
  129. package/dist/runtime/shutdown.d.ts +39 -0
  130. package/dist/runtime/shutdown.js +120 -0
  131. package/dist/runtime/stop-watchdog.d.ts +16 -0
  132. package/dist/runtime/stop-watchdog.js +32 -0
  133. package/dist/runtime/task-driver.d.ts +2 -2
  134. package/dist/runtime/task-driver.js +3 -3
  135. package/dist/runtime/task-migration.js +2 -2
  136. package/dist/runtime/task-spawn.d.ts +1 -1
  137. package/dist/runtime/task-spawn.js +1 -1
  138. package/dist/runtime/turn-handler.d.ts +47 -0
  139. package/dist/runtime/turn-handler.js +318 -0
  140. package/dist/runtime/turn-run.d.ts +52 -0
  141. package/dist/runtime/turn-run.js +318 -0
  142. package/dist/security/command-guard.js +4 -0
  143. package/dist/security/network.js +4 -0
  144. package/dist/security/path-guard.js +4 -0
  145. package/dist/security/types.d.ts +1 -2
  146. package/dist/security/types.js +1 -2
  147. package/dist/shared/exact-keys.d.ts +1 -1
  148. package/dist/shared/host-process.js +1 -1
  149. package/dist/shared/wake-claim.d.ts +1 -1
  150. package/dist/{runtime/skill-commands.d.ts → skills/commands.d.ts} +2 -2
  151. package/dist/{runtime/skill-commands.js → skills/commands.js} +1 -1
  152. package/dist/{agent/workspace-resources.js → skills/loader.js} +1 -1
  153. package/dist/{tools/skill-security.js → skills/validation.js} +4 -0
  154. package/dist/skills/workspace.d.ts +33 -0
  155. package/dist/skills/workspace.js +116 -0
  156. package/dist/{runtime/subagent-commands.d.ts → subagents/commands.d.ts} +4 -3
  157. package/dist/{runtime/subagent-commands.js → subagents/commands.js} +2 -2
  158. package/dist/subagents/completion-wake.d.ts +17 -0
  159. package/dist/subagents/completion-wake.js +76 -0
  160. package/dist/subagents/detached-discovery.js +1 -1
  161. package/dist/subagents/discovery.d.ts +1 -1
  162. package/dist/subagents/discovery.js +2 -2
  163. package/dist/subagents/dispatch.d.ts +33 -0
  164. package/dist/subagents/dispatch.js +190 -0
  165. package/dist/subagents/external/dispatch.d.ts +25 -0
  166. package/dist/subagents/external/dispatch.js +90 -0
  167. package/dist/subagents/external/harness.d.ts +1 -1
  168. package/dist/subagents/external/progress-tail.d.ts +1 -1
  169. package/dist/subagents/external/run.d.ts +2 -1
  170. package/dist/subagents/external/run.js +2 -2
  171. package/dist/subagents/external/settlement.d.ts +1 -1
  172. package/dist/subagents/format.d.ts +1 -1
  173. package/dist/subagents/grace.d.ts +24 -0
  174. package/dist/subagents/grace.js +57 -0
  175. package/dist/subagents/internal/outcome.d.ts +24 -0
  176. package/dist/subagents/internal/outcome.js +149 -0
  177. package/dist/subagents/internal/provider-retry.d.ts +19 -0
  178. package/dist/subagents/internal/provider-retry.js +83 -0
  179. package/dist/subagents/internal/run.d.ts +31 -0
  180. package/dist/subagents/internal/run.js +240 -0
  181. package/dist/subagents/internal/state.d.ts +43 -0
  182. package/dist/subagents/internal/state.js +48 -0
  183. package/dist/subagents/internal/worker.d.ts +51 -0
  184. package/dist/subagents/internal/worker.js +167 -0
  185. package/dist/subagents/result.d.ts +62 -0
  186. package/dist/subagents/result.js +103 -0
  187. package/dist/subagents/run-record.d.ts +222 -0
  188. package/dist/subagents/run-record.js +101 -0
  189. package/dist/subagents/run-registry.d.ts +9 -0
  190. package/dist/subagents/run-registry.js +125 -0
  191. package/dist/subagents/runs.d.ts +7 -243
  192. package/dist/subagents/runs.js +8 -291
  193. package/dist/subagents/task-envelope.d.ts +36 -0
  194. package/dist/subagents/task-envelope.js +168 -0
  195. package/dist/subagents/types.d.ts +154 -0
  196. package/dist/subagents/types.js +1 -0
  197. package/dist/subagents/verification-outcome.d.ts +1 -1
  198. package/dist/tasks/board.d.ts +2 -2
  199. package/dist/tasks/board.js +2 -2
  200. package/dist/tasks/{work-log.d.ts → bound-work.d.ts} +1 -1
  201. package/dist/tasks/{work-log.js → bound-work.js} +1 -1
  202. package/dist/tasks/brief.js +1 -1
  203. package/dist/{runtime/task-commands.d.ts → tasks/commands.d.ts} +1 -1
  204. package/dist/{runtime/task-commands.js → tasks/commands.js} +12 -8
  205. package/dist/tasks/contract-input.d.ts +1 -1
  206. package/dist/tasks/contract-input.js +1 -1
  207. package/dist/tasks/create.js +1 -1
  208. package/dist/tasks/{log.js → loop-log.js} +1 -1
  209. package/dist/tasks/mutation-lock.js +1 -1
  210. package/dist/tasks/session-path.js +1 -1
  211. package/dist/tasks/steer.js +1 -1
  212. package/dist/tasks/store.js +2 -2
  213. package/dist/tools/bash.d.ts +1 -1
  214. package/dist/tools/{tool-details.d.ts → contract/details.d.ts} +2 -2
  215. package/dist/tools/{tool-details.js → contract/details.js} +4 -4
  216. package/dist/tools/{presentation.js → contract/presentation.js} +3 -3
  217. package/dist/tools/event-manage.d.ts +1 -1
  218. package/dist/tools/event-manage.js +4 -4
  219. package/dist/tools/index.d.ts +3 -3
  220. package/dist/tools/index.js +7 -6
  221. package/dist/tools/job.d.ts +1 -1
  222. package/dist/tools/registry.d.ts +7 -7
  223. package/dist/tools/registry.js +6 -6
  224. package/dist/tools/session-search.d.ts +1 -1
  225. package/dist/tools/skill.d.ts +2 -34
  226. package/dist/tools/skill.js +8 -116
  227. package/dist/tools/subagent-manage.js +4 -3
  228. package/dist/tools/subagent.d.ts +46 -0
  229. package/dist/tools/subagent.js +127 -0
  230. package/dist/tools/{task-manage.d.ts → task-manage/factory.d.ts} +7 -3
  231. package/dist/tools/{task-manage.js → task-manage/factory.js} +7 -7
  232. package/dist/tools/task-manage/lifecycle.js +2 -2
  233. package/dist/tools/task-manage/log-view.js +2 -2
  234. package/dist/tools/task-manage/shared.js +3 -3
  235. package/dist/tools/task-manage/step-end.js +3 -3
  236. package/dist/tools/task-manage/types.d.ts +1 -1
  237. package/dist/tools/web-fetch.d.ts +1 -1
  238. package/dist/tools/web-search.d.ts +1 -1
  239. package/dist/tui/app.d.ts +1 -1
  240. package/dist/tui/app.js +6 -6
  241. package/dist/tui/cli.d.ts +1 -1
  242. package/dist/tui/cli.js +1 -1
  243. package/dist/tui/frontend.d.ts +44 -0
  244. package/dist/tui/frontend.js +13 -0
  245. package/dist/tui/pitui-frontend.d.ts +1 -1
  246. package/dist/tui/plain-frontend.d.ts +1 -1
  247. package/dist/tui/renderer.d.ts +3 -42
  248. package/dist/tui/terminal-context.d.ts +2 -2
  249. package/dist/tui/terminal-media-sender.d.ts +1 -1
  250. package/dist/tui/turn-controller.d.ts +1 -1
  251. package/dist/usage/ledger.js +4 -0
  252. package/dist/{shared/types.d.ts → usage/totals.d.ts} +3 -0
  253. package/dist/web/client.d.ts +5 -1
  254. package/dist/web/client.js +4 -0
  255. package/dist/web/config.d.ts +1 -1
  256. package/dist/web/fetch.d.ts +1 -1
  257. package/dist/web/search-providers.d.ts +1 -1
  258. package/dist/web/search.d.ts +1 -1
  259. package/package.json +9 -7
  260. package/dist/events/events.d.ts +0 -159
  261. package/dist/runtime/dingtalk.d.ts +0 -272
  262. package/dist/runtime/dingtalk.js +0 -1470
  263. package/dist/subagents/tool.d.ts +0 -213
  264. package/dist/subagents/tool.js +0 -1282
  265. /package/dist/{runtime → agent/prompt}/workspace-templates.d.ts +0 -0
  266. /package/dist/{runtime → agent/prompt}/workspace-templates.js +0 -0
  267. /package/dist/agent/{session-resource-gate.d.ts → session/session-resource-gate.d.ts} +0 -0
  268. /package/dist/agent/{context-budget.d.ts → turn/context-budget.d.ts} +0 -0
  269. /package/dist/agent/{progress-formatter.js → turn/progress-formatter.js} +0 -0
  270. /package/dist/{memory → agent/turn}/task-digest.d.ts +0 -0
  271. /package/dist/agent/{turn-error.d.ts → turn/turn-error.d.ts} +0 -0
  272. /package/dist/agent/{turn-error.js → turn/turn-error.js} +0 -0
  273. /package/dist/agent/{turn-recovery.d.ts → turn/turn-recovery.d.ts} +0 -0
  274. /package/dist/agent/{turn-state.js → turn/turn-state.js} +0 -0
  275. /package/dist/{runtime → app}/proxy.d.ts +0 -0
  276. /package/dist/{runtime → app}/proxy.js +0 -0
  277. /package/dist/{runtime → dingtalk}/channel-queue.d.ts +0 -0
  278. /package/dist/{runtime → dingtalk}/delivery.js +0 -0
  279. /package/dist/{runtime → dingtalk}/inbound-media.d.ts +0 -0
  280. /package/dist/{runtime → dingtalk}/inbound-media.js +0 -0
  281. /package/dist/events/{event-commands.d.ts → commands.d.ts} +0 -0
  282. /package/dist/events/{event-validation.js → validation.js} +0 -0
  283. /package/dist/{agent/workspace-resources.d.ts → skills/loader.d.ts} +0 -0
  284. /package/dist/{tools/skill-security.d.ts → skills/validation.d.ts} +0 -0
  285. /package/dist/tasks/{ledger.d.ts → contract.d.ts} +0 -0
  286. /package/dist/tasks/{ledger.js → contract.js} +0 -0
  287. /package/dist/tasks/{log.d.ts → loop-log.d.ts} +0 -0
  288. /package/dist/tools/{subagent-tool-names.d.ts → contract/names.d.ts} +0 -0
  289. /package/dist/tools/{subagent-tool-names.js → contract/names.js} +0 -0
  290. /package/dist/tools/{presentation.d.ts → contract/presentation.d.ts} +0 -0
  291. /package/dist/{shared/types.js → usage/totals.js} +0 -0
@@ -1,5 +1,5 @@
1
1
  import type { SecurityConfig } from "../security/types.js";
2
- import type { ScheduledEvent } from "./events.js";
2
+ import type { ScheduledEvent } from "./types.js";
3
3
  /**
4
4
  * Admission rules for scheduled events (spec 031, D4).
5
5
  *
@@ -0,0 +1,67 @@
1
+ import type { ChannelEventSink } from "../channel/channel-event.js";
2
+ import type { Executor } from "../executor.js";
3
+ import type { SecurityConfig } from "../security/types.js";
4
+ import type { EventsWatcherOptions } from "./types.js";
5
+ export declare class EventsWatcher {
6
+ private eventsDir;
7
+ private bot;
8
+ private executor;
9
+ private commandGuardConfig?;
10
+ private options;
11
+ private timers;
12
+ private crons;
13
+ private debounceTimers;
14
+ private startTime;
15
+ private watcher;
16
+ private started;
17
+ private knownFiles;
18
+ private readonly historyAppender?;
19
+ constructor(eventsDir: string, bot: ChannelEventSink, executor: Executor, commandGuardConfig?: SecurityConfig["commandGuard"] | undefined, options?: EventsWatcherOptions);
20
+ start(): void;
21
+ stop(): void;
22
+ flush(): Promise<void>;
23
+ private ensureHistoryFile;
24
+ private appendHistory;
25
+ private appendEventHistory;
26
+ private debounce;
27
+ private scanExisting;
28
+ private handleFileChange;
29
+ /**
30
+ * Watch callbacks are the top of their own stack, so a rejection here reaches nobody — and
31
+ * `handleFile` can reject: reloading a due one-shot dispatches it inline, and dispatch
32
+ * writes to disk. `scanExisting` already wraps its own calls; this is the same guard for
33
+ * the live path. One bad file must not take the watcher, or the process, down with it.
34
+ */
35
+ private handleFileSafely;
36
+ private handleDelete;
37
+ private cancelScheduled;
38
+ private handleFile;
39
+ private parseEvent;
40
+ /**
41
+ * The admission gate (spec 031, D4). `event_manage` applies the same rules first, but the
42
+ * events directory is agent-writable, so a file that arrived any other way is only ever
43
+ * stopped here. Returns the rejection reason, or undefined when the event may be scheduled.
44
+ */
45
+ private admissionFailure;
46
+ private wasWrittenAfterStart;
47
+ private handleOneShot;
48
+ private handlePeriodic;
49
+ private execute;
50
+ /**
51
+ * Deliver a template event: ask the runtime for a fresh task instance (spec 052, D2). The
52
+ * occurrence is the one this trigger was *due* for — a one-shot's `at`, a periodic's cron tick —
53
+ * so a post-restart replay of the same occurrence lands on the same instance instead of making a
54
+ * second one.
55
+ */
56
+ private spawnTaskInstance;
57
+ private runPreAction;
58
+ private deleteFile;
59
+ private getInvalidMarkerPath;
60
+ private markInvalid;
61
+ private clearInvalidMarker;
62
+ private sleep;
63
+ }
64
+ /**
65
+ * Create and start an events watcher.
66
+ */
67
+ export declare function createEventsWatcher(workspaceDir: string, bot: ChannelEventSink, executor: Executor, commandGuardConfig?: SecurityConfig["commandGuard"], historyPath?: string, dispatch?: EventsWatcherOptions["dispatch"], spawnTask?: EventsWatcherOptions["spawnTask"]): EventsWatcher;
@@ -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 { EventDefinitionError, 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,115 +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 EventDefinitionError("missing-field", `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 EventDefinitionError("payload", `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 EventDefinitionError("task-template", `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 EventDefinitionError("pre-action", `Invalid 'preAction' field in ${filename}, expected an object`);
58
- }
59
- const action = data.preAction;
60
- if (action.type !== "bash") {
61
- throw new EventDefinitionError("pre-action", `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 EventDefinitionError("pre-action", `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 EventDefinitionError("pre-action", `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
- let data;
79
- try {
80
- data = JSON.parse(content);
81
- }
82
- catch (error) {
83
- throw new EventDefinitionError("malformed", `Invalid JSON in ${filename}: ${errorMessage(error)}`);
84
- }
85
- if (!isPlainObject(data)) {
86
- throw new EventDefinitionError("missing-field", `Missing required fields (type, channelId, and text or task) in ${filename}`);
87
- }
88
- const type = readRequiredString(data, "type", filename);
89
- const channelId = readRequiredString(data, "channelId", filename);
90
- const payload = parsePayload(data, filename);
91
- const preAction = parsePreAction(data, filename);
92
- switch (type) {
93
- // Removed in spec 031 (D4): an event that fires the moment it is written is a
94
- // self-triggering loop with no gate in front of it, and nothing in the runtime produced
95
- // one. Rejecting it here — rather than only in `event_manage` — is what makes the guard
96
- // enforced, since the events directory is agent-writable.
97
- case "immediate":
98
- throw new EventDefinitionError("immediate", `Immediate events are no longer supported (${filename}); do the work in the current turn, ` +
99
- "or schedule a one-shot at least 2 minutes out via event_manage.");
100
- case "one-shot": {
101
- if (typeof data.at !== "string" || data.at.trim().length === 0) {
102
- throw new EventDefinitionError("missing-field", `Missing 'at' field for one-shot event in ${filename}`);
103
- }
104
- return { type, channelId, ...payload, at: data.at, ...(preAction ? { preAction } : {}) };
105
- }
106
- case "periodic": {
107
- if (typeof data.schedule !== "string" || data.schedule.trim().length === 0) {
108
- throw new EventDefinitionError("missing-field", `Missing 'schedule' field for periodic event in ${filename}`);
109
- }
110
- return {
111
- type,
112
- channelId,
113
- ...payload,
114
- schedule: data.schedule,
115
- ...(preAction ? { preAction } : {}),
116
- };
117
- }
118
- default:
119
- throw new EventDefinitionError("unknown-type", `Unknown event type '${type}' in ${filename}`);
120
- }
121
- }
122
- /**
123
- * Stable, provenance-derived dispatch id (spec 031, D1).
124
- *
125
- * The identity of a wake is its *occurrence*, never the moment it happened to be executed.
126
- * A one-shot keyed on its own `at` therefore lands on the same durable record whether it
127
- * arrives via the outbox retry or via the post-restart file recovery path, so the two
128
- * independent retry systems can no longer deliver the same occurrence twice. A live periodic
129
- * occurrence is keyed on Croner's callback start time, so its durable outbox retries collapse
130
- * while the next callback produces a genuinely new record.
131
- */
132
29
  function eventDispatchId(filename, event, occurrence) {
133
30
  const name = eventNameFromFilename(filename);
134
31
  return event.type === "one-shot" ? `event:${name}:${event.at}` : `event:${name}:${occurrence.toISOString()}`;
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;
@@ -9,77 +9,10 @@ import { writeFileAtomically } from "../shared/atomic-file.js";
9
9
  import { shellEscape } from "../shared/os.js";
10
10
  import { createSerialQueue } from "../shared/serial-queue.js";
11
11
  import { errorMessage } from "../shared/text-utils.js";
12
- import { isRecord } from "../shared/type-guards.js";
13
12
  import { beginWakeClaim, finishWakeClaim } from "../shared/wake-claim.js";
14
- import { logTaskDispatch, logTaskSettlement } from "../tasks/work-log.js";
15
- function jobArtifacts(spillFile) {
16
- return {
17
- spillFile,
18
- exitFile: `${spillFile}.exit`,
19
- exitTmp: `${spillFile}.exit.tmp`,
20
- readyFile: `${spillFile}.ready`,
21
- readyTmp: `${spillFile}.ready.tmp`,
22
- metaFile: `${spillFile}.meta`,
23
- metaTmp: `${spillFile}.meta.tmp`,
24
- };
25
- }
26
- /** ~2s of readiness polling: 40 iterations of a 50ms sleep in the wrapper shell. */
27
- const LAUNCH_HANDSHAKE_MAX_POLLS = 40;
28
- /**
29
- * Build the wrapper shell that launches a background job with a verifiable startup handshake.
30
- *
31
- * The inner shell writes an atomic `ready` marker as its very first action — *before* the user
32
- * command — so the parent can distinguish "wrapper live, spill writable, command about to run"
33
- * from "launch silently failed" (a read-only spill dir, a `setsid`/`sh` that could not exec). The
34
- * parent also writes a metadata file (pid, and under `setsid` the pgid/start-time) *before* it
35
- * waits on the handshake, so an abort that lands mid-handshake still leaves a recoverable pid.
36
- *
37
- * `setsid` (when present) makes the job its own session/process-group leader (pgid == pid), so a
38
- * later cancel/timeout can terminate the whole group. A host without it falls back to `nohup` —
39
- * still detached and restart-safe, but single-pid, so pgid/identity are deliberately not claimed.
40
- *
41
- * On handshake success the parent prints `MODE`/`PID`(/`PGID`/`LSTART`) and exits 0. On failure it
42
- * kills whatever it spawned, echoes the inner error, removes the scratch files, and exits 1.
43
- */
44
- function buildLaunchScript(command, art) {
45
- const spill = shellEscape(art.spillFile);
46
- const exitFile = shellEscape(art.exitFile);
47
- const exitTmp = shellEscape(art.exitTmp);
48
- const ready = shellEscape(art.readyFile);
49
- const readyTmp = shellEscape(art.readyTmp);
50
- const meta = shellEscape(art.metaFile);
51
- const metaTmp = shellEscape(art.metaTmp);
52
- // Subshell around the user command so its own `exit N` only leaves the subshell and the
53
- // exit-capture still runs; the exit code is written temp-then-renamed so a probe never reads a
54
- // half-written `.exit`.
55
- const inner = `printf 'ready\\n' > ${readyTmp} && mv -f ${readyTmp} ${ready} || exit 127; ` +
56
- `( ${command} )\n__pc_rc=$?; ` +
57
- `printf '%s\\n' "$__pc_rc" > ${exitTmp} && mv -f ${exitTmp} ${exitFile}`;
58
- const escInner = shellEscape(inner);
59
- // `ps` can momentarily miss a just-forked process on a loaded host: one short retry.
60
- const psField = (field) => `"$(ps -o ${field}= -p "$__pc_pid" 2>/dev/null || { sleep 0.1; ps -o ${field}= -p "$__pc_pid" 2>/dev/null; })"`;
61
- const handshake = (killExpr) => `__pc_i=0; while [ ! -s ${ready} ] && [ "$__pc_i" -lt ${LAUNCH_HANDSHAKE_MAX_POLLS} ]; do ` +
62
- `sleep 0.05; __pc_i=$((__pc_i+1)); done; ` +
63
- `if [ ! -s ${ready} ]; then ${killExpr}printf 'HANDSHAKE failed\\n'; cat ${spill} 2>/dev/null; ` +
64
- `rm -f ${ready} ${readyTmp} ${meta} ${metaTmp} ${exitFile} ${exitTmp} ${spill}; exit 1; fi`;
65
- const setsidKill = `kill -TERM "-$__pc_pid" 2>/dev/null; kill -TERM "$__pc_pid" 2>/dev/null; sleep 0.1; ` +
66
- `kill -KILL "-$__pc_pid" 2>/dev/null; `;
67
- const nohupKill = `kill -TERM "$__pc_pid" 2>/dev/null; sleep 0.1; kill -KILL "$__pc_pid" 2>/dev/null; `;
68
- const setsidBranch = `setsid sh -c ${escInner} > ${spill} 2>&1 & __pc_pid=$!; ` +
69
- `__pc_pgid=$(printf '%s' ${psField("pgid")} | tr -d ' '); __pc_lstart=${psField("lstart")}; ` +
70
- `printf 'MODE setsid\\nPID %s\\nPGID %s\\nLSTART %s\\n' "$__pc_pid" "$__pc_pgid" "$__pc_lstart" ` +
71
- `> ${metaTmp} && mv -f ${metaTmp} ${meta}; ` +
72
- `${handshake(setsidKill)}; ` +
73
- `printf 'MODE setsid\\nPID %s\\nPGID %s\\nLSTART %s\\n' "$__pc_pid" "$__pc_pgid" "$__pc_lstart"`;
74
- const nohupBranch = `nohup sh -c ${escInner} > ${spill} 2>&1 & __pc_pid=$!; ` +
75
- `printf 'MODE nohup\\nPID %s\\n' "$__pc_pid" > ${metaTmp} && mv -f ${metaTmp} ${meta}; ` +
76
- `${handshake(nohupKill)}; ` +
77
- `printf 'MODE nohup\\nPID %s\\n' "$__pc_pid"`;
78
- // `umask 077`: the spill holds whatever the command printed (routinely credentials) in a
79
- // world-readable /tmp; set the mask rather than chmod afterwards so there is no readable window.
80
- return (`umask 077; rm -f ${exitFile} ${exitTmp} ${ready} ${readyTmp} ${meta} ${metaTmp}; ` +
81
- `if command -v setsid >/dev/null 2>&1; then ${setsidBranch}; else ${nohupBranch}; fi`);
82
- }
13
+ import { logTaskDispatch, logTaskSettlement } from "../tasks/bound-work.js";
14
+ import { buildLaunchScript, jobArtifacts, parseLaunchOutput } from "./launch.js";
15
+ import { isTerminal, parseJobRecord, toSnapshot } from "./record.js";
83
16
  /** Outcomes that prove the job's process is gone — safe to apply a terminal status. */
84
17
  const KILL_CONFIRMED_GONE = new Set([
85
18
  "terminated",
@@ -113,69 +46,6 @@ const JOB_OUTPUT_READ_MAX_BYTES = 512 * 1024;
113
46
  function jobSpillPath(id, spillDir) {
114
47
  return join(spillDir ?? tmpdir(), `pipiclaw-job-${id}.log`);
115
48
  }
116
- function isTerminal(status) {
117
- return status !== "running";
118
- }
119
- /** Accept a persisted record only if the fields the manager actually relies on are intact. */
120
- function parseJobRecord(raw) {
121
- const value = JSON.parse(raw);
122
- if (!isRecord(value) ||
123
- typeof value.id !== "string" ||
124
- typeof value.pid !== "number" ||
125
- typeof value.spillFile !== "string" ||
126
- typeof value.exitFile !== "string" ||
127
- typeof value.startedAt !== "number" ||
128
- typeof value.timeoutSeconds !== "number" ||
129
- !isRecord(value.contract)) {
130
- return undefined;
131
- }
132
- return value;
133
- }
134
- /**
135
- * Read the launch command's stdout: an optional `MODE setsid|nohup` line followed by `PID <n>`
136
- * and — only in `setsid` mode — `PGID <n>` / `LSTART <...>`. A bare number on its own line is also
137
- * accepted as the pid so older/simpler executor fakes keep working. `pgid` and `pidStartedAt` are
138
- * returned only when the job was launched under `setsid` *and* `ps` actually reported them; the
139
- * `nohup` fallback never yields them, and the caller must then treat identity as unprovable.
140
- */
141
- function parseLaunchOutput(stdout) {
142
- let pid;
143
- let pgid;
144
- let pidStartedAt;
145
- let mode;
146
- let handshakeFailed = false;
147
- for (const raw of stdout.split("\n")) {
148
- const line = raw.trim();
149
- if (!line)
150
- continue;
151
- if (line === "HANDSHAKE failed") {
152
- handshakeFailed = true;
153
- continue;
154
- }
155
- if (/^\d+$/.test(line)) {
156
- pid ??= Number.parseInt(line, 10);
157
- continue;
158
- }
159
- const match = line.match(/^(MODE|PID|PGID|LSTART)\s+(.*)$/);
160
- if (!match)
161
- continue;
162
- const [, key, value] = match;
163
- if (key === "MODE" && (value === "setsid" || value === "nohup"))
164
- mode = value;
165
- else if (key === "PID" && /^\d+$/.test(value))
166
- pid = Number.parseInt(value, 10);
167
- else if (key === "PGID" && /^\d+$/.test(value))
168
- pgid = Number.parseInt(value, 10);
169
- else if (key === "LSTART" && value)
170
- pidStartedAt = value;
171
- }
172
- // The nohup fallback cannot capture these reliably; drop them even if something printed them.
173
- if (mode === "nohup") {
174
- pgid = undefined;
175
- pidStartedAt = undefined;
176
- }
177
- return { pid, pgid, pidStartedAt, mode, handshakeFailed };
178
- }
179
49
  function sleep(ms, signal) {
180
50
  return new Promise((resolve) => {
181
51
  const timer = setTimeout(resolve, ms);
@@ -185,19 +55,6 @@ function sleep(ms, signal) {
185
55
  }, { once: true });
186
56
  });
187
57
  }
188
- function toSnapshot(record) {
189
- return {
190
- id: record.id,
191
- label: record.label,
192
- command: record.command,
193
- status: record.status,
194
- startedAt: record.startedAt,
195
- durationMs: record.status === "running" ? Date.now() - record.startedAt : record.durationMs,
196
- exitCode: record.exitCode,
197
- timeoutSeconds: record.timeoutSeconds,
198
- taskId: record.contract.taskId,
199
- };
200
- }
201
58
  export class ChannelJobManager {
202
59
  constructor(channelId, executor, options = {}) {
203
60
  this.channelId = channelId;