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

A crew run can spend a granted OpenAI-type account, on the OpenAI runner, per run #17787

opened this

Merged 6h 10m ago, live in production

feat/crew-openai-account → main 0 commits

  • Merged. feat/crew-openai-account was merged into main as b43bdad.

Review

Sign in to review this change.
23 files changed +1022 −129
docs/features/openai-runner.md +31 −1
@@ -11,7 +11,7 @@ The default is unchanged: without the switch below every run uses Claude Code.
1111 Switch it on, in the forge's environment (only there: a run's env, where granted secrets land, is never
1212 read for these, and a secret cannot be named `OPENAI_*`):
1313
14 - `FORGE_AGENT_RUNNER=openai` chooses the runner (any other value keeps Claude).
14 - `FORGE_AGENT_RUNNER=openai` chooses the runner for every run, except one on a granted OpenAI-compatible account, which always uses it (any other value keeps Claude).
1515 - `OPENAI_BASE_URL` is the endpoint's base, `http://` or `https://`, for example `https://api.openai.com/v1`.
1616 - `OPENAI_MODEL` names the model, unless the run names one.
1717 - `OPENAI_API_KEY` is sent as a bearer token; leave it unset for an endpoint that needs none.
@@ -72,6 +72,36 @@ a crew run), never to `OPENAI_BASE_URL` with the operator's key. An account with
7272 Anthropic token) cannot drive this runner, so the run ends as an error saying so rather than spending the
7373 operator's key on it.
7474
75 **A granted OpenAI-compatible account runs the crew, run by run.** An account of the chat completions
76 kind (Settings → Connect your AI) that is granted to a repository, an owner or one agent takes crew runs
77 there on this runner, at its own base with its own key, whatever `FORGE_AGENT_RUNNER` says; a run on an
78 Anthropic account is unchanged.
79
80 - It is used only where it is granted, never from the pool, and the grant a person's own connection gets
81 when it is saved for Talk does not count. A grant of a forge connection to a person also lets them pick it
82 in Talk.
83 - Order: the Claude plans, then the granted account, then pay-per-token keys. The forge's own token is the
84 plan where no Anthropic account may be used and it has something to spend. One an admin ranks before every
85 Claude account goes first.
86 - With nobody to take a run it waits for the soonest of its accounts: a plan's reset or a connection's wake.
87 - While the plans' week holds the crew, a run already queued or assigned to an agent with such a grant still
88 starts, and picks no plan. The crew's own new picks, in an autonomous repository, may still wait for the week: a repository with connections alone is held to the
89 week of the forge's own token, as one with no account is.
90 - The model is the account's chosen one, else the first its test listed, passing over SubQ's `subq-snap-*`
91 decision models; an account with none is passed over, and the
92 run's log says so and names `/settings/model`. The agent's Claude model is not used.
93 - The key is in no environment: the runner alone holds it, and the agent's shell never sees it.
94 - A run never carries a session to or from such an account. It starts fresh on the same clone with the
95 whole brief, and a retry or the wrap-up is told the task again.
96 - A 429 or a 5xx is asked again after 2, 5, 15, 30 and 60 seconds. A 429 then pauses the run as any per-minute limit does. A 5xx
97 then rests the account 15 minutes, and a refused key or payment (401, 402, 403) rests it at once for a day,
98 or until someone wakes it or tests it and it works; another account takes the run. An endpoint that
99 cannot be reached at all is an outage: the run waits for it and the account does not rest, as with Claude's.
100 - SubQ's `subq-*` models take `low`, `high` or `max`: `none` and `minimal` are sent as `low`, `medium` as
101 `high`.
102
103 Pinned by `test/crew-openai-account.test.ts`.
104
75105 **Cost and the cap.** An endpoint reports tokens, not dollars, so the forge prices them from the table
76106 in `src/crew/openai_price.ts`: `cost = tokens in × in/1e6 + tokens out × out/1e6`, at the providers' list
77107 prices in USD per million tokens. It errs high: cached input is charged as fresh, a model pays the
src/actions/crew_accounts.ts +12 −3
@@ -14,16 +14,19 @@ import {
1414 budgetSpent,
1515 getSubscriptionByName,
1616 listSubscriptions,
17 crewNext,
1718 rankAfter,
1819 reachWords,
1920 scopeAccounts,
2021 setLimited,
22 PLATFORM,
2123 type ScopeAccount,
2224 } from "../core/subscriptions.ts";
2325 import { getUserById, getUserByName, type User } from "../core/users.ts";
2426 import { weekUse } from "../core/capacity.ts";
2527 import { orgAccess, accessAllows } from "../core/orgs.ts";
2628 import { err, ok, type Result } from "../kernel/result.ts";
29 import { crewPick } from "../crew/key_fallback.ts";
2730 import { whenText } from "../crew/limits.ts";
2831 import { recheckHeld } from "../crew/recheck_held.ts";
2932
@@ -248,7 +251,10 @@ export function crewAccountWords(
248251 spend,
249252 });
250253 }
251 const withRoom = usable.filter((a) => noRoom(app, a, now) === undefined);
254 // In the pick's own order (`crewOrder`); one it would pass over now comes last.
255 const order = crewNext(app.db, scope, now, crewPick(app));
256 const place = (a: ScopeAccount): number => (order.includes(a.id) ? order.indexOf(a.id) : order.length);
257 const withRoom = usable.filter((a) => noRoom(app, a, now) === undefined).sort((a, b) => place(a) - place(b));
252258 const room = withRoom[0];
253259 // The next in order with room: the fallback when the first runs out, and what it has spent.
254260 const next = withRoom[1];
@@ -278,8 +284,11 @@ export function crewAccountWords(
278284 room === undefined && spare !== undefined
279285 ? ` ${spare.name} has room but is not used here: allow it here.`
280286 : "";
281 const says =
282 room !== undefined
287 // Connections alone: the server's own token is in their order too (`withOwnToken`).
288 const own = order[0] === PLATFORM;
289 const says = own
290 ? `The next run for ${scope.name} spends the server's own token.${room === undefined ? "" : ` ${named(room.createdBy, room.name)} is the fallback.`}`
291 : room !== undefined
283292 ? `The next run for ${scope.name} spends ${named(room.createdBy, room.name)}: it has room this week.${fallback}`
284293 : usable.length === 0
285294 ? ownerAdmin(app, scope.ownerId)
src/core/connections.ts +3 −1
@@ -365,7 +365,9 @@ export function recordTest(
365365 },
366366 ): void {
367367 db.query(
368 "UPDATE subscription SET tested_at = ?2, test_ok = ?3, test_said = ?4, models = COALESCE(?5, models) WHERE id = ?1",
368 // A connection that works again is used again, not when its rest for a refused key ends.
369 `UPDATE subscription SET tested_at = ?2, test_ok = ?3, test_said = ?4, models = COALESCE(?5, models),
370 resting_until = CASE WHEN ?3 = 1 AND protocol = 'openai' THEN NULL ELSE resting_until END WHERE id = ?1`,
369371 ).run(
370372 connectionId,
371373 new Date().toISOString(),
src/core/subscriptions.ts +198 −42
@@ -297,7 +297,9 @@ export function gatewayUsable(apiBase: string | null): boolean {
297297 export function credentialEnvOf(
298298 picked: Extract<Pick, { kind: "ready" }>,
299299 ): Record<string, string> {
300 return accountEnv(picked);
300 // An OpenAI-compatible account's key goes to its runner as the run's account, never under a name
301 // Claude Code would send to its base.
302 return picked.connection === undefined ? accountEnv(picked) : {};
301303 }
302304
303305 /**
@@ -644,7 +646,10 @@ export function rankAfter(db: Database, subscriptionId: string, afterId: string)
644646 // ---- the pick ----
645647
646648 export type Pick =
647 /** No account may be used here and the scope's owner is a forge admin: the server's own token. */
649 /**
650 * The server's own token, for a forge admin's scope: no account may be used here, or connections
651 * alone may and the token comes first.
652 */
648653 | { readonly kind: "env" }
649654 /** No account may be used here and the scope's owner is not a forge admin: nothing to spend. */
650655 | { readonly kind: "none" }
@@ -657,6 +662,11 @@ export type Pick =
657662 readonly apiBase: string | null;
658663 /** On a budgeted account: the most this run may spend, reserved for it. */
659664 readonly capUsd?: number;
665 /**
666 * Set when the account speaks the chat completions API: the run then goes to the
667 * OpenAI-compatible runner at `apiBase`, and its key is never in the run's environment.
668 */
669 readonly connection?: PickedConnection;
660670 }
661671 /** Every account that may be used here is resting or spent; the earliest to wake. */
662672 | {
@@ -664,8 +674,20 @@ export type Pick =
664674 readonly until: string;
665675 readonly said: string;
666676 readonly names: readonly string[];
677 /** A granted connection is among them: the wait is no try of the run's. */
678 readonly connection?: boolean;
667679 };
668680
681 /** What a crew run on an OpenAI-compatible account needs beside its key and base. */
682 export interface PickedConnection {
683 /** The model chosen for the account, else the first listed that can do crew work; "" when it has none. */
684 readonly model: string;
685 /** The reasoning effort the account asks for; "" asks none. */
686 readonly effort: string;
687 /** Reached only through the outbound guard: every account but one an admin may put on a private address. */
688 readonly guarded: boolean;
689 }
690
669691 export interface PickScope {
670692 readonly repoId: string;
671693 readonly ownerId: string;
@@ -680,8 +702,37 @@ type CandidateRow = Row & {
680702 budget_usd: number | null;
681703 spent_usd: number;
682704 reach: Reach;
705 rank: number;
706 protocol: string;
707 models: string;
708 chosen: string;
709 effort: string;
710 private_ok: number;
683711 };
684712
713 const COLUMNS = "s.id, s.name, s.kind, s.token_enc, s.api_base, s.resting_until, s.resting_said, s.last_used_at, s.created_by, s.created_at, s.budget_usd, s.rank, s.protocol, s.models, s.chosen, s.effort, s.private_ok";
714
715 const speaksOpenAI = (r: { protocol: string }): boolean => r.protocol === "openai";
716
717 /** SubQ's snap models answer a decision and do no crew work: one runs only where it was chosen by name. */
718 const DECIDES_ONLY = /^(?:.*\/)?subq-snap\b/i;
719
720 /** The first model of an account's stored choice, else the first its last test listed that can do crew work; "" for none. */
721 function modelOfRow(r: { models: string; chosen: string }): string {
722 const list = (text: string): unknown[] => {
723 try {
724 const v: unknown = JSON.parse(text);
725 return Array.isArray(v) ? v : [];
726 } catch {
727 return [];
728 }
729 };
730 const chosen = list(r.chosen)[0];
731 if (typeof chosen === "string" && chosen !== "") return chosen;
732 const listed = list(r.models).map((m) => (m as { id?: unknown } | null)?.id);
733 return listed.find((m): m is string => typeof m === "string" && m !== "" && !DECIDES_ONLY.test(m)) ?? "";
734 }
735
685736 /**
686737 * The accounts a run at `scope` may use, in the order they are tried: an admin's order first
687738 * (`rank`, lower first: "use espo-api-key only after espo-corp"); then those allowed here (a
@@ -691,22 +742,41 @@ type CandidateRow = Row & {
691742 * allowed. The pool is a forge admin's accounts for a forge admin's scopes, and anyone's own
692743 * accounts for their own: a person's run never spends an account that is not theirs or allowed to
693744 * them. Within each, the account used longest ago first.
745 *
746 * `crew` also takes an OpenAI-compatible account, where someone chose it: by a grant, never from
747 * the pool, so a model saved for Talk moves no crew work. The grant `saveConnection` writes by
748 * itself, a person's own connection to their own repositories, is no such choice; one at a
749 * repository or for one agent is. Everything else here (Talk's default, one-shots, deepsec)
750 * speaks Anthropic's protocol and never sees one.
694751 */
695 function candidates(db: Database, scope: PickScope, runId: string): CandidateRow[] {
752 function candidates(db: Database, scope: PickScope, runId: string, crew: boolean): CandidateRow[] {
753 return reachable(db, scope, runId, crew).filter((r) => !speaksOpenAI(r) || modelOfRow(r) !== "");
754 }
755
756 /**
757 * The connections a crew run at `scope` passes over because they have no model it can use: named in
758 * the run's log, so nobody has to guess why one was not taken.
759 */
760 export const passedOver = (db: Database, scope: PickScope): string[] =>
761 reachable(db, scope, "", true)
762 .filter((r) => speaksOpenAI(r) && modelOfRow(r) === "")
763 .map((r) => r.name);
764
765 /** `candidates`, with the connections that have no model a crew run can use. */
766 function reachable(db: Database, scope: PickScope, runId: string, crew: boolean): CandidateRow[] {
696767 const rows = db
697 .query<CandidateRow & { tier: number }, [string, string, string, string]>(
768 .query<CandidateRow & { tier: number }, [string, string, string, string, number]>(
698769 `SELECT * FROM (
699 SELECT s.id, s.name, s.kind, s.token_enc, s.api_base, s.resting_until, s.resting_said,
700 s.last_used_at, s.created_by, s.created_at, s.budget_usd, ${COMMITTED} AS spent_usd, s.rank,
770 SELECT ${COLUMNS}, ${COMMITTED} AS spent_usd,
701771 CASE WHEN g.scope_id = ?1 THEN 'repo' ELSE 'owner' END AS reach,
702772 (CASE WHEN g.scope_id = ?1 THEN 0 ELSE 2 END) + (CASE WHEN g.agent_id = ?3 THEN 0 ELSE 1 END) AS tier
703773 FROM subscription_grant g JOIN subscription s ON s.id = g.subscription_id
704774 WHERE g.scope_id IN (?1, ?2) AND g.agent_id IN (?3, '') AND s.id <> 'platform'
705 -- A crew run speaks Anthropic's protocol; another connection is Talk's (core/connections.ts).
706 AND s.protocol = 'anthropic'
775 AND (s.protocol = 'anthropic'
776 OR (?5 = 1 AND s.protocol = 'openai'
777 AND NOT (s.scope <> 'forge' AND g.agent_id = '' AND g.scope_id = s.created_by)))
707778 UNION ALL
708 SELECT s.id, s.name, s.kind, s.token_enc, s.api_base, s.resting_until, s.resting_said,
709 s.last_used_at, s.created_by, s.created_at, s.budget_usd, ${COMMITTED} AS spent_usd, s.rank,
779 SELECT ${COLUMNS}, ${COMMITTED} AS spent_usd,
710780 'pool' AS reach, 4 AS tier
711781 FROM subscription s
712782 WHERE s.id <> 'platform' AND s.protocol = 'anthropic'
@@ -718,12 +788,45 @@ function candidates(db: Database, scope: PickScope, runId: string): CandidateRow
718788 )
719789 ORDER BY rank, tier, kind = 'api_key', last_used_at IS NOT NULL, last_used_at, name COLLATE NOCASE`,
720790 )
721 .all(scope.repoId, scope.ownerId, scope.agentId, runId)
722 .filter((r) => gatewayUsable(r.api_base));
791 .all(scope.repoId, scope.ownerId, scope.agentId, runId, crew ? 1 : 0)
792 // A connection's base was judged when it was saved (`parseConnectionBase`).
793 .filter((r) => (speaksOpenAI(r) ? (r.api_base ?? "") !== "" : gatewayUsable(r.api_base)));
723794 const seen = new Set<string>();
724795 return rows.filter((r) => !seen.has(r.id) && seen.add(r.id) !== undefined);
725796 }
726797
798 /** Whether a run at a scope may use a connection at all, resting or not. */
799 export const connectionHere = (db: Database, scope: PickScope): boolean => candidates(db, scope, "", true).some(speaksOpenAI);
800
801 /**
802 * Whether a run of `agentId` (of any agent when absent) at a scope has a granted OpenAI-compatible
803 * account with room now: what lets it start while the plans' week holds everyone else.
804 */
805 export const connectionRoom = (db: Database, scope: RoomScope, now: Date = new Date()): boolean => roomFor(db, scope, now, speaksOpenAI);
806
807 /** The same for a pay-per-token key with a cap: what the metered fallback may spend on this run. */
808 export const cappedKeyRoom = (db: Database, scope: RoomScope, now: Date = new Date()): boolean => roomFor(db, scope, now, (r) => r.kind === "api_key" && !speaksOpenAI(r) && r.budget_usd !== null);
809
810 type RoomScope = { readonly repoId: string; readonly ownerId: string; readonly agentId?: string | undefined };
811
812 function roomFor(db: Database, scope: RoomScope, now: Date, which: (r: CandidateRow) => boolean): boolean {
813 const agents =
814 scope.agentId !== undefined
815 ? [scope.agentId]
816 : db.query<{ agent_id: string }, [string, string]>("SELECT DISTINCT agent_id FROM subscription_grant WHERE scope_id IN (?1, ?2)").all(scope.repoId, scope.ownerId).map((r) => r.agent_id);
817 return agents.some((agentId) => candidates(db, { repoId: scope.repoId, ownerId: scope.ownerId, agentId }, "", true).some((r) => which(r) && awakeAt(r, now)));
818 }
819
820 /**
821 * Where the granted OpenAI-compatible accounts go in a crew run's order: after the plans and before
822 * the pay-per-token keys, or ahead of every Anthropic account while an admin ranks them so.
823 */
824 function withConnections(claude: readonly CandidateRow[], connections: readonly CandidateRow[], firstRank: number): CandidateRow[] {
825 const ahead = connections.filter((r) => r.rank < firstRank);
826 const next = connections.filter((r) => r.rank >= firstRank);
827 return [...ahead, ...claude.filter((r) => r.kind !== "api_key"), ...next, ...claude.filter((r) => r.kind === "api_key")];
828 }
829
727830 /**
728831 * A plan's window the crew may not draw on now: measured and not yet reset, with no more free than
729832 * the share its admin keeps for people (`headroom_pct`). A key has no windows.
@@ -746,6 +849,13 @@ export function crewWindowFull(db: Database, subscriptionId: string, now: Date):
746849 */
747850 export interface CrewPick {
748851 readonly fallback: boolean;
852 /** The forge's own token has something to spend (`ownTokenLeft`). */
853 readonly ownToken?: boolean;
854 /**
855 * The run started past the week's hold (`letPastWeek`): the plans, and the forge's own token,
856 * are what that hold spares, so it picks none of them.
857 */
858 readonly pastWeek?: boolean;
749859 }
750860
751861 /** Less than `MIN_RUN_USD` left on its whole-life budget. */
@@ -753,9 +863,58 @@ export const budgetSpent = (r: { budget_usd: number | null; spent_usd: number })
753863 r.budget_usd !== null && r.budget_usd - r.spent_usd < MIN_RUN_USD;
754864
755865 /**
756 * The account a run works on: the first of `candidates` that is awake and has budget. When every
757 * one is resting or spent the run waits for the soonest to wake. The server's own token is used
758 * only when no account may be used here at all, and only for a forge admin's scope.
866 * `found`, with the forge's own token as one more plan where every account that may be used is a
867 * connection: only for a forge admin's scope, and only while it has something to spend.
868 */
869 function withOwnToken(db: Database, scope: { readonly ownerId: string }, found: CandidateRow[], crew: CrewPick | undefined): CandidateRow[] {
870 if (crew?.ownToken !== true || found.length === 0 || !found.every(speaksOpenAI) || !ownerIsAdmin(db, scope.ownerId)) return found;
871 const own = db.query<CandidateRow, []>(`SELECT ${COLUMNS}, 0 AS spent_usd, 'pool' AS reach FROM subscription s WHERE s.id = 'platform'`).get();
872 return own === null ? found : [{ ...own, kind: "oauth", protocol: "anthropic", budget_usd: null }, ...found];
873 }
874
875 /** The accounts of `all` a run may take, in order, and the plans passed over with a full window. */
876 function crewOrder(db: Database, all: readonly CandidateRow[], now: Date, crew: CrewPick | undefined): { rows: readonly CandidateRow[]; full: ReadonlyMap<string, { window: LimitWindow; resetsAt: string }> } {
877 // A crew run passes over a full plan, and takes a key only as the capped, switched-on fallback.
878 const full = new Map<string, { window: LimitWindow; resetsAt: string }>();
879 // Where there is no plan, a key is simply what the crew runs on, as it always was.
880 const plans = all.some((r) => r.kind === "oauth");
881 const connections = all.filter(speaksOpenAI);
882 const claude = all.filter((r) => !speaksOpenAI(r));
883 const kept =
884 crew === undefined || !plans
885 ? claude
886 : claude.filter((r) => {
887 if (r.kind !== "api_key" && crew.pastWeek === true) return false;
888 if (r.kind === "api_key") return crew.fallback;
889 const f = crewWindowFull(db, r.id, now);
890 if (f !== undefined) full.set(r.name, f);
891 return f === undefined;
892 });
893 // A key with a cap is the fallback before one without: its spend has an end the owner chose.
894 const ordered = crew === undefined || !plans ? kept : [...kept.filter((r) => r.kind !== "api_key"), ...kept.filter((r) => r.kind === "api_key" && r.budget_usd !== null), ...kept.filter((r) => r.kind === "api_key" && r.budget_usd === null)];
895 // The grant is the choice: the metered fallback's switch does not hold a connection back.
896 const rows = connections.length === 0 ? ordered : withConnections(ordered, connections, Math.min(...claude.map((r) => r.rank)));
897 return { rows, full };
898 }
899
900 const awakeAt = (r: CandidateRow, now: Date): boolean => !budgetSpent(r) && (r.resting_until === null || r.resting_until <= now.toISOString());
901
902 /** The accounts a crew run at a scope would take now, the next one first; `PLATFORM` is the forge's own token. */
903 export function crewNext(db: Database, scope: { readonly repoId: string; readonly ownerId: string }, now: Date, crew: CrewPick): string[] {
904 const all = withOwnToken(db, scope, candidates(db, { repoId: scope.repoId, ownerId: scope.ownerId, agentId: "" }, "", true), crew);
905 return crewOrder(db, all, now, crew).rows.filter((r) => awakeAt(r, now)).map((r) => r.id);
906 }
907
908 /**
909 * The account a run works on: the first in order that is awake and has budget. When every one is
910 * resting or spent the run waits for the soonest to wake. With no account at all it is the server's
911 * own token, for a forge admin's scope only.
912 *
913 * A crew run's order: the plans go first (the forge's own token is the plan where no Anthropic
914 * account may be used and it has something to spend), then the granted connections, then the keys.
915 * A connection an admin ranks ahead of every Anthropic account goes before them all. An account is
916 * passed over while it is resting, spent or full; every plan is passed over only by a run let past
917 * the week's hold. Where there are plans, keys are taken only while the fallback's switch is on.
759918 */
760919 export function pickSubscription(
761920 db: Database,
@@ -765,23 +924,13 @@ export function pickSubscription(
765924 reserve?: { readonly runId: string; readonly usd: number },
766925 crew?: CrewPick,
767926 ): Pick {
768 const all = candidates(db, scope, reserve?.runId ?? "");
769 if (all.length === 0) return ownerIsAdmin(db, scope.ownerId) ? { kind: "env" } : { kind: "none" };
770 // A crew run passes over a full plan, and takes a key only as the capped, switched-on fallback.
771 const full = new Map<string, { window: LimitWindow; resetsAt: string }>();
772 // Where there is no plan, a key is simply what the crew runs on, as it always was.
773 const plans = all.some((r) => r.kind === "oauth");
774 const kept =
775 crew === undefined || !plans
776 ? all
777 : all.filter((r) => {
778 if (r.kind === "api_key") return crew.fallback;
779 const f = crewWindowFull(db, r.id, now);
780 if (f !== undefined) full.set(r.name, f);
781 return f === undefined;
782 });
783 // A key with a cap is the fallback before one without: its spend has an end the owner chose.
784 const rows = crew === undefined || !plans ? kept : [...kept.filter((r) => r.kind !== "api_key"), ...kept.filter((r) => r.kind === "api_key" && r.budget_usd !== null), ...kept.filter((r) => r.kind === "api_key" && r.budget_usd === null)];
927 const all = withOwnToken(db, scope, candidates(db, scope, reserve?.runId ?? "", crew !== undefined), crew);
928 if (all.length === 0) {
929 // Let past the week for an account that has since gone: it spends nothing the hold is for.
930 if (crew?.pastWeek === true) return { kind: "resting", until: new Date(now.getTime() + BUDGET_RECHECK_MS).toISOString(), said: "the week holds the crew and no other account may be used here", names: ["the crew's accounts"] };
931 return ownerIsAdmin(db, scope.ownerId) ? { kind: "env" } : { kind: "none" };
932 }
933 const { rows, full } = crewOrder(db, all, now, crew);
785934 if (rows.length === 0) {
786935 // Every plan is full and no fallback may take the run: it waits for the first window to reset.
787936 const soonest = [...full].sort((a, b) => a[1].resetsAt.localeCompare(b[1].resetsAt))[0];
@@ -799,14 +948,18 @@ export function pickSubscription(
799948 // Spent counts what other runs on it may still spend (their reservation)
800949 // as well as what every run has spent, so runs started together cannot
801950 // each pass a budget that only one of them fits in.
802 const awake = rows.find(
803 (r) => !budgetSpent(r) && (r.resting_until === null || r.resting_until <= now.toISOString()),
804 );
951 const awake = rows.find((r) => awakeAt(r, now));
952 // A full plan is waited for too, beside a connection that rests or is spent: the soonest of them.
953 const reset = [...full.values()].map((f) => f.resetsAt).sort()[0];
954 const soonestOf = (until: string): string => (reset !== undefined && reset < until ? reset : until);
955 const waits = rows.some(speaksOpenAI) ? { connection: true } : {};
956 if (awake?.id === PLATFORM) return { kind: "env" };
805957 if (awake === undefined && rows.every(budgetSpent)) {
806958 const first = rows[0]!;
807959 return {
808960 kind: "resting",
809 until: new Date(now.getTime() + BUDGET_RECHECK_MS).toISOString(),
961 until: soonestOf(new Date(now.getTime() + BUDGET_RECHECK_MS).toISOString()),
962 ...waits,
810963 said: storedText(`its $${first.budget_usd} budget is spent.`, "an admin of this forge", "raise it"),
811964 names: rows.map((r) => r.name),
812965 };
@@ -819,12 +972,14 @@ export function pickSubscription(
819972 .at(0)!;
820973 return {
821974 kind: "resting",
822 until: soonest,
975 until: soonestOf(soonest),
976 ...waits,
823977 said: rows.find((r) => r.resting_until === soonest)!.resting_said,
824978 names: rows.map((r) => r.name),
825979 };
826980 }
827 const opened = open(dataDir, awake.token_enc, aad(awake.id));
981 // A local server that takes no key keeps none: nothing is sealed.
982 const opened = speaksOpenAI(awake) && awake.token_enc === "" ? ok("") : open(dataDir, awake.token_enc, aad(awake.id));
828983 // A token that will not open (a data directory restored under another
829984 // key) is a resting account with the reason on it, not a run that fails.
830985 if (!opened.ok) {
@@ -863,6 +1018,7 @@ export function pickSubscription(
8631018 token: opened.value,
8641019 apiBase: subscription.apiBase,
8651020 ...(capUsd === undefined ? {} : { capUsd }),
1021 ...(speaksOpenAI(awake) ? { connection: { model: modelOfRow(awake), effort: awake.effort, guarded: awake.private_ok !== 1 } } : {}),
8661022 };
8671023 }
8681024
@@ -885,7 +1041,7 @@ export interface ScopeAccount {
8851041 * pick tries them. Empty when none may: the server's own token, for a forge admin's scope.
8861042 */
8871043 export function scopeAccounts(db: Database, repoId: string, ownerId: string): ScopeAccount[] {
888 return candidates(db, { repoId, ownerId, agentId: "" }, "").map((r) => ({
1044 return candidates(db, { repoId, ownerId, agentId: "" }, "", true).map((r) => ({
8891045 id: r.id,
8901046 name: r.name,
8911047 reach: r.reach,
@@ -897,15 +1053,15 @@ export function scopeAccounts(db: Database, repoId: string, ownerId: string): Sc
8971053 }
8981054
8991055 /**
900 * The accounts the crew on a repository works on, for pacing: every one a pick may try there.
901 * Empty when none may (the server's own token).
1056 * The Anthropic accounts the crew on a repository works on, for pacing: every one a pick may try
1057 * there. Empty when none may (the server's own token); a connection has no window to pace by.
9021058 */
9031059 export function grantedAccounts(
9041060 db: Database,
9051061 repoId: string,
9061062 ownerId: string,
9071063 ): { id: string; name: string }[] {
908 return scopeAccounts(db, repoId, ownerId).map((a) => ({ id: a.id, name: a.name }));
1064 return candidates(db, { repoId, ownerId, agentId: "" }, "", false).map((r) => ({ id: r.id, name: r.name }));
9091065 }
9101066
9111067 /**
src/crew/agent_runner.ts +12 −2
@@ -159,6 +159,8 @@ export interface Spent {
159159 export interface RunnerLimit {
160160 readonly limitedUntil?: string | undefined;
161161 readonly window?: LimitWindow | undefined;
162 /** The key or its payment was refused: it stays so until a person sees to it. */
163 readonly refused?: boolean | undefined;
162164 /** One line a person can read about it. */
163165 readonly said?: string | undefined;
164166 }
@@ -275,6 +277,14 @@ export function currentRunner(): AgentRunner {
275277 return chosen ?? (process.env["FORGE_AGENT_RUNNER"] === "openai" ? openaiRunner : claude);
276278 }
277279
280 /**
281 * The runner a run on `account` uses: an OpenAI-compatible account's own, whatever
282 * `FORGE_AGENT_RUNNER` says; any other account, and none, the current one.
283 */
284 export function runnerFor(account: RunAccount | undefined): AgentRunner {
285 return chosen ?? (account?.connection === undefined ? currentRunner() : openaiRunner);
286 }
287
278288 /** Swap the runner (tests drive a fake one through the crew); undefined restores the default. */
279289 export function useRunner(runner: AgentRunner | undefined): void {
280290 chosen = runner;
@@ -295,13 +305,13 @@ export const ownCost = (reported: number, priorUsd: number | undefined): number
295305 };
296306
297307 /**
298 * Runs `input` on the current runner. Behind this seam a cumulative runner's cost is made the
308 * Runs `input` on its account's runner (`runnerFor`). Behind this seam a cumulative runner's cost is made the
299309 * run's own (`ownCost`), in the outcome and in the live `onUsage` reports; a runner that reports
300310 * per-run cost, a fresh session and a run cut before its result (priced from what streamed) pass
301311 * through unchanged.
302312 */
303313 export async function runAgent(input: AgentRun): Promise<AgentOutcome> {
304 const runner = currentRunner();
314 const runner = runnerFor(input.account);
305315 if (runner.cumulativeCost !== true) return runner.run(input);
306316 const prior = input.resume !== undefined && input.resume !== "" ? input.priorUsd : undefined;
307317 const out = await runner.run({
src/crew/autonomy_pace.ts +4 −2
@@ -11,7 +11,7 @@ import { pickOrder } from "../core/next_up.ts";
1111 import { ranksInRepo } from "../core/rank.ts";
1212 import type { Repo } from "../core/repos.ts";
1313 import { standing } from "../core/standing.ts";
14 import { grantedAccounts } from "../core/subscriptions.ts";
14 import { connectionRoom, grantedAccounts } from "../core/subscriptions.ts";
1515 import { meanRunUsd } from "./autonomy_spend.ts";
1616 import { activeRuns, autonomyStatus, slottedRuns } from "./autonomy_status.ts";
1717 import { governorFor } from "./governed.ts";
@@ -46,7 +46,9 @@ export function repoPace(app: App, repo: Repo, now = new Date(), crew = true, pi
4646 const limited = governed < paced.slots ? { ...paced, slots: governed } : paced;
4747 // The week's ceiling is one budget for the whole crew on these accounts (#8989).
4848 const week = crewWeekFor(app, repo, now);
49 return week !== null && week.slots === 0 ? { ...limited, slots: 0, reason: week.sentence } : limited;
49 // An OpenAI-compatible account granted here is outside that week: the pump holds each agent
50 // without a grant of its own (`dispatch.ts`).
51 return week !== null && week.slots === 0 && !connectionRoom(app.db, { repoId: repo.id, ownerId: repo.ownerId }, now) ? { ...limited, slots: 0, reason: week.sentence } : limited;
5052 }
5153
5254 /**
src/crew/brief.ts +8
@@ -57,6 +57,8 @@ export interface BriefInput {
5757 readonly ownApp?: OwnApp | undefined;
5858 /** Whether a session is being continued (the task was already given). */
5959 readonly resuming: boolean;
60 /** No session crosses to this run's runner or from the last one's: it is told what is in the clone. */
61 readonly sessionless?: boolean | undefined;
6062 /** What this agent is for on this repository; a planner writes maps. */
6163 readonly role?: CrewRole | undefined;
6264 /** The machine this role's shell runs in (`crew/machines.ts`). */
@@ -451,6 +453,12 @@ export interface HandedOver {
451453 export function taskPrompt(input: TaskInput): string {
452454 const body = taskBody(input);
453455 if (input.paused !== true) return body;
456 if (input.sessionless === true)
457 return [
458 "An earlier turn on this task was cut short, and you remember none of it. The clone is as it was left, uncommitted changes included: read git status, git diff and git log for what is done, then carry on from there.",
459 "",
460 body,
461 ].join("\n");
454462 return [
455463 "Your last turn was cut short — the provider's usage limit, or the forge restarting — and nothing you did was lost. This is the same session, and the clone is as you left it, uncommitted changes included. Carry on from where you stopped.",
456464 "",
src/crew/dispatch.ts +10 −5
@@ -70,11 +70,12 @@ import { bugsFirst } from "../flow/bugs.ts";
7070 import { forgeFailed } from "../flow/alarm_lane.ts";
7171 import { byDials } from "./team_share.ts";
7272 import { peopleFirst } from "./people_first.ts";
73 import { fallbackActive, reviewsFirst, weekHolds } from "./key_fallback.ts";
73 import { fallbackActive, letPastWeek, reviewsFirst, weekHolds } from "./key_fallback.ts";
7474 import { inFocus } from "./focus.ts";
7575 import { inMaintenance } from "../maintenance/state.ts";
7676 import { gateQueue } from "../flow/valve_gate.ts";
7777 import { ARCHIVED_WHY, canWrite, contributes, getRepoById, type Repo } from "../core/repos.ts";
78 import { connectionRoom } from "../core/subscriptions.ts";
7879 import { mentionedReviewer, requestReview } from "../actions/review_requests.ts";
7980 import {
8081 crewReviews,
@@ -644,7 +645,8 @@ export function queueAgentRun(
644645 reason !== "assigned" &&
645646 !directed &&
646647 repo.autonomy === "autonomous" &&
647 weekSpent(app, repo, new Date())
648 weekSpent(app, repo, new Date()) &&
649 !connectionRoom(app.db, { repoId: repo.id, ownerId: repo.ownerId, agentId: agent.user.id })
648650 ) {
649651 log.info("the week's share is spent; not queued", {
650652 repo: `${repo.ownerName}/${repo.name}`,
@@ -1900,8 +1902,9 @@ export function pump(
19001902 if (!weeks.has(home.id)) weeks.set(home.id, weekFor(app, home, new Date()));
19011903 const week = weeks.get(home.id)!;
19021904 const paced = fresh.sent && week !== null && week.usedPct < 100 ? null : weekHold(week);
1903 // The capped key, when it may, takes what the week's hold would stop (`key_fallback.ts`).
1904 if (weekHolds(app.db, paced)) {
1905 // A granted connection or the capped key, where this run may use one, takes what the week's
1906 // hold would stop (`key_fallback.ts`).
1907 if (weekHolds(app.db, paced, { repoId: home.id, ownerId: home.ownerId, agentId: fresh.actorId ?? "" })) {
19051908 held.set(fresh.id, "pace");
19061909 if (!noted.has(fresh.id)) {
19071910 noted.add(fresh.id);
@@ -1910,6 +1913,8 @@ export function pump(
19101913 }
19111914 continue;
19121915 }
1916 // Started while the week held the crew: its picks spare the plans that hold is for.
1917 letPastWeek(app.db, fresh.id, paced !== null);
19131918 }
19141919 // A bet at its daily cap holds its scopes' queued runs till the UTC day turns (#13979).
19151920 const capped = fresh.issueId === null ? null : betCapHold(app, fresh.repoId, fresh.issueId, capDay);
@@ -1986,7 +1991,7 @@ export function pump(
19861991 error: String(error),
19871992 }),
19881993 )
1989 .finally(() => inFlight.delete(queued.id));
1994 .finally(() => (letPastWeek(app.db, queued.id, false), inFlight.delete(queued.id)));
19901995 inFlight.set(queued.id, running);
19911996 }
19921997 noteHeld(app.db, held);
src/crew/key_fallback.ts +27 −12
@@ -13,17 +13,36 @@ import type { Database } from "bun:sqlite";
1313 import type { App } from "../app.ts";
1414 import { capacityValue, setCapacity } from "../core/capacity.ts";
1515 import type { Run } from "../core/runs.ts";
16 import { budgetRefusal, crewWindowFull, setBudget, type CrewPick } from "../core/subscriptions.ts";
16 import { budgetRefusal, cappedKeyRoom, connectionRoom, crewWindowFull, setBudget, type CrewPick } from "../core/subscriptions.ts";
1717 import type { User } from "../core/users.ts";
1818 import { err, ok, type Result } from "../kernel/result.ts";
19 import { ownTokenLeft } from "../spawn/funding.ts";
1920 import { whenText } from "./limits.ts";
2021
2122 /** Whether the switch lets the crew fall back to a capped key. */
2223 /** Off unless the owner switched it on: an unset forge holds the run rather than spend on a key. */
2324 export const fallbackOn = (db: Database): boolean => capacityValue(db, "crew.fallback") === "on";
2425
25 /** What a crew run's pick weighs: the switch. */
26 export const crewPick = (db: Database): CrewPick => ({ fallback: fallbackOn(db) });
26 /**
27 * Per forge (its database): the runs the pump started past the week's hold. Set as each starts and
28 * read by its picks; a restart queues such a run again, and the pump judges it again.
29 */
30 const past = new WeakMap<Database, Set<string>>();
31
32 /** The pump started this run while the week held the crew (`yes`), or with room in it. */
33 export function letPastWeek(db: Database, runId: string, yes: boolean): void {
34 let runs = past.get(db);
35 if (runs === undefined) past.set(db, (runs = new Set()));
36 if (yes) runs.add(runId);
37 else runs.delete(runId);
38 }
39
40 /** What a crew run's pick weighs: the switch, the forge's own token, and whether the run started past the week's hold. */
41 export const crewPick = (app: App, runId?: string): CrewPick => ({
42 fallback: fallbackOn(app.db),
43 ownToken: ownTokenLeft(app.config.dataDir),
44 ...(runId !== undefined && past.get(app.db)?.has(runId) === true ? { pastWeek: true } : {}),
45 });
2746
2847 /** The forge's plans and capped keys, as the fallback reads them. */
2948 interface Accounts {
@@ -65,18 +84,14 @@ export function fallbackActive(db: Database, now: Date = new Date()): boolean {
6584 return fullPlans(db, now, plans).length === plans.length;
6685 }
6786
68 /** Whether the fallback can take runs the week's hold would stop: on, with a capped key under its cap. */
69 export function fallbackReady(db: Database): boolean {
70 const { key } = accountsOf(db);
71 return key !== undefined && key.capUsd - key.spentUsd >= 0.01 && fallbackOn(db);
72 }
73
7487 /**
7588 * Whether the week's hold (`week_hold.ts`, its sentence `paced`) stops a crew run: the plans are
76 * at the share kept for people, and no fallback may take the run (off, or capped). With the
77 * fallback ready the run goes on, and the pick passes the full plans over for the key.
89 * at the share kept for people, and no other account this run may use can take it: a granted
90 * OpenAI-compatible one, or a capped key under its cap while the fallback is on. With one the run
91 * goes on, and its pick passes the plans over (`letPastWeek`).
7892 */
79 export const weekHolds = (db: Database, paced: string | null): boolean => paced !== null && !fallbackReady(db);
93 export const weekHolds = (db: Database, paced: string | null, scope: { readonly repoId: string; readonly ownerId: string; readonly agentId: string }): boolean =>
94 paced !== null && !connectionRoom(db, scope) && !(fallbackOn(db) && cappedKeyRoom(db, scope));
8095
8196 /** While the key takes the crew's runs, reviews start first: they are cheap and they land work. */
8297 export const reviewsFirst = (runs: readonly Run[]): Run[] => [...runs.filter((r) => r.reason === "review"), ...runs.filter((r) => r.reason !== "review")];
src/crew/limits.ts +3 −4
@@ -29,11 +29,11 @@ export function isRateLimited(outcome: AgentOutcome): outcome is AgentOutcome &
2929
3030 /**
3131 * When to try again: the runner's `limitedUntil` plus a minute. A limit
32 * that names no time waits the default.
32 * that names no time waits the default, a refused key a day (a person can wake it, or test it).
3333 */
3434 export function resumeAt(limit: RunnerLimit | undefined, now: Date): Date {
3535 const at = limit?.limitedUntil === undefined ? NaN : Date.parse(limit.limitedUntil);
36 if (Number.isNaN(at)) return new Date(now.getTime() + DEFAULT_WAIT_MS);
36 if (Number.isNaN(at)) return new Date(now.getTime() + (limit?.refused === true ? 86_400_000 : DEFAULT_WAIT_MS));
3737 return new Date(at + SLACK_MS);
3838 }
3939
@@ -54,8 +54,7 @@ export function limitOf(
5454 * The provider's refusal, taken in: the window it names is noted on the
5555 * account's standing, and a sealed account (`subscriptionId` given) rests
5656 * until the provider's time. The forge's own token (`undefined`) is noted
57 * but never rested — nothing else would take its place. One place for a run
58 * and a conversation turn alike.
57 * but not rested here — where a connection is granted, `limitEnding` rests it. One place for a run and a conversation turn alike.
5958 */
6059 export function takeLimit(
6160 db: Database,
src/crew/openai_price.ts +2
@@ -35,6 +35,8 @@ export const PRICES: Readonly<Record<string, Price>> = {
3535 "gpt-4o-mini": { inPerM: 0.15, outPerM: 0.6 },
3636 "o3": { inPerM: 2, outPerM: 8 },
3737 "o4-mini": { inPerM: 1.1, outPerM: 4.4 },
38 // SubQ's list price; its $0.01 for cached input is charged as fresh, as every row's is.
39 "subq-savant": { inPerM: 0.1, outPerM: 0.5 },
3840 "claude-opus": { inPerM: 15, outPerM: 75 },
3941 "claude-sonnet": { inPerM: 3, outPerM: 15 },
4042 "claude-haiku": { inPerM: 1, outPerM: 5 },
src/crew/openai_runner.ts +46 −4
@@ -38,6 +38,7 @@ import { BUDGET_REACHED, type AgentDetection, type AgentOutcome, type AgentRun,
3838 import { openMcp } from "./openai_mcp.ts";
3939 import { outboundFetch, type OutboundOptions } from "../kernel/outbound.ts";
4040 import { costOf, priceOf } from "./openai_price.ts";
41 import { pause } from "./network.ts";
4142 import { stopGroup, type GroupStop } from "./stop_group.ts";
4243 import { childEnv } from "../apps/process.ts";
4344 import { isModelCredential } from "./runner_env.ts";
@@ -369,6 +370,25 @@ function modelOf(model: string | undefined, get: (k: string) => string): string
369370 /** The reasoning efforts an endpoint may be asked for (`reasoning_effort`); unset, none is sent. */
370371 const EFFORTS = /^(none|minimal|low|medium|high)$/;
371372
373 /**
374 * `effort` as `model`'s server takes it. SubQ's savant takes low, high or max and cannot turn its
375 * thinking off, so the nearest it knows is sent; any other model is sent the word as it is.
376 */
377 export function effortFor(model: string, effort: string): string {
378 if (!/^(?:.*\/)?subq-/i.test(model)) return effort;
379 return effort === "none" || effort === "minimal" ? "low" : effort === "medium" ? "high" : effort;
380 }
381
382 /**
383 * How this runner's session ids begin. It keeps no session, and an id that says so is never handed
384 * to a runner that does, wherever the run record carried it and whatever became of the account.
385 */
386 export const OPENAI_SESSION = "openai-";
387 export const isOpenAISession = (sessionId: string): boolean => sessionId.startsWith(OPENAI_SESSION);
388
389 /** Seconds a crew run waits after each 429 or 5xx before it asks again: an endpoint may say no Retry-After. */
390 export const BUSY_SECONDS: readonly number[] = [2, 5, 15, 30, 60];
391
372392 /** Why a picked account without a gateway does not run here. */
373393 export const NO_GATEWAY = "the picked subscription has no gateway, and this runner reaches a model only through an OpenAI-compatible one; it does not spend the forge's own key on another account's run";
374394
@@ -395,7 +415,7 @@ export function settings(run: AgentRun, config: Record<string, string | undefine
395415 // A connection's base is the OpenAI-compatible one itself; a gateway's is its root.
396416 // A connection's own effort (`core/connections.ts`) is its own, over the operator's.
397417 const own = account.connection?.effort ?? "";
398 return { base: account.connection === undefined ? `${base}/v1` : base, key: account.token, model, ...(own === "" ? effort : { reasoningEffort: own }) };
418 return { base: account.connection === undefined ? `${base}/v1` : base, key: account.token, model, ...(own !== "" ? { reasoningEffort: effortFor(model, own) } : reasoningEffort === "" ? {} : { reasoningEffort: effortFor(model, reasoningEffort) }) };
399419 }
400420 const base = baseUrl(get);
401421 if (base === "" || model === "") return { refused: "OPENAI_BASE_URL (http/https) and a model name are required" };
@@ -442,8 +462,8 @@ export function callAsText(text: string): boolean {
442462 * One run on an OpenAI-compatible endpoint. `guard` is the outbound guard's options for a person's
443463 * own connection (a test hands it a resolver); the forge's own endpoints never read it.
444464 */
445 export async function runOpenAI(run: AgentRun, config: Record<string, string | undefined> = process.env, guard: OutboundOptions = {}): Promise<AgentOutcome> {
446 const sessionId = run.resume ?? crypto.randomUUID();
465 export async function runOpenAI(run: AgentRun, config: Record<string, string | undefined> = process.env, guard: OutboundOptions = {}, busySeconds: readonly number[] = BUSY_SECONDS): Promise<AgentOutcome> {
466 const sessionId = run.mcp !== undefined ? (run.resume ?? crypto.randomUUID()) : run.resume !== undefined && isOpenAISession(run.resume) ? run.resume : `${OPENAI_SESSION}${crypto.randomUUID()}`;
447467 let tokensIn = 0, tokensOut = 0, turns = 0, contextTokens = 0, costUsd = 0, result = "";
448468 const done = (ok: boolean, reason: string): AgentOutcome => ({
449469 ok, sessionId, result, costUsd, turns, tokensIn, tokensOut, contextTokens, contextWindow: 0, reason,
@@ -483,10 +503,32 @@ export async function runOpenAI(run: AgentRun, config: Record<string, string | u
483503 signal,
484504 };
485505 // A person's own connection is reached only through the guard, which follows no redirect.
486 const res = run.account?.connection?.guarded === true ? await outboundFetch(`${cfg.base}/chat/completions`, { ...ask, signal }, guard) : await fetch(`${cfg.base}/chat/completions`, { ...ask, signal });
506 const send = (): Promise<Response> =>
507 run.account?.connection?.guarded === true ? outboundFetch(`${cfg.base}/chat/completions`, { ...ask, signal }, guard) : fetch(`${cfg.base}/chat/completions`, { ...ask, signal });
508 let res = await send();
509 // A crew run keeps no session, so a 429 that ended it would throw its work's thread away: it
510 // waits and asks the same thing again. Talk answers the person at once, as before.
511 for (const seconds of run.mcp === undefined ? busySeconds : []) {
512 if ((res.status !== 429 && res.status < 500) || signal.aborted) break;
513 await res.body?.cancel().catch(() => {});
514 run.log(`the endpoint answered ${res.status}; asking again in ${seconds} s`);
515 await pause(seconds * 1000, signal);
516 signal.throwIfAborted();
517 res = await send();
518 }
487519 if (!res.ok) {
488520 result = `endpoint answered ${res.status}: ${(await readCapped(res.body, 2000)).text.slice(0, 300)}`;
489521 run.log(`! ${result}`);
522 // The seam's own word for a provider's refusal: a crew run pauses on it and is not a failure.
523 if (res.status === 429 && run.mcp === undefined) return { ...done(false, "rate_limited"), limit: { said: `429, too many requests: ${result}`.slice(0, 160) } };
524 // A granted account that refuses its key or its payment, or is down, rests as a Claude account
525 // turned away does, and another takes the run. The words are ours: no body, so nothing in
526 // it reads as a per-minute limit or as a dead network.
527 const refused = res.status >= 500 ? "the account's endpoint is failing" : [401, 402, 403].includes(res.status) ? "the account's endpoint refused its key or its payment" : undefined;
528 if (refused !== undefined && run.account?.connection !== undefined && run.mcp === undefined) {
529 result = `${refused} (HTTP ${res.status})`;
530 return { ...done(false, "error"), limit: { said: result, refused: res.status < 500 } };
531 }
490532 return done(false, res.status === 429 ? "rate_limited" : "error");
491533 }
492534 const sent = tokensAbout(messages, tools);
src/crew/recheck_held.ts +2 −2
@@ -7,7 +7,7 @@
77 */
88
99 import type { Database } from "bun:sqlite";
10 import { scopeAccounts } from "../core/subscriptions.ts";
10 import { crewWindowFull, scopeAccounts } from "../core/subscriptions.ts";
1111 import { releasePaused } from "./meter_watch.ts";
1212 import { forgetWeek } from "./week_read.ts";
1313
@@ -42,7 +42,7 @@ export function recheckHeld(db: Database, which?: HeldScope, now: Date = new Dat
4242 roomy.set(
4343 key,
4444 scopeAccounts(db, run.repo_id, run.owner_id).some(
45 (a) => !a.budgetSpent && (a.restingUntil === null || a.restingUntil <= at),
45 (a) => !a.budgetSpent && (a.restingUntil === null || a.restingUntil <= at) && crewWindowFull(db, a.id, now) === undefined,
4646 ),
4747 );
4848 if (roomy.get(key)) released += releasePaused(db, { runId: run.id }, now);
src/crew/run_limits.ts +37 −19
@@ -6,7 +6,7 @@
66
77 import type { App } from "../app.ts";
88 import type { Run } from "../core/runs.ts";
9 import { PLATFORM, pickSubscription, type Pick } from "../core/subscriptions.ts";
9 import { connectionHere, PLATFORM, pickSubscription, restSubscription, type Pick } from "../core/subscriptions.ts";
1010 import { crewPick } from "./key_fallback.ts";
1111 import type { AgentOutcome } from "./agent_runner.ts";
1212 import {
@@ -76,25 +76,43 @@ export function limitEnding(s: LimitState): LimitEnding {
7676 result.reason,
7777 now,
7878 );
79 if (picked.kind === "ready") {
80 // Only a look at who could take over: no reservation is made here.
81 // The run pauses, and on resume it picks again with its reserve.
82 const next = pickSubscription(app.db, app.config.dataDir, scope, new Date(), undefined, crewPick(app.db));
83 if (next.kind === "ready" && next.subscription.id !== picked.subscription.id) {
84 write(
85 `${picked.subscription.name} rests until ${whenText(until)}; ${next.subscription.name} takes the run`,
86 );
87 return {
88 outcome: {
89 state: "paused",
90 summary: `paused: ${pauseReason(picked.subscription.name, limit, said)}; ${next.subscription.name} takes over`,
91 resumeAt: new Date().toISOString(),
92 sessionId: result.sessionId,
93 costUsd: result.costUsd,
94 },
95 };
96 }
79 const was = picked.kind === "ready" ? picked.subscription : undefined;
80 const wasName = was?.name ?? "the forge's own token";
81 // Where connections are granted the forge's own token is one more plan, and rests as one.
82 const ownRests = picked.kind === "env" && connectionHere(app.db, scope);
83 if (ownRests) restSubscription(app.db, PLATFORM, until.toISOString(), said);
84 // Only a look at who could take over: no reservation is made here.
85 // The run pauses, and on resume it picks again with its reserve.
86 const next = was !== undefined || ownRests ? pickSubscription(app.db, app.config.dataDir, scope, new Date(), undefined, crewPick(app, run.id)) : undefined;
87 const name = next?.kind === "env" ? "the forge's own token" : next?.kind === "ready" && next.subscription.id !== was?.id ? next.subscription.name : undefined;
88 if (name !== undefined) {
89 write(`${wasName} rests until ${whenText(until)}; ${name} takes the run`);
90 return {
91 outcome: {
92 state: "paused",
93 summary: `paused: ${pauseReason(wasName, limit, said)}; ${name} takes over`,
94 resumeAt: new Date().toISOString(),
95 sessionId: result.sessionId,
96 costUsd: result.costUsd,
97 },
98 };
9799 }
100 // Nobody to take over: the run waits for the soonest of its accounts, a full plan's reset included.
101 // A connection that was down or refused before it answered once is not the run's failure, so that
102 // wait is no try. After a paid turn it is one: no session is kept, so a resume pays for it again.
103 const refusedHere = picked.kind === "ready" && picked.connection !== undefined;
104 const noTry = refusedHere && result.turns === 0;
105 if ((refusedHere || ownRests) && (noTry || run.attempt < MAX_PAUSES) && next?.kind === "resting")
106 return {
107 outcome: {
108 state: "paused",
109 summary: `paused: ${said}; resumes ${whenText(new Date(next.until))}`,
110 resumeAt: next.until,
111 sessionId: result.sessionId,
112 costUsd: result.costUsd,
113 ...(noTry ? { keepAttempt: true } : {}),
114 },
115 };
98116 if (run.attempt < MAX_PAUSES) {
99117 const at = resumeAt(result.limit, new Date());
100118 return {
src/crew/run_prepare.ts +21 −8
@@ -15,7 +15,7 @@ import { meterOf, trackCompute } from "../core/run_compute.ts";
1515 import { noteRunProgress, type Run } from "../core/runs.ts";
1616 import { PLATFORM, type Pick } from "../core/subscriptions.ts";
1717 import { redactValues } from "../kernel/log.ts";
18 import { currentRunner, runAgent, type AgentOutcome } from "./agent_runner.ts";
18 import { runAgent, runnerFor, type AgentOutcome } from "./agent_runner.ts";
1919 import { ownApp, ownAppUrls } from "./app_hosts.ts";
2020 import { promptVersion, systemPrompt, type BriefInput } from "./brief.ts";
2121 import { credentialEnv, holdModelCredential } from "./credential_env.ts";
@@ -110,8 +110,9 @@ export interface Prepared {
110110 }
111111
112112 /** What the agent said, with every held secret value taken out of it. */
113 function redactResult<T extends { result: string }>(r: T): T {
114 return { ...r, result: redactValues(r.result) };
113 function redactResult(r: AgentOutcome): AgentOutcome {
114 const said = r.limit?.said;
115 return { ...r, result: redactValues(r.result), ...(r.limit === undefined || said === undefined ? {} : { limit: { ...r.limit, said: redactValues(said) } }) };
115116 }
116117
117118 export async function prepareAgent(s: PrepareState): Promise<Prepared> {
@@ -123,7 +124,9 @@ export async function prepareAgent(s: PrepareState): Promise<Prepared> {
123124 // its log, its last message and every event. The gateway's address is
124125 // not a secret and stays readable.
125126 const modelEnv = credentialEnv(picked, app.config.dataDir);
126 held.modelSecrets = holdModelCredential(s.modelHold, modelEnv);
127 // An OpenAI-compatible account's key is its runner's alone, in no environment; it is held too.
128 const connection = picked.kind === "ready" ? picked.connection : undefined;
129 held.modelSecrets = holdModelCredential(s.modelHold, picked.kind === "ready" && connection !== undefined ? { OPENAI_API_KEY: picked.token } : modelEnv);
127130 const env = layerRunEnv({
128131 forge: {
129132 // The shard count an admin set (`core/capacity.ts`), for the checks an
@@ -225,7 +228,10 @@ export async function prepareAgent(s: PrepareState): Promise<Prepared> {
225228 s.reviewing,
226229 handed,
227230 );
228 const chosen = chooseModel(facts);
231 // The account's own model on an OpenAI-compatible one: an agent's Claude model names nothing there.
232 const chosen = connection === undefined ? chooseModel(facts) : { model: connection.model, reason: "account" };
233 /** The run's first prompt, for a runner that keeps no session to continue. */
234 let task: string | undefined;
229235 const invoke = async (
230236 prompt: string,
231237 budgetUsd: number,
@@ -233,16 +239,21 @@ export async function prepareAgent(s: PrepareState): Promise<Prepared> {
233239 ): Promise<AgentOutcome> => {
234240 // Idempotent: the first invocation starts the run's compute meter (#1388).
235241 trackCompute(meterOf(app.db), run.id, `crew:${agent.user.username}`);
242 // A later turn (a retry, the wrap-up) resumes a session; this runner has none, so it is told
243 // the task again and where its work is.
244 const again = connection !== undefined && resume !== undefined && task !== undefined;
245 const ask = again ? `${task}\n\nYou worked on this already and remember none of it. Read git status, git diff and git log in the clone for what is done, then: ${prompt}` : prompt;
246 task ??= prompt;
236247 const spent = redactResult(
237248 await runAgent({
238249 binary: options.binary,
239250 cwd: s.dir,
240 prompt,
251 prompt: ask,
241252 appendSystemPrompt: systemPrompt({ ...brief, devices: held.devices?.aliases }),
242253 model: chosen.model || undefined,
243254 budgetUsd,
244255 account: runAccount(picked, env),
245 resume,
256 resume: connection === undefined ? resume : undefined,
246257 env,
247258 sandbox: shellPolicy(),
248259 limits: machineLimits(s.machine),
@@ -273,11 +284,13 @@ export async function prepareAgent(s: PrepareState): Promise<Prepared> {
273284 meter.tokensIn += spent.tokensIn;
274285 meter.tokensOut += spent.tokensOut;
275286 meter.costUsd += spent.costUsd ?? 0;
287 if (picked.kind === "ready" && connection !== undefined && !spent.ok && !signal.aborted)
288 write(`${picked.subscription.name} (${chosen.model}) did not finish: ${spent.reason}${spent.result === "" ? "" : `, ${spent.result.slice(0, 200)}`}`);
276289 return spent;
277290 };
278291 // The runner and model this run uses, and what holds its spend: a runner
279292 // with no price says so instead of a dollar budget it cannot keep.
280 const heading = currentRunner().heading?.(chosen.model || undefined, env);
293 const heading = runnerFor(runAccount(picked, env)).heading?.(chosen.model || undefined, env);
281294 write(
282295 `${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}` : ""}`,
283296 );
src/crew/run_spend.ts +4 −1
@@ -13,6 +13,7 @@ import type { Run } from "../core/runs.ts";
1313 import { noteRunProgress } from "../core/runs.ts";
1414 import {
1515 MIN_RUN_USD,
16 passedOver,
1617 pickSubscription,
1718 PLATFORM,
1819 type Pick,
@@ -82,11 +83,12 @@ export async function settleSpend(s: SpendState): Promise<Spend> {
8283 : isOwnForge(app)
8384 ? budgetLimit(app.db, "run")
8485 : s.defaultBudgetUsd;
86 for (const name of passedOver(app.db, scope)) write(`${name}: no usable model, passed over; choose one at /settings/model`);
8587 // A crew run passes over a full plan and falls back to the capped key while the switch is on.
8688 const picked = pickSubscription(app.db, app.config.dataDir, scope, new Date(), {
8789 runId: run.id,
8890 usd: ownBudget,
89 }, crewPick(app.db));
91 }, crewPick(app, run.id));
9092 if (picked.kind === "resting") {
9193 const names = picked.names.join(", ");
9294 write(
@@ -101,6 +103,7 @@ export async function settleSpend(s: SpendState): Promise<Spend> {
101103 resumeAt: picked.until,
102104 sessionId: s.previousSessionId ?? "",
103105 costUsd: 0,
106 ...(picked.connection === true ? { keepAttempt: true } : {}),
104107 },
105108 };
106109 return {
src/crew/runner.ts +18 −13
@@ -32,6 +32,7 @@ import { getIssue, getIssueById } from "../core/issues.ts";
3232 import { crewGrantedRepos } from "../core/origin_read_grant.ts";
3333 import { getPull, isFirstBuild, listPulls, type Pull } from "../core/pulls.ts";
3434 import { canWrite, getRepoById } from "../core/repos.ts";
35 import { isOpenAISession } from "./openai_runner.ts";
3536 import { mintRunToken } from "../core/run_token.ts";
3637 import { answerCancelled, cancelRun, claimRun, finishRun, getRun, lastAgentRun, noteRunProgress, overranBefore, setRunBase, type Run } from "../core/runs.ts";
3738 import { deleteToken } from "../core/tokens.ts";
@@ -851,6 +852,21 @@ async function work(
851852 ? undefined
852853 : lastAgentRun(app.db, taskIssue.id, agent.user.id));
853854 const resumption = resumeDecision(previous, (options.now ?? Date.now)());
855 const spend = await settleSpend({
856 app,
857 run,
858 repo,
859 agent,
860 defaultBudgetUsd: options.budgetUsd,
861 previousSessionId: previous?.sessionId,
862 meter,
863 write,
864 });
865 if (!spend.ok) return spend.outcome;
866 const { picked, scope, own, budget } = spend;
867 // A session lives in the runner that made it: one never crosses to, or from, an
868 // OpenAI-compatible account. Such a run starts fresh on the same clone, with the whole brief.
869 const crosses = (picked.kind === "ready" && picked.connection !== undefined) || isOpenAISession(previous?.sessionId ?? "");
854870 const since = feedbackSince(app.db, repo, issue, agent);
855871 const record = getAppByRepo(app.db, repo.id);
856872 const runtime = appsRuntime(app);
@@ -884,7 +900,8 @@ async function work(
884900 // A review reads one head afresh: a resumed session would carry an
885901 // older head's diff and preview into the verdict on this one. Any
886902 // other follow-up resumes only while it is cheap to (`resume.ts`).
887 resuming: !reviewing && resumption.resume,
903 resuming: !reviewing && resumption.resume && !crosses,
904 sessionless: crosses,
888905 role,
889906 // The owner's reference files, by name and path (`actions/drop.ts`), never their contents.
890907 drop: dropBrief(app.config.dataDir, repo),
@@ -916,18 +933,6 @@ async function work(
916933 lessons,
917934 });
918935
919 const spend = await settleSpend({
920 app,
921 run,
922 repo,
923 agent,
924 defaultBudgetUsd: options.budgetUsd,
925 previousSessionId: previous?.sessionId,
926 meter,
927 write,
928 });
929 if (!spend.ok) return spend.outcome;
930 const { picked, scope, own, budget } = spend;
931936 const ready = await prepareAgent({
932937 app,
933938 options,
src/crew/runner_env.ts +6
@@ -89,6 +89,9 @@ export function runnerCredentialInEnv(env: Env): boolean {
8989 return (runnerSettings(env).configDir ?? "").trim() !== "";
9090 }
9191
92 /** Whether a run with no account of its own carries a credential (`ownEnv`, or the runner's signed-in config dir). */
93 export const ownCredentialInEnv = (env: Env): boolean => runnerCredentialInEnv(env) || (env["ANTHROPIC_AUTH_TOKEN"] ?? "").trim() !== "";
94
9295 /** The platform account's own subscription token, when the process holds one. */
9396 export const platformToken = (env: Env): string | undefined => (env["CLAUDE_CODE_OAUTH_TOKEN"] ?? "").trim() || undefined;
9497
@@ -178,6 +181,9 @@ export function layerRunEnv(layers: {
178181 */
179182 export function runAccount(picked: Pick, env: Readonly<Record<string, string>>): RunAccount | undefined {
180183 if (picked.kind !== "ready") return undefined;
184 // The account's own base and key together: one account's key never reaches another's host.
185 if (picked.connection !== undefined)
186 return { token: picked.token, base: picked.apiBase ?? "", connection: { guarded: picked.connection.guarded, effort: picked.connection.effort } };
181187 const base = picked.apiBase !== null && picked.apiBase !== "" ? env[GATEWAY_VAR] : undefined;
182188 return { token: picked.token, ...(base === undefined || base === "" ? {} : { base }) };
183189 }
src/spawn/funding.ts +8 −2
@@ -8,11 +8,11 @@
88 * is good for nothing but that door.
99 */
1010
11 import { crewHasCredential } from "../core/subscriptions.ts";
11 import { crewHasCredential, MIN_RUN_USD } from "../core/subscriptions.ts";
1212 import { join } from "node:path";
1313 import type { App } from "../app.ts";
1414 import { readPrivate, writePrivate } from "../kernel/file_modes.ts";
15 import { lentEnv } from "../crew/runner_env.ts";
15 import { lentEnv, ownCredentialInEnv } from "../crew/runner_env.ts";
1616 import { leftUsd, usdWords } from "./credit.ts";
1717 import { isParentLocal } from "./beat-door.ts";
1818
@@ -167,6 +167,12 @@ export function lentCreditLeft(draws: boolean, dataDir: string): number | undefi
167167 return Math.max(0, f.capUsd - (f.spentUsd ?? 0));
168168 }
169169
170 /** Whether the forge's own token has something to spend: lent credit where the host lends it, else a token in its environment. */
171 export function ownTokenLeft(dataDir: string): boolean {
172 const lent = lentCreditLeft(true, dataDir);
173 return lent !== undefined ? lent >= MIN_RUN_USD : fundingOf(dataDir) !== undefined || ownCredentialInEnv(process.env);
174 }
175
170176 /** A run's budget in USD: what it asked for, never more than the lent credit left (#11948). */
171177 export const cappedByLent = (wanted: number, lentLeft: number | undefined): number =>
172178 lentLeft === undefined ? wanted : Math.min(wanted, lentLeft);
test/crew-accounts.test.ts +5 −2
@@ -154,10 +154,13 @@ describe("the order, the fallback and the spend", () => {
154154 expect(line.says).toContain("$0.07 in all, of a $500 budget it stops at ($499.93 left)");
155155 expect(line.spend?.runs.map((r) => [r.repo, r.usd])).toEqual([["trevato/forge", 0.07]]);
156156
157 // An admin puts espo-corp after the key: the key is tried first, espo-corp is the fallback.
157 // An admin puts espo-corp after the key: a person's turn tries the key first. A crew run still takes
158 // the plan, with the fallback on or off, and the words are the crew's.
158159 expect(orderAccount(app, trevato, "espo-corp", "espo-api-key").ok).toBe(true);
159160 expect(named(pick(forge))).toBe("espo-api-key");
160 expect(crewAccountWords(app, trevato, scope, NOW).says).toContain("espo-corp is the fallback");
161 const crew = (fallback: boolean) => pickSubscription(app.db, dir, { repoId: forge.id, ownerId: forge.ownerId, agentId: "" }, NOW, undefined, { fallback });
162 expect([named(crew(false)), named(crew(true))]).toEqual(["espo-corp", "espo-corp"]);
163 expect(crewAccountWords(app, trevato, scope, NOW).says).toContain("The next run for trevato spends espo-corp");
161164 expect(orderAccount(app, bob, "espo-api-key", "espo-corp")).toEqual({ ok: false, error: "forbidden" });
162165 expect(orderAccount(app, trevato, "espo-api-key", "espo-corp").ok).toBe(true);
163166 expect(named(pick(forge))).toBe("espo-corp");
test/crew-key-fallback.test.ts +7 −4
@@ -32,7 +32,7 @@ let planId = "", keyId = "";
3232 const KEY_TOKEN = "sk-ant-api03-never-shown-0123456789";
3333 const scope = () => ({ repoId: "", ownerId: alice.id, agentId: "" });
3434 const nameOf = (p: Pick): string => (p.kind === "ready" ? p.subscription.name : p.kind);
35 const crewPickNow = () => pickSubscription(app.db, dir, scope(), new Date(), undefined, crewPick(app.db));
35 const crewPickNow = () => pickSubscription(app.db, dir, scope(), new Date(), undefined, crewPick(app));
3636 const inAnHour = () => new Date(Date.now() + 3_600_000).toISOString();
3737
3838 /** The plan's 5-hour window as the provider last said: `used` percent, resetting in an hour. */
@@ -128,17 +128,20 @@ test("the week's share kept for people holds the crew again, unless the capped k
128128 .run(planId, new Date(Date.now() + 3 * 86_400_000).toISOString(), new Date().toISOString());
129129 const paced = weekHold(weekFor(app, made.value, new Date()));
130130 expect(paced).not.toBeNull();
131 const at = { repoId: made.value.id, ownerId: made.value.ownerId, agentId: "" };
131132 // On, under its cap: the run goes on, and the pick passes the plan over for the key.
132 expect(weekHolds(app.db, paced)).toBe(false);
133 expect(weekHolds(app.db, paced, at)).toBe(false);
134 // The key is not one this run may use: another owner's run stays held.
135 expect(weekHolds(app.db, paced, { repoId: "elsewhere", ownerId: "nobody", agentId: "" })).toBe(true);
133136 measure(10);
134137 expect(nameOf(crewPickNow())).toBe("key-a");
135138 // Off: the hold holds.
136139 setFallback(app, alice, false);
137 expect(weekHolds(app.db, paced)).toBe(true);
140 expect(weekHolds(app.db, paced, at)).toBe(true);
138141 setFallback(app, alice, true);
139142 // Capped: the hold holds.
140143 app.db.query("UPDATE subscription SET spent_usd = 500 WHERE id = ?1").run(keyId);
141 expect(weekHolds(app.db, paced)).toBe(true);
144 expect(weekHolds(app.db, paced, at)).toBe(true);
142145 app.db.query("UPDATE subscription SET spent_usd = 0 WHERE id = ?1").run(keyId);
143146 app.db.query("UPDATE subscription SET headroom_pct = 0 WHERE id = ?1").run(planId);
144147 app.db.query("DELETE FROM subscription_measure WHERE subscription_id = ?1 AND span = 'week'").run(planId);
test/crew-openai-account.test.ts added +556
@@ -0,0 +1,556 @@
1 /**
2 * A crew run on an OpenAI-compatible account (SubQ): taken by a grant and never from the pool, on
3 * the account's own host, key and model, after the Claude plans and before the pay-per-token keys.
4 */
5 import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test";
6 import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
7 import { readFileSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { assignIssue, openIssue } from "../src/actions/issues.ts";
12 import { recordTest, saveConnection } from "../src/core/connections.ts";
13 import { noteMeasure } from "../src/core/measure.ts";
14 import { setCapacity } from "../src/core/capacity.ts";
15 import { createRepo, updateRepoSettings } from "../src/actions/repos.ts";
16 import { crewAccountWords } from "../src/actions/crew_accounts.ts";
17 import { getAgent } from "../src/core/agents.ts";
18 import { getRepoById } from "../src/core/repos.ts";
19 import { listRuns, type Run } from "../src/core/runs.ts";
20 import { repoPace } from "../src/crew/autonomy_pace.ts";
21 import { MAX_PAUSES, perMinute } from "../src/crew/limits.ts";
22 import { limitEnding } from "../src/crew/run_limits.ts";
23 import { isNetworkError } from "../src/crew/network.ts";
24 import { ownTokenLeft } from "../src/spawn/funding.ts";
25 import { queueAgentRun } from "../src/crew/registry.ts";
26 import { forgetWeek, weekFor } from "../src/crew/week_read.ts";
27 import { weekHold } from "../src/crew/week_hold.ts";
28 import { addSubscription, connectionRoom, credentialEnvOf, EVERYONE, getSubscriptionByName, passedOver, pickSubscription, PLATFORM, restSubscription, setGrants, type Pick } from "../src/core/subscriptions.ts";
29 import { waitFor } from "./helpers/poll.ts";
30 import type { User } from "../src/core/users.ts";
31 import { runnerFor, useRunner, type AgentRun, type AgentRunner, type RunnerLimit } from "../src/crew/agent_runner.ts";
32 import { costOf, priceOf } from "../src/crew/openai_price.ts";
33 import { effortFor, isOpenAISession, openaiRunner, runOpenAI } from "../src/crew/openai_runner.ts";
34 import { runAccount } from "../src/crew/runner_env.ts";
35 import { readRunLog } from "../src/runs/log.ts";
36 import { seedAdmin } from "./helpers/admin.ts";
37 import { agentRunSettled, startStandInCrew, stopStandInCrew, type StandInCrew } from "./helpers/crew-standin.ts";
38 import { quietLogs, withoutEnv } from "./helpers/globals.ts";
39
40 quietLogs();
41 // What the machine may hold: whether the forge has a token of its own is each test's to say.
42 withoutEnv("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "FORGE_AGENT_CONFIG_DIR", "FORGE_CLAUDE_CONFIG_DIR");
43
44 const PLAN = "sk-ant-oat01-a-plan-for-the-test";
45 const KEY = "sk-ant-api03-a-key-for-the-test";
46 const SUBQ = "subq-key-for-the-test";
47 const NOW = new Date("2026-12-03T03:00:00Z");
48 const LATER = "2026-12-03T09:00:00.000Z";
49
50 let dir = "";
51 let app: App;
52 let alice: User;
53 beforeAll(async () => {
54 dir = await mkdtemp(join(tmpdir(), "forge-crew-openai-"));
55 app = createApp({ dataDir: dir, port: 0 });
56 const made = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "a-good-passphrase" });
57 if (!made.ok) throw new Error(String(made.error));
58 alice = made.value;
59 });
60 afterAll(async () => {
61 app.close();
62 await rm(dir, { recursive: true, force: true });
63 });
64 beforeEach(() => {
65 app.db.run("DELETE FROM subscription_grant");
66 app.db.run("DELETE FROM subscription WHERE id <> 'platform'");
67 });
68
69 const connect = (name: string, over: { scope?: "yours" | "forge"; base?: string; models?: { id: string }[] } = {}): string => {
70 const made = saveConnection(app.db, dir, {
71 name, protocol: "openai", base: over.base ?? "https://api.subq.ai/v1", key: SUBQ, scope: over.scope ?? "forge", userId: alice.id,
72 models: over.models ?? [{ id: "subq-savant-1.4" }, { id: "subq-savant-latest" }], said: "listed",
73 });
74 if (!made.ok) throw new Error(made.error);
75 return made.value.id;
76 };
77 const claude = (name: string, token: string): string => {
78 const made = addSubscription(app.db, dir, { name, token, createdBy: alice.id });
79 if (!made.ok) throw new Error(made.error);
80 return made.value.id;
81 };
82 const pick = (agentId = "bot", fallback = false, ownToken = true): Pick => pickSubscription(app.db, dir, { repoId: "repo", ownerId: alice.id, agentId }, NOW, undefined, { fallback, ownToken });
83 const named = (p: Pick): string => (p.kind === "ready" ? p.subscription.name : p.kind);
84
85 /** An owner who is no forge admin, so no token of the forge's own stands behind a pick. */
86 const OWNER = "someone";
87 const pickFor = (agentId = "bot"): Pick => pickSubscription(app.db, dir, { repoId: "repo", ownerId: OWNER, agentId }, NOW, undefined, { fallback: false });
88
89 describe("the pick", () => {
90 test("a connection is never taken from the pool, nor by the grant saving one's own writes; a repository's, an owner's or an agent's grant takes it", () => {
91 const subq = connect("SubQ");
92 expect(named(pickFor())).toBe("none");
93 for (const [scope, agent] of [["repo", EVERYONE], [OWNER, EVERYONE], ["repo", "bot"]] as const) {
94 setGrants(app.db, scope, agent, [subq]);
95 expect(named(pickFor())).toBe("SubQ");
96 setGrants(app.db, scope, agent, []);
97 }
98 setGrants(app.db, "repo", "bot", [subq]);
99 expect(named(pickFor("other"))).toBe("none");
100 setGrants(app.db, "repo", "bot", []);
101 // Alice's own: its self-written grant counts for none of her crew's runs, past the week's hold too.
102 const mine = connect("Mine", { scope: "yours" });
103 const hers = (): string => named(pickSubscription(app.db, dir, { repoId: "repo", ownerId: alice.id, agentId: "bot" }, NOW, undefined, { fallback: false, ownToken: true, pastWeek: true }));
104 // Nothing left to use past the hold: it waits, and never spends the forge's own token.
105 expect(hers()).toBe("resting");
106 setGrants(app.db, "repo", EVERYONE, [mine]);
107 expect(hers()).toBe("Mine");
108 // A person's own is reached only through the outbound guard.
109 const own = pickFor();
110 expect(own.kind === "ready" && own.connection?.guarded).toBe(true);
111 });
112
113 test("the forge's own token goes first where no Anthropic account may be used, unless its window is full or the connection is ranked ahead of it", () => {
114 const subq = connect("SubQ");
115 setGrants(app.db, "repo", EVERYONE, [subq]);
116 expect(named(pick())).toBe("env");
117 app.db.run("UPDATE subscription SET rank = 1 WHERE id = 'platform'");
118 expect(named(pick())).toBe("SubQ");
119 restSubscription(app.db, subq, LATER, "refused its key");
120 expect(named(pick())).toBe("env");
121 app.db.run("UPDATE subscription SET resting_until = NULL");
122 app.db.run("UPDATE subscription SET rank = 0 WHERE id = 'platform'");
123 noteMeasure(app.db, PLATFORM, { window: "week", usedPct: 100, resetsAt: LATER, observedAt: NOW.toISOString() });
124 expect(named(pick())).toBe("SubQ");
125 app.db.run("DELETE FROM subscription_measure");
126 });
127
128 test("a run past the week's hold picks no plan and not the forge's own token; the plan's window has room all the same", () => {
129 const plan = claude("Plan", PLAN);
130 setGrants(app.db, "repo", EVERYONE, [connect("SubQ")]);
131 noteMeasure(app.db, plan, { window: "week", usedPct: 95, resetsAt: LATER, observedAt: NOW.toISOString() });
132 const past = (pastWeek: boolean): string => named(pickSubscription(app.db, dir, { repoId: "repo", ownerId: alice.id, agentId: "bot" }, NOW, undefined, { fallback: false, ownToken: true, pastWeek }));
133 expect(past(false)).toBe("Plan");
134 expect(past(true)).toBe("SubQ");
135 app.db.run("DELETE FROM subscription_measure");
136 // The same where the forge's own token is the plan.
137 app.db.run("DELETE FROM subscription WHERE id = ?1", [plan]);
138 expect(past(false)).toBe("env");
139 expect(past(true)).toBe("SubQ");
140 });
141
142 test("a forge with no token of its own and one granted connection runs on the connection", async () => {
143 const subq = connect("SubQ");
144 setGrants(app.db, "repo", EVERYONE, [subq]);
145 expect(named(pick("bot", false, false))).toBe("SubQ");
146 restSubscription(app.db, subq, LATER, "refused its key");
147 expect(named(pick("bot", false, false))).toBe("resting");
148 // What there is to spend: a token or a signed-in directory, or lent credit while some is left.
149 const own = join(dir, "lent");
150 expect(ownTokenLeft(own)).toBe(false);
151 process.env["ANTHROPIC_AUTH_TOKEN"] = "a-gateway's";
152 expect(ownTokenLeft(own)).toBe(true);
153 delete process.env["ANTHROPIC_AUTH_TOKEN"];
154 process.env["FORGE_AGENT_CONFIG_DIR"] = dir;
155 expect(ownTokenLeft(own)).toBe(true);
156 await mkdir(own);
157 const credit = (spentUsd: number): Promise<void> => writeFile(join(own, "parent.json"), JSON.stringify({ credit: { token: "bearer-token-1", capUsd: 2, spentUsd } }), { mode: 0o600 });
158 await credit(2);
159 expect(ownTokenLeft(own)).toBe(false);
160 delete process.env["FORGE_AGENT_CONFIG_DIR"];
161 await credit(0);
162 expect(ownTokenLeft(own)).toBe(true);
163 });
164
165 test("on the forge's own token a connection granted to everyone leaves the week's hold on, and the account words true", async () => {
166 const made = await createRepo(app, alice, { name: "weekly", visibility: "private" });
167 if (!made.ok) throw new Error(String(made.error));
168 const repo = made.value;
169 setGrants(app.db, repo.id, EVERYONE, [connect("SubQ")]);
170 const now = new Date();
171 noteMeasure(app.db, PLATFORM, { window: "week", usedPct: 95, resetsAt: new Date(now.getTime() + 3 * 86_400_000).toISOString(), observedAt: now.toISOString() });
172 forgetWeek();
173 process.env["FORGE_AGENT_CONFIG_DIR"] = dir;
174 try {
175 expect(weekFor(app, repo, now)?.usedPct).toBe(95);
176 expect(weekHold(weekFor(app, repo, now))).not.toBeNull();
177 const said = (): string => crewAccountWords(app, alice, { scopeId: repo.id, repoId: repo.id, ownerId: repo.ownerId, name: "alice/weekly" }, now).says;
178 expect(said()).toBe("The next run for alice/weekly spends the server's own token. SubQ is the fallback.");
179 delete process.env["FORGE_AGENT_CONFIG_DIR"];
180 expect(said()).toContain("The next run for alice/weekly spends SubQ");
181 // A plan from the pool goes first, though the grant is nearer.
182 app.db.run("DELETE FROM subscription_measure");
183 claude("Plan", PLAN);
184 expect(said()).toContain("The next run for alice/weekly spends Plan");
185 expect(said()).toContain("SubQ is the fallback");
186 } finally {
187 delete process.env["FORGE_AGENT_CONFIG_DIR"];
188 app.db.run("DELETE FROM subscription_measure");
189 forgetWeek();
190 }
191 });
192
193 test("a connection with no model a crew run can use is no candidate: it blocks nothing behind it and opens no hold", () => {
194 const empty = connect("Empty", { models: [] });
195 setGrants(app.db, "repo", EVERYONE, [empty]);
196 expect(connectionRoom(app.db, { repoId: "repo", ownerId: OWNER }, NOW)).toBe(false);
197 expect(named(pickFor())).toBe("none");
198 setGrants(app.db, "repo", EVERYONE, [empty, connect("Works")]);
199 expect(named(pickFor())).toBe("Works");
200 expect(passedOver(app.db, { repoId: "repo", ownerId: OWNER, agentId: "bot" })).toEqual(["Empty"]);
201 });
202
203 test("only a crew run takes one: Talk's default, one-shots and deepsec pick without it", () => {
204 setGrants(app.db, "repo", EVERYONE, [connect("SubQ")]);
205 expect(pickSubscription(app.db, dir, { repoId: "repo", ownerId: alice.id, agentId: "bot" }, NOW).kind).toBe("env");
206 });
207
208 test("the plan first, the connection while it rests, the keys last; one ranked before every Claude account goes first", () => {
209 const subq = connect("SubQ");
210 const plan = claude("Plan", PLAN);
211 claude("Key", KEY);
212 setGrants(app.db, "repo", EVERYONE, [subq]);
213 expect(named(pick("bot", true))).toBe("Plan");
214 restSubscription(app.db, plan, LATER, "weekly limit");
215 expect(named(pick("bot", true))).toBe("SubQ");
216 // Its grant is the choice: the metered fallback's switch does not hold it back.
217 expect(named(pick("bot", false))).toBe("SubQ");
218 expect(connectionRoom(app.db, { repoId: "repo", ownerId: alice.id, agentId: "bot" }, NOW)).toBe(true);
219 expect(connectionRoom(app.db, { repoId: "elsewhere", ownerId: "nobody" }, NOW)).toBe(false);
220 restSubscription(app.db, subq, LATER, "too many requests");
221 expect(connectionRoom(app.db, { repoId: "repo", ownerId: alice.id }, NOW)).toBe(false);
222 expect(named(pick("bot", true))).toBe("Key");
223 app.db.run("UPDATE subscription SET resting_until = NULL");
224 // Full, not only resting: passed over as well.
225 noteMeasure(app.db, plan, { window: "week", usedPct: 100, resetsAt: LATER, observedAt: NOW.toISOString() });
226 expect(named(pick("bot", false))).toBe("SubQ");
227 app.db.run("DELETE FROM subscription_measure");
228 // Keys and no plan: the grant is the choice of that work, so it goes before them.
229 app.db.run("DELETE FROM subscription WHERE id = ?1", [plan]);
230 expect(named(pick("bot", true))).toBe("SubQ");
231 claude("Plan", PLAN);
232 app.db.run("UPDATE subscription SET rank = 1 WHERE protocol = 'anthropic' AND id <> 'platform'");
233 expect(named(pick("bot", true))).toBe("SubQ");
234 });
235
236 test("it carries its own base, key and model, and nothing of it is in a Claude run's environment", () => {
237 const subq = connect("SubQ");
238 setGrants(app.db, "repo", EVERYONE, [subq]);
239 const p = pickFor();
240 if (p.kind !== "ready") throw new Error(p.kind);
241 expect(p.connection).toEqual({ model: "subq-savant-1.4", effort: "", guarded: false });
242 expect(credentialEnvOf(p)).toEqual({});
243 expect(runAccount(p, { ANTHROPIC_BASE_URL: "https://elsewhere.example" })).toEqual({ token: SUBQ, base: "https://api.subq.ai/v1", connection: { guarded: false, effort: "" } });
244 app.db.run(`UPDATE subscription SET chosen = '["subq-savant-latest"]' WHERE id = ?1`, [subq]);
245 const again = pickFor();
246 expect(again.kind === "ready" && again.connection?.model).toBe("subq-savant-latest");
247 // A decision model is never taken by its place in the list, only when it is chosen by name.
248 const model = (chosen: string[], listed: string[]): string | undefined => {
249 app.db.run("UPDATE subscription SET chosen = ?2, models = ?3 WHERE id = ?1", [subq, JSON.stringify(chosen), JSON.stringify(listed.map((id) => ({ id })))]);
250 const at = pickFor();
251 return at.kind === "ready" ? at.connection?.model : undefined;
252 };
253 expect(model([], ["subq-snap-1.1", "subq-snap-latest", "subq-savant-1.4"])).toBe("subq-savant-1.4");
254 expect(model([], ["subq-snap-1.1", "subq-snap-preview"])).toBeUndefined();
255 expect(model(["subq-snap-1.2"], ["subq-savant-1.4"])).toBe("subq-snap-1.2");
256 expect(model([], [])).toBeUndefined();
257 });
258 });
259
260 describe("a refusal, and the wait after it", () => {
261 const soon = (minutes: number): string => new Date(Date.now() + minutes * 60_000).toISOString();
262 const scope = { repoId: "repo", agentId: "bot" };
263 const ending = (picked: Pick, limit: RunnerLimit, lines: string[] = [], turns = 0, attempt = 5) =>
264 limitEnding({
265 app, picked, scope: { ...scope, ownerId: alice.id }, aborted: false, write: (l) => lines.push(l),
266 run: { id: "a-run", attempt, sent: false } as Run,
267 result: { ok: false, sessionId: "s", result: "", costUsd: 0, turns, tokensIn: 0, tokensOut: 0, contextTokens: 0, contextWindow: 0, reason: "error", limit },
268 });
269 const now = (): Pick => pickSubscription(app.db, dir, { ...scope, ownerId: alice.id }, new Date(), undefined, { fallback: false, ownToken: true });
270
271 test("a full plan beside a connection that refuses, or is spent: the run waits for the plan's reset and spends no try", () => {
272 const plan = claude("Plan", PLAN);
273 const subq = connect("SubQ");
274 setGrants(app.db, "repo", EVERYONE, [subq]);
275 const reset = soon(30);
276 noteMeasure(app.db, plan, { window: "5h", usedPct: 100, resetsAt: reset, observedAt: soon(0) });
277 const picked = now();
278 expect(named(picked)).toBe("SubQ");
279 expect(ending(picked, { said: "the account's endpoint refused its key or its payment (HTTP 401)", refused: true })).toMatchObject({ outcome: { state: "paused", resumeAt: reset, keepAttempt: true } });
280 expect(Date.parse(getSubscriptionByName(app.db, "SubQ")!.restingUntil!)).toBeGreaterThan(Date.parse(soon(23 * 60)));
281 expect(now()).toMatchObject({ kind: "resting", until: reset, connection: true });
282 // A test that works uses it again at once.
283 recordTest(app.db, subq, { working: true, said: "listed" });
284 expect(named(now())).toBe("SubQ");
285 app.db.run("UPDATE subscription SET budget_usd = 1, spent_usd = 1 WHERE id = ?1", [subq]);
286 expect(now()).toMatchObject({ kind: "resting", until: reset, connection: true });
287 app.db.run("DELETE FROM subscription_measure");
288 });
289
290 test("a connection that fails after paid turns uses the run's tries; one that never answered does not", () => {
291 setGrants(app.db, "repo", EVERYONE, [connect("SubQ")]);
292 const picked = pickSubscription(app.db, dir, { ...scope, ownerId: alice.id }, new Date(), undefined, { fallback: false, ownToken: false });
293 expect(named(picked)).toBe("SubQ");
294 const down = { said: "the account's endpoint is failing (HTTP 503)" };
295 const paid = ending(picked, down, [], 2);
296 expect(paid).toMatchObject({ outcome: { state: "paused" } });
297 expect("outcome" in paid && paid.outcome.state === "paused" && paid.outcome.keepAttempt).toBeFalsy();
298 // Its tries used, it is not paused again; with no turn taken it still is, and spends none.
299 expect(ending(picked, down, [], 2, MAX_PAUSES)).not.toHaveProperty("outcome");
300 expect(ending(picked, down, [], 0, MAX_PAUSES)).toMatchObject({ outcome: { state: "paused", keepAttempt: true } });
301 });
302
303 test("the forge's own token refused: a granted connection takes the run, and the next pick is the connection; with none granted the token does not rest", () => {
304 const limit = { limitedUntil: soon(60), window: "5h", said: "usage limit reached" } as const;
305 process.env["FORGE_AGENT_CONFIG_DIR"] = dir;
306 try {
307 ending({ kind: "env" }, limit);
308 expect(app.db.query("SELECT resting_until AS u FROM subscription WHERE id = 'platform'").get()).toEqual({ u: null });
309 setGrants(app.db, "repo", EVERYONE, [connect("SubQ")]);
310 expect(named(now())).toBe("env");
311 const lines: string[] = [];
312 ending({ kind: "env" }, limit, lines);
313 expect(lines.join("\n")).toContain("SubQ takes the run");
314 expect(named(now())).toBe("SubQ");
315 // The connection rests too: refused again, the token rests all the same, and the run waits for the first to wake.
316 app.db.run("UPDATE subscription SET resting_until = NULL WHERE id = 'platform'");
317 const wakes = soon(15);
318 restSubscription(app.db, getSubscriptionByName(app.db, "SubQ")!.id, wakes, "down");
319 expect(ending({ kind: "env" }, limit)).toMatchObject({ outcome: { state: "paused", resumeAt: wakes } });
320 // The token's window measured full, and the connection resting: the same wait, and no try of the run's.
321 app.db.run("UPDATE subscription SET resting_until = NULL WHERE id = 'platform'");
322 noteMeasure(app.db, PLATFORM, { window: "5h", usedPct: 100, resetsAt: soon(60), observedAt: soon(0) });
323 expect(now()).toMatchObject({ kind: "resting", until: wakes, connection: true });
324 app.db.run("DELETE FROM subscription_measure");
325 } finally {
326 delete process.env["FORGE_AGENT_CONFIG_DIR"];
327 app.db.run("UPDATE subscription SET resting_until = NULL, resting_said = '' WHERE id = 'platform'");
328 }
329 });
330 });
331
332 describe("the runner", () => {
333 test("a 5xx is asked again, then rests the account with words that are no per-minute limit; a refused key rests it at once", async () => {
334 let asked = 0;
335 let status = 503;
336 const srv = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => (asked++, new Response(`rate limit, connection error ${SUBQ}`, { status })) });
337 const run: AgentRun = {
338 binary: "", cwd: dir, prompt: "p", appendSystemPrompt: "s", model: "subq-savant-1.4", budgetUsd: 1, env: {},
339 account: { token: SUBQ, base: `http://127.0.0.1:${srv.port}/v1`, connection: { guarded: false } },
340 sandbox: { allowHosts: [], denyRead: [], enforced: false, readAllow: [] } as AgentRun["sandbox"],
341 timeoutMs: 20_000, log: () => {}, signal: new AbortController().signal,
342 };
343 try {
344 for (const [code, asks] of [[503, 3], [502, 3], [401, 1], [402, 1], [403, 1]] as const) {
345 status = code;
346 asked = 0;
347 const out = await runOpenAI(run, {}, {}, [0, 0]);
348 expect([code, asked]).toEqual([code, asks]);
349 expect(out.limit?.said).toContain(`HTTP ${code}`);
350 expect(out.limit?.said).not.toContain(SUBQ);
351 expect(perMinute(out.limit)).toBe(false);
352 expect(isNetworkError(out)).toBe(false);
353 }
354 // A bad request is the run's own failure and rests nobody.
355 status = 400;
356 expect((await runOpenAI(run, {}, {}, [])).limit).toBeUndefined();
357 } finally {
358 srv.stop(true);
359 }
360 });
361
362 test("follows the account: a connection's own, whatever the forge's default is; any other keeps the default", () => {
363 expect(runnerFor({ token: "t", base: "https://x.example/v1", connection: { guarded: true } })).toBe(openaiRunner);
364 expect(runnerFor({ token: "t" })).not.toBe(openaiRunner);
365 expect(runnerFor(undefined)).not.toBe(openaiRunner);
366 });
367
368 test("savant's price is in the table, and its efforts are the ones its server takes", () => {
369 expect(priceOf("subq-savant-1.4")).toEqual({ price: { inPerM: 0.1, outPerM: 0.5 }, known: true });
370 expect(costOf(priceOf("subq-savant-latest").price, 1_000_000, 1_000_000)).toBeCloseTo(0.6, 9);
371 expect(["none", "minimal", "low", "medium", "high", "max"].map((e) => effortFor("subq-savant-1.4", e))).toEqual(["low", "low", "low", "high", "high", "max"]);
372 expect(effortFor("gpt-5", "medium")).toBe("medium");
373 });
374
375 test("a 429 is asked again on the same host and key; past the waits the run ends as the provider's refusal", async () => {
376 const heard: { auth: string | null; body: Record<string, unknown> }[] = [];
377 let busy = 2;
378 const srv = Bun.serve({
379 port: 0, hostname: "127.0.0.1",
380 async fetch(req) {
381 heard.push({ auth: req.headers.get("authorization"), body: (await req.json()) as Record<string, unknown> });
382 if (busy-- > 0) return new Response("slow down", { status: 429 });
383 return Response.json({ choices: [{ message: { role: "assistant", content: "done" } }], usage: { prompt_tokens: 1_000_000, completion_tokens: 0 } });
384 },
385 });
386 const run: AgentRun = {
387 binary: "", cwd: dir, prompt: "p", appendSystemPrompt: "s", model: "subq-savant-1.4", budgetUsd: 1, env: {},
388 account: { token: SUBQ, base: `http://127.0.0.1:${srv.port}/v1`, connection: { guarded: false, effort: "medium" } },
389 sandbox: { allowHosts: [], denyRead: [], enforced: false, readAllow: [] } as AgentRun["sandbox"],
390 timeoutMs: 20_000, log: () => {}, signal: new AbortController().signal,
391 };
392 // The operator's own endpoint and key are configured too, and are never used for this account.
393 const operator = { OPENAI_BASE_URL: "http://127.0.0.1:1/v1", OPENAI_API_KEY: "operator-key" };
394 try {
395 const out = await runOpenAI(run, operator, {}, [0, 0, 0]);
396 expect(out).toMatchObject({ ok: true, result: "done" });
397 expect(out.costUsd).toBeCloseTo(0.1, 9);
398 expect(heard.map((h) => h.auth)).toEqual(Array(3).fill(`Bearer ${SUBQ}`));
399 expect(heard[2]!.body).toMatchObject({ model: "subq-savant-1.4", reasoning_effort: "high" });
400 expect(heard[2]!.body).not.toHaveProperty("temperature");
401 busy = 99;
402 const refused = await runOpenAI(run, operator, {}, [0]);
403 expect(refused).toMatchObject({ ok: false, reason: "rate_limited" });
404 expect(refused.limit?.said).toContain("429");
405 // Its session ids say whose they are; a Claude session handed to it is not taken over.
406 expect(isOpenAISession(out.sessionId)).toBe(true);
407 expect(isOpenAISession((await runOpenAI({ ...run, resume: "a-claude-session" }, operator, {}, [])).sessionId)).toBe(true);
408 } finally {
409 srv.stop(true);
410 }
411 });
412 });
413
414 /** A stand-in crew whose bot is granted SubQ at `answer`'s server, in a repository of `alice`'s. */
415 async function onSubQ(answer: (n: number) => Response, use: (c: { standIn: StandInCrew; heard: { auth: string | null; model: string; prompt: string }[]; subq: string }) => Promise<void>, grant = true): Promise<void> {
416 const heard: { auth: string | null; model: string; prompt: string }[] = [];
417 const srv = Bun.serve({
418 port: 0, hostname: "127.0.0.1",
419 async fetch(req) {
420 const body = (await req.json()) as { model: string; messages: { content?: string | null }[] };
421 heard.push({ auth: req.headers.get("authorization"), model: body.model, prompt: body.messages[1]?.content ?? "" });
422 return answer(heard.length);
423 },
424 });
425 const standIn = await startStandInCrew({ tickMs: 50 });
426 try {
427 const made = saveConnection(standIn.app.db, standIn.dataDir, {
428 name: "SubQ", protocol: "openai", base: `http://127.0.0.1:${srv.port}/v1`, key: SUBQ, scope: "forge", userId: standIn.alice.id, models: [{ id: "subq-savant-1.4" }], said: "listed",
429 });
430 if (!made.ok) throw new Error(made.error);
431 // Ranked ahead of every Claude account and of the forge's own token.
432 standIn.app.db.run("UPDATE subscription SET rank = 1 WHERE id <> ?1", [made.value.id]);
433 if (grant) setGrants(standIn.app.db, standIn.repo.id, standIn.bot.id, [made.value.id]);
434 await use({ standIn, heard, subq: made.value.id });
435 } finally {
436 await stopStandInCrew(standIn);
437 srv.stop(true);
438 }
439 }
440 const assign = ({ app: forge, alice: owner, bot, repo }: StandInCrew, title: string): string => {
441 const issue = openIssue(forge, owner, repo, { title, body: "anything" });
442 if (!issue.ok) throw new Error(String(issue.error));
443 expect(assignIssue(forge, owner, repo, issue.value, bot).ok).toBe(true);
444 return issue.value.id;
445 };
446
447 test("a 401 rests the account and the next pick is the forge's own: the same task goes on there, with no session carried over, and the key is in no log", async () => {
448 process.env["FORGE_AGENT_CONFIG_DIR"] = dir;
449 await onSubQ(
450 () => new Response(`bad key ${SUBQ}: rate limit`, { status: 401 }),
451 async ({ standIn, heard }) => {
452 const issueId = assign(standIn, "On SubQ");
453 const { app: forge, repo } = standIn;
454 const first = await agentRunSettled(forge, repo, (r) => r.issueId === issueId && r.attempt === 0);
455 const log = readRunLog(standIn.dataDir, first.id).lines.join("\n");
456 expect(log).toContain("subscription: SubQ");
457 expect(log).toContain("SubQ (subq-savant-1.4) did not finish");
458 expect(log).not.toContain(SUBQ);
459 expect(heard).toHaveLength(1);
460 expect(heard[0]).toMatchObject({ auth: `Bearer ${SUBQ}`, model: "subq-savant-1.4" });
461 const rests = getSubscriptionByName(forge.db, "SubQ")!;
462 expect(rests.restingUntil).not.toBeNull();
463 expect(rests.restingSaid).toContain("HTTP 401");
464 expect(rests.restingSaid).not.toContain(SUBQ);
465 expect(isOpenAISession(first.sessionId)).toBe(true);
466 // Handed over at once, not in 15 minutes: the account rests, so it is not asked again.
467 expect(first.summary).toContain("the forge's own token takes over");
468 const next = await agentRunSettled(forge, repo, (r) => r.issueId === issueId && r.attempt === 1);
469 expect(readRunLog(standIn.dataDir, next.id).lines.join("\n")).toContain("subscription: platform (env)");
470 expect(heard).toHaveLength(1);
471 const argv = readFileSync(standIn.argsFile, "utf8");
472 expect(argv).not.toContain("--resume");
473 expect(readFileSync(standIn.promptFile, "utf8")).not.toContain("This is the same session");
474 },
475 ).finally(() => delete process.env["FORGE_AGENT_CONFIG_DIR"]);
476 }, 90_000);
477
478 test("the week's hold, through the pump: a plan at 95% holds a run with no grant; the grant starts it, on the connection and never the plan", async () => {
479 await onSubQ(
480 () => new Response("no", { status: 401 }),
481 async ({ standIn, heard, subq }) => {
482 const { app: forge, alice: owner, bot, repo } = standIn;
483 const plan = addSubscription(forge.db, standIn.dataDir, { name: "Plan", token: PLAN, createdBy: owner.id });
484 if (!plan.ok) throw new Error(plan.error);
485 // The plan would go first by rank: only the hold spares it. 95% used is past the crew's 90%, and short of full.
486 forge.db.run("UPDATE subscription SET rank = 0");
487 setCapacity(forge.db, "week.use", "90", owner.id, "for the test");
488 noteMeasure(forge.db, plan.value.id, { window: "week", usedPct: 95, resetsAt: new Date(Date.now() + 3 * 86_400_000).toISOString(), observedAt: new Date().toISOString() });
489 const on = await updateRepoSettings(forge, owner, repo, { autonomy: "autonomous", autonomyDirection: "Keep the garden." });
490 expect(on.ok).toBe(true);
491 forgetWeek();
492 const issueId = assign(standIn, "Past the week");
493 // The other two gates on the way to a run: the queue's, and the pace a new pick takes.
494 const agent = getAgent(forge.db, bot.id)!;
495 const asked = openIssue(forge, owner, repo, { title: "Another", body: "b" });
496 if (!asked.ok) throw new Error(String(asked.error));
497 const now = (): NonNullable<ReturnType<typeof getRepoById>> => getRepoById(forge.db, repo.id)!;
498 // A conflict run: one the week's share gates, and nothing else here refuses.
499 const ask = () => queueAgentRun(forge, now(), asked.value, agent, "conflict", undefined, { notBefore: new Date(Date.now() + 3_600_000).toISOString(), attempt: 0, summary: "for the test" });
500 expect(repoPace(forge, now()).slots).toBe(0);
501 expect(ask()).toBeUndefined();
502 const held = (): string => listRuns(forge.db, repo.id, { kind: "agent" }).filter((r) => r.issueId === issueId).map((r) => readRunLog(standIn.dataDir, r.id).lines.join("\n")).join("\n");
503 expect(await waitFor(() => held().includes("queued, not started: 95% of the week used"), { within: 20_000 })).toBe(true);
504 expect(heard).toHaveLength(0);
505 setGrants(forge.db, repo.id, bot.id, [subq]);
506 expect(repoPace(forge, now()).slots).toBeGreaterThan(0);
507 expect(ask()).toBeDefined();
508 expect(await waitFor(() => heard.length > 0, { within: 20_000 })).toBe(true);
509 expect(held()).toContain("subscription: SubQ");
510 expect(held()).not.toContain("subscription: Plan");
511 },
512 false,
513 );
514 }, 90_000);
515
516 test("what the run is handed: its own account and no key in its environment, no session of Claude's, and the passed-over connection named in the log", async () => {
517 const runs: AgentRun[] = [];
518 const spy: AgentRunner = {
519 detect: async () => ({ ok: true, version: "spy" }),
520 run: async (run) => {
521 runs.push(run);
522 // A network error: the same run is asked again, as a session would be resumed.
523 const lost = runs.length === 1;
524 return { ok: !lost, sessionId: "openai-1", result: lost ? "ECONNRESET" : "nothing to do", costUsd: 0, turns: 1, tokensIn: 0, tokensOut: 0, contextTokens: 0, contextWindow: 0, reason: lost ? "error" : "completed" };
525 },
526 };
527 await onSubQ(
528 () => new Response("unused", { status: 500 }),
529 async ({ standIn, subq }) => {
530 const { app: forge, alice: owner, bot, repo } = standIn;
531 const empty = saveConnection(forge.db, standIn.dataDir, { name: "Empty", protocol: "openai", base: "https://empty.example/v1", key: "k-empty", scope: "forge", userId: owner.id, models: [], said: "" });
532 if (!empty.ok) throw new Error(empty.error);
533 setGrants(forge.db, repo.id, bot.id, [empty.value.id, subq]);
534 useRunner(spy);
535 try {
536 const issueId = assign(standIn, "Handed over");
537 const run = await agentRunSettled(forge, repo, (r) => r.issueId === issueId);
538 expect(readRunLog(standIn.dataDir, run.id).lines.join("\n")).toContain("Empty: no usable model, passed over; choose one at /settings/model");
539 } finally {
540 useRunner(undefined);
541 }
542 },
543 false,
544 );
545 expect(runs).toHaveLength(2);
546 for (const run of runs) {
547 expect(run.account).toMatchObject({ token: SUBQ, connection: { guarded: false } });
548 expect(run.model).toBe("subq-savant-1.4");
549 expect(run.resume).toBeUndefined();
550 expect(Object.values(run.env)).not.toContain(SUBQ);
551 expect(Object.keys(run.env).filter((k) => k.startsWith("ANTHROPIC_") || k.startsWith("OPENAI_"))).toEqual([]);
552 }
553 // The second ask keeps no session, so it is told the task again and where its work is.
554 expect(runs[1]!.prompt).toStartWith(runs[0]!.prompt);
555 expect(runs[1]!.prompt).toContain("remember none of it");
556 }, 60_000);
test/openai-runner.test.ts +2 −2
@@ -123,9 +123,9 @@ const say = (message: object) => Response.json({ choices: [{ message }], usage:
123123
124124 test("a 429 is rate_limited with the endpoint's words, any other failure is an error", async () => {
125125 const cwd = mkdtempSync(join(tmpdir(), "oai-"));
126 const limited = await withEndpoint(() => new Response("slow down", { status: 429 }), (env) => runOpenAI(runIn(cwd), env));
126 const limited = await withEndpoint(() => new Response("slow down", { status: 429 }), (env) => runOpenAI(runIn(cwd), env, {}, []));
127127 expect(limited).toMatchObject({ ok: false, reason: "rate_limited", result: "endpoint answered 429: slow down" });
128 const broken = await withEndpoint(() => new Response("boom", { status: 500 }), (env) => runOpenAI(runIn(cwd), env));
128 const broken = await withEndpoint(() => new Response("boom", { status: 500 }), (env) => runOpenAI(runIn(cwd), env, {}, []));
129129 expect(broken).toMatchObject({ ok: false, reason: "error" });
130130 });
131131

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs