pi-async-jobs 0.1.4 → 0.2.0

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 (3) hide show
  1. package/README.md +11 -2
  2. package/index.ts +73 -8
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -74,7 +74,16 @@ Log: ~/.pi/agent/async-jobs/j1.log — read it with job_output({ id: "j1" }).
74
74
  失败和超时会把最后 15 行输出直接贴进消息,省一轮 `job_output`。
75
75
  消息用 `followUp + triggerTurn` 投递:agent 空闲时立刻唤醒,正在跑就等这一轮结束再送。
76
76
 
77
- 后台进程是 detached 的,**pi 退出后仍会继续跑**,日志留在 `~/.pi/agent/async-jobs/`(7 天后自动清理)。
77
+ 后台进程是 detached 的(自己的进程组,收不到终端 SIGHUP),但**不会**变成孤儿:
78
+ pi 关闭(`/quit`、`Ctrl+D`、`Ctrl+C`×2、关闭终端、`SIGTERM`)或切换会话
79
+ (`/reload`、`/new`、`/resume`、`/fork`)时,所有在跑的任务先 `SIGTERM`,3 秒内没退的补 `SIGKILL`。
80
+ 日志留在 `~/.pi/agent/async-jobs/`(7 天后自动清理)。
81
+
82
+ 若确实要让任务在 pi 退出后继续跑(长构建、下载),关掉这个行为:
83
+
84
+ ```json
85
+ { "jobs": { "notify": true, "killOnExit": false } }
86
+ ```
78
87
 
79
88
  人工操作:
80
89
 
@@ -97,7 +106,7 @@ Log: ~/.pi/agent/async-jobs/j1.log — read it with job_output({ id: "j1" }).
97
106
  "perTool": { "mcp__slow__query": 20 },
98
107
  "exempt": ["ask_user_question", "contact_supervisor", "subagent*", "computer_*", "browser*", "window*", "clipboard*", "recording*", "diagnostics*"]
99
108
  },
100
- "jobs": { "notify": true }
109
+ "jobs": { "notify": true, "killOnExit": true }
101
110
  }
102
111
  ```
103
112
 
package/index.ts CHANGED
@@ -50,7 +50,11 @@ type Config = {
50
50
  /** Tool name patterns that wait on a human and must never be nagged or aborted. */
51
51
  exempt: string[];
52
52
  };
53
- jobs: { notify: boolean };
53
+ jobs: {
54
+ notify: boolean;
55
+ /** Kill every running job when pi shuts down (quit, reload, /new, /resume, /fork). */
56
+ killOnExit: boolean;
57
+ };
54
58
  };
55
59
 
56
60
  const DEFAULT_CONFIG: Config = {
@@ -75,10 +79,32 @@ const DEFAULT_CONFIG: Config = {
75
79
  "diagnostics*",
76
80
  ],
77
81
  },
78
- jobs: { notify: true },
82
+ jobs: { notify: true, killOnExit: true },
79
83
  };
80
84
 
81
85
  const AGENT_DIR = getAgentDir();
86
+
87
+ // Survives /reload: the process keeps one pid registry and one exit hook no matter
88
+ // how many times the extension runtime is replaced.
89
+ const STATE: { pids: Set<number>; killOnExit: boolean; hooked: boolean } = ((globalThis as any)[
90
+ Symbol.for("pi-async-jobs.state")
91
+ ] ??= { pids: new Set<number>(), killOnExit: true, hooked: false });
92
+
93
+ if (!STATE.hooked) {
94
+ STATE.hooked = true;
95
+ // Last-resort net: if the graceful shutdown path never finished, nothing is
96
+ // left running once the process goes away.
97
+ process.on("exit", () => {
98
+ if (!STATE.killOnExit) return;
99
+ for (const pid of STATE.pids) {
100
+ try {
101
+ process.kill(-pid, "SIGKILL");
102
+ } catch {
103
+ /* already gone */
104
+ }
105
+ }
106
+ });
107
+ }
82
108
  const CONFIG_PATH = join(AGENT_DIR, "async-jobs.json");
83
109
  const JOBS_DIR = join(AGENT_DIR, "async-jobs");
84
110
  const LOG_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
@@ -219,14 +245,13 @@ function jobTitle(raw: string | undefined, command: string): string {
219
245
  return cutWord(title, TITLE_MAX);
220
246
  }
221
247
 
222
- function killTree(child: ChildProcess, signal: NodeJS.Signals): void {
223
- const pid = child.pid;
248
+ function killTree(pid: number | undefined, signal: NodeJS.Signals): void {
224
249
  if (!pid) return;
225
250
  try {
226
251
  process.kill(-pid, signal); // detached child leads its own process group
227
252
  } catch {
228
253
  try {
229
- child.kill(signal);
254
+ process.kill(pid, signal);
230
255
  } catch {
231
256
  /* already gone */
232
257
  }
@@ -304,16 +329,18 @@ interface Job {
304
329
 
305
330
  export default function piAsyncJobs(pi: ExtensionAPI) {
306
331
  let cfg = loadConfig();
332
+ STATE.killOnExit = cfg.jobs.killOnExit;
307
333
  ensureDir(JOBS_DIR);
308
334
  pruneLogs();
309
335
 
310
336
  const jobs = new Map<string, Job>();
311
337
  let seq = 0;
338
+ let shuttingDown = false;
312
339
 
313
340
  // -------- notifications --------
314
341
 
315
342
  function notify(text: string): void {
316
- if (!cfg.jobs.notify) return;
343
+ if (!cfg.jobs.notify || shuttingDown) return;
317
344
  try {
318
345
  pi.sendMessage(
319
346
  { customType: "async-job", content: text, display: true, details: { kind: "async-job" } },
@@ -332,6 +359,7 @@ export default function piAsyncJobs(pi: ExtensionAPI) {
332
359
  job.endedAt = Date.now();
333
360
  job.exitCode = exitCode;
334
361
  job.signal = signal;
362
+ if (job.pid) STATE.pids.delete(job.pid);
335
363
  if (job.timer) clearTimeout(job.timer);
336
364
 
337
365
  const elapsed = fmtDuration(job.endedAt - job.startedAt);
@@ -375,6 +403,7 @@ export default function piAsyncJobs(pi: ExtensionAPI) {
375
403
  logPath,
376
404
  };
377
405
  jobs.set(id, job);
406
+ if (child.pid) STATE.pids.add(child.pid);
378
407
 
379
408
  child.on("error", (err: Error) => {
380
409
  job.error = err.message;
@@ -388,8 +417,8 @@ export default function piAsyncJobs(pi: ExtensionAPI) {
388
417
  if (limit) {
389
418
  job.timer = setTimeout(() => {
390
419
  job.killStatus = "timeout";
391
- killTree(child, "SIGTERM");
392
- const hard = setTimeout(() => killTree(child, "SIGKILL"), 5000);
420
+ killTree(child.pid, "SIGTERM");
421
+ const hard = setTimeout(() => killTree(child.pid, "SIGKILL"), 5000);
393
422
  hard.unref?.();
394
423
  }, limit * 1000);
395
424
  job.timer.unref?.();
@@ -425,6 +454,35 @@ export default function piAsyncJobs(pi: ExtensionAPI) {
425
454
  hard.unref?.();
426
455
  }
427
456
 
457
+ async function shutdownJobs(): Promise<void> {
458
+ if (!cfg.jobs.killOnExit) return;
459
+ const running = [...jobs.values()].filter((job) => job.status === "running" && job.pid);
460
+ if (running.length === 0) {
461
+ shuttingDown = true;
462
+ return;
463
+ }
464
+ shuttingDown = true;
465
+ for (const job of running) {
466
+ job.killStatus = "killed";
467
+ killTree(job.pid, "SIGTERM");
468
+ }
469
+ const deadline = Date.now() + 3000;
470
+ while (Date.now() < deadline && running.some((job) => job.status === "running")) {
471
+ await new Promise((resolve) => setTimeout(resolve, 50));
472
+ }
473
+ for (const job of running) {
474
+ if (job.status !== "running") continue;
475
+ job.killStatus = "killed";
476
+ job.status = "killed";
477
+ job.endedAt = Date.now();
478
+ if (job.timer) clearTimeout(job.timer);
479
+ if (job.pid) {
480
+ STATE.pids.delete(job.pid);
481
+ killTree(job.pid, "SIGKILL");
482
+ }
483
+ }
484
+ }
485
+
428
486
  function resolveJob(idOrPrefix: string): Job | undefined {
429
487
  const key = idOrPrefix.trim().replace(/^#/, "");
430
488
  if (!key) return undefined;
@@ -798,7 +856,14 @@ export default function piAsyncJobs(pi: ExtensionAPI) {
798
856
 
799
857
  pi.on("session_start", () => {
800
858
  cfg = loadConfig();
859
+ STATE.killOnExit = cfg.jobs.killOnExit;
801
860
  ensureDir(JOBS_DIR);
802
861
  pruneLogs();
803
862
  });
863
+
864
+ // Jobs do not outlive the session that owns them: /reload, /new, /resume and
865
+ // /fork replace the extension runtime, so a survivor would be unmanageable.
866
+ pi.on("session_shutdown", async () => {
867
+ await shutdownJobs();
868
+ });
804
869
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-async-jobs",
3
- "version": "0.1.4",
3
+ "version": "0.2.0",
4
4
  "description": "Foreground command timeouts plus background jobs for the pi coding agent: kill slow tool calls, then run long commands with job_start and get completion, failure, and timeout notifications.",
5
5
  "type": "module",
6
6
  "license": "MIT",