Public: anyone can read this; the crew can change it.
Split work() in src/crew/runner.ts into steps that take their state as a plain object #16813
Check · Review · Land · Live done — Landed and live in production.
mason/forge:mason/16789-split-work-in-src-crew-runner-ts-into-st → main 0 commits fork
12 files
changed +2142
−1093
AGENTS.md +2
| @@ -100,3 +100,5 @@ A pull that adds a page (`src/web/pages/*.ts`), an MCP tool (`src/http/mcp/tools | ||
| 100 | 100 | `src/actions/places_refresh.ts`: `running`, the one catalog refresh in flight per forge database (#16203), so concurrent admin reads wait on it; at most one per forge, gone on restart. Its terminal door is `src/tui/screens/places.ts` (`p` pins; `pinPlace` gives the API and the terminal the same gate and the `cloud.place_pinned` event). |
| 101 | 101 | |
| 102 | 102 | `bun scripts/gate.ts --explain` (#16325) lists every gate rule (`GATE_RULES`, `scripts/gate.ts`) and every fast tree-reading guard test (`GUARDS`, `scripts/gate_explain.ts`) against your diff, satisfied or not, each with the line that satisfies it and where the rule lives; a refusing gate ends with one line naming all the rules that refused. No network, no socket, about fifteen seconds. In a sandboxed session `bun x tsc --noEmit` without installed dependencies, tests that bind a port or unix socket, and the full suite cannot run: report them as not run. A rule added to `GATE_RULES` is judged and explained at once; a new tree-reading guard goes in `GUARDS`. |
| 103 | ||
| 104 | `src/crew/runner.ts`'s `work()` is the order of one agent run, and each step of it is a module that takes its state as a plain object and returns plain data (#16789): `run_spend.ts` (`settleSpend`: the account, ceilings and budget, or the refusal), `run_prompt.ts` (`promptFor`, `reviewInputs`), `run_retry.ts` (`retryNetwork`, `outagePause`), `run_limits.ts` (`limitEnding`: a provider's refusal as a pause), `run_verdict.ts` (`verdictOf`, `settleReview`: a decline or a review's verdict), `run_prepare.ts` (`prepareAgent`: the environment, sandbox, devices, model and the metered `invoke` closure, with what the `finally` must free in a `Held`), `run_wrapup.ts` (`wrapUp`: the reserve turn), `run_settle.ts` (`settleRun`: a cancel, a refused token, a verdict, or the landing, as the outcome), with `meter.ts` holding the `Outcome` and `Meter` records they share. A step imports nothing of `runner.ts` but the `CrewOptions` type; `runner.ts` re-exports the names it was imported by. Tests: `test/run-steps.test.ts`. |
src/crew/run_limits.ts added +111
| @@ -0,0 +1,111 @@ | ||
| 1 | /** | |
| 2 | * What the run does when the provider turned its session away: the provider's refusal is not the | |
| 3 | * agent's failure, so the run pauses with its clone and session as they are and goes on when the | |
| 4 | * limit lifts, or another account takes it. A limit that never lifts is not waited on forever. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { App } from "../app.ts"; | |
| 8 | import type { Run } from "../core/runs.ts"; | |
| 9 | import { PLATFORM, pickSubscription, type Pick } from "../core/subscriptions.ts"; | |
| 10 | import type { AgentOutcome } from "./agent_runner.ts"; | |
| 11 | import { | |
| 12 | breathWait, | |
| 13 | breathWords, | |
| 14 | isRateLimited, | |
| 15 | limitOf, | |
| 16 | MAX_PAUSES, | |
| 17 | noteBreath, | |
| 18 | perMinute, | |
| 19 | resumeAt, | |
| 20 | takeLimit, | |
| 21 | whenText, | |
| 22 | } from "./limits.ts"; | |
| 23 | import { pauseReason } from "./pacing.ts"; | |
| 24 | import type { Outcome } from "./meter.ts"; | |
| 25 | import type { SpendScope } from "./run_spend.ts"; | |
| 26 | ||
| 27 | /** What `limitEnding` is given: plain data and the run's log. */ | |
| 28 | export interface LimitState { | |
| 29 | readonly app: App; | |
| 30 | readonly run: Run; | |
| 31 | readonly picked: Pick; | |
| 32 | readonly scope: SpendScope; | |
| 33 | readonly result: AgentOutcome; | |
| 34 | readonly aborted: boolean; | |
| 35 | readonly write: (line: string) => void; | |
| 36 | } | |
| 37 | ||
| 38 | /** | |
| 39 | * The run's ending when the provider turned it away, or when the limit will lift (`limitLifts`) for | |
| 40 | * a run that has paused as often as it may; neither when the session was not refused. | |
| 41 | */ | |
| 42 | export type LimitEnding = | |
| 43 | | { readonly outcome: Outcome } | |
| 44 | | { readonly limitLifts: Date | undefined }; | |
| 45 | ||
| 46 | export function limitEnding(s: LimitState): LimitEnding { | |
| 47 | const { app, run, picked, scope, result, write } = s; | |
| 48 | const account = picked.kind === "ready" ? picked.subscription.id : PLATFORM; | |
| 49 | // A per-minute refusal (a 429 naming no window): no account rests for it, the run waits a | |
| 50 | // minute or a few by who sent it, and the crew's own runs on that account hold a while so a | |
| 51 | // person's build gets the next minute. Plain words; the provider's are in the log. | |
| 52 | if (isRateLimited(result) && !s.aborted && perMinute(result.limit) && run.attempt < MAX_PAUSES) { | |
| 53 | const now = new Date(); | |
| 54 | const at = new Date(now.getTime() + breathWait(run.attempt, run.sent)); | |
| 55 | noteBreath(app.db, account, new Date(now.getTime() + breathWait(0, false))); | |
| 56 | write(`the provider: ${result.limit.said ?? result.reason}`); | |
| 57 | return { | |
| 58 | outcome: { | |
| 59 | state: "paused", | |
| 60 | summary: `paused: ${breathWords(at, run.sent)}`, | |
| 61 | resumeAt: at.toISOString(), | |
| 62 | sessionId: result.sessionId, | |
| 63 | costUsd: result.costUsd, | |
| 64 | }, | |
| 65 | }; | |
| 66 | } | |
| 67 | if (!isRateLimited(result) || s.aborted) return { limitLifts: undefined }; | |
| 68 | const now = new Date(); | |
| 69 | // The account rests until the provider's time; another on the same | |
| 70 | // grant, if one is awake, takes the run straight away. | |
| 71 | const { until, limit, said } = takeLimit( | |
| 72 | app.db, | |
| 73 | picked.kind === "ready" ? picked.subscription.id : undefined, | |
| 74 | result.limit, | |
| 75 | result.reason, | |
| 76 | now, | |
| 77 | ); | |
| 78 | if (picked.kind === "ready") { | |
| 79 | // Only a look at who could take over: no reservation is made here. | |
| 80 | // The run pauses, and on resume it picks again with its reserve. | |
| 81 | const next = pickSubscription(app.db, app.config.dataDir, scope, new Date()); | |
| 82 | if (next.kind === "ready" && next.subscription.id !== picked.subscription.id) { | |
| 83 | write( | |
| 84 | `${picked.subscription.name} rests until ${whenText(until)}; ${next.subscription.name} takes the run`, | |
| 85 | ); | |
| 86 | return { | |
| 87 | outcome: { | |
| 88 | state: "paused", | |
| 89 | summary: `paused: ${pauseReason(picked.subscription.name, limit, said)}; ${next.subscription.name} takes over`, | |
| 90 | resumeAt: new Date().toISOString(), | |
| 91 | sessionId: result.sessionId, | |
| 92 | costUsd: result.costUsd, | |
| 93 | }, | |
| 94 | }; | |
| 95 | } | |
| 96 | } | |
| 97 | if (run.attempt < MAX_PAUSES) { | |
| 98 | const at = resumeAt(result.limit, new Date()); | |
| 99 | return { | |
| 100 | outcome: { | |
| 101 | state: "paused", | |
| 102 | summary: `paused: ${pauseReason(picked.kind === "ready" ? picked.subscription.name : undefined, limitOf(result.limit), said)}; resumes ${whenText(at)}`, | |
| 103 | resumeAt: at.toISOString(), | |
| 104 | sessionId: result.sessionId, | |
| 105 | costUsd: result.costUsd, | |
| 106 | }, | |
| 107 | }; | |
| 108 | } | |
| 109 | write(`paused ${MAX_PAUSES} times already; not waiting again`); | |
| 110 | return { limitLifts: resumeAt(result.limit, new Date()) }; | |
| 111 | } |
src/crew/run_prepare.ts added +294
| @@ -0,0 +1,294 @@ | ||
| 1 | /** | |
| 2 | * Everything between a settled budget and the agent's first turn: the environment its shell sees, | |
| 3 | * the sandbox around it, the run's own temp directory and devices, the model it runs on, and the | |
| 4 | * closure that invokes it, metered as it goes. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { App } from "../app.ts"; | |
| 8 | import type { Agent } from "../core/agents.ts"; | |
| 9 | import { capacityEnv } from "../core/capacity.ts"; | |
| 10 | import type { Issue } from "../core/issues.ts"; | |
| 11 | import { forgetMeasure, noteMeasure } from "../core/measure.ts"; | |
| 12 | import type { Repo } from "../core/repos.ts"; | |
| 13 | import { noteRunProgress, type Run } from "../core/runs.ts"; | |
| 14 | import { PLATFORM, type Pick } from "../core/subscriptions.ts"; | |
| 15 | import { redactValues } from "../kernel/log.ts"; | |
| 16 | import { currentRunner, runAgent, type AgentOutcome } from "./agent_runner.ts"; | |
| 17 | import { ownApp, ownAppUrls } from "./app_hosts.ts"; | |
| 18 | import { promptVersion, systemPrompt, type BriefInput } from "./brief.ts"; | |
| 19 | import { credentialEnv, holdModelCredential } from "./credential_env.ts"; | |
| 20 | import { deviceKit, type DeviceKit } from "./devices.ts"; | |
| 21 | import { doorForRun, type GatewayDoor } from "./gateway_door.ts"; | |
| 22 | import type { Grant } from "./grant.ts"; | |
| 23 | import { handedOverPulls } from "./guard.ts"; | |
| 24 | import { handedLimbs } from "./handed_limbs.ts"; | |
| 25 | import { machineEnv, machineLimits, reachableApps, type Machine } from "./machines.ts"; | |
| 26 | import { meterLive, type Meter } from "./meter.ts"; | |
| 27 | import { chooseModel, modelFacts } from "./model_choice.ts"; | |
| 28 | import { parkedTwice } from "./parks.ts"; | |
| 29 | import { passportEnv } from "./passport_env.ts"; | |
| 30 | import { layerRunEnv, runAccount, sandboxTmpEnv } from "./runner_env.ts"; | |
| 31 | import type { CrewOptions } from "./runner.ts"; | |
| 32 | import { installCacheEnv, makeRunTmp, sandboxPolicy } from "./sandbox.ts"; | |
| 33 | import { listenForSteer } from "./steer.ts"; | |
| 34 | import { keepToken } from "./token_refused.ts"; | |
| 35 | import { handedTooLarge } from "./too_large.ts"; | |
| 36 | ||
| 37 | /** The share of a run's budget held back for finishing. */ | |
| 38 | const RESERVE = 0.15; | |
| 39 | /** ...and never less than this: a wrap-up that cannot run a test is none. */ | |
| 40 | const RESERVE_FLOOR_USD = 0.5; | |
| 41 | ||
| 42 | /** | |
| 43 | * What a run keeps for its wrap-up: fifteen percent of the budget, at | |
| 44 | * least fifty cents, never more than half — a budget too small to split | |
| 45 | * is not made worse by splitting it. | |
| 46 | */ | |
| 47 | export function wrapUpReserve(budgetUsd: number): number { | |
| 48 | return Math.min(Math.max(budgetUsd * RESERVE, RESERVE_FLOOR_USD), budgetUsd / 2); | |
| 49 | } | |
| 50 | ||
| 51 | /** | |
| 52 | * What the run holds that its `finally` must free, written as each is made: a step that throws | |
| 53 | * half way leaves the rest of it as it was. | |
| 54 | */ | |
| 55 | export interface Held { | |
| 56 | /** The model credential's values, held for redaction. */ | |
| 57 | modelSecrets: string[]; | |
| 58 | /** The run's own temp directory. */ | |
| 59 | runTmp: string | undefined; | |
| 60 | devices: DeviceKit | undefined; | |
| 61 | gatewayDoor: GatewayDoor | undefined; | |
| 62 | } | |
| 63 | ||
| 64 | /** What `prepareAgent` is given: plain data, the run's meter, and what it writes to. */ | |
| 65 | export interface PrepareState { | |
| 66 | readonly app: App; | |
| 67 | readonly options: CrewOptions; | |
| 68 | readonly run: Run; | |
| 69 | readonly repo: Repo; | |
| 70 | readonly agent: Agent; | |
| 71 | readonly issue: Issue; | |
| 72 | /** The issue the task's session began on, when the task spans a pull. */ | |
| 73 | readonly taskIssue: Issue | undefined; | |
| 74 | readonly brief: BriefInput; | |
| 75 | readonly machine: Machine; | |
| 76 | readonly reviewing: boolean; | |
| 77 | readonly picked: Pick; | |
| 78 | /** What the run is budgeted, the reserve included. */ | |
| 79 | readonly budget: number; | |
| 80 | /** Git's environment for the clone and the credential the run's tools carry. */ | |
| 81 | readonly gitEnv: Record<string, string>; | |
| 82 | readonly forgeToken: { readonly id: string; readonly token: string }; | |
| 83 | readonly grant: Grant; | |
| 84 | /** The session this run resumes, and what was said about resuming it. */ | |
| 85 | readonly previousSessionId: string | undefined; | |
| 86 | readonly resumeWhy: string; | |
| 87 | readonly dir: string; | |
| 88 | readonly modelHold: string; | |
| 89 | readonly held: Held; | |
| 90 | readonly meter: Meter; | |
| 91 | readonly signal: AbortSignal; | |
| 92 | readonly write: (line: string) => void; | |
| 93 | } | |
| 94 | ||
| 95 | /** What the run goes on with. */ | |
| 96 | export interface Prepared { | |
| 97 | /** Runs the agent once, its tokens and spend added to the meter. */ | |
| 98 | readonly invoke: ( | |
| 99 | prompt: string, | |
| 100 | budgetUsd: number, | |
| 101 | resume: string | undefined, | |
| 102 | ) => Promise<AgentOutcome>; | |
| 103 | readonly deadline: number; | |
| 104 | /** What the wrap-up may spend. */ | |
| 105 | readonly reserve: number; | |
| 106 | /** What the work may spend: the budget less the reserve. */ | |
| 107 | readonly working: number; | |
| 108 | } | |
| 109 | ||
| 110 | /** What the agent said, with every held secret value taken out of it. */ | |
| 111 | function redactResult<T extends { result: string }>(r: T): T { | |
| 112 | return { ...r, result: redactValues(r.result) }; | |
| 113 | } | |
| 114 | ||
| 115 | export async function prepareAgent(s: PrepareState): Promise<Prepared> { | |
| 116 | const { app, options, run, repo, agent, issue, brief, picked, budget, grant, held, meter, signal, write } = s; | |
| 117 | const started = Date.now(); | |
| 118 | // The model credential sits in the agent's environment, where its shell | |
| 119 | // can read it. Held like a granted secret from before the agent starts | |
| 120 | // until the `finally` below: a run that says it leaves `[redacted]` in | |
| 121 | // its log, its last message and every event. The gateway's address is | |
| 122 | // not a secret and stays readable. | |
| 123 | const modelEnv = credentialEnv(picked, app.config.dataDir); | |
| 124 | held.modelSecrets = holdModelCredential(s.modelHold, modelEnv); | |
| 125 | const env = layerRunEnv({ | |
| 126 | forge: { | |
| 127 | // The shard count an admin set (`core/capacity.ts`), for the checks an | |
| 128 | // agent runs in its clone; never the pod's environment. | |
| 129 | ...capacityEnv(app.db), | |
| 130 | ...s.gitEnv, | |
| 131 | FORGE_URL: options.forgeUrl, | |
| 132 | FORGE_TOKEN: s.forgeToken.token, | |
| 133 | ...passportEnv(app.config.dataDir), | |
| 134 | }, | |
| 135 | // Granted secrets sit under the model's own variables (`layerRunEnv`). | |
| 136 | granted: grant.env, | |
| 137 | model: modelEnv, | |
| 138 | machine: machineEnv(s.machine), | |
| 139 | configDir: options.configDir, | |
| 140 | }); | |
| 141 | // The budget in two parts: the work, and a reserve for landing it. An | |
| 142 | // agent cut off mid-task otherwise leaves a tree the forge commits blind | |
| 143 | // and a pull whose description is the error. | |
| 144 | // A member's gateway is a name they keep: Claude Code dials the forge's | |
| 145 | // loopback door, which resolves the name, judges every address and | |
| 146 | // dials only a public one (`crew/gateway_door.ts`, #14750). | |
| 147 | held.gatewayDoor = doorForRun(picked, env); | |
| 148 | const reserve = wrapUpReserve(budget); | |
| 149 | // Asked again for every invocation (`crew/sandbox.ts`): an agent made | |
| 150 | // since the last one is denied from this one on. | |
| 151 | const hosts = grant.hosts; | |
| 152 | const shellPolicy = () => | |
| 153 | sandboxPolicy({ | |
| 154 | dataDir: app.config.dataDir, | |
| 155 | agentName: agent.user.username, | |
| 156 | urls: [options.localUrl, options.forgeUrl], | |
| 157 | appUrls: reachableApps(s.machine, ownAppUrls(ownApp(app, repo))), | |
| 158 | extraHosts: [ | |
| 159 | ...(options.allowHosts ?? []), | |
| 160 | ...hosts, | |
| 161 | ...(held.devices?.hosts ?? []), | |
| 162 | ], | |
| 163 | gateway: held.gatewayDoor?.base, | |
| 164 | enforced: options.sandboxEnforced, | |
| 165 | runId: run.id, | |
| 166 | repoId: repo.id, | |
| 167 | }); | |
| 168 | const sandbox = shellPolicy(); | |
| 169 | // The run's own temp directory, never the machine's shared one; it goes | |
| 170 | // when the run does (the `finally` below). Both names: Claude Code's | |
| 171 | // sandbox reads its own temp-dir variable, but its shell still binds | |
| 172 | // `<TMPDIR>/claude-<uid>` writable, so TMPDIR has to say the same. | |
| 173 | held.runTmp = sandbox.tmpDir; | |
| 174 | if (held.runTmp !== undefined) { | |
| 175 | makeRunTmp(app.config.dataDir, held.runTmp); | |
| 176 | Object.assign(env, sandboxTmpEnv(held.runTmp)); | |
| 177 | env["TMPDIR"] = held.runTmp; | |
| 178 | // The devices the owner granted this repository: a key file, a pinned | |
| 179 | // known_hosts and an `ssh` wrapper that logs, all inside the run's own | |
| 180 | // temp directory, which goes with the run. | |
| 181 | held.devices = deviceKit( | |
| 182 | app.db, | |
| 183 | app.config.dataDir, | |
| 184 | app.bus, | |
| 185 | { id: run.id, repoId: repo.id, actorId: agent.user.id }, | |
| 186 | held.runTmp, | |
| 187 | ); | |
| 188 | if (held.devices !== undefined) { | |
| 189 | env["PATH"] = `${held.devices.binDir}:${process.env["PATH"] ?? "/usr/local/bin:/usr/bin:/bin"}`; | |
| 190 | for (const [alias, entry] of Object.entries(held.devices.aliases)) | |
| 191 | write(`device: ssh ${alias} is ${entry}`); | |
| 192 | for (const entry of held.devices.missing) | |
| 193 | write(`device not reachable: ${entry} (its key is not a repository secret)`); | |
| 194 | } | |
| 195 | } | |
| 196 | // Bun's install cache is the repository's, shared by its runs, so a | |
| 197 | // package is downloaded once rather than by every clone. | |
| 198 | installCacheEnv(sandbox, env); | |
| 199 | // The sandbox refuses a unix socket's bind; the forge's own servers take | |
| 200 | // a loopback port instead (`git/hook-address.ts`), so `bun test` runs. | |
| 201 | if (sandbox.enforced) env["FORGE_TEST_SOCKET"] = "port"; | |
| 202 | // One deadline for the run, whatever it takes to get there: the token | |
| 203 | // dies ten minutes after it, so a second invocation gets what is left. | |
| 204 | const deadline = Date.now() + options.runTimeoutMs; | |
| 205 | // The token was minted before the setup above spent time: hold it to the deadline (#16106). | |
| 206 | keepToken(app.db, s.forgeToken.id, deadline); | |
| 207 | // The agent's own model, unless the work asks for Opus (#7570). A | |
| 208 | // planner's plain pass runs on Sonnet; one handed work the crew could | |
| 209 | // not finish runs on Opus (`model_choice.ts`). | |
| 210 | const handed = | |
| 211 | brief.role === "planner" && | |
| 212 | (parkedTwice(app.db, [repo]).length > 0 || | |
| 213 | handedTooLarge(app.db, repo).length > 0 || | |
| 214 | handedOverPulls(app.db, repo).length > 0 || | |
| 215 | handedLimbs(app, repo).length > 0); | |
| 216 | const facts = modelFacts( | |
| 217 | app.db, | |
| 218 | repo, | |
| 219 | s.taskIssue === undefined ? [issue] : [issue, s.taskIssue], | |
| 220 | agent.model, | |
| 221 | brief.role, | |
| 222 | s.reviewing, | |
| 223 | handed, | |
| 224 | ); | |
| 225 | const chosen = chooseModel(facts); | |
| 226 | const invoke = async ( | |
| 227 | prompt: string, | |
| 228 | budgetUsd: number, | |
| 229 | resume: string | undefined, | |
| 230 | ): Promise<AgentOutcome> => { | |
| 231 | const spent = redactResult( | |
| 232 | await runAgent({ | |
| 233 | binary: options.binary, | |
| 234 | cwd: s.dir, | |
| 235 | prompt, | |
| 236 | appendSystemPrompt: systemPrompt({ ...brief, devices: held.devices?.aliases }), | |
| 237 | model: chosen.model || undefined, | |
| 238 | budgetUsd, | |
| 239 | account: runAccount(picked, env), | |
| 240 | resume, | |
| 241 | env, | |
| 242 | sandbox: shellPolicy(), | |
| 243 | limits: machineLimits(s.machine), | |
| 244 | label: `crew:${agent.user.username}`, | |
| 245 | timeoutMs: Math.max(deadline - Date.now(), 0), | |
| 246 | log: write, | |
| 247 | signal, | |
| 248 | onSteer: (send) => { | |
| 249 | listenForSteer(run.id, send); | |
| 250 | }, | |
| 251 | onMeasure: (m) => noteMeasure(app.db, meter.subscriptionId ?? PLATFORM, m), | |
| 252 | onCleared: (window) => forgetMeasure(app.db, meter.subscriptionId ?? PLATFORM, window), | |
| 253 | onUsage: (so) => | |
| 254 | meterLive( | |
| 255 | app, | |
| 256 | run, | |
| 257 | meter, | |
| 258 | { | |
| 259 | tokensIn: meter.tokensIn + so.tokensIn, | |
| 260 | tokensOut: meter.tokensOut + so.tokensOut, | |
| 261 | costUsd: meter.costUsd + (so.costUsd ?? 0), | |
| 262 | }, | |
| 263 | started, | |
| 264 | (so.costUsd ?? 0) > 0, | |
| 265 | ), | |
| 266 | }), | |
| 267 | ); | |
| 268 | meter.tokensIn += spent.tokensIn; | |
| 269 | meter.tokensOut += spent.tokensOut; | |
| 270 | meter.costUsd += spent.costUsd ?? 0; | |
| 271 | return spent; | |
| 272 | }; | |
| 273 | // The runner and model this run uses, and what holds its spend: a runner | |
| 274 | // with no price says so instead of a dollar budget it cannot keep. | |
| 275 | const heading = currentRunner().heading?.(chosen.model || undefined, env); | |
| 276 | write( | |
| 277 | `${heading ?? `claude${chosen.model ? ` (${chosen.model})` : ""}: budget $${budget.toFixed(2)}, $${reserve.toFixed(2)} of it kept for the wrap-up`}${brief.resuming ? `, resuming ${s.previousSessionId}` : ""}`, | |
| 278 | ); | |
| 279 | if (!s.reviewing && s.resumeWhy !== "") write(s.resumeWhy); | |
| 280 | noteRunProgress(app.db, run.id, { | |
| 281 | model: chosen.model, | |
| 282 | modelReason: chosen.reason, | |
| 283 | promptVersion: promptVersion(agent, brief.role), | |
| 284 | sandbox: { | |
| 285 | enforced: sandbox.enforced, | |
| 286 | note: options.sandboxNote ?? "", | |
| 287 | }, | |
| 288 | }); | |
| 289 | if (!sandbox.enforced) | |
| 290 | write( | |
| 291 | `sandbox: off here${options.sandboxNote === undefined ? "" : ` — ${options.sandboxNote}`}; the shell runs unrestricted`, | |
| 292 | ); | |
| 293 | return { invoke, deadline, reserve, working: budget - reserve }; | |
| 294 | } |
src/crew/run_prompt.ts added +315
| @@ -0,0 +1,315 @@ | ||
| 1 | /** | |
| 2 | * The task prompt an agent is first told: the issue, the pull and its conversation, and whatever | |
| 3 | * the run's reason adds (a failed check, a conflict, a review's diff, a planner's handed work). | |
| 4 | * Read from the database and the repository; writes nothing. | |
| 5 | */ | |
| 6 | ||
| 7 | import { join } from "node:path"; | |
| 8 | import { UPSTREAM_TITLE, sourceFollowing, upstreamFollowing } from "../actions/upstream_follow.ts"; | |
| 9 | import type { App } from "../app.ts"; | |
| 10 | import type { Agent } from "../core/agents.ts"; | |
| 11 | import type { AppRecord } from "../core/apps.ts"; | |
| 12 | import { labelsForIssues, listComments, type Issue } from "../core/issues.ts"; | |
| 13 | import { looksForEnv } from "../core/looks.ts"; | |
| 14 | import { pullDir, type Pull } from "../core/pulls.ts"; | |
| 15 | import { forkParentFor, type Repo } from "../core/repos.ts"; | |
| 16 | import { listReviewComments, listReviews } from "../core/reviews.ts"; | |
| 17 | import type { Run } from "../core/runs.ts"; | |
| 18 | import type { User } from "../core/users.ts"; | |
| 19 | import { runGitCapture } from "../git/env.ts"; | |
| 20 | import { resolveOid } from "../git/merge.ts"; | |
| 21 | import { lastWeekFor } from "./last_week.ts"; | |
| 22 | import { boxesOf, landedBoxes } from "./box_pass.ts"; | |
| 23 | import { taskPrompt, type BriefInput, type LastTry, type RunReason, type TaskInput } from "./brief.ts"; | |
| 24 | import { holdsNaming } from "./desk_posts.ts"; | |
| 25 | import { readersAmong, voiceOf } from "./direct.ts"; | |
| 26 | import { failureBrief } from "./failure_brief.ts"; | |
| 27 | import { RETRY_SUMMARY, handedOverPulls } from "./guard.ts"; | |
| 28 | import { handedLimbs } from "./handed_limbs.ts"; | |
| 29 | import { heldNow, stuckOf } from "./held.ts"; | |
| 30 | import { laterGate } from "./later.ts"; | |
| 31 | import { feedbackSince } from "./news.ts"; | |
| 32 | import { parkReasons, parkedTwice } from "./parks.ts"; | |
| 33 | import { resolutionBrief } from "./proposal.ts"; | |
| 34 | import { reviewRange } from "./review_range.ts"; | |
| 35 | import { touchesDesign } from "./review.ts"; | |
| 36 | import { SEALED_REMOTE } from "./sealed_head.ts"; | |
| 37 | import { reviewSourceNote } from "./source_held.ts"; | |
| 38 | import { isStrangerPull } from "./stranger.ts"; | |
| 39 | import { owed } from "./team_share.ts"; | |
| 40 | import { handedTooLarge } from "./too_large.ts"; | |
| 41 | ||
| 42 | /** What `promptFor` is given: plain data, read-only. */ | |
| 43 | export interface PromptState { | |
| 44 | readonly app: App; | |
| 45 | readonly run: Run; | |
| 46 | readonly repo: Repo; | |
| 47 | readonly issue: Issue; | |
| 48 | readonly agent: Agent; | |
| 49 | readonly pull: Pull | undefined; | |
| 50 | /** The merged or foreign pull this run continues from, whose diff the brief carries. */ | |
| 51 | readonly foreign: Pull | undefined; | |
| 52 | readonly reason: RunReason; | |
| 53 | readonly brief: BriefInput; | |
| 54 | readonly branch: string; | |
| 55 | /** The repository's bare path, and its agent fork's. */ | |
| 56 | readonly bare: string; | |
| 57 | readonly forkBare: string; | |
| 58 | readonly record: AppRecord | undefined; | |
| 59 | readonly sealedHead: Repo | undefined; | |
| 60 | readonly since: ReturnType<typeof feedbackSince>; | |
| 61 | readonly signal: AbortSignal; | |
| 62 | } | |
| 63 | ||
| 64 | export async function promptFor(s: PromptState): Promise<string> { | |
| 65 | const { app, run, repo, issue, agent, pull, foreign, reason, brief, branch, bare, forkBare, record, sealedHead, since, signal } = s; | |
| 66 | const role = brief.role; | |
| 67 | // Only a check or deploy that failed is handed back as the failure (#12968): never the | |
| 68 | // success summary of a preview that came up. | |
| 69 | const failure = failureBrief( | |
| 70 | app.db, | |
| 71 | app.config.dataDir, | |
| 72 | reason, | |
| 73 | pull?.id, | |
| 74 | pull ? ((await resolveOid(forkBare, `refs/heads/${branch}`)) ?? pull.headOid) : "", | |
| 75 | ); | |
| 76 | // Imported words speak as their origin author (`voiceOf`), so the | |
| 77 | // brief marks a stranger's as a reader's, not the connecting user's. | |
| 78 | const comments = listComments(app.db, issue.id, { kind: "comment" }).map( | |
| 79 | voiceOf, | |
| 80 | ); | |
| 81 | const reviews = pull ? listReviews(app.db, pull.id).map(voiceOf) : []; | |
| 82 | const reviewComments = pull | |
| 83 | ? listReviewComments(app.db, pull.id).map(voiceOf) | |
| 84 | : []; | |
| 85 | return taskPrompt({ | |
| 86 | ...brief, | |
| 87 | issue: voiceOf(brief.issue), | |
| 88 | reason, | |
| 89 | ...(role === "builder" ? { holds: holdsNaming(app.db, repo) } : {}), | |
| 90 | paused: run.attempt > 0, | |
| 91 | stranger: | |
| 92 | reason === "review" && pull !== undefined | |
| 93 | ? isStrangerPull(app.db, repo, pull) | |
| 94 | : undefined, | |
| 95 | comments, | |
| 96 | labels: (labelsForIssues(app.db, [issue.id]).get(issue.id) ?? []).map( | |
| 97 | (label) => label.name, | |
| 98 | ), | |
| 99 | reviews, | |
| 100 | reviewComments, | |
| 101 | readers: readersAmong( | |
| 102 | app.db, | |
| 103 | repo, | |
| 104 | [voiceOf(issue), ...comments, ...reviews, ...reviewComments].map( | |
| 105 | (c) => c.authorName, | |
| 106 | ), | |
| 107 | ), | |
| 108 | since, | |
| 109 | lastTry: | |
| 110 | reason === "feedback" && run.summary === RETRY_SUMMARY | |
| 111 | ? lastTryOf(app, issue.id, run, reviews) | |
| 112 | : undefined, | |
| 113 | ...failure, | |
| 114 | foreignPull: foreign | |
| 115 | ? { | |
| 116 | branch: foreign.headBranch, | |
| 117 | diff: ( | |
| 118 | await reviewInputs(app, repo, foreign, undefined, await pullDir(app.db, app.reposRoot, repo, foreign)) | |
| 119 | ).reviewDiff, | |
| 120 | } | |
| 121 | : undefined, | |
| 122 | resolution: | |
| 123 | reason === "resolve" && pull | |
| 124 | ? await resolutionBrief(app, repo, pull) | |
| 125 | : undefined, | |
| 126 | conflictFiles: | |
| 127 | reason === "conflict" || reason === "converge" | |
| 128 | ? conflictFilesOf(run.summary) | |
| 129 | : undefined, | |
| 130 | following: | |
| 131 | reason === "converge" | |
| 132 | ? convergeFollowing(app, repo, issue, agent.user) | |
| 133 | : undefined, | |
| 134 | ...(reason === "review" && pull | |
| 135 | ? { | |
| 136 | // A sealed pull's head is in its builder's sealed fork, not the base (#14917). | |
| 137 | ...(await reviewInputs(app, repo, pull, record, await pullDir(app.db, app.reposRoot, repo, pull), signal)), | |
| 138 | sourceNote: await reviewSourceNote(app, repo, pull, bare), | |
| 139 | ...(sealedHead === undefined ? {} : { sealedRef: `${SEALED_REMOTE}/${pull.headBranch}` }), | |
| 140 | boxes: boxesOf(app, repo, pull), | |
| 141 | retry: | |
| 142 | app.db | |
| 143 | .query<{ n: number }, [string, string, string]>( | |
| 144 | `SELECT COUNT(*) AS n FROM run WHERE issue_id = ?1 AND kind = 'agent' | |
| 145 | AND reason = 'review' AND state = 'failed' AND id <> ?2 | |
| 146 | AND created_at < ?3`, | |
| 147 | ) | |
| 148 | .get(issue.id, run.id, run.createdAt)!.n > 0, | |
| 149 | } | |
| 150 | : {}), | |
| 151 | ...(brief.role === "builder" && issue.id !== repo.directionIssueId | |
| 152 | ? { earlierParks: parkReasons(app.db, repo, issue.id) } | |
| 153 | : {}), | |
| 154 | // A planning run is given what the crew handed over (`parks.ts`), | |
| 155 | // what holds the ready list when nothing on it can start (`held.ts`). | |
| 156 | ...(brief.role === "planner" && issue.id === repo.directionIssueId | |
| 157 | ? { | |
| 158 | parkedTwice: [ | |
| 159 | ...parkedTwice(app.db, [repo]), | |
| 160 | ...handedTooLarge(app.db, repo), | |
| 161 | ...handedOverPulls(app.db, repo), | |
| 162 | ], | |
| 163 | limbs: handedLimbs(app, repo), | |
| 164 | laterGate: laterGate(app.db, repo.id), | |
| 165 | lastWeek: lastWeekFor(app, repo), | |
| 166 | ...(() => { | |
| 167 | const held = heldNow(app, repo); | |
| 168 | return { | |
| 169 | landed: landedBoxes(held.by.landed), | |
| 170 | stuck: stuckOf(held), | |
| 171 | }; | |
| 172 | })(), | |
| 173 | owed: owed(app.db, repo.id), | |
| 174 | } | |
| 175 | : {}), | |
| 176 | }); | |
| 177 | } | |
| 178 | ||
| 179 | /** | |
| 180 | * What a reviewer reads: the pull's diff (`review_range.ts` — a landed pull's | |
| 181 | * is its merge commit's), and its pictures. `landedAs` names the merge commit | |
| 182 | * the diff was read from, when it was. | |
| 183 | */ | |
| 184 | export async function reviewInputs( | |
| 185 | app: App, | |
| 186 | repo: Repo, | |
| 187 | pull: Pull, | |
| 188 | record: AppRecord | undefined, | |
| 189 | bare: string, | |
| 190 | /** | |
| 191 | * The run's own: a review past its budget stops reading the diff instead of finishing it | |
| 192 | * (#16096). | |
| 193 | */ | |
| 194 | signal?: AbortSignal, | |
| 195 | ): Promise<{ | |
| 196 | reviewDiff: string; | |
| 197 | looks: string[]; | |
| 198 | design: boolean; | |
| 199 | landedAs?: string; | |
| 200 | }> { | |
| 201 | const range = await reviewRange(bare, pull); | |
| 202 | let reviewDiff = "(no diff available)"; | |
| 203 | let design = false; | |
| 204 | if (range !== undefined) { | |
| 205 | const names = await runGitCapture( | |
| 206 | ["diff", "--name-only", range.from, range.to], | |
| 207 | { cwd: bare, ...(signal === undefined ? {} : { signal }) }, | |
| 208 | ); | |
| 209 | design = touchesDesign( | |
| 210 | names.stdout | |
| 211 | .toString() | |
| 212 | .split("\n") | |
| 213 | .filter((n) => n !== ""), | |
| 214 | ); | |
| 215 | const out = await runGitCapture( | |
| 216 | ["diff", "--stat", "-p", range.from, range.to], | |
| 217 | { cwd: bare, ...(signal === undefined ? {} : { signal }) }, | |
| 218 | ); | |
| 219 | const text = out.stdout.toString(); | |
| 220 | if (out.code === 0) | |
| 221 | reviewDiff = | |
| 222 | text.length > REVIEW_DIFF_MAX | |
| 223 | ? `${text.slice(0, REVIEW_DIFF_MAX)}\n… (cut at ${REVIEW_DIFF_MAX} bytes)` | |
| 224 | : text; | |
| 225 | } | |
| 226 | const looks = | |
| 227 | record === undefined | |
| 228 | ? [] | |
| 229 | : looksForEnv(app.db, record.id, `pull-${pull.number}`) | |
| 230 | .filter( | |
| 231 | (l) => | |
| 232 | l.commitOid === pull.headOid && | |
| 233 | l.error === null && | |
| 234 | (l.kind === "phone" || l.kind === "desktop"), | |
| 235 | ) | |
| 236 | .sort( | |
| 237 | (a, b) => | |
| 238 | (a.kind === "phone" ? -1 : 1) - (b.kind === "phone" ? -1 : 1), | |
| 239 | ) | |
| 240 | .map((l) => | |
| 241 | l.path.startsWith("/") ? l.path : join(app.config.dataDir, l.path), | |
| 242 | ); | |
| 243 | return { | |
| 244 | reviewDiff, | |
| 245 | looks, | |
| 246 | design, | |
| 247 | ...(range?.landed === true && reviewDiff !== "(no diff available)" | |
| 248 | ? { landedAs: range.to } | |
| 249 | : {}), | |
| 250 | }; | |
| 251 | } | |
| 252 | ||
| 253 | const REVIEW_DIFF_MAX = 60 * 1024; | |
| 254 | ||
| 255 | /** | |
| 256 | * What a retried follow-up is told: the latest verdict asking for changes, and the last builder | |
| 257 | * run's final answer. | |
| 258 | */ | |
| 259 | export function lastTryOf( | |
| 260 | app: App, | |
| 261 | pullId: string, | |
| 262 | run: Run, | |
| 263 | reviews: readonly { state: string; authorName: string; body: string }[], | |
| 264 | ): LastTry | undefined { | |
| 265 | const verdict = reviews.findLast((r) => r.state === "changes_requested"); | |
| 266 | if (verdict === undefined) return undefined; | |
| 267 | const answer = app.db | |
| 268 | .query<{ summary: string }, [string, string]>( | |
| 269 | `SELECT summary FROM run WHERE issue_id = ?1 AND kind = 'agent' AND reason != 'review' | |
| 270 | AND id <> ?2 AND summary NOT LIKE 'skipped: %' | |
| 271 | ORDER BY created_at DESC, id DESC LIMIT 1`, | |
| 272 | ) | |
| 273 | .get(pullId, run.id); | |
| 274 | return { | |
| 275 | reviewer: verdict.authorName, | |
| 276 | verdict: verdict.body, | |
| 277 | answer: answer?.summary ?? "", | |
| 278 | }; | |
| 279 | } | |
| 280 | ||
| 281 | /** | |
| 282 | * The file names a conflict or converge run's summary carries, after "main|parent|upstream moved: | |
| 283 | * ". | |
| 284 | */ | |
| 285 | export function conflictFilesOf(summary: string): string[] { | |
| 286 | return summary | |
| 287 | .replace(/^(main|parent|upstream) moved: /, "") | |
| 288 | .split(", ") | |
| 289 | .filter((f) => f !== ""); | |
| 290 | } | |
| 291 | ||
| 292 | /** | |
| 293 | * What a converge brief says the repository follows: the outside upstream | |
| 294 | * for an issue titled "Upstream: …", else a forge parent the agent may read. | |
| 295 | */ | |
| 296 | export function convergeFollowing( | |
| 297 | app: App, | |
| 298 | repo: Repo, | |
| 299 | issue: Issue, | |
| 300 | user: User, | |
| 301 | ): TaskInput["following"] { | |
| 302 | if (issue.title.startsWith(UPSTREAM_TITLE)) { | |
| 303 | const upstream = | |
| 304 | sourceFollowing(app, issue.id) ?? upstreamFollowing(app, repo.id); | |
| 305 | if (upstream !== undefined) return upstream; | |
| 306 | } | |
| 307 | // Only a parent the agent may read is put in its brief. | |
| 308 | const parent = forkParentFor(app.db, repo, user); | |
| 309 | return parent === undefined | |
| 310 | ? undefined | |
| 311 | : { | |
| 312 | parent: `${parent.ownerName}/${parent.name}`, | |
| 313 | branch: parent.defaultBranch, | |
| 314 | }; | |
| 315 | } |
src/crew/run_retry.ts added +81
| @@ -0,0 +1,81 @@ | ||
| 1 | /** | |
| 2 | * A dropped connection says nothing about the work: the session is asked again before the run is | |
| 3 | * judged, and one that is still unreachable after the retries is an outage, not a verdict. | |
| 4 | */ | |
| 5 | ||
| 6 | import type { AgentOutcome } from "./agent_runner.ts"; | |
| 7 | import { MAX_PAUSES, whenText } from "./limits.ts"; | |
| 8 | import { isNetworkError, NETWORK_PAUSE_MS, NETWORK_RETRY_SECONDS, pause } from "./network.ts"; | |
| 9 | import type { Outcome } from "./meter.ts"; | |
| 10 | ||
| 11 | /** What the retry steps are given: plain data and the one thing that asks the session again. */ | |
| 12 | export interface RetryState { | |
| 13 | /** Runs the agent once more: the prompt, its budget, the session to resume. */ | |
| 14 | readonly invoke: ( | |
| 15 | prompt: string, | |
| 16 | budgetUsd: number, | |
| 17 | resume: string | undefined, | |
| 18 | ) => Promise<AgentOutcome>; | |
| 19 | readonly signal: AbortSignal; | |
| 20 | /** When the run's deadline falls (epoch ms). */ | |
| 21 | readonly deadline: number; | |
| 22 | /** How many times the run has paused already. */ | |
| 23 | readonly attempt: number; | |
| 24 | /** Scales the wait before a retry; tests pass 0. */ | |
| 25 | readonly waitScale: number; | |
| 26 | readonly write: (line: string) => void; | |
| 27 | } | |
| 28 | ||
| 29 | /** | |
| 30 | * Asks again while the last answer was a network error. `next` names the prompt and session for | |
| 31 | * each new ask, given what the last one left; the main turn and the wrap-up share this. | |
| 32 | */ | |
| 33 | export async function retryNetwork( | |
| 34 | s: RetryState, | |
| 35 | first: AgentOutcome, | |
| 36 | budgetUsd: number, | |
| 37 | what: string, | |
| 38 | next: (last: AgentOutcome) => { prompt: string; sessionId: string | undefined }, | |
| 39 | ): Promise<AgentOutcome> { | |
| 40 | let current = first; | |
| 41 | for (const seconds of NETWORK_RETRY_SECONDS) { | |
| 42 | if (!isNetworkError(current) || s.signal.aborted) break; | |
| 43 | s.write(`network error; retrying${what} in ${seconds}s`); | |
| 44 | await pause(seconds * 1000 * s.waitScale, s.signal); | |
| 45 | if (s.signal.aborted || Date.now() >= s.deadline) break; | |
| 46 | const ask = next(current); | |
| 47 | const again = await s.invoke(ask.prompt, budgetUsd, ask.sessionId); | |
| 48 | current = { | |
| 49 | ...again, | |
| 50 | sessionId: again.sessionId || current.sessionId, | |
| 51 | costUsd: current.costUsd + again.costUsd, | |
| 52 | turns: current.turns + again.turns, | |
| 53 | contextTokens: again.contextTokens || current.contextTokens, | |
| 54 | }; | |
| 55 | } | |
| 56 | return current; | |
| 57 | } | |
| 58 | ||
| 59 | /** | |
| 60 | * Still unreachable after the retries: an outage, not a verdict. The run pauses with its clone and | |
| 61 | * session and asks again later, as it does for a provider limit, rather than ending as "no changes | |
| 62 | * pushed". Nothing when the answer was not an outage or the run may not pause again. | |
| 63 | */ | |
| 64 | export function outagePause(s: RetryState, last: AgentOutcome, costUsd: number): Outcome | undefined { | |
| 65 | if ( | |
| 66 | !isNetworkError(last) || | |
| 67 | s.signal.aborted || | |
| 68 | Date.now() >= s.deadline || | |
| 69 | s.attempt >= MAX_PAUSES | |
| 70 | ) | |
| 71 | return undefined; | |
| 72 | const at = new Date(Date.now() + NETWORK_PAUSE_MS); | |
| 73 | s.write(`network still down; paused, resumes ${whenText(at)}`); | |
| 74 | return { | |
| 75 | state: "paused", | |
| 76 | summary: `paused: network error, resumes ${whenText(at)}`, | |
| 77 | resumeAt: at.toISOString(), | |
| 78 | sessionId: last.sessionId, | |
| 79 | costUsd, | |
| 80 | }; | |
| 81 | } |
src/crew/run_settle.ts added +175
| @@ -0,0 +1,175 @@ | ||
| 1 | /** | |
| 2 | * What a run is judged on once its agent has stopped: a cancel the run did not outrun, a token the | |
| 3 | * forge stopped honouring, the runs whose work is not a push (a decline, a verdict), and | |
| 4 | * otherwise the landing of what the agent left, said as the run's outcome. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { App } from "../app.ts"; | |
| 8 | import type { Agent } from "../core/agents.ts"; | |
| 9 | import type { Issue } from "../core/issues.ts"; | |
| 10 | import type { Pull } from "../core/pulls.ts"; | |
| 11 | import type { Repo } from "../core/repos.ts"; | |
| 12 | import type { Run } from "../core/runs.ts"; | |
| 13 | import type { AgentOutcome } from "./agent_runner.ts"; | |
| 14 | import { answeredBeforeStop } from "./already.ts"; | |
| 15 | import type { Ending } from "./early.ts"; | |
| 16 | import { cutOffBy, type budgetVerdict } from "./forge_budget.ts"; | |
| 17 | import type { Hops } from "./hops.ts"; | |
| 18 | import { landWork } from "./land_work.ts"; | |
| 19 | import { MAX_PAUSES } from "./limits.ts"; | |
| 20 | import type { Meter, Outcome } from "./meter.ts"; | |
| 21 | import { isNetworkError } from "./network.ts"; | |
| 22 | import { verdictOf } from "./run_verdict.ts"; | |
| 23 | import type { CrewOptions } from "./runner.ts"; | |
| 24 | import { refusedToken } from "./token_refused.ts"; | |
| 25 | ||
| 26 | /** What `settleRun` is given: plain data, the run's meter, and what it writes to. */ | |
| 27 | export interface SettleState { | |
| 28 | readonly app: App; | |
| 29 | readonly options: CrewOptions; | |
| 30 | readonly run: Run; | |
| 31 | readonly repo: Repo; | |
| 32 | readonly agent: Agent; | |
| 33 | readonly issue: Issue; | |
| 34 | /** The pull the task opened or continues, when there is one. */ | |
| 35 | readonly pull: Pull | undefined; | |
| 36 | /** The pull's branch lives in another fork: this run started a fresh one. */ | |
| 37 | readonly foreign: Pull | undefined; | |
| 38 | /** The pull is a merged (or foreign) one's follow-up: it lands as a pull of its own. */ | |
| 39 | readonly continuing: boolean; | |
| 40 | readonly reviewing: boolean; | |
| 41 | /** The agent's own fork. */ | |
| 42 | readonly fork: Repo; | |
| 43 | readonly branch: string; | |
| 44 | readonly dir: string; | |
| 45 | readonly bare: string; | |
| 46 | readonly forkBare: string; | |
| 47 | /** Git's environment for the clone: the run's credential and the agent's identity. */ | |
| 48 | readonly gitEnv: Record<string, string>; | |
| 49 | /** Every value held for redaction, scrubbed from the tree before it is committed. */ | |
| 50 | readonly secrets: readonly string[]; | |
| 51 | readonly meter: Meter; | |
| 52 | readonly hops: Hops; | |
| 53 | /** The run's token and the deadline it was held to. */ | |
| 54 | readonly tokenId: string; | |
| 55 | readonly deadline: number; | |
| 56 | readonly began: string; | |
| 57 | readonly signal: AbortSignal; | |
| 58 | /** The answer to judge, the wrap-up's included. */ | |
| 59 | readonly result: AgentOutcome; | |
| 60 | /** What the main turn had spent when the budget ran out and the reserve was used. */ | |
| 61 | readonly stoppedAt: number | undefined; | |
| 62 | /** When the provider's limit lifts, for a run that is not paused for it. */ | |
| 63 | readonly limitLifts: Date | undefined; | |
| 64 | /** What the forge's own limits left this run. */ | |
| 65 | readonly own: ReturnType<typeof budgetVerdict>; | |
| 66 | readonly write: (line: string) => void; | |
| 67 | } | |
| 68 | ||
| 69 | /** The run's outcome, and the ending its pull is settled with when the step decided one. */ | |
| 70 | export interface Settled { | |
| 71 | readonly outcome: Outcome; | |
| 72 | readonly ending?: Ending | undefined; | |
| 73 | } | |
| 74 | ||
| 75 | /** The paragraphs a pull description opens with, or nothing when there are none. */ | |
| 76 | export function pullNote(...parts: (string | undefined)[]): string | undefined { | |
| 77 | const present = parts.filter((part): part is string => part !== undefined); | |
| 78 | return present.length === 0 ? undefined : present.join("\n\n"); | |
| 79 | } | |
| 80 | ||
| 81 | export async function settleRun(s: SettleState): Promise<Settled> { | |
| 82 | const { app, run, repo, agent, issue, pull, foreign, result, stoppedAt, write } = s; | |
| 83 | // A run whose pull closed under it may still have reached its answer: an | |
| 84 | // already-done decline is kept (`answerCancelled`). One the meter stopped is not. | |
| 85 | if (s.signal.aborted && !answeredBeforeStop(s.meter.stoppedFor, result.result)) | |
| 86 | return { | |
| 87 | outcome: { | |
| 88 | state: "failed", | |
| 89 | summary: s.meter.stoppedFor ?? "cancelled", | |
| 90 | sessionId: result.sessionId, | |
| 91 | costUsd: result.costUsd, | |
| 92 | turns: result.turns, | |
| 93 | contextTokens: result.contextTokens, | |
| 94 | }, | |
| 95 | }; | |
| 96 | ||
| 97 | // A token the forge stopped honouring mid-run refused every write: that is a failed run, | |
| 98 | // never an ok one that opened nothing (#16106). | |
| 99 | const refused = refusedToken(app.db, s.tokenId, s.deadline); | |
| 100 | if (refused !== undefined) { | |
| 101 | write(refused); | |
| 102 | return { | |
| 103 | outcome: { | |
| 104 | state: "failed", | |
| 105 | summary: refused, | |
| 106 | sessionId: result.sessionId, | |
| 107 | costUsd: result.costUsd, | |
| 108 | turns: result.turns, | |
| 109 | contextTokens: result.contextTokens, | |
| 110 | pushed: false, | |
| 111 | }, | |
| 112 | }; | |
| 113 | } | |
| 114 | ||
| 115 | const verdict = await verdictOf({ | |
| 116 | app, | |
| 117 | repo, | |
| 118 | agent, | |
| 119 | pull, | |
| 120 | reviewing: s.reviewing, | |
| 121 | bare: s.bare, | |
| 122 | began: s.began, | |
| 123 | result, | |
| 124 | write, | |
| 125 | }); | |
| 126 | if (verdict !== undefined) return { outcome: verdict.outcome, ending: verdict.ending }; | |
| 127 | ||
| 128 | // Bookkeeping the agent does not have to get right. | |
| 129 | const landed = await landWork( | |
| 130 | app, | |
| 131 | s.options, | |
| 132 | repo, | |
| 133 | agent, | |
| 134 | issue, | |
| 135 | s.continuing ? undefined : pull, | |
| 136 | s.fork, | |
| 137 | s.branch, | |
| 138 | s.dir, | |
| 139 | s.forkBare, | |
| 140 | s.bare, | |
| 141 | s.gitEnv, | |
| 142 | result.result, | |
| 143 | pullNote( | |
| 144 | foreign | |
| 145 | ? `A fresh start: pull #${foreign.number}'s branch \`${foreign.headBranch}\` lives in another fork, which the crew cannot push to, so this work began from \`${repo.defaultBranch}\` and does not carry that branch's commits.` | |
| 146 | : undefined, | |
| 147 | stoppedAt === undefined | |
| 148 | ? undefined | |
| 149 | : `Budget reached at $${stoppedAt.toFixed(2)}; this is where it stopped.`, | |
| 150 | ), | |
| 151 | write, | |
| 152 | s.secrets, | |
| 153 | run.variantGroup, | |
| 154 | s.hops, | |
| 155 | ); | |
| 156 | // An outage that outlasted every pause is named as one, not as a push | |
| 157 | // that found nothing: the board and the sentinel read the difference. | |
| 158 | const outage = !landed.pushed && isNetworkError(result); | |
| 159 | return { | |
| 160 | outcome: { | |
| 161 | state: result.ok || landed.pushed ? "ok" : "failed", | |
| 162 | summary: outage | |
| 163 | ? `network unreachable after ${MAX_PAUSES} pauses; nothing to land (${result.reason})` | |
| 164 | : landed.summary + | |
| 165 | (result.ok ? "" : ` (${result.reason})`) + | |
| 166 | cutOffBy(app.db, s.own, stoppedAt !== undefined), | |
| 167 | resumesAt: s.limitLifts, | |
| 168 | sessionId: result.sessionId, | |
| 169 | costUsd: result.costUsd, | |
| 170 | turns: result.turns, | |
| 171 | contextTokens: result.contextTokens, | |
| 172 | pushed: landed.pushed, | |
| 173 | }, | |
| 174 | }; | |
| 175 | } |
src/crew/run_spend.ts added +202
| @@ -0,0 +1,202 @@ | ||
| 1 | /** | |
| 2 | * What a run may spend, settled before its agent starts: the account it works on, the ceilings it | |
| 3 | * counts against, and the budget they leave. Every refusal is an outcome the run ends with, said | |
| 4 | * in the forge's words, never a model call that would be turned away. | |
| 5 | */ | |
| 6 | ||
| 7 | import { accountsSaid } from "../actions/crew_accounts.ts"; | |
| 8 | import type { App } from "../app.ts"; | |
| 9 | import type { Agent } from "../core/agents.ts"; | |
| 10 | import { reserveCeiling } from "../core/account_ceiling.ts"; | |
| 11 | import type { Repo } from "../core/repos.ts"; | |
| 12 | import type { Run } from "../core/runs.ts"; | |
| 13 | import { noteRunProgress } from "../core/runs.ts"; | |
| 14 | import { | |
| 15 | MIN_RUN_USD, | |
| 16 | pickSubscription, | |
| 17 | PLATFORM, | |
| 18 | type Pick, | |
| 19 | } from "../core/subscriptions.ts"; | |
| 20 | import { capReached } from "../core/wallet.ts"; | |
| 21 | import { cappedByLent, lentCreditLeft, lentSpent, refreshFundingOnce } from "../spawn/funding.ts"; | |
| 22 | import { budgetLimit, budgetVerdict, isOwnForge } from "./forge_budget.ts"; | |
| 23 | import { breathingUntil, breathWords, MAX_PAUSES, whenText } from "./limits.ts"; | |
| 24 | import { modelAccess } from "./model_access.ts"; | |
| 25 | import type { Meter, Outcome } from "./meter.ts"; | |
| 26 | ||
| 27 | /** What `settleSpend` is given: plain data, and the two things it writes to. */ | |
| 28 | export interface SpendState { | |
| 29 | readonly app: App; | |
| 30 | readonly run: Run; | |
| 31 | readonly repo: Repo; | |
| 32 | readonly agent: Agent; | |
| 33 | /** The spend a run gets when its agent has no budget of its own. */ | |
| 34 | readonly defaultBudgetUsd: number; | |
| 35 | /** The session the run resumes, for a pause that has to carry it. */ | |
| 36 | readonly previousSessionId: string | undefined; | |
| 37 | readonly meter: Meter; | |
| 38 | readonly write: (line: string) => void; | |
| 39 | } | |
| 40 | ||
| 41 | /** The account scope a run picks a subscription in. */ | |
| 42 | export interface SpendScope { | |
| 43 | readonly repoId: string; | |
| 44 | readonly ownerId: string; | |
| 45 | readonly agentId: string; | |
| 46 | } | |
| 47 | ||
| 48 | export type Spend = | |
| 49 | | { readonly ok: false; readonly outcome: Outcome } | |
| 50 | | { | |
| 51 | readonly ok: true; | |
| 52 | readonly picked: Pick; | |
| 53 | readonly scope: SpendScope; | |
| 54 | /** What the run is budgeted at most, wrap-up reserve included. */ | |
| 55 | readonly budget: number; | |
| 56 | readonly own: ReturnType<typeof budgetVerdict>; | |
| 57 | }; | |
| 58 | ||
| 59 | const failed = (write: (line: string) => void, said: string): Spend => { | |
| 60 | write(said); | |
| 61 | return { ok: false, outcome: { state: "failed", summary: said } }; | |
| 62 | }; | |
| 63 | ||
| 64 | /** | |
| 65 | * The account this run works on: the nearest grant's, rotating; the forge's own token when nothing | |
| 66 | * is granted. A grant whose accounts are all resting holds the run until the first wakes, without | |
| 67 | * a call. Records the account on the run and the meter, and the ceilings the run counts against. | |
| 68 | */ | |
| 69 | export async function settleSpend(s: SpendState): Promise<Spend> { | |
| 70 | const { app, run, repo, agent, meter, write } = s; | |
| 71 | const scope: SpendScope = { | |
| 72 | repoId: repo.id, | |
| 73 | ownerId: repo.ownerId, | |
| 74 | agentId: agent.user.id, | |
| 75 | }; | |
| 76 | // What this run may spend at most; on a budgeted account the pick | |
| 77 | // reserves it (or what is left, if less) against the account's budget. | |
| 78 | const ownBudget = | |
| 79 | agent.budgetUsd > 0 | |
| 80 | ? agent.budgetUsd | |
| 81 | : isOwnForge(app) | |
| 82 | ? budgetLimit(app.db, "run") | |
| 83 | : s.defaultBudgetUsd; | |
| 84 | const picked = pickSubscription(app.db, app.config.dataDir, scope, new Date(), { | |
| 85 | runId: run.id, | |
| 86 | usd: ownBudget, | |
| 87 | }); | |
| 88 | if (picked.kind === "resting") { | |
| 89 | const names = picked.names.join(", "); | |
| 90 | write( | |
| 91 | `${names}: resting (${picked.said}) until ${whenText(new Date(picked.until))}. ${accountsSaid(app, repo)}`, | |
| 92 | ); | |
| 93 | if (run.attempt < MAX_PAUSES) | |
| 94 | return { | |
| 95 | ok: false, | |
| 96 | outcome: { | |
| 97 | state: "paused", | |
| 98 | summary: `paused: ${names} resting — ${picked.said}; resumes ${whenText(new Date(picked.until))}`, | |
| 99 | resumeAt: picked.until, | |
| 100 | sessionId: s.previousSessionId ?? "", | |
| 101 | costUsd: 0, | |
| 102 | }, | |
| 103 | }; | |
| 104 | return { | |
| 105 | ok: false, | |
| 106 | outcome: { | |
| 107 | state: "failed", | |
| 108 | summary: `every subscription this repository may use is resting (${picked.said})`, | |
| 109 | resumesAt: new Date(picked.until), | |
| 110 | }, | |
| 111 | }; | |
| 112 | } | |
| 113 | // The account turned requests away this minute: the crew's own work holds, a person's run | |
| 114 | // goes ahead (#16490). The hold is not a pause the run is counted for. | |
| 115 | const breathing = run.sent | |
| 116 | ? undefined | |
| 117 | : breathingUntil(app.db, picked.kind === "ready" ? picked.subscription.id : PLATFORM, new Date()); | |
| 118 | if (breathing !== undefined) { | |
| 119 | const words = breathWords(breathing, false); | |
| 120 | write(words); | |
| 121 | return { | |
| 122 | ok: false, | |
| 123 | outcome: { | |
| 124 | state: "paused", | |
| 125 | summary: `paused: ${words}`, | |
| 126 | resumeAt: breathing.toISOString(), | |
| 127 | sessionId: s.previousSessionId ?? "", | |
| 128 | costUsd: 0, | |
| 129 | keepAttempt: true, | |
| 130 | }, | |
| 131 | }; | |
| 132 | } | |
| 133 | // The forge's own token is for admin-owned repositories only; anyone | |
| 134 | // else's run waits for a grant rather than spend what is not theirs. | |
| 135 | // The owner's capped monthly grant (`core/model_grant.ts`) is the one | |
| 136 | // way past it: the forge's token, up to what is left of the month. | |
| 137 | // The host's included credit is a way past it too (#12105); a copy that says | |
| 138 | // there is too little may be stale: ask the host before refusing (at most once in 15 s). | |
| 139 | // The repository's own monthly cap (`core/wallet.ts`): reached, no new run starts. | |
| 140 | const walletSaid = capReached(app.db, repo.id, new Date()); | |
| 141 | if (walletSaid !== undefined) return failed(write, walletSaid); | |
| 142 | const heldLeft = lentCreditLeft(picked.kind === "none", app.config.dataDir); | |
| 143 | if (picked.kind === "none" && (heldLeft === undefined || heldLeft < MIN_RUN_USD)) | |
| 144 | await refreshFundingOnce(app); | |
| 145 | // The forge's own key drawing on lent credit: the same stale copy, asked about the same way. | |
| 146 | if (picked.kind === "env" && lentSpent(lentCreditLeft(true, app.config.dataDir), MIN_RUN_USD) !== undefined) | |
| 147 | await refreshFundingOnce(app); | |
| 148 | const access = modelAccess(app, picked, repo.ownerId, repo.ownerName); | |
| 149 | if (!access.ok) return failed(write, access.said); | |
| 150 | const grantCap = picked.kind === "none" ? access.grantCap : undefined; | |
| 151 | // What this run would spend before the account's ceilings: its own | |
| 152 | // budget, under the subscription's reservation or the grant's rest. | |
| 153 | const lentLeft = lentCreditLeft(picked.kind === "env" || picked.kind === "none", app.config.dataDir); | |
| 154 | // Spent credit is said in the forge's words before anything starts: a run budgeted $0 would | |
| 155 | // only hand the person the model tool's refusal of that figure. | |
| 156 | const spentSaid = lentSpent(lentLeft, MIN_RUN_USD); | |
| 157 | if (spentSaid !== undefined) return failed(write, spentSaid); | |
| 158 | const wantedBy = | |
| 159 | picked.kind === "ready" && picked.capUsd !== undefined | |
| 160 | ? Math.min(ownBudget, picked.capUsd) | |
| 161 | : grantCap !== undefined | |
| 162 | ? Math.min(ownBudget, grantCap) | |
| 163 | : ownBudget; | |
| 164 | // On the host's included credit a run is budgeted at most what is left of it | |
| 165 | // (#11948), so the budget line and the credit line say one number. | |
| 166 | const wanted = cappedByLent(wantedBy, lentLeft); | |
| 167 | // The account's own ceilings, daily and per run, apart from the forge's: | |
| 168 | // a run past either does not start and spends nothing. What it may | |
| 169 | // spend is reserved against the day now, so a run started beside it is | |
| 170 | // handed only what is left. | |
| 171 | const ceiling = reserveCeiling( | |
| 172 | app.db, | |
| 173 | repo.ownerId, | |
| 174 | { id: run.id, wantUsd: wanted }, | |
| 175 | MIN_RUN_USD, | |
| 176 | new Date(), | |
| 177 | ); | |
| 178 | if (!ceiling.ok) return failed(write, ceiling.said); | |
| 179 | // The owner's own limits on a forge that is theirs (`forge_budget.ts`). | |
| 180 | const own = budgetVerdict(app, ceiling.capUsd ?? wanted, new Date(), run.id); | |
| 181 | if (own !== undefined && !own.ok) return failed(write, own.said); | |
| 182 | meter.ceilingOwner = repo.ownerId; | |
| 183 | if (picked.kind === "ready") { | |
| 184 | write(`subscription: ${picked.subscription.name}`); | |
| 185 | noteRunProgress(app.db, run.id, { subscriptionId: picked.subscription.id }); | |
| 186 | meter.subscriptionId = picked.subscription.id; | |
| 187 | } else { | |
| 188 | if (grantCap !== undefined) { | |
| 189 | meter.grantOwner = repo.ownerId; | |
| 190 | write(`model grant: $${grantCap.toFixed(2)} left this month`); | |
| 191 | } | |
| 192 | write("subscription: platform (env)"); | |
| 193 | noteRunProgress(app.db, run.id, { subscriptionId: PLATFORM }); | |
| 194 | meter.subscriptionId = PLATFORM; | |
| 195 | } | |
| 196 | const budget = Math.min( | |
| 197 | ceiling.capUsd ?? Infinity, | |
| 198 | wanted, | |
| 199 | own?.ok === true ? own.capUsd : Infinity, | |
| 200 | ); | |
| 201 | return { ok: true, picked, scope, budget, own }; | |
| 202 | } |
src/crew/run_verdict.ts added +125
| @@ -0,0 +1,125 @@ | ||
| 1 | /** | |
| 2 | * The runs that end without landing anything: an agent that declined the task, and a reviewer | |
| 3 | * whose work is its verdict. Judged from what the session left, before any bookkeeping on the | |
| 4 | * branch. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { App } from "../app.ts"; | |
| 8 | import type { Agent } from "../core/agents.ts"; | |
| 9 | import type { Pull } from "../core/pulls.ts"; | |
| 10 | import type { Repo } from "../core/repos.ts"; | |
| 11 | import { listReviews, type Review } from "../core/reviews.ts"; | |
| 12 | import type { AgentOutcome } from "./agent_runner.ts"; | |
| 13 | import { alreadyDoneSummary, declineOf, namedCommits, onBase } from "./already.ts"; | |
| 14 | import type { Ending } from "./early.ts"; | |
| 15 | import type { Outcome } from "./meter.ts"; | |
| 16 | import { noVerdictSummary } from "./review.ts"; | |
| 17 | ||
| 18 | /** What `verdictOf` is given: plain data and the run's log. */ | |
| 19 | export interface VerdictState { | |
| 20 | readonly app: App; | |
| 21 | readonly repo: Repo; | |
| 22 | readonly agent: Agent; | |
| 23 | /** The pull under review, when the run is a review. */ | |
| 24 | readonly pull: Pull | undefined; | |
| 25 | readonly reviewing: boolean; | |
| 26 | /** The repository's bare path, where "done already" is looked for. */ | |
| 27 | readonly bare: string; | |
| 28 | /** When the run began (ISO): a verdict older than this is not this run's. */ | |
| 29 | readonly began: string; | |
| 30 | readonly result: AgentOutcome; | |
| 31 | readonly write: (line: string) => void; | |
| 32 | } | |
| 33 | ||
| 34 | /** A run's ending decided here, and how its pull's status should read, if it says. */ | |
| 35 | export interface Verdict { | |
| 36 | readonly outcome: Outcome; | |
| 37 | readonly ending?: Ending | undefined; | |
| 38 | } | |
| 39 | ||
| 40 | /** | |
| 41 | * How a review run ends, read from the verdicts on the pull: `ok` when the | |
| 42 | * reviewer passed one since the run began, or stands by one on the head it | |
| 43 | * was given (the same verdict sent again is the one already there); | |
| 44 | * `failed` when it did neither. A reviewer pushes nothing by design, so | |
| 45 | * what it pushed never decides it. A run the harness refused a tool says | |
| 46 | * which (#16177): that is the forge's failure, not the reviewer's. | |
| 47 | */ | |
| 48 | export function settleReview( | |
| 49 | reviews: readonly Review[], | |
| 50 | reviewerId: string, | |
| 51 | since: string, | |
| 52 | headOid: string, | |
| 53 | /** | |
| 54 | * The tools the harness refused the reviewer (`AgentOutcome.denied`): named when no verdict came. | |
| 55 | */ | |
| 56 | denied: readonly string[] = [], | |
| 57 | ): { state: "ok" | "failed"; summary: string } { | |
| 58 | const verdict = reviews.findLast( | |
| 59 | (r) => | |
| 60 | r.authorId === reviewerId && | |
| 61 | (r.createdAt >= since || r.commitOid === headOid), | |
| 62 | ); | |
| 63 | return verdict === undefined | |
| 64 | ? { state: "failed", summary: noVerdictSummary(denied) } | |
| 65 | : { state: "ok", summary: `reviewed: ${verdict.state.replace("_", " ")}` }; | |
| 66 | } | |
| 67 | ||
| 68 | /** What of the session's own accounting every ending here carries. */ | |
| 69 | function carried(result: AgentOutcome) { | |
| 70 | return { | |
| 71 | sessionId: result.sessionId, | |
| 72 | costUsd: result.costUsd, | |
| 73 | turns: result.turns, | |
| 74 | contextTokens: result.contextTokens, | |
| 75 | pushed: false, | |
| 76 | }; | |
| 77 | } | |
| 78 | ||
| 79 | /** The verdict on a session that declined or reviewed, or nothing when the run has work to land. */ | |
| 80 | export async function verdictOf(s: VerdictState): Promise<Verdict | undefined> { | |
| 81 | const { app, repo, agent, pull, result, write } = s; | |
| 82 | // The decline contract: an agent that should not do the task says so | |
| 83 | // instead of guessing, and nothing it touched becomes a proposal. | |
| 84 | const why = declineOf(result.result); | |
| 85 | if (why !== undefined) { | |
| 86 | const sentence = why.split("\n")[0] ?? ""; | |
| 87 | write(`declined: ${sentence}`); | |
| 88 | const ending: Ending = { kind: "declined", sentence }; | |
| 89 | // Done on the base already, by a commit that is there: its own | |
| 90 | // outcome, not a park (`already.ts`). A claim without one is an | |
| 91 | // ordinary decline. | |
| 92 | const done = await onBase(s.bare, repo.defaultBranch, namedCommits(sentence)); | |
| 93 | if (done.length > 0) | |
| 94 | return { | |
| 95 | ending, | |
| 96 | outcome: { state: "ok", summary: alreadyDoneSummary(done), ...carried(result) }, | |
| 97 | }; | |
| 98 | // The reason lives on the run record (its summary) and the ledger | |
| 99 | // line, never as a comment: a comment on an assigned issue is the | |
| 100 | // thing that starts the next run. | |
| 101 | return { | |
| 102 | ending, | |
| 103 | outcome: { | |
| 104 | state: "failed", | |
| 105 | summary: `declined: ${sentence.slice(0, 200)}`, | |
| 106 | ...carried(result), | |
| 107 | }, | |
| 108 | }; | |
| 109 | } | |
| 110 | // A reviewer's work is its verdict, posted through the API; it pushes | |
| 111 | // nothing and has nothing to land. The run is judged by whether the | |
| 112 | // verdict is there, not by what the session said about itself. | |
| 113 | if (s.reviewing && pull !== undefined) { | |
| 114 | const settled = settleReview( | |
| 115 | listReviews(app.db, pull.id), | |
| 116 | agent.user.id, | |
| 117 | s.began, | |
| 118 | pull.headOid, | |
| 119 | result.denied, | |
| 120 | ); | |
| 121 | write(settled.summary); | |
| 122 | return { outcome: { ...settled, ...carried(result) } }; | |
| 123 | } | |
| 124 | return undefined; | |
| 125 | } |
src/crew/run_wrapup.ts added +84
| @@ -0,0 +1,84 @@ | ||
| 1 | /** | |
| 2 | * The reserve: when the agent ran out of budget mid-task, the same session gets one more turn, to | |
| 3 | * land what exists rather than to keep working. Its ending is the run's ending, with the whole | |
| 4 | * spend; the pull says where the work stopped. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { App } from "../app.ts"; | |
| 8 | import type { Stopwatch } from "../apps/timing.ts"; | |
| 9 | import { noteRunProgress, type Run } from "../core/runs.ts"; | |
| 10 | import { BUDGET_REACHED, type AgentOutcome } from "./agent_runner.ts"; | |
| 11 | import { wrapUpPrompt } from "./brief.ts"; | |
| 12 | import type { Outcome } from "./meter.ts"; | |
| 13 | import { outagePause, retryNetwork, type RetryState } from "./run_retry.ts"; | |
| 14 | ||
| 15 | /** | |
| 16 | * What `wrapUp` is given: plain data, the retry state it asks again with, and what it writes to. | |
| 17 | */ | |
| 18 | export interface WrapUpState { | |
| 19 | readonly app: App; | |
| 20 | readonly run: Run; | |
| 21 | /** The main turn's answer. */ | |
| 22 | readonly result: AgentOutcome; | |
| 23 | readonly retry: RetryState; | |
| 24 | /** What the reserve may spend. */ | |
| 25 | readonly reserve: number; | |
| 26 | readonly deadline: number; | |
| 27 | readonly signal: AbortSignal; | |
| 28 | /** The run's progress: set while the wrap-up turn is in flight. */ | |
| 29 | readonly ran: { inWrapUp: boolean }; | |
| 30 | readonly watch: Stopwatch; | |
| 31 | readonly write: (line: string) => void; | |
| 32 | } | |
| 33 | ||
| 34 | /** | |
| 35 | * Either the run's ending (the wrap-up never got through: the run pauses as the main turn does), | |
| 36 | * or the answer to judge, whole when a wrap-up ran, and `stoppedAt`, what the main turn had spent | |
| 37 | * when it did. | |
| 38 | */ | |
| 39 | export type WrapUp = | |
| 40 | | { readonly ok: false; readonly outcome: Outcome } | |
| 41 | | { readonly ok: true; readonly result: AgentOutcome; readonly stoppedAt: number | undefined }; | |
| 42 | ||
| 43 | export async function wrapUp(s: WrapUpState): Promise<WrapUp> { | |
| 44 | const { app, run, retry, reserve, write } = s; | |
| 45 | const first = s.result; | |
| 46 | if ( | |
| 47 | first.reason !== BUDGET_REACHED || | |
| 48 | first.sessionId === "" || | |
| 49 | s.signal.aborted || | |
| 50 | Date.now() >= s.deadline | |
| 51 | ) | |
| 52 | return { ok: true, result: first, stoppedAt: undefined }; | |
| 53 | const stoppedAt = first.costUsd; | |
| 54 | s.ran.inWrapUp = true; | |
| 55 | write(`claude: wrapping up with the reserve, $${reserve.toFixed(2)}`); | |
| 56 | const wrapped = await retryNetwork( | |
| 57 | retry, | |
| 58 | await retry.invoke(wrapUpPrompt(), reserve, first.sessionId), | |
| 59 | reserve, | |
| 60 | " the wrap-up", | |
| 61 | (last) => ({ | |
| 62 | prompt: wrapUpPrompt(), | |
| 63 | sessionId: last.sessionId || first.sessionId, | |
| 64 | }), | |
| 65 | ); | |
| 66 | // Still unreachable after the retries: the work is not judged on a | |
| 67 | // wrap-up that never got through; the run pauses as the main turn does. | |
| 68 | const down = outagePause(retry, wrapped, first.costUsd + wrapped.costUsd); | |
| 69 | if (down !== undefined) return { ok: false, outcome: down }; | |
| 70 | write(`claude: ${wrapped.reason}, ${wrapped.turns} turns, $${wrapped.costUsd.toFixed(2)}`); | |
| 71 | const result: AgentOutcome = { | |
| 72 | ...wrapped, | |
| 73 | // A refusal in either turn is one the run met (#16177). | |
| 74 | denied: [...new Set([...(first.denied ?? []), ...(wrapped.denied ?? [])])], | |
| 75 | sessionId: wrapped.sessionId || first.sessionId, | |
| 76 | costUsd: first.costUsd + wrapped.costUsd, | |
| 77 | turns: first.turns + wrapped.turns, | |
| 78 | contextTokens: wrapped.contextTokens || first.contextTokens, | |
| 79 | }; | |
| 80 | noteRunProgress(app.db, run.id, { costUsd: result.costUsd }); | |
| 81 | s.watch.lap("wrap-up"); | |
| 82 | s.ran.inWrapUp = false; | |
| 83 | return { ok: true, result, stoppedAt }; | |
| 84 | } |
src/crew/runner.ts +161 −1089
| @@ -11,201 +11,73 @@ | ||
| 11 | 11 | * what the forge has. |
| 12 | 12 | */ |
| 13 | 13 | |
| 14 | import { crewGrantedRepos } from "../core/origin_read_grant.ts"; | |
| 15 | import { accountsSaid } from "../actions/crew_accounts.ts"; | |
| 16 | import { failureBrief } from "./failure_brief.ts"; | |
| 17 | import { holdsNaming } from "./desk_posts.ts"; | |
| 18 | import { isStrangerPull } from "./stranger.ts"; | |
| 19 | import { forgetMeasure, noteMeasure } from "../core/measure.ts"; | |
| 20 | import { capacityEnv } from "../core/capacity.ts"; | |
| 21 | 14 | import { existsSync } from "node:fs"; |
| 22 | 15 | import { rm } from "node:fs/promises"; |
| 23 | 16 | import { join } from "node:path"; |
| 24 | import type { App } from "../app.ts"; | |
| 25 | 17 | import { dropBrief } from "../actions/drop.ts"; |
| 26 | import { resolutionBrief } from "./proposal.ts"; | |
| 27 | import { | |
| 28 | watchForPull, | |
| 29 | type EarlyPull, | |
| 30 | type Ending, | |
| 31 | } from "./early.ts"; | |
| 32 | 18 | import { announceRun } from "../actions/runs.ts"; |
| 33 | import { Stopwatch } from "../apps/timing.ts"; | |
| 19 | import type { App } from "../app.ts"; | |
| 34 | 20 | import { previewEnv } from "../apps/data.ts"; |
| 35 | 21 | import { appsRuntime } from "../apps/runtime.ts"; |
| 36 | import { chooseModel, modelFacts } from "./model_choice.ts"; | |
| 37 | import { ownApp, ownAppUrls } from "./app_hosts.ts"; | |
| 38 | import { | |
| 39 | machineEnv, | |
| 40 | machineFor, | |
| 41 | machineLimits, | |
| 42 | reachableApps, | |
| 43 | } from "./machines.ts"; | |
| 44 | import { repoMachines } from "./machines_read.ts"; | |
| 45 | import { authorsInRepoPull } from "./authors_pull.ts"; | |
| 22 | import { Stopwatch } from "../apps/timing.ts"; | |
| 23 | import { declarationsOf } from "../cloud/declared.ts"; | |
| 24 | import { bar } from "../cloud/gate.ts"; | |
| 25 | import { policyBrief } from "../contract/audit.ts"; | |
| 46 | 26 | import { crewRole, getAgent } from "../core/agents.ts"; |
| 47 | import { getAppByRepo, type AppRecord } from "../core/apps.ts"; | |
| 48 | import { | |
| 49 | getIssue, | |
| 50 | getIssueById, | |
| 51 | labelsForIssues, | |
| 52 | listComments, | |
| 53 | type Issue, | |
| 54 | } from "../core/issues.ts"; | |
| 27 | import { getAppByRepo } from "../core/apps.ts"; | |
| 28 | import { accountOfSecret } from "../core/cloud_account.ts"; | |
| 55 | 29 | import { refreshPullHead } from "../core/following.ts"; |
| 56 | import { reviewSourceNote } from "./source_held.ts"; | |
| 57 | import { | |
| 58 | UPSTREAM_TITLE, | |
| 59 | sourceFollowing, | |
| 60 | upstreamFollowing, | |
| 61 | } from "../actions/upstream_follow.ts"; | |
| 62 | import { getPull, isFirstBuild, listPulls, type Pull, pullDir } from "../core/pulls.ts"; | |
| 63 | import { | |
| 64 | canWrite, | |
| 65 | forkParentFor, | |
| 66 | getRepoById, | |
| 67 | type Repo, | |
| 68 | } from "../core/repos.ts"; | |
| 69 | import { getUserById, type User } from "../core/users.ts"; | |
| 70 | import { | |
| 71 | listReviewComments, | |
| 72 | listReviews, | |
| 73 | type Review, | |
| 74 | } from "../core/reviews.ts"; | |
| 75 | import { | |
| 76 | answerCancelled, | |
| 77 | cancelRun, | |
| 78 | claimRun, | |
| 79 | finishRun, | |
| 80 | getRun, | |
| 81 | lastAgentRun, | |
| 82 | noteRunProgress, | |
| 83 | setRunBase, | |
| 84 | overranBefore, | |
| 85 | type Run, | |
| 86 | } from "../core/runs.ts"; | |
| 30 | import { getIssue, getIssueById } from "../core/issues.ts"; | |
| 31 | import { crewGrantedRepos } from "../core/origin_read_grant.ts"; | |
| 32 | import { getPull, isFirstBuild, listPulls, type Pull } from "../core/pulls.ts"; | |
| 33 | import { canWrite, getRepoById } from "../core/repos.ts"; | |
| 87 | 34 | import { mintRunToken } from "../core/run_token.ts"; |
| 88 | import { keepToken, refusedToken } from "./token_refused.ts"; | |
| 35 | import { answerCancelled, cancelRun, claimRun, finishRun, getRun, lastAgentRun, noteRunProgress, overranBefore, setRunBase, type Run } from "../core/runs.ts"; | |
| 89 | 36 | import { deleteToken } from "../core/tokens.ts"; |
| 90 | import { Hops } from "./hops.ts"; | |
| 37 | import { getUserById } from "../core/users.ts"; | |
| 91 | 38 | import { isSafeRef } from "../git/guard.ts"; |
| 92 | import { checkoutReviewHead, noteUnreviewed } from "./review_head.ts"; | |
| 93 | import { runGitCapture } from "../git/env.ts"; | |
| 94 | import { looksForEnv } from "../core/looks.ts"; | |
| 95 | 39 | import { resolveOid } from "../git/merge.ts"; |
| 96 | 40 | import { repoDir } from "../git/repos.ts"; |
| 97 | import { bar } from "../cloud/gate.ts"; | |
| 98 | import { declarationsOf } from "../cloud/declared.ts"; | |
| 99 | import { accountOfSecret } from "../core/cloud_account.ts"; | |
| 100 | import { | |
| 101 | alreadyDoneSummary, | |
| 102 | answeredBeforeStop, | |
| 103 | declineOf, | |
| 104 | isAnswer, | |
| 105 | namedCommits, | |
| 106 | onBase, | |
| 107 | } from "./already.ts"; | |
| 108 | import { | |
| 109 | CHECK_PENDING_SUMMARY, | |
| 110 | NOT_REVIEWED_PREFIX, | |
| 111 | noVerdictSummary, | |
| 112 | overranWhere, | |
| 113 | SEALED_FETCH_PREFIX, | |
| 114 | touchesDesign, | |
| 115 | waitingOnCheck, | |
| 116 | } from "./review.ts"; | |
| 117 | import { fetchSealedHead, SEALED_REMOTE, sealedHeadRepo } from "./sealed_head.ts"; | |
| 118 | 41 | import { BUDGETS, BUDGET_PREFIX, RUN_THREW_PREFIX, budgetSummary } from "../kernel/budgets.ts"; |
| 119 | import { createLog, holdValues, redactValues, releaseValues } from "../kernel/log.ts"; | |
| 42 | import { createLog, holdValues, releaseValues } from "../kernel/log.ts"; | |
| 43 | import { cancelledLine } from "../runs/cancelled.ts"; | |
| 44 | import { workBegins, workEnds } from "../runs/ending.ts"; | |
| 120 | 45 | import { holdLease } from "../runs/lease.ts"; |
| 121 | 46 | import { appendRunLog } from "../runs/log.ts"; |
| 122 | import { cancelledLine } from "../runs/cancelled.ts"; | |
| 123 | import { | |
| 124 | branchFor, | |
| 125 | issueOfBranch, | |
| 126 | promptVersion, | |
| 127 | systemPrompt, | |
| 128 | taskPrompt, | |
| 129 | wrapUpPrompt, | |
| 130 | type LastTry, | |
| 131 | type RunReason, | |
| 132 | type TaskInput, | |
| 133 | } from "./brief.ts"; | |
| 134 | import { policyBrief } from "../contract/audit.ts"; | |
| 135 | import { | |
| 136 | isNetworkError, | |
| 137 | NETWORK_PAUSE_MS, | |
| 138 | NETWORK_RETRY_SECONDS, | |
| 139 | pause, | |
| 140 | } from "./network.ts"; | |
| 141 | import { BUDGET_REACHED, briefTools, currentRunner, runAgent, type AgentOutcome } from "./agent_runner.ts"; | |
| 142 | import { | |
| 143 | breathingUntil, | |
| 144 | breathWait, | |
| 145 | breathWords, | |
| 146 | isRateLimited, | |
| 147 | limitOf, | |
| 148 | MAX_PAUSES, | |
| 149 | noteBreath, | |
| 150 | perMinute, | |
| 151 | resumeAt, | |
| 152 | takeLimit, | |
| 153 | whenText, | |
| 154 | } from "./limits.ts"; | |
| 155 | import { interruptedSummary, interruptionOf, landedPullOf, landedSummary, settleLanded } from "./interrupted.ts"; | |
| 156 | import { lastWeekFor } from "./last_week.ts"; | |
| 157 | import { laterGate } from "./later.ts"; | |
| 47 | import { fundingOf, lentCost, runEnded } from "../spawn/funding.ts"; | |
| 48 | import { briefTools } from "./agent_runner.ts"; | |
| 49 | import { isAnswer } from "./already.ts"; | |
| 50 | import { ownApp } from "./app_hosts.ts"; | |
| 51 | import { authorsInRepoPull } from "./authors_pull.ts"; | |
| 52 | import { branchFor, issueOfBranch, type RunReason } from "./brief.ts"; | |
| 158 | 53 | import { MERGES_CLEAN_NOW, mergesCleanNow } from "./clean_now.ts"; |
| 159 | import { handedLimbs } from "./handed_limbs.ts"; | |
| 160 | import { parkedTwice, parkReasons } from "./parks.ts"; | |
| 161 | import { handedTooLarge } from "./too_large.ts"; | |
| 162 | import { budgetLimit, budgetVerdict, cutOffBy, isOwnForge } from "./forge_budget.ts"; | |
| 163 | import { boxesOf, landedBoxes } from "./box_pass.ts"; | |
| 164 | import { reviewRange } from "./review_range.ts"; | |
| 165 | import { heldNow, stuckOf } from "./held.ts"; | |
| 166 | import { resumeDecision } from "./resume.ts"; | |
| 167 | import { owed } from "./team_share.ts"; | |
| 168 | import { pauseReason } from "./pacing.ts"; | |
| 169 | import { modelAccess } from "./model_access.ts"; | |
| 170 | import { capReached } from "../core/wallet.ts"; | |
| 171 | import { reserveCeiling } from "../core/account_ceiling.ts"; | |
| 172 | import { listenForSteer, stopSteering } from "./steer.ts"; | |
| 173 | import { credentialEnv, holdModelCredential } from "./credential_env.ts"; | |
| 174 | import { forkFor, prepareClone, GIT_TRANSFER_MS } from "./clone.ts"; | |
| 175 | import { landWork } from "./land_work.ts"; | |
| 176 | import { meterLive, meterUsage, usageKind, type Meter, type Outcome } from "./meter.ts"; | |
| 177 | import { | |
| 178 | MIN_RUN_USD, | |
| 179 | pickSubscription, | |
| 180 | PLATFORM, | |
| 181 | } from "../core/subscriptions.ts"; | |
| 182 | import { trackAgentRun, untrackAgentRun } from "./running.ts"; | |
| 183 | import { workBegins, workEnds } from "../runs/ending.ts"; | |
| 184 | import { installCacheEnv, makeRunTmp, sandboxPolicy } from "./sandbox.ts"; | |
| 54 | import { GIT_TRANSFER_MS, forkFor, prepareClone } from "./clone.ts"; | |
| 55 | import { recordDeviceSessions } from "./devices.ts"; | |
| 56 | import { watchForPull, type EarlyPull, type Ending } from "./early.ts"; | |
| 185 | 57 | import { runGitAuth } from "./git_auth.ts"; |
| 186 | import { deviceKit, recordDeviceSessions, type DeviceKit } from "./devices.ts"; | |
| 187 | 58 | import { grantSecrets, needsYou, parseDeclaration, ungrantedSentence, type Grant } from "./grant.ts"; |
| 188 | import { | |
| 189 | installCacheDir, | |
| 190 | installDependencies, | |
| 191 | installNote, | |
| 192 | type InstallRunner, | |
| 193 | removeClone, | |
| 194 | workdirFor, | |
| 195 | claimWorkdir, | |
| 196 | } from "./workdir.ts"; | |
| 197 | import { readersAmong, voiceOf } from "./direct.ts"; | |
| 59 | import { RETRY_SUMMARY, SKIP_SUMMARY, skipsFeedback } from "./guard.ts"; | |
| 60 | import { Hops } from "./hops.ts"; | |
| 61 | import { interruptedSummary, interruptionOf, landedPullOf, landedSummary, settleLanded } from "./interrupted.ts"; | |
| 62 | import { isRateLimited } from "./limits.ts"; | |
| 63 | import { repoMachines } from "./machines_read.ts"; | |
| 64 | import { machineFor } from "./machines.ts"; | |
| 65 | import { meterUsage, usageKind, type Meter, type Outcome } from "./meter.ts"; | |
| 198 | 66 | import { feedbackSince } from "./news.ts"; |
| 199 | import { | |
| 200 | handedOverPulls, | |
| 201 | RETRY_SUMMARY, | |
| 202 | SKIP_SUMMARY, | |
| 203 | skipsFeedback, | |
| 204 | } from "./guard.ts"; | |
| 205 | import { doorForRun, type GatewayDoor } from "./gateway_door.ts"; | |
| 206 | import { passportEnv } from "./passport_env.ts"; | |
| 207 | import { layerRunEnv, runAccount, sandboxTmpEnv } from "./runner_env.ts"; | |
| 208 | import { cappedByLent, fundingOf, lentCost, lentCreditLeft, lentSpent, refreshFundingOnce, runEnded } from "../spawn/funding.ts"; | |
| 67 | import { resumeDecision } from "./resume.ts"; | |
| 68 | import { checkoutReviewHead, noteUnreviewed } from "./review_head.ts"; | |
| 69 | import { CHECK_PENDING_SUMMARY, NOT_REVIEWED_PREFIX, SEALED_FETCH_PREFIX, overranWhere, waitingOnCheck } from "./review.ts"; | |
| 70 | import { limitEnding } from "./run_limits.ts"; | |
| 71 | import { prepareAgent, type Held } from "./run_prepare.ts"; | |
| 72 | import { promptFor } from "./run_prompt.ts"; | |
| 73 | import { outagePause, retryNetwork, type RetryState } from "./run_retry.ts"; | |
| 74 | import { settleRun } from "./run_settle.ts"; | |
| 75 | import { settleSpend } from "./run_spend.ts"; | |
| 76 | import { wrapUp } from "./run_wrapup.ts"; | |
| 77 | import { trackAgentRun, untrackAgentRun } from "./running.ts"; | |
| 78 | import { fetchSealedHead, sealedHeadRepo } from "./sealed_head.ts"; | |
| 79 | import { stopSteering } from "./steer.ts"; | |
| 80 | import { claimWorkdir, installCacheDir, installDependencies, installNote, removeClone, workdirFor, type InstallRunner } from "./workdir.ts"; | |
| 209 | 81 | |
| 210 | 82 | const log = createLog("crew"); |
| 211 | 83 | |
| @@ -254,130 +126,13 @@ export interface CrewOptions { | ||
| 254 | 126 | } |
| 255 | 127 | |
| 256 | 128 | export { crewRoot, workdirFor } from "./workdir.ts"; |
| 129 | export { settleReview } from "./run_verdict.ts"; | |
| 130 | export { conflictFilesOf, convergeFollowing, reviewInputs } from "./run_prompt.ts"; | |
| 257 | 131 | |
| 258 | 132 | /** After the abort, how long a run gets to wind down before the forge ends it without it. */ |
| 259 | 133 | const OVERRUN_GRACE_MS = 5_000; |
| 260 | 134 | |
| 261 | /** | |
| 262 | * What a reviewer reads: the pull's diff (`review_range.ts` — a landed pull's | |
| 263 | * is its merge commit's), and its pictures. `landedAs` names the merge commit | |
| 264 | * the diff was read from, when it was. | |
| 265 | */ | |
| 266 | export async function reviewInputs( | |
| 267 | app: App, | |
| 268 | repo: Repo, | |
| 269 | pull: Pull, | |
| 270 | record: AppRecord | undefined, | |
| 271 | bare: string, | |
| 272 | /** | |
| 273 | * The run's own: a review past its budget stops reading the diff instead of finishing it | |
| 274 | * (#16096). | |
| 275 | */ | |
| 276 | signal?: AbortSignal, | |
| 277 | ): Promise<{ | |
| 278 | reviewDiff: string; | |
| 279 | looks: string[]; | |
| 280 | design: boolean; | |
| 281 | landedAs?: string; | |
| 282 | }> { | |
| 283 | const range = await reviewRange(bare, pull); | |
| 284 | let reviewDiff = "(no diff available)"; | |
| 285 | let design = false; | |
| 286 | if (range !== undefined) { | |
| 287 | const names = await runGitCapture( | |
| 288 | ["diff", "--name-only", range.from, range.to], | |
| 289 | { cwd: bare, ...(signal === undefined ? {} : { signal }) }, | |
| 290 | ); | |
| 291 | design = touchesDesign( | |
| 292 | names.stdout | |
| 293 | .toString() | |
| 294 | .split("\n") | |
| 295 | .filter((n) => n !== ""), | |
| 296 | ); | |
| 297 | const out = await runGitCapture( | |
| 298 | ["diff", "--stat", "-p", range.from, range.to], | |
| 299 | { cwd: bare, ...(signal === undefined ? {} : { signal }) }, | |
| 300 | ); | |
| 301 | const text = out.stdout.toString(); | |
| 302 | if (out.code === 0) | |
| 303 | reviewDiff = | |
| 304 | text.length > REVIEW_DIFF_MAX | |
| 305 | ? `${text.slice(0, REVIEW_DIFF_MAX)}\n… (cut at ${REVIEW_DIFF_MAX} bytes)` | |
| 306 | : text; | |
| 307 | } | |
| 308 | const looks = | |
| 309 | record === undefined | |
| 310 | ? [] | |
| 311 | : looksForEnv(app.db, record.id, `pull-${pull.number}`) | |
| 312 | .filter( | |
| 313 | (l) => | |
| 314 | l.commitOid === pull.headOid && | |
| 315 | l.error === null && | |
| 316 | (l.kind === "phone" || l.kind === "desktop"), | |
| 317 | ) | |
| 318 | .sort( | |
| 319 | (a, b) => | |
| 320 | (a.kind === "phone" ? -1 : 1) - (b.kind === "phone" ? -1 : 1), | |
| 321 | ) | |
| 322 | .map((l) => | |
| 323 | l.path.startsWith("/") ? l.path : join(app.config.dataDir, l.path), | |
| 324 | ); | |
| 325 | return { | |
| 326 | reviewDiff, | |
| 327 | looks, | |
| 328 | design, | |
| 329 | ...(range?.landed === true && reviewDiff !== "(no diff available)" | |
| 330 | ? { landedAs: range.to } | |
| 331 | : {}), | |
| 332 | }; | |
| 333 | } | |
| 334 | ||
| 335 | const REVIEW_DIFF_MAX = 60 * 1024; | |
| 336 | ||
| 337 | /** The share of a run's budget held back for finishing. */ | |
| 338 | const RESERVE = 0.15; | |
| 339 | /** ...and never less than this: a wrap-up that cannot run a test is none. */ | |
| 340 | const RESERVE_FLOOR_USD = 0.5; | |
| 341 | ||
| 342 | /** | |
| 343 | * What a run keeps for its wrap-up: fifteen percent of the budget, at | |
| 344 | * least fifty cents, never more than half — a budget too small to split | |
| 345 | * is not made worse by splitting it. | |
| 346 | */ | |
| 347 | export function wrapUpReserve(budgetUsd: number): number { | |
| 348 | return Math.min( | |
| 349 | Math.max(budgetUsd * RESERVE, RESERVE_FLOOR_USD), | |
| 350 | budgetUsd / 2, | |
| 351 | ); | |
| 352 | } | |
| 353 | ||
| 354 | /** | |
| 355 | * How a review run ends, read from the verdicts on the pull: `ok` when the | |
| 356 | * reviewer passed one since the run began, or stands by one on the head it | |
| 357 | * was given (the same verdict sent again is the one already there); | |
| 358 | * `failed` when it did neither. A reviewer pushes nothing by design, so | |
| 359 | * what it pushed never decides it. A run the harness refused a tool says | |
| 360 | * which (#16177): that is the forge's failure, not the reviewer's. | |
| 361 | */ | |
| 362 | export function settleReview( | |
| 363 | reviews: readonly Review[], | |
| 364 | reviewerId: string, | |
| 365 | since: string, | |
| 366 | headOid: string, | |
| 367 | /** | |
| 368 | * The tools the harness refused the reviewer (`AgentOutcome.denied`): named when no verdict came. | |
| 369 | */ | |
| 370 | denied: readonly string[] = [], | |
| 371 | ): { state: "ok" | "failed"; summary: string } { | |
| 372 | const verdict = reviews.findLast( | |
| 373 | (r) => | |
| 374 | r.authorId === reviewerId && | |
| 375 | (r.createdAt >= since || r.commitOid === headOid), | |
| 376 | ); | |
| 377 | return verdict === undefined | |
| 378 | ? { state: "failed", summary: noVerdictSummary(denied) } | |
| 379 | : { state: "ok", summary: `reviewed: ${verdict.state.replace("_", " ")}` }; | |
| 380 | } | |
| 135 | export { wrapUpReserve } from "./run_prepare.ts"; | |
| 381 | 136 | |
| 382 | 137 | /** How far a run got, for the timing line an early return would cut short. */ |
| 383 | 138 | interface Ran { |
| @@ -680,32 +435,6 @@ async function forkTipOf(app: App, pull: Pull): Promise<string | undefined> { | ||
| 680 | 435 | ); |
| 681 | 436 | } |
| 682 | 437 | |
| 683 | /** | |
| 684 | * What a retried follow-up is told: the latest verdict asking for changes, and the last builder | |
| 685 | * run's final answer. | |
| 686 | */ | |
| 687 | function lastTryOf( | |
| 688 | app: App, | |
| 689 | pullId: string, | |
| 690 | run: Run, | |
| 691 | reviews: readonly { state: string; authorName: string; body: string }[], | |
| 692 | ): LastTry | undefined { | |
| 693 | const verdict = reviews.findLast((r) => r.state === "changes_requested"); | |
| 694 | if (verdict === undefined) return undefined; | |
| 695 | const answer = app.db | |
| 696 | .query<{ summary: string }, [string, string]>( | |
| 697 | `SELECT summary FROM run WHERE issue_id = ?1 AND kind = 'agent' AND reason != 'review' | |
| 698 | AND id <> ?2 AND summary NOT LIKE 'skipped: %' | |
| 699 | ORDER BY created_at DESC, id DESC LIMIT 1`, | |
| 700 | ) | |
| 701 | .get(pullId, run.id); | |
| 702 | return { | |
| 703 | reviewer: verdict.authorName, | |
| 704 | verdict: verdict.body, | |
| 705 | answer: answer?.summary ?? "", | |
| 706 | }; | |
| 707 | } | |
| 708 | ||
| 709 | 438 | /** Whether a queued follow-up would find nothing new (`news.ts`): recorded as a skip. */ |
| 710 | 439 | function skipsQueued(app: App, run: Run): boolean { |
| 711 | 440 | const repo = getRepoById(app.db, run.repoId); |
| @@ -812,48 +541,6 @@ export interface Pause { | ||
| 812 | 541 | readonly summary?: string | undefined; |
| 813 | 542 | } |
| 814 | 543 | |
| 815 | /** | |
| 816 | * The file names a conflict or converge run's summary carries, after "main|parent|upstream moved: | |
| 817 | * ". | |
| 818 | */ | |
| 819 | export function conflictFilesOf(summary: string): string[] { | |
| 820 | return summary | |
| 821 | .replace(/^(main|parent|upstream) moved: /, "") | |
| 822 | .split(", ") | |
| 823 | .filter((f) => f !== ""); | |
| 824 | } | |
| 825 | ||
| 826 | /** | |
| 827 | * What a converge brief says the repository follows: the outside upstream | |
| 828 | * for an issue titled "Upstream: …", else a forge parent the agent may read. | |
| 829 | */ | |
| 830 | export function convergeFollowing( | |
| 831 | app: App, | |
| 832 | repo: Repo, | |
| 833 | issue: Issue, | |
| 834 | user: User, | |
| 835 | ): TaskInput["following"] { | |
| 836 | if (issue.title.startsWith(UPSTREAM_TITLE)) { | |
| 837 | const upstream = | |
| 838 | sourceFollowing(app, issue.id) ?? upstreamFollowing(app, repo.id); | |
| 839 | if (upstream !== undefined) return upstream; | |
| 840 | } | |
| 841 | // Only a parent the agent may read is put in its brief. | |
| 842 | const parent = forkParentFor(app.db, repo, user); | |
| 843 | return parent === undefined | |
| 844 | ? undefined | |
| 845 | : { | |
| 846 | parent: `${parent.ownerName}/${parent.name}`, | |
| 847 | branch: parent.defaultBranch, | |
| 848 | }; | |
| 849 | } | |
| 850 | ||
| 851 | /** The paragraphs a pull description opens with, or nothing when there are none. */ | |
| 852 | function pullNote(...parts: (string | undefined)[]): string | undefined { | |
| 853 | const present = parts.filter((part): part is string => part !== undefined); | |
| 854 | return present.length === 0 ? undefined : present.join("\n\n"); | |
| 855 | } | |
| 856 | ||
| 857 | 544 | async function work( |
| 858 | 545 | app: App, |
| 859 | 546 | run: Run, |
| @@ -1004,10 +691,7 @@ async function work( | ||
| 1004 | 691 | // The model credential's values, held for redaction under a key of their |
| 1005 | 692 | // own: the grant's is `run:<id>`, and holding under it would replace it. |
| 1006 | 693 | const modelHold = `run:${run.id}:model`; |
| 1007 | let modelSecrets: string[] = []; | |
| 1008 | let runTmp: string | undefined; | |
| 1009 | let devices: DeviceKit | undefined; | |
| 1010 | let gatewayDoor: GatewayDoor | undefined; | |
| 694 | const held: Held = { modelSecrets: [], runTmp: undefined, devices: undefined, gatewayDoor: undefined }; | |
| 1011 | 695 | let early: EarlyPull | undefined; |
| 1012 | 696 | // A paused run resumes: its pull keeps saying "In progress". |
| 1013 | 697 | let pausing = false; |
| @@ -1188,436 +872,66 @@ async function work( | ||
| 1188 | 872 | // The documents a first run reads, named only where the clone has them. |
| 1189 | 873 | docs: ["docs/VISION.md", "docs/PRINCIPLES.md"].filter((p) => existsSync(join(dir, p))), |
| 1190 | 874 | }; |
| 1191 | // Only a check or deploy that failed is handed back as the failure (#12968): never the | |
| 1192 | // success summary of a preview that came up. | |
| 1193 | const failure = failureBrief( | |
| 1194 | app.db, | |
| 1195 | app.config.dataDir, | |
| 875 | const prompt = await promptFor({ | |
| 876 | app, | |
| 877 | run, | |
| 878 | repo, | |
| 879 | issue, | |
| 880 | agent, | |
| 881 | pull, | |
| 882 | foreign, | |
| 1196 | 883 | reason, |
| 1197 | pull?.id, | |
| 1198 | pull ? ((await resolveOid(forkBare, `refs/heads/${branch}`)) ?? pull.headOid) : "", | |
| 1199 | ); | |
| 1200 | // Imported words speak as their origin author (`voiceOf`), so the | |
| 1201 | // brief marks a stranger's as a reader's, not the connecting user's. | |
| 1202 | const comments = listComments(app.db, issue.id, { kind: "comment" }).map( | |
| 1203 | voiceOf, | |
| 1204 | ); | |
| 1205 | const reviews = pull ? listReviews(app.db, pull.id).map(voiceOf) : []; | |
| 1206 | const reviewComments = pull | |
| 1207 | ? listReviewComments(app.db, pull.id).map(voiceOf) | |
| 1208 | : []; | |
| 1209 | const prompt = taskPrompt({ | |
| 1210 | ...brief, | |
| 1211 | issue: voiceOf(brief.issue), | |
| 1212 | reason, | |
| 1213 | ...(role === "builder" ? { holds: holdsNaming(app.db, repo) } : {}), | |
| 1214 | paused: run.attempt > 0, | |
| 1215 | stranger: | |
| 1216 | reason === "review" && pull !== undefined | |
| 1217 | ? isStrangerPull(app.db, repo, pull) | |
| 1218 | : undefined, | |
| 1219 | comments, | |
| 1220 | labels: (labelsForIssues(app.db, [issue.id]).get(issue.id) ?? []).map( | |
| 1221 | (label) => label.name, | |
| 1222 | ), | |
| 1223 | reviews, | |
| 1224 | reviewComments, | |
| 1225 | readers: readersAmong( | |
| 1226 | app.db, | |
| 1227 | repo, | |
| 1228 | [voiceOf(issue), ...comments, ...reviews, ...reviewComments].map( | |
| 1229 | (c) => c.authorName, | |
| 1230 | ), | |
| 1231 | ), | |
| 884 | brief, | |
| 885 | branch, | |
| 886 | bare, | |
| 887 | forkBare, | |
| 888 | record, | |
| 889 | sealedHead, | |
| 1232 | 890 | since, |
| 1233 | lastTry: | |
| 1234 | reason === "feedback" && run.summary === RETRY_SUMMARY | |
| 1235 | ? lastTryOf(app, issue.id, run, reviews) | |
| 1236 | : undefined, | |
| 1237 | ...failure, | |
| 1238 | foreignPull: foreign | |
| 1239 | ? { | |
| 1240 | branch: foreign.headBranch, | |
| 1241 | diff: ( | |
| 1242 | await reviewInputs(app, repo, foreign, undefined, await pullDir(app.db, app.reposRoot, repo, foreign)) | |
| 1243 | ).reviewDiff, | |
| 1244 | } | |
| 1245 | : undefined, | |
| 1246 | resolution: | |
| 1247 | reason === "resolve" && pull | |
| 1248 | ? await resolutionBrief(app, repo, pull) | |
| 1249 | : undefined, | |
| 1250 | conflictFiles: | |
| 1251 | reason === "conflict" || reason === "converge" | |
| 1252 | ? conflictFilesOf(run.summary) | |
| 1253 | : undefined, | |
| 1254 | following: | |
| 1255 | reason === "converge" | |
| 1256 | ? convergeFollowing(app, repo, issue, agent.user) | |
| 1257 | : undefined, | |
| 1258 | ...(reason === "review" && pull | |
| 1259 | ? { | |
| 1260 | // A sealed pull's head is in its builder's sealed fork, not the base (#14917). | |
| 1261 | ...(await reviewInputs(app, repo, pull, record, await pullDir(app.db, app.reposRoot, repo, pull), signal)), | |
| 1262 | sourceNote: await reviewSourceNote(app, repo, pull, bare), | |
| 1263 | ...(sealedHead === undefined ? {} : { sealedRef: `${SEALED_REMOTE}/${pull.headBranch}` }), | |
| 1264 | boxes: boxesOf(app, repo, pull), | |
| 1265 | retry: | |
| 1266 | app.db | |
| 1267 | .query<{ n: number }, [string, string, string]>( | |
| 1268 | `SELECT COUNT(*) AS n FROM run WHERE issue_id = ?1 AND kind = 'agent' | |
| 1269 | AND reason = 'review' AND state = 'failed' AND id <> ?2 | |
| 1270 | AND created_at < ?3`, | |
| 1271 | ) | |
| 1272 | .get(issue.id, run.id, run.createdAt)!.n > 0, | |
| 1273 | } | |
| 1274 | : {}), | |
| 1275 | ...(brief.role === "builder" && issue.id !== repo.directionIssueId | |
| 1276 | ? { earlierParks: parkReasons(app.db, repo, issue.id) } | |
| 1277 | : {}), | |
| 1278 | // A planning run is given what the crew handed over (`parks.ts`), | |
| 1279 | // what holds the ready list when nothing on it can start (`held.ts`). | |
| 1280 | ...(brief.role === "planner" && issue.id === repo.directionIssueId | |
| 1281 | ? { | |
| 1282 | parkedTwice: [ | |
| 1283 | ...parkedTwice(app.db, [repo]), | |
| 1284 | ...handedTooLarge(app.db, repo), | |
| 1285 | ...handedOverPulls(app.db, repo), | |
| 1286 | ], | |
| 1287 | limbs: handedLimbs(app, repo), | |
| 1288 | laterGate: laterGate(app.db, repo.id), | |
| 1289 | lastWeek: lastWeekFor(app, repo), | |
| 1290 | ...(() => { | |
| 1291 | const held = heldNow(app, repo); | |
| 1292 | return { | |
| 1293 | landed: landedBoxes(held.by.landed), | |
| 1294 | stuck: stuckOf(held), | |
| 1295 | }; | |
| 1296 | })(), | |
| 1297 | owed: owed(app.db, repo.id), | |
| 1298 | } | |
| 1299 | : {}), | |
| 891 | signal, | |
| 1300 | 892 | }); |
| 1301 | 893 | |
| 1302 | // The account this run works on: the nearest grant's, rotating; the | |
| 1303 | // forge's own token when nothing is granted. A grant whose accounts are | |
| 1304 | // all resting holds the run until the first wakes, without a call. | |
| 1305 | const scope = { | |
| 1306 | repoId: repo.id, | |
| 1307 | ownerId: repo.ownerId, | |
| 1308 | agentId: agent.user.id, | |
| 1309 | }; | |
| 1310 | // What this run may spend at most; on a budgeted account the pick | |
| 1311 | // reserves it (or what is left, if less) against the account's budget. | |
| 1312 | const ownBudget = | |
| 1313 | agent.budgetUsd > 0 | |
| 1314 | ? agent.budgetUsd | |
| 1315 | : isOwnForge(app) | |
| 1316 | ? budgetLimit(app.db, "run") | |
| 1317 | : options.budgetUsd; | |
| 1318 | const picked = pickSubscription( | |
| 1319 | app.db, | |
| 1320 | app.config.dataDir, | |
| 1321 | scope, | |
| 1322 | new Date(), | |
| 1323 | { runId: run.id, usd: ownBudget }, | |
| 1324 | ); | |
| 1325 | if (picked.kind === "resting") { | |
| 1326 | const names = picked.names.join(", "); | |
| 1327 | write( | |
| 1328 | `${names}: resting (${picked.said}) until ${whenText(new Date(picked.until))}. ${accountsSaid(app, repo)}`, | |
| 1329 | ); | |
| 1330 | if (run.attempt < MAX_PAUSES) | |
| 1331 | return { | |
| 1332 | state: "paused", | |
| 1333 | summary: `paused: ${names} resting — ${picked.said}; resumes ${whenText(new Date(picked.until))}`, | |
| 1334 | resumeAt: picked.until, | |
| 1335 | sessionId: previous?.sessionId ?? "", | |
| 1336 | costUsd: 0, | |
| 1337 | }; | |
| 1338 | return { | |
| 1339 | state: "failed", | |
| 1340 | summary: `every subscription this repository may use is resting (${picked.said})`, | |
| 1341 | resumesAt: new Date(picked.until), | |
| 1342 | }; | |
| 1343 | } | |
| 1344 | // The account turned requests away this minute: the crew's own work holds, a person's run | |
| 1345 | // goes ahead (#16490). The hold is not a pause the run is counted for. | |
| 1346 | const breathing = run.sent ? undefined : breathingUntil(app.db, picked.kind === "ready" ? picked.subscription.id : PLATFORM, new Date()); | |
| 1347 | if (breathing !== undefined) { | |
| 1348 | const words = breathWords(breathing, false); | |
| 1349 | write(words); | |
| 1350 | return { | |
| 1351 | state: "paused", | |
| 1352 | summary: `paused: ${words}`, | |
| 1353 | resumeAt: breathing.toISOString(), | |
| 1354 | sessionId: previous?.sessionId ?? "", | |
| 1355 | costUsd: 0, | |
| 1356 | keepAttempt: true, | |
| 1357 | }; | |
| 1358 | } | |
| 1359 | // The forge's own token is for admin-owned repositories only; anyone | |
| 1360 | // else's run waits for a grant rather than spend what is not theirs. | |
| 1361 | // The owner's capped monthly grant (`core/model_grant.ts`) is the one | |
| 1362 | // way past it: the forge's token, up to what is left of the month. | |
| 1363 | // The host's included credit is a way past it too (#12105); a copy that says | |
| 1364 | // there is too little may be stale: ask the host before refusing (at most once in 15 s). | |
| 1365 | // The repository's own monthly cap (`core/wallet.ts`): reached, no new run starts. | |
| 1366 | const walletSaid = capReached(app.db, repo.id, new Date()); | |
| 1367 | if (walletSaid !== undefined) { | |
| 1368 | write(walletSaid); | |
| 1369 | return { state: "failed", summary: walletSaid }; | |
| 1370 | } | |
| 1371 | const heldLeft = lentCreditLeft(picked.kind === "none", app.config.dataDir); | |
| 1372 | if (picked.kind === "none" && (heldLeft === undefined || heldLeft < MIN_RUN_USD)) await refreshFundingOnce(app); | |
| 1373 | // The forge's own key drawing on lent credit: the same stale copy, asked about the same way. | |
| 1374 | if (picked.kind === "env" && lentSpent(lentCreditLeft(true, app.config.dataDir), MIN_RUN_USD) !== undefined) await refreshFundingOnce(app); | |
| 1375 | const access = modelAccess(app, picked, repo.ownerId, repo.ownerName); | |
| 1376 | if (!access.ok) { | |
| 1377 | write(access.said); | |
| 1378 | return { state: "failed", summary: access.said }; | |
| 1379 | } | |
| 1380 | const grantCap = picked.kind === "none" ? access.grantCap : undefined; | |
| 1381 | // What this run would spend before the account's ceilings: its own | |
| 1382 | // budget, under the subscription's reservation or the grant's rest. | |
| 1383 | const lentLeft = lentCreditLeft(picked.kind === "env" || picked.kind === "none", app.config.dataDir); | |
| 1384 | // Spent credit is said in the forge's words before anything starts: a run budgeted $0 would | |
| 1385 | // only hand the person the model tool's refusal of that figure. | |
| 1386 | const spentSaid = lentSpent(lentLeft, MIN_RUN_USD); | |
| 1387 | if (spentSaid !== undefined) { | |
| 1388 | write(spentSaid); | |
| 1389 | return { state: "failed", summary: spentSaid }; | |
| 1390 | } | |
| 1391 | const wantedBy = | |
| 1392 | picked.kind === "ready" && picked.capUsd !== undefined | |
| 1393 | ? Math.min(ownBudget, picked.capUsd) | |
| 1394 | : grantCap !== undefined | |
| 1395 | ? Math.min(ownBudget, grantCap) | |
| 1396 | : ownBudget; | |
| 1397 | // On the host's included credit a run is budgeted at most what is left of it | |
| 1398 | // (#11948), so the budget line and the credit line say one number. | |
| 1399 | const wanted = cappedByLent(wantedBy, lentLeft); | |
| 1400 | // The account's own ceilings, daily and per run, apart from the forge's: | |
| 1401 | // a run past either does not start and spends nothing. What it may | |
| 1402 | // spend is reserved against the day now, so a run started beside it is | |
| 1403 | // handed only what is left. | |
| 1404 | const ceiling = reserveCeiling( | |
| 1405 | app.db, | |
| 1406 | repo.ownerId, | |
| 1407 | { id: run.id, wantUsd: wanted }, | |
| 1408 | MIN_RUN_USD, | |
| 1409 | new Date(), | |
| 1410 | ); | |
| 1411 | if (!ceiling.ok) { | |
| 1412 | write(ceiling.said); | |
| 1413 | return { state: "failed", summary: ceiling.said }; | |
| 1414 | } | |
| 1415 | // The owner's own limits on a forge that is theirs (`forge_budget.ts`). | |
| 1416 | const own = budgetVerdict(app, ceiling.capUsd ?? wanted, new Date(), run.id); | |
| 1417 | if (own !== undefined && !own.ok) { | |
| 1418 | write(own.said); | |
| 1419 | return { state: "failed", summary: own.said }; | |
| 1420 | } | |
| 1421 | meter.ceilingOwner = repo.ownerId; | |
| 1422 | if (picked.kind === "ready") { | |
| 1423 | write(`subscription: ${picked.subscription.name}`); | |
| 1424 | noteRunProgress(app.db, run.id, { | |
| 1425 | subscriptionId: picked.subscription.id, | |
| 1426 | }); | |
| 1427 | meter.subscriptionId = picked.subscription.id; | |
| 1428 | } else { | |
| 1429 | if (grantCap !== undefined) { | |
| 1430 | meter.grantOwner = repo.ownerId; | |
| 1431 | write(`model grant: $${grantCap.toFixed(2)} left this month`); | |
| 1432 | } | |
| 1433 | write("subscription: platform (env)"); | |
| 1434 | noteRunProgress(app.db, run.id, { subscriptionId: PLATFORM }); | |
| 1435 | meter.subscriptionId = PLATFORM; | |
| 1436 | } | |
| 1437 | const started = Date.now(); | |
| 1438 | // The model credential sits in the agent's environment, where its shell | |
| 1439 | // can read it. Held like a granted secret from before the agent starts | |
| 1440 | // until the `finally` below: a run that says it leaves `[redacted]` in | |
| 1441 | // its log, its last message and every event. The gateway's address is | |
| 1442 | // not a secret and stays readable. | |
| 1443 | const modelEnv = credentialEnv(picked, app.config.dataDir); | |
| 1444 | modelSecrets = holdModelCredential(modelHold, modelEnv); | |
| 1445 | const env = layerRunEnv({ | |
| 1446 | forge: { | |
| 1447 | // The shard count an admin set (`core/capacity.ts`), for the checks an | |
| 1448 | // agent runs in its clone; never the pod's environment. | |
| 1449 | ...capacityEnv(app.db), | |
| 1450 | ...gitAuth, | |
| 1451 | ...identity, | |
| 1452 | FORGE_URL: options.forgeUrl, | |
| 1453 | FORGE_TOKEN: token.token, | |
| 1454 | ...passportEnv(app.config.dataDir), | |
| 1455 | }, | |
| 1456 | // Granted secrets sit under the model's own variables (`layerRunEnv`). | |
| 1457 | granted: grant.env, | |
| 1458 | model: modelEnv, | |
| 1459 | machine: machineEnv(machine), | |
| 1460 | configDir: options.configDir, | |
| 1461 | }); | |
| 1462 | // The budget in two parts: the work, and a reserve for landing it. An | |
| 1463 | // agent cut off mid-task otherwise leaves a tree the forge commits blind | |
| 1464 | // and a pull whose description is the error. | |
| 1465 | // A member's gateway is a name they keep: Claude Code dials the forge's | |
| 1466 | // loopback door, which resolves the name, judges every address and | |
| 1467 | // dials only a public one (`crew/gateway_door.ts`, #14750). | |
| 1468 | gatewayDoor = doorForRun(picked, env); | |
| 1469 | const budget = Math.min(ceiling.capUsd ?? Infinity, wanted, own?.ok === true ? own.capUsd : Infinity); | |
| 1470 | const reserve = wrapUpReserve(budget); | |
| 1471 | // Asked again for every invocation (`crew/sandbox.ts`): an agent made | |
| 1472 | // since the last one is denied from this one on. | |
| 1473 | const hosts = grant.hosts; | |
| 1474 | const shellPolicy = () => | |
| 1475 | sandboxPolicy({ | |
| 1476 | dataDir: app.config.dataDir, | |
| 1477 | agentName: agent.user.username, | |
| 1478 | urls: [options.localUrl, options.forgeUrl], | |
| 1479 | appUrls: reachableApps(machine, ownAppUrls(ownApp(app, repo))), | |
| 1480 | extraHosts: [ | |
| 1481 | ...(options.allowHosts ?? []), | |
| 1482 | ...hosts, | |
| 1483 | ...(devices?.hosts ?? []), | |
| 1484 | ], | |
| 1485 | gateway: gatewayDoor?.base, | |
| 1486 | enforced: options.sandboxEnforced, | |
| 1487 | runId: run.id, | |
| 1488 | repoId: repo.id, | |
| 1489 | }); | |
| 1490 | const sandbox = shellPolicy(); | |
| 1491 | // The run's own temp directory, never the machine's shared one; it goes | |
| 1492 | // when the run does (the `finally` below). Both names: Claude Code's | |
| 1493 | // sandbox reads its own temp-dir variable, but its shell still binds | |
| 1494 | // `<TMPDIR>/claude-<uid>` writable, so TMPDIR has to say the same. | |
| 1495 | runTmp = sandbox.tmpDir; | |
| 1496 | if (runTmp !== undefined) { | |
| 1497 | makeRunTmp(app.config.dataDir, runTmp); | |
| 1498 | Object.assign(env, sandboxTmpEnv(runTmp)); | |
| 1499 | env["TMPDIR"] = runTmp; | |
| 1500 | // The devices the owner granted this repository: a key file, a pinned | |
| 1501 | // known_hosts and an `ssh` wrapper that logs, all inside the run's own | |
| 1502 | // temp directory, which goes with the run. | |
| 1503 | devices = deviceKit( | |
| 1504 | app.db, | |
| 1505 | app.config.dataDir, | |
| 1506 | app.bus, | |
| 1507 | { id: run.id, repoId: repo.id, actorId: agent.user.id }, | |
| 1508 | runTmp, | |
| 1509 | ); | |
| 1510 | if (devices !== undefined) { | |
| 1511 | env["PATH"] = `${devices.binDir}:${process.env["PATH"] ?? "/usr/local/bin:/usr/bin:/bin"}`; | |
| 1512 | for (const [alias, entry] of Object.entries(devices.aliases)) | |
| 1513 | write(`device: ssh ${alias} is ${entry}`); | |
| 1514 | for (const entry of devices.missing) | |
| 1515 | write(`device not reachable: ${entry} (its key is not a repository secret)`); | |
| 1516 | } | |
| 1517 | } | |
| 1518 | // Bun's install cache is the repository's, shared by its runs, so a | |
| 1519 | // package is downloaded once rather than by every clone. | |
| 1520 | installCacheEnv(sandbox, env); | |
| 1521 | // The sandbox refuses a unix socket's bind; the forge's own servers take | |
| 1522 | // a loopback port instead (`git/hook-address.ts`), so `bun test` runs. | |
| 1523 | if (sandbox.enforced) env["FORGE_TEST_SOCKET"] = "port"; | |
| 1524 | // One deadline for the run, whatever it takes to get there: the token | |
| 1525 | // dies ten minutes after it, so a second invocation gets what is left. | |
| 1526 | const deadline = Date.now() + options.runTimeoutMs; | |
| 1527 | // The token was minted before the setup above spent time: hold it to the deadline (#16106). | |
| 1528 | keepToken(app.db, token.id, deadline); | |
| 1529 | // The agent's own model, unless the work asks for Opus (#7570). A | |
| 1530 | // planner's plain pass runs on Sonnet; one handed work the crew could | |
| 1531 | // not finish runs on Opus (`model_choice.ts`). | |
| 1532 | const handed = | |
| 1533 | brief.role === "planner" && | |
| 1534 | (parkedTwice(app.db, [repo]).length > 0 || | |
| 1535 | handedTooLarge(app.db, repo).length > 0 || | |
| 1536 | handedOverPulls(app.db, repo).length > 0 || | |
| 1537 | handedLimbs(app, repo).length > 0); | |
| 1538 | const facts = modelFacts( | |
| 1539 | app.db, | |
| 894 | const spend = await settleSpend({ | |
| 895 | app, | |
| 896 | run, | |
| 1540 | 897 | repo, |
| 1541 | taskIssue === undefined ? [issue] : [issue, taskIssue], | |
| 1542 | agent.model, | |
| 1543 | brief.role, | |
| 1544 | reviewing, | |
| 1545 | handed, | |
| 1546 | ); | |
| 1547 | const chosen = chooseModel(facts); | |
| 1548 | const invoke = async ( | |
| 1549 | prompt: string, | |
| 1550 | budgetUsd: number, | |
| 1551 | resume: string | undefined, | |
| 1552 | ): Promise<AgentOutcome> => { | |
| 1553 | const spent = redactResult( | |
| 1554 | await runAgent({ | |
| 1555 | binary: options.binary, | |
| 1556 | cwd: dir, | |
| 1557 | prompt, | |
| 1558 | appendSystemPrompt: systemPrompt({ ...brief, devices: devices?.aliases }), | |
| 1559 | model: chosen.model || undefined, | |
| 1560 | budgetUsd, | |
| 1561 | account: runAccount(picked, env), | |
| 1562 | resume, | |
| 1563 | env, | |
| 1564 | sandbox: shellPolicy(), | |
| 1565 | limits: machineLimits(machine), | |
| 1566 | label: `crew:${agent.user.username}`, | |
| 1567 | timeoutMs: Math.max(deadline - Date.now(), 0), | |
| 1568 | log: write, | |
| 1569 | signal, | |
| 1570 | onSteer: (send) => { | |
| 1571 | listenForSteer(run.id, send); | |
| 1572 | }, | |
| 1573 | onMeasure: (m) => | |
| 1574 | noteMeasure(app.db, meter.subscriptionId ?? PLATFORM, m), | |
| 1575 | onCleared: (window) => | |
| 1576 | forgetMeasure(app.db, meter.subscriptionId ?? PLATFORM, window), | |
| 1577 | onUsage: (so) => | |
| 1578 | meterLive( | |
| 1579 | app, | |
| 1580 | run, | |
| 1581 | meter, | |
| 1582 | { | |
| 1583 | tokensIn: meter.tokensIn + so.tokensIn, | |
| 1584 | tokensOut: meter.tokensOut + so.tokensOut, | |
| 1585 | costUsd: meter.costUsd + (so.costUsd ?? 0), | |
| 1586 | }, | |
| 1587 | started, | |
| 1588 | (so.costUsd ?? 0) > 0, | |
| 1589 | ), | |
| 1590 | }), | |
| 1591 | ); | |
| 1592 | meter.tokensIn += spent.tokensIn; | |
| 1593 | meter.tokensOut += spent.tokensOut; | |
| 1594 | meter.costUsd += spent.costUsd ?? 0; | |
| 1595 | return spent; | |
| 1596 | }; | |
| 1597 | // The runner and model this run uses, and what holds its spend: a runner | |
| 1598 | // with no price says so instead of a dollar budget it cannot keep. | |
| 1599 | const heading = currentRunner().heading?.(chosen.model || undefined, env); | |
| 1600 | write( | |
| 1601 | `${heading ?? `claude${chosen.model ? ` (${chosen.model})` : ""}: budget $${budget.toFixed(2)}, $${reserve.toFixed(2)} of it kept for the wrap-up`}${brief.resuming ? `, resuming ${previous?.sessionId}` : ""}`, | |
| 1602 | ); | |
| 1603 | if (!reviewing && resumption.why !== "") write(resumption.why); | |
| 1604 | noteRunProgress(app.db, run.id, { | |
| 1605 | model: chosen.model, | |
| 1606 | modelReason: chosen.reason, | |
| 1607 | promptVersion: promptVersion(agent, brief.role), | |
| 1608 | sandbox: { | |
| 1609 | enforced: sandbox.enforced, | |
| 1610 | note: options.sandboxNote ?? "", | |
| 1611 | }, | |
| 898 | agent, | |
| 899 | defaultBudgetUsd: options.budgetUsd, | |
| 900 | previousSessionId: previous?.sessionId, | |
| 901 | meter, | |
| 902 | write, | |
| 1612 | 903 | }); |
| 1613 | if (!sandbox.enforced) | |
| 1614 | write( | |
| 1615 | `sandbox: off here${options.sandboxNote === undefined ? "" : ` — ${options.sandboxNote}`}; the shell runs unrestricted`, | |
| 1616 | ); | |
| 904 | if (!spend.ok) return spend.outcome; | |
| 905 | const { picked, scope, own, budget } = spend; | |
| 906 | const ready = await prepareAgent({ | |
| 907 | app, | |
| 908 | options, | |
| 909 | run, | |
| 910 | repo, | |
| 911 | agent, | |
| 912 | issue, | |
| 913 | taskIssue, | |
| 914 | brief, | |
| 915 | machine, | |
| 916 | reviewing, | |
| 917 | picked, | |
| 918 | budget, | |
| 919 | gitEnv: { ...gitAuth, ...identity }, | |
| 920 | forgeToken: token, | |
| 921 | grant, | |
| 922 | previousSessionId: previous?.sessionId, | |
| 923 | resumeWhy: resumption.why, | |
| 924 | dir, | |
| 925 | modelHold, | |
| 926 | held, | |
| 927 | meter, | |
| 928 | signal, | |
| 929 | write, | |
| 930 | }); | |
| 931 | const { invoke, deadline, working } = ready; | |
| 1617 | 932 | watch.lap("brief"); |
| 1618 | 933 | ran.inHarness = true; |
| 1619 | 934 | ran.reached = true; |
| 1620 | const working = budget - reserve; | |
| 1621 | 935 | if (!reviewing) |
| 1622 | 936 | early = watchForPull({ |
| 1623 | 937 | app, |
| @@ -1658,62 +972,15 @@ async function work( | ||
| 1658 | 972 | write("the session could not be resumed; starting fresh"); |
| 1659 | 973 | result = await invoke(prompt, working, undefined); |
| 1660 | 974 | } |
| 1661 | // A dropped connection says nothing about the work: ask again before the | |
| 1662 | // run is judged. `next` names the prompt and session for each new ask, | |
| 1663 | // given what the last one left; the main turn and the wrap-up share this. | |
| 1664 | const retrying = async ( | |
| 1665 | first: typeof result, | |
| 1666 | budgetUsd: number, | |
| 1667 | what: string, | |
| 1668 | next: (last: typeof result) => { | |
| 1669 | prompt: string; | |
| 1670 | sessionId: string | undefined; | |
| 1671 | }, | |
| 1672 | ): Promise<typeof result> => { | |
| 1673 | let current = first; | |
| 1674 | for (const seconds of NETWORK_RETRY_SECONDS) { | |
| 1675 | if (!isNetworkError(current) || signal.aborted) break; | |
| 1676 | write(`network error; retrying${what} in ${seconds}s`); | |
| 1677 | await pause(seconds * 1000 * (options.networkRetryScale ?? 1), signal); | |
| 1678 | if (signal.aborted || Date.now() >= deadline) break; | |
| 1679 | const ask = next(current); | |
| 1680 | const again = await invoke(ask.prompt, budgetUsd, ask.sessionId); | |
| 1681 | current = { | |
| 1682 | ...again, | |
| 1683 | sessionId: again.sessionId || current.sessionId, | |
| 1684 | costUsd: current.costUsd + again.costUsd, | |
| 1685 | turns: current.turns + again.turns, | |
| 1686 | contextTokens: again.contextTokens || current.contextTokens, | |
| 1687 | }; | |
| 1688 | } | |
| 1689 | return current; | |
| 975 | const retry: RetryState = { | |
| 976 | invoke, | |
| 977 | signal, | |
| 978 | deadline, | |
| 979 | attempt: run.attempt, | |
| 980 | waitScale: options.networkRetryScale ?? 1, | |
| 981 | write, | |
| 1690 | 982 | }; |
| 1691 | // Still unreachable after the retries: an outage, not a verdict. The run | |
| 1692 | // pauses with its clone and session and asks again later, as it does for | |
| 1693 | // a provider limit, rather than ending as "no changes pushed". | |
| 1694 | const outagePause = ( | |
| 1695 | last: typeof result, | |
| 1696 | costUsd: number, | |
| 1697 | ): Outcome | undefined => { | |
| 1698 | if ( | |
| 1699 | !isNetworkError(last) || | |
| 1700 | signal.aborted || | |
| 1701 | Date.now() >= deadline || | |
| 1702 | run.attempt >= MAX_PAUSES | |
| 1703 | ) | |
| 1704 | return undefined; | |
| 1705 | pausing = true; | |
| 1706 | const at = new Date(Date.now() + NETWORK_PAUSE_MS); | |
| 1707 | write(`network still down; paused, resumes ${whenText(at)}`); | |
| 1708 | return { | |
| 1709 | state: "paused", | |
| 1710 | summary: `paused: network error, resumes ${whenText(at)}`, | |
| 1711 | resumeAt: at.toISOString(), | |
| 1712 | sessionId: last.sessionId, | |
| 1713 | costUsd, | |
| 1714 | }; | |
| 1715 | }; | |
| 1716 | result = await retrying(result, working, "", (last) => | |
| 983 | result = await retryNetwork(retry, result, working, "", (last) => | |
| 1717 | 984 | last.sessionId === "" |
| 1718 | 985 | ? { prompt, sessionId: undefined } |
| 1719 | 986 | : { prompt: "Continue where you stopped.", sessionId: last.sessionId }, |
| @@ -1729,8 +996,11 @@ async function work( | ||
| 1729 | 996 | ); |
| 1730 | 997 | ran.hops.record("agent", options.forgeUrl); |
| 1731 | 998 | } |
| 1732 | const down = outagePause(result, result.costUsd); | |
| 1733 | if (down !== undefined) return down; | |
| 999 | const down = outagePause(retry, result, result.costUsd); | |
| 1000 | if (down !== undefined) { | |
| 1001 | pausing = true; | |
| 1002 | return down; | |
| 1003 | } | |
| 1734 | 1004 | noteRunProgress(app.db, run.id, { |
| 1735 | 1005 | sessionId: result.sessionId, |
| 1736 | 1006 | costUsd: result.costUsd, |
| @@ -1739,278 +1009,80 @@ async function work( | ||
| 1739 | 1009 | `claude: ${result.reason}, ${result.turns} turns, $${result.costUsd.toFixed(2)}`, |
| 1740 | 1010 | ); |
| 1741 | 1011 | |
| 1742 | // The provider's refusal, not the agent's failure: the run pauses with | |
| 1743 | // its clone and session as they are, and goes on when the limit lifts. | |
| 1744 | // A limit that never lifts is not waited on forever. | |
| 1745 | let limitLifts: Date | undefined; | |
| 1746 | // A per-minute refusal (a 429 naming no window): no account rests for it, the run waits a | |
| 1747 | // minute or a few by who sent it, and the crew's own runs on that account hold a while so a | |
| 1748 | // person's build gets the next minute. Plain words; the provider's are in the log. | |
| 1749 | if (isRateLimited(result) && !signal.aborted && perMinute(result.limit) && run.attempt < MAX_PAUSES) { | |
| 1750 | const now = new Date(); | |
| 1751 | const at = new Date(now.getTime() + breathWait(run.attempt, run.sent)); | |
| 1752 | noteBreath(app.db, picked.kind === "ready" ? picked.subscription.id : PLATFORM, new Date(now.getTime() + breathWait(0, false))); | |
| 1753 | write(`the provider: ${result.limit.said ?? result.reason}`); | |
| 1012 | const limited = limitEnding({ app, run, picked, scope, result, aborted: signal.aborted, write }); | |
| 1013 | if ("outcome" in limited) { | |
| 1754 | 1014 | pausing = true; |
| 1755 | return { | |
| 1756 | state: "paused", | |
| 1757 | summary: `paused: ${breathWords(at, run.sent)}`, | |
| 1758 | resumeAt: at.toISOString(), | |
| 1759 | sessionId: result.sessionId, | |
| 1760 | costUsd: result.costUsd, | |
| 1761 | }; | |
| 1762 | } | |
| 1763 | if (isRateLimited(result) && !signal.aborted) { | |
| 1764 | const now = new Date(); | |
| 1765 | // The account rests until the provider's time; another on the same | |
| 1766 | // grant, if one is awake, takes the run straight away. | |
| 1767 | const { until, limit, said } = takeLimit( | |
| 1768 | app.db, | |
| 1769 | picked.kind === "ready" ? picked.subscription.id : undefined, | |
| 1770 | result.limit, | |
| 1771 | result.reason, | |
| 1772 | now, | |
| 1773 | ); | |
| 1774 | if (picked.kind === "ready") { | |
| 1775 | // Only a look at who could take over: no reservation is made here. | |
| 1776 | // The run pauses, and on resume it picks again with its reserve. | |
| 1777 | const next = pickSubscription( | |
| 1778 | app.db, | |
| 1779 | app.config.dataDir, | |
| 1780 | scope, | |
| 1781 | new Date(), | |
| 1782 | ); | |
| 1783 | if ( | |
| 1784 | next.kind === "ready" && | |
| 1785 | next.subscription.id !== picked.subscription.id | |
| 1786 | ) { | |
| 1787 | write( | |
| 1788 | `${picked.subscription.name} rests until ${whenText(until)}; ${next.subscription.name} takes the run`, | |
| 1789 | ); | |
| 1790 | pausing = true; | |
| 1791 | return { | |
| 1792 | state: "paused", | |
| 1793 | summary: `paused: ${pauseReason(picked.subscription.name, limit, said)}; ${next.subscription.name} takes over`, | |
| 1794 | resumeAt: new Date().toISOString(), | |
| 1795 | sessionId: result.sessionId, | |
| 1796 | costUsd: result.costUsd, | |
| 1797 | }; | |
| 1798 | } | |
| 1799 | } | |
| 1800 | if (run.attempt < MAX_PAUSES) { | |
| 1801 | const at = resumeAt(result.limit, new Date()); | |
| 1802 | pausing = true; | |
| 1803 | return { | |
| 1804 | state: "paused", | |
| 1805 | summary: `paused: ${pauseReason(picked.kind === "ready" ? picked.subscription.name : undefined, limitOf(result.limit), said)}; resumes ${whenText(at)}`, | |
| 1806 | resumeAt: at.toISOString(), | |
| 1807 | sessionId: result.sessionId, | |
| 1808 | costUsd: result.costUsd, | |
| 1809 | }; | |
| 1810 | } | |
| 1811 | write(`paused ${MAX_PAUSES} times already; not waiting again`); | |
| 1812 | limitLifts = resumeAt(result.limit, new Date()); | |
| 1015 | return limited.outcome; | |
| 1813 | 1016 | } |
| 1017 | const limitLifts = limited.limitLifts; | |
| 1814 | 1018 | |
| 1815 | 1019 | watch.lap("harness"); |
| 1816 | 1020 | ran.inHarness = false; |
| 1817 | // The reserve: the same session gets one more turn, to land what exists | |
| 1818 | // rather than to keep working. Its ending is the run's ending, with the | |
| 1819 | // whole spend; the pull says where the work stopped. | |
| 1820 | let stoppedAt: number | undefined; | |
| 1821 | if ( | |
| 1822 | result.reason === BUDGET_REACHED && | |
| 1823 | result.sessionId !== "" && | |
| 1824 | !signal.aborted && | |
| 1825 | Date.now() < deadline | |
| 1826 | ) { | |
| 1827 | stoppedAt = result.costUsd; | |
| 1828 | ran.inWrapUp = true; | |
| 1829 | write(`claude: wrapping up with the reserve, $${reserve.toFixed(2)}`); | |
| 1830 | const wrapped = await retrying( | |
| 1831 | await invoke(wrapUpPrompt(), reserve, result.sessionId), | |
| 1832 | reserve, | |
| 1833 | " the wrap-up", | |
| 1834 | (last) => ({ | |
| 1835 | prompt: wrapUpPrompt(), | |
| 1836 | sessionId: last.sessionId || result.sessionId, | |
| 1837 | }), | |
| 1838 | ); | |
| 1839 | // Still unreachable after the retries: the work is not judged on a | |
| 1840 | // wrap-up that never got through; the run pauses as the main turn does. | |
| 1841 | const wrapDown = outagePause(wrapped, result.costUsd + wrapped.costUsd); | |
| 1842 | if (wrapDown !== undefined) return wrapDown; | |
| 1843 | write( | |
| 1844 | `claude: ${wrapped.reason}, ${wrapped.turns} turns, $${wrapped.costUsd.toFixed(2)}`, | |
| 1845 | ); | |
| 1846 | result = { | |
| 1847 | ...wrapped, | |
| 1848 | // A refusal in either turn is one the run met (#16177). | |
| 1849 | denied: [...new Set([...(result.denied ?? []), ...(wrapped.denied ?? [])])], | |
| 1850 | sessionId: wrapped.sessionId || result.sessionId, | |
| 1851 | costUsd: result.costUsd + wrapped.costUsd, | |
| 1852 | turns: result.turns + wrapped.turns, | |
| 1853 | contextTokens: wrapped.contextTokens || result.contextTokens, | |
| 1854 | }; | |
| 1855 | noteRunProgress(app.db, run.id, { costUsd: result.costUsd }); | |
| 1856 | watch.lap("wrap-up"); | |
| 1857 | ran.inWrapUp = false; | |
| 1021 | const wrapped = await wrapUp({ | |
| 1022 | app, | |
| 1023 | run, | |
| 1024 | result, | |
| 1025 | retry, | |
| 1026 | reserve: ready.reserve, | |
| 1027 | deadline, | |
| 1028 | signal, | |
| 1029 | ran, | |
| 1030 | watch, | |
| 1031 | write, | |
| 1032 | }); | |
| 1033 | if (!wrapped.ok) { | |
| 1034 | pausing = true; | |
| 1035 | return wrapped.outcome; | |
| 1858 | 1036 | } |
| 1859 | // A run whose pull closed under it may still have reached its answer: an | |
| 1860 | // already-done decline is kept (`answerCancelled`). One the meter stopped is not. | |
| 1861 | if (signal.aborted && !answeredBeforeStop(meter.stoppedFor, result.result)) | |
| 1862 | return { | |
| 1863 | state: "failed", | |
| 1864 | summary: meter.stoppedFor ?? "cancelled", | |
| 1865 | sessionId: result.sessionId, | |
| 1866 | costUsd: result.costUsd, | |
| 1867 | turns: result.turns, | |
| 1868 | contextTokens: result.contextTokens, | |
| 1869 | }; | |
| 1870 | ||
| 1871 | // A token the forge stopped honouring mid-run refused every write: that is a failed run, | |
| 1872 | // never an ok one that opened nothing (#16106). | |
| 1873 | const refused = refusedToken(app.db, token.id, deadline); | |
| 1874 | if (refused !== undefined) { | |
| 1875 | write(refused); | |
| 1876 | return { | |
| 1877 | state: "failed", | |
| 1878 | summary: refused, | |
| 1879 | sessionId: result.sessionId, | |
| 1880 | costUsd: result.costUsd, | |
| 1881 | turns: result.turns, | |
| 1882 | contextTokens: result.contextTokens, | |
| 1883 | pushed: false, | |
| 1884 | }; | |
| 1885 | } | |
| 1886 | ||
| 1887 | // The decline contract: an agent that should not do the task says so | |
| 1888 | // instead of guessing, and nothing it touched becomes a proposal. | |
| 1889 | const why = declineOf(result.result); | |
| 1890 | if (why !== undefined) { | |
| 1891 | write(`declined: ${why.split("\n")[0] ?? ""}`); | |
| 1892 | ending = { kind: "declined", sentence: why.split("\n")[0] ?? "" }; | |
| 1893 | // Done on the base already, by a commit that is there: its own | |
| 1894 | // outcome, not a park (`already.ts`). A claim without one is an | |
| 1895 | // ordinary decline. | |
| 1896 | const done = await onBase( | |
| 1897 | bare, | |
| 1898 | repo.defaultBranch, | |
| 1899 | namedCommits(why.split("\n")[0] ?? ""), | |
| 1900 | ); | |
| 1901 | if (done.length > 0) | |
| 1902 | return { | |
| 1903 | state: "ok", | |
| 1904 | summary: alreadyDoneSummary(done), | |
| 1905 | sessionId: result.sessionId, | |
| 1906 | costUsd: result.costUsd, | |
| 1907 | turns: result.turns, | |
| 1908 | contextTokens: result.contextTokens, | |
| 1909 | pushed: false, | |
| 1910 | }; | |
| 1911 | // The reason lives on the run record (its summary) and the ledger | |
| 1912 | // line, never as a comment: a comment on an assigned issue is the | |
| 1913 | // thing that starts the next run. | |
| 1914 | return { | |
| 1915 | state: "failed", | |
| 1916 | summary: `declined: ${(why.split("\n")[0] ?? "").slice(0, 200)}`, | |
| 1917 | sessionId: result.sessionId, | |
| 1918 | costUsd: result.costUsd, | |
| 1919 | turns: result.turns, | |
| 1920 | contextTokens: result.contextTokens, | |
| 1921 | pushed: false, | |
| 1922 | }; | |
| 1923 | } | |
| 1924 | ||
| 1925 | // A reviewer's work is its verdict, posted through the API; it pushes | |
| 1926 | // nothing and has nothing to land. The run is judged by whether the | |
| 1927 | // verdict is there, not by what the session said about itself. | |
| 1928 | if (reviewing && pull !== undefined) { | |
| 1929 | const settled = settleReview( | |
| 1930 | listReviews(app.db, pull.id), | |
| 1931 | agent.user.id, | |
| 1932 | began, | |
| 1933 | pull.headOid, | |
| 1934 | result.denied, | |
| 1935 | ); | |
| 1936 | write(settled.summary); | |
| 1937 | return { | |
| 1938 | ...settled, | |
| 1939 | sessionId: result.sessionId, | |
| 1940 | costUsd: result.costUsd, | |
| 1941 | turns: result.turns, | |
| 1942 | contextTokens: result.contextTokens, | |
| 1943 | pushed: false, | |
| 1944 | }; | |
| 1945 | } | |
| 1946 | ||
| 1947 | // Bookkeeping the agent does not have to get right. | |
| 1948 | const landed = await landWork( | |
| 1037 | const settled = await settleRun({ | |
| 1949 | 1038 | app, |
| 1950 | 1039 | options, |
| 1040 | run, | |
| 1951 | 1041 | repo, |
| 1952 | 1042 | agent, |
| 1953 | 1043 | issue, |
| 1954 | continuing ? undefined : pull, | |
| 1955 | fork.value, | |
| 1044 | pull, | |
| 1045 | foreign, | |
| 1046 | continuing, | |
| 1047 | reviewing, | |
| 1048 | fork: fork.value, | |
| 1956 | 1049 | branch, |
| 1957 | 1050 | dir, |
| 1958 | forkBare, | |
| 1959 | 1051 | bare, |
| 1960 | { ...gitAuth, ...identity }, | |
| 1961 | result.result, | |
| 1962 | pullNote( | |
| 1963 | foreign | |
| 1964 | ? `A fresh start: pull #${foreign.number}'s branch \`${foreign.headBranch}\` lives in another fork, which the crew cannot push to, so this work began from \`${repo.defaultBranch}\` and does not carry that branch's commits.` | |
| 1965 | : undefined, | |
| 1966 | stoppedAt === undefined | |
| 1967 | ? undefined | |
| 1968 | : `Budget reached at $${stoppedAt.toFixed(2)}; this is where it stopped.`, | |
| 1969 | ), | |
| 1052 | forkBare, | |
| 1053 | gitEnv: { ...gitAuth, ...identity }, | |
| 1054 | secrets: [...Object.values(grant.env), ...held.modelSecrets, ...(held.devices?.values ?? [])], | |
| 1055 | meter, | |
| 1056 | hops: ran.hops, | |
| 1057 | tokenId: token.id, | |
| 1058 | deadline, | |
| 1059 | began, | |
| 1060 | signal, | |
| 1061 | result: wrapped.result, | |
| 1062 | stoppedAt: wrapped.stoppedAt, | |
| 1063 | limitLifts, | |
| 1064 | own, | |
| 1970 | 1065 | write, |
| 1971 | [...Object.values(grant.env), ...modelSecrets, ...(devices?.values ?? [])], | |
| 1972 | run.variantGroup, | |
| 1973 | ran.hops, | |
| 1974 | ); | |
| 1975 | // An outage that outlasted every pause is named as one, not as a push | |
| 1976 | // that found nothing: the board and the sentinel read the difference. | |
| 1977 | const outage = !landed.pushed && isNetworkError(result); | |
| 1978 | return { | |
| 1979 | state: result.ok || landed.pushed ? "ok" : "failed", | |
| 1980 | summary: outage | |
| 1981 | ? `network unreachable after ${MAX_PAUSES} pauses; nothing to land (${result.reason})` | |
| 1982 | : landed.summary + | |
| 1983 | (result.ok ? "" : ` (${result.reason})`) + | |
| 1984 | cutOffBy(app.db, own, stoppedAt !== undefined), | |
| 1985 | resumesAt: limitLifts, | |
| 1986 | sessionId: result.sessionId, | |
| 1987 | costUsd: result.costUsd, | |
| 1988 | turns: result.turns, | |
| 1989 | contextTokens: result.contextTokens, | |
| 1990 | pushed: landed.pushed, | |
| 1991 | }; | |
| 1066 | }); | |
| 1067 | if (settled.ending !== undefined) ending = settled.ending; | |
| 1068 | return settled.outcome; | |
| 1992 | 1069 | } finally { |
| 1993 | 1070 | await early?.stop(); |
| 1994 | 1071 | if (!pausing) early?.settle(ending); |
| 1995 | 1072 | grant?.release(); |
| 1996 | if (devices !== undefined) { | |
| 1997 | recordDeviceSessions(app.bus, devices, run, agent.user.id, write); | |
| 1998 | devices.release(); | |
| 1073 | if (held.devices !== undefined) { | |
| 1074 | recordDeviceSessions(app.bus, held.devices, run, agent.user.id, write); | |
| 1075 | held.devices.release(); | |
| 1999 | 1076 | } |
| 2000 | gatewayDoor?.close(); | |
| 1077 | held.gatewayDoor?.close(); | |
| 2001 | 1078 | releaseValues(modelHold); |
| 2002 | 1079 | releaseValues(tokenHold); |
| 2003 | 1080 | await workdir.release(); |
| 2004 | 1081 | deleteToken(app.db, agent.user.id, token.id); |
| 2005 | 1082 | // Whatever the run left in its temp directory, however much: removed off this thread. |
| 2006 | if (runTmp !== undefined) await rm(runTmp, { recursive: true, force: true }); | |
| 1083 | if (held.runTmp !== undefined) await rm(held.runTmp, { recursive: true, force: true }); | |
| 2007 | 1084 | // The host counted what the run cost: ask it now, so the credit line moves |
| 2008 | 1085 | // when a run spends (#11948). |
| 2009 | 1086 | void runEnded(app, fetch, { costUsd: lentCost(app, getRun(app.db, run.id)?.costUsd ?? 0), spentAtStart }); |
| 2010 | 1087 | } |
| 2011 | 1088 | } |
| 2012 | ||
| 2013 | /** What the agent said, with every held secret value taken out of it. */ | |
| 2014 | function redactResult<T extends { result: string }>(r: T): T { | |
| 2015 | return { ...r, result: redactValues(r.result) }; | |
| 2016 | } |
test/crew-devices.test.ts +6 −4
| @@ -425,9 +425,11 @@ describe("over HTTP, and from a run's end to the sandbox", () => { | ||
| 425 | 425 | }); |
| 426 | 426 | |
| 427 | 427 | test("the runner wires the kit: hosts into the sandbox, keys into the held values, events at the end", () => { |
| 428 | const src = readFileSync(join(import.meta.dir, "../src/crew/runner.ts"), "utf8"); | |
| 429 | expect(src).toContain("...(devices?.hosts ?? [])"); | |
| 430 | expect(src).toMatch(/\.\.\.\(devices\?\.values \?\? \[\]\)\s*\]/); | |
| 431 | expect(src).toContain("recordDeviceSessions(app.bus, devices,"); | |
| 428 | const read = (f: string) => readFileSync(join(import.meta.dir, "../src/crew", f), "utf8"); | |
| 429 | // The sandbox is built in the prepare step; the held values and the end are the runner's own. | |
| 430 | expect(read("run_prepare.ts")).toContain("...(held.devices?.hosts ?? [])"); | |
| 431 | const runner = read("runner.ts"); | |
| 432 | expect(runner).toMatch(/\.\.\.\(held\.devices\?\.values \?\? \[\]\)\s*\]/); | |
| 433 | expect(runner).toContain("recordDeviceSessions(app.bus, held.devices,"); | |
| 432 | 434 | }); |
| 433 | 435 | }); |
test/run-steps.test.ts added +586
| @@ -0,0 +1,586 @@ | ||
| 1 | /** | |
| 2 | * The steps `work()` in `src/crew/runner.ts` was split into (#16789): each takes its state as a | |
| 3 | * plain object, so each is tested on its own, without an agent or a clone. | |
| 4 | */ | |
| 5 | import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; | |
| 6 | import { tmpdir } from "node:os"; | |
| 7 | import { join } from "node:path"; | |
| 8 | import { createAgent } from "../src/actions/crew.ts"; | |
| 9 | import { createRepo } from "../src/actions/repos.ts"; | |
| 10 | import { createApp, type App } from "../src/app.ts"; | |
| 11 | import { Stopwatch } from "../src/apps/timing.ts"; | |
| 12 | import { clearAccountCeiling, setAccountCeiling } from "../src/core/account_ceiling.ts"; | |
| 13 | import type { Agent } from "../src/core/agents.ts"; | |
| 14 | import { addComment, createIssue, type Issue } from "../src/core/issues.ts"; | |
| 15 | import type { Repo } from "../src/core/repos.ts"; | |
| 16 | import type { Review } from "../src/core/reviews.ts"; | |
| 17 | import { createRun, type Run } from "../src/core/runs.ts"; | |
| 18 | import { addSubscription, restSubscription, setGrants, wakeSubscription, type Pick } from "../src/core/subscriptions.ts"; | |
| 19 | import { createUser, type User } from "../src/core/users.ts"; | |
| 20 | import { setMonthCap } from "../src/core/wallet.ts"; | |
| 21 | import { BUDGET_REACHED, type AgentOutcome } from "../src/crew/agent_runner.ts"; | |
| 22 | import { wrapUpPrompt, type RunReason } from "../src/crew/brief.ts"; | |
| 23 | import { setBudget, stoppedBy } from "../src/crew/forge_budget.ts"; | |
| 24 | import { MAX_PAUSES, noteBreath } from "../src/crew/limits.ts"; | |
| 25 | import type { Meter, Outcome } from "../src/crew/meter.ts"; | |
| 26 | import { feedbackSince } from "../src/crew/news.ts"; | |
| 27 | import { limitEnding } from "../src/crew/run_limits.ts"; | |
| 28 | import { conflictFilesOf, lastTryOf, promptFor } from "../src/crew/run_prompt.ts"; | |
| 29 | import { outagePause, retryNetwork, type RetryState } from "../src/crew/run_retry.ts"; | |
| 30 | import { settleSpend, type Spend } from "../src/crew/run_spend.ts"; | |
| 31 | import { settleReview, verdictOf } from "../src/crew/run_verdict.ts"; | |
| 32 | import { wrapUp } from "../src/crew/run_wrapup.ts"; | |
| 33 | import { CREDIT_SPENT_SAID } from "../src/spawn/funding.ts"; | |
| 34 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 35 | ||
| 36 | const outcome = (over: Partial<AgentOutcome> = {}): AgentOutcome => ({ | |
| 37 | ok: true, | |
| 38 | sessionId: "s1", | |
| 39 | result: "done", | |
| 40 | costUsd: 0.5, | |
| 41 | turns: 3, | |
| 42 | tokensIn: 1, | |
| 43 | tokensOut: 1, | |
| 44 | contextTokens: 10, | |
| 45 | contextWindow: 100, | |
| 46 | reason: "completed", | |
| 47 | ...over, | |
| 48 | }); | |
| 49 | const down = (over: Partial<AgentOutcome> = {}) => | |
| 50 | outcome({ ok: false, result: "connect ECONNREFUSED", reason: "error", turns: 0, costUsd: 0, ...over }); | |
| 51 | ||
| 52 | const retryState = (over: Partial<RetryState> & { calls?: string[] } = {}): RetryState => { | |
| 53 | const calls = over.calls ?? []; | |
| 54 | return { | |
| 55 | invoke: async (prompt, _budget, resume) => { | |
| 56 | calls.push(`${prompt}|${resume ?? ""}`); | |
| 57 | return outcome({ sessionId: "s2" }); | |
| 58 | }, | |
| 59 | signal: new AbortController().signal, | |
| 60 | deadline: Date.now() + 60_000, | |
| 61 | attempt: 0, | |
| 62 | waitScale: 0, | |
| 63 | write: () => {}, | |
| 64 | ...over, | |
| 65 | }; | |
| 66 | }; | |
| 67 | ||
| 68 | describe("retryNetwork", () => { | |
| 69 | test("an answer that was not a network error is returned as it is, nothing asked again", async () => { | |
| 70 | const calls: string[] = []; | |
| 71 | const first = outcome(); | |
| 72 | expect(await retryNetwork(retryState({ calls }), first, 1, "", () => ({ prompt: "p", sessionId: "s" }))).toBe(first); | |
| 73 | expect(calls).toEqual([]); | |
| 74 | }); | |
| 75 | ||
| 76 | test("asks again with what `next` names, and adds the spend of every ask", async () => { | |
| 77 | const calls: string[] = []; | |
| 78 | const said: string[] = []; | |
| 79 | const got = await retryNetwork( | |
| 80 | retryState({ calls, write: (l) => said.push(l) }), | |
| 81 | down({ sessionId: "s1", costUsd: 0.25 }), | |
| 82 | 1, | |
| 83 | " the wrap-up", | |
| 84 | (last) => ({ prompt: "again", sessionId: last.sessionId }), | |
| 85 | ); | |
| 86 | expect(calls).toEqual(["again|s1"]); | |
| 87 | expect(said[0]).toMatch(/^network error; retrying the wrap-up in \d+s$/); | |
| 88 | expect(got.ok).toBe(true); | |
| 89 | expect(got.sessionId).toBe("s2"); | |
| 90 | expect(got.costUsd).toBeCloseTo(0.75); | |
| 91 | expect(got.turns).toBe(3); | |
| 92 | }); | |
| 93 | ||
| 94 | test("a run that was stopped is not asked again", async () => { | |
| 95 | const calls: string[] = []; | |
| 96 | const stop = new AbortController(); | |
| 97 | stop.abort(); | |
| 98 | await retryNetwork(retryState({ calls, signal: stop.signal }), down(), 1, "", () => ({ prompt: "p", sessionId: undefined })); | |
| 99 | expect(calls).toEqual([]); | |
| 100 | }); | |
| 101 | }); | |
| 102 | ||
| 103 | describe("outagePause", () => { | |
| 104 | test("an outage pauses the run with its session and what it spent", () => { | |
| 105 | const paused = outagePause(retryState(), down({ sessionId: "s9" }), 1.25); | |
| 106 | expect(paused?.state).toBe("paused"); | |
| 107 | if (paused?.state !== "paused") throw new Error("not paused"); | |
| 108 | expect(paused.sessionId).toBe("s9"); | |
| 109 | expect(paused.costUsd).toBe(1.25); | |
| 110 | expect(paused.summary).toStartWith("paused: network error, resumes "); | |
| 111 | }); | |
| 112 | ||
| 113 | test("not an outage, a past deadline, a stopped run and a run out of pauses are no pause", () => { | |
| 114 | expect(outagePause(retryState(), outcome(), 0)).toBeUndefined(); | |
| 115 | expect(outagePause(retryState({ deadline: Date.now() - 1 }), down(), 0)).toBeUndefined(); | |
| 116 | expect(outagePause(retryState({ attempt: MAX_PAUSES }), down(), 0)).toBeUndefined(); | |
| 117 | const stop = new AbortController(); | |
| 118 | stop.abort(); | |
| 119 | expect(outagePause(retryState({ signal: stop.signal }), down(), 0)).toBeUndefined(); | |
| 120 | }); | |
| 121 | }); | |
| 122 | ||
| 123 | describe("limitEnding", () => { | |
| 124 | let dataDir: string; | |
| 125 | let app: App; | |
| 126 | beforeAll(async () => { | |
| 127 | dataDir = await mkdtemp(join(tmpdir(), "forge-run-steps-")); | |
| 128 | app = createApp({ dataDir, port: 0 }); | |
| 129 | }); | |
| 130 | afterAll(async () => { | |
| 131 | await rm(dataDir, { recursive: true, force: true }); | |
| 132 | }); | |
| 133 | ||
| 134 | const state = (result: AgentOutcome, run: Partial<Run> = {}, aborted = false) => ({ | |
| 135 | app, | |
| 136 | run: { attempt: 0, sent: false, ...run } as Run, | |
| 137 | picked: { kind: "env" } as unknown as Pick, | |
| 138 | scope: { repoId: "r", ownerId: "o", agentId: "a" }, | |
| 139 | result, | |
| 140 | aborted, | |
| 141 | write: () => {}, | |
| 142 | }); | |
| 143 | ||
| 144 | test("a session that was not refused has no limit to wait out", () => { | |
| 145 | expect(limitEnding(state(outcome()))).toEqual({ limitLifts: undefined }); | |
| 146 | expect(limitEnding(state(outcome({ ok: false, reason: "error" })))).toEqual({ limitLifts: undefined }); | |
| 147 | }); | |
| 148 | ||
| 149 | test("a per-minute refusal pauses the run for a minute or so, with its session", () => { | |
| 150 | const got = limitEnding(state(outcome({ ok: false, limit: { said: "429 too many requests" } }))); | |
| 151 | if (!("outcome" in got) || got.outcome.state !== "paused") throw new Error("expected a pause"); | |
| 152 | expect(got.outcome.sessionId).toBe("s1"); | |
| 153 | expect(Date.parse(got.outcome.resumeAt)).toBeGreaterThan(Date.now()); | |
| 154 | }); | |
| 155 | ||
| 156 | test("a usage limit pauses the run until the limit lifts; past its pauses it names when it lifts", () => { | |
| 157 | const limit = { said: "usage limit reached", limitedUntil: new Date(Date.now() + 3_600_000).toISOString() }; | |
| 158 | const paused = limitEnding(state(outcome({ ok: false, limit }))); | |
| 159 | if (!("outcome" in paused) || paused.outcome.state !== "paused") throw new Error("expected a pause"); | |
| 160 | expect(paused.outcome.summary).toContain("resumes"); | |
| 161 | const spent = limitEnding(state(outcome({ ok: false, limit }), { attempt: MAX_PAUSES })); | |
| 162 | if (!("limitLifts" in spent)) throw new Error("expected no pause"); | |
| 163 | expect(spent.limitLifts).toBeInstanceOf(Date); | |
| 164 | }); | |
| 165 | ||
| 166 | test("a run that was stopped is not paused by the limit it met", () => { | |
| 167 | expect(limitEnding(state(outcome({ ok: false, limit: { said: "usage limit" } }), {}, true))).toEqual({ | |
| 168 | limitLifts: undefined, | |
| 169 | }); | |
| 170 | }); | |
| 171 | }); | |
| 172 | ||
| 173 | describe("verdictOf", () => { | |
| 174 | const base = { | |
| 175 | app: undefined as unknown as App, | |
| 176 | repo: { defaultBranch: "main" } as Repo, | |
| 177 | agent: { user: { id: "u1" } } as Agent, | |
| 178 | pull: undefined, | |
| 179 | reviewing: false, | |
| 180 | bare: "/nonexistent", | |
| 181 | began: "2026-01-01T00:00:00.000Z", | |
| 182 | write: () => {}, | |
| 183 | }; | |
| 184 | ||
| 185 | test("an agent's decline is a failed run that carries the session and pushed nothing", async () => { | |
| 186 | const said: string[] = []; | |
| 187 | const got = await verdictOf({ | |
| 188 | ...base, | |
| 189 | write: (l) => said.push(l), | |
| 190 | result: outcome({ result: "DECLINED: the issue asks for the impossible\nmore" }), | |
| 191 | }); | |
| 192 | expect(got?.ending).toEqual({ kind: "declined", sentence: "the issue asks for the impossible" }); | |
| 193 | expect(got?.outcome).toMatchObject({ state: "failed", sessionId: "s1", turns: 3, pushed: false }); | |
| 194 | expect(said[0]).toStartWith("declined: "); | |
| 195 | }); | |
| 196 | ||
| 197 | test("a session that neither declined nor reviewed has work to land", async () => { | |
| 198 | expect(await verdictOf({ ...base, result: outcome() })).toBeUndefined(); | |
| 199 | }); | |
| 200 | }); | |
| 201 | ||
| 202 | describe("settleReview", () => { | |
| 203 | const review = (over: Partial<Review>): Review => ({ authorId: "u1", createdAt: "2026-02-01", commitOid: "x", state: "approved", ...over }) as Review; | |
| 204 | ||
| 205 | test("a verdict since the run began, or on the head it was given, is ok; none is failed", () => { | |
| 206 | expect(settleReview([review({})], "u1", "2026-01-01", "h").summary).toBe("reviewed: approved"); | |
| 207 | expect(settleReview([review({ createdAt: "2025-01-01", commitOid: "h", state: "changes_requested" })], "u1", "2026-01-01", "h").summary).toBe( | |
| 208 | "reviewed: changes requested", | |
| 209 | ); | |
| 210 | expect(settleReview([review({ authorId: "u2" })], "u1", "2026-01-01", "h").state).toBe("failed"); | |
| 211 | }); | |
| 212 | }); | |
| 213 | ||
| 214 | describe("the prompt's helpers", () => { | |
| 215 | test("conflictFilesOf reads the file names off a moved-main summary", () => { | |
| 216 | expect(conflictFilesOf("main moved: a.ts, b/c.ts")).toEqual(["a.ts", "b/c.ts"]); | |
| 217 | expect(conflictFilesOf("upstream moved: x")).toEqual(["x"]); | |
| 218 | expect(conflictFilesOf("")).toEqual([]); | |
| 219 | }); | |
| 220 | ||
| 221 | test("lastTryOf is the latest verdict asking for changes, and none without one", () => { | |
| 222 | const app = createApp({ dataDir: join(tmpdir(), `forge-run-steps-lt-${Date.now()}`), port: 0 }); | |
| 223 | const run = { id: "r1" } as Run; | |
| 224 | expect(lastTryOf(app, "i1", run, [{ state: "approved", authorName: "r", body: "ok" }])).toBeUndefined(); | |
| 225 | expect( | |
| 226 | lastTryOf(app, "i1", run, [ | |
| 227 | { state: "changes_requested", authorName: "old", body: "first" }, | |
| 228 | { state: "changes_requested", authorName: "rev", body: "second" }, | |
| 229 | ]), | |
| 230 | ).toEqual({ reviewer: "rev", verdict: "second", answer: "" }); | |
| 231 | }); | |
| 232 | }); | |
| 233 | ||
| 234 | describe("settleSpend", () => { | |
| 235 | const NOW = new Date(); | |
| 236 | let dir: string; | |
| 237 | let app: App; | |
| 238 | let own: App; | |
| 239 | let admin: User; | |
| 240 | let guest: User; | |
| 241 | let ownAdmin: User; | |
| 242 | let repo: Repo; | |
| 243 | let guestRepo: Repo; | |
| 244 | let ownRepo: Repo; | |
| 245 | ||
| 246 | const user = async (a: App, username: string, adminIfFirst: boolean): Promise<User> => { | |
| 247 | const made: any = await createUser(a.db, { | |
| 248 | origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst, | |
| 249 | }); | |
| 250 | return made.value ?? made; | |
| 251 | }; | |
| 252 | const repoOf = async (a: App, owner: User, name: string): Promise<Repo> => { | |
| 253 | const made: any = await createRepo(a, owner, { name, visibility: "public" }); | |
| 254 | return made.value ?? made; | |
| 255 | }; | |
| 256 | ||
| 257 | beforeAll(async () => { | |
| 258 | dir = await mkdtemp(join(tmpdir(), "forge-run-spend-")); | |
| 259 | app = createApp({ dataDir: join(dir, "plain"), port: 0 }); | |
| 260 | admin = await user(app, "trevato", true); | |
| 261 | guest = await user(app, "guest", false); | |
| 262 | repo = await repoOf(app, admin, "garden"); | |
| 263 | guestRepo = await repoOf(app, guest, "yard"); | |
| 264 | // A forge somebody owns: its host's file is in its directory, and lent credit with it. | |
| 265 | await mkdir(join(dir, "own"), { recursive: true }); | |
| 266 | await writeFile(join(dir, "own", "parent.json"), JSON.stringify({ credit: { token: "bearer-token-1", capUsd: 2, spentUsd: 0 } }), { mode: 0o600 }); | |
| 267 | own = createApp({ dataDir: join(dir, "own"), port: 0 }); | |
| 268 | ownAdmin = await user(own, "maria", true); | |
| 269 | ownRepo = await repoOf(own, ownAdmin, "shop"); | |
| 270 | }); | |
| 271 | afterAll(async () => { | |
| 272 | app.close(); | |
| 273 | own.close(); | |
| 274 | await rm(dir, { recursive: true, force: true }); | |
| 275 | }); | |
| 276 | ||
| 277 | /** | |
| 278 | * A run that cost `usd` today, in the ledger the wallet, the ceilings and the forge's limits | |
| 279 | * count. | |
| 280 | */ | |
| 281 | const costing = (a: App, r: Repo, usd: number): void => { | |
| 282 | const run = createRun(a.db, { repoId: r.id, kind: "agent" }); | |
| 283 | a.db.query(`INSERT INTO usage (run_id, repo_id, kind, cost_usd, outcome, at) VALUES (?1, ?2, 'build', ?3, 'ok', ?4)`).run(run.id, r.id, usd, new Date().toISOString()); | |
| 284 | }; | |
| 285 | const agentFor = (a: App, budgetUsd: number): Agent => ({ budgetUsd, user: { id: `agent-${a.config.dataDir}` } }) as unknown as Agent; | |
| 286 | const meterOf = (): Meter => ({ tokensIn: 0, tokensOut: 0, costUsd: 0, subscriptionId: null, kind: "build", reportedAt: 0, stop: () => {} }) as Meter; | |
| 287 | const settle = async (over: { app?: App; repo?: Repo; budgetUsd?: number; run?: Partial<Run>; meter?: Meter } = {}) => { | |
| 288 | const a = over.app ?? app; | |
| 289 | const said: string[] = []; | |
| 290 | const meter = over.meter ?? meterOf(); | |
| 291 | const spend = await settleSpend({ | |
| 292 | app: a, | |
| 293 | run: { id: "run-spend", attempt: 0, sent: false, ...over.run } as Run, | |
| 294 | repo: over.repo ?? repo, | |
| 295 | agent: agentFor(a, over.budgetUsd ?? 3), | |
| 296 | defaultBudgetUsd: 4, | |
| 297 | previousSessionId: "prev", | |
| 298 | meter, | |
| 299 | write: (l) => said.push(l), | |
| 300 | }); | |
| 301 | return { spend, said, meter }; | |
| 302 | }; | |
| 303 | const refused = (spend: Spend): Outcome => { | |
| 304 | if (spend.ok) throw new Error("expected a refusal"); | |
| 305 | return spend.outcome; | |
| 306 | }; | |
| 307 | ||
| 308 | test("a repository whose owner may use the forge's key is budgeted what its agent is, and the meter says whose account", async () => { | |
| 309 | const { spend, said, meter } = await settle(); | |
| 310 | if (!spend.ok) throw new Error("expected to start"); | |
| 311 | expect(spend.picked.kind).toBe("env"); | |
| 312 | expect(spend.budget).toBe(3); | |
| 313 | expect(spend.scope).toEqual({ repoId: repo.id, ownerId: repo.ownerId, agentId: "agent-" + app.config.dataDir }); | |
| 314 | expect(meter.subscriptionId).toBe("platform"); | |
| 315 | expect(meter.ceilingOwner).toBe(repo.ownerId); | |
| 316 | expect(said).toEqual(["subscription: platform (env)"]); | |
| 317 | }); | |
| 318 | ||
| 319 | test("an agent with no budget of its own gets the one the forge was given for runs", async () => { | |
| 320 | const { spend } = await settle({ budgetUsd: 0 }); | |
| 321 | expect(spend.ok && spend.budget).toBe(4); | |
| 322 | }); | |
| 323 | ||
| 324 | test("a repository whose owner has no account is refused in the forge's words, before anything starts", async () => { | |
| 325 | const { spend, said, meter } = await settle({ repo: guestRepo }); | |
| 326 | const out = refused(spend); | |
| 327 | expect(out.state).toBe("failed"); | |
| 328 | expect(out.summary).toContain("has no model account"); | |
| 329 | expect(said).toEqual([out.summary]); | |
| 330 | expect(meter.subscriptionId).toBeNull(); | |
| 331 | }); | |
| 332 | ||
| 333 | test("the repository's monthly cap, once reached, starts no run", async () => { | |
| 334 | setMonthCap(app.db, repo.id, 1, admin.id, NOW); | |
| 335 | try { | |
| 336 | costing(app, repo, 1); | |
| 337 | const { spend, said } = await settle(); | |
| 338 | const out = refused(spend); | |
| 339 | expect(out.state).toBe("failed"); | |
| 340 | expect(out.summary).toContain("monthly cap of $1 is reached"); | |
| 341 | expect(said).toEqual([out.summary]); | |
| 342 | } finally { | |
| 343 | setMonthCap(app.db, repo.id, undefined, admin.id, NOW); | |
| 344 | app.db.query("DELETE FROM usage").run(); | |
| 345 | } | |
| 346 | }); | |
| 347 | ||
| 348 | test("the account's per-run ceiling lowers the budget; its daily ceiling, once spent, refuses the run", async () => { | |
| 349 | setAccountCeiling(app.db, admin.id, 100, 2, admin.id, NOW); | |
| 350 | try { | |
| 351 | const capped = await settle(); | |
| 352 | expect(capped.spend.ok && capped.spend.budget).toBe(2); | |
| 353 | setAccountCeiling(app.db, admin.id, 1, 2, admin.id, NOW); | |
| 354 | costing(app, repo, 1); | |
| 355 | const spent = await settle(); | |
| 356 | const out = refused(spent.spend); | |
| 357 | expect(out.state).toBe("failed"); | |
| 358 | expect(out.summary).toContain("daily ceiling ($1.00) is spent for today"); | |
| 359 | expect(spent.meter.ceilingOwner).toBeUndefined(); | |
| 360 | } finally { | |
| 361 | clearAccountCeiling(app.db, admin.id); | |
| 362 | app.db.query("DELETE FROM usage").run(); | |
| 363 | } | |
| 364 | }); | |
| 365 | ||
| 366 | test("a per-run ceiling too small to start a run refuses it", async () => { | |
| 367 | setAccountCeiling(app.db, admin.id, 100, 0.1, admin.id, NOW); | |
| 368 | try { | |
| 369 | const out = refused((await settle()).spend); | |
| 370 | expect(out.state).toBe("failed"); | |
| 371 | expect(out.summary).toContain("per-run ceiling ($0.10) is too small"); | |
| 372 | } finally { | |
| 373 | clearAccountCeiling(app.db, admin.id); | |
| 374 | } | |
| 375 | }); | |
| 376 | ||
| 377 | describe("a granted account", () => { | |
| 378 | let subscription: string; | |
| 379 | beforeAll(() => { | |
| 380 | const added = addSubscription(app.db, app.config.dataDir, { name: "work plan", token: "sk-ant-api03-abcdef" }); | |
| 381 | if (!added.ok) throw new Error("subscription"); | |
| 382 | subscription = added.value.id; | |
| 383 | setGrants(app.db, repo.id, "", [subscription]); | |
| 384 | }); | |
| 385 | afterAll(() => setGrants(app.db, repo.id, "", [])); | |
| 386 | ||
| 387 | test("is the account the run works on, noted on the run and the meter", async () => { | |
| 388 | const { spend, said, meter } = await settle(); | |
| 389 | if (!spend.ok) throw new Error("expected to start"); | |
| 390 | expect(spend.picked.kind).toBe("ready"); | |
| 391 | expect(meter.subscriptionId).toBe(subscription); | |
| 392 | expect(said).toEqual(["subscription: work plan"]); | |
| 393 | }); | |
| 394 | ||
| 395 | test("every account resting pauses the run with its session until the first wakes, uncounted as a failure", async () => { | |
| 396 | restSubscription(app.db, subscription, new Date(NOW.getTime() + 3_600_000).toISOString(), "usage limit"); | |
| 397 | try { | |
| 398 | const out = refused((await settle()).spend); | |
| 399 | if (out.state !== "paused") throw new Error("expected a pause"); | |
| 400 | expect(out.summary).toStartWith("paused: work plan resting — usage limit; resumes "); | |
| 401 | expect(out.sessionId).toBe("prev"); | |
| 402 | expect(out.costUsd).toBe(0); | |
| 403 | expect(Date.parse(out.resumeAt)).toBeGreaterThan(NOW.getTime()); | |
| 404 | } finally { | |
| 405 | wakeSubscription(app.db, subscription); | |
| 406 | } | |
| 407 | }); | |
| 408 | ||
| 409 | test("a run that has paused as often as it may fails instead, naming when the account wakes", async () => { | |
| 410 | restSubscription(app.db, subscription, new Date(NOW.getTime() + 3_600_000).toISOString(), "usage limit"); | |
| 411 | try { | |
| 412 | const out = refused((await settle({ run: { attempt: MAX_PAUSES } })).spend); | |
| 413 | if (out.state !== "failed") throw new Error("expected a failure"); | |
| 414 | expect(out.summary).toBe("every subscription this repository may use is resting (usage limit)"); | |
| 415 | expect(out.resumesAt).toBeInstanceOf(Date); | |
| 416 | } finally { | |
| 417 | wakeSubscription(app.db, subscription); | |
| 418 | } | |
| 419 | }); | |
| 420 | ||
| 421 | test("an account that turned requests away this minute holds the crew's run, not a person's", async () => { | |
| 422 | noteBreath(app.db, subscription, new Date(Date.now() + 60_000)); | |
| 423 | const held = refused((await settle()).spend); | |
| 424 | if (held.state !== "paused") throw new Error("expected a hold"); | |
| 425 | expect(held.keepAttempt).toBe(true); | |
| 426 | expect(held.sessionId).toBe("prev"); | |
| 427 | expect(held.summary).toContain("catching its breath"); | |
| 428 | const person = await settle({ run: { sent: true } }); | |
| 429 | expect(person.spend.ok).toBe(true); | |
| 430 | }); | |
| 431 | }); | |
| 432 | ||
| 433 | describe("on a forge that is somebody's own", () => { | |
| 434 | test("lent credit that is spent refuses the run in the forge's words, whatever it asked for", async () => { | |
| 435 | await writeFile(join(dir, "own", "parent.json"), JSON.stringify({ credit: { token: "bearer-token-1", capUsd: 2, spentUsd: 2 } }), { mode: 0o600 }); | |
| 436 | try { | |
| 437 | const out = refused((await settle({ app: own, repo: ownRepo })).spend); | |
| 438 | expect(out.state).toBe("failed"); | |
| 439 | expect(out.summary).toBe(CREDIT_SPENT_SAID); | |
| 440 | } finally { | |
| 441 | await writeFile(join(dir, "own", "parent.json"), JSON.stringify({ credit: { token: "bearer-token-1", capUsd: 2, spentUsd: 0 } }), { mode: 0o600 }); | |
| 442 | } | |
| 443 | }); | |
| 444 | ||
| 445 | test("lent credit with less left than a run asks for is the most the run is budgeted", async () => { | |
| 446 | await writeFile(join(dir, "own", "parent.json"), JSON.stringify({ credit: { token: "bearer-token-1", capUsd: 2, spentUsd: 1.5 } }), { mode: 0o600 }); | |
| 447 | try { | |
| 448 | const { spend } = await settle({ app: own, repo: ownRepo }); | |
| 449 | expect(spend.ok && spend.budget).toBeCloseTo(0.5); | |
| 450 | } finally { | |
| 451 | await writeFile(join(dir, "own", "parent.json"), JSON.stringify({ credit: { token: "bearer-token-1", capUsd: 2, spentUsd: 0 } }), { mode: 0o600 }); | |
| 452 | } | |
| 453 | }); | |
| 454 | ||
| 455 | test("the owner's limits per run, day and month cap the budget, and one reached refuses it", async () => { | |
| 456 | await writeFile(join(dir, "own", "parent.json"), JSON.stringify({ credit: { token: "bearer-token-1", capUsd: 100, spentUsd: 0 } }), { mode: 0o600 }); | |
| 457 | // Without a budget of its own the run asks for the forge's per-run limit. | |
| 458 | expect((await settle({ app: own, repo: ownRepo, budgetUsd: 0 })).spend).toMatchObject({ ok: true, budget: 5 }); | |
| 459 | setBudget(own.db, "run", 1, ownAdmin.id); | |
| 460 | expect((await settle({ app: own, repo: ownRepo, budgetUsd: 0 })).spend).toMatchObject({ ok: true, budget: 1 }); | |
| 461 | setBudget(own.db, "run", 0.01, ownAdmin.id); | |
| 462 | const tiny = refused((await settle({ app: own, repo: ownRepo, budgetUsd: 0 })).spend); | |
| 463 | expect(tiny.state).toBe("failed"); | |
| 464 | setBudget(own.db, "run", 5, ownAdmin.id); | |
| 465 | setBudget(own.db, "day", 1, ownAdmin.id); | |
| 466 | costing(own, ownRepo, 1); | |
| 467 | const day = refused((await settle({ app: own, repo: ownRepo, budgetUsd: 0 })).spend); | |
| 468 | expect(day.state).toBe("failed"); | |
| 469 | expect(day.summary).toBe(stoppedBy(own.db, "day")); | |
| 470 | }); | |
| 471 | }); | |
| 472 | }); | |
| 473 | ||
| 474 | describe("promptFor", () => { | |
| 475 | let dir: string; | |
| 476 | let app: App; | |
| 477 | let owner: User; | |
| 478 | let repo: Repo; | |
| 479 | let agent: Agent; | |
| 480 | ||
| 481 | beforeAll(async () => { | |
| 482 | dir = await mkdtemp(join(tmpdir(), "forge-run-prompt-")); | |
| 483 | app = createApp({ dataDir: dir, port: 0 }); | |
| 484 | const made: any = await createUser(app.db, { | |
| 485 | origin: "seed", trusted: true, username: "trevato", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true, | |
| 486 | }); | |
| 487 | owner = made.value ?? made; | |
| 488 | const r: any = await createRepo(app, owner, { name: "garden", visibility: "public" }); | |
| 489 | repo = r.value ?? r; | |
| 490 | const a = await createAgent(app, owner, { username: "mason" }); | |
| 491 | if (!a.ok) throw new Error("agent"); | |
| 492 | agent = a.value; | |
| 493 | }); | |
| 494 | afterAll(async () => { | |
| 495 | app.close(); | |
| 496 | await rm(dir, { recursive: true, force: true }); | |
| 497 | }); | |
| 498 | ||
| 499 | const promptOf = async (over: { reason?: RunReason; attempt?: number; summary?: string; issue?: Issue } = {}): Promise<string> => { | |
| 500 | const issue = over.issue ?? (() => { | |
| 501 | const made = createIssue(app.db, { repoId: repo.id, authorId: owner.id, title: "Water the beans", body: "Every morning, before nine." }); | |
| 502 | if (!made.ok) throw new Error("issue"); | |
| 503 | return made.value; | |
| 504 | })(); | |
| 505 | return promptFor({ | |
| 506 | app, | |
| 507 | run: { id: "run-prompt", attempt: over.attempt ?? 0, summary: over.summary ?? "", createdAt: new Date().toISOString() } as Run, | |
| 508 | repo, | |
| 509 | issue, | |
| 510 | agent, | |
| 511 | pull: undefined, | |
| 512 | foreign: undefined, | |
| 513 | reason: over.reason ?? "assigned", | |
| 514 | brief: { agent, repo, issue, branch: "mason/1-water", forgeUrl: "https://forge.test", isApp: false, resuming: false, role: "builder" }, | |
| 515 | branch: "mason/1-water", | |
| 516 | bare: join(dir, "none.git"), | |
| 517 | forkBare: join(dir, "none-fork.git"), | |
| 518 | record: undefined, | |
| 519 | sealedHead: undefined, | |
| 520 | since: feedbackSince(app.db, repo, issue, agent), | |
| 521 | signal: new AbortController().signal, | |
| 522 | }); | |
| 523 | }; | |
| 524 | ||
| 525 | test("an issue's title, body and discussion reach the agent", async () => { | |
| 526 | const issue = createIssue(app.db, { repoId: repo.id, authorId: owner.id, title: "Mulch the beds", body: "Use the bark pile." }); | |
| 527 | if (!issue.ok) throw new Error("issue"); | |
| 528 | addComment(app.db, { issueId: issue.value.id, authorId: owner.id, body: "Only the east ones, please." }); | |
| 529 | const prompt = await promptOf({ issue: issue.value }); | |
| 530 | expect(prompt).toContain("Mulch the beds"); | |
| 531 | expect(prompt).toContain("Use the bark pile."); | |
| 532 | expect(prompt).toContain("Discussion so far:"); | |
| 533 | expect(prompt).toContain("Only the east ones, please."); | |
| 534 | }); | |
| 535 | ||
| 536 | test("a conflict run is told which files clash, read off its summary", async () => { | |
| 537 | const prompt = await promptOf({ reason: "conflict", summary: "main moved: a.ts, b/c.ts" }); | |
| 538 | expect(prompt).toContain("no longer merges cleanly: a.ts, b/c.ts"); | |
| 539 | }); | |
| 540 | ||
| 541 | test("a run that paused is told to carry on in the clone it left; one that did not, is not", async () => { | |
| 542 | expect(await promptOf({ attempt: 1 })).toStartWith("Your last turn was cut short"); | |
| 543 | expect(await promptOf({ attempt: 0 })).not.toContain("Your last turn was cut short"); | |
| 544 | }); | |
| 545 | }); | |
| 546 | ||
| 547 | describe("wrapUp", () => { | |
| 548 | const stateOf = (result: AgentOutcome, calls: string[] = []) => { | |
| 549 | const ran = { inWrapUp: false }; | |
| 550 | return { | |
| 551 | ran, | |
| 552 | state: { | |
| 553 | app: createApp({ dataDir: join(tmpdir(), `forge-run-wrap-${Date.now()}-${Math.random()}`), port: 0 }), | |
| 554 | run: { id: "none" } as Run, | |
| 555 | result, | |
| 556 | retry: retryState({ calls }), | |
| 557 | reserve: 0.5, | |
| 558 | deadline: Date.now() + 60_000, | |
| 559 | signal: new AbortController().signal, | |
| 560 | ran, | |
| 561 | watch: new Stopwatch(), | |
| 562 | write: () => {}, | |
| 563 | }, | |
| 564 | }; | |
| 565 | }; | |
| 566 | ||
| 567 | test("a run that did not run out of budget has no wrap-up and keeps its answer", async () => { | |
| 568 | const calls: string[] = []; | |
| 569 | const first = outcome(); | |
| 570 | const { state } = stateOf(first, calls); | |
| 571 | expect(await wrapUp(state)).toEqual({ ok: true, result: first, stoppedAt: undefined }); | |
| 572 | expect(calls).toEqual([]); | |
| 573 | }); | |
| 574 | ||
| 575 | test("a run out of budget gets one more turn in its session, and its ending carries the whole spend", async () => { | |
| 576 | const calls: string[] = []; | |
| 577 | const { state, ran } = stateOf(outcome({ reason: BUDGET_REACHED, costUsd: 2, turns: 4 }), calls); | |
| 578 | const got = await wrapUp(state); | |
| 579 | if (!got.ok) throw new Error("expected a wrap-up"); | |
| 580 | expect(calls).toEqual([`${wrapUpPrompt()}|s1`]); | |
| 581 | expect(got.stoppedAt).toBe(2); | |
| 582 | expect(got.result.costUsd).toBeCloseTo(2.5); | |
| 583 | expect(got.result.turns).toBe(7); | |
| 584 | expect(ran.inWrapUp).toBe(false); | |
| 585 | }); | |
| 586 | }); |
new above
offline