@notation/factory 0.5.4 → 0.6.0
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/contracts/index.ts +1 -1
- package/contracts/outpost.ts +5 -2
- package/contracts/runner.ts +16 -0
- package/deployer/sdk.gen.ts +1 -1
- package/implementations/container.ts +10 -3
- package/package.json +1 -1
- package/router/channel.ts +18 -8
- package/router/deliveries.ts +110 -9
- package/router/handle.test.ts +305 -7
- package/router/handle.ts +247 -17
- package/router/index.ts +27 -2
- package/router/run.ts +73 -7
- package/runner/index.ts +352 -52
- package/runner/runner.test.ts +304 -7
package/runner/runner.test.ts
CHANGED
|
@@ -6,7 +6,7 @@ import { tmpdir } from "node:os";
|
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import { after, before, test } from "node:test";
|
|
8
8
|
import type { ThreadMessage } from "../router/channel.ts";
|
|
9
|
-
import type { MessagesRequest, Relay, Run, TokenRequest } from "../router/run.ts";
|
|
9
|
+
import type { Heartbeat, MessagesRequest, Relay, Run, TokenRequest } from "../router/run.ts";
|
|
10
10
|
|
|
11
11
|
const root = realpathSync(mkdtempSync(join(tmpdir(), "factory-runner-")));
|
|
12
12
|
const bin = join(root, "bin");
|
|
@@ -20,8 +20,10 @@ const sh = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd,
|
|
|
20
20
|
// A fake Claude Code: it records how it was called, the prompt on its stdin
|
|
21
21
|
// and the token that gh gets, and writes a transcript for a session named after its
|
|
22
22
|
// working directory, and writes stream-json. It fails, edits the worktree,
|
|
23
|
-
//
|
|
24
|
-
//
|
|
23
|
+
// exits with no result after it reports its session, runs until it's stopped the first time,
|
|
24
|
+
// waits for the runner to refresh its tokens, hangs, writes messages
|
|
25
|
+
// before its result, has the fake earlyoom stop it, or stalls after it edits the worktree and reports its
|
|
26
|
+
// session the first time, when the prompt says so.
|
|
25
27
|
const FAKE_CLAUDE = `#!/bin/sh
|
|
26
28
|
prompt="$(cat)"
|
|
27
29
|
case "$prompt" in
|
|
@@ -35,6 +37,13 @@ projects="\${CLAUDE_CONFIG_DIR:-$HOME/.claude}/projects"
|
|
|
35
37
|
mkdir -p "$projects/-p-$(basename "$(pwd)")"
|
|
36
38
|
echo "$prompt" >> "$projects/-p-$(basename "$(pwd)")/$session.jsonl"
|
|
37
39
|
case "$prompt" in
|
|
40
|
+
*"run forever"*)
|
|
41
|
+
if [ ! -e forever.txt ]; then
|
|
42
|
+
echo forever > forever.txt
|
|
43
|
+
echo "{\\"type\\":\\"system\\",\\"subtype\\":\\"init\\",\\"session_id\\":\\"$session\\"}"
|
|
44
|
+
exec sleep 30
|
|
45
|
+
fi ;;
|
|
46
|
+
*"crash now"*) echo "{\\"type\\":\\"system\\",\\"subtype\\":\\"init\\",\\"session_id\\":\\"$session\\"}"; echo "killed" >&2; exit 137 ;;
|
|
38
47
|
*"fail now"*) echo "{\\"type\\":\\"result\\",\\"is_error\\":true,\\"result\\":\\"it broke\\",\\"session_id\\":\\"$session\\"}"; exit 1 ;;
|
|
39
48
|
*"edit the code"*)
|
|
40
49
|
echo committed > committed.txt
|
|
@@ -51,9 +60,34 @@ case "$prompt" in
|
|
|
51
60
|
echo '{"type":"assistant","parent_tool_use_id":null,"message":{"content":[{"type":"thinking","thinking":"still hidden"}]}}'
|
|
52
61
|
sleep 0.3
|
|
53
62
|
echo '{"type":"assistant","parent_tool_use_id":"t1","message":{"content":[{"type":"text","text":"A subagent."}]}}'
|
|
54
|
-
|
|
63
|
+
printf '%s\\n' '{"type":"assistant","parent_tool_use_id":null,"message":{"content":[{"type":"tool_use","name":"Bash","input":{"command":"npm test\\n -- --watch=false","timeout":60000}}]}}'
|
|
64
|
+
echo '{"type":"assistant","parent_tool_use_id":"t1","message":{"content":[{"type":"tool_use","name":"Read","input":{"file_path":"/src/a.ts"}}]}}'
|
|
55
65
|
echo '{"type":"assistant","parent_tool_use_id":null,"message":{"content":[{"type":"text","text":"Found it."}]}}'
|
|
56
66
|
sleep 0.3 ;;
|
|
67
|
+
*"use memory"*)
|
|
68
|
+
echo "sending SIGTERM to process $$ uid 1000 \\"tsc\\": badness 900, VmRSS 3174 MiB" > "${calls}.oom.new"
|
|
69
|
+
echo "sending SIGKILL to process $$ uid 1000 \\"tsc\\": badness 900, VmRSS 3174 MiB" >> "${calls}.oom.new"
|
|
70
|
+
mv "${calls}.oom.new" "${calls}.oom"
|
|
71
|
+
sleep 1 ;;
|
|
72
|
+
*"leave a child"*)
|
|
73
|
+
if [ ! -e child.pid ]; then
|
|
74
|
+
sleep 30 >/dev/null 2>&1 &
|
|
75
|
+
echo $! > child.pid
|
|
76
|
+
echo "{\\"type\\":\\"system\\",\\"subtype\\":\\"init\\",\\"session_id\\":\\"$session\\"}"
|
|
77
|
+
wait
|
|
78
|
+
fi ;;
|
|
79
|
+
*"talk forever"*)
|
|
80
|
+
if [ ! -e forever.txt ]; then
|
|
81
|
+
echo forever > forever.txt
|
|
82
|
+
echo '{"type":"assistant","parent_tool_use_id":null,"message":{"content":[{"type":"text","text":"Looking."}]}}'
|
|
83
|
+
exec sleep 30
|
|
84
|
+
fi ;;
|
|
85
|
+
*stall*)
|
|
86
|
+
if [ ! -e draft.txt ]; then
|
|
87
|
+
echo draft > draft.txt
|
|
88
|
+
echo "{\\"type\\":\\"system\\",\\"subtype\\":\\"init\\",\\"session_id\\":\\"$session\\"}"
|
|
89
|
+
sleep 5
|
|
90
|
+
fi ;;
|
|
57
91
|
esac
|
|
58
92
|
echo "{\\"type\\":\\"result\\",\\"result\\":\\"done\\",\\"session_id\\":\\"$session\\"}"
|
|
59
93
|
`;
|
|
@@ -79,6 +113,9 @@ case "$prompt" in
|
|
|
79
113
|
echo '{"type":"system","subtype":"init","session_id":"'"$session"'","model":"Composer 2.5"}'
|
|
80
114
|
echo '{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"Looking."}]},"model_call_id":"m1","timestamp_ms":1}'
|
|
81
115
|
sleep 0.3
|
|
116
|
+
echo '{"type":"tool_call","subtype":"started","tool_call":{"shellToolCall":{"args":{"command":"ls -la"}}}}'
|
|
117
|
+
echo '{"type":"tool_call","subtype":"completed","tool_call":{"shellToolCall":{"args":{"command":"ls -la"},"result":{}}}}'
|
|
118
|
+
echo '{"type":"tool_call","subtype":"started","tool_call":{"function":{"name":"search","arguments":"{\\"q\\":1}"}}}'
|
|
82
119
|
echo '{"type":"tool_call","subtype":"completed","tool_call":{"taskToolCall":{"result":{"success":{"conversationSteps":[{"assistantMessage":{"text":"A subagent."}}]}}}}}'
|
|
83
120
|
echo '{"type":"thinking","subtype":"delta","text":"hidden"}'
|
|
84
121
|
sleep 0.15
|
|
@@ -115,6 +152,7 @@ case "$prompt" in
|
|
|
115
152
|
echo '{"type":"reasoning","text":"The bug is in the parser."}'
|
|
116
153
|
sleep 0.3
|
|
117
154
|
echo '{"type":"tool_call","toolName":"Task","parameters":{"subagent_type":"worker"}}'
|
|
155
|
+
echo "{\\"type\\":\\"tool_call\\",\\"toolName\\":\\"Execute\\",\\"parameters\\":{\\"command\\":\\"echo $(printf '%0300d' 0)\\"}}"
|
|
118
156
|
echo '{"type":"tool_result","toolId":"Task","value":"A subagent."}'
|
|
119
157
|
echo '{"type":"message","role":"assistant","text":"Found it."}'
|
|
120
158
|
sleep 0.3 ;;
|
|
@@ -122,6 +160,20 @@ esac
|
|
|
122
160
|
echo "{\\"type\\":\\"completion\\",\\"finalText\\":\\"done\\",\\"numTurns\\":1,\\"session_id\\":\\"$session\\"}"
|
|
123
161
|
`;
|
|
124
162
|
|
|
163
|
+
// A fake earlyoom: it records its arguments, and writes the lines that a
|
|
164
|
+
// fake agent leaves for it to stderr, as earlyoom does, until the runner exits.
|
|
165
|
+
const FAKE_EARLYOOM = `#!/bin/sh
|
|
166
|
+
printf '%s' "$*" > "${calls}.earlyoom"
|
|
167
|
+
echo "earlyoom v1.7" >&2
|
|
168
|
+
while kill -0 $PPID 2>/dev/null; do
|
|
169
|
+
if [ -e "${calls}.oom" ]; then
|
|
170
|
+
cat "${calls}.oom" >&2
|
|
171
|
+
rm -f "${calls}.oom"
|
|
172
|
+
fi
|
|
173
|
+
sleep 0.1
|
|
174
|
+
done
|
|
175
|
+
`;
|
|
176
|
+
|
|
125
177
|
/** The hub's runner modules, by the path the runner fetches them at. */
|
|
126
178
|
const MODULES: Record<string, string> = {
|
|
127
179
|
"runtimes/claude.ts": join(import.meta.dirname, "../../claude/runtime/runner.ts"),
|
|
@@ -140,11 +192,23 @@ let relays = 0;
|
|
|
140
192
|
/** The token that the fake router mints when the runner asks for new tokens. */
|
|
141
193
|
let freshToken = "push-token";
|
|
142
194
|
const tokenRequests: TokenRequest[] = [];
|
|
195
|
+
/** The heartbeats that the runner has posted. */
|
|
196
|
+
const heartbeats: Heartbeat[] = [];
|
|
197
|
+
/** The runs that the fake router answers heartbeats for as lost, and whose replies it refuses as lost. */
|
|
198
|
+
const lostRuns = new Set<string>();
|
|
199
|
+
/** The replies that the fake router refused because their run was lost. */
|
|
200
|
+
const refused: Relay[] = [];
|
|
201
|
+
/** How many more `done` heartbeats the fake router fails with status 503. */
|
|
202
|
+
let failDone = 0;
|
|
143
203
|
let waiting: (() => void) | undefined;
|
|
144
204
|
let server: Server;
|
|
145
205
|
let runner: ChildProcess;
|
|
206
|
+
/** What the runners have written to stdout, which is the container's logs. */
|
|
207
|
+
let output = "";
|
|
146
208
|
/** The state store's objects, by key. */
|
|
147
209
|
const state = new Map<string, Buffer>();
|
|
210
|
+
/** How many times the runner has written each of the state store's objects. */
|
|
211
|
+
const writes = new Map<string, number>();
|
|
148
212
|
/** Each conversation's thread, which the fake router answers for its runs. */
|
|
149
213
|
const threads = new Map<string, ThreadMessage[]>();
|
|
150
214
|
/** The conversations whose threads the fake router can't read. */
|
|
@@ -164,6 +228,8 @@ const nextReply = () =>
|
|
|
164
228
|
const check = () => {
|
|
165
229
|
const reply = replies.shift();
|
|
166
230
|
if (!reply) return void (waiting = check);
|
|
231
|
+
// A reply that comes while no test waits stays for the next one.
|
|
232
|
+
waiting = undefined;
|
|
167
233
|
clearTimeout(timer);
|
|
168
234
|
resolve(reply);
|
|
169
235
|
};
|
|
@@ -177,6 +243,7 @@ before(async () => {
|
|
|
177
243
|
writeFileSync(join(bin, "agent"), FAKE_CURSOR, { mode: 0o755 });
|
|
178
244
|
writeFileSync(join(bin, "droid"), FAKE_DROID, { mode: 0o755 });
|
|
179
245
|
writeFileSync(join(bin, "gh"), FAKE_GH, { mode: 0o755 });
|
|
246
|
+
writeFileSync(join(bin, "earlyoom"), FAKE_EARLYOOM, { mode: 0o755 });
|
|
180
247
|
|
|
181
248
|
const work = join(root, "work");
|
|
182
249
|
mkdirSync(join(work, ".factory"), { recursive: true });
|
|
@@ -205,6 +272,7 @@ before(async () => {
|
|
|
205
272
|
const key = pathname.slice("/state/".length);
|
|
206
273
|
if (request.method === "PUT") {
|
|
207
274
|
state.set(key, Buffer.concat(chunks));
|
|
275
|
+
writes.set(key, (writes.get(key) ?? 0) + 1);
|
|
208
276
|
return response.end();
|
|
209
277
|
}
|
|
210
278
|
const object = state.get(key);
|
|
@@ -220,6 +288,16 @@ before(async () => {
|
|
|
220
288
|
}
|
|
221
289
|
return response.end(JSON.stringify({ messages: threads.get(conversation) ?? [] }));
|
|
222
290
|
}
|
|
291
|
+
if (pathname === "/heartbeat") {
|
|
292
|
+
const body = JSON.parse(Buffer.concat(chunks).toString()) as Heartbeat;
|
|
293
|
+
heartbeats.push(body);
|
|
294
|
+
if (body.done && failDone > 0) {
|
|
295
|
+
failDone--;
|
|
296
|
+
response.statusCode = 503;
|
|
297
|
+
return response.end("unavailable");
|
|
298
|
+
}
|
|
299
|
+
return response.end(JSON.stringify({ ok: true, ...(lostRuns.has(body.ticket.run!) && { lost: true }) }));
|
|
300
|
+
}
|
|
223
301
|
if (pathname === "/tokens") {
|
|
224
302
|
const body = JSON.parse(Buffer.concat(chunks).toString()) as TokenRequest;
|
|
225
303
|
tokenRequests.push(body);
|
|
@@ -227,6 +305,11 @@ before(async () => {
|
|
|
227
305
|
}
|
|
228
306
|
// Like the router, it names the message that each reply posted or replaced.
|
|
229
307
|
const relay = JSON.parse(Buffer.concat(chunks).toString()) as Relay;
|
|
308
|
+
if (lostRuns.has(relay.ticket.run!)) {
|
|
309
|
+
refused.push(relay);
|
|
310
|
+
response.statusCode = 409;
|
|
311
|
+
return response.end(JSON.stringify({ error: "the router marked the run lost", lost: true }));
|
|
312
|
+
}
|
|
230
313
|
replies.push(relay);
|
|
231
314
|
relays++;
|
|
232
315
|
waiting?.();
|
|
@@ -257,6 +340,9 @@ const startRunner = async () => {
|
|
|
257
340
|
FACTORY_MODULES_URL: `${serverUrl()}/modules`,
|
|
258
341
|
FACTORY_TOKEN_REFRESH_MS: "300",
|
|
259
342
|
FACTORY_PROGRESS_INTERVAL_MS: "100",
|
|
343
|
+
FACTORY_SAVE_INTERVAL_MS: "200",
|
|
344
|
+
FACTORY_HEARTBEAT_INTERVAL_MS: "200",
|
|
345
|
+
FACTORY_DONE_RETRY_MS: "50",
|
|
260
346
|
// Clones of github.com come from the local remotes.
|
|
261
347
|
GIT_CONFIG_COUNT: "1",
|
|
262
348
|
GIT_CONFIG_KEY_0: `url.${join(root, "remotes")}/.insteadOf`,
|
|
@@ -264,6 +350,9 @@ const startRunner = async () => {
|
|
|
264
350
|
},
|
|
265
351
|
stdio: ["ignore", "pipe", "inherit"],
|
|
266
352
|
});
|
|
353
|
+
runner.stdout!.on("data", (chunk) => {
|
|
354
|
+
output += String(chunk);
|
|
355
|
+
});
|
|
267
356
|
await new Promise<void>((resolve, reject) => {
|
|
268
357
|
runner.stdout!.on("data", (chunk) => String(chunk).includes("listening") && resolve());
|
|
269
358
|
runner.once("exit", (code) => reject(new Error(`The runner exited with code ${code}.`)));
|
|
@@ -314,6 +403,26 @@ const base = () => ({
|
|
|
314
403
|
const post = (body: Run) =>
|
|
315
404
|
fetch(`http://127.0.0.1:${port}/runs`, { method: "POST", body: JSON.stringify(body) });
|
|
316
405
|
|
|
406
|
+
/** Resolves once `check` is true. */
|
|
407
|
+
const until = async (check: () => boolean) => {
|
|
408
|
+
const deadline = Date.now() + 10_000;
|
|
409
|
+
while (!check()) {
|
|
410
|
+
if (Date.now() > deadline) throw new Error("timed out");
|
|
411
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
|
|
415
|
+
/** The tool calls that the runner logged for a run, without their times. */
|
|
416
|
+
const toolLogs = (runId: string) =>
|
|
417
|
+
output
|
|
418
|
+
.split("\n")
|
|
419
|
+
.flatMap((line) => (line.startsWith("{") ? [JSON.parse(line) as Record<string, unknown>] : []))
|
|
420
|
+
.filter((entry) => entry.run === runId && entry.tool)
|
|
421
|
+
.map(({ at, ...entry }) => {
|
|
422
|
+
assert.match(String(at), /^\d{4}-\d\d-\d\dT/);
|
|
423
|
+
return entry;
|
|
424
|
+
});
|
|
425
|
+
|
|
317
426
|
const lastCall = () => readFileSync(calls, "utf8").trim().split("\n").slice(-3);
|
|
318
427
|
const lastPrompt = () => readFileSync(`${calls}.prompt`, "utf8");
|
|
319
428
|
|
|
@@ -383,7 +492,8 @@ test("a cursor agent's messages during a run share one comment, which its final
|
|
|
383
492
|
const id = `m${relays + 1}`;
|
|
384
493
|
const agent = { id: "coder", runtime: "cursor", model: "composer-2.5" };
|
|
385
494
|
const conversation = "github:acme/api#32";
|
|
386
|
-
|
|
495
|
+
const body = run({ id: conversation, message: say(conversation, "talk to me") }, { runtimes: ["cursor"], agent });
|
|
496
|
+
await post(body);
|
|
387
497
|
const first = await nextReply();
|
|
388
498
|
assert.match(first.text, /^> Looking\.\n\n<sub>Composer 2\.5 working • 0:0\d<\/sub>$/);
|
|
389
499
|
assert.equal(first.message, undefined);
|
|
@@ -396,6 +506,11 @@ test("a cursor agent's messages during a run share one comment, which its final
|
|
|
396
506
|
const final = await nextReply();
|
|
397
507
|
assert.equal(final.text, "done");
|
|
398
508
|
assert.deepEqual(final.message, { id, signature: "msig" });
|
|
509
|
+
// A tool call is logged once, as it starts.
|
|
510
|
+
assert.deepEqual(toolLogs(body.id), [
|
|
511
|
+
{ run: body.id, worktree: "issue-1", tool: "shell", argument: "ls -la" },
|
|
512
|
+
{ run: body.id, worktree: "issue-1", tool: "search", argument: '{"q":1}' },
|
|
513
|
+
]);
|
|
399
514
|
});
|
|
400
515
|
|
|
401
516
|
test("a failed cursor run replies with the error", async () => {
|
|
@@ -458,7 +573,8 @@ test("a droid agent's messages during a run share one comment, which its final r
|
|
|
458
573
|
const id = `m${relays + 1}`;
|
|
459
574
|
const agent = { id: "coder", runtime: "droid" };
|
|
460
575
|
const conversation = "github:acme/api#23";
|
|
461
|
-
|
|
576
|
+
const body = run({ id: conversation, message: say(conversation, "talk to me") }, { runtimes: ["droid"], agent });
|
|
577
|
+
await post(body);
|
|
462
578
|
const first = await nextReply();
|
|
463
579
|
assert.match(first.text, /^> Looking\.\n\n<sub>Claude Sonnet 5\.5 working • 0:0\d<\/sub>$/);
|
|
464
580
|
const thinking = await nextReply();
|
|
@@ -470,6 +586,10 @@ test("a droid agent's messages during a run share one comment, which its final r
|
|
|
470
586
|
const final = await nextReply();
|
|
471
587
|
assert.equal(final.text, "done");
|
|
472
588
|
assert.deepEqual(final.message, { id, signature: "msig" });
|
|
589
|
+
assert.deepEqual(toolLogs(body.id), [
|
|
590
|
+
{ run: body.id, worktree: "issue-1", tool: "Task", argument: '{"subagent_type":"worker"}' },
|
|
591
|
+
{ run: body.id, worktree: "issue-1", tool: "Execute", argument: `echo ${"0".repeat(195)}…` },
|
|
592
|
+
]);
|
|
473
593
|
});
|
|
474
594
|
|
|
475
595
|
test("a droid run sets Droid's user settings to send thinking as reasoning, and keeps the other settings", async () => {
|
|
@@ -727,7 +847,8 @@ test("a run with no branch gets a scratch worktree for its conversation", async
|
|
|
727
847
|
test("the agent's messages during a run share one comment, which its final reply replaces", async () => {
|
|
728
848
|
const id = `m${relays + 1}`;
|
|
729
849
|
const conversation = "github:acme/api#5";
|
|
730
|
-
|
|
850
|
+
const body = run({ id: conversation, message: say(conversation, "talk to me") }, { worktree: { branch: "issue-5" } });
|
|
851
|
+
await post(body);
|
|
731
852
|
const first = await nextReply();
|
|
732
853
|
assert.match(first.text, /^> Looking\.\n\n<sub>Claude Opus 5\.5 working • 0:0\d<\/sub>$/);
|
|
733
854
|
assert.equal(first.message, undefined);
|
|
@@ -741,6 +862,11 @@ test("the agent's messages during a run share one comment, which its final reply
|
|
|
741
862
|
const final = await nextReply();
|
|
742
863
|
assert.equal(final.text, "done");
|
|
743
864
|
assert.deepEqual(final.message, { id, signature: "msig" });
|
|
865
|
+
// A subagent's tool calls are logged too, and a command is logged on one line.
|
|
866
|
+
assert.deepEqual(toolLogs(body.id), [
|
|
867
|
+
{ run: body.id, worktree: "issue-5", tool: "Bash", argument: "npm test -- --watch=false" },
|
|
868
|
+
{ run: body.id, worktree: "issue-5", tool: "Read", argument: "/src/a.ts" },
|
|
869
|
+
]);
|
|
744
870
|
});
|
|
745
871
|
|
|
746
872
|
test("a run of a runtime that the hub has no runner module for replies with the error", async () => {
|
|
@@ -759,6 +885,16 @@ test("a failed run replies with the error, and its session has still seen the th
|
|
|
759
885
|
assert.deepEqual(Object.keys(session.seen), [message]);
|
|
760
886
|
});
|
|
761
887
|
|
|
888
|
+
test("a run whose CLI exits with no result saves the session that its output reported", async () => {
|
|
889
|
+
const id = "github:acme/api#15";
|
|
890
|
+
const message = say(id, "crash now");
|
|
891
|
+
await post(run({ id, message }, { worktree: { branch: "issue-15" } }));
|
|
892
|
+
assert.match((await nextReply()).text, /The run failed: Claude Code exited with code 137: killed/);
|
|
893
|
+
const saved = JSON.parse(state.get("sessions/github-acme-api-15/coder.json")!.toString());
|
|
894
|
+
assert.equal(saved.id, "s-issue-15");
|
|
895
|
+
assert.deepEqual(Object.keys(saved.seen), [message]);
|
|
896
|
+
});
|
|
897
|
+
|
|
762
898
|
test("after the container sleeps, a run restores its worktree and its conversation's session", async () => {
|
|
763
899
|
const id = "github:acme/api#9";
|
|
764
900
|
await post(run({ id, message: say(id, "edit the code") }, { worktree: { branch: "issue-9" } }));
|
|
@@ -790,6 +926,37 @@ test("a snapshot that can't be restored leaves a note, and the run starts from t
|
|
|
790
926
|
assert.equal(sh(join(data, "worktrees", "acme-api", "issue-10"), "log", "-1", "--format=%s"), "init");
|
|
791
927
|
});
|
|
792
928
|
|
|
929
|
+
test("during a run, the runner saves the worktree and session when they change, so a lost run can resume", async () => {
|
|
930
|
+
const id = "github:acme/api#13";
|
|
931
|
+
const first = say(id, "stall");
|
|
932
|
+
await post(run({ id, message: first }, { worktree: { branch: "issue-13" } }));
|
|
933
|
+
const session = "sessions/github-acme-api-13/coder";
|
|
934
|
+
await until(() => state.has("worktrees/issue-13.bundle") && state.has(`${session}.json`));
|
|
935
|
+
// A new session hasn't seen the thread until the run finishes.
|
|
936
|
+
assert.deepEqual(JSON.parse(state.get(`${session}.json`)!.toString()), {
|
|
937
|
+
id: "s-issue-13",
|
|
938
|
+
cwd: join(data, "worktrees", "acme-api", "issue-13"),
|
|
939
|
+
seen: {},
|
|
940
|
+
});
|
|
941
|
+
// Saves of a worktree and transcript that haven't changed upload nothing.
|
|
942
|
+
const counts = () => [writes.get("worktrees/issue-13.bundle"), writes.get(`${session}.tar.gz`)];
|
|
943
|
+
const before = counts();
|
|
944
|
+
await new Promise((resolve) => setTimeout(resolve, 700));
|
|
945
|
+
assert.deepEqual(counts(), before);
|
|
946
|
+
|
|
947
|
+
const lost = nextReply();
|
|
948
|
+
await sleepContainer();
|
|
949
|
+
assert.match((await lost).text, /the run was lost/);
|
|
950
|
+
await startRunner();
|
|
951
|
+
|
|
952
|
+
await post(run({ id, message: say(id, "carry on") }, { worktree: { branch: "issue-13" } }));
|
|
953
|
+
assert.equal((await nextReply()).text, "done");
|
|
954
|
+
const worktree = join(data, "worktrees", "acme-api", "issue-13");
|
|
955
|
+
assert.match(lastCall()[2]!, /--resume s-issue-13/);
|
|
956
|
+
assert.equal(readFileSync(join(worktree, "draft.txt"), "utf8"), "draft\n");
|
|
957
|
+
assert.match(lastPrompt(), /### Messages in thread since last turn[^]*stall[^]*carry on/);
|
|
958
|
+
});
|
|
959
|
+
|
|
793
960
|
test("during a long run, the runner refreshes the tokens that gh and git read", async () => {
|
|
794
961
|
freshToken = "fresh-token";
|
|
795
962
|
tokenRequests.length = 0;
|
|
@@ -804,6 +971,136 @@ test("during a long run, the runner refreshes the tokens that gh and git read",
|
|
|
804
971
|
assert.equal(readFileSync(join(data, "github", "code"), "utf8"), "fresh-token");
|
|
805
972
|
});
|
|
806
973
|
|
|
974
|
+
test("the runner starts earlyoom, logs its output, and says in a run's reply when earlyoom stopped its agent's process", async () => {
|
|
975
|
+
assert.equal(readFileSync(`${calls}.earlyoom`, "utf8"), "-r 60 -s 100,100");
|
|
976
|
+
const id = "github:acme/api#14";
|
|
977
|
+
await post(run({ id, message: say(id, "use memory") }, { worktree: { branch: "issue-14" } }));
|
|
978
|
+
// earlyoom's SIGTERM and SIGKILL for one process make one note.
|
|
979
|
+
assert.equal(
|
|
980
|
+
(await nextReply()).text,
|
|
981
|
+
"done\n\n> earlyoom stopped `tsc` (3.1 GiB) because the container was out of memory.",
|
|
982
|
+
);
|
|
983
|
+
assert.match(output, /\{"at":"[^"]+","earlyoom":"sending SIGTERM to process \d+ uid 1000 \\"tsc\\": badness 900, VmRSS 3174 MiB"\}/);
|
|
984
|
+
});
|
|
985
|
+
|
|
986
|
+
/** A run whose reply ticket names it, with the router's heartbeat route. */
|
|
987
|
+
const watched = (conversation: Run["conversation"], over: Partial<Run> = {}): Run => {
|
|
988
|
+
const body = run(conversation, over);
|
|
989
|
+
body.reply.ticket.run = body.id;
|
|
990
|
+
body.reply.heartbeat = `${serverUrl()}/heartbeat`;
|
|
991
|
+
return body;
|
|
992
|
+
};
|
|
993
|
+
|
|
994
|
+
const beatsOf = (runId: string) => heartbeats.filter((h) => h.ticket.run === runId);
|
|
995
|
+
|
|
996
|
+
/** Resolves once the runner has logged that the run ended because the router marked it lost. */
|
|
997
|
+
const endedLost = (runId: string) =>
|
|
998
|
+
until(() => new RegExp(`"run":"${runId}","state":"(skipped|stopped)","reason":"lost"`).test(output));
|
|
999
|
+
|
|
1000
|
+
test("the runner posts heartbeats for each run it holds, queued or running, with the message that its replies replace, and its last reply ends the watch", async () => {
|
|
1001
|
+
const id = "github:acme/api#20";
|
|
1002
|
+
const first = watched({ id, message: say(id, "talk to me") }, { worktree: { branch: "issue-20" } });
|
|
1003
|
+
const second = watched({ id, message: say(id, "and then this") }, { worktree: { branch: "issue-20" } });
|
|
1004
|
+
await post(first);
|
|
1005
|
+
await post(second);
|
|
1006
|
+
await until(() => beatsOf(second.id).length >= 2);
|
|
1007
|
+
// The first run read the second's message, so the second is skipped.
|
|
1008
|
+
await until(() => beatsOf(second.id).some((h) => h.done));
|
|
1009
|
+
const firstReplies = replies.filter((r) => r.ticket.run === first.id);
|
|
1010
|
+
assert.equal(firstReplies.at(-1)!.done, true);
|
|
1011
|
+
assert.equal(firstReplies.filter((r) => r.done).length, 1);
|
|
1012
|
+
const firstBeats = beatsOf(first.id);
|
|
1013
|
+
assert.equal(firstBeats.some((h) => h.done), false);
|
|
1014
|
+
assert.ok(firstBeats.some((h) => h.message?.signature === "msig"));
|
|
1015
|
+
assert.equal(firstBeats[0]!.signature, "sig");
|
|
1016
|
+
while (replies.length) replies.shift();
|
|
1017
|
+
});
|
|
1018
|
+
|
|
1019
|
+
test("a queued run that the router marks lost doesn't run, and posts nothing", async () => {
|
|
1020
|
+
const id = "github:acme/api#61";
|
|
1021
|
+
const first = watched({ id, message: say(id, "wait for it") }, { worktree: { branch: "issue-61" } });
|
|
1022
|
+
const body = watched({ id, message: say(id, "talk to me") }, { worktree: { branch: "issue-61" } });
|
|
1023
|
+
lostRuns.add(body.id);
|
|
1024
|
+
await post(first);
|
|
1025
|
+
await post(body);
|
|
1026
|
+
await endedLost(body.id);
|
|
1027
|
+
assert.equal(replies.filter((r) => r.ticket.run === body.id).length, 0);
|
|
1028
|
+
assert.match(output, new RegExp(`"run":"${body.id}","state":"lost"`));
|
|
1029
|
+
assert.doesNotMatch(output, new RegExp(`"run":"${body.id}","repo"`));
|
|
1030
|
+
assert.equal((await nextReply()).text, "done");
|
|
1031
|
+
});
|
|
1032
|
+
|
|
1033
|
+
test("a running run that the router marks lost stops its agent, saves its work, and posts nothing, so its restart resumes it", async () => {
|
|
1034
|
+
const id = "github:acme/api#62";
|
|
1035
|
+
const first = say(id, "run forever");
|
|
1036
|
+
const body = watched({ id, message: first }, { worktree: { branch: "issue-62" } });
|
|
1037
|
+
await post(body);
|
|
1038
|
+
const worktree = join(data, "worktrees", "acme-api", "issue-62");
|
|
1039
|
+
await until(() => existsSync(join(worktree, "forever.txt")));
|
|
1040
|
+
lostRuns.add(body.id);
|
|
1041
|
+
await endedLost(body.id);
|
|
1042
|
+
assert.equal(replies.filter((r) => r.ticket.run === body.id).length, 0);
|
|
1043
|
+
// The lost run's session hasn't seen the thread, so its restart gets the lost run's messages again.
|
|
1044
|
+
assert.deepEqual(JSON.parse(state.get("sessions/github-acme-api-62/coder.json")!.toString()), {
|
|
1045
|
+
id: "s-issue-62",
|
|
1046
|
+
cwd: worktree,
|
|
1047
|
+
seen: {},
|
|
1048
|
+
});
|
|
1049
|
+
await post(run({ id, message: say(id, "carry on") }, { worktree: { branch: "issue-62" } }));
|
|
1050
|
+
assert.equal((await nextReply()).text, "done");
|
|
1051
|
+
assert.match(lastCall()[2]!, /--resume s-issue-62/);
|
|
1052
|
+
assert.match(lastPrompt(), /### Messages in thread since last turn[^]*run forever[^]*carry on/);
|
|
1053
|
+
});
|
|
1054
|
+
|
|
1055
|
+
test("stopping a run's agent stops the processes that the agent started too", async () => {
|
|
1056
|
+
const id = "github:acme/api#64";
|
|
1057
|
+
const body = watched({ id, message: say(id, "leave a child") }, { worktree: { branch: "issue-64" } });
|
|
1058
|
+
await post(body);
|
|
1059
|
+
const pidFile = join(data, "worktrees", "acme-api", "issue-64", "child.pid");
|
|
1060
|
+
await until(() => existsSync(pidFile) && readFileSync(pidFile, "utf8").trim() !== "");
|
|
1061
|
+
const child = Number(readFileSync(pidFile, "utf8"));
|
|
1062
|
+
const alive = () => {
|
|
1063
|
+
try {
|
|
1064
|
+
process.kill(child, 0);
|
|
1065
|
+
return true;
|
|
1066
|
+
} catch {
|
|
1067
|
+
return false;
|
|
1068
|
+
}
|
|
1069
|
+
};
|
|
1070
|
+
assert.ok(alive());
|
|
1071
|
+
lostRuns.add(body.id);
|
|
1072
|
+
await endedLost(body.id);
|
|
1073
|
+
await until(() => !alive());
|
|
1074
|
+
});
|
|
1075
|
+
|
|
1076
|
+
test("a run whose reply the router refuses because it marked the run lost stops its agent and posts nothing more", async () => {
|
|
1077
|
+
const id = "github:acme/api#63";
|
|
1078
|
+
const body = watched({ id, message: say(id, "talk forever") }, { worktree: { branch: "issue-63" } });
|
|
1079
|
+
// Only the replies say that the run is lost.
|
|
1080
|
+
delete body.reply.heartbeat;
|
|
1081
|
+
lostRuns.add(body.id);
|
|
1082
|
+
const started = Date.now();
|
|
1083
|
+
await post(body);
|
|
1084
|
+
await endedLost(body.id);
|
|
1085
|
+
assert.ok(Date.now() - started < 20_000);
|
|
1086
|
+
assert.equal(refused.filter((r) => r.ticket.run === body.id).length, 1);
|
|
1087
|
+
assert.equal(replies.filter((r) => r.ticket.run === body.id).length, 0);
|
|
1088
|
+
});
|
|
1089
|
+
|
|
1090
|
+
test("a skipped run that posts nothing posts its done heartbeat, again if the router fails it", async () => {
|
|
1091
|
+
const id = "github:acme/api#60";
|
|
1092
|
+
const first = say(id, "first");
|
|
1093
|
+
const second = say(id, "second");
|
|
1094
|
+
await post(watched({ id, message: first }, { worktree: { branch: "issue-60" } }));
|
|
1095
|
+
const skipped = watched({ id, message: second }, { worktree: { branch: "issue-60" } });
|
|
1096
|
+
failDone = 2;
|
|
1097
|
+
await post(skipped);
|
|
1098
|
+
assert.equal((await nextReply()).text, "done");
|
|
1099
|
+
await until(() => beatsOf(skipped.id).filter((h) => h.done).length === 3);
|
|
1100
|
+
assert.equal(failDone, 0);
|
|
1101
|
+
assert.equal(replies.filter((r) => r.ticket.run === skipped.id).length, 0);
|
|
1102
|
+
});
|
|
1103
|
+
|
|
807
1104
|
test("status counts the runs that are running or queued", async () => {
|
|
808
1105
|
const response = await fetch(`http://127.0.0.1:${port}/status`);
|
|
809
1106
|
assert.deepEqual(await response.json(), { active: 0 });
|