@saltpub/agent-autoloop 0.0.0-stage → 0.1.2

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 (171) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/INSTALL.md +118 -0
  3. package/LICENSE +21 -0
  4. package/README.en.md +264 -0
  5. package/README.md +260 -2
  6. package/SECURITY.md +48 -0
  7. package/dist/bin/agent-autoloop.js +2 -0
  8. package/dist/cli/backup.js +144 -0
  9. package/dist/cli/explain.js +84 -0
  10. package/dist/cli/main.js +1016 -0
  11. package/dist/cli/mcp.js +151 -0
  12. package/dist/cli/runs.js +40 -0
  13. package/dist/cli/spend.js +21 -0
  14. package/dist/cli/status.js +304 -0
  15. package/dist/cli/try.js +6 -0
  16. package/dist/cli/uninstall.js +84 -0
  17. package/dist/cli/update.js +65 -0
  18. package/dist/cli/why.js +115 -0
  19. package/dist/host/background-launcher.js +12 -0
  20. package/dist/host/background.js +24 -0
  21. package/dist/host/channels.js +4 -0
  22. package/dist/host/command.js +98 -0
  23. package/dist/host/config.js +37 -0
  24. package/dist/host/files.js +22 -0
  25. package/dist/host/home.js +5 -0
  26. package/dist/host/http.js +43 -0
  27. package/dist/host/launcher.js +188 -0
  28. package/dist/host/lines.js +15 -0
  29. package/dist/host/node-path.js +33 -0
  30. package/dist/host/npm.js +28 -0
  31. package/dist/host/plugins.js +26 -0
  32. package/dist/host/program.js +14 -0
  33. package/dist/host/runtime.js +179 -0
  34. package/dist/host/server.js +159 -0
  35. package/dist/host/service.js +325 -0
  36. package/dist/host/state.js +203 -0
  37. package/dist/host/up.js +162 -0
  38. package/dist/host/update.js +286 -0
  39. package/dist/host/version.js +81 -0
  40. package/dist/kernel/card-page.js +54 -0
  41. package/dist/kernel/credentials.js +16 -0
  42. package/dist/kernel/cron.js +135 -0
  43. package/dist/kernel/decide.js +826 -0
  44. package/dist/kernel/due.js +73 -0
  45. package/dist/kernel/errors.js +9 -0
  46. package/dist/kernel/evolve.js +264 -0
  47. package/dist/kernel/http.js +357 -0
  48. package/dist/kernel/query.js +202 -0
  49. package/dist/kernel/rules.js +20 -0
  50. package/dist/kernel/store.js +52 -0
  51. package/dist/plugins/acp/agent.js +32 -0
  52. package/dist/plugins/acp/bridge.js +204 -0
  53. package/dist/plugins/claude/agent.js +113 -0
  54. package/dist/plugins/codex/agent.js +105 -0
  55. package/dist/plugins/command/agent.js +25 -0
  56. package/dist/plugins/delivery/action.js +25 -0
  57. package/dist/plugins/delivery/agent.js +13 -0
  58. package/dist/plugins/delivery/delivery.js +388 -0
  59. package/dist/plugins/delivery/github.js +201 -0
  60. package/dist/plugins/delivery/handoff.js +50 -0
  61. package/dist/plugins/delivery/input.js +47 -0
  62. package/dist/plugins/delivery/poll.js +72 -0
  63. package/dist/plugins/delivery/project.js +144 -0
  64. package/dist/plugins/delivery/review-ledger.js +82 -0
  65. package/dist/plugins/delivery/review-policy.js +99 -0
  66. package/dist/plugins/delivery/review.js +280 -0
  67. package/dist/plugins/delivery/run.js +204 -0
  68. package/dist/plugins/desktop/channel.js +94 -0
  69. package/dist/plugins/dsh/agent.js +116 -0
  70. package/dist/plugins/feishu/channel.js +245 -0
  71. package/dist/plugins/github/source.js +30 -0
  72. package/dist/plugins/gitlab/source.js +30 -0
  73. package/dist/plugins/omp/agent.js +3 -0
  74. package/dist/plugins/opencode/agent.js +88 -0
  75. package/dist/plugins/pi/agent.js +92 -0
  76. package/dist/plugins/webhook/channel.js +70 -0
  77. package/dist/plugins/webhook/templates.js +34 -0
  78. package/dist/plugins/xiaojiu/channel.js +410 -0
  79. package/dist/plugins/zcode/agent.js +102 -0
  80. package/dist/protocol/client.js +56 -0
  81. package/dist/protocol/conformance.js +184 -0
  82. package/dist/protocol/job.js +1 -0
  83. package/dist/protocol/rules.js +230 -0
  84. package/dist/protocol/schema.js +70 -0
  85. package/dist/protocol/schema.json +985 -0
  86. package/dist/protocol/validate.js +150 -0
  87. package/dist/worker/agents.js +47 -0
  88. package/dist/worker/contract.js +178 -0
  89. package/dist/worker/run.js +52 -0
  90. package/dist/worker/usage.js +45 -0
  91. package/dist/worker/windows.ps1 +48 -0
  92. package/dist/worker/worker.js +595 -0
  93. package/docs/architecture.en.svg +178 -0
  94. package/docs/architecture.svg +178 -0
  95. package/docs/auto-update.md +53 -0
  96. package/docs/plugins.md +139 -0
  97. package/docs/protocol.md +582 -0
  98. package/docs/state-machines.md +77 -0
  99. package/examples/channel.sh +15 -0
  100. package/examples/plugins/hello-agent/agent.ts +40 -0
  101. package/examples/plugins/hello-channel/channel.ts +54 -0
  102. package/examples/plugins/hello-source/source.ts +19 -0
  103. package/examples/recipes/browser-handoff/README.md +44 -0
  104. package/examples/recipes/browser-handoff/SKILL.md +22 -0
  105. package/examples/recipes/browser-handoff/browser.json +10 -0
  106. package/examples/recipes/browser-handoff/handoff.ts +44 -0
  107. package/examples/recipes/browser-handoff/rules.json +19 -0
  108. package/examples/recipes/feedback/README.md +34 -0
  109. package/examples/recipes/feedback/SKILL.md +22 -0
  110. package/examples/recipes/feedback/event.json +8 -0
  111. package/examples/recipes/feedback/rules.json +37 -0
  112. package/examples/recipes/feishu-brief/README.md +28 -0
  113. package/examples/recipes/feishu-brief/SKILL.md +16 -0
  114. package/examples/recipes/feishu-brief/collect.ts +164 -0
  115. package/examples/recipes/feishu-brief/rules.json +57 -0
  116. package/examples/recipes/feishu-brief/sources.json +13 -0
  117. package/examples/recipes/github-issues/README.md +17 -0
  118. package/examples/recipes/github-issues/SKILL.md +18 -0
  119. package/examples/recipes/github-issues/rules.json +30 -0
  120. package/examples/recipes/inbox-triage/README.md +36 -0
  121. package/examples/recipes/inbox-triage/SKILL.md +19 -0
  122. package/examples/recipes/inbox-triage/collect.ts +191 -0
  123. package/examples/recipes/inbox-triage/rules.json +57 -0
  124. package/examples/recipes/inbox-triage/sources.json +8 -0
  125. package/examples/recipes/morning-brief/README.md +17 -0
  126. package/examples/recipes/morning-brief/SKILL.md +17 -0
  127. package/examples/recipes/morning-brief/rules.json +16 -0
  128. package/examples/recipes/ops-alerts/README.md +18 -0
  129. package/examples/recipes/ops-alerts/SKILL.md +34 -0
  130. package/examples/recipes/ops-alerts/restart.sh +5 -0
  131. package/examples/recipes/ops-alerts/rules.json +29 -0
  132. package/examples/recipes/website-watch/README.md +26 -0
  133. package/examples/recipes/website-watch/SKILL.md +19 -0
  134. package/examples/recipes/website-watch/check.ts +86 -0
  135. package/examples/recipes/website-watch/rules.json +56 -0
  136. package/examples/recipes/website-watch/site.json +6 -0
  137. package/examples/skills/weekly-sweep/SKILL.md +17 -0
  138. package/examples/watch-github-issues.sh +23 -0
  139. package/examples/worker.sh +18 -0
  140. package/package.json +55 -4
  141. package/plugins/acp/agent.ts +31 -0
  142. package/plugins/acp/bridge.ts +190 -0
  143. package/plugins/claude/agent.ts +121 -0
  144. package/plugins/codex/agent.ts +103 -0
  145. package/plugins/command/agent.ts +25 -0
  146. package/plugins/delivery/action.ts +29 -0
  147. package/plugins/delivery/action.yml +28 -0
  148. package/plugins/delivery/agent.ts +15 -0
  149. package/plugins/delivery/delivery.ts +408 -0
  150. package/plugins/delivery/github.ts +207 -0
  151. package/plugins/delivery/handoff.ts +72 -0
  152. package/plugins/delivery/input.ts +55 -0
  153. package/plugins/delivery/poll.ts +65 -0
  154. package/plugins/delivery/project.ts +161 -0
  155. package/plugins/delivery/review-ledger.ts +90 -0
  156. package/plugins/delivery/review-policy.ts +126 -0
  157. package/plugins/delivery/review.ts +324 -0
  158. package/plugins/delivery/run.ts +219 -0
  159. package/plugins/desktop/channel.ts +100 -0
  160. package/plugins/dsh/agent.ts +100 -0
  161. package/plugins/feishu/channel.ts +243 -0
  162. package/plugins/github/source.ts +33 -0
  163. package/plugins/gitlab/source.ts +32 -0
  164. package/plugins/omp/agent.ts +4 -0
  165. package/plugins/opencode/agent.ts +78 -0
  166. package/plugins/pi/agent.ts +80 -0
  167. package/plugins/webhook/channel.ts +74 -0
  168. package/plugins/webhook/templates.ts +32 -0
  169. package/plugins/xiaojiu/channel.ts +426 -0
  170. package/plugins/zcode/agent.ts +96 -0
  171. package/skills/agent-autoloop/SKILL.md +260 -0
@@ -0,0 +1,151 @@
1
+ // `agent-autoloop mcp`: the hub's doors as MCP tools over stdio, using the keys already in this machine's config.json.
2
+ import { readConfig } from "../host/config.js";
3
+ import { eachLine } from "../host/lines.js";
4
+ import { versionName } from "../host/version.js";
5
+ import { hubClient } from "../protocol/client.js";
6
+ const positive = { type: "integer", minimum: 1 };
7
+ const string = { type: "string", minLength: 1 };
8
+ const specs = [
9
+ ["status", "查看现在的事项和卡片;before 写上一页的 nextBefore,往前翻更早的轮次", { before: positive }, []],
10
+ ["why", "查看一轮的事件、规则和结果", { run: positive }, ["run"]],
11
+ [
12
+ "answer",
13
+ "回答卡片;选项从 0 开始,也可以写自己的答案",
14
+ { card: positive, choice: { type: "integer", minimum: 0 }, text: string },
15
+ ["card"],
16
+ ],
17
+ ["resolve", "将卡片结案,写明已核实的结果", { card: positive, reason: string }, ["card", "reason"]],
18
+ ["stop", "停止一轮", { run: positive }, ["run"]],
19
+ [
20
+ "emit",
21
+ "用本机来源发送事件;相同编号只记一次",
22
+ { id: string, type: string, subject: string, summary: string, detail: string, link: string },
23
+ ["id", "type"],
24
+ ],
25
+ ["tell", "用本机来源发送通知;相同编号只发一次", { key: string, text: string }, ["key", "text"]],
26
+ [
27
+ "pause",
28
+ "暂停一条规则:到点不跑、来事件不接也不排队;跳过的事件不会自动补,手动恢复时会列出,之后可以 replay",
29
+ { rule: string, reason: string, until: string },
30
+ ["rule"],
31
+ ],
32
+ ["resume", "恢复一条暂停的规则,结果里列出暂停期间跳过的事件(paused.skipped)", { rule: string }, ["rule"]],
33
+ [
34
+ "replay",
35
+ "补跑一条规则从 since 起暂停时跳过的事件,每条只补一次;since 用恢复结果里的 paused.since",
36
+ { rule: string, since: string },
37
+ ["rule", "since"],
38
+ ],
39
+ ["run", "立即运行一条规则一轮", { rule: string, subject: string, reason: string }, ["rule"]],
40
+ ];
41
+ const usesSourceKey = (name) => ["emit", "tell"].includes(name);
42
+ function toolsFor(config) {
43
+ return specs
44
+ .filter(([name]) => (usesSourceKey(name) ? config.source : config.owner))
45
+ .map(([name, description, properties, required]) => ({
46
+ name,
47
+ description,
48
+ inputSchema: { type: "object", properties, required, additionalProperties: false },
49
+ annotations: { readOnlyHint: ["status", "why"].includes(name), destructiveHint: name === "stop" },
50
+ }));
51
+ }
52
+ function validArguments(tool, args) {
53
+ if (!args || typeof args !== "object" || Array.isArray(args))
54
+ return false;
55
+ if (!tool.inputSchema.required.every((key) => Object.hasOwn(args, key)))
56
+ return false;
57
+ const properties = tool.inputSchema.properties;
58
+ const fits = ([key, value]) => {
59
+ const schema = properties[key];
60
+ if (!schema)
61
+ return false;
62
+ if (schema.type === "integer")
63
+ return Number.isSafeInteger(value) && value >= schema.minimum;
64
+ return typeof value === "string" && value.trim().length > 0;
65
+ };
66
+ if (!Object.entries(args).every(fits))
67
+ return false;
68
+ return tool.name !== "answer" || (args.choice !== undefined) !== (args.text !== undefined);
69
+ }
70
+ function callTool(hub, name, args) {
71
+ switch (name) {
72
+ case "status":
73
+ return hub.state(args.before);
74
+ case "why":
75
+ return hub.why(args.run);
76
+ case "answer": {
77
+ const { card, ...answer } = args;
78
+ return hub.answer(card, answer);
79
+ }
80
+ case "resolve":
81
+ return hub.resolve(args.card, args.reason);
82
+ case "stop":
83
+ return hub.cancel(args.run);
84
+ case "emit":
85
+ return hub.event(args);
86
+ case "tell":
87
+ return hub.tell(args);
88
+ case "pause":
89
+ return hub.pause(args.rule, {
90
+ ...(args.reason !== undefined && { reason: args.reason }),
91
+ ...(args.until !== undefined && { until: args.until }),
92
+ });
93
+ case "resume":
94
+ return hub.resume(args.rule);
95
+ case "replay":
96
+ return hub.replay(args.rule, { since: args.since });
97
+ case "run":
98
+ return hub.run(args.rule, {
99
+ ...(args.subject !== undefined && { subject: args.subject }),
100
+ ...(args.reason !== undefined && { reason: args.reason }),
101
+ });
102
+ }
103
+ }
104
+ export async function mcp() {
105
+ const config = readConfig();
106
+ const tools = toolsFor(config);
107
+ const reply = (id, body) => console.log(JSON.stringify({ jsonrpc: "2.0", id, ...body }));
108
+ const refuse = (id, code, message) => reply(id, { error: { code, message } });
109
+ async function answerCall(id, params) {
110
+ const tool = tools.find((tool) => tool.name === params?.name);
111
+ const args = params?.arguments ?? {};
112
+ if (!tool || !validArguments(tool, args))
113
+ return refuse(id, -32602, "工具名或参数不正确");
114
+ const hub = hubClient(config.url, usesSourceKey(tool.name) ? config.source.key : config.owner);
115
+ try {
116
+ const result = await callTool(hub, tool.name, args);
117
+ reply(id, { result: { content: [{ type: "text", text: JSON.stringify(result) }] } });
118
+ }
119
+ catch (error) {
120
+ reply(id, { result: { isError: true, content: [{ type: "text", text: error.message }] } });
121
+ }
122
+ }
123
+ eachLine(process.stdin, (line) => {
124
+ let request;
125
+ try {
126
+ request = JSON.parse(line);
127
+ }
128
+ catch {
129
+ return refuse(null, -32700, "不是 JSON");
130
+ }
131
+ if (!request || request.jsonrpc !== "2.0" || typeof request.method !== "string") {
132
+ return refuse(request?.id ?? null, -32600, "请求格式不正确");
133
+ }
134
+ const { id, method, params } = request;
135
+ if (id === undefined)
136
+ return;
137
+ if (method === "initialize") {
138
+ const serverInfo = { name: "agent-autoloop", version: versionName() };
139
+ reply(id, { result: { protocolVersion: "2025-11-25", capabilities: { tools: {} }, serverInfo } });
140
+ }
141
+ else if (method === "ping")
142
+ reply(id, { result: {} });
143
+ else if (method === "tools/list")
144
+ reply(id, { result: { tools } });
145
+ // Each answers by itself, however long it takes: a client's ping has to get through meanwhile.
146
+ else if (method === "tools/call")
147
+ void answerCall(id, params);
148
+ else
149
+ refuse(id, -32601, "没有这个方法");
150
+ });
151
+ }
@@ -0,0 +1,40 @@
1
+ // `agent-autoloop runs`: the finished runs before the few `status` shows, so `why` can be given a number. It pages through
2
+ // /v1/state the way any owner's client can; picking one rule is done here, so the protocol stays as it is.
3
+ import { finished, runRows } from "./status.js";
4
+ /**
5
+ * Up to `want` finished runs, newest first, older than `before` and of `rule` when given. `more` is where the next list
6
+ * starts, or null when there's nothing older.
7
+ */
8
+ export async function findRuns(page, { rule, before, want = 20 }) {
9
+ const runs = [];
10
+ let cursor = before;
11
+ let first;
12
+ for (;;) {
13
+ const state = await page(cursor);
14
+ first ??= state;
15
+ // The newest page also carries every run still unsettled, however old; each is read on its own page instead.
16
+ const own = state.runs.filter((run) => state.nextBefore === null || run.id >= state.nextBefore);
17
+ const matching = own.filter((run) => finished(run) && (rule === undefined || run.rule === rule));
18
+ for (const run of matching) {
19
+ if (runs.length === want)
20
+ return { state: first, runs, more: runs.at(-1).id };
21
+ runs.push(run);
22
+ }
23
+ if (!state.hasMore)
24
+ return { state: first, runs, more: null };
25
+ if (runs.length === want)
26
+ return { state: first, runs, more: runs.at(-1).id };
27
+ cursor = state.nextBefore;
28
+ }
29
+ }
30
+ export function runsText(found, { rule, color, columns }) {
31
+ if (!found.runs.length)
32
+ return rule === undefined ? "还没有做完的轮次。" : `规则「${rule}」没有做完的轮次。`;
33
+ const lines = runRows(found.state, found.runs, { color, columns });
34
+ lines.push("", "细节:agent-autoloop why <第几轮>");
35
+ if (found.more !== null) {
36
+ const named = rule === undefined ? "" : ` ${/^[^\s"'\\$`]+$/.test(rule) ? rule : JSON.stringify(rule)}`;
37
+ lines.push(`更早的:agent-autoloop runs${named} --before ${found.more}`);
38
+ }
39
+ return lines.join("\n");
40
+ }
@@ -0,0 +1,21 @@
1
+ const count = new Intl.NumberFormat("zh-CN", { notation: "compact", maximumFractionDigits: 1 });
2
+ /** To two places, a day on a cheap model would read as nothing at all. */
3
+ const dollars = (amount) => (amount > 0 && amount < 0.01 ? "<$0.01" : `$${amount.toFixed(2)}`);
4
+ function tally(label, { rounds, tokens, cached, cost, missingTokens, missingCost }) {
5
+ if (!rounds)
6
+ return `${label} 0 轮`;
7
+ const notes = (...said) => (said.some(Boolean) ? `(${said.filter(Boolean).join(";")})` : "");
8
+ const missing = (silent) => (silent ? `${silent} 轮没上报` : "");
9
+ // Read from a cache, a token costs a fraction of the price, so a total mostly made of them overstates the bill.
10
+ // Rounds recorded before Claude's input took in its cache can make the share more than all of it; those say nothing.
11
+ const fromCache = cached > 0 && cached <= tokens ? `其中缓存 ${Math.round((cached / tokens) * 100)}%` : "";
12
+ const shownTokens = missingTokens === rounds
13
+ ? "Token 没上报"
14
+ : `${count.format(tokens).replace(/(万|亿)/, " $1")} Token${notes(fromCache, missing(missingTokens))}`;
15
+ const shownCost = missingCost === rounds ? "费用没上报" : `${dollars(cost)}${notes(missing(missingCost))}`;
16
+ return `${label} ${rounds} 轮 · ${shownTokens} · ${shownCost}`;
17
+ }
18
+ /** Two lines, labels padded to the same terminal width so the figures line up. */
19
+ export function spendLines(spending) {
20
+ return [tally("今天 ", spending.today), tally("最近 7 天", spending.week)];
21
+ }
@@ -0,0 +1,304 @@
1
+ // `agent-autoloop status` for a person: what waits for them first, then what's going on, then what only reports.
2
+ // Colour only on a terminal: a pipe, a file or an Agent reading it gets plain text, and scripts use --json.
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
+ }
43
+ const LINK = /\[([^\]]+)\]\(([^)\s]+)\)/g;
44
+ const unlinked = (text) => text.replace(LINK, "$1");
45
+ 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
+ /** Times as a person reads them, in the hub's time zone, counted from the hub's now. */
53
+ export function clockFor(state) {
54
+ const zone = state.timezone;
55
+ const now = Date.parse(state.now);
56
+ const dayOf = (at) => {
57
+ const [y, m, d] = new Intl.DateTimeFormat("en-CA", { timeZone: zone }).format(at).split("-").map(Number);
58
+ return Date.UTC(y, m - 1, d) / 86_400_000;
59
+ };
60
+ const clock = (at) => new Date(at).toLocaleString("zh-CN", { timeZone: zone, hour: "2-digit", minute: "2-digit", hourCycle: "h23" });
61
+ /** Today's is just the time; yesterday, tomorrow and the coming week by name; further off by date. */
62
+ const when = (iso) => {
63
+ const at = Date.parse(iso);
64
+ const days = dayOf(at) - dayOf(now);
65
+ if (days === 0)
66
+ return clock(at);
67
+ if (days === -1)
68
+ return `昨天 ${clock(at)}`;
69
+ if (days === 1)
70
+ return `明天 ${clock(at)}`;
71
+ if (days > 1 && days < 7)
72
+ return `${WEEK[new Date(dayOf(at) * 86_400_000).getUTCDay()]} ${clock(at)}`;
73
+ const date = new Date(at).toLocaleString("zh-CN", { timeZone: zone, month: "numeric", day: "numeric" });
74
+ return `${date} ${clock(at)}`;
75
+ };
76
+ const lasted = (iso) => {
77
+ const minutes = Math.max(0, Math.round((now - Date.parse(iso)) / 60_000));
78
+ return minutes < 60 ? `${minutes} 分钟` : `${Math.floor(minutes / 60)} 小时 ${minutes % 60} 分钟`;
79
+ };
80
+ return { when, lasted };
81
+ }
82
+ // A word both sh and PowerShell take as it is: # starts a comment and @ a splat only at the front of a word.
83
+ const PLAIN = /^[\p{L}\p{N}_./][\p{L}\p{N}_.#@:/-]*$/u;
84
+ /** A word the user's shell reads back unchanged: single quotes, which neither expands inside, as each shell escapes them.
85
+ * PowerShell also takes the curly single quotes (common in Chinese text) as quotes, so each of those is doubled too. */
86
+ const shellWord = (word, windows) => PLAIN.test(word)
87
+ ? word
88
+ : windows
89
+ ? `'${word.replace(/['\u2018\u2019\u201a\u201b]/g, "$&$&")}'`
90
+ : `'${word.replaceAll("'", `'\\''`)}'`;
91
+ /** The command that hands a rule what its pause skipped since then, to copy as it is into this machine's shell. */
92
+ export const replayCommand = (rule, since, windows = process.platform === "win32") => `agent-autoloop replay ${shellWord(rule, windows)} --since ${shellWord(since, windows)}`;
93
+ /** One event a pause skipped, in a line no wider than `room`: when it came, from where, what and about what. */
94
+ export function skippedLine(event, room, when, from = (id) => id) {
95
+ const head = `${when(event.receivedAt)} `;
96
+ const what = `${from(event.source)} ${event.type} ${event.subject}${event.summary ? `:${event.summary}` : ""}`;
97
+ return head + wrap(what, room - width(head), 1)[0];
98
+ }
99
+ /** A finished run is no longer going or waiting to go. */
100
+ export const finished = (run) => run.state !== "claimed" && run.state !== "queued";
101
+ /** Finished runs, each its own entry: when it ended, its number, how and its rule, then a line or two of what came of it. */
102
+ export function runRows(state, runs, { color, columns }) {
103
+ const room = Math.min(columns || 100, 120);
104
+ const { dim, red, green, yellow } = stylesFor(color);
105
+ const { when } = clockFor(state);
106
+ const RUN_LOOK = {
107
+ done: ["做完了", green],
108
+ nothing: ["没事可做", dim],
109
+ cancelled: ["停了", yellow],
110
+ unknown: ["不确定", red],
111
+ };
112
+ const out = [];
113
+ const ended = runs.map((run) => (run.finishedAt ? when(run.finishedAt) : ""));
114
+ const timeRoom = Math.max(0, ...ended.map(width));
115
+ const runRoom = Math.max(0, ...runs.map((run) => width(`#${run.id}`)));
116
+ const lookRoom = Math.max(...Object.values(RUN_LOOK).map(([label]) => width(label)));
117
+ runs.forEach((run, index) => {
118
+ const [label, style] = RUN_LOOK[run.state] ?? [run.state, (text) => text];
119
+ const before = ` ${pad(ended[index], timeRoom)} ${pad(`#${run.id}`, runRoom)} ${pad(label, lookRoom)} `;
120
+ out.push(` ${dim(pad(ended[index], timeRoom))} ${dim(pad(`#${run.id}`, runRoom))} ${style(pad(label, lookRoom))} ${run.rule}`);
121
+ const outcome = run.error || run.summary;
122
+ if (!outcome)
123
+ return;
124
+ const look = run.error ? red : run.state === "nothing" ? dim : (text) => text;
125
+ const indent = " ".repeat(width(before));
126
+ for (const line of wrap(unlinked(outcome), room - indent.length, 2))
127
+ out.push(indent + look(line));
128
+ });
129
+ return out;
130
+ }
131
+ export function render(state, { color, columns }) {
132
+ const room = Math.min(columns || 100, 120);
133
+ const { bold, dim, underline, red, green, yellow, magenta, cyan, heading } = stylesFor(color);
134
+ const { when, lasted } = clockFor(state);
135
+ const out = [];
136
+ const say = (line = "") => out.push(line);
137
+ const section = (title) => {
138
+ say();
139
+ say(title);
140
+ };
141
+ const { totals } = state;
142
+ const count = (label, n, style) => n > 0 ? `${label} ${bold(style(String(n)))}` : dim(`${label} 0`);
143
+ say([
144
+ count("等你", state.cards.length, yellow),
145
+ count("在跑", totals.running, cyan),
146
+ count("排队", totals.queued - totals.retrying, yellow),
147
+ totals.retrying ? count("等重派", totals.retrying, yellow) : "",
148
+ totals.unknown ? count("不确定", totals.unknown, red) : "",
149
+ `今天做完 ${totals.doneToday}`,
150
+ ]
151
+ .filter(Boolean)
152
+ .join(dim(" · ")));
153
+ for (const line of spendLines(state.spending))
154
+ say(dim(line));
155
+ const presence = [
156
+ ...state.agents.map((agent) => ({ ...agent, where: agent.worker })),
157
+ ...state.channels.map((channel) => ({ ...channel, where: "通道" })),
158
+ ];
159
+ if (presence.length)
160
+ section(heading("在线"));
161
+ const nameRoom = Math.max(0, ...presence.map((one) => width(one.name)));
162
+ const whereRoom = Math.max(0, ...presence.map((one) => width(one.where)));
163
+ for (const one of presence) {
164
+ const head = ` ${one.online ? green("●") : red("○")} ${pad(one.name, nameRoom)} `;
165
+ if (one.online)
166
+ say(head + dim(one.where));
167
+ else
168
+ say(`${head}${dim(pad(one.where, whereRoom))} ${red(`离线,最后在线 ${one.seenAt ? when(one.seenAt) : "没见过"}`)}`);
169
+ }
170
+ const sourceName = (id) => state.sources.find((one) => one.id === id)?.name ?? id;
171
+ const paused = state.lines.filter((line) => line.paused);
172
+ if (paused.length)
173
+ section(`${heading("暂停中")}${dim("(恢复:agent-autoloop resume <规则>)")}`);
174
+ for (const line of paused) {
175
+ const { reason, since, until, skipped } = line.paused;
176
+ say(` ${line.name}${reason ? dim(`:${reason}`) : ""}`);
177
+ // A schedule lets its moments pass and keeps no events, so it has no count.
178
+ const ends = until ? `,${when(until)} 自动恢复` : "";
179
+ say(dim(` ${when(since)} 起${ends}${skipped ? `,跳过 ${skipped.count} 条事件` : ""}`));
180
+ const shown = skipped?.events.slice(0, 5) ?? [];
181
+ for (const event of shown)
182
+ say(` ${skippedLine(event, room - 6, when, sourceName)}`);
183
+ if (shown.length < (skipped?.count ?? 0))
184
+ say(dim(` 共 ${skipped.count} 条,这里列出最近 ${shown.length} 条`));
185
+ // Nobody reads anything when a pause ends by itself, so the way to replay is told while it lasts.
186
+ if (until && skipped?.count)
187
+ say(dim(` 到时不会列出这些事件,之后补跑:${replayCommand(line.name, since)}`));
188
+ }
189
+ const INDENT = " ";
190
+ if (state.cards.length)
191
+ section(bold(yellow(`等你 ${state.cards.length}`)));
192
+ for (const card of state.cards) {
193
+ const label = card.kind === "ask" ? bold(yellow("决定")) : bold(magenta("留意"));
194
+ say(` ${label} ${dim(`#${card.id}`)} ${bold(card.title)}`);
195
+ if (card.rule && card.rule !== card.title)
196
+ say(dim(`${INDENT}来源:${card.rule}`));
197
+ for (const paragraph of (card.text ?? "").split(/\n\s*\n/).filter((one) => one.trim())) {
198
+ for (const line of wrap(unlinked(paragraph), room - INDENT.length))
199
+ say(INDENT + line);
200
+ for (const [, words, url] of paragraph.matchAll(LINK))
201
+ say(`${INDENT}${underline(words)} ${dim(url)}`);
202
+ }
203
+ if (card.kind === "ask") {
204
+ card.options.forEach((option, index) => {
205
+ say(`${INDENT}${index + 1}. ${option}${index === card.recommend ? green("(推荐)") : ""}`);
206
+ });
207
+ say(dim(`${INDENT}回答:agent-autoloop answer ${card.id} <序号>`));
208
+ }
209
+ else
210
+ say(dim(`${INDENT}处理完了:agent-autoloop answer ${card.id}`));
211
+ }
212
+ const because = (event) => {
213
+ if (event.type === "card.answered")
214
+ return `你回答了卡片「${event.summary}」`;
215
+ if (event.type === "schedule.tick")
216
+ return "到点了";
217
+ if (event.type === "timer.due")
218
+ return `约好的复查到了${event.subject ? `:${event.subject}` : ""}`;
219
+ if (event.type === "run.manual")
220
+ return event.summary;
221
+ return `${sourceName(event.source)} ${event.type} ${event.summary || event.subject}`.trim();
222
+ };
223
+ const running = state.runs.filter((run) => run.state === "claimed");
224
+ const queued = state.runs.filter((run) => run.state === "queued");
225
+ if (running.length || queued.length)
226
+ section(heading("正在做"));
227
+ for (const run of running) {
228
+ const stopping = run.stopping ? ` ${yellow("正在停")}` : "";
229
+ say(` ${dim(`#${run.id}`)} ${run.rule} ${cyan(`已跑 ${lasted(run.claimedAt)}`)}${stopping}`);
230
+ if (run.events[0])
231
+ for (const line of wrap(`因为${because(run.events[0])}`, room - 6, 1))
232
+ say(` ${dim(line)}`);
233
+ }
234
+ for (const run of queued) {
235
+ const retry = run.attempts > 0;
236
+ say(` ${dim(`#${run.id}`)} ${run.rule} ${yellow(retry ? `等重派,${when(run.notBefore)} 再试` : "排队")}`);
237
+ if (retry && run.error)
238
+ for (const line of wrap(run.error, room - 6, 2))
239
+ say(` ${red(line)}`);
240
+ }
241
+ const recentRuns = state.runs.filter(finished).slice(0, 8);
242
+ if (recentRuns.length)
243
+ section(heading("最近几轮"));
244
+ for (const line of runRows(state, recentRuns, { color, columns }))
245
+ say(line);
246
+ const CARD_LOOK = {
247
+ decided: ["已回答", cyan],
248
+ done: ["已完成", green],
249
+ closed: ["已关闭", dim],
250
+ };
251
+ const recent = state.recentCards.slice(0, 5);
252
+ if (recent.length)
253
+ section(heading("最近的卡片"));
254
+ const cardRoom = Math.max(0, ...recent.map((card) => width(`#${card.id}`)));
255
+ for (const card of recent) {
256
+ const [label, style] = card.kind === "notice" && card.state === "closed"
257
+ ? ["已处理", dim]
258
+ : (CARD_LOOK[card.state] ?? [card.state, (text) => text]);
259
+ const before = ` ${pad(`#${card.id}`, cardRoom)} ${pad(label, 6)} `;
260
+ const [title] = wrap(card.title, room - width(before), 1);
261
+ say(` ${dim(pad(`#${card.id}`, cardRoom))} ${style(pad(label, 6))} ${bold(title)}`);
262
+ const indent = " ".repeat(width(before));
263
+ const parts = [];
264
+ if (card.choice !== null && card.choice !== undefined)
265
+ parts.push([`你选了 ${card.options[card.choice]}`, green]);
266
+ if (card.answer)
267
+ parts.push([`你说:${card.answer}`, (text) => text]);
268
+ // A notice dealt with says so already in its label.
269
+ if (card.result && card.result !== "已处理")
270
+ parts.push([unlinked(card.result), (text) => text]);
271
+ else if (card.state === "decided")
272
+ parts.push(["Agent 接着在做", dim]);
273
+ // What `tell` says is closed as soon as it's made, so this is where it's read; one line keeps the list a list.
274
+ else if (card.kind === "notice" && card.text)
275
+ parts.push([unlinked(card.text), dim]);
276
+ if (!parts.length)
277
+ continue;
278
+ const plain = parts.map(([text]) => text.replace(/\s*\n\s*/g, " ")).join(" → ");
279
+ const lines = wrap(plain, room - indent.length, card.kind === "notice" ? 1 : 2);
280
+ if (lines.length === 1 && lines[0] === plain)
281
+ say(indent + parts.map(([text, look]) => look(text)).join(dim(" → ")));
282
+ else
283
+ for (const line of lines)
284
+ say(indent + line);
285
+ }
286
+ const timed = [...state.lines.filter((line) => line.every), ...state.elsewhere];
287
+ if (timed.length)
288
+ section(heading("定时"));
289
+ const ruleRoom = Math.max(0, ...timed.map((line) => width(line.name)));
290
+ const everyRoom = Math.max(0, ...timed.map((line) => width(line.every)));
291
+ for (const line of timed) {
292
+ const head = ` ${pad(line.name, ruleRoom)} ${pad(line.every, everyRoom)} 下次 ${when(line.next)}`;
293
+ const [where] = line.where ? wrap(`(在别处:${line.where})`, room - width(head), 1) : [""];
294
+ say(` ${pad(line.name, ruleRoom)} ${pad(line.every, everyRoom)} ${dim("下次")} ${when(line.next)}${dim(where)}`);
295
+ }
296
+ const unrouted = state.unrouted.slice(0, 5);
297
+ if (unrouted.length)
298
+ section(heading("没有规则接的事件"));
299
+ for (const event of unrouted) {
300
+ const words = `${sourceName(event.source)} ${event.type} ${event.subject}`;
301
+ say(` ${yellow(words)}${event.summary ? dim(`:${event.summary}`) : ""}`);
302
+ }
303
+ return out.join("\n");
304
+ }
@@ -0,0 +1,6 @@
1
+ const failed = (run) => run.rule === "试一下" && run.state === "queued" && run.attempts > 0;
2
+ /** A run still waiting for its retry as this try starts. */
3
+ export const waitingRetry = (runs) => runs.find(failed);
4
+ export const attemptsOf = (runs) => new Map(runs.map((run) => [run.id, run.attempts]));
5
+ /** A run that has failed since those attempts were counted. */
6
+ export const newFailure = (runs, before) => runs.find((run) => failed(run) && run.attempts > (before.get(run.id) ?? 0));
@@ -0,0 +1,84 @@
1
+ // `agent-autoloop uninstall`: takes away what the install put on this computer and nothing else. A link is ours only if it really
2
+ // leads to this program: someone else's agent-autoloop, or a folder of their own by that name, stays where it is.
3
+ import { existsSync, lstatSync, realpathSync, rmSync, unlinkSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import path from "node:path";
6
+ import { HOME } from "../host/home.js";
7
+ import { ENTRY, ROOT } from "../host/program.js";
8
+ import { removeService, stopUp } from "../host/service.js";
9
+ import { powershell, psQuote } from "../host/command.js";
10
+ import { npm, npmPrefix, PACKAGE } from "../host/npm.js";
11
+ import { launcherFile, skillTarget, updateDir, versionsDir } from "../host/update.js";
12
+ function removeLink(link, ours) {
13
+ if (!lstatSync(link, { throwIfNoEntry: false })?.isSymbolicLink())
14
+ return;
15
+ let leads;
16
+ try {
17
+ leads = realpathSync(link);
18
+ }
19
+ catch {
20
+ return; // It leads nowhere, so not here.
21
+ }
22
+ if (!ours(leads))
23
+ return;
24
+ // Not rmSync: Node 25.1 refuses it for a link that leads to a folder.
25
+ unlinkSync(link);
26
+ console.log(`删掉了 ${link}`);
27
+ }
28
+ const leadsTo = (target) => (leads) => {
29
+ try {
30
+ return leads === realpathSync(target);
31
+ }
32
+ catch {
33
+ return false;
34
+ }
35
+ };
36
+ function removeLinks(keep) {
37
+ const program = ENTRY;
38
+ const onPath = (process.env.PATH ?? "").split(path.delimiter).filter((place) => path.isAbsolute(place));
39
+ const places = [path.join(homedir(), ".local", "bin"), "/opt/homebrew/bin", "/usr/local/bin", ...onPath];
40
+ for (const place of new Set(places))
41
+ if (!keep.has(path.resolve(place)))
42
+ removeLink(path.join(place, "agent-autoloop"), leadsTo(program));
43
+ // The Skill points into this install's data folder, whichever version is current; a checkout's own folder counts too.
44
+ const skill = leadsTo(skillTarget(HOME));
45
+ const ourSkill = (leads) => leads.startsWith(`${path.resolve(HOME)}${path.sep}`) || skill(leads);
46
+ // .claude and .codex are where earlier versions put it; those copies are ours to take away too.
47
+ for (const place of [".agents", ".claude", ".codex"])
48
+ removeLink(path.join(homedir(), place, "skills", "agent-autoloop"), ourSkill);
49
+ }
50
+ /** Confirmation is about removing the program; data is never part of this command. */
51
+ export async function uninstall(yes, ask) {
52
+ if (!yes) {
53
+ if (!ask)
54
+ throw new Error("运行 agent-autoloop uninstall --yes 卸载程序,规则、密钥和记录会保留。");
55
+ if (!/^y(es)?$/i.test((await ask("卸载程序并保留数据?[y/N] ")).trim())) {
56
+ console.log("没有卸载。");
57
+ return;
58
+ }
59
+ }
60
+ removeService();
61
+ stopUp();
62
+ const prefix = npmPrefix(ROOT);
63
+ // A link npm made is npm's to remove, and it goes with the package.
64
+ const npmBin = prefix && (process.platform === "win32" ? prefix : path.join(prefix, "bin"));
65
+ // Links go before their targets: a link to a deleted folder can't be told apart from anyone else's.
66
+ removeLinks(new Set(npmBin ? [path.resolve(npmBin)] : []));
67
+ // The versions, the launcher, the shared Skill and the bookkeeping are the program; data elsewhere stays.
68
+ for (const dir of [versionsDir(HOME), path.dirname(launcherFile(HOME)), path.join(HOME, "skills"), updateDir(HOME)]) {
69
+ if (path.resolve(dir) !== path.resolve(HOME))
70
+ rmSync(dir, { recursive: true, force: true });
71
+ }
72
+ if (prefix)
73
+ npm(["uninstall", "-g", PACKAGE, "--prefix", prefix]);
74
+ const installedApp = path.join(HOME, "app");
75
+ if (existsSync(installedApp) && realpathSync(installedApp) === realpathSync(ROOT)) {
76
+ if (process.platform === "win32") {
77
+ powershell(`$old = [Environment]::GetEnvironmentVariable('Path', 'User');
78
+ $next = ($old -split ';' | Where-Object { $_ -ne ${psQuote(path.join(ROOT, "bin"))} }) -join ';';
79
+ if ($next -ne $old) { [Environment]::SetEnvironmentVariable('Path', $next, 'User') }`);
80
+ }
81
+ rmSync(installedApp, { recursive: true });
82
+ }
83
+ console.log(existsSync(HOME) ? `卸载好了。规则、密钥和记录还留在 ${HOME}。` : "卸载好了。");
84
+ }