@saltpub/agent-autoloop 0.1.2 → 0.1.4

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/dist/cli/main.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // The command line: what a person, or their Agent, types.
2
- import { spawnSync } from "node:child_process";
2
+ import { spawn, spawnSync } from "node:child_process";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
5
5
  import { hostname } from "node:os";
@@ -15,62 +15,98 @@ import { aboveDesktop, installService, removeService, restartService, runningUp,
15
15
  import { versionLine } from "../host/version.js";
16
16
  import { ENTRY as PROGRAM, ROOT } from "../host/program.js";
17
17
  import { pointSkill } from "../host/update.js";
18
+ import { AGENT_NAMES, AGENT_TITLES, BUILTIN_AGENTS } from "./agents.js";
18
19
  import { clockFor, colorFor, render, replayCommand, skippedLine } from "./status.js";
20
+ import { box, steps, stylesFor } from "./ui.js";
19
21
  import { attemptsOf, newFailure, waitingRetry } from "./try.js";
20
- const HELP = `Agent 自动化中台
21
-
22
- agent-autoloop init [--agent claude|codex] [--command '某个命令 {prompt}'] [--port 3350] [--no-service]
23
- 在这台电脑上装好:一个人一台电脑就够
24
- agent-autoloop try 用你的 Agent 跑一遍完整流程
25
- agent-autoloop why <第几轮> [--json] 查看时间线;--json 输出原始事实
26
- agent-autoloop conformance <地址> --config <测试凭据文件>
27
- 在测试中台上检查协议
28
- agent-autoloop status [--json] 现在什么情况:谁在线、等你什么、在做什么、做过什么、花了多少
29
- --json 输出 /v1/state 的原始结构,给脚本用
30
- agent-autoloop runs [规则] [--before <第几轮>] [--json]
31
- 列出做完的轮次,可以只看一条规则、往前翻;细节再用 why
32
- agent-autoloop answer <卡片> [序号] [--text 别的想法]
33
- 回答一张卡片;通知不用写序号
34
- agent-autoloop resolve <卡片> <结果> 这件事不用决定了,写一句结果
35
- agent-autoloop doctor 查哪里没配好
36
- agent-autoloop check [文件] 检查规则文件,不碰中台;不写文件就查 rules.json
37
- agent-autoloop rules explain [文件] 按本机 rules.json(或指定草稿)说明生效的规则、Agent、通道和下次定时
38
- agent-autoloop pause <规则> [--reason 原因] [--until 时间]
39
- 暂停一条规则:到点不跑、来事件不接也不排队,直到恢复
40
- agent-autoloop resume <规则>
41
- 恢复,列出暂停期间跳过的事件;错过的时段不补跑
42
- agent-autoloop replay <规则> --since <时间>
43
- 补跑这条规则从这个时间起暂停时跳过的事件,每条只补一次
44
- agent-autoloop run <规则> [--subject 对象] [--reason 说明]
45
- 立即运行一轮,照常排队派活
46
- agent-autoloop emit <类型> [--dry-run] [--subject x] [--summary x] [--detail x] [--link x] [--id x] [--key 来源密钥]
47
- 发一条事件;--dry-run 只预演会派给谁,不连接中台
48
- agent-autoloop tell <编号> [--task 定时任务名]
49
- 直接告诉你一件事,内容从标准输入读
50
- agent-autoloop ask --task <定时任务名>
51
- 定时任务问你一件事:标准输入传回执那样的 ask;你答了,它的 Agent 在 cwd 接着做
52
- agent-autoloop stop <第几轮> 停掉一轮
53
- agent-autoloop key new <source|worker|channel|owner> <名字>
54
- 新建一把密钥(只显示这一次)
55
- agent-autoloop key list 有哪些密钥
56
- agent-autoloop key remove <种类> <名字> 立即收回一把密钥
57
- agent-autoloop add <git 地址> 安装插件,不自动更新
58
- agent-autoloop mcp 用标准输入输出连接 MCP 客户端
59
- agent-autoloop join <中台地址> --worker <名字> --key <密钥> [--no-service]
60
- 另一台电脑只接活时用
61
- agent-autoloop backup [目录] 备份数据库、主密钥、配置、规则和 secrets.env;不填目录就放在 ~/.agent-autoloop/backups
62
- agent-autoloop restore <目录> [--yes] 停掉中台后,用一次备份恢复本机数据
63
- agent-autoloop update 更新到 npm 上的最新版本
64
- agent-autoloop uninstall [--yes] 卸载程序并保留数据;--yes 跳过确认
65
- agent-autoloop --version 版本(源码检出还会有提交)
66
- agent-autoloop help 这份说明
67
- agent-autoloop up 启动(平时由系统服务调用)
68
- agent-autoloop service install|remove 系统服务
69
-
70
- 配置和数据在 ${HOME}。规则在 ${RULES_FILE},改了自动生效。`;
71
- const INIT_USAGE = `用法:agent-autoloop init [--agent claude|codex] [--command '某个命令 {prompt}'] [--port 3350] [--no-service]
22
+ // The manual, in the order a person needs it: get it running, see what's going on, then everything else.
23
+ const HELP_GROUPS = [
24
+ [
25
+ "开始用",
26
+ [
27
+ [
28
+ "init [--agent <名字>] [--command '某个命令 {prompt}'] [--port 3350] [--no-service]",
29
+ "在这台电脑上装好:一个人一台电脑就够",
30
+ ],
31
+ ["try", "用你的 Agent 跑一遍完整流程"],
32
+ ["doctor", "查哪里没配好,说下一步"],
33
+ ],
34
+ ],
35
+ [
36
+ "看现在的情况",
37
+ [
38
+ ["status [--json]", "谁在线、等你什么、在做什么、花了多少;--json 给脚本"],
39
+ [
40
+ "dashboard [--port 3351] [--no-open]",
41
+ "打开看板:规则、在跑、待你、今天跑完,点数字看全部;--no-open 不发开浏览器",
42
+ ],
43
+ ["runs [规则] [--before <第几轮>] [--json]", "做完的轮次,可以只看一条规则、往前翻"],
44
+ ["why <第几轮> [--json]", "一轮的时间线;--json 输出原始事实"],
45
+ ["answer <卡片> [序号] [--text 别的想法]", "回答一张卡片;通知不用写序号"],
46
+ ["resolve <卡片> <结果>", "这件事不用决定了,写一句结果"],
47
+ ],
48
+ ],
49
+ [
50
+ "规则",
51
+ [
52
+ ["check [文件]", "检查规则文件,不碰中台;不写文件就查 rules.json"],
53
+ ["rules explain [文件]", "按规则文件说明生效的 Agent、通道和下次定时"],
54
+ ["pause <规则> [--reason 原因] [--until 时间]", "到点不跑、来事件不接也不排队,直到恢复"],
55
+ ["resume <规则>", "恢复,列出暂停期间跳过的事件;错过的时段不补跑"],
56
+ ["replay <规则> --since <时间>", "补跑暂停期间跳过的事件,每条只补一次"],
57
+ ["run <规则> [--subject 对象] [--reason 说明]", "立即运行一轮,照常排队派活"],
58
+ ["stop <第几轮>", "停掉一轮"],
59
+ ],
60
+ ],
61
+ [
62
+ "接进来",
63
+ [
64
+ [
65
+ "emit <类型> [--dry-run] [--subject x] [--summary x] [--detail x] [--link x] [--id x] [--key 来源密钥]",
66
+ "发一条事件;--dry-run 只预演会派给谁,不连接中台",
67
+ ],
68
+ ["tell <编号> [--task 定时任务名]", "直接告诉你一件事,内容从标准输入读"],
69
+ ["ask --task <定时任务名>", "定时任务问你一件事:你答了,它的 Agent 在 cwd 接着做"],
70
+ ["add <git 地址>", "安装插件,不自动更新"],
71
+ ["join <中台地址> --worker <名字> --key <密钥> [--no-service]", "另一台电脑只接活时用"],
72
+ ["mcp", "用标准输入输出连接 MCP 客户端"],
73
+ ],
74
+ ],
75
+ [
76
+ "维护",
77
+ [
78
+ ["key new <source|worker|channel|owner> <名字>", "新建一把密钥(只显示这一次)"],
79
+ ["key list", "有哪些密钥"],
80
+ ["key remove <种类> <名字>", "立即收回一把密钥"],
81
+ ["backup [目录]", "备份数据库、主密钥、配置、规则和 secrets.env"],
82
+ ["restore <目录> [--yes]", "停掉中台后,用一次备份恢复本机数据"],
83
+ ["update", "更新到 npm 上的最新版本"],
84
+ ["uninstall [--yes]", "卸载程序并保留数据;--yes 跳过确认"],
85
+ ["up", "启动(平时由系统服务调用)"],
86
+ ["service install|remove", "装成系统服务,开机自己起来"],
87
+ ["conformance <地址> --config <测试凭据文件>", "在测试中台上检查协议"],
88
+ ["--version", "版本(源码检出还会有提交)"],
89
+ ["help", "这份说明"],
90
+ ],
91
+ ],
92
+ ];
93
+ /** The manual as it reads on this terminal: the groups, then where the configuration and the rules live. */
94
+ function helpText() {
95
+ const style = stylesFor(colorFor(process.stdout, process.env));
96
+ const lines = [
97
+ style.bold("Agent 自动化中台"),
98
+ style.dim(versionLine().replace(/^agent-autoloop\s*/, "")),
99
+ "",
100
+ ` ${style.bold("agent-autoloop <命令> [参数]")} ${style.dim("改了 rules.json 就生效,不用重启")}`,
101
+ ];
102
+ for (const [title, entries] of HELP_GROUPS)
103
+ lines.push("", style.bold(title), ...steps(entries, { bold: style.bold, dim: style.dim, room: Math.min(process.stdout.columns || 100, 120) }));
104
+ lines.push("", ` ${style.dim("不知道从哪开始:")}${style.bold("agent-autoloop init")}`, "", style.dim(`配置和数据在 ${HOME}`), style.dim(`规则在 ${RULES_FILE},改了自动生效。`));
105
+ return lines.join("\n");
106
+ }
107
+ const INIT_USAGE = `用法:agent-autoloop init [--agent <名字>] [--command '某个命令 {prompt}'] [--port 3350] [--no-service]
72
108
 
73
- --agent 只接这个 Agent:claude 或 codex。不写就接本机装好的全部
109
+ --agent 只接这个 Agent:${AGENT_NAMES}。不写就接本机装好的全部
74
110
  --command 改用别的命令行 Agent;{prompt} 会作为一个独立参数传进去,带空格的路径用引号括起来;
75
111
  这台电脑上找不到这个程序就不装
76
112
  --port 中台监听的端口,默认 3350
@@ -82,6 +118,12 @@ const STATUS_USAGE = `用法:agent-autoloop status [--json]
82
118
 
83
119
  现在什么情况:谁在线、等你什么、在做什么、做过什么、花了多少。
84
120
  --json 输出 /v1/state 的原始结构,给脚本和看板用`;
121
+ const DASHBOARD_USAGE = `用法:agent-autoloop dashboard [--port 3351] [--no-open]
122
+
123
+ 在这台电脑上打开看板:最近 24 小时的轨道、每条规则、在跑和排着的活、等你决定的卡片。
124
+ 只读;回答卡片仍然走通道或 agent-autoloop answer。
125
+ --port 看板占用的端口,默认 3351
126
+ --no-open 不发开浏览器,只打印地址`;
85
127
  const RUNS_USAGE = `用法:agent-autoloop runs [规则] [--before <第几轮>] [--json]
86
128
 
87
129
  列出做完的轮次,新的在前,一次 20 轮:编号、结束时间、怎么样了、规则和结果。
@@ -144,6 +186,7 @@ rules.json 里这个定时任务要写 cwd;你答了,中台叫醒它的 Agen
144
186
  runs: { flags: ["before", "json"], usage: RUNS_USAGE },
145
187
  run: { flags: ["subject", "reason"], usage: "用法:agent-autoloop run <规则> [--subject 对象] [--reason 说明]" },
146
188
  service: { flags: [], usage: "用法:agent-autoloop service install|remove" },
189
+ dashboard: { flags: ["port", "no-open"], usage: DASHBOARD_USAGE },
147
190
  status: { flags: ["json"], usage: STATUS_USAGE },
148
191
  stop: { flags: [], usage: "用法:agent-autoloop stop <第几轮>" },
149
192
  tell: { flags: ["task"], usage: "用法:agent-autoloop tell <编号> [--task 定时任务名],内容从标准输入读" },
@@ -306,14 +349,13 @@ async function agentsToUse(named, worker) {
306
349
  contextFile: "",
307
350
  folder: "",
308
351
  };
309
- for (const name of ["claude", "codex"]) {
310
- if (wanted && wanted !== name)
352
+ for (const { use, name } of BUILTIN_AGENTS) {
353
+ if (wanted && wanted !== use)
311
354
  continue;
312
- const adapter = await adapterFor(name);
313
355
  try {
314
356
  // An adapter finds its program to build the command line, and throws if it's not there.
315
- adapter.command(emptyTurn);
316
- agents[name] = { name: name === "claude" ? "Claude Code" : "Codex", worker, use: name };
357
+ (await adapterFor(use)).command(emptyTurn);
358
+ agents[use] = { name, worker, use };
317
359
  }
318
360
  catch { }
319
361
  }
@@ -337,7 +379,8 @@ async function init(args) {
337
379
  if (rest.length)
338
380
  return fail(`不认识的参数:${rest.join(" ")}\n\n${INIT_USAGE}`);
339
381
  if (existsSync(CONFIG_FILE))
340
- return fail(`已经装过了:${CONFIG_FILE}`);
382
+ return fail(`已经装过了:${CONFIG_FILE}\n` +
383
+ `重装程序后接着用原来的规则和记录,运行 ${howToRun()} service install;要从头配,先删掉这个文件再运行 init。`);
341
384
  privateDirectory(HOME);
342
385
  mkdirSync(path.join(HOME, "try"), { recursive: true });
343
386
  const hostName = hostname()
@@ -346,7 +389,7 @@ async function init(args) {
346
389
  const worker = hostName.replace(/[^a-z0-9-]/g, "-").replace(/^[^a-z]+/, "") || "this-machine";
347
390
  const agents = await agentsToUse(named, worker);
348
391
  if (!Object.keys(agents).length) {
349
- return fail("这台电脑上没找到 Claude Code 或 Codex。先装好并登录," +
392
+ return fail(`这台电脑上没找到能用的命令行 Agent(${AGENT_TITLES})。先装好并登录,` +
350
393
  "或者用 --command 指定别的命令行 Agent,比如 --command 'hermes chat -Q -q {prompt}'");
351
394
  }
352
395
  const port = text(named.port) ?? "3350";
@@ -373,12 +416,26 @@ async function init(args) {
373
416
  await waitForHub();
374
417
  }
375
418
  const names = Object.values(agents).map((agent) => agent.name);
376
- const reach = ownRules ? " 通道:桌面通知\n" : "";
377
419
  const run = howToRun();
378
- const next = named["no-service"]
379
- ? `先运行 ${run} up 启动中台,再开一个终端运行 ${run} try 跑一遍完整流程。`
380
- : `运行 ${run} try 跑一遍完整流程。`;
381
- console.log(`装好了。\n Agent:${names.join("、")}\n${reach} 规则:${RULES_FILE}\n\n${next}`);
420
+ const color = colorFor(process.stdout, process.env);
421
+ const { bold, dim } = stylesFor(color);
422
+ const room = Math.min(process.stdout.columns || 100, 120);
423
+ const summary = [
424
+ `Agent ${names.join("、")}`,
425
+ ...(ownRules ? ["通道 桌面通知(先在这台电脑上试)"] : []),
426
+ `规则 ${RULES_FILE}`,
427
+ ];
428
+ for (const line of box("装好了", summary, { color, room }))
429
+ console.log(line);
430
+ const rows = named["no-service"]
431
+ ? [
432
+ [`${run} up`, "先运行它启动中台,这一步不返回"],
433
+ [`${run} try`, "另开一个终端,用你的 Agent 跑一遍完整流程"],
434
+ ]
435
+ : [[`${run} try`, "用你的 Agent 跑一遍完整流程"]];
436
+ console.log();
437
+ for (const line of steps(rows, { bold, dim, room }))
438
+ console.log(line);
382
439
  }
383
440
  async function join(args) {
384
441
  const { named, rest } = flags(args);
@@ -438,18 +495,34 @@ async function tryIt() {
438
495
  else
439
496
  console.log("事件发出去了,Agent 开始干活……");
440
497
  let asked = null;
498
+ // Five minutes with nothing on screen reads as a hang: a terminal gets the seconds going by, a pipe gets silence.
499
+ let ticker = null;
500
+ let waited = 0;
501
+ const clear = () => {
502
+ clearInterval(ticker ?? undefined);
503
+ ticker = null;
504
+ if (process.stdout.isTTY)
505
+ process.stdout.write("\r\x1b[K");
506
+ };
507
+ if (process.stdout.isTTY) {
508
+ const { dim } = stylesFor(true);
509
+ ticker = setInterval(() => process.stdout.write(`\r ${dim(`已等 ${++waited} 秒`)}`), 1000);
510
+ }
441
511
  for (let i = 0; i < 300; i++) {
442
512
  await sleep(1000);
443
513
  const state = await owner.state();
444
514
  const failed = newFailure(state.runs, attempts);
445
- if (failed)
515
+ if (failed) {
516
+ clear();
446
517
  return fail(`Agent 没跑成:${failed.error}\n运行 agent-autoloop doctor 看看。`);
518
+ }
447
519
  if (asked === null) {
448
520
  // An agent asking the same thing again lands on the card already open, so this may be from before: it's the one.
449
521
  const card = state.cards.find((open) => open.kind === "ask" && open.title.startsWith("试跑"));
450
522
  if (!card)
451
523
  continue;
452
524
  asked = card.id;
525
+ clear();
453
526
  console.log("\nAgent 结束了这一轮,问了你一个问题。它现在不占进程、不花 Token。");
454
527
  showCard(card);
455
528
  if (!process.stdin.isTTY) {
@@ -471,6 +544,42 @@ async function tryIt() {
471
544
  }
472
545
  fail("五分钟没等到结果。运行 agent-autoloop doctor 看看。");
473
546
  }
547
+ /** Opens the page in this machine's browser, if it has one: a board nobody opened is no use. */
548
+ function openPage(url) {
549
+ const [program, argv] = process.platform === "win32"
550
+ ? [process.env.ComSpec ?? "cmd.exe", ["/c", "start", "", url]]
551
+ : process.platform === "darwin"
552
+ ? ["open", [url]]
553
+ : ["xdg-open", [url]];
554
+ try {
555
+ spawn(program, argv, { detached: true, stdio: "ignore" })
556
+ .on("error", () => { })
557
+ .unref();
558
+ }
559
+ catch { }
560
+ }
561
+ async function dashboard(args) {
562
+ const { named } = flags(args);
563
+ const given = text(named.port);
564
+ const port = given === undefined ? 3351 : Number(given);
565
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
566
+ return fail(`端口要写 1 到 65535 之间的数字:${given}`);
567
+ const config = readConfig();
568
+ const { startDashboard } = await import("./dashboard.js");
569
+ const board = await startDashboard({
570
+ url: config.url,
571
+ key: config.owner ?? fail("这台电脑上没有本人的密钥(只接活的电脑看不了)"),
572
+ port,
573
+ }).catch((error) => fail(`看板起不来:${error.message}`));
574
+ console.log(`看板在 ${board.url} · 按 Ctrl-C 结束`);
575
+ if (named["no-open"] === undefined)
576
+ openPage(board.url);
577
+ const stop = Promise.withResolvers();
578
+ process.once("SIGINT", stop.resolve);
579
+ process.once("SIGTERM", stop.resolve);
580
+ await stop.promise;
581
+ board.close();
582
+ }
474
583
  async function status(named) {
475
584
  const state = await ownerClient().state();
476
585
  if (named.json !== undefined)
@@ -588,12 +697,22 @@ async function runNow(args) {
588
697
  console.log(`排上了:第 ${done.run} 轮。`);
589
698
  }
590
699
  async function doctor() {
700
+ const style = stylesFor(colorFor(process.stdout, process.env));
591
701
  let bad = 0;
592
702
  const say = (ok, words) => {
593
- console.log(`${ok ? "●" : "○"} ${words}`);
703
+ console.log(` ${ok ? style.green("●") : style.red("○")} ${words}`);
594
704
  if (!ok)
595
705
  bad += 1;
596
706
  };
707
+ // What the person can't fix by turning something on stays a note, so the exit code means "something is off".
708
+ const note = (words) => console.log(` ${style.yellow("○")} ${words}`);
709
+ let started = 0;
710
+ const group = (title) => {
711
+ if (started++)
712
+ console.log();
713
+ console.log(style.bold(title));
714
+ };
715
+ group("这台电脑");
597
716
  say(Number(process.versions.node.split(".")[0]) >= 24, `Node ${process.versions.node}`);
598
717
  if (!existsSync(CONFIG_FILE))
599
718
  return say(false, "还没装好:运行 agent-autoloop init");
@@ -605,7 +724,7 @@ async function doctor() {
605
724
  for (const [id, channel] of Object.entries(channels)) {
606
725
  // Nobody answers from a desktop notification, and a link goes only to whoever it's sent to.
607
726
  if (id !== "desktop" && !channel.links && !channel.answerers) {
608
- console.log(`○ ${channel.name}没写 answerers:这个通道里谁都能回答卡片。`);
727
+ note(`${channel.name}没写 answerers:这个通道里谁都能回答卡片。`);
609
728
  }
610
729
  }
611
730
  }
@@ -629,29 +748,35 @@ async function doctor() {
629
748
  if (config.owner) {
630
749
  try {
631
750
  const state = await ownerClient(config).state();
632
- for (const agent of state.agents) {
633
- say(agent.online, `${agent.name}(${agent.worker})${agent.online ? "在线" : "不在线"}`);
634
- if (agent.worker === config.worker?.name) {
635
- const { adapterFor } = await import("../worker/agents.js");
636
- const problem = await adapterFor(agent.use).then((adapter) => adapter.check?.(agent.program) ?? null, (error) => String(error.message));
637
- say(!problem, problem ?? `${agent.name} 可以用`);
751
+ if (state.agents.length) {
752
+ group("Agent");
753
+ for (const agent of state.agents) {
754
+ const mine = agent.worker === config.worker?.name;
755
+ let problem = null;
756
+ if (mine) {
757
+ const { adapterFor } = await import("../worker/agents.js");
758
+ problem = await adapterFor(agent.use).then((adapter) => adapter.check?.(agent.program) ?? null, (error) => String(error.message));
759
+ }
760
+ const usable = problem ? `,${style.red("用不了")}:${problem}` : mine ? `,${style.green("可以用")}` : "";
761
+ say(agent.online && !problem, `${agent.name}(${agent.worker})${agent.online ? "在线" : "不在线"}${usable}`);
638
762
  }
639
763
  }
764
+ group("通道");
640
765
  for (const channel of state.channels) {
641
- say(channel.online, `${channel.name}${channel.online ? "在线" : "不在线"}`);
766
+ say(channel.online, `${channel.name} ${channel.online ? "在线" : "不在线"}`);
642
767
  const failure = channel.lastFailure;
643
768
  if (!failure)
644
769
  continue;
645
770
  // Not "still retrying": a card closed before it got through is never tried again, though its failure stays the last.
646
771
  const tried = `试了 ${failure.tries} 次${failure.givenUp ? ",已经不再重试" : ""}`;
647
- say(false, `${channel.name}最近一张卡片(#${failure.card})没送到:${failure.error}(${tried})`);
772
+ say(false, `最近一张卡片(#${failure.card})没送到:${failure.error}(${tried})`);
648
773
  }
649
774
  const manual = path.join(ROOT, "skills", "agent-autoloop", "SKILL.md");
650
775
  if (!state.channels.length) {
651
- console.log(`○ 还没接通道:Agent 问你时不会主动告诉你,要自己运行 agent-autoloop status 看。接法见 ${manual}`);
776
+ note(`还没接通道:Agent 问你时不会主动告诉你,要自己运行 agent-autoloop status 看。接法见 ${manual}`);
652
777
  }
653
778
  else if (state.channels.length === 1 && state.channels[0].id === "desktop") {
654
- console.log("○ 只接了桌面通知:Agent 问你时只有这台电脑会弹通知,人不在电脑前、或者电脑没有图形界面就看不到。" +
779
+ note("只接了桌面通知:Agent 问你时只有这台电脑会弹通知,人不在电脑前、或者电脑没有图形界面就看不到。" +
655
780
  `要发到飞书、钉钉这些地方,接法见 ${manual}`);
656
781
  }
657
782
  }
@@ -966,6 +1091,7 @@ const commands = {
966
1091
  join: () => join(args),
967
1092
  up: async () => (await import("../host/up.js")).up(),
968
1093
  try: () => tryIt(),
1094
+ dashboard: () => dashboard(args),
969
1095
  status: () => status(flags(args).named),
970
1096
  why: () => why(args),
971
1097
  runs: () => runs(args),
@@ -997,13 +1123,13 @@ const commands = {
997
1123
  await uninstall(flags(args).named.yes !== undefined, process.stdin.isTTY ? askAtTerminal : null);
998
1124
  },
999
1125
  service: () => service(args),
1000
- help: () => console.log(HELP),
1001
- "--help": () => console.log(HELP),
1002
- "-h": () => console.log(HELP),
1126
+ help: () => console.log(helpText()),
1127
+ "--help": () => console.log(helpText()),
1128
+ "-h": () => console.log(helpText()),
1003
1129
  "--version": () => console.log(versionLine()),
1004
1130
  };
1005
1131
  if (!command || !commands[command]) {
1006
- console.log(HELP);
1132
+ console.log(helpText());
1007
1133
  if (command)
1008
1134
  process.exit(1);
1009
1135
  }
@@ -1,54 +1,11 @@
1
1
  // `agent-autoloop status` for a person: what waits for them first, then what's going on, then what only reports.
2
2
  // Colour only on a terminal: a pipe, a file or an Agent reading it gets plain text, and scripts use --json.
3
3
  import { spendLines } from "./spend.js";
4
- /** https://no-color.org: set and not empty turns colour off. */
5
- export const colorFor = (out, env) => out.isTTY === true && !env.NO_COLOR;
6
- // Hangul Jamo, CJK radicals through Yi, Hangul syllables, compatibility ideographs and forms, full-width forms, and the
7
- // supplementary ideograph planes: the characters a terminal draws two columns wide.
8
- const WIDE = /[ᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩\u{20000}-\u{3fffd}]/u;
9
- const ANSI = /\x1b\[[0-9;]*m/g;
10
- export const width = (text) => [...text.replace(ANSI, "")].reduce((sum, char) => sum + (WIDE.test(char) ? 2 : 1), 0);
11
- const pad = (text, to) => text + " ".repeat(Math.max(0, to - width(text)));
12
- const CLOSING = ",。;:!?、)」』”,.;:!?)";
13
- /** Plain text in lines no wider than `room`, at most `max` of them, the last cut with "…". */
14
- function wrap(text, room, max = Infinity) {
15
- const lines = [];
16
- for (const paragraph of text.split("\n")) {
17
- let line = "";
18
- for (const char of paragraph) {
19
- // Closing punctuation stays with what it closes rather than starting a line.
20
- if (line && width(line + char) > room && !CLOSING.includes(char)) {
21
- // A Latin word goes to the next line whole; the space it breaks at isn't kept.
22
- const space = line.lastIndexOf(" ");
23
- const word = line.slice(space + 1);
24
- const whole = char !== " " && space > 0 && /^[\x21-\x7e]+$/.test(word) && /[\x21-\x7e]/.test(char);
25
- lines.push((whole ? line.slice(0, space) : line).trimEnd());
26
- line = whole ? word : "";
27
- if (char === " ")
28
- continue;
29
- }
30
- line += char;
31
- }
32
- lines.push(line);
33
- }
34
- if (lines.length <= max)
35
- return lines;
36
- const kept = lines.slice(0, max);
37
- let last = kept[max - 1];
38
- while (last && width(last + "…") > room)
39
- last = [...last].slice(0, -1).join("");
40
- kept[max - 1] = `${last}…`;
41
- return kept;
42
- }
4
+ import { pad, rule, steps, stylesFor, width, wrap } from "./ui.js";
5
+ export { colorFor, width } from "./ui.js";
43
6
  const LINK = /\[([^\]]+)\]\(([^)\s]+)\)/g;
44
7
  const unlinked = (text) => text.replace(LINK, "$1");
45
8
  const WEEK = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
46
- /** Colours that are there only on a terminal. */
47
- function stylesFor(color) {
48
- const sgr = (code) => (text) => color ? `\x1b[${code}m${text}\x1b[0m` : text;
49
- const [bold, dim, underline, red, green, yellow, magenta, cyan] = ["1", "2", "4", "31", "32", "33", "35", "36"].map(sgr);
50
- return { bold, dim, underline, red, green, yellow, magenta, cyan, heading: sgr("1;34") };
51
- }
52
9
  /** Times as a person reads them, in the hub's time zone, counted from the hub's now. */
53
10
  export function clockFor(state) {
54
11
  const zone = state.timezone;
@@ -136,6 +93,7 @@ export function render(state, { color, columns }) {
136
93
  const say = (line = "") => out.push(line);
137
94
  const section = (title) => {
138
95
  say();
96
+ say(rule(room, dim));
139
97
  say(title);
140
98
  };
141
99
  const { totals } = state;
@@ -300,5 +258,15 @@ export function render(state, { color, columns }) {
300
258
  const words = `${sourceName(event.source)} ${event.type} ${event.subject}`;
301
259
  say(` ${yellow(words)}${event.summary ? dim(`:${event.summary}`) : ""}`);
302
260
  }
261
+ // What this view only reports on, one command away.
262
+ const last = state.runs[0];
263
+ say();
264
+ const rows = [
265
+ [`agent-autoloop why ${last ? last.id : "<第几轮>"}`, "一轮的经过"],
266
+ ["agent-autoloop runs", "往前翻"],
267
+ ["agent-autoloop doctor", "哪里没配好"],
268
+ ];
269
+ for (const line of steps(rows, { bold: dim, dim, room }))
270
+ say(line);
303
271
  return out.join("\n");
304
272
  }
package/dist/cli/ui.js ADDED
@@ -0,0 +1,75 @@
1
+ /** https://no-color.org: set and not empty turns colour off. */
2
+ export const colorFor = (out, env) => out.isTTY === true && !env.NO_COLOR;
3
+ // Hangul Jamo, CJK radicals through Yi, Hangul syllables, compatibility ideographs and forms, full-width forms, and the
4
+ // supplementary ideograph planes: the characters a terminal draws two columns wide.
5
+ const WIDE = /[ᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩\u{20000}-\u{3fffd}]/u;
6
+ const ANSI = /\x1b\[[0-9;]*m/g;
7
+ export const width = (text) => [...text.replace(ANSI, "")].reduce((sum, char) => sum + (WIDE.test(char) ? 2 : 1), 0);
8
+ export const pad = (text, to) => text + " ".repeat(Math.max(0, to - width(text)));
9
+ const CLOSING = ",。;:!?、)」』”,.;:!?)";
10
+ /** Plain text in lines no wider than `room`, at most `max` of them, the last cut with "…". */
11
+ export function wrap(text, room, max = Infinity) {
12
+ const lines = [];
13
+ for (const paragraph of text.split("\n")) {
14
+ let line = "";
15
+ for (const char of paragraph) {
16
+ // Closing punctuation stays with what it closes rather than starting a line.
17
+ if (line && width(line + char) > room && !CLOSING.includes(char)) {
18
+ // A Latin word goes to the next line whole; the space it breaks at isn't kept.
19
+ const space = line.lastIndexOf(" ");
20
+ const word = line.slice(space + 1);
21
+ const whole = char !== " " && space > 0 && /^[\x21-\x7e]+$/.test(word) && /[\x21-\x7e]/.test(char);
22
+ lines.push((whole ? line.slice(0, space) : line).trimEnd());
23
+ line = whole ? word : "";
24
+ if (char === " ")
25
+ continue;
26
+ }
27
+ line += char;
28
+ }
29
+ lines.push(line);
30
+ }
31
+ if (lines.length <= max)
32
+ return lines;
33
+ const kept = lines.slice(0, max);
34
+ let last = kept[max - 1];
35
+ while (last && width(last + "…") > room)
36
+ last = [...last].slice(0, -1).join("");
37
+ kept[max - 1] = `${last}…`;
38
+ return kept;
39
+ }
40
+ /** Colours that are there only on a terminal. */
41
+ export function stylesFor(color) {
42
+ const sgr = (code) => (text) => color ? `\x1b[${code}m${text}\x1b[0m` : text;
43
+ const [bold, dim, underline, red, green, yellow, magenta, cyan] = ["1", "2", "4", "31", "32", "33", "35", "36"].map(sgr);
44
+ return { bold, dim, underline, red, green, yellow, magenta, cyan, heading: sgr("1;34") };
45
+ }
46
+ /** The line a section starts under, no wider than the room a row has. */
47
+ export const rule = (room, dim) => dim("─".repeat(Math.max(0, Math.min(room, 120))));
48
+ /** What to type next, one command a row, the descriptions lined up after the longest of them that still fits; a longer
49
+ * command keeps its own line so the rest don't drift far to the right. Descriptions wrap inside `room`. */
50
+ export function steps(rows, { bold, dim, limit = 46, room = Infinity }) {
51
+ const widest = Math.min(limit, Math.max(0, ...rows.map(([command]) => width(command))));
52
+ const out = [];
53
+ for (const [command, what] of rows) {
54
+ if (width(command) > widest) {
55
+ out.push(` ${bold(command)}`);
56
+ for (const line of wrap(what, room - 6))
57
+ out.push(` ${dim(line)}`);
58
+ continue;
59
+ }
60
+ const indent = ` ${" ".repeat(widest + 2)}`;
61
+ const lines = wrap(what, room - width(indent));
62
+ out.push(` ${bold(pad(command, widest))} ${dim(lines[0] ?? "")}`);
63
+ for (const line of lines.slice(1))
64
+ out.push(indent + dim(line));
65
+ }
66
+ return out;
67
+ }
68
+ /** A short summary in a rounded frame: long lines wrap inside it rather than running past its edge. */
69
+ export function box(title, lines, { color, room }) {
70
+ const { bold, dim } = stylesFor(color);
71
+ const inner = Math.max(width(title) + 1, Math.min(room - 4, Math.max(0, ...lines.map((line) => width(line)))));
72
+ const top = `╭─ ${bold(title)} ${dim("─".repeat(Math.max(0, inner - width(title) - 1)))}╮`;
73
+ const body = lines.flatMap((line) => wrap(line, inner)).map((line) => `│ ${pad(line, inner)} │`);
74
+ return [top, ...body, `╰${dim("─".repeat(inner + 2))}╯`];
75
+ }
@@ -80,5 +80,7 @@ export async function uninstall(yes, ask) {
80
80
  }
81
81
  rmSync(installedApp, { recursive: true });
82
82
  }
83
- console.log(existsSync(HOME) ? `卸载好了。规则、密钥和记录还留在 ${HOME}。` : "卸载好了。");
83
+ console.log(existsSync(HOME)
84
+ ? `卸载好了。规则、密钥和记录还留在 ${HOME};重装后运行 agent-autoloop service install 接着用,不用 init。`
85
+ : "卸载好了。");
84
86
  }
package/dist/host/http.js CHANGED
@@ -26,6 +26,8 @@ export function serve(port, host = "127.0.0.1", { commit = "dev" } = {}) {
26
26
  res.writeHead(answer.status, Object.fromEntries(answer.headers));
27
27
  if (!answer.body)
28
28
  return void res.end();
29
+ // Node holds the head until the first chunk: a quiet stream would look like a closed one to whoever is listening.
30
+ res.flushHeaders();
29
31
  Readable.fromWeb(answer.body)
30
32
  .on("error", () => res.destroy())
31
33
  .pipe(res);
@@ -583,6 +583,10 @@ function tick(draft) {
583
583
  const rule = ruleNamed(draft, timer.rule);
584
584
  const event = { id: `timer:${timer.id}`, type: "timer.due", subject: timer.lane, hops: timer.hops ?? 0 };
585
585
  const eventId = recordEvent(draft, timer.source, event, rule ? [rule.name] : []);
586
+ // The row these were written on is removed once the round this wakes ends, and an answer can wake a round after that:
587
+ // they travel with the event itself, which every later reader already has (#338).
588
+ if (timer.events)
589
+ put(draft, "events", eventId, { events: timer.events });
586
590
  if (rule) {
587
591
  put(draft, "timers", timer.id, { event_id: eventId });
588
592
  enqueue(draft, rule, eventId, timer.lane, timer.agent === rule.to ? timer.session : null);
@@ -36,10 +36,11 @@ export function askedAbout(view, runId, seen = new Set()) {
36
36
  const ids = eventsOf(view, runId).flatMap((event) => {
37
37
  const cards = rows(view, "cards", { answer_event: event.id });
38
38
  if (cards.length === 0) {
39
- // A check that came due: its row names no run, so what it was set for was written on it when it was set; the row
40
- // itself is gone once this round ends. A check set before that was written down keeps its own event.
39
+ // A check that came due: what it was set for was written on the event when it fired, and on the row before that for
40
+ // logs written then. The row is gone once the round it wakes ends, and an answer can wake a round later still.
41
41
  const [fired] = rows(view, "timers", { event_id: event.id }).filter((timer) => timer.events);
42
- return fired ? JSON.parse(fired.events) : [event.key];
42
+ const written = event.events ?? fired?.events;
43
+ return written ? JSON.parse(written) : [event.key];
43
44
  }
44
45
  return cards.flatMap((card) => (card.run_id === null ? [event.key] : askedAbout(view, card.run_id, seen)));
45
46
  });