@foldrun/core 12.2.0 → 13.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -113,6 +113,9 @@ export interface EgressHooks {
113
113
  * `delegates` — the `sandbox: own` sub-agents this step may hand a job
114
114
  * to over the delegate door (delegate-tools.ts); the proxy refuses any
115
115
  * other name. */
116
+ /** `job` — a lease for a host-side model call (an eval's judge, a
117
+ * grader, a draft, the assistant) rather than a step: what the model
118
+ * gateway records the call against. */
116
119
  lease(args: {
117
120
  tenant: string;
118
121
  runId: string;
@@ -123,6 +126,10 @@ export interface EgressHooks {
123
126
  peers?: PeerInfo[];
124
127
  who?: LeaseWho;
125
128
  delegates?: string[];
129
+ job?: {
130
+ kind: "grade" | "judge" | "draft" | "assistant";
131
+ name?: string;
132
+ };
126
133
  }): Promise<EgressLease | null>;
127
134
  /** The run is still being driven: renew its leases' heartbeat. Optional —
128
135
  * an install without leases has nothing to renew. */
@@ -170,6 +177,10 @@ export declare const HOP_BY_HOP: Set<string>;
170
177
  * Adds the grants it needs to `grant`. Pure apart from that.
171
178
  */
172
179
  export declare function proxyModelEnv(env: Record<string, string | undefined>, leaseUrl: string, grant: EgressGrant, knownSecrets?: Record<string, string>, name?: string): Record<string, string | undefined>;
180
+ /** Grant a model credential under `name`: the platform's key when `value`
181
+ * is a supply marker (foldrun's models — the proxy fills it and meters
182
+ * the call), else the value itself. */
183
+ export declare function grantModelKey(grant: EgressGrant, name: string, value: string, host: string): void;
173
184
  /** Put the `${NAME}` back where a known secret's value sits in `text`,
174
185
  * granting the name to `host`. Longest values first, so one that contains
175
186
  * another is replaced whole. */
@@ -42,6 +42,7 @@
42
42
  // This file is the vocabulary both sides share. The server is the
43
43
  // platform's (it needs a long-lived process and a Service); the pod side is
44
44
  // here in core, because it is what the runner image runs.
45
+ import { supplyProviderOfToken } from "./model-supply.js";
45
46
  import { trimSlashes } from "./paths.js";
46
47
  /** `${NAME}` — the shape a secret reference takes everywhere in foldrun. */
47
48
  export const PLACEHOLDER = /\$\{([A-Z][A-Z0-9_]*)\}/g;
@@ -107,7 +108,7 @@ export function proxyModelEnv(env, leaseUrl, grant, knownSecrets = {}, name = MO
107
108
  for (const key of credentialKeys) {
108
109
  const value = env[key];
109
110
  if (typeof value === "string" && value.length) {
110
- addGrant(grant, name, value, host);
111
+ grantModelKey(grant, name, value, host);
111
112
  out[key] = `\${${name}}`;
112
113
  }
113
114
  }
@@ -116,6 +117,16 @@ export function proxyModelEnv(env, leaseUrl, grant, knownSecrets = {}, name = MO
116
117
  }
117
118
  return out;
118
119
  }
120
+ /** Grant a model credential under `name`: the platform's key when `value`
121
+ * is a supply marker (foldrun's models — the proxy fills it and meters
122
+ * the call), else the value itself. */
123
+ export function grantModelKey(grant, name, value, host) {
124
+ const supply = supplyProviderOfToken(value);
125
+ if (supply)
126
+ addSupplyGrant(grant, name, supply, host);
127
+ else
128
+ addGrant(grant, name, value, host);
129
+ }
119
130
  /** Put the `${NAME}` back where a known secret's value sits in `text`,
120
131
  * granting the name to `host`. Longest values first, so one that contains
121
132
  * another is replaced whole. */
@@ -161,7 +161,7 @@ export async function gradeRun(tenant, workspace, info, run, opts = {}) {
161
161
  for (const a of judges) {
162
162
  try {
163
163
  const m = accountModelEnv(tenant, workspace, judgeProcessEnv);
164
- const said = await withModelEnv(m, (env) => ask(a.value, output, info.model, info.effort, env, task));
164
+ const said = await withModelEnv(m, (env) => ask(a.value, output, info.model, info.effort, env, task), { kind: "grade", name: info.name });
165
165
  costUsd += said.costUsd;
166
166
  const v = judgeVerdict(said.text);
167
167
  if (v.decided === false) {
@@ -14,9 +14,13 @@ export declare const NO_MODEL_KEY: string;
14
14
  */
15
15
  export declare function accountModelEnv(tenant: string, workspace: string, platformEnv: () => Record<string, string | undefined>): {
16
16
  env: Record<string, string | undefined>;
17
- supply: "provider" | "platform";
17
+ /** "foldrun": the platform's key for a provider the account chose —
18
+ * withModelEnv sends it through the egress proxy, which meters and bills
19
+ * each call; the caller charges nothing for it itself. */
20
+ supply: "provider" | "platform" | "foldrun";
18
21
  format: string;
19
22
  translator: TranslatorSpec | null;
23
+ tenant?: string;
20
24
  };
21
25
  /**
22
26
  * Run `fn` with the model env, through a translator on this host — the one a
@@ -30,8 +34,15 @@ export declare function accountModelEnv(tenant: string, workspace: string, platf
30
34
  export declare function withModelEnv<T>(m: {
31
35
  env: Record<string, string | undefined>;
32
36
  translator?: TranslatorSpec | null;
33
- supply?: "provider" | "platform";
34
- }, fn: (env: Record<string, string | undefined>) => Promise<T>): Promise<T>;
37
+ supply?: "provider" | "platform" | "foldrun";
38
+ tenant?: string;
39
+ }, fn: (env: Record<string, string | undefined>) => Promise<T>,
40
+ /** What is asking, for the gateway's record of a foldrun's-models call. */
41
+ job?: {
42
+ kind: HostJobKind;
43
+ name?: string;
44
+ }): Promise<T>;
45
+ export type HostJobKind = "grade" | "judge" | "draft" | "assistant";
35
46
  /** The passthrough for an Anthropic-format provider, read back from the env
36
47
  * providerEnvFor (store.ts) built for it: the base URL, the key in the slot
37
48
  * that names its header, and ANTHROPIC_CUSTOM_HEADERS. Null with no base. */
@@ -12,6 +12,8 @@ import { platform, hostUrlProblem } from "./platform.js";
12
12
  import { accountModelBlock, isClaudeLoginToken } from "./model-credential.js";
13
13
  import { providerPreset } from "./providers.js";
14
14
  import { startTranslator, translatorSpecFor } from "./translator.js";
15
+ import { supplyProviderBlock } from "./model-supply.js";
16
+ import { MODEL_KEY_NAME, grantModelKey, hostOf } from "./egress.js";
15
17
  /** Refused for want of a usable key; `status` is what an HTTP layer answers. */
16
18
  export class ModelKeyError extends Error {
17
19
  status;
@@ -30,9 +32,35 @@ export const NO_MODEL_KEY = "no model key: this account runs on its own API key,
30
32
  * it, so a judge or a draft works on any key a run works on (FOL-16).
31
33
  */
32
34
  export function accountModelEnv(tenant, workspace, platformEnv) {
33
- const raw = readAgentsMd(workspaceDir(tenant, workspace))?.data?.provider ??
34
- readAgentsMd(accountDir(tenant))?.data?.provider ??
35
- accountModelBlock((name) => getSecret(tenant, name)?.value ?? null);
35
+ const written = readAgentsMd(workspaceDir(tenant, workspace))?.data?.provider ??
36
+ readAgentsMd(accountDir(tenant))?.data?.provider;
37
+ // foldrun's models, the same rung a step takes (runner.ts agentContext):
38
+ // after the written blocks, before the account's stored key; chosen but
39
+ // refused fails here, never onto the stored key or the operator's.
40
+ const supply = written ? { kind: "none" } : platform.modelSupply?.(tenant) ?? { kind: "none" };
41
+ if (supply.kind === "refused")
42
+ throw new ModelKeyError(`foldrun's models: ${supply.reason}`, 403);
43
+ if (supply.kind === "foldrun") {
44
+ const s = parseProvider(supplyProviderBlock(supply.provider, supply.tiers));
45
+ const preset = providerPreset(s.name);
46
+ return {
47
+ env: providerEnvFor({ baseUrl: s.baseUrl, token: s.token, auth: s.auth, models: s.models, headers: {} }),
48
+ supply: "foldrun",
49
+ format: s.format,
50
+ translator: translatorSpecFor({
51
+ format: s.format,
52
+ baseUrl: s.baseUrl,
53
+ token: s.token,
54
+ headers: {},
55
+ params: s.params,
56
+ name: s.name,
57
+ maxTokensParam: preset?.maxTokensParam,
58
+ reasoningEffort: preset?.reasoningEffort,
59
+ }),
60
+ tenant,
61
+ };
62
+ }
63
+ const raw = written ?? accountModelBlock((name) => getSecret(tenant, name)?.value ?? null);
36
64
  const spec = parseProvider(raw);
37
65
  if (!spec?.baseUrl) {
38
66
  if (!platform.platformKeyAllowed(tenant))
@@ -80,7 +108,11 @@ export function accountModelEnv(tenant, workspace, platformEnv) {
80
108
  * The platform's own credential (`supply: "platform"`) goes as it always did.
81
109
  * Started for this call and closed after it.
82
110
  */
83
- export async function withModelEnv(m, fn) {
111
+ export async function withModelEnv(m, fn,
112
+ /** What is asking, for the gateway's record of a foldrun's-models call. */
113
+ job = { kind: "judge" }) {
114
+ if (m.supply === "foldrun")
115
+ return withSupply(m, fn, job);
84
116
  const spec = m.translator ?? (m.supply === "provider" ? anthropicPassthrough(m.env) : null);
85
117
  if (!spec)
86
118
  return fn(m.env);
@@ -95,6 +127,31 @@ export async function withModelEnv(m, fn) {
95
127
  await t.close();
96
128
  }
97
129
  }
130
+ /**
131
+ * A host-side call on foldrun's models (an eval's judge, a grader, a draft):
132
+ * through a short lease on the egress proxy, like a step's — the platform's
133
+ * key is filled there and every call metered and billed by the gateway. No
134
+ * proxy: refused, never sent with the key from here.
135
+ */
136
+ async function withSupply(m, fn, job) {
137
+ const spec = m.translator ?? anthropicPassthrough(m.env);
138
+ const host = spec ? hostOf(spec.upstreamBase) : null;
139
+ if (!spec || !host || !m.tenant)
140
+ throw new ModelKeyError("foldrun's models: no endpoint for this call", 500);
141
+ const grant = { secrets: {} };
142
+ grantModelKey(grant, MODEL_KEY_NAME, spec.upstreamKey, host);
143
+ const lease = await platform.egress.lease({ tenant: m.tenant, runId: `${job.kind}:${job.name ?? "-"}`, grant, job });
144
+ if (!lease)
145
+ throw new ModelKeyError("foldrun's models need the platform's egress proxy, and this install has none", 503);
146
+ const t = await startTranslator({ ...spec, egress: lease.url, upstreamKey: `\${${MODEL_KEY_NAME}}` });
147
+ try {
148
+ return await fn({ ...m.env, ...t.env });
149
+ }
150
+ finally {
151
+ await t.close();
152
+ await lease.release().catch(() => { });
153
+ }
154
+ }
98
155
  /** The passthrough for an Anthropic-format provider, read back from the env
99
156
  * providerEnvFor (store.ts) built for it: the base URL, the key in the slot
100
157
  * that names its header, and ANTHROPIC_CUSTOM_HEADERS. Null with no base. */
@@ -25,9 +25,33 @@ export interface SupplyProvider {
25
25
  }
26
26
  export declare const SUPPLY_PROVIDERS: Record<SupplyProviderName, SupplyProvider>;
27
27
  export declare const SUPPLY_PROVIDER_NAMES: SupplyProviderName[];
28
+ /** How each reads to a person: on a step's credential line, in Settings. */
29
+ export declare const SUPPLY_TITLES: Record<SupplyProviderName, string>;
28
30
  export declare function isSupplyProvider(name: unknown): name is SupplyProviderName;
29
31
  /** The placeholder name a supply grant is filed under in a step's lease. */
30
32
  export declare const SUPPLY_KEY_NAME = "FOLDRUN_SUPPLY_KEY";
33
+ /**
34
+ * What the platform says about one account's model supply, before any
35
+ * provider: block of its own is considered (a written block always wins):
36
+ * none — it did not choose foldrun's models: its own key, as before
37
+ * foldrun — it chose them and they are on: run on the platform's key
38
+ * refused — it chose them and they cannot be had now (switched off, the
39
+ * provider withdrawn, the account refused). The step FAILS
40
+ * with the reason: never quietly onto the account's stored
41
+ * key, and never onto the operator's.
42
+ */
43
+ export type SupplyAnswer = {
44
+ kind: "none";
45
+ } | {
46
+ kind: "foldrun";
47
+ provider: SupplyProviderName;
48
+ tiers: Partial<Record<"fast" | "default" | "max", string>>;
49
+ } | {
50
+ kind: "refused";
51
+ reason: string;
52
+ };
53
+ export declare const supplyToken: (provider: SupplyProviderName) => string;
54
+ export declare function supplyProviderOfToken(value: string | null | undefined): SupplyProviderName | null;
31
55
  /** The provider block a step on foldrun's models runs with: the preset's
32
56
  * endpoint and format, the operator's tier map, and the key as a
33
57
  * placeholder only. */
@@ -58,11 +58,30 @@ export const SUPPLY_PROVIDERS = {
58
58
  },
59
59
  };
60
60
  export const SUPPLY_PROVIDER_NAMES = Object.keys(SUPPLY_PROVIDERS);
61
+ /** How each reads to a person: on a step's credential line, in Settings. */
62
+ export const SUPPLY_TITLES = {
63
+ anthropic: "Anthropic",
64
+ openai: "OpenAI",
65
+ gemini: "Google Gemini",
66
+ openrouter: "OpenRouter",
67
+ };
61
68
  export function isSupplyProvider(name) {
62
69
  return typeof name === "string" && Object.hasOwn(SUPPLY_PROVIDERS, name);
63
70
  }
64
71
  /** The placeholder name a supply grant is filed under in a step's lease. */
65
72
  export const SUPPLY_KEY_NAME = "FOLDRUN_SUPPLY_KEY";
73
+ /** The token a supply provider block carries: a marker, not a secret. The
74
+ * proxy grant built from it is a supply grant (egress.ts grantModelKey),
75
+ * which the proxy fills with the platform's key. Sent anywhere unproxied
76
+ * it is only a word a provider refuses. */
77
+ const MARKER = "foldrun-supply:";
78
+ export const supplyToken = (provider) => `${MARKER}${provider}`;
79
+ export function supplyProviderOfToken(value) {
80
+ if (typeof value !== "string" || !value.startsWith(MARKER))
81
+ return null;
82
+ const p = value.slice(MARKER.length);
83
+ return isSupplyProvider(p) ? p : null;
84
+ }
66
85
  /** The provider block a step on foldrun's models runs with: the preset's
67
86
  * endpoint and format, the operator's tier map, and the key as a
68
87
  * placeholder only. */
@@ -75,7 +94,7 @@ export function supplyProviderBlock(provider, tiers) {
75
94
  name: p.preset,
76
95
  base_url: preset.baseUrl,
77
96
  format: p.format,
78
- token: `\${${SUPPLY_KEY_NAME}}`,
97
+ token: supplyToken(provider),
79
98
  ...(Object.keys(tiers).length ? { models: tiers } : {}),
80
99
  };
81
100
  }
@@ -1,3 +1,4 @@
1
+ import type { SupplyAnswer } from "./model-supply.ts";
1
2
  import type { FlowInfo, FlowStep, RunRecord } from "./store.ts";
2
3
  import type { RunInContainerArgs, ContainerStepOutcome } from "./run-container.ts";
3
4
  import type { EgressHooks } from "./egress.ts";
@@ -142,6 +143,11 @@ export interface PlatformHooks {
142
143
  * operator's accounts do so; every customer brings their own API key.
143
144
  * Default: yes — a laptop or a self-hosted install is its own operator. */
144
145
  platformKeyAllowed(tenant: string): boolean;
146
+ /** foldrun's models (3 Nov 2026): whether this account chose to run on
147
+ * the platform's own key for a provider, and whether it can now. Asked
148
+ * only where no provider: block of the account's own says otherwise.
149
+ * Absent: nobody can (a laptop, a self-hosted install). */
150
+ modelSupply?(tenant: string): SupplyAnswer;
145
151
  /**
146
152
  * An operator setting, by the environment variable that used to hold it
147
153
  * (30 Oct 2026): the platform answers with the operator's value where one
@@ -1,3 +1,4 @@
1
+ import { type SupplyAnswer } from "./model-supply.ts";
1
2
  import { type DelegateSpec, type SubagentSpec } from "./subagents.ts";
2
3
  import { type FlowStep, type RunRecord, type StepRecord } from "./store.ts";
3
4
  import { type Catalog } from "./catalog.ts";
@@ -315,6 +316,8 @@ grantsOnly?: boolean): {
315
316
  FOLDRUN_BROWSER_VIDEO?: string | undefined;
316
317
  FOLDRUN_BROWSER_LIVE_VIEW?: string | undefined;
317
318
  };
319
+ /** foldrun's models: what the platform said for this account. */
320
+ supply: SupplyAnswer;
318
321
  /** The zone, where it came from, and anything unreadable on the way —
319
322
  * reported by the step, not here, so it lands in the run's trace. */
320
323
  clock: ClockChoice;
@@ -23,7 +23,8 @@ import { hostSafeEnv, platformApiUrl } from "./host-env.js";
23
23
  import { resolveModelCredential, credentialLine, accountModelBlock, isClaudeLoginToken, isModelEnvName, DECLARED_ENV_PREFIX } from "./model-credential.js";
24
24
  import { parseJudge } from "./judge-verdict.js";
25
25
  import { validateSchema, describeSchemaErrors, looksLikeSchema } from "./json-schema.js";
26
- import { EGRESS_ENV, MODEL_KEY_NAME, addGrant, hostOf, placeholderNames, proxyModelEnv, unsubstitute } from "./egress.js";
26
+ import { EGRESS_ENV, MODEL_KEY_NAME, addGrant, grantModelKey, hostOf, placeholderNames, proxyModelEnv, unsubstitute } from "./egress.js";
27
+ import { SUPPLY_TITLES, supplyProviderBlock } from "./model-supply.js";
27
28
  import { explainRefusal, isRefusalStatus, refusalFromLine, supplyNote } from "./refusal.js";
28
29
  import { platform } from "./platform.js";
29
30
  import { healthKey } from "./secret-health.js";
@@ -1209,7 +1210,17 @@ grantsOnly = false) {
1209
1210
  // Then the account's own model key (Settings → Model), when it set one:
1210
1211
  // an account that brings its key need not write a block anywhere.
1211
1212
  const fileBlock = front.provider ?? workspaceFrontmatter(agentDir, tenant).provider;
1212
- const providerBlock = fileBlock ?? accountModelBlock((name) => getSecret(tenant, name)?.value ?? null);
1213
+ // foldrun's models (3 Nov 2026): an account that chose the platform's key
1214
+ // for a provider runs on it here, between its written blocks (which still
1215
+ // win) and its stored key. Chosen but not to be had now — refused, and
1216
+ // the step fails with why (runStep); it never falls to the stored key.
1217
+ const supply = fileBlock ? { kind: "none" } : platform.modelSupply?.(tenant) ?? { kind: "none" };
1218
+ const providerBlock = fileBlock ??
1219
+ (supply.kind === "foldrun"
1220
+ ? supplyProviderBlock(supply.provider, supply.tiers)
1221
+ : supply.kind === "refused"
1222
+ ? undefined
1223
+ : accountModelBlock((name) => getSecret(tenant, name)?.value ?? null));
1213
1224
  let providerEnv = {};
1214
1225
  let providerLabel = null;
1215
1226
  // Secret values pulled into the provider block, name → value. Kept apart
@@ -1669,6 +1680,8 @@ grantsOnly = false) {
1669
1680
  return {
1670
1681
  front,
1671
1682
  clockEnv,
1683
+ /** foldrun's models: what the platform said for this account. */
1684
+ supply,
1672
1685
  /** The zone, where it came from, and anything unreadable on the way —
1673
1686
  * reported by the step, not here, so it lands in the run's trace. */
1674
1687
  clock,
@@ -1835,7 +1848,7 @@ reattach = false) {
1835
1848
  };
1836
1849
  // A slim go the browser pod was lost under, before this attempt re-ran
1837
1850
  // on the full image: its own row, first (runStep set it aside).
1838
- const lost = step.podLostTry ? [{ ...numbered(), ...step.podLostTry, startedAt }] : [];
1851
+ const lost = step.podLostTry ? [{ ...numbered(), ...step.podLostTry, startedAt, ...(step.supply ? { supply: step.supply } : {}) }] : [];
1839
1852
  const row = {
1840
1853
  ...numbered(),
1841
1854
  status,
@@ -1843,6 +1856,7 @@ reattach = false) {
1843
1856
  tokens: step.tokens ?? null,
1844
1857
  ...(typeof step.turns === "number" ? { turns: step.turns } : {}),
1845
1858
  computeSecs: step.computeSecs ?? null,
1859
+ ...(step.supply ? { supply: step.supply } : {}),
1846
1860
  startedAt: step.podLostTry?.finishedAt ?? startedAt,
1847
1861
  finishedAt: step.finishedAt ?? new Date().toISOString(),
1848
1862
  ...(status === "failed" && lastError ? { error: lastError.slice(0, 500) } : {}),
@@ -2156,7 +2170,7 @@ mayDefer) {
2156
2170
  // step: the generic HTTP tool still works without the typed ones.
2157
2171
  for (const w of await prefetchOpenApi(tenant, openApiSources(agentDir, tenant)))
2158
2172
  push("error", `openapi: ${w}`);
2159
- const { front, clockEnv, clock, systemPrompt, promptLayers, allowed, disabled, apiTools, scriptTools, secretEnv, secretScopes, missingSecrets, missingTools, runtime, unknownTools, shadowed, legacyUse, retiredTools, mcpServers, mcpNames, apiSpecs, scriptSpecs, brokenTools, size: agentSize, remotes, remoteOnlySecrets, remoteSecretEnv, providerEnv, providerLabel, providerSecrets, providerWarnings, formatWarning, searchChoice, fetchChoice, actionChoices, web, language, region, fallbackEnv, apiWarnings, searchRoots, historyDigest, deskDigest, searchTools, historyTools, deskTools, ask, peers, translator, fallbackTranslator, outward, } = agentContext(agentDir, tenant, tags, { runId, agent: step.agent }, flowTimezone);
2173
+ const { front, clockEnv, clock, systemPrompt, promptLayers, allowed, disabled, apiTools, scriptTools, secretEnv, secretScopes, missingSecrets, missingTools, runtime, unknownTools, shadowed, legacyUse, retiredTools, mcpServers, mcpNames, apiSpecs, scriptSpecs, brokenTools, size: agentSize, remotes, remoteOnlySecrets, remoteSecretEnv, providerEnv, providerLabel, providerSecrets, providerWarnings, formatWarning, searchChoice, fetchChoice, actionChoices, web, language, region, fallbackEnv, apiWarnings, searchRoots, historyDigest, deskDigest, searchTools, historyTools, deskTools, ask, peers, translator, fallbackTranslator, outward, supply, } = agentContext(agentDir, tenant, tags, { runId, agent: step.agent }, flowTimezone);
2160
2174
  disposeRuntime = runtime.dispose;
2161
2175
  canActOutward = outward;
2162
2176
  // Sent again on every turn; with turns and the tools' result sizes, what
@@ -2265,7 +2279,37 @@ mayDefer) {
2265
2279
  const primaryOnPlatform = Object.keys(providerEnv).length === 0;
2266
2280
  const noKey = primaryOnPlatform && !platform.platformKeyAllowed(tenant);
2267
2281
  const credential = !primaryOnPlatform || noKey ? null : resolveModelCredential(isolatedRun() ? platformModelEnv() : process.env);
2268
- step.credential = credential ? credential.label : noKey ? "none — this account has no model key" : `provider: ${providerLabel}`;
2282
+ const onSupply = supply.kind === "foldrun" && !primaryOnPlatform;
2283
+ // Attempts recorded before supply was (older records) are stamped with
2284
+ // the one their credential said, before this attempt overwrites it: a
2285
+ // retry on another supply must not reclassify what they spent.
2286
+ const before = (step.credential ?? "").startsWith("provider:") ? "own" : "operator";
2287
+ for (const t of step.tries ?? [])
2288
+ t.supply ??= before;
2289
+ step.credential = onSupply
2290
+ ? `foldrun models · ${SUPPLY_TITLES[supply.provider]}`
2291
+ : credential ? credential.label : noKey ? "none — this account has no model key" : `provider: ${providerLabel}`;
2292
+ step.supply = onSupply ? "foldrun" : primaryOnPlatform ? "operator" : "own";
2293
+ if (onSupply)
2294
+ step.supplyProvider = supply.provider;
2295
+ else
2296
+ delete step.supplyProvider;
2297
+ // Chosen, but not to be had now: failed with why, before a sandbox —
2298
+ // never onto the account's stored key or the operator's.
2299
+ if (supply.kind === "refused") {
2300
+ push("error", `foldrun's models: ${supply.reason} — or switch this account back to its own key (Settings → Model, \`foldrun account model use own\`)`);
2301
+ step.status = "failed";
2302
+ save();
2303
+ return;
2304
+ }
2305
+ // The platform's key only ever crosses the egress proxy, which meters
2306
+ // every call: a step that would run without one is refused.
2307
+ if (onSupply && !isolatedRun()) {
2308
+ push("error", "foldrun's models run only in the platform's sandbox, where every call is metered — this step would run here, so it is refused");
2309
+ step.status = "failed";
2310
+ save();
2311
+ return;
2312
+ }
2269
2313
  // Core's own Docker container has no login to fall back to (below):
2270
2314
  // there, "none set" is refused with what to do, not described.
2271
2315
  const noCredentialInContainer = credential?.kind === "none" && process.env.FOLDRUN_RUN_ISOLATION === "container";
@@ -2760,6 +2804,15 @@ mayDefer) {
2760
2804
  // sandbox: own sub-agents: the only names the delegate door takes.
2761
2805
  ...(delegates.length ? { delegates: delegates.map((d) => d.name) } : {}),
2762
2806
  });
2807
+ // foldrun's models need the proxy: it holds the platform's key and
2808
+ // meters each call. No lease (no FOLDRUN_EGRESS_URL) — refused, and
2809
+ // nothing is sent; the marker token alone would only be refused.
2810
+ if (step.supply === "foldrun" && !lease) {
2811
+ push("error", "foldrun's models need the platform's egress proxy, and this step has none — refused before it ran");
2812
+ step.status = "failed";
2813
+ save();
2814
+ return;
2815
+ }
2763
2816
  // Serve those jobs while this step runs: each one becomes a step of
2764
2817
  // its own (delegateJob), and the door answers the long-poll with its
2765
2818
  // reply. No proxy, or a platform without the door: not offered — the
@@ -2932,7 +2985,7 @@ mayDefer) {
2932
2985
  const host = hostOf(spec.upstreamBase);
2933
2986
  if (!host)
2934
2987
  return spec;
2935
- addGrant(grant, name, spec.upstreamKey, host);
2988
+ grantModelKey(grant, name, spec.upstreamKey, host);
2936
2989
  return {
2937
2990
  ...spec,
2938
2991
  egress: lease.url,
@@ -1095,6 +1095,9 @@ export interface StepAttempt {
1095
1095
  status: "completed" | "failed" | "lost";
1096
1096
  costUsd: number | null;
1097
1097
  tokens: TokenUsage | null;
1098
+ /** Whose key this attempt ran on (StepRecord.supply): a retry may run on
1099
+ * another, and the meter bills each attempt by its own. */
1100
+ supply?: StepSupply;
1098
1101
  /** Model turns this attempt took; absent before 18 Oct 2026. */
1099
1102
  turns?: number | null;
1100
1103
  computeSecs: number | null;
@@ -1207,6 +1210,14 @@ export interface StepRecord {
1207
1210
  * (ANTHROPIC_API_KEY)", "Claude login token (CLAUDE_CODE_OAUTH_TOKEN)",
1208
1211
  * "provider: …" — or "none set" (model-credential.ts). */
1209
1212
  credential?: string;
1213
+ /** Whose key paid for the step's model calls (3 Nov 2026): "own" — the
1214
+ * account's (a provider: block, Settings → Model), billed by its
1215
+ * provider; "operator" — the platform's own credential, billed from the
1216
+ * step's tokens; "foldrun" — foldrun's models, billed per call by the
1217
+ * model gateway, never from the step. Absent on older records. */
1218
+ supply?: StepSupply;
1219
+ /** With supply "foldrun": which provider's key. */
1220
+ supplyProvider?: string;
1210
1221
  /** Slim browsing through the account's pod (browser-pod.ts): reconnect
1211
1222
  * tries and how many got through; when the pod was lost, why and what
1212
1223
  * the step had written by then; and what happened — `fallback` (the
@@ -1710,7 +1721,20 @@ export declare function runCost(run: RunRecord): number;
1710
1721
  * a provider: block, or Settings → Model), which the provider bills. The
1711
1722
  * meter, the Usage page and the ledger split all ask this one question, so
1712
1723
  * what a page shows is what was charged. */
1713
- export declare function stepBillsTokens(s: Pick<StepRecord, "credential">): boolean;
1724
+ export declare function stepBillsTokens(s: Pick<StepRecord, "credential" | "supply">): boolean;
1725
+ export type StepSupply = "own" | "operator" | "foldrun";
1726
+ /** Only the operator's credential is billed from what a step reports. The
1727
+ * account's own key is its provider's to bill; foldrun's models are billed
1728
+ * per call by the gateway, so billing the step too would charge twice. */
1729
+ export declare const supplyBillsTokens: (supply: StepSupply) => supply is "operator";
1730
+ /** The step's tokens the platform bills, attempt by attempt where the
1731
+ * attempts say whose key they ran on. */
1732
+ export declare function billedTokenCost(s: {
1733
+ credential?: string;
1734
+ supply?: StepSupply;
1735
+ costUsd?: number | null;
1736
+ tries?: StepAttempt[];
1737
+ }): number;
1714
1738
  /**
1715
1739
  * What a finished run consumed, in the units the format itself has — the
1716
1740
  * shape ledger.ts prices. Structural, not an import, because ledger.ts
package/dist/src/store.js CHANGED
@@ -3254,8 +3254,26 @@ export function runCost(run) {
3254
3254
  * meter, the Usage page and the ledger split all ask this one question, so
3255
3255
  * what a page shows is what was charged. */
3256
3256
  export function stepBillsTokens(s) {
3257
+ if (s.supply)
3258
+ return supplyBillsTokens(s.supply);
3257
3259
  return !(s.credential ?? "").startsWith("provider:");
3258
3260
  }
3261
+ /** Only the operator's credential is billed from what a step reports. The
3262
+ * account's own key is its provider's to bill; foldrun's models are billed
3263
+ * per call by the gateway, so billing the step too would charge twice. */
3264
+ export const supplyBillsTokens = (supply) => supply === "operator";
3265
+ /** The step's tokens the platform bills, attempt by attempt where the
3266
+ * attempts say whose key they ran on. */
3267
+ export function billedTokenCost(s) {
3268
+ const tries = s.tries ?? [];
3269
+ if (!tries.some((t) => t.supply))
3270
+ return stepBillsTokens(s) ? s.costUsd ?? 0 : 0;
3271
+ // Each attempt by its own supply — a lost slim go spent its tokens too,
3272
+ // as the step's total says (sumAttempts) — and a row from before the
3273
+ // field by the step's older rule (its credential).
3274
+ const legacy = !(s.credential ?? "").startsWith("provider:");
3275
+ return tries.reduce((n, t) => n + ((t.supply ? supplyBillsTokens(t.supply) : legacy) ? t.costUsd ?? 0 : 0), 0);
3276
+ }
3259
3277
  /**
3260
3278
  * What a finished run consumed, in the units the format itself has — the
3261
3279
  * shape ledger.ts prices. Structural, not an import, because ledger.ts
@@ -3286,8 +3304,7 @@ export function runMeter(run) {
3286
3304
  if (s.carriedFrom)
3287
3305
  continue;
3288
3306
  steps += 1;
3289
- if (stepBillsTokens(s))
3290
- tokenCostUsd += s.costUsd ?? 0;
3307
+ tokenCostUsd += billedTokenCost(s);
3291
3308
  const secs = s.computeSecs ?? 0;
3292
3309
  computeSecs += secs;
3293
3310
  if (s.size === "small")
@@ -1095,7 +1095,12 @@ async function passthrough(spec, base, label, req, url, raw, res, log, started)
1095
1095
  const target = `${base}${url.pathname}${url.search}`;
1096
1096
  let upstream;
1097
1097
  try {
1098
- upstream = await fetchUntrusted(target, { method, headers, body: method === "GET" || method === "HEAD" ? undefined : raw }, { sameOrigin: true, maxBytes: UPSTREAM_MAX_BYTES });
1098
+ const init = { method, headers, body: method === "GET" || method === "HEAD" ? undefined : raw };
1099
+ // Through the lease when there is one (foldrun's models, host-side): the
1100
+ // proxy fills the key and meters the call; the placeholder never leaves.
1101
+ upstream = spec.egress
1102
+ ? await fetch(viaEgress(spec.egress, target), init)
1103
+ : await fetchUntrusted(target, init, { sameOrigin: true, maxBytes: UPSTREAM_MAX_BYTES });
1099
1104
  }
1100
1105
  catch (err) {
1101
1106
  const message = err instanceof Error ? err.message : String(err);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "12.2.0",
3
+ "version": "13.0.0",
4
4
  "description": "Agents are just folders. The format, the runner, the checks.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "type": "module",
package/src/egress.ts CHANGED
@@ -43,6 +43,7 @@
43
43
  // platform's (it needs a long-lived process and a Service); the pod side is
44
44
  // here in core, because it is what the runner image runs.
45
45
 
46
+ import { supplyProviderOfToken } from "./model-supply.ts";
46
47
  import type { DelegationResult, PeerInfo } from "./operator.ts";
47
48
  import { trimSlashes } from "./paths.ts";
48
49
  import type { TestEffect } from "./test-mode.ts";
@@ -175,7 +176,10 @@ export interface EgressHooks {
175
176
  * `delegates` — the `sandbox: own` sub-agents this step may hand a job
176
177
  * to over the delegate door (delegate-tools.ts); the proxy refuses any
177
178
  * other name. */
178
- lease(args: { tenant: string; runId: string; grant: EgressGrant; test?: boolean; step?: number; agent?: string; peers?: PeerInfo[]; who?: LeaseWho; delegates?: string[] }): Promise<EgressLease | null>;
179
+ /** `job` — a lease for a host-side model call (an eval's judge, a
180
+ * grader, a draft, the assistant) rather than a step: what the model
181
+ * gateway records the call against. */
182
+ lease(args: { tenant: string; runId: string; grant: EgressGrant; test?: boolean; step?: number; agent?: string; peers?: PeerInfo[]; who?: LeaseWho; delegates?: string[]; job?: { kind: "grade" | "judge" | "draft" | "assistant"; name?: string } }): Promise<EgressLease | null>;
179
183
  /** The run is still being driven: renew its leases' heartbeat. Optional —
180
184
  * an install without leases has nothing to renew. */
181
185
  renew?(runId: string): Promise<number>;
@@ -236,7 +240,7 @@ export function proxyModelEnv(
236
240
  for (const key of credentialKeys) {
237
241
  const value = env[key];
238
242
  if (typeof value === "string" && value.length) {
239
- addGrant(grant, name, value, host);
243
+ grantModelKey(grant, name, value, host);
240
244
  out[key] = `\${${name}}`;
241
245
  }
242
246
  }
@@ -246,6 +250,15 @@ export function proxyModelEnv(
246
250
  return out;
247
251
  }
248
252
 
253
+ /** Grant a model credential under `name`: the platform's key when `value`
254
+ * is a supply marker (foldrun's models — the proxy fills it and meters
255
+ * the call), else the value itself. */
256
+ export function grantModelKey(grant: EgressGrant, name: string, value: string, host: string): void {
257
+ const supply = supplyProviderOfToken(value);
258
+ if (supply) addSupplyGrant(grant, name, supply, host);
259
+ else addGrant(grant, name, value, host);
260
+ }
261
+
249
262
  /** Put the `${NAME}` back where a known secret's value sits in `text`,
250
263
  * granting the name to `host`. Longest values first, so one that contains
251
264
  * another is replaced whole. */
package/src/grades.ts CHANGED
@@ -212,7 +212,7 @@ export async function gradeRun(
212
212
  for (const a of judges) {
213
213
  try {
214
214
  const m = accountModelEnv(tenant, workspace, judgeProcessEnv);
215
- const said = await withModelEnv(m, (env) => ask(a.value, output, info.model, info.effort, env, task));
215
+ const said = await withModelEnv(m, (env) => ask(a.value, output, info.model, info.effort, env, task), { kind: "grade", name: info.name });
216
216
  costUsd += said.costUsd;
217
217
  const v = judgeVerdict(said.text);
218
218
  if (v.decided === false) {
package/src/model-env.ts CHANGED
@@ -13,6 +13,8 @@ import { platform, hostUrlProblem } from "./platform.ts";
13
13
  import { accountModelBlock, isClaudeLoginToken } from "./model-credential.ts";
14
14
  import { providerPreset } from "./providers.ts";
15
15
  import { startTranslator, translatorSpecFor, type TranslatorSpec } from "./translator.ts";
16
+ import { supplyProviderBlock, type SupplyAnswer } from "./model-supply.ts";
17
+ import { MODEL_KEY_NAME, grantModelKey, hostOf, type EgressGrant } from "./egress.ts";
16
18
 
17
19
  /** Refused for want of a usable key; `status` is what an HTTP layer answers. */
18
20
  export class ModelKeyError extends Error {
@@ -40,14 +42,43 @@ export function accountModelEnv(
40
42
  platformEnv: () => Record<string, string | undefined>,
41
43
  ): {
42
44
  env: Record<string, string | undefined>;
43
- supply: "provider" | "platform";
45
+ /** "foldrun": the platform's key for a provider the account chose —
46
+ * withModelEnv sends it through the egress proxy, which meters and bills
47
+ * each call; the caller charges nothing for it itself. */
48
+ supply: "provider" | "platform" | "foldrun";
44
49
  format: string;
45
50
  translator: TranslatorSpec | null;
51
+ tenant?: string;
46
52
  } {
47
- const raw =
53
+ const written =
48
54
  (readAgentsMd(workspaceDir(tenant, workspace))?.data?.provider as Record<string, unknown> | undefined) ??
49
- (readAgentsMd(accountDir(tenant))?.data?.provider as Record<string, unknown> | undefined) ??
50
- accountModelBlock((name) => getSecret(tenant, name)?.value ?? null);
55
+ (readAgentsMd(accountDir(tenant))?.data?.provider as Record<string, unknown> | undefined);
56
+ // foldrun's models, the same rung a step takes (runner.ts agentContext):
57
+ // after the written blocks, before the account's stored key; chosen but
58
+ // refused fails here, never onto the stored key or the operator's.
59
+ const supply: SupplyAnswer = written ? { kind: "none" } : platform.modelSupply?.(tenant) ?? { kind: "none" };
60
+ if (supply.kind === "refused") throw new ModelKeyError(`foldrun's models: ${supply.reason}`, 403);
61
+ if (supply.kind === "foldrun") {
62
+ const s = parseProvider(supplyProviderBlock(supply.provider, supply.tiers))!;
63
+ const preset = providerPreset(s.name);
64
+ return {
65
+ env: providerEnvFor({ baseUrl: s.baseUrl!, token: s.token, auth: s.auth, models: s.models, headers: {} }),
66
+ supply: "foldrun",
67
+ format: s.format,
68
+ translator: translatorSpecFor({
69
+ format: s.format,
70
+ baseUrl: s.baseUrl!,
71
+ token: s.token,
72
+ headers: {},
73
+ params: s.params,
74
+ name: s.name,
75
+ maxTokensParam: preset?.maxTokensParam,
76
+ reasoningEffort: preset?.reasoningEffort,
77
+ }),
78
+ tenant,
79
+ };
80
+ }
81
+ const raw = written ?? accountModelBlock((name) => getSecret(tenant, name)?.value ?? null);
51
82
  const spec = parseProvider(raw);
52
83
  if (!spec?.baseUrl) {
53
84
  if (!platform.platformKeyAllowed(tenant)) throw new ModelKeyError(NO_MODEL_KEY);
@@ -95,9 +126,12 @@ export function accountModelEnv(
95
126
  * Started for this call and closed after it.
96
127
  */
97
128
  export async function withModelEnv<T>(
98
- m: { env: Record<string, string | undefined>; translator?: TranslatorSpec | null; supply?: "provider" | "platform" },
129
+ m: { env: Record<string, string | undefined>; translator?: TranslatorSpec | null; supply?: "provider" | "platform" | "foldrun"; tenant?: string },
99
130
  fn: (env: Record<string, string | undefined>) => Promise<T>,
131
+ /** What is asking, for the gateway's record of a foldrun's-models call. */
132
+ job: { kind: HostJobKind; name?: string } = { kind: "judge" },
100
133
  ): Promise<T> {
134
+ if (m.supply === "foldrun") return withSupply(m, fn, job);
101
135
  const spec = m.translator ?? (m.supply === "provider" ? anthropicPassthrough(m.env) : null);
102
136
  if (!spec) return fn(m.env);
103
137
  const why = await platform.checkUntrustedUrl(spec.upstreamBase);
@@ -110,6 +144,35 @@ export async function withModelEnv<T>(
110
144
  }
111
145
  }
112
146
 
147
+ export type HostJobKind = "grade" | "judge" | "draft" | "assistant";
148
+
149
+ /**
150
+ * A host-side call on foldrun's models (an eval's judge, a grader, a draft):
151
+ * through a short lease on the egress proxy, like a step's — the platform's
152
+ * key is filled there and every call metered and billed by the gateway. No
153
+ * proxy: refused, never sent with the key from here.
154
+ */
155
+ async function withSupply<T>(
156
+ m: { env: Record<string, string | undefined>; translator?: TranslatorSpec | null; tenant?: string },
157
+ fn: (env: Record<string, string | undefined>) => Promise<T>,
158
+ job: { kind: HostJobKind; name?: string },
159
+ ): Promise<T> {
160
+ const spec = m.translator ?? anthropicPassthrough(m.env);
161
+ const host = spec ? hostOf(spec.upstreamBase) : null;
162
+ if (!spec || !host || !m.tenant) throw new ModelKeyError("foldrun's models: no endpoint for this call", 500);
163
+ const grant: EgressGrant = { secrets: {} };
164
+ grantModelKey(grant, MODEL_KEY_NAME, spec.upstreamKey, host);
165
+ const lease = await platform.egress.lease({ tenant: m.tenant, runId: `${job.kind}:${job.name ?? "-"}`, grant, job });
166
+ if (!lease) throw new ModelKeyError("foldrun's models need the platform's egress proxy, and this install has none", 503);
167
+ const t = await startTranslator({ ...spec, egress: lease.url, upstreamKey: `\${${MODEL_KEY_NAME}}` });
168
+ try {
169
+ return await fn({ ...m.env, ...t.env });
170
+ } finally {
171
+ await t.close();
172
+ await lease.release().catch(() => {});
173
+ }
174
+ }
175
+
113
176
  /** The passthrough for an Anthropic-format provider, read back from the env
114
177
  * providerEnvFor (store.ts) built for it: the base URL, the key in the slot
115
178
  * that names its header, and ANTHROPIC_CUSTOM_HEADERS. Null with no base. */
@@ -85,6 +85,14 @@ export const SUPPLY_PROVIDERS: Record<SupplyProviderName, SupplyProvider> = {
85
85
 
86
86
  export const SUPPLY_PROVIDER_NAMES = Object.keys(SUPPLY_PROVIDERS) as SupplyProviderName[];
87
87
 
88
+ /** How each reads to a person: on a step's credential line, in Settings. */
89
+ export const SUPPLY_TITLES: Record<SupplyProviderName, string> = {
90
+ anthropic: "Anthropic",
91
+ openai: "OpenAI",
92
+ gemini: "Google Gemini",
93
+ openrouter: "OpenRouter",
94
+ };
95
+
88
96
  export function isSupplyProvider(name: unknown): name is SupplyProviderName {
89
97
  return typeof name === "string" && Object.hasOwn(SUPPLY_PROVIDERS, name);
90
98
  }
@@ -92,6 +100,33 @@ export function isSupplyProvider(name: unknown): name is SupplyProviderName {
92
100
  /** The placeholder name a supply grant is filed under in a step's lease. */
93
101
  export const SUPPLY_KEY_NAME = "FOLDRUN_SUPPLY_KEY";
94
102
 
103
+ /**
104
+ * What the platform says about one account's model supply, before any
105
+ * provider: block of its own is considered (a written block always wins):
106
+ * none — it did not choose foldrun's models: its own key, as before
107
+ * foldrun — it chose them and they are on: run on the platform's key
108
+ * refused — it chose them and they cannot be had now (switched off, the
109
+ * provider withdrawn, the account refused). The step FAILS
110
+ * with the reason: never quietly onto the account's stored
111
+ * key, and never onto the operator's.
112
+ */
113
+ export type SupplyAnswer =
114
+ | { kind: "none" }
115
+ | { kind: "foldrun"; provider: SupplyProviderName; tiers: Partial<Record<"fast" | "default" | "max", string>> }
116
+ | { kind: "refused"; reason: string };
117
+
118
+ /** The token a supply provider block carries: a marker, not a secret. The
119
+ * proxy grant built from it is a supply grant (egress.ts grantModelKey),
120
+ * which the proxy fills with the platform's key. Sent anywhere unproxied
121
+ * it is only a word a provider refuses. */
122
+ const MARKER = "foldrun-supply:";
123
+ export const supplyToken = (provider: SupplyProviderName) => `${MARKER}${provider}`;
124
+ export function supplyProviderOfToken(value: string | null | undefined): SupplyProviderName | null {
125
+ if (typeof value !== "string" || !value.startsWith(MARKER)) return null;
126
+ const p = value.slice(MARKER.length);
127
+ return isSupplyProvider(p) ? p : null;
128
+ }
129
+
95
130
  /** The provider block a step on foldrun's models runs with: the preset's
96
131
  * endpoint and format, the operator's tier map, and the key as a
97
132
  * placeholder only. */
@@ -103,7 +138,7 @@ export function supplyProviderBlock(provider: SupplyProviderName, tiers: Partial
103
138
  name: p.preset,
104
139
  base_url: preset.baseUrl,
105
140
  format: p.format,
106
- token: `\${${SUPPLY_KEY_NAME}}`,
141
+ token: supplyToken(provider),
107
142
  ...(Object.keys(tiers).length ? { models: tiers } : {}),
108
143
  };
109
144
  }
package/src/platform.ts CHANGED
@@ -12,6 +12,7 @@
12
12
  // and calls registerPlatform() once at boot. A process that forgets to is a
13
13
  // local install — which is exactly the failure that is safe.
14
14
 
15
+ import type { SupplyAnswer } from "./model-supply.ts";
15
16
  import type { FlowInfo, FlowStep, RunRecord } from "./store.ts";
16
17
  import type { RunInContainerArgs, ContainerStepOutcome } from "./run-container.ts";
17
18
  import type { EgressHooks } from "./egress.ts";
@@ -149,6 +150,11 @@ export interface PlatformHooks {
149
150
  * operator's accounts do so; every customer brings their own API key.
150
151
  * Default: yes — a laptop or a self-hosted install is its own operator. */
151
152
  platformKeyAllowed(tenant: string): boolean;
153
+ /** foldrun's models (3 Nov 2026): whether this account chose to run on
154
+ * the platform's own key for a provider, and whether it can now. Asked
155
+ * only where no provider: block of the account's own says otherwise.
156
+ * Absent: nobody can (a laptop, a self-hosted install). */
157
+ modelSupply?(tenant: string): SupplyAnswer;
152
158
  /**
153
159
  * An operator setting, by the environment variable that used to hold it
154
160
  * (30 Oct 2026): the platform answers with the operator's value where one
package/src/runner.ts CHANGED
@@ -25,7 +25,9 @@ import { hostSafeEnv, platformApiUrl } from "./host-env.ts";
25
25
  import { resolveModelCredential, credentialLine, accountModelBlock, isClaudeLoginToken, isModelEnvName, DECLARED_ENV_PREFIX } from "./model-credential.ts";
26
26
  import { parseJudge } from "./judge-verdict.ts";
27
27
  import { validateSchema, describeSchemaErrors, looksLikeSchema } from "./json-schema.ts";
28
- import { EGRESS_ENV, MODEL_KEY_NAME, addGrant, hostOf, placeholderNames, proxyModelEnv, unsubstitute, type EgressGrant } from "./egress.ts";
28
+ import { EGRESS_ENV, MODEL_KEY_NAME, addGrant, grantModelKey, hostOf, placeholderNames, proxyModelEnv, unsubstitute, type EgressGrant } from "./egress.ts";
29
+ import { SUPPLY_TITLES, supplyProviderBlock, type SupplyAnswer } from "./model-supply.ts";
30
+ import type { StepSupply } from "./store.ts";
29
31
  import { explainRefusal, isRefusalStatus, refusalFromLine, supplyNote, type SupplyState } from "./refusal.ts";
30
32
  import { platform } from "./platform.ts";
31
33
  import { healthKey } from "./secret-health.ts";
@@ -1351,7 +1353,18 @@ export function agentContext(
1351
1353
  // an account that brings its key need not write a block anywhere.
1352
1354
  const fileBlock =
1353
1355
  (front.provider as Record<string, unknown> | undefined) ?? workspaceFrontmatter(agentDir, tenant).provider;
1354
- const providerBlock = fileBlock ?? accountModelBlock((name) => getSecret(tenant, name)?.value ?? null);
1356
+ // foldrun's models (3 Nov 2026): an account that chose the platform's key
1357
+ // for a provider runs on it here, between its written blocks (which still
1358
+ // win) and its stored key. Chosen but not to be had now — refused, and
1359
+ // the step fails with why (runStep); it never falls to the stored key.
1360
+ const supply: SupplyAnswer = fileBlock ? { kind: "none" } : platform.modelSupply?.(tenant) ?? { kind: "none" };
1361
+ const providerBlock =
1362
+ fileBlock ??
1363
+ (supply.kind === "foldrun"
1364
+ ? supplyProviderBlock(supply.provider, supply.tiers)
1365
+ : supply.kind === "refused"
1366
+ ? undefined
1367
+ : accountModelBlock((name) => getSecret(tenant, name)?.value ?? null));
1355
1368
  let providerEnv: Record<string, string> = {};
1356
1369
  let providerLabel: string | null = null;
1357
1370
  // Secret values pulled into the provider block, name → value. Kept apart
@@ -1826,6 +1839,8 @@ export function agentContext(
1826
1839
  return {
1827
1840
  front,
1828
1841
  clockEnv,
1842
+ /** foldrun's models: what the platform said for this account. */
1843
+ supply,
1829
1844
  /** The zone, where it came from, and anything unreadable on the way —
1830
1845
  * reported by the step, not here, so it lands in the run's trace. */
1831
1846
  clock,
@@ -2006,7 +2021,7 @@ export function recordAttempt(
2006
2021
  };
2007
2022
  // A slim go the browser pod was lost under, before this attempt re-ran
2008
2023
  // on the full image: its own row, first (runStep set it aside).
2009
- const lost: StepAttempt[] = step.podLostTry ? [{ ...numbered(), ...step.podLostTry, startedAt }] : [];
2024
+ const lost: StepAttempt[] = step.podLostTry ? [{ ...numbered(), ...step.podLostTry, startedAt, ...(step.supply ? { supply: step.supply } : {}) }] : [];
2010
2025
  const row: StepAttempt = {
2011
2026
  ...numbered(),
2012
2027
  status,
@@ -2014,6 +2029,7 @@ export function recordAttempt(
2014
2029
  tokens: step.tokens ?? null,
2015
2030
  ...(typeof step.turns === "number" ? { turns: step.turns } : {}),
2016
2031
  computeSecs: step.computeSecs ?? null,
2032
+ ...(step.supply ? { supply: step.supply } : {}),
2017
2033
  startedAt: step.podLostTry?.finishedAt ?? startedAt,
2018
2034
  finishedAt: step.finishedAt ?? new Date().toISOString(),
2019
2035
  ...(status === "failed" && lastError ? { error: lastError.slice(0, 500) } : {}),
@@ -2350,6 +2366,7 @@ async function runStep(
2350
2366
  peers,
2351
2367
  translator, fallbackTranslator,
2352
2368
  outward,
2369
+ supply,
2353
2370
  } = agentContext(agentDir, tenant, tags, { runId, agent: step.agent }, flowTimezone);
2354
2371
  disposeRuntime = runtime.dispose;
2355
2372
  canActOutward = outward;
@@ -2458,7 +2475,34 @@ async function runStep(
2458
2475
  const primaryOnPlatform = Object.keys(providerEnv).length === 0;
2459
2476
  const noKey = primaryOnPlatform && !platform.platformKeyAllowed(tenant);
2460
2477
  const credential = !primaryOnPlatform || noKey ? null : resolveModelCredential(isolatedRun() ? platformModelEnv() : process.env);
2461
- step.credential = credential ? credential.label : noKey ? "none — this account has no model key" : `provider: ${providerLabel}`;
2478
+ const onSupply = supply.kind === "foldrun" && !primaryOnPlatform;
2479
+ // Attempts recorded before supply was (older records) are stamped with
2480
+ // the one their credential said, before this attempt overwrites it: a
2481
+ // retry on another supply must not reclassify what they spent.
2482
+ const before: StepSupply = (step.credential ?? "").startsWith("provider:") ? "own" : "operator";
2483
+ for (const t of step.tries ?? []) t.supply ??= before;
2484
+ step.credential = onSupply
2485
+ ? `foldrun models · ${SUPPLY_TITLES[supply.provider]}`
2486
+ : credential ? credential.label : noKey ? "none — this account has no model key" : `provider: ${providerLabel}`;
2487
+ step.supply = onSupply ? "foldrun" : primaryOnPlatform ? "operator" : "own";
2488
+ if (onSupply) step.supplyProvider = supply.provider;
2489
+ else delete step.supplyProvider;
2490
+ // Chosen, but not to be had now: failed with why, before a sandbox —
2491
+ // never onto the account's stored key or the operator's.
2492
+ if (supply.kind === "refused") {
2493
+ push("error", `foldrun's models: ${supply.reason} — or switch this account back to its own key (Settings → Model, \`foldrun account model use own\`)`);
2494
+ step.status = "failed";
2495
+ save();
2496
+ return;
2497
+ }
2498
+ // The platform's key only ever crosses the egress proxy, which meters
2499
+ // every call: a step that would run without one is refused.
2500
+ if (onSupply && !isolatedRun()) {
2501
+ push("error", "foldrun's models run only in the platform's sandbox, where every call is metered — this step would run here, so it is refused");
2502
+ step.status = "failed";
2503
+ save();
2504
+ return;
2505
+ }
2462
2506
  // Core's own Docker container has no login to fall back to (below):
2463
2507
  // there, "none set" is refused with what to do, not described.
2464
2508
  const noCredentialInContainer = credential?.kind === "none" && process.env.FOLDRUN_RUN_ISOLATION === "container";
@@ -2966,6 +3010,15 @@ async function runStep(
2966
3010
  // sandbox: own sub-agents: the only names the delegate door takes.
2967
3011
  ...(delegates.length ? { delegates: delegates.map((d) => d.name) } : {}),
2968
3012
  });
3013
+ // foldrun's models need the proxy: it holds the platform's key and
3014
+ // meters each call. No lease (no FOLDRUN_EGRESS_URL) — refused, and
3015
+ // nothing is sent; the marker token alone would only be refused.
3016
+ if (step.supply === "foldrun" && !lease) {
3017
+ push("error", "foldrun's models need the platform's egress proxy, and this step has none — refused before it ran");
3018
+ step.status = "failed";
3019
+ save();
3020
+ return;
3021
+ }
2969
3022
  // Serve those jobs while this step runs: each one becomes a step of
2970
3023
  // its own (delegateJob), and the door answers the long-poll with its
2971
3024
  // reply. No proxy, or a platform without the door: not offered — the
@@ -3140,7 +3193,7 @@ async function runStep(
3140
3193
  if (!spec || !lease) return spec;
3141
3194
  const host = hostOf(spec.upstreamBase);
3142
3195
  if (!host) return spec;
3143
- addGrant(grant, name, spec.upstreamKey, host);
3196
+ grantModelKey(grant, name, spec.upstreamKey, host);
3144
3197
  return {
3145
3198
  ...spec,
3146
3199
  egress: lease.url,
package/src/store.ts CHANGED
@@ -3413,6 +3413,9 @@ export interface StepAttempt {
3413
3413
  status: "completed" | "failed" | "lost";
3414
3414
  costUsd: number | null;
3415
3415
  tokens: TokenUsage | null;
3416
+ /** Whose key this attempt ran on (StepRecord.supply): a retry may run on
3417
+ * another, and the meter bills each attempt by its own. */
3418
+ supply?: StepSupply;
3416
3419
  /** Model turns this attempt took; absent before 18 Oct 2026. */
3417
3420
  turns?: number | null;
3418
3421
  computeSecs: number | null;
@@ -3532,6 +3535,14 @@ export interface StepRecord {
3532
3535
  * (ANTHROPIC_API_KEY)", "Claude login token (CLAUDE_CODE_OAUTH_TOKEN)",
3533
3536
  * "provider: …" — or "none set" (model-credential.ts). */
3534
3537
  credential?: string;
3538
+ /** Whose key paid for the step's model calls (3 Nov 2026): "own" — the
3539
+ * account's (a provider: block, Settings → Model), billed by its
3540
+ * provider; "operator" — the platform's own credential, billed from the
3541
+ * step's tokens; "foldrun" — foldrun's models, billed per call by the
3542
+ * model gateway, never from the step. Absent on older records. */
3543
+ supply?: StepSupply;
3544
+ /** With supply "foldrun": which provider's key. */
3545
+ supplyProvider?: string;
3535
3546
  /** Slim browsing through the account's pod (browser-pod.ts): reconnect
3536
3547
  * tries and how many got through; when the pod was lost, why and what
3537
3548
  * the step had written by then; and what happened — `fallback` (the
@@ -4387,10 +4398,30 @@ export function runCost(run: RunRecord): number {
4387
4398
  * a provider: block, or Settings → Model), which the provider bills. The
4388
4399
  * meter, the Usage page and the ledger split all ask this one question, so
4389
4400
  * what a page shows is what was charged. */
4390
- export function stepBillsTokens(s: Pick<StepRecord, "credential">): boolean {
4401
+ export function stepBillsTokens(s: Pick<StepRecord, "credential" | "supply">): boolean {
4402
+ if (s.supply) return supplyBillsTokens(s.supply);
4391
4403
  return !(s.credential ?? "").startsWith("provider:");
4392
4404
  }
4393
4405
 
4406
+ export type StepSupply = "own" | "operator" | "foldrun";
4407
+
4408
+ /** Only the operator's credential is billed from what a step reports. The
4409
+ * account's own key is its provider's to bill; foldrun's models are billed
4410
+ * per call by the gateway, so billing the step too would charge twice. */
4411
+ export const supplyBillsTokens = (supply: StepSupply) => supply === "operator";
4412
+
4413
+ /** The step's tokens the platform bills, attempt by attempt where the
4414
+ * attempts say whose key they ran on. */
4415
+ export function billedTokenCost(s: { credential?: string; supply?: StepSupply; costUsd?: number | null; tries?: StepAttempt[] }): number {
4416
+ const tries = s.tries ?? [];
4417
+ if (!tries.some((t) => t.supply)) return stepBillsTokens(s) ? s.costUsd ?? 0 : 0;
4418
+ // Each attempt by its own supply — a lost slim go spent its tokens too,
4419
+ // as the step's total says (sumAttempts) — and a row from before the
4420
+ // field by the step's older rule (its credential).
4421
+ const legacy = !(s.credential ?? "").startsWith("provider:");
4422
+ return tries.reduce((n, t) => n + ((t.supply ? supplyBillsTokens(t.supply) : legacy) ? t.costUsd ?? 0 : 0), 0);
4423
+ }
4424
+
4394
4425
  /**
4395
4426
  * What a finished run consumed, in the units the format itself has — the
4396
4427
  * shape ledger.ts prices. Structural, not an import, because ledger.ts
@@ -4427,7 +4458,7 @@ export function runMeter(run: RunRecord): {
4427
4458
  // A carried step ran — and was billed — in the run it was carried from.
4428
4459
  if (s.carriedFrom) continue;
4429
4460
  steps += 1;
4430
- if (stepBillsTokens(s)) tokenCostUsd += s.costUsd ?? 0;
4461
+ tokenCostUsd += billedTokenCost(s);
4431
4462
  const secs = s.computeSecs ?? 0;
4432
4463
  computeSecs += secs;
4433
4464
  if (s.size === "small") smallSecs += secs;
package/src/translator.ts CHANGED
@@ -1154,7 +1154,12 @@ async function passthrough(
1154
1154
  const target = `${base}${url.pathname}${url.search}`;
1155
1155
  let upstream: Response;
1156
1156
  try {
1157
- upstream = await fetchUntrusted(target, { method, headers, body: method === "GET" || method === "HEAD" ? undefined : raw }, { sameOrigin: true, maxBytes: UPSTREAM_MAX_BYTES });
1157
+ const init = { method, headers, body: method === "GET" || method === "HEAD" ? undefined : raw };
1158
+ // Through the lease when there is one (foldrun's models, host-side): the
1159
+ // proxy fills the key and meters the call; the placeholder never leaves.
1160
+ upstream = spec.egress
1161
+ ? await fetch(viaEgress(spec.egress, target), init as RequestInit)
1162
+ : await fetchUntrusted(target, init, { sameOrigin: true, maxBytes: UPSTREAM_MAX_BYTES });
1158
1163
  } catch (err) {
1159
1164
  const message = err instanceof Error ? err.message : String(err);
1160
1165
  log.push(`${method} ${label}${url.pathname} → unreachable: ${message}`);