ensemble-plugin 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.cursor-plugin/plugin.json +14 -0
- package/.mcp.json +8 -0
- package/LICENSE +21 -0
- package/NOTICE +53 -0
- package/README.md +13 -2
- package/assets/ensemble-bowtie.svg +34 -0
- package/assets/icon.svg +7 -0
- package/assets/logo.svg +8 -0
- package/dist/THIRD-PARTY-NOTICES.txt +1090 -0
- package/dist/ensemble.mjs +71699 -0
- package/dist/web/assets/antigravity-DgAQAdn3.svg +1 -0
- package/dist/web/assets/claude-BizdYttu.svg +1 -0
- package/dist/web/assets/claude-code-B8eqCvAs.svg +1 -0
- package/dist/web/assets/codex-BvkQYgV5.svg +12 -0
- package/dist/web/assets/composer-BWvu9foS.svg +1 -0
- package/dist/web/assets/cormorant-garamond-latin-300-normal-Cw-E_7L1.woff2 +0 -0
- package/dist/web/assets/cormorant-garamond-latin-400-italic-Dc_OZ8oc.woff2 +0 -0
- package/dist/web/assets/cormorant-garamond-latin-400-normal-B-1hWBU7.woff2 +0 -0
- package/dist/web/assets/cormorant-garamond-latin-500-italic-Y14P-dkT.woff2 +0 -0
- package/dist/web/assets/cormorant-garamond-latin-500-normal-BsRWmXhO.woff2 +0 -0
- package/dist/web/assets/cormorant-garamond-latin-600-normal-Co1r35X9.woff2 +0 -0
- package/dist/web/assets/cursor-D2tyRWTE.svg +12 -0
- package/dist/web/assets/deepseek-Cl8NyQEB.svg +1 -0
- package/dist/web/assets/dsh-DNAEj8if.svg +3 -0
- package/dist/web/assets/ensemble-bowtie-C5PHHV-v.svg +34 -0
- package/dist/web/assets/gemini-CGCgtdu_.svg +1 -0
- package/dist/web/assets/glm-efVYFzYJ.svg +1 -0
- package/dist/web/assets/grok-CXGI5ZJ8.svg +1 -0
- package/dist/web/assets/index-GjPJz5g5.js +48 -0
- package/dist/web/assets/index-lM4j_QFj.css +1 -0
- package/dist/web/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
- package/dist/web/assets/kimi-CoXq7FVU.svg +1 -0
- package/dist/web/assets/llama-CBjxA_UR.svg +1 -0
- package/dist/web/assets/minimax-DgXRHG5V.svg +1 -0
- package/dist/web/assets/mistral-B4GaxyUG.svg +1 -0
- package/dist/web/assets/openai-L0iksW7i.svg +1 -0
- package/dist/web/assets/opencode-CdSE0wKU.svg +4 -0
- package/dist/web/assets/pi-DP_DEFhy.svg +6 -0
- package/dist/web/assets/qwen-2yX8JBoZ.svg +1 -0
- package/dist/web/favicon.svg +8 -0
- package/dist/web/index.html +18 -0
- package/dist/web/licenses/CORMORANT-OFL.txt +93 -0
- package/dist/web/licenses/HARNESS-MARKS.md +11 -0
- package/dist/web/licenses/MODEL-MARKS.md +33 -0
- package/dist/web/licenses/THINKING-ORBS-SWIFT-MIT.txt +22 -0
- package/dist/web/licenses/THINKING-ORBS-TS-MIT.txt +21 -0
- package/mcp.json +10 -0
- package/package.json +82 -4
- package/plugin.json +30 -0
- package/skills/ensemble-delegate/SKILL.md +196 -0
- package/skills/ensemble-delegate/scripts/watch.mjs +1170 -0
- package/skills/ensemble-delegate/scripts/watch.rules.example.json +35 -0
|
@@ -0,0 +1,1170 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Ensemble 会话看门狗(随插件分发:skills/ensemble-delegate/scripts/watch.mjs)。
|
|
4
|
+
*
|
|
5
|
+
* 主 Agent 派发会话之后在后台运行它:每隔一会儿向本机的 Ensemble 服务读一遍会话,只在有事发生时输出一行,
|
|
6
|
+
* 让宿主把你叫回来,不必靠反复调用 `wait` / `status` 轮询。
|
|
7
|
+
*
|
|
8
|
+
* [ALERT] 值得现在看一眼:一条有事件依据的事实,不是“卡住了”的判决
|
|
9
|
+
* [DONE] 被盯的会话结束了,该去 `read` 取结果
|
|
10
|
+
* [INFO] 知道就好,不必反应
|
|
11
|
+
* [TICK] 周期小结,不需要反应(配置通知时把它排除在外)
|
|
12
|
+
* [WAKE] 只在 --wake 下出现:退出前的最后一行,写明有几个结束、几个需要看一眼
|
|
13
|
+
*
|
|
14
|
+
* 叫醒主 Agent 的两种方式:
|
|
15
|
+
* - `--wake`(首选,整台机器只起一个):宿主只在后台命令**退出**时才会叫醒空闲的主 Agent,所以出现第一条
|
|
16
|
+
* [DONE] 或 [ALERT] 之后,再等一个很短的合并窗口(--wake-batch)把同一时刻到的几条一并打出来,补一行 [WAKE]
|
|
17
|
+
* 摘要,以退出码 10 退出;主 Agent 处理完,用同样的参数重新启动它。两次之间发生的事靠 `--state` 文件接上:
|
|
18
|
+
* 重启后补报退出期间结束的会话,已经说过的不重复,每个会话的事件接着上次读到的位置读。
|
|
19
|
+
* `--origin` / `--origin-of` 只盯某个 Main Agent 名下的会话(一个服务可能被多个 Main Agent 共用)。
|
|
20
|
+
* - 不带 `--wake`:命令一直活着、有事打印一行,靠宿主“输出匹配”之类的机制通知;盯着的会话都结束后自己退出。
|
|
21
|
+
*
|
|
22
|
+
* 对服务只读:只发 GET 请求,从不取消、发消息或改动任何会话。它自己唯一会写的是 `--state` 点名的那个状态文件
|
|
23
|
+
* (先写同目录下的临时文件再改名)。
|
|
24
|
+
* 只依赖 Node 内置模块与服务的 HTTP 接口(地址与令牌取自 <ENSEMBLE_HOME>/run/service.json),不读服务的内部文件。
|
|
25
|
+
* 它不是 `wait` 的替代:`wait` 是主 Agent 主动等,这个脚本是让宿主在后台把主 Agent 叫回来。
|
|
26
|
+
*
|
|
27
|
+
* 退出码:0 盯着的会话都结束了(或 --once);2 参数不对,或点名的会话一个都不存在;3 服务连不上(超过 --gone-after 分钟);
|
|
28
|
+
* 10 唤醒(--wake):有会话结束或有事要看,处理完再启动它。
|
|
29
|
+
*
|
|
30
|
+
* 判断来源:
|
|
31
|
+
* - “值得留意”那几类(静默、工具长时间没动静、运行很久、同一文件被别的会话写过、补充消息迟迟未确认)
|
|
32
|
+
* 直接取服务端算好的 `summary.attention`,口径与 MCP 的 `attention:` 行一致,这里不再算第二遍;
|
|
33
|
+
* - 需要读事件流才看得出的几类:连续失败、同一调用反复出现、文件冲突类报错,以及排队过久;
|
|
34
|
+
* - 项目自己的规矩只在传了 `--rules` 时才检查(见 watch.rules.example.json)。
|
|
35
|
+
* 每条输出都是从服务返回的数据里读出来的事实,没有推测;措辞不下判决,怎么处理由读到的人决定。
|
|
36
|
+
*/
|
|
37
|
+
import { closeSync, openSync, readFileSync, realpathSync, renameSync, statSync, writeSync } from "node:fs";
|
|
38
|
+
import { homedir } from "node:os";
|
|
39
|
+
import { dirname, join, resolve } from "node:path";
|
|
40
|
+
import { fileURLToPath } from "node:url";
|
|
41
|
+
|
|
42
|
+
// ───────────────────────── 常量 ─────────────────────────
|
|
43
|
+
|
|
44
|
+
const TOKEN_HEADER = "x-ensemble-token";
|
|
45
|
+
/** 同一件事持续存在时,隔多久再提醒一次。 */
|
|
46
|
+
const REALERT_MS = 12 * 60_000;
|
|
47
|
+
/** 连续这么多个工具调用都失败了才提。 */
|
|
48
|
+
const FAIL_STREAK = 4;
|
|
49
|
+
/** 在最近这么多个已结束的工具调用里……同一个调用出现了至少 LOOP_MIN_REPEATS 次、其中至少 LOOP_MIN_FAILED 次失败。 */
|
|
50
|
+
const LOOP_WINDOW = 8;
|
|
51
|
+
const LOOP_MIN_REPEATS = 4;
|
|
52
|
+
const LOOP_MIN_FAILED = 2;
|
|
53
|
+
/** 排队多久、而服务报告还有空闲名额,才值得提。 */
|
|
54
|
+
const QUEUED_MS = 25 * 60_000;
|
|
55
|
+
/** 开始盯一个会话时往回读多少条事件;其中只有发生在最近 3 分钟内的才会触发规则与冲突提示(更早的事早该有人看过了)。 */
|
|
56
|
+
const BACKLOG_EVENTS = 600;
|
|
57
|
+
const BACKLOG_FRESH_MS = 3 * 60_000;
|
|
58
|
+
/** 待命(ready)的会话安静多久才算“没有东西在跑”:刚创建的那一瞬间也可能短暂处在这个阶段。 */
|
|
59
|
+
const READY_GRACE_MS = 2 * 60_000;
|
|
60
|
+
/** 一次输出最多这么长;输出会直接进主 Agent 的上下文。 */
|
|
61
|
+
const LINE_MAX = 420;
|
|
62
|
+
/** --wake:第一条需要反应的输出之后,再等这么久(秒),把同一时刻到的几条一并带上。 */
|
|
63
|
+
const WAKE_BATCH_DEFAULT = 3;
|
|
64
|
+
/** --wake 以这个退出码退出:有事要处理(宿主据此叫醒主 Agent)。 */
|
|
65
|
+
const WAKE_EXIT = 10;
|
|
66
|
+
/** 状态文件的格式版本;不认识的版本当作没有这个文件。 */
|
|
67
|
+
const STATE_VERSION = 1;
|
|
68
|
+
/** 判断“同一个调用反复出现”时,一个调用的指纹(命令或目标)最多取多长。 */
|
|
69
|
+
const FINGERPRINT_MAX = 200;
|
|
70
|
+
/** 多个 Agent 并行改同一批文件时常见的报错。 */
|
|
71
|
+
const CONFLICT_ERRORS = /(ftruncate|EBUSY|EPERM|being used by another process|another process|string to replace not found|old_string.*not found|file has been modified|was modified since|STATUS_SHARING)/i;
|
|
72
|
+
|
|
73
|
+
const USAGE = `Usage: node watch.mjs [session-id ...] [options]
|
|
74
|
+
|
|
75
|
+
Watches Ensemble sessions in the background and prints a line only when something needs you:
|
|
76
|
+
[ALERT] worth a look now: a fact with its evidence, never a verdict
|
|
77
|
+
[DONE] a watched session finished; fetch its result with the \`read\` tool
|
|
78
|
+
[INFO] good to know
|
|
79
|
+
[TICK] periodic summary, nothing to do (leave it out of notifications)
|
|
80
|
+
[WAKE] only with --wake: the last line before it exits, how many finished and how many need a look
|
|
81
|
+
|
|
82
|
+
With no session ids it watches every session that is still unfinished, plus any created after it started,
|
|
83
|
+
plus any finished one that is resumed. It exits by itself once everything it watches has finished (--wake and
|
|
84
|
+
--forever never do that). It only reads from the service: it never cancels or messages a session. The one file it
|
|
85
|
+
may write is the --state file you name.
|
|
86
|
+
|
|
87
|
+
Options
|
|
88
|
+
--sessions <id,id,...> same as listing the ids
|
|
89
|
+
--wake for ONE global watcher that wakes you: as soon as a session finishes ([DONE]) or something needs a
|
|
90
|
+
look ([ALERT]), print it, wait --wake-batch seconds for the ones that arrive together, print a
|
|
91
|
+
[WAKE] summary line and exit with code 10. A host wakes an idle main agent when a background
|
|
92
|
+
command exits, so: handle what was printed, then start this watcher again with the same
|
|
93
|
+
arguments. Having nothing to watch is not an error; it waits. Not with --forever or --once.
|
|
94
|
+
--wake-batch <seconds> with --wake: how long to collect lines that arrive together after the first one (default 3; 0 = at once)
|
|
95
|
+
--state <file> remember what was already reported and how far each session's events were read, in this JSON file
|
|
96
|
+
(replaced atomically; its folder must exist). A restarted watcher then reports sessions that
|
|
97
|
+
finished in between and does not repeat itself. Without it a restart starts from now and says
|
|
98
|
+
the same things again. Use one file per distinct set of arguments.
|
|
99
|
+
--origin <key> only watch sessions of this Main Agent (the origin key, matched exactly); repeatable; default all.
|
|
100
|
+
A session of another origin is never read, even when it follows one of yours.
|
|
101
|
+
--origin-of <id> same, taking the origin from a session id you delegated (so you need not know the key)
|
|
102
|
+
--interval <seconds> poll interval (default 30)
|
|
103
|
+
--tick <minutes> summary line every so often; 0 turns it off (default 5)
|
|
104
|
+
--rules <file.json> your project's rules to check (see watch.rules.example.json); none are checked without it
|
|
105
|
+
--gone-after <minutes> give up when the service has been unreachable this long (default 10)
|
|
106
|
+
--forever keep watching after everything has finished
|
|
107
|
+
--once do one pass, then exit
|
|
108
|
+
--help show this text
|
|
109
|
+
|
|
110
|
+
Environment: ENSEMBLE_HOME selects the state directory, the same as for the plugin.
|
|
111
|
+
Exit codes: 0 finished (or --once), 2 bad arguments or none of the named sessions exist, 3 service unreachable, 10 --wake: something needs handling.`;
|
|
112
|
+
|
|
113
|
+
// ───────────────────────── 小工具 ─────────────────────────
|
|
114
|
+
|
|
115
|
+
const isHighSurrogate = (unit) => unit >= 0xd800 && unit <= 0xdbff;
|
|
116
|
+
const isLowSurrogate = (unit) => unit >= 0xdc00 && unit <= 0xdfff;
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* 取开头最多 max 个 UTF-16 码元;截点落在代理对(emoji 等超出 BMP 的字符占两个码元)中间时少取一个,不留孤立的代理项。
|
|
120
|
+
* 原文里本来就有的孤立代理项原样保留。与服务端 src/shared/safe-slice.ts 的 `sliceHead` 同一语义(脚本独立分发,抄了一份,测试对照)。
|
|
121
|
+
*/
|
|
122
|
+
export function sliceHead(text, max) {
|
|
123
|
+
let end = Math.min(text.length, Math.max(0, Math.floor(max)));
|
|
124
|
+
if (end > 0 && end < text.length && isHighSurrogate(text.charCodeAt(end - 1)) && isLowSurrogate(text.charCodeAt(end))) end -= 1;
|
|
125
|
+
return text.slice(0, end);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** 取结尾最多 max 个码元;起点落在代理对中间时少取一个。与服务端 src/shared/safe-slice.ts 的 `sliceTail` 同一语义。 */
|
|
129
|
+
export function sliceTail(text, max) {
|
|
130
|
+
const size = Math.min(text.length, Math.max(0, Math.floor(max)));
|
|
131
|
+
let start = text.length - size;
|
|
132
|
+
if (start > 0 && start < text.length && isLowSurrogate(text.charCodeAt(start)) && isHighSurrogate(text.charCodeAt(start - 1))) start += 1;
|
|
133
|
+
return text.slice(start);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** 压成一行并截断:工具输出可能很长、带换行。截法与服务端的 `clip(collapseWhitespace(text), max)` 相同(含代理对安全)。 */
|
|
137
|
+
export function clip(text, max = 120) {
|
|
138
|
+
const flat = String(text ?? "").replace(/\s+/g, " ").trim();
|
|
139
|
+
return flat.length > max ? `${sliceHead(flat, Math.max(0, max - 1)).trimEnd()}…` : flat;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const basename = (path) => {
|
|
143
|
+
const normalized = String(path).replace(/[\\/]+$/, "");
|
|
144
|
+
const index = Math.max(normalized.lastIndexOf("/"), normalized.lastIndexOf("\\"));
|
|
145
|
+
return index >= 0 ? normalized.slice(index + 1) : normalized;
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/** 中间省略的路径缩写,始终保留文件名;与服务端的 `shortenPath` 逐字相同(含代理对安全;脚本独立分发,所以抄了一份,测试对照)。 */
|
|
149
|
+
export function shortenPath(path, max = 52) {
|
|
150
|
+
if (path.length <= max) return path;
|
|
151
|
+
const name = basename(path);
|
|
152
|
+
// 名字本身放不下,或者连同省略号几乎占满 max(名字长度 ≥ max - 2):不留头部,只留名字的结尾,至多 max - 1 个字符。
|
|
153
|
+
// 名字只有 max - 2 个字符时,max - 1 比它还长,sliceTail 把越界的数夹成整段,所以整个名字都留下;
|
|
154
|
+
// 别改回 name.slice(name.length - (max - 1)):这个边界上下标是 -1,slice 把它当成“倒数第一个”,名字就只剩最后一个字符。
|
|
155
|
+
if (name.length >= max - 2) return `…${sliceTail(name, max - 1)}`;
|
|
156
|
+
const room = max - name.length - 2;
|
|
157
|
+
return `${sliceHead(path, Math.max(3, room))}…${sliceTail(path, name.length + 1)}`;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** 首字母大写拼不出品牌写法的执行端(与 src/mcp/format.ts 的 HARNESS_BRAND_NAMES 逐项相同;agy 是 Antigravity CLI 的命令名)。 */
|
|
161
|
+
const HARNESS_BRAND_NAMES = { dsh: "DSH", agy: "Antigravity CLI" };
|
|
162
|
+
|
|
163
|
+
/** 执行端的显示名:与 MCP 输出里 `[Codex]` 那一栏同一种写法(模拟的执行端会注明)。 */
|
|
164
|
+
export function harnessLabel(summary) {
|
|
165
|
+
const harness = String(summary.harness ?? "harness");
|
|
166
|
+
const name = HARNESS_BRAND_NAMES[harness] ?? harness.charAt(0).toUpperCase() + harness.slice(1);
|
|
167
|
+
return summary.runtime === "fixture" ? `${name} (simulated)` : name;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** 与服务端 `formatDuration`(src/shared/format.ts)同一种写法,MCP 输出与这里的读数一致。 */
|
|
171
|
+
export function formatDuration(ms) {
|
|
172
|
+
if (!Number.isFinite(ms) || ms < 0) return "0s";
|
|
173
|
+
const totalSeconds = Math.floor(ms / 1000);
|
|
174
|
+
if (totalSeconds < 60) return `${totalSeconds}s`;
|
|
175
|
+
const minutes = Math.floor(totalSeconds / 60);
|
|
176
|
+
const seconds = totalSeconds % 60;
|
|
177
|
+
if (minutes < 60) return `${minutes}m ${String(seconds).padStart(2, "0")}s`;
|
|
178
|
+
const hours = Math.floor(minutes / 60);
|
|
179
|
+
return `${hours}h ${String(minutes % 60).padStart(2, "0")}m`;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const two = (value) => String(value).padStart(2, "0");
|
|
183
|
+
const clock = (ms) => {
|
|
184
|
+
const date = new Date(ms);
|
|
185
|
+
return `${two(date.getHours())}:${two(date.getMinutes())}:${two(date.getSeconds())}`;
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
const labelOf = (summary) => `"${clip(summary.title, 40)}" (${summary.id})`;
|
|
189
|
+
|
|
190
|
+
/** 状态目录:与 src/server/paths.ts 的 resolveHome 同一套规则(脚本独立分发,所以在这里抄一份,由测试对照)。 */
|
|
191
|
+
export function resolveHome(env = process.env, platform = process.platform) {
|
|
192
|
+
const override = env.ENSEMBLE_HOME;
|
|
193
|
+
if (override && override.trim().length > 0) return override;
|
|
194
|
+
if (platform === "win32") return join(env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local"), "Ensemble");
|
|
195
|
+
if (platform === "darwin") return join(homedir(), "Library", "Application Support", "Ensemble");
|
|
196
|
+
return join(env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), "ensemble");
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** 会话是否已经“结束到可以去取结果”:与 src/shared/session-end.ts 的 isSessionSettled 同一口径。 */
|
|
200
|
+
export function isSettled(summary) {
|
|
201
|
+
switch (summary.phase) {
|
|
202
|
+
case "done":
|
|
203
|
+
case "failed":
|
|
204
|
+
case "cancelled":
|
|
205
|
+
return (summary.messages?.pending ?? 0) === 0;
|
|
206
|
+
case "stopped":
|
|
207
|
+
case "lost":
|
|
208
|
+
return true;
|
|
209
|
+
default:
|
|
210
|
+
return false;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// ───────────────────────── 参数 ─────────────────────────
|
|
215
|
+
|
|
216
|
+
const VALUE_OPTIONS = new Set(["sessions", "interval", "tick", "rules", "gone-after", "wake-batch", "state", "origin", "origin-of"]);
|
|
217
|
+
const SESSION_ID = /^[\w.:-]{1,100}$/;
|
|
218
|
+
|
|
219
|
+
export function parseArgs(argv) {
|
|
220
|
+
const options = {
|
|
221
|
+
ids: [],
|
|
222
|
+
interval: 30,
|
|
223
|
+
tick: 5,
|
|
224
|
+
goneAfter: 10,
|
|
225
|
+
forever: false,
|
|
226
|
+
once: false,
|
|
227
|
+
help: false,
|
|
228
|
+
wake: false,
|
|
229
|
+
wakeBatch: WAKE_BATCH_DEFAULT,
|
|
230
|
+
origins: [],
|
|
231
|
+
originOf: [],
|
|
232
|
+
};
|
|
233
|
+
const errors = [];
|
|
234
|
+
let wakeBatchGiven = false;
|
|
235
|
+
const number = (name, raw, min) => {
|
|
236
|
+
const value = raw === undefined ? Number.NaN : Number(raw);
|
|
237
|
+
if (!Number.isFinite(value) || value < min) {
|
|
238
|
+
errors.push(`--${name} needs a number of at least ${min}`);
|
|
239
|
+
return undefined;
|
|
240
|
+
}
|
|
241
|
+
return value;
|
|
242
|
+
};
|
|
243
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
244
|
+
const token = argv[index];
|
|
245
|
+
if (!token.startsWith("--")) {
|
|
246
|
+
options.ids.push(token);
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
const equals = token.indexOf("=");
|
|
250
|
+
const name = equals === -1 ? token.slice(2) : token.slice(2, equals);
|
|
251
|
+
let value = equals === -1 ? undefined : token.slice(equals + 1);
|
|
252
|
+
if (VALUE_OPTIONS.has(name) && value === undefined) {
|
|
253
|
+
const next = argv[index + 1];
|
|
254
|
+
if (next !== undefined && !next.startsWith("--")) {
|
|
255
|
+
value = next;
|
|
256
|
+
index += 1;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
switch (name) {
|
|
260
|
+
case "sessions":
|
|
261
|
+
if (value === undefined || value === "") errors.push("--sessions needs a comma-separated list of session ids");
|
|
262
|
+
else options.ids.push(...value.split(",").filter(Boolean));
|
|
263
|
+
break;
|
|
264
|
+
case "interval": {
|
|
265
|
+
const seconds = number(name, value, 0.1);
|
|
266
|
+
if (seconds !== undefined) options.interval = seconds;
|
|
267
|
+
break;
|
|
268
|
+
}
|
|
269
|
+
case "tick": {
|
|
270
|
+
const minutes = number(name, value, 0);
|
|
271
|
+
if (minutes !== undefined) options.tick = minutes;
|
|
272
|
+
break;
|
|
273
|
+
}
|
|
274
|
+
case "gone-after": {
|
|
275
|
+
const minutes = number(name, value, 0);
|
|
276
|
+
if (minutes !== undefined) options.goneAfter = minutes;
|
|
277
|
+
break;
|
|
278
|
+
}
|
|
279
|
+
case "rules":
|
|
280
|
+
if (value === undefined || value === "") errors.push("--rules needs a file");
|
|
281
|
+
else options.rules = value;
|
|
282
|
+
break;
|
|
283
|
+
case "state":
|
|
284
|
+
if (value === undefined || value === "") errors.push("--state needs a file");
|
|
285
|
+
else options.state = value;
|
|
286
|
+
break;
|
|
287
|
+
case "wake":
|
|
288
|
+
options.wake = true;
|
|
289
|
+
break;
|
|
290
|
+
case "wake-batch": {
|
|
291
|
+
wakeBatchGiven = true;
|
|
292
|
+
const seconds = number(name, value, 0);
|
|
293
|
+
if (seconds !== undefined) options.wakeBatch = seconds;
|
|
294
|
+
break;
|
|
295
|
+
}
|
|
296
|
+
case "origin":
|
|
297
|
+
if (value === undefined || value === "") errors.push("--origin needs an origin key (the Main Agent's `origin.key`; or use --origin-of <session id>)");
|
|
298
|
+
else options.origins.push(value);
|
|
299
|
+
break;
|
|
300
|
+
case "origin-of":
|
|
301
|
+
if (value === undefined || value === "") errors.push("--origin-of needs a session id");
|
|
302
|
+
else options.originOf.push(value);
|
|
303
|
+
break;
|
|
304
|
+
case "forever":
|
|
305
|
+
options.forever = true;
|
|
306
|
+
break;
|
|
307
|
+
case "once":
|
|
308
|
+
options.once = true;
|
|
309
|
+
break;
|
|
310
|
+
case "help":
|
|
311
|
+
options.help = true;
|
|
312
|
+
break;
|
|
313
|
+
default:
|
|
314
|
+
errors.push(`unknown option --${name}`);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
for (const id of [...options.ids, ...options.originOf]) {
|
|
318
|
+
if (!SESSION_ID.test(id)) errors.push(`"${clip(id, 40)}" is not a session id (they look like ses_…)`);
|
|
319
|
+
}
|
|
320
|
+
// --wake 靠“退出”叫醒主 Agent:与永不退出(--forever)或只看一遍(--once)矛盾,直接拒绝,不悄悄选一个。
|
|
321
|
+
if (options.wake && options.forever) errors.push("--wake cannot be combined with --forever: --wake exits to wake you, --forever never exits");
|
|
322
|
+
if (options.wake && options.once) errors.push("--wake cannot be combined with --once: --once looks once and exits, --wake waits for something to happen");
|
|
323
|
+
if (wakeBatchGiven && !options.wake) errors.push("--wake-batch only applies together with --wake");
|
|
324
|
+
// 点名了会话 id 就是盯这几个:来源过滤只用于“自己找该盯哪些”,两者同用会让点名的会话被悄悄忽略。
|
|
325
|
+
if (options.ids.length > 0 && (options.origins.length > 0 || options.originOf.length > 0)) {
|
|
326
|
+
errors.push("--origin / --origin-of choose which sessions to pick up on its own; they cannot be combined with explicit session ids");
|
|
327
|
+
}
|
|
328
|
+
options.ids = [...new Set(options.ids)];
|
|
329
|
+
options.origins = [...new Set(options.origins)];
|
|
330
|
+
options.originOf = [...new Set(options.originOf)];
|
|
331
|
+
return { options, errors };
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// ───────────────────────── 项目规矩(可选) ─────────────────────────
|
|
335
|
+
|
|
336
|
+
export const NO_RULES = Object.freeze({ commands: [], paths: [] });
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* 规矩文件的形状:{ "commands": [{ "match": "<正则>", "flags": "i", "message": "…" }], "paths": [ … ] }。
|
|
340
|
+
* `commands` 对 shell 命令的文本逐条检查(每个工具调用只查一次);
|
|
341
|
+
* `paths` 对执行端报告的文件变更逐个检查,路径相对会话的工作目录、用正斜杠写。`flags` 缺省为 i;不接受 g / y(会让正则带上状态)。
|
|
342
|
+
*/
|
|
343
|
+
export function compileRules(raw) {
|
|
344
|
+
const compiled = { commands: [], paths: [] };
|
|
345
|
+
for (const kind of ["commands", "paths"]) {
|
|
346
|
+
const list = raw?.[kind] ?? [];
|
|
347
|
+
if (!Array.isArray(list)) throw new Error(`"${kind}" must be an array`);
|
|
348
|
+
list.forEach((rule, index) => {
|
|
349
|
+
const where = `${kind}[${index}]`;
|
|
350
|
+
if (typeof rule?.match !== "string" || typeof rule?.message !== "string" || rule.message === "") {
|
|
351
|
+
throw new Error(`${where} needs a "match" pattern and a "message", both strings`);
|
|
352
|
+
}
|
|
353
|
+
const flags = typeof rule.flags === "string" ? rule.flags : "i";
|
|
354
|
+
if (/[gy]/.test(flags)) throw new Error(`${where}.flags must not contain g or y`);
|
|
355
|
+
try {
|
|
356
|
+
compiled[kind].push({ regex: new RegExp(rule.match, flags), message: rule.message });
|
|
357
|
+
} catch (error) {
|
|
358
|
+
throw new Error(`${where}.match is not a valid regular expression: ${error.message}`);
|
|
359
|
+
}
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
return compiled;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
export function loadRules(file) {
|
|
366
|
+
const text = readFileSync(resolve(file), "utf8").replace(/^\uFEFF/, "");
|
|
367
|
+
return compileRules(JSON.parse(text));
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** 文件路径写成相对会话工作目录的正斜杠形式;不在工作目录里的保持绝对路径(正斜杠)。 */
|
|
371
|
+
export function normalizePath(file, cwd) {
|
|
372
|
+
const slashed = String(file ?? "").replace(/\\/g, "/");
|
|
373
|
+
const base = String(cwd ?? "").replace(/\\/g, "/").replace(/\/+$/, "");
|
|
374
|
+
if (base) {
|
|
375
|
+
const insensitive = process.platform === "win32" || process.platform === "darwin";
|
|
376
|
+
const fold = (text) => (insensitive ? text.toLowerCase() : text);
|
|
377
|
+
if (fold(slashed) === fold(base)) return "";
|
|
378
|
+
if (fold(slashed).startsWith(`${fold(base)}/`)) return slashed.slice(base.length + 1);
|
|
379
|
+
}
|
|
380
|
+
return slashed.replace(/^\.\//, "");
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// ───────────────────────── 一条“值得留意”的事实怎么说 ─────────────────────────
|
|
384
|
+
|
|
385
|
+
/** 与 src/shared/attention.ts 的 attentionKey 同一口径:同一件事持续期间标识不变。 */
|
|
386
|
+
export function attentionKey(item) {
|
|
387
|
+
switch (item.kind) {
|
|
388
|
+
case "quiet":
|
|
389
|
+
return `quiet|${item.since}`;
|
|
390
|
+
case "long_tool":
|
|
391
|
+
return `long_tool|${item.tool?.callId}|${item.since}`;
|
|
392
|
+
case "long_run":
|
|
393
|
+
return `long_run|${item.runId ?? item.since}`;
|
|
394
|
+
case "shared_file":
|
|
395
|
+
return `shared_file|${item.path}`;
|
|
396
|
+
case "undelivered":
|
|
397
|
+
return `undelivered|${item.messageId}`;
|
|
398
|
+
case "question":
|
|
399
|
+
// 以提问为准:同一个提问持续期间标识不变,回答之后它的标识就不再出现。
|
|
400
|
+
return `question|${item.questionId}`;
|
|
401
|
+
default:
|
|
402
|
+
// 服务端将来新增的类型:照样有标识,不会被悄悄丢掉。
|
|
403
|
+
return `${item.kind}|${item.since}`;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
const STAGE_TEXT = { recorded: "recorded by Ensemble", queued: "queued", handed_off: "handed to the harness", applied: "applied", failed: "failed", cancelled: "cancelled" };
|
|
408
|
+
|
|
409
|
+
/** 措辞与 src/mcp/format.ts 的 describeAttention 逐字一致(测试对照):只陈述事实,并明说这不是诊断。 */
|
|
410
|
+
export function describeAttention(item, summary, now) {
|
|
411
|
+
const since = formatDuration(now - Date.parse(item.since));
|
|
412
|
+
switch (item.kind) {
|
|
413
|
+
case "quiet":
|
|
414
|
+
return `no events from ${harnessLabel(summary)} for ${since} (last event #${item.seq}) and no tool call is in progress — read the transcript to see what it was last doing before deciding anything`;
|
|
415
|
+
case "long_tool":
|
|
416
|
+
return `no events for ${since} since ${item.tool?.category ?? "tool"} \`${clip(item.tool?.title, 80)}\` started ${formatDuration(now - Date.parse(item.tool?.startedAt))} ago — a long build or test is normal; read the transcript if that is not what you expect`;
|
|
417
|
+
case "long_run":
|
|
418
|
+
return `this run has been going for ${since}`;
|
|
419
|
+
case "shared_file":
|
|
420
|
+
return `${shortenPath(String(item.path ?? ""), 90)} was also written by ${(item.withSessionIds ?? []).join(", ")} (latest write ${since} ago) — concurrent edits to one file can overwrite each other`;
|
|
421
|
+
case "undelivered": {
|
|
422
|
+
const what = item.messageKind === "task" ? "the task" : `the ${item.messageKind === "steer" ? "correction" : "follow-up"}`;
|
|
423
|
+
return `${what} message ${item.messageId} is still "${STAGE_TEXT[item.stage] ?? item.stage}" after ${since} — the harness has not confirmed it was applied`;
|
|
424
|
+
}
|
|
425
|
+
case "question": {
|
|
426
|
+
// 与 src/mcp/format-questions.ts 的 questionSummary 一致:一行摘要,只含第一个问题;怎么回复见 `status` 的整块输出。
|
|
427
|
+
const prompts = item.prompts ?? [];
|
|
428
|
+
const more = prompts.length > 1 ? ` (+${prompts.length - 1} more)` : "";
|
|
429
|
+
return `${harnessLabel(summary)} is waiting for an answer to a question (${item.questionId}): "${prompts[0] ? clip(prompts[0].text, 160) : ""}"${more}`;
|
|
430
|
+
}
|
|
431
|
+
default:
|
|
432
|
+
// 服务端将来新增的类型:照实写出,不丢。
|
|
433
|
+
return `${item.kind} since ${item.since}`;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// ───────────────────────── 逐会话的判断(纯函数,时间由参数传入) ─────────────────────────
|
|
438
|
+
|
|
439
|
+
/** 一个被盯着的会话的记忆:读到哪一条事件、各工具调用的最新样子、已经提醒过什么。 */
|
|
440
|
+
export function createTracker(summary) {
|
|
441
|
+
return {
|
|
442
|
+
id: summary.id,
|
|
443
|
+
cwd: summary.cwd ?? "",
|
|
444
|
+
afterSeq: 0,
|
|
445
|
+
backfilling: true,
|
|
446
|
+
tools: new Map(),
|
|
447
|
+
finished: [],
|
|
448
|
+
emitted: new Map(),
|
|
449
|
+
readySince: undefined,
|
|
450
|
+
// 最近一次说过的“结束”的标识(settle 给每次结束的 key):状态文件靠它认出“这一次结束已经说过了”。
|
|
451
|
+
lastEnd: undefined,
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
const TOOL_FIELDS = ["name", "category", "title", "status", "error", "exitCode", "startedAt", "endedAt"];
|
|
456
|
+
const isShell = (tool) => tool.category === "shell" || tool.name === "shell";
|
|
457
|
+
|
|
458
|
+
function parseJson(text) {
|
|
459
|
+
try {
|
|
460
|
+
return JSON.parse(text);
|
|
461
|
+
} catch {
|
|
462
|
+
// 预览被截断时不是完整的 JSON:调用方退回用标题。
|
|
463
|
+
return undefined;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** shell 类调用的完整命令文本:直接是命令的取原文,是 JSON 参数的取 command;都取不到才用标题。 */
|
|
468
|
+
function commandOf(tool) {
|
|
469
|
+
const text = tool.input?.text;
|
|
470
|
+
if (typeof text === "string" && text !== "") {
|
|
471
|
+
if (tool.input?.format !== "json") return text;
|
|
472
|
+
const parsed = parseJson(text);
|
|
473
|
+
const command = parsed?.command ?? parsed?.cmd;
|
|
474
|
+
if (typeof command === "string" && command !== "") return command;
|
|
475
|
+
}
|
|
476
|
+
return String(tool.title ?? "");
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/** 非 shell 类调用的目标:参数里的路径 / 模式 / 查询 / 地址(有几个取几个),没有就用标题。 */
|
|
480
|
+
const TARGET_KEYS = ["file_path", "filePath", "path", "notebook_path", "pattern", "query", "url"];
|
|
481
|
+
function targetOf(tool) {
|
|
482
|
+
const parsed = tool.input?.format === "json" && typeof tool.input.text === "string" ? parseJson(tool.input.text) : undefined;
|
|
483
|
+
if (parsed !== null && typeof parsed === "object") {
|
|
484
|
+
const picked = TARGET_KEYS.map((key) => parsed[key]).filter((value) => typeof value === "string" && value !== "");
|
|
485
|
+
if (picked.length > 0) return picked.join(" ");
|
|
486
|
+
}
|
|
487
|
+
return String(tool.title ?? "");
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* 判断“同一个调用反复出现”用的指纹:shell 类取规范化后的完整命令(折叠空白、至多 FINGERPRINT_MAX 个字符),
|
|
492
|
+
* 所以 `git log -n 1` 与 `git log -n 2` 是两个调用;其它工具取“工具名 + 目标路径 / 关键参数”。
|
|
493
|
+
*/
|
|
494
|
+
export function callFingerprint(tool) {
|
|
495
|
+
return `${tool.name}: ${clip(isShell(tool) ? commandOf(tool) : targetOf(tool), FINGERPRINT_MAX)}`;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/** 失败的调用给出的原因:输出与错误常常是同一段话,只写一遍。 */
|
|
499
|
+
function failureText(tool, max) {
|
|
500
|
+
const output = clip(tool.output?.text, max);
|
|
501
|
+
const error = clip(tool.error, max);
|
|
502
|
+
return error && !output.includes(error) ? clip(`${output} ${error}`, max) : output || error;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/**
|
|
506
|
+
* 把新读到的事件并进会话的记忆,返回由事件本身触发的发现(规矩被触碰、文件冲突类报错)。
|
|
507
|
+
* 工具调用的更新是一块一块来的(先有名字与输入,后有状态与输出),所以按 callId 合并。
|
|
508
|
+
*/
|
|
509
|
+
export function ingest(tracker, events, { rules = NO_RULES, now }) {
|
|
510
|
+
const findings = [];
|
|
511
|
+
for (const event of events) {
|
|
512
|
+
if (typeof event.seq === "number" && event.seq > tracker.afterSeq) tracker.afterSeq = event.seq;
|
|
513
|
+
// 补读历史时,只有最近发生的才触发;这之后读到的一律算新的。
|
|
514
|
+
const fresh = !tracker.backfilling || !(now - Date.parse(event.at) > BACKLOG_FRESH_MS);
|
|
515
|
+
const data = event.data ?? {};
|
|
516
|
+
|
|
517
|
+
if (event.kind === "tool.updated" && data.callId) {
|
|
518
|
+
const tool = tracker.tools.get(data.callId) ?? { callId: data.callId, name: "tool", category: "other", title: "", status: "running" };
|
|
519
|
+
for (const field of TOOL_FIELDS) if (data[field] !== undefined) tool[field] = data[field];
|
|
520
|
+
if (data.input !== undefined) tool.input = data.input;
|
|
521
|
+
if (data.output !== undefined) tool.output = data.output;
|
|
522
|
+
tracker.tools.set(tool.callId, tool);
|
|
523
|
+
|
|
524
|
+
if (!tool.finished && (tool.status === "completed" || tool.status === "failed" || tool.status === "cancelled")) {
|
|
525
|
+
tool.finished = true;
|
|
526
|
+
tracker.finished.push(tool.callId);
|
|
527
|
+
if (tracker.finished.length > 60) tracker.tools.delete(tracker.finished.shift());
|
|
528
|
+
if (tool.status === "failed" && fresh && CONFLICT_ERRORS.test(`${tool.output?.text ?? ""} ${tool.error ?? ""}`)) {
|
|
529
|
+
findings.push({ tag: "INFO", key: `conflict|${tool.callId}`, text: `a tool call failed with a file-conflict style error — \`${clip(tool.title, 60)}\` → ${failureText(tool, 140)}` });
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
if (rules.commands.length > 0 && isShell(tool)) {
|
|
534
|
+
// 命令文本可能先以标题出现、完整输入随后才到:两者各查一次;同一条规则对同一个调用只会提醒一次(key 相同)。
|
|
535
|
+
tool.checked ??= new Set();
|
|
536
|
+
for (const text of [tool.input?.text, tool.title]) {
|
|
537
|
+
if (!text || tool.checked.has(text)) continue;
|
|
538
|
+
tool.checked.add(text);
|
|
539
|
+
if (!fresh) continue;
|
|
540
|
+
for (const rule of rules.commands) {
|
|
541
|
+
if (rule.regex.test(text)) findings.push({ tag: "ALERT", key: `rule|${tool.callId}|${rule.message}`, text: `${rule.message}: ${clip(text, 160)}` });
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
} else if (event.kind === "file.changed" && fresh && rules.paths.length > 0) {
|
|
546
|
+
for (const file of data.files ?? []) {
|
|
547
|
+
const path = normalizePath(file.path, tracker.cwd);
|
|
548
|
+
for (const rule of rules.paths) {
|
|
549
|
+
if (rule.regex.test(path)) findings.push({ tag: "ALERT", key: `path|${path}|${rule.message}`, text: `${rule.message}: ${clip(path, 160)}` });
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
tracker.backfilling = false;
|
|
555
|
+
return findings;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* 对会话此刻的样子做判断,返回仍然成立的发现。是否真的输出(新出现 / 隔了多久再提醒)由调用方按 key 决定。
|
|
560
|
+
* `capacity` 是服务的并发名额(可能没有读到)。
|
|
561
|
+
*/
|
|
562
|
+
export function inspect(tracker, summary, { now, capacity }) {
|
|
563
|
+
const findings = [];
|
|
564
|
+
|
|
565
|
+
if (summary.phase === "starting" || summary.phase === "running") {
|
|
566
|
+
let streak = 0;
|
|
567
|
+
for (let index = tracker.finished.length - 1; index >= 0; index -= 1) {
|
|
568
|
+
if (tracker.tools.get(tracker.finished[index])?.status !== "failed") break;
|
|
569
|
+
streak += 1;
|
|
570
|
+
}
|
|
571
|
+
if (streak >= FAIL_STREAK) {
|
|
572
|
+
const last = tracker.tools.get(tracker.finished.at(-1));
|
|
573
|
+
findings.push({
|
|
574
|
+
tag: "ALERT",
|
|
575
|
+
key: "failstreak",
|
|
576
|
+
repeat: true,
|
|
577
|
+
text: `${streak} tool calls in a row have failed; latest: \`${clip(last?.title, 80)}\` → ${last ? failureText(last, 120) : ""}`,
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
const recent = tracker.finished.slice(-LOOP_WINDOW).map((id) => tracker.tools.get(id)).filter((tool) => tool && tool.title !== "");
|
|
582
|
+
const counts = new Map();
|
|
583
|
+
for (const tool of recent) {
|
|
584
|
+
const key = callFingerprint(tool);
|
|
585
|
+
const entry = counts.get(key) ?? { repeats: 0, failed: 0 };
|
|
586
|
+
entry.repeats += 1;
|
|
587
|
+
if (tool.status === "failed") entry.failed += 1;
|
|
588
|
+
counts.set(key, entry);
|
|
589
|
+
}
|
|
590
|
+
for (const [key, { repeats, failed }] of counts) {
|
|
591
|
+
if (repeats >= LOOP_MIN_REPEATS && failed >= LOOP_MIN_FAILED) {
|
|
592
|
+
findings.push({ tag: "ALERT", key: `repeat|${key}`, repeat: true, text: `the same tool call ran ${repeats} times among the last ${recent.length} finished calls, ${failed} of them failed: ${clip(key, 140)}` });
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
if (summary.phase === "queued" && capacity) {
|
|
598
|
+
const since = Date.parse(summary.activity?.since ?? summary.updatedAt);
|
|
599
|
+
const free = capacity.max === 0 || capacity.occupied < capacity.max;
|
|
600
|
+
if (free && now - since >= QUEUED_MS) {
|
|
601
|
+
findings.push({
|
|
602
|
+
tag: "ALERT",
|
|
603
|
+
key: "queued",
|
|
604
|
+
repeat: true,
|
|
605
|
+
text: `waiting for a concurrency slot for ${formatDuration(now - since)}, although the service reports free capacity (${capacity.occupied} of ${capacity.max === 0 ? "unlimited" : capacity.max} in use)`,
|
|
606
|
+
});
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
// 服务端已经算好的“值得留意”:与 `wait` 提前返回、MCP 的 `attention:` 行是同一份,这里原样转述、不再算第二遍。
|
|
611
|
+
for (const item of summary.attention ?? []) {
|
|
612
|
+
findings.push({ tag: "ALERT", key: `attention|${attentionKey(item)}`, repeat: true, text: describeAttention(item, summary, now) });
|
|
613
|
+
}
|
|
614
|
+
return findings;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** 会话结束时说一次(每次运行各说一次:结束后又被补发消息、再结束,会再说)。 */
|
|
618
|
+
export function settle(tracker, summary, now) {
|
|
619
|
+
const { phase } = summary;
|
|
620
|
+
if (phase === "ready") {
|
|
621
|
+
tracker.readySince ??= now;
|
|
622
|
+
if (now - tracker.readySince < READY_GRACE_MS) return [];
|
|
623
|
+
return [{ tag: "INFO", key: `ready|${summary.lastRun?.id ?? ""}`, text: "is idle (ready): nothing is running in it" }];
|
|
624
|
+
}
|
|
625
|
+
tracker.readySince = undefined;
|
|
626
|
+
if (!isSettled(summary)) return [];
|
|
627
|
+
const key = `end|${summary.lastRun?.id ?? ""}|${phase}`;
|
|
628
|
+
if (phase === "done") {
|
|
629
|
+
const { tools = 0, failedTools = 0, files = 0 } = summary.counters ?? {};
|
|
630
|
+
const facts = [`${tools} tool call${tools === 1 ? "" : "s"}`, ...(failedTools ? [`${failedTools} failed`] : []), ...(files ? [`${files} file${files === 1 ? "" : "s"} changed`] : [])];
|
|
631
|
+
return [{ tag: "DONE", key, text: `finished (${facts.join(", ")}) — use the \`read\` tool for its result` }];
|
|
632
|
+
}
|
|
633
|
+
// 失败与丢失需要去看;被取消或主动关闭是有人做的决定(用户在面板上做的会随下一次工具调用的结果告诉主 Agent)。
|
|
634
|
+
const error = summary.lastError;
|
|
635
|
+
return [{ tag: phase === "failed" || phase === "lost" ? "ALERT" : "INFO", key, text: `ended as ${phase}${error ? ` — [${error.code}] ${clip(error.message, 200)}` : ""}` }];
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
// ───────────────────────── 连接服务 ─────────────────────────
|
|
639
|
+
|
|
640
|
+
/** 服务的地址与令牌(service.json 由服务写下;不存在或损坏都当作没有服务)。 */
|
|
641
|
+
export function readService(home) {
|
|
642
|
+
try {
|
|
643
|
+
const file = JSON.parse(readFileSync(join(home, "run", "service.json"), "utf8"));
|
|
644
|
+
if (typeof file.port === "number" && typeof file.token === "string") return { port: file.port, token: file.token };
|
|
645
|
+
} catch {
|
|
646
|
+
// 没有服务在运行,或文件正被改写。
|
|
647
|
+
}
|
|
648
|
+
return undefined;
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
async function fetchJson(service, path) {
|
|
652
|
+
const response = await fetch(`http://127.0.0.1:${service.port}/api${path}`, {
|
|
653
|
+
headers: { [TOKEN_HEADER]: service.token },
|
|
654
|
+
signal: AbortSignal.timeout(10_000),
|
|
655
|
+
});
|
|
656
|
+
if (!response.ok) throw new Error(`HTTP ${response.status} for ${path}`);
|
|
657
|
+
return response.json();
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
const reasonOf = (error) => clip(error?.cause?.code ?? error?.message ?? error, 100);
|
|
661
|
+
|
|
662
|
+
// ───────────────────────── 状态文件(可选,--state) ─────────────────────────
|
|
663
|
+
|
|
664
|
+
/**
|
|
665
|
+
* 状态文件让重启接得上(--wake 每次叫醒后都要重启)。JSON,version 1:
|
|
666
|
+
* savedAt 写文件的时刻(毫秒时间戳)
|
|
667
|
+
* lastPoll 最近一轮读到会话列表的开始时刻:重启时,结束于它之后、还没说过的会话按“上次退出之后结束的”补报
|
|
668
|
+
* sessions { <会话 id>: { cursor, ended, alerts } },只记仍被盯着的会话,各字段缺省即“没有”
|
|
669
|
+
* cursor 已读到的事件序号:重启后从这里接着读,不重读旧事件去触发规则
|
|
670
|
+
* ended 最近一次说过的“这一次结束”的标识
|
|
671
|
+
* alerts { <提醒的指纹>: <说的时刻> }:只记还没到“可以再提醒”的那些,重启后同一件事不会立刻再说一遍
|
|
672
|
+
* “这一次结束”的标识就是 settle() 给每次结束的 key:`end|<最近一轮的运行 id>|<阶段>`。运行 id 在运行结束后不再变,
|
|
673
|
+
* 所以同一次结束在重启前后是同一个标识(不重复说);被 send 续跑会有新的运行,再结束时标识不同(会再说一次)。
|
|
674
|
+
*/
|
|
675
|
+
|
|
676
|
+
/** 解析状态文件的文本:成功得到 `{ state }`,不认识或不完整得到 `{ problem }`(调用方当作没有这个文件)。 */
|
|
677
|
+
export function parseState(text) {
|
|
678
|
+
let raw;
|
|
679
|
+
try {
|
|
680
|
+
raw = JSON.parse(String(text).replace(/^\uFEFF/, ""));
|
|
681
|
+
} catch {
|
|
682
|
+
return { problem: "it is not valid JSON" };
|
|
683
|
+
}
|
|
684
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return { problem: "it is not a JSON object" };
|
|
685
|
+
if (raw.version !== STATE_VERSION) {
|
|
686
|
+
return { problem: `${raw.version === undefined ? "it has no version" : `it is version ${clip(JSON.stringify(raw.version), 20)}`}, this script reads version ${STATE_VERSION}` };
|
|
687
|
+
}
|
|
688
|
+
if (!Number.isFinite(raw.lastPoll) || !Number.isFinite(raw.savedAt)) return { problem: "it has no usable lastPoll / savedAt" };
|
|
689
|
+
const sessions = new Map();
|
|
690
|
+
const given = raw.sessions !== null && typeof raw.sessions === "object" && !Array.isArray(raw.sessions) ? Object.entries(raw.sessions) : [];
|
|
691
|
+
for (const [id, entry] of given) {
|
|
692
|
+
if (entry === null || typeof entry !== "object") continue;
|
|
693
|
+
const alerts = new Map();
|
|
694
|
+
const mentioned = entry.alerts !== null && typeof entry.alerts === "object" && !Array.isArray(entry.alerts) ? Object.entries(entry.alerts) : [];
|
|
695
|
+
for (const [key, at] of mentioned) if (Number.isFinite(at)) alerts.set(key, at);
|
|
696
|
+
sessions.set(id, {
|
|
697
|
+
cursor: Number.isInteger(entry.cursor) && entry.cursor > 0 ? entry.cursor : undefined,
|
|
698
|
+
ended: typeof entry.ended === "string" && entry.ended !== "" ? entry.ended : undefined,
|
|
699
|
+
alerts,
|
|
700
|
+
});
|
|
701
|
+
}
|
|
702
|
+
return { state: { savedAt: raw.savedAt, lastPoll: raw.lastPoll, sessions } };
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/** 读状态文件:`{ state }`、`{ missing: true }`(还没有,第一次运行),或 `{ problem }`。 */
|
|
706
|
+
export function readStateFile(file) {
|
|
707
|
+
let text;
|
|
708
|
+
try {
|
|
709
|
+
text = readFileSync(file, "utf8");
|
|
710
|
+
} catch (error) {
|
|
711
|
+
return error?.code === "ENOENT" ? { missing: true } : { problem: `it cannot be read (${reasonOf(error)})` };
|
|
712
|
+
}
|
|
713
|
+
return parseState(text);
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/** 先写同目录下的临时文件再改名:读的一方(包括下一个看门狗)永远只会读到完整的旧文件或完整的新文件。 */
|
|
717
|
+
function writeStateFile(file, text) {
|
|
718
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
719
|
+
const bytes = Buffer.from(text, "utf8");
|
|
720
|
+
const handle = openSync(temporary, "w");
|
|
721
|
+
try {
|
|
722
|
+
for (let written = 0; written < bytes.length; ) written += writeSync(handle, bytes, written, bytes.length - written);
|
|
723
|
+
} finally {
|
|
724
|
+
closeSync(handle);
|
|
725
|
+
}
|
|
726
|
+
renameSync(temporary, file);
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/** 把此刻要记住的东西整理成状态(见上)。提醒的指纹只留还没到“可以再提醒”的:再老的,不记与记着等效。 */
|
|
730
|
+
export function buildState(watcher, now) {
|
|
731
|
+
const sessions = new Map();
|
|
732
|
+
for (const [id, tracker] of watcher.trackers) {
|
|
733
|
+
const alerts = {};
|
|
734
|
+
for (const [key, at] of tracker.emitted) if (!key.startsWith("end|") && now - at < REALERT_MS) alerts[key] = at;
|
|
735
|
+
const record = {
|
|
736
|
+
...(tracker.afterSeq > 0 ? { cursor: tracker.afterSeq } : {}),
|
|
737
|
+
...(tracker.lastEnd ? { ended: tracker.lastEnd } : {}),
|
|
738
|
+
...(Object.keys(alerts).length > 0 ? { alerts } : {}),
|
|
739
|
+
};
|
|
740
|
+
if (Object.keys(record).length > 0) sessions.set(id, record);
|
|
741
|
+
}
|
|
742
|
+
return { version: STATE_VERSION, savedAt: now, lastPoll: watcher.lastPoll ?? now, sessions: Object.fromEntries(sessions) };
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
/** 每一轮之后写一次(没有 --state 就什么也不做)。写失败只说一次、下一轮再试:看门狗本身比记忆重要。 */
|
|
746
|
+
function saveState(watcher) {
|
|
747
|
+
const file = watcher.options.state;
|
|
748
|
+
if (!file) return;
|
|
749
|
+
try {
|
|
750
|
+
writeStateFile(resolve(file), `${JSON.stringify(buildState(watcher, watcher.now()), null, 2)}\n`);
|
|
751
|
+
watcher.saveFailed = false;
|
|
752
|
+
} catch (error) {
|
|
753
|
+
if (!watcher.saveFailed) watcher.say("INFO", `could not save the --state file ${file} (${reasonOf(error)}) — will try again on the next pass; until it works a restart forgets what was reported`);
|
|
754
|
+
watcher.saveFailed = true;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/** 启动时读一次状态文件,并说明是接着上次、从现在开始,还是忽略了一个坏文件。 */
|
|
759
|
+
function loadMemory(watcher, now) {
|
|
760
|
+
const file = watcher.options.state;
|
|
761
|
+
if (!file) return;
|
|
762
|
+
const result = readStateFile(resolve(file));
|
|
763
|
+
if (result.state) {
|
|
764
|
+
watcher.memory = result.state;
|
|
765
|
+
watcher.lastPoll = result.state.lastPoll;
|
|
766
|
+
watcher.say("INFO", `resuming from the --state file ${file} (it was last saved ${formatDuration(now - result.state.savedAt)} ago)`);
|
|
767
|
+
} else if (result.missing) {
|
|
768
|
+
watcher.say("INFO", `the --state file ${file} does not exist yet — starting from now; it is created after the first pass`);
|
|
769
|
+
} else {
|
|
770
|
+
watcher.say("INFO", `ignoring the --state file ${file}: ${result.problem} — starting from now; it is replaced after the first pass`);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/** 启动时核对状态文件的位置:目录不存在或路径本身是个目录,写了也白写,直接说清楚比悄悄丢状态好。返回问题描述,没问题返回 undefined。 */
|
|
775
|
+
function checkStatePath(file) {
|
|
776
|
+
const path = resolve(file);
|
|
777
|
+
try {
|
|
778
|
+
if (statSync(path).isDirectory()) return "that path is a folder, not a file";
|
|
779
|
+
} catch {
|
|
780
|
+
// 文件还不存在是正常的(第一次运行)。
|
|
781
|
+
}
|
|
782
|
+
try {
|
|
783
|
+
if (!statSync(dirname(path)).isDirectory()) return `${dirname(path)} is not a folder`;
|
|
784
|
+
} catch {
|
|
785
|
+
return `the folder ${dirname(path)} does not exist (create it first; the script does not make folders)`;
|
|
786
|
+
}
|
|
787
|
+
return undefined;
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/** 会话最近一次运行的结束时刻(毫秒);服务没有记录就返回 undefined——宁可不报,也不拿别的时间去猜。 */
|
|
791
|
+
export function endedAtOf(summary) {
|
|
792
|
+
const stamp = Date.parse(summary.endedAt ?? summary.lastRun?.endedAt ?? "");
|
|
793
|
+
return Number.isFinite(stamp) ? stamp : undefined;
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
// ───────────────────────── 来源过滤(可选,--origin) ─────────────────────────
|
|
797
|
+
|
|
798
|
+
/**
|
|
799
|
+
* 要盯哪些来源(`summary.origin.key` 字符串全等):--origin 给的,加上 --origin-of 那些会话所属的来源。
|
|
800
|
+
* 没有过滤返回 `{ keys: undefined }`;点名的会话不存在或没有来源返回 `{ problem }`。
|
|
801
|
+
*/
|
|
802
|
+
function resolveOrigins(watcher, byId) {
|
|
803
|
+
const { origins, originOf } = watcher.options;
|
|
804
|
+
if (origins.length === 0 && originOf.length === 0) return { keys: undefined };
|
|
805
|
+
const keys = new Set(origins);
|
|
806
|
+
for (const id of originOf) {
|
|
807
|
+
const summary = byId.get(id);
|
|
808
|
+
if (!summary) return { problem: `--origin-of ${id}: the service has no such session (archived sessions are not listed)` };
|
|
809
|
+
const key = summary.origin?.key;
|
|
810
|
+
if (typeof key !== "string" || key === "") return { problem: `--origin-of ${id}: that session has no origin key recorded` };
|
|
811
|
+
keys.add(key);
|
|
812
|
+
}
|
|
813
|
+
return { keys };
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
/** 会话是否在要盯的来源里。跨来源的会话(比如 follows 了你的会话)按它自己的来源判断,不跟上级走。 */
|
|
817
|
+
const inScope = (watcher, summary) => watcher.originKeys === undefined || watcher.originKeys.has(summary.origin?.key);
|
|
818
|
+
|
|
819
|
+
// ───────────────────────── 巡检 ─────────────────────────
|
|
820
|
+
|
|
821
|
+
/** `deps` 都可以替换(测试用):now / say / sleep / readService / fetchJson / rules / home / env。 */
|
|
822
|
+
export function createWatcher(options, deps = {}) {
|
|
823
|
+
const now = deps.now ?? Date.now;
|
|
824
|
+
return {
|
|
825
|
+
options: { ids: [], origins: [], originOf: [], wake: false, wakeBatch: WAKE_BATCH_DEFAULT, ...options },
|
|
826
|
+
home: deps.home ?? resolveHome(deps.env ?? process.env),
|
|
827
|
+
rules: deps.rules ?? NO_RULES,
|
|
828
|
+
now,
|
|
829
|
+
say: deps.say ?? ((tag, text) => process.stdout.write(`${clock(now())} [${tag}] ${clip(text, LINE_MAX)}\n`)),
|
|
830
|
+
sleep: deps.sleep ?? sleep,
|
|
831
|
+
readService: deps.readService ?? readService,
|
|
832
|
+
fetchJson: deps.fetchJson ?? fetchJson,
|
|
833
|
+
trackers: new Map(),
|
|
834
|
+
known: undefined,
|
|
835
|
+
lastTick: now(),
|
|
836
|
+
failures: 0,
|
|
837
|
+
goneSince: undefined,
|
|
838
|
+
goneAnnounced: false,
|
|
839
|
+
// --origin 解析出来的来源 key;没有过滤时是 undefined。
|
|
840
|
+
originKeys: undefined,
|
|
841
|
+
// --state:启动时读到的记忆、最近一轮读到会话列表的开始时刻、最近一次写文件是否失败(只说一次)。
|
|
842
|
+
memory: undefined,
|
|
843
|
+
lastPoll: undefined,
|
|
844
|
+
saveFailed: false,
|
|
845
|
+
// --wake:这一次叫醒要带上的输出(只记标签:DONE / ALERT)。
|
|
846
|
+
waking: [],
|
|
847
|
+
};
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
function unreachable(watcher, error, now) {
|
|
851
|
+
const { options } = watcher;
|
|
852
|
+
watcher.goneSince ??= now;
|
|
853
|
+
watcher.failures += 1;
|
|
854
|
+
const down = now - watcher.goneSince;
|
|
855
|
+
const reason = reasonOf(error);
|
|
856
|
+
if (options.once) {
|
|
857
|
+
watcher.say("ALERT", `cannot reach the Ensemble service (${reason})`);
|
|
858
|
+
return { exit: 3 };
|
|
859
|
+
}
|
|
860
|
+
if (down >= options.goneAfter * 60_000) {
|
|
861
|
+
watcher.say("ALERT", `the Ensemble service has been unreachable for ${formatDuration(down)} (${reason}); giving up. Sessions that were running in it are interrupted if it has stopped.`);
|
|
862
|
+
return { exit: 3 };
|
|
863
|
+
}
|
|
864
|
+
// 一次读取失败可能只是服务正忙或正在重启;连着两次才说。
|
|
865
|
+
if (watcher.failures === 2) {
|
|
866
|
+
watcher.goneAnnounced = true;
|
|
867
|
+
watcher.say("ALERT", `the Ensemble service is unreachable (${reason}) — sessions running in it are interrupted if it has stopped. Still retrying.`);
|
|
868
|
+
}
|
|
869
|
+
return {};
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
function emit(watcher, tracker, summary, findings) {
|
|
873
|
+
const now = watcher.now();
|
|
874
|
+
for (const finding of findings) {
|
|
875
|
+
const last = tracker.emitted.get(finding.key);
|
|
876
|
+
if (last !== undefined && !(finding.repeat && now - last >= REALERT_MS)) continue;
|
|
877
|
+
tracker.emitted.set(finding.key, now);
|
|
878
|
+
// 状态文件要记住“这一次结束已经说过了”:key 就是 settle() 给每次结束的标识。
|
|
879
|
+
if (finding.key.startsWith("end|")) tracker.lastEnd = finding.key;
|
|
880
|
+
// --wake:只有 [DONE] 与 [ALERT] 值得叫醒主 Agent;[INFO] 与 [TICK] 不算。
|
|
881
|
+
if (watcher.options.wake && (finding.tag === "DONE" || finding.tag === "ALERT")) watcher.waking.push(finding.tag);
|
|
882
|
+
watcher.say(finding.tag, `${labelOf(summary)}: ${finding.text}`);
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
/** 开始盯一个会话;状态文件里记着它的话,接着上次的位置读、说过的不再说。 */
|
|
887
|
+
function adopt(watcher, summary) {
|
|
888
|
+
const tracker = createTracker(summary);
|
|
889
|
+
const remembered = watcher.memory?.sessions.get(summary.id);
|
|
890
|
+
if (remembered) {
|
|
891
|
+
// 游标之前的事件上次已经处理过:不再读,也就不会拿旧事件去触发规则;游标之后的一律算新的。
|
|
892
|
+
if (remembered.cursor !== undefined) {
|
|
893
|
+
tracker.afterSeq = remembered.cursor;
|
|
894
|
+
tracker.backfilling = false;
|
|
895
|
+
}
|
|
896
|
+
if (remembered.ended !== undefined) {
|
|
897
|
+
tracker.emitted.set(remembered.ended, watcher.memory.lastPoll);
|
|
898
|
+
tracker.lastEnd = remembered.ended;
|
|
899
|
+
}
|
|
900
|
+
for (const [key, at] of remembered.alerts) tracker.emitted.set(key, at);
|
|
901
|
+
}
|
|
902
|
+
watcher.trackers.set(summary.id, tracker);
|
|
903
|
+
return tracker;
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
/**
|
|
907
|
+
* 看门狗没在运行(或两轮之间)结束、还没人说过的会话:为它们建好记录,由后面的循环照常说出 [DONE] / [ALERT] / [INFO]。
|
|
908
|
+
* 它们的事件不读(属于“之前”)。只在启动那一轮、有状态文件时做;点名了会话 id 时只盯那几个,不做这件事。
|
|
909
|
+
* 返回补报的会话。
|
|
910
|
+
*/
|
|
911
|
+
function adoptEndedSince(watcher, sessions) {
|
|
912
|
+
const since = watcher.lastPoll;
|
|
913
|
+
const adopted = [];
|
|
914
|
+
if (since === undefined) return adopted;
|
|
915
|
+
for (const summary of sessions) {
|
|
916
|
+
if (watcher.trackers.has(summary.id) || !inScope(watcher, summary) || !isSettled(summary)) continue;
|
|
917
|
+
const endedAt = endedAtOf(summary);
|
|
918
|
+
if (endedAt === undefined || endedAt <= since) continue;
|
|
919
|
+
const tracker = adopt(watcher, summary);
|
|
920
|
+
tracker.afterSeq = Number(summary.seq) || 0;
|
|
921
|
+
tracker.backfilling = false;
|
|
922
|
+
adopted.push(summary);
|
|
923
|
+
}
|
|
924
|
+
return adopted;
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
const settledForExit = (tracker, summary, now) => isSettled(summary) || (summary.phase === "ready" && tracker.readySince !== undefined && now - tracker.readySince >= READY_GRACE_MS);
|
|
928
|
+
|
|
929
|
+
/** 读一遍服务并处理。返回 `{ exit }` 表示该结束了(退出码),否则 `{}`。 */
|
|
930
|
+
async function scan(watcher) {
|
|
931
|
+
const { options } = watcher;
|
|
932
|
+
const now = watcher.now();
|
|
933
|
+
// --wake 与 --forever 一样不会因为“盯着的会话都结束了”而退出:前者靠叫醒退出,后者常驻。
|
|
934
|
+
const keepAlive = options.forever || options.wake;
|
|
935
|
+
|
|
936
|
+
let sessions;
|
|
937
|
+
let capacity;
|
|
938
|
+
try {
|
|
939
|
+
const service = watcher.readService(watcher.home);
|
|
940
|
+
if (!service) throw new Error(`no service.json under ${join(watcher.home, "run")}`);
|
|
941
|
+
const body = await watcher.fetchJson(service, "/sessions");
|
|
942
|
+
if (!Array.isArray(body?.sessions)) throw new Error("the service answered /api/sessions with something unexpected");
|
|
943
|
+
sessions = body.sessions;
|
|
944
|
+
capacity = await watcher.fetchJson(service, "/health").then((body) => body.capacity, () => undefined);
|
|
945
|
+
watcher.service = service;
|
|
946
|
+
} catch (error) {
|
|
947
|
+
return unreachable(watcher, error, now);
|
|
948
|
+
}
|
|
949
|
+
if (watcher.goneSince !== undefined) {
|
|
950
|
+
if (watcher.goneAnnounced) watcher.say("INFO", `the Ensemble service is reachable again after ${formatDuration(now - watcher.goneSince)}`);
|
|
951
|
+
watcher.goneSince = undefined;
|
|
952
|
+
watcher.goneAnnounced = false;
|
|
953
|
+
}
|
|
954
|
+
watcher.failures = 0;
|
|
955
|
+
|
|
956
|
+
// 读到了会话列表的这一轮才算“看过”:记下它的开始时刻并存状态(下面提前返回的出口也走这里)。
|
|
957
|
+
const done = (result) => {
|
|
958
|
+
watcher.lastPoll = now;
|
|
959
|
+
saveState(watcher);
|
|
960
|
+
return result;
|
|
961
|
+
};
|
|
962
|
+
|
|
963
|
+
const byId = new Map(sessions.map((summary) => [summary.id, summary]));
|
|
964
|
+
const explicit = options.ids.length > 0;
|
|
965
|
+
|
|
966
|
+
if (watcher.known === undefined) {
|
|
967
|
+
const resolved = resolveOrigins(watcher, byId);
|
|
968
|
+
if (resolved.problem) {
|
|
969
|
+
watcher.say("ALERT", resolved.problem);
|
|
970
|
+
return { exit: 2 };
|
|
971
|
+
}
|
|
972
|
+
watcher.originKeys = resolved.keys;
|
|
973
|
+
loadMemory(watcher, now);
|
|
974
|
+
|
|
975
|
+
watcher.known = new Set(byId.keys());
|
|
976
|
+
const adopted = [];
|
|
977
|
+
if (explicit) {
|
|
978
|
+
for (const id of options.ids) {
|
|
979
|
+
const summary = byId.get(id);
|
|
980
|
+
if (summary) adopted.push(summary);
|
|
981
|
+
else watcher.say("ALERT", `unknown session ${id} — not watching it`);
|
|
982
|
+
}
|
|
983
|
+
} else {
|
|
984
|
+
// 待命(ready)的会话此刻什么也没在做,不算“没结束”:只盯真正在进行的;之后新建的会话不论什么阶段都盯。
|
|
985
|
+
adopted.push(...sessions.filter((summary) => inScope(watcher, summary) && !isSettled(summary) && summary.phase !== "ready"));
|
|
986
|
+
}
|
|
987
|
+
for (const summary of adopted) adopt(watcher, summary);
|
|
988
|
+
// 有状态文件时:上次看过之后才结束、还没说过的会话,这一轮补报。
|
|
989
|
+
const ended = explicit ? [] : adoptEndedSince(watcher, sessions);
|
|
990
|
+
if (adopted.length === 0 && ended.length === 0) {
|
|
991
|
+
if (explicit) return { exit: 2 };
|
|
992
|
+
if (options.wake) {
|
|
993
|
+
watcher.say("INFO", "no unfinished sessions to watch yet — waiting for one to start (--wake keeps waiting)");
|
|
994
|
+
} else {
|
|
995
|
+
watcher.say("INFO", "no unfinished sessions to watch");
|
|
996
|
+
if (!options.forever) return done({ exit: 0 });
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
if (adopted.length > 0) {
|
|
1000
|
+
const shown = adopted.slice(0, 5).map(labelOf).join(", ");
|
|
1001
|
+
const more = adopted.length > 5 ? ` and ${adopted.length - 5} more` : "";
|
|
1002
|
+
const rules = watcher.rules.commands.length + watcher.rules.paths.length;
|
|
1003
|
+
const origins = watcher.originKeys ? `; only origin ${[...watcher.originKeys].join(", ")}` : "";
|
|
1004
|
+
const ending = options.wake ? "; exits when one finishes or needs attention" : options.forever ? "" : "; exits once they have finished";
|
|
1005
|
+
watcher.say(
|
|
1006
|
+
"INFO",
|
|
1007
|
+
`watching ${adopted.length} session${adopted.length === 1 ? "" : "s"}: ${shown}${more}; checking every ${options.interval}s${rules ? `, ${rules} project rule${rules === 1 ? "" : "s"} loaded` : ""}${origins}${ending}`,
|
|
1008
|
+
);
|
|
1009
|
+
}
|
|
1010
|
+
if (ended.length > 0) {
|
|
1011
|
+
const shown = ended.slice(0, 5).map(labelOf).join(", ");
|
|
1012
|
+
const more = ended.length > 5 ? ` and ${ended.length - 5} more` : "";
|
|
1013
|
+
watcher.say("INFO", `${ended.length} session${ended.length === 1 ? "" : "s"} finished since this watcher last looked (${formatDuration(now - watcher.lastPoll)} ago): ${shown}${more}`);
|
|
1014
|
+
}
|
|
1015
|
+
} else if (!explicit) {
|
|
1016
|
+
for (const summary of sessions) {
|
|
1017
|
+
if (watcher.trackers.has(summary.id) || !inScope(watcher, summary)) continue;
|
|
1018
|
+
if (!watcher.known.has(summary.id)) {
|
|
1019
|
+
watcher.known.add(summary.id);
|
|
1020
|
+
adopt(watcher, summary);
|
|
1021
|
+
watcher.say("INFO", `now also watching ${labelOf(summary)}`);
|
|
1022
|
+
} else if (!isSettled(summary) && summary.phase !== "ready") {
|
|
1023
|
+
// 之前没盯(待命或已结束),现在又在进行了:它被 send 续跑了。状态文件里记着读到的位置就接着读;没有记录就按新会话
|
|
1024
|
+
// 补读一遍历史(其中只有最近 3 分钟内的事才会触发规则与冲突提示)。这一轮盯过又结束的会话不走这里:它的记录一直留着。
|
|
1025
|
+
adopt(watcher, summary);
|
|
1026
|
+
watcher.say("INFO", `watching ${labelOf(summary)} again: it is back in progress`);
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
const live = [];
|
|
1032
|
+
for (const [id, tracker] of [...watcher.trackers]) {
|
|
1033
|
+
const summary = byId.get(id);
|
|
1034
|
+
if (!summary) {
|
|
1035
|
+
watcher.trackers.delete(id);
|
|
1036
|
+
watcher.say("INFO", `session ${id} no longer exists — not watching it any more`);
|
|
1037
|
+
continue;
|
|
1038
|
+
}
|
|
1039
|
+
if (summary.seq < tracker.afterSeq) Object.assign(tracker, { afterSeq: 0, backfilling: true, tools: new Map(), finished: [] });
|
|
1040
|
+
|
|
1041
|
+
const findings = [];
|
|
1042
|
+
// 已经结束的会话不必再读事件;结束后又被补发消息而重新活跃时,从上次读到的位置接着读。
|
|
1043
|
+
if (summary.seq > tracker.afterSeq && (!isSettled(summary) || tracker.backfilling)) {
|
|
1044
|
+
try {
|
|
1045
|
+
const query = tracker.afterSeq === 0 ? `?after=0&limit=${BACKLOG_EVENTS}` : `?after=${tracker.afterSeq}`;
|
|
1046
|
+
const { events } = await watcher.fetchJson(watcher.service, `/sessions/${encodeURIComponent(id)}/events${query}`);
|
|
1047
|
+
findings.push(...ingest(tracker, events ?? [], { rules: watcher.rules, now }));
|
|
1048
|
+
} catch {
|
|
1049
|
+
// 这一轮读不到就下一轮再读;会话真的没有了,上面的列表检查会说。
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
findings.push(...inspect(tracker, summary, { now, capacity }), ...settle(tracker, summary, now));
|
|
1053
|
+
emit(watcher, tracker, summary, findings);
|
|
1054
|
+
live.push([tracker, summary]);
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
if (options.tick > 0 && now - watcher.lastTick >= options.tick * 60_000) {
|
|
1058
|
+
watcher.lastTick = now;
|
|
1059
|
+
const count = (...phases) => live.filter(([, summary]) => phases.includes(summary.phase)).length;
|
|
1060
|
+
const other = live.length - count("starting", "running", "queued", "done");
|
|
1061
|
+
watcher.say("TICK", `watching ${live.length} · running ${count("starting", "running")} · queued ${count("queued")} · finished ${count("done")} · other ${other} · service ok`);
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
if (options.once) return done({ exit: 0 });
|
|
1065
|
+
if (!keepAlive && live.length === 0) {
|
|
1066
|
+
// 盯着的会话都被删掉了。
|
|
1067
|
+
watcher.say("INFO", "nothing left to watch; the watcher is exiting");
|
|
1068
|
+
return done({ exit: 0 });
|
|
1069
|
+
}
|
|
1070
|
+
if (!keepAlive && live.every(([tracker, summary]) => settledForExit(tracker, summary, now))) {
|
|
1071
|
+
watcher.say("INFO", `all ${live.length} watched session${live.length === 1 ? "" : "s"} ${live.length === 1 ? "has" : "have"} finished; the watcher is exiting`);
|
|
1072
|
+
return done({ exit: 0 });
|
|
1073
|
+
}
|
|
1074
|
+
return done({});
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
/**
|
|
1078
|
+
* 一次巡检。返回 `{ exit }` 表示该结束了(退出码),否则 `{}`。
|
|
1079
|
+
* --wake 时:这一遍之后若有 [DONE] / [ALERT],再等 --wake-batch 秒把同一时刻到的几条一并带上,补一行 [WAKE] 摘要,以退出码 10 退出。
|
|
1080
|
+
*/
|
|
1081
|
+
export async function pass(watcher) {
|
|
1082
|
+
const first = await scan(watcher);
|
|
1083
|
+
const { options } = watcher;
|
|
1084
|
+
if (!options.wake || first.exit !== undefined || watcher.waking.length === 0) return first;
|
|
1085
|
+
|
|
1086
|
+
let last = {};
|
|
1087
|
+
if (options.wakeBatch > 0) {
|
|
1088
|
+
await watcher.sleep(options.wakeBatch * 1000);
|
|
1089
|
+
last = await scan(watcher);
|
|
1090
|
+
}
|
|
1091
|
+
const finished = watcher.waking.filter((tag) => tag === "DONE").length;
|
|
1092
|
+
const attention = watcher.waking.length - finished;
|
|
1093
|
+
watcher.waking = [];
|
|
1094
|
+
const counts = [...(finished > 0 ? [`${finished} finished`] : []), ...(attention > 0 ? [`${attention} attention`] : [])].join(", ");
|
|
1095
|
+
const advice = `handle ${finished + attention === 1 ? "it" : "them"}, then start this watcher again with the same arguments`;
|
|
1096
|
+
const hint = options.state ? "" : "; pass --state <file> next time so a restart does not repeat what it already told you";
|
|
1097
|
+
watcher.say("WAKE", `${counts} — ${advice}${hint}.`);
|
|
1098
|
+
return { exit: last.exit ?? WAKE_EXIT };
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
// ───────────────────────── 入口 ─────────────────────────
|
|
1102
|
+
|
|
1103
|
+
const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
|
|
1104
|
+
|
|
1105
|
+
/** `deps` 与 createWatcher 的相同(测试用,比如换掉 sleep 与 now,就不必等真实的时间)。 */
|
|
1106
|
+
export async function main(argv, env = process.env, deps = {}) {
|
|
1107
|
+
const { options, errors } = parseArgs(argv);
|
|
1108
|
+
if (options.help) {
|
|
1109
|
+
process.stdout.write(`${USAGE}\n`);
|
|
1110
|
+
return 0;
|
|
1111
|
+
}
|
|
1112
|
+
if (errors.length > 0) {
|
|
1113
|
+
process.stderr.write(`${errors.join("\n")}\n\n${USAGE}\n`);
|
|
1114
|
+
return 2;
|
|
1115
|
+
}
|
|
1116
|
+
let rules = NO_RULES;
|
|
1117
|
+
if (options.rules) {
|
|
1118
|
+
try {
|
|
1119
|
+
rules = loadRules(options.rules);
|
|
1120
|
+
} catch (error) {
|
|
1121
|
+
process.stderr.write(`Cannot use --rules ${options.rules}: ${error.message}\n`);
|
|
1122
|
+
return 2;
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
if (options.state) {
|
|
1126
|
+
const problem = checkStatePath(options.state);
|
|
1127
|
+
if (problem) {
|
|
1128
|
+
process.stderr.write(`Cannot use --state ${options.state}: ${problem}\n`);
|
|
1129
|
+
return 2;
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
const watcher = createWatcher(options, { env, rules, ...deps });
|
|
1133
|
+
for (;;) {
|
|
1134
|
+
let result;
|
|
1135
|
+
try {
|
|
1136
|
+
result = await pass(watcher);
|
|
1137
|
+
} catch (error) {
|
|
1138
|
+
watcher.say("INFO", `a pass failed and was skipped: ${clip(error?.message ?? error, 160)}`);
|
|
1139
|
+
result = {};
|
|
1140
|
+
}
|
|
1141
|
+
if (result.exit !== undefined) return result.exit;
|
|
1142
|
+
await watcher.sleep(options.interval * 1000);
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
function runAsScript() {
|
|
1147
|
+
const entry = process.argv[1];
|
|
1148
|
+
if (!entry) return false;
|
|
1149
|
+
try {
|
|
1150
|
+
return realpathSync(entry) === realpathSync(fileURLToPath(import.meta.url));
|
|
1151
|
+
} catch {
|
|
1152
|
+
return false;
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
if (runAsScript()) {
|
|
1157
|
+
// 读输出的一方走了(管道关闭)就不必再盯了。
|
|
1158
|
+
process.stdout.on("error", () => process.exit(0));
|
|
1159
|
+
main(process.argv.slice(2)).then(
|
|
1160
|
+
async (code) => {
|
|
1161
|
+
// 等输出写完再退出;keep-alive 的连接会让进程多挂几秒,所以显式退出。
|
|
1162
|
+
await new Promise((done) => process.stdout.write("", done));
|
|
1163
|
+
process.exit(code);
|
|
1164
|
+
},
|
|
1165
|
+
(error) => {
|
|
1166
|
+
process.stderr.write(`watch.mjs: ${error?.message ?? error}\n`);
|
|
1167
|
+
process.exit(1);
|
|
1168
|
+
},
|
|
1169
|
+
);
|
|
1170
|
+
}
|