@saltpub/agent-autoloop 0.1.8 → 0.1.10

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 CHANGED
@@ -1,5 +1,26 @@
1
1
  # @saltpub/agent-autoloop
2
2
 
3
+ ## 0.1.10
4
+
5
+ ### Patch Changes
6
+
7
+ - 合并上游 15 个提交:
8
+
9
+ - 新增 `agent-autoloop wakeups`:按触发原因核对历史轮次、Agent 唤醒次数和用量
10
+ - 通道卡片带上 lane,通道可以把卡片发回事项来的地方
11
+ - 修复:回执事件的编号已被别的引用占用时不再报错;负责人可以结束一轮没人听过的事项;没人看见收尾的停止保留 worker 给的原因;超时的轮次不再谎报「已停止」
12
+ - 修复:布尔参数不再吞掉后面的位置参数,支持 `--flag=value`;`init` 收到非法端口不再留下半安装状态;`join` 收到无效中台地址不再留下坏配置
13
+ - 修复:`up` 拒绝从一轮 Agent 运行内部重启跑这轮的中台
14
+ - 修复(交付):慢的全量检查会等它完成而不是当成失败;只有还在跑的检查才会等到半点
15
+ - 性能:长历史下状态汇总更快;Windows 上 worker 用进程句柄检查自己启动的任务
16
+
17
+ ## 0.1.9
18
+
19
+ ### Patch Changes
20
+
21
+ - d7a8b22: 修好 0.1.8 装不上:`update` 把新版本装到 `versions/` 后会先试跑它,但新副本的 shim 把自己转手给了正在跑的旧版,试跑看到的版本号不对,于是报「起不来」并把新副本删掉。现在 `versions/` 下的受管副本一律运行自己,只有 npm 全局安装跟随指针。
22
+ - 6d1bbc6: `agent-autoloop update` 装好新版本(或新版本已经在等重启)时,列出这一版的更新内容,取自包里的 CHANGELOG,不再只显示一个版本号。
23
+
3
24
  ## 0.1.8
4
25
 
5
26
  ### Patch Changes
package/README.en.md CHANGED
@@ -95,7 +95,7 @@ External events work the same way once the source is connected. To hand new GitH
95
95
  }
96
96
  ```
97
97
 
98
- `agent-autoloop pause <rule>` and `resume <rule>` pause and resume one rule: while paused it skips its scheduled times and doesn't take or queue events, and a resume doesn't catch up on its own. A resume lists the events the pause skipped and prints `agent-autoloop replay <rule> --since <time>`, which hands them all to the rule at once, each only once. `agent-autoloop run <rule>` runs it once now. These are kept in the hub's log; `rules.json` is not changed. `agent-autoloop runs [rule]` lists finished rounds, `--before <round>` pages back, and `agent-autoloop why <round>` tells the full story of one.
98
+ `agent-autoloop pause <rule>` and `resume <rule>` pause and resume one rule: while paused it skips its scheduled times and doesn't take or queue events, and a resume doesn't catch up on its own. A resume lists the events the pause skipped and prints `agent-autoloop replay <rule> --since <time>`, which hands them all to the rule at once, each only once. `agent-autoloop run <rule>` runs it once now. These are kept in the hub's log; `rules.json` is not changed. `agent-autoloop runs [rule]` lists finished rounds, `--before <round>` pages back, and `agent-autoloop why <round>` tells the full story of one. `agent-autoloop wakeups [rule]` groups the last 100 rounds by rule and by what woke them (a recheck the agent booked, your answer, other events), with each group's round count, reported usage and a few round numbers, so a rule that keeps rechecking stands out.
99
99
 
100
100
  Changes take effect within seconds of saving. Run `agent-autoloop check` to validate, `agent-autoloop check <file>` to validate a draft without touching the running hub, `agent-autoloop rules explain [file]` to see the rules in effect and their next runs (a draft file too), and `agent-autoloop emit <type> --dry-run` to preview who an event would go to (it doesn't contact the hub or write to the log). If you make a mistake, or the file is deleted or can't be read, the hub keeps running the previous valid rules and sends you a card about it.
101
101
 
@@ -221,10 +221,10 @@ Apple M5 Pro, 24 GB, Node 24.21.0. Each write is a separate request, acknowledge
221
221
  | Durable writes | 2,394 events/s |
222
222
  | Dispatch p99 | 1.82 ms |
223
223
  | Held-back heartbeat p99 with 5,000 queued | 1.66 ms |
224
- | Startup at 1.1 million facts | 99.8 ms |
224
+ | Startup at 1.1 million facts | 112.3 ms |
225
225
  | Runtime dependencies | 0 |
226
226
 
227
- As history grows, the status summary slows down and the log and indexes keep using disk. The first start after a format change rebuilds from the log, which took 43.1 seconds for 1.1 million facts. [Full numbers and method](docs/protocol.md#历史增长实测) (in Chinese).
227
+ As history grows, the status summary slows down and the log and indexes keep using disk. The first start after a format change rebuilds from the log, which took 48.2 seconds for 1.1 million facts. [Full numbers and method](docs/protocol.md#历史增长实测) (in Chinese).
228
228
 
229
229
  ## Usage and provider terms
230
230
 
package/README.md CHANGED
@@ -93,7 +93,7 @@ Agent 结束了这一轮,问了你一个问题。它现在不占进程、不
93
93
  }
94
94
  ```
95
95
 
96
- `agent-autoloop pause <规则>`、`resume <规则>` 暂停和恢复一条规则,暂停期间到点不跑、来事件不接也不排队,恢复后不自动补跑;恢复时会列出暂停期间跳过的事件,照着给出的 `agent-autoloop replay <规则> --since <时间>` 一次补跑,每条只补一次。`agent-autoloop run <规则>` 立即跑一轮。这些记在中台的日志里,不改 `rules.json`。`agent-autoloop runs [规则]` 列出做完的轮次,`--before <第几轮>` 往前翻,拿到编号再用 `agent-autoloop why <第几轮>` 看来龙去脉。
96
+ `agent-autoloop pause <规则>`、`resume <规则>` 暂停和恢复一条规则,暂停期间到点不跑、来事件不接也不排队,恢复后不自动补跑;恢复时会列出暂停期间跳过的事件,照着给出的 `agent-autoloop replay <规则> --since <时间>` 一次补跑,每条只补一次。`agent-autoloop run <规则>` 立即跑一轮。这些记在中台的日志里,不改 `rules.json`。`agent-autoloop runs [规则]` 列出做完的轮次,`--before <第几轮>` 往前翻,拿到编号再用 `agent-autoloop why <第几轮>` 看来龙去脉。`agent-autoloop wakeups [规则]` 把最近 100 轮按规则和叫醒原因(约好的复查、你的回答、别的事件)分组,列出每组的轮数、已上报的用量和几个轮次编号,方便看出哪条规则在反复复查。
97
97
 
98
98
  保存后几秒内自动生效,可以运行 `agent-autoloop check` 检查,`agent-autoloop check <文件>` 检查一份草稿,不碰正在跑的中台;`agent-autoloop rules explain [文件]` 看生效的规则和下次定时(也可以指定一份草稿),`agent-autoloop emit <类型> --dry-run` 预演一条事件会派给谁(不连接中台、不写日志)。就算改错了,或者文件被删、读不到,系统也会继续按旧规则跑,并发卡片提醒你。
99
99
 
@@ -218,10 +218,10 @@ Apple M5 Pro、24 GB、Node 24.21.0。写入逐条提交,事务落盘后才应
218
218
  | 持久化写入 | 2394 条/秒 |
219
219
  | 派活 p99 | 1.82 ms |
220
220
  | 排队 5000 时被挡下的心跳 p99 | 1.66 ms |
221
- | 110 万条事实时的启动 | 99.8 ms |
221
+ | 110 万条事实时的启动 | 112.3 ms |
222
222
  | 运行时依赖 | 0 |
223
223
 
224
- 历史变大后,状态汇总会变慢,日志和索引也继续占磁盘;格式变化后的首次启动要从日志全量重建,110 万条用时 43.1 秒。[完整数据和测法](docs/protocol.md#历史增长实测)。
224
+ 历史变大后,状态汇总会变慢,日志和索引也继续占磁盘;格式变化后的首次启动要从日志全量重建,110 万条用时 48.2 秒。[完整数据和测法](docs/protocol.md#历史增长实测)。
225
225
 
226
226
  ## 用量与合规说明
227
227
 
@@ -2,7 +2,8 @@
2
2
  // AGENT_AUTOLOOP_SHIM_V1 — version shim, rustup-style. The npm global install resolves the self-update pointer and
3
3
  // re-runs the versioned copy, so a command follows the version the hub runs after an update instead of the stale
4
4
  // global package. Every failure mode (no pointer, corrupt JSON, missing target, a pointer naming this very
5
- // install, a git checkout) falls back to this package's own CLI — the behaviour before the shim.
5
+ // install, a git checkout, a copy the updater unpacked under versions/) falls back to this package's own CLI —
6
+ // the behaviour before the shim.
6
7
  import { spawn } from "node:child_process";
7
8
  import { existsSync, readFileSync } from "node:fs";
8
9
  import { homedir } from "node:os";
@@ -14,6 +15,10 @@ const ROOT = COMPILED ? path.dirname(path.dirname(HERE)) : path.dirname(HERE);
14
15
  const HOME = process.env.AGENT_AUTOLOOP_HOME?.trim() || path.join(homedir(), ".agent-autoloop");
15
16
  /** The managed copy's entry, or undefined to fall back to this package. */
16
17
  function pointedEntry() {
18
+ // A copy the updater unpacked under versions/ runs as itself: the trial run checks this very version, and the
19
+ // launcher names the copy to start. Only an install outside versions/ (the npm global one) follows the pointer.
20
+ if (path.resolve(ROOT).startsWith(`${path.resolve(path.join(HOME, "versions"))}${path.sep}`))
21
+ return undefined;
17
22
  let pointer;
18
23
  try {
19
24
  pointer = JSON.parse(readFileSync(path.join(HOME, "update", "current.json"), "utf8"));
package/dist/cli/main.js CHANGED
@@ -7,7 +7,7 @@ import path from "node:path";
7
7
  import { createInterface } from "node:readline/promises";
8
8
  import { hubClient } from "../protocol/client.js";
9
9
  import { parseRules } from "../protocol/rules.js";
10
- import { CONFIG_FILE, readConfig, writeConfig } from "../host/config.js";
10
+ import { CONFIG_FILE, parseListen, readConfig, writeConfig } from "../host/config.js";
11
11
  import { HOME, RULES_FILE } from "../host/home.js";
12
12
  import { findOnPath, psQuote } from "../host/command.js";
13
13
  import { privateDirectory } from "../host/files.js";
@@ -185,6 +185,7 @@ rules.json 里这个定时任务要写 cwd;你答了,中台叫醒它的 Agen
185
185
  },
186
186
  rules: { flags: [], usage: "用法:agent-autoloop rules explain [文件]" },
187
187
  runs: { flags: ["before", "json"], usage: RUNS_USAGE },
188
+ wakeups: { flags: ["limit", "json"], usage: "用法:agent-autoloop wakeups [规则] [--limit 正整数] [--json]" },
188
189
  run: { flags: ["subject", "reason"], usage: "用法:agent-autoloop run <规则> [--subject 对象] [--reason 说明]" },
189
190
  service: { flags: [], usage: "用法:agent-autoloop service install|remove" },
190
191
  dashboard: { flags: ["port", "no-open", "stop"], usage: DASHBOARD_USAGE },
@@ -197,6 +198,7 @@ rules.json 里这个定时任务要写 cwd;你答了,中台叫醒它的 Agen
197
198
  update: { flags: [], usage: UPDATE_USAGE },
198
199
  why: { flags: ["json"], usage: "用法:agent-autoloop why <第几轮> [--json]" },
199
200
  };
201
+ const BOOLEAN_FLAGS = new Set(["dry-run", "json", "no-service", "yes"]);
200
202
  function flags(args) {
201
203
  const named = {};
202
204
  const rest = [];
@@ -205,8 +207,15 @@ function flags(args) {
205
207
  rest.push(args[i]);
206
208
  continue;
207
209
  }
210
+ const eq = args[i].indexOf("=", 2);
211
+ if (eq !== -1) {
212
+ named[args[i].slice(2, eq)] = args[i].slice(eq + 1);
213
+ continue;
214
+ }
208
215
  const name = args[i].slice(2);
209
- if (args[i + 1] !== undefined && !args[i + 1].startsWith("--"))
216
+ if (BOOLEAN_FLAGS.has(name))
217
+ named[name] = true;
218
+ else if (args[i + 1] !== undefined && !args[i + 1].startsWith("--"))
210
219
  named[name] = args[++i];
211
220
  else
212
221
  named[name] = true;
@@ -227,9 +236,13 @@ function refuseUnknownFlags(args, { flags: known, usage }) {
227
236
  console.log(usage);
228
237
  process.exit(0);
229
238
  }
230
- const unknown = Object.keys(flags(args).named).filter((name) => !known.includes(name));
239
+ const { named } = flags(args);
240
+ const unknown = Object.keys(named).filter((name) => !known.includes(name));
231
241
  if (unknown.length)
232
242
  fail(`不认识的参数:${unknown.map((name) => `--${name}`).join("、")}\n\n${usage}`);
243
+ const badBool = Object.entries(named).find(([name, value]) => BOOLEAN_FLAGS.has(name) && value !== true);
244
+ if (badBool)
245
+ fail(`--${badBool[0]} 不接参数值\n\n${usage}`);
233
246
  }
234
247
  const client = (key, config = readConfig()) => hubClient(config.url, key);
235
248
  const ownerClient = (config = readConfig()) => client(config.owner ?? fail("这台电脑上没有本人的密钥(只接活的电脑看不了)"), config);
@@ -375,6 +388,16 @@ async function init(args) {
375
388
  if (existsSync(CONFIG_FILE))
376
389
  return fail(`已经装过了:${CONFIG_FILE}\n` +
377
390
  `重装程序后接着用原来的规则和记录,运行 ${howToRun()} service install;要从头配,先删掉这个文件再运行 init。`);
391
+ if (named.port === true)
392
+ return fail(INIT_USAGE);
393
+ const portText = text(named.port) ?? "3350";
394
+ let port;
395
+ try {
396
+ port = parseListen(`127.0.0.1:${portText}`).port;
397
+ }
398
+ catch {
399
+ return fail(`--port 要写 1 到 65535 之间的整数端口:${portText}`);
400
+ }
378
401
  privateDirectory(HOME);
379
402
  mkdirSync(path.join(HOME, "try"), { recursive: true });
380
403
  const hostName = hostname()
@@ -386,7 +409,6 @@ async function init(args) {
386
409
  return fail(`这台电脑上没找到能用的命令行 Agent(${AGENT_TITLES})。先装好并登录,` +
387
410
  "或者用 --command 指定别的命令行 Agent,比如 --command 'hermes chat -Q -q {prompt}'");
388
411
  }
389
- const port = text(named.port) ?? "3350";
390
412
  const url = `http://127.0.0.1:${port}`;
391
413
  const ownRules = !existsSync(RULES_FILE);
392
414
  if (ownRules) {
@@ -438,6 +460,21 @@ async function join(args) {
438
460
  const key = text(named.key);
439
461
  if (!url || !name || !key)
440
462
  return fail(TAKES.join.usage);
463
+ const badAddress = "中台地址要写完整的 http:// 或 https:// 地址,不能带账号、查询参数或片段";
464
+ let address;
465
+ try {
466
+ address = new URL(url);
467
+ }
468
+ catch {
469
+ return fail(badAddress);
470
+ }
471
+ if (!["http:", "https:"].includes(address.protocol) ||
472
+ address.username ||
473
+ address.password ||
474
+ address.search ||
475
+ address.hash) {
476
+ return fail(badAddress);
477
+ }
441
478
  // Joining another hub must not silently replace this machine's existing hub, worker or owner keys.
442
479
  if (existsSync(CONFIG_FILE)) {
443
480
  return fail(`已经配置过了:${CONFIG_FILE}。为防止覆盖现有设置,请先备份并手动修改配置。`);
@@ -611,6 +648,15 @@ async function runs(args) {
611
648
  const color = colorFor(process.stdout, process.env);
612
649
  console.log(runsText(found, { rule: rest[0], color, columns: process.stdout.columns }));
613
650
  }
651
+ async function wakeups(args) {
652
+ const { named, rest } = flags(args);
653
+ if (rest.length > 1 || named.limit === true)
654
+ return fail(TAKES.wakeups.usage);
655
+ const limit = named.limit === undefined ? 100 : runOf(named.limit, TAKES.wakeups.usage);
656
+ const { wakeupReport, wakeupText } = await import("./wakeups.js");
657
+ const report = await wakeupReport(ownerClient(), rest[0], limit);
658
+ console.log(named.json ? JSON.stringify(report, null, 2) : wakeupText(report));
659
+ }
614
660
  async function answer(args) {
615
661
  const { named, rest } = flags(args);
616
662
  const card = Number(rest[0]);
@@ -948,9 +994,12 @@ function runOf(word, usage) {
948
994
  return id;
949
995
  }
950
996
  async function why(args) {
951
- const id = runOf(args.find((arg) => !arg.startsWith("--")), "用法:agent-autoloop why <第几轮> [--json]");
997
+ const { named, rest } = flags(args);
998
+ if (rest.length !== 1)
999
+ return fail(TAKES.why.usage);
1000
+ const id = runOf(rest[0], TAKES.why.usage);
952
1001
  const facts = await ownerClient().why(id);
953
- if (args.includes("--json"))
1002
+ if (named.json !== undefined)
954
1003
  return console.log(JSON.stringify(facts, null, 2));
955
1004
  const { formatWhy } = await import("./why.js");
956
1005
  console.log(formatWhy(id, facts));
@@ -1078,8 +1127,12 @@ async function update() {
1078
1127
  const result = stageLatest();
1079
1128
  if (result.status === "current")
1080
1129
  return console.log(`已经是最新的(v${result.version})。`);
1081
- if (result.status === "pending")
1082
- return console.log(`v${result.version} 已经准备好,中台重启时换上。`);
1130
+ if (result.status === "pending") {
1131
+ console.log(`v${result.version} 已经准备好,中台重启时换上。`);
1132
+ for (const note of result.notes)
1133
+ console.log(`- ${note}`);
1134
+ return;
1135
+ }
1083
1136
  if (result.status === "bad")
1084
1137
  return fail(`v${result.version} 之前启动失败过,先不装它;修好后删掉 ${path.join(HOME, "update", "bad.json")} 再试。`);
1085
1138
  if (result.status === "busy")
@@ -1091,6 +1144,8 @@ async function update() {
1091
1144
  if (told === undefined && service)
1092
1145
  await waitForHub();
1093
1146
  console.log(`更新好了(v${result.version})。${told ?? (service ? "" : "下次启动中台时换上。")}`);
1147
+ for (const note of result.notes)
1148
+ console.log(`- ${note}`);
1094
1149
  }
1095
1150
  async function askAtTerminal(question) {
1096
1151
  const terminal = createInterface({ input: process.stdin, output: process.stdout });
@@ -1110,6 +1165,7 @@ const commands = {
1110
1165
  status: () => status(flags(args).named),
1111
1166
  why: () => why(args),
1112
1167
  runs: () => runs(args),
1168
+ wakeups: () => wakeups(args),
1113
1169
  conformance: () => checkConformance(args),
1114
1170
  answer: () => answer(args),
1115
1171
  resolve: () => resolve(args),
@@ -0,0 +1,106 @@
1
+ import { readRuns } from "./runs.js";
2
+ const labels = { recheck: "到期复查", answer: "人工回答", mixed: "多种触发", other: "其他触发", unknown: "来源未明" };
3
+ async function causeOf(owner, run) {
4
+ if (!run.events?.length)
5
+ return "unknown";
6
+ // The history API shows at most 20 events. A full page may hide a trigger of a different kind.
7
+ if (run.events.length < 20 && run.events.every((e) => e.type !== "timer.due" && e.type !== "card.answered"))
8
+ return "other";
9
+ // Sources can use the same event type names. Only an actual timer or decision proves who woke the run.
10
+ const facts = await owner.why(run.id);
11
+ const links = new Map();
12
+ const causes = new Map();
13
+ for (const fact of facts) {
14
+ for (const { table, key, row } of fact.changes) {
15
+ if (table === "run_events") {
16
+ if (row?.run_id === run.id)
17
+ links.set(key, row.event_id);
18
+ if (!row)
19
+ links.delete(key);
20
+ }
21
+ if (table === "events" && row && !causes.has(row.id))
22
+ causes.set(row.id, "other");
23
+ if (table === "timers" && row?.event_id != null)
24
+ causes.set(row.event_id, "recheck");
25
+ if (table === "cards" && row?.answer_event != null)
26
+ causes.set(row.answer_event, "answer");
27
+ }
28
+ }
29
+ const kinds = new Set([...links.values()].map((id) => causes.get(id) ?? "unknown"));
30
+ if (kinds.size === 1)
31
+ return [...kinds][0];
32
+ return kinds.size ? "mixed" : "unknown";
33
+ }
34
+ const measure = () => ({ sum: 0, reported: 0 });
35
+ function add(total, value) {
36
+ if (value === undefined || value === null)
37
+ return;
38
+ total.sum += value;
39
+ total.reported++;
40
+ }
41
+ function newGroup(rule, cause) {
42
+ return {
43
+ rule,
44
+ cause,
45
+ rounds: 0,
46
+ withFailures: 0,
47
+ examples: [],
48
+ input: measure(),
49
+ cached: measure(),
50
+ uncachedInput: measure(),
51
+ output: measure(),
52
+ cost: measure(),
53
+ };
54
+ }
55
+ export async function wakeupReport(owner, rule, limit) {
56
+ const groups = new Map();
57
+ let examined = 0;
58
+ let excluded = 0;
59
+ let before;
60
+ let hasMore = false;
61
+ while (examined < limit) {
62
+ const page = await readRuns(owner, rule, before);
63
+ const batch = page.runs.slice(0, limit - examined);
64
+ for (const run of batch) {
65
+ examined++;
66
+ if (!run.finishedAt || (!run.claimedAt && !run.usage && !run.attempts)) {
67
+ excluded++;
68
+ continue;
69
+ }
70
+ const cause = await causeOf(owner, run);
71
+ const key = JSON.stringify([run.rule, cause]);
72
+ const group = groups.get(key) ?? newGroup(run.rule, cause);
73
+ groups.set(key, group);
74
+ group.rounds++;
75
+ if (run.attempts > 0)
76
+ group.withFailures++;
77
+ if (group.examples.length < 3)
78
+ group.examples.push(run.id);
79
+ const u = run.usage ?? {};
80
+ add(group.input, u.input);
81
+ add(group.cached, u.cached);
82
+ // Older adapters could report input excluding cache reads.
83
+ if (u.input != null && u.cached != null && u.input >= u.cached)
84
+ add(group.uncachedInput, u.input - u.cached);
85
+ add(group.output, u.output);
86
+ add(group.cost, u.cost);
87
+ }
88
+ hasMore = batch.length < page.runs.length || page.more != null;
89
+ if (page.more == null || examined >= limit)
90
+ break;
91
+ before = page.more;
92
+ }
93
+ return { examined, excluded, hasMore, groups: [...groups.values()] };
94
+ }
95
+ export function wakeupText(report) {
96
+ const lines = [
97
+ `查看了 ${report.examined} 条历史,排除未结束或未执行的 ${report.excluded} 条。${report.hasMore ? "还有更早的历史,可增大 --limit。" : ""}`,
98
+ ];
99
+ for (const group of report.groups) {
100
+ const show = (m) => (m.reported ? `${m.sum}(${m.reported}/${group.rounds} 轮上报)` : "未上报");
101
+ lines.push(`${group.rule} · ${labels[group.cause]} · ${group.rounds} 轮,其中有过失败的 ${group.withFailures} 轮`, ` 输入 ${show(group.input)},其中缓存读取 ${show(group.cached)};未缓存输入 ${show(group.uncachedInput)},输出 ${show(group.output)},费用 ${show(group.cost)}`, ` 核对轮次:${group.examples.map((id) => "#" + id).join("、")}`);
102
+ if (group.cause === "recheck" && group.rounds > 1)
103
+ lines.push(" 多次到期复查。用 why 核对事项和外部状态是否变化,再决定是否改用脚本探测。");
104
+ }
105
+ return lines.join("\n");
106
+ }
package/dist/cli/why.js CHANGED
@@ -46,7 +46,9 @@ export function formatWhy(id, facts) {
46
46
  if (row.link && row.link === links.get(row.issued) && row.link !== before?.link)
47
47
  add(fact.at, `会话:${row.link}`);
48
48
  if (row.finished_at && row.finished_at !== before?.finished_at) {
49
- add(row.finished_at, `结束:${row.summary || (row.state === "cancelled" ? "已停止" : "没有填写结论")}`);
49
+ add(row.finished_at,
50
+ // An error that came with this end is its reason; one left from an earlier attempt was told when it came.
51
+ `结束:${row.summary || (row.error !== before?.error && row.error) || (row.state === "cancelled" ? "已停止" : "没有填写结论")}`);
50
52
  }
51
53
  if (receipt && row.state === "queued" && row.attempts !== before?.attempts) {
52
54
  add(fact.at, `本次未完成:${row.error};重试时间 ${time(row.not_before)}`);
@@ -48,10 +48,20 @@ const format = digest([`../kernel/evolve${COMPILED ? ".js" : ".ts"}`, `../kernel
48
48
  digest(environment.secret));
49
49
  let current = openView(db, format);
50
50
  db.exec(CARD_HASH_INDEX);
51
- // Only the history reader needs this index. Adding it to an existing projection doesn't require replaying the log.
52
- db.exec(`CREATE INDEX IF NOT EXISTS projection_run_history
53
- ON projections(collection, json_extract(data,'$.rule'), json_extract(data,'$.id'))
54
- WHERE collection='runs'`);
51
+ // These indexes serve the host's read queries. SQLite can build them from an existing projection without replaying facts.
52
+ db.exec(`
53
+ CREATE INDEX IF NOT EXISTS projection_run_history
54
+ ON projections(collection, json_extract(data,'$.rule'), json_extract(data,'$.id'))
55
+ WHERE collection='runs';
56
+ CREATE INDEX IF NOT EXISTS projection_run_counts
57
+ ON projections(collection, json_extract(data,'$.rule'), json_extract(data,'$.agent'), json_extract(data,'$.state'),
58
+ json_extract(data,'$.attempts'), json_extract(data,'$.finished_at'), json_extract(data,'$.usage'))
59
+ WHERE collection='runs';
60
+ CREATE INDEX IF NOT EXISTS projection_run_spending
61
+ ON projections(collection, json_extract(data,'$.finished_at'), json_extract(data,'$.claimed_at'),
62
+ json_extract(data,'$.usage'))
63
+ WHERE collection='runs';
64
+ `);
55
65
  export const all = (sql, params = []) => db
56
66
  .prepare(sql)
57
67
  .all(...params)
@@ -43,8 +43,8 @@ export function startupShortcut(folder = "[Environment]::GetFolderPath('Startup'
43
43
  }
44
44
  /** For an account that can't, or shouldn't, have the login task: the desktop starts it, with the desktop's rights. */
45
45
  export const startupInstead = () => "可以改用「启动」文件夹:在 PowerShell 里运行下面这行,以后登录时由桌面以普通权限拉起中台,退出后照样自动重启," +
46
- "现在注销再登录一次就开始跑。这样起的中台不算系统服务:doctor 会说服务没在跑;再运行 `agent-autoloop service install` 会去建登录任务," +
47
- "想继续用「启动」文件夹就别运行它;更新之后注销再登录一次才用上新版。\n\n" +
46
+ "现在注销再登录一次就开始跑。这样起的中台不算系统服务:doctor 会说服务没在跑;重新运行安装器更新时加 --no-service," +
47
+ "不然它又去建登录任务;更新之后结束数据目录里 up.pid 记着的进程,十秒后就用上新版(注销再登录也行)。\n\n" +
48
48
  startupShortcut();
49
49
  function installWindowsService() {
50
50
  const { program, args, directory } = windowsLauncher();
package/dist/host/up.js CHANGED
@@ -82,6 +82,14 @@ function startAutoUpdate(say, switchOut) {
82
82
  void check();
83
83
  }
84
84
  export async function up() {
85
+ // Everything an Agent starts belongs to its turn: Windows ends the turn's job when the turn ends, and Unix signals the
86
+ // whole process group when it stops one. Restarting the hub that runs the turn from inside it would take that hub along.
87
+ // A throwaway hub on another home, as tests and acceptance runs start, goes with the turn as it should.
88
+ const { AGENT_AUTOLOOP_RUN: run, AGENT_AUTOLOOP_CONTEXT: context } = process.env;
89
+ const turn = run && context ? path.relative(HOME, context) : "";
90
+ if (turn && !turn.startsWith("..") && !path.isAbsolute(turn))
91
+ throw new Error(`这是在第 ${run} 轮 Agent 里启动这个中台:这一轮结束或被停掉时,中台可能跟着一起结束,通道也会断。` +
92
+ `要重启:装了登录服务的运行 agent-autoloop service install;用「启动」文件夹的,结束 ${path.join(HOME, "up.pid")} 里记着的进程,十秒后会自动用新代码拉起;都没有的,请本人在自己的登录会话里启动。`);
85
93
  const config = readConfig();
86
94
  mkdirSync(HOME, { recursive: true, mode: 0o700 });
87
95
  const unlock = lock();
@@ -63,6 +63,28 @@ export function readPending(home = HOME) {
63
63
  return null;
64
64
  return pending;
65
65
  }
66
+ /** The bullets this version's CHANGELOG section lists, commit hashes stripped. [] when there is nothing to show. */
67
+ export function releaseNotes(dir, version) {
68
+ let changelog;
69
+ try {
70
+ changelog = readFileSync(path.join(dir, "CHANGELOG.md"), "utf8");
71
+ }
72
+ catch {
73
+ return [];
74
+ }
75
+ const notes = [];
76
+ let inside = false;
77
+ for (const line of changelog.split("\n")) {
78
+ if (line.startsWith("## ")) {
79
+ inside = line.trimEnd() === `## ${version}`;
80
+ continue;
81
+ }
82
+ const bullet = /^- (?:[0-9a-f]{7,}: )?(.+?)\s*$/.exec(line.trimStart());
83
+ if (inside && bullet)
84
+ notes.push(bullet[1]);
85
+ }
86
+ return notes;
87
+ }
66
88
  export function managedAt(home = HOME) {
67
89
  return readPointer(home) !== null && existsSync(launcherFile(home));
68
90
  }
@@ -250,8 +272,10 @@ export function stageLatest(home = HOME) {
250
272
  return { status: "current", version: pointer.version };
251
273
  if (badVersions(home).includes(latest))
252
274
  return { status: "bad", version: latest };
253
- if (readPending(home)?.version === latest)
254
- return { status: "pending", version: latest };
275
+ const waiting = readPending(home);
276
+ if (waiting?.version === latest) {
277
+ return { status: "pending", version: latest, notes: releaseNotes(waiting.dir, latest) };
278
+ }
255
279
  const lock = acquireLock(home);
256
280
  if (!lock)
257
281
  return { status: "busy" };
@@ -273,7 +297,7 @@ export function stageLatest(home = HOME) {
273
297
  throw new Error(`${PACKAGE}@${latest} 起不来:${done.stderr?.trim() || done.stdout?.trim() || done.error}`);
274
298
  }
275
299
  writeJson(pendingFile(home), { version: latest, dir, at: Date.now() });
276
- return { status: "staged", version: latest };
300
+ return { status: "staged", version: latest, notes: releaseNotes(dir, latest) };
277
301
  }
278
302
  catch (error) {
279
303
  rmSync(prefix, { recursive: true, force: true });
@@ -436,6 +436,7 @@ function scheduleReview(draft, run, later) {
436
436
  const source = sourceOf(draft.view, run.id) ?? SCHEDULE;
437
437
  add(draft, "timers", { ...fields, rule, lane, key: later.key, source, event_id: null, created_at: draft.at });
438
438
  }
439
+ const sameEvent = (kept, sent) => ["type", "subject", "summary", "detail", "link"].every((field) => kept[field] === (sent[field] ?? ""));
439
440
  /** A receipt takes effect here, all of it in the one fact. */
440
441
  function applyReceipt(draft, run, result) {
441
442
  const { id } = run;
@@ -471,8 +472,11 @@ function applyReceipt(draft, run, result) {
471
472
  if (rule?.emits && typeMatches(rule.emits.types, event.type)) {
472
473
  const sent = ingest(draft, rule.emits.source, { ...event, hops: hopsOf(draft, run) + 1 });
473
474
  // A number already taken is an earlier event's, perhaps another source's: what it says isn't what this receipt sent.
475
+ // Sending the same thing again under its fixed number is how sources stay idempotent, so only a clash is told.
474
476
  if (!sent.duplicate)
475
477
  emitted.push(sent.event);
478
+ else if (!sameEvent(draft.view.get("events", sent.event), event))
479
+ rejected.push({ what: "events", reason: `事件「${event.id}」这个编号已经记过另一件事,这次没有记` });
476
480
  }
477
481
  else
478
482
  rejected.push({ what: "events", reason: `规则「${run.rule}」没有写可以发 ${event.type}` });
@@ -502,10 +506,13 @@ function finish(draft, id, token, given) {
502
506
  let rejected = [];
503
507
  // Told to stop, one that failed first has stopped all the same: trying again would start what the owner ended.
504
508
  if (result.outcome === "cancelled" || (result.outcome === "failed" && run.cancel_at)) {
509
+ // A failure here is the worker saying it couldn't see the stop finish: that, not "stopped", is what happened.
510
+ const error = result.outcome === "failed" ? result.error?.trim().replace(/[。.]+$/, "") : undefined;
505
511
  put(draft, "runs", id, {
506
512
  state: "cancelled",
507
513
  finished_at: draft.at,
508
514
  summary: result.summary ?? "",
515
+ ...(error ? { error } : {}),
509
516
  cancel_at: null,
510
517
  });
511
518
  clearFiredTimers(draft, run);
@@ -593,7 +600,11 @@ function nextCard(draft, channel) {
593
600
  }
594
601
  const attempt = { tries: delivery.tries + 1, first_try_at: firstTry ?? draft.at, not_before: iso(now + MINUTE) };
595
602
  put(draft, "deliveries", key, { card_id: card.id, channel, ...attempt });
596
- return cardView(card, draft.env, delivery.ref, draft.rules.channels[channel]?.links === true);
603
+ // The lane lets a channel send the card back to where its matter came from; the card page doesn't get it.
604
+ return {
605
+ ...cardView(card, draft.env, delivery.ref, draft.rules.channels[channel]?.links === true),
606
+ lane: card.lane,
607
+ };
597
608
  }
598
609
  return null;
599
610
  }
@@ -862,6 +873,18 @@ const HANDLERS = {
862
873
  }
863
874
  else if (run.state === "claimed")
864
875
  put(draft, "runs", id, { cancel_at: draft.at });
876
+ // No worker reports this round any more, so there is no process a stop could reach and nothing to wait for: the owner
877
+ // ending it is the whole of it. The summary says it went quiet rather than that it stopped, which nobody knows.
878
+ else if (run.state === "unknown") {
879
+ put(draft, "runs", id, {
880
+ state: "cancelled",
881
+ finished_at: draft.at,
882
+ summary: "本人停掉:这一轮早已没有回音",
883
+ cancel_at: null,
884
+ });
885
+ clearFiredTimers(draft, run);
886
+ closeStopped(draft, id, "本人不再等了");
887
+ }
865
888
  else
866
889
  throw new InputError("这一轮已经结束了");
867
890
  },
@@ -10,6 +10,14 @@ export class DeliveryRefusal extends Error {
10
10
  }
11
11
  export class DeliverySuperseded extends Error {
12
12
  }
13
+ /** GitHub has the full check and it is going: only GitHub's own time limits end it, so outlasting a round isn't a failure. */
14
+ export class ChecksStillRunning extends Error {
15
+ head;
16
+ constructor(head, waited) {
17
+ super(waited instanceof Error ? waited.message : String(waited), { cause: waited });
18
+ this.head = head;
19
+ }
20
+ }
13
21
  const FINDINGS = "审查发现问题,修复后推新提交才会重审";
14
22
  const STALL = 10 * 60_000;
15
23
  const labels = (pr) => new Set((pr.labels ?? []).map((label) => label.name));
@@ -368,7 +376,16 @@ export async function deliver(repo, number, io, testLocalHealth = false) {
368
376
  throw new Error("尚未确认合并,稍后继续核实");
369
377
  }
370
378
  }
371
- await io.wait();
379
+ try {
380
+ await io.wait();
381
+ }
382
+ catch (error) {
383
+ // A finished run waits too when its required job was skipped or isn't there; only one still going ends on its own.
384
+ const going = state === "waiting" ? await newestCheck(head, config, io) : undefined;
385
+ if (going && going.id > after && going.status !== "completed")
386
+ throw new ChecksStillRunning(head, error);
387
+ throw error;
388
+ }
372
389
  }
373
390
  }
374
391
  catch (error) {
@@ -6,6 +6,8 @@ import { setTimeout } from "node:timers/promises";
6
6
  import { git, liveRelease, releaseRequired, REPO } from "./project.js";
7
7
  import { readSharedPolicy, reviewDelivery } from "./review.js";
8
8
  const LONGEST_WAIT = 1800000;
9
+ // Several deliveries share one account's 5,000 requests an hour, and a check loop asks three things each time round.
10
+ const POLL = 30_000;
9
11
  class GitHubHiccup extends Error {
10
12
  }
11
13
  export function isGitHubHiccup(error) {
@@ -195,7 +197,7 @@ export function createIO(repo, folder, options = {}) {
195
197
  async wait() {
196
198
  if (Date.now() - started > LONGEST_WAIT)
197
199
  throw new Error("等待超过半小时,保留远端状态,稍后继续核实");
198
- await setTimeout(5000);
200
+ await setTimeout(POLL);
199
201
  },
200
202
  };
201
203
  }
@@ -16,11 +16,23 @@ export function retryState(timers) {
16
16
  const saved = timers.find((timer) => timer.key === retryKey)?.about;
17
17
  return saved ? JSON.parse(saved) : undefined;
18
18
  }
19
- export function retryHandoff(timers, head, hiccup, now = Date.now(), canReturn = true, checkRecovery) {
19
+ function carried(timers, head, checkRecovery) {
20
20
  const previous = retryState(timers);
21
21
  const count = previous?.head === head ? previous : { head, github: 0, execution: 0 };
22
22
  if (checkRecovery?.head === head)
23
23
  count.checkAfter = checkRecovery.after;
24
+ return count;
25
+ }
26
+ /** A full check still going isn't a failed try: look again in a minute with the counts as they were. */
27
+ export function waitHandoff(timers, head, now = Date.now(), checkRecovery) {
28
+ return {
29
+ key: retryKey,
30
+ at: new Date(now + retryInterval).toISOString(),
31
+ about: JSON.stringify(carried(timers, head, checkRecovery)),
32
+ };
33
+ }
34
+ export function retryHandoff(timers, head, hiccup, now = Date.now(), canReturn = true, checkRecovery) {
35
+ const count = carried(timers, head, checkRecovery);
24
36
  const kind = hiccup ? "github" : "execution";
25
37
  const limit = hiccup ? 60 : 5;
26
38
  count[kind] = Math.min(count[kind] + 1, limit);
@@ -5,9 +5,10 @@ import { join } from "node:path";
5
5
  import { setTimeout } from "node:timers/promises";
6
6
  import { parseArgs } from "node:util";
7
7
  import { createIO, gh, isGitHubHiccup } from "./github.js";
8
- import { deliver, DeliveryRefusal, DeliverySuperseded, disableAuto, status } from "./delivery.js";
8
+ import { ChecksStillRunning, deliver, DeliveryRefusal, DeliverySuperseded, disableAuto, status, } from "./delivery.js";
9
9
  import { deliveryReceipt, question, receiptBlock, subjectNumber } from "./input.js";
10
- import { hasLabel, retryHandoff, retryState, runHook, tellQuestion, tellReturn, unattendedFailure } from "./handoff.js";
10
+ import { hasLabel, retryHandoff, retryState, runHook, tellQuestion, tellReturn, unattendedFailure, waitHandoff, } from "./handoff.js";
11
+ const STILL_RUNNING = "完整检查还在跑,一分钟后接着等";
11
12
  async function handoff(repo, number, context, io, options, testLocalHealth) {
12
13
  const timers = context.timers ?? [];
13
14
  const previous = retryState(timers);
@@ -73,6 +74,10 @@ async function handoff(repo, number, context, io, options, testLocalHealth) {
73
74
  catch (error) {
74
75
  if (error instanceof DeliverySuperseded)
75
76
  return { text: error.message, exit: 2 };
77
+ if (error instanceof ChecksStillRunning) {
78
+ await io.report?.("retrying", error.head, { detail: "checks" });
79
+ return { text: STILL_RUNNING, retry: waitHandoff(timers, error.head, Date.now(), io.checkRecovery) };
80
+ }
76
81
  if (error instanceof DeliveryRefusal) {
77
82
  head = error.head ?? head;
78
83
  try {
@@ -158,6 +163,8 @@ export async function run(repo, context, testLocalHealth = false, options = {})
158
163
  catch (error) {
159
164
  if (error instanceof DeliverySuperseded)
160
165
  return error.message;
166
+ if (error instanceof ChecksStillRunning)
167
+ return `${STILL_RUNNING}\n${receiptBlock({ later: [waitHandoff([], error.head)] })}`;
161
168
  const pr = await io.api(`pulls/${number}`);
162
169
  if (pr.auto_merge)
163
170
  await disableAuto(number, io);
@@ -632,6 +632,12 @@
632
632
  },
633
633
  "link": {
634
634
  "type": ["string", "null"]
635
+ },
636
+ "rule": {
637
+ "type": ["string", "null"]
638
+ },
639
+ "lane": {
640
+ "type": "string"
635
641
  }
636
642
  },
637
643
  "required": [
@@ -82,9 +82,11 @@ async function alive(entry) {
82
82
  return null;
83
83
  }
84
84
  }
85
- function signal(entry, name) {
85
+ function signal(entry, name, child) {
86
86
  try {
87
- if (entry.pid)
87
+ if (child)
88
+ child.kill(name);
89
+ else if (entry.pid)
88
90
  process.kill(process.platform === "win32" ? entry.pid : -entry.pid, name);
89
91
  }
90
92
  catch { }
@@ -145,6 +147,11 @@ export function createWorker({ hub, name, capacity = 2, log = () => { }, unreach
145
147
  let restored = false;
146
148
  let cleaning;
147
149
  const active = new Map();
150
+ const supervisors = new Map();
151
+ const supervisor = (entry) => {
152
+ const child = supervisors.get(entry.dir);
153
+ return child?.pid === entry.pid ? child : undefined;
154
+ };
148
155
  const unreadable = new Set();
149
156
  const said = new Set();
150
157
  /** Trouble that lasts comes round every second, and once in the log will do. */
@@ -199,6 +206,7 @@ export function createWorker({ hub, name, capacity = 2, log = () => { }, unreach
199
206
  }
200
207
  /** Starts a turn of the agent: a process that outlives this one, leaving its output and exit code in files. */
201
208
  function launch(entry, adapter, prompt) {
209
+ supervisors.delete(entry.dir);
202
210
  entry.turn += 1;
203
211
  entry.launchedAt = now();
204
212
  entry.usageBaseline = entry.resume ? loadUsage(entry.job.agent.use, entry.resume) : undefined;
@@ -248,6 +256,8 @@ export function createWorker({ hub, name, capacity = 2, log = () => { }, unreach
248
256
  child.on("error", (error) => log(`run ${entry.run}: ${error}`));
249
257
  child.unref();
250
258
  entry.pid = child.pid;
259
+ if (child.pid !== undefined)
260
+ supervisors.set(entry.dir, child);
251
261
  }
252
262
  finally {
253
263
  closeSync(output);
@@ -357,7 +367,7 @@ export function createWorker({ hub, name, capacity = 2, log = () => { }, unreach
357
367
  return adapter.link && (!entry.triedFresh || seen.started) ? entry.session : undefined;
358
368
  }
359
369
  /** A turn has ended. What it said is a result, or a reason to ask it again without redoing anything. */
360
- function conclude(entry, adapter, code) {
370
+ function conclude(entry, adapter, code, unseen = false) {
361
371
  // One ended because its turn was over but it wouldn't exit said what it had to say first.
362
372
  const seen = read(entry, adapter, entry.finishedAt ? 0 : code);
363
373
  entry.usage = addUsage(addUsage(entry.usage, seen.usage), sessionRise(entry, seen));
@@ -370,7 +380,10 @@ export function createWorker({ hub, name, capacity = 2, log = () => { }, unreach
370
380
  return endWith(entry, { outcome: "cancelled", summary: "已停止", ...known, ...usage });
371
381
  if (entry.why === "timeout") {
372
382
  const minutes = entry.job.agent.timeout ?? TIMEOUT_MINUTES;
373
- const error = `超过 ${minutes} 分钟还没结束,已停止`;
383
+ // Past the grace period with a group that could be neither looked at nor signalled, nothing watched this run stop:
384
+ // 已停止 there is a claim about a fact nobody observed, and it is the line the owner reads on the third failure.
385
+ const stopped = unseen ? "停止信号发出后没能确认进程组已结束,进程可能还在" : "已停止";
386
+ const error = `超过 ${minutes} 分钟还没结束,${stopped}`;
374
387
  if (entry.repairs)
375
388
  return discardReceipt(entry, adapter, error);
376
389
  return endWith(entry, { outcome: "failed", error, ...known, ...usage });
@@ -446,22 +459,24 @@ export function createWorker({ hub, name, capacity = 2, log = () => { }, unreach
446
459
  }
447
460
  const { exit } = files(entry);
448
461
  const exitCode = () => (existsSync(exit) ? Number(readFileSync(exit, "utf8").trim()) : null);
462
+ const child = supervisor(entry);
449
463
  if (entry.stopping !== undefined) {
450
464
  const going = await groupAlive(entry);
451
465
  const overdue = now() - entry.stopping > STOP_GRACE;
452
466
  if (going === true) {
453
467
  if (overdue)
454
- signal(entry, "SIGKILL");
468
+ signal(entry, "SIGKILL", child);
455
469
  return;
456
470
  }
457
471
  if (going === null) {
458
472
  // The forced kill is the last thing that can be done to it, and whether it worked can't be seen.
459
473
  if (!overdue)
460
474
  return;
461
- signal(entry, "SIGKILL");
475
+ if (process.platform !== "win32" || child)
476
+ signal(entry, "SIGKILL", child);
462
477
  // A turn that was over, or a timeout, ends on what it said: `failed` there is tried again, redoing work done.
463
478
  if (entry.why !== "cancel")
464
- return conclude(entry, adapter, exitCode());
479
+ return conclude(entry, adapter, exitCode(), true);
465
480
  // Reporting `cancelled` would release the item while a process may still be in it, which the protocol forbids
466
481
  // (docs/protocol.md: 确认组内没有活进程后才交 cancelled). A cancelled run's `failed` isn't tried again.
467
482
  return endWith(entry, {
@@ -474,7 +489,8 @@ export function createWorker({ hub, name, capacity = 2, log = () => { }, unreach
474
489
  if (existsSync(exit))
475
490
  return conclude(entry, adapter, exitCode());
476
491
  // The shell can publish its exit between the first file check and ps returning.
477
- const looking = await alive(entry);
492
+ // A Windows supervisor started here already has a process handle and an exit watcher.
493
+ const looking = child ? child.exitCode === null && child.signalCode === null : await alive(entry);
478
494
  if (looking === false)
479
495
  return conclude(entry, adapter, exitCode());
480
496
  // Unable to look, the run counts as still going, so its timeout and its finished turn still end it.
@@ -509,17 +525,19 @@ export function createWorker({ hub, name, capacity = 2, log = () => { }, unreach
509
525
  save(entry);
510
526
  }
511
527
  else if (moment - entry.finishedAt > GRACE) {
512
- stop(entry, "finished");
528
+ await stop(entry, "finished");
513
529
  }
514
530
  }
515
531
  }
516
- function stop(entry, why) {
532
+ async function stop(entry, why) {
517
533
  if (entry.stopping !== undefined || entry.result)
518
534
  return;
519
535
  entry.stopping = now();
520
536
  entry.why = why;
521
537
  save(entry);
522
- signal(entry, "SIGTERM");
538
+ const child = supervisor(entry);
539
+ if (child || process.platform !== "win32" || (await alive(entry)) === true)
540
+ signal(entry, "SIGTERM", child);
523
541
  log(`run ${entry.run}: stopping (${why})`);
524
542
  }
525
543
  /** Hands in what has ended. One the hub can't take now waits for next time; one it refuses is dropped and said so. */
@@ -546,6 +564,7 @@ export function createWorker({ hub, name, capacity = 2, log = () => { }, unreach
546
564
  throw error;
547
565
  }
548
566
  active.delete(entry.dir);
567
+ supervisors.delete(entry.dir);
549
568
  }
550
569
  /** Nothing else can tell the owner when the hub is what's gone. */
551
570
  function watchHub(reachable, moment) {
@@ -614,7 +633,7 @@ export function createWorker({ hub, name, capacity = 2, log = () => { }, unreach
614
633
  for (const id of answer?.cancel ?? []) {
615
634
  const entry = held.find((entry) => entry.run === id);
616
635
  if (entry)
617
- stop(entry, "cancel");
636
+ await stop(entry, "cancel");
618
637
  }
619
638
  if (answer?.job) {
620
639
  claim = randomUUID();
@@ -34,7 +34,7 @@ npm 安装的副本不在原地覆盖着换版本。每个版本解包在自己
34
34
 
35
35
  ## 手动更新
36
36
 
37
- `agent-autoloop update` 先数没跑完的轮次,有就拒绝。没有就做上面第 1 到第 3 步,然后重启服务;没装服务时,下次 `up` 换上。
37
+ `agent-autoloop update` 先数没跑完的轮次,有就拒绝。没有就做上面第 1 到第 3 步,然后重启服务;没装服务时,下次 `up` 换上。装好或已经在等的版本,会把这一版的更新内容(包里 CHANGELOG 的条目)一并列出来。
38
38
 
39
39
  `update` 只准备版本,不改 `rules.json`、密钥和记录。投影格式变了会在新版第一次启动时从日志重建,见 [安装说明](../INSTALL.md)。
40
40
 
package/docs/protocol.md CHANGED
@@ -150,7 +150,7 @@ GET /v1/events/34 Authorization: Bearer <来源的密钥>
150
150
  | ----------- | ------------------------------------------------------------------------------------------ |
151
151
  | `queued` | 排队;`attempts` 大于 0 时是没跑成、等重试 |
152
152
  | `claimed` | 接单程序领走了,在跑 |
153
- | `unknown` | 接单程序 5 分钟没报这一轮,不确定还在不在跑;之后交的结果照样收 |
153
+ | `unknown` | 接单程序 5 分钟没报这一轮,不确定还在不在跑;之后交的结果照样收,除非本人已经停掉它 |
154
154
  | `done` | 做成了 |
155
155
  | `nothing` | 看过了,没事可做 |
156
156
  | `cancelled` | 结束了,没做成:连续 10 次没跑成不再重试、规则删掉了(`summary` 写明是哪种),或本人停掉的 |
@@ -191,7 +191,7 @@ GET /v1/work?claim=<这次领活的编号>&wait=50&running=7,8&capacity=1 Aut
191
191
  - 没活时最多等 `wait` 秒,新活一来立即返回。`running` 是手上在跑的,同时也是心跳。`capacity=0` 只报到、不领活。
192
192
  - 手上有活时可以每秒来问活、查取消。心跳最多一分钟记进日志一次,手上有几轮都只记一条;通道领卡片也一样。所以 `/v1/state` 的 `seenAt` 可能比最后一次来的时间早不到一分钟,“5 分钟没报”“10 分钟没连上”也可能因此提前不到一分钟判断;`online` 留了这一分钟的余量,记录后 3 分钟内都算在线。
193
193
  - 响应丢了,用同一个 `claim` 再来一次,拿回的是同一份活。
194
- - `cancel` 是要停掉的。Unix 接单程序先向整个进程组发停止信号,10 秒后仍有进程运行就强制结束;Windows 每轮运行在独立 Job Object 中,停止时结束整个子进程树。确认进程已停止后才交 `outcome: "cancelled"`,这个事项才放开。停止期间重启接单程序也继续这一步。要停的这一轮交回 `failed` 也算停了,不再重试。
194
+ - `cancel` 是要停掉的。Unix 接单程序先向整个进程组发停止信号,10 秒后仍有进程运行就强制结束;Windows 每轮运行在独立 Job Object 中,停止时结束整个子进程树。确认进程已停止后才交 `outcome: "cancelled"`,这个事项才放开。停止期间重启接单程序也继续这一步。要停的这一轮交回 `failed` 也算停了,不再重试;`error` 照记,`why` 显示它,不写成“已停止”。
195
195
 
196
196
  ```jsonc
197
197
  // Job:一轮的全部。token 只对这一轮的这一次执行有效。
@@ -245,7 +245,7 @@ POST /v1/runs/12/result Authorization: Bearer <token> Result
245
245
  - `notice` 可选填布尔字段 `fyi`:`true` 表示「仅告知」,卡片创建时就是 `closed`,仍会在创建后的 24 小时内投递,飞书显示灰卡、不带「已处理」按钮;不会进入后续轮次的 `open`,点击也不会产生回答事件。省略或填 `false` 时,通知带「已处理」按钮,也能被 `resolve` 结案。它一创建就结案了,所以同一个 `key` 下一轮再写还会再发一张;同一轮重试只发一次。规则写了 `tell: "never"` 时照样不发。老中台不认识这个字段,会拒收整份回执:中台和接单程序分开部署时先升中台。
246
246
  - `resolve` 只能结同来源、同组、这一轮领活前就有的卡片,越界的写进 `rejected`,不影响这一轮的结果。
247
247
  - `later` 的 `key` 范围是这个事项,同一个 `key` 再写一次就是改时间。
248
- - `events` 的来源由规则的 `emits` 决定,回执改不了。
248
+ - `events` 的来源由规则的 `emits` 决定,回执改不了。规则没写的类型、这个来源已经用同一编号记过另一件事的不记,写进 `rejected`,不影响这一轮的结果。同一件事原样重发用同一个编号,照样只记一次,不算没记上;不同的事换编号。
249
249
 
250
250
  ### Agent 只需要做一件事
251
251
 
@@ -300,10 +300,11 @@ GET /v1/cards/next?wait=50 Authorization: Bearer <通道的密钥>
300
300
  // Card:这张卡片现在的样子。内容创建后不变,只有状态会变
301
301
  { "id": 56, "version": 2, "ref": null, "kind": "ask", "state": "open",
302
302
  "title": "…", "text": "…", "options": ["…", "…"], "recommend": 0,
303
- "choice": null, "answer": null, "by": null, "result": null, "link": null, "rule": "…" }
303
+ "choice": null, "answer": null, "by": null, "result": null, "link": null, "rule": "…", "lane": "#12" }
304
304
  ```
305
305
 
306
306
  - `rule` 是创建这张卡片的规则或别处定时任务的名字,可能没有(比如中台自己的告警,标题就写着从哪来)。卡片从很多地方来,自带的飞书、桌面、Webhook 通道、卡片网页和 `agent-autoloop status` 都写明“来源:<rule>”,标题就是这个名字时不重复;自己写的通道也照这样。
307
+ - `lane` 是卡片所在的事项,和 `/v1/state` 里的一样:写了 `parallel` 的规则是事件的 `subject`,别的规则和 `tell` 是空字符串。通道可以按它把卡片发回事项来的地方,比如来源在单聊里收到的任务,问题和结果也回那个单聊。它是对象,不是凭据:别的规则的回执可以用 `emits` 以同一来源发事件,本人 `run --subject` 也能写,回答和复查沿用原来的事项。所以通道只把认得的 `lane` 对到自己记过的去处(比如自己受理时记下的会话),不按它直接打开任意会话;发到哪里,回答都照样核对 `answerers` 和 `ref`。旧通道忽略这一项即可。
307
308
  - `ref` 是空的就发一条新的;不是空的就把那条改成现在的样子,改不了就直接报告。
308
309
  - 发完报告:`POST /v1/cards/56/delivered { "version": 2, "ref": "om_xxx" }`。没报告的过一分钟会再给你。**支持幂等键的平台,发新消息只用卡片编号,不带版本**(飞书改不动已经结束的卡片时另发一条,这一条才带版本)。平台不支持时无法保证去重,Webhook 模板可能在报告丢失后重发。
309
310
  - 发不出去:`POST /v1/cards/56/failed { "version": 2, "error": "…" }`。第一次发送隔得越来越久地重试,一小时后放弃(卡片还开着,`agent-autoloop status` 看得到);通道一直没来领不算在内。
@@ -329,7 +330,7 @@ POST /v1/runs/12/cancel {}
329
330
 
330
331
  `channels` 里的 `online` 只说明通道程序还在来领卡片,不说明卡片送到了:最近一张卡片没送到时,这个通道多一项 `lastFailure`(`card`、`tries`、通道报的 `error`,`givenUp` 表示试满了一小时、已经放弃;卡片在送到前被结掉也不会再发),送到了或还没发过就没有这一项,`agent-autoloop doctor` 照它提醒。
331
332
 
332
- 整份状态在同一个快照里读出,`seq` 是那时的日志序号:自己做看板的,先取状态,再从 `GET /v1/stream?after=<seq>` 接着读,不漏也不重。`cards`、`recentCards` 在这里多带两项:`lane` 是卡片所在的事项(写了 `parallel` 的规则是事件的对象,别的规则是空字符串),`about` 是提问时留给接着干的那一轮的说明。通道和卡片页拿不到这两项。`lines`、`runs`、`cards`、`recentCards` 的每一项还带规则的 `tags`(见上面规则一节)。旧客户端忽略这些字段即可。
333
+ 整份状态在同一个快照里读出,`seq` 是那时的日志序号:自己做看板的,先取状态,再从 `GET /v1/stream?after=<seq>` 接着读,不漏也不重。`cards`、`recentCards` 在这里多带两项:`lane` 是卡片所在的事项(写了 `parallel` 的规则是事件的对象,别的规则是空字符串),`about` 是提问时留给接着干的那一轮的说明。通道拿得到 `lane`,拿不到 `about`;卡片页两项都拿不到。`lines`、`runs`、`cards`、`recentCards` 的每一项还带规则的 `tags`(见上面规则一节)。旧客户端忽略这些字段即可。
333
334
 
334
335
  `GET /healthz` 不带密钥,返回 `{ "ok": true, "commit": "<中台运行的版本>" }`;`doctor`、服务状态和一致性检查都用它判断中台是否在线。
335
336
 
@@ -371,7 +372,7 @@ POST /v1/rules/巡检/run { "subject": "#12", "reason": "看一眼" }
371
372
 
372
373
  命令行:`agent-autoloop pause <规则> [--reason 原因] [--until 时间]`、`resume <规则>`、`replay <规则> --since <时间>`、`run <规则> [--subject 对象] [--reason 说明]`。`pause` 说明暂停期间的事件不排队、恢复时会列出;`resume` 列出这次暂停跳过的事件(最多 20 条,多了写明共几条),并给出补跑这一段的 `replay` 命令;`status` 列出暂停中的规则、从什么时候起、跳过了几条和最近 5 条。已经恢复的规则以前跳过的事件不再出现在 `status` 里。
373
374
 
374
- `agent-autoloop check [文件]` 只读文件、校验规则,不打开中台数据库,也不把文件载入中台;不写文件名就查 `rules.json`。可以先校验一份草稿再换上去。`/v1/state` 一次给最近 60 轮,`?before=<nextBefore>` 翻更早的。`agent-autoloop runs [规则] [--before <第几轮>]` 一次列 20 轮做完的。指定规则时,使用本人密钥请求 `GET /v1/runs?rule=<URL 编码的规则名>[&before=<编号>]`,返回 `{now, timezone, runs, nextBefore}`。轮次与 state 同形,按编号倒序,排除 queued 和 claimed;before 不含该轮,末页游标为 null,规则没有历史时返回空列表。旧中台没有这个地址时,命令行仍从 state 翻页筛选。
375
+ `agent-autoloop check [文件]` 只读文件、校验规则,不打开中台数据库,也不把文件载入中台;不写文件名就查 `rules.json`。可以先校验一份草稿再换上去。`/v1/state` 一次给最近 60 轮,`?before=<nextBefore>` 翻更早的。`agent-autoloop runs [规则] [--before <第几轮>]` 一次列 20 轮做完的。指定规则时,使用本人密钥请求 `GET /v1/runs?rule=<URL 编码的规则名>[&before=<编号>]`,返回 `{now, timezone, runs, nextBefore}`。轮次与 state 同形,按编号倒序,排除 queued 和 claimed;before 不含该轮,末页游标为 null,规则没有历史时返回空列表。旧中台没有这个地址时,命令行仍从 state 翻页筛选。`agent-autoloop wakeups [规则] [--limit 条数] [--json]` 也这样翻页,默认看最近 100 轮,再逐轮读 `why` 的事实,按规则和叫醒原因分组:到期复查只认中台自己的定时器,人工回答只认卡片的回答,来源发来的同名事件算别的事件,几种原因并进一轮的单列;每组给出轮数、有过失败的轮数、已上报的用量合计和覆盖的轮数,以及几个轮次编号。统计在命令行这边做,协议不变。
375
376
 
376
377
  `/v1/state` 的 `spending.today`、`spending.week` 独立于分页,按规则时区的今天和过去 7 × 24 小时的完成时间汇总。每项含 `rounds`、`tokens`、`cached`、`cost`、`missingTokens`、`missingCost`,`tokens` 是输入加输出,`cached` 是其中从缓存读的,后两项是没报对应用量的轮数;从未开始就取消的轮次不计入。
377
378
 
@@ -522,14 +523,14 @@ Apple M5 Pro、24 GB、Node 24.21.0,用 `node scripts/history.ts 1000 10000 10
522
523
 
523
524
  | 已完成任务轮数(约) | 事实条数(约) | 正常启动 | 空闲 RSS | 领活 HTTP 中位数 | 状态汇总 |
524
525
  | -------------------- | -------------: | -------: | -------: | ---------------: | -------: |
525
- | 2,000 | 11,000 | 84.7 ms | 59.1 MB | 0.89 ms | 11.2 ms |
526
- | 20,000 | 110,000 | 83.2 ms | 58.9 MB | 0.84 ms | 83.6 ms |
527
- | 200,000 | 1,100,000 | 99.8 ms | 59.1 MB | 0.82 ms | 927.1 ms |
528
-
529
- - 110 万条事实时,收事件、去重、交结果、心跳、空闲通道轮询和 `why` 的请求中位数为 0.39–0.69 ms;进程被强杀后正常恢复约 101 ms。
530
- - 内存:持续写入历史时最高约 282 MB;业务请求加一个慢速日志订阅约 75 MB。
531
- - 会随历史变大的:状态汇总耗时,以及日志和索引占的磁盘。
532
- - 格式变化后首次启动要从日志全量重建:110 万条用时 43.1 秒,峰值约 141 MB,重建前后数据一致。平时重启不重放。
526
+ | 2,000 | 11,000 | 84.7 ms | 60.3 MB | 0.66 ms | 6.0 ms |
527
+ | 20,000 | 110,000 | 84.1 ms | 60.1 MB | 0.63 ms | 31.3 ms |
528
+ | 200,000 | 1,100,000 | 112.3 ms | 60.4 MB | 0.63 ms | 300.2 ms |
529
+
530
+ - 110 万条事实时,收事件、去重、交结果、心跳、空闲通道轮询和 `why` 的请求中位数为 0.27–0.66 ms;进程被强杀后正常恢复约 104 ms。
531
+ - 内存:持续写入历史时最高约 302 MB;业务请求加一个慢速日志订阅约 75 MB。
532
+ - 会随历史变大的:状态汇总耗时,以及日志和索引占的磁盘。状态汇总按规则、Agent 和状态分组计数时走索引顺序,统计费用只读索引;加这两个索引前,同一台机器上 2 千、2 万、20 万轮分别是 11.2、103.6、1079.2 ms。
533
+ - 格式变化后首次启动要从日志全量重建:110 万条用时 48.2 秒,峰值约 165 MB,重建前后数据一致。平时重启不重放;已有的大库升级到带这两个索引的版本后,第一次启动要先建索引。
533
534
  - 20 万步模拟(观察项):93.8 秒,2131 步/秒。
534
535
 
535
536
  ## 交付插件
@@ -551,7 +552,7 @@ Apple M5 Pro、24 GB、Node 24.21.0,用 `node scripts/history.ts 1000 10000 10
551
552
  | 发布 | 等一个覆盖合并提交的 Ship 成功,再核对健康版本;健康 HTTP 200 不能覆盖 Ship 失败或尚未完成 |
552
553
  | 后续发布 | 新版覆盖且确实上线可以完成旧交付;已经完成的交付不因后来的失败发布倒退 |
553
554
 
554
- 等待完整检查时,当前提交最新的 `pull_request` 运行必须比转正式前记录的检查编号更新。从开始等待(草稿先转正式)起超过 10 分钟仍没有新运行,或者新运行尚未结束、从 `created_at` 起超过 10 分钟仍没有 `check.job` 指定的任务,判为 GitHub 没有开始必需的检查;前置任务已经完成也不能代替必需任务。插件把 PR 转草稿再转正式,自救一次,并从这次转正式重新计时。转正式前重新记录最新的 `pull_request` 运行编号,排除转草稿触发的检查,只接受之后的新运行。自救记录与提交绑定,执行期间存在 `DeliveryIO.checkRecovery`,需要复查时把检查编号作为 `checkAfter` 写进已有 `delivery-retry` 的 `about` JSON,与 `head` 和错误次数一起保存,下一轮继续使用,提交变化后重新计。重新触发后按同样条件再次卡住时,立即通过交付退回和通知流程说明 GitHub 一直没有开始检查,不计入五次执行错误。必需任务已经创建、正在排队或执行时继续等待,不因运行时间长而自救,其余情况仍受原有 30 分钟等待和错误重试规则约束。`workflow_dispatch` 运行不作为完整检查依据。
555
+ 等待完整检查时,当前提交最新的 `pull_request` 运行必须比转正式前记录的检查编号更新。从开始等待(草稿先转正式)起超过 10 分钟仍没有新运行,或者新运行尚未结束、从 `created_at` 起超过 10 分钟仍没有 `check.job` 指定的任务,判为 GitHub 没有开始必需的检查;前置任务已经完成也不能代替必需任务。插件把 PR 转草稿再转正式,自救一次,并从这次转正式重新计时。转正式前重新记录最新的 `pull_request` 运行编号,排除转草稿触发的检查,只接受之后的新运行。自救记录与提交绑定,执行期间存在 `DeliveryIO.checkRecovery`,需要复查时把检查编号作为 `checkAfter` 写进已有 `delivery-retry` 的 `about` JSON,与 `head` 和错误次数一起保存,下一轮继续使用,提交变化后重新计。重新触发后按同样条件再次卡住时,立即通过交付退回和通知流程说明 GitHub 一直没有开始检查,不计入五次执行错误。必需任务已经创建、正在排队或执行时继续等待,不因运行时间长而自救;这一轮等满 30 分钟检查还没跑完,就结束这一轮、一分钟后接着等,不算执行错误,也不写 `delivery` 失败,检查最长跑多久由 GitHub 自己的任务时限决定。其余情况仍受原有 30 分钟等待和错误重试规则约束。等待检查、合并和发布时每 30 秒向 GitHub 查一次,几个交付共用一个账号也远低于每小时 5000 次的额度。`workflow_dispatch` 运行不作为完整检查依据。
555
556
 
556
557
  `deliver-review` 审查通过就结束并移除交付标签。在等待检查期间加上它,合并前也会停在只审查。等待检查时撤回 `deliver` 会结束本轮,并报告 `withdrawn`,表示没有合并或发布。关闭未合并的 PR 先写 `delivery` 失败再清交付标签,不让等待者卡在 pending。默认用中台的失败重试和提问卡片。接入已有交付工具时,`--notify-command` 把 `ask-owner` 转告给通知程序,成功后移除标签。退回写 `delivery` 失败并移除交付标签。已有 `deliver-attended` 的退回等待三分钟,仍未清除才转告。临时错误用中台的一分钟复查重试,GitHub 的 5xx 等平台错误最多 60 次,其他执行错误最多 5 次。每个审查器最多跑 30 分钟,超时算一次执行错误。执行错误的第一行原因写进本轮结果和退回说明,完整原因留在本轮输出。
557
558
 
@@ -8,8 +8,8 @@
8
8
  | --- | --- | --- |
9
9
  | 事件 | `events` 的 `source + key` 去重;`routed/paused/hops` 区分已派、暂停跳过、无人接、超过 8 层未派,记下后不再改;补跑不改事件,接到这条规则的一轮上就算补过 | `kernel/decide.ts` 的 `ingest/recordEvent` 接来源、回执、回答、时钟和手动运行;`replayRule` 补跑暂停跳过的事件 |
10
10
  | 事项 | 没有单独状态列;`rule + lane` 对应的轮次、未结卡片、未来复查共同表达进展 | `enqueue/answer/tick/retryLater`;运行中来的事件排下一轮,失败时把同事项的队列合进重试轮次 |
11
- | 轮次 | `runs.state`: `queued → claimed → done/nothing/cancelled`;`claimed → unknown`;失败从 claimed/unknown 回 queued,`attempts/not_before` 表达等重试 | `claimNext/finish/applyReceipt/retryLater/cancel/stopRun/sweep`。unknown 不是失败,迟到结果照收,后续新活可以继续 |
12
- | 停止 | `claimed + cancel_at` 表示正在停;进程结束才 cancelled;排队可直接取消 | 本人 `cancel`,worker 停整个进程组后交结果;停止期间收到 failed 也归 cancelled,不能重派 |
11
+ | 轮次 | `runs.state`: `queued → claimed → done/nothing/cancelled`;`claimed → unknown`;失败从 claimed/unknown 回 queued,`attempts/not_before` 表达等重试 | `claimNext/finish/applyReceipt/retryLater/cancel/stopRun/sweep`。unknown 不是失败,迟到结果照收,后续新活可以继续;本人停掉之后就结束了,不再收结果 |
12
+ | 停止 | `claimed + cancel_at` 表示正在停;进程结束才 cancelled;排队和没有回音的(`unknown`)可直接取消 | 本人 `cancel`,worker 停整个进程组后交结果;停止期间收到 failed 也归 cancelled,不能重派。`unknown` 没有在报它的接单程序,等不到谁来确认,本人停掉就是结束,`summary` 写明是本人停掉、此前已没有回音 |
13
13
  | 执行归属 | `agent/rules_version/issued/claim` 固定领取归属;`session/resume` 是续接提示 | `assignQueued/settleSession/claimNext/started/finish`。排队用最新规则,领取后保留原 worker 和规则快照;重复 claim 换 token |
14
14
 
15
15
  `done + open 提问`、`done + 未来复查` 都合法:只结束这一轮。连续失败最多 10 次,终态轮次不能重排。本人要再做用新事件或手动 `run`。已交回的 `last_issued/last_result/last_answer` 保证同 token 同内容重交只确认一次,不同内容返回 409。
@@ -56,7 +56,7 @@
56
56
  | reviewed | deliver-review 要求只审查,完成清标签;部分清除失败不能变成全文交付 |
57
57
  | returned | delivery=failure,去 deliver/deliver-review;deliver-attended 由交接者领取,三分钟未领才按既有规则转告 |
58
58
  | withdrawn | 检查中撤 deliver,关闭 auto-merge,成功结束但未合并发布,明确报告撤回;不等于 live |
59
- | retrying | 中台 later 的 delivery-retry 保存 head、GitHub/执行错误计数;换 head 清计数,达限退回;不可写结果时保留重交 |
59
+ | retrying | 中台 later 的 delivery-retry 保存 head、GitHub/执行错误计数;换 head 清计数,达限退回;完整检查还在跑时只顺延、不计数;不可写结果时保留重交 |
60
60
 
61
61
  关闭未合并的 PR 先写 delivery 失败再清标签,避免等待者卡 pending。ask-owner 是独立 Issue 的转告状态,转告成功才清除,不是上线阶段。来源只认可信账号的 `delivery-agent/<PR号>` 状态;PR 正文审查账本与可信状态绑定轮次、head、审查器和正文摘要。免审不是审查通过,填写「处理」不是复审完成;连续两轮挡上线后只认可信账号写的 `delivery-owner/<PR号>`。
62
62
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@saltpub/agent-autoloop",
3
- "version": "0.1.8",
3
+ "version": "0.1.10",
4
4
  "description": "Let Agents follow up on work and ask when they need your judgment.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -52,6 +52,16 @@ export class DeliveryRefusal extends Error {
52
52
 
53
53
  export class DeliverySuperseded extends Error {}
54
54
 
55
+ /** GitHub has the full check and it is going: only GitHub's own time limits end it, so outlasting a round isn't a failure. */
56
+ export class ChecksStillRunning extends Error {
57
+ readonly head: string;
58
+
59
+ constructor(head: string, waited: unknown) {
60
+ super(waited instanceof Error ? waited.message : String(waited), { cause: waited });
61
+ this.head = head;
62
+ }
63
+ }
64
+
55
65
  const FINDINGS = "审查发现问题,修复后推新提交才会重审";
56
66
  const STALL = 10 * 60_000;
57
67
  const labels = (pr: any) => new Set<string>((pr.labels ?? []).map((label: any) => label.name));
@@ -391,7 +401,14 @@ export async function deliver(
391
401
  if (!auto || !pr.auto_merge) throw new Error("尚未确认合并,稍后继续核实");
392
402
  }
393
403
  }
394
- await io.wait();
404
+ try {
405
+ await io.wait();
406
+ } catch (error) {
407
+ // A finished run waits too when its required job was skipped or isn't there; only one still going ends on its own.
408
+ const going = state === "waiting" ? await newestCheck(head, config, io) : undefined;
409
+ if (going && going.id > after && going.status !== "completed") throw new ChecksStillRunning(head, error);
410
+ throw error;
411
+ }
395
412
  }
396
413
  } catch (error) {
397
414
  await stopAuto();
@@ -8,6 +8,8 @@ import { git, liveRelease, releaseRequired, REPO } from "./project.ts";
8
8
  import { readSharedPolicy, reviewDelivery } from "./review.ts";
9
9
 
10
10
  const LONGEST_WAIT = 1800000;
11
+ // Several deliveries share one account's 5,000 requests an hour, and a check loop asks three things each time round.
12
+ const POLL = 30_000;
11
13
  class GitHubHiccup extends Error {}
12
14
  export function isGitHubHiccup(error: unknown): boolean {
13
15
  return error instanceof GitHubHiccup || (error instanceof Error && !!error.cause && isGitHubHiccup(error.cause));
@@ -201,7 +203,7 @@ export function createIO(repo: string, folder: string, options: DeliveryOptions
201
203
  live: liveRelease,
202
204
  async wait() {
203
205
  if (Date.now() - started > LONGEST_WAIT) throw new Error("等待超过半小时,保留远端状态,稍后继续核实");
204
- await setTimeout(5000);
206
+ await setTimeout(POLL);
205
207
  },
206
208
  };
207
209
  }
@@ -28,6 +28,27 @@ export function retryState(timers: Timer[]): RetryState | undefined {
28
28
  return saved ? JSON.parse(saved) : undefined;
29
29
  }
30
30
 
31
+ function carried(timers: Timer[], head: string, checkRecovery?: DeliveryIO["checkRecovery"]) {
32
+ const previous = retryState(timers);
33
+ const count = previous?.head === head ? previous : { head, github: 0, execution: 0 };
34
+ if (checkRecovery?.head === head) count.checkAfter = checkRecovery.after;
35
+ return count;
36
+ }
37
+
38
+ /** A full check still going isn't a failed try: look again in a minute with the counts as they were. */
39
+ export function waitHandoff(
40
+ timers: Timer[],
41
+ head: string,
42
+ now = Date.now(),
43
+ checkRecovery?: DeliveryIO["checkRecovery"],
44
+ ) {
45
+ return {
46
+ key: retryKey,
47
+ at: new Date(now + retryInterval).toISOString(),
48
+ about: JSON.stringify(carried(timers, head, checkRecovery)),
49
+ };
50
+ }
51
+
31
52
  export function retryHandoff(
32
53
  timers: Timer[],
33
54
  head: string,
@@ -36,9 +57,7 @@ export function retryHandoff(
36
57
  canReturn = true,
37
58
  checkRecovery?: DeliveryIO["checkRecovery"],
38
59
  ) {
39
- const previous = retryState(timers);
40
- const count = previous?.head === head ? previous : { head, github: 0, execution: 0 };
41
- if (checkRecovery?.head === head) count.checkAfter = checkRecovery.after;
60
+ const count = carried(timers, head, checkRecovery);
42
61
  const kind = hiccup ? "github" : "execution";
43
62
  const limit = hiccup ? 60 : 5;
44
63
  count[kind] = Math.min(count[kind] + 1, limit);
@@ -5,9 +5,28 @@ import { join } from "node:path";
5
5
  import { setTimeout } from "node:timers/promises";
6
6
  import { parseArgs } from "node:util";
7
7
  import { createIO, gh, isGitHubHiccup, type DeliveryOptions } from "./github.ts";
8
- import { deliver, DeliveryRefusal, DeliverySuperseded, disableAuto, status, type DeliveryIO } from "./delivery.ts";
8
+ import {
9
+ ChecksStillRunning,
10
+ deliver,
11
+ DeliveryRefusal,
12
+ DeliverySuperseded,
13
+ disableAuto,
14
+ status,
15
+ type DeliveryIO,
16
+ } from "./delivery.ts";
9
17
  import { deliveryReceipt, question, receiptBlock, subjectNumber } from "./input.ts";
10
- import { hasLabel, retryHandoff, retryState, runHook, tellQuestion, tellReturn, unattendedFailure } from "./handoff.ts";
18
+ import {
19
+ hasLabel,
20
+ retryHandoff,
21
+ retryState,
22
+ runHook,
23
+ tellQuestion,
24
+ tellReturn,
25
+ unattendedFailure,
26
+ waitHandoff,
27
+ } from "./handoff.ts";
28
+
29
+ const STILL_RUNNING = "完整检查还在跑,一分钟后接着等";
11
30
 
12
31
  type Options = DeliveryOptions & { progressCommand?: string; notifyCommand?: string; direct?: boolean };
13
32
  type Context = Parameters<typeof subjectNumber>[1] & {
@@ -80,6 +99,10 @@ async function handoff(
80
99
  return { text: result.summary, exit: result.merged || result.reviewOnly ? undefined : 2 };
81
100
  } catch (error) {
82
101
  if (error instanceof DeliverySuperseded) return { text: error.message, exit: 2 };
102
+ if (error instanceof ChecksStillRunning) {
103
+ await io.report?.("retrying", error.head, { detail: "checks" });
104
+ return { text: STILL_RUNNING, retry: waitHandoff(timers, error.head, Date.now(), io.checkRecovery) };
105
+ }
83
106
  if (error instanceof DeliveryRefusal) {
84
107
  head = error.head ?? head;
85
108
  try {
@@ -173,6 +196,8 @@ export async function run(repo: string, context: Context, testLocalHealth = fals
173
196
  return deliveryReceipt(number, result, hasLabel(issue, "deliver-attended"));
174
197
  } catch (error) {
175
198
  if (error instanceof DeliverySuperseded) return error.message;
199
+ if (error instanceof ChecksStillRunning)
200
+ return `${STILL_RUNNING}\n${receiptBlock({ later: [waitHandoff([], error.head)] })}`;
176
201
  const pr = await io.api(`pulls/${number}`);
177
202
  if (pr.auto_merge) await disableAuto(number, io);
178
203
  await status(io, pr.head.sha, "delivery", "failure", (error as Error).message);
@@ -9,7 +9,7 @@ description: 配置 Agent 自动化中台:加规则、接新的事件插件、
9
9
 
10
10
  ## 看情况、回答
11
11
 
12
- `agent-autoloop status` 列出谁在线、等用户什么、在做什么、做过什么,还有按完成时间统计的今天和最近 7 天的轮数、Token 和费用(Token 含缓存,写出其中缓存占多少;同一轮重试的已报用量相加,没上报的轮数会写出来)。终端里它带颜色,接管道、被 Agent 调用或设了 `NO_COLOR` 时是纯文本。`agent-autoloop status --json` 输出 `/v1/state` 的原样结构,给脚本和看板用。`agent-autoloop answer <卡片> <序号>` 回答,`agent-autoloop resolve <卡片> <结果>` 结案,`agent-autoloop stop <第几轮>` 停掉一轮,等整个进程组退出才报告已停。
12
+ `agent-autoloop status` 列出谁在线、等用户什么、在做什么、做过什么,还有按完成时间统计的今天和最近 7 天的轮数、Token 和费用(Token 含缓存,写出其中缓存占多少;同一轮重试的已报用量相加,没上报的轮数会写出来)。终端里它带颜色,接管道、被 Agent 调用或设了 `NO_COLOR` 时是纯文本。`agent-autoloop status --json` 输出 `/v1/state` 的原样结构,给脚本和看板用。`agent-autoloop answer <卡片> <序号>` 回答,`agent-autoloop resolve <卡片> <结果>` 结案,`agent-autoloop stop <第几轮>` 停掉一轮:在跑的等整个进程组退出才报告已停;已经没有回音(`status` 里写着不确定)的一轮直接结束,不再收它后来交的结果。
13
13
 
14
14
  用户说 Agent 额度用完了、中台还在一轮轮派活时:内置的 Claude Code 插件已经会报恢复时间,中台到那时前不派活给这个 Agent,排着的事件到点自动接着做,不用暂停规则或调小 `parallel`;`status` 在这个 Agent 后面写着几点恢复。想提前试,对用它的一条规则 `agent-autoloop run`,跑通就恢复派活。别的 CLI 要有这个行为,在它的插件 `read` 里返回 `limitedUntil`(见 `docs/plugins.md`)。
15
15
 
@@ -179,7 +179,7 @@ gh api repos/owner/app/statuses/<完整提交编号> -f context=delivery-agent/<
179
179
 
180
180
  `check.job` 写 job 的名字;矩阵 job(名字像 `check (ubuntu-latest)`)算同一个 job,每一项都要成功。检查工作流的触发类型要带 `ready_for_review`:草稿转 ready 后,只接受这之后新跑的一次检查,而 `pull_request` 默认不在转 ready 时触发。写成 `on: { pull_request: { types: [opened, synchronize, reopened, ready_for_review] } }`。
181
181
 
182
- 开始等待检查(草稿先转正式)后超过 10 分钟仍没有新 `pull_request` 检查,或者新检查尚未结束、创建超过 10 分钟仍没有 `check.job` 指定的必需任务,插件会把 PR 转草稿再转正式,重新触发一次,只认可转回正式之后的新检查,并重新计时。前置任务已经完成也不能代替必需任务。同一个提交的自救记录随中台复查保留。重新触发后按同样条件再次卡住时,交付立即退回,说明 GitHub 收下了检查却一直没有开始,等 GitHub 恢复后重新交付。必需任务已经创建、正在排队等机器或执行时继续等待,不因运行时间长而重新触发。其他情况仍最多等待 30 分钟,暂时的 GitHub 或执行错误按原有规则重试。手动触发的 `workflow_dispatch` 检查不作为合并依据。
182
+ 开始等待检查(草稿先转正式)后超过 10 分钟仍没有新 `pull_request` 检查,或者新检查尚未结束、创建超过 10 分钟仍没有 `check.job` 指定的必需任务,插件会把 PR 转草稿再转正式,重新触发一次,只认可转回正式之后的新检查,并重新计时。前置任务已经完成也不能代替必需任务。同一个提交的自救记录随中台复查保留。重新触发后按同样条件再次卡住时,交付立即退回,说明 GitHub 收下了检查却一直没有开始,等 GitHub 恢复后重新交付。必需任务已经创建、正在排队等机器或执行时继续等待,不因运行时间长而重新触发;一轮等满 30 分钟还没跑完就一分钟后接着等,不算出错,跑一两个小时的检查也不会被退回。其他情况仍最多等待 30 分钟,暂时的 GitHub 或执行错误按原有规则重试。手动触发的 `workflow_dispatch` 检查不作为合并依据。
183
183
 
184
184
  规则示例(把绝对路径、接单电脑和仓库改成自己的):
185
185
 
@@ -266,11 +266,13 @@ MCP 服务不区分调用方,都按本人记录(`answer` 记成本人,`emi
266
266
 
267
267
  Windows 用任务计划程序在本人登录后启动;通过 SSH 管理时仍用这个登录任务运行 Codex,避免它在 OpenSSH 会话中的沙箱启动限制(见 `INSTALL.md`);`service install`、`service remove`、`update` 同样适用,更新会重启中台;自动更新换版本时登录任务不动,只换它启动的那一份。Windows 自带的 Administrator 账号用「启动」文件夹代替登录任务,`service install` 会打印做法。安装见 `INSTALL.md`。
268
268
 
269
+ Agent 不要在轮次里直接运行 `up` 重启派它来的这个中台:轮次结束或被停掉时,中台会跟着一起结束,`up` 会拒绝并说明原因。要用上新代码:装了登录服务的运行 `agent-autoloop service install`;Windows 用「启动」文件夹的,结束数据目录(默认 `%USERPROFILE%\.agent-autoloop`)里 `up.pid` 记着的进程,wscript 十秒后会用新代码再拉起;都没有的,请用户在自己的登录会话里启动。用临时数据目录起的测试中台不受这条限制。
270
+
269
271
  日志:Windows 在 `%USERPROFILE%\.agent-autoloop\logs\up.log`,macOS 在 `~/.agent-autoloop/logs/up.log`,Linux 运行 `journalctl --user -u agent-autoloop`。
270
272
 
271
273
  接插件先在专用测试中台验证:`agent-autoloop conformance <地址> --config <测试凭据文件>`。文件里的 `keys` 分别放来源、接单程序、通道、本人密钥;`eventType` 匹配测试规则,`answerer` 在测试通道的允许名单内。检查会写事件和卡片,不指向正在用的中台。协议类型在 `protocol/schema.json`。
272
274
 
273
- `agent-autoloop runs [规则] [--before <第几轮>]` 列出更早做完的轮次和编号,`agent-autoloop why 42` 查一轮的事件、规则和回执;`GET /v1/stream?after=42` 供本人客户端按序号续读。备份用 `agent-autoloop backup [目录]`,中台运行时也能做;恢复用 `agent-autoloop restore <目录>`,要先停中台。手工备份要一起保留 `hub.db` 和权限为 0600 的 `master.key`;后者推导轮次和卡片链接的 token。
275
+ `agent-autoloop runs [规则] [--before <第几轮>]` 列出更早做完的轮次和编号,`agent-autoloop why 42` 查一轮的事件、规则和回执;`agent-autoloop wakeups [规则]` 按叫醒原因(到期复查、人工回答、别的事件)汇总最近的轮次和用量,看哪条规则在反复复查;`GET /v1/stream?after=42` 供本人客户端按序号续读。备份用 `agent-autoloop backup [目录]`,中台运行时也能做;恢复用 `agent-autoloop restore <目录>`,要先停中台。手工备份要一起保留 `hub.db` 和权限为 0600 的 `master.key`;后者推导轮次和卡片链接的 token。
274
276
 
275
277
  ## 版本与卸载
276
278