@notation/factory 0.1.2 → 0.1.5

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@notation/factory",
3
- "version": "0.1.2",
3
+ "version": "0.1.5",
4
4
  "author": "Daniel Grant",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -33,9 +33,9 @@
33
33
  "access": "public"
34
34
  },
35
35
  "dependencies": {
36
- "@notation/core": "0.28.0",
37
- "@notation/resource": "0.28.0",
38
- "@notation/std": "0.28.0",
36
+ "@notation/core": "0.28.1",
37
+ "@notation/resource": "0.28.1",
38
+ "@notation/std": "0.28.1",
39
39
  "sucrase": "^3.35.1",
40
40
  "valibot": "^1.1.0"
41
41
  }
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
- /** Where the runner puts a `gh` that reads its token from `FACTORY_TOKEN_FILE`. */
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; token?: string; env?: Record<string, string | undefined> } = {},
81
+ options: { cwd?: string; auth?: string[]; env?: Record<string, string | undefined> } = {},
77
82
  ) => {
78
- // The token goes in a header for this command only, so the agent can't
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
- const url = `https://github.com/${run.repo}.git`;
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", url, path], { token: run.cloneToken });
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, token: run.cloneToken });
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
  });
@@ -306,7 +308,9 @@ const refreshTokens = async (run: Run) => {
306
308
 
307
309
  type Session = { id: string; cwd: string };
308
310
 
309
- const sessionPath = (run: Run) => join(DATA, "sessions", `${slug(run.conversation.id)}.json`);
311
+ // Each agent in a conversation has its own session, since one runtime
312
+ // can't resume another's.
313
+ const sessionPath = (run: Run) => join(DATA, "sessions", slug(run.conversation.id), `${slug(run.agent.id)}.json`);
310
314
 
311
315
  const readSession = async (run: Run): Promise<Session | undefined> => {
312
316
  try {
@@ -316,76 +320,51 @@ const readSession = async (run: Run): Promise<Session | undefined> => {
316
320
  }
317
321
  };
318
322
 
319
- const sessionKey = (run: Run) => `sessions/${slug(run.conversation.id)}`;
320
-
321
- /** A runtime the runner runs: the CLI a container's image installs, and how a run invokes it. */
322
- type RuntimeAdapter = {
323
- /** The command the image must have. */
324
- command: string;
325
- /** The CLI's name, for errors. */
326
- name: string;
327
- /** Where the CLI keeps its sessions' transcripts, in a directory per working directory. */
328
- transcripts: string;
329
- /** The CLI's arguments for a run. */
330
- args: (run: Run, cwd: string) => Promise<string[]>;
331
- /** The arguments that resume a session. */
332
- resume: (sessionId: string) => string[];
333
- /** Extra environment for the CLI. */
334
- env?: Record<string, string>;
335
- };
336
-
337
- const claude: RuntimeAdapter = {
338
- command: "claude",
339
- name: "Claude Code",
340
- transcripts: join(HOME, ".claude", "projects"),
341
- args: async (run, cwd) => {
342
- const { agent } = run;
343
- const args = ["-p", run.conversation.prompt, "--output-format", "json", "--dangerously-skip-permissions"];
344
- if (typeof agent.model === "string") args.push("--model", agent.model);
345
- if (typeof agent.effort === "string") args.push("--effort", agent.effort);
346
- args.push("--append-system-prompt", await systemPrompt(run, cwd));
347
- if (agent.settings) args.push("--settings", JSON.stringify(agent.settings));
348
- return args;
349
- },
350
- resume: (sessionId) => ["--resume", sessionId],
351
- env: { DISABLE_AUTOUPDATER: "1" },
323
+ const sessionKey = (run: Run) => `sessions/${slug(run.conversation.id)}/${slug(run.agent.id)}`;
324
+
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;
352
339
  };
353
340
 
354
- const droid: RuntimeAdapter = {
355
- command: "droid",
356
- name: "Droid",
357
- transcripts: join(HOME, ".factory", "sessions"),
358
- args: async (run, cwd) => {
359
- const { agent } = run;
360
- const args = ["exec", run.conversation.prompt, "--output-format", "json"];
361
- // A container is disposable, so a run skips every permission prompt
362
- // unless the agent sets an autonomy level.
363
- if (typeof agent.autonomy === "string") args.push("--auto", agent.autonomy);
364
- else args.push("--skip-permissions-unsafe");
365
- if (typeof agent.model === "string") args.push("--model", agent.model);
366
- if (typeof agent.effort === "string") args.push("--reasoning-effort", agent.effort);
367
- args.push("--append-system-prompt", await systemPrompt(run, cwd));
368
- if (agent.settings) {
369
- // `--settings` takes a file, which a run merges for that run only.
370
- const path = join(DATA, "agents", agent.id, "settings.json");
371
- await mkdir(dirname(path), { recursive: true });
372
- await writeFile(path, `${JSON.stringify(agent.settings, null, 2)}\n`);
373
- args.push("--settings", path);
374
- }
375
- return args;
376
- },
377
- 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;
378
355
  };
379
356
 
380
- /** The runtimes the runner runs, by id. */
381
- const runtimes: Record<string, RuntimeAdapter> = { claude, droid };
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
+ });
382
361
 
383
362
  /**
384
363
  * Saves the conversation's session to the state store: its transcript
385
364
  * files, as a tarball of their paths under the runtime's transcripts
386
365
  * directory, and then the session's id and working directory.
387
366
  */
388
- const saveSession = async (run: Run, adapter: RuntimeAdapter) => {
367
+ const saveSession = async (run: Run, adapter: RuntimeRunner) => {
389
368
  const session = await readSession(run);
390
369
  if (!session) return;
391
370
  const paths: string[] = [];
@@ -408,7 +387,7 @@ const saveSession = async (run: Run, adapter: RuntimeAdapter) => {
408
387
  };
409
388
 
410
389
  /** Restores the conversation's session from the state store, if this container doesn't have it. */
411
- const restoreSession = async (run: Run, adapter: RuntimeAdapter) => {
390
+ const restoreSession = async (run: Run, adapter: RuntimeRunner) => {
412
391
  if (existsSync(sessionPath(run))) return;
413
392
  const session = await getState(`${sessionKey(run)}.json`);
414
393
  if (!session) return;
@@ -430,8 +409,8 @@ const restoreSession = async (run: Run, adapter: RuntimeAdapter) => {
430
409
  * final message. It resumes the conversation's session if the session ran
431
410
  * in the same worktree.
432
411
  */
433
- const runAgent = async (adapter: RuntimeAdapter, run: Run, cwd: string) => {
434
- 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 });
435
414
  const session = await readSession(run);
436
415
  if (session?.cwd === cwd) args.push(...adapter.resume(session.id));
437
416
 
@@ -440,15 +419,12 @@ const runAgent = async (adapter: RuntimeAdapter, run: Run, cwd: string) => {
440
419
  env: { ...process.env, PATH: `${BIN}:${process.env.PATH}`, FACTORY_TOKEN_FILE: tokenFile(run), ...adapter.env },
441
420
  timeout: RUN_TIMEOUT_MS,
442
421
  });
443
- let output: { result?: string; is_error?: boolean; session_id?: string } | undefined;
444
- try {
445
- output = JSON.parse(result.stdout);
446
- } catch {}
447
- if (output?.session_id) {
422
+ const output = adapter.parse(result.stdout);
423
+ if (output?.sessionId) {
448
424
  await mkdir(dirname(sessionPath(run)), { recursive: true });
449
- await writeFile(sessionPath(run), JSON.stringify({ id: output.session_id, cwd } satisfies Session));
425
+ await writeFile(sessionPath(run), JSON.stringify({ id: output.sessionId, cwd } satisfies Session));
450
426
  }
451
- if (result.code !== 0 || !output || output.is_error) {
427
+ if (result.code !== 0 || !output || output.isError) {
452
428
  const detail = output?.result ?? (result.stderr.trim() || result.stdout.trim()).slice(-4000);
453
429
  throw new Error(`${adapter.name} exited with code ${result.code}: ${detail}`);
454
430
  }
@@ -477,7 +453,8 @@ let active = 0;
477
453
 
478
454
  /**
479
455
  * Runs one run:
480
- * 1. Updates the repo's clone, and checks out the run's worktree.
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.
481
458
  * 2. Restores the conversation's session if this container doesn't have it.
482
459
  * 3. Writes the container's files and the policies' tokens.
483
460
  * 4. Runs the agent in the worktree, and has the router mint new tokens
@@ -491,16 +468,16 @@ const execute = async (run: Run) => {
491
468
  log({ run: run.id, repo: run.repo, trigger: run.trigger, worktree: run.worktree?.branch ?? "scratch", state: "started" });
492
469
  const worktree = worktreeOf(run);
493
470
  const notes: string[] = [];
494
- const adapter = runtimes[run.agent.runtime];
471
+ let adapter: RuntimeRunner | undefined;
495
472
  let checkedOut = false;
496
473
  let text: string;
497
474
  try {
498
- if (!adapter) throw new Error(`The runner can't run agents of the runtime ${run.agent.runtime}.`);
475
+ adapter = await loadRuntime(run.agent.runtime);
499
476
  await assertCommand(adapter.command, adapter.name);
500
- const repo = await fetchRepo(run);
477
+ const repo = await fetchRepo(run, await loadCodeHost());
501
478
  await checkout(run, repo, worktree, notes);
502
479
  checkedOut = true;
503
- await restoreSession(run, adapter).catch((error) =>
480
+ await restoreSession(run, adapter).catch((error: unknown) =>
504
481
  notes.push(`Factory couldn't restore this conversation's session, so the agent started a new one: ${message(error)}`),
505
482
  );
506
483
  await writeFiles(run, worktree.path);
@@ -559,37 +536,10 @@ const readBody = async (request: IncomingMessage) => {
559
536
  return Buffer.concat(chunks).toString("utf8");
560
537
  };
561
538
 
562
- /**
563
- * Git signs commits as the hub, and pushes with the token in the file that
564
- * `FACTORY_TOKEN_FILE` names. Each write locks the config file, so they
565
- * run in turn.
566
- */
539
+ /** Git signs commits as the hub. Each write locks the config file, so they run in turn. */
567
540
  const configureGit = async () => {
568
541
  await git(["config", "--global", "user.name", "Notation Factory"]);
569
542
  await git(["config", "--global", "user.email", "notation-factory@users.noreply.github.com"]);
570
- await git([
571
- "config",
572
- "--global",
573
- "credential.https://github.com.helper",
574
- '!f() { test -n "$FACTORY_TOKEN_FILE" || exit 0; echo username=x-access-token; echo "password=$(cat "$FACTORY_TOKEN_FILE")"; }; f',
575
- ]);
576
- };
577
-
578
- /**
579
- * Puts a `gh` in `/data/bin` that runs the installed `gh` with the token in
580
- * `FACTORY_TOKEN_FILE`. `GH_TOKEN` would keep the first token after the
581
- * router refreshes it.
582
- */
583
- const installGh = async () => {
584
- const found = await exec("sh", ["-c", "command -v gh"]);
585
- const gh = found.stdout.trim();
586
- if (found.code !== 0 || !gh) return;
587
- await mkdir(BIN, { recursive: true });
588
- const script = `#!/bin/sh
589
- if [ -n "$FACTORY_TOKEN_FILE" ]; then GH_TOKEN="$(cat "$FACTORY_TOKEN_FILE")"; export GH_TOKEN; fi
590
- exec ${JSON.stringify(gh)} "$@"
591
- `;
592
- await writeFile(join(BIN, "gh"), script, { mode: 0o755 });
593
543
  };
594
544
 
595
545
  /**
@@ -624,5 +574,4 @@ process.on("SIGTERM", () => {
624
574
  });
625
575
 
626
576
  await configureGit();
627
- await installGh();
628
577
  server.listen(PORT, () => log({ state: "listening", port: PORT }));
@@ -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({
@@ -260,6 +321,23 @@ test("a droid agent with autonomy runs with --auto, and resumes its session", as
260
321
  assert.match(lastCall()[2]!, /--session-id s-issue-1$/);
261
322
  });
262
323
 
324
+ test("agents in the same conversation and worktree keep their own sessions", async () => {
325
+ const conversation = { id: "github:acme/api#22", prompt: "go" };
326
+ await post(run({ conversation }));
327
+ assert.equal((await nextReply()).text, "done");
328
+ const droidAgent = { id: "droid-coder", runtime: "droid" };
329
+ await post(run({ runtimes: ["droid"], agent: droidAgent, conversation }));
330
+ assert.equal((await nextReply()).text, "done");
331
+ assert.doesNotMatch(lastCall()[2]!, /--session-id/);
332
+
333
+ await post(run({ conversation: { ...conversation, prompt: "carry on" } }));
334
+ assert.equal((await nextReply()).text, "done");
335
+ assert.match(lastCall()[2]!, /--resume s-issue-1$/);
336
+ await post(run({ runtimes: ["droid"], agent: droidAgent, conversation: { ...conversation, prompt: "carry on" } }));
337
+ assert.equal((await nextReply()).text, "done");
338
+ assert.match(lastCall()[2]!, /--session-id s-issue-1$/);
339
+ });
340
+
263
341
  test("a run with no branch gets a scratch worktree for its conversation", async () => {
264
342
  await post(run({ worktree: undefined, conversation: { id: "github:acme/api#2", prompt: "look" } }));
265
343
  assert.equal((await nextReply()).text, "done");
@@ -268,6 +346,11 @@ test("a run with no branch gets a scratch worktree for its conversation", async
268
346
  assert.ok(existsSync(join(scratch, ".factory", "prompt.md")));
269
347
  });
270
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
+
271
354
  test("a failed run replies with the error", async () => {
272
355
  await post(run({ conversation: { id: "github:acme/api#3", prompt: "fail now" } }));
273
356
  assert.match((await nextReply()).text, /The run failed: Claude Code exited with code 1: it broke/);
@@ -278,7 +361,7 @@ test("after the container sleeps, a run restores its worktree and its conversati
278
361
  await post(run({ worktree: { branch: "issue-9" }, conversation }));
279
362
  assert.equal((await nextReply()).text, "done");
280
363
  assert.ok(state.has("worktrees/issue-9.bundle"));
281
- assert.ok(state.has("sessions/github-acme-api-9.json"));
364
+ assert.ok(state.has("sessions/github-acme-api-9/coder.json"));
282
365
 
283
366
  await sleepContainer();
284
367
  await startRunner();