@notation/factory 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/contracts/channel.ts +43 -0
- package/contracts/connection.ts +15 -0
- package/contracts/hub.ts +33 -0
- package/contracts/index.ts +36 -0
- package/contracts/outpost.ts +54 -0
- package/contracts/router.ts +104 -0
- package/contracts/vault.ts +22 -0
- package/deployer/collect.ts +31 -0
- package/deployer/deploy.test.ts +50 -0
- package/deployer/index.ts +152 -0
- package/deployer/sdk.gen.ts +2 -0
- package/deployer/sdk.ts +18 -0
- package/implementations/container.ts +67 -0
- package/implementations/outpost.ts +50 -0
- package/implementations/policy.ts +26 -0
- package/implementations/trigger.ts +67 -0
- package/index.ts +3 -0
- package/lib/binding-name.ts +9 -0
- package/lib/collect.ts +21 -0
- package/lib/outpost.ts +17 -0
- package/lib/scoped-name.ts +10 -0
- package/outpost.ts +12 -0
- package/package.json +39 -3
- package/resources/outpost-config.ts +102 -0
- package/resources/random-key.ts +54 -0
- package/resources/router-sync.ts +53 -0
- package/router/channel.ts +114 -0
- package/router/handle.test.ts +419 -0
- package/router/handle.ts +442 -0
- package/router/index.ts +52 -0
- package/router/keys.ts +36 -0
- package/router/run.ts +91 -0
- package/runner/index.ts +628 -0
- package/runner/runner.test.ts +322 -0
- package/README.md +0 -3
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { type ChildProcess, execFileSync, spawn } from "node:child_process";
|
|
3
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { createServer, type Server } from "node:http";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { after, before, test } from "node:test";
|
|
8
|
+
import type { Relay, Run, TokenRequest } from "../router/run.ts";
|
|
9
|
+
|
|
10
|
+
const root = realpathSync(mkdtempSync(join(tmpdir(), "factory-runner-")));
|
|
11
|
+
const bin = join(root, "bin");
|
|
12
|
+
const data = join(root, "data");
|
|
13
|
+
const home = join(root, "home");
|
|
14
|
+
const calls = join(root, "calls");
|
|
15
|
+
const port = 40000 + Math.floor(Math.random() * 20000);
|
|
16
|
+
|
|
17
|
+
const sh = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, stdio: "pipe" }).toString().trim();
|
|
18
|
+
|
|
19
|
+
// A fake Claude Code: it records how it was called and the token that gh
|
|
20
|
+
// gets, and writes a transcript for a session named after its working
|
|
21
|
+
// directory. It fails, edits the worktree, or waits for the runner to
|
|
22
|
+
// refresh its tokens, when the prompt says so.
|
|
23
|
+
const FAKE_CLAUDE = `#!/bin/sh
|
|
24
|
+
prompt="$2"
|
|
25
|
+
case "$prompt" in
|
|
26
|
+
wait*) sleep 1 ;;
|
|
27
|
+
esac
|
|
28
|
+
printf '%s\\n' "$(pwd)" "$(gh)" "$(printf '%s' "$*" | tr '\\n' ' ')" >> "${calls}"
|
|
29
|
+
session="s-$(basename "$(pwd)")"
|
|
30
|
+
mkdir -p "$HOME/.claude/projects/-p-$(basename "$(pwd)")"
|
|
31
|
+
echo "$prompt" >> "$HOME/.claude/projects/-p-$(basename "$(pwd)")/$session.jsonl"
|
|
32
|
+
case "$prompt" in
|
|
33
|
+
fail*) echo "{\\"is_error\\":true,\\"result\\":\\"it broke\\",\\"session_id\\":\\"$session\\"}"; exit 1 ;;
|
|
34
|
+
edit*)
|
|
35
|
+
echo committed > committed.txt
|
|
36
|
+
git add committed.txt
|
|
37
|
+
git commit -q -m "local work"
|
|
38
|
+
echo draft > notes.txt
|
|
39
|
+
rm README.md ;;
|
|
40
|
+
wait*) printf 'protocol=https\\nhost=github.com\\n\\n' | git credential fill | grep password= >> "${calls}" ;;
|
|
41
|
+
esac
|
|
42
|
+
echo "{\\"result\\":\\"done\\",\\"session_id\\":\\"$session\\"}"
|
|
43
|
+
`;
|
|
44
|
+
|
|
45
|
+
/** A fake Droid: like the fake Claude Code, but for droid's CLI. */
|
|
46
|
+
const FAKE_DROID = `#!/bin/sh
|
|
47
|
+
prompt="$2"
|
|
48
|
+
printf '%s\\n' "$(pwd)" "$(gh)" "$(printf '%s' "$*" | tr '\\n' ' ')" >> "${calls}"
|
|
49
|
+
session="s-$(basename "$(pwd)")"
|
|
50
|
+
mkdir -p "$HOME/.factory/sessions/-p-$(basename "$(pwd)")"
|
|
51
|
+
echo "$prompt" >> "$HOME/.factory/sessions/-p-$(basename "$(pwd)")/$session.jsonl"
|
|
52
|
+
echo "{\\"result\\":\\"done\\",\\"session_id\\":\\"$session\\"}"
|
|
53
|
+
`;
|
|
54
|
+
|
|
55
|
+
/** A fake gh, which prints the token it gets. */
|
|
56
|
+
const FAKE_GH = `#!/bin/sh
|
|
57
|
+
echo "$GH_TOKEN"
|
|
58
|
+
`;
|
|
59
|
+
|
|
60
|
+
const replies: Relay[] = [];
|
|
61
|
+
/** The token that the fake router mints when the runner asks for new tokens. */
|
|
62
|
+
let freshToken = "push-token";
|
|
63
|
+
const tokenRequests: TokenRequest[] = [];
|
|
64
|
+
let waiting: (() => void) | undefined;
|
|
65
|
+
let server: Server;
|
|
66
|
+
let runner: ChildProcess;
|
|
67
|
+
/** The state store's objects, by key. */
|
|
68
|
+
const state = new Map<string, Buffer>();
|
|
69
|
+
|
|
70
|
+
const nextReply = () =>
|
|
71
|
+
new Promise<Relay>((resolve, reject) => {
|
|
72
|
+
const timer = setTimeout(() => reject(new Error("no reply")), 20_000);
|
|
73
|
+
const check = () => {
|
|
74
|
+
const reply = replies.shift();
|
|
75
|
+
if (!reply) return void (waiting = check);
|
|
76
|
+
clearTimeout(timer);
|
|
77
|
+
resolve(reply);
|
|
78
|
+
};
|
|
79
|
+
check();
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
before(async () => {
|
|
83
|
+
mkdirSync(bin);
|
|
84
|
+
mkdirSync(home);
|
|
85
|
+
writeFileSync(join(bin, "claude"), FAKE_CLAUDE, { mode: 0o755 });
|
|
86
|
+
writeFileSync(join(bin, "droid"), FAKE_DROID, { mode: 0o755 });
|
|
87
|
+
writeFileSync(join(bin, "gh"), FAKE_GH, { mode: 0o755 });
|
|
88
|
+
|
|
89
|
+
const work = join(root, "work");
|
|
90
|
+
mkdirSync(join(work, ".factory"), { recursive: true });
|
|
91
|
+
writeFileSync(join(work, ".factory", "prompt.md"), "Be brief.");
|
|
92
|
+
writeFileSync(join(work, ".factory", "npmrc"), "registry=x");
|
|
93
|
+
writeFileSync(join(work, "README.md"), "# api\n");
|
|
94
|
+
sh(root, "init", "-q", "-b", "main", work);
|
|
95
|
+
sh(work, "add", ".");
|
|
96
|
+
sh(work, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "init");
|
|
97
|
+
mkdirSync(join(root, "remotes", "acme"), { recursive: true });
|
|
98
|
+
sh(root, "clone", "-q", "--bare", work, join(root, "remotes", "acme", "api.git"));
|
|
99
|
+
|
|
100
|
+
server = createServer((request, response) => {
|
|
101
|
+
const chunks: Buffer[] = [];
|
|
102
|
+
request.on("data", (chunk) => chunks.push(chunk));
|
|
103
|
+
request.on("end", () => {
|
|
104
|
+
const { pathname } = new URL(request.url!, "http://test");
|
|
105
|
+
if (pathname.startsWith("/state/")) {
|
|
106
|
+
const key = pathname.slice("/state/".length);
|
|
107
|
+
if (request.method === "PUT") {
|
|
108
|
+
state.set(key, Buffer.concat(chunks));
|
|
109
|
+
return response.end();
|
|
110
|
+
}
|
|
111
|
+
const object = state.get(key);
|
|
112
|
+
response.statusCode = object ? 200 : 404;
|
|
113
|
+
return response.end(object);
|
|
114
|
+
}
|
|
115
|
+
if (pathname === "/tokens") {
|
|
116
|
+
const body = JSON.parse(Buffer.concat(chunks).toString()) as TokenRequest;
|
|
117
|
+
tokenRequests.push(body);
|
|
118
|
+
return response.end(JSON.stringify([{ policy: "code", repo: body.ticket.repo, token: freshToken }]));
|
|
119
|
+
}
|
|
120
|
+
replies.push(JSON.parse(Buffer.concat(chunks).toString()));
|
|
121
|
+
waiting?.();
|
|
122
|
+
response.end("{}");
|
|
123
|
+
});
|
|
124
|
+
});
|
|
125
|
+
await new Promise<void>((resolve) => server.listen(0, resolve));
|
|
126
|
+
await startRunner();
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
after(() => {
|
|
130
|
+
runner?.kill();
|
|
131
|
+
server?.close();
|
|
132
|
+
rmSync(root, { recursive: true, force: true });
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
const serverUrl = () => `http://127.0.0.1:${(server.address() as { port: number }).port}`;
|
|
136
|
+
|
|
137
|
+
const startRunner = async () => {
|
|
138
|
+
runner = spawn(process.execPath, [join(import.meta.dirname, "index.ts")], {
|
|
139
|
+
env: {
|
|
140
|
+
...process.env,
|
|
141
|
+
PATH: `${bin}:${process.env.PATH}`,
|
|
142
|
+
HOME: home,
|
|
143
|
+
FACTORY_DATA: data,
|
|
144
|
+
FACTORY_RUNNER_PORT: String(port),
|
|
145
|
+
FACTORY_STATE_URL: `${serverUrl()}/state`,
|
|
146
|
+
FACTORY_TOKEN_REFRESH_MS: "300",
|
|
147
|
+
// Clones of github.com come from the local remotes.
|
|
148
|
+
GIT_CONFIG_COUNT: "1",
|
|
149
|
+
GIT_CONFIG_KEY_0: `url.${join(root, "remotes")}/.insteadOf`,
|
|
150
|
+
GIT_CONFIG_VALUE_0: "https://github.com/",
|
|
151
|
+
},
|
|
152
|
+
stdio: ["ignore", "pipe", "inherit"],
|
|
153
|
+
});
|
|
154
|
+
await new Promise<void>((resolve, reject) => {
|
|
155
|
+
runner.stdout!.on("data", (chunk) => String(chunk).includes("listening") && resolve());
|
|
156
|
+
runner.once("exit", (code) => reject(new Error(`The runner exited with code ${code}.`)));
|
|
157
|
+
});
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
/** Stops the runner, and deletes what a container loses when it sleeps. */
|
|
161
|
+
const sleepContainer = async () => {
|
|
162
|
+
const exited = new Promise((resolve) => runner.once("exit", resolve));
|
|
163
|
+
runner.kill("SIGTERM");
|
|
164
|
+
// An exit code, not a signal, shows that the runner handled SIGTERM. As
|
|
165
|
+
// a container's PID 1, it would ignore it otherwise.
|
|
166
|
+
assert.equal(await exited, 0);
|
|
167
|
+
rmSync(data, { recursive: true, force: true });
|
|
168
|
+
rmSync(home, { recursive: true, force: true });
|
|
169
|
+
mkdirSync(home);
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
const run = (over: Partial<Run> = {}): Run => ({
|
|
173
|
+
id: crypto.randomUUID(),
|
|
174
|
+
repo: "acme/api",
|
|
175
|
+
trigger: "mention",
|
|
176
|
+
container: "dev",
|
|
177
|
+
runtimes: ["claude"],
|
|
178
|
+
files: { "~/.npmrc": "npmrc", "~/.config/app.json": { region: "eu" } },
|
|
179
|
+
agent: { id: "coder", runtime: "claude", model: "claude-opus-5-5", effort: "high", systemPrompt: "prompt.md" },
|
|
180
|
+
conversation: { id: "github:acme/api#1", prompt: "fix it" },
|
|
181
|
+
worktree: { branch: "issue-1" },
|
|
182
|
+
cloneToken: "clone-token",
|
|
183
|
+
tokens: [{ policy: "code", repo: "acme/api", token: "push-token" }],
|
|
184
|
+
refresh: {
|
|
185
|
+
url: `${serverUrl()}/tokens`,
|
|
186
|
+
ticket: { repo: "acme/api", container: "dev", expires: Date.now() + 60_000 },
|
|
187
|
+
signature: "token-sig",
|
|
188
|
+
},
|
|
189
|
+
reply: {
|
|
190
|
+
url: `${serverUrl()}/relay`,
|
|
191
|
+
ticket: { connection: "github/x", thread: { issue: 1 }, expires: Date.now() + 60_000 },
|
|
192
|
+
signature: "sig",
|
|
193
|
+
},
|
|
194
|
+
...over,
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
const post = (body: Run) =>
|
|
198
|
+
fetch(`http://127.0.0.1:${port}/runs`, { method: "POST", body: JSON.stringify(body) });
|
|
199
|
+
|
|
200
|
+
const lastCall = () => readFileSync(calls, "utf8").trim().split("\n").slice(-3);
|
|
201
|
+
|
|
202
|
+
test("runs the agent on its branch's worktree, and replies with its final message", async () => {
|
|
203
|
+
const response = await post(run());
|
|
204
|
+
assert.equal(response.status, 202);
|
|
205
|
+
const reply = await nextReply();
|
|
206
|
+
assert.equal(reply.text, "done");
|
|
207
|
+
assert.deepEqual(reply.ticket.thread, { issue: 1 });
|
|
208
|
+
assert.equal(reply.signature, "sig");
|
|
209
|
+
|
|
210
|
+
const worktree = join(data, "worktrees", "acme-api", "issue-1");
|
|
211
|
+
const [cwd, token, args] = lastCall();
|
|
212
|
+
assert.equal(cwd, worktree);
|
|
213
|
+
assert.equal(token, "push-token");
|
|
214
|
+
// The runner's prompt comes first, then the agent's own.
|
|
215
|
+
assert.match(args!, /--model claude-opus-5-5 --effort high --append-system-prompt You're running headless, .* Be brief\./);
|
|
216
|
+
assert.equal(sh(worktree, "branch", "--show-current"), "issue-1");
|
|
217
|
+
assert.equal(readFileSync(join(home, ".npmrc"), "utf8"), "registry=x");
|
|
218
|
+
assert.deepEqual(JSON.parse(readFileSync(join(home, ".config", "app.json"), "utf8")), { region: "eu" });
|
|
219
|
+
assert.equal(readFileSync(join(data, "github", "code"), "utf8"), "push-token");
|
|
220
|
+
// The clone token isn't kept in the repo's config.
|
|
221
|
+
assert.doesNotMatch(readFileSync(join(data, "repos", "acme-api.git", "config"), "utf8"), /clone-token|extraHeader/i);
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
test("a later run in the same conversation and worktree resumes its session", async () => {
|
|
225
|
+
await post(run());
|
|
226
|
+
await nextReply();
|
|
227
|
+
assert.match(lastCall()[2]!, /--resume s-issue-1/);
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
test("a droid run invokes droid exec, skipping permissions without an autonomy level", async () => {
|
|
231
|
+
await post(
|
|
232
|
+
run({
|
|
233
|
+
runtimes: ["droid"],
|
|
234
|
+
agent: { id: "coder", runtime: "droid", model: "claude-opus-5-5", effort: "medium", systemPrompt: "prompt.md" },
|
|
235
|
+
conversation: { id: "github:acme/api#20", prompt: "droid it" },
|
|
236
|
+
}),
|
|
237
|
+
);
|
|
238
|
+
assert.equal((await nextReply()).text, "done");
|
|
239
|
+
const [cwd, token, args] = lastCall();
|
|
240
|
+
assert.equal(cwd, join(data, "worktrees", "acme-api", "issue-1"));
|
|
241
|
+
assert.equal(token, "push-token");
|
|
242
|
+
assert.match(
|
|
243
|
+
args!,
|
|
244
|
+
/^exec droid it --output-format json --skip-permissions-unsafe --model claude-opus-5-5 --reasoning-effort medium --append-system-prompt You're running headless, .* Be brief\.$/,
|
|
245
|
+
);
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
test("a droid agent with autonomy runs with --auto, and resumes its session", async () => {
|
|
249
|
+
const agent = { id: "coder", runtime: "droid", autonomy: "high", settings: { hooks: { hooksDisabled: true } } };
|
|
250
|
+
const conversation = { id: "github:acme/api#21", prompt: "droid it" };
|
|
251
|
+
await post(run({ runtimes: ["droid"], agent, conversation }));
|
|
252
|
+
assert.equal((await nextReply()).text, "done");
|
|
253
|
+
assert.match(
|
|
254
|
+
lastCall()[2]!,
|
|
255
|
+
/^exec droid it --output-format json --auto high --append-system-prompt You're running headless, .*Link the pull request in your reply\. --settings \S*agents\/coder\/settings\.json$/,
|
|
256
|
+
);
|
|
257
|
+
|
|
258
|
+
await post(run({ runtimes: ["droid"], agent, conversation: { ...conversation, prompt: "carry on" } }));
|
|
259
|
+
assert.equal((await nextReply()).text, "done");
|
|
260
|
+
assert.match(lastCall()[2]!, /--session-id s-issue-1$/);
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
test("a run with no branch gets a scratch worktree for its conversation", async () => {
|
|
264
|
+
await post(run({ worktree: undefined, conversation: { id: "github:acme/api#2", prompt: "look" } }));
|
|
265
|
+
assert.equal((await nextReply()).text, "done");
|
|
266
|
+
const scratch = join(data, "scratch", "github-acme-api-2");
|
|
267
|
+
assert.equal(lastCall()[0], scratch);
|
|
268
|
+
assert.ok(existsSync(join(scratch, ".factory", "prompt.md")));
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
test("a failed run replies with the error", async () => {
|
|
272
|
+
await post(run({ conversation: { id: "github:acme/api#3", prompt: "fail now" } }));
|
|
273
|
+
assert.match((await nextReply()).text, /The run failed: Claude Code exited with code 1: it broke/);
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
test("after the container sleeps, a run restores its worktree and its conversation's session", async () => {
|
|
277
|
+
const conversation = { id: "github:acme/api#9", prompt: "edit the code" };
|
|
278
|
+
await post(run({ worktree: { branch: "issue-9" }, conversation }));
|
|
279
|
+
assert.equal((await nextReply()).text, "done");
|
|
280
|
+
assert.ok(state.has("worktrees/issue-9.bundle"));
|
|
281
|
+
assert.ok(state.has("sessions/github-acme-api-9.json"));
|
|
282
|
+
|
|
283
|
+
await sleepContainer();
|
|
284
|
+
await startRunner();
|
|
285
|
+
|
|
286
|
+
await post(run({ worktree: { branch: "issue-9" }, conversation: { ...conversation, prompt: "carry on" } }));
|
|
287
|
+
assert.equal((await nextReply()).text, "done");
|
|
288
|
+
const worktree = join(data, "worktrees", "acme-api", "issue-9");
|
|
289
|
+
assert.match(lastCall()[2]!, /--resume s-issue-9/);
|
|
290
|
+
assert.equal(sh(worktree, "branch", "--show-current"), "issue-9");
|
|
291
|
+
assert.equal(sh(worktree, "log", "-1", "--format=%s"), "local work");
|
|
292
|
+
assert.equal(readFileSync(join(worktree, "notes.txt"), "utf8"), "draft\n");
|
|
293
|
+
assert.equal(sh(worktree, "status", "--porcelain"), "D README.md\n?? notes.txt");
|
|
294
|
+
const transcript = join(home, ".claude", "projects", "-p-issue-9", "s-issue-9.jsonl");
|
|
295
|
+
assert.equal(readFileSync(transcript, "utf8"), "edit the code\ncarry on\n");
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
test("a snapshot that can't be restored leaves a note, and the run starts from the remote", async () => {
|
|
299
|
+
state.set("worktrees/issue-10.bundle", Buffer.from("not a bundle"));
|
|
300
|
+
await post(run({ worktree: { branch: "issue-10" }, conversation: { id: "github:acme/api#10", prompt: "go" } }));
|
|
301
|
+
const reply = await nextReply();
|
|
302
|
+
assert.match(reply.text, /^done\n\n> Factory couldn't restore this worktree's saved state/);
|
|
303
|
+
assert.equal(sh(join(data, "worktrees", "acme-api", "issue-10"), "log", "-1", "--format=%s"), "init");
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
test("during a long run, the runner refreshes the tokens that gh and git read", async () => {
|
|
307
|
+
freshToken = "fresh-token";
|
|
308
|
+
tokenRequests.length = 0;
|
|
309
|
+
await post(run({ conversation: { id: "github:acme/api#11", prompt: "wait for it" } }));
|
|
310
|
+
assert.equal((await nextReply()).text, "done");
|
|
311
|
+
const lines = readFileSync(calls, "utf8").trim().split("\n").slice(-4);
|
|
312
|
+
assert.equal(lines[1], "fresh-token");
|
|
313
|
+
assert.equal(lines[3], "password=fresh-token");
|
|
314
|
+
const { ticket, signature } = tokenRequests[0]!;
|
|
315
|
+
assert.deepEqual([ticket.repo, ticket.container, signature], ["acme/api", "dev", "token-sig"]);
|
|
316
|
+
assert.equal(readFileSync(join(data, "github", "code"), "utf8"), "fresh-token");
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
test("status counts the runs that are running or queued", async () => {
|
|
320
|
+
const response = await fetch(`http://127.0.0.1:${port}/status`);
|
|
321
|
+
assert.deepEqual(await response.json(), { active: 0 });
|
|
322
|
+
});
|
package/README.md
DELETED