pi-async-jobs 0.1.2 → 0.1.4
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.
- package/README.md +26 -3
- package/index.ts +98 -8
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -37,17 +37,31 @@ 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
|
|
|
44
46
|
| 工具 | 作用 |
|
|
45
47
|
| --- | --- |
|
|
46
48
|
| `job_start` | `{ command, title?, cwd?, timeout? }`,立即返回 job id 和日志路径 |
|
|
47
|
-
| `job_list` | `{ include_finished? }`,状态 / 耗时 / 退出码 /
|
|
49
|
+
| `job_list` | `{ include_finished? }`,状态 / 耗时 / 退出码 / 标题 |
|
|
48
50
|
| `job_output` | `{ id, lines?, pattern? }`,读日志尾部,可用正则过滤 |
|
|
49
51
|
| `job_kill` | `{ id }`,SIGTERM 进程组,5s 后 SIGKILL |
|
|
50
52
|
|
|
53
|
+
### 任务标题
|
|
54
|
+
|
|
55
|
+
`title` 是给人看的标签,不是命令。扩展会强制约束:
|
|
56
|
+
|
|
57
|
+
- 单行、≤48 字符,超长按词边界截断加省略号
|
|
58
|
+
- 模型漏传、或把命令原文/命令开头塞进 `title` 时,自动改写成从命令派生的短标签
|
|
59
|
+
(跳过 `cd x &&`、`FOO=1`、`sudo` 前缀,取前 3 个词,去掉路径)
|
|
60
|
+
- `promptGuidelines` 里要求模型给 3–6 个词的具体名字,禁止 "job"/"command" 这类空标签
|
|
61
|
+
|
|
62
|
+
效果:通知头变成 `[async-job] j1 “install deps” ✅ finished in 42.1s`,`job_list` 第一列是标题,
|
|
63
|
+
命令只在后面附带,方便扫。
|
|
64
|
+
|
|
51
65
|
任务跑完、失败、超时都会推一条消息(`customType: "async-job"`):
|
|
52
66
|
|
|
53
67
|
```text
|
|
@@ -77,11 +91,20 @@ Log: ~/.pi/agent/async-jobs/j1.log — read it with job_output({ id: "j1" }).
|
|
|
77
91
|
```json
|
|
78
92
|
{
|
|
79
93
|
"timeouts": { "bash": 30, "read": 20, "grep": 20, "find": 20, "ls": 10, "write": 0, "edit": 0 },
|
|
80
|
-
"watchdog": {
|
|
94
|
+
"watchdog": {
|
|
95
|
+
"default": 60,
|
|
96
|
+
"hardAbort": false,
|
|
97
|
+
"perTool": { "mcp__slow__query": 20 },
|
|
98
|
+
"exempt": ["ask_user_question", "contact_supervisor", "subagent*", "computer_*", "browser*", "window*", "clipboard*", "recording*", "diagnostics*"]
|
|
99
|
+
},
|
|
81
100
|
"jobs": { "notify": true }
|
|
82
101
|
}
|
|
83
102
|
```
|
|
84
103
|
|
|
104
|
+
`watchdog.exempt` 是默认放过的交互式工具(通配符):这类工具的耗时是人造成的,
|
|
105
|
+
催模型也没用,硬 abort 更糟糕。要监控某个被豁免的工具,在 `perTool` 里显式写一个值即可
|
|
106
|
+
(`perTool` 优先于 `exempt`);写 `0` 则彻底关掉该工具的监控。
|
|
107
|
+
|
|
85
108
|
环境变量(临时覆盖,优先级最高):
|
|
86
109
|
|
|
87
110
|
```bash
|
package/index.ts
CHANGED
|
@@ -43,7 +43,13 @@ 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: {
|
|
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
|
+
};
|
|
47
53
|
jobs: { notify: boolean };
|
|
48
54
|
};
|
|
49
55
|
|
|
@@ -51,7 +57,24 @@ const DEFAULT_CONFIG: Config = {
|
|
|
51
57
|
// 30s for shells is the point of the extension. write/edit default to 0:
|
|
52
58
|
// aborting them mid-write risks a half-written file.
|
|
53
59
|
timeouts: { bash: 30, powershell: 30, read: 20, grep: 20, find: 20, ls: 10, write: 0, edit: 0 },
|
|
54
|
-
watchdog: {
|
|
60
|
+
watchdog: {
|
|
61
|
+
default: 60,
|
|
62
|
+
hardAbort: false,
|
|
63
|
+
perTool: {},
|
|
64
|
+
// Human-in-the-loop tools are slow by definition: the user is the one holding
|
|
65
|
+
// the tool call open. Warning on them is noise, and aborting them is worse.
|
|
66
|
+
exempt: [
|
|
67
|
+
"ask_user_question",
|
|
68
|
+
"contact_supervisor",
|
|
69
|
+
"subagent*",
|
|
70
|
+
"computer_*",
|
|
71
|
+
"browser*",
|
|
72
|
+
"window*",
|
|
73
|
+
"clipboard*",
|
|
74
|
+
"recording*",
|
|
75
|
+
"diagnostics*",
|
|
76
|
+
],
|
|
77
|
+
},
|
|
55
78
|
jobs: { notify: true },
|
|
56
79
|
};
|
|
57
80
|
|
|
@@ -79,6 +102,7 @@ function loadConfig(): Config {
|
|
|
79
102
|
...DEFAULT_CONFIG.watchdog,
|
|
80
103
|
...(raw?.watchdog ?? {}),
|
|
81
104
|
perTool: { ...(raw?.watchdog?.perTool ?? {}) },
|
|
105
|
+
exempt: Array.isArray(raw?.watchdog?.exempt) ? raw.watchdog.exempt : DEFAULT_CONFIG.watchdog.exempt,
|
|
82
106
|
},
|
|
83
107
|
jobs: { ...DEFAULT_CONFIG.jobs, ...(raw?.jobs ?? {}) },
|
|
84
108
|
};
|
|
@@ -142,6 +166,59 @@ function fmtDuration(ms: number): string {
|
|
|
142
166
|
return `${m}m${Math.round(s - m * 60)}s`;
|
|
143
167
|
}
|
|
144
168
|
|
|
169
|
+
const TITLE_MAX = 48;
|
|
170
|
+
|
|
171
|
+
/** Glob match for tool names: `ask_user_question`, `subagent*`, `mcp__*`. */
|
|
172
|
+
function matchesAny(name: string, patterns: string[]): boolean {
|
|
173
|
+
return patterns.some((pattern) => {
|
|
174
|
+
if (!pattern.includes("*")) return pattern === name;
|
|
175
|
+
const body = pattern
|
|
176
|
+
.split("*")
|
|
177
|
+
.map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&"))
|
|
178
|
+
.join(".*");
|
|
179
|
+
return new RegExp(`^${body}$`).test(name);
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Cut on a word boundary so labels never end mid-word. */
|
|
184
|
+
function cutWord(text: string, max: number): string {
|
|
185
|
+
if (text.length <= max) return text;
|
|
186
|
+
const slice = text.slice(0, max);
|
|
187
|
+
const space = slice.lastIndexOf(" ");
|
|
188
|
+
return `${(space > max * 0.6 ? slice.slice(0, space) : slice).trimEnd()}…`;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Short label derived from a command: skip `cd`/env prefixes, first 3 words, no paths. */
|
|
192
|
+
function deriveTitle(command: string): string {
|
|
193
|
+
let rest = command.trim();
|
|
194
|
+
for (let i = 0; i < 6; i++) {
|
|
195
|
+
const next = rest
|
|
196
|
+
.replace(/^(?:cd|pushd)\s+\S+\s*(?:&&\s*)?/, "")
|
|
197
|
+
.replace(/^(?:env|sudo|nohup|time|command)\s+/, "")
|
|
198
|
+
.replace(/^[A-Za-z_][A-Za-z0-9_]*=\S*\s+/, "");
|
|
199
|
+
if (next === rest) break;
|
|
200
|
+
rest = next;
|
|
201
|
+
}
|
|
202
|
+
const first = rest.split(/&&|\|\||[;|\n]/)[0].trim();
|
|
203
|
+
const tokens = first
|
|
204
|
+
.split(/\s+/)
|
|
205
|
+
.filter(Boolean)
|
|
206
|
+
.slice(0, 3)
|
|
207
|
+
.map((token) => token.split("/").filter(Boolean).pop() ?? token);
|
|
208
|
+
return tokens.join(" ") || "shell command";
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Job titles are labels, not commands: single line, short, and never a copy of the
|
|
213
|
+
* command itself (that is what the notification's `$ ...` line is for).
|
|
214
|
+
*/
|
|
215
|
+
function jobTitle(raw: string | undefined, command: string): string {
|
|
216
|
+
const cmd = truncate(command, 400);
|
|
217
|
+
let title = truncate(raw ?? "", TITLE_MAX).replace(/^[$>#]\s*/, "");
|
|
218
|
+
if (!title || cmd.startsWith(title) || title.startsWith(cmd.slice(0, 24))) title = deriveTitle(cmd);
|
|
219
|
+
return cutWord(title, TITLE_MAX);
|
|
220
|
+
}
|
|
221
|
+
|
|
145
222
|
function killTree(child: ChildProcess, signal: NodeJS.Signals): void {
|
|
146
223
|
const pid = child.pid;
|
|
147
224
|
if (!pid) return;
|
|
@@ -260,7 +337,7 @@ export default function piAsyncJobs(pi: ExtensionAPI) {
|
|
|
260
337
|
const elapsed = fmtDuration(job.endedAt - job.startedAt);
|
|
261
338
|
const icon =
|
|
262
339
|
job.status === "done" ? "✅ finished" : job.status === "timeout" ? "⏱ timed out" : job.status === "killed" ? "⛔ killed" : "❌ failed";
|
|
263
|
-
const head = `[async-job] ${job.id} ${icon} in ${elapsed}${exitCode !== undefined ? ` · exit ${exitCode}` : ""}`;
|
|
340
|
+
const head = `[async-job] ${job.id} “${job.title}” ${icon} in ${elapsed}${exitCode !== undefined ? ` · exit ${exitCode}` : ""}`;
|
|
264
341
|
const lines = [`${head}`, `$ ${truncate(job.command, 200)}`];
|
|
265
342
|
|
|
266
343
|
if (job.status !== "done") {
|
|
@@ -291,7 +368,7 @@ export default function piAsyncJobs(pi: ExtensionAPI) {
|
|
|
291
368
|
id,
|
|
292
369
|
command,
|
|
293
370
|
cwd,
|
|
294
|
-
title: opts.title,
|
|
371
|
+
title: jobTitle(opts.title, command),
|
|
295
372
|
startedAt: Date.now(),
|
|
296
373
|
status: "running",
|
|
297
374
|
pid: child.pid,
|
|
@@ -370,7 +447,7 @@ export default function piAsyncJobs(pi: ExtensionAPI) {
|
|
|
370
447
|
: job.signal
|
|
371
448
|
? `sig ${job.signal}`
|
|
372
449
|
: "-";
|
|
373
|
-
return `${job.id.padEnd(4)} ${job.status.padEnd(8)} ${elapsed.padStart(7)} ${exit.padEnd(12)} ${
|
|
450
|
+
return `${job.id.padEnd(4)} ${job.status.padEnd(8)} ${elapsed.padStart(7)} ${exit.padEnd(12)} ${job.title}${job.title === job.command ? "" : ` · ${truncate(job.command, 60)}`}`;
|
|
374
451
|
});
|
|
375
452
|
return [rows.join("\n"), "", `Logs: ${JOBS_DIR}`].join("\n");
|
|
376
453
|
}
|
|
@@ -385,11 +462,17 @@ export default function piAsyncJobs(pi: ExtensionAPI) {
|
|
|
385
462
|
promptSnippet: "Run a long command in the background and get a job id immediately",
|
|
386
463
|
promptGuidelines: [
|
|
387
464
|
"Long-running commands (builds, installs, full test suites, servers, watchers) must use job_start; foreground bash is capped at 30 seconds by default.",
|
|
465
|
+
'Give every job a specific title (3-6 words naming the task, e.g. "install deps", "build webpack", "pytest full suite"). Do not paste the command into the title, and do not use vague labels like "job" or "command".',
|
|
388
466
|
"After job_start, do not poll in a loop. Wait for the completion message, or call job_list/job_output when you have other work done.",
|
|
389
467
|
],
|
|
390
468
|
parameters: Type.Object({
|
|
391
469
|
command: Type.String({ description: "Shell command to run" }),
|
|
392
|
-
title: Type.Optional(
|
|
470
|
+
title: Type.Optional(
|
|
471
|
+
Type.String({
|
|
472
|
+
description:
|
|
473
|
+
'Short human-readable label, 3-6 words, in the user\'s language: e.g. "install deps", "build webpack", "pytest full suite". Never restate the command and never pass a bare command string; if omitted, a label is derived from the command.',
|
|
474
|
+
}),
|
|
475
|
+
),
|
|
393
476
|
cwd: Type.Optional(Type.String({ description: "Working directory (defaults to the session cwd)" })),
|
|
394
477
|
timeout: Type.Optional(Type.Number({ description: "Kill the job after this many seconds (0 or omitted = no limit)" })),
|
|
395
478
|
}),
|
|
@@ -409,7 +492,8 @@ export default function piAsyncJobs(pi: ExtensionAPI) {
|
|
|
409
492
|
{
|
|
410
493
|
type: "text",
|
|
411
494
|
text: [
|
|
412
|
-
`Started ${job.id}
|
|
495
|
+
`Started ${job.id} “${job.title}”${job.pid ? ` (pid ${job.pid})` : ""} in ${job.cwd}`,
|
|
496
|
+
`Title shows up in job_list and in the completion message; pass a better one with title: "..." if this label is wrong.`,
|
|
413
497
|
`$ ${truncate(command, 200)}`,
|
|
414
498
|
`Log: ${job.logPath}`,
|
|
415
499
|
timeout && timeout > 0 ? `Killed automatically after ${timeout}s.` : "",
|
|
@@ -632,13 +716,19 @@ export default function piAsyncJobs(pi: ExtensionAPI) {
|
|
|
632
716
|
pi.on("tool_call", (event, ctx) => {
|
|
633
717
|
const name = event.toolName;
|
|
634
718
|
if (wrapped.has(name) || name.startsWith("job_")) return;
|
|
719
|
+
// An explicit perTool entry overrides the exempt list; otherwise interactive
|
|
720
|
+
// tools (waiting for the user) are skipped entirely.
|
|
721
|
+
if (cfg.watchdog.perTool[name] === undefined && matchesAny(name, cfg.watchdog.exempt)) return;
|
|
635
722
|
const limit = cfg.watchdog.perTool[name] ?? cfg.watchdog.default;
|
|
636
723
|
if (!limit || limit <= 0) return;
|
|
637
724
|
const callId = event.toolCallId;
|
|
638
725
|
clearWatchdog(callId);
|
|
639
726
|
const timer = setTimeout(() => {
|
|
640
727
|
watchdogs.delete(callId);
|
|
641
|
-
const
|
|
728
|
+
const advice = name.startsWith("mcp__")
|
|
729
|
+
? "Job tools cannot run MCP calls, so narrow the request or check the server."
|
|
730
|
+
: "If it does not return soon, prefer job_start for work like this.";
|
|
731
|
+
const msg = `${name} has been running for ${limit}s (tool call ${callId}). ${advice}`;
|
|
642
732
|
try {
|
|
643
733
|
ctx?.ui?.notify?.(`⚠ ${name} 超过 ${limit}s 仍在运行`, "warning");
|
|
644
734
|
} catch {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-async-jobs",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
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",
|