@notation/factory 0.1.3 → 0.1.6
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/hub.ts +2 -0
- package/contracts/index.ts +1 -0
- package/contracts/outpost.ts +10 -2
- package/contracts/router.ts +3 -0
- package/contracts/runner.ts +57 -0
- package/deployer/collect.ts +2 -2
- package/deployer/deploy.test.ts +5 -5
- package/deployer/index.ts +6 -6
- package/deployer/sdk.gen.ts +1 -1
- package/deployer/sdk.ts +1 -0
- package/implementations/container.ts +7 -1
- package/implementations/outpost.ts +1 -1
- package/package.json +1 -1
- package/runner/index.ts +62 -115
- package/runner/runner.test.ts +66 -0
|
@@ -9,6 +9,11 @@ const containerConfig = v.object({
|
|
|
9
9
|
* default image, which has Claude Code and Droid.
|
|
10
10
|
*/
|
|
11
11
|
image: v.optional(v.string()),
|
|
12
|
+
/**
|
|
13
|
+
* The size of the machine, in the provider's names, such as Cloudflare's
|
|
14
|
+
* `standard-2`. Without it, the provider picks its default.
|
|
15
|
+
*/
|
|
16
|
+
instanceType: v.optional(v.string()),
|
|
12
17
|
runtimes: v.optional(
|
|
13
18
|
v.array(
|
|
14
19
|
v.custom<Runtime>(
|
|
@@ -42,7 +47,7 @@ export class Container extends OutpostGroup<ContainerConfig> {
|
|
|
42
47
|
readonly policies: PolicyContract[];
|
|
43
48
|
|
|
44
49
|
constructor(id: string, { policies = [], ...config }: ContainerOptions) {
|
|
45
|
-
const { image, runtimes, files } = v.parse(containerConfig, config);
|
|
50
|
+
const { image, instanceType, runtimes, files } = v.parse(containerConfig, config);
|
|
46
51
|
const seen = new Set<string>();
|
|
47
52
|
for (const runtime of runtimes) {
|
|
48
53
|
if (seen.has(runtime.id)) {
|
|
@@ -57,6 +62,7 @@ export class Container extends OutpostGroup<ContainerConfig> {
|
|
|
57
62
|
containers: {
|
|
58
63
|
[id]: {
|
|
59
64
|
...(image && { image }),
|
|
65
|
+
...(instanceType && { instanceType }),
|
|
60
66
|
runtimes: runtimes.map((r) => r.id),
|
|
61
67
|
policies: policies.map((p) => p.id),
|
|
62
68
|
files,
|
|
@@ -23,7 +23,7 @@ const currentOutpost = (): Outpost => {
|
|
|
23
23
|
const collection = getActiveResourceCollection();
|
|
24
24
|
if (!collection) {
|
|
25
25
|
throw new Error(
|
|
26
|
-
"Declare outpost resources in .factory/
|
|
26
|
+
"Declare outpost resources in .factory/infra.ts, which the deployer evaluates with Notation",
|
|
27
27
|
);
|
|
28
28
|
}
|
|
29
29
|
let outpost = outposts.get(collection);
|
package/package.json
CHANGED
package/runner/index.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
2
3
|
import { existsSync } from "node:fs";
|
|
3
4
|
import { copyFile, mkdir, mkdtemp, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
4
5
|
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
|
5
6
|
import { homedir, tmpdir } from "node:os";
|
|
6
7
|
import { dirname, join, normalize, resolve } from "node:path";
|
|
8
|
+
import { pathToFileURL } from "node:url";
|
|
9
|
+
import type { CodeHostRunner, RuntimeRunner } from "../contracts/runner.ts";
|
|
7
10
|
import type { Relay, Run, TokenRequest, Tokens } from "../router/run.ts";
|
|
8
11
|
|
|
9
12
|
const PORT = Number(process.env.FACTORY_RUNNER_PORT ?? 8080);
|
|
@@ -11,11 +14,13 @@ const DATA = process.env.FACTORY_DATA ?? "/data";
|
|
|
11
14
|
const HOME = homedir();
|
|
12
15
|
/** The container's state store, which outlives the container. The provider answers this host. */
|
|
13
16
|
const STATE_URL = process.env.FACTORY_STATE_URL ?? "http://state.factory";
|
|
17
|
+
/** Where the hub serves its plugins' runner modules. The provider answers this host. */
|
|
18
|
+
const MODULES_URL = process.env.FACTORY_MODULES_URL ?? "http://runner.factory";
|
|
14
19
|
|
|
15
20
|
/** How often a run asks the router for new tokens. GitHub's installation tokens last an hour. */
|
|
16
21
|
const TOKEN_REFRESH_MS = Number(process.env.FACTORY_TOKEN_REFRESH_MS ?? 30 * 60 * 1000);
|
|
17
22
|
|
|
18
|
-
/**
|
|
23
|
+
/** First on the agent's PATH, for the code host's wrappers, such as a `gh` that reads its token from `FACTORY_TOKEN_FILE`. */
|
|
19
24
|
const BIN = join(DATA, "bin");
|
|
20
25
|
|
|
21
26
|
/** The longest a run's agent may take. */
|
|
@@ -70,17 +75,12 @@ const exec = (
|
|
|
70
75
|
});
|
|
71
76
|
});
|
|
72
77
|
|
|
73
|
-
/** Runs git, and returns its output. Throws with its stderr if it fails. */
|
|
78
|
+
/** Runs git, and returns its output. Throws with its stderr if it fails. `auth` is the code host's options for this command only. */
|
|
74
79
|
const git = async (
|
|
75
80
|
args: string[],
|
|
76
|
-
options: { cwd?: string;
|
|
81
|
+
options: { cwd?: string; auth?: string[]; env?: Record<string, string | undefined> } = {},
|
|
77
82
|
) => {
|
|
78
|
-
|
|
79
|
-
// read it from the repo's config.
|
|
80
|
-
const auth = options.token
|
|
81
|
-
? ["-c", `http.extraHeader=Authorization: Basic ${Buffer.from(`x-access-token:${options.token}`).toString("base64")}`]
|
|
82
|
-
: [];
|
|
83
|
-
const result = await exec("git", [...auth, ...args], {
|
|
83
|
+
const result = await exec("git", [...(options.auth ?? []), ...args], {
|
|
84
84
|
cwd: options.cwd,
|
|
85
85
|
env: options.env && { ...process.env, ...options.env },
|
|
86
86
|
});
|
|
@@ -115,16 +115,18 @@ const slug = (value: string) => value.toLowerCase().replace(/[^a-z0-9._-]+/g, "-
|
|
|
115
115
|
* time. Its remote branches are `origin/*`. Returns its path and the
|
|
116
116
|
* default branch.
|
|
117
117
|
*/
|
|
118
|
-
const fetchRepo = (run: Run) =>
|
|
118
|
+
const fetchRepo = (run: Run, codeHost: CodeHostRunner) =>
|
|
119
119
|
repoLock(run.repo, async () => {
|
|
120
120
|
const path = join(DATA, "repos", `${slug(run.repo)}.git`);
|
|
121
|
-
|
|
121
|
+
// The clone token goes in this command's options, so the agent can't
|
|
122
|
+
// read it from the repo's config.
|
|
123
|
+
const auth = codeHost.gitAuth(run.cloneToken);
|
|
122
124
|
if (!existsSync(path)) {
|
|
123
125
|
await mkdir(dirname(path), { recursive: true });
|
|
124
|
-
await git(["clone", "--bare",
|
|
126
|
+
await git(["clone", "--bare", codeHost.cloneUrl(run.repo), path], { auth });
|
|
125
127
|
await git(["config", "remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*"], { cwd: path });
|
|
126
128
|
}
|
|
127
|
-
await git(["fetch", "--prune", "origin"], { cwd: path,
|
|
129
|
+
await git(["fetch", "--prune", "origin"], { cwd: path, auth });
|
|
128
130
|
const head = await git(["symbolic-ref", "--short", "HEAD"], { cwd: path });
|
|
129
131
|
return { path, defaultBranch: head };
|
|
130
132
|
});
|
|
@@ -320,74 +322,49 @@ const readSession = async (run: Run): Promise<Session | undefined> => {
|
|
|
320
322
|
|
|
321
323
|
const sessionKey = (run: Run) => `sessions/${slug(run.conversation.id)}/${slug(run.agent.id)}`;
|
|
322
324
|
|
|
323
|
-
/**
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
};
|
|
338
|
-
|
|
339
|
-
const claude: RuntimeAdapter = {
|
|
340
|
-
command: "claude",
|
|
341
|
-
name: "Claude Code",
|
|
342
|
-
transcripts: join(HOME, ".claude", "projects"),
|
|
343
|
-
args: async (run, cwd) => {
|
|
344
|
-
const { agent } = run;
|
|
345
|
-
const args = ["-p", run.conversation.prompt, "--output-format", "json", "--dangerously-skip-permissions"];
|
|
346
|
-
if (typeof agent.model === "string") args.push("--model", agent.model);
|
|
347
|
-
if (typeof agent.effort === "string") args.push("--effort", agent.effort);
|
|
348
|
-
args.push("--append-system-prompt", await systemPrompt(run, cwd));
|
|
349
|
-
if (agent.settings) args.push("--settings", JSON.stringify(agent.settings));
|
|
350
|
-
return args;
|
|
351
|
-
},
|
|
352
|
-
resume: (sessionId) => ["--resume", sessionId],
|
|
353
|
-
env: { DISABLE_AUTOUPDATER: "1" },
|
|
325
|
+
/** Imports the hub's runner module at `path`, once for each version of it. */
|
|
326
|
+
const loadModule = async <T>(path: string): Promise<T> => {
|
|
327
|
+
const response = await fetch(`${MODULES_URL}/${path}`);
|
|
328
|
+
if (response.status === 404) throw new Error(`The hub has no runner module ${path}.`);
|
|
329
|
+
if (!response.ok) throw new Error(`The hub refused the runner module ${path} with status ${response.status}.`);
|
|
330
|
+
const source = await response.text();
|
|
331
|
+
// A file per version, since an import of the same path returns the module it imported first.
|
|
332
|
+
const file = join(DATA, "modules", `${createHash("sha256").update(source).digest("hex").slice(0, 16)}.ts`);
|
|
333
|
+
if (!existsSync(file)) {
|
|
334
|
+
await mkdir(dirname(file), { recursive: true });
|
|
335
|
+
await writeFile(`${file}.new`, source);
|
|
336
|
+
await rename(`${file}.new`, file);
|
|
337
|
+
}
|
|
338
|
+
return ((await import(pathToFileURL(file).href)) as { default: T }).default;
|
|
354
339
|
};
|
|
355
340
|
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
if (agent.settings) {
|
|
371
|
-
// `--settings` takes a file, which a run merges for that run only.
|
|
372
|
-
const path = join(DATA, "agents", agent.id, "settings.json");
|
|
373
|
-
await mkdir(dirname(path), { recursive: true });
|
|
374
|
-
await writeFile(path, `${JSON.stringify(agent.settings, null, 2)}\n`);
|
|
375
|
-
args.push("--settings", path);
|
|
376
|
-
}
|
|
377
|
-
return args;
|
|
378
|
-
},
|
|
379
|
-
resume: (sessionId) => ["--session-id", sessionId],
|
|
341
|
+
/** The code host's setups that have run, by module, so concurrent runs don't write git's config at once. */
|
|
342
|
+
const codeHostSetups = new Map<CodeHostRunner, Promise<void>>();
|
|
343
|
+
|
|
344
|
+
/** The code host's runner module, set up. */
|
|
345
|
+
const loadCodeHost = async () => {
|
|
346
|
+
const codeHost = await loadModule<CodeHostRunner>("code-host.ts");
|
|
347
|
+
let setup = codeHostSetups.get(codeHost);
|
|
348
|
+
if (!setup) {
|
|
349
|
+
setup = codeHost.setup({ bin: BIN });
|
|
350
|
+
codeHostSetups.set(codeHost, setup);
|
|
351
|
+
setup.catch(() => codeHostSetups.delete(codeHost));
|
|
352
|
+
}
|
|
353
|
+
await setup;
|
|
354
|
+
return codeHost;
|
|
380
355
|
};
|
|
381
356
|
|
|
382
|
-
|
|
383
|
-
|
|
357
|
+
const loadRuntime = (id: string) =>
|
|
358
|
+
loadModule<RuntimeRunner>(`runtimes/${encodeURIComponent(id)}.ts`).catch((error) => {
|
|
359
|
+
throw new Error(`The runner can't run agents of the runtime ${id}: ${message(error)}`);
|
|
360
|
+
});
|
|
384
361
|
|
|
385
362
|
/**
|
|
386
363
|
* Saves the conversation's session to the state store: its transcript
|
|
387
364
|
* files, as a tarball of their paths under the runtime's transcripts
|
|
388
365
|
* directory, and then the session's id and working directory.
|
|
389
366
|
*/
|
|
390
|
-
const saveSession = async (run: Run, adapter:
|
|
367
|
+
const saveSession = async (run: Run, adapter: RuntimeRunner) => {
|
|
391
368
|
const session = await readSession(run);
|
|
392
369
|
if (!session) return;
|
|
393
370
|
const paths: string[] = [];
|
|
@@ -410,7 +387,7 @@ const saveSession = async (run: Run, adapter: RuntimeAdapter) => {
|
|
|
410
387
|
};
|
|
411
388
|
|
|
412
389
|
/** Restores the conversation's session from the state store, if this container doesn't have it. */
|
|
413
|
-
const restoreSession = async (run: Run, adapter:
|
|
390
|
+
const restoreSession = async (run: Run, adapter: RuntimeRunner) => {
|
|
414
391
|
if (existsSync(sessionPath(run))) return;
|
|
415
392
|
const session = await getState(`${sessionKey(run)}.json`);
|
|
416
393
|
if (!session) return;
|
|
@@ -432,8 +409,8 @@ const restoreSession = async (run: Run, adapter: RuntimeAdapter) => {
|
|
|
432
409
|
* final message. It resumes the conversation's session if the session ran
|
|
433
410
|
* in the same worktree.
|
|
434
411
|
*/
|
|
435
|
-
const runAgent = async (adapter:
|
|
436
|
-
const args = await adapter.args(run, cwd);
|
|
412
|
+
const runAgent = async (adapter: RuntimeRunner, run: Run, cwd: string) => {
|
|
413
|
+
const args = await adapter.args(run, { cwd, systemPrompt: await systemPrompt(run, cwd), dataDir: DATA });
|
|
437
414
|
const session = await readSession(run);
|
|
438
415
|
if (session?.cwd === cwd) args.push(...adapter.resume(session.id));
|
|
439
416
|
|
|
@@ -442,15 +419,12 @@ const runAgent = async (adapter: RuntimeAdapter, run: Run, cwd: string) => {
|
|
|
442
419
|
env: { ...process.env, PATH: `${BIN}:${process.env.PATH}`, FACTORY_TOKEN_FILE: tokenFile(run), ...adapter.env },
|
|
443
420
|
timeout: RUN_TIMEOUT_MS,
|
|
444
421
|
});
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
output = JSON.parse(result.stdout);
|
|
448
|
-
} catch {}
|
|
449
|
-
if (output?.session_id) {
|
|
422
|
+
const output = adapter.parse(result.stdout);
|
|
423
|
+
if (output?.sessionId) {
|
|
450
424
|
await mkdir(dirname(sessionPath(run)), { recursive: true });
|
|
451
|
-
await writeFile(sessionPath(run), JSON.stringify({ id: output.
|
|
425
|
+
await writeFile(sessionPath(run), JSON.stringify({ id: output.sessionId, cwd } satisfies Session));
|
|
452
426
|
}
|
|
453
|
-
if (result.code !== 0 || !output || output.
|
|
427
|
+
if (result.code !== 0 || !output || output.isError) {
|
|
454
428
|
const detail = output?.result ?? (result.stderr.trim() || result.stdout.trim()).slice(-4000);
|
|
455
429
|
throw new Error(`${adapter.name} exited with code ${result.code}: ${detail}`);
|
|
456
430
|
}
|
|
@@ -479,7 +453,8 @@ let active = 0;
|
|
|
479
453
|
|
|
480
454
|
/**
|
|
481
455
|
* Runs one run:
|
|
482
|
-
* 1.
|
|
456
|
+
* 1. Imports the runtime's and the code host's runner modules, updates the
|
|
457
|
+
* repo's clone, and checks out the run's worktree.
|
|
483
458
|
* 2. Restores the conversation's session if this container doesn't have it.
|
|
484
459
|
* 3. Writes the container's files and the policies' tokens.
|
|
485
460
|
* 4. Runs the agent in the worktree, and has the router mint new tokens
|
|
@@ -493,16 +468,16 @@ const execute = async (run: Run) => {
|
|
|
493
468
|
log({ run: run.id, repo: run.repo, trigger: run.trigger, worktree: run.worktree?.branch ?? "scratch", state: "started" });
|
|
494
469
|
const worktree = worktreeOf(run);
|
|
495
470
|
const notes: string[] = [];
|
|
496
|
-
|
|
471
|
+
let adapter: RuntimeRunner | undefined;
|
|
497
472
|
let checkedOut = false;
|
|
498
473
|
let text: string;
|
|
499
474
|
try {
|
|
500
|
-
|
|
475
|
+
adapter = await loadRuntime(run.agent.runtime);
|
|
501
476
|
await assertCommand(adapter.command, adapter.name);
|
|
502
|
-
const repo = await fetchRepo(run);
|
|
477
|
+
const repo = await fetchRepo(run, await loadCodeHost());
|
|
503
478
|
await checkout(run, repo, worktree, notes);
|
|
504
479
|
checkedOut = true;
|
|
505
|
-
await restoreSession(run, adapter).catch((error) =>
|
|
480
|
+
await restoreSession(run, adapter).catch((error: unknown) =>
|
|
506
481
|
notes.push(`Factory couldn't restore this conversation's session, so the agent started a new one: ${message(error)}`),
|
|
507
482
|
);
|
|
508
483
|
await writeFiles(run, worktree.path);
|
|
@@ -561,37 +536,10 @@ const readBody = async (request: IncomingMessage) => {
|
|
|
561
536
|
return Buffer.concat(chunks).toString("utf8");
|
|
562
537
|
};
|
|
563
538
|
|
|
564
|
-
/**
|
|
565
|
-
* Git signs commits as the hub, and pushes with the token in the file that
|
|
566
|
-
* `FACTORY_TOKEN_FILE` names. Each write locks the config file, so they
|
|
567
|
-
* run in turn.
|
|
568
|
-
*/
|
|
539
|
+
/** Git signs commits as the hub. Each write locks the config file, so they run in turn. */
|
|
569
540
|
const configureGit = async () => {
|
|
570
541
|
await git(["config", "--global", "user.name", "Notation Factory"]);
|
|
571
542
|
await git(["config", "--global", "user.email", "notation-factory@users.noreply.github.com"]);
|
|
572
|
-
await git([
|
|
573
|
-
"config",
|
|
574
|
-
"--global",
|
|
575
|
-
"credential.https://github.com.helper",
|
|
576
|
-
'!f() { test -n "$FACTORY_TOKEN_FILE" || exit 0; echo username=x-access-token; echo "password=$(cat "$FACTORY_TOKEN_FILE")"; }; f',
|
|
577
|
-
]);
|
|
578
|
-
};
|
|
579
|
-
|
|
580
|
-
/**
|
|
581
|
-
* Puts a `gh` in `/data/bin` that runs the installed `gh` with the token in
|
|
582
|
-
* `FACTORY_TOKEN_FILE`. `GH_TOKEN` would keep the first token after the
|
|
583
|
-
* router refreshes it.
|
|
584
|
-
*/
|
|
585
|
-
const installGh = async () => {
|
|
586
|
-
const found = await exec("sh", ["-c", "command -v gh"]);
|
|
587
|
-
const gh = found.stdout.trim();
|
|
588
|
-
if (found.code !== 0 || !gh) return;
|
|
589
|
-
await mkdir(BIN, { recursive: true });
|
|
590
|
-
const script = `#!/bin/sh
|
|
591
|
-
if [ -n "$FACTORY_TOKEN_FILE" ]; then GH_TOKEN="$(cat "$FACTORY_TOKEN_FILE")"; export GH_TOKEN; fi
|
|
592
|
-
exec ${JSON.stringify(gh)} "$@"
|
|
593
|
-
`;
|
|
594
|
-
await writeFile(join(BIN, "gh"), script, { mode: 0o755 });
|
|
595
543
|
};
|
|
596
544
|
|
|
597
545
|
/**
|
|
@@ -626,5 +574,4 @@ process.on("SIGTERM", () => {
|
|
|
626
574
|
});
|
|
627
575
|
|
|
628
576
|
await configureGit();
|
|
629
|
-
await installGh();
|
|
630
577
|
server.listen(PORT, () => log({ state: "listening", port: PORT }));
|
package/runner/runner.test.ts
CHANGED
|
@@ -42,6 +42,15 @@ esac
|
|
|
42
42
|
echo "{\\"result\\":\\"done\\",\\"session_id\\":\\"$session\\"}"
|
|
43
43
|
`;
|
|
44
44
|
|
|
45
|
+
/** A fake Cursor Agent: like the fake Claude Code, but for Cursor's CLI. */
|
|
46
|
+
const FAKE_CURSOR = `#!/bin/sh
|
|
47
|
+
printf '%s\\n' "$(pwd)" "$(gh)" "$(printf '%s' "$*" | tr '\\n' ' ')" >> "${calls}"
|
|
48
|
+
session="s-$(basename "$(pwd)")"
|
|
49
|
+
mkdir -p "$HOME/.cursor/chats/-p-$(basename "$(pwd)")"
|
|
50
|
+
echo "$*" >> "$HOME/.cursor/chats/-p-$(basename "$(pwd)")/$session"
|
|
51
|
+
echo "{\\"result\\":\\"done\\",\\"session_id\\":\\"$session\\"}"
|
|
52
|
+
`;
|
|
53
|
+
|
|
45
54
|
/** A fake Droid: like the fake Claude Code, but for droid's CLI. */
|
|
46
55
|
const FAKE_DROID = `#!/bin/sh
|
|
47
56
|
prompt="$2"
|
|
@@ -52,6 +61,14 @@ echo "$prompt" >> "$HOME/.factory/sessions/-p-$(basename "$(pwd)")/$session.json
|
|
|
52
61
|
echo "{\\"result\\":\\"done\\",\\"session_id\\":\\"$session\\"}"
|
|
53
62
|
`;
|
|
54
63
|
|
|
64
|
+
/** The hub's runner modules, by the path the runner fetches them at. */
|
|
65
|
+
const MODULES: Record<string, string> = {
|
|
66
|
+
"runtimes/claude.ts": join(import.meta.dirname, "../../claude/runtime/runner.ts"),
|
|
67
|
+
"runtimes/cursor.ts": join(import.meta.dirname, "../../cursor/runtime/runner.ts"),
|
|
68
|
+
"runtimes/droid.ts": join(import.meta.dirname, "../../droid/runtime/runner.ts"),
|
|
69
|
+
"code-host.ts": join(import.meta.dirname, "../../github/runner/index.ts"),
|
|
70
|
+
};
|
|
71
|
+
|
|
55
72
|
/** A fake gh, which prints the token it gets. */
|
|
56
73
|
const FAKE_GH = `#!/bin/sh
|
|
57
74
|
echo "$GH_TOKEN"
|
|
@@ -83,6 +100,7 @@ before(async () => {
|
|
|
83
100
|
mkdirSync(bin);
|
|
84
101
|
mkdirSync(home);
|
|
85
102
|
writeFileSync(join(bin, "claude"), FAKE_CLAUDE, { mode: 0o755 });
|
|
103
|
+
writeFileSync(join(bin, "agent"), FAKE_CURSOR, { mode: 0o755 });
|
|
86
104
|
writeFileSync(join(bin, "droid"), FAKE_DROID, { mode: 0o755 });
|
|
87
105
|
writeFileSync(join(bin, "gh"), FAKE_GH, { mode: 0o755 });
|
|
88
106
|
|
|
@@ -102,6 +120,11 @@ before(async () => {
|
|
|
102
120
|
request.on("data", (chunk) => chunks.push(chunk));
|
|
103
121
|
request.on("end", () => {
|
|
104
122
|
const { pathname } = new URL(request.url!, "http://test");
|
|
123
|
+
if (pathname.startsWith("/modules/")) {
|
|
124
|
+
const file = MODULES[pathname.slice("/modules/".length)];
|
|
125
|
+
response.statusCode = file ? 200 : 404;
|
|
126
|
+
return response.end(file && readFileSync(file));
|
|
127
|
+
}
|
|
105
128
|
if (pathname.startsWith("/state/")) {
|
|
106
129
|
const key = pathname.slice("/state/".length);
|
|
107
130
|
if (request.method === "PUT") {
|
|
@@ -143,6 +166,7 @@ const startRunner = async () => {
|
|
|
143
166
|
FACTORY_DATA: data,
|
|
144
167
|
FACTORY_RUNNER_PORT: String(port),
|
|
145
168
|
FACTORY_STATE_URL: `${serverUrl()}/state`,
|
|
169
|
+
FACTORY_MODULES_URL: `${serverUrl()}/modules`,
|
|
146
170
|
FACTORY_TOKEN_REFRESH_MS: "300",
|
|
147
171
|
// Clones of github.com come from the local remotes.
|
|
148
172
|
GIT_CONFIG_COUNT: "1",
|
|
@@ -227,6 +251,43 @@ test("a later run in the same conversation and worktree resumes its session", as
|
|
|
227
251
|
assert.match(lastCall()[2]!, /--resume s-issue-1/);
|
|
228
252
|
});
|
|
229
253
|
|
|
254
|
+
test("a cursor run invokes agent in print mode, and resumes its session", async () => {
|
|
255
|
+
const agent = {
|
|
256
|
+
id: "coder",
|
|
257
|
+
runtime: "cursor",
|
|
258
|
+
model: "composer-2.5",
|
|
259
|
+
systemPrompt: "prompt.md",
|
|
260
|
+
settings: { approvalMode: "unrestricted" },
|
|
261
|
+
};
|
|
262
|
+
const conversation = { id: "github:acme/api#30", prompt: "cursor it" };
|
|
263
|
+
await post(run({ runtimes: ["cursor"], agent, conversation }));
|
|
264
|
+
assert.equal((await nextReply()).text, "done");
|
|
265
|
+
const [cwd, token, args] = lastCall();
|
|
266
|
+
assert.equal(cwd, join(data, "worktrees", "acme-api", "issue-1"));
|
|
267
|
+
assert.equal(token, "push-token");
|
|
268
|
+
assert.match(
|
|
269
|
+
args!,
|
|
270
|
+
/^-p --output-format json --force --trust --sandbox disabled --disable-auto-update You're running headless, .* Be brief\.\s+cursor it --model composer-2\.5$/,
|
|
271
|
+
);
|
|
272
|
+
assert.equal(JSON.parse(readFileSync(join(home, ".cursor", "cli-config.json"), "utf8")).approvalMode, "unrestricted");
|
|
273
|
+
|
|
274
|
+
await post(run({ runtimes: ["cursor"], agent, conversation: { ...conversation, prompt: "carry on" } }));
|
|
275
|
+
assert.equal((await nextReply()).text, "done");
|
|
276
|
+
assert.match(lastCall()[2]!, /--resume s-issue-1$/);
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
test("a cursor agent in plan mode passes --mode plan", async () => {
|
|
280
|
+
await post(
|
|
281
|
+
run({
|
|
282
|
+
runtimes: ["cursor"],
|
|
283
|
+
agent: { id: "planner", runtime: "cursor", model: "composer-2.5", mode: "plan" },
|
|
284
|
+
conversation: { id: "github:acme/api#31", prompt: "plan it" },
|
|
285
|
+
}),
|
|
286
|
+
);
|
|
287
|
+
assert.equal((await nextReply()).text, "done");
|
|
288
|
+
assert.match(lastCall()[2]!, / --model composer-2\.5 --mode plan$/);
|
|
289
|
+
});
|
|
290
|
+
|
|
230
291
|
test("a droid run invokes droid exec, skipping permissions without an autonomy level", async () => {
|
|
231
292
|
await post(
|
|
232
293
|
run({
|
|
@@ -285,6 +346,11 @@ test("a run with no branch gets a scratch worktree for its conversation", async
|
|
|
285
346
|
assert.ok(existsSync(join(scratch, ".factory", "prompt.md")));
|
|
286
347
|
});
|
|
287
348
|
|
|
349
|
+
test("a run of a runtime that the hub has no runner module for replies with the error", async () => {
|
|
350
|
+
await post(run({ agent: { id: "coder", runtime: "codex" }, conversation: { id: "github:acme/api#4", prompt: "go" } }));
|
|
351
|
+
assert.match((await nextReply()).text, /The run failed: The runner can't run agents of the runtime codex: The hub has no runner module runtimes\/codex\.ts\./);
|
|
352
|
+
});
|
|
353
|
+
|
|
288
354
|
test("a failed run replies with the error", async () => {
|
|
289
355
|
await post(run({ conversation: { id: "github:acme/api#3", prompt: "fail now" } }));
|
|
290
356
|
assert.match((await nextReply()).text, /The run failed: Claude Code exited with code 1: it broke/);
|