@oyasmi/pipiclaw 0.9.5 → 0.9.6-beta.1

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 (182) hide show
  1. package/README.en.md +220 -126
  2. package/README.md +217 -123
  3. package/dist/agent/channel-runner.d.ts +1 -1
  4. package/dist/agent/channel-runner.js +1 -1
  5. package/dist/agent/prompt/sections.js +1 -1
  6. package/dist/agent/prompt/types.d.ts +2 -1
  7. package/dist/agent/session/compaction.d.ts +2 -0
  8. package/dist/agent/session/compaction.js +22 -14
  9. package/dist/agent/session/session-host.d.ts +1 -1
  10. package/dist/agent/session/session-host.js +3 -1
  11. package/dist/agent/stop-watchdog.js +5 -1
  12. package/dist/agent/turn/turn-state.d.ts +2 -0
  13. package/dist/agent/turn/turn-state.js +2 -1
  14. package/dist/agent/types.d.ts +3 -1
  15. package/dist/channel/attachments.d.ts +4 -0
  16. package/dist/channel/attachments.js +4 -0
  17. package/dist/channel/store.d.ts +1 -1
  18. package/dist/commands/catalog.js +25 -9
  19. package/dist/commands/router.js +5 -1
  20. package/dist/desk/commands.d.ts +14 -2
  21. package/dist/desk/commands.js +68 -20
  22. package/dist/desk/registry.d.ts +6 -2
  23. package/dist/desk/registry.js +70 -4
  24. package/dist/desk/types.d.ts +17 -0
  25. package/dist/dingtalk/bot.d.ts +1 -1
  26. package/dist/dingtalk/bot.js +4 -3
  27. package/dist/dingtalk/delivery.js +13 -8
  28. package/dist/dingtalk/inbound-media.d.ts +36 -14
  29. package/dist/dingtalk/inbound-media.js +71 -12
  30. package/dist/dingtalk/inbound.d.ts +9 -2
  31. package/dist/dingtalk/inbound.js +18 -2
  32. package/dist/dingtalk/media.d.ts +4 -10
  33. package/dist/dingtalk/media.js +58 -32
  34. package/dist/events/commands.d.ts +2 -0
  35. package/dist/events/commands.js +13 -8
  36. package/dist/events/history.d.ts +9 -0
  37. package/dist/events/history.js +66 -0
  38. package/dist/events/parse.js +7 -3
  39. package/dist/events/types.d.ts +3 -0
  40. package/dist/events/watcher.d.ts +3 -7
  41. package/dist/events/watcher.js +51 -56
  42. package/dist/jobs/kill.d.ts +23 -0
  43. package/dist/jobs/kill.js +65 -0
  44. package/dist/jobs/manager.d.ts +19 -18
  45. package/dist/jobs/manager.js +36 -103
  46. package/dist/memory/reflect.js +23 -3
  47. package/dist/memory/session-corpus.d.ts +1 -1
  48. package/dist/memory/session-corpus.js +70 -1
  49. package/dist/memory/session-search.js +13 -11
  50. package/dist/memory/store.d.ts +2 -0
  51. package/dist/memory/store.js +19 -9
  52. package/dist/playbooks/agent-delegation.md +5 -4
  53. package/dist/playbooks/memory-and-learning.md +1 -1
  54. package/dist/playbooks/task-lead.md +4 -4
  55. package/dist/runtime/bootstrap.d.ts +6 -0
  56. package/dist/runtime/bootstrap.js +11 -7
  57. package/dist/runtime/desk-runtime.d.ts +8 -2
  58. package/dist/runtime/desk-runtime.js +35 -4
  59. package/dist/runtime/durable-dispatch.d.ts +14 -2
  60. package/dist/runtime/durable-dispatch.js +207 -65
  61. package/dist/runtime/ingress-busy.js +17 -8
  62. package/dist/runtime/ingress-deps.d.ts +4 -1
  63. package/dist/runtime/ingress.js +6 -1
  64. package/dist/runtime/request-execution.js +7 -6
  65. package/dist/runtime/shutdown.d.ts +1 -0
  66. package/dist/runtime/shutdown.js +87 -35
  67. package/dist/runtime/task-control.d.ts +1 -0
  68. package/dist/runtime/task-control.js +25 -2
  69. package/dist/runtime/task-lane.d.ts +1 -0
  70. package/dist/runtime/task-lane.js +21 -6
  71. package/dist/runtime/task-step.js +11 -2
  72. package/dist/runtime/turn-run.js +103 -66
  73. package/dist/security/command-guard.d.ts +1 -1
  74. package/dist/security/command-guard.js +237 -314
  75. package/dist/security/path-guard.js +48 -7
  76. package/dist/security/shell-parse.d.ts +10 -0
  77. package/dist/security/shell-parse.js +224 -0
  78. package/dist/security/types.d.ts +2 -0
  79. package/dist/subagents/commands.d.ts +1 -1
  80. package/dist/subagents/detached-discovery.d.ts +1 -1
  81. package/dist/subagents/discovery.d.ts +18 -199
  82. package/dist/subagents/discovery.js +35 -289
  83. package/dist/subagents/dispatch.d.ts +1 -2
  84. package/dist/subagents/dispatch.js +39 -20
  85. package/dist/subagents/external/antigravity-cli.d.ts +2 -0
  86. package/dist/subagents/external/antigravity-cli.js +517 -0
  87. package/dist/subagents/external/claude-code.js +8 -17
  88. package/dist/subagents/external/codex-cli.js +8 -18
  89. package/dist/subagents/external/cursor-cli.js +34 -31
  90. package/dist/subagents/external/dispatch.d.ts +21 -7
  91. package/dist/subagents/external/dispatch.js +139 -11
  92. package/dist/subagents/external/exec.js +3 -0
  93. package/dist/subagents/external/harness.d.ts +57 -33
  94. package/dist/subagents/external/harness.js +69 -40
  95. package/dist/subagents/external/reconciliation.js +1 -0
  96. package/dist/subagents/external/registry.js +4 -1
  97. package/dist/subagents/external/role-warnings.d.ts +4 -13
  98. package/dist/subagents/external/role-warnings.js +4 -28
  99. package/dist/subagents/external/run.d.ts +1 -2
  100. package/dist/subagents/external/run.js +11 -11
  101. package/dist/subagents/external/settlement.d.ts +2 -0
  102. package/dist/subagents/external/settlement.js +8 -2
  103. package/dist/subagents/format.d.ts +1 -1
  104. package/dist/subagents/format.js +1 -1
  105. package/dist/subagents/internal/outcome.d.ts +1 -2
  106. package/dist/subagents/internal/provider-retry.d.ts +1 -2
  107. package/dist/subagents/internal/provider-retry.js +1 -1
  108. package/dist/subagents/internal/run.d.ts +1 -2
  109. package/dist/subagents/internal/state.d.ts +1 -2
  110. package/dist/subagents/internal/worker.d.ts +1 -2
  111. package/dist/subagents/internal/worker.js +3 -1
  112. package/dist/subagents/resolve.d.ts +56 -0
  113. package/dist/subagents/resolve.js +202 -0
  114. package/dist/subagents/result.d.ts +1 -2
  115. package/dist/subagents/result.js +7 -3
  116. package/dist/subagents/run-record.d.ts +33 -2
  117. package/dist/subagents/run-record.js +2 -0
  118. package/dist/subagents/runs.d.ts +2 -24
  119. package/dist/subagents/runs.js +6 -0
  120. package/dist/subagents/task-envelope.d.ts +1 -2
  121. package/dist/subagents/task-envelope.js +8 -4
  122. package/dist/subagents/types.d.ts +93 -4
  123. package/dist/subagents/types.js +16 -1
  124. package/dist/subagents/workspace-lease.d.ts +11 -21
  125. package/dist/subagents/workspace-lease.js +48 -21
  126. package/dist/subagents/worktree.d.ts +10 -0
  127. package/dist/subagents/worktree.js +77 -0
  128. package/dist/tasks/archive.js +4 -0
  129. package/dist/tasks/commands.d.ts +3 -0
  130. package/dist/tasks/commands.js +16 -2
  131. package/dist/tasks/control.d.ts +2 -0
  132. package/dist/tasks/delivery.d.ts +2 -0
  133. package/dist/tasks/delivery.js +141 -21
  134. package/dist/tasks/loop-log.d.ts +2 -0
  135. package/dist/tasks/loop-log.js +9 -0
  136. package/dist/tools/bash.js +2 -0
  137. package/dist/tools/contract/presentation.js +3 -4
  138. package/dist/tools/event-manage.d.ts +2 -0
  139. package/dist/tools/event-manage.js +20 -2
  140. package/dist/tools/index.d.ts +2 -1
  141. package/dist/tools/index.js +2 -0
  142. package/dist/tools/registry.js +3 -1
  143. package/dist/tools/send-media.js +9 -5
  144. package/dist/tools/session-search.js +1 -1
  145. package/dist/tools/subagent-manage.d.ts +1 -1
  146. package/dist/tools/subagent-manage.js +15 -149
  147. package/dist/tools/subagent.d.ts +2 -0
  148. package/dist/tools/subagent.js +6 -1
  149. package/dist/tools/task-manage/factory.js +2 -2
  150. package/dist/tools/task-manage/lifecycle.d.ts +3 -3
  151. package/dist/tools/task-manage/lifecycle.js +49 -9
  152. package/dist/tools/task-manage/schema.d.ts +4 -1
  153. package/dist/tools/task-manage/schema.js +4 -1
  154. package/dist/tools/task-manage/types.d.ts +4 -1
  155. package/dist/tui/cli.d.ts +1 -6
  156. package/dist/tui/cli.js +29 -3
  157. package/dist/tui/client.d.ts +2 -0
  158. package/dist/tui/client.js +13 -4
  159. package/dist/usage/ledger.d.ts +1 -1
  160. package/dist/usage/render.js +1 -1
  161. package/examples/sub-agents/README.md +39 -73
  162. package/examples/sub-agents/agents/agy-main.md +23 -0
  163. package/examples/sub-agents/agents/claude-high.md +9 -9
  164. package/examples/sub-agents/agents/claude-main.md +9 -9
  165. package/examples/sub-agents/agents/codex-flash.md +9 -9
  166. package/examples/sub-agents/agents/codex-high.md +9 -9
  167. package/examples/sub-agents/agents/codex-main.md +9 -9
  168. package/examples/sub-agents/agents/codex-review.md +9 -9
  169. package/examples/sub-agents/agents/cursor-high.md +9 -9
  170. package/examples/sub-agents/agents/cursor-main.md +9 -9
  171. package/examples/sub-agents/agents/glm-flash.md +9 -9
  172. package/examples/sub-agents/agents/glm-high.md +9 -9
  173. package/package.json +8 -8
  174. package/examples/sub-agents/agents/scout.md +0 -30
  175. package/examples/sub-agents/roles/builder-hard.md +0 -34
  176. package/examples/sub-agents/roles/builder.md +0 -34
  177. package/examples/sub-agents/roles/explorer.md +0 -39
  178. package/examples/sub-agents/roles/git-committer.md +0 -43
  179. package/examples/sub-agents/roles/planner.md +0 -33
  180. package/examples/sub-agents/roles/reviewer.md +0 -33
  181. package/examples/sub-agents/roles/verifier.md +0 -35
  182. package/examples/sub-agents/roles/worker.md +0 -34
@@ -90,6 +90,8 @@ export type SpawnTaskResult =
90
90
  export interface EventsWatcherOptions {
91
91
  /** The desk this watcher serves; stamped on every dispatch, history record and spawn request. */
92
92
  desk: string;
93
+ /** Working directory for `preAction` commands (`desk.json` `cwd` when set, else `deskDir`). */
94
+ cwd?: string;
93
95
  /**
94
96
  * Whether a delivery channel is still bound to this desk (spec 058, D7's producer-side check).
95
97
  * An occurrence whose channel is not bound is skipped, never redirected.
@@ -101,6 +103,7 @@ export interface EventsWatcherOptions {
101
103
  */
102
104
  isReachable: (channelId: string) => boolean;
103
105
  historyPath?: string;
106
+ historyMaxBytes?: number;
104
107
  /**
105
108
  * Creates the task instance a template event asks for. Injected by the runtime so the events
106
109
  * subsystem never reads or writes task files (spec 052, INV-8).
@@ -11,6 +11,7 @@ export declare class EventsWatcher {
11
11
  private timers;
12
12
  private crons;
13
13
  private debounceTimers;
14
+ private readonly fileQueue;
14
15
  private startTime;
15
16
  private watcher;
16
17
  private started;
@@ -28,16 +29,11 @@ export declare class EventsWatcher {
28
29
  private debounce;
29
30
  private scanExisting;
30
31
  private handleFileChange;
31
- /**
32
- * Watch callbacks are the top of their own stack, so a rejection here reaches nobody — and
33
- * `handleFile` can reject: reloading a due one-shot dispatches it inline, and dispatch
34
- * writes to disk. `scanExisting` already wraps its own calls; this is the same guard for
35
- * the live path. One bad file must not take the watcher, or the process, down with it.
36
- */
37
- private handleFileSafely;
38
32
  private handleDelete;
33
+ private stopScheduled;
39
34
  private cancelScheduled;
40
35
  private handleFile;
36
+ private loadFile;
41
37
  private parseEvent;
42
38
  /**
43
39
  * The admission gate (spec 031, D4). `event_manage` applies the same rules first, but the
@@ -3,15 +3,16 @@
3
3
  * (cron, optional pre-action gate) and enqueues every occurrence through the injected event sink.
4
4
  */
5
5
  import { Cron } from "croner";
6
- import { chmodSync, existsSync, mkdirSync, readdirSync, statSync, unlinkSync, watch, writeFileSync, } from "fs";
6
+ import { existsSync, mkdirSync, readdirSync, statSync, unlinkSync, watch } from "fs";
7
7
  import { readFile } from "fs/promises";
8
- import { dirname, join, resolve } from "path";
8
+ import { join, resolve } from "path";
9
9
  import * as log from "../log.js";
10
10
  import { guardCommand } from "../security/command-guard.js";
11
11
  import { writeFileAtomicallySync } from "../shared/atomic-file.js";
12
- import { createJsonlAppender } from "../shared/jsonl-appender.js";
13
12
  import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
13
+ import { createSerialQueue } from "../shared/serial-queue.js";
14
14
  import { clipText, errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
15
+ import { ensureEventHistoryFile, getEventHistoryAppender } from "./history.js";
15
16
  import { describeEventPayload, parseScheduledEventContent } from "./parse.js";
16
17
  import { EventPreActionError } from "./pre-action-error.js";
17
18
  import { MAX_EVENT_FILES, MAX_ONE_SHOT_DELAY_MS, validateScheduledEvent } from "./validation.js";
@@ -42,6 +43,7 @@ export class EventsWatcher {
42
43
  this.timers = new Map();
43
44
  this.crons = new Map();
44
45
  this.debounceTimers = new Map();
46
+ this.fileQueue = createSerialQueue();
45
47
  this.watcher = null;
46
48
  this.started = false;
47
49
  /** Set once by `stop()` and never cleared: in-flight loads check it before scheduling anything. */
@@ -49,11 +51,7 @@ export class EventsWatcher {
49
51
  this.knownFiles = new Set();
50
52
  this.startTime = Date.now();
51
53
  this.historyAppender = options.historyPath
52
- ? createJsonlAppender({
53
- path: options.historyPath,
54
- maxPendingRecords: 4_000,
55
- maxPendingBytes: 8 * 1024 * 1024,
56
- })
54
+ ? getEventHistoryAppender(options.historyPath, options.historyMaxBytes)
57
55
  : undefined;
58
56
  }
59
57
  start() {
@@ -97,23 +95,12 @@ export class EventsWatcher {
97
95
  await this.historyAppender?.flush();
98
96
  }
99
97
  ensureHistoryFile() {
100
- if (!this.options.historyPath) {
101
- return;
102
- }
103
- try {
104
- const historyDir = dirname(this.options.historyPath);
105
- mkdirSync(historyDir, { recursive: true, mode: 0o700 });
106
- writeFileSync(this.options.historyPath, "", { flag: "a", mode: 0o600 });
107
- chmodSync(this.options.historyPath, 0o600);
108
- }
109
- catch (err) {
110
- log.logWarn("events.history.init_failed", "Event history file init failed", { reason: String(err) });
111
- }
98
+ if (this.options.historyPath)
99
+ ensureEventHistoryFile(this.options.historyPath);
112
100
  }
113
101
  appendHistory(record) {
114
- if (!this.options.historyPath) {
102
+ if (!this.options.historyPath)
115
103
  return;
116
- }
117
104
  const { filename, ...rest } = record;
118
105
  const fullRecord = {
119
106
  ts: formatLocalTime(),
@@ -173,26 +160,21 @@ export class EventsWatcher {
173
160
  }
174
161
  }
175
162
  handleFileChange(filename) {
176
- const filePath = join(this.eventsDir, filename);
177
- if (!existsSync(filePath)) {
178
- this.handleDelete(filename);
179
- }
180
- else if (this.knownFiles.has(filename)) {
181
- this.cancelScheduled(filename);
182
- this.handleFileSafely(filename);
183
- }
184
- else {
185
- this.handleFileSafely(filename);
186
- }
187
- }
188
- /**
189
- * Watch callbacks are the top of their own stack, so a rejection here reaches nobody — and
190
- * `handleFile` can reject: reloading a due one-shot dispatches it inline, and dispatch
191
- * writes to disk. `scanExisting` already wraps its own calls; this is the same guard for
192
- * the live path. One bad file must not take the watcher, or the process, down with it.
193
- */
194
- handleFileSafely(filename) {
195
- void this.handleFile(filename).catch((err) => {
163
+ // Serialize per filename with `scanExisting`/`handleFile` so an overlapping watch event
164
+ // cannot race an in-flight read and overwrite `this.crons`/`this.timers` without stopping the old one.
165
+ void this.fileQueue
166
+ .run(filename, async () => {
167
+ if (this.stopped)
168
+ return;
169
+ if (!existsSync(join(this.eventsDir, filename))) {
170
+ this.handleDelete(filename);
171
+ return;
172
+ }
173
+ if (this.knownFiles.has(filename))
174
+ this.cancelScheduled(filename);
175
+ await this.loadFile(filename);
176
+ })
177
+ .catch((err) => {
196
178
  log.logWarn("events.file.load_failed", "Event file load failed", {
197
179
  reason: errorMessage(err),
198
180
  fields: { file: filename },
@@ -200,33 +182,32 @@ export class EventsWatcher {
200
182
  });
201
183
  }
202
184
  handleDelete(filename) {
185
+ this.clearInvalidMarker(filename);
203
186
  if (!this.knownFiles.has(filename))
204
187
  return;
205
188
  log.logInfo(`Event file deleted: ${filename}`);
206
189
  this.cancelScheduled(filename);
207
190
  this.knownFiles.delete(filename);
208
- this.appendHistory({
209
- filename,
210
- eventType: "unknown",
211
- action: "deleted",
212
- result: "ok",
213
- });
191
+ this.appendHistory({ filename, eventType: "unknown", action: "deleted", result: "ok" });
214
192
  }
215
- cancelScheduled(filename) {
216
- let cancelled = false;
193
+ stopScheduled(filename) {
194
+ let stoppedAny = false;
217
195
  const timer = this.timers.get(filename);
218
196
  if (timer) {
219
197
  clearTimeout(timer);
220
198
  this.timers.delete(filename);
221
- cancelled = true;
199
+ stoppedAny = true;
222
200
  }
223
201
  const cron = this.crons.get(filename);
224
202
  if (cron) {
225
203
  cron.stop();
226
204
  this.crons.delete(filename);
227
- cancelled = true;
205
+ stoppedAny = true;
228
206
  }
229
- if (cancelled) {
207
+ return stoppedAny;
208
+ }
209
+ cancelScheduled(filename) {
210
+ if (this.stopScheduled(filename)) {
230
211
  this.appendHistory({
231
212
  filename,
232
213
  eventType: "unknown",
@@ -236,7 +217,10 @@ export class EventsWatcher {
236
217
  });
237
218
  }
238
219
  }
239
- async handleFile(filename) {
220
+ handleFile(filename) {
221
+ return this.fileQueue.run(filename, () => this.loadFile(filename));
222
+ }
223
+ async loadFile(filename) {
240
224
  const filePath = join(this.eventsDir, filename);
241
225
  let event = null;
242
226
  let lastError = null;
@@ -258,6 +242,9 @@ export class EventsWatcher {
258
242
  // or cron that nothing would ever stop.
259
243
  if (this.stopped)
260
244
  return;
245
+ // Stop any prior timer/cron before re-evaluating or re-scheduling this filename, so even two
246
+ // direct `handleFile` calls can never leave an orphan Cron or Timeout behind.
247
+ this.stopScheduled(filename);
261
248
  if (!event) {
262
249
  log.logWarn("events.file.parse_failed", "Event file parse failed", {
263
250
  reason: lastError?.message,
@@ -377,9 +364,11 @@ export class EventsWatcher {
377
364
  });
378
365
  }
379
366
  }, delay);
367
+ this.stopScheduled(filename);
380
368
  this.timers.set(filename, timer);
381
369
  }
382
370
  handlePeriodic(filename, event) {
371
+ this.stopScheduled(filename);
383
372
  try {
384
373
  const cron = new Cron(event.schedule, { protect: true, catch: true }, async () => {
385
374
  try {
@@ -592,7 +581,10 @@ export class EventsWatcher {
592
581
  const timeoutSeconds = Math.max(1, Math.ceil(timeoutMs / 1000));
593
582
  let result;
594
583
  try {
595
- result = await this.executor.exec(action.command, { timeout: timeoutSeconds });
584
+ result = await this.executor.exec(action.command, {
585
+ timeout: timeoutSeconds,
586
+ ...(this.options.cwd ? { cwd: this.options.cwd } : {}),
587
+ });
596
588
  }
597
589
  catch (err) {
598
590
  throw new EventPreActionError("failed", errorMessage(err), {
@@ -665,5 +657,8 @@ export class EventsWatcher {
665
657
  /** Create the events watcher of one desk: it watches `<deskDir>/events/` (spec 058, D14). */
666
658
  export function createEventsWatcher(input) {
667
659
  const { deskDir, sink, executor, commandGuardConfig, ...options } = input;
668
- return new EventsWatcher(join(deskDir, "events"), sink, executor, commandGuardConfig, options);
660
+ return new EventsWatcher(join(deskDir, "events"), sink, executor, commandGuardConfig, {
661
+ ...options,
662
+ cwd: options.cwd ?? deskDir,
663
+ });
669
664
  }
@@ -0,0 +1,23 @@
1
+ import type { Executor } from "../executor.js";
2
+ import type { JobRecord } from "./record.js";
3
+ /**
4
+ * The outcome of one kill attempt, decided from the kill script's own printed token plus the
5
+ * executor result — never from "the shell exited 0", which a failed `kill` inside `2>/dev/null`
6
+ * would still do.
7
+ * - `terminated` — we signalled the target and then confirmed the pid is gone.
8
+ * - `gone` — the target was already gone before we signalled (or its pgid became unroutable).
9
+ * - `identity-mismatch` — the pid now belongs to an unrelated process, so *our* process is gone.
10
+ * - `unconfirmed` — the kill ran but the pid is still alive afterwards.
11
+ * - `not-submitted` — the executor could not even run the kill.
12
+ * - `no-target` — there is no pid we can safely signal (pid <= 1 / not finite).
13
+ */
14
+ type KillOutcome = "terminated" | "gone" | "identity-mismatch" | "unconfirmed" | "not-submitted" | "no-target";
15
+ /** Outcomes that prove the job's process is gone — safe to apply a terminal status. */
16
+ export declare const KILL_CONFIRMED_GONE: ReadonlySet<KillOutcome>;
17
+ /**
18
+ * Run one kill attempt and classify it from the printed token plus the executor result — never
19
+ * from "the shell exited 0". Used by cancel, timeout, the persist-failure rollback and the
20
+ * interrupted-launch recovery; the last two pass no signal so an aborted caller cannot skip it.
21
+ */
22
+ export declare function killJob(executor: Executor, record: Pick<JobRecord, "pid" | "pgid" | "pidStartedAt">, signal?: AbortSignal): Promise<KillOutcome>;
23
+ export {};
@@ -0,0 +1,65 @@
1
+ import { shellEscape } from "../shared/os.js";
2
+ /** Outcomes that prove the job's process is gone — safe to apply a terminal status. */
3
+ export const KILL_CONFIRMED_GONE = new Set([
4
+ "terminated",
5
+ "gone",
6
+ "identity-mismatch",
7
+ "no-target",
8
+ ]);
9
+ /**
10
+ * The shell command that terminates `record`'s process and prints one token describing what
11
+ * happened (`TERMINATED` / `GONE` / `IDENTITY_MISMATCH` / `UNCONFIRMED`), or `undefined` when
12
+ * there is no pid we can safely signal.
13
+ *
14
+ * A negative-PGID target is used only when `setsid` gave the job pgid == pid (spec: everything
15
+ * the command spawned dies with it). When a start time was captured it is checked first: a
16
+ * recycled pid reads as `IDENTITY_MISMATCH` and is never signalled; a pid `ps` cannot see but
17
+ * that `kill -0` says is alive reads as `UNCONFIRMED` (do not signal what we cannot prove is
18
+ * ours). Legacy / nohup records have only `kill -0` liveness and a plain pid kill.
19
+ */
20
+ function buildKillCommand(record) {
21
+ const pid = record.pid;
22
+ if (!Number.isFinite(pid) || pid <= 1)
23
+ return undefined;
24
+ const groupSafe = record.pgid !== undefined && record.pgid === pid;
25
+ const target = groupSafe ? `"-${pid}"` : `${pid}`;
26
+ const gate = record.pidStartedAt
27
+ ? `__pc_cur="$(ps -o lstart= -p ${pid} 2>/dev/null)"; ` +
28
+ `if [ -z "$__pc_cur" ]; then ` +
29
+ `if kill -0 ${pid} 2>/dev/null; then printf 'UNCONFIRMED\\n'; exit 0; else printf 'GONE\\n'; exit 0; fi; fi; ` +
30
+ `if [ "$__pc_cur" != ${shellEscape(record.pidStartedAt)} ]; then printf 'IDENTITY_MISMATCH\\n'; exit 0; fi; `
31
+ : `if ! kill -0 ${pid} 2>/dev/null; then printf 'GONE\\n'; exit 0; fi; `;
32
+ return (gate +
33
+ `kill -TERM ${target} 2>/dev/null; sleep 0.2; kill -KILL ${target} 2>/dev/null; sleep 0.05; ` +
34
+ `if kill -0 ${pid} 2>/dev/null; then printf 'UNCONFIRMED\\n'; else printf 'TERMINATED\\n'; fi`);
35
+ }
36
+ /**
37
+ * Run one kill attempt and classify it from the printed token plus the executor result — never
38
+ * from "the shell exited 0". Used by cancel, timeout, the persist-failure rollback and the
39
+ * interrupted-launch recovery; the last two pass no signal so an aborted caller cannot skip it.
40
+ */
41
+ export async function killJob(executor, record, signal) {
42
+ const command = buildKillCommand(record);
43
+ if (!command)
44
+ return "no-target";
45
+ let result;
46
+ try {
47
+ result = await executor.exec(command, signal ? { signal } : {});
48
+ }
49
+ catch {
50
+ return "not-submitted";
51
+ }
52
+ const token = result.stdout.trim().split("\n").pop()?.trim() ?? "";
53
+ switch (token) {
54
+ case "TERMINATED":
55
+ return "terminated";
56
+ case "GONE":
57
+ return "gone";
58
+ case "IDENTITY_MISMATCH":
59
+ return "identity-mismatch";
60
+ case "UNCONFIRMED":
61
+ return "unconfirmed";
62
+ default:
63
+ return "not-submitted";
64
+ }
65
+ }
@@ -2,9 +2,27 @@ import type { WakeEvent } from "../channel/channel-event.js";
2
2
  import type { Executor } from "../executor.js";
3
3
  import { type FileStore } from "../file-store.js";
4
4
  import { type JobRecord, type JobSnapshot, type JobStatus } from "./record.js";
5
+ /**
6
+ * Per-desk manager for background bash jobs. A long command that ran synchronously would hold
7
+ * the channel's run queue for its whole duration, blocking `/steer`, `/followup`, and every other
8
+ * message. A background job instead returns immediately and the model can end its turn.
9
+ *
10
+ * Jobs live on the host, managed through shell commands (`setsid` to launch as its own process
11
+ * group with a startup handshake, a three-state identity probe, a confirmed kill) with no
12
+ * in-process child handles. Records
13
+ * are mirrored to `state/jobs/<desk>/<id>.json` so they survive a restart: a detached
14
+ * process outlives the daemon, and losing the record while the process kept running meant orphaned
15
+ * work, leaked slots, and unreachable output (spec 031, D6).
16
+ *
17
+ * A finished job wakes its channel by itself. Making the model predict a completion time and
18
+ * arrange its own callback was a judgement call it could not make correctly, so completion is a
19
+ * runtime guarantee instead.
20
+ */
5
21
  export interface JobStartOptions {
6
22
  /** The channel the job was started from: its completion wake goes back there (spec 058, D7). */
7
23
  channelId: string;
24
+ /** Working directory for the background process; falls back to the desk directory when omitted. */
25
+ cwd?: string;
8
26
  signal?: AbortSignal;
9
27
  notify?: boolean;
10
28
  /** The task whose step starts the job (spec 064, INV-8): its completion is recorded there instead of waking `channelId`. */
@@ -114,6 +132,7 @@ export declare class DeskJobManager {
114
132
  stop(): void;
115
133
  private stopSweeper;
116
134
  private sweep;
135
+ private refreshBatch;
117
136
  /**
118
137
  * Probe every given job in one shell invocation, returning
119
138
  * `id → EXIT:<code> | ALIVE | GONE | DIFFERENT | UNKNOWN`.
@@ -163,24 +182,6 @@ export declare class DeskJobManager {
163
182
  private announce;
164
183
  /** Same contract as `SubAgentRunManager.suppressWake`: drop the chat wake of a job whose channel left the desk. */
165
184
  private suppressWake;
166
- /**
167
- * The shell command that terminates `record`'s process and prints one token describing what
168
- * happened (`TERMINATED` / `GONE` / `IDENTITY_MISMATCH` / `UNCONFIRMED`), or `undefined` when
169
- * there is no pid we can safely signal.
170
- *
171
- * A negative-PGID target is used only when `setsid` gave the job pgid == pid (spec: everything
172
- * the command spawned dies with it). When a start time was captured it is checked first: a
173
- * recycled pid reads as `IDENTITY_MISMATCH` and is never signalled; a pid `ps` cannot see but
174
- * that `kill -0` says is alive reads as `UNCONFIRMED` (do not signal what we cannot prove is
175
- * ours). Legacy / nohup records have only `kill -0` liveness and a plain pid kill.
176
- */
177
- private killCommand;
178
- /**
179
- * Run one kill attempt and classify it from the printed token plus the executor result — never
180
- * from "the shell exited 0". Used by cancel, timeout, the persist-failure rollback and the
181
- * interrupted-launch recovery; the last two pass no signal so an aborted caller cannot skip it.
182
- */
183
- private runKill;
184
185
  list(signal?: AbortSignal): Promise<JobSnapshot[]>;
185
186
  cancel(ids: string[], signal?: AbortSignal): Promise<Array<{
186
187
  id: string;
@@ -5,7 +5,6 @@ import { join } from "node:path";
5
5
  import { createFileStore } from "../file-store.js";
6
6
  import * as log from "../log.js";
7
7
  import { writeFileAtomically } from "../shared/atomic-file.js";
8
- import { shellEscape } from "../shared/os.js";
9
8
  import { createSerialQueue } from "../shared/serial-queue.js";
10
9
  import { errorMessage } from "../shared/text-utils.js";
11
10
  import { logTaskDispatch, logTaskSettlement } from "../tasks/bound-work.js";
@@ -13,16 +12,10 @@ import { readStoredTask } from "../tasks/store.js";
13
12
  import { JobCompletionObserver } from "./completion-observer.js";
14
13
  import { CompletionSignal } from "./completion-signal.js";
15
14
  import { buildJobCompletionWake } from "./completion-wake.js";
15
+ import { KILL_CONFIRMED_GONE, killJob } from "./kill.js";
16
16
  import { buildLaunchScript, jobArtifacts, parseLaunchOutput } from "./launch.js";
17
17
  import { probeJobs } from "./probe.js";
18
18
  import { isTerminal, parseJobRecord, toSnapshot } from "./record.js";
19
- /** Outcomes that prove the job's process is gone — safe to apply a terminal status. */
20
- const KILL_CONFIRMED_GONE = new Set([
21
- "terminated",
22
- "gone",
23
- "identity-mismatch",
24
- "no-target",
25
- ]);
26
19
  /** Cap on concurrently running jobs per desk, so a runaway model can't spawn unbounded processes. */
27
20
  export const MAX_RUNNING_JOBS = 5;
28
21
  /** Longest a single `poll` call blocks before returning a snapshot; the model can poll again. */
@@ -161,9 +154,8 @@ export class DeskJobManager {
161
154
  .filter((record) => isTerminal(record.status) && record.finishedAt)
162
155
  .map((record) => record.finishedAt + FINISHED_JOB_RETENTION_MS)
163
156
  .reduce((earliest, expiry) => (earliest === undefined ? expiry : Math.min(earliest, expiry)), undefined);
164
- if (nextExpiry === undefined) {
157
+ if (nextExpiry === undefined)
165
158
  return;
166
- }
167
159
  this.garbageCollectionTimer = setTimeout(() => {
168
160
  this.garbageCollectionTimer = undefined;
169
161
  void this.collectGarbage().finally(() => this.scheduleGarbageCollection());
@@ -188,16 +180,16 @@ export class DeskJobManager {
188
180
  throw new Error(`Too many background jobs already running (>= ${MAX_RUNNING_JOBS}). Poll or cancel some with the job tool first.`);
189
181
  }
190
182
  const id = randomBytes(6).toString("hex");
191
- if (this.options.spillDir) {
183
+ if (this.options.spillDir)
192
184
  await mkdir(this.options.spillDir, { recursive: true }).catch(() => undefined);
193
- }
194
185
  const spillFile = jobSpillPath(id, this.options.spillDir);
195
186
  const art = jobArtifacts(spillFile);
196
187
  const launch = buildLaunchScript(command, art);
188
+ const cwd = options.cwd ?? this.target.deskDir;
197
189
  this.observer.add(id, art.exitFile);
198
190
  let result;
199
191
  try {
200
- result = await this.executor.exec(launch, { signal: options.signal });
192
+ result = await this.executor.exec(launch, { signal: options.signal, ...(cwd ? { cwd } : {}) });
201
193
  }
202
194
  catch (error) {
203
195
  // The launch was aborted (or the executor could not run it). A detached child may
@@ -258,7 +250,7 @@ export class DeskJobManager {
258
250
  // not inherit the caller's AbortSignal (it may already be aborted).
259
251
  const reason = `its record could not be persisted (${errorMessage(error)})`;
260
252
  const failure = await this.reconcileQueue.run(id, async () => {
261
- const outcome = await this.runKill(record);
253
+ const outcome = await killJob(this.executor, record);
262
254
  if (!KILL_CONFIRMED_GONE.has(outcome)) {
263
255
  // The process could not be confirmed gone (kill unconfirmed, or the executor could
264
256
  // not run it). Deleting the only trace of a live process is exactly the orphan this
@@ -326,7 +318,7 @@ export class DeskJobManager {
326
318
  ...(launched.pgid !== undefined ? { pgid: launched.pgid } : {}),
327
319
  ...(launched.pidStartedAt ? { pidStartedAt: launched.pidStartedAt } : {}),
328
320
  };
329
- const outcome = await this.runKill(provisional); // deliberately no signal
321
+ const outcome = await killJob(this.executor, provisional); // deliberately no signal
330
322
  await this.unlinkArtifacts(art);
331
323
  const tail = KILL_CONFIRMED_GONE.has(outcome)
332
324
  ? outcome === "terminated"
@@ -381,41 +373,40 @@ export class DeskJobManager {
381
373
  log.logEvent("debug", "job.completion.hinted", "Background job completion check requested", {
382
374
  fields: { desk: this.target.desk, jobIds: running.map((r) => r.id), trigger: "sweep" },
383
375
  });
384
- // One shell for the whole sweep, not one per job: the sweeper runs every 10s for as
385
- // long as any job lives, so per-job spawns are the steady-state cost of backgrounding.
386
- const probes = await this.probeAll(running);
376
+ await this.refreshBatch(running);
377
+ await this.collectGarbage();
378
+ }
379
+ finally {
380
+ this.sweeping = false;
381
+ if (this.runningCount() === 0 && this.pendingCompletion.size === 0) {
382
+ this.stopSweeper();
383
+ }
384
+ }
385
+ }
386
+ async refreshBatch(running, signal) {
387
+ if (running.length > 0) {
388
+ const probes = await this.probeAll(running, signal);
387
389
  for (const record of running) {
388
- // The batched probe is a read; the state transition it implies still goes through the
389
- // per-job slot so it cannot race a concurrent list/poll/cancel.
390
390
  await this.reconcileQueue
391
391
  .run(record.id, async () => {
392
392
  if (this.stopped || record.status !== "running")
393
393
  return;
394
- await this.applyProbe(record, probes.get(record.id) ?? "");
394
+ await this.applyProbe(record, probes.get(record.id) ?? "", signal);
395
395
  })
396
- .catch((error) => {
397
- log.logWarn("job.sweep.refresh_failed", "Background job refresh failed", {
398
- reason: errorMessage(error),
399
- fields: { jobId: record.id },
400
- });
401
- });
402
- }
403
- for (const id of this.pendingCompletion) {
404
- const record = this.jobs.get(id);
405
- if (!record || this.stopped)
406
- break;
407
- await this.refresh(record).catch((error) => log.logWarn("job.completion.retry_failed", "Background job completion failed", {
396
+ .catch((error) => log.logWarn("job.sweep.refresh_failed", "Background job refresh failed", {
408
397
  reason: errorMessage(error),
409
- fields: { jobId: id },
398
+ fields: { jobId: record.id },
410
399
  }));
411
400
  }
412
- await this.collectGarbage();
413
401
  }
414
- finally {
415
- this.sweeping = false;
416
- if (this.runningCount() === 0 && this.pendingCompletion.size === 0) {
417
- this.stopSweeper();
418
- }
402
+ for (const id of this.pendingCompletion) {
403
+ const record = this.jobs.get(id);
404
+ if (!record || this.stopped)
405
+ break;
406
+ await this.refresh(record, signal).catch((error) => log.logWarn("job.completion.retry_failed", "Background job completion failed", {
407
+ reason: errorMessage(error),
408
+ fields: { jobId: id },
409
+ }));
419
410
  }
420
411
  }
421
412
  /**
@@ -496,7 +487,7 @@ export class DeskJobManager {
496
487
  // Still running (ALIVE / UNKNOWN / torn-EXIT). A cancel or timeout whose kill could not be
497
488
  // confirmed earlier retries here every sweep until the process is proven gone.
498
489
  if (record.pendingKill) {
499
- const outcome = await this.runKill(record, signal);
490
+ const outcome = await killJob(this.executor, record, signal);
500
491
  if (record.status === "running" && KILL_CONFIRMED_GONE.has(outcome)) {
501
492
  const t = this.takePendingTerminal(record, "lost", undefined);
502
493
  record.exitCode = t.exitCode;
@@ -508,7 +499,7 @@ export class DeskJobManager {
508
499
  // to a terminal status once the kill is confirmed; otherwise mark it pending and keep
509
500
  // managing it (the sweeper retries).
510
501
  if (Date.now() - record.startedAt > record.timeoutSeconds * 1000) {
511
- const outcome = await this.runKill(record, signal);
502
+ const outcome = await killJob(this.executor, record, signal);
512
503
  if (record.status !== "running")
513
504
  return;
514
505
  if (KILL_CONFIRMED_GONE.has(outcome)) {
@@ -629,67 +620,9 @@ export class DeskJobManager {
629
620
  record.notified = true;
630
621
  await this.persist(record);
631
622
  }
632
- /**
633
- * The shell command that terminates `record`'s process and prints one token describing what
634
- * happened (`TERMINATED` / `GONE` / `IDENTITY_MISMATCH` / `UNCONFIRMED`), or `undefined` when
635
- * there is no pid we can safely signal.
636
- *
637
- * A negative-PGID target is used only when `setsid` gave the job pgid == pid (spec: everything
638
- * the command spawned dies with it). When a start time was captured it is checked first: a
639
- * recycled pid reads as `IDENTITY_MISMATCH` and is never signalled; a pid `ps` cannot see but
640
- * that `kill -0` says is alive reads as `UNCONFIRMED` (do not signal what we cannot prove is
641
- * ours). Legacy / nohup records have only `kill -0` liveness and a plain pid kill.
642
- */
643
- killCommand(record) {
644
- const pid = record.pid;
645
- if (!Number.isFinite(pid) || pid <= 1)
646
- return undefined;
647
- const groupSafe = record.pgid !== undefined && record.pgid === pid;
648
- const target = groupSafe ? `"-${pid}"` : `${pid}`;
649
- const gate = record.pidStartedAt
650
- ? `__pc_cur="$(ps -o lstart= -p ${pid} 2>/dev/null)"; ` +
651
- `if [ -z "$__pc_cur" ]; then ` +
652
- `if kill -0 ${pid} 2>/dev/null; then printf 'UNCONFIRMED\\n'; exit 0; else printf 'GONE\\n'; exit 0; fi; fi; ` +
653
- `if [ "$__pc_cur" != ${shellEscape(record.pidStartedAt)} ]; then printf 'IDENTITY_MISMATCH\\n'; exit 0; fi; `
654
- : `if ! kill -0 ${pid} 2>/dev/null; then printf 'GONE\\n'; exit 0; fi; `;
655
- return (gate +
656
- `kill -TERM ${target} 2>/dev/null; sleep 0.2; kill -KILL ${target} 2>/dev/null; sleep 0.05; ` +
657
- `if kill -0 ${pid} 2>/dev/null; then printf 'UNCONFIRMED\\n'; else printf 'TERMINATED\\n'; fi`);
658
- }
659
- /**
660
- * Run one kill attempt and classify it from the printed token plus the executor result — never
661
- * from "the shell exited 0". Used by cancel, timeout, the persist-failure rollback and the
662
- * interrupted-launch recovery; the last two pass no signal so an aborted caller cannot skip it.
663
- */
664
- async runKill(record, signal) {
665
- const command = this.killCommand(record);
666
- if (!command)
667
- return "no-target";
668
- let result;
669
- try {
670
- result = await this.executor.exec(command, signal ? { signal } : {});
671
- }
672
- catch {
673
- return "not-submitted";
674
- }
675
- const token = result.stdout.trim().split("\n").pop()?.trim() ?? "";
676
- switch (token) {
677
- case "TERMINATED":
678
- return "terminated";
679
- case "GONE":
680
- return "gone";
681
- case "IDENTITY_MISMATCH":
682
- return "identity-mismatch";
683
- case "UNCONFIRMED":
684
- return "unconfirmed";
685
- default:
686
- return "not-submitted";
687
- }
688
- }
689
623
  async list(signal) {
690
- for (const record of this.jobs.values()) {
691
- await this.refresh(record, signal);
692
- }
624
+ const running = Array.from(this.jobs.values()).filter((r) => r.status === "running");
625
+ await this.refreshBatch(running, signal);
693
626
  return Array.from(this.jobs.values()).map(toSnapshot);
694
627
  }
695
628
  async cancel(ids, signal) {
@@ -709,7 +642,7 @@ export class DeskJobManager {
709
642
  }
710
643
  // An explicit cancel is the model's own decision, so it needs no wake to learn about it.
711
644
  record.contract.notify = false;
712
- const outcome = await this.runKill(record, signal);
645
+ const outcome = await killJob(this.executor, record, signal);
713
646
  if (KILL_CONFIRMED_GONE.has(outcome)) {
714
647
  // A timeout kill already pending (`failed`/124) outranks this cancel — the job did
715
648
  // overrun its budget. `takePendingTerminal` applies that precedence and only falls