pi-auto-unattended 0.6.0 → 0.7.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 +21 -0
- package/README.md +20 -2
- package/extensions/pi-auto.ts +243 -3
- package/package.json +2 -2
- package/test/pi-auto.test.mjs +184 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,26 @@
|
|
|
1
1
|
# CHANGELOG
|
|
2
2
|
|
|
3
|
+
## 0.7.0 (2026-12-05)
|
|
4
|
+
|
|
5
|
+
- 新增**交接线**(用户口径:全天候 agent = 一个 agent 做完本轮把活交给下一轮):`agent_before_settle`
|
|
6
|
+
时用 `ctx.getContextUsage()` 读真实百分比(与 footer/`context_usage` 同一个数),到线(默认 **35%**,
|
|
7
|
+
`PI_AUTO_HANDOFF_AT` 可改)且本轮 idle:
|
|
8
|
+
- **无人值守会话(keepAlive)**:把「续轮草稿」换成「交接草稿」——本会话只写 brief 并
|
|
9
|
+
`session_handoff`,交接后新会话接着干(上下文回到 ~0)。提醒过一次还没交接 ⇒ 升级口径(本会话只做交接);
|
|
10
|
+
百分比回落到「阈值 −5」以下自动重新武装(压缩后不再骚扰),audit `handoff-remind` / `handoff-rearm`。
|
|
11
|
+
- **手开会话**:只 `ui.notify` 提一句(不注入消息、不触发新一轮),同一条线只提一次,audit `handoff-notify`。
|
|
12
|
+
- **`PI_AUTO_HANDOFF=auto`(opt-in)**:插件按仓内可核实事实自己拼 mechanical brief(AGENTS/TODO/PLAN 指针 +
|
|
13
|
+
`git log --oneline -5` + `git status --short` 前 20 行 + 推进口径),settle 后直接派 `/handoff-new`,
|
|
14
|
+
不需要模型再跑一轮;`handoff-auto` / `handoff-auto-pending`。检测到 settings 里没有 pi-agent-handoff ⇒
|
|
15
|
+
自动退回提醒口径(不派不存在的命令)。
|
|
16
|
+
- 计时器跟着**进程**走:`/new`、交接(`session_shutdown.reason=new`)不再丢计时器,只有真退出才清;
|
|
17
|
+
启动时清掉持有者 pid 已死的孤儿计时器文件(audit `timer-prune`)。
|
|
18
|
+
- 回归:`node --test` 23 → 31 条全 pass(判据纯函数、两档文案、到线换草稿/升级/重新武装、
|
|
19
|
+
手开会话只 notify、auto 模式派 `/handoff-new` 且 brief 含仓内事实、未装 handoff 退回 remind、
|
|
20
|
+
交接不丢计时器 + 孤儿清理)。
|
|
21
|
+
- 实测(remind 口径,真会话):`/tmp` e2e 会话在闸门触发后交出 brief → 新会话接 kickoff → 立刻 `auto_switch off`,
|
|
22
|
+
audit 依次 `session-start → continue → session-end(reason=new) → session-start`,无死循环。
|
|
23
|
+
|
|
3
24
|
## 0.6.0 (2026-12-05)
|
|
4
25
|
|
|
5
26
|
- 新增工具 **`auto_timer`**:会话内自主预约「到点唤醒」。`auto_timer({after:"25m", note:"…"})` 调完
|
package/README.md
CHANGED
|
@@ -147,6 +147,24 @@ auto_schedule({ action: "cancel", id: "sch-…" }) // 取消(id:"all"
|
|
|
147
147
|
- 只写 plan.json,**不影响当前会话**(`auto_switch` 管续轮,预约管排班;两者正交)。
|
|
148
148
|
- 落地时不需要装 systemd timer:daemon 每 60s 扫一次 `schedules`。
|
|
149
149
|
|
|
150
|
+
## 交接线:上下文 30–40% 且本轮 idle ⇒ 交给下一轮
|
|
151
|
+
|
|
152
|
+
「全天候 agent」的前提是**一个 agent 做完本轮把活交给下一轮**,而不是一路干到 80% 再崩。判据在
|
|
153
|
+
`agent_before_settle`(本轮真的 idle):
|
|
154
|
+
|
|
155
|
+
| 场景 | 行为 |
|
|
156
|
+
|---|---|
|
|
157
|
+
| 无人值守会话(keepAlive) | 把「续轮草稿」换成「**交接草稿**」:写自包含 brief + `session_handoff`,新会话接着干(上下文回 ~0);提醒过一次还没交接 ⇒ 升级口径(本会话只做交接) |
|
|
158
|
+
| 手开会话 | 只 `ui.notify` 提一句(不注入消息、不触发新一轮),同一条线只提一次 |
|
|
159
|
+
| `PI_AUTO_HANDOFF=auto` | 插件按仓内事实拼 mechanical brief,settle 后**直接派 `/handoff-new`**,不需要模型再跑一轮 |
|
|
160
|
+
|
|
161
|
+
- 阈值:默认 **35%**(`PI_AUTO_HANDOFF_AT=35`),读数用 `ctx.getContextUsage()`(与 footer/`context_usage` 同源);
|
|
162
|
+
读数未知(刚压缩完)就什么都不做。回落到「阈值 −5」以下自动重新武装(audit `handoff-rearm`)。
|
|
163
|
+
- `PI_AUTO_HANDOFF=off` 关掉;`remind`(默认)由模型写 brief,`auto` 由插件写 brief(要求 settings 里已装
|
|
164
|
+
`pi-agent-handoff`,否则自动退回 `remind`)。
|
|
165
|
+
- audit 关键字:`handoff-notify` / `handoff-remind` / `handoff-rearm` / `handoff-auto-pending` / `handoff-auto`。
|
|
166
|
+
- 边界:交接由 `pi-agent-handoff` 完成会话替换(TUI-only);opencode 形态的 `--mode json` 会话不会被交接。
|
|
167
|
+
|
|
150
168
|
## 给 agent 的入口(三):`auto_timer` / `auto_bg`(等东西,但不空转)
|
|
151
169
|
|
|
152
170
|
2026-12-05 之前的口径是「等 CI/跑批就在轮内 `bash sleep 1500`」。limbus 那轮的真机批实证了代价:
|
|
@@ -249,7 +267,7 @@ systemd --user pi-auto.service
|
|
|
249
267
|
扩展写 `retired/<slug>.json`,当天不再拉起,跨天自动恢复。
|
|
250
268
|
- 不设夜间时段门禁、不观察桌面登录:服务只服从 `plan.json` 和「用户优先」这一条。
|
|
251
269
|
|
|
252
|
-
## 会话内:`auto_switch` / `auto_schedule` / `auto_timer` / `auto_bg`
|
|
270
|
+
## 会话内:`auto_switch` / `auto_schedule` / `auto_timer` / `auto_bg` / 交接线
|
|
253
271
|
|
|
254
272
|
- 无人值守会话(`PI_AUTO_SESSION_ID` / 兼容 `PI_BOOT_SESSION_ID` / `PI_RUN_DIR`)默认 **on**;
|
|
255
273
|
用户手开会话默认 **off**(不许静默自己续轮)。
|
|
@@ -312,7 +330,7 @@ pi-auto service install # 或手抄 systemd/pi-aut
|
|
|
312
330
|
cd ~/pi-plugins/pi-auto
|
|
313
331
|
npm run validate # = node 单测 + lib.sh/schedule shell 门禁 + import check + pack --dry-run
|
|
314
332
|
# 分开跑:
|
|
315
|
-
node --test 'test/*.test.mjs' # 开关/续轮/retired/mailbox 轻推/auto_schedule 与 when 解析/auto_timer/auto_bg
|
|
333
|
+
node --test 'test/*.test.mjs' # 开关/续轮/retired/mailbox 轻推/auto_schedule 与 when 解析/auto_timer/auto_bg/交接线
|
|
316
334
|
bash test/lib.test.sh # plan/retired/slug/prompt/预约判据
|
|
317
335
|
bash test/schedule.test.sh # 预约端到端(dry-launch:once 消费即清理 / recurring 保留 prompt)
|
|
318
336
|
```
|
package/extensions/pi-auto.ts
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
* audit.log 一行一条 JSON
|
|
17
17
|
*/
|
|
18
18
|
import crypto from "node:crypto";
|
|
19
|
-
import { spawn } from "node:child_process";
|
|
19
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
20
20
|
import fs from "node:fs";
|
|
21
21
|
import os from "node:os";
|
|
22
22
|
import path from "node:path";
|
|
@@ -36,6 +36,12 @@ export type AutoState = {
|
|
|
36
36
|
lastNudgeAt: string | null;
|
|
37
37
|
startedAt: string;
|
|
38
38
|
updatedAt: string;
|
|
39
|
+
/** 交接线状态:0 未到线 / 1 已提醒 / 2 提醒过仍未交接(升级口径)。 */
|
|
40
|
+
handoffStage?: number;
|
|
41
|
+
handoffPercent?: number | null;
|
|
42
|
+
handoffReminders?: number;
|
|
43
|
+
/** 观测到的最高上下文百分比(审计用,便于事后核「为什么这时交接」)。 */
|
|
44
|
+
contextPercentMax?: number | null;
|
|
39
45
|
};
|
|
40
46
|
|
|
41
47
|
const STATUS_KEY = "pi-auto";
|
|
@@ -553,6 +559,39 @@ export function readTimers(pid: number = process.pid): TimerEntry[] {
|
|
|
553
559
|
}
|
|
554
560
|
}
|
|
555
561
|
|
|
562
|
+
/** 清掉「持有者 pid 已经不在了」的计时器文件(崩溃/重启留下的孤儿,不参与唤醒)。 */
|
|
563
|
+
export function pruneDeadTimerFiles(isAlive: (pid: number) => boolean = (pid) => {
|
|
564
|
+
try {
|
|
565
|
+
process.kill(pid, 0);
|
|
566
|
+
return true;
|
|
567
|
+
} catch (error) {
|
|
568
|
+
// EPERM = 进程在但不属于我们;只把 ESRCH 当死亡
|
|
569
|
+
return (error as NodeJS.ErrnoException)?.code === "EPERM";
|
|
570
|
+
}
|
|
571
|
+
}): number {
|
|
572
|
+
let removed = 0;
|
|
573
|
+
let files: string[] = [];
|
|
574
|
+
try {
|
|
575
|
+
files = fs.readdirSync(timersRoot());
|
|
576
|
+
} catch {
|
|
577
|
+
return 0;
|
|
578
|
+
}
|
|
579
|
+
for (const file of files) {
|
|
580
|
+
const m = /^(\d+)\.json$/.exec(file);
|
|
581
|
+
if (!m) continue;
|
|
582
|
+
const pid = Number(m[1]);
|
|
583
|
+
if (pid === process.pid) continue;
|
|
584
|
+
if (isAlive(pid)) continue;
|
|
585
|
+
try {
|
|
586
|
+
fs.rmSync(path.join(timersRoot(), file), { force: true });
|
|
587
|
+
removed += 1;
|
|
588
|
+
} catch {
|
|
589
|
+
/* ignore */
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
return removed;
|
|
593
|
+
}
|
|
594
|
+
|
|
556
595
|
export function writeTimers(list: TimerEntry[], pid: number = process.pid): void {
|
|
557
596
|
try {
|
|
558
597
|
fs.mkdirSync(timersRoot(), { recursive: true });
|
|
@@ -644,6 +683,108 @@ export function writeJobs(list: BgJob[], pid: number = process.pid): void {
|
|
|
644
683
|
}
|
|
645
684
|
}
|
|
646
685
|
|
|
686
|
+
// ---------------------------------------------------------------- 交接线(上下文 30–40% 且本轮 idle)
|
|
687
|
+
//
|
|
688
|
+
// 2026-12-05 用户口径:「全天候 agent 自动化 = 一个 agent 做完本轮把活交给下一轮」。
|
|
689
|
+
// 所以交接不能只靠模型自己记得(规则 23 写在文档里,实测会话照样一路干到 80%+)。判据放在
|
|
690
|
+
// `agent_before_settle`(本轮真的 idle 了):
|
|
691
|
+
// - 无人值守会话(keepAlive):把「续轮草稿」换成「交接草稿」——本会话只写 brief 并
|
|
692
|
+
// `session_handoff`,交接后新会话接着干(上下文回到 ~0);
|
|
693
|
+
// - 手开会话:只 `ui.notify` 提一句,不注入消息、不触发新一轮;
|
|
694
|
+
// - `PI_AUTO_HANDOFF=auto`:插件按仓内事实自己拼 mechanical brief 并派 `/handoff-new`
|
|
695
|
+
// (默认 `remind`,auto 需要 pi-agent-handoff 已装)。
|
|
696
|
+
// 读数一律用 `ctx.getContextUsage()`(与 footer/context_usage 同一个数),unknown 就什么都不做。
|
|
697
|
+
export const HANDOFF_DEFAULT_AT = 35;
|
|
698
|
+
export type HandoffMode = "off" | "remind" | "auto";
|
|
699
|
+
|
|
700
|
+
export function handoffThreshold(env: NodeJS.ProcessEnv = process.env): number {
|
|
701
|
+
const raw = Number(env.PI_AUTO_HANDOFF_AT ?? "");
|
|
702
|
+
return Number.isFinite(raw) && raw > 0 && raw < 100 ? raw : HANDOFF_DEFAULT_AT;
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
export function handoffMode(env: NodeJS.ProcessEnv = process.env): HandoffMode {
|
|
706
|
+
const raw = String(env.PI_AUTO_HANDOFF ?? "").trim().toLowerCase();
|
|
707
|
+
return raw === "off" || raw === "auto" || raw === "remind" ? (raw as HandoffMode) : "remind";
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
/** 百分比掉回「阈值 − 5」以下才重新武装(压缩后不该一直催交接)。 */
|
|
711
|
+
export const HANDOFF_REARM_DROP = 5;
|
|
712
|
+
|
|
713
|
+
/** 本轮要不要发交接提醒:0 = 不用,1 = 首次提醒,2 = 提醒过仍未交接(升级)。 */
|
|
714
|
+
export function handoffStage(percent: number | null, threshold: number, reminded: number): 0 | 1 | 2 {
|
|
715
|
+
if (percent === null || !Number.isFinite(percent)) return 0;
|
|
716
|
+
if (percent < threshold) return 0;
|
|
717
|
+
return reminded >= 1 ? 2 : 1;
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
export function handoffContinuationText(round: number, percent: number, threshold: number, stage: number): string {
|
|
721
|
+
const pct = `${percent.toFixed(1)}%`;
|
|
722
|
+
if (stage >= 2) {
|
|
723
|
+
return (
|
|
724
|
+
`【pi-auto 交接线·升级】上下文 ${pct}(阈值 ${threshold}%),上一轮已经提醒过交接但还没交接。` +
|
|
725
|
+
"本会话**不要再开新活**:把手上状态写成自包含 brief(背景与已定决策、绝对路径、待办、验收判据)" +
|
|
726
|
+
"并立刻 `session_handoff({brief, goal})`。交接失败(brief 写不出来)比上下文耗尽便宜得多;" +
|
|
727
|
+
"确实已经全部收口、只剩人工门,才 `auto_switch({action:\"off\", note:\"…\"})` 收工。"
|
|
728
|
+
);
|
|
729
|
+
}
|
|
730
|
+
return (
|
|
731
|
+
`【pi-auto 续轮 #${round} · 交接线】上下文 ${pct}(阈值 ${threshold}%)。` +
|
|
732
|
+
"先把这单交给新会话再继续:调 `session_handoff({brief, goal})`,brief 必须自包含" +
|
|
733
|
+
"(背景与已定决策、绝对路径、待办、验收判据),因为新会话看不到这段对话;交接后新会话接着推进。" +
|
|
734
|
+
"不要把剩下的活继续压在本会话里。"
|
|
735
|
+
);
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
/** 机械 brief(`PI_AUTO_HANDOFF=auto` 用):只写仓内**可核实的事实**,不编状态。 */
|
|
739
|
+
export function mechanicalBrief(
|
|
740
|
+
cwd: string,
|
|
741
|
+
sessionId: string,
|
|
742
|
+
percent: number,
|
|
743
|
+
threshold: number,
|
|
744
|
+
exec: (file: string, args: string[]) => string = (file, args) =>
|
|
745
|
+
execFileSync(file, args, { cwd, timeout: 5_000, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }),
|
|
746
|
+
): string {
|
|
747
|
+
const git = (args: string[]): string => {
|
|
748
|
+
try {
|
|
749
|
+
return exec("git", args).trim();
|
|
750
|
+
} catch {
|
|
751
|
+
return "";
|
|
752
|
+
}
|
|
753
|
+
};
|
|
754
|
+
const commits = git(["log", "--oneline", "-5"]) || "(不是 git 仓或没有提交)";
|
|
755
|
+
const dirty = git(["status", "--short"]);
|
|
756
|
+
const dirtyLine = dirty ? dirty.split("\n").slice(0, 20).join("\n") : "(工作树干净)";
|
|
757
|
+
const candidates = ["AGENTS.md", "TODO.md", "PLAN.md", "BACKLOG.md", "ROADMAP.md", ".pi/plans"];
|
|
758
|
+
const found = candidates.filter((f) => {
|
|
759
|
+
try {
|
|
760
|
+
fs.statSync(path.join(cwd, f));
|
|
761
|
+
return true;
|
|
762
|
+
} catch {
|
|
763
|
+
return false;
|
|
764
|
+
}
|
|
765
|
+
});
|
|
766
|
+
const pointers = found.length ? found.map((f) => path.join(cwd, f)).join("\n - ") : "(仓内没找到 AGENTS/TODO/PLAN,向上游/记忆里找)";
|
|
767
|
+
return [
|
|
768
|
+
`# 自动交接(pi-auto:上下文 ${percent.toFixed(1)}% ≥ ${threshold}%)`,
|
|
769
|
+
"",
|
|
770
|
+
`上一个会话已经 idle,上下文到线 ⇒ 由 pi-auto 自动交接。来源会话 ${sessionId},cwd ${cwd}。`,
|
|
771
|
+
"",
|
|
772
|
+
"## 先读这些(单一出处,别凭这段 brief 猜)",
|
|
773
|
+
` - ${pointers}`,
|
|
774
|
+
"",
|
|
775
|
+
"## 最近提交(git log --oneline -5)",
|
|
776
|
+
commits,
|
|
777
|
+
"",
|
|
778
|
+
"## 工作树(未提交改动,前 20 行)",
|
|
779
|
+
dirtyLine,
|
|
780
|
+
"",
|
|
781
|
+
"## 接下来怎么干",
|
|
782
|
+
"- 这是无人值守会话:不问问题、不等确认;按仓内 AGENTS/规则 18 分层推进,自己只做编排 + 复核。",
|
|
783
|
+
"- 先核现状(git status / 日志 / 子代理 / 待办文件),再决定这条线的下一步;口径不确定先查记忆/技能。",
|
|
784
|
+
"- 要等(批次/CI/长命令)用 `auto_timer` / `auto_bg`,不要轮内 `sleep`;做完或只剩人工门就 `auto_switch({action:\"off\", note:\"…\"})`。",
|
|
785
|
+
].join("\n");
|
|
786
|
+
}
|
|
787
|
+
|
|
647
788
|
function shellQuote(value: string): string {
|
|
648
789
|
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
649
790
|
}
|
|
@@ -661,6 +802,29 @@ export default function (pi: ExtensionAPI) {
|
|
|
661
802
|
// 计时器/后台命令的运行期句柄(磁盘状态是权威,这里只是“到点提醒”的定时器)
|
|
662
803
|
const timerHandles = new Map<string, ReturnType<typeof setTimeout>>();
|
|
663
804
|
let bgPoller: ReturnType<typeof setInterval> | undefined;
|
|
805
|
+
// `PI_AUTO_HANDOFF=auto`:本轮 settle 时拼好的机械 brief,等 agent_settled 再派 /handoff-new
|
|
806
|
+
let pendingAutoBrief: string | undefined;
|
|
807
|
+
|
|
808
|
+
/** 与 footer / context_usage 同一个数;拿不到就是 null(不猜)。 */
|
|
809
|
+
const contextPercent = (ctx: ExtensionContext): number | null => {
|
|
810
|
+
try {
|
|
811
|
+
const usage = ctx.getContextUsage?.();
|
|
812
|
+
const pct = usage?.percent;
|
|
813
|
+
return typeof pct === "number" && Number.isFinite(pct) ? pct : null;
|
|
814
|
+
} catch {
|
|
815
|
+
return null;
|
|
816
|
+
}
|
|
817
|
+
};
|
|
818
|
+
|
|
819
|
+
/** auto 模式要求 pi-agent-handoff 已装:settings 里没有就当 remind,别派一个不存在的命令。 */
|
|
820
|
+
const handoffExtensionInstalled = (): boolean => {
|
|
821
|
+
try {
|
|
822
|
+
const raw = fs.readFileSync(path.join(agentDir(), "settings.json"), "utf8");
|
|
823
|
+
return /pi-agent-handoff/.test(raw);
|
|
824
|
+
} catch {
|
|
825
|
+
return false;
|
|
826
|
+
}
|
|
827
|
+
};
|
|
664
828
|
|
|
665
829
|
const fireTimer = (entry: TimerEntry): void => {
|
|
666
830
|
timerHandles.delete(entry.id);
|
|
@@ -1365,7 +1529,26 @@ export default function (pi: ExtensionAPI) {
|
|
|
1365
1529
|
}
|
|
1366
1530
|
lastOutcome = event.outcome;
|
|
1367
1531
|
const now = touch(ctx, { phase: "settle", outcome: event.outcome });
|
|
1532
|
+
const pct = contextPercent(ctx);
|
|
1533
|
+
const hMode = handoffMode();
|
|
1534
|
+
const hAt = handoffThreshold();
|
|
1535
|
+
if (pct !== null) {
|
|
1536
|
+
touch(ctx, { handoffPercent: pct, contextPercentMax: Math.max(pct, now.contextPercentMax ?? 0) });
|
|
1537
|
+
}
|
|
1368
1538
|
if (!now.keepAlive) {
|
|
1539
|
+
// 手开会话:到线只提一句(不注入消息、不触发新一轮),同一条线只提醒一次
|
|
1540
|
+
if (hMode !== "off" && pct !== null && pct >= hAt && (now.handoffStage ?? 0) === 0) {
|
|
1541
|
+
touch(ctx, { handoffStage: 1, handoffReminders: 1 });
|
|
1542
|
+
try {
|
|
1543
|
+
ctx.ui?.notify?.(
|
|
1544
|
+
`上下文 ${pct.toFixed(1)}% ≥ ${hAt}%:按规则 23 该准备/执行交接(session_handoff),或把这一轮收口到可交接状态`,
|
|
1545
|
+
"info",
|
|
1546
|
+
);
|
|
1547
|
+
} catch {
|
|
1548
|
+
/* print/json 模式没有 UI */
|
|
1549
|
+
}
|
|
1550
|
+
audit({ kind: "handoff-notify", percent: pct, threshold: hAt, cwd: now.cwd });
|
|
1551
|
+
}
|
|
1369
1552
|
audit({ kind: "skip", reason: "off", cwd: now.cwd, rounds: now.rounds });
|
|
1370
1553
|
return;
|
|
1371
1554
|
}
|
|
@@ -1375,6 +1558,50 @@ export default function (pi: ExtensionAPI) {
|
|
|
1375
1558
|
}
|
|
1376
1559
|
// error/aborted:不走 continue(aborted 会被宿主抑制),交给 agent_settled 用 mailbox 轻推
|
|
1377
1560
|
if (event.outcome !== "completed") return;
|
|
1561
|
+
// 交接线:上下文到线就把这一轮变成「交接轮」(计时器/后台命令先让位 —— 交接优先级最高)
|
|
1562
|
+
if (hMode !== "off" && pct !== null) {
|
|
1563
|
+
if (pct < hAt - HANDOFF_REARM_DROP && (now.handoffStage ?? 0) > 0) {
|
|
1564
|
+
touch(ctx, { handoffStage: 0, handoffReminders: 0 });
|
|
1565
|
+
audit({ kind: "handoff-rearm", percent: pct, threshold: hAt, cwd: now.cwd });
|
|
1566
|
+
}
|
|
1567
|
+
const stage = handoffStage(pct, hAt, now.handoffReminders ?? 0);
|
|
1568
|
+
if (stage > 0) {
|
|
1569
|
+
const round = now.rounds + 1;
|
|
1570
|
+
const auto = hMode === "auto" && handoffExtensionInstalled();
|
|
1571
|
+
const next = touch(ctx, {
|
|
1572
|
+
rounds: round,
|
|
1573
|
+
phase: "continue",
|
|
1574
|
+
handoffStage: stage,
|
|
1575
|
+
handoffReminders: (now.handoffReminders ?? 0) + 1,
|
|
1576
|
+
handoffPercent: pct,
|
|
1577
|
+
});
|
|
1578
|
+
nudgeAttempts = 0;
|
|
1579
|
+
audit({ kind: "handoff-remind", percent: pct, threshold: hAt, stage, mode: hMode, auto, round, cwd: next.cwd });
|
|
1580
|
+
if (auto) {
|
|
1581
|
+
// 直接自动化交接:brief 由插件按仓内事实拼,settle 后派 /handoff-new,不需要模型再跑一轮
|
|
1582
|
+
pendingAutoBrief = mechanicalBrief(
|
|
1583
|
+
ctx.cwd,
|
|
1584
|
+
ctx.sessionManager?.getSessionId?.() ?? "unknown",
|
|
1585
|
+
pct,
|
|
1586
|
+
hAt,
|
|
1587
|
+
);
|
|
1588
|
+
audit({ kind: "handoff-auto-pending", percent: pct, threshold: hAt, stage, briefBytes: Buffer.byteLength(pendingAutoBrief, "utf8") });
|
|
1589
|
+
return;
|
|
1590
|
+
}
|
|
1591
|
+
return {
|
|
1592
|
+
entries: [
|
|
1593
|
+
...(event.entries ?? []),
|
|
1594
|
+
{
|
|
1595
|
+
type: "custom_message" as const,
|
|
1596
|
+
customType: "pi-auto-handoff",
|
|
1597
|
+
display: true,
|
|
1598
|
+
content: handoffContinuationText(round, pct, hAt, stage),
|
|
1599
|
+
},
|
|
1600
|
+
],
|
|
1601
|
+
continue: true,
|
|
1602
|
+
};
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1378
1605
|
// 有排着的计时器/后台命令 ⇒ 不空转一轮:本轮收口,到点由 pi-mailbox 叫醒
|
|
1379
1606
|
const pendingTimers = readTimers();
|
|
1380
1607
|
const pendingJobs = readJobs();
|
|
@@ -1412,6 +1639,17 @@ export default function (pi: ExtensionAPI) {
|
|
|
1412
1639
|
});
|
|
1413
1640
|
|
|
1414
1641
|
pi.on("agent_settled", async (event, ctx) => {
|
|
1642
|
+
if (pendingAutoBrief) {
|
|
1643
|
+
const brief = pendingAutoBrief;
|
|
1644
|
+
pendingAutoBrief = undefined;
|
|
1645
|
+
try {
|
|
1646
|
+
pi.sendUserMessage(`/handoff-new ${brief}`, { expandPromptTemplates: true });
|
|
1647
|
+
audit({ kind: "handoff-auto", cwd: ctx.cwd, percent: contextPercent(ctx), briefBytes: Buffer.byteLength(brief, "utf8") });
|
|
1648
|
+
} catch (error) {
|
|
1649
|
+
audit({ kind: "handoff-auto-failed", cwd: ctx.cwd, error: String(error) });
|
|
1650
|
+
}
|
|
1651
|
+
return;
|
|
1652
|
+
}
|
|
1415
1653
|
const now = touch(ctx, { phase: "settled" });
|
|
1416
1654
|
if (!now.keepAlive) return;
|
|
1417
1655
|
if (retiredToday(now.cwd)) {
|
|
@@ -1431,6 +1669,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
1431
1669
|
const now = touch(ctx, { phase: "start" });
|
|
1432
1670
|
audit({ kind: "session-start", cwd: now.cwd, boot: now.boot, keepAlive: now.keepAlive });
|
|
1433
1671
|
// 恢复磁盘上的计时器(跨 /new、/resume 与崩溃重启);过期的立即叫一次
|
|
1672
|
+
const pruned = pruneDeadTimerFiles();
|
|
1673
|
+
if (pruned) audit({ kind: "timer-prune", removed: pruned, cwd: now.cwd });
|
|
1434
1674
|
for (const t of readTimers()) {
|
|
1435
1675
|
if (t.dueAt <= Date.now()) fireTimer(t);
|
|
1436
1676
|
else armTimer(t);
|
|
@@ -1449,8 +1689,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
1449
1689
|
clearInterval(bgPoller);
|
|
1450
1690
|
bgPoller = undefined;
|
|
1451
1691
|
}
|
|
1452
|
-
//
|
|
1453
|
-
writeTimers([]);
|
|
1692
|
+
// 进程真退出才丢计时器;/new 或交接(reason=new)是同一进程换会话,计时器要留着
|
|
1693
|
+
if (event.reason !== "new") writeTimers([]);
|
|
1454
1694
|
if (!state) return;
|
|
1455
1695
|
audit({ kind: "session-end", cwd: state.cwd, rounds: state.rounds, keepAlive: state.keepAlive, reason: event.reason });
|
|
1456
1696
|
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, 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.",
|
|
3
|
+
"version": "0.7.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, context-threshold handoff at idle) 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/test/pi-auto.test.mjs
CHANGED
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
// pi-auto 门禁:开关语义、续轮不丢别人的草稿、无轮次上限、abort/error 走 mailbox 轻推、
|
|
2
2
|
// retired 当天不再拉起、正常退出才删状态。
|
|
3
3
|
import assert from "node:assert/strict";
|
|
4
|
-
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
|
|
4
|
+
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import test from "node:test";
|
|
8
8
|
|
|
9
9
|
import register, {
|
|
10
10
|
bgIndexPath,
|
|
11
|
+
HANDOFF_DEFAULT_AT,
|
|
12
|
+
handoffContinuationText,
|
|
13
|
+
handoffMode,
|
|
14
|
+
handoffStage,
|
|
15
|
+
handoffThreshold,
|
|
16
|
+
mechanicalBrief,
|
|
11
17
|
checkTodayWrite,
|
|
12
18
|
continuationText,
|
|
13
19
|
describeSchedule,
|
|
@@ -47,11 +53,16 @@ function createHost({ boot = true, cwd = "/tmp/proj-a", sessionId = "sess-1" } =
|
|
|
47
53
|
const tools = {};
|
|
48
54
|
const commands = {};
|
|
49
55
|
const status = {};
|
|
56
|
+
const sent = [];
|
|
57
|
+
const usage = { percent: null };
|
|
50
58
|
const api = {
|
|
51
59
|
registerTool: (def) => (tools[def.name] = def),
|
|
52
60
|
registerCommand: (name, def) => (commands[name] = def),
|
|
53
61
|
on: (event, handler) => ((events[event] ??= []).push(handler), undefined),
|
|
54
|
-
sendUserMessage: () =>
|
|
62
|
+
sendUserMessage: (text, opts) => {
|
|
63
|
+
sent.push({ text, opts });
|
|
64
|
+
return Promise.resolve();
|
|
65
|
+
},
|
|
55
66
|
};
|
|
56
67
|
const ctx = {
|
|
57
68
|
cwd,
|
|
@@ -59,6 +70,13 @@ function createHost({ boot = true, cwd = "/tmp/proj-a", sessionId = "sess-1" } =
|
|
|
59
70
|
sessionManager: { getSessionId: () => sessionId, getCwd: () => cwd },
|
|
60
71
|
ui: { setStatus: (k, v) => (status[k] = v), notify: () => undefined },
|
|
61
72
|
isIdle: () => true,
|
|
73
|
+
getContextUsage: () =>
|
|
74
|
+
usage.percent === null
|
|
75
|
+
? { tokens: null, contextWindow: 200_000, percent: null }
|
|
76
|
+
: { tokens: Math.round((200_000 * usage.percent) / 100), contextWindow: 200_000, percent: usage.percent },
|
|
77
|
+
};
|
|
78
|
+
const setPercent = (p) => {
|
|
79
|
+
usage.percent = p;
|
|
62
80
|
};
|
|
63
81
|
register(api);
|
|
64
82
|
|
|
@@ -74,6 +92,8 @@ function createHost({ boot = true, cwd = "/tmp/proj-a", sessionId = "sess-1" } =
|
|
|
74
92
|
tools,
|
|
75
93
|
commands,
|
|
76
94
|
status,
|
|
95
|
+
sent,
|
|
96
|
+
setPercent,
|
|
77
97
|
emit,
|
|
78
98
|
callTool: (name, args) => tools[name].execute("call-1", args, undefined, undefined, ctx),
|
|
79
99
|
boot: () => emit("session_start", {}),
|
|
@@ -94,6 +114,8 @@ function createHost({ boot = true, cwd = "/tmp/proj-a", sessionId = "sess-1" } =
|
|
|
94
114
|
delete process.env.PI_AUTO_SESSION_ID;
|
|
95
115
|
delete process.env.PI_AUTO_NUDGE_DELAY_MS;
|
|
96
116
|
delete process.env.PI_AUTO_BG_POLL_MS;
|
|
117
|
+
delete process.env.PI_AUTO_HANDOFF;
|
|
118
|
+
delete process.env.PI_AUTO_HANDOFF_AT;
|
|
97
119
|
delete process.env.PI_BOOT_SESSION_ID;
|
|
98
120
|
delete process.env.PI_RUN_DIR;
|
|
99
121
|
rmSync(dir, { recursive: true, force: true });
|
|
@@ -635,3 +657,163 @@ test("auto_bg:list / tail / cancel(kill 整个进程组)", async () => {
|
|
|
635
657
|
host.cleanup();
|
|
636
658
|
}
|
|
637
659
|
});
|
|
660
|
+
|
|
661
|
+
// ---------------------------------------------------------------- 交接线(30–40% 且本轮 idle)
|
|
662
|
+
test("handoff 判据:阈值默认 35、可环境覆盖;stage 只到线才提醒、提醒过就升级", () => {
|
|
663
|
+
assert.equal(HANDOFF_DEFAULT_AT, 35);
|
|
664
|
+
assert.equal(handoffThreshold({}), 35);
|
|
665
|
+
assert.equal(handoffThreshold({ PI_AUTO_HANDOFF_AT: "32" }), 32);
|
|
666
|
+
assert.equal(handoffThreshold({ PI_AUTO_HANDOFF_AT: "abc" }), 35);
|
|
667
|
+
assert.equal(handoffThreshold({ PI_AUTO_HANDOFF_AT: "0" }), 35);
|
|
668
|
+
assert.equal(handoffMode({}), "remind");
|
|
669
|
+
assert.equal(handoffMode({ PI_AUTO_HANDOFF: "auto" }), "auto");
|
|
670
|
+
assert.equal(handoffMode({ PI_AUTO_HANDOFF: "off" }), "off");
|
|
671
|
+
assert.equal(handoffMode({ PI_AUTO_HANDOFF: "乱写" }), "remind");
|
|
672
|
+
|
|
673
|
+
assert.equal(handoffStage(null, 35, 0), 0, "读数未知不催");
|
|
674
|
+
assert.equal(handoffStage(34.9, 35, 0), 0);
|
|
675
|
+
assert.equal(handoffStage(35, 35, 0), 1);
|
|
676
|
+
assert.equal(handoffStage(36, 35, 1), 2, "提醒过还没交接 ⇒ 升级");
|
|
677
|
+
assert.match(handoffContinuationText(3, 36, 35, 1), /交接线/);
|
|
678
|
+
assert.match(handoffContinuationText(3, 36, 35, 1), /36\.0%/);
|
|
679
|
+
assert.match(handoffContinuationText(3, 36, 35, 2), /升级/);
|
|
680
|
+
});
|
|
681
|
+
|
|
682
|
+
test("mechanicalBrief:只写仓内可核实事实(指针/提交/工作树),不编状态", () => {
|
|
683
|
+
const calls = [];
|
|
684
|
+
const brief = mechanicalBrief("/repo/x", "sess-9", 36.2, 35, (file, args) => {
|
|
685
|
+
calls.push([file, ...args].join(" "));
|
|
686
|
+
if (args[0] === "log") return "abc123 fix(a): x\ndef456 feat(b): y\n";
|
|
687
|
+
if (args[0] === "status") return " M tools/a.sh\n?? notes.md\n";
|
|
688
|
+
throw new Error("nope");
|
|
689
|
+
});
|
|
690
|
+
assert.match(brief, /上下文 36\.2% ≥ 35%/);
|
|
691
|
+
assert.match(brief, /abc123 fix\(a\): x/);
|
|
692
|
+
assert.match(brief, /M tools\/a\.sh/);
|
|
693
|
+
assert.match(brief, /sess-9/);
|
|
694
|
+
assert.match(brief, /自动交接/);
|
|
695
|
+
assert.ok(calls.some((c) => c.startsWith("git log --oneline -5")));
|
|
696
|
+
assert.ok(calls.some((c) => c.startsWith("git status --short")));
|
|
697
|
+
});
|
|
698
|
+
|
|
699
|
+
test("无人值守会话:上下文到线就把续轮换成交接指令(两次后升级)", async () => {
|
|
700
|
+
const host = createHost({ boot: true });
|
|
701
|
+
try {
|
|
702
|
+
await host.boot();
|
|
703
|
+
host.setPercent(20);
|
|
704
|
+
const normal = await host.settle("completed");
|
|
705
|
+
assert.ok(normal?.continue === true);
|
|
706
|
+
assert.match(normal.entries.at(-1).content, /续轮/);
|
|
707
|
+
|
|
708
|
+
host.setPercent(36);
|
|
709
|
+
const first = await host.settle("completed");
|
|
710
|
+
assert.ok(first?.continue === true, "第一次到线要 continue 给模型交接的机会");
|
|
711
|
+
assert.equal(first.entries.at(-1).customType, "pi-auto-handoff");
|
|
712
|
+
assert.match(first.entries.at(-1).content, /交接线/);
|
|
713
|
+
assert.match(host.audit(), /handoff-remind/);
|
|
714
|
+
assert.equal(host.state().handoffReminders, 1);
|
|
715
|
+
|
|
716
|
+
const second = await host.settle("completed");
|
|
717
|
+
assert.match(second.entries.at(-1).content, /升级/);
|
|
718
|
+
assert.equal(host.state().handoffReminders, 2);
|
|
719
|
+
} finally {
|
|
720
|
+
host.cleanup();
|
|
721
|
+
}
|
|
722
|
+
});
|
|
723
|
+
|
|
724
|
+
test("交接后缩回低水位:重新武装(不会一直催)", async () => {
|
|
725
|
+
const host = createHost({ boot: true });
|
|
726
|
+
try {
|
|
727
|
+
await host.boot();
|
|
728
|
+
host.setPercent(36);
|
|
729
|
+
await host.settle("completed");
|
|
730
|
+
host.setPercent(12);
|
|
731
|
+
await host.settle("completed");
|
|
732
|
+
assert.match(host.audit(), /handoff-rearm/);
|
|
733
|
+
assert.equal(host.state().handoffStage, 0);
|
|
734
|
+
assert.equal(host.state().handoffReminders, 0);
|
|
735
|
+
host.setPercent(40);
|
|
736
|
+
const again = await host.settle("completed");
|
|
737
|
+
assert.match(again.entries.at(-1).content, /交接线/);
|
|
738
|
+
} finally {
|
|
739
|
+
host.cleanup();
|
|
740
|
+
}
|
|
741
|
+
});
|
|
742
|
+
|
|
743
|
+
test("手开会话(keepAlive=off):只 ui.notify 提一句,不注入消息、不触发新一轮", async () => {
|
|
744
|
+
const host = createHost({ boot: false });
|
|
745
|
+
try {
|
|
746
|
+
await host.boot();
|
|
747
|
+
host.setPercent(45);
|
|
748
|
+
const out = await host.settle("completed");
|
|
749
|
+
assert.equal(out, undefined, "手开会话不许被插件续轮");
|
|
750
|
+
assert.equal(host.sent.length, 0, "不许注入消息");
|
|
751
|
+
assert.match(host.audit(), /handoff-notify/);
|
|
752
|
+
assert.equal(host.state().handoffReminders, 1);
|
|
753
|
+
// 同一条线只提醒一次
|
|
754
|
+
await host.settle("completed");
|
|
755
|
+
assert.equal((host.audit().match(/handoff-notify/g) ?? []).length, 1);
|
|
756
|
+
} finally {
|
|
757
|
+
host.cleanup();
|
|
758
|
+
}
|
|
759
|
+
});
|
|
760
|
+
|
|
761
|
+
test("PI_AUTO_HANDOFF=auto:插件自己拼 brief 并在 settle 后派 /handoff-new", async () => {
|
|
762
|
+
const host = createHost({ boot: true });
|
|
763
|
+
try {
|
|
764
|
+
writeFileSync(join(host.dir, "settings.json"), '{"packages":["npm:pi-agent-handoff"]}\n');
|
|
765
|
+
process.env.PI_AUTO_HANDOFF = "auto";
|
|
766
|
+
await host.boot();
|
|
767
|
+
host.setPercent(37);
|
|
768
|
+
const out = await host.settle("completed");
|
|
769
|
+
assert.equal(out, undefined, "auto 模式不跑额外一轮,直接 settle");
|
|
770
|
+
assert.match(host.audit(), /handoff-auto-pending/);
|
|
771
|
+
await host.settled(false);
|
|
772
|
+
assert.equal(host.sent.length, 1);
|
|
773
|
+
assert.match(host.sent[0].text, /^\/handoff-new /);
|
|
774
|
+
assert.match(host.sent[0].text, /自动交接/);
|
|
775
|
+
assert.equal(host.sent[0].opts.expandPromptTemplates, true);
|
|
776
|
+
assert.match(host.audit(), /handoff-auto/);
|
|
777
|
+
} finally {
|
|
778
|
+
host.cleanup();
|
|
779
|
+
}
|
|
780
|
+
});
|
|
781
|
+
|
|
782
|
+
test("auto 模式但没装 pi-agent-handoff ⇒ 退回提醒(不派不存在的命令)", async () => {
|
|
783
|
+
const host = createHost({ boot: true });
|
|
784
|
+
try {
|
|
785
|
+
writeFileSync(join(host.dir, "settings.json"), '{"packages":[]}\n');
|
|
786
|
+
process.env.PI_AUTO_HANDOFF = "auto";
|
|
787
|
+
await host.boot();
|
|
788
|
+
host.setPercent(37);
|
|
789
|
+
const out = await host.settle("completed");
|
|
790
|
+
assert.ok(out?.continue === true, "退回 remind:continue 让模型自己交接");
|
|
791
|
+
assert.match(out.entries.at(-1).content, /交接线/);
|
|
792
|
+
await host.settled(false);
|
|
793
|
+
assert.equal(host.sent.length, 0);
|
|
794
|
+
} finally {
|
|
795
|
+
host.cleanup();
|
|
796
|
+
}
|
|
797
|
+
});
|
|
798
|
+
|
|
799
|
+
test("交接(reason=new)不丢计时器;真退出才清;死 pid 的孤儿计时器会被清掉", async () => {
|
|
800
|
+
const host = createHost({ boot: true });
|
|
801
|
+
try {
|
|
802
|
+
writeTimers([{ id: "tm-keep", dueAt: Date.now() + 3_600_000, note: "交接后还要用", createdAt: new Date().toISOString() }]);
|
|
803
|
+
await host.boot();
|
|
804
|
+
assert.equal(readTimers().length, 1, "启动时恢复");
|
|
805
|
+
await host.shutdown("new");
|
|
806
|
+
assert.equal(readTimers().length, 1, "换会话不是退出,计时器留着");
|
|
807
|
+
await host.shutdown("quit");
|
|
808
|
+
assert.equal(readTimers().length, 0, "真退出清掉");
|
|
809
|
+
|
|
810
|
+
// 死 pid 的孤儿文件:写到别的 pid,重新 boot 应被清掉
|
|
811
|
+
const deadPid = 999_999;
|
|
812
|
+
writeTimers([{ id: "tm-orphan", dueAt: Date.now() + 60_000, note: "孤儿", createdAt: new Date().toISOString() }], deadPid);
|
|
813
|
+
await host.boot();
|
|
814
|
+
assert.equal(existsSync(join(host.dir, "state", "auto", "timers", `${deadPid}.json`)), false);
|
|
815
|
+
assert.match(host.audit(), /timer-prune/);
|
|
816
|
+
} finally {
|
|
817
|
+
host.cleanup();
|
|
818
|
+
}
|
|
819
|
+
});
|