pi-async-jobs 0.1.3 → 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 +24 -4
  2. package/index.ts +118 -11
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -37,7 +37,9 @@ pi install npm:pi-async-jobs
37
37
  - 给模型一条 steer 消息,提示这次调用已经太久、以后这类活该走 `job_start`;
38
38
  - `watchdog.hardAbort: true` 时直接 `ctx.abort()` 中断当前回合。
39
39
 
40
- watchdog 默认 60s,只警告不杀。
40
+ watchdog 默认 60s,只警告不杀。**人机交互类工具一律放过**(`ask_user_question`、`contact_supervisor`、
41
+ `subagent*`、`computer_*`、`browser*` 等,见 `watchdog.exempt`):它们的耗时是用户在思考,
42
+ 催模型没用。
41
43
 
42
44
  ## 后台任务
43
45
 
@@ -72,7 +74,16 @@ Log: ~/.pi/agent/async-jobs/j1.log — read it with job_output({ id: "j1" }).
72
74
  失败和超时会把最后 15 行输出直接贴进消息,省一轮 `job_output`。
73
75
  消息用 `followUp + triggerTurn` 投递:agent 空闲时立刻唤醒,正在跑就等这一轮结束再送。
74
76
 
75
- 后台进程是 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
+ ```
76
87
 
77
88
  人工操作:
78
89
 
@@ -89,11 +100,20 @@ Log: ~/.pi/agent/async-jobs/j1.log — read it with job_output({ id: "j1" }).
89
100
  ```json
90
101
  {
91
102
  "timeouts": { "bash": 30, "read": 20, "grep": 20, "find": 20, "ls": 10, "write": 0, "edit": 0 },
92
- "watchdog": { "default": 60, "hardAbort": false, "perTool": { "mcp__slow__query": 20 } },
93
- "jobs": { "notify": true }
103
+ "watchdog": {
104
+ "default": 60,
105
+ "hardAbort": false,
106
+ "perTool": { "mcp__slow__query": 20 },
107
+ "exempt": ["ask_user_question", "contact_supervisor", "subagent*", "computer_*", "browser*", "window*", "clipboard*", "recording*", "diagnostics*"]
108
+ },
109
+ "jobs": { "notify": true, "killOnExit": true }
94
110
  }
95
111
  ```
96
112
 
113
+ `watchdog.exempt` 是默认放过的交互式工具(通配符):这类工具的耗时是人造成的,
114
+ 催模型也没用,硬 abort 更糟糕。要监控某个被豁免的工具,在 `perTool` 里显式写一个值即可
115
+ (`perTool` 优先于 `exempt`);写 `0` 则彻底关掉该工具的监控。
116
+
97
117
  环境变量(临时覆盖,优先级最高):
98
118
 
99
119
  ```bash
package/index.ts CHANGED
@@ -43,19 +43,68 @@ type Config = {
43
43
  /** Foreground cap per built-in tool, in seconds. 0 disables the cap. */
44
44
  timeouts: Record<string, number>;
45
45
  /** Watchdog for tools this extension cannot wrap. */
46
- watchdog: { default: number; hardAbort: boolean; perTool: Record<string, number> };
47
- jobs: { notify: boolean };
46
+ watchdog: {
47
+ default: number;
48
+ hardAbort: boolean;
49
+ perTool: Record<string, number>;
50
+ /** Tool name patterns that wait on a human and must never be nagged or aborted. */
51
+ exempt: string[];
52
+ };
53
+ jobs: {
54
+ notify: boolean;
55
+ /** Kill every running job when pi shuts down (quit, reload, /new, /resume, /fork). */
56
+ killOnExit: boolean;
57
+ };
48
58
  };
49
59
 
50
60
  const DEFAULT_CONFIG: Config = {
51
61
  // 30s for shells is the point of the extension. write/edit default to 0:
52
62
  // aborting them mid-write risks a half-written file.
53
63
  timeouts: { bash: 30, powershell: 30, read: 20, grep: 20, find: 20, ls: 10, write: 0, edit: 0 },
54
- watchdog: { default: 60, hardAbort: false, perTool: {} },
55
- jobs: { notify: true },
64
+ watchdog: {
65
+ default: 60,
66
+ hardAbort: false,
67
+ perTool: {},
68
+ // Human-in-the-loop tools are slow by definition: the user is the one holding
69
+ // the tool call open. Warning on them is noise, and aborting them is worse.
70
+ exempt: [
71
+ "ask_user_question",
72
+ "contact_supervisor",
73
+ "subagent*",
74
+ "computer_*",
75
+ "browser*",
76
+ "window*",
77
+ "clipboard*",
78
+ "recording*",
79
+ "diagnostics*",
80
+ ],
81
+ },
82
+ jobs: { notify: true, killOnExit: true },
56
83
  };
57
84
 
58
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
+ }
59
108
  const CONFIG_PATH = join(AGENT_DIR, "async-jobs.json");
60
109
  const JOBS_DIR = join(AGENT_DIR, "async-jobs");
61
110
  const LOG_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
@@ -79,6 +128,7 @@ function loadConfig(): Config {
79
128
  ...DEFAULT_CONFIG.watchdog,
80
129
  ...(raw?.watchdog ?? {}),
81
130
  perTool: { ...(raw?.watchdog?.perTool ?? {}) },
131
+ exempt: Array.isArray(raw?.watchdog?.exempt) ? raw.watchdog.exempt : DEFAULT_CONFIG.watchdog.exempt,
82
132
  },
83
133
  jobs: { ...DEFAULT_CONFIG.jobs, ...(raw?.jobs ?? {}) },
84
134
  };
@@ -144,6 +194,18 @@ function fmtDuration(ms: number): string {
144
194
 
145
195
  const TITLE_MAX = 48;
146
196
 
197
+ /** Glob match for tool names: `ask_user_question`, `subagent*`, `mcp__*`. */
198
+ function matchesAny(name: string, patterns: string[]): boolean {
199
+ return patterns.some((pattern) => {
200
+ if (!pattern.includes("*")) return pattern === name;
201
+ const body = pattern
202
+ .split("*")
203
+ .map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&"))
204
+ .join(".*");
205
+ return new RegExp(`^${body}$`).test(name);
206
+ });
207
+ }
208
+
147
209
  /** Cut on a word boundary so labels never end mid-word. */
148
210
  function cutWord(text: string, max: number): string {
149
211
  if (text.length <= max) return text;
@@ -183,14 +245,13 @@ function jobTitle(raw: string | undefined, command: string): string {
183
245
  return cutWord(title, TITLE_MAX);
184
246
  }
185
247
 
186
- function killTree(child: ChildProcess, signal: NodeJS.Signals): void {
187
- const pid = child.pid;
248
+ function killTree(pid: number | undefined, signal: NodeJS.Signals): void {
188
249
  if (!pid) return;
189
250
  try {
190
251
  process.kill(-pid, signal); // detached child leads its own process group
191
252
  } catch {
192
253
  try {
193
- child.kill(signal);
254
+ process.kill(pid, signal);
194
255
  } catch {
195
256
  /* already gone */
196
257
  }
@@ -268,16 +329,18 @@ interface Job {
268
329
 
269
330
  export default function piAsyncJobs(pi: ExtensionAPI) {
270
331
  let cfg = loadConfig();
332
+ STATE.killOnExit = cfg.jobs.killOnExit;
271
333
  ensureDir(JOBS_DIR);
272
334
  pruneLogs();
273
335
 
274
336
  const jobs = new Map<string, Job>();
275
337
  let seq = 0;
338
+ let shuttingDown = false;
276
339
 
277
340
  // -------- notifications --------
278
341
 
279
342
  function notify(text: string): void {
280
- if (!cfg.jobs.notify) return;
343
+ if (!cfg.jobs.notify || shuttingDown) return;
281
344
  try {
282
345
  pi.sendMessage(
283
346
  { customType: "async-job", content: text, display: true, details: { kind: "async-job" } },
@@ -296,6 +359,7 @@ export default function piAsyncJobs(pi: ExtensionAPI) {
296
359
  job.endedAt = Date.now();
297
360
  job.exitCode = exitCode;
298
361
  job.signal = signal;
362
+ if (job.pid) STATE.pids.delete(job.pid);
299
363
  if (job.timer) clearTimeout(job.timer);
300
364
 
301
365
  const elapsed = fmtDuration(job.endedAt - job.startedAt);
@@ -339,6 +403,7 @@ export default function piAsyncJobs(pi: ExtensionAPI) {
339
403
  logPath,
340
404
  };
341
405
  jobs.set(id, job);
406
+ if (child.pid) STATE.pids.add(child.pid);
342
407
 
343
408
  child.on("error", (err: Error) => {
344
409
  job.error = err.message;
@@ -352,8 +417,8 @@ export default function piAsyncJobs(pi: ExtensionAPI) {
352
417
  if (limit) {
353
418
  job.timer = setTimeout(() => {
354
419
  job.killStatus = "timeout";
355
- killTree(child, "SIGTERM");
356
- const hard = setTimeout(() => killTree(child, "SIGKILL"), 5000);
420
+ killTree(child.pid, "SIGTERM");
421
+ const hard = setTimeout(() => killTree(child.pid, "SIGKILL"), 5000);
357
422
  hard.unref?.();
358
423
  }, limit * 1000);
359
424
  job.timer.unref?.();
@@ -389,6 +454,35 @@ export default function piAsyncJobs(pi: ExtensionAPI) {
389
454
  hard.unref?.();
390
455
  }
391
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
+
392
486
  function resolveJob(idOrPrefix: string): Job | undefined {
393
487
  const key = idOrPrefix.trim().replace(/^#/, "");
394
488
  if (!key) return undefined;
@@ -680,13 +774,19 @@ export default function piAsyncJobs(pi: ExtensionAPI) {
680
774
  pi.on("tool_call", (event, ctx) => {
681
775
  const name = event.toolName;
682
776
  if (wrapped.has(name) || name.startsWith("job_")) return;
777
+ // An explicit perTool entry overrides the exempt list; otherwise interactive
778
+ // tools (waiting for the user) are skipped entirely.
779
+ if (cfg.watchdog.perTool[name] === undefined && matchesAny(name, cfg.watchdog.exempt)) return;
683
780
  const limit = cfg.watchdog.perTool[name] ?? cfg.watchdog.default;
684
781
  if (!limit || limit <= 0) return;
685
782
  const callId = event.toolCallId;
686
783
  clearWatchdog(callId);
687
784
  const timer = setTimeout(() => {
688
785
  watchdogs.delete(callId);
689
- const msg = `${name} has been running for ${limit}s (tool call ${callId}). If it does not return soon, prefer job_start for work like this.`;
786
+ const advice = name.startsWith("mcp__")
787
+ ? "Job tools cannot run MCP calls, so narrow the request or check the server."
788
+ : "If it does not return soon, prefer job_start for work like this.";
789
+ const msg = `${name} has been running for ${limit}s (tool call ${callId}). ${advice}`;
690
790
  try {
691
791
  ctx?.ui?.notify?.(`⚠ ${name} 超过 ${limit}s 仍在运行`, "warning");
692
792
  } catch {
@@ -756,7 +856,14 @@ export default function piAsyncJobs(pi: ExtensionAPI) {
756
856
 
757
857
  pi.on("session_start", () => {
758
858
  cfg = loadConfig();
859
+ STATE.killOnExit = cfg.jobs.killOnExit;
759
860
  ensureDir(JOBS_DIR);
760
861
  pruneLogs();
761
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
+ });
762
869
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-async-jobs",
3
- "version": "0.1.3",
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",