pi-auto-unattended 0.6.0 → 0.8.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 +33 -0
- package/README.md +22 -4
- package/extensions/pi-auto.ts +296 -13
- package/lib.sh +32 -4
- package/package.json +2 -2
- package/pi-auto +1 -1
- package/test/lib.test.sh +34 -0
- package/test/pi-auto.test.mjs +220 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,38 @@
|
|
|
1
1
|
# CHANGELOG
|
|
2
2
|
|
|
3
|
+
## 0.8.0 (2026-12-05)
|
|
4
|
+
|
|
5
|
+
- 修语义偏差(用户 2026-12-05):「off = 服务今天不会再拉起本目录」把 agent 的开关说成了**目录**级,
|
|
6
|
+
而它实际关的是**本会话**。现在:
|
|
7
|
+
- `retired/<slug>.json` 记 `scope:"session"` + `sessionId` + `pid` + `boot` + `promptHash`,
|
|
8
|
+
文案改为「本会话已收工:不再续轮。服务今天不再为这份需求拉起本目录(改 `projects[].prompt`、
|
|
9
|
+
写今日补充、预约到点或 `pi-auto on` 才会重新拉起)」。
|
|
10
|
+
- 新增工单指纹 `jobFingerprint` = `sha1(projects[].prompt + "\n" + 作用域内 today.prompt)`(TS 与
|
|
11
|
+
`lib.sh:pi_job_fingerprint` 同口径、两边各自有测试):**指纹变了 ⇒ 当天的收工标记作废**
|
|
12
|
+
(`pi_retired_today` 返回「未收工」),服务可以重新拉起 —— 这样「agent 关掉自己」不会把目录整天锁死。
|
|
13
|
+
- legacy 标记(没有 `promptHash` 的旧文件)按已收工处理,升级不会把旧标记当成新活。
|
|
14
|
+
- 回归:`node --test` 31 → 32 条、`test/lib.test.sh` 新增 4 条(指纹一致/legacy/需求变更/今日补充变更)。
|
|
15
|
+
## 0.7.0 (2026-12-05)
|
|
16
|
+
|
|
17
|
+
- 新增**交接线**(用户口径:全天候 agent = 一个 agent 做完本轮把活交给下一轮):`agent_before_settle`
|
|
18
|
+
时用 `ctx.getContextUsage()` 读真实百分比(与 footer/`context_usage` 同一个数),到线(默认 **35%**,
|
|
19
|
+
`PI_AUTO_HANDOFF_AT` 可改)且本轮 idle:
|
|
20
|
+
- **无人值守会话(keepAlive)**:把「续轮草稿」换成「交接草稿」——本会话只写 brief 并
|
|
21
|
+
`session_handoff`,交接后新会话接着干(上下文回到 ~0)。提醒过一次还没交接 ⇒ 升级口径(本会话只做交接);
|
|
22
|
+
百分比回落到「阈值 −5」以下自动重新武装(压缩后不再骚扰),audit `handoff-remind` / `handoff-rearm`。
|
|
23
|
+
- **手开会话**:只 `ui.notify` 提一句(不注入消息、不触发新一轮),同一条线只提一次,audit `handoff-notify`。
|
|
24
|
+
- **`PI_AUTO_HANDOFF=auto`(opt-in)**:插件按仓内可核实事实自己拼 mechanical brief(AGENTS/TODO/PLAN 指针 +
|
|
25
|
+
`git log --oneline -5` + `git status --short` 前 20 行 + 推进口径),settle 后直接派 `/handoff-new`,
|
|
26
|
+
不需要模型再跑一轮;`handoff-auto` / `handoff-auto-pending`。检测到 settings 里没有 pi-agent-handoff ⇒
|
|
27
|
+
自动退回提醒口径(不派不存在的命令)。
|
|
28
|
+
- 计时器跟着**进程**走:`/new`、交接(`session_shutdown.reason=new`)不再丢计时器,只有真退出才清;
|
|
29
|
+
启动时清掉持有者 pid 已死的孤儿计时器文件(audit `timer-prune`)。
|
|
30
|
+
- 回归:`node --test` 23 → 31 条全 pass(判据纯函数、两档文案、到线换草稿/升级/重新武装、
|
|
31
|
+
手开会话只 notify、auto 模式派 `/handoff-new` 且 brief 含仓内事实、未装 handoff 退回 remind、
|
|
32
|
+
交接不丢计时器 + 孤儿清理)。
|
|
33
|
+
- 实测(remind 口径,真会话):`/tmp` e2e 会话在闸门触发后交出 brief → 新会话接 kickoff → 立刻 `auto_switch off`,
|
|
34
|
+
audit 依次 `session-start → continue → session-end(reason=new) → session-start`,无死循环。
|
|
35
|
+
|
|
3
36
|
## 0.6.0 (2026-12-05)
|
|
4
37
|
|
|
5
38
|
- 新增工具 **`auto_timer`**:会话内自主预约「到点唤醒」。`auto_timer({after:"25m", note:"…"})` 调完
|
package/README.md
CHANGED
|
@@ -19,7 +19,7 @@ extensions/pi-auto.ts ──> state/auto/*.json (不 import bash/服务代
|
|
|
19
19
|
服务/CLI ──写文件──> pi-mailbox inbox ──读/注入──> 会话
|
|
20
20
|
```
|
|
21
21
|
|
|
22
|
-
- 扩展与服务只通过文件契约通信:`session-<pid>.json`(开关/轮次)、`retired/<slug>.json
|
|
22
|
+
- 扩展与服务只通过文件契约通信:`session-<pid>.json`(开关/轮次)、`retired/<slug>.json`(本会话当天收工 + 工单指纹)、
|
|
23
23
|
`audit.log`(审计)。
|
|
24
24
|
- 进上下文的话**只有一条通道**:`pi-mailbox`。本仓不实现 `send-keys`,也不自己调 `sendUserMessage`。
|
|
25
25
|
- 代理探测仍是单向依赖 `~/bin/lib-proxy.sh`;没有反向调用。
|
|
@@ -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,12 +267,12 @@ 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**(不许静默自己续轮)。
|
|
256
274
|
- `on`:本轮结束后在 `agent_before_settle` 追加一条续轮草稿并 `continue: true`,**无轮次上限**。
|
|
257
|
-
- `off`:唯一收工信号。写 `retired/<slug>.json`
|
|
275
|
+
- `off`:唯一收工信号。写 `retired/<slug>.json` 后停;服务当天不再为同一份需求拉起该目录。
|
|
258
276
|
- `aborted`(Escape/断流)或 `error`(上游重试耗尽):不做硬续轮,而是延迟 15s/30s/1m/2m/5m
|
|
259
277
|
往自己的 mailbox inbox 写一条轻推;`completed` 轮会重置退避计数。
|
|
260
278
|
- 子代理/async runner 进程(`PI_SUBAGENT_*`、`PI_ASYNC_NATIVE_RUNNER`)直接不参与。
|
|
@@ -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
|
@@ -12,11 +12,12 @@
|
|
|
12
12
|
*
|
|
13
13
|
* 状态(`<agentDir>/state/auto/`,`PI_AUTO_STATE_DIR` 可覆盖):
|
|
14
14
|
* session-<pid>.json { pid,cwd,slug,sessionId,boot,keepAlive,rounds,outcome,phase,updatedAt,... }
|
|
15
|
-
* retired/<slug>.json { date,reason }
|
|
15
|
+
* retired/<slug>.json { date,reason,scope,sessionId,pid,boot,promptHash }
|
|
16
|
+
* 本会话已收工 + 哪个工单收的(指纹变了 ⇒ 服务可重新拉起)
|
|
16
17
|
* audit.log 一行一条 JSON
|
|
17
18
|
*/
|
|
18
19
|
import crypto from "node:crypto";
|
|
19
|
-
import { spawn } from "node:child_process";
|
|
20
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
20
21
|
import fs from "node:fs";
|
|
21
22
|
import os from "node:os";
|
|
22
23
|
import path from "node:path";
|
|
@@ -36,6 +37,12 @@ export type AutoState = {
|
|
|
36
37
|
lastNudgeAt: string | null;
|
|
37
38
|
startedAt: string;
|
|
38
39
|
updatedAt: string;
|
|
40
|
+
/** 交接线状态:0 未到线 / 1 已提醒 / 2 提醒过仍未交接(升级口径)。 */
|
|
41
|
+
handoffStage?: number;
|
|
42
|
+
handoffPercent?: number | null;
|
|
43
|
+
handoffReminders?: number;
|
|
44
|
+
/** 观测到的最高上下文百分比(审计用,便于事后核「为什么这时交接」)。 */
|
|
45
|
+
contextPercentMax?: number | null;
|
|
39
46
|
};
|
|
40
47
|
|
|
41
48
|
const STATUS_KEY = "pi-auto";
|
|
@@ -102,10 +109,38 @@ export function retiredFile(cwd: string): string {
|
|
|
102
109
|
return path.join(retiredRoot(), `${slugFor(cwd)}.json`);
|
|
103
110
|
}
|
|
104
111
|
|
|
112
|
+
/**
|
|
113
|
+
* 「这份工单」的指纹 = sha1(projects[].prompt + "\n" + 作用域命中的 today.prompt)。
|
|
114
|
+
* 与 lib.sh:pi_job_fingerprint 同口径。收工标记记的是**哪个工单收的工**,
|
|
115
|
+
* 不是「这个目录今天不许再动」——需求变了就该重新拉起(2026-12-05 用户口径)。
|
|
116
|
+
*/
|
|
117
|
+
export function jobFingerprint(cwd: string, now = new Date()): string {
|
|
118
|
+
const dir = resolveDir(cwd);
|
|
119
|
+
let prompt = "";
|
|
120
|
+
let today = "";
|
|
121
|
+
try {
|
|
122
|
+
const plan = readPlan();
|
|
123
|
+
const proj = plan.projects.find((p) => p.dir && resolveDir(p.dir) === dir);
|
|
124
|
+
prompt = proj?.prompt ?? "";
|
|
125
|
+
if (plan.today.date === localDate(now) && (!plan.today.dir || resolveDir(plan.today.dir) === dir)) {
|
|
126
|
+
today = plan.today.prompt ?? "";
|
|
127
|
+
}
|
|
128
|
+
} catch {
|
|
129
|
+
/* plan 读不到就按空指纹算(等价于 legacy 行为) */
|
|
130
|
+
}
|
|
131
|
+
return crypto.createHash("sha1").update(`${prompt}\n${today}`).digest("hex");
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* 今天是否已为**这份工单**收工。legacy(没有 promptHash 的旧文件)按「已收工」处理,
|
|
136
|
+
* 避免升级后把旧的收工标记当成新活。
|
|
137
|
+
*/
|
|
105
138
|
export function retiredToday(cwd: string, now = new Date()): boolean {
|
|
106
139
|
try {
|
|
107
|
-
const data = JSON.parse(fs.readFileSync(retiredFile(cwd), "utf8")) as { date?: string };
|
|
108
|
-
|
|
140
|
+
const data = JSON.parse(fs.readFileSync(retiredFile(cwd), "utf8")) as { date?: string; promptHash?: string };
|
|
141
|
+
if (data.date !== localDate(now)) return false;
|
|
142
|
+
if (!data.promptHash) return true;
|
|
143
|
+
return data.promptHash === jobFingerprint(cwd, now);
|
|
109
144
|
} catch {
|
|
110
145
|
return false;
|
|
111
146
|
}
|
|
@@ -116,11 +151,21 @@ function localDate(d: Date): string {
|
|
|
116
151
|
return new Date(d.getTime() - off).toISOString().slice(0, 10);
|
|
117
152
|
}
|
|
118
153
|
|
|
119
|
-
|
|
154
|
+
/** 收工 = 本会话停;顺带记下「哪份工单、哪个会话」收的,服务据此决定还要不要为同样的需求再拉起。 */
|
|
155
|
+
export function retire(cwd: string, reason: string, extra: { sessionId?: string; pid?: number; boot?: boolean } = {}): void {
|
|
120
156
|
try {
|
|
121
157
|
fs.mkdirSync(retiredRoot(), { recursive: true });
|
|
122
158
|
const file = retiredFile(cwd);
|
|
123
|
-
|
|
159
|
+
const payload = {
|
|
160
|
+
date: localDate(new Date()),
|
|
161
|
+
reason,
|
|
162
|
+
scope: "session",
|
|
163
|
+
sessionId: extra.sessionId ?? "",
|
|
164
|
+
pid: extra.pid ?? process.pid,
|
|
165
|
+
boot: extra.boot ?? false,
|
|
166
|
+
promptHash: jobFingerprint(cwd),
|
|
167
|
+
};
|
|
168
|
+
fs.writeFileSync(file, `${JSON.stringify(payload, null, 2)}\n`);
|
|
124
169
|
} catch {
|
|
125
170
|
/* 收工标记写不进去不影响会话退出 */
|
|
126
171
|
}
|
|
@@ -553,6 +598,39 @@ export function readTimers(pid: number = process.pid): TimerEntry[] {
|
|
|
553
598
|
}
|
|
554
599
|
}
|
|
555
600
|
|
|
601
|
+
/** 清掉「持有者 pid 已经不在了」的计时器文件(崩溃/重启留下的孤儿,不参与唤醒)。 */
|
|
602
|
+
export function pruneDeadTimerFiles(isAlive: (pid: number) => boolean = (pid) => {
|
|
603
|
+
try {
|
|
604
|
+
process.kill(pid, 0);
|
|
605
|
+
return true;
|
|
606
|
+
} catch (error) {
|
|
607
|
+
// EPERM = 进程在但不属于我们;只把 ESRCH 当死亡
|
|
608
|
+
return (error as NodeJS.ErrnoException)?.code === "EPERM";
|
|
609
|
+
}
|
|
610
|
+
}): number {
|
|
611
|
+
let removed = 0;
|
|
612
|
+
let files: string[] = [];
|
|
613
|
+
try {
|
|
614
|
+
files = fs.readdirSync(timersRoot());
|
|
615
|
+
} catch {
|
|
616
|
+
return 0;
|
|
617
|
+
}
|
|
618
|
+
for (const file of files) {
|
|
619
|
+
const m = /^(\d+)\.json$/.exec(file);
|
|
620
|
+
if (!m) continue;
|
|
621
|
+
const pid = Number(m[1]);
|
|
622
|
+
if (pid === process.pid) continue;
|
|
623
|
+
if (isAlive(pid)) continue;
|
|
624
|
+
try {
|
|
625
|
+
fs.rmSync(path.join(timersRoot(), file), { force: true });
|
|
626
|
+
removed += 1;
|
|
627
|
+
} catch {
|
|
628
|
+
/* ignore */
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
return removed;
|
|
632
|
+
}
|
|
633
|
+
|
|
556
634
|
export function writeTimers(list: TimerEntry[], pid: number = process.pid): void {
|
|
557
635
|
try {
|
|
558
636
|
fs.mkdirSync(timersRoot(), { recursive: true });
|
|
@@ -644,6 +722,108 @@ export function writeJobs(list: BgJob[], pid: number = process.pid): void {
|
|
|
644
722
|
}
|
|
645
723
|
}
|
|
646
724
|
|
|
725
|
+
// ---------------------------------------------------------------- 交接线(上下文 30–40% 且本轮 idle)
|
|
726
|
+
//
|
|
727
|
+
// 2026-12-05 用户口径:「全天候 agent 自动化 = 一个 agent 做完本轮把活交给下一轮」。
|
|
728
|
+
// 所以交接不能只靠模型自己记得(规则 23 写在文档里,实测会话照样一路干到 80%+)。判据放在
|
|
729
|
+
// `agent_before_settle`(本轮真的 idle 了):
|
|
730
|
+
// - 无人值守会话(keepAlive):把「续轮草稿」换成「交接草稿」——本会话只写 brief 并
|
|
731
|
+
// `session_handoff`,交接后新会话接着干(上下文回到 ~0);
|
|
732
|
+
// - 手开会话:只 `ui.notify` 提一句,不注入消息、不触发新一轮;
|
|
733
|
+
// - `PI_AUTO_HANDOFF=auto`:插件按仓内事实自己拼 mechanical brief 并派 `/handoff-new`
|
|
734
|
+
// (默认 `remind`,auto 需要 pi-agent-handoff 已装)。
|
|
735
|
+
// 读数一律用 `ctx.getContextUsage()`(与 footer/context_usage 同一个数),unknown 就什么都不做。
|
|
736
|
+
export const HANDOFF_DEFAULT_AT = 35;
|
|
737
|
+
export type HandoffMode = "off" | "remind" | "auto";
|
|
738
|
+
|
|
739
|
+
export function handoffThreshold(env: NodeJS.ProcessEnv = process.env): number {
|
|
740
|
+
const raw = Number(env.PI_AUTO_HANDOFF_AT ?? "");
|
|
741
|
+
return Number.isFinite(raw) && raw > 0 && raw < 100 ? raw : HANDOFF_DEFAULT_AT;
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
export function handoffMode(env: NodeJS.ProcessEnv = process.env): HandoffMode {
|
|
745
|
+
const raw = String(env.PI_AUTO_HANDOFF ?? "").trim().toLowerCase();
|
|
746
|
+
return raw === "off" || raw === "auto" || raw === "remind" ? (raw as HandoffMode) : "remind";
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/** 百分比掉回「阈值 − 5」以下才重新武装(压缩后不该一直催交接)。 */
|
|
750
|
+
export const HANDOFF_REARM_DROP = 5;
|
|
751
|
+
|
|
752
|
+
/** 本轮要不要发交接提醒:0 = 不用,1 = 首次提醒,2 = 提醒过仍未交接(升级)。 */
|
|
753
|
+
export function handoffStage(percent: number | null, threshold: number, reminded: number): 0 | 1 | 2 {
|
|
754
|
+
if (percent === null || !Number.isFinite(percent)) return 0;
|
|
755
|
+
if (percent < threshold) return 0;
|
|
756
|
+
return reminded >= 1 ? 2 : 1;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
export function handoffContinuationText(round: number, percent: number, threshold: number, stage: number): string {
|
|
760
|
+
const pct = `${percent.toFixed(1)}%`;
|
|
761
|
+
if (stage >= 2) {
|
|
762
|
+
return (
|
|
763
|
+
`【pi-auto 交接线·升级】上下文 ${pct}(阈值 ${threshold}%),上一轮已经提醒过交接但还没交接。` +
|
|
764
|
+
"本会话**不要再开新活**:把手上状态写成自包含 brief(背景与已定决策、绝对路径、待办、验收判据)" +
|
|
765
|
+
"并立刻 `session_handoff({brief, goal})`。交接失败(brief 写不出来)比上下文耗尽便宜得多;" +
|
|
766
|
+
"确实已经全部收口、只剩人工门,才 `auto_switch({action:\"off\", note:\"…\"})` 收工。"
|
|
767
|
+
);
|
|
768
|
+
}
|
|
769
|
+
return (
|
|
770
|
+
`【pi-auto 续轮 #${round} · 交接线】上下文 ${pct}(阈值 ${threshold}%)。` +
|
|
771
|
+
"先把这单交给新会话再继续:调 `session_handoff({brief, goal})`,brief 必须自包含" +
|
|
772
|
+
"(背景与已定决策、绝对路径、待办、验收判据),因为新会话看不到这段对话;交接后新会话接着推进。" +
|
|
773
|
+
"不要把剩下的活继续压在本会话里。"
|
|
774
|
+
);
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/** 机械 brief(`PI_AUTO_HANDOFF=auto` 用):只写仓内**可核实的事实**,不编状态。 */
|
|
778
|
+
export function mechanicalBrief(
|
|
779
|
+
cwd: string,
|
|
780
|
+
sessionId: string,
|
|
781
|
+
percent: number,
|
|
782
|
+
threshold: number,
|
|
783
|
+
exec: (file: string, args: string[]) => string = (file, args) =>
|
|
784
|
+
execFileSync(file, args, { cwd, timeout: 5_000, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }),
|
|
785
|
+
): string {
|
|
786
|
+
const git = (args: string[]): string => {
|
|
787
|
+
try {
|
|
788
|
+
return exec("git", args).trim();
|
|
789
|
+
} catch {
|
|
790
|
+
return "";
|
|
791
|
+
}
|
|
792
|
+
};
|
|
793
|
+
const commits = git(["log", "--oneline", "-5"]) || "(不是 git 仓或没有提交)";
|
|
794
|
+
const dirty = git(["status", "--short"]);
|
|
795
|
+
const dirtyLine = dirty ? dirty.split("\n").slice(0, 20).join("\n") : "(工作树干净)";
|
|
796
|
+
const candidates = ["AGENTS.md", "TODO.md", "PLAN.md", "BACKLOG.md", "ROADMAP.md", ".pi/plans"];
|
|
797
|
+
const found = candidates.filter((f) => {
|
|
798
|
+
try {
|
|
799
|
+
fs.statSync(path.join(cwd, f));
|
|
800
|
+
return true;
|
|
801
|
+
} catch {
|
|
802
|
+
return false;
|
|
803
|
+
}
|
|
804
|
+
});
|
|
805
|
+
const pointers = found.length ? found.map((f) => path.join(cwd, f)).join("\n - ") : "(仓内没找到 AGENTS/TODO/PLAN,向上游/记忆里找)";
|
|
806
|
+
return [
|
|
807
|
+
`# 自动交接(pi-auto:上下文 ${percent.toFixed(1)}% ≥ ${threshold}%)`,
|
|
808
|
+
"",
|
|
809
|
+
`上一个会话已经 idle,上下文到线 ⇒ 由 pi-auto 自动交接。来源会话 ${sessionId},cwd ${cwd}。`,
|
|
810
|
+
"",
|
|
811
|
+
"## 先读这些(单一出处,别凭这段 brief 猜)",
|
|
812
|
+
` - ${pointers}`,
|
|
813
|
+
"",
|
|
814
|
+
"## 最近提交(git log --oneline -5)",
|
|
815
|
+
commits,
|
|
816
|
+
"",
|
|
817
|
+
"## 工作树(未提交改动,前 20 行)",
|
|
818
|
+
dirtyLine,
|
|
819
|
+
"",
|
|
820
|
+
"## 接下来怎么干",
|
|
821
|
+
"- 这是无人值守会话:不问问题、不等确认;按仓内 AGENTS/规则 18 分层推进,自己只做编排 + 复核。",
|
|
822
|
+
"- 先核现状(git status / 日志 / 子代理 / 待办文件),再决定这条线的下一步;口径不确定先查记忆/技能。",
|
|
823
|
+
"- 要等(批次/CI/长命令)用 `auto_timer` / `auto_bg`,不要轮内 `sleep`;做完或只剩人工门就 `auto_switch({action:\"off\", note:\"…\"})`。",
|
|
824
|
+
].join("\n");
|
|
825
|
+
}
|
|
826
|
+
|
|
647
827
|
function shellQuote(value: string): string {
|
|
648
828
|
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
649
829
|
}
|
|
@@ -661,6 +841,29 @@ export default function (pi: ExtensionAPI) {
|
|
|
661
841
|
// 计时器/后台命令的运行期句柄(磁盘状态是权威,这里只是“到点提醒”的定时器)
|
|
662
842
|
const timerHandles = new Map<string, ReturnType<typeof setTimeout>>();
|
|
663
843
|
let bgPoller: ReturnType<typeof setInterval> | undefined;
|
|
844
|
+
// `PI_AUTO_HANDOFF=auto`:本轮 settle 时拼好的机械 brief,等 agent_settled 再派 /handoff-new
|
|
845
|
+
let pendingAutoBrief: string | undefined;
|
|
846
|
+
|
|
847
|
+
/** 与 footer / context_usage 同一个数;拿不到就是 null(不猜)。 */
|
|
848
|
+
const contextPercent = (ctx: ExtensionContext): number | null => {
|
|
849
|
+
try {
|
|
850
|
+
const usage = ctx.getContextUsage?.();
|
|
851
|
+
const pct = usage?.percent;
|
|
852
|
+
return typeof pct === "number" && Number.isFinite(pct) ? pct : null;
|
|
853
|
+
} catch {
|
|
854
|
+
return null;
|
|
855
|
+
}
|
|
856
|
+
};
|
|
857
|
+
|
|
858
|
+
/** auto 模式要求 pi-agent-handoff 已装:settings 里没有就当 remind,别派一个不存在的命令。 */
|
|
859
|
+
const handoffExtensionInstalled = (): boolean => {
|
|
860
|
+
try {
|
|
861
|
+
const raw = fs.readFileSync(path.join(agentDir(), "settings.json"), "utf8");
|
|
862
|
+
return /pi-agent-handoff/.test(raw);
|
|
863
|
+
} catch {
|
|
864
|
+
return false;
|
|
865
|
+
}
|
|
866
|
+
};
|
|
664
867
|
|
|
665
868
|
const fireTimer = (entry: TimerEntry): void => {
|
|
666
869
|
timerHandles.delete(entry.id);
|
|
@@ -761,7 +964,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
761
964
|
const setKeepAlive = (ctx: ExtensionContext, enabled: boolean, by: "agent" | "command" | "retired", note?: string): AutoState => {
|
|
762
965
|
const next = touch(ctx, { keepAlive: enabled });
|
|
763
966
|
if (enabled) unretire(next.cwd);
|
|
764
|
-
else if (next.boot)
|
|
967
|
+
else if (next.boot) {
|
|
968
|
+
retire(next.cwd, note?.trim() || by, { sessionId: next.sessionId, pid: next.pid, boot: next.boot });
|
|
969
|
+
}
|
|
765
970
|
audit({ kind: enabled ? "on" : "off", by, cwd: next.cwd, note: note ?? null, rounds: next.rounds });
|
|
766
971
|
return next;
|
|
767
972
|
};
|
|
@@ -789,11 +994,11 @@ export default function (pi: ExtensionAPI) {
|
|
|
789
994
|
label: "无人值守续轮开关",
|
|
790
995
|
description:
|
|
791
996
|
"pi-auto 的续轮开关:on = 本轮结束后自动接着推下一轮(无轮次上限,直到你自己 off);" +
|
|
792
|
-
"off =
|
|
997
|
+
"off = 本会话收工(不再自动续轮;服务当天不再为这份需求拉起本目录,需求/今日补充/预约变了才重新拉起);status = 看当前开关/轮次。",
|
|
793
998
|
promptSnippet: "无人值守续轮开关(pi-auto):要接着干就 on,收工就 off",
|
|
794
999
|
promptGuidelines: [
|
|
795
1000
|
"还有自己能做的活 → `auto_switch({action:\"on\"})`(无人值守会话默认已开);",
|
|
796
|
-
"收工或只剩人工/审批/环境门 → `auto_switch({action:\"off\", note:\"原因\"})
|
|
1001
|
+
"收工或只剩人工/审批/环境门 → `auto_switch({action:\"off\", note:\"原因\"})`:这是唯一的收工信号(关的是**本会话**,服务当天不再为同一份需求拉起本目录);",
|
|
797
1002
|
"等 CI/子代理/分钟级 ⇒ `auto_timer({after:\"25m\"})`;等一条长命令 ⇒ `auto_bg({command:…})`(都是调完就结束本轮,不要 `bash sleep`);",
|
|
798
1003
|
],
|
|
799
1004
|
parameters: {
|
|
@@ -816,7 +1021,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
816
1021
|
type: "text" as const,
|
|
817
1022
|
text:
|
|
818
1023
|
`pi-auto:keepAlive=${next.keepAlive}(轮次 ${next.rounds})。` +
|
|
819
|
-
(next.keepAlive ? "本轮结束后自动续下一轮;收工时记得 off。" : "
|
|
1024
|
+
(next.keepAlive ? "本轮结束后自动续下一轮;收工时记得 off。" : "本会话已收工:不再续轮。服务今天不再为这份需求拉起本目录(改 projects[].prompt、写今日补充、预约到点或 `pi-auto on` 才会重新拉起)。"),
|
|
820
1025
|
},
|
|
821
1026
|
],
|
|
822
1027
|
details: { state: next },
|
|
@@ -1365,7 +1570,26 @@ export default function (pi: ExtensionAPI) {
|
|
|
1365
1570
|
}
|
|
1366
1571
|
lastOutcome = event.outcome;
|
|
1367
1572
|
const now = touch(ctx, { phase: "settle", outcome: event.outcome });
|
|
1573
|
+
const pct = contextPercent(ctx);
|
|
1574
|
+
const hMode = handoffMode();
|
|
1575
|
+
const hAt = handoffThreshold();
|
|
1576
|
+
if (pct !== null) {
|
|
1577
|
+
touch(ctx, { handoffPercent: pct, contextPercentMax: Math.max(pct, now.contextPercentMax ?? 0) });
|
|
1578
|
+
}
|
|
1368
1579
|
if (!now.keepAlive) {
|
|
1580
|
+
// 手开会话:到线只提一句(不注入消息、不触发新一轮),同一条线只提醒一次
|
|
1581
|
+
if (hMode !== "off" && pct !== null && pct >= hAt && (now.handoffStage ?? 0) === 0) {
|
|
1582
|
+
touch(ctx, { handoffStage: 1, handoffReminders: 1 });
|
|
1583
|
+
try {
|
|
1584
|
+
ctx.ui?.notify?.(
|
|
1585
|
+
`上下文 ${pct.toFixed(1)}% ≥ ${hAt}%:按规则 23 该准备/执行交接(session_handoff),或把这一轮收口到可交接状态`,
|
|
1586
|
+
"info",
|
|
1587
|
+
);
|
|
1588
|
+
} catch {
|
|
1589
|
+
/* print/json 模式没有 UI */
|
|
1590
|
+
}
|
|
1591
|
+
audit({ kind: "handoff-notify", percent: pct, threshold: hAt, cwd: now.cwd });
|
|
1592
|
+
}
|
|
1369
1593
|
audit({ kind: "skip", reason: "off", cwd: now.cwd, rounds: now.rounds });
|
|
1370
1594
|
return;
|
|
1371
1595
|
}
|
|
@@ -1375,6 +1599,50 @@ export default function (pi: ExtensionAPI) {
|
|
|
1375
1599
|
}
|
|
1376
1600
|
// error/aborted:不走 continue(aborted 会被宿主抑制),交给 agent_settled 用 mailbox 轻推
|
|
1377
1601
|
if (event.outcome !== "completed") return;
|
|
1602
|
+
// 交接线:上下文到线就把这一轮变成「交接轮」(计时器/后台命令先让位 —— 交接优先级最高)
|
|
1603
|
+
if (hMode !== "off" && pct !== null) {
|
|
1604
|
+
if (pct < hAt - HANDOFF_REARM_DROP && (now.handoffStage ?? 0) > 0) {
|
|
1605
|
+
touch(ctx, { handoffStage: 0, handoffReminders: 0 });
|
|
1606
|
+
audit({ kind: "handoff-rearm", percent: pct, threshold: hAt, cwd: now.cwd });
|
|
1607
|
+
}
|
|
1608
|
+
const stage = handoffStage(pct, hAt, now.handoffReminders ?? 0);
|
|
1609
|
+
if (stage > 0) {
|
|
1610
|
+
const round = now.rounds + 1;
|
|
1611
|
+
const auto = hMode === "auto" && handoffExtensionInstalled();
|
|
1612
|
+
const next = touch(ctx, {
|
|
1613
|
+
rounds: round,
|
|
1614
|
+
phase: "continue",
|
|
1615
|
+
handoffStage: stage,
|
|
1616
|
+
handoffReminders: (now.handoffReminders ?? 0) + 1,
|
|
1617
|
+
handoffPercent: pct,
|
|
1618
|
+
});
|
|
1619
|
+
nudgeAttempts = 0;
|
|
1620
|
+
audit({ kind: "handoff-remind", percent: pct, threshold: hAt, stage, mode: hMode, auto, round, cwd: next.cwd });
|
|
1621
|
+
if (auto) {
|
|
1622
|
+
// 直接自动化交接:brief 由插件按仓内事实拼,settle 后派 /handoff-new,不需要模型再跑一轮
|
|
1623
|
+
pendingAutoBrief = mechanicalBrief(
|
|
1624
|
+
ctx.cwd,
|
|
1625
|
+
ctx.sessionManager?.getSessionId?.() ?? "unknown",
|
|
1626
|
+
pct,
|
|
1627
|
+
hAt,
|
|
1628
|
+
);
|
|
1629
|
+
audit({ kind: "handoff-auto-pending", percent: pct, threshold: hAt, stage, briefBytes: Buffer.byteLength(pendingAutoBrief, "utf8") });
|
|
1630
|
+
return;
|
|
1631
|
+
}
|
|
1632
|
+
return {
|
|
1633
|
+
entries: [
|
|
1634
|
+
...(event.entries ?? []),
|
|
1635
|
+
{
|
|
1636
|
+
type: "custom_message" as const,
|
|
1637
|
+
customType: "pi-auto-handoff",
|
|
1638
|
+
display: true,
|
|
1639
|
+
content: handoffContinuationText(round, pct, hAt, stage),
|
|
1640
|
+
},
|
|
1641
|
+
],
|
|
1642
|
+
continue: true,
|
|
1643
|
+
};
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1378
1646
|
// 有排着的计时器/后台命令 ⇒ 不空转一轮:本轮收口,到点由 pi-mailbox 叫醒
|
|
1379
1647
|
const pendingTimers = readTimers();
|
|
1380
1648
|
const pendingJobs = readJobs();
|
|
@@ -1412,6 +1680,17 @@ export default function (pi: ExtensionAPI) {
|
|
|
1412
1680
|
});
|
|
1413
1681
|
|
|
1414
1682
|
pi.on("agent_settled", async (event, ctx) => {
|
|
1683
|
+
if (pendingAutoBrief) {
|
|
1684
|
+
const brief = pendingAutoBrief;
|
|
1685
|
+
pendingAutoBrief = undefined;
|
|
1686
|
+
try {
|
|
1687
|
+
pi.sendUserMessage(`/handoff-new ${brief}`, { expandPromptTemplates: true });
|
|
1688
|
+
audit({ kind: "handoff-auto", cwd: ctx.cwd, percent: contextPercent(ctx), briefBytes: Buffer.byteLength(brief, "utf8") });
|
|
1689
|
+
} catch (error) {
|
|
1690
|
+
audit({ kind: "handoff-auto-failed", cwd: ctx.cwd, error: String(error) });
|
|
1691
|
+
}
|
|
1692
|
+
return;
|
|
1693
|
+
}
|
|
1415
1694
|
const now = touch(ctx, { phase: "settled" });
|
|
1416
1695
|
if (!now.keepAlive) return;
|
|
1417
1696
|
if (retiredToday(now.cwd)) {
|
|
@@ -1431,6 +1710,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
1431
1710
|
const now = touch(ctx, { phase: "start" });
|
|
1432
1711
|
audit({ kind: "session-start", cwd: now.cwd, boot: now.boot, keepAlive: now.keepAlive });
|
|
1433
1712
|
// 恢复磁盘上的计时器(跨 /new、/resume 与崩溃重启);过期的立即叫一次
|
|
1713
|
+
const pruned = pruneDeadTimerFiles();
|
|
1714
|
+
if (pruned) audit({ kind: "timer-prune", removed: pruned, cwd: now.cwd });
|
|
1434
1715
|
for (const t of readTimers()) {
|
|
1435
1716
|
if (t.dueAt <= Date.now()) fireTimer(t);
|
|
1436
1717
|
else armTimer(t);
|
|
@@ -1449,12 +1730,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
1449
1730
|
clearInterval(bgPoller);
|
|
1450
1731
|
bgPoller = undefined;
|
|
1451
1732
|
}
|
|
1452
|
-
//
|
|
1453
|
-
writeTimers([]);
|
|
1733
|
+
// 进程真退出才丢计时器;/new 或交接(reason=new)是同一进程换会话,计时器要留着
|
|
1734
|
+
if (event.reason !== "new") writeTimers([]);
|
|
1454
1735
|
if (!state) return;
|
|
1455
1736
|
audit({ kind: "session-end", cwd: state.cwd, rounds: state.rounds, keepAlive: state.keepAlive, reason: event.reason });
|
|
1456
1737
|
if (!state.keepAlive) {
|
|
1457
|
-
if (state.boot)
|
|
1738
|
+
if (state.boot) {
|
|
1739
|
+
retire(state.cwd, `session_shutdown:${event.reason}`, { sessionId: state.sessionId, pid: state.pid, boot: state.boot });
|
|
1740
|
+
}
|
|
1458
1741
|
try {
|
|
1459
1742
|
fs.rmSync(statePath(state.pid), { force: true });
|
|
1460
1743
|
} catch {
|
package/lib.sh
CHANGED
|
@@ -163,12 +163,40 @@ pi_sid_current() {
|
|
|
163
163
|
# 由扩展在 auto_switch off / 正常退出时写,由本库读;服务据此当天不再拉起。
|
|
164
164
|
pi_retired_file() { printf '%s/%s.json' "$PI_AUTO_RETIRED_DIR" "$(pi_slug_for "$1")"; }
|
|
165
165
|
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
166
|
+
# 「这份工单」的指纹 = sha1(projects[].prompt + "\n" + 作用域命中的 today.prompt)。
|
|
167
|
+
# 与 extensions/pi-auto.ts:jobFingerprint 同口径。收工标记记的是**哪个工单收的工**:
|
|
168
|
+
# 需求/今日补充一变,指纹就变 ⇒ 同一目录当天还能被重新拉起(2026-12-05 用户口径:
|
|
169
|
+
# agent 关掉的是**本会话**,不是「这个目录今天不许再动」)。
|
|
170
|
+
pi_plan_project_prompt() { # <目录>
|
|
171
|
+
local dir="${1:-}"
|
|
172
|
+
pi_plan_has || return 0
|
|
173
|
+
jq -r --arg home "$HOME" --arg d "$dir" '
|
|
174
|
+
[ .projects[]? | select((.dir // "") != "")
|
|
175
|
+
| (.dir as $x | (if ($x | startswith("~")) then ($home + ($x | sub("^~"; ""))) else $x end)) as $abs
|
|
176
|
+
| select($abs == $d) | (.prompt // "") ] | (first // "")' "$PI_AUTO_PLAN_FILE" 2>/dev/null | head -1
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
pi_job_fingerprint() { # <目录>
|
|
180
|
+
local dir prompt today
|
|
181
|
+
dir="$(realpath -m -- "${1:-$PWD}" 2>/dev/null || printf '%s' "${1:-$PWD}")"
|
|
182
|
+
prompt="$(pi_plan_project_prompt "$dir")"
|
|
183
|
+
today="$(pi_plan_today_for "$dir")"
|
|
184
|
+
pi_plan_hash "$prompt
|
|
185
|
+
$today"
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
pi_retired_today() { # <目录>;返回 0 = 这份工单今天已收工
|
|
189
|
+
local f dir d ph
|
|
190
|
+
dir="$(realpath -m -- "${1:-$PWD}" 2>/dev/null || printf '%s' "${1:-$PWD}")"
|
|
191
|
+
f="$(pi_retired_file "$dir")"
|
|
169
192
|
[ -f "$f" ] || return 1
|
|
170
193
|
d="$(jq -r '.date // empty' "$f" 2>/dev/null)"
|
|
171
|
-
[ "$d" = "$(date +%F)" ]
|
|
194
|
+
[ "$d" = "$(date +%F)" ] || return 1
|
|
195
|
+
ph="$(jq -r '.promptHash // empty' "$f" 2>/dev/null)"
|
|
196
|
+
[ -n "$ph" ] || return 0 # legacy(升级前的收工标记)按已收工处理,避免被当成新活
|
|
197
|
+
[ "$ph" = "$(pi_job_fingerprint "$dir")" ] && return 0
|
|
198
|
+
pi_log "收工标记已过期(工单指纹变了):$dir ⇒ 视为未收工,可重新拉起"
|
|
199
|
+
return 1
|
|
172
200
|
}
|
|
173
201
|
|
|
174
202
|
pi_retired_set() { # <目录> <原因>
|
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.8.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/pi-auto
CHANGED
|
@@ -78,7 +78,7 @@ ensure_one() { # <目录> <常驻需求> [force] [一次性请求]
|
|
|
78
78
|
pi_state_init "$session" "$PI_AUTO_DIR" "$PI_AUTO_TAG"
|
|
79
79
|
|
|
80
80
|
if [ "$force" != "1" ] && pi_retired_today "$PI_AUTO_DIR"; then
|
|
81
|
-
pi_log "跳过 $session
|
|
81
|
+
pi_log "跳过 $session:这份需求今天已收工(改 projects[].prompt / 写今日补充 / 预约到点 / pi-auto on 都会重新拉起)"
|
|
82
82
|
return 0
|
|
83
83
|
fi
|
|
84
84
|
|
package/test/lib.test.sh
CHANGED
|
@@ -145,4 +145,38 @@ jq '.projects += [{"dir":"'"$HOME"'/expired","enabled":true,"prompt":"","until":
|
|
|
145
145
|
# 锁用后不留痕迹
|
|
146
146
|
[ ! -e "$PI_AUTO_PLAN_FILE.lockdir" ] || fail "plan.json 锁未释放"
|
|
147
147
|
|
|
148
|
+
|
|
149
|
+
# 收工标记绑定「这份工单」:指纹变了(projects[].prompt 或作用域内 today.prompt 变)⇒ 视为未收工
|
|
150
|
+
mkdir -p "$HOME/job"
|
|
151
|
+
cat >"$PI_AUTO_PLAN_FILE" <<JSON
|
|
152
|
+
{"version":2,"today":{"date":"$(date +%F)","dir":"","prompt":"今日补充A","hash":"x","deliveredTo":[]},
|
|
153
|
+
"projects":[{"dir":"$HOME/job","enabled":true,"prompt":"需求A"}],"schedules":[]}
|
|
154
|
+
JSON
|
|
155
|
+
fp="$(pi_job_fingerprint "$HOME/job")"
|
|
156
|
+
[ "${#fp}" = 40 ] || fail "job 指纹应是 sha1"
|
|
157
|
+
pi_retired_write() { # <promptHash|空>
|
|
158
|
+
mkdir -p "$PI_AUTO_RETIRED_DIR"
|
|
159
|
+
jq -n --arg d "$(date +%F)" --arg h "$1" --arg s "pi-auto-job-1" '{date:$d,reason:"agent off",scope:"session",sessionId:$s,pid:123,boot:true,promptHash:$h}' \
|
|
160
|
+
>"$(pi_retired_file "$HOME/job")"
|
|
161
|
+
}
|
|
162
|
+
pi_retired_write "$fp"
|
|
163
|
+
pi_retired_today "$HOME/job" || fail "指纹一致 ⇒ 应判已收工"
|
|
164
|
+
# legacy(没有 promptHash)仍按已收工处理
|
|
165
|
+
pi_retired_write ""
|
|
166
|
+
pi_retired_today "$HOME/job" || fail "legacy 收工标记应仍算已收工"
|
|
167
|
+
# 需求变了 ⇒ 视为未收工(同一目录当天要能重新拉起)
|
|
168
|
+
pi_retired_write "$fp"
|
|
169
|
+
jq '.projects[0].prompt="需求B"' "$PI_AUTO_PLAN_FILE" >"$PI_AUTO_PLAN_FILE.t" && mv "$PI_AUTO_PLAN_FILE.t" "$PI_AUTO_PLAN_FILE"
|
|
170
|
+
if pi_retired_today "$HOME/job"; then fail "projects[].prompt 变了仍判已收工"; fi
|
|
171
|
+
# 今日补充变了同样唤醒
|
|
172
|
+
cat >"$PI_AUTO_PLAN_FILE" <<JSON
|
|
173
|
+
{"version":2,"today":{"date":"$(date +%F)","dir":"$HOME/job","prompt":"今日补充A","hash":"x","deliveredTo":[]},
|
|
174
|
+
"projects":[{"dir":"$HOME/job","enabled":true,"prompt":"需求A"}],"schedules":[]}
|
|
175
|
+
JSON
|
|
176
|
+
pi_retired_write "$(pi_job_fingerprint "$HOME/job")"
|
|
177
|
+
pi_retired_today "$HOME/job" || fail "补充未变 ⇒ 已收工"
|
|
178
|
+
jq '.today.prompt="今日补充B"' "$PI_AUTO_PLAN_FILE" >"$PI_AUTO_PLAN_FILE.t" && mv "$PI_AUTO_PLAN_FILE.t" "$PI_AUTO_PLAN_FILE"
|
|
179
|
+
if pi_retired_today "$HOME/job"; then fail "今日补充变了仍判已收工"; fi
|
|
180
|
+
rm -f "$(pi_retired_file "$HOME/job")"
|
|
181
|
+
|
|
148
182
|
echo "lib.sh gate: OK"
|
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,
|
|
@@ -23,10 +29,12 @@ import register, {
|
|
|
23
29
|
retire,
|
|
24
30
|
retiredFile,
|
|
25
31
|
retiredToday,
|
|
32
|
+
jobFingerprint,
|
|
26
33
|
slugFor,
|
|
27
34
|
statePath,
|
|
28
35
|
timersPath,
|
|
29
36
|
todayHash,
|
|
37
|
+
updatePlan,
|
|
30
38
|
writeTimers,
|
|
31
39
|
} from "../extensions/pi-auto.ts";
|
|
32
40
|
|
|
@@ -47,11 +55,16 @@ function createHost({ boot = true, cwd = "/tmp/proj-a", sessionId = "sess-1" } =
|
|
|
47
55
|
const tools = {};
|
|
48
56
|
const commands = {};
|
|
49
57
|
const status = {};
|
|
58
|
+
const sent = [];
|
|
59
|
+
const usage = { percent: null };
|
|
50
60
|
const api = {
|
|
51
61
|
registerTool: (def) => (tools[def.name] = def),
|
|
52
62
|
registerCommand: (name, def) => (commands[name] = def),
|
|
53
63
|
on: (event, handler) => ((events[event] ??= []).push(handler), undefined),
|
|
54
|
-
sendUserMessage: () =>
|
|
64
|
+
sendUserMessage: (text, opts) => {
|
|
65
|
+
sent.push({ text, opts });
|
|
66
|
+
return Promise.resolve();
|
|
67
|
+
},
|
|
55
68
|
};
|
|
56
69
|
const ctx = {
|
|
57
70
|
cwd,
|
|
@@ -59,6 +72,13 @@ function createHost({ boot = true, cwd = "/tmp/proj-a", sessionId = "sess-1" } =
|
|
|
59
72
|
sessionManager: { getSessionId: () => sessionId, getCwd: () => cwd },
|
|
60
73
|
ui: { setStatus: (k, v) => (status[k] = v), notify: () => undefined },
|
|
61
74
|
isIdle: () => true,
|
|
75
|
+
getContextUsage: () =>
|
|
76
|
+
usage.percent === null
|
|
77
|
+
? { tokens: null, contextWindow: 200_000, percent: null }
|
|
78
|
+
: { tokens: Math.round((200_000 * usage.percent) / 100), contextWindow: 200_000, percent: usage.percent },
|
|
79
|
+
};
|
|
80
|
+
const setPercent = (p) => {
|
|
81
|
+
usage.percent = p;
|
|
62
82
|
};
|
|
63
83
|
register(api);
|
|
64
84
|
|
|
@@ -74,6 +94,8 @@ function createHost({ boot = true, cwd = "/tmp/proj-a", sessionId = "sess-1" } =
|
|
|
74
94
|
tools,
|
|
75
95
|
commands,
|
|
76
96
|
status,
|
|
97
|
+
sent,
|
|
98
|
+
setPercent,
|
|
77
99
|
emit,
|
|
78
100
|
callTool: (name, args) => tools[name].execute("call-1", args, undefined, undefined, ctx),
|
|
79
101
|
boot: () => emit("session_start", {}),
|
|
@@ -94,6 +116,8 @@ function createHost({ boot = true, cwd = "/tmp/proj-a", sessionId = "sess-1" } =
|
|
|
94
116
|
delete process.env.PI_AUTO_SESSION_ID;
|
|
95
117
|
delete process.env.PI_AUTO_NUDGE_DELAY_MS;
|
|
96
118
|
delete process.env.PI_AUTO_BG_POLL_MS;
|
|
119
|
+
delete process.env.PI_AUTO_HANDOFF;
|
|
120
|
+
delete process.env.PI_AUTO_HANDOFF_AT;
|
|
97
121
|
delete process.env.PI_BOOT_SESSION_ID;
|
|
98
122
|
delete process.env.PI_RUN_DIR;
|
|
99
123
|
rmSync(dir, { recursive: true, force: true });
|
|
@@ -635,3 +659,197 @@ test("auto_bg:list / tail / cancel(kill 整个进程组)", async () => {
|
|
|
635
659
|
host.cleanup();
|
|
636
660
|
}
|
|
637
661
|
});
|
|
662
|
+
|
|
663
|
+
// ---------------------------------------------------------------- 交接线(30–40% 且本轮 idle)
|
|
664
|
+
test("handoff 判据:阈值默认 35、可环境覆盖;stage 只到线才提醒、提醒过就升级", () => {
|
|
665
|
+
assert.equal(HANDOFF_DEFAULT_AT, 35);
|
|
666
|
+
assert.equal(handoffThreshold({}), 35);
|
|
667
|
+
assert.equal(handoffThreshold({ PI_AUTO_HANDOFF_AT: "32" }), 32);
|
|
668
|
+
assert.equal(handoffThreshold({ PI_AUTO_HANDOFF_AT: "abc" }), 35);
|
|
669
|
+
assert.equal(handoffThreshold({ PI_AUTO_HANDOFF_AT: "0" }), 35);
|
|
670
|
+
assert.equal(handoffMode({}), "remind");
|
|
671
|
+
assert.equal(handoffMode({ PI_AUTO_HANDOFF: "auto" }), "auto");
|
|
672
|
+
assert.equal(handoffMode({ PI_AUTO_HANDOFF: "off" }), "off");
|
|
673
|
+
assert.equal(handoffMode({ PI_AUTO_HANDOFF: "乱写" }), "remind");
|
|
674
|
+
|
|
675
|
+
assert.equal(handoffStage(null, 35, 0), 0, "读数未知不催");
|
|
676
|
+
assert.equal(handoffStage(34.9, 35, 0), 0);
|
|
677
|
+
assert.equal(handoffStage(35, 35, 0), 1);
|
|
678
|
+
assert.equal(handoffStage(36, 35, 1), 2, "提醒过还没交接 ⇒ 升级");
|
|
679
|
+
assert.match(handoffContinuationText(3, 36, 35, 1), /交接线/);
|
|
680
|
+
assert.match(handoffContinuationText(3, 36, 35, 1), /36\.0%/);
|
|
681
|
+
assert.match(handoffContinuationText(3, 36, 35, 2), /升级/);
|
|
682
|
+
});
|
|
683
|
+
|
|
684
|
+
test("mechanicalBrief:只写仓内可核实事实(指针/提交/工作树),不编状态", () => {
|
|
685
|
+
const calls = [];
|
|
686
|
+
const brief = mechanicalBrief("/repo/x", "sess-9", 36.2, 35, (file, args) => {
|
|
687
|
+
calls.push([file, ...args].join(" "));
|
|
688
|
+
if (args[0] === "log") return "abc123 fix(a): x\ndef456 feat(b): y\n";
|
|
689
|
+
if (args[0] === "status") return " M tools/a.sh\n?? notes.md\n";
|
|
690
|
+
throw new Error("nope");
|
|
691
|
+
});
|
|
692
|
+
assert.match(brief, /上下文 36\.2% ≥ 35%/);
|
|
693
|
+
assert.match(brief, /abc123 fix\(a\): x/);
|
|
694
|
+
assert.match(brief, /M tools\/a\.sh/);
|
|
695
|
+
assert.match(brief, /sess-9/);
|
|
696
|
+
assert.match(brief, /自动交接/);
|
|
697
|
+
assert.ok(calls.some((c) => c.startsWith("git log --oneline -5")));
|
|
698
|
+
assert.ok(calls.some((c) => c.startsWith("git status --short")));
|
|
699
|
+
});
|
|
700
|
+
|
|
701
|
+
test("无人值守会话:上下文到线就把续轮换成交接指令(两次后升级)", async () => {
|
|
702
|
+
const host = createHost({ boot: true });
|
|
703
|
+
try {
|
|
704
|
+
await host.boot();
|
|
705
|
+
host.setPercent(20);
|
|
706
|
+
const normal = await host.settle("completed");
|
|
707
|
+
assert.ok(normal?.continue === true);
|
|
708
|
+
assert.match(normal.entries.at(-1).content, /续轮/);
|
|
709
|
+
|
|
710
|
+
host.setPercent(36);
|
|
711
|
+
const first = await host.settle("completed");
|
|
712
|
+
assert.ok(first?.continue === true, "第一次到线要 continue 给模型交接的机会");
|
|
713
|
+
assert.equal(first.entries.at(-1).customType, "pi-auto-handoff");
|
|
714
|
+
assert.match(first.entries.at(-1).content, /交接线/);
|
|
715
|
+
assert.match(host.audit(), /handoff-remind/);
|
|
716
|
+
assert.equal(host.state().handoffReminders, 1);
|
|
717
|
+
|
|
718
|
+
const second = await host.settle("completed");
|
|
719
|
+
assert.match(second.entries.at(-1).content, /升级/);
|
|
720
|
+
assert.equal(host.state().handoffReminders, 2);
|
|
721
|
+
} finally {
|
|
722
|
+
host.cleanup();
|
|
723
|
+
}
|
|
724
|
+
});
|
|
725
|
+
|
|
726
|
+
test("交接后缩回低水位:重新武装(不会一直催)", async () => {
|
|
727
|
+
const host = createHost({ boot: true });
|
|
728
|
+
try {
|
|
729
|
+
await host.boot();
|
|
730
|
+
host.setPercent(36);
|
|
731
|
+
await host.settle("completed");
|
|
732
|
+
host.setPercent(12);
|
|
733
|
+
await host.settle("completed");
|
|
734
|
+
assert.match(host.audit(), /handoff-rearm/);
|
|
735
|
+
assert.equal(host.state().handoffStage, 0);
|
|
736
|
+
assert.equal(host.state().handoffReminders, 0);
|
|
737
|
+
host.setPercent(40);
|
|
738
|
+
const again = await host.settle("completed");
|
|
739
|
+
assert.match(again.entries.at(-1).content, /交接线/);
|
|
740
|
+
} finally {
|
|
741
|
+
host.cleanup();
|
|
742
|
+
}
|
|
743
|
+
});
|
|
744
|
+
|
|
745
|
+
test("手开会话(keepAlive=off):只 ui.notify 提一句,不注入消息、不触发新一轮", async () => {
|
|
746
|
+
const host = createHost({ boot: false });
|
|
747
|
+
try {
|
|
748
|
+
await host.boot();
|
|
749
|
+
host.setPercent(45);
|
|
750
|
+
const out = await host.settle("completed");
|
|
751
|
+
assert.equal(out, undefined, "手开会话不许被插件续轮");
|
|
752
|
+
assert.equal(host.sent.length, 0, "不许注入消息");
|
|
753
|
+
assert.match(host.audit(), /handoff-notify/);
|
|
754
|
+
assert.equal(host.state().handoffReminders, 1);
|
|
755
|
+
// 同一条线只提醒一次
|
|
756
|
+
await host.settle("completed");
|
|
757
|
+
assert.equal((host.audit().match(/handoff-notify/g) ?? []).length, 1);
|
|
758
|
+
} finally {
|
|
759
|
+
host.cleanup();
|
|
760
|
+
}
|
|
761
|
+
});
|
|
762
|
+
|
|
763
|
+
test("PI_AUTO_HANDOFF=auto:插件自己拼 brief 并在 settle 后派 /handoff-new", async () => {
|
|
764
|
+
const host = createHost({ boot: true });
|
|
765
|
+
try {
|
|
766
|
+
writeFileSync(join(host.dir, "settings.json"), '{"packages":["npm:pi-agent-handoff"]}\n');
|
|
767
|
+
process.env.PI_AUTO_HANDOFF = "auto";
|
|
768
|
+
await host.boot();
|
|
769
|
+
host.setPercent(37);
|
|
770
|
+
const out = await host.settle("completed");
|
|
771
|
+
assert.equal(out, undefined, "auto 模式不跑额外一轮,直接 settle");
|
|
772
|
+
assert.match(host.audit(), /handoff-auto-pending/);
|
|
773
|
+
await host.settled(false);
|
|
774
|
+
assert.equal(host.sent.length, 1);
|
|
775
|
+
assert.match(host.sent[0].text, /^\/handoff-new /);
|
|
776
|
+
assert.match(host.sent[0].text, /自动交接/);
|
|
777
|
+
assert.equal(host.sent[0].opts.expandPromptTemplates, true);
|
|
778
|
+
assert.match(host.audit(), /handoff-auto/);
|
|
779
|
+
} finally {
|
|
780
|
+
host.cleanup();
|
|
781
|
+
}
|
|
782
|
+
});
|
|
783
|
+
|
|
784
|
+
test("auto 模式但没装 pi-agent-handoff ⇒ 退回提醒(不派不存在的命令)", async () => {
|
|
785
|
+
const host = createHost({ boot: true });
|
|
786
|
+
try {
|
|
787
|
+
writeFileSync(join(host.dir, "settings.json"), '{"packages":[]}\n');
|
|
788
|
+
process.env.PI_AUTO_HANDOFF = "auto";
|
|
789
|
+
await host.boot();
|
|
790
|
+
host.setPercent(37);
|
|
791
|
+
const out = await host.settle("completed");
|
|
792
|
+
assert.ok(out?.continue === true, "退回 remind:continue 让模型自己交接");
|
|
793
|
+
assert.match(out.entries.at(-1).content, /交接线/);
|
|
794
|
+
await host.settled(false);
|
|
795
|
+
assert.equal(host.sent.length, 0);
|
|
796
|
+
} finally {
|
|
797
|
+
host.cleanup();
|
|
798
|
+
}
|
|
799
|
+
});
|
|
800
|
+
|
|
801
|
+
test("交接(reason=new)不丢计时器;真退出才清;死 pid 的孤儿计时器会被清掉", async () => {
|
|
802
|
+
const host = createHost({ boot: true });
|
|
803
|
+
try {
|
|
804
|
+
writeTimers([{ id: "tm-keep", dueAt: Date.now() + 3_600_000, note: "交接后还要用", createdAt: new Date().toISOString() }]);
|
|
805
|
+
await host.boot();
|
|
806
|
+
assert.equal(readTimers().length, 1, "启动时恢复");
|
|
807
|
+
await host.shutdown("new");
|
|
808
|
+
assert.equal(readTimers().length, 1, "换会话不是退出,计时器留着");
|
|
809
|
+
await host.shutdown("quit");
|
|
810
|
+
assert.equal(readTimers().length, 0, "真退出清掉");
|
|
811
|
+
|
|
812
|
+
// 死 pid 的孤儿文件:写到别的 pid,重新 boot 应被清掉
|
|
813
|
+
const deadPid = 999_999;
|
|
814
|
+
writeTimers([{ id: "tm-orphan", dueAt: Date.now() + 60_000, note: "孤儿", createdAt: new Date().toISOString() }], deadPid);
|
|
815
|
+
await host.boot();
|
|
816
|
+
assert.equal(existsSync(join(host.dir, "state", "auto", "timers", `${deadPid}.json`)), false);
|
|
817
|
+
assert.match(host.audit(), /timer-prune/);
|
|
818
|
+
} finally {
|
|
819
|
+
host.cleanup();
|
|
820
|
+
}
|
|
821
|
+
});
|
|
822
|
+
|
|
823
|
+
test("收工标记绑的是会话+工单(不是目录):写 sessionId/scope/promptHash,需求变了当天还能重新拉起", async () => {
|
|
824
|
+
const host = createHost({ boot: true });
|
|
825
|
+
try {
|
|
826
|
+
await host.boot();
|
|
827
|
+
updatePlan((p) => {
|
|
828
|
+
p.projects = [{ dir: host.ctx.cwd, enabled: true, prompt: "需求A" }];
|
|
829
|
+
});
|
|
830
|
+
assert.match(jobFingerprint(host.ctx.cwd), /^[0-9a-f]{40}$/);
|
|
831
|
+
const off = await host.callTool("auto_switch", { action: "off", note: "做完了" });
|
|
832
|
+
assert.match(off.content[0].text, /本会话已收工/);
|
|
833
|
+
assert.match(off.content[0].text, /不再为这份需求拉起本目录/);
|
|
834
|
+
|
|
835
|
+
const raw = JSON.parse(readFileSync(retiredFile(host.ctx.cwd), "utf8"));
|
|
836
|
+
assert.equal(raw.scope, "session");
|
|
837
|
+
assert.equal(raw.sessionId, "sess-1");
|
|
838
|
+
assert.equal(raw.reason, "做完了");
|
|
839
|
+
assert.equal(raw.boot, true);
|
|
840
|
+
assert.match(raw.promptHash, /^[0-9a-f]{40}$/);
|
|
841
|
+
assert.equal(retiredToday(host.ctx.cwd), true);
|
|
842
|
+
|
|
843
|
+
// 同一目录换了工单 ⇒ 今天的收工标记不再算数(服务可以重新拉起)
|
|
844
|
+
updatePlan((p) => {
|
|
845
|
+
p.projects[0].prompt = "需求B";
|
|
846
|
+
});
|
|
847
|
+
assert.equal(retiredToday(host.ctx.cwd), false);
|
|
848
|
+
|
|
849
|
+
// legacy 标记(升级前写的、没有 promptHash)仍按已收工处理
|
|
850
|
+
writeFileSync(retiredFile(host.ctx.cwd), JSON.stringify({ date: new Date().toISOString().slice(0, 10), reason: "old" }));
|
|
851
|
+
assert.equal(retiredToday(host.ctx.cwd), true);
|
|
852
|
+
} finally {
|
|
853
|
+
host.cleanup();
|
|
854
|
+
}
|
|
855
|
+
});
|