pi-auto-unattended 0.5.0 → 0.6.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.
- package/CHANGELOG.md +15 -0
- package/README.md +30 -2
- package/extensions/pi-auto.ts +458 -1
- package/package.json +2 -2
- package/prompt.md +2 -0
- package/test/pi-auto.test.mjs +150 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# CHANGELOG
|
|
2
2
|
|
|
3
|
+
## 0.6.0 (2026-12-05)
|
|
4
|
+
|
|
5
|
+
- 新增工具 **`auto_timer`**:会话内自主预约「到点唤醒」。`auto_timer({after:"25m", note:"…"})` 调完
|
|
6
|
+
直接结束本轮,到点由 pi-mailbox 递一条消息把会话叫起来;等待期间不烧 token、不占工具位。
|
|
7
|
+
落 `state/auto/timers/<pid>.json`,支持 `list` / `cancel`;`agent_before_settle` 在有计时器时
|
|
8
|
+
**不再空转续轮**(audit `timer-wait`),到点 audit `timer-fired`。上限 7 天,跨天开工退回 `auto_schedule`。
|
|
9
|
+
- 新增工具 **`auto_bg`**:跑一条长命令并在**命令真的结束**时唤醒(不是按时长赌)。进程 `detached`
|
|
10
|
+
脱离会话、输出进 `state/auto/bg/<id>/out.log`、子 shell 包一层保证 `exit N`/`set -e` 也拿得到 rc;
|
|
11
|
+
会话内 5 s 轮询 rc(`PI_AUTO_BG_POLL_MS` 可调),落盘即经 pi-mailbox 带 rc + 日志尾叫醒
|
|
12
|
+
(audit `bg-done`);`list` / `tail` / `cancel`(杀进程组)。
|
|
13
|
+
- 动机(实测数字):2026-12-05 07:40 的 limbus 真机批会话 113 min 里 110 min 是 `bash sleep 1500`,
|
|
14
|
+
一次 abort 整轮作废(0 收口)。`auto_switch` 的 `promptGuidelines` 相应改写:长等待不再建议轮内 `sleep`。
|
|
15
|
+
- 回归:`parseAfter` / set-list-cancel / 有计时器时 settle 不续轮 / 到点 mailbox / 重启后过期计时器立刻叫 /
|
|
16
|
+
`auto_bg` 完成带 rc=3 与日志尾且不重复叫醒 / cancel 真杀进程组;`node --test` 17 → 23 条全 pass。
|
|
17
|
+
|
|
3
18
|
## 0.5.0 (2026-12-05)
|
|
4
19
|
|
|
5
20
|
- 新增工具 **`auto_today`**:agent 写今日补充(`today.prompt`)的唯一通道,作用域**默认 = 会话 cwd**
|
package/README.md
CHANGED
|
@@ -147,6 +147,34 @@ auto_schedule({ action: "cancel", id: "sch-…" }) // 取消(id:"all"
|
|
|
147
147
|
- 只写 plan.json,**不影响当前会话**(`auto_switch` 管续轮,预约管排班;两者正交)。
|
|
148
148
|
- 落地时不需要装 systemd timer:daemon 每 60s 扫一次 `schedules`。
|
|
149
149
|
|
|
150
|
+
## 给 agent 的入口(三):`auto_timer` / `auto_bg`(等东西,但不空转)
|
|
151
|
+
|
|
152
|
+
2026-12-05 之前的口径是「等 CI/跑批就在轮内 `bash sleep 1500`」。limbus 那轮的真机批实证了代价:
|
|
153
|
+
113 min 的会话里 110 min 是 `sleep`,一次 abort(用户登录后关掉 pane)整轮就白等,什么都没落地。
|
|
154
|
+
现在给两个**调完就结束本轮**的入口,等的东西好了再由 pi-mailbox 把会话叫起来:
|
|
155
|
+
|
|
156
|
+
```js
|
|
157
|
+
// 按钟点:25 分钟后叫醒我,去看批进度
|
|
158
|
+
auto_timer({ action: "set", after: "25m", note: "看 perf-stats 的 actions/ocr 计数" })
|
|
159
|
+
auto_timer({ action: "list" }) // 本会话排着的计时器
|
|
160
|
+
auto_timer({ action: "cancel", id: "tm-…" }) // 取消(id:"all" 清空)
|
|
161
|
+
|
|
162
|
+
// 按「命令真的结束」:跑一条长命令,结束时带 rc + 日志尾叫醒我
|
|
163
|
+
auto_bg({ action: "run", command: "timeout -k 60 9600 bash tools/aacl-run.sh tools/run-aalc-mirror.py --minutes 150" })
|
|
164
|
+
auto_bg({ action: "list" }) // 本会话的后台命令(running / rc=N)
|
|
165
|
+
auto_bg({ action: "tail", id: "bg-…" }) // 看日志尾
|
|
166
|
+
auto_bg({ action: "cancel", id: "bg-…" }) // 杀整个进程组
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
- `auto_timer`:只吃相对时长(`25m` / `90s` / `2h` / `150分钟`,上限 7 天),落
|
|
170
|
+
`state/auto/timers/<pid>.json`;排着计时器时 `agent_before_settle` **不空转续轮**(audit `timer-wait`),
|
|
171
|
+
到点写一条 pi-mailbox 消息(audit `timer-fired`)。跨天/跨进程开工仍用 `auto_schedule`。
|
|
172
|
+
- `auto_bg`:`/bin/bash -c` 起**脱离会话**的进程(`detached`,pi 退出不影响它),stdout/stderr 进
|
|
173
|
+
`state/auto/bg/<id>/out.log`,包一层子 shell 保证命令自己 `exit N`/`set -e` 也能拿到 rc;
|
|
174
|
+
会话内每 5 s 轮询 rc 文件(`PI_AUTO_BG_POLL_MS` 可调),落盘即叫醒(audit `bg-done`)。
|
|
175
|
+
- 边界(诚实写清楚):两个都依赖**会话进程活着**——会话被 kill/`q` 掉,唤醒就没了(命令照样跑完),
|
|
176
|
+
那种场景用 `auto_schedule` 预约到点回收;子代理进程不加载本插件,也就没有这两个工具。
|
|
177
|
+
|
|
150
178
|
CLI(人用,等价入口):
|
|
151
179
|
|
|
152
180
|
```bash
|
|
@@ -221,7 +249,7 @@ systemd --user pi-auto.service
|
|
|
221
249
|
扩展写 `retired/<slug>.json`,当天不再拉起,跨天自动恢复。
|
|
222
250
|
- 不设夜间时段门禁、不观察桌面登录:服务只服从 `plan.json` 和「用户优先」这一条。
|
|
223
251
|
|
|
224
|
-
## 会话内:`auto_switch`
|
|
252
|
+
## 会话内:`auto_switch` / `auto_schedule` / `auto_timer` / `auto_bg`
|
|
225
253
|
|
|
226
254
|
- 无人值守会话(`PI_AUTO_SESSION_ID` / 兼容 `PI_BOOT_SESSION_ID` / `PI_RUN_DIR`)默认 **on**;
|
|
227
255
|
用户手开会话默认 **off**(不许静默自己续轮)。
|
|
@@ -284,7 +312,7 @@ pi-auto service install # 或手抄 systemd/pi-aut
|
|
|
284
312
|
cd ~/pi-plugins/pi-auto
|
|
285
313
|
npm run validate # = node 单测 + lib.sh/schedule shell 门禁 + import check + pack --dry-run
|
|
286
314
|
# 分开跑:
|
|
287
|
-
node --test 'test/*.test.mjs' # 开关/续轮/retired/mailbox 轻推/auto_schedule 与 when
|
|
315
|
+
node --test 'test/*.test.mjs' # 开关/续轮/retired/mailbox 轻推/auto_schedule 与 when 解析/auto_timer/auto_bg
|
|
288
316
|
bash test/lib.test.sh # plan/retired/slug/prompt/预约判据
|
|
289
317
|
bash test/schedule.test.sh # 预约端到端(dry-launch:once 消费即清理 / recurring 保留 prompt)
|
|
290
318
|
```
|
package/extensions/pi-auto.ts
CHANGED
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
* audit.log 一行一条 JSON
|
|
17
17
|
*/
|
|
18
18
|
import crypto from "node:crypto";
|
|
19
|
+
import { spawn } from "node:child_process";
|
|
19
20
|
import fs from "node:fs";
|
|
20
21
|
import os from "node:os";
|
|
21
22
|
import path from "node:path";
|
|
@@ -519,6 +520,134 @@ export function checkTodayWrite(plan: PlanFile, scope: string, cwd: string, text
|
|
|
519
520
|
return { needsConfirm: false };
|
|
520
521
|
}
|
|
521
522
|
|
|
523
|
+
// ---------------------------------------------------------------- 计时器(会话内自主预约)
|
|
524
|
+
//
|
|
525
|
+
// 2026-12-05 事故:limbus 那轮 113 min 里有 110 min 是 `bash sleep 1500`(轮内阻塞等待),
|
|
526
|
+
// 一次 abort 就让整轮白等。改成「预约一个到点唤醒」:调完直接结束本轮,到点由 pi-mailbox
|
|
527
|
+
// 递一条消息把会话叫起来 —— 等待期间不烧 token、不占工具位、可 list/cancel。
|
|
528
|
+
//
|
|
529
|
+
// 落盘 `state/auto/timers/<pid>.json`(与 session-<pid>.json 分开,避免 touch() 覆盖它)。
|
|
530
|
+
// 进程死了就不再有唤醒(这是本工具与 auto_schedule 的分界:跨进程用 auto_schedule)。
|
|
531
|
+
export type TimerEntry = {
|
|
532
|
+
id: string;
|
|
533
|
+
dueAt: number;
|
|
534
|
+
note: string;
|
|
535
|
+
createdAt: string;
|
|
536
|
+
};
|
|
537
|
+
|
|
538
|
+
export function timersRoot(): string {
|
|
539
|
+
return path.join(autoRoot(), "timers");
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
export function timersPath(pid: number = process.pid): string {
|
|
543
|
+
return path.join(timersRoot(), `${pid}.json`);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
export function readTimers(pid: number = process.pid): TimerEntry[] {
|
|
547
|
+
try {
|
|
548
|
+
const raw = JSON.parse(fs.readFileSync(timersPath(pid), "utf8"));
|
|
549
|
+
if (!Array.isArray(raw)) return [];
|
|
550
|
+
return raw.filter((t) => t && typeof t.dueAt === "number" && typeof t.id === "string") as TimerEntry[];
|
|
551
|
+
} catch {
|
|
552
|
+
return [];
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
export function writeTimers(list: TimerEntry[], pid: number = process.pid): void {
|
|
557
|
+
try {
|
|
558
|
+
fs.mkdirSync(timersRoot(), { recursive: true });
|
|
559
|
+
const file = timersPath(pid);
|
|
560
|
+
if (!list.length) {
|
|
561
|
+
fs.rmSync(file, { force: true });
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
const tmp = `${file}.tmp`;
|
|
565
|
+
fs.writeFileSync(tmp, `${JSON.stringify(list, null, 2)}\n`);
|
|
566
|
+
fs.renameSync(tmp, file);
|
|
567
|
+
} catch {
|
|
568
|
+
/* 写不进去就少一次唤醒,不阻断会话 */
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* 认「多久之后」:25m / 90s / 2h / 150min / 25分钟 / 1天。
|
|
574
|
+
* 只吃相对时长;绝对时点归 auto_schedule(不要在会话里挂一个跨进程的钟)。
|
|
575
|
+
*/
|
|
576
|
+
export function parseAfter(raw: string, now = new Date()): Date {
|
|
577
|
+
const s = String(raw ?? "")
|
|
578
|
+
.trim()
|
|
579
|
+
.replace(/[\uFF01-\uFF5E]/g, (c) => String.fromCharCode(c.charCodeAt(0) - 0xfee0))
|
|
580
|
+
.replace(/^\+/, "")
|
|
581
|
+
.toLowerCase();
|
|
582
|
+
const m = /^(\d+)\s*(秒钟|秒|分钟|分|小时|钟头|天|s|sec|secs|second|seconds|min|mins|minute|minutes|m|h|hr|hrs|hour|hours|d|day|days)$/.exec(s);
|
|
583
|
+
if (!m) throw new Error(`认不出时长:${raw}(例:25m / 90s / 2h / 150min)`);
|
|
584
|
+
const n = Number(m[1]);
|
|
585
|
+
const u = m[2];
|
|
586
|
+
const ms = /^(s|sec|second)/.test(u) || /秒/.test(u)
|
|
587
|
+
? 1_000
|
|
588
|
+
: /^(m|min|minute)/.test(u) || /分/.test(u)
|
|
589
|
+
? 60_000
|
|
590
|
+
: /^(h|hr|hour)/.test(u) || /小时|钟头/.test(u)
|
|
591
|
+
? 3_600_000
|
|
592
|
+
: 86_400_000;
|
|
593
|
+
return new Date(now.getTime() + n * ms);
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/** 计时器一律走 auto_schedule 的上限:会话内 setTimeout 只可靠到几小时~几天。 */
|
|
597
|
+
export const MAX_TIMER_MS = 7 * 86_400_000;
|
|
598
|
+
|
|
599
|
+
// ---------------------------------------------------------------- 后台命令(完成即唤醒)
|
|
600
|
+
//
|
|
601
|
+
// `auto_bg` = 「跑一条长命令,跑完叫我」:脱离会话起进程(pi 退出也不受影响),
|
|
602
|
+
// 命令结束时写 rc 文件,会话内 5 s 一轮的轻量轮询发现 rc 落盘 ⇒ 走 pi-mailbox 唤醒。
|
|
603
|
+
// 与 auto_timer 的区别:那个按钟点叫,这个按「命令真的结束」叫(跑批/编译/长测试)。
|
|
604
|
+
export type BgJob = {
|
|
605
|
+
id: string;
|
|
606
|
+
pid: number;
|
|
607
|
+
command: string;
|
|
608
|
+
cwd: string;
|
|
609
|
+
log: string;
|
|
610
|
+
rcFile: string;
|
|
611
|
+
startedAt: string;
|
|
612
|
+
};
|
|
613
|
+
|
|
614
|
+
export function bgRoot(): string {
|
|
615
|
+
return path.join(autoRoot(), "bg");
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
export function bgIndexPath(pid: number = process.pid): string {
|
|
619
|
+
return path.join(bgRoot(), `${pid}.json`);
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
export function readJobs(pid: number = process.pid): BgJob[] {
|
|
623
|
+
try {
|
|
624
|
+
const raw = JSON.parse(fs.readFileSync(bgIndexPath(pid), "utf8"));
|
|
625
|
+
return Array.isArray(raw) ? (raw as BgJob[]) : [];
|
|
626
|
+
} catch {
|
|
627
|
+
return [];
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
export function writeJobs(list: BgJob[], pid: number = process.pid): void {
|
|
632
|
+
try {
|
|
633
|
+
fs.mkdirSync(bgRoot(), { recursive: true });
|
|
634
|
+
const file = bgIndexPath(pid);
|
|
635
|
+
if (!list.length) {
|
|
636
|
+
fs.rmSync(file, { force: true });
|
|
637
|
+
return;
|
|
638
|
+
}
|
|
639
|
+
const tmp = `${file}.tmp`;
|
|
640
|
+
fs.writeFileSync(tmp, `${JSON.stringify(list, null, 2)}\n`);
|
|
641
|
+
fs.renameSync(tmp, file);
|
|
642
|
+
} catch {
|
|
643
|
+
/* ignore */
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
function shellQuote(value: string): string {
|
|
648
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
649
|
+
}
|
|
650
|
+
|
|
522
651
|
export default function (pi: ExtensionAPI) {
|
|
523
652
|
if (inChildProcess()) return;
|
|
524
653
|
let state: AutoState | undefined;
|
|
@@ -529,6 +658,77 @@ export default function (pi: ExtensionAPI) {
|
|
|
529
658
|
// 今日补充的跨项目二次确认:key = scope\u0000text,值为过期时刻(会话内有效,不跨进程)
|
|
530
659
|
const pendingToday = new Map<string, number>();
|
|
531
660
|
const TODAY_CONFIRM_TTL_MS = 10 * 60_000;
|
|
661
|
+
// 计时器/后台命令的运行期句柄(磁盘状态是权威,这里只是“到点提醒”的定时器)
|
|
662
|
+
const timerHandles = new Map<string, ReturnType<typeof setTimeout>>();
|
|
663
|
+
let bgPoller: ReturnType<typeof setInterval> | undefined;
|
|
664
|
+
|
|
665
|
+
const fireTimer = (entry: TimerEntry): void => {
|
|
666
|
+
timerHandles.delete(entry.id);
|
|
667
|
+
writeTimers(readTimers().filter((t) => t.id !== entry.id));
|
|
668
|
+
const at = formatLocal(new Date(entry.dueAt));
|
|
669
|
+
enqueueMailbox(
|
|
670
|
+
`【pi-auto 计时器】到点(${at}):${entry.note}\n` +
|
|
671
|
+
"开关仍开就接着推进这单;等的东西还没好就再 `auto_timer` 排下一次,确实收工才 `auto_switch({action:\"off\"})`。",
|
|
672
|
+
);
|
|
673
|
+
audit({ kind: "timer-fired", id: entry.id, dueAt: at, note: entry.note.slice(0, 120) });
|
|
674
|
+
};
|
|
675
|
+
|
|
676
|
+
const armTimer = (entry: TimerEntry): void => {
|
|
677
|
+
const prev = timerHandles.get(entry.id);
|
|
678
|
+
if (prev) clearTimeout(prev);
|
|
679
|
+
const delay = Math.max(0, entry.dueAt - Date.now());
|
|
680
|
+
const handle = setTimeout(() => fireTimer(entry), delay);
|
|
681
|
+
(handle as unknown as { unref?: () => void }).unref?.();
|
|
682
|
+
timerHandles.set(entry.id, handle);
|
|
683
|
+
};
|
|
684
|
+
|
|
685
|
+
/** 后台任务完成轮询:只在有活任务时挂一个 5 s 的 unref 定时器。 */
|
|
686
|
+
const refreshBgPoller = (): void => {
|
|
687
|
+
if (bgPoller) {
|
|
688
|
+
clearInterval(bgPoller);
|
|
689
|
+
bgPoller = undefined;
|
|
690
|
+
}
|
|
691
|
+
if (!readJobs().length) return;
|
|
692
|
+
const pollMs = Number(process.env.PI_AUTO_BG_POLL_MS ?? "");
|
|
693
|
+
const interval = Number.isFinite(pollMs) && pollMs > 0 ? pollMs : 5_000;
|
|
694
|
+
bgPoller = setInterval(() => {
|
|
695
|
+
const jobs = readJobs();
|
|
696
|
+
if (!jobs.length) {
|
|
697
|
+
refreshBgPoller();
|
|
698
|
+
return;
|
|
699
|
+
}
|
|
700
|
+
let changed = false;
|
|
701
|
+
const keep: BgJob[] = [];
|
|
702
|
+
for (const job of jobs) {
|
|
703
|
+
let rc: string | undefined;
|
|
704
|
+
try {
|
|
705
|
+
rc = fs.readFileSync(job.rcFile, "utf8").trim();
|
|
706
|
+
} catch {
|
|
707
|
+
rc = undefined;
|
|
708
|
+
}
|
|
709
|
+
if (rc === undefined) {
|
|
710
|
+
keep.push(job);
|
|
711
|
+
continue;
|
|
712
|
+
}
|
|
713
|
+
changed = true;
|
|
714
|
+
let tail = "";
|
|
715
|
+
try {
|
|
716
|
+
tail = fs.readFileSync(job.log, "utf8").slice(-800).trim();
|
|
717
|
+
} catch {
|
|
718
|
+
tail = "(日志读不到)";
|
|
719
|
+
}
|
|
720
|
+
enqueueMailbox(
|
|
721
|
+
`【pi-auto 后台命令结束】${job.command}\n` +
|
|
722
|
+
` rc=${rc} 日志:${job.log}\n` +
|
|
723
|
+
(tail ? ` 日志尾:\n${tail}\n` : "") +
|
|
724
|
+
"开关仍开就接着收这单(读数/收口/提交);做完才 `auto_switch({action:\"off\"})`。",
|
|
725
|
+
);
|
|
726
|
+
audit({ kind: "bg-done", id: job.id, rc, log: job.log, command: job.command.slice(0, 120) });
|
|
727
|
+
}
|
|
728
|
+
if (changed) writeJobs(keep);
|
|
729
|
+
}, interval);
|
|
730
|
+
(bgPoller as unknown as { unref?: () => void }).unref?.();
|
|
731
|
+
};
|
|
532
732
|
|
|
533
733
|
const touch = (ctx: ExtensionContext, patch: Partial<AutoState> = {}): AutoState => {
|
|
534
734
|
const now = new Date().toISOString();
|
|
@@ -594,7 +794,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
594
794
|
promptGuidelines: [
|
|
595
795
|
"还有自己能做的活 → `auto_switch({action:\"on\"})`(无人值守会话默认已开);",
|
|
596
796
|
"收工或只剩人工/审批/环境门 → `auto_switch({action:\"off\", note:\"原因\"})`:这是唯一的收工信号;",
|
|
597
|
-
"等 CI
|
|
797
|
+
"等 CI/子代理/分钟级 ⇒ `auto_timer({after:\"25m\"})`;等一条长命令 ⇒ `auto_bg({command:…})`(都是调完就结束本轮,不要 `bash sleep`);",
|
|
598
798
|
],
|
|
599
799
|
parameters: {
|
|
600
800
|
type: "object",
|
|
@@ -909,6 +1109,235 @@ export default function (pi: ExtensionAPI) {
|
|
|
909
1109
|
},
|
|
910
1110
|
});
|
|
911
1111
|
|
|
1112
|
+
// ---------------------------------------------------------------- 计时器入口
|
|
1113
|
+
pi.registerTool({
|
|
1114
|
+
name: "auto_timer",
|
|
1115
|
+
label: "会话内计时器",
|
|
1116
|
+
description:
|
|
1117
|
+
"给自己排一个到点唤醒(不阻塞、不烧 token):调完就结束这一轮,到点 pi-mailbox 把会话叫起来。" +
|
|
1118
|
+
"等几分钟到几小时都用它,代替 `bash sleep 600`(那个会把整轮堵死、被 abort 就白等)。" +
|
|
1119
|
+
"只吃相对时长(25m/90s/2h/150min);跨进程/明天到点开工用 auto_schedule。" +
|
|
1120
|
+
"action=set(需 after)| list | cancel(id 或 all)。",
|
|
1121
|
+
promptSnippet: "会话内计时器(pi-auto):auto_timer({after:\"25m\", note:\"继续看批\"}),然后直接结束这一轮",
|
|
1122
|
+
promptGuidelines: [
|
|
1123
|
+
"等批次/CI/外部作业几分钟以上 ⇒ `auto_timer({after:\"25m\", note:\"要接着看什么\"})` 然后本轮结束,**不要** `bash sleep 1500`。",
|
|
1124
|
+
"到点被叫起来后:先看读数再决定继续等还是收口;要再等就再排一次。",
|
|
1125
|
+
"等的是「命令真的结束」⇒ 用 `auto_bg`(按完成叫醒),不要拿固定时长去赌。",
|
|
1126
|
+
],
|
|
1127
|
+
parameters: {
|
|
1128
|
+
type: "object",
|
|
1129
|
+
properties: {
|
|
1130
|
+
action: { type: "string", enum: ["set", "list", "cancel"], description: "set | list | cancel" },
|
|
1131
|
+
after: { type: "string", description: "多久之后:25m / 90s / 2h / 150min(最长 7 天)" },
|
|
1132
|
+
note: { type: "string", description: "到点时给自己看的一句话:该干什么/该看什么" },
|
|
1133
|
+
id: { type: "string", description: "cancel 的目标 id(或 all)" },
|
|
1134
|
+
},
|
|
1135
|
+
required: ["action"],
|
|
1136
|
+
additionalProperties: false,
|
|
1137
|
+
},
|
|
1138
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1139
|
+
const p = (params ?? {}) as { action?: string; after?: string; note?: string; id?: string };
|
|
1140
|
+
const action = String(p.action ?? "list");
|
|
1141
|
+
const fail = (text: string) => ({ content: [{ type: "text" as const, text }], isError: true });
|
|
1142
|
+
const describe = (t: TimerEntry) =>
|
|
1143
|
+
` ${t.id} ${formatLocal(new Date(t.dueAt))}${t.dueAt <= Date.now() ? "(已到点,下一轮会叫)" : ""}\n ${t.note.replace(/\s+/g, " ").slice(0, 160)}`;
|
|
1144
|
+
|
|
1145
|
+
if (action === "list") {
|
|
1146
|
+
const list = readTimers();
|
|
1147
|
+
return {
|
|
1148
|
+
content: [
|
|
1149
|
+
{
|
|
1150
|
+
type: "text" as const,
|
|
1151
|
+
text: list.length
|
|
1152
|
+
? `本会话计时器(${list.length} 个):\n${list.map(describe).join("\n")}`
|
|
1153
|
+
: "本会话没有计时器(auto_timer({action:\"set\", after:\"25m\"}) 排一个)",
|
|
1154
|
+
},
|
|
1155
|
+
],
|
|
1156
|
+
details: { timers: list },
|
|
1157
|
+
};
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
if (action === "cancel") {
|
|
1161
|
+
const id = String(p.id ?? "").trim();
|
|
1162
|
+
if (!id) return fail('cancel 需要 id(用 action="list" 查),或 id="all"');
|
|
1163
|
+
const before = readTimers();
|
|
1164
|
+
const after = id === "all" ? [] : before.filter((t) => t.id !== id);
|
|
1165
|
+
for (const t of before) {
|
|
1166
|
+
if (id === "all" || t.id === id) {
|
|
1167
|
+
const h = timerHandles.get(t.id);
|
|
1168
|
+
if (h) clearTimeout(h);
|
|
1169
|
+
timerHandles.delete(t.id);
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
writeTimers(after);
|
|
1173
|
+
audit({ kind: "timer-cancel", id, removed: before.length - after.length, cwd: ctx.cwd });
|
|
1174
|
+
if (before.length === after.length) return fail(`没有这个计时器:${id}`);
|
|
1175
|
+
return { content: [{ type: "text" as const, text: `已取消 ${before.length - after.length} 个计时器(${id})` }], details: { id } };
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
if (action !== "set") return fail(`未知 action:${action}(set | list | cancel)`);
|
|
1179
|
+
const raw = String(p.after ?? p.note ?? "").trim();
|
|
1180
|
+
if (!String(p.after ?? "").trim()) return fail('set 需要 after:多久之后叫醒(例:25m / 90s / 2h)');
|
|
1181
|
+
let due: Date;
|
|
1182
|
+
try {
|
|
1183
|
+
due = parseAfter(raw);
|
|
1184
|
+
} catch (error) {
|
|
1185
|
+
return fail(String((error as Error).message ?? error));
|
|
1186
|
+
}
|
|
1187
|
+
if (due.getTime() - Date.now() > MAX_TIMER_MS) {
|
|
1188
|
+
return fail(`计时器最长 ${MAX_TIMER_MS / 86_400_000} 天;跨天开工请用 auto_schedule(mode:\"once\", when:\"明天 07:40\")`);
|
|
1189
|
+
}
|
|
1190
|
+
const entry: TimerEntry = {
|
|
1191
|
+
id: `tm-${Date.now().toString(36)}-${crypto.randomBytes(2).toString("hex")}`,
|
|
1192
|
+
dueAt: due.getTime(),
|
|
1193
|
+
note: String(p.note ?? "接着推进手头这单").trim() || "接着推进手头这单",
|
|
1194
|
+
createdAt: new Date().toISOString(),
|
|
1195
|
+
};
|
|
1196
|
+
writeTimers([...readTimers(), entry]);
|
|
1197
|
+
armTimer(entry);
|
|
1198
|
+
audit({ kind: "timer-set", id: entry.id, dueAt: formatLocal(due), note: entry.note.slice(0, 120), cwd: ctx.cwd });
|
|
1199
|
+
return {
|
|
1200
|
+
content: [
|
|
1201
|
+
{
|
|
1202
|
+
type: "text" as const,
|
|
1203
|
+
text:
|
|
1204
|
+
`计时器已排:${entry.id} → ${formatLocal(due)}(约 ${Math.round((due.getTime() - Date.now()) / 60_000)} 分钟)\n` +
|
|
1205
|
+
` 到点会以 pi-mailbox 消息叫醒:${entry.note}\n` +
|
|
1206
|
+
" 现在可以直接结束这一轮(不要再 `bash sleep`);开关仍开就 auto_switch 不管它。",
|
|
1207
|
+
},
|
|
1208
|
+
],
|
|
1209
|
+
details: { timer: entry },
|
|
1210
|
+
};
|
|
1211
|
+
},
|
|
1212
|
+
});
|
|
1213
|
+
|
|
1214
|
+
// ---------------------------------------------------------------- 后台命令入口
|
|
1215
|
+
pi.registerTool({
|
|
1216
|
+
name: "auto_bg",
|
|
1217
|
+
label: "后台命令(完成即唤醒)",
|
|
1218
|
+
description:
|
|
1219
|
+
"跑一条长命令(跑批/编译/长测试),**命令真的结束**时用 pi-mailbox 叫醒本会话;不等进程数完就结束本轮。" +
|
|
1220
|
+
"命令进程与 pi 脱离(pi 退出不影响它),输出写 $PI_CODING_AGENT_DIR/state/auto/bg/<id>/out.log。" +
|
|
1221
|
+
"action=run(需 command)| list | tail(需 id)| cancel(id 或 all)。",
|
|
1222
|
+
promptSnippet: "后台命令(pi-auto):auto_bg({command:\"…\"}) 立即返回,命令结束时叫醒本会话",
|
|
1223
|
+
promptGuidelines: [
|
|
1224
|
+
"等一条长命令(真机批/全量测试/大编译,>5 min)⇒ `auto_bg({command:\"timeout -k 60 9600 bash tools/… \\| tee logs/…\"})`,然后本轮结束,**不要**守着 `sleep`。",
|
|
1225
|
+
"命令里必须自带 `timeout -k`(硬规则 14);被唤醒后先 `auto_bg({action:\"tail\", id})` 看尾巴再决定下一步。",
|
|
1226
|
+
"会话被 kill / 进程退出 ⇒ 唤醒丢失(命令照样跑完);那种场景用 `auto_schedule` 预约到点回收。",
|
|
1227
|
+
],
|
|
1228
|
+
parameters: {
|
|
1229
|
+
type: "object",
|
|
1230
|
+
properties: {
|
|
1231
|
+
action: { type: "string", enum: ["run", "list", "tail", "cancel"], description: "run | list | tail | cancel" },
|
|
1232
|
+
command: { type: "string", description: "要跑的命令(bash -c;自带 timeout)" },
|
|
1233
|
+
id: { type: "string", description: "tail/cancel 的目标 id(cancel 接受 all)" },
|
|
1234
|
+
},
|
|
1235
|
+
required: ["action"],
|
|
1236
|
+
additionalProperties: false,
|
|
1237
|
+
},
|
|
1238
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1239
|
+
const p = (params ?? {}) as { action?: string; command?: string; id?: string };
|
|
1240
|
+
const action = String(p.action ?? "list");
|
|
1241
|
+
const fail = (text: string) => ({ content: [{ type: "text" as const, text }], isError: true });
|
|
1242
|
+
const state = (job: BgJob): string => {
|
|
1243
|
+
try {
|
|
1244
|
+
return `rc=${fs.readFileSync(job.rcFile, "utf8").trim()}`;
|
|
1245
|
+
} catch {
|
|
1246
|
+
return "running";
|
|
1247
|
+
}
|
|
1248
|
+
};
|
|
1249
|
+
|
|
1250
|
+
if (action === "list") {
|
|
1251
|
+
const jobs = readJobs();
|
|
1252
|
+
return {
|
|
1253
|
+
content: [
|
|
1254
|
+
{
|
|
1255
|
+
type: "text" as const,
|
|
1256
|
+
text: jobs.length
|
|
1257
|
+
? `本会话后台命令(${jobs.length}):\n${jobs
|
|
1258
|
+
.map((j) => ` ${j.id} ${state(j)} ${j.startedAt.slice(11, 16)} ${j.command.slice(0, 100)}\n 日志:${j.log}`)
|
|
1259
|
+
.join("\n")}`
|
|
1260
|
+
: "本会话没有后台命令",
|
|
1261
|
+
},
|
|
1262
|
+
],
|
|
1263
|
+
details: { jobs },
|
|
1264
|
+
};
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
if (action === "tail" || action === "cancel") {
|
|
1268
|
+
const id = String(p.id ?? "").trim();
|
|
1269
|
+
if (!id) return fail(`${action} 需要 id(用 action="list" 查)`);
|
|
1270
|
+
const jobs = readJobs();
|
|
1271
|
+
const hit = jobs.filter((j) => (id === "all" ? true : j.id === id));
|
|
1272
|
+
if (!hit.length) return fail(`没有这个后台命令:${id}`);
|
|
1273
|
+
if (action === "tail") {
|
|
1274
|
+
const job = hit[0];
|
|
1275
|
+
let tail = "";
|
|
1276
|
+
try {
|
|
1277
|
+
tail = fs.readFileSync(job.log, "utf8").slice(-4000).trim();
|
|
1278
|
+
} catch {
|
|
1279
|
+
tail = "(日志还没生成)";
|
|
1280
|
+
}
|
|
1281
|
+
return {
|
|
1282
|
+
content: [{ type: "text" as const, text: `${job.id} ${state(job)} ${job.command}\n日志:${job.log}\n---\n${tail}` }],
|
|
1283
|
+
details: { job },
|
|
1284
|
+
};
|
|
1285
|
+
}
|
|
1286
|
+
for (const job of hit) {
|
|
1287
|
+
try {
|
|
1288
|
+
process.kill(-job.pid, "SIGTERM");
|
|
1289
|
+
} catch {
|
|
1290
|
+
/* 已经死了 */
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
writeJobs(jobs.filter((j) => !hit.includes(j)));
|
|
1294
|
+
audit({ kind: "bg-cancel", id, removed: hit.length, cwd: ctx.cwd });
|
|
1295
|
+
return { content: [{ type: "text" as const, text: `已取消 ${hit.length} 条后台命令(${id})` }], details: { id } };
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
if (action !== "run") return fail(`未知 action:${action}(run | list | tail | cancel)`);
|
|
1299
|
+
const command = String(p.command ?? "").trim();
|
|
1300
|
+
if (!command) return fail('run 需要 command');
|
|
1301
|
+
if (!fs.existsSync(ctx.cwd) || !fs.statSync(ctx.cwd).isDirectory()) return fail(`cwd 不存在:${ctx.cwd}`);
|
|
1302
|
+
const id = `bg-${Date.now().toString(36)}-${crypto.randomBytes(2).toString("hex")}`;
|
|
1303
|
+
const dir = path.join(bgRoot(), id);
|
|
1304
|
+
let job: BgJob;
|
|
1305
|
+
try {
|
|
1306
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
1307
|
+
const log = path.join(dir, "out.log");
|
|
1308
|
+
const rcFile = path.join(dir, "rc");
|
|
1309
|
+
const fd = fs.openSync(log, "a");
|
|
1310
|
+
// 用子 shell 包住:命令自己 `exit N`/`set -e` 只退子 shell,不会跳过写 rc
|
|
1311
|
+
const child = spawn("/bin/bash", ["-c", `( ${command}\n) ; printf '%s' "$?" > ${shellQuote(rcFile)}`], {
|
|
1312
|
+
cwd: ctx.cwd,
|
|
1313
|
+
detached: true,
|
|
1314
|
+
stdio: ["ignore", fd, fd],
|
|
1315
|
+
env: process.env,
|
|
1316
|
+
});
|
|
1317
|
+
child.unref();
|
|
1318
|
+
fs.closeSync(fd);
|
|
1319
|
+
job = { id, pid: child.pid ?? -1, command, cwd: ctx.cwd, log, rcFile, startedAt: new Date().toISOString() };
|
|
1320
|
+
} catch (error) {
|
|
1321
|
+
return fail(`起后台命令失败:${String(error)}`);
|
|
1322
|
+
}
|
|
1323
|
+
writeJobs([...readJobs(), job]);
|
|
1324
|
+
refreshBgPoller();
|
|
1325
|
+
audit({ kind: "bg-start", id, pid: job.pid, command: command.slice(0, 160), cwd: ctx.cwd });
|
|
1326
|
+
return {
|
|
1327
|
+
content: [
|
|
1328
|
+
{
|
|
1329
|
+
type: "text" as const,
|
|
1330
|
+
text:
|
|
1331
|
+
`后台命令已起:${id}(pid=${job.pid},cwd=${job.cwd})\n` +
|
|
1332
|
+
` 日志:${job.log}\n` +
|
|
1333
|
+
" 结束时会用 pi-mailbox 叫醒本会话(rc + 日志尾);现在可以结束这一轮。",
|
|
1334
|
+
},
|
|
1335
|
+
],
|
|
1336
|
+
details: { job },
|
|
1337
|
+
};
|
|
1338
|
+
},
|
|
1339
|
+
});
|
|
1340
|
+
|
|
912
1341
|
pi.registerCommand("auto", {
|
|
913
1342
|
description: "pi-auto 开关:/auto on|off|status(无人值守会话默认 on,手开会话默认 off)",
|
|
914
1343
|
handler: async (args, ctx) => {
|
|
@@ -946,6 +1375,20 @@ export default function (pi: ExtensionAPI) {
|
|
|
946
1375
|
}
|
|
947
1376
|
// error/aborted:不走 continue(aborted 会被宿主抑制),交给 agent_settled 用 mailbox 轻推
|
|
948
1377
|
if (event.outcome !== "completed") return;
|
|
1378
|
+
// 有排着的计时器/后台命令 ⇒ 不空转一轮:本轮收口,到点由 pi-mailbox 叫醒
|
|
1379
|
+
const pendingTimers = readTimers();
|
|
1380
|
+
const pendingJobs = readJobs();
|
|
1381
|
+
if (pendingTimers.length || pendingJobs.length) {
|
|
1382
|
+
const nextDue = pendingTimers.length ? Math.min(...pendingTimers.map((t) => t.dueAt)) : 0;
|
|
1383
|
+
audit({
|
|
1384
|
+
kind: "timer-wait",
|
|
1385
|
+
cwd: now.cwd,
|
|
1386
|
+
timers: pendingTimers.length,
|
|
1387
|
+
jobs: pendingJobs.length,
|
|
1388
|
+
next: nextDue ? formatLocal(new Date(nextDue)) : null,
|
|
1389
|
+
});
|
|
1390
|
+
return;
|
|
1391
|
+
}
|
|
949
1392
|
|
|
950
1393
|
const round = now.rounds + 1;
|
|
951
1394
|
const next = touch(ctx, { rounds: round, phase: "continue" });
|
|
@@ -987,6 +1430,12 @@ export default function (pi: ExtensionAPI) {
|
|
|
987
1430
|
pi.on("session_start", async (_event, ctx) => {
|
|
988
1431
|
const now = touch(ctx, { phase: "start" });
|
|
989
1432
|
audit({ kind: "session-start", cwd: now.cwd, boot: now.boot, keepAlive: now.keepAlive });
|
|
1433
|
+
// 恢复磁盘上的计时器(跨 /new、/resume 与崩溃重启);过期的立即叫一次
|
|
1434
|
+
for (const t of readTimers()) {
|
|
1435
|
+
if (t.dueAt <= Date.now()) fireTimer(t);
|
|
1436
|
+
else armTimer(t);
|
|
1437
|
+
}
|
|
1438
|
+
refreshBgPoller();
|
|
990
1439
|
});
|
|
991
1440
|
|
|
992
1441
|
pi.on("session_shutdown", async (event, ctx) => {
|
|
@@ -994,6 +1443,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
994
1443
|
clearTimeout(nudgeTimer);
|
|
995
1444
|
nudgeTimer = undefined;
|
|
996
1445
|
}
|
|
1446
|
+
for (const h of timerHandles.values()) clearTimeout(h);
|
|
1447
|
+
timerHandles.clear();
|
|
1448
|
+
if (bgPoller) {
|
|
1449
|
+
clearInterval(bgPoller);
|
|
1450
|
+
bgPoller = undefined;
|
|
1451
|
+
}
|
|
1452
|
+
// 本进程的计时器跟着会话走:进程没了就不会有唤醒,留着只会骗下一个人
|
|
1453
|
+
writeTimers([]);
|
|
997
1454
|
if (!state) return;
|
|
998
1455
|
audit({ kind: "session-end", cwd: state.cwd, rounds: state.rounds, keepAlive: state.keepAlive, reason: event.reason });
|
|
999
1456
|
if (!state.keepAlive) {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-auto-unattended",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Unattended Pi sessions: tool-side extensions (auto_switch keep-alive, auto_schedule timed runs, auto_today project-scoped daily brief) plus a pi-auto CLI and systemd daemon that keeps one agent alive per selected folder and nudges them through pi-mailbox.",
|
|
3
|
+
"version": "0.6.0",
|
|
4
|
+
"description": "Unattended Pi sessions: tool-side extensions (auto_switch keep-alive, auto_schedule timed runs, auto_today project-scoped daily brief, auto_timer/auto_bg wait-without-blocking) plus a pi-auto CLI and systemd daemon that keeps one agent alive per selected folder and nudges them through pi-mailbox.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
|
7
7
|
"pi-extension",
|
package/prompt.md
CHANGED
|
@@ -10,5 +10,7 @@ cwd 就是本项目根,只做本仓的活;需要人做的事(特权命令
|
|
|
10
10
|
- 一轮把整个工单做完(含子代理验收):改完自测、提交、推送;口径不确定先查记忆/技能,别猜。
|
|
11
11
|
- 要「明早/每天到点」自己开工:直接调 `auto_schedule`(`mode:"once"` 触发后 prompt 自动清理;
|
|
12
12
|
`mode:"recurring"` 的 prompt 长期保留),不要手写 plan.json、也不要自己装 systemd timer。
|
|
13
|
+
- 要等(批次/CI/长命令)不要轮内 `sleep`:按小时点等 ⇒ `auto_timer({after:"25m", note:"…"})`;
|
|
14
|
+
等一条命令跑完 ⇒ `auto_bg({command:"…"})`。两个都是调完就结束本轮,到点由 pi-mailbox 叫醒你。
|
|
13
15
|
- 还有自己能做的活就保持 `auto_switch` 开着;做完了/只剩人工/审批/环境门就 `auto_switch({action:"off"})` 收工。
|
|
14
16
|
服务当天不会因为 off 再拉起本目录,跨天自动恢复;要手动恢复用 `pi-auto on`。
|
package/test/pi-auto.test.mjs
CHANGED
|
@@ -7,12 +7,17 @@ import { join } from "node:path";
|
|
|
7
7
|
import test from "node:test";
|
|
8
8
|
|
|
9
9
|
import register, {
|
|
10
|
+
bgIndexPath,
|
|
10
11
|
checkTodayWrite,
|
|
11
12
|
continuationText,
|
|
12
13
|
describeSchedule,
|
|
13
14
|
inChildProcess,
|
|
14
15
|
isBootSession,
|
|
16
|
+
MAX_TIMER_MS,
|
|
17
|
+
parseAfter,
|
|
18
|
+
readJobs,
|
|
15
19
|
readPlan,
|
|
20
|
+
readTimers,
|
|
16
21
|
planFile,
|
|
17
22
|
parseWhen,
|
|
18
23
|
retire,
|
|
@@ -20,7 +25,9 @@ import register, {
|
|
|
20
25
|
retiredToday,
|
|
21
26
|
slugFor,
|
|
22
27
|
statePath,
|
|
28
|
+
timersPath,
|
|
23
29
|
todayHash,
|
|
30
|
+
writeTimers,
|
|
24
31
|
} from "../extensions/pi-auto.ts";
|
|
25
32
|
|
|
26
33
|
function createHost({ boot = true, cwd = "/tmp/proj-a", sessionId = "sess-1" } = {}) {
|
|
@@ -86,6 +93,7 @@ function createHost({ boot = true, cwd = "/tmp/proj-a", sessionId = "sess-1" } =
|
|
|
86
93
|
delete process.env.PI_AUTO_MAILBOX_DIR;
|
|
87
94
|
delete process.env.PI_AUTO_SESSION_ID;
|
|
88
95
|
delete process.env.PI_AUTO_NUDGE_DELAY_MS;
|
|
96
|
+
delete process.env.PI_AUTO_BG_POLL_MS;
|
|
89
97
|
delete process.env.PI_BOOT_SESSION_ID;
|
|
90
98
|
delete process.env.PI_RUN_DIR;
|
|
91
99
|
rmSync(dir, { recursive: true, force: true });
|
|
@@ -485,3 +493,145 @@ test("auto_today:默认作用域=本会话 cwd;跨项目/广播第一次拦
|
|
|
485
493
|
host.cleanup();
|
|
486
494
|
}
|
|
487
495
|
});
|
|
496
|
+
|
|
497
|
+
// ---------------------------------------------------------------- 计时器(auto_timer)
|
|
498
|
+
test("parseAfter:认 25m / 90s / 2h / 150分钟 / 1天,拒绝裸数字", () => {
|
|
499
|
+
const now = new Date("2026-12-05T10:00:00+08:00");
|
|
500
|
+
assert.equal(parseAfter("25m", now).toISOString(), new Date("2026-12-05T10:25:00+08:00").toISOString());
|
|
501
|
+
assert.equal(parseAfter("+90s", now).toISOString(), new Date("2026-12-05T10:01:30+08:00").toISOString());
|
|
502
|
+
assert.equal(parseAfter("2h", now).toISOString(), new Date("2026-12-05T12:00:00+08:00").toISOString());
|
|
503
|
+
assert.equal(parseAfter("150分钟", now).toISOString(), new Date("2026-12-05T12:30:00+08:00").toISOString());
|
|
504
|
+
assert.equal(parseAfter("1天", now).toISOString(), new Date("2026-12-06T10:00:00+08:00").toISOString());
|
|
505
|
+
for (const bad of ["25", "", "明天 07:40", "abc"]) assert.throws(() => parseAfter(bad, now));
|
|
506
|
+
});
|
|
507
|
+
|
|
508
|
+
test("auto_timer:set 落盘、list 看得到、cancel 清掉,超过 7 天退回 auto_schedule", async () => {
|
|
509
|
+
const host = createHost();
|
|
510
|
+
try {
|
|
511
|
+
await host.boot();
|
|
512
|
+
const set = await host.callTool("auto_timer", { action: "set", after: "25m", note: "看批" });
|
|
513
|
+
assert.equal(set.isError, undefined);
|
|
514
|
+
assert.equal(readTimers().length, 1);
|
|
515
|
+
assert.match(set.content[0].text, /计时器已排/);
|
|
516
|
+
assert.match(host.audit(), /timer-set/);
|
|
517
|
+
|
|
518
|
+
const list = await host.callTool("auto_timer", { action: "list" });
|
|
519
|
+
assert.match(list.content[0].text, /本会话计时器(1 个)/);
|
|
520
|
+
assert.match(list.content[0].text, /看批/);
|
|
521
|
+
|
|
522
|
+
const far = await host.callTool("auto_timer", { action: "set", after: "8天" });
|
|
523
|
+
assert.equal(far.isError, true);
|
|
524
|
+
assert.match(far.content[0].text, /auto_schedule/);
|
|
525
|
+
assert.ok(MAX_TIMER_MS === 7 * 86_400_000);
|
|
526
|
+
|
|
527
|
+
const id = readTimers()[0].id;
|
|
528
|
+
const cancel = await host.callTool("auto_timer", { action: "cancel", id });
|
|
529
|
+
assert.equal(cancel.isError, undefined);
|
|
530
|
+
assert.equal(readTimers().length, 0);
|
|
531
|
+
assert.equal(existsSync(timersPath()), false);
|
|
532
|
+
} finally {
|
|
533
|
+
host.cleanup();
|
|
534
|
+
}
|
|
535
|
+
});
|
|
536
|
+
|
|
537
|
+
test("计时器排着时 settle 不空转续轮(timer-wait),到点后走 mailbox 叫醒", async () => {
|
|
538
|
+
const host = createHost();
|
|
539
|
+
try {
|
|
540
|
+
await host.boot();
|
|
541
|
+
await host.callTool("auto_timer", { action: "set", after: "1s", note: "到点看读数" });
|
|
542
|
+
const settled = await host.settle("completed");
|
|
543
|
+
assert.equal(settled, undefined, "有计时器等 ⇒ 不该 continue");
|
|
544
|
+
assert.match(host.audit(), /timer-wait/);
|
|
545
|
+
assert.equal(host.inbox().length, 0);
|
|
546
|
+
|
|
547
|
+
await sleep(1400);
|
|
548
|
+
const inbox = host.inbox();
|
|
549
|
+
assert.equal(inbox.length, 1);
|
|
550
|
+
assert.match(inbox[0].text, /pi-auto 计时器/);
|
|
551
|
+
assert.match(inbox[0].text, /到点看读数/);
|
|
552
|
+
assert.equal(readTimers().length, 0, "触发后从磁盘清掉");
|
|
553
|
+
assert.match(host.audit(), /timer-fired/);
|
|
554
|
+
|
|
555
|
+
// 没有计时器后恢复正常续轮
|
|
556
|
+
const next = await host.settle("completed");
|
|
557
|
+
assert.ok(next && next.continue === true);
|
|
558
|
+
} finally {
|
|
559
|
+
host.cleanup();
|
|
560
|
+
}
|
|
561
|
+
});
|
|
562
|
+
|
|
563
|
+
test("重启/重启会话后:过期的计时器立刻叫一次,没到点的继续排着", async () => {
|
|
564
|
+
const host = createHost();
|
|
565
|
+
try {
|
|
566
|
+
writeTimers([
|
|
567
|
+
{ id: "tm-past", dueAt: Date.now() - 60_000, note: "早就该醒了", createdAt: new Date().toISOString() },
|
|
568
|
+
{ id: "tm-future", dueAt: Date.now() + 3_600_000, note: "还早", createdAt: new Date().toISOString() },
|
|
569
|
+
]);
|
|
570
|
+
await host.boot();
|
|
571
|
+
const inbox = host.inbox();
|
|
572
|
+
assert.equal(inbox.length, 1);
|
|
573
|
+
assert.match(inbox[0].text, /早就该醒了/);
|
|
574
|
+
assert.deepEqual(readTimers().map((t) => t.id), ["tm-future"]);
|
|
575
|
+
await host.shutdown("quit");
|
|
576
|
+
assert.equal(readTimers().length, 0, "退出时清掉本进程的计时器");
|
|
577
|
+
} finally {
|
|
578
|
+
host.cleanup();
|
|
579
|
+
}
|
|
580
|
+
});
|
|
581
|
+
|
|
582
|
+
// ---------------------------------------------------------------- 后台命令(auto_bg)
|
|
583
|
+
test("auto_bg:run 脱离会话起进程,命令结束时 mailbox 带回 rc 与日志尾", async () => {
|
|
584
|
+
const host = createHost();
|
|
585
|
+
try {
|
|
586
|
+
process.env.PI_AUTO_BG_POLL_MS = "20";
|
|
587
|
+
host.ctx.cwd = host.dir; // 后台命令真的要 chdir,得用存在的目录
|
|
588
|
+
await host.boot();
|
|
589
|
+
const run = await host.callTool("auto_bg", { action: "run", command: "echo hello-bg; exit 3" });
|
|
590
|
+
assert.equal(run.isError, undefined);
|
|
591
|
+
assert.equal(readJobs().length, 1);
|
|
592
|
+
const job = readJobs()[0];
|
|
593
|
+
assert.ok(existsSync(job.log));
|
|
594
|
+
assert.match(host.audit(), /bg-start/);
|
|
595
|
+
|
|
596
|
+
for (let i = 0; i < 100 && host.inbox().length === 0; i++) await sleep(50);
|
|
597
|
+
const inbox = host.inbox();
|
|
598
|
+
assert.equal(inbox.length, 1, "命令结束应叫醒会话");
|
|
599
|
+
assert.match(inbox[0].text, /后台命令结束/);
|
|
600
|
+
assert.match(inbox[0].text, /rc=3/);
|
|
601
|
+
assert.match(inbox[0].text, /hello-bg/);
|
|
602
|
+
assert.equal(readJobs().length, 0, "完成后从索引里摘掉");
|
|
603
|
+
await sleep(100);
|
|
604
|
+
assert.equal(host.inbox().length, 1, "不许重复叫醒");
|
|
605
|
+
} finally {
|
|
606
|
+
host.cleanup();
|
|
607
|
+
}
|
|
608
|
+
});
|
|
609
|
+
|
|
610
|
+
test("auto_bg:list / tail / cancel(kill 整个进程组)", async () => {
|
|
611
|
+
const host = createHost();
|
|
612
|
+
try {
|
|
613
|
+
process.env.PI_AUTO_BG_POLL_MS = "1000";
|
|
614
|
+
host.ctx.cwd = host.dir;
|
|
615
|
+
await host.boot();
|
|
616
|
+
await host.callTool("auto_bg", { action: "run", command: "sleep 30; echo never" });
|
|
617
|
+
const job = readJobs()[0];
|
|
618
|
+
const list = await host.callTool("auto_bg", { action: "list" });
|
|
619
|
+
assert.match(list.content[0].text, /running/);
|
|
620
|
+
assert.equal(existsSync(bgIndexPath()), true);
|
|
621
|
+
const cancel = await host.callTool("auto_bg", { action: "cancel", id: job.id });
|
|
622
|
+
assert.equal(cancel.isError, undefined);
|
|
623
|
+
assert.equal(readJobs().length, 0);
|
|
624
|
+
await sleep(100);
|
|
625
|
+
let gone = false;
|
|
626
|
+
try {
|
|
627
|
+
process.kill(job.pid, 0);
|
|
628
|
+
} catch {
|
|
629
|
+
gone = true;
|
|
630
|
+
}
|
|
631
|
+
assert.equal(gone, true, "cancel 应真的杀掉进程");
|
|
632
|
+
const tail = await host.callTool("auto_bg", { action: "tail", id: job.id });
|
|
633
|
+
assert.equal(tail.isError, true, "取消后索引里没有它");
|
|
634
|
+
} finally {
|
|
635
|
+
host.cleanup();
|
|
636
|
+
}
|
|
637
|
+
});
|