@saltpub/agent-autoloop 0.0.0-stage → 0.1.3

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.
Files changed (177) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/INSTALL.md +120 -0
  3. package/LICENSE +21 -0
  4. package/README.en.md +268 -0
  5. package/README.md +264 -2
  6. package/SECURITY.md +49 -0
  7. package/dist/bin/agent-autoloop.js +2 -0
  8. package/dist/cli/agents.js +14 -0
  9. package/dist/cli/backup.js +144 -0
  10. package/dist/cli/dashboard/app.js +424 -0
  11. package/dist/cli/dashboard/index.html +15 -0
  12. package/dist/cli/dashboard/style.css +629 -0
  13. package/dist/cli/dashboard.js +94 -0
  14. package/dist/cli/explain.js +84 -0
  15. package/dist/cli/main.js +1142 -0
  16. package/dist/cli/mcp.js +151 -0
  17. package/dist/cli/runs.js +40 -0
  18. package/dist/cli/spend.js +21 -0
  19. package/dist/cli/status.js +272 -0
  20. package/dist/cli/try.js +6 -0
  21. package/dist/cli/ui.js +75 -0
  22. package/dist/cli/uninstall.js +86 -0
  23. package/dist/cli/update.js +65 -0
  24. package/dist/cli/why.js +115 -0
  25. package/dist/host/background-launcher.js +12 -0
  26. package/dist/host/background.js +24 -0
  27. package/dist/host/channels.js +4 -0
  28. package/dist/host/command.js +98 -0
  29. package/dist/host/config.js +37 -0
  30. package/dist/host/files.js +22 -0
  31. package/dist/host/home.js +5 -0
  32. package/dist/host/http.js +45 -0
  33. package/dist/host/launcher.js +188 -0
  34. package/dist/host/lines.js +15 -0
  35. package/dist/host/node-path.js +33 -0
  36. package/dist/host/npm.js +28 -0
  37. package/dist/host/plugins.js +26 -0
  38. package/dist/host/program.js +14 -0
  39. package/dist/host/runtime.js +179 -0
  40. package/dist/host/server.js +159 -0
  41. package/dist/host/service.js +325 -0
  42. package/dist/host/state.js +203 -0
  43. package/dist/host/up.js +162 -0
  44. package/dist/host/update.js +286 -0
  45. package/dist/host/version.js +81 -0
  46. package/dist/kernel/card-page.js +54 -0
  47. package/dist/kernel/credentials.js +16 -0
  48. package/dist/kernel/cron.js +135 -0
  49. package/dist/kernel/decide.js +826 -0
  50. package/dist/kernel/due.js +73 -0
  51. package/dist/kernel/errors.js +9 -0
  52. package/dist/kernel/evolve.js +264 -0
  53. package/dist/kernel/http.js +357 -0
  54. package/dist/kernel/query.js +202 -0
  55. package/dist/kernel/rules.js +20 -0
  56. package/dist/kernel/store.js +52 -0
  57. package/dist/plugins/acp/agent.js +32 -0
  58. package/dist/plugins/acp/bridge.js +204 -0
  59. package/dist/plugins/claude/agent.js +113 -0
  60. package/dist/plugins/codex/agent.js +105 -0
  61. package/dist/plugins/command/agent.js +25 -0
  62. package/dist/plugins/delivery/action.js +25 -0
  63. package/dist/plugins/delivery/agent.js +13 -0
  64. package/dist/plugins/delivery/delivery.js +388 -0
  65. package/dist/plugins/delivery/github.js +201 -0
  66. package/dist/plugins/delivery/handoff.js +50 -0
  67. package/dist/plugins/delivery/input.js +47 -0
  68. package/dist/plugins/delivery/poll.js +72 -0
  69. package/dist/plugins/delivery/project.js +144 -0
  70. package/dist/plugins/delivery/review-ledger.js +82 -0
  71. package/dist/plugins/delivery/review-policy.js +99 -0
  72. package/dist/plugins/delivery/review.js +280 -0
  73. package/dist/plugins/delivery/run.js +204 -0
  74. package/dist/plugins/desktop/channel.js +94 -0
  75. package/dist/plugins/dsh/agent.js +116 -0
  76. package/dist/plugins/feishu/channel.js +245 -0
  77. package/dist/plugins/github/source.js +30 -0
  78. package/dist/plugins/gitlab/source.js +30 -0
  79. package/dist/plugins/omp/agent.js +3 -0
  80. package/dist/plugins/opencode/agent.js +88 -0
  81. package/dist/plugins/pi/agent.js +92 -0
  82. package/dist/plugins/webhook/channel.js +70 -0
  83. package/dist/plugins/webhook/templates.js +34 -0
  84. package/dist/plugins/xiaojiu/channel.js +410 -0
  85. package/dist/plugins/zcode/agent.js +102 -0
  86. package/dist/protocol/client.js +56 -0
  87. package/dist/protocol/conformance.js +184 -0
  88. package/dist/protocol/job.js +1 -0
  89. package/dist/protocol/rules.js +230 -0
  90. package/dist/protocol/schema.js +70 -0
  91. package/dist/protocol/schema.json +985 -0
  92. package/dist/protocol/validate.js +150 -0
  93. package/dist/worker/agents.js +47 -0
  94. package/dist/worker/contract.js +178 -0
  95. package/dist/worker/run.js +52 -0
  96. package/dist/worker/usage.js +45 -0
  97. package/dist/worker/windows.ps1 +48 -0
  98. package/dist/worker/worker.js +595 -0
  99. package/docs/architecture.en.svg +178 -0
  100. package/docs/architecture.svg +178 -0
  101. package/docs/auto-update.md +53 -0
  102. package/docs/plugins.md +139 -0
  103. package/docs/protocol.md +582 -0
  104. package/docs/state-machines.md +77 -0
  105. package/examples/channel.sh +15 -0
  106. package/examples/plugins/hello-agent/agent.ts +40 -0
  107. package/examples/plugins/hello-channel/channel.ts +54 -0
  108. package/examples/plugins/hello-source/source.ts +19 -0
  109. package/examples/recipes/browser-handoff/README.md +44 -0
  110. package/examples/recipes/browser-handoff/SKILL.md +22 -0
  111. package/examples/recipes/browser-handoff/browser.json +10 -0
  112. package/examples/recipes/browser-handoff/handoff.ts +44 -0
  113. package/examples/recipes/browser-handoff/rules.json +19 -0
  114. package/examples/recipes/feedback/README.md +34 -0
  115. package/examples/recipes/feedback/SKILL.md +22 -0
  116. package/examples/recipes/feedback/event.json +8 -0
  117. package/examples/recipes/feedback/rules.json +37 -0
  118. package/examples/recipes/feishu-brief/README.md +28 -0
  119. package/examples/recipes/feishu-brief/SKILL.md +16 -0
  120. package/examples/recipes/feishu-brief/collect.ts +164 -0
  121. package/examples/recipes/feishu-brief/rules.json +57 -0
  122. package/examples/recipes/feishu-brief/sources.json +13 -0
  123. package/examples/recipes/github-issues/README.md +17 -0
  124. package/examples/recipes/github-issues/SKILL.md +18 -0
  125. package/examples/recipes/github-issues/rules.json +30 -0
  126. package/examples/recipes/inbox-triage/README.md +36 -0
  127. package/examples/recipes/inbox-triage/SKILL.md +19 -0
  128. package/examples/recipes/inbox-triage/collect.ts +191 -0
  129. package/examples/recipes/inbox-triage/rules.json +57 -0
  130. package/examples/recipes/inbox-triage/sources.json +8 -0
  131. package/examples/recipes/morning-brief/README.md +17 -0
  132. package/examples/recipes/morning-brief/SKILL.md +17 -0
  133. package/examples/recipes/morning-brief/rules.json +16 -0
  134. package/examples/recipes/ops-alerts/README.md +18 -0
  135. package/examples/recipes/ops-alerts/SKILL.md +34 -0
  136. package/examples/recipes/ops-alerts/restart.sh +5 -0
  137. package/examples/recipes/ops-alerts/rules.json +29 -0
  138. package/examples/recipes/website-watch/README.md +26 -0
  139. package/examples/recipes/website-watch/SKILL.md +19 -0
  140. package/examples/recipes/website-watch/check.ts +86 -0
  141. package/examples/recipes/website-watch/rules.json +56 -0
  142. package/examples/recipes/website-watch/site.json +6 -0
  143. package/examples/skills/weekly-sweep/SKILL.md +17 -0
  144. package/examples/watch-github-issues.sh +23 -0
  145. package/examples/worker.sh +18 -0
  146. package/package.json +57 -4
  147. package/plugins/acp/agent.ts +31 -0
  148. package/plugins/acp/bridge.ts +190 -0
  149. package/plugins/claude/agent.ts +121 -0
  150. package/plugins/codex/agent.ts +103 -0
  151. package/plugins/command/agent.ts +25 -0
  152. package/plugins/delivery/action.ts +29 -0
  153. package/plugins/delivery/action.yml +28 -0
  154. package/plugins/delivery/agent.ts +15 -0
  155. package/plugins/delivery/delivery.ts +408 -0
  156. package/plugins/delivery/github.ts +207 -0
  157. package/plugins/delivery/handoff.ts +72 -0
  158. package/plugins/delivery/input.ts +55 -0
  159. package/plugins/delivery/poll.ts +65 -0
  160. package/plugins/delivery/project.ts +161 -0
  161. package/plugins/delivery/review-ledger.ts +90 -0
  162. package/plugins/delivery/review-policy.ts +126 -0
  163. package/plugins/delivery/review.ts +324 -0
  164. package/plugins/delivery/run.ts +219 -0
  165. package/plugins/desktop/channel.ts +100 -0
  166. package/plugins/dsh/agent.ts +100 -0
  167. package/plugins/feishu/channel.ts +243 -0
  168. package/plugins/github/source.ts +33 -0
  169. package/plugins/gitlab/source.ts +32 -0
  170. package/plugins/omp/agent.ts +4 -0
  171. package/plugins/opencode/agent.ts +78 -0
  172. package/plugins/pi/agent.ts +80 -0
  173. package/plugins/webhook/channel.ts +74 -0
  174. package/plugins/webhook/templates.ts +32 -0
  175. package/plugins/xiaojiu/channel.ts +426 -0
  176. package/plugins/zcode/agent.ts +96 -0
  177. package/skills/agent-autoloop/SKILL.md +260 -0
@@ -0,0 +1,1142 @@
1
+ // The command line: what a person, or their Agent, types.
2
+ import { spawn, spawnSync } from "node:child_process";
3
+ import { randomUUID } from "node:crypto";
4
+ import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
5
+ import { hostname } from "node:os";
6
+ import path from "node:path";
7
+ import { createInterface } from "node:readline/promises";
8
+ import { hubClient } from "../protocol/client.js";
9
+ import { parseRules } from "../protocol/rules.js";
10
+ import { CONFIG_FILE, readConfig, writeConfig } from "../host/config.js";
11
+ import { HOME, RULES_FILE } from "../host/home.js";
12
+ import { findOnPath, psQuote } from "../host/command.js";
13
+ import { privateDirectory } from "../host/files.js";
14
+ import { aboveDesktop, installService, removeService, restartService, runningUp, serviceLogs, serviceRunning, startupInstead, systemUnit, untilAnswering, } from "../host/service.js";
15
+ import { versionLine } from "../host/version.js";
16
+ import { ENTRY as PROGRAM, ROOT } from "../host/program.js";
17
+ import { pointSkill } from "../host/update.js";
18
+ import { AGENT_NAMES, AGENT_TITLES, BUILTIN_AGENTS } from "./agents.js";
19
+ import { clockFor, colorFor, render, replayCommand, skippedLine } from "./status.js";
20
+ import { box, steps, stylesFor } from "./ui.js";
21
+ import { attemptsOf, newFailure, waitingRetry } from "./try.js";
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]
108
+
109
+ --agent 只接这个 Agent:${AGENT_NAMES}。不写就接本机装好的全部
110
+ --command 改用别的命令行 Agent;{prompt} 会作为一个独立参数传进去,带空格的路径用引号括起来;
111
+ 这台电脑上找不到这个程序就不装
112
+ --port 中台监听的端口,默认 3350
113
+ --no-service 先不装系统服务,之后手动运行 agent-autoloop up`;
114
+ const TRY_USAGE = `用法:agent-autoloop try
115
+
116
+ 用本机接好的 Agent 跑一遍完整流程:提问,进程退出等你回复,你拍板,它接着干完。`;
117
+ const STATUS_USAGE = `用法:agent-autoloop status [--json]
118
+
119
+ 现在什么情况:谁在线、等你什么、在做什么、做过什么、花了多少。
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 不发开浏览器,只打印地址`;
127
+ const RUNS_USAGE = `用法:agent-autoloop runs [规则] [--before <第几轮>] [--json]
128
+
129
+ 列出做完的轮次,新的在前,一次 20 轮:编号、结束时间、怎么样了、规则和结果。
130
+ 规则 只看这一条规则的
131
+ --before 从这一轮往前列,接着上一次列到的地方
132
+ --json 输出这些轮次的原始结构和下一页的 before,给脚本用`;
133
+ const UPDATE_USAGE = `用法:agent-autoloop update
134
+
135
+ 更新到最新发布的版本。没有参数。`;
136
+ const UNINSTALL_USAGE = `用法:agent-autoloop uninstall [--yes]
137
+
138
+ 卸载程序并保留规则、密钥和记录。
139
+ --yes 跳过确认`;
140
+ const RESTORE_USAGE = `用法:agent-autoloop restore <目录> [--yes]
141
+
142
+ 恢复会替换本机的数据库、主密钥、配置、规则和 secrets.env;先停掉中台,--yes 跳过确认。`;
143
+ /** What each command reads besides its own words, and how to use it. */
144
+ const TAKES = {
145
+ add: { flags: [], usage: "用法:agent-autoloop add <git 地址>" },
146
+ answer: { flags: ["text"], usage: "用法:agent-autoloop answer <卡片> [序号] [--text 别的想法]" },
147
+ ask: {
148
+ flags: ["task"],
149
+ usage: `用法:agent-autoloop ask --task <定时任务名>,问题从标准输入读:
150
+ { "title": "…", "text": "…", "options": ["…", "…"], "recommend": 0, "about": "留给接着做的", "key": "这件事的固定名字" }
151
+ rules.json 里这个定时任务要写 cwd;你答了,中台叫醒它的 Agent 在 cwd 照 skill、prompt 接着做。`,
152
+ },
153
+ backup: { flags: [], usage: "用法:agent-autoloop backup [目录]" },
154
+ check: { flags: [], usage: "用法:agent-autoloop check [文件]" },
155
+ conformance: { flags: ["config"], usage: "用法:agent-autoloop conformance <测试中台地址> --config <测试凭据文件>" },
156
+ doctor: { flags: [], usage: "用法:agent-autoloop doctor" },
157
+ emit: {
158
+ flags: ["dry-run", "subject", "summary", "detail", "link", "id", "key"],
159
+ usage: "用法:agent-autoloop emit <类型> [--dry-run] [--subject x] [--summary x] [--detail x] [--link x] [--id x] [--key 来源密钥]",
160
+ },
161
+ init: { flags: ["agent", "command", "port", "no-service"], usage: INIT_USAGE },
162
+ join: {
163
+ flags: ["worker", "key", "no-service"],
164
+ usage: "用法:agent-autoloop join <中台地址> --worker <名字> --key <密钥> [--no-service]",
165
+ },
166
+ key: {
167
+ flags: [],
168
+ usage: `用法:agent-autoloop key new <source|worker|channel|owner> <名字>
169
+ agent-autoloop key list
170
+ agent-autoloop key remove <种类> <名字>`,
171
+ },
172
+ mcp: { flags: [], usage: "用法:agent-autoloop mcp" },
173
+ pause: {
174
+ flags: ["reason", "until"],
175
+ usage: "用法:agent-autoloop pause <规则> [--reason 原因] [--until 时间]",
176
+ },
177
+ // Only its first word is read as anything: the rest is a result in someone's own words, dashes and all.
178
+ resolve: { flags: [], usage: "用法:agent-autoloop resolve <卡片> <结果>" },
179
+ restore: { flags: ["yes"], usage: RESTORE_USAGE },
180
+ resume: { flags: [], usage: "用法:agent-autoloop resume <规则>" },
181
+ replay: {
182
+ flags: ["since"],
183
+ usage: "用法:agent-autoloop replay <规则> --since <时间>(恢复时打印的就是这条命令)",
184
+ },
185
+ rules: { flags: [], usage: "用法:agent-autoloop rules explain [文件]" },
186
+ runs: { flags: ["before", "json"], usage: RUNS_USAGE },
187
+ run: { flags: ["subject", "reason"], usage: "用法:agent-autoloop run <规则> [--subject 对象] [--reason 说明]" },
188
+ service: { flags: [], usage: "用法:agent-autoloop service install|remove" },
189
+ dashboard: { flags: ["port", "no-open"], usage: DASHBOARD_USAGE },
190
+ status: { flags: ["json"], usage: STATUS_USAGE },
191
+ stop: { flags: [], usage: "用法:agent-autoloop stop <第几轮>" },
192
+ tell: { flags: ["task"], usage: "用法:agent-autoloop tell <编号> [--task 定时任务名],内容从标准输入读" },
193
+ try: { flags: [], usage: TRY_USAGE },
194
+ uninstall: { flags: ["yes"], usage: UNINSTALL_USAGE },
195
+ up: { flags: [], usage: "用法:agent-autoloop up" },
196
+ update: { flags: [], usage: UPDATE_USAGE },
197
+ why: { flags: ["json"], usage: "用法:agent-autoloop why <第几轮> [--json]" },
198
+ };
199
+ function flags(args) {
200
+ const named = {};
201
+ const rest = [];
202
+ for (let i = 0; i < args.length; i++) {
203
+ if (!args[i].startsWith("--")) {
204
+ rest.push(args[i]);
205
+ continue;
206
+ }
207
+ const name = args[i].slice(2);
208
+ if (args[i + 1] !== undefined && !args[i + 1].startsWith("--"))
209
+ named[name] = args[++i];
210
+ else
211
+ named[name] = true;
212
+ }
213
+ return { named, rest };
214
+ }
215
+ const text = (value) => (typeof value === "string" ? value : undefined);
216
+ const fail = (words) => {
217
+ console.error(words);
218
+ process.exit(1);
219
+ };
220
+ /**
221
+ * Stops at a flag the command doesn't read. A misspelt --port would otherwise install with the default in silence, and
222
+ * --help would install at all.
223
+ */
224
+ function refuseUnknownFlags(args, { flags: known, usage }) {
225
+ if (args.includes("--help") || args.includes("-h")) {
226
+ console.log(usage);
227
+ process.exit(0);
228
+ }
229
+ const unknown = Object.keys(flags(args).named).filter((name) => !known.includes(name));
230
+ if (unknown.length)
231
+ fail(`不认识的参数:${unknown.map((name) => `--${name}`).join("、")}\n\n${usage}`);
232
+ }
233
+ const client = (key, config = readConfig()) => hubClient(config.url, key);
234
+ const ownerClient = (config = readConfig()) => client(config.owner ?? fail("这台电脑上没有本人的密钥(只接活的电脑看不了)"), config);
235
+ /** The first rules of a new install: its agents and one rule to try the whole loop with. */
236
+ function starterRules(agents, first) {
237
+ return {
238
+ sources: { local: { name: "本机" } },
239
+ agents,
240
+ channels: { desktop: { name: "桌面通知" } },
241
+ rules: [
242
+ {
243
+ name: "试一下",
244
+ when: { source: "local", types: ["try.*"] },
245
+ to: first,
246
+ cwd: path.join(HOME, "try"),
247
+ prompt: "这是 agent-autoloop try 的试跑,不要改任何文件,不要做别的事。读资料文件。" +
248
+ "如果 answers 是空的,就问一个问题:title 写“试跑:选一个颜色”,text 写“这是一次试跑,选哪个都行。”," +
249
+ 'options 写 ["蓝色","绿色"],key 写 try-color,第一行结论写“问了一个问题”。' +
250
+ "如果 answers 不是空的,第一行结论写“你选了某某,试跑通过”,把某某换成 answers 里的 chosen(所选那项的文字),不附回执。",
251
+ },
252
+ ],
253
+ elsewhere: [],
254
+ };
255
+ }
256
+ /** Shows the user's Agents how to set it up: one link in the shared skills folder every Agent reads, and the manual's
257
+ * relative paths lead to the documents and plugin sources of the version that's running. */
258
+ function linkSkill() {
259
+ pointSkill();
260
+ }
261
+ /** What to type to run this program: its name if that's what a shell finds, otherwise where it is. */
262
+ function howToRun() {
263
+ if (process.platform === "win32") {
264
+ const found = findOnPath("agent-autoloop");
265
+ // npm's shim names this package rather than sitting inside its folder.
266
+ let ours = false;
267
+ try {
268
+ ours =
269
+ found !== null &&
270
+ readFileSync(found, "utf8").replaceAll("\\", "/").includes("node_modules/@saltpub/agent-autoloop/");
271
+ }
272
+ catch { }
273
+ if (ours)
274
+ return "agent-autoloop";
275
+ return `& ${psQuote(process.execPath)} ${psQuote(PROGRAM)}`;
276
+ }
277
+ const found = spawnSync("/bin/sh", ["-c", "command -v agent-autoloop"], { encoding: "utf8" }).stdout.trim();
278
+ if (found && realpathSync(found) === realpathSync(PROGRAM))
279
+ return "agent-autoloop";
280
+ return /\s/.test(PROGRAM) ? `'${PROGRAM}'` : PROGRAM;
281
+ }
282
+ /**
283
+ * A command line split the way a shell would: spaces part words, quotes keep one together and are dropped. No escapes, as
284
+ * a Windows path is all backslashes. Null when a quote is left open.
285
+ */
286
+ function commandWords(line) {
287
+ const words = [];
288
+ let word = null;
289
+ let quote = null;
290
+ for (const char of line) {
291
+ if (quote) {
292
+ if (char === quote)
293
+ quote = null;
294
+ else
295
+ word += char;
296
+ }
297
+ else if (char === '"' || char === "'") {
298
+ quote = char;
299
+ word ??= "";
300
+ }
301
+ else if (/\s/.test(char)) {
302
+ if (word !== null)
303
+ words.push(word);
304
+ word = null;
305
+ }
306
+ else
307
+ word = (word ?? "") + char;
308
+ }
309
+ if (quote)
310
+ return null;
311
+ if (word !== null)
312
+ words.push(word);
313
+ return words;
314
+ }
315
+ /** What was asked for on the command line, or whichever of the usual Agents is installed. */
316
+ async function agentsToUse(named, worker) {
317
+ const agents = {};
318
+ const { adapterFor, findProgram } = await import("../worker/agents.js");
319
+ const command = text(named.command);
320
+ if (command) {
321
+ const words = commandWords(command);
322
+ if (!words?.length)
323
+ return fail(`--command 里有没配对的引号:${command}`);
324
+ // Found now, or every run of every rule fails later with the install long said to be done.
325
+ const [first] = words;
326
+ const there = /[\\/]/.test(first)
327
+ ? existsSync(path.resolve(first))
328
+ : /^[\w.+@-]+$/.test(first) &&
329
+ (() => {
330
+ try {
331
+ return Boolean(findProgram(first));
332
+ }
333
+ catch {
334
+ return false;
335
+ }
336
+ })();
337
+ if (!there)
338
+ return fail(`找不到 ${first}:先装好它,或者在 --command 里写它的完整路径。`);
339
+ agents.agent = { name: "Agent", worker, use: "command", command: words };
340
+ return agents;
341
+ }
342
+ const wanted = text(named.agent);
343
+ const emptyTurn = {
344
+ prompt: "",
345
+ session: "",
346
+ resume: null,
347
+ cwd: "",
348
+ access: "edit",
349
+ contextFile: "",
350
+ folder: "",
351
+ };
352
+ for (const { use, name } of BUILTIN_AGENTS) {
353
+ if (wanted && wanted !== use)
354
+ continue;
355
+ try {
356
+ // An adapter finds its program to build the command line, and throws if it's not there.
357
+ (await adapterFor(use)).command(emptyTurn);
358
+ agents[use] = { name, worker, use };
359
+ }
360
+ catch { }
361
+ }
362
+ return agents;
363
+ }
364
+ /** An npm install gets the managed layout before its service points at it; a checkout keeps running itself. */
365
+ async function prepareManagedInstall() {
366
+ try {
367
+ const { prepareManaged } = await import("../host/update.js");
368
+ const pointer = prepareManaged(ROOT);
369
+ if (pointer)
370
+ console.log(`程序副本:${pointer.dir}`);
371
+ }
372
+ catch (error) {
373
+ console.log(`没能准备自动更新:${error.message}。服务会直接运行当前程序。`);
374
+ }
375
+ }
376
+ async function init(args) {
377
+ const { named, rest } = flags(args);
378
+ // `init -p 4000` would otherwise install on the default port in silence.
379
+ if (rest.length)
380
+ return fail(`不认识的参数:${rest.join(" ")}\n\n${INIT_USAGE}`);
381
+ if (existsSync(CONFIG_FILE))
382
+ return fail(`已经装过了:${CONFIG_FILE}\n` +
383
+ `重装程序后接着用原来的规则和记录,运行 ${howToRun()} service install;要从头配,先删掉这个文件再运行 init。`);
384
+ privateDirectory(HOME);
385
+ mkdirSync(path.join(HOME, "try"), { recursive: true });
386
+ const hostName = hostname()
387
+ .toLowerCase()
388
+ .replace(/\.local$/, "");
389
+ const worker = hostName.replace(/[^a-z0-9-]/g, "-").replace(/^[^a-z]+/, "") || "this-machine";
390
+ const agents = await agentsToUse(named, worker);
391
+ if (!Object.keys(agents).length) {
392
+ return fail(`这台电脑上没找到能用的命令行 Agent(${AGENT_TITLES})。先装好并登录,` +
393
+ "或者用 --command 指定别的命令行 Agent,比如 --command 'hermes chat -Q -q {prompt}'");
394
+ }
395
+ const port = text(named.port) ?? "3350";
396
+ const url = `http://127.0.0.1:${port}`;
397
+ const ownRules = !existsSync(RULES_FILE);
398
+ if (ownRules) {
399
+ writeFileSync(RULES_FILE, `${JSON.stringify(starterRules(agents, Object.keys(agents)[0]), null, 2)}\n`);
400
+ }
401
+ const { addKey } = await import("../host/runtime.js");
402
+ const config = {
403
+ url,
404
+ hub: { listen: `127.0.0.1:${port}`, publicUrl: url },
405
+ worker: { name: worker, key: addKey("worker", worker) },
406
+ source: { name: "local", key: addKey("source", "local") },
407
+ owner: addKey("owner", "owner"),
408
+ // A channel only rules.json knows about, or only this file, would do nothing: it's on only if both are ours to write.
409
+ ...(ownRules && { channels: { desktop: { key: addKey("channel", "desktop") } } }),
410
+ };
411
+ writeConfig(config);
412
+ await prepareManagedInstall();
413
+ linkSkill();
414
+ if (!named["no-service"]) {
415
+ installService();
416
+ await waitForHub();
417
+ }
418
+ const names = Object.values(agents).map((agent) => agent.name);
419
+ const run = howToRun();
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);
439
+ }
440
+ async function join(args) {
441
+ const { named, rest } = flags(args);
442
+ const [url] = rest;
443
+ const name = text(named.worker);
444
+ const key = text(named.key);
445
+ if (!url || !name || !key)
446
+ return fail(TAKES.join.usage);
447
+ // Joining another hub must not silently replace this machine's existing hub, worker or owner keys.
448
+ if (existsSync(CONFIG_FILE)) {
449
+ return fail(`已经配置过了:${CONFIG_FILE}。为防止覆盖现有设置,请先备份并手动修改配置。`);
450
+ }
451
+ writeConfig({ url, worker: { name, key } });
452
+ if (!named["no-service"])
453
+ installService();
454
+ const next = named["no-service"] ? `运行 ${howToRun()} up 开始。` : "";
455
+ console.log(`这台电脑以 ${name} 的身份接活了。${next}`);
456
+ }
457
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
458
+ function showCard(card) {
459
+ console.log(`\n【${card.kind === "ask" ? "等你决定" : "要你留意"}】#${card.id} ${card.title}`);
460
+ if (card.text)
461
+ console.log(card.text);
462
+ if (card.kind !== "ask")
463
+ return;
464
+ card.options.forEach((option, index) => {
465
+ console.log(` ${index + 1}. ${option}${index === card.recommend ? "(推荐)" : ""}`);
466
+ });
467
+ }
468
+ const howToAnswer = (card) => card.kind === "ask" ? `回答:agent-autoloop answer ${card.id} <序号>` : `处理完了:agent-autoloop answer ${card.id}`;
469
+ async function chooseAt(terminal, card) {
470
+ for (;;) {
471
+ const choice = Number(await terminal.question("\n选几?"));
472
+ if (Number.isInteger(choice) && choice >= 1 && choice <= card.options.length)
473
+ return choice - 1;
474
+ console.log(`输入 1 到 ${card.options.length}。`);
475
+ }
476
+ }
477
+ async function tryIt() {
478
+ const config = readConfig();
479
+ if (!config.source)
480
+ return fail("这台电脑上没有来源的密钥。");
481
+ const owner = ownerClient(config);
482
+ const stamp = Date.now();
483
+ // A hub that can't be reached is said just below, when the event doesn't go through.
484
+ const before = await owner.state().catch(() => ({ runs: [] }));
485
+ const attempts = attemptsOf(before.runs);
486
+ await client(config.source.key, config)
487
+ .event({ id: `try-${stamp}`, type: "try.start", subject: `#${stamp}` })
488
+ .catch((error) => fail(`连不上中台(${error.message}):先 agent-autoloop up 或 agent-autoloop service install`));
489
+ const retrying = waitingRetry(before.runs);
490
+ if (retrying) {
491
+ const clock = { timeZone: before.timezone, hour: "2-digit", minute: "2-digit", hourCycle: "h23" };
492
+ const time = new Date(retrying.notBefore).toLocaleString("zh-CN", clock);
493
+ console.log(`上一次没跑成(${retrying.error}),${time} 会自动再试,这次的事件会一起处理。`);
494
+ }
495
+ else
496
+ console.log("事件发出去了,Agent 开始干活……");
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
+ }
511
+ for (let i = 0; i < 300; i++) {
512
+ await sleep(1000);
513
+ const state = await owner.state();
514
+ const failed = newFailure(state.runs, attempts);
515
+ if (failed) {
516
+ clear();
517
+ return fail(`Agent 没跑成:${failed.error}\n运行 agent-autoloop doctor 看看。`);
518
+ }
519
+ if (asked === null) {
520
+ // An agent asking the same thing again lands on the card already open, so this may be from before: it's the one.
521
+ const card = state.cards.find((open) => open.kind === "ask" && open.title.startsWith("试跑"));
522
+ if (!card)
523
+ continue;
524
+ asked = card.id;
525
+ clear();
526
+ console.log("\nAgent 结束了这一轮,问了你一个问题。它现在不占进程、不花 Token。");
527
+ showCard(card);
528
+ if (!process.stdin.isTTY) {
529
+ console.log(`${howToAnswer(card)}\n答完运行 agent-autoloop status,能看到它接着把活干完。`);
530
+ return;
531
+ }
532
+ const terminal = createInterface({ input: process.stdin, output: process.stdout });
533
+ const choice = await chooseAt(terminal, card);
534
+ terminal.close();
535
+ await owner.answer(card.id, { choice });
536
+ console.log("收到,Agent 接着干……");
537
+ continue;
538
+ }
539
+ const done = state.recentCards.find((card) => card.id === asked && card.state === "done");
540
+ if (done) {
541
+ console.log(`它把活干完了:${done.result}\n\n通了。接下来把 ${RULES_FILE} 改成你自己的规则,或者跟你的 Agent 说一句。`);
542
+ return;
543
+ }
544
+ }
545
+ fail("五分钟没等到结果。运行 agent-autoloop doctor 看看。");
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
+ }
583
+ async function status(named) {
584
+ const state = await ownerClient().state();
585
+ if (named.json !== undefined)
586
+ return console.log(JSON.stringify(state, null, 2));
587
+ console.log(render(state, { color: colorFor(process.stdout, process.env), columns: process.stdout.columns }));
588
+ }
589
+ async function runs(args) {
590
+ const { named, rest } = flags(args);
591
+ if (rest.length > 1 || named.before === true)
592
+ return fail(RUNS_USAGE);
593
+ const before = named.before === undefined ? undefined : runOf(named.before, RUNS_USAGE);
594
+ const owner = ownerClient();
595
+ const { findRuns, runsText } = await import("./runs.js");
596
+ const found = await findRuns((at) => owner.state(at), { rule: rest[0], before });
597
+ if (named.json !== undefined)
598
+ return console.log(JSON.stringify({ runs: found.runs, before: found.more }, null, 2));
599
+ const color = colorFor(process.stdout, process.env);
600
+ console.log(runsText(found, { rule: rest[0], color, columns: process.stdout.columns }));
601
+ }
602
+ async function answer(args) {
603
+ const { named, rest } = flags(args);
604
+ const card = Number(rest[0]);
605
+ if (!Number.isInteger(card) || card < 1)
606
+ return fail(TAKES.answer.usage);
607
+ const words = text(named.text);
608
+ const done = await ownerClient().answer(card, {
609
+ ...(rest[1] !== undefined && { choice: Number(rest[1]) - 1 }),
610
+ ...(words && { text: words }),
611
+ });
612
+ console.log(!done.changed
613
+ ? "这张卡片已经处理过了,这次没有改动。"
614
+ : done.state === "closed"
615
+ ? "结案了。"
616
+ : "收到,Agent 接着干。");
617
+ }
618
+ async function resolve(args) {
619
+ const [id, ...words] = args;
620
+ const card = Number(id);
621
+ if (!Number.isInteger(card) || card < 1 || !words.length)
622
+ return fail(TAKES.resolve.usage);
623
+ const { changed } = await ownerClient().resolve(card, words.join(" "));
624
+ console.log(changed ? "结案了。" : "这张卡片已经处理过了,这次没有改动。");
625
+ }
626
+ async function pause(args) {
627
+ const { named, rest } = flags(args);
628
+ const body = {
629
+ ...(text(named.reason) && { reason: text(named.reason) }),
630
+ ...(text(named.until) && { until: text(named.until) }),
631
+ };
632
+ if (!rest[0])
633
+ return fail(TAKES.pause.usage);
634
+ const done = await ownerClient().pause(rest[0], body);
635
+ const { since, until, skipped } = done.paused;
636
+ const ends = until ? `,${localClock().when(until)} 自动恢复` : "";
637
+ const lines = [done.changed ? `暂停了「${done.rule}」${ends}。` : `「${done.rule}」本来就暂停着${ends}。`];
638
+ // A schedule lets its moments pass and keeps no events.
639
+ if (skipped === null)
640
+ lines.push("暂停期间到点不跑,恢复后也不补跑错过的时段。");
641
+ else if (!until)
642
+ lines.push("暂停期间来的事件这条规则不接,也不排队等恢复;恢复时会列出这些事件,可以补跑。");
643
+ // Nobody reads anything when a pause ends by itself, so the way to replay is told now.
644
+ else
645
+ lines.push("暂停期间来的事件这条规则不接,也不排队;到时不会列出,之后补跑:", ` ${replayCommand(done.rule, since)}`);
646
+ if (skipped?.count)
647
+ lines.push(`到现在跳过了 ${skipped.count} 条事件。`);
648
+ console.log(lines.join("\n"));
649
+ }
650
+ /** Times from the hub as they read here, for what answers a command rather than the state. */
651
+ const localClock = () => clockFor({ now: new Date().toISOString(), timezone: Intl.DateTimeFormat().resolvedOptions().timeZone });
652
+ async function resume(args) {
653
+ const { rest } = flags(args);
654
+ if (!rest[0])
655
+ return fail(TAKES.resume.usage);
656
+ const done = await ownerClient().resume(rest[0]);
657
+ if (!done.changed)
658
+ return console.log(`「${done.rule}」本来就没暂停。`);
659
+ const { since, skipped } = done.paused ?? {};
660
+ const { when } = localClock();
661
+ const lines = [`恢复了「${done.rule}」。`];
662
+ if (skipped === null)
663
+ lines[0] += "错过的时段不补跑,从下一个时刻照常跑。";
664
+ else if (skipped?.count === 0)
665
+ lines[0] += "暂停期间没有跳过事件。";
666
+ else if (skipped) {
667
+ lines[0] += `暂停期间(${when(since)} 起)跳过了 ${skipped.count} 条事件,没有补跑:`;
668
+ const room = Math.min(process.stdout.columns || 100, 120) - 2;
669
+ for (const event of skipped.events)
670
+ lines.push(` ${skippedLine(event, room, when)}`);
671
+ if (skipped.count > skipped.events.length) {
672
+ lines.push(` 共 ${skipped.count} 条,这里列出最近 ${skipped.events.length} 条`);
673
+ }
674
+ lines.push(`补跑这 ${skipped.count} 条:${replayCommand(done.rule, since)}`);
675
+ }
676
+ console.log(lines.join("\n"));
677
+ }
678
+ async function replay(args) {
679
+ const { named, rest } = flags(args);
680
+ const since = text(named.since);
681
+ if (!rest[0] || !since)
682
+ return fail(TAKES.replay.usage);
683
+ const done = await ownerClient().replay(rest[0], { since });
684
+ if (!done.events.length)
685
+ return console.log("没有要补跑的事件:这段时间没有跳过的,或者都已经补跑过了。");
686
+ console.log(`补跑了 ${done.events.length} 条,排上了第 ${done.runs.join("、")} 轮。`);
687
+ }
688
+ async function runNow(args) {
689
+ const { named, rest } = flags(args);
690
+ if (!rest[0])
691
+ return fail(TAKES.run.usage);
692
+ const body = {
693
+ ...(text(named.subject) && { subject: text(named.subject) }),
694
+ ...(text(named.reason) && { reason: text(named.reason) }),
695
+ };
696
+ const done = await ownerClient().run(rest[0], body);
697
+ console.log(`排上了:第 ${done.run} 轮。`);
698
+ }
699
+ async function doctor() {
700
+ const style = stylesFor(colorFor(process.stdout, process.env));
701
+ let bad = 0;
702
+ const say = (ok, words) => {
703
+ console.log(` ${ok ? style.green("●") : style.red("○")} ${words}`);
704
+ if (!ok)
705
+ bad += 1;
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("这台电脑");
716
+ say(Number(process.versions.node.split(".")[0]) >= 24, `Node ${process.versions.node}`);
717
+ if (!existsSync(CONFIG_FILE))
718
+ return say(false, "还没装好:运行 agent-autoloop init");
719
+ const config = readConfig();
720
+ if (config.hub) {
721
+ try {
722
+ const { channels } = checkRulesFile(RULES_FILE);
723
+ say(true, `规则 ${RULES_FILE}`);
724
+ for (const [id, channel] of Object.entries(channels)) {
725
+ // Nobody answers from a desktop notification, and a link goes only to whoever it's sent to.
726
+ if (id !== "desktop" && !channel.links && !channel.answerers) {
727
+ note(`${channel.name}没写 answerers:这个通道里谁都能回答卡片。`);
728
+ }
729
+ }
730
+ }
731
+ catch (error) {
732
+ say(false, error.message);
733
+ }
734
+ }
735
+ if (serviceRunning())
736
+ say(true, "系统服务在跑");
737
+ else if (systemUnit())
738
+ say(true, "系统级服务在跑");
739
+ else
740
+ say(false, "系统服务没在跑:agent-autoloop service install");
741
+ try {
742
+ const health = await (await fetch(`${config.url}/healthz`, { signal: AbortSignal.timeout(5000) })).json();
743
+ say(health.ok === true, `中台 ${config.url}(${String(health.commit).slice(0, 12)})`);
744
+ }
745
+ catch (error) {
746
+ say(false, `连不上中台 ${config.url}:${error.cause?.code ?? error.message}`);
747
+ }
748
+ if (config.owner) {
749
+ try {
750
+ const state = await ownerClient(config).state();
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}`);
762
+ }
763
+ }
764
+ group("通道");
765
+ for (const channel of state.channels) {
766
+ say(channel.online, `${channel.name} ${channel.online ? "在线" : "不在线"}`);
767
+ const failure = channel.lastFailure;
768
+ if (!failure)
769
+ continue;
770
+ // Not "still retrying": a card closed before it got through is never tried again, though its failure stays the last.
771
+ const tried = `试了 ${failure.tries} 次${failure.givenUp ? ",已经不再重试" : ""}`;
772
+ say(false, `最近一张卡片(#${failure.card})没送到:${failure.error}(${tried})`);
773
+ }
774
+ const manual = path.join(ROOT, "skills", "agent-autoloop", "SKILL.md");
775
+ if (!state.channels.length) {
776
+ note(`还没接通道:Agent 问你时不会主动告诉你,要自己运行 agent-autoloop status 看。接法见 ${manual}`);
777
+ }
778
+ else if (state.channels.length === 1 && state.channels[0].id === "desktop") {
779
+ note("只接了桌面通知:Agent 问你时只有这台电脑会弹通知,人不在电脑前、或者电脑没有图形界面就看不到。" +
780
+ `要发到飞书、钉钉这些地方,接法见 ${manual}`);
781
+ }
782
+ }
783
+ catch (error) {
784
+ say(false, `读不到中台状态:${error.message}`);
785
+ }
786
+ }
787
+ if (bad)
788
+ process.exit(1);
789
+ }
790
+ /** Only reads the file: checking a draft must not open the hub's database or load the draft into it. */
791
+ function checkRulesFile(file) {
792
+ let json;
793
+ try {
794
+ json = readFileSync(file, "utf8");
795
+ }
796
+ catch (error) {
797
+ throw new Error(`读不到 ${file}:${error.code ?? error.message}`);
798
+ }
799
+ return parseRules(json, Date.now(), Intl.DateTimeFormat().resolvedOptions().timeZone);
800
+ }
801
+ function check(args) {
802
+ const file = path.resolve(args[0] ?? RULES_FILE);
803
+ checkRulesFile(file);
804
+ console.log(`规则没问题:${file}`);
805
+ }
806
+ async function key(args) {
807
+ const [action, kind, name] = args;
808
+ if (action === "remove") {
809
+ if (!kind || !name)
810
+ return fail("用法:agent-autoloop key remove <种类> <名字>");
811
+ const { changed } = await ownerClient().removeKey(kind, name);
812
+ console.log(changed ? "密钥已失效。" : "没有这把密钥,可能已经删过了。");
813
+ return;
814
+ }
815
+ const { addKey, listKeys } = await import("../host/runtime.js");
816
+ if (action === "list") {
817
+ for (const row of listKeys())
818
+ console.log(`${row.kind} ${row.name} ${row.created_at}`);
819
+ return;
820
+ }
821
+ if (action !== "new" || !["source", "worker", "channel", "owner"].includes(kind) || !name) {
822
+ return fail("用法:agent-autoloop key new <source|worker|channel|owner> <名字>");
823
+ }
824
+ console.log(addKey(kind, name));
825
+ }
826
+ async function emit(args) {
827
+ const { named, rest } = flags(args);
828
+ const config = readConfig();
829
+ const type = rest[0] ?? fail(TAKES.emit.usage);
830
+ const event = {
831
+ id: text(named.id) ?? randomUUID(),
832
+ type,
833
+ ...(text(named.subject) && { subject: text(named.subject) }),
834
+ ...(text(named.summary) && { summary: text(named.summary) }),
835
+ ...(text(named.detail) && { detail: text(named.detail) }),
836
+ ...(text(named.link) && { link: text(named.link) }),
837
+ };
838
+ if (named["dry-run"] !== undefined) {
839
+ // The hub tells a source by its key, and only the key's own source is known here.
840
+ if (text(named.key))
841
+ return fail("--dry-run 按这台电脑的来源预演,不能和 --key 一起用");
842
+ if (!config.source)
843
+ return fail("这台电脑上没有来源的密钥:--dry-run 需要知道来源名");
844
+ const { previewEvent } = await import("./explain.js");
845
+ console.log("预演(按本机 rules.json,不连接中台、不写日志):");
846
+ for (const line of previewEvent(readFileSync(RULES_FILE, "utf8"), config.source.name, event))
847
+ console.log(line);
848
+ return;
849
+ }
850
+ const secret = text(named.key) ?? config.source?.key ?? fail("这台电脑上没有来源的密钥:用 --key");
851
+ const answer = await client(secret, config).event(event);
852
+ const paused = answer.paused?.length ? `暂停中没接:${answer.paused.join("、")}` : "";
853
+ if (answer.routed.length)
854
+ console.log(`交给了:${answer.routed.join("、")}${paused && `;${paused}`}`);
855
+ else
856
+ console.log(paused ? `记下了,${paused}。` : "记下了,没有规则接它。");
857
+ }
858
+ async function backupCommand(args) {
859
+ const { rest } = flags(args);
860
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
861
+ const target = path.resolve(rest[0] ?? path.join(HOME, "backups", stamp));
862
+ const { backup } = await import("./backup.js");
863
+ const { files } = await backup(HOME, target);
864
+ console.log(`备份好了:${target}\n ${files.join("、")}\n里面有密钥,把它放到安全的地方;恢复要中台停下来。`);
865
+ }
866
+ async function restoreCommand(args) {
867
+ const { named, rest } = flags(args);
868
+ if (!rest[0])
869
+ return fail(RESTORE_USAGE);
870
+ if (named.yes === undefined) {
871
+ if (!process.stdin.isTTY)
872
+ return fail("恢复会替换本机数据;确认后运行 agent-autoloop restore <目录> --yes");
873
+ const answer = await askAtTerminal("恢复会替换本机的数据库、主密钥、配置、规则和 secrets.env,继续?[y/N] ");
874
+ if (!/^y(es)?$/i.test(answer.trim())) {
875
+ console.log("没有恢复。");
876
+ return;
877
+ }
878
+ }
879
+ const { restore } = await import("./backup.js");
880
+ const { safety } = await restore(HOME, path.resolve(rest[0]));
881
+ console.log(`恢复好了。原来的文件在 ${safety}。\n启动:agent-autoloop up 或 agent-autoloop service install`);
882
+ }
883
+ async function rulesCommand(args) {
884
+ const { rest } = flags(args);
885
+ if (rest[0] !== "explain" || rest.length > 2)
886
+ return fail(TAKES.rules.usage);
887
+ const file = rest[1] ? path.resolve(rest[1]) : RULES_FILE;
888
+ let text;
889
+ try {
890
+ text = readFileSync(file, "utf8");
891
+ }
892
+ catch (error) {
893
+ return fail(`读不到 ${file}:${error.message}`);
894
+ }
895
+ const { explainRules } = await import("./explain.js");
896
+ for (const line of explainRules(text, Date.now()))
897
+ console.log(line);
898
+ }
899
+ async function tell(args) {
900
+ const { named, rest } = flags(args);
901
+ const config = readConfig();
902
+ const matter = rest[0] ?? fail(TAKES.tell.usage);
903
+ const words = readFileSync(0, "utf8").trim();
904
+ if (!words)
905
+ return fail("要说的话从标准输入传,不能为空。");
906
+ const task = text(named.task);
907
+ const secret = task ? config.worker?.key : config.source?.key;
908
+ if (!secret)
909
+ return fail(task ? "这台电脑不是接单程序" : "这台电脑上没有来源的密钥");
910
+ const answer = await client(secret, config).tell({ key: matter, text: words, ...(task && { task }) });
911
+ console.log(answer.duplicate ? "这件事已经说过了,这次没再发。" : "说了。");
912
+ }
913
+ async function ask(args) {
914
+ const { named, rest } = flags(args);
915
+ const task = text(named.task);
916
+ if (!task || rest.length)
917
+ return fail(TAKES.ask.usage);
918
+ let question;
919
+ try {
920
+ question = JSON.parse(readFileSync(0, "utf8"));
921
+ }
922
+ catch {
923
+ return fail("问题从标准输入传,是一段 JSON:和回执里的 ask 一样");
924
+ }
925
+ const config = readConfig();
926
+ if (!config.worker)
927
+ return fail("这台电脑不是接单程序");
928
+ const answer = await client(config.worker.key, config).tell({ task, ask: question });
929
+ console.log(answer.duplicate ? "同一件事还在等你回答,这次没再问。" : "问了。");
930
+ }
931
+ /** A run is named by its number; anything else would reach the hub as /v1/runs/NaN and come back as "没有这个地址". */
932
+ function runOf(word, usage) {
933
+ const id = Number(word);
934
+ if (word === undefined || !/^[1-9][0-9]*$/.test(word) || !Number.isSafeInteger(id))
935
+ return fail(usage);
936
+ return id;
937
+ }
938
+ async function why(args) {
939
+ const id = runOf(args.find((arg) => !arg.startsWith("--")), "用法:agent-autoloop why <第几轮> [--json]");
940
+ const facts = await ownerClient().why(id);
941
+ if (args.includes("--json"))
942
+ return console.log(JSON.stringify(facts, null, 2));
943
+ const { formatWhy } = await import("./why.js");
944
+ console.log(formatWhy(id, facts));
945
+ }
946
+ async function checkConformance(args) {
947
+ const { named, rest } = flags(args);
948
+ const file = text(named.config) ?? process.env.AGENT_AUTOLOOP_CONFORMANCE;
949
+ if (!rest[0] || !file)
950
+ return fail(TAKES.conformance.usage);
951
+ const { conformance } = await import("../protocol/conformance.js");
952
+ console.log(JSON.stringify(await conformance(rest[0], JSON.parse(readFileSync(file, "utf8"))), null, 2));
953
+ }
954
+ async function stop(args) {
955
+ const id = runOf(args[0], "用法:agent-autoloop stop <第几轮>");
956
+ await ownerClient().cancel(id);
957
+ console.log("通知它停了。");
958
+ }
959
+ /** A command run right after starting the service would find no hub yet: this machine's is waited for, if it has one. */
960
+ async function waitForHub() {
961
+ const config = readConfig();
962
+ if (!config.hub)
963
+ return;
964
+ const answering = await untilAnswering(config.url);
965
+ if (answering === false) {
966
+ const log = serviceLogs();
967
+ const last = existsSync(log) ? readFileSync(log, "utf8").trimEnd().split("\n").slice(-5).join("\n") : "";
968
+ console.error(`系统服务起了,但中台 20 秒内没有应答。看看日志:${log}${last ? `\n\n${last}` : ""}`);
969
+ }
970
+ // A login task asks for the user's limited token, and the built-in Administrator gets the full one all the same.
971
+ const hub = answering && process.platform === "win32" ? runningUp() : null;
972
+ if (hub !== null && aboveDesktop(hub)) {
973
+ removeService();
974
+ fail("登录任务拉起的中台拿到了比你的桌面高的完整管理员权限,它派的每个 Agent 也会带着,所以没有装这个任务" +
975
+ `(Windows 自带的 Administrator 账号会这样)。${startupInstead()}`);
976
+ }
977
+ }
978
+ /** fetch says only "fetch failed" when no hub answers; which hub, why and what to do are what a person can act on. */
979
+ function plainly(error) {
980
+ if (!(error instanceof TypeError && error.message === "fetch failed"))
981
+ return error?.message ?? String(error);
982
+ let url = "";
983
+ try {
984
+ url = readConfig().url;
985
+ }
986
+ catch { }
987
+ const cause = error.cause;
988
+ const why = cause?.code ?? cause?.message;
989
+ return (`连不上中台 ${url}${why ? `(${why})` : ""}:中台没在运行,或者刚启动还没好。` +
990
+ "在中台那台电脑上运行 agent-autoloop service install 启动它;刚装好、刚更新的等几秒再试。");
991
+ }
992
+ async function service(args) {
993
+ if (args[0] === "install") {
994
+ // Installing over kept data comes here and not to init, and uninstalling took the links away.
995
+ await prepareManagedInstall();
996
+ linkSkill();
997
+ installService();
998
+ return waitForHub();
999
+ }
1000
+ if (args[0] === "remove")
1001
+ return removeService();
1002
+ fail(TAKES.service.usage);
1003
+ }
1004
+ /** A plugin is a folder of its own under this install, named after its repository. */
1005
+ function addPlugin(args) {
1006
+ const url = args[0] ?? fail(TAKES.add.usage);
1007
+ const name = url
1008
+ .replace(/\/$/, "")
1009
+ .split(/[/:]/)
1010
+ .at(-1)
1011
+ .replace(/\.git$/, "")
1012
+ .toLowerCase();
1013
+ if (!/^[a-z][a-z0-9-]*$/.test(name))
1014
+ fail(`插件名字「${name}」不能用:只能用小写字母、数字和 -,规则里的 use 也写这个名字`);
1015
+ mkdirSync(path.join(HOME, "plugins"), { recursive: true });
1016
+ const clone = spawnSync("git", ["clone", "--", url, path.join(HOME, "plugins", name)], { stdio: "inherit" });
1017
+ if (clone.status !== 0)
1018
+ fail("安装失败。");
1019
+ console.log(`已安装 ${name}。`);
1020
+ }
1021
+ /** What the hub is doing right now; a hub that isn't answering has nothing to cut short. */
1022
+ async function activeRunCount() {
1023
+ try {
1024
+ const state = await ownerClient().state();
1025
+ return state.runs.filter((run) => ["queued", "claimed", "unknown"].includes(run.state)).length;
1026
+ }
1027
+ catch {
1028
+ return 0;
1029
+ }
1030
+ }
1031
+ async function update() {
1032
+ const { managedAt, prepareManaged, stageLatest } = await import("../host/update.js");
1033
+ // Installed before versions were unpacked: update the npm package, then put the new files under the launcher.
1034
+ if (!managedAt(HOME)) {
1035
+ const { updateCode } = await import("./update.js");
1036
+ const { changed, to } = updateCode(ROOT);
1037
+ if (changed) {
1038
+ let managed = false;
1039
+ try {
1040
+ managed = prepareManaged(ROOT) !== null;
1041
+ }
1042
+ catch (error) {
1043
+ console.log(`自动更新没准备好:${error.message}`);
1044
+ }
1045
+ if (managed) {
1046
+ installService();
1047
+ await waitForHub();
1048
+ return console.log(`更新好了(${to}),服务已从新副本启动。`);
1049
+ }
1050
+ }
1051
+ const version = to ? `(${to})` : "";
1052
+ if (!changed)
1053
+ return console.log(`已经是最新的${version}。`);
1054
+ const told = restartService();
1055
+ if (told === undefined)
1056
+ await waitForHub();
1057
+ console.log(`更新好了${version}。${told ?? ""}`);
1058
+ return;
1059
+ }
1060
+ const running = await activeRunCount();
1061
+ if (running > 0)
1062
+ return fail(`还有 ${running} 轮在跑,等它们做完再更新。`);
1063
+ const result = stageLatest();
1064
+ if (result.status === "current")
1065
+ return console.log(`已经是最新的(v${result.version})。`);
1066
+ if (result.status === "pending")
1067
+ return console.log(`v${result.version} 已经准备好,中台重启时换上。`);
1068
+ if (result.status === "bad")
1069
+ return fail(`v${result.version} 之前启动失败过,先不装它;修好后删掉 ${path.join(HOME, "update", "bad.json")} 再试。`);
1070
+ if (result.status === "busy")
1071
+ return fail("另一个更新正在准备,过一会儿再看。");
1072
+ if (result.status === "unmanaged")
1073
+ return fail("这个副本不在受管理的位置里,没法按版本更新。");
1074
+ const told = restartService();
1075
+ const service = serviceRunning();
1076
+ if (told === undefined && service)
1077
+ await waitForHub();
1078
+ console.log(`更新好了(v${result.version})。${told ?? (service ? "" : "下次启动中台时换上。")}`);
1079
+ }
1080
+ async function askAtTerminal(question) {
1081
+ const terminal = createInterface({ input: process.stdin, output: process.stdout });
1082
+ const answer = await terminal.question(question);
1083
+ terminal.close();
1084
+ return answer;
1085
+ }
1086
+ const [command, ...args] = process.argv.slice(2);
1087
+ const commands = {
1088
+ mcp: async () => (await import("./mcp.js")).mcp(),
1089
+ add: () => addPlugin(args),
1090
+ init: () => init(args),
1091
+ join: () => join(args),
1092
+ up: async () => (await import("../host/up.js")).up(),
1093
+ try: () => tryIt(),
1094
+ dashboard: () => dashboard(args),
1095
+ status: () => status(flags(args).named),
1096
+ why: () => why(args),
1097
+ runs: () => runs(args),
1098
+ conformance: () => checkConformance(args),
1099
+ answer: () => answer(args),
1100
+ resolve: () => resolve(args),
1101
+ doctor,
1102
+ check: () => check(args),
1103
+ rules: () => rulesCommand(args),
1104
+ pause: () => pause(args),
1105
+ resume: () => resume(args),
1106
+ replay: () => replay(args),
1107
+ run: () => runNow(args),
1108
+ key: () => key(args),
1109
+ emit: () => emit(args),
1110
+ tell: () => tell(args),
1111
+ ask: () => ask(args),
1112
+ stop: () => stop(args),
1113
+ backup: () => backupCommand(args),
1114
+ restore: () => restoreCommand(args),
1115
+ update,
1116
+ "stage-update": async () => {
1117
+ const { stageLatest } = await import("../host/update.js");
1118
+ const result = stageLatest();
1119
+ console.log(`${new Date().toISOString()} ${JSON.stringify(result)}`);
1120
+ },
1121
+ uninstall: async () => {
1122
+ const { uninstall } = await import("./uninstall.js");
1123
+ await uninstall(flags(args).named.yes !== undefined, process.stdin.isTTY ? askAtTerminal : null);
1124
+ },
1125
+ service: () => service(args),
1126
+ help: () => console.log(helpText()),
1127
+ "--help": () => console.log(helpText()),
1128
+ "-h": () => console.log(helpText()),
1129
+ "--version": () => console.log(versionLine()),
1130
+ };
1131
+ if (!command || !commands[command]) {
1132
+ console.log(helpText());
1133
+ if (command)
1134
+ process.exit(1);
1135
+ }
1136
+ else {
1137
+ if (TAKES[command])
1138
+ refuseUnknownFlags(command === "resolve" ? args.slice(0, 1) : args, TAKES[command]);
1139
+ Promise.resolve()
1140
+ .then(commands[command])
1141
+ .catch((error) => fail(plainly(error)));
1142
+ }