@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,162 @@
1
+ // Everything this machine does, in one process: the hub, the worker and its channels, whichever config.json says. They
2
+ // speak the same protocol to each other here as they would across the world. A stop leaves agents running: they're
3
+ // detached, and the worker finds them again when it's back.
4
+ import { existsSync, mkdirSync, unlinkSync, writeFileSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { loadChannel } from "./channels.js";
7
+ import { cantListen, parseListen, readConfig } from "./config.js";
8
+ import { HOME } from "./home.js";
9
+ import { runningUp } from "./service.js";
10
+ import { commitOf } from "./version.js";
11
+ import { RESTART_EXIT, autoUpdateOff, managedAt, markBootReady, pointSkill, readPending, refreshLauncher, stageInBackground, } from "./update.js";
12
+ import { hubClient } from "../protocol/client.js";
13
+ import { createWorker } from "../worker/worker.js";
14
+ const log = (who) => (line) => console.log(`${new Date().toISOString()} [${who}] ${line}`);
15
+ /** Only one of these per install: a second would take work beside the first. */
16
+ function lock() {
17
+ const running = runningUp();
18
+ // Its own number is what was left behind: pid 1 every time in a container, and a matter of luck after a restart.
19
+ if (running !== null && running !== process.pid)
20
+ throw new Error(`已经在跑了(进程 ${running})`);
21
+ const file = path.join(HOME, "up.pid");
22
+ writeFileSync(file, String(process.pid));
23
+ return () => {
24
+ try {
25
+ unlinkSync(file);
26
+ }
27
+ catch { }
28
+ };
29
+ }
30
+ /** secrets.env: what an adapter needs to check a webhook, kept out of rules.json. */
31
+ function loadSecrets() {
32
+ const file = path.join(HOME, "secrets.env");
33
+ if (existsSync(file))
34
+ process.loadEnvFile(file);
35
+ }
36
+ /** What runs beside the hub is started again however it stops, after a pause: one that returned at once would hog it. */
37
+ async function keepRunning(say, run, signal) {
38
+ while (!signal.aborted) {
39
+ try {
40
+ await run();
41
+ if (signal.aborted)
42
+ return;
43
+ say("stopped; starting again in 30 seconds");
44
+ }
45
+ catch (error) {
46
+ say(`stopped: ${error}; starting again in 30 seconds`);
47
+ }
48
+ await new Promise((resolve) => setTimeout(resolve, 30_000));
49
+ }
50
+ }
51
+ function keepChannelRunning(id, { use, key, ...options }, url, signal) {
52
+ const say = log(id);
53
+ return keepRunning(say, async () => {
54
+ const start = await loadChannel(use ?? id);
55
+ await start({ hub: hubClient(url, key), options, log: say, signal });
56
+ }, signal);
57
+ }
58
+ /** Waits for a staged version. Runs that are already working are never cut short; the switch happens between them. */
59
+ function startAutoUpdate(say, switchOut) {
60
+ if (!managedAt(HOME) || process.env.AGENT_AUTOLOOP_LAUNCHED !== "1" || autoUpdateOff())
61
+ return;
62
+ let switching = false;
63
+ const every = Number(process.env.AGENT_AUTOLOOP_UPDATE_INTERVAL_MS ?? 6 * 60 * 60 * 1000);
64
+ // Unpacking happens in another process: a slow registry must not hold up claims.
65
+ setTimeout(() => stageInBackground(), Number(process.env.AGENT_AUTOLOOP_UPDATE_DELAY_MS ?? 60_000)).unref();
66
+ setInterval(() => stageInBackground(), every).unref();
67
+ const check = async () => {
68
+ const pending = readPending();
69
+ if (!pending || switching)
70
+ return;
71
+ const { activeRuns } = await import("./runtime.js");
72
+ if (activeRuns() !== 0)
73
+ return;
74
+ switching = true;
75
+ clearInterval(timer);
76
+ say(`${pending.version} 已准备好,现在换过去`);
77
+ await switchOut();
78
+ };
79
+ const timer = setInterval(check, 60_000);
80
+ timer.unref();
81
+ void check();
82
+ }
83
+ export async function up() {
84
+ const config = readConfig();
85
+ mkdirSync(HOME, { recursive: true, mode: 0o700 });
86
+ const unlock = lock();
87
+ // Plugins run in this process, and an `error` event or a promise nobody handled is theirs to answer for, not the hub's.
88
+ // Everything that matters is in transactions, so the rest can carry on.
89
+ const stray = log("up");
90
+ process.on("uncaughtException", (error) => stray(`stray error: ${error?.stack ?? error}`));
91
+ process.on("unhandledRejection", (error) => stray(`stray error: ${error?.stack ?? error}`));
92
+ // Except losing where the log goes: writing that down fails the same way, for ever. It stops, and a service brings it back.
93
+ for (const output of [process.stdout, process.stderr])
94
+ output.on("error", () => process.exit(1));
95
+ const stop = new AbortController();
96
+ const jobs = [];
97
+ let close = () => { };
98
+ if (config.hub) {
99
+ loadSecrets();
100
+ const { host, port } = parseListen(config.hub.listen);
101
+ process.env.AGENT_AUTOLOOP_PUBLIC_URL = config.hub.publicUrl ?? `http://${config.hub.listen}`;
102
+ const { serve } = await import("./http.js");
103
+ const say = log("hub");
104
+ if (!["127.0.0.1", "localhost", "::1"].includes(host)) {
105
+ say(`${host} 不是本机回环地址,中台会向这个地址所在的网络开放;前面要有 HTTPS 反向代理`);
106
+ }
107
+ const server = serve(port, host, { commit: commitOf() });
108
+ server.on("listening", () => say(`listening on ${config.hub.listen}`));
109
+ server.on("error", (error) => {
110
+ say(cantListen(error));
111
+ process.exit(1);
112
+ });
113
+ close = () => {
114
+ server.close();
115
+ server.closeAllConnections();
116
+ };
117
+ await new Promise((resolve) => {
118
+ if (server.listening)
119
+ resolve();
120
+ else
121
+ server.once("listening", () => resolve());
122
+ });
123
+ }
124
+ if (config.worker) {
125
+ const { key, name, capacity, unreachable } = config.worker;
126
+ const say = log("worker");
127
+ const worker = createWorker({ hub: hubClient(config.url, key), name, capacity, unreachable, log: say });
128
+ jobs.push(keepRunning(say, () => worker.run(stop.signal), stop.signal));
129
+ }
130
+ for (const [id, channel] of Object.entries(config.channels ?? {})) {
131
+ jobs.push(keepChannelRunning(id, channel, config.url, stop.signal));
132
+ }
133
+ refreshLauncher();
134
+ // A hub that starts matters more than the link to its manual: a folder the user's home won't take is worth a line, not
135
+ // refusing to run.
136
+ try {
137
+ pointSkill();
138
+ }
139
+ catch (error) {
140
+ log("hub")(`没能把 Skill 链接指过来:${error.message}`);
141
+ }
142
+ markBootReady();
143
+ const finish = () => {
144
+ stop.abort();
145
+ close();
146
+ unlock();
147
+ process.exit(0);
148
+ };
149
+ const switchOut = async () => {
150
+ const { activeRuns } = await import("./runtime.js");
151
+ if (activeRuns() > 0)
152
+ return;
153
+ stop.abort();
154
+ close();
155
+ unlock();
156
+ process.exit(RESTART_EXIT);
157
+ };
158
+ process.on("SIGTERM", finish);
159
+ process.on("SIGINT", finish);
160
+ startAutoUpdate(log("update"), switchOut);
161
+ await Promise.all(jobs);
162
+ }
@@ -0,0 +1,286 @@
1
+ // Updating an npm install without writing over the copy that's running: each version is unpacked beside the others under
2
+ // HOME/versions, and a small launcher starts the one update/current.json names. A staged version waits in pending.json
3
+ // until the hub has no run in flight; then the launcher switches at the next start.
4
+ import { spawn, spawnSync } from "node:child_process";
5
+ import { closeSync, cpSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync, } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import path from "node:path";
8
+ import { HOME } from "./home.js";
9
+ import { npm, npmPrefix, PACKAGE } from "./npm.js";
10
+ import { ROOT } from "./program.js";
11
+ /** What the launcher exits with when it should start the staged version now. */
12
+ export const RESTART_EXIT = 75;
13
+ /** Only the official registry is asked: a mirror's "latest" is not what was published. */
14
+ export const REGISTRY = "https://registry.npmjs.org/";
15
+ const ENTRY = path.join("dist", "bin", "agent-autoloop.js");
16
+ const STALE_LOCK_MS = 30 * 60 * 1000;
17
+ export const updateDir = (home = HOME) => path.join(home, "update");
18
+ export const versionsDir = (home = HOME) => path.join(home, "versions");
19
+ export const launcherFile = (home = HOME) => path.join(home, "launcher", "launcher.mjs");
20
+ const pointerFile = (home) => path.join(updateDir(home), "current.json");
21
+ const pendingFile = (home) => path.join(updateDir(home), "pending.json");
22
+ const badFile = (home) => path.join(updateDir(home), "bad.json");
23
+ const bootFile = (home) => path.join(updateDir(home), "boot.json");
24
+ function readJson(file) {
25
+ try {
26
+ return JSON.parse(readFileSync(file, "utf8"));
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
32
+ /** A half-written file is never read as a pointer: a rename is what makes one visible. */
33
+ function writeJson(file, value) {
34
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
35
+ const temporary = `${file}.${process.pid}.tmp`;
36
+ writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
37
+ renameSync(temporary, file);
38
+ }
39
+ /** The package folder a version is unpacked to, as npm lays a global install out. */
40
+ export function packageDir(version, home = HOME) {
41
+ return path.join(versionsDir(home), version, "node_modules", ...PACKAGE.split("/"));
42
+ }
43
+ export function manifestVersion(dir) {
44
+ const manifest = readJson(path.join(dir, "package.json"));
45
+ if (manifest?.name !== PACKAGE || typeof manifest.version !== "string")
46
+ return null;
47
+ return /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(manifest.version) ? manifest.version : null;
48
+ }
49
+ /** What the launcher should start: both the pointer and the folder it names have to be there. */
50
+ export function readPointer(home = HOME) {
51
+ const pointer = readJson(pointerFile(home));
52
+ if (!pointer || typeof pointer.version !== "string" || typeof pointer.dir !== "string")
53
+ return null;
54
+ if (!existsSync(path.join(pointer.dir, ENTRY)))
55
+ return null;
56
+ return pointer;
57
+ }
58
+ export function readPending(home = HOME) {
59
+ const pending = readJson(pendingFile(home));
60
+ if (!pending || typeof pending.version !== "string" || typeof pending.dir !== "string")
61
+ return null;
62
+ if (!existsSync(path.join(pending.dir, ENTRY)))
63
+ return null;
64
+ return pending;
65
+ }
66
+ export function managedAt(home = HOME) {
67
+ return readPointer(home) !== null && existsSync(launcherFile(home));
68
+ }
69
+ export function managedVersion(home = HOME) {
70
+ return readPointer(home)?.version ?? null;
71
+ }
72
+ /** Unlike a try-out, a stable release wins over the same version's prerelease. A version this can't tell apart stays. */
73
+ export function isNewer(latest, current) {
74
+ const [left, right] = [latest, current].map((version) => version.split("-")[0].split(".").map(Number));
75
+ const order = left[0] - right[0] || left[1] - right[1] || left[2] - right[2];
76
+ return order > 0 || (order === 0 && !latest.includes("-") && current.includes("-"));
77
+ }
78
+ /**
79
+ * Puts this npm install under the managed layout: its files are copied to versions/<v>, the launcher from the same
80
+ * build goes to HOME/launcher, and current.json points at the copy. A checkout is left as it is.
81
+ */
82
+ export function prepareManaged(root = ROOT, home = HOME) {
83
+ // Already one of the copies: pointing at it again would nest versions inside versions.
84
+ if (path.resolve(root).startsWith(`${path.resolve(versionsDir(home))}${path.sep}`))
85
+ return readPointer(home);
86
+ // A checkout runs its own files; copying it would freeze a snapshot and cut `update` off git.
87
+ if (existsSync(path.join(root, ".git")))
88
+ return null;
89
+ if (npmPrefix(root) === null)
90
+ return null;
91
+ const version = manifestVersion(root);
92
+ if (!version)
93
+ throw new Error(`${root} 的 package.json 里没有能用的版本号`);
94
+ const sourceLauncher = path.join(root, "dist", "host", "launcher.js");
95
+ if (!existsSync(sourceLauncher))
96
+ throw new Error(`${root} 里没有编译好的启动器(dist/host/launcher.js)`);
97
+ const dir = packageDir(version, home);
98
+ if (!existsSync(path.join(dir, ENTRY))) {
99
+ const temporary = `${dir}.${process.pid}.tmp`;
100
+ mkdirSync(path.dirname(dir), { recursive: true, mode: 0o700 });
101
+ rmSync(temporary, { recursive: true, force: true });
102
+ cpSync(root, temporary, {
103
+ recursive: true,
104
+ filter: (source) => ![".git", "node_modules", ".output"].includes(path.basename(source)),
105
+ });
106
+ rmSync(dir, { recursive: true, force: true });
107
+ renameSync(temporary, dir);
108
+ }
109
+ const launcher = launcherFile(home);
110
+ mkdirSync(path.dirname(launcher), { recursive: true, mode: 0o700 });
111
+ writeFileSync(launcher, readFileSync(sourceLauncher), { mode: 0o700 });
112
+ const before = readPointer(home);
113
+ const pointer = before && before.version !== version
114
+ ? { version, dir, previous: { version: before.version, dir: before.dir } }
115
+ : { version, dir, ...(before?.previous && { previous: before.previous }) };
116
+ writeJson(pointerFile(home), pointer);
117
+ // It's already this version; anything staged for it adds nothing.
118
+ const pending = readPending(home);
119
+ if (pending?.version === version)
120
+ rmSync(pendingFile(home), { force: true });
121
+ return pointer;
122
+ }
123
+ /**
124
+ * The shared Skill is a link to the running version's folder: the manual's `../../README.md`, `docs/`, `examples/` and
125
+ * `plugins/` sources are the ones in the copy that's running, the same as in a checkout. A link this install made moves
126
+ * to the new version; a folder, a file or someone else's link in that place is left alone.
127
+ */
128
+ export function pointSkill(home = HOME, person = homedir()) {
129
+ // A data folder somewhere else is a throwaway: no user's home is told about it.
130
+ if (!path.resolve(home).startsWith(`${path.resolve(person)}${path.sep}`))
131
+ return;
132
+ const target = skillTarget(home);
133
+ if (!existsSync(target))
134
+ return;
135
+ const link = path.join(person, ".agents", "skills", "agent-autoloop");
136
+ const existing = lstatSync(link, { throwIfNoEntry: false });
137
+ if (existing) {
138
+ let leads = null;
139
+ if (existing.isSymbolicLink()) {
140
+ try {
141
+ leads = realpathSync(link);
142
+ }
143
+ catch {
144
+ // It leads nowhere: not ours to move.
145
+ }
146
+ }
147
+ if (leads === realpathSync(target))
148
+ return;
149
+ // Only a link into this install's data folder is ours; an older version kept a copy there instead.
150
+ if (leads === null || !leads.startsWith(`${path.resolve(home)}${path.sep}`))
151
+ return;
152
+ unlinkSync(link);
153
+ }
154
+ rmSync(path.join(home, "skills"), { recursive: true, force: true });
155
+ mkdirSync(path.dirname(link), { recursive: true, mode: 0o700 });
156
+ symlinkSync(target, link, process.platform === "win32" ? "junction" : "dir");
157
+ }
158
+ /** The Skill folder of the version that's running, or of this checkout when nothing is managed. */
159
+ export function skillTarget(home = HOME) {
160
+ return path.join(readPointer(home)?.dir ?? ROOT, "skills", "agent-autoloop");
161
+ }
162
+ /** A fixed launcher is picked up at the next start; the one running now keeps its code. */
163
+ export function refreshLauncher(root = ROOT, home = HOME) {
164
+ if (!readPointer(home))
165
+ return;
166
+ const source = path.join(root, "dist", "host", "launcher.js");
167
+ if (!existsSync(source))
168
+ return;
169
+ const target = launcherFile(home);
170
+ const bytes = readFileSync(source);
171
+ if (existsSync(target) && readFileSync(target).equals(bytes))
172
+ return;
173
+ mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
174
+ writeFileSync(target, bytes, { mode: 0o700 });
175
+ }
176
+ function badVersions(home) {
177
+ const bad = readJson(badFile(home));
178
+ return Array.isArray(bad?.versions) ? bad.versions : [];
179
+ }
180
+ export function markBad(version, home = HOME) {
181
+ const versions = new Set(badVersions(home));
182
+ versions.add(version);
183
+ writeJson(badFile(home), { versions: [...versions] });
184
+ }
185
+ /** Marks the hub that the launcher just started as ready; a start that never gets here is counted as a failure. */
186
+ export function markBootReady(home = HOME) {
187
+ const pointer = readPointer(home);
188
+ if (!pointer)
189
+ return;
190
+ writeJson(bootFile(home), { ready: true, pid: process.pid, version: pointer.version, at: Date.now() });
191
+ }
192
+ /** Automatic updates are the default; a person who doesn't want them says so in config.json. */
193
+ export function autoUpdateOff() {
194
+ if (process.env.AGENT_AUTOLOOP_NO_UPDATE === "1" || process.env.CI === "true")
195
+ return true;
196
+ const config = readJson(path.join(HOME, "config.json"));
197
+ return config?.update?.autoUpdate === false;
198
+ }
199
+ function acquireLock(home) {
200
+ const lock = path.join(updateDir(home), "stage.lock");
201
+ mkdirSync(updateDir(home), { recursive: true, mode: 0o700 });
202
+ try {
203
+ mkdirSync(lock);
204
+ return lock;
205
+ }
206
+ catch {
207
+ // A launcher killed mid-stage leaves this behind; an old one is taken over.
208
+ try {
209
+ if (Date.now() - statSync(lock).mtimeMs < STALE_LOCK_MS)
210
+ return null;
211
+ rmSync(lock, { recursive: true, force: true });
212
+ mkdirSync(lock);
213
+ return lock;
214
+ }
215
+ catch {
216
+ return null;
217
+ }
218
+ }
219
+ }
220
+ /**
221
+ * Does the check in another process: `npm install` takes seconds, and the hub answers claims while it runs. Its result
222
+ * lands in pending.json; what went wrong goes to logs/update.log.
223
+ */
224
+ export function stageInBackground(home = HOME) {
225
+ const logs = path.join(home, "logs");
226
+ mkdirSync(logs, { recursive: true, mode: 0o700 });
227
+ const log = openSync(path.join(logs, "update.log"), "a", 0o600);
228
+ const child = spawn(process.execPath, ["--disable-warning=ExperimentalWarning", path.join(ROOT, ENTRY), "stage-update"], {
229
+ env: { ...process.env, AGENT_AUTOLOOP_HOME: home },
230
+ stdio: ["ignore", log, log],
231
+ detached: true,
232
+ windowsHide: true,
233
+ });
234
+ child.unref();
235
+ closeSync(log);
236
+ }
237
+ /**
238
+ * Unpacks the newest published version beside the running one and leaves it pending. Nothing running is touched: the
239
+ * launcher switches when the hub next starts. Failures leave no pending version behind.
240
+ */
241
+ export function stageLatest(home = HOME) {
242
+ const pointer = readPointer(home);
243
+ if (!pointer)
244
+ return { status: "unmanaged" };
245
+ const latest = npm(["view", PACKAGE, "version", "--registry", REGISTRY]);
246
+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(latest)) {
247
+ throw new Error(`npm 上 ${PACKAGE} 的版本号读不出来:${latest}`);
248
+ }
249
+ if (!isNewer(latest, pointer.version))
250
+ return { status: "current", version: pointer.version };
251
+ if (badVersions(home).includes(latest))
252
+ return { status: "bad", version: latest };
253
+ if (readPending(home)?.version === latest)
254
+ return { status: "pending", version: latest };
255
+ const lock = acquireLock(home);
256
+ if (!lock)
257
+ return { status: "busy" };
258
+ const prefix = path.join(versionsDir(home), latest);
259
+ const dir = packageDir(latest, home);
260
+ try {
261
+ if (manifestVersion(dir) !== latest) {
262
+ rmSync(prefix, { recursive: true, force: true });
263
+ npm(["install", "--prefix", prefix, `${PACKAGE}@${latest}`, "--no-audit", "--no-fund", "--registry", REGISTRY]);
264
+ }
265
+ if (manifestVersion(dir) !== latest)
266
+ throw new Error(`装好的 ${PACKAGE}@${latest} 版本号不对`);
267
+ const done = spawnSync(process.execPath, [path.join(dir, ENTRY), "--version"], {
268
+ encoding: "utf8",
269
+ timeout: 30_000,
270
+ env: { ...process.env, AGENT_AUTOLOOP_NO_UPDATE: "1" },
271
+ });
272
+ if (done.status !== 0 || !done.stdout.includes(latest)) {
273
+ throw new Error(`${PACKAGE}@${latest} 起不来:${done.stderr?.trim() || done.stdout?.trim() || done.error}`);
274
+ }
275
+ writeJson(pendingFile(home), { version: latest, dir, at: Date.now() });
276
+ return { status: "staged", version: latest };
277
+ }
278
+ catch (error) {
279
+ rmSync(prefix, { recursive: true, force: true });
280
+ rmSync(pendingFile(home), { force: true });
281
+ throw error;
282
+ }
283
+ finally {
284
+ rmSync(lock, { recursive: true, force: true });
285
+ }
286
+ }
@@ -0,0 +1,81 @@
1
+ // Which code this is: the release tag on a checkout's commit, or the version in the manifest of an installed copy, and the
2
+ // commit. The npm registry requires a version in package.json, so that and the tag say the same thing; a checkout past its
3
+ // tag still says "未发布", because the number in a file names the last release on every commit after it.
4
+ import { execFileSync } from "node:child_process";
5
+ import { existsSync, readFileSync } from "node:fs";
6
+ import path from "node:path";
7
+ import { HOME } from "./home.js";
8
+ import { ROOT } from "./program.js";
9
+ import { managedVersion, versionsDir } from "./update.js";
10
+ const VERSION = /^v\d+\.\d+\.\d+(-[a-z0-9.]+)?$/;
11
+ /** A copy unpacked under versions names itself; the pointer would name whichever one runs now. */
12
+ const insideVersions = (root, home) => path.resolve(root).startsWith(`${path.resolve(versionsDir(home))}${path.sep}`);
13
+ /** The version the launcher is running, for the npm bootstrap whose own manifest names what it shipped with. */
14
+ export function managedRelease(home = HOME) {
15
+ const managed = managedVersion(home);
16
+ return managed ? `v${managed}` : null;
17
+ }
18
+ /** What `npm install` gave: the manifest says which release these files are. */
19
+ function installedRelease(root) {
20
+ try {
21
+ const manifest = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8"));
22
+ const version = typeof manifest.version === "string" ? `v${manifest.version}` : "";
23
+ return VERSION.test(version) ? version : null;
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ }
29
+ /** What was deployed, or the checkout's commit. Git says: after a gc a branch's ref is no longer a file of its own. */
30
+ export function commitOf(root = ROOT) {
31
+ if (process.env.AGENT_AUTOLOOP_COMMIT)
32
+ return process.env.AGENT_AUTOLOOP_COMMIT;
33
+ try {
34
+ // Only a checkout has its own .git entry; unpacked copies must not inherit a parent repository's commit.
35
+ if (!existsSync(path.join(root, ".git")))
36
+ return "dev";
37
+ const args = ["-C", root, "rev-parse", "HEAD"];
38
+ return execFileSync("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
39
+ }
40
+ catch {
41
+ return "dev";
42
+ }
43
+ }
44
+ /**
45
+ * The release this commit is, if it is one. A try-out tag left on the same commit gives way to the release it became.
46
+ * A deployment unpacked from a tag has no tag of its own: the environment it was started with carries it, the way
47
+ * `AGENT_AUTOLOOP_COMMIT` carries the commit. A value that isn't a version counts for nothing.
48
+ */
49
+ export function releaseOf(root = ROOT, home = HOME) {
50
+ const fromEnv = process.env.AGENT_AUTOLOOP_RELEASE?.trim();
51
+ if (fromEnv)
52
+ return /^v\d+\.\d+\.\d+(-[a-z0-9.]+)?$/.test(fromEnv) ? fromEnv : null;
53
+ try {
54
+ if (!existsSync(path.join(root, ".git"))) {
55
+ // The command that was typed can be the npm bootstrap, whose own manifest still names the version it shipped
56
+ // with: what's running is what the managed pointer names. A version unpacked under versions says its own number.
57
+ if (root === ROOT && !insideVersions(root, home)) {
58
+ const managed = managedRelease(home);
59
+ if (managed)
60
+ return managed;
61
+ }
62
+ return installedRelease(root);
63
+ }
64
+ const args = ["-C", root, "tag", "--points-at", "HEAD"];
65
+ const tags = execFileSync("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).split("\n");
66
+ return tags.find((tag) => /^v\d+\.\d+\.\d+$/.test(tag)) ?? tags.find((tag) => /^v\d+\.\d+\.\d+-/.test(tag)) ?? null;
67
+ }
68
+ catch {
69
+ return null;
70
+ }
71
+ }
72
+ /** What other programs are told this is. */
73
+ export function versionName(root = ROOT) {
74
+ return releaseOf(root) ?? commitOf(root).slice(0, 12);
75
+ }
76
+ export function versionLine(root = ROOT) {
77
+ const release = releaseOf(root) ?? "未发布";
78
+ const commit = commitOf(root).slice(0, 12);
79
+ // An install from npm has no commit to name; a checkout or an unpacked copy still does.
80
+ return commit === "dev" ? `agent-autoloop ${release}` : `agent-autoloop ${release}(提交 ${commit})`;
81
+ }
@@ -0,0 +1,54 @@
1
+ // The one page there is: a card at its own link, for channels that can only send words. A plain form, so it needs no
2
+ // script, no sign-in and nothing else from the hub. An Agent wrote what it shows after reading other people's words:
3
+ // all of it is escaped, and the only thing the page may load is its own style.
4
+ import { createHash } from "node:crypto";
5
+ const STYLE = `:root{color-scheme:light dark;font:16px/1.6 system-ui,sans-serif}
6
+ body{max-width:34rem;margin:0 auto;padding:32px 16px;overflow-wrap:anywhere}
7
+ h1{font-size:1.25rem;line-height:1.4;margin:0 0 12px}
8
+ p{white-space:pre-wrap;margin:0 0 20px}
9
+ .from{margin:-8px 0 16px;color:GrayText;font-size:.875rem}
10
+ form{display:flex;flex-wrap:wrap;gap:8px;margin:0 0 12px}
11
+ button,input{font:inherit;min-height:44px;border-radius:8px;border:1px solid GrayText;padding:0 16px;\
12
+ background:Canvas;color:CanvasText}
13
+ button.best{background:CanvasText;color:Canvas;border-color:CanvasText}
14
+ input{flex:1 1 12rem;min-width:0}`;
15
+ const STYLE_SHA = createHash("sha256").update(STYLE).digest("base64");
16
+ const POLICY = `default-src 'none'; style-src 'sha256-${STYLE_SHA}'; ` +
17
+ "form-action 'self'; frame-ancestors 'none'; base-uri 'none'";
18
+ export const PAGE_HEADERS = {
19
+ "content-type": "text/html; charset=utf-8",
20
+ "cache-control": "no-store",
21
+ "x-content-type-options": "nosniff",
22
+ "referrer-policy": "no-referrer",
23
+ "content-security-policy": POLICY,
24
+ };
25
+ const ENTITIES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
26
+ const escaped = (words) => words.replace(/[&<>"']/g, (char) => ENTITIES[char]);
27
+ const shell = (title, content) => `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">` +
28
+ `<meta name="viewport" content="width=device-width,initial-scale=1"><title>${escaped(title)}</title>` +
29
+ `<style>${STYLE}</style></head><body>${content}</body></html>`;
30
+ export const wordsPage = (words) => shell(words, `<p>${escaped(words)}</p>`);
31
+ export function cardPage(card) {
32
+ const from = card.rule && card.rule !== card.title ? `<p class="from">来源:${escaped(card.rule)}</p>` : "";
33
+ const words = `<h1>${escaped(card.title)}</h1>${from}${card.text ? `<p>${escaped(card.text)}</p>` : ""}`;
34
+ if (card.state === "open") {
35
+ const focused = card.recommend ?? 0;
36
+ const button = (option, index) => {
37
+ const best = index === card.recommend ? ' class="best"' : "";
38
+ const focus = index === focused ? " autofocus" : "";
39
+ return `<button name="choice" value="${index}"${best}${focus}>${escaped(option)}</button>`;
40
+ };
41
+ // Its own form: Enter in the box mustn't press the first option.
42
+ // A notice can take a line on how it was handled: optional, and kept with the closing.
43
+ const notice = card.kind === "notice";
44
+ const box = notice
45
+ ? `<input name="text" placeholder="我实际怎么处理的(可不填)" aria-label="处理说明">`
46
+ : `<input name="text" placeholder="别的想法" aria-label="别的想法" required>`;
47
+ const other = `<form method="post">${box}<button>${notice ? "记录并结案" : "发送"}</button></form>`;
48
+ return shell(card.title, `${words}<form method="post">${card.options.map(button).join("")}</form>${other}`);
49
+ }
50
+ const chosen = card.kind === "ask" ? (card.choice !== null ? card.options[card.choice] : card.answer) : null;
51
+ const outcome = [chosen ? `你选了「${chosen}」` : "", card.result ?? ""].filter(Boolean).join("。");
52
+ const settled = card.kind === "notice" && card.answer ? `<p>处理说明:${escaped(card.answer)}</p>` : "";
53
+ return shell(card.title, `${words}${outcome ? `<p>${escaped(outcome)}</p>` : ""}${settled}`);
54
+ }
@@ -0,0 +1,16 @@
1
+ // Run tokens and card links derive from the master key, so they're never stored. Access keys are kept only as hashes.
2
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
3
+ import { rows } from "./evolve.js";
4
+ export const digest = (text) => createHash("sha256").update(text).digest("hex");
5
+ export const credential = (env, purpose, ...parts) => createHmac("sha256", env.secret)
6
+ .update(JSON.stringify([purpose, ...parts]))
7
+ .digest("base64url");
8
+ /** What a card is found by from its link, which isn't stored. */
9
+ export const cardHash = (env, id, at) => digest(credential(env, "card", id, at));
10
+ export function whose(view, kind, key) {
11
+ if (!key)
12
+ return null;
13
+ const given = Buffer.from(digest(key), "hex");
14
+ const found = rows(view, "keys").find((row) => row.kind === kind && timingSafeEqual(Buffer.from(row.hash, "hex"), given));
15
+ return found?.name ?? null;
16
+ }