@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.
- package/CHANGELOG.md +27 -0
- package/INSTALL.md +120 -0
- package/LICENSE +21 -0
- package/README.en.md +268 -0
- package/README.md +264 -2
- package/SECURITY.md +49 -0
- package/dist/bin/agent-autoloop.js +2 -0
- package/dist/cli/agents.js +14 -0
- package/dist/cli/backup.js +144 -0
- package/dist/cli/dashboard/app.js +424 -0
- package/dist/cli/dashboard/index.html +15 -0
- package/dist/cli/dashboard/style.css +629 -0
- package/dist/cli/dashboard.js +94 -0
- package/dist/cli/explain.js +84 -0
- package/dist/cli/main.js +1142 -0
- package/dist/cli/mcp.js +151 -0
- package/dist/cli/runs.js +40 -0
- package/dist/cli/spend.js +21 -0
- package/dist/cli/status.js +272 -0
- package/dist/cli/try.js +6 -0
- package/dist/cli/ui.js +75 -0
- package/dist/cli/uninstall.js +86 -0
- package/dist/cli/update.js +65 -0
- package/dist/cli/why.js +115 -0
- package/dist/host/background-launcher.js +12 -0
- package/dist/host/background.js +24 -0
- package/dist/host/channels.js +4 -0
- package/dist/host/command.js +98 -0
- package/dist/host/config.js +37 -0
- package/dist/host/files.js +22 -0
- package/dist/host/home.js +5 -0
- package/dist/host/http.js +45 -0
- package/dist/host/launcher.js +188 -0
- package/dist/host/lines.js +15 -0
- package/dist/host/node-path.js +33 -0
- package/dist/host/npm.js +28 -0
- package/dist/host/plugins.js +26 -0
- package/dist/host/program.js +14 -0
- package/dist/host/runtime.js +179 -0
- package/dist/host/server.js +159 -0
- package/dist/host/service.js +325 -0
- package/dist/host/state.js +203 -0
- package/dist/host/up.js +162 -0
- package/dist/host/update.js +286 -0
- package/dist/host/version.js +81 -0
- package/dist/kernel/card-page.js +54 -0
- package/dist/kernel/credentials.js +16 -0
- package/dist/kernel/cron.js +135 -0
- package/dist/kernel/decide.js +826 -0
- package/dist/kernel/due.js +73 -0
- package/dist/kernel/errors.js +9 -0
- package/dist/kernel/evolve.js +264 -0
- package/dist/kernel/http.js +357 -0
- package/dist/kernel/query.js +202 -0
- package/dist/kernel/rules.js +20 -0
- package/dist/kernel/store.js +52 -0
- package/dist/plugins/acp/agent.js +32 -0
- package/dist/plugins/acp/bridge.js +204 -0
- package/dist/plugins/claude/agent.js +113 -0
- package/dist/plugins/codex/agent.js +105 -0
- package/dist/plugins/command/agent.js +25 -0
- package/dist/plugins/delivery/action.js +25 -0
- package/dist/plugins/delivery/agent.js +13 -0
- package/dist/plugins/delivery/delivery.js +388 -0
- package/dist/plugins/delivery/github.js +201 -0
- package/dist/plugins/delivery/handoff.js +50 -0
- package/dist/plugins/delivery/input.js +47 -0
- package/dist/plugins/delivery/poll.js +72 -0
- package/dist/plugins/delivery/project.js +144 -0
- package/dist/plugins/delivery/review-ledger.js +82 -0
- package/dist/plugins/delivery/review-policy.js +99 -0
- package/dist/plugins/delivery/review.js +280 -0
- package/dist/plugins/delivery/run.js +204 -0
- package/dist/plugins/desktop/channel.js +94 -0
- package/dist/plugins/dsh/agent.js +116 -0
- package/dist/plugins/feishu/channel.js +245 -0
- package/dist/plugins/github/source.js +30 -0
- package/dist/plugins/gitlab/source.js +30 -0
- package/dist/plugins/omp/agent.js +3 -0
- package/dist/plugins/opencode/agent.js +88 -0
- package/dist/plugins/pi/agent.js +92 -0
- package/dist/plugins/webhook/channel.js +70 -0
- package/dist/plugins/webhook/templates.js +34 -0
- package/dist/plugins/xiaojiu/channel.js +410 -0
- package/dist/plugins/zcode/agent.js +102 -0
- package/dist/protocol/client.js +56 -0
- package/dist/protocol/conformance.js +184 -0
- package/dist/protocol/job.js +1 -0
- package/dist/protocol/rules.js +230 -0
- package/dist/protocol/schema.js +70 -0
- package/dist/protocol/schema.json +985 -0
- package/dist/protocol/validate.js +150 -0
- package/dist/worker/agents.js +47 -0
- package/dist/worker/contract.js +178 -0
- package/dist/worker/run.js +52 -0
- package/dist/worker/usage.js +45 -0
- package/dist/worker/windows.ps1 +48 -0
- package/dist/worker/worker.js +595 -0
- package/docs/architecture.en.svg +178 -0
- package/docs/architecture.svg +178 -0
- package/docs/auto-update.md +53 -0
- package/docs/plugins.md +139 -0
- package/docs/protocol.md +582 -0
- package/docs/state-machines.md +77 -0
- package/examples/channel.sh +15 -0
- package/examples/plugins/hello-agent/agent.ts +40 -0
- package/examples/plugins/hello-channel/channel.ts +54 -0
- package/examples/plugins/hello-source/source.ts +19 -0
- package/examples/recipes/browser-handoff/README.md +44 -0
- package/examples/recipes/browser-handoff/SKILL.md +22 -0
- package/examples/recipes/browser-handoff/browser.json +10 -0
- package/examples/recipes/browser-handoff/handoff.ts +44 -0
- package/examples/recipes/browser-handoff/rules.json +19 -0
- package/examples/recipes/feedback/README.md +34 -0
- package/examples/recipes/feedback/SKILL.md +22 -0
- package/examples/recipes/feedback/event.json +8 -0
- package/examples/recipes/feedback/rules.json +37 -0
- package/examples/recipes/feishu-brief/README.md +28 -0
- package/examples/recipes/feishu-brief/SKILL.md +16 -0
- package/examples/recipes/feishu-brief/collect.ts +164 -0
- package/examples/recipes/feishu-brief/rules.json +57 -0
- package/examples/recipes/feishu-brief/sources.json +13 -0
- package/examples/recipes/github-issues/README.md +17 -0
- package/examples/recipes/github-issues/SKILL.md +18 -0
- package/examples/recipes/github-issues/rules.json +30 -0
- package/examples/recipes/inbox-triage/README.md +36 -0
- package/examples/recipes/inbox-triage/SKILL.md +19 -0
- package/examples/recipes/inbox-triage/collect.ts +191 -0
- package/examples/recipes/inbox-triage/rules.json +57 -0
- package/examples/recipes/inbox-triage/sources.json +8 -0
- package/examples/recipes/morning-brief/README.md +17 -0
- package/examples/recipes/morning-brief/SKILL.md +17 -0
- package/examples/recipes/morning-brief/rules.json +16 -0
- package/examples/recipes/ops-alerts/README.md +18 -0
- package/examples/recipes/ops-alerts/SKILL.md +34 -0
- package/examples/recipes/ops-alerts/restart.sh +5 -0
- package/examples/recipes/ops-alerts/rules.json +29 -0
- package/examples/recipes/website-watch/README.md +26 -0
- package/examples/recipes/website-watch/SKILL.md +19 -0
- package/examples/recipes/website-watch/check.ts +86 -0
- package/examples/recipes/website-watch/rules.json +56 -0
- package/examples/recipes/website-watch/site.json +6 -0
- package/examples/skills/weekly-sweep/SKILL.md +17 -0
- package/examples/watch-github-issues.sh +23 -0
- package/examples/worker.sh +18 -0
- package/package.json +57 -4
- package/plugins/acp/agent.ts +31 -0
- package/plugins/acp/bridge.ts +190 -0
- package/plugins/claude/agent.ts +121 -0
- package/plugins/codex/agent.ts +103 -0
- package/plugins/command/agent.ts +25 -0
- package/plugins/delivery/action.ts +29 -0
- package/plugins/delivery/action.yml +28 -0
- package/plugins/delivery/agent.ts +15 -0
- package/plugins/delivery/delivery.ts +408 -0
- package/plugins/delivery/github.ts +207 -0
- package/plugins/delivery/handoff.ts +72 -0
- package/plugins/delivery/input.ts +55 -0
- package/plugins/delivery/poll.ts +65 -0
- package/plugins/delivery/project.ts +161 -0
- package/plugins/delivery/review-ledger.ts +90 -0
- package/plugins/delivery/review-policy.ts +126 -0
- package/plugins/delivery/review.ts +324 -0
- package/plugins/delivery/run.ts +219 -0
- package/plugins/desktop/channel.ts +100 -0
- package/plugins/dsh/agent.ts +100 -0
- package/plugins/feishu/channel.ts +243 -0
- package/plugins/github/source.ts +33 -0
- package/plugins/gitlab/source.ts +32 -0
- package/plugins/omp/agent.ts +4 -0
- package/plugins/opencode/agent.ts +78 -0
- package/plugins/pi/agent.ts +80 -0
- package/plugins/webhook/channel.ts +74 -0
- package/plugins/webhook/templates.ts +32 -0
- package/plugins/xiaojiu/channel.ts +426 -0
- package/plugins/zcode/agent.ts +96 -0
- package/skills/agent-autoloop/SKILL.md +260 -0
|
@@ -0,0 +1,595 @@
|
|
|
1
|
+
// The worker: on a machine that nothing can reach, it keeps coming to the hub for work and starts an agent for each
|
|
2
|
+
// job. An agent runs detached, in its own process group, writing to files, so the worker can stop and come back and
|
|
3
|
+
// find it still going, or finished. A job is saved before anything slow happens; a result is saved before it's handed
|
|
4
|
+
// in and stays until the hub has taken it.
|
|
5
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, } from "node:fs";
|
|
8
|
+
import { homedir } from "node:os";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import { HubError } from "../protocol/client.js";
|
|
11
|
+
import { HOME } from "../host/home.js";
|
|
12
|
+
import { sibling } from "../host/program.js";
|
|
13
|
+
import { commandLine, processCommand } from "../host/command.js";
|
|
14
|
+
import { addUsage } from "../protocol/validate.js";
|
|
15
|
+
import { adapterFor } from "./agents.js";
|
|
16
|
+
import { promptFor, readMessage, repairPrompt, resultFrom } from "./contract.js";
|
|
17
|
+
import { loadUsage, saveUsage, usageDelta } from "./usage.js";
|
|
18
|
+
const RUNS = path.join(HOME, "worker", "runs");
|
|
19
|
+
const NOTHING = { input: 0, output: 0, cached: 0, cost: 0 };
|
|
20
|
+
const TIMEOUT_MINUTES = 180;
|
|
21
|
+
/** A reader of the turn's end that doesn't exit is given this long. */
|
|
22
|
+
const GRACE = 30_000;
|
|
23
|
+
/** A process told to stop is given this long. */
|
|
24
|
+
const STOP_GRACE = 10_000;
|
|
25
|
+
const REPAIRS = 2;
|
|
26
|
+
const KEEP_DAYS = 14;
|
|
27
|
+
/** A worker can run for months, so clearing can't wait for it to start again. */
|
|
28
|
+
const TIDY_EVERY = 60 * 60_000;
|
|
29
|
+
const WAIT = 50;
|
|
30
|
+
const PAUSE = 30_000;
|
|
31
|
+
const UNREACHABLE = 10 * 60_000;
|
|
32
|
+
const TELL_TRIES = 5;
|
|
33
|
+
/** Enough of a long output to find what's at either end of it, while it runs. */
|
|
34
|
+
const HEAD = 64 * 1024;
|
|
35
|
+
const TAIL = 1024 * 1024;
|
|
36
|
+
function save(entry) {
|
|
37
|
+
const file = path.join(entry.dir, "entry.json");
|
|
38
|
+
writeFileSync(`${file}.tmp`, JSON.stringify(entry), { mode: 0o600 });
|
|
39
|
+
renameSync(`${file}.tmp`, file);
|
|
40
|
+
}
|
|
41
|
+
/** How far a launch took its session's total. One that didn't go on in that session started it from nothing. */
|
|
42
|
+
function sessionRise(entry, { session, sessionUsage }) {
|
|
43
|
+
if (!session || !sessionUsage)
|
|
44
|
+
return;
|
|
45
|
+
saveUsage(entry.job.agent.use, session, sessionUsage);
|
|
46
|
+
return usageDelta(sessionUsage, session === entry.resume ? entry.usageBaseline : NOTHING);
|
|
47
|
+
}
|
|
48
|
+
/** What the agent's environment gets: never the hub's secrets, and nothing of a session the worker itself may be in. */
|
|
49
|
+
function agentEnvironment(entry) {
|
|
50
|
+
const env = {};
|
|
51
|
+
for (const [name, value] of Object.entries(process.env)) {
|
|
52
|
+
if (/^(AGENT_AUTOLOOP_|CLAUDECODE$|CLAUDE_CODE_|CODEX_(?!HOME$))/.test(name))
|
|
53
|
+
continue;
|
|
54
|
+
env[name] = value;
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
...env,
|
|
58
|
+
AGENT_AUTOLOOP_HOME: HOME,
|
|
59
|
+
AGENT_AUTOLOOP_RUN: String(entry.run),
|
|
60
|
+
AGENT_AUTOLOOP_CONTEXT: path.join(entry.dir, "context.json"),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
const files = (entry) => ({
|
|
64
|
+
out: path.join(entry.dir, `stdout-${entry.turn}.log`),
|
|
65
|
+
err: path.join(entry.dir, `stderr-${entry.turn}.log`),
|
|
66
|
+
exit: path.join(entry.dir, `exit-${entry.turn}`),
|
|
67
|
+
command: path.join(entry.dir, `command-${entry.turn}.${process.platform === "win32" ? "json" : "sh"}`),
|
|
68
|
+
});
|
|
69
|
+
const quoted = (word) => `'${word.replaceAll("'", `'\\''`)}'`;
|
|
70
|
+
const marker = (entry) => `agent-autoloop-run:${entry.run}:${entry.attempt}:${entry.turn}`;
|
|
71
|
+
/** Whether the run's process is still going: false when it is gone, null when we could not look. */
|
|
72
|
+
async function alive(entry) {
|
|
73
|
+
if (!entry.pid)
|
|
74
|
+
return false;
|
|
75
|
+
try {
|
|
76
|
+
const command = await processCommand(entry.pid);
|
|
77
|
+
return command.includes(marker(entry));
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
// A process that is gone makes ps exit with status 1; anything else (EPERM, EACCES, a spawn
|
|
81
|
+
// failure) means we could not look, which is not the same as it being gone.
|
|
82
|
+
const status = error.code;
|
|
83
|
+
if (process.platform !== "win32" && status === 1)
|
|
84
|
+
return false;
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function signal(entry, name) {
|
|
89
|
+
try {
|
|
90
|
+
if (entry.pid)
|
|
91
|
+
process.kill(process.platform === "win32" ? entry.pid : -entry.pid, name);
|
|
92
|
+
}
|
|
93
|
+
catch { }
|
|
94
|
+
}
|
|
95
|
+
/** Whether anything in the run's group is still going, null when we could not look. */
|
|
96
|
+
async function groupAlive(entry) {
|
|
97
|
+
// The wrapper can die before a child; zombies have already stopped and only their parent can reap them.
|
|
98
|
+
if (!entry.pid)
|
|
99
|
+
return false;
|
|
100
|
+
if (process.platform === "win32")
|
|
101
|
+
return alive(entry);
|
|
102
|
+
try {
|
|
103
|
+
return execFileSync("ps", ["-ax", "-o", "pgid=", "-o", "stat="], { encoding: "utf8" })
|
|
104
|
+
.trim()
|
|
105
|
+
.split("\n")
|
|
106
|
+
.some((line) => {
|
|
107
|
+
const [group, state] = line.trim().split(/\s+/);
|
|
108
|
+
return Number(group) === entry.pid && !state.startsWith("Z");
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
// ps itself may be missing or blocked in a sandbox. This group was started here, so it can be asked about
|
|
113
|
+
// directly: no such group is gone, anything else means it couldn't be looked at.
|
|
114
|
+
try {
|
|
115
|
+
process.kill(-entry.pid, 0);
|
|
116
|
+
return true;
|
|
117
|
+
}
|
|
118
|
+
catch (failure) {
|
|
119
|
+
return failure.code === "ESRCH" ? false : null;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function snapshot(file) {
|
|
124
|
+
if (!existsSync(file))
|
|
125
|
+
return "";
|
|
126
|
+
const size = statSync(file).size;
|
|
127
|
+
if (size <= HEAD + TAIL)
|
|
128
|
+
return readFileSync(file, "utf8");
|
|
129
|
+
const fd = openSync(file, "r");
|
|
130
|
+
try {
|
|
131
|
+
const head = Buffer.alloc(HEAD);
|
|
132
|
+
const end = Buffer.alloc(TAIL);
|
|
133
|
+
readSync(fd, head, 0, HEAD, 0);
|
|
134
|
+
readSync(fd, end, 0, TAIL, size - TAIL);
|
|
135
|
+
return `${head.toString("utf8")}\n${end.toString("utf8")}`;
|
|
136
|
+
}
|
|
137
|
+
finally {
|
|
138
|
+
closeSync(fd);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
export function createWorker({ hub, name, capacity = 2, log = () => { }, unreachable, wait = WAIT, now = Date.now, }) {
|
|
142
|
+
let claim = randomUUID();
|
|
143
|
+
let unreachableSince = null;
|
|
144
|
+
let told = false;
|
|
145
|
+
let tries = 0;
|
|
146
|
+
let blind = false;
|
|
147
|
+
let tidied = -Infinity;
|
|
148
|
+
const said = new Set();
|
|
149
|
+
/** Trouble that lasts comes round every second, and once in the log will do. */
|
|
150
|
+
const sayOnce = (line) => {
|
|
151
|
+
if (!said.has(line))
|
|
152
|
+
log(line);
|
|
153
|
+
said.add(line);
|
|
154
|
+
};
|
|
155
|
+
mkdirSync(RUNS, { recursive: true, mode: 0o700 });
|
|
156
|
+
const entries = () => readdirSync(RUNS).flatMap((id) => {
|
|
157
|
+
try {
|
|
158
|
+
return [JSON.parse(readFileSync(path.join(RUNS, id, "entry.json"), "utf8"))];
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
return [];
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
/** Starts a turn of the agent: a process that outlives this one, leaving its output and exit code in files. */
|
|
165
|
+
function launch(entry, adapter, prompt) {
|
|
166
|
+
entry.turn += 1;
|
|
167
|
+
entry.launchedAt = now();
|
|
168
|
+
entry.usageBaseline = entry.resume ? loadUsage(entry.job.agent.use, entry.resume) : undefined;
|
|
169
|
+
delete entry.finishedAt;
|
|
170
|
+
delete entry.pid;
|
|
171
|
+
delete entry.stopping;
|
|
172
|
+
delete entry.why;
|
|
173
|
+
save(entry);
|
|
174
|
+
const { rule, agent } = entry.job;
|
|
175
|
+
const cwd = rule.cwd.replace(/^~(?=[/\\])/, homedir());
|
|
176
|
+
const turn = {
|
|
177
|
+
prompt,
|
|
178
|
+
session: entry.session,
|
|
179
|
+
resume: entry.resume,
|
|
180
|
+
cwd,
|
|
181
|
+
model: agent.model,
|
|
182
|
+
effort: agent.effort,
|
|
183
|
+
tier: agent.tier,
|
|
184
|
+
access: agent.access,
|
|
185
|
+
command: agent.command,
|
|
186
|
+
program: agent.program,
|
|
187
|
+
contextFile: path.join(entry.dir, "context.json"),
|
|
188
|
+
folder: entry.dir,
|
|
189
|
+
};
|
|
190
|
+
if (!existsSync(cwd))
|
|
191
|
+
throw new Error(`在 ${cwd} 启动不了:这个目录不存在`);
|
|
192
|
+
const argv = adapter.command(turn);
|
|
193
|
+
const { out, err, exit, command } = files(entry);
|
|
194
|
+
if (process.platform === "win32") {
|
|
195
|
+
writeFileSync(command, JSON.stringify({ argv, cwd, exit }), { mode: 0o600 });
|
|
196
|
+
const output = openSync(out, "w");
|
|
197
|
+
const errors = openSync(err, "w");
|
|
198
|
+
try {
|
|
199
|
+
const child = spawn(process.execPath, [
|
|
200
|
+
"--disable-warning=ExperimentalWarning",
|
|
201
|
+
sibling(import.meta.dirname, "run.ts"),
|
|
202
|
+
"--supervise",
|
|
203
|
+
command,
|
|
204
|
+
marker(entry),
|
|
205
|
+
], {
|
|
206
|
+
cwd,
|
|
207
|
+
env: { ...agentEnvironment(entry), AGENT_AUTOLOOP_NODE: process.execPath },
|
|
208
|
+
detached: true,
|
|
209
|
+
windowsHide: true,
|
|
210
|
+
stdio: ["ignore", output, errors],
|
|
211
|
+
});
|
|
212
|
+
child.on("error", (error) => log(`run ${entry.run}: ${error}`));
|
|
213
|
+
child.unref();
|
|
214
|
+
entry.pid = child.pid;
|
|
215
|
+
}
|
|
216
|
+
finally {
|
|
217
|
+
closeSync(output);
|
|
218
|
+
closeSync(errors);
|
|
219
|
+
}
|
|
220
|
+
save(entry);
|
|
221
|
+
log(`run ${entry.run} (${rule.name}) turn ${entry.turn} started, pid ${entry.pid}`);
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
// Login shells don't agree on how a command reads its arguments (fish has no $0 or $@), so the command waits in a
|
|
225
|
+
// file for /bin/sh. Its path travels by environment because the install path can hold any character.
|
|
226
|
+
writeFileSync(command, `unset AGENT_AUTOLOOP_COMMAND\nexec ${argv.map(quoted).join(" ")}\n`, { mode: 0o600 });
|
|
227
|
+
// Output and the exit code go through the shell, so they land in their files even if this program has gone by then.
|
|
228
|
+
const script = [
|
|
229
|
+
"out=$1",
|
|
230
|
+
"err=$2",
|
|
231
|
+
"result=$3",
|
|
232
|
+
"shift 3",
|
|
233
|
+
"umask 077",
|
|
234
|
+
'"$@" >"$out" 2>"$err"',
|
|
235
|
+
'echo $? >"$result.tmp"',
|
|
236
|
+
'mv "$result.tmp" "$result"',
|
|
237
|
+
// A final external command can replace the shell before publishing its exit file.
|
|
238
|
+
":",
|
|
239
|
+
].join("\n");
|
|
240
|
+
// The login shell gives it the PATH and sign-in its owner has in a terminal; launchd and systemd give neither.
|
|
241
|
+
const login = [process.env.SHELL ?? "/bin/sh", "-lc", 'exec /bin/sh "$AGENT_AUTOLOOP_COMMAND"'];
|
|
242
|
+
const child = spawn("/bin/sh", ["-c", script, marker(entry), out, err, exit, ...login], {
|
|
243
|
+
cwd,
|
|
244
|
+
env: { ...agentEnvironment(entry), AGENT_AUTOLOOP_COMMAND: command },
|
|
245
|
+
detached: true,
|
|
246
|
+
stdio: "ignore",
|
|
247
|
+
});
|
|
248
|
+
child.on("error", (error) => log(`run ${entry.run}: ${error}`));
|
|
249
|
+
child.unref();
|
|
250
|
+
entry.pid = child.pid;
|
|
251
|
+
save(entry);
|
|
252
|
+
log(`run ${entry.run} (${rule.name}) turn ${entry.turn} started, pid ${child.pid}`);
|
|
253
|
+
}
|
|
254
|
+
function endWith(entry, result) {
|
|
255
|
+
entry.result = result;
|
|
256
|
+
save(entry);
|
|
257
|
+
}
|
|
258
|
+
async function start(job) {
|
|
259
|
+
const dir = path.join(RUNS, `${job.run}-${job.attempt}`);
|
|
260
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
261
|
+
const entry = {
|
|
262
|
+
run: job.run,
|
|
263
|
+
token: job.token,
|
|
264
|
+
attempt: job.attempt,
|
|
265
|
+
job,
|
|
266
|
+
dir,
|
|
267
|
+
prompt: "",
|
|
268
|
+
turn: 0,
|
|
269
|
+
session: job.session ?? randomUUID(),
|
|
270
|
+
resume: job.session,
|
|
271
|
+
repairs: 0,
|
|
272
|
+
triedFresh: false,
|
|
273
|
+
};
|
|
274
|
+
// Kept before anything slow: a worker stopped from here on still has the job.
|
|
275
|
+
save(entry);
|
|
276
|
+
try {
|
|
277
|
+
writeFileSync(path.join(dir, "context.json"), JSON.stringify(job.context, null, 2), { mode: 0o600 });
|
|
278
|
+
const adapter = await adapterFor(job.agent.use);
|
|
279
|
+
entry.prompt = promptFor(job, path.join(dir, "context.json"));
|
|
280
|
+
save(entry);
|
|
281
|
+
launch(entry, adapter, entry.prompt);
|
|
282
|
+
}
|
|
283
|
+
catch (error) {
|
|
284
|
+
endWith(entry, { outcome: "failed", error: String(error.message ?? error).slice(0, 500) });
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
function read(entry, adapter, code) {
|
|
288
|
+
const { out, err } = files(entry);
|
|
289
|
+
try {
|
|
290
|
+
const reading = adapter.read(snapshot(out), code, code === null ? "" : snapshot(err));
|
|
291
|
+
if (!reading)
|
|
292
|
+
throw new Error("它什么也没给");
|
|
293
|
+
return reading;
|
|
294
|
+
}
|
|
295
|
+
catch (error) {
|
|
296
|
+
sayOnce(`run ${entry.run}: couldn't read its output: ${error}`);
|
|
297
|
+
// One still going goes on, since this says nothing about how it's doing. Whether one that has ended got started isn't
|
|
298
|
+
// known, and starting it again in a new session could do its work twice: it stays in this one.
|
|
299
|
+
return { started: true, error: `读不懂这个 Agent 的输出:${error.message ?? error}` };
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
function discardReceipt(entry, adapter, problem) {
|
|
303
|
+
const original = { ...entry, turn: entry.turn - entry.repairs };
|
|
304
|
+
const reading = read(original, adapter, 0);
|
|
305
|
+
const { result } = resultFrom(readMessage(reading.text ?? ""), {
|
|
306
|
+
session: reading.session ?? (adapter.link ? entry.session : undefined),
|
|
307
|
+
usage: entry.usage,
|
|
308
|
+
});
|
|
309
|
+
const notice = {
|
|
310
|
+
title: `「${entry.job.rule.name}」的回执读不懂`,
|
|
311
|
+
text: `这一轮按第一行算结束了,但它要中台做的事没有生效(${problem})。原文在 ${files(original).out},留 ${KEEP_DAYS} 天。`,
|
|
312
|
+
};
|
|
313
|
+
endWith(entry, { ...result, notice: [...(result.notice ?? []), notice] });
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* The session a run is in when its CLI hasn't said. The one made up after the old one couldn't be gone on in counts once
|
|
317
|
+
* that run has started: a CLI that never got going, or one that names its own sessions, has no such session, and handing
|
|
318
|
+
* it in would take the old one's place, so the retry would start over in a new one.
|
|
319
|
+
*/
|
|
320
|
+
function madeUp(entry, adapter, seen) {
|
|
321
|
+
return adapter.link && (!entry.triedFresh || seen.started) ? entry.session : undefined;
|
|
322
|
+
}
|
|
323
|
+
/** A turn has ended. What it said is a result, or a reason to ask it again without redoing anything. */
|
|
324
|
+
function conclude(entry, adapter, code) {
|
|
325
|
+
// One ended because its turn was over but it wouldn't exit said what it had to say first.
|
|
326
|
+
const seen = read(entry, adapter, entry.finishedAt ? 0 : code);
|
|
327
|
+
entry.usage = addUsage(addUsage(entry.usage, seen.usage), sessionRise(entry, seen));
|
|
328
|
+
const session = seen.session ?? (entry.turn > 0 ? madeUp(entry, adapter, seen) : undefined);
|
|
329
|
+
if (seen.session)
|
|
330
|
+
entry.session = seen.session;
|
|
331
|
+
const usage = entry.usage && { usage: entry.usage };
|
|
332
|
+
const known = session && { session };
|
|
333
|
+
if (entry.why === "cancel")
|
|
334
|
+
return endWith(entry, { outcome: "cancelled", summary: "已停止", ...known, ...usage });
|
|
335
|
+
if (entry.why === "timeout") {
|
|
336
|
+
const minutes = entry.job.agent.timeout ?? TIMEOUT_MINUTES;
|
|
337
|
+
const error = `超过 ${minutes} 分钟还没结束,已停止`;
|
|
338
|
+
if (entry.repairs)
|
|
339
|
+
return discardReceipt(entry, adapter, error);
|
|
340
|
+
return endWith(entry, { outcome: "failed", error, ...known, ...usage });
|
|
341
|
+
}
|
|
342
|
+
if (seen.error !== undefined || !seen.text?.trim()) {
|
|
343
|
+
const error = seen.error || "没留下结果";
|
|
344
|
+
if (entry.repairs)
|
|
345
|
+
return discardReceipt(entry, adapter, error);
|
|
346
|
+
// The conversation may not be there to go on in, or something else has it open: this go carries on in a new one.
|
|
347
|
+
// Not once the turn has started: a new one would do its work again. The hub tries again later, in this one.
|
|
348
|
+
if (entry.resume && !entry.triedFresh && entry.repairs === 0 && !seen.started) {
|
|
349
|
+
log(`run ${entry.run}: couldn't go on in ${entry.resume} (${error}); starting a new session`);
|
|
350
|
+
entry.triedFresh = true;
|
|
351
|
+
entry.resume = null;
|
|
352
|
+
entry.session = randomUUID();
|
|
353
|
+
try {
|
|
354
|
+
launch(entry, adapter, entry.prompt);
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
catch (failure) {
|
|
358
|
+
return endWith(entry, { outcome: "failed", error: String(failure).slice(0, 500) });
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
return endWith(entry, { outcome: "failed", error: error.slice(0, 500), ...known, ...usage });
|
|
362
|
+
}
|
|
363
|
+
const { result, problem } = resultFrom(readMessage(seen.text), { session, usage: entry.usage });
|
|
364
|
+
if (entry.repairs && !problem && result.outcome === "failed")
|
|
365
|
+
return discardReceipt(entry, adapter, result.error);
|
|
366
|
+
if (!problem)
|
|
367
|
+
return endWith(entry, result);
|
|
368
|
+
// Its work is done and only the receipt is wrong: it writes the receipt again, and does nothing again.
|
|
369
|
+
if (entry.repairs < REPAIRS && seen.session) {
|
|
370
|
+
log(`run ${entry.run}: receipt not readable (${problem}); asking again`);
|
|
371
|
+
entry.repairs += 1;
|
|
372
|
+
entry.resume = seen.session;
|
|
373
|
+
try {
|
|
374
|
+
launch(entry, adapter, repairPrompt(problem));
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
catch (error) {
|
|
378
|
+
return discardReceipt(entry, adapter, String(error));
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
discardReceipt(entry, adapter, problem);
|
|
382
|
+
}
|
|
383
|
+
/** Looks at a run in hand: still going, to be stopped, or ended. */
|
|
384
|
+
async function check(entry) {
|
|
385
|
+
if (entry.result)
|
|
386
|
+
return;
|
|
387
|
+
let adapter;
|
|
388
|
+
try {
|
|
389
|
+
adapter = await adapterFor(entry.job.agent.use);
|
|
390
|
+
}
|
|
391
|
+
catch (error) {
|
|
392
|
+
return endWith(entry, { outcome: "failed", error: String(error.message).slice(0, 500) });
|
|
393
|
+
}
|
|
394
|
+
if (entry.turn === 0) {
|
|
395
|
+
// The worker stopped while starting it, before anything was launched.
|
|
396
|
+
if (!entry.prompt)
|
|
397
|
+
entry.prompt = promptFor(entry.job, path.join(entry.dir, "context.json"));
|
|
398
|
+
try {
|
|
399
|
+
writeFileSync(path.join(entry.dir, "context.json"), JSON.stringify(entry.job.context, null, 2), {
|
|
400
|
+
mode: 0o600,
|
|
401
|
+
});
|
|
402
|
+
return launch(entry, adapter, entry.prompt);
|
|
403
|
+
}
|
|
404
|
+
catch (error) {
|
|
405
|
+
return endWith(entry, { outcome: "failed", error: String(error.message ?? error).slice(0, 500) });
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
const { exit } = files(entry);
|
|
409
|
+
const exitCode = () => (existsSync(exit) ? Number(readFileSync(exit, "utf8").trim()) : null);
|
|
410
|
+
if (entry.stopping !== undefined) {
|
|
411
|
+
const going = await groupAlive(entry);
|
|
412
|
+
const overdue = now() - entry.stopping > STOP_GRACE;
|
|
413
|
+
if (going === true) {
|
|
414
|
+
if (overdue)
|
|
415
|
+
signal(entry, "SIGKILL");
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
if (going === null) {
|
|
419
|
+
// The forced kill is the last thing that can be done to it, and whether it worked can't be seen.
|
|
420
|
+
if (!overdue)
|
|
421
|
+
return;
|
|
422
|
+
signal(entry, "SIGKILL");
|
|
423
|
+
// A turn that was over, or a timeout, ends on what it said: `failed` there is tried again, redoing work done.
|
|
424
|
+
if (entry.why !== "cancel")
|
|
425
|
+
return conclude(entry, adapter, exitCode());
|
|
426
|
+
// Reporting `cancelled` would release the item while a process may still be in it, which the protocol forbids
|
|
427
|
+
// (docs/protocol.md: 确认组内没有活进程后才交 cancelled). A cancelled run's `failed` isn't tried again.
|
|
428
|
+
return endWith(entry, {
|
|
429
|
+
outcome: "failed",
|
|
430
|
+
error: "停止信号发出后没能确认进程组已结束:这一轮按没跑成记,不再重试,进程可能还在。",
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
return conclude(entry, adapter, exitCode());
|
|
434
|
+
}
|
|
435
|
+
if (existsSync(exit))
|
|
436
|
+
return conclude(entry, adapter, exitCode());
|
|
437
|
+
// The shell can publish its exit between the first file check and ps returning.
|
|
438
|
+
const looking = await alive(entry);
|
|
439
|
+
if (looking === false)
|
|
440
|
+
return conclude(entry, adapter, exitCode());
|
|
441
|
+
// Unable to look, the run counts as still going, so its timeout and its finished turn still end it.
|
|
442
|
+
if (looking === null && !blind)
|
|
443
|
+
log(`couldn't inspect processes; runs count as going until they end or time out`);
|
|
444
|
+
blind = looking === null;
|
|
445
|
+
const seen = read(entry, adapter, null);
|
|
446
|
+
// Kept as soon as it's read: if the end can't be read, the one made up at launch may be nothing its CLI knows of.
|
|
447
|
+
if (seen.session && seen.session !== entry.session) {
|
|
448
|
+
entry.session = seen.session;
|
|
449
|
+
save(entry);
|
|
450
|
+
}
|
|
451
|
+
const session = seen.session ?? madeUp(entry, adapter, seen);
|
|
452
|
+
if (session && session !== entry.told) {
|
|
453
|
+
try {
|
|
454
|
+
await hub.started(entry.run, entry.token, { session, ...(adapter.link && { link: adapter.link(session) }) });
|
|
455
|
+
entry.told = session;
|
|
456
|
+
save(entry);
|
|
457
|
+
}
|
|
458
|
+
catch (error) {
|
|
459
|
+
log(`run ${entry.run}: couldn't say it started: ${error}`);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
const moment = now();
|
|
463
|
+
const limit = (entry.job.agent.timeout ?? TIMEOUT_MINUTES) * 60_000;
|
|
464
|
+
if (moment - (entry.launchedAt ?? moment) > limit)
|
|
465
|
+
return stop(entry, "timeout");
|
|
466
|
+
if (seen.finished) {
|
|
467
|
+
// Its turn is over but it hasn't gone: whatever it's stuck on, the answer is already there.
|
|
468
|
+
if (!entry.finishedAt) {
|
|
469
|
+
entry.finishedAt = moment;
|
|
470
|
+
save(entry);
|
|
471
|
+
}
|
|
472
|
+
else if (moment - entry.finishedAt > GRACE) {
|
|
473
|
+
stop(entry, "finished");
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
function stop(entry, why) {
|
|
478
|
+
if (entry.stopping !== undefined || entry.result)
|
|
479
|
+
return;
|
|
480
|
+
entry.stopping = now();
|
|
481
|
+
entry.why = why;
|
|
482
|
+
save(entry);
|
|
483
|
+
signal(entry, "SIGTERM");
|
|
484
|
+
log(`run ${entry.run}: stopping (${why})`);
|
|
485
|
+
}
|
|
486
|
+
/** Hands in what has ended. One the hub can't take now waits for next time; one it refuses is dropped and said so. */
|
|
487
|
+
async function settle(entry) {
|
|
488
|
+
if (!entry.result)
|
|
489
|
+
return;
|
|
490
|
+
try {
|
|
491
|
+
const answer = await hub.result(entry.run, entry.token, entry.result);
|
|
492
|
+
for (const item of answer?.rejected ?? [])
|
|
493
|
+
log(`run ${entry.run}: not applied: ${JSON.stringify(item)}`);
|
|
494
|
+
log(`run ${entry.run}: ${entry.result.outcome}`);
|
|
495
|
+
}
|
|
496
|
+
catch (error) {
|
|
497
|
+
if (!(error instanceof HubError) || error.status >= 500) {
|
|
498
|
+
return log(`run ${entry.run}: couldn't hand in the result: ${error}`);
|
|
499
|
+
}
|
|
500
|
+
log(`run ${entry.run}: the hub refused its result (${error.status}: ${error.message}); dropped`);
|
|
501
|
+
}
|
|
502
|
+
unlinkSync(path.join(entry.dir, "entry.json"));
|
|
503
|
+
}
|
|
504
|
+
/** Nothing else can tell the owner when the hub is what's gone. */
|
|
505
|
+
function watchHub(reachable, moment) {
|
|
506
|
+
if (reachable) {
|
|
507
|
+
unreachableSince = null;
|
|
508
|
+
told = false;
|
|
509
|
+
tries = 0;
|
|
510
|
+
return;
|
|
511
|
+
}
|
|
512
|
+
unreachableSince ??= moment;
|
|
513
|
+
if (!unreachable?.length || told || tries >= TELL_TRIES || moment - unreachableSince < UNREACHABLE)
|
|
514
|
+
return;
|
|
515
|
+
tries += 1;
|
|
516
|
+
const minutes = Math.floor((moment - unreachableSince) / 60_000);
|
|
517
|
+
const text = `${name} 连不上中台已经 ${minutes} 分钟了,派给它的活暂时没人接;它还在一直重试。`;
|
|
518
|
+
const [program, args] = commandLine(unreachable.map((part) => part.replaceAll("{text}", text)));
|
|
519
|
+
try {
|
|
520
|
+
execFileSync(program, args, { timeout: 60_000, stdio: "ignore" });
|
|
521
|
+
told = true;
|
|
522
|
+
}
|
|
523
|
+
catch (error) {
|
|
524
|
+
log(`couldn't tell anyone the hub is gone: ${error}`);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
/** Trouble with one run, a folder it can't write to say, is for the next round and holds up no other. */
|
|
528
|
+
async function eachEntry(step) {
|
|
529
|
+
for (const entry of entries()) {
|
|
530
|
+
try {
|
|
531
|
+
await step(entry);
|
|
532
|
+
}
|
|
533
|
+
catch (error) {
|
|
534
|
+
sayOnce(`run ${entry.run}: ${error}`);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
/** One round: look at what's in hand, hand in what's ended, come for more. Whether the hub could be reached. */
|
|
539
|
+
async function tick() {
|
|
540
|
+
// Here and not in run: whatever drives the worker comes through here.
|
|
541
|
+
if (now() - tidied >= TIDY_EVERY) {
|
|
542
|
+
tidied = now();
|
|
543
|
+
tidy(tidied);
|
|
544
|
+
}
|
|
545
|
+
await eachEntry(check);
|
|
546
|
+
await eachEntry(settle);
|
|
547
|
+
const held = entries();
|
|
548
|
+
let reachable = true;
|
|
549
|
+
try {
|
|
550
|
+
const answer = await hub.work({
|
|
551
|
+
claim,
|
|
552
|
+
wait: held.length ? 1 : wait,
|
|
553
|
+
running: held.map((entry) => entry.run),
|
|
554
|
+
capacity: held.length < capacity,
|
|
555
|
+
});
|
|
556
|
+
for (const id of answer?.cancel ?? []) {
|
|
557
|
+
const entry = held.find((entry) => entry.run === id);
|
|
558
|
+
if (entry)
|
|
559
|
+
stop(entry, "cancel");
|
|
560
|
+
}
|
|
561
|
+
if (answer?.job) {
|
|
562
|
+
claim = randomUUID();
|
|
563
|
+
await start(answer.job);
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
catch (error) {
|
|
567
|
+
log(`couldn't reach the hub: ${error}`);
|
|
568
|
+
reachable = false;
|
|
569
|
+
}
|
|
570
|
+
watchHub(reachable, now());
|
|
571
|
+
return reachable;
|
|
572
|
+
}
|
|
573
|
+
/** Output of finished runs is kept a while for looking into, then goes. */
|
|
574
|
+
function tidy(moment = now()) {
|
|
575
|
+
for (const id of readdirSync(RUNS)) {
|
|
576
|
+
const dir = path.join(RUNS, id);
|
|
577
|
+
try {
|
|
578
|
+
const expired = moment - statSync(dir).mtimeMs > KEEP_DAYS * 24 * 3600_000;
|
|
579
|
+
if (!existsSync(path.join(dir, "entry.json")) && expired)
|
|
580
|
+
rmSync(dir, { recursive: true, force: true });
|
|
581
|
+
}
|
|
582
|
+
catch (error) {
|
|
583
|
+
sayOnce(`couldn't clear ${dir}: ${error}`);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
async function run(signalled) {
|
|
588
|
+
log(`worker ${name} started`);
|
|
589
|
+
while (!signalled.aborted) {
|
|
590
|
+
if (!(await tick()))
|
|
591
|
+
await new Promise((resolve) => setTimeout(resolve, PAUSE));
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
return { tick, run, entries, tidy };
|
|
595
|
+
}
|