@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,65 @@
1
+ // `agent-autoloop update`: an installed copy follows the npm package, whose latest version has passed every check. A
2
+ // checkout keeps following its repository, as it did before, so a copy made the old way can still update.
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { spawnSync } from "node:child_process";
6
+ import { npm, npmPrefix, PACKAGE } from "../host/npm.js";
7
+ import { isNewer } from "../host/update.js";
8
+ const PUBLISHED = "https://github.com/KKKKhazix/agent-autoloop.git";
9
+ const RELEASE = /refs\/tags\/(v(\d+)\.(\d+)\.(\d+))$/;
10
+ const VERSION = /^(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?$/;
11
+ function git(root, ...args) {
12
+ const done = spawnSync("git", ["-C", root, ...args], { encoding: "utf8" });
13
+ if (done.status !== 0)
14
+ throw new Error(`git ${args[0]} 没成功:${done.stderr?.trim() || done.error?.message}`);
15
+ return done.stdout.trim();
16
+ }
17
+ function latestRelease(root) {
18
+ const origin = spawnSync("git", ["-C", root, "config", "--get", "remote.origin.url"], { encoding: "utf8" });
19
+ if (origin.stdout?.trim() !== PUBLISHED)
20
+ return null;
21
+ const releases = git(root, "ls-remote", "--refs", "--tags", "origin", "v*")
22
+ .split("\n")
23
+ .flatMap((line) => {
24
+ const found = RELEASE.exec(line);
25
+ return found ? [{ tag: found[1], version: found.slice(2).map(Number) }] : [];
26
+ });
27
+ const newer = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
28
+ return releases.sort((a, b) => newer(a.version, b.version)).at(-1)?.tag ?? null;
29
+ }
30
+ function updateCheckout(root) {
31
+ const before = git(root, "rev-parse", "HEAD");
32
+ const to = latestRelease(root);
33
+ if (to) {
34
+ git(root, "fetch", "--quiet", "--depth", "1", "origin", `refs/tags/${to}:refs/tags/${to}`);
35
+ git(root, "checkout", "--quiet", "--detach", to);
36
+ }
37
+ else
38
+ git(root, "pull", "--quiet", "--ff-only");
39
+ return { changed: git(root, "rev-parse", "HEAD") !== before, to };
40
+ }
41
+ function installedVersion(root) {
42
+ const manifest = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8"));
43
+ const version = typeof manifest.version === "string" ? manifest.version : "";
44
+ if (!VERSION.test(version))
45
+ throw new Error(`${path.join(root, "package.json")} 里没有能用的版本号`);
46
+ return version;
47
+ }
48
+ export { isNewer };
49
+ function updateInstalled(root) {
50
+ const current = installedVersion(root);
51
+ const latest = npm(["view", PACKAGE, "version"]);
52
+ if (!VERSION.test(latest))
53
+ throw new Error(`npm 上 ${PACKAGE} 的版本号读不出来:${latest}`);
54
+ if (!isNewer(latest, current))
55
+ return { changed: false, to: `v${current}` };
56
+ // The exact version that was checked, not a moving tag: what gets installed is what was compared. A custom prefix is
57
+ // passed back, or an install from one would be replaced by a second copy somewhere else.
58
+ const prefix = npmPrefix(root);
59
+ npm(["install", "-g", `${PACKAGE}@${latest}`, "--no-audit", "--no-fund", ...(prefix ? ["--prefix", prefix] : [])]);
60
+ return { changed: true, to: `v${latest}` };
61
+ }
62
+ /** Brings this copy up to date. `to` is the release it's now at. */
63
+ export function updateCode(root) {
64
+ return existsSync(path.join(root, ".git")) ? updateCheckout(root) : updateInstalled(root);
65
+ }
@@ -0,0 +1,115 @@
1
+ function time(value) {
2
+ const date = new Date(value);
3
+ const pad = (part) => String(part).padStart(2, "0");
4
+ return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
5
+ }
6
+ const eventText = (event) => `来源 ${event.source} · 类型 ${event.type} · 对象 ${event.subject || "无"}`;
7
+ export function formatWhy(id, facts) {
8
+ const allChanges = facts.flatMap((fact) => fact.changes);
9
+ const relations = new Map();
10
+ for (const { table, key, row } of allChanges) {
11
+ if (table !== "run_events")
12
+ continue;
13
+ if (row)
14
+ relations.set(key, row);
15
+ else
16
+ relations.delete(key);
17
+ }
18
+ const ownRelations = [...relations.values()].filter((relation) => relation.run_id === id);
19
+ const events = new Set(ownRelations.map((relation) => relation.event_id));
20
+ const runs = allChanges.filter(({ table, row }) => table === "runs" && row?.id === id).map(({ row }) => row);
21
+ const links = new Map();
22
+ for (const run of runs)
23
+ if (run.issued && run.link)
24
+ links.set(run.issued, run.link);
25
+ const versions = new Set(runs.map((run) => run.rules_version));
26
+ const rulesAt = new Map();
27
+ for (const fact of facts) {
28
+ if (fact.type !== "rules")
29
+ continue;
30
+ const config = fact.changes.find(({ table, key }) => table === "config" && key === "rules");
31
+ rulesAt.set(fact.seq, config.row.value);
32
+ }
33
+ const lines = [`第 ${id} 轮 · ${runs.at(-1).rule}`];
34
+ const add = (at, text) => lines.push(`${time(at)} ${text}`);
35
+ const previous = new Map();
36
+ const started = new Set();
37
+ function tellRun(fact, row, before, receipt) {
38
+ if (row.claimed_at && row.claimed_at !== before?.claimed_at) {
39
+ const agent = rulesAt.get(row.rules_version).agents[row.agent];
40
+ add(row.claimed_at, `${agent.worker} 领取(${agent.name})`);
41
+ }
42
+ if (fact.type === "started" && !started.has(row.issued)) {
43
+ add(fact.at, "开始处理");
44
+ started.add(row.issued);
45
+ }
46
+ if (row.link && row.link === links.get(row.issued) && row.link !== before?.link)
47
+ add(fact.at, `会话:${row.link}`);
48
+ if (row.finished_at && row.finished_at !== before?.finished_at) {
49
+ add(row.finished_at, `结束:${row.summary || (row.state === "cancelled" ? "已停止" : "没有填写结论")}`);
50
+ }
51
+ if (receipt && row.state === "queued" && row.attempts !== before?.attempts) {
52
+ add(fact.at, `本次未完成:${row.error};重试时间 ${time(row.not_before)}`);
53
+ }
54
+ if (receipt)
55
+ for (const rejected of JSON.parse(row.last_answer ?? "[]"))
56
+ add(fact.at, `未执行:${rejected.reason}`);
57
+ }
58
+ function tellCard(row, before, receipt) {
59
+ const own = row.run_id === id;
60
+ if (!before && own && (!row.fyi || row.key.startsWith("thread:"))) {
61
+ const options = JSON.parse(row.options);
62
+ add(row.created_at, `${row.kind === "ask" ? "提问" : "通知"}:${row.title}`);
63
+ if (row.text)
64
+ lines.push(...String(row.text)
65
+ .split("\n")
66
+ .map((line) => ` ${line}`));
67
+ if (options.length)
68
+ lines.push(` 选项:${options.join(" / ")}`);
69
+ }
70
+ if (row.decided_at && row.decided_at !== before?.decided_at && (own || events.has(row.answer_event))) {
71
+ const answer = row.answer ?? JSON.parse(row.options)[row.choice];
72
+ add(row.decided_at, `${row.by || "本人"}回答「${row.title}」:${answer}`);
73
+ if (own) {
74
+ const next = [...relations.values()].filter((relation) => relation.event_id === row.answer_event && relation.run_id !== id);
75
+ for (const { run_id } of next)
76
+ add(row.decided_at, `回答后继续:第 ${run_id} 轮`);
77
+ }
78
+ }
79
+ if (row.state === "closed" && before?.state !== "closed" && (receipt || own) && !row.fyi) {
80
+ add(row.closed_at, `结案:${row.title};${row.result}`);
81
+ }
82
+ }
83
+ for (const fact of facts) {
84
+ if (fact.type === "rules" && versions.has(fact.seq))
85
+ add(fact.at, `规则版本 #${fact.seq}`);
86
+ const changes = new Map(fact.changes.map((change) => [`${change.table}:${change.key}`, change]));
87
+ const receipt = fact.type === "finish" && Boolean(changes.get(`runs:${id}`)?.row);
88
+ for (const [changed, { table, key, row }] of changes) {
89
+ const before = previous.get(changed);
90
+ if (table === "events" && row && !before && events.has(row.id)) {
91
+ add(row.received_at, `触发事件:${eventText(row)}`);
92
+ }
93
+ if (fact.type === "replayRule" && table === "run_events" && row?.run_id === id) {
94
+ const event = previous.get(`events:${row.event_id}`);
95
+ add(fact.at, `本人补跑暂停时跳过的事件${event ? `:${eventText(event)}` : ""}`);
96
+ }
97
+ if (table === "runs" && row?.id === id)
98
+ tellRun(fact, row, before, receipt);
99
+ if (table === "cards" && row)
100
+ tellCard(row, before, receipt);
101
+ // A look-again that already came due leaves the projection once its run ends; that is not a cancellation.
102
+ if (receipt && table === "timers" && (row || before?.event_id == null)) {
103
+ add(fact.at, row ? `安排复查:${row.about};时间 ${time(row.at)}` : `取消复查:${before?.key ?? key}`);
104
+ }
105
+ if (receipt && table === "events" && row && !before && !events.has(row.id)) {
106
+ add(fact.at, `发出事件:${eventText(row)}`);
107
+ }
108
+ if (row)
109
+ previous.set(changed, row);
110
+ else
111
+ previous.delete(changed);
112
+ }
113
+ }
114
+ return lines.join("\n");
115
+ }
@@ -0,0 +1,12 @@
1
+ // The Windows login task runs this with wscript, which has no console, so the hub's own console stays hidden. A hub that
2
+ // stops is started again after ten seconds, as launchd and systemd do. WSH reads this file in the system code page, so it
3
+ // stays ASCII; the paths come in as arguments, which keep every character.
4
+ var shell = new ActiveXObject("WScript.Shell");
5
+ var words = [];
6
+ for (var i = 0; i < WScript.Arguments.length; i++) {
7
+ words.push('"' + WScript.Arguments(i).replace(/(\\+)$/, "$1$1") + '"');
8
+ }
9
+ for (;;) {
10
+ shell.Run(words.join(" "), 0, true);
11
+ WScript.Sleep(10000);
12
+ }
@@ -0,0 +1,24 @@
1
+ // The hub as the Windows login task runs it, through background-launcher.js: output goes straight to files, without PowerShell
2
+ // changing its encoding, and the hub's exit is this one's, so background-launcher.js starts both again.
3
+ import { spawn } from "node:child_process";
4
+ import { closeSync, mkdirSync, openSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { ENTRY } from "./program.js";
7
+ import { launcherFile, managedAt } from "./update.js";
8
+ const home = process.argv[2];
9
+ mkdirSync(path.join(home, "logs"), { recursive: true });
10
+ const log = openSync(path.join(home, "logs", "up.log"), "a");
11
+ // The launcher starts whichever version is current and switches when one was staged.
12
+ const managed = managedAt(home);
13
+ const program = managed ? launcherFile(home) : ENTRY;
14
+ const child = spawn(process.execPath, ["--disable-warning=ExperimentalWarning", program, ...(managed ? [] : ["up"])], {
15
+ env: { ...process.env, AGENT_AUTOLOOP_HOME: home, ...(managed && { AGENT_AUTOLOOP_LAUNCHED: "1" }) },
16
+ stdio: ["ignore", log, log],
17
+ windowsHide: true,
18
+ });
19
+ closeSync(log);
20
+ child.on("error", (error) => {
21
+ console.error(error.message);
22
+ process.exit(1);
23
+ });
24
+ child.on("exit", (code) => process.exit(code ?? 1));
@@ -0,0 +1,4 @@
1
+ import { loadPlugin } from "./plugins.js";
2
+ export async function loadChannel(use) {
3
+ return (await loadPlugin(use, "channel"));
4
+ }
@@ -0,0 +1,98 @@
1
+ // Node cannot exec a Windows npm .cmd shim. Run what it points at (a JavaScript entry or a native program) directly so
2
+ // multiline arguments never become cmd source.
3
+ import { execFile, execFileSync } from "node:child_process";
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { promisify } from "node:util";
7
+ const execFileAsync = promisify(execFile);
8
+ /** Windows looks for a bare program name in its working folder first, and an Agent can write to a turn's folder. */
9
+ export const POWERSHELL = path.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
10
+ /**
11
+ * The file Windows runs for `name` from PATH, trying extensions in PATHEXT's order. Not where.exe: it prints in the console's
12
+ * code page, so a folder outside it (a Chinese user name) came back as a path that isn't there. The current folder isn't
13
+ * searched, so a project can't put its own program in place of the one installed.
14
+ */
15
+ export function findOnPath(name, extensions = [".exe", ".com", ".cmd", ".bat", ".ps1"]) {
16
+ if (/[\\/]/.test(name))
17
+ return null;
18
+ const listed = (process.env.PATHEXT ?? "").toLowerCase().split(";");
19
+ const order = [
20
+ ...listed.filter((ext) => extensions.includes(ext)),
21
+ ...extensions.filter((ext) => !listed.includes(ext)),
22
+ ];
23
+ const names = [
24
+ ...(extensions.includes(path.extname(name).toLowerCase()) ? [name] : []),
25
+ ...order.map((ext) => name + ext),
26
+ ];
27
+ for (const entry of (process.env.PATH ?? "").split(";")) {
28
+ const folder = entry.trim().replace(/^"(.*)"$/, "$1");
29
+ if (!folder)
30
+ continue;
31
+ for (const file of names.map((each) => path.join(folder, each)))
32
+ if (existsSync(file))
33
+ return file;
34
+ }
35
+ return null;
36
+ }
37
+ /**
38
+ * The npm.cmd and npx.cmd of npm 10 and later name their script in a variable set from %~dp0, then run
39
+ * `"%NODE_EXE%" "%NPM_CLI_JS%" %*`. The npm they ship with is the one run: their step that may pick a newer npm installed
40
+ * under the global prefix is left out.
41
+ */
42
+ function throughVariable(shim) {
43
+ const run = /^"%\w+%"\s+"%(\w+)%"\s+%\*\s*$/im.exec(shim);
44
+ if (!run)
45
+ return null;
46
+ return new RegExp(`^SET\\s+"${run[1]}=%~dp0\\\\?([^"\\r\\n]+\\.[cm]?js)"\\s*$`, "im").exec(shim);
47
+ }
48
+ export function commandLine(argv) {
49
+ if (process.platform !== "win32")
50
+ return [argv[0], argv.slice(1)];
51
+ let program = argv[0];
52
+ if (!path.isAbsolute(program))
53
+ program = findOnPath(program) ?? program;
54
+ if (/\.cmd$/i.test(program)) {
55
+ const shim = readFileSync(program, "utf8");
56
+ const entry = /"%(?:dp0%|~dp0)\\?([^"\r\n]+\.(?:[cm]?js|exe))"\s+%\*/i.exec(shim) ?? throughVariable(shim);
57
+ if (!entry)
58
+ throw new Error(`不能直接运行 ${program}:请在 command 写可执行文件,或用 node 运行脚本。`);
59
+ // A package whose bin is a native program (Claude Code from npm) gets a shim that runs it with no node in front.
60
+ if (/\.exe$/i.test(entry[1]))
61
+ return [path.resolve(path.dirname(program), entry[1]), argv.slice(1)];
62
+ const adjacentNode = path.join(path.dirname(program), "node.exe");
63
+ return [
64
+ existsSync(adjacentNode) ? adjacentNode : process.execPath,
65
+ [path.resolve(path.dirname(program), entry[1]), ...argv.slice(1)],
66
+ ];
67
+ }
68
+ if (/\.ps1$/i.test(program))
69
+ return [POWERSHELL, ["-NoLogo", "-NoProfile", "-NonInteractive", "-File", program, ...argv.slice(1)]];
70
+ if (/\.bat$/i.test(program))
71
+ throw new Error(`不能直接运行 ${program}:请在 command 写可执行文件,或用 node 运行脚本。`);
72
+ return [program, argv.slice(1)];
73
+ }
74
+ const encoded = (script) => [
75
+ "-NoLogo",
76
+ "-NoProfile",
77
+ "-NonInteractive",
78
+ "-EncodedCommand",
79
+ Buffer.from("$ErrorActionPreference='Stop'; [Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); " + script, "utf16le").toString("base64"),
80
+ ];
81
+ export function powershell(script) {
82
+ return execFileSync(POWERSHELL, encoded(script), {
83
+ encoding: "utf8",
84
+ windowsHide: true,
85
+ stdio: ["ignore", "pipe", "pipe"],
86
+ }).trim();
87
+ }
88
+ export const psQuote = (word) => `'${word.replaceAll("'", "''")}'`;
89
+ const commandOf = (pid) => process.platform === "win32"
90
+ ? [POWERSHELL, encoded(`(Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}').CommandLine`)]
91
+ : ["ps", ["-p", String(pid), "-o", "command="]];
92
+ export function processCommandSync(pid) {
93
+ return execFileSync(...commandOf(pid), { encoding: "utf8", windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
94
+ }
95
+ /** Without stopping the process while it looks: the worker shares one with the hub, and PowerShell takes over a second to start. */
96
+ export async function processCommand(pid) {
97
+ return (await execFileAsync(...commandOf(pid), { encoding: "utf8", windowsHide: true })).stdout;
98
+ }
@@ -0,0 +1,37 @@
1
+ // What this machine is in the system: config.json, private to its owner. On a machine that runs everything it has all
2
+ // of these; a machine that only does work has the hub's address and a worker's key.
3
+ import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { HOME } from "./home.js";
6
+ import { privateDirectory } from "./files.js";
7
+ export const CONFIG_FILE = path.join(HOME, "config.json");
8
+ /** The hub's address: host:port, or [host]:port for an IPv6 address. A bare port is a mistake, not every interface. */
9
+ export function parseListen(listen) {
10
+ const match = /^\[([0-9a-fA-F:.]+)\]:([0-9]+)$/.exec(listen) ?? /^([^:\s]+):([0-9]+)$/.exec(listen);
11
+ if (!match)
12
+ throw new Error(`hub.listen 要写成 主机:端口(IPv6 用 [地址]:端口):${listen}`);
13
+ const port = Number(match[2]);
14
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
15
+ throw new Error(`hub.listen 的端口要在 1 到 65535 之间:${listen}`);
16
+ }
17
+ return { host: match[1], port };
18
+ }
19
+ /** What `up` says when it can't take its port. */
20
+ export function cantListen(error, platform = process.platform) {
21
+ const said = `can't listen: ${error}`;
22
+ if (platform !== "win32" || error.code !== "EACCES")
23
+ return said;
24
+ return (`${said}。这个端口可能在 Windows 的系统保留范围里(Hyper-V、WSL 常占一段,重启后还会变),` +
25
+ "运行 netsh int ipv4 show excludedportrange protocol=tcp 查看;" +
26
+ `换一个范围外的端口:改 ${CONFIG_FILE} 里的 url 和 hub.listen(hub.publicUrl 是本机地址时也改),再重启中台`);
27
+ }
28
+ export function readConfig() {
29
+ if (!existsSync(CONFIG_FILE))
30
+ throw new Error("还没装好:先运行 agent-autoloop init");
31
+ return JSON.parse(readFileSync(CONFIG_FILE, "utf8"));
32
+ }
33
+ export function writeConfig(config) {
34
+ privateDirectory(HOME);
35
+ writeFileSync(`${CONFIG_FILE}.tmp`, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
36
+ renameSync(`${CONFIG_FILE}.tmp`, CONFIG_FILE);
37
+ }
@@ -0,0 +1,22 @@
1
+ // POSIX modes do not protect Windows secrets. A private directory gives new files only the owner's and SYSTEM's access.
2
+ import { chmodSync, mkdirSync } from "node:fs";
3
+ import { powershell, psQuote } from "./command.js";
4
+ export function privateDirectory(directory) {
5
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
6
+ if (process.platform !== "win32")
7
+ return chmodSync(directory, 0o700);
8
+ powershell(`
9
+ $acl = [Security.AccessControl.DirectorySecurity]::new()
10
+ $acl.SetAccessRuleProtection($true, $false)
11
+ $owner = [Security.Principal.WindowsIdentity]::GetCurrent().User
12
+ $folder = ${psQuote(directory)}
13
+ # Setting even the same owner needs the right to take ownership, which a data drive's Modify doesn't give.
14
+ if ([IO.Directory]::GetAccessControl($folder, 'Owner').GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $owner.Value) {
15
+ $acl.SetOwner($owner)
16
+ }
17
+ foreach ($sid in @($owner, [Security.Principal.SecurityIdentifier]::new('S-1-5-18'))) {
18
+ $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
19
+ }
20
+ [IO.Directory]::SetAccessControl($folder, $acl)
21
+ `);
22
+ }
@@ -0,0 +1,5 @@
1
+ // Where this install keeps its things: rules.json, config.json, secrets.env, hub.db and the worker's runs.
2
+ import { homedir } from "node:os";
3
+ import path from "node:path";
4
+ export const HOME = path.resolve(process.env.AGENT_AUTOLOOP_HOME ?? path.join(homedir(), ".agent-autoloop"));
5
+ export const RULES_FILE = path.resolve(process.env.AGENT_AUTOLOOP_RULES ?? path.join(HOME, "rules.json"));
@@ -0,0 +1,45 @@
1
+ // Node's HTTP server and nothing more: each request becomes a web Request for the kernel, each answer goes back out.
2
+ import { createServer } from "node:http";
3
+ import { Readable } from "node:stream";
4
+ import { makeHandler } from "./server.js";
5
+ export function serve(port, host = "127.0.0.1", { commit = "dev" } = {}) {
6
+ const runtime = makeHandler(commit);
7
+ const server = createServer(async (req, res) => {
8
+ const gone = new AbortController();
9
+ res.on("close", () => gone.abort());
10
+ try {
11
+ const body = !["GET", "HEAD"].includes(req.method) && {
12
+ body: Readable.toWeb(req),
13
+ duplex: "half",
14
+ };
15
+ const headers = req.headers;
16
+ const request = new Request(`http://${req.headers.host}${req.url}`, {
17
+ method: req.method,
18
+ headers,
19
+ signal: gone.signal,
20
+ ...body,
21
+ });
22
+ const answer = await runtime.handle(request);
23
+ // The rest of an unread body would be taken for the next request on this connection.
24
+ if (!req.complete)
25
+ res.setHeader("connection", "close");
26
+ res.writeHead(answer.status, Object.fromEntries(answer.headers));
27
+ if (!answer.body)
28
+ return void res.end();
29
+ // Node holds the head until the first chunk: a quiet stream would look like a closed one to whoever is listening.
30
+ res.flushHeaders();
31
+ Readable.fromWeb(answer.body)
32
+ .on("error", () => res.destroy())
33
+ .pipe(res);
34
+ }
35
+ catch (error) {
36
+ console.error(error);
37
+ if (res.headersSent)
38
+ return void res.end();
39
+ res.writeHead(500, { "content-type": "application/json" }).end(JSON.stringify({ error: "中台出错了" }));
40
+ }
41
+ });
42
+ server.on("close", runtime.close);
43
+ server.listen({ port, host, backlog: 2048 });
44
+ return server;
45
+ }
@@ -0,0 +1,188 @@
1
+ // The fixed supervisor an npm install is started through: it reads update/current.json, starts that version, and switches
2
+ // to a staged one when the hub asks. It imports nothing from the program and changes only by being replaced, so a broken
3
+ // release can never take the ability to roll back with it. Protocol, frozen for old launchers: exit 75 means start the
4
+ // pending version now; boot.json ready:true means the started hub got as far as listening.
5
+ import { spawn } from "node:child_process";
6
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
7
+ import path from "node:path";
8
+ const HOME = path.resolve(process.env.AGENT_AUTOLOOP_HOME ?? path.dirname(path.dirname(import.meta.dirname)));
9
+ const UPDATE = path.join(HOME, "update");
10
+ const CURRENT = path.join(UPDATE, "current.json");
11
+ const PENDING = path.join(UPDATE, "pending.json");
12
+ const BOOT = path.join(UPDATE, "boot.json");
13
+ const BAD = path.join(UPDATE, "bad.json");
14
+ const FAILURES = path.join(UPDATE, "failures.json");
15
+ const PID_FILE = path.join(UPDATE, "launcher.pid");
16
+ const ENTRY = path.join("dist", "bin", "agent-autoloop.js");
17
+ const RESTART_EXIT = 75;
18
+ const BOOT_TIMEOUT = Number(process.env.AGENT_AUTOLOOP_BOOT_TIMEOUT_MS ?? 90_000);
19
+ const RESTART_DELAY = Number(process.env.AGENT_AUTOLOOP_RESTART_DELAY_MS ?? 5_000);
20
+ const log = (line) => {
21
+ const text = `${new Date().toISOString()} [launcher] ${line}\n`;
22
+ try {
23
+ mkdirSync(UPDATE, { recursive: true, mode: 0o700 });
24
+ appendFileSync(path.join(UPDATE, "launcher.log"), text);
25
+ }
26
+ catch { }
27
+ process.stderr.write(text);
28
+ };
29
+ function readJson(file) {
30
+ try {
31
+ return JSON.parse(readFileSync(file, "utf8"));
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ }
37
+ function writeJson(file, value) {
38
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
39
+ const temporary = `${file}.${process.pid}.tmp`;
40
+ writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
41
+ renameSync(temporary, file);
42
+ }
43
+ const runs = (pointer) => existsSync(path.join(pointer.dir, ENTRY));
44
+ function current() {
45
+ const value = readJson(CURRENT);
46
+ return value && typeof value.version === "string" && typeof value.dir === "string" && runs(value) ? value : null;
47
+ }
48
+ function pending() {
49
+ const value = readJson(PENDING);
50
+ return value && typeof value.version === "string" && typeof value.dir === "string" && runs(value) ? value : null;
51
+ }
52
+ function boot() {
53
+ return readJson(BOOT);
54
+ }
55
+ /** Counted here, not in boot.json: the child writes that file when it is ready. */
56
+ function failuresFor(version) {
57
+ const state = readJson(FAILURES);
58
+ return state?.version === version ? (state.count ?? 0) : 0;
59
+ }
60
+ const setFailures = (version, count) => writeJson(FAILURES, { version, count });
61
+ /** A staged version becomes current before the next start. Same version pending is dropped, never made its own previous. */
62
+ function applyPending() {
63
+ const next = pending();
64
+ if (!next)
65
+ return;
66
+ const running = current();
67
+ rmSync(PENDING, { force: true });
68
+ if (running?.version === next.version)
69
+ return;
70
+ writeJson(CURRENT, {
71
+ version: next.version,
72
+ dir: next.dir,
73
+ ...(running && { previous: { version: running.version, dir: running.dir } }),
74
+ });
75
+ log(`staged ${next.version} is now current`);
76
+ }
77
+ function markBad(version) {
78
+ const bad = readJson(BAD);
79
+ const versions = new Set(Array.isArray(bad?.versions) ? bad.versions : []);
80
+ versions.add(version);
81
+ writeJson(BAD, { versions: [...versions] });
82
+ }
83
+ function rollback() {
84
+ const failed = current();
85
+ if (!failed)
86
+ return false;
87
+ markBad(failed.version);
88
+ const previous = failed.previous;
89
+ if (!previous || !runs(previous)) {
90
+ log(`${failed.version} failed twice and there is no earlier version to go back to`);
91
+ return false;
92
+ }
93
+ writeJson(CURRENT, { version: previous.version, dir: previous.dir });
94
+ log(`${failed.version} failed twice; back to ${previous.version}`);
95
+ return true;
96
+ }
97
+ const ready = (pid, version) => {
98
+ const state = boot();
99
+ return state?.ready === true && state.pid === pid && state.version === version;
100
+ };
101
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
102
+ function removePidFile() {
103
+ if (readJson(PID_FILE)?.pid === process.pid)
104
+ rmSync(PID_FILE, { force: true });
105
+ }
106
+ async function main() {
107
+ mkdirSync(UPDATE, { recursive: true, mode: 0o700 });
108
+ writeJson(PID_FILE, { pid: process.pid });
109
+ let stopping = false;
110
+ let child = null;
111
+ const stop = () => {
112
+ if (stopping)
113
+ return;
114
+ stopping = true;
115
+ if (child && child.exitCode === null) {
116
+ child.kill("SIGTERM");
117
+ setTimeout(() => child?.kill("SIGKILL"), 5_000).unref();
118
+ }
119
+ };
120
+ process.on("SIGTERM", stop);
121
+ process.on("SIGINT", stop);
122
+ try {
123
+ while (!stopping) {
124
+ applyPending();
125
+ const running = current();
126
+ if (!running) {
127
+ log(`没有可启动的版本:${CURRENT} 不存在或指向的副本不完整`);
128
+ process.exitCode = 1;
129
+ return;
130
+ }
131
+ let failures = failuresFor(running.version);
132
+ writeJson(BOOT, { ready: false, version: running.version, at: Date.now() });
133
+ const started = spawn(process.execPath, ["--disable-warning=ExperimentalWarning", path.join(running.dir, ENTRY), "up"], {
134
+ cwd: HOME,
135
+ env: { ...process.env, AGENT_AUTOLOOP_HOME: HOME, AGENT_AUTOLOOP_LAUNCHED: "1" },
136
+ stdio: "inherit",
137
+ });
138
+ child = started;
139
+ let gaveUp = false;
140
+ const timer = setTimeout(() => {
141
+ if (ready(started.pid ?? -1, running.version))
142
+ return;
143
+ gaveUp = true;
144
+ log(`${running.version} 在 ${BOOT_TIMEOUT} 毫秒内没有开始应答,停掉它`);
145
+ started.kill("SIGTERM");
146
+ setTimeout(() => started.kill("SIGKILL"), 5_000).unref();
147
+ }, BOOT_TIMEOUT);
148
+ const [code] = await new Promise((resolve) => {
149
+ started.once("exit", (exit, signal) => resolve([exit, signal]));
150
+ started.once("error", (error) => {
151
+ log(`启动 ${running.version} 失败:${error.message}`);
152
+ resolve([1, null]);
153
+ });
154
+ });
155
+ clearTimeout(timer);
156
+ child = null;
157
+ if (stopping)
158
+ return;
159
+ if (code === RESTART_EXIT) {
160
+ log(`${running.version} 要求现在切换`);
161
+ continue;
162
+ }
163
+ if (ready(started.pid ?? -1, running.version)) {
164
+ rmSync(FAILURES, { force: true });
165
+ await sleep(RESTART_DELAY);
166
+ continue;
167
+ }
168
+ failures += 1;
169
+ setFailures(running.version, failures);
170
+ log(`${running.version} 没有就绪就退出了(${gaveUp ? "启动超时" : `退出码 ${code}`}),第 ${failures} 次`);
171
+ if (failures >= 2) {
172
+ if (!rollback())
173
+ process.exitCode = 1;
174
+ if (process.exitCode)
175
+ return;
176
+ continue;
177
+ }
178
+ await sleep(RESTART_DELAY);
179
+ }
180
+ }
181
+ finally {
182
+ removePidFile();
183
+ }
184
+ }
185
+ main().catch((error) => {
186
+ log(`启动器停了:${error?.stack ?? error}`);
187
+ process.exit(1);
188
+ });
@@ -0,0 +1,15 @@
1
+ export function eachLine(input, onLine, onEnd = () => { }) {
2
+ let rest = "";
3
+ input.setEncoding("utf8");
4
+ input.on("data", (chunk) => {
5
+ const lines = (rest + chunk).split("\n");
6
+ rest = lines.pop();
7
+ for (const line of lines)
8
+ onLine(line);
9
+ });
10
+ input.on("end", () => {
11
+ if (rest)
12
+ onLine(rest);
13
+ onEnd();
14
+ });
15
+ }