Public: anyone can read this; the crew can change it.

src/crew/runner.ts and src/crew/autonomy.ts split into modules of one concept each, with the same behaviour #16785

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/15368-src-crew-runner-ts-and-src-crew-autonomy → main 0 commits fork

  • Merged. torque/15368-src-crew-runner-ts-and-src-crew-autonomy was merged into main as 5c1611e.

Review

Sign in to review this change.
17 files changed +817 −750
src/actions/runs.ts +1 −1
@@ -17,7 +17,7 @@ import { mayView, mayViewId } from "../core/sealed.ts";
1717 import { requireVerified } from "./verify.ts";
1818 import { requireAbility } from "./roles.ts";
1919 import type { App } from "../app.ts";
20 import { steerRun } from "../crew/runner.ts";
20 import { steerRun } from "../crew/steer.ts";
2121 import { getIssueById, getIssuesByIds } from "../core/issues.ts";
2222 import { addComment } from "./issues.ts";
2323 import { getAppByRepo } from "../core/apps.ts";
src/crew/clone.ts added +305
@@ -0,0 +1,305 @@
1 /**
2 * The agent's fork and its clone: made on first use, on the branch, matching what the forge holds.
3 */
4 import type { CrewOptions } from "./runner.ts";
5
6 import {
7 existsSync,
8 mkdirSync,
9 readdirSync,
10 renameSync,
11 writeFileSync,
12 } from "node:fs";
13 import { rm } from "node:fs/promises";
14 import { join } from "node:path";
15 import type { App } from "../app.ts";
16 import { forkRepo, sealedForkFor } from "../actions/repos.ts";
17 import { type Agent } from "../core/agents.ts";
18 import { getForkOf, type Repo } from "../core/repos.ts";
19 import { runGit } from "../git/env.ts";
20 import { foreignGitDir, runCloneGit } from "./clone_git.ts";
21 import { installPinHook } from "./pin_hook.ts";
22 import { cloneWithMirror } from "./mirror.ts";
23 import { resolveOid } from "../git/merge.ts";
24 import { repoDir } from "../git/repos.ts";
25 import { err, ok, type Result } from "../kernel/result.ts";
26 import { clearStaleLocks, lockedOut } from "./locks.ts";
27
28 /**
29 * How long a run's fetch or push may take. Two minutes killed every fetch of the forge's own
30 * repository on 2026-11-20, when its transfers ran near 120 KB/s: a slow transfer that would
31 * finish is worth more than a run that dies and is started again.
32 */
33 export const GIT_TRANSFER_MS = 10 * 60_000;
34
35 /**
36 * The agent's fork of the repository it is working on, made on first use.
37 * One fork per agent per repository; a name already taken by something
38 * else of the agent's gets the owner's name in front.
39 */
40 export async function forkFor(
41 app: App,
42 agent: Agent,
43 repo: Repo,
44 write: (line: string) => void,
45 /** The task is a sealed report: its work goes in a private repository (`core/sealed.ts`). */
46 sealed = false,
47 ): Promise<Result<Repo, string>> {
48 if (sealed) {
49 const made = await sealedForkFor(app, agent.user, repo);
50 if (!made.ok)
51 return err(
52 `could not make a private place for ${repo.ownerName}/${repo.name}'s sealed work: ${made.error}`,
53 );
54 return ok(made.value);
55 }
56 const existing = getForkOf(app.db, agent.user.id, repo.id);
57 if (existing !== undefined) return ok(existing);
58 let made = await forkRepo(app, agent.user, repo);
59 if (!made.ok && made.error === "name_taken")
60 made = await forkRepo(
61 app,
62 agent.user,
63 repo,
64 `${repo.ownerName}-${repo.name}`,
65 );
66 if (!made.ok)
67 return err(
68 `could not fork ${repo.ownerName}/${repo.name} for ${agent.user.username}: ${String(made.error)}`,
69 );
70 write(
71 `forked ${repo.ownerName}/${repo.name} as ${made.value.ownerName}/${made.value.name}`,
72 );
73 return ok(made.value);
74 }
75
76 /** Whether `dir` is empty, or a work tree git can read: its `.git` resolves. */
77 export async function readsAsClone(
78 dir: string,
79 env: Record<string, string>,
80 ): Promise<boolean> {
81 if (readdirSync(dir).length === 0) return true;
82 // A `.git` that is a link, a gitfile or borrows another repository is
83 // not the clone's own (#14747): moved aside, never run in.
84 if (foreignGitDir(dir) !== undefined) return false;
85 // Its own `.git`, named: never a repository above it that git would find.
86 const top = await runGit(
87 ["--git-dir", join(dir, ".git"), "rev-parse", "--git-dir"],
88 { cwd: dir, env },
89 );
90 return top.ok;
91 }
92
93 /**
94 * A clone on `branch`, matching what the forge holds. The clone is the
95 * triangle git was built for: it fetches from the repository and pushes to
96 * the agent's fork, so a plain `git push` lands where the agent may write
97 * and nowhere else.
98 */
99 export async function prepareClone(
100 app: App,
101 options: CrewOptions,
102 repo: Repo,
103 fork: Repo,
104 branch: string,
105 dir: string,
106 env: Record<string, string>,
107 write: (line: string) => void,
108 signal: AbortSignal,
109 keep = false,
110 fresh = false,
111 ): Promise<{ ok: true } | { ok: false; error: string }> {
112 // Two addresses for one forge. The forge itself clones and fetches over
113 // `localUrl`, on this machine. The agent's remotes carry `forgeUrl`, the
114 // forge as the agent is told it: inside the shell sandbox, `localhost` is
115 // the sandbox's own and reaches nothing, while a named host goes out
116 // through the sandbox's proxy — so a remote on the local address would
117 // leave `git push` nowhere to go, and the only way to push would be to
118 // leave the sandbox, which is not a way.
119 const url = `${options.localUrl}/${repo.ownerName}/${repo.name}.git`;
120 const forkUrl = `${options.localUrl}/${fork.ownerName}/${fork.name}.git`;
121 const agentUrl = `${options.forgeUrl}/${repo.ownerName}/${repo.name}.git`;
122 const agentForkUrl = `${options.forgeUrl}/${fork.ownerName}/${fork.name}.git`;
123 if (signal.aborted) return { ok: false, error: "cancelled" };
124 // A kept clone git no longer reads as one — a clone a network blip cut
125 // short — is moved aside, never reused, and cloned afresh (#6263).
126 if (existsSync(dir) && !(await readsAsClone(dir, env))) {
127 const aside = `${dir}.broken-${Date.now()}`;
128 renameSync(dir, aside);
129 write(
130 `the kept clone is not a git repository; moved aside to ${aside}, cloning afresh`,
131 );
132 return prepareClone(
133 app,
134 options,
135 repo,
136 fork,
137 branch,
138 dir,
139 env,
140 write,
141 signal,
142 false,
143 true,
144 );
145 }
146 if (!existsSync(join(dir, ".git"))) {
147 mkdirSync(dir, { recursive: true });
148 write(`cloning ${repo.ownerName}/${repo.name}`);
149 const cloned = await cloneWithMirror({
150 dataDir: app.config.dataDir,
151 repoId: repo.id,
152 url,
153 dir,
154 env,
155 signal,
156 });
157 if (!cloned.ok)
158 return {
159 ok: false,
160 error: `clone failed: ${cloned.error.stderr.slice(0, 200)}`,
161 };
162 } else {
163 // A kept clone may carry the locks of a run the forge cut off. This run
164 // owns the clone now, so a lock a minute old is nobody's.
165 clearStaleLocks(dir, write);
166 const fetched = await runCloneGit(
167 dir,
168 [
169 "fetch",
170 "--quiet",
171 "--prune",
172 url,
173 `+refs/heads/*:refs/remotes/origin/*`,
174 ],
175 { env, timeoutMs: GIT_TRANSFER_MS },
176 );
177 if (!fetched.ok)
178 return {
179 ok: false,
180 error: `fetch failed: ${fetched.error.stderr.slice(0, 200)}`,
181 };
182 // The remotes are the agent's, set again on every visit — a clone from
183 // before the forge changed where they point (a kept clone resumed after
184 // a release) would otherwise push to an address that is no longer the
185 // forge's for the sandbox.
186 await runCloneGit(dir, ["config", "remote.origin.url", agentUrl], { env });
187 await runCloneGit(dir, ["config", "remote.origin.pushurl", agentForkUrl], {
188 env,
189 });
190 // A paused run resumes in the tree it left — its uncommitted work is
191 // part of the session that is about to continue — so long as the clone
192 // is still on its branch.
193 if (keep) {
194 const head = await runCloneGit(dir, ["rev-parse", "--abbrev-ref", "HEAD"], {
195 env,
196 });
197 if (head.ok && head.value.trim() === branch) {
198 write(`clone kept as it was left, on ${branch}`);
199 return { ok: true };
200 }
201 }
202 }
203 await runCloneGit(dir, ["config", "remote.origin.url", agentUrl], { env });
204 await runCloneGit(dir, ["config", "remote.origin.pushurl", agentForkUrl], {
205 env,
206 });
207 // The branch, if it exists, lives in the fork; its tracking ref is fetched
208 // from there so the checkout starts at what the agent last pushed.
209 const forkBare = repoDir(app.reposRoot, fork.ownerName, fork.name);
210 const remote = await resolveOid(forkBare, `refs/heads/${branch}`);
211 if (remote !== undefined) {
212 const fetched = await runCloneGit(
213 dir,
214 [
215 "fetch",
216 "--quiet",
217 forkUrl,
218 `+refs/heads/${branch}:refs/remotes/origin/${branch}`,
219 ],
220 { env, timeoutMs: GIT_TRANSFER_MS },
221 );
222 if (!fetched.ok)
223 return {
224 ok: false,
225 error: `fetch from the fork failed: ${fetched.error.stderr.slice(0, 200)}`,
226 };
227 }
228 const start =
229 remote === undefined ? `origin/${repo.defaultBranch}` : `origin/${branch}`;
230 // A leftover from a cut-off run is discarded: the remote is truth.
231 await runCloneGit(dir, ["reset", "--quiet", "--hard"], { env });
232 await runCloneGit(dir, ["clean", "-fdq"], { env });
233 const checked = await runCloneGit(dir, ["checkout", "--quiet", "-B", branch, start], {
234 env,
235 });
236 if (!checked.ok && !fresh && lockedOut(checked.error.stderr)) {
237 // A lock too young to clear, or one the sweep missed: start over once
238 // from a fresh clone rather than failing the follow-up.
239 // Only when nothing would be lost: a cut-off run may hold commits that
240 // were never pushed, and those live nowhere else.
241 const unpushed = await runCloneGit(
242 dir,
243 ["rev-list", "--branches", "--not", "--remotes=origin"],
244 { env },
245 );
246 if (!unpushed.ok || unpushed.value.trim() !== "")
247 return {
248 ok: false,
249 error:
250 "checkout blocked by a git lock, and the kept clone holds commits that were never pushed; left as it is",
251 };
252 write("checkout blocked by a git lock; cloning afresh");
253 await rm(dir, { recursive: true, force: true });
254 return prepareClone(
255 app,
256 options,
257 repo,
258 fork,
259 branch,
260 dir,
261 env,
262 write,
263 signal,
264 false,
265 true,
266 );
267 }
268 if (!checked.ok)
269 return {
270 ok: false,
271 error: `checkout failed: ${checked.error.stderr.slice(0, 200)}`,
272 };
273 // The branch tracks its remote from the start, set here where git config
274 // is writable: inside the sandbox `.git/config` is not, so a plain
275 // `git push` must already know where to go.
276 await runCloneGit(dir, ["config", `branch.${branch}.remote`, "origin"], {
277 env,
278 });
279 await runCloneGit(dir, ["config", `branch.${branch}.merge`, `refs/heads/${branch}`], {
280 env,
281 });
282 // What a run leaves in its tree that is never the work: the temp
283 // directory a sandboxed shell keeps beside the code (`.tmp/`), with a
284 // test's data in it, and `node_modules/`. The wrap-up
285 // commits leftovers with `git add -A`, so the clone says so once, in its
286 // own exclude file — the repository's `.gitignore` is the repository's.
287 mkdirSync(join(dir, ".git", "info"), { recursive: true });
288 writeFileSync(join(dir, ".git", "info", "exclude"), CLONE_EXCLUDES);
289 // A push that adds a migration commits its pin first (#6938).
290 installPinHook(dir);
291 write(
292 remote === undefined
293 ? `branch ${branch} from ${repo.defaultBranch}`
294 : `branch ${branch} at ${remote.slice(0, 7)}`,
295 );
296 return { ok: true };
297 }
298
299 /** Never the work, in any repository the crew clones: git's own exclude syntax. */
300 export const CLONE_EXCLUDES = [
301 "# written by the forge for every crew clone",
302 ".tmp/",
303 "node_modules/",
304 "",
305 ].join("\n");
src/crew/conversation.ts +2 −1
@@ -57,7 +57,8 @@ import { liveDelta, liveEnd, liveReset, liveSaid } from "./conversation_live.ts"
5757 import { callBook } from "./conversation_calls.ts";
5858 import { isRateLimited, takeLimit, whenText } from "./limits.ts";
5959 import { turnBudget } from "./model_access.ts";
60 import { credentialEnv, holdModelCredential, listenForSteer, steerable, steerRun } from "./runner.ts";
60 import { credentialEnv, holdModelCredential } from "./credential_env.ts";
61 import { listenForSteer, steerable, steerRun } from "./steer.ts";
6162 import { sandboxPolicy } from "./sandbox.ts";
6263 import { sandboxRefusal } from "./sandbox_policy.ts";
6364
src/crew/credential_env.ts added +37
@@ -0,0 +1,37 @@
1 /** The credential a run's environment carries, and its values held for redaction. */
2
3 import { holdValues } from "../kernel/log.ts";
4 import { credentialEnvOf, type Pick } from "../core/subscriptions.ts";
5 import { isGatewayAddress, ownEnv } from "./runner_env.ts";
6 import { fundedEnv } from "../spawn/funding.ts";
7
8 /**
9 * Hold the secret values of a model credential's environment for redaction
10 * under `key`, until `releaseValues(key)`: the one way a child that carries
11 * the credential (a crew run, a conversation turn, a one-shot) keeps what it
12 * says of it out of what the forge keeps. The gateway's address is not a
13 * secret, and an empty or very short value is not held. Answers what is held.
14 */
15 export function holdModelCredential(key: string, env: Record<string, string>): string[] {
16 const secrets = Object.entries(env)
17 .filter(([name, value]) => !isGatewayAddress(name) && value.length >= 4)
18 .map(([, value]) => value);
19 holdValues(key, secrets);
20 return secrets;
21 }
22
23 /**
24 * The credential a run's environment carries: the picked account's token
25 * under the variable Claude Code reads it from (plus a gateway base URL when
26 * the account has one), or — with nothing granted — whatever the forge
27 * itself was started with.
28 */
29 export function credentialEnv(picked: Pick, dataDir?: string): Record<string, string> {
30 if (picked.kind === "ready") return credentialEnvOf(picked);
31 // A forge its parent funds (#10484): with no account of its own, the crew calls the model through
32 // the parent. "none" reaches here only under an owner's grant (an org's, #10991), which is the
33 // forge's account too.
34 const lent = (picked.kind === "env" || picked.kind === "none") && dataDir !== undefined ? fundedEnv(dataDir) : undefined;
35 if (lent !== undefined) return lent;
36 return ownEnv();
37 }
src/crew/dispatch.ts +1 −1
@@ -146,8 +146,8 @@ import {
146146 workdirFor,
147147 type CrewOptions,
148148 type Pause,
149 steerRun,
150149 } from "./runner.ts";
150 import { steerRun } from "./steer.ts";
151151 import { STALE_AFTER_MS } from "../runs/lease.ts";
152152 import { stoppedMark } from "../spawn/stopped.ts";
153153 import { abortAgentRun } from "./running.ts";
src/crew/land_work.ts added +203
@@ -0,0 +1,203 @@
1 /** After the agent stops: land what it committed. */
2 import type { CrewOptions } from "./runner.ts";
3 import { GIT_TRANSFER_MS } from "./clone.ts";
4
5 import type { App } from "../app.ts";
6 import { addComment } from "../actions/issues.ts";
7 import { openPull } from "../actions/pulls.ts";
8 import { fillPull, isEarlyBody, pullOfBranch, trailerFor } from "./early.ts";
9 import { type Agent } from "../core/agents.ts";
10 import { type Issue } from "../core/issues.ts";
11 import { type Pull } from "../core/pulls.ts";
12 import { type Repo } from "../core/repos.ts";
13 import { runCloneGit } from "./clone_git.ts";
14 import { Hops } from "./hops.ts";
15 import { aheadCount, contentOnBase, resolveOid } from "../git/merge.ts";
16 import { historyHolds, scrubTree } from "./leak.ts";
17
18 /**
19 * After the agent stops: push what it committed if it did not, open the
20 * pull if there is none, and report on the conversation — the agent's
21 * last message, and the forge's note under it when there is one.
22 */
23 export async function landWork(
24 app: App,
25 options: CrewOptions,
26 repo: Repo,
27 agent: Agent,
28 issue: Issue,
29 pull: Pull | undefined,
30 fork: Repo,
31 branch: string,
32 dir: string,
33 forkBare: string,
34 bare: string,
35 env: Record<string, string>,
36 message: string,
37 note: string | undefined,
38 write: (line: string) => void,
39 granted: readonly string[] = [],
40 variantGroup: string | null = null,
41 hops?: Hops,
42 ): Promise<{ pushed: boolean; summary: string }> {
43 // A model may echo a granted value into a file; the tree is scrubbed
44 // before the forge commits it, and the agent's own commits are searched
45 // before anything is pushed.
46 const scrubbed = await scrubTree(dir, granted, env);
47 if (scrubbed.length > 0)
48 write(`scrubbed a granted secret value from ${scrubbed.join(", ")}`);
49 // Work left in the tree is committed on the agent's behalf: a proposal a
50 // person can read beats an edit nobody sees. The summary says it happened.
51 const status = await runCloneGit(dir, ["status", "--porcelain"], { env });
52 let committedForIt = false;
53 if (status.ok && status.value.trim() !== "") {
54 const subject =
55 message
56 .split("\n")
57 .find((l) => l.trim() !== "")
58 ?.trim() ?? issue.title;
59 await runCloneGit(dir, ["add", "-A"], { env });
60 const commit = await runCloneGit(
61 dir,
62 [
63 "commit",
64 "--quiet",
65 // The clone's hooks are the agent's (#14747); `runCloneGit` also
66 // points `core.hooksPath` at nothing.
67 "--no-verify",
68 "-m",
69 subject.slice(0, 200),
70 "-m",
71 `Work by @${agent.user.username} on #${issue.number}, committed by the forge.`,
72 ],
73 { env },
74 );
75 committedForIt = commit.ok;
76 write(
77 commit.ok
78 ? "committed the agent's uncommitted changes"
79 : `could not commit leftover changes: ${commit.error.stderr.slice(0, 200)}`,
80 );
81 }
82 const head = await runCloneGit(dir, ["rev-parse", "--verify", "HEAD"], {
83 env,
84 });
85 const local = head.ok ? head.value.trim() : undefined;
86 // The branch is the fork's; the base it is measured against is the
87 // repository's own default branch.
88 let remote = await resolveOid(forkBare, `refs/heads/${branch}`);
89 const base = await resolveOid(bare, `refs/heads/${repo.defaultBranch}`);
90 if (local !== undefined && local !== remote) {
91 // Ahead of what the forge holds: the branch if it exists there, the
92 // default branch otherwise — a fresh branch at the base tip is nothing.
93 const against = remote ?? base;
94 const ahead =
95 against === undefined ? 1 : await aheadCount(dir, against, local);
96 if (
97 ahead > 0 &&
98 (await historyHolds(
99 dir,
100 against === undefined ? "HEAD" : `${against}..HEAD`,
101 granted,
102 env,
103 ))
104 ) {
105 write("refused: a granted secret value is in the commits; not pushed");
106 return {
107 pushed: false,
108 summary:
109 "refused to push: a secret this run held is in its commits; nothing pushed",
110 };
111 }
112 if (ahead > 0) {
113 write(
114 `pushing ${branch} (${ahead} commit${ahead === 1 ? "" : "s"} the agent did not push)`,
115 );
116 // The forge pushes for the agent over its own local address — the
117 // clone's `origin` carries the public one, for the agent inside the
118 // sandbox (`prepareClone`), and this push is the forge's, not the
119 // agent's. The branch already tracks `origin`, set there.
120 const pushed = await runCloneGit(
121 dir,
122 [
123 "push",
124 "--quiet",
125 // The clone's hooks are the agent's sandbox's, never the forge's.
126 "--no-verify",
127 `${options.localUrl}/${fork.ownerName}/${fork.name}.git`,
128 `${branch}:${branch}`,
129 ],
130 { env, timeoutMs: GIT_TRANSFER_MS },
131 );
132 if (!pushed.ok)
133 write(`push refused: ${pushed.error.stderr.slice(0, 300)}`);
134 else hops?.record("push", options.localUrl);
135 remote = await resolveOid(forkBare, `refs/heads/${branch}`);
136 }
137 }
138 // Counted in the fork, which sees the repository's objects through its
139 // alternates and its own on top.
140 const proposed =
141 remote !== undefined && base !== undefined
142 ? (await contentOnBase(forkBare, base, remote))
143 ? 0
144 : await aheadCount(forkBare, base, remote)
145 : 0;
146 const report = [message.trim(), note]
147 .filter((part): part is string => part !== undefined && part !== "")
148 .join("\n\n");
149
150 if (proposed === 0) {
151 write(
152 "nothing to propose: the branch has no commits beyond the default branch",
153 );
154 if (report !== "" && pull === undefined)
155 addComment(app, agent.user, repo, issue, report);
156 else if (report !== "" && pull !== undefined)
157 addComment(app, agent.user, repo, pull, report);
158 const first = report.split("\n").find((l) => l.trim() !== "") ?? "";
159 return {
160 pushed: false,
161 summary:
162 first === ""
163 ? "no changes pushed"
164 : `no changes pushed: ${first.slice(0, 200)}`,
165 };
166 }
167
168 const existing = pull ?? pullOfBranch(app, repo, fork, branch);
169 if (existing !== undefined) {
170 // A pull this run opened at its first push is still the run's opening.
171 const openedByRun = isEarlyBody(existing.body);
172 fillPull(app, agent, repo, existing, issue, report);
173 if (report !== "") addComment(app, agent.user, repo, existing, report);
174 return {
175 pushed: true,
176 summary: `${openedByRun ? "opened" : "updated"} pull #${existing.number} (${remote?.slice(0, 7)})${committedForIt ? ", committing its leftover changes" : ""}`,
177 };
178 }
179 // No pull to update and yet the task is one: the pull it continues was
180 // merged, and this one follows it rather than closing it.
181 const trailer = trailerFor(issue);
182 const body = `${report === "" ? "" : `${report}\n\n`}${trailer}`;
183 const opened = await openPull(app, agent.user, repo, {
184 title: issue.title,
185 body,
186 baseBranch: repo.defaultBranch,
187 headBranch: branch,
188 headRepo: fork,
189 ...(variantGroup === null ? {} : { variantGroup }),
190 });
191 if (!opened.ok) {
192 write(`could not open the pull: ${JSON.stringify(opened.error)}`);
193 return {
194 pushed: true,
195 summary: `pushed ${branch} but could not open a pull (${String(opened.error)})`,
196 };
197 }
198 write(`opened pull #${opened.value.number}`);
199 return {
200 pushed: true,
201 summary: `opened pull #${opened.value.number}${committedForIt ? ", committing its leftover changes" : ""}`,
202 };
203 }
src/crew/meter.ts added +185
@@ -0,0 +1,185 @@
1 /**
2 * What a run spends: its outcome, its meter, and the usage ledger lines written as it goes and when
3 * it ends.
4 */
5
6 import { storedText } from "../kernel/blocked.ts";
7 import type { App } from "../app.ts";
8 import { crewRole } from "../core/agents.ts";
9 import { type Run } from "../core/runs.ts";
10 import { grantLeft } from "../core/model_grant.ts";
11 import { noteLowWallet } from "../core/wallet.ts";
12 import { dailyLeft } from "../core/account_ceiling.ts";
13 import {
14 recordUsage,
15 type UsageKind,
16 type UsageOutcome,
17 } from "../core/usage.ts";
18
19 import { createLog } from "../kernel/log.ts";
20
21 const log = createLog("crew");
22
23 export type Outcome =
24 | {
25 readonly state: "ok" | "failed";
26 readonly summary: string;
27 /** When a run the provider cut short can go on (`interrupted.ts`). */
28 readonly resumesAt?: Date | undefined;
29 readonly sessionId?: string | undefined;
30 readonly costUsd?: number | undefined;
31 readonly turns?: number | undefined;
32 /** The context the session held at its end, in tokens (`resume.ts` reads it). */
33 readonly contextTokens?: number | undefined;
34 /** Whether the run moved its branch; undefined when it cannot say. */
35 readonly pushed?: boolean | undefined;
36 }
37 | {
38 /** The provider turned the run away; it goes on again at `resumeAt`. */
39 readonly state: "paused";
40 readonly summary: string;
41 readonly resumeAt: string;
42 readonly sessionId: string;
43 readonly costUsd: number;
44 /** Held before it began (a person's run goes first): the wait does not count as a pause. */
45 readonly keepAttempt?: boolean;
46 };
47
48 /**
49 * What a run spent that its outcome does not carry: the tokens of every
50 * model invocation it made, and the account it made them on. Filled by
51 * `work` as it goes, read once the run ends.
52 */
53 export interface Meter {
54 tokensIn: number;
55 tokensOut: number;
56 /** US dollars reported by invocations that have ended. */
57 costUsd: number;
58 subscriptionId: string | null;
59 kind: UsageKind;
60 /** When a `running` line was last written (epoch ms); 0 for never. */
61 reportedAt: number;
62 /** Ends the run. */
63 stop: () => void;
64 /** Set when the run spends an owner's capped grant: whose. */
65 grantOwner?: string;
66 /** Set on every run: whose daily ceiling it counts against. */
67 ceilingOwner?: string;
68 /** Why the run was stopped by its grant's cap, when it was. */
69 stoppedFor?: string;
70 }
71
72 /** What a run is for, as the ledger sums it: its reason, or its agent's role. */
73 export function usageKind(app: App, run: Run): UsageKind {
74 if (run.reason === "review") return "review";
75 if (run.reason === "check_failed") return "check";
76 if (
77 run.actorId !== null &&
78 crewRole(app.db, run.repoId, run.actorId) === "planner"
79 )
80 return "plan";
81 return "build";
82 }
83
84 /** How often a running session's spend is written and announced, at most. */
85 const LIVE_MS = 2_000;
86
87 /** Said on a run stopped at its grant's cap. */
88 const GRANT_SPENT =
89 storedText("This month's model grant is spent: the run stopped at the cap.", "an admin of this forge", "raise it");
90
91 /** Said on a run stopped at its account's daily ceiling. */
92 const DAILY_SPENT =
93 storedText("This account's daily ceiling is spent: the run stopped.", "an admin of this forge", "raise it");
94
95 /**
96 * A running session's spend so far, as its `running` line in the ledger,
97 * and a `usage.delta` on the outbox so the board and the Subscriptions page
98 * move within seconds. At most once per `LIVE_MS` unless `force`; the
99 * event carries only the run's id — spend is the owner's fact, and a
100 * reader who may see it reads it from the page.
101 */
102 export function meterLive(
103 app: App,
104 run: Run,
105 meter: Meter,
106 live: { tokensIn: number; tokensOut: number; costUsd: number },
107 started: number,
108 force: boolean,
109 ): void {
110 const now = Date.now();
111 if (!force && now - meter.reportedAt < LIVE_MS) return;
112 meter.reportedAt = now;
113 try {
114 recordUsage(app.db, {
115 runId: run.id,
116 repoId: run.repoId,
117 issueId: run.issueId,
118 agentId: run.actorId,
119 subscriptionId: meter.subscriptionId,
120 kind: meter.kind,
121 tokensIn: live.tokensIn,
122 tokensOut: live.tokensOut,
123 costUsd: live.costUsd,
124 wallMs: now - started,
125 outcome: "running",
126 at: new Date(now).toISOString(),
127 });
128 noteLowWallet(app.db, app.bus, run.repoId, new Date(now));
129 // The cap is checked on each spend tick, not only at the start.
130 if (meter.grantOwner !== undefined && meter.stoppedFor === undefined) {
131 const left = grantLeft(app.db, meter.grantOwner, new Date(now));
132 if (left !== undefined && left <= 0) {
133 meter.stoppedFor = GRANT_SPENT;
134 meter.stop();
135 }
136 }
137 if (meter.ceilingOwner !== undefined && meter.stoppedFor === undefined) {
138 const left = dailyLeft(app.db, meter.ceilingOwner, new Date(now));
139 if (left !== undefined && left <= 0) {
140 meter.stoppedFor = DAILY_SPENT;
141 meter.stop();
142 }
143 }
144 app.bus.append({
145 kind: "usage.delta",
146 repoId: run.repoId,
147 payload: { runId: run.id },
148 });
149 } catch (error) {
150 log.warn("live usage not recorded", { run: run.id, error: String(error) });
151 }
152 }
153
154 /** The run's line in the usage ledger (`core/usage.ts`), written once it ends. */
155 export function meterUsage(
156 app: App,
157 run: Run,
158 outcome: Outcome,
159 meter: Meter,
160 started: number,
161 ): void {
162 const ended = new Date();
163 const result: UsageOutcome = outcome.state;
164 // The ledger is bookkeeping: a line it cannot write (the repository
165 // deleted under the run) is logged, never the run's failure.
166 try {
167 recordUsage(app.db, {
168 runId: run.id,
169 repoId: run.repoId,
170 issueId: run.issueId,
171 agentId: run.actorId,
172 subscriptionId: meter.subscriptionId,
173 kind: meter.kind,
174 tokensIn: meter.tokensIn,
175 tokensOut: meter.tokensOut,
176 costUsd: outcome.costUsd ?? 0,
177 wallMs: ended.getTime() - started,
178 outcome: result,
179 at: ended.toISOString(),
180 });
181 noteLowWallet(app.db, app.bus, run.repoId, ended);
182 } catch (error) {
183 log.warn("usage not recorded", { run: run.id, error: String(error) });
184 }
185 }
src/crew/one_shot.ts +1 −1
@@ -17,7 +17,7 @@ import { runAccount } from "./runner_env.ts";
1717 import { conversationOptions, sessionsDir, turnDir } from "./conversation.ts";
1818 import { isRateLimited } from "./limits.ts";
1919 import { turnBudget } from "./model_access.ts";
20 import { credentialEnv, holdModelCredential } from "./runner.ts";
20 import { credentialEnv, holdModelCredential } from "./credential_env.ts";
2121 import { sandboxPolicy } from "./sandbox.ts";
2222 import { sandboxRefusal } from "./sandbox_policy.ts";
2323
src/crew/runner.ts +13 −734
@@ -12,36 +12,22 @@
1212 */
1313
1414 import { crewGrantedRepos } from "../core/origin_read_grant.ts";
15 import { storedText } from "../kernel/blocked.ts";
1615 import { failureBrief } from "./failure_brief.ts";
1716 import { holdsNaming } from "./desk_posts.ts";
1817 import { isStrangerPull } from "./stranger.ts";
1918 import { forgetMeasure, noteMeasure } from "../core/measure.ts";
2019 import { capacityEnv } from "../core/capacity.ts";
21 import {
22 existsSync,
23 mkdirSync,
24 readdirSync,
25 renameSync,
26 writeFileSync,
27 } from "node:fs";
20 import { existsSync } from "node:fs";
2821 import { rm } from "node:fs/promises";
2922 import { join } from "node:path";
3023 import type { App } from "../app.ts";
31 import { addComment } from "../actions/issues.ts";
3224 import { dropBrief } from "../actions/drop.ts";
3325 import { resolutionBrief } from "./proposal.ts";
34 import { openPull } from "../actions/pulls.ts";
3526 import {
36 fillPull,
37 isEarlyBody,
38 pullOfBranch,
39 trailerFor,
4027 watchForPull,
4128 type EarlyPull,
4229 type Ending,
4330 } from "./early.ts";
44 import { forkRepo, sealedForkFor } from "../actions/repos.ts";
4531 import { announceRun } from "../actions/runs.ts";
4632 import { Stopwatch } from "../apps/timing.ts";
4733 import { previewEnv } from "../apps/data.ts";
@@ -56,7 +42,7 @@ import {
5642 } from "./machines.ts";
5743 import { repoMachines } from "./machines_read.ts";
5844 import { authorsInRepoPull } from "./authors_pull.ts";
59 import { crewRole, getAgent, type Agent } from "../core/agents.ts";
45 import { crewRole, getAgent } from "../core/agents.ts";
6046 import { getAppByRepo, type AppRecord } from "../core/apps.ts";
6147 import {
6248 getIssue,
@@ -76,7 +62,6 @@ import { getPull, isFirstBuild, listPulls, type Pull, pullDir } from "../core/pu
7662 import {
7763 canWrite,
7864 forkParentFor,
79 getForkOf,
8065 getRepoById,
8166 type Repo,
8267 } from "../core/repos.ts";
@@ -101,16 +86,12 @@ import {
10186 import { mintRunToken } from "../core/run_token.ts";
10287 import { keepToken, refusedToken } from "./token_refused.ts";
10388 import { deleteToken } from "../core/tokens.ts";
104 import { runGit } from "../git/env.ts";
105 import { foreignGitDir, runCloneGit } from "./clone_git.ts";
106 import { installPinHook } from "./pin_hook.ts";
107 import { cloneWithMirror } from "./mirror.ts";
10889 import { Hops } from "./hops.ts";
10990 import { isSafeRef } from "../git/guard.ts";
11091 import { checkoutReviewHead, noteUnreviewed } from "./review_head.ts";
11192 import { runGitCapture } from "../git/env.ts";
11293 import { looksForEnv } from "../core/looks.ts";
113 import { aheadCount, contentOnBase, resolveOid } from "../git/merge.ts";
94 import { resolveOid } from "../git/merge.ts";
11495 import { repoDir } from "../git/repos.ts";
11596 import { bar } from "../cloud/gate.ts";
11697 import { declarationsOf } from "../cloud/declared.ts";
@@ -135,7 +116,6 @@ import {
135116 import { fetchSealedHead, SEALED_REMOTE, sealedHeadRepo } from "./sealed_head.ts";
136117 import { BUDGETS, BUDGET_PREFIX, RUN_THREW_PREFIX, budgetSummary } from "../kernel/budgets.ts";
137118 import { createLog, holdValues, redactValues, releaseValues } from "../kernel/log.ts";
138 import { err, ok, type Result } from "../kernel/result.ts";
139119 import { holdLease } from "../runs/lease.ts";
140120 import { appendRunLog } from "../runs/log.ts";
141121 import { cancelledLine } from "../runs/cancelled.ts";
@@ -171,7 +151,6 @@ import {
171151 takeLimit,
172152 whenText,
173153 } from "./limits.ts";
174 import { clearStaleLocks, lockedOut } from "./locks.ts";
175154 import { interruptedSummary, interruptionOf, landedPullOf, landedSummary, settleLanded } from "./interrupted.ts";
176155 import { lastWeekFor } from "./autonomy.ts";
177156 import { laterGate } from "./later.ts";
@@ -186,29 +165,25 @@ import { heldNow, stuckOf } from "./held.ts";
186165 import { resumeDecision } from "./resume.ts";
187166 import { owed } from "./team_share.ts";
188167 import { pauseReason } from "./pacing.ts";
189 import { grantLeft } from "../core/model_grant.ts";
190168 import { modelAccess } from "./model_access.ts";
191 import { capReached, noteLowWallet } from "../core/wallet.ts";
192 import { dailyLeft, reserveCeiling } from "../core/account_ceiling.ts";
169 import { capReached } from "../core/wallet.ts";
170 import { reserveCeiling } from "../core/account_ceiling.ts";
171 import { listenForSteer, stopSteering } from "./steer.ts";
172 import { credentialEnv, holdModelCredential } from "./credential_env.ts";
173 import { forkFor, prepareClone, GIT_TRANSFER_MS } from "./clone.ts";
174 import { landWork } from "./land_work.ts";
175 import { meterLive, meterUsage, usageKind, type Meter, type Outcome } from "./meter.ts";
193176 import {
194 credentialEnvOf,
195177 MIN_RUN_USD,
196178 pickSubscription,
197179 PLATFORM,
198 type Pick,
199180 } from "../core/subscriptions.ts";
200 import {
201 recordUsage,
202 type UsageKind,
203 type UsageOutcome,
204 } from "../core/usage.ts";
205181 import { trackAgentRun, untrackAgentRun } from "./running.ts";
206182 import { workBegins, workEnds } from "../runs/ending.ts";
207183 import { installCacheEnv, makeRunTmp, sandboxPolicy } from "./sandbox.ts";
208184 import { runGitAuth } from "./git_auth.ts";
209185 import { deviceKit, recordDeviceSessions, type DeviceKit } from "./devices.ts";
210186 import { grantSecrets, needsYou, parseDeclaration, ungrantedSentence, type Grant } from "./grant.ts";
211 import { historyHolds, scrubTree } from "./leak.ts";
212187 import {
213188 installCacheDir,
214189 installDependencies,
@@ -228,18 +203,11 @@ import {
228203 } from "./guard.ts";
229204 import { doorForRun, type GatewayDoor } from "./gateway_door.ts";
230205 import { passportEnv } from "./passport_env.ts";
231 import { isGatewayAddress, layerRunEnv, ownEnv, runAccount, sandboxTmpEnv } from "./runner_env.ts";
232 import { cappedByLent, fundedEnv, fundingOf, lentCost, lentCreditLeft, lentSpent, refreshFundingOnce, runEnded } from "../spawn/funding.ts";
206 import { layerRunEnv, runAccount, sandboxTmpEnv } from "./runner_env.ts";
207 import { cappedByLent, fundingOf, lentCost, lentCreditLeft, lentSpent, refreshFundingOnce, runEnded } from "../spawn/funding.ts";
233208
234209 const log = createLog("crew");
235210
236 /**
237 * How long a run's fetch or push may take. Two minutes killed every fetch of the forge's own
238 * repository on 2026-11-20, when its transfers ran near 120 KB/s: a slow transfer that would
239 * finish is worth more than a run that dies and is started again.
240 */
241 const GIT_TRANSFER_MS = 10 * 60_000;
242
243211 export interface CrewOptions {
244212 /** The forge's public URL — what the agent is told and links to. */
245213 readonly forgeUrl: string;
@@ -286,41 +254,6 @@ export interface CrewOptions {
286254
287255 export { crewRoot, workdirFor } from "./workdir.ts";
288256
289 /** Runs with an agent listening: what a person says reaches it next. */
290 const steering = new Map<string, (text: string) => boolean>();
291
292 /** A session starts listening to a run; the answer stops it. */
293 export function listenForSteer(
294 runId: string,
295 send: (text: string) => boolean,
296 ): () => void {
297 steering.set(runId, send);
298 return () => {
299 if (steering.get(runId) === send) steering.delete(runId);
300 };
301 }
302
303 /**
304 * Say something to an agent while its run goes. Written to the run's log
305 * as the person's line first, so the record holds it whether or not the
306 * agent gets to answer, then handed to the session as its next user turn.
307 * False when the run has no session listening: queued, ended, or between
308 * invocations.
309 */
310 /** Whether run `runId` can be handed words now: its input is open and listening. */
311 export const steerable = (runId: string): boolean => steering.has(runId);
312
313 export function steerRun(app: App, runId: string, text: string): boolean {
314 const send = steering.get(runId);
315 if (send === undefined) return false;
316 appendRunLog(
317 app.config.dataDir,
318 runId,
319 `you: ${text.replace(/\s*\n\s*/g, " ")}`,
320 );
321 return send(text);
322 }
323
324257 /** After the abort, how long a run gets to wind down before the forge ends it without it. */
325258 const OVERRUN_GRACE_MS = 5_000;
326259
@@ -604,7 +537,7 @@ async function runClaimed(
604537 clearTimeout(clock);
605538 clearTimeout(grace);
606539 untrackAgentRun(run.id);
607 steering.delete(run.id);
540 stopSteering(run.id);
608541 lease();
609542 }
610543 // Whatever the agent left running in its clone — a server it started to
@@ -870,170 +803,6 @@ async function reapOrphans(
870803 }
871804 }
872805
873 type Outcome =
874 | {
875 readonly state: "ok" | "failed";
876 readonly summary: string;
877 /** When a run the provider cut short can go on (`interrupted.ts`). */
878 readonly resumesAt?: Date | undefined;
879 readonly sessionId?: string | undefined;
880 readonly costUsd?: number | undefined;
881 readonly turns?: number | undefined;
882 /** The context the session held at its end, in tokens (`resume.ts` reads it). */
883 readonly contextTokens?: number | undefined;
884 /** Whether the run moved its branch; undefined when it cannot say. */
885 readonly pushed?: boolean | undefined;
886 }
887 | {
888 /** The provider turned the run away; it goes on again at `resumeAt`. */
889 readonly state: "paused";
890 readonly summary: string;
891 readonly resumeAt: string;
892 readonly sessionId: string;
893 readonly costUsd: number;
894 /** Held before it began (a person's run goes first): the wait does not count as a pause. */
895 readonly keepAttempt?: boolean;
896 };
897
898 /**
899 * What a run spent that its outcome does not carry: the tokens of every
900 * model invocation it made, and the account it made them on. Filled by
901 * `work` as it goes, read once the run ends.
902 */
903 interface Meter {
904 tokensIn: number;
905 tokensOut: number;
906 /** US dollars reported by invocations that have ended. */
907 costUsd: number;
908 subscriptionId: string | null;
909 kind: UsageKind;
910 /** When a `running` line was last written (epoch ms); 0 for never. */
911 reportedAt: number;
912 /** Ends the run. */
913 stop: () => void;
914 /** Set when the run spends an owner's capped grant: whose. */
915 grantOwner?: string;
916 /** Set on every run: whose daily ceiling it counts against. */
917 ceilingOwner?: string;
918 /** Why the run was stopped by its grant's cap, when it was. */
919 stoppedFor?: string;
920 }
921
922 /** What a run is for, as the ledger sums it: its reason, or its agent's role. */
923 function usageKind(app: App, run: Run): UsageKind {
924 if (run.reason === "review") return "review";
925 if (run.reason === "check_failed") return "check";
926 if (
927 run.actorId !== null &&
928 crewRole(app.db, run.repoId, run.actorId) === "planner"
929 )
930 return "plan";
931 return "build";
932 }
933
934 /** How often a running session's spend is written and announced, at most. */
935 const LIVE_MS = 2_000;
936
937 /** Said on a run stopped at its grant's cap. */
938 const GRANT_SPENT =
939 storedText("This month's model grant is spent: the run stopped at the cap.", "an admin of this forge", "raise it");
940
941 /** Said on a run stopped at its account's daily ceiling. */
942 const DAILY_SPENT =
943 storedText("This account's daily ceiling is spent: the run stopped.", "an admin of this forge", "raise it");
944
945 /**
946 * A running session's spend so far, as its `running` line in the ledger,
947 * and a `usage.delta` on the outbox so the board and the Subscriptions page
948 * move within seconds. At most once per `LIVE_MS` unless `force`; the
949 * event carries only the run's id — spend is the owner's fact, and a
950 * reader who may see it reads it from the page.
951 */
952 function meterLive(
953 app: App,
954 run: Run,
955 meter: Meter,
956 live: { tokensIn: number; tokensOut: number; costUsd: number },
957 started: number,
958 force: boolean,
959 ): void {
960 const now = Date.now();
961 if (!force && now - meter.reportedAt < LIVE_MS) return;
962 meter.reportedAt = now;
963 try {
964 recordUsage(app.db, {
965 runId: run.id,
966 repoId: run.repoId,
967 issueId: run.issueId,
968 agentId: run.actorId,
969 subscriptionId: meter.subscriptionId,
970 kind: meter.kind,
971 tokensIn: live.tokensIn,
972 tokensOut: live.tokensOut,
973 costUsd: live.costUsd,
974 wallMs: now - started,
975 outcome: "running",
976 at: new Date(now).toISOString(),
977 });
978 noteLowWallet(app.db, app.bus, run.repoId, new Date(now));
979 // The cap is checked on each spend tick, not only at the start.
980 if (meter.grantOwner !== undefined && meter.stoppedFor === undefined) {
981 const left = grantLeft(app.db, meter.grantOwner, new Date(now));
982 if (left !== undefined && left <= 0) {
983 meter.stoppedFor = GRANT_SPENT;
984 meter.stop();
985 }
986 }
987 if (meter.ceilingOwner !== undefined && meter.stoppedFor === undefined) {
988 const left = dailyLeft(app.db, meter.ceilingOwner, new Date(now));
989 if (left !== undefined && left <= 0) {
990 meter.stoppedFor = DAILY_SPENT;
991 meter.stop();
992 }
993 }
994 app.bus.append({
995 kind: "usage.delta",
996 repoId: run.repoId,
997 payload: { runId: run.id },
998 });
999 } catch (error) {
1000 log.warn("live usage not recorded", { run: run.id, error: String(error) });
1001 }
1002 }
1003
1004 /** The run's line in the usage ledger (`core/usage.ts`), written once it ends. */
1005 function meterUsage(
1006 app: App,
1007 run: Run,
1008 outcome: Outcome,
1009 meter: Meter,
1010 started: number,
1011 ): void {
1012 const ended = new Date();
1013 const result: UsageOutcome = outcome.state;
1014 // The ledger is bookkeeping: a line it cannot write (the repository
1015 // deleted under the run) is logged, never the run's failure.
1016 try {
1017 recordUsage(app.db, {
1018 runId: run.id,
1019 repoId: run.repoId,
1020 issueId: run.issueId,
1021 agentId: run.actorId,
1022 subscriptionId: meter.subscriptionId,
1023 kind: meter.kind,
1024 tokensIn: meter.tokensIn,
1025 tokensOut: meter.tokensOut,
1026 costUsd: outcome.costUsd ?? 0,
1027 wallMs: ended.getTime() - started,
1028 outcome: result,
1029 at: ended.toISOString(),
1030 });
1031 noteLowWallet(app.db, app.bus, run.repoId, ended);
1032 } catch (error) {
1033 log.warn("usage not recorded", { run: run.id, error: String(error) });
1034 }
1035 }
1036
1037806 /** What a paused run hands back: when its task may start again, and the count. */
1038807 export interface Pause {
1039808 readonly resumeAt: string;
@@ -2240,497 +2009,7 @@ async function work(
22402009 }
22412010 }
22422011
2243 /**
2244 * The agent's fork of the repository it is working on, made on first use.
2245 * One fork per agent per repository; a name already taken by something
2246 * else of the agent's gets the owner's name in front.
2247 */
2248 export async function forkFor(
2249 app: App,
2250 agent: Agent,
2251 repo: Repo,
2252 write: (line: string) => void,
2253 /** The task is a sealed report: its work goes in a private repository (`core/sealed.ts`). */
2254 sealed = false,
2255 ): Promise<Result<Repo, string>> {
2256 if (sealed) {
2257 const made = await sealedForkFor(app, agent.user, repo);
2258 if (!made.ok)
2259 return err(
2260 `could not make a private place for ${repo.ownerName}/${repo.name}'s sealed work: ${made.error}`,
2261 );
2262 return ok(made.value);
2263 }
2264 const existing = getForkOf(app.db, agent.user.id, repo.id);
2265 if (existing !== undefined) return ok(existing);
2266 let made = await forkRepo(app, agent.user, repo);
2267 if (!made.ok && made.error === "name_taken")
2268 made = await forkRepo(
2269 app,
2270 agent.user,
2271 repo,
2272 `${repo.ownerName}-${repo.name}`,
2273 );
2274 if (!made.ok)
2275 return err(
2276 `could not fork ${repo.ownerName}/${repo.name} for ${agent.user.username}: ${String(made.error)}`,
2277 );
2278 write(
2279 `forked ${repo.ownerName}/${repo.name} as ${made.value.ownerName}/${made.value.name}`,
2280 );
2281 return ok(made.value);
2282 }
2283
2284 /** Whether `dir` is empty, or a work tree git can read: its `.git` resolves. */
2285 async function readsAsClone(
2286 dir: string,
2287 env: Record<string, string>,
2288 ): Promise<boolean> {
2289 if (readdirSync(dir).length === 0) return true;
2290 // A `.git` that is a link, a gitfile or borrows another repository is
2291 // not the clone's own (#14747): moved aside, never run in.
2292 if (foreignGitDir(dir) !== undefined) return false;
2293 // Its own `.git`, named: never a repository above it that git would find.
2294 const top = await runGit(
2295 ["--git-dir", join(dir, ".git"), "rev-parse", "--git-dir"],
2296 { cwd: dir, env },
2297 );
2298 return top.ok;
2299 }
2300
2301 /**
2302 * A clone on `branch`, matching what the forge holds. The clone is the
2303 * triangle git was built for: it fetches from the repository and pushes to
2304 * the agent's fork, so a plain `git push` lands where the agent may write
2305 * and nowhere else.
2306 */
2307 async function prepareClone(
2308 app: App,
2309 options: CrewOptions,
2310 repo: Repo,
2311 fork: Repo,
2312 branch: string,
2313 dir: string,
2314 env: Record<string, string>,
2315 write: (line: string) => void,
2316 signal: AbortSignal,
2317 keep = false,
2318 fresh = false,
2319 ): Promise<{ ok: true } | { ok: false; error: string }> {
2320 // Two addresses for one forge. The forge itself clones and fetches over
2321 // `localUrl`, on this machine. The agent's remotes carry `forgeUrl`, the
2322 // forge as the agent is told it: inside the shell sandbox, `localhost` is
2323 // the sandbox's own and reaches nothing, while a named host goes out
2324 // through the sandbox's proxy — so a remote on the local address would
2325 // leave `git push` nowhere to go, and the only way to push would be to
2326 // leave the sandbox, which is not a way.
2327 const url = `${options.localUrl}/${repo.ownerName}/${repo.name}.git`;
2328 const forkUrl = `${options.localUrl}/${fork.ownerName}/${fork.name}.git`;
2329 const agentUrl = `${options.forgeUrl}/${repo.ownerName}/${repo.name}.git`;
2330 const agentForkUrl = `${options.forgeUrl}/${fork.ownerName}/${fork.name}.git`;
2331 if (signal.aborted) return { ok: false, error: "cancelled" };
2332 // A kept clone git no longer reads as one — a clone a network blip cut
2333 // short — is moved aside, never reused, and cloned afresh (#6263).
2334 if (existsSync(dir) && !(await readsAsClone(dir, env))) {
2335 const aside = `${dir}.broken-${Date.now()}`;
2336 renameSync(dir, aside);
2337 write(
2338 `the kept clone is not a git repository; moved aside to ${aside}, cloning afresh`,
2339 );
2340 return prepareClone(
2341 app,
2342 options,
2343 repo,
2344 fork,
2345 branch,
2346 dir,
2347 env,
2348 write,
2349 signal,
2350 false,
2351 true,
2352 );
2353 }
2354 if (!existsSync(join(dir, ".git"))) {
2355 mkdirSync(dir, { recursive: true });
2356 write(`cloning ${repo.ownerName}/${repo.name}`);
2357 const cloned = await cloneWithMirror({
2358 dataDir: app.config.dataDir,
2359 repoId: repo.id,
2360 url,
2361 dir,
2362 env,
2363 signal,
2364 });
2365 if (!cloned.ok)
2366 return {
2367 ok: false,
2368 error: `clone failed: ${cloned.error.stderr.slice(0, 200)}`,
2369 };
2370 } else {
2371 // A kept clone may carry the locks of a run the forge cut off. This run
2372 // owns the clone now, so a lock a minute old is nobody's.
2373 clearStaleLocks(dir, write);
2374 const fetched = await runCloneGit(
2375 dir,
2376 [
2377 "fetch",
2378 "--quiet",
2379 "--prune",
2380 url,
2381 `+refs/heads/*:refs/remotes/origin/*`,
2382 ],
2383 { env, timeoutMs: GIT_TRANSFER_MS },
2384 );
2385 if (!fetched.ok)
2386 return {
2387 ok: false,
2388 error: `fetch failed: ${fetched.error.stderr.slice(0, 200)}`,
2389 };
2390 // The remotes are the agent's, set again on every visit — a clone from
2391 // before the forge changed where they point (a kept clone resumed after
2392 // a release) would otherwise push to an address that is no longer the
2393 // forge's for the sandbox.
2394 await runCloneGit(dir, ["config", "remote.origin.url", agentUrl], { env });
2395 await runCloneGit(dir, ["config", "remote.origin.pushurl", agentForkUrl], {
2396 env,
2397 });
2398 // A paused run resumes in the tree it left — its uncommitted work is
2399 // part of the session that is about to continue — so long as the clone
2400 // is still on its branch.
2401 if (keep) {
2402 const head = await runCloneGit(dir, ["rev-parse", "--abbrev-ref", "HEAD"], {
2403 env,
2404 });
2405 if (head.ok && head.value.trim() === branch) {
2406 write(`clone kept as it was left, on ${branch}`);
2407 return { ok: true };
2408 }
2409 }
2410 }
2411 await runCloneGit(dir, ["config", "remote.origin.url", agentUrl], { env });
2412 await runCloneGit(dir, ["config", "remote.origin.pushurl", agentForkUrl], {
2413 env,
2414 });
2415 // The branch, if it exists, lives in the fork; its tracking ref is fetched
2416 // from there so the checkout starts at what the agent last pushed.
2417 const forkBare = repoDir(app.reposRoot, fork.ownerName, fork.name);
2418 const remote = await resolveOid(forkBare, `refs/heads/${branch}`);
2419 if (remote !== undefined) {
2420 const fetched = await runCloneGit(
2421 dir,
2422 [
2423 "fetch",
2424 "--quiet",
2425 forkUrl,
2426 `+refs/heads/${branch}:refs/remotes/origin/${branch}`,
2427 ],
2428 { env, timeoutMs: GIT_TRANSFER_MS },
2429 );
2430 if (!fetched.ok)
2431 return {
2432 ok: false,
2433 error: `fetch from the fork failed: ${fetched.error.stderr.slice(0, 200)}`,
2434 };
2435 }
2436 const start =
2437 remote === undefined ? `origin/${repo.defaultBranch}` : `origin/${branch}`;
2438 // A leftover from a cut-off run is discarded: the remote is truth.
2439 await runCloneGit(dir, ["reset", "--quiet", "--hard"], { env });
2440 await runCloneGit(dir, ["clean", "-fdq"], { env });
2441 const checked = await runCloneGit(dir, ["checkout", "--quiet", "-B", branch, start], {
2442 env,
2443 });
2444 if (!checked.ok && !fresh && lockedOut(checked.error.stderr)) {
2445 // A lock too young to clear, or one the sweep missed: start over once
2446 // from a fresh clone rather than failing the follow-up.
2447 // Only when nothing would be lost: a cut-off run may hold commits that
2448 // were never pushed, and those live nowhere else.
2449 const unpushed = await runCloneGit(
2450 dir,
2451 ["rev-list", "--branches", "--not", "--remotes=origin"],
2452 { env },
2453 );
2454 if (!unpushed.ok || unpushed.value.trim() !== "")
2455 return {
2456 ok: false,
2457 error:
2458 "checkout blocked by a git lock, and the kept clone holds commits that were never pushed; left as it is",
2459 };
2460 write("checkout blocked by a git lock; cloning afresh");
2461 await rm(dir, { recursive: true, force: true });
2462 return prepareClone(
2463 app,
2464 options,
2465 repo,
2466 fork,
2467 branch,
2468 dir,
2469 env,
2470 write,
2471 signal,
2472 false,
2473 true,
2474 );
2475 }
2476 if (!checked.ok)
2477 return {
2478 ok: false,
2479 error: `checkout failed: ${checked.error.stderr.slice(0, 200)}`,
2480 };
2481 // The branch tracks its remote from the start, set here where git config
2482 // is writable: inside the sandbox `.git/config` is not, so a plain
2483 // `git push` must already know where to go.
2484 await runCloneGit(dir, ["config", `branch.${branch}.remote`, "origin"], {
2485 env,
2486 });
2487 await runCloneGit(dir, ["config", `branch.${branch}.merge`, `refs/heads/${branch}`], {
2488 env,
2489 });
2490 // What a run leaves in its tree that is never the work: the temp
2491 // directory a sandboxed shell keeps beside the code (`.tmp/`), with a
2492 // test's data in it, and `node_modules/`. The wrap-up
2493 // commits leftovers with `git add -A`, so the clone says so once, in its
2494 // own exclude file — the repository's `.gitignore` is the repository's.
2495 mkdirSync(join(dir, ".git", "info"), { recursive: true });
2496 writeFileSync(join(dir, ".git", "info", "exclude"), CLONE_EXCLUDES);
2497 // A push that adds a migration commits its pin first (#6938).
2498 installPinHook(dir);
2499 write(
2500 remote === undefined
2501 ? `branch ${branch} from ${repo.defaultBranch}`
2502 : `branch ${branch} at ${remote.slice(0, 7)}`,
2503 );
2504 return { ok: true };
2505 }
2506
2507 /** Never the work, in any repository the crew clones: git's own exclude syntax. */
2508 export const CLONE_EXCLUDES = [
2509 "# written by the forge for every crew clone",
2510 ".tmp/",
2511 "node_modules/",
2512 "",
2513 ].join("\n");
2514
2515 /**
2516 * After the agent stops: push what it committed if it did not, open the
2517 * pull if there is none, and report on the conversation — the agent's
2518 * last message, and the forge's note under it when there is one.
2519 */
2520 async function landWork(
2521 app: App,
2522 options: CrewOptions,
2523 repo: Repo,
2524 agent: Agent,
2525 issue: Issue,
2526 pull: Pull | undefined,
2527 fork: Repo,
2528 branch: string,
2529 dir: string,
2530 forkBare: string,
2531 bare: string,
2532 env: Record<string, string>,
2533 message: string,
2534 note: string | undefined,
2535 write: (line: string) => void,
2536 granted: readonly string[] = [],
2537 variantGroup: string | null = null,
2538 hops?: Hops,
2539 ): Promise<{ pushed: boolean; summary: string }> {
2540 // A model may echo a granted value into a file; the tree is scrubbed
2541 // before the forge commits it, and the agent's own commits are searched
2542 // before anything is pushed.
2543 const scrubbed = await scrubTree(dir, granted, env);
2544 if (scrubbed.length > 0)
2545 write(`scrubbed a granted secret value from ${scrubbed.join(", ")}`);
2546 // Work left in the tree is committed on the agent's behalf: a proposal a
2547 // person can read beats an edit nobody sees. The summary says it happened.
2548 const status = await runCloneGit(dir, ["status", "--porcelain"], { env });
2549 let committedForIt = false;
2550 if (status.ok && status.value.trim() !== "") {
2551 const subject =
2552 message
2553 .split("\n")
2554 .find((l) => l.trim() !== "")
2555 ?.trim() ?? issue.title;
2556 await runCloneGit(dir, ["add", "-A"], { env });
2557 const commit = await runCloneGit(
2558 dir,
2559 [
2560 "commit",
2561 "--quiet",
2562 // The clone's hooks are the agent's (#14747); `runCloneGit` also
2563 // points `core.hooksPath` at nothing.
2564 "--no-verify",
2565 "-m",
2566 subject.slice(0, 200),
2567 "-m",
2568 `Work by @${agent.user.username} on #${issue.number}, committed by the forge.`,
2569 ],
2570 { env },
2571 );
2572 committedForIt = commit.ok;
2573 write(
2574 commit.ok
2575 ? "committed the agent's uncommitted changes"
2576 : `could not commit leftover changes: ${commit.error.stderr.slice(0, 200)}`,
2577 );
2578 }
2579 const head = await runCloneGit(dir, ["rev-parse", "--verify", "HEAD"], {
2580 env,
2581 });
2582 const local = head.ok ? head.value.trim() : undefined;
2583 // The branch is the fork's; the base it is measured against is the
2584 // repository's own default branch.
2585 let remote = await resolveOid(forkBare, `refs/heads/${branch}`);
2586 const base = await resolveOid(bare, `refs/heads/${repo.defaultBranch}`);
2587 if (local !== undefined && local !== remote) {
2588 // Ahead of what the forge holds: the branch if it exists there, the
2589 // default branch otherwise — a fresh branch at the base tip is nothing.
2590 const against = remote ?? base;
2591 const ahead =
2592 against === undefined ? 1 : await aheadCount(dir, against, local);
2593 if (
2594 ahead > 0 &&
2595 (await historyHolds(
2596 dir,
2597 against === undefined ? "HEAD" : `${against}..HEAD`,
2598 granted,
2599 env,
2600 ))
2601 ) {
2602 write("refused: a granted secret value is in the commits; not pushed");
2603 return {
2604 pushed: false,
2605 summary:
2606 "refused to push: a secret this run held is in its commits; nothing pushed",
2607 };
2608 }
2609 if (ahead > 0) {
2610 write(
2611 `pushing ${branch} (${ahead} commit${ahead === 1 ? "" : "s"} the agent did not push)`,
2612 );
2613 // The forge pushes for the agent over its own local address — the
2614 // clone's `origin` carries the public one, for the agent inside the
2615 // sandbox (`prepareClone`), and this push is the forge's, not the
2616 // agent's. The branch already tracks `origin`, set there.
2617 const pushed = await runCloneGit(
2618 dir,
2619 [
2620 "push",
2621 "--quiet",
2622 // The clone's hooks are the agent's sandbox's, never the forge's.
2623 "--no-verify",
2624 `${options.localUrl}/${fork.ownerName}/${fork.name}.git`,
2625 `${branch}:${branch}`,
2626 ],
2627 { env, timeoutMs: GIT_TRANSFER_MS },
2628 );
2629 if (!pushed.ok)
2630 write(`push refused: ${pushed.error.stderr.slice(0, 300)}`);
2631 else hops?.record("push", options.localUrl);
2632 remote = await resolveOid(forkBare, `refs/heads/${branch}`);
2633 }
2634 }
2635 // Counted in the fork, which sees the repository's objects through its
2636 // alternates and its own on top.
2637 const proposed =
2638 remote !== undefined && base !== undefined
2639 ? (await contentOnBase(forkBare, base, remote))
2640 ? 0
2641 : await aheadCount(forkBare, base, remote)
2642 : 0;
2643 const report = [message.trim(), note]
2644 .filter((part): part is string => part !== undefined && part !== "")
2645 .join("\n\n");
2646
2647 if (proposed === 0) {
2648 write(
2649 "nothing to propose: the branch has no commits beyond the default branch",
2650 );
2651 if (report !== "" && pull === undefined)
2652 addComment(app, agent.user, repo, issue, report);
2653 else if (report !== "" && pull !== undefined)
2654 addComment(app, agent.user, repo, pull, report);
2655 const first = report.split("\n").find((l) => l.trim() !== "") ?? "";
2656 return {
2657 pushed: false,
2658 summary:
2659 first === ""
2660 ? "no changes pushed"
2661 : `no changes pushed: ${first.slice(0, 200)}`,
2662 };
2663 }
2664
2665 const existing = pull ?? pullOfBranch(app, repo, fork, branch);
2666 if (existing !== undefined) {
2667 // A pull this run opened at its first push is still the run's opening.
2668 const openedByRun = isEarlyBody(existing.body);
2669 fillPull(app, agent, repo, existing, issue, report);
2670 if (report !== "") addComment(app, agent.user, repo, existing, report);
2671 return {
2672 pushed: true,
2673 summary: `${openedByRun ? "opened" : "updated"} pull #${existing.number} (${remote?.slice(0, 7)})${committedForIt ? ", committing its leftover changes" : ""}`,
2674 };
2675 }
2676 // No pull to update and yet the task is one: the pull it continues was
2677 // merged, and this one follows it rather than closing it.
2678 const trailer = trailerFor(issue);
2679 const body = `${report === "" ? "" : `${report}\n\n`}${trailer}`;
2680 const opened = await openPull(app, agent.user, repo, {
2681 title: issue.title,
2682 body,
2683 baseBranch: repo.defaultBranch,
2684 headBranch: branch,
2685 headRepo: fork,
2686 ...(variantGroup === null ? {} : { variantGroup }),
2687 });
2688 if (!opened.ok) {
2689 write(`could not open the pull: ${JSON.stringify(opened.error)}`);
2690 return {
2691 pushed: true,
2692 summary: `pushed ${branch} but could not open a pull (${String(opened.error)})`,
2693 };
2694 }
2695 write(`opened pull #${opened.value.number}`);
2696 return {
2697 pushed: true,
2698 summary: `opened pull #${opened.value.number}${committedForIt ? ", committing its leftover changes" : ""}`,
2699 };
2700 }
2701
27022012 /** What the agent said, with every held secret value taken out of it. */
27032013 function redactResult<T extends { result: string }>(r: T): T {
27042014 return { ...r, result: redactValues(r.result) };
27052015 }
2706
2707 /**
2708 * Hold the secret values of a model credential's environment for redaction
2709 * under `key`, until `releaseValues(key)`: the one way a child that carries
2710 * the credential (a crew run, a conversation turn, a one-shot) keeps what it
2711 * says of it out of what the forge keeps. The gateway's address is not a
2712 * secret, and an empty or very short value is not held. Answers what is held.
2713 */
2714 export function holdModelCredential(key: string, env: Record<string, string>): string[] {
2715 const secrets = Object.entries(env)
2716 .filter(([name, value]) => !isGatewayAddress(name) && value.length >= 4)
2717 .map(([, value]) => value);
2718 holdValues(key, secrets);
2719 return secrets;
2720 }
2721
2722 /**
2723 * The credential a run's environment carries: the picked account's token
2724 * under the variable Claude Code reads it from (plus a gateway base URL when
2725 * the account has one), or — with nothing granted — whatever the forge
2726 * itself was started with.
2727 */
2728 export function credentialEnv(picked: Pick, dataDir?: string): Record<string, string> {
2729 if (picked.kind === "ready") return credentialEnvOf(picked);
2730 // A forge its parent funds (#10484): with no account of its own, the crew calls the model through
2731 // the parent. "none" reaches here only under an owner's grant (an org's, #10991), which is the
2732 // forge's account too.
2733 const lent = (picked.kind === "env" || picked.kind === "none") && dataDir !== undefined ? fundedEnv(dataDir) : undefined;
2734 if (lent !== undefined) return lent;
2735 return ownEnv();
2736 }
src/crew/steer.ts added +44
@@ -0,0 +1,44 @@
1 /** Steering a run in flight: the sessions listening, and what a person says to one. */
2
3 import type { App } from "../app.ts";
4 import { appendRunLog } from "../runs/log.ts";
5
6 /** Runs with an agent listening: what a person says reaches it next. */
7 const steering = new Map<string, (text: string) => boolean>();
8
9 /** A session starts listening to a run; the answer stops it. */
10 export function listenForSteer(
11 runId: string,
12 send: (text: string) => boolean,
13 ): () => void {
14 steering.set(runId, send);
15 return () => {
16 if (steering.get(runId) === send) steering.delete(runId);
17 };
18 }
19
20 /** Whether run `runId` can be handed words now: its input is open and listening. */
21 export const steerable = (runId: string): boolean => steering.has(runId);
22
23 /**
24 * Say something to an agent while its run goes. Written to the run's log
25 * as the person's line first, so the record holds it whether or not the
26 * agent gets to answer, then handed to the session as its next user turn.
27 * False when the run has no session listening: queued, ended, or between
28 * invocations.
29 */
30 export function steerRun(app: App, runId: string, text: string): boolean {
31 const send = steering.get(runId);
32 if (send === undefined) return false;
33 appendRunLog(
34 app.config.dataDir,
35 runId,
36 `you: ${text.replace(/\s*\n\s*/g, " ")}`,
37 );
38 return send(text);
39 }
40
41 /** The run ended: nothing listens to it any more. */
42 export function stopSteering(runId: string): void {
43 steering.delete(runId);
44 }
test/boundary-tokens-crew.test.ts +1 −1
@@ -58,7 +58,7 @@ import { deleteToken, verifyToken } from "../src/core/tokens.ts";
5858 import { createUser, type User } from "../src/core/users.ts";
5959 import { landsOnItsOwn } from "../src/crew/direct.ts";
6060 import { runGitAuth } from "../src/crew/git_auth.ts";
61 import { forkFor } from "../src/crew/runner.ts";
61 import { forkFor } from "../src/crew/clone.ts";
6262 import { isStrangerPull } from "../src/crew/stranger.ts";
6363 import { forgeHttp } from "../src/http/server.ts";
6464 import { sha256 } from "../src/kernel/hash.ts";
test/child-credit.test.ts +1 −1
@@ -15,7 +15,7 @@ import { join } from "node:path";
1515 import { createRepo } from "../src/actions/repos.ts";
1616 import { childDirOf } from "../src/actions/spawn.ts";
1717 import { createApp, type App } from "../src/app.ts";
18 import { credentialEnv } from "../src/crew/runner.ts";
18 import { credentialEnv } from "../src/crew/credential_env.ts";
1919 import { eventAudience } from "../src/core/event_audience.ts";
2020 import { readCapped } from "../src/spawn/bounded_read.ts";
2121 import { crewReadiness } from "../src/web/pages/crew.ts";
test/crew-clone-git.test.ts +9 −6
@@ -331,14 +331,17 @@ describe("the OpenAI runner fences the clone's .git (#14747)", () => {
331331 });
332332 });
333333
334 describe("runner.ts runs no git in the clone but through runCloneGit (#14747)", () => {
334 describe("the crew runner runs no git in the clone but through runCloneGit (#14747)", () => {
335335 test("prepareClone and landWork name no runGit with the clone as cwd", () => {
336 const src = readFileSync(join(import.meta.dir, "..", "src", "crew", "runner.ts"), "utf8");
337 const from = src.indexOf("async function prepareClone(");
338 const to = src.indexOf("// Counted in the fork, which sees", from);
336 // prepareClone lives in clone.ts, landWork in land_work.ts (#15368): read both, whole.
337 const read = (name: string) => readFileSync(join(import.meta.dir, "..", "src", "crew", name), "utf8");
338 const clone = read("clone.ts");
339 const land = read("land_work.ts");
340 const from = clone.indexOf("async function prepareClone(");
341 const to = land.indexOf("// Counted in the fork, which sees");
339342 expect(from).toBeGreaterThan(0);
340 expect(to).toBeGreaterThan(from);
341 const body = src.slice(from, to);
343 expect(to).toBeGreaterThan(0);
344 const body = clone.slice(from) + land.slice(0, to);
342345 expect(body).not.toMatch(/runGit(Raw|Capture)?\(/);
343346 expect(body).toMatch(/"commit",\s*"--quiet",[\s\S]*?"--no-verify"/);
344347 });
test/module-state.baseline.txt +1 −1
@@ -80,7 +80,7 @@ src/crew/plan.ts:found
8080 src/crew/repeat_checks.ts:swept
8181 src/crew/requested.ts:said
8282 src/crew/review.ts:said
83 src/crew/runner.ts:steering
83 src/crew/steer.ts:steering
8484 src/crew/running.ts:running
8585 src/crew/waits.ts:last
8686 src/crew/week_read.ts:remembered
test/review-head-fetch.test.ts +2 −1
@@ -24,7 +24,8 @@ import { createRun, getRun } from "../src/core/runs.ts";
2424 import type { User } from "../src/core/users.ts";
2525 import { runGitAuth } from "../src/crew/git_auth.ts";
2626 import { checkoutReviewHead, noteUnreviewed } from "../src/crew/review_head.ts";
27 import { executeAgentRun, forkFor } from "../src/crew/runner.ts";
27 import { forkFor } from "../src/crew/clone.ts";
28 import { executeAgentRun } from "../src/crew/runner.ts";
2829 import { runGitCapture } from "../src/git/env.ts";
2930 import { forgeHttp } from "../src/http/server.ts";
3031 import { readRunLog } from "../src/runs/log.ts";
test/sealed-git.test.ts +1 −1
@@ -29,7 +29,7 @@ import { getRepoById, type Repo } from "../src/core/repos.ts";
2929 import { createToken } from "../src/core/tokens.ts";
3030 import { createUser, type User } from "../src/core/users.ts";
3131 import { repoDir } from "../src/git/repos.ts";
32 import { forkFor } from "../src/crew/runner.ts";
32 import { forkFor } from "../src/crew/clone.ts";
3333 import { serve, type Servers } from "../src/http/server.ts";
3434 import { gitClientEnv } from "./helpers/git-client.ts";
3535 import { quietLogs } from "./helpers/globals.ts";
test/tui-steer.test.ts +10 −1
@@ -14,7 +14,7 @@ import { addTeamMember, createOrg, createTeam, removeTeamMember } from "../src/c
1414 import { canWrite, createRepo, type Repo } from "../src/core/repos.ts";
1515 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
1616 import { createUser, type User } from "../src/core/users.ts";
17 import { listenForSteer } from "../src/crew/runner.ts";
17 import { listenForSteer, steerable, stopSteering } from "../src/crew/steer.ts";
1818 import { createForgeApp } from "../src/tui/forge.ts";
1919 import { issueScreen } from "../src/tui/screens/issue.ts";
2020 import { pullScreen } from "../src/tui/screens/pull.ts";
@@ -247,3 +247,12 @@ test("a refusal reads as the run page and MCP read it", async () => {
247247 expect(listComments(forge.db, issue.id)).toHaveLength(0);
248248 h.app.stop();
249249 });
250
251 test("stopSteering: a run that ended no longer listens, whoever registered", () => {
252 const stop = listenForSteer("run-stopped", () => true);
253 expect(steerable("run-stopped")).toBe(true);
254 stopSteering("run-stopped");
255 expect(steerable("run-stopped")).toBe(false);
256 stop(); // the late unlisten of a session already stopped is harmless
257 expect(steerable("run-stopped")).toBe(false);
258 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs