@foldrun/core 14.2.1 → 14.3.1

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.
@@ -89,6 +89,7 @@ const FIELDS = {
89
89
  { label: "description", insert: "description: ", hint: "required — what it does, and when" },
90
90
  { label: "model", insert: "model: default" },
91
91
  { label: "effort", insert: "effort: high", hint: "how hard it thinks" },
92
+ { label: "max_output_tokens", insert: "max_output_tokens: 16000", hint: "the longest one reply may be, in tokens" },
92
93
  { label: "tools", insert: "tools:\n - write", hint: "what the runtime gives it" },
93
94
  { label: "secrets", insert: "secrets:\n - ", hint: "credentials it may spend" },
94
95
  { label: "skills", insert: "skills:\n - ", hint: "allowlist; omit to inherit all" },
@@ -162,6 +163,7 @@ const FIELDS = {
162
163
  { label: "timezone", insert: "timezone: Australia/Sydney" },
163
164
  { label: "model", insert: "model: fast", hint: "every step, unless the step says" },
164
165
  { label: "effort", insert: "effort: high", hint: "every step, unless the step says" },
166
+ { label: "max_output_tokens", insert: "max_output_tokens: 16000", hint: "every step's longest reply, unless the step says" },
165
167
  ],
166
168
  evalFile: [
167
169
  { label: "name", insert: "name: " },
@@ -271,6 +273,7 @@ const STEP_OPTIONS = [
271
273
  { label: "each", insert: "each: items", hint: "fan out: lines | items | rows of <csv>" },
272
274
  { label: "model", insert: "model: fast" },
273
275
  { label: "effort", insert: "effort: high", hint: "this step only" },
276
+ { label: "max_output_tokens", insert: "max_output_tokens: 16000", hint: "the longest one reply may be, this step only" },
274
277
  { label: "approve", insert: "approve: true", hint: "pause for a human" },
275
278
  ];
276
279
  // Header and query-parameter names, for the indented lines under `headers:`
@@ -21,7 +21,7 @@ const SUBFLOW_DROPPED = [
21
21
  ["effort", "effort:"], ["onFail", "on-fail:"], ["waitSecs", "wait:"], ["waitFor", "wait:"],
22
22
  ["ask", "ask:"], ["preview", "preview:"], ["delegate", "delegate:"], ["loop", "loop:"],
23
23
  ["until", "until:"], ["each", "each:"], ["max", "max:"], ["output", "output:"],
24
- ["schema", "schema:"], ["parallel", "parallel:"], ["maxTurns", "max_turns:"], ["limits", "limits:"],
24
+ ["schema", "schema:"], ["parallel", "parallel:"], ["maxTurns", "max_turns:"], ["maxOutputTokens", "max_output_tokens:"], ["limits", "limits:"],
25
25
  ];
26
26
  // Anaphora: phrases that only mean something if earlier output exists.
27
27
  // Deliberately conservative — a false warning is worse than a missed one,
@@ -33,6 +33,7 @@ const AGENT = [
33
33
  { key: "owner", type: "string", help: "the person accountable for it — an email or a name; else the workspace's, else the account's" },
34
34
  { key: "model", type: "string", help: "fast | default | max, an alias, or a full model id" },
35
35
  { key: "effort", type: "string", values: EFFORT_LEVELS, help: "how long it thinks" },
36
+ { key: "max_output_tokens", type: ["number", "string"], help: "the most tokens one model reply may have, 1 to 1048576; on foldrun's models the price list's ceiling applies too" },
36
37
  { key: "size", type: "string", values: ["small", "large", "heavy"], help: "the sandbox it rents; anything else becomes large" },
37
38
  { key: "resources", type: "object", help: "{cpu, memory, disk} in numbers, over the size class's figures key by key — cpu 0.5–8, memory 256Mi–16Gi, disk 1–40Gi" },
38
39
  { key: "permissionMode", type: "string", values: ["plan"], help: "plan = read-only; no other mode changes anything here" },
@@ -104,6 +105,7 @@ const FLOW = [
104
105
  { key: "timezone", type: "string", validated: true, help: "the zone its schedule reads in" },
105
106
  { key: "model", type: "string", help: "every step's model unless the step says" },
106
107
  { key: "effort", type: "string", values: EFFORT_LEVELS, help: "every step's effort unless the step says" },
108
+ { key: "max_output_tokens", type: ["number", "string"], help: "every step's longest reply, in tokens, unless the step or its agent says" },
107
109
  { key: "overlap", type: "string", validated: true, help: "skip | queue" },
108
110
  { key: "issues", type: "string", values: ["stay-open", "auto-close"], help: "what a good run does to this flow's open issues: stay-open (the default — a person resolves them) or auto-close" },
109
111
  { key: "priority", type: "string", validated: true, help: "high | normal | low" },
@@ -3,7 +3,7 @@
3
3
  // field list alone from frontmatter-fields.ts.
4
4
  import { FRONTMATTER, JOBS } from "./frontmatter-fields.js";
5
5
  import { jobFold } from "./matter.js";
6
- import { resolveEffort, parseDuration, parseInstant, parseRate, STEP_OPTION_KEYS } from "./store.js";
6
+ import { resolveEffort, parseDuration, parseInstant, parseRate, STEP_OPTION_KEYS, parseMaxOutputTokens, MAX_OUTPUT_TOKENS_CAP } from "./store.js";
7
7
  import { budgetProblem } from "./budget.js";
8
8
  import { cronProblem, parseCron, cronCanFire } from "./cron.js";
9
9
  import { SECRET_NAME } from "./secrets.js";
@@ -27,11 +27,16 @@ const DURATION = (min, max, unit = "") => (v) => {
27
27
  return `"${String(v)}" is outside ${unit || `${min}s to ${max}s`}`;
28
28
  return null;
29
29
  };
30
+ /** `max_output_tokens:` — a whole number of tokens the runtime can be told. */
31
+ function maxOutputProblem(v) {
32
+ return parseMaxOutputTokens(v) === undefined ? `${shown(v)} is not a number of tokens, 1 to ${MAX_OUTPUT_TOKENS_CAP}; the model's own limit applies` : null;
33
+ }
30
34
  /** Why a value is wrong, or null — per kind, per field: the rules a list of
31
35
  * values cannot say (aliases, durations, cron, budgets). */
32
36
  const CHECKS = {
33
37
  "agent": {
34
38
  effort: (v) => (resolveEffort(v) ? null : `"${String(v)}" is not an effort — low, medium, high, xhigh or max; the step runs at the model's default`),
39
+ max_output_tokens: maxOutputProblem,
35
40
  apis: apisProblem,
36
41
  remotes: remotesProblem,
37
42
  budget: (v) => budgetProblem(v, ["run"]),
@@ -47,6 +52,7 @@ const CHECKS = {
47
52
  "flow": {
48
53
  schedule: cronProblem,
49
54
  effort: (v) => (resolveEffort(v) ? null : `"${String(v)}" is not an effort — low, medium, high, xhigh or max`),
55
+ max_output_tokens: maxOutputProblem,
50
56
  at: (v) => (parseInstant(v) ? null : `"${String(v)}" is not an ISO 8601 instant — a once flow with it never fires`),
51
57
  url: (v) => (/^https?:\/\//i.test(String(v)) ? null : `"${String(v)}" is not an http(s) URL`),
52
58
  every: DURATION(1, 30 * 86400, "1s to 30 days"),
@@ -66,6 +66,9 @@ export type SupplyAnswer = {
66
66
  kind: "foldrun";
67
67
  provider: SupplyProviderName;
68
68
  tiers: Partial<Record<"fast" | "default" | "max", string>>;
69
+ /** The price list's output ceiling per model id: the most one reply
70
+ * may be on the platform's key, told to the runtime up front. */
71
+ ceilings?: Record<string, number>;
69
72
  } | {
70
73
  kind: "refused";
71
74
  reason: string;
@@ -42,7 +42,7 @@ import { ASK_TOOL, PEER_TOOLS, applyOperatorEvent, askPromptLine, askTimeoutSec,
42
42
  import { sendPlainNotification } from "./notify.js";
43
43
  import { TOOL_MAP, BUILTIN_TOOLS, ownToolNames, toolRefs, legacyUseNames, legacyUseError, retiredToolNames, retiredToolError } from "./tool-names.js";
44
44
  import { refNames } from "./refs.js";
45
- import { accountDir, workspaceDir, buildMemoryIndex, workspaceMemoryIndex, knowledgeIndex, workspaceKnowledgeIndex, workspaceTools, brokenToolReport, listWorkspaces, listTenants, listRuns, liveRuns, syncBundleFor, parseToolDef, readFlow, markerPresent, whenRowsPath, parseApis, resolveModel, parseProvider, providerEnvFor, resolveEffort, isEffortWord, EFFORT_LEVELS, checkFormatVersion, readRun, writeRun, isSplicedRecord, runSummary, verdictOf, sumAttempts, tokensOf, parseSchemaText, STORAGE_DIR, adoptLegacyVersionKey, listAgents, isOneSegment, stoppedByText, } from "./store.js";
45
+ import { accountDir, workspaceDir, buildMemoryIndex, workspaceMemoryIndex, knowledgeIndex, workspaceKnowledgeIndex, workspaceTools, brokenToolReport, listWorkspaces, listTenants, listRuns, liveRuns, syncBundleFor, parseToolDef, readFlow, markerPresent, whenRowsPath, parseApis, resolveModel, parseProvider, providerEnvFor, resolveEffort, parseMaxOutputTokens, isEffortWord, EFFORT_LEVELS, checkFormatVersion, readRun, writeRun, isSplicedRecord, runSummary, verdictOf, sumAttempts, tokensOf, parseSchemaText, STORAGE_DIR, adoptLegacyVersionKey, listAgents, isOneSegment, stoppedByText, } from "./store.js";
46
46
  import { canReadBack } from "./tool-output.js";
47
47
  import { PromptLayers, promptCacheKey } from "./prompt-layers.js";
48
48
  import { loadCatalog, checkModel, clampEffort, catalogCost, findModel, tokenPriceOf } from "./catalog.js";
@@ -2470,6 +2470,20 @@ mayDefer) {
2470
2470
  // this the in-pod meter priced haiku and sonnet at Opus rates and a
2471
2471
  // step was stopped at up to fifteen times what it had spent.
2472
2472
  tokenPrice ??= knownPrice(wireModel);
2473
+ // `max_output_tokens:` — the step's own (or its flow's, snapshotted on
2474
+ // the run), else the agent's; on foldrun's models never above the price
2475
+ // list's ceiling for the model it runs, so the runtime knows its real
2476
+ // limit up front instead of the gateway cutting it short (3 Nov 2026).
2477
+ const askedOut = step.maxOutputTokens ?? parseMaxOutputTokens(front.max_output_tokens);
2478
+ const outCeiling = onSupply && supply.kind === "foldrun" ? supply.ceilings?.[wireModel] : undefined;
2479
+ const maxOut = askedOut && outCeiling ? Math.min(askedOut, outCeiling) : (askedOut ?? outCeiling);
2480
+ if (askedOut && outCeiling && askedOut > outCeiling) {
2481
+ push("info", `max_output_tokens: ${askedOut} runs as ${outCeiling} — the price list's ceiling for ${wireModel} on foldrun's models`);
2482
+ }
2483
+ const outputEnv = maxOut ? { CLAUDE_CODE_MAX_OUTPUT_TOKENS: String(maxOut) } : {};
2484
+ if (maxOut && !(askedOut && outCeiling && askedOut > outCeiling)) {
2485
+ push("info", `max_output_tokens: ${maxOut}${askedOut ? "" : " — the price list's ceiling on foldrun's models"}`);
2486
+ }
2473
2487
  fs.mkdirSync(path.join(agentDir, "outputs"), { recursive: true });
2474
2488
  fs.mkdirSync(path.join(agentDir, "memory"), { recursive: true });
2475
2489
  // Expose the workspace's shared scripts/ as ./shared so every agent reaches
@@ -3065,6 +3079,7 @@ mayDefer) {
3065
3079
  // A provider: block still wins, because providerEnv is spread
3066
3080
  // after and carries the agent's chosen endpoint + token.
3067
3081
  ...proxied(Object.keys(providerEnv).length === 0 ? modelEnv : providerEnv, keyName),
3082
+ ...outputEnv,
3068
3083
  ...(lease ? { [EGRESS_ENV]: lease.url } : {}),
3069
3084
  // Every program's HTTP(S) through the proxy's forward door, and
3070
3085
  // the CA it signs bound sites with, for the sandbox to trust.
@@ -3533,7 +3548,7 @@ mayDefer) {
3533
3548
  // the allowlisted host environment, not process.env: the SDK's
3534
3549
  // Bash tool runs with this, and on a platform process.env holds
3535
3550
  // every tenant's root key and the datastore credentials.
3536
- env: { ...hostSafeEnv(), ...clockEnv, ...(testRun ? testModeEnv() : {}), ...mat.env, ...installEnv, ...modelEnv },
3551
+ env: { ...hostSafeEnv(), ...clockEnv, ...(testRun ? testModeEnv() : {}), ...mat.env, ...installEnv, ...modelEnv, ...outputEnv },
3537
3552
  timeoutSec: step.timeout,
3538
3553
  budgetUsd: stepBudgetUsd,
3539
3554
  budgetNote: stepBudgetNote,
@@ -4185,6 +4200,13 @@ export function createFlowRun(tenant, workspace, steps, flowName, status, tags =
4185
4200
  /** An A2A task's correlation (foldrun-platform flow-admission.ts) — its
4186
4201
  * own trailing argument, so the signature only widened. */
4187
4202
  a2a) {
4203
+ let flowMaxOut;
4204
+ try {
4205
+ flowMaxOut = readFlow(tenant, workspace, flowName)?.maxOutputTokens;
4206
+ }
4207
+ catch {
4208
+ flowMaxOut = undefined;
4209
+ }
4188
4210
  const run = {
4189
4211
  id: `run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`,
4190
4212
  flow: flowName,
@@ -4203,6 +4225,11 @@ a2a) {
4203
4225
  optional: s.optional ?? false,
4204
4226
  model: s.model,
4205
4227
  effort: s.effort,
4228
+ // The flow's default snapshotted here, as a step's own options are:
4229
+ // what the run started with is what it runs with. A step from a
4230
+ // nested flow carries that flow's own (expandSubflows).
4231
+ ...((s.maxOutputTokens ?? s.flowMaxOutputTokens ?? flowMaxOut) ? { maxOutputTokens: s.maxOutputTokens ?? s.flowMaxOutputTokens ?? flowMaxOut } : {}),
4232
+ ...((s.flowMaxOutputTokens ?? flowMaxOut) ? { flowMaxOutputTokens: s.flowMaxOutputTokens ?? flowMaxOut } : {}),
4206
4233
  approve: s.approve,
4207
4234
  when: s.when,
4208
4235
  case: s.case,
@@ -5152,6 +5179,8 @@ function driveRunInner(tenant, workspace, run, modelOverride, tags, opts) {
5152
5179
  delegation: id,
5153
5180
  instruction: job,
5154
5181
  group: parent.group,
5182
+ // A job done for a step is held to that step's output limit.
5183
+ ...(parent.maxOutputTokens ? { maxOutputTokens: parent.maxOutputTokens } : {}),
5155
5184
  optional: true,
5156
5185
  timeout: parent.timeout,
5157
5186
  attempts: 1,
@@ -5641,6 +5670,9 @@ function driveRunInner(tenant, workspace, run, modelOverride, tags, opts) {
5641
5670
  optional: false,
5642
5671
  model: step.model,
5643
5672
  effort: step.effort,
5673
+ // The step's output limit (its own, or the flow's snapshotted
5674
+ // on it) holds for whoever takes the step over (Codex review).
5675
+ ...(step.maxOutputTokens ? { maxOutputTokens: step.maxOutputTokens } : {}),
5644
5676
  timeout: step.timeout,
5645
5677
  // The rescuer inherits the contract, not just the job: a step
5646
5678
  // that promised data still owes data when someone else does it,
@@ -5734,6 +5766,10 @@ function driveRunInner(tenant, workspace, run, modelOverride, tags, opts) {
5734
5766
  instruction: m[2].trim(),
5735
5767
  group: chooser.group,
5736
5768
  optional: false,
5769
+ // The output limit of the flow the chooser was written in, as a
5770
+ // step of that file would have it (Codex review); the chooser's
5771
+ // own options are its own.
5772
+ ...(chooser.flowMaxOutputTokens ? { maxOutputTokens: chooser.flowMaxOutputTokens, flowMaxOutputTokens: chooser.flowMaxOutputTokens } : {}),
5737
5773
  attempts: 0,
5738
5774
  status: "pending",
5739
5775
  events: [],
@@ -5933,11 +5969,17 @@ function expandSubflows(tenant, workspace, steps, seen = [], depth = 0) {
5933
5969
  for (const ns of nestedSteps) {
5934
5970
  const g = base + ns.group;
5935
5971
  maxGroup = Math.max(maxGroup, g);
5972
+ // The nested flow's own output limit holds for its steps (a step's
5973
+ // own still wins), as its file says (Codex review).
5974
+ const flowMax = ns.flowMaxOutputTokens ?? nested.maxOutputTokens;
5975
+ const maxOut = ns.maxOutputTokens ?? flowMax;
5936
5976
  out.push({
5937
5977
  ...ns,
5938
5978
  group: g,
5939
5979
  optional: ns.optional || step.optional,
5940
5980
  instruction: ns.instruction || step.instruction,
5981
+ ...(maxOut ? { maxOutputTokens: maxOut } : {}),
5982
+ ...(flowMax ? { flowMaxOutputTokens: flowMax } : {}),
5941
5983
  });
5942
5984
  }
5943
5985
  group = maxGroup;
@@ -48,6 +48,14 @@ export interface ScanOptions {
48
48
  model: string;
49
49
  on: string;
50
50
  } | null;
51
+ /** The most one reply may be on the model this account's steps run on
52
+ * (a `model:` word or id) — the price list's ceiling on foldrun's
53
+ * models — or null when that is not known here. */
54
+ outputCeiling?: (model: string) => {
55
+ ceiling: number;
56
+ model: string;
57
+ on: string;
58
+ } | null;
51
59
  }
52
60
  export declare const OWASP_URL = "https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026";
53
61
  export declare const SCAN_RULES: readonly ScanRule[];
package/dist/src/scan.js CHANGED
@@ -32,7 +32,7 @@ import { resolveNetwork } from "./network.js";
32
32
  import { frontmatterProblems, schemaKindOf } from "./frontmatter-schema.js";
33
33
  import { parseRemotes } from "./a2a-remotes.js";
34
34
  import { isA2aPublished } from "./a2a-publish.js";
35
- import { parseFlow, resolveEffort } from "./store.js";
35
+ import { parseFlow, resolveEffort, parseMaxOutputTokens } from "./store.js";
36
36
  export const OWASP_URL = "https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026";
37
37
  export const SCAN_RULES = [
38
38
  {
@@ -239,6 +239,15 @@ export const SCAN_RULES = [
239
239
  "The step still runs, at the nearest level the model has, and the step's log says so. Write the level it has, or choose " +
240
240
  "a provider whose model has the one you want (Settings → Model provider).",
241
241
  },
242
+ {
243
+ id: "config/output-fitted",
244
+ category: "config",
245
+ level: "warn",
246
+ title: "A max_output_tokens above what the account's model allows",
247
+ help: "On foldrun's models one reply may be at most the price list's ceiling for its model. The step still runs, with " +
248
+ "the ceiling as its limit, and the step's log says so. Write a number at or under the ceiling, or run the agent " +
249
+ "on your own key.",
250
+ },
242
251
  {
243
252
  id: "config/cron-never-fires",
244
253
  category: "config",
@@ -956,6 +965,67 @@ function scanEfforts(agents, flows, runsAs, push) {
956
965
  });
957
966
  }
958
967
  }
968
+ /**
969
+ * A `max_output_tokens:` above the ceiling of the model a step will run on:
970
+ * warned, not refused (the step runs at the ceiling). Resolved step → flow
971
+ * → agent, the written value first, as scanEfforts does.
972
+ */
973
+ function scanOutputs(agents, flows, ceilingOf, push) {
974
+ const say = (file, line, asked, model, whence) => {
975
+ const c = ceilingOf(model);
976
+ if (!c || asked <= c.ceiling)
977
+ return;
978
+ push("config/output-fitted", file, line, `config/output-fitted ${file} ${whence} ${asked} ${c.model}`, `max_output_tokens: ${asked}${whence} runs as ${c.ceiling} on ${c.on} (${c.model}) — the price list's ceiling for that model.`);
979
+ };
980
+ const byName = new Map();
981
+ const ownProvider = new Set();
982
+ for (const a of agents) {
983
+ const model = typeof a.data.model === "string" && a.data.model.trim() ? a.data.model.trim() : "default";
984
+ byName.set(a.name, { model, raw: a.data.max_output_tokens });
985
+ if (a.data.provider) {
986
+ ownProvider.add(a.name);
987
+ continue;
988
+ }
989
+ const n = parseMaxOutputTokens(a.data.max_output_tokens);
990
+ if (n)
991
+ say(a.file, keyLine(a.lines, "max_output_tokens"), n, model, "");
992
+ }
993
+ for (const fl of flows) {
994
+ let info;
995
+ try {
996
+ info = parseFlow(fl.file, fl.content);
997
+ }
998
+ catch {
999
+ continue;
1000
+ }
1001
+ const steps = [...(info.steps ?? [])].sort((x, y) => (x.line ?? 0) - (y.line ?? 0));
1002
+ const flowLine = keyLine(fl.lines, "max_output_tokens");
1003
+ steps.forEach((st, i) => {
1004
+ if (st.subflow || ownProvider.has(st.agent))
1005
+ return;
1006
+ const agent = byName.get(st.agent);
1007
+ const from = st.maxOutputTokens != null ? "step" : info.maxOutputTokens != null ? "flow" : "agent";
1008
+ const n = from === "step" ? st.maxOutputTokens : from === "flow" ? info.maxOutputTokens : parseMaxOutputTokens(agent?.raw);
1009
+ if (!n)
1010
+ return;
1011
+ const model = st.model ?? info.model ?? agent?.model ?? "default";
1012
+ if (from === "step") {
1013
+ const to = steps[i + 1]?.line ?? fl.lines.length + 1;
1014
+ let at;
1015
+ for (let k = st.line ?? 1; k < to; k++)
1016
+ if (/^\s+max_output_tokens\s*:/.test(fl.lines[k - 1] ?? ""))
1017
+ at = k;
1018
+ say(fl.file, at ?? st.line, n, model, ` (step ${st.agent})`);
1019
+ }
1020
+ else if (from === "flow") {
1021
+ say(fl.file, flowLine, n, model, ` (the flow's, on step ${st.agent})`);
1022
+ }
1023
+ else if (st.model || info.model) {
1024
+ say(fl.file, st.line, n, model, ` (${st.agent}'s own, on this step's model)`);
1025
+ }
1026
+ });
1027
+ }
1028
+ }
959
1029
  export function scanFiles(files, options = {}) {
960
1030
  const want = options.only?.length ? new Set(options.only) : null;
961
1031
  const enabled = (rule) => !want || want.has(rule) || want.has(scanRule(rule)?.category ?? "") || rule === "check/ignore-needs-reason";
@@ -1066,8 +1136,11 @@ export function scanFiles(files, options = {}) {
1066
1136
  scanPublishedFlows(flows, legs, push);
1067
1137
  // A workspace that names its own provider: does not run on the account's
1068
1138
  // choice, so the account's models say nothing about its efforts.
1069
- if (options.effortRunsAs && !(workspaceMd && frontOf(workspaceMd.content, "AGENTS.md")?.provider))
1139
+ const ownWorkspaceProvider = Boolean(workspaceMd && frontOf(workspaceMd.content, "AGENTS.md")?.provider);
1140
+ if (options.effortRunsAs && !ownWorkspaceProvider)
1070
1141
  scanEfforts(agents, flows, options.effortRunsAs, push);
1142
+ if (options.outputCeiling && !ownWorkspaceProvider)
1143
+ scanOutputs(agents, flows, options.outputCeiling, push);
1071
1144
  for (const m of more.values()) {
1072
1145
  findings.push({ rule: m.rule, level: m.level ?? scanRule(m.rule)?.level ?? "warn", file: m.file, message: `and ${m.n} more like this in this file, not listed`, fingerprint: m.hash.digest("hex").slice(0, 16), truncated: true });
1073
1146
  }
@@ -451,6 +451,7 @@ Indented under a step, any of:
451
451
  | \`verify: judge: <claim>\` | a model grades the claim against the output |
452
452
  | \`verify: contains:\` / \`not-contains:\` / \`matches:\` / \`file:\` | the cheap checks, no shell |
453
453
  | \`model:\` / \`effort:\` | override the flow's default for this step |
454
+ | \`max_output_tokens:\` | the longest one reply may be, in tokens, for this step |
454
455
  | \`loop: 3\` / \`until: <condition>\` | repeat until it holds, at most 5 |
455
456
  | \`each: lines\` | run once per line of the previous result |
456
457
  | \`each: rows of <path>\` | run once per CSV row |
@@ -306,6 +306,8 @@ export interface AgentInfo {
306
306
  * the interface did not say so, so every consumer had to re-read the file
307
307
  * to show it. */
308
308
  effort: string | null;
309
+ /** `max_output_tokens:` — the longest one reply may be, when it says. */
310
+ maxOutputTokens?: number;
309
311
  tools: string[];
310
312
  apis: ApiSpec[];
311
313
  /** `remotes:` — the outside A2A agents it may call, the entries that read
@@ -511,6 +513,14 @@ export interface FlowStep {
511
513
  parallel?: number;
512
514
  /** `max_turns:` — the most model turns this step may take before it is
513
515
  * stopped, beside `budget:` (money) and `timeout:` (time). */
516
+ /** `max_output_tokens:` — the longest one model reply may be, in tokens.
517
+ * On a run's step: the step's own, else the flow's, snapshotted when the
518
+ * run was created (createFlowRun); the agent's is read at the step. */
519
+ maxOutputTokens?: number;
520
+ /** The `max_output_tokens:` default of the flow this step was written in
521
+ * (a nested flow's own, when it came from one): what a `delegate:`
522
+ * chooser's picks are held to. Set by expansion and createFlowRun. */
523
+ flowMaxOutputTokens?: number;
514
524
  maxTurns?: number;
515
525
  /** `limits: {web.search: 10}` — this step's call limits, over the agent's
516
526
  * (nearest wins per key). See limits.ts. */
@@ -536,6 +546,8 @@ export interface FlowInfo {
536
546
  model: string | null;
537
547
  /** Same, for effort. */
538
548
  effort: string | null;
549
+ /** `max_output_tokens:` — every step's longest reply unless it says. */
550
+ maxOutputTokens?: number;
539
551
  /** What a new fire does while a run of this flow is still live:
540
552
  * "skip" doesn't start one, "queue" starts it but the worker holds it
541
553
  * until the live run finishes. Unset keeps today's behaviour (runs may
@@ -688,6 +700,12 @@ export declare const STEP_OPTION_KEYS: ReadonlySet<string>;
688
700
  /** The most fan-out instances `parallel:` may run at once — the fan-out's
689
701
  * own hard cap, since more slots than items is no cap. */
690
702
  export declare const PARALLEL_CAP = 20;
703
+ /** The most `max_output_tokens:` may say — 2^20, above any model's own
704
+ * limit today (Kimi's 1,048,576): a ceiling on typos, not on models. */
705
+ export declare const MAX_OUTPUT_TOKENS_CAP = 1048576;
706
+ /** `max_output_tokens:` as a whole number of tokens, or undefined when it
707
+ * is not one in range (YAML may hand over a number or a string). */
708
+ export declare function parseMaxOutputTokens(v: unknown): number | undefined;
691
709
  /** The most turns `max_turns:` may allow. A turn is one model reply, tool
692
710
  * calls included; a step that needs more than this is not one step. */
693
711
  export declare const MAX_TURNS_CAP = 500;
@@ -792,7 +810,7 @@ declare function setFlowTriggerLF(raw: string, opts: {
792
810
  schedule?: string;
793
811
  timezone?: string;
794
812
  }): string;
795
- declare function updateFlowStepLF(raw: string, index: number, options: Partial<Record<"model" | "effort" | "retry" | "timeout" | "verify" | "when" | "case" | "else" | "loop" | "until" | "each" | "max" | "limits", string | number | null>>): string;
813
+ declare function updateFlowStepLF(raw: string, index: number, options: Partial<Record<"model" | "effort" | "max_output_tokens" | "retry" | "timeout" | "verify" | "when" | "case" | "else" | "loop" | "until" | "each" | "max" | "limits", string | number | null>>): string;
796
814
  /** Append a step as its own group at the end of the flow. */
797
815
  declare function addFlowStepLF(raw: string, step: {
798
816
  target: string;
@@ -1258,6 +1276,9 @@ export interface StepRecord {
1258
1276
  schema?: Record<string, unknown> | boolean;
1259
1277
  schemaPath?: string;
1260
1278
  parallel?: number;
1279
+ maxOutputTokens?: number;
1280
+ /** See FlowStep: the default of the flow this step was written in. */
1281
+ flowMaxOutputTokens?: number;
1261
1282
  maxTurns?: number;
1262
1283
  limits?: Record<string, number>;
1263
1284
  /** The parsed JSON an `output: json` step returned. Kept beside the prose
package/dist/src/store.js CHANGED
@@ -1186,6 +1186,7 @@ export function listAgents(tenant, workspace) {
1186
1186
  ...resolveOwner(data.owner, workspaceFront.owner, accountFront.owner),
1187
1187
  model: data.model ?? "default",
1188
1188
  effort: data.effort ?? null,
1189
+ ...(parseMaxOutputTokens(data.max_output_tokens) ? { maxOutputTokens: parseMaxOutputTokens(data.max_output_tokens) } : {}),
1189
1190
  tools,
1190
1191
  apis: parseApis(data.apis),
1191
1192
  remotes: parseRemotes(data.remotes),
@@ -1239,7 +1240,7 @@ const OPTION_RE = /^(\s+)([a-z_-]+):(.*)$/;
1239
1240
  * swallowed as an unknown option, silently, along with any typo of a real
1240
1241
  * key. The consistency suite reads this list against the docs. */
1241
1242
  export const STEP_OPTION_KEYS = new Set([
1242
- "approve", "ask", "case", "delegate", "each", "effort", "else", "limits", "loop", "max", "max_turns", "model",
1243
+ "approve", "ask", "case", "delegate", "each", "effort", "else", "limits", "loop", "max", "max_output_tokens", "max_turns", "model",
1243
1244
  "on-fail", "onfail", "output", "parallel", "preview", "retry", "schema", "timeout", "until", "verify", "wait", "when",
1244
1245
  ]);
1245
1246
  /** A line that opens a markdown block rather than continuing a sentence:
@@ -1250,6 +1251,15 @@ const MARKDOWN_BLOCK_RE = /^(?:#{1,6}\s|[-*+]\s|>\s|\d+[.)]\s|\*\*|__|---|\|)/;
1250
1251
  /** The most fan-out instances `parallel:` may run at once — the fan-out's
1251
1252
  * own hard cap, since more slots than items is no cap. */
1252
1253
  export const PARALLEL_CAP = 20;
1254
+ /** The most `max_output_tokens:` may say — 2^20, above any model's own
1255
+ * limit today (Kimi's 1,048,576): a ceiling on typos, not on models. */
1256
+ export const MAX_OUTPUT_TOKENS_CAP = 1_048_576;
1257
+ /** `max_output_tokens:` as a whole number of tokens, or undefined when it
1258
+ * is not one in range (YAML may hand over a number or a string). */
1259
+ export function parseMaxOutputTokens(v) {
1260
+ const n = typeof v === "number" ? v : typeof v === "string" && /^\s*\d+\s*$/.test(v) ? Number(v) : NaN;
1261
+ return Number.isInteger(n) && n >= 1 && n <= MAX_OUTPUT_TOKENS_CAP ? n : undefined;
1262
+ }
1253
1263
  /** The most turns `max_turns:` may allow. A turn is one model reply, tool
1254
1264
  * calls included; a step that needs more than this is not one step. */
1255
1265
  export const MAX_TURNS_CAP = 500;
@@ -1601,6 +1611,13 @@ export function parseFlow(file, raw) {
1601
1611
  else
1602
1612
  step.parallel = n;
1603
1613
  }
1614
+ else if (key === "max_output_tokens") {
1615
+ const n = parseMaxOutputTokens(value);
1616
+ if (n === undefined)
1617
+ problem(`a whole number of tokens, 1 to ${MAX_OUTPUT_TOKENS_CAP}`);
1618
+ else
1619
+ step.maxOutputTokens = n;
1620
+ }
1604
1621
  else if (key === "max_turns") {
1605
1622
  const n = parseCount(value, 1, MAX_TURNS_CAP);
1606
1623
  if (n === undefined)
@@ -1659,6 +1676,7 @@ export function parseFlow(file, raw) {
1659
1676
  timezone: data.timezone ?? null,
1660
1677
  model: data.model ?? null,
1661
1678
  effort: data.effort ?? null,
1679
+ ...(parseMaxOutputTokens(data.max_output_tokens) ? { maxOutputTokens: parseMaxOutputTokens(data.max_output_tokens) } : {}),
1662
1680
  overlap: data.overlap === "skip" || data.overlap === "queue" ? data.overlap : null,
1663
1681
  ...(data.issues === "auto-close" || data.issues === "stay-open" ? { issues: data.issues } : {}),
1664
1682
  live: data.live === true,
@@ -1919,6 +1937,14 @@ function updateFlowStepLF(raw, index, options) {
1919
1937
  const clamp = {
1920
1938
  model: (v) => v || null,
1921
1939
  effort: (v) => resolveEffort(v) ?? null,
1940
+ max_output_tokens: (v) => {
1941
+ if (!v)
1942
+ return null;
1943
+ const n = parseMaxOutputTokens(v);
1944
+ if (n === undefined)
1945
+ throw new Error(`max_output_tokens: ${v} is not a whole number of tokens, 1 to ${MAX_OUTPUT_TOKENS_CAP}`);
1946
+ return String(n);
1947
+ },
1922
1948
  verify: (v) => v || null,
1923
1949
  when: (v) => v || null,
1924
1950
  case: (v) => v || null,
@@ -3667,8 +3693,23 @@ export function providerEnvFor(spec) {
3667
3693
  const lines = Object.entries(spec.headers).map(([k, v]) => `${k}: ${v}`);
3668
3694
  if (lines.length)
3669
3695
  env.ANTHROPIC_CUSTOM_HEADERS = lines.join("\n");
3696
+ // Claude Code puts an attribution line in every request's system prompt,
3697
+ // which means something to Anthropic only. Anywhere else it is prompt
3698
+ // text the provider is sent for nothing (e2e check, 3 Nov 2026).
3699
+ if (spec.baseUrl && !isAnthropicOrigin(spec.baseUrl))
3700
+ env.CLAUDE_CODE_ATTRIBUTION_HEADER = "0";
3670
3701
  return env;
3671
3702
  }
3703
+ /** Whether a base URL is Anthropic's own API (where the SDK's own
3704
+ * attribution belongs). */
3705
+ function isAnthropicOrigin(baseUrl) {
3706
+ try {
3707
+ return new URL(baseUrl).hostname.toLowerCase() === "api.anthropic.com";
3708
+ }
3709
+ catch {
3710
+ return false;
3711
+ }
3712
+ }
3672
3713
  // The workspace tree, for history's first commit — see registerTreeReader.
3673
3714
  registerTreeReader((tenant, scope) => {
3674
3715
  if (scope === "@library" || !fs.existsSync(workspaceDir(tenant, scope)))
@@ -62,6 +62,12 @@ function effortCheck(tenant, accountProvider) {
62
62
  const runs = effortRunsAs(provider, id, effort);
63
63
  return runs ? { effort: runs, model: id, on } : null;
64
64
  },
65
+ outputCeiling: (model) => {
66
+ const tier = resolveTier(model);
67
+ const id = tier ? tiers[tier] : model;
68
+ const ceiling = id ? answer.ceilings?.[id] : undefined;
69
+ return id && ceiling ? { ceiling, model: id, on } : null;
70
+ },
65
71
  };
66
72
  }
67
73
  export function checkWorkspace(tenant, workspace, tree = checkTree(workspaceDir(tenant, workspace))) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "14.2.1",
3
+ "version": "14.3.1",
4
4
  "description": "Agents are just folders. The format, the runner, the checks.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "type": "module",
@@ -138,6 +138,7 @@ const FIELDS: Record<string, Completion[]> = {
138
138
  { label: "description", insert: "description: ", hint: "required — what it does, and when" },
139
139
  { label: "model", insert: "model: default" },
140
140
  { label: "effort", insert: "effort: high", hint: "how hard it thinks" },
141
+ { label: "max_output_tokens", insert: "max_output_tokens: 16000", hint: "the longest one reply may be, in tokens" },
141
142
  { label: "tools", insert: "tools:\n - write", hint: "what the runtime gives it" },
142
143
  { label: "secrets", insert: "secrets:\n - ", hint: "credentials it may spend" },
143
144
  { label: "skills", insert: "skills:\n - ", hint: "allowlist; omit to inherit all" },
@@ -212,6 +213,7 @@ const FIELDS: Record<string, Completion[]> = {
212
213
  { label: "timezone", insert: "timezone: Australia/Sydney" },
213
214
  { label: "model", insert: "model: fast", hint: "every step, unless the step says" },
214
215
  { label: "effort", insert: "effort: high", hint: "every step, unless the step says" },
216
+ { label: "max_output_tokens", insert: "max_output_tokens: 16000", hint: "every step's longest reply, unless the step says" },
215
217
  ],
216
218
  evalFile: [
217
219
  { label: "name", insert: "name: " },
@@ -322,6 +324,7 @@ const STEP_OPTIONS: Completion[] = [
322
324
  { label: "each", insert: "each: items", hint: "fan out: lines | items | rows of <csv>" },
323
325
  { label: "model", insert: "model: fast" },
324
326
  { label: "effort", insert: "effort: high", hint: "this step only" },
327
+ { label: "max_output_tokens", insert: "max_output_tokens: 16000", hint: "the longest one reply may be, this step only" },
325
328
  { label: "approve", insert: "approve: true", hint: "pause for a human" },
326
329
  ];
327
330
 
package/src/flow-lint.ts CHANGED
@@ -24,7 +24,7 @@ const SUBFLOW_DROPPED: [keyof FlowStep, string][] = [
24
24
  ["effort", "effort:"], ["onFail", "on-fail:"], ["waitSecs", "wait:"], ["waitFor", "wait:"],
25
25
  ["ask", "ask:"], ["preview", "preview:"], ["delegate", "delegate:"], ["loop", "loop:"],
26
26
  ["until", "until:"], ["each", "each:"], ["max", "max:"], ["output", "output:"],
27
- ["schema", "schema:"], ["parallel", "parallel:"], ["maxTurns", "max_turns:"], ["limits", "limits:"],
27
+ ["schema", "schema:"], ["parallel", "parallel:"], ["maxTurns", "max_turns:"], ["maxOutputTokens", "max_output_tokens:"], ["limits", "limits:"],
28
28
  ];
29
29
 
30
30
  export interface FlowWarning {
@@ -78,6 +78,7 @@ const AGENT: FieldSpec[] = [
78
78
  { key: "owner", type: "string", help: "the person accountable for it — an email or a name; else the workspace's, else the account's" },
79
79
  { key: "model", type: "string", help: "fast | default | max, an alias, or a full model id" },
80
80
  { key: "effort", type: "string", values: EFFORT_LEVELS, help: "how long it thinks" },
81
+ { key: "max_output_tokens", type: ["number", "string"], help: "the most tokens one model reply may have, 1 to 1048576; on foldrun's models the price list's ceiling applies too" },
81
82
  { key: "size", type: "string", values: ["small", "large", "heavy"], help: "the sandbox it rents; anything else becomes large" },
82
83
  { key: "resources", type: "object", help: "{cpu, memory, disk} in numbers, over the size class's figures key by key — cpu 0.5–8, memory 256Mi–16Gi, disk 1–40Gi" },
83
84
  { key: "permissionMode", type: "string", values: ["plan"], help: "plan = read-only; no other mode changes anything here" },
@@ -151,6 +152,7 @@ const FLOW: FieldSpec[] = [
151
152
  { key: "timezone", type: "string", validated: true, help: "the zone its schedule reads in" },
152
153
  { key: "model", type: "string", help: "every step's model unless the step says" },
153
154
  { key: "effort", type: "string", values: EFFORT_LEVELS, help: "every step's effort unless the step says" },
155
+ { key: "max_output_tokens", type: ["number", "string"], help: "every step's longest reply, in tokens, unless the step or its agent says" },
154
156
  { key: "overlap", type: "string", validated: true, help: "skip | queue" },
155
157
  { key: "issues", type: "string", values: ["stay-open", "auto-close"], help: "what a good run does to this flow's open issues: stay-open (the default — a person resolves them) or auto-close" },
156
158
  { key: "priority", type: "string", validated: true, help: "high | normal | low" },
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { FRONTMATTER, JOBS, type FieldType, type SchemaKind } from "./frontmatter-fields.ts";
6
6
  import { jobFold } from "./matter.ts";
7
- import { resolveEffort, parseDuration, parseInstant, parseRate, STEP_OPTION_KEYS } from "./store.ts";
7
+ import { resolveEffort, parseDuration, parseInstant, parseRate, STEP_OPTION_KEYS, parseMaxOutputTokens, MAX_OUTPUT_TOKENS_CAP } from "./store.ts";
8
8
  import { budgetProblem } from "./budget.ts";
9
9
  import { cronProblem, parseCron, cronCanFire } from "./cron.ts";
10
10
  import { SECRET_NAME } from "./secrets.ts";
@@ -29,11 +29,17 @@ const DURATION = (min: number, max: number, unit = "") => (v: unknown) => {
29
29
  return null;
30
30
  };
31
31
 
32
+ /** `max_output_tokens:` — a whole number of tokens the runtime can be told. */
33
+ function maxOutputProblem(v: unknown): string | null {
34
+ return parseMaxOutputTokens(v) === undefined ? `${shown(v)} is not a number of tokens, 1 to ${MAX_OUTPUT_TOKENS_CAP}; the model's own limit applies` : null;
35
+ }
36
+
32
37
  /** Why a value is wrong, or null — per kind, per field: the rules a list of
33
38
  * values cannot say (aliases, durations, cron, budgets). */
34
39
  const CHECKS: Partial<Record<SchemaKind, Record<string, (value: unknown) => string | null>>> = {
35
40
  "agent": {
36
41
  effort: (v) => (resolveEffort(v) ? null : `"${String(v)}" is not an effort — low, medium, high, xhigh or max; the step runs at the model's default`),
42
+ max_output_tokens: maxOutputProblem,
37
43
  apis: apisProblem,
38
44
  remotes: remotesProblem,
39
45
  budget: (v) => budgetProblem(v, ["run"]),
@@ -49,6 +55,7 @@ const CHECKS: Partial<Record<SchemaKind, Record<string, (value: unknown) => stri
49
55
  "flow": {
50
56
  schedule: cronProblem,
51
57
  effort: (v) => (resolveEffort(v) ? null : `"${String(v)}" is not an effort — low, medium, high, xhigh or max`),
58
+ max_output_tokens: maxOutputProblem,
52
59
  at: (v) => (parseInstant(v) ? null : `"${String(v)}" is not an ISO 8601 instant — a once flow with it never fires`),
53
60
  url: (v) => (/^https?:\/\//i.test(String(v)) ? null : `"${String(v)}" is not an http(s) URL`),
54
61
  every: DURATION(1, 30 * 86400, "1s to 30 days"),
@@ -165,7 +165,14 @@ export const SUPPLY_KEY_NAME = "FOLDRUN_SUPPLY_KEY";
165
165
  */
166
166
  export type SupplyAnswer =
167
167
  | { kind: "none" }
168
- | { kind: "foldrun"; provider: SupplyProviderName; tiers: Partial<Record<"fast" | "default" | "max", string>> }
168
+ | {
169
+ kind: "foldrun";
170
+ provider: SupplyProviderName;
171
+ tiers: Partial<Record<"fast" | "default" | "max", string>>;
172
+ /** The price list's output ceiling per model id: the most one reply
173
+ * may be on the platform's key, told to the runtime up front. */
174
+ ceilings?: Record<string, number>;
175
+ }
169
176
  | { kind: "refused"; reason: string };
170
177
 
171
178
  /** The token a supply provider block carries: a marker, not a secret. The
package/src/runner.ts CHANGED
@@ -73,6 +73,7 @@ import {
73
73
  parseProvider,
74
74
  providerEnvFor,
75
75
  resolveEffort,
76
+ parseMaxOutputTokens,
76
77
  isEffortWord,
77
78
  EFFORT_LEVELS,
78
79
  checkFormatVersion,
@@ -2672,6 +2673,21 @@ async function runStep(
2672
2673
  // step was stopped at up to fifteen times what it had spent.
2673
2674
  tokenPrice ??= knownPrice(wireModel);
2674
2675
 
2676
+ // `max_output_tokens:` — the step's own (or its flow's, snapshotted on
2677
+ // the run), else the agent's; on foldrun's models never above the price
2678
+ // list's ceiling for the model it runs, so the runtime knows its real
2679
+ // limit up front instead of the gateway cutting it short (3 Nov 2026).
2680
+ const askedOut = step.maxOutputTokens ?? parseMaxOutputTokens(front.max_output_tokens);
2681
+ const outCeiling = onSupply && supply.kind === "foldrun" ? supply.ceilings?.[wireModel] : undefined;
2682
+ const maxOut = askedOut && outCeiling ? Math.min(askedOut, outCeiling) : (askedOut ?? outCeiling);
2683
+ if (askedOut && outCeiling && askedOut > outCeiling) {
2684
+ push("info", `max_output_tokens: ${askedOut} runs as ${outCeiling} — the price list's ceiling for ${wireModel} on foldrun's models`);
2685
+ }
2686
+ const outputEnv: Record<string, string> = maxOut ? { CLAUDE_CODE_MAX_OUTPUT_TOKENS: String(maxOut) } : {};
2687
+ if (maxOut && !(askedOut && outCeiling && askedOut > outCeiling)) {
2688
+ push("info", `max_output_tokens: ${maxOut}${askedOut ? "" : " — the price list's ceiling on foldrun's models"}`);
2689
+ }
2690
+
2675
2691
  fs.mkdirSync(path.join(agentDir, "outputs"), { recursive: true });
2676
2692
  fs.mkdirSync(path.join(agentDir, "memory"), { recursive: true });
2677
2693
 
@@ -3276,6 +3292,7 @@ async function runStep(
3276
3292
  // A provider: block still wins, because providerEnv is spread
3277
3293
  // after and carries the agent's chosen endpoint + token.
3278
3294
  ...proxied(Object.keys(providerEnv).length === 0 ? modelEnv : providerEnv, keyName),
3295
+ ...outputEnv,
3279
3296
  ...(lease ? { [EGRESS_ENV]: lease.url } : {}),
3280
3297
  // Every program's HTTP(S) through the proxy's forward door, and
3281
3298
  // the CA it signs bound sites with, for the sandbox to trust.
@@ -3742,7 +3759,7 @@ async function runStep(
3742
3759
  // the allowlisted host environment, not process.env: the SDK's
3743
3760
  // Bash tool runs with this, and on a platform process.env holds
3744
3761
  // every tenant's root key and the datastore credentials.
3745
- env: { ...hostSafeEnv(), ...clockEnv, ...(testRun ? testModeEnv() : {}), ...mat.env, ...installEnv, ...modelEnv },
3762
+ env: { ...hostSafeEnv(), ...clockEnv, ...(testRun ? testModeEnv() : {}), ...mat.env, ...installEnv, ...modelEnv, ...outputEnv },
3746
3763
  timeoutSec: step.timeout,
3747
3764
  budgetUsd: stepBudgetUsd,
3748
3765
  budgetNote: stepBudgetNote,
@@ -4401,6 +4418,12 @@ export function createFlowRun(
4401
4418
  * own trailing argument, so the signature only widened. */
4402
4419
  a2a?: { task: string; key: string },
4403
4420
  ): RunRecord {
4421
+ let flowMaxOut: number | undefined;
4422
+ try {
4423
+ flowMaxOut = readFlow(tenant, workspace, flowName)?.maxOutputTokens;
4424
+ } catch {
4425
+ flowMaxOut = undefined;
4426
+ }
4404
4427
  const run: RunRecord = {
4405
4428
  id: `run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`,
4406
4429
  flow: flowName,
@@ -4419,6 +4442,11 @@ export function createFlowRun(
4419
4442
  optional: s.optional ?? false,
4420
4443
  model: s.model,
4421
4444
  effort: s.effort,
4445
+ // The flow's default snapshotted here, as a step's own options are:
4446
+ // what the run started with is what it runs with. A step from a
4447
+ // nested flow carries that flow's own (expandSubflows).
4448
+ ...((s.maxOutputTokens ?? s.flowMaxOutputTokens ?? flowMaxOut) ? { maxOutputTokens: s.maxOutputTokens ?? s.flowMaxOutputTokens ?? flowMaxOut } : {}),
4449
+ ...((s.flowMaxOutputTokens ?? flowMaxOut) ? { flowMaxOutputTokens: s.flowMaxOutputTokens ?? flowMaxOut } : {}),
4422
4450
  approve: s.approve,
4423
4451
  when: s.when,
4424
4452
  case: s.case,
@@ -5387,6 +5415,8 @@ function driveRunInner(
5387
5415
  delegation: id,
5388
5416
  instruction: job,
5389
5417
  group: parent.group,
5418
+ // A job done for a step is held to that step's output limit.
5419
+ ...(parent.maxOutputTokens ? { maxOutputTokens: parent.maxOutputTokens } : {}),
5390
5420
  optional: true,
5391
5421
  timeout: parent.timeout,
5392
5422
  attempts: 1,
@@ -5901,6 +5931,9 @@ function driveRunInner(
5901
5931
  optional: false,
5902
5932
  model: step.model,
5903
5933
  effort: step.effort,
5934
+ // The step's output limit (its own, or the flow's snapshotted
5935
+ // on it) holds for whoever takes the step over (Codex review).
5936
+ ...(step.maxOutputTokens ? { maxOutputTokens: step.maxOutputTokens } : {}),
5904
5937
  timeout: step.timeout,
5905
5938
  // The rescuer inherits the contract, not just the job: a step
5906
5939
  // that promised data still owes data when someone else does it,
@@ -5990,6 +6023,10 @@ function driveRunInner(
5990
6023
  instruction: m[2].trim(),
5991
6024
  group: chooser.group,
5992
6025
  optional: false,
6026
+ // The output limit of the flow the chooser was written in, as a
6027
+ // step of that file would have it (Codex review); the chooser's
6028
+ // own options are its own.
6029
+ ...(chooser.flowMaxOutputTokens ? { maxOutputTokens: chooser.flowMaxOutputTokens, flowMaxOutputTokens: chooser.flowMaxOutputTokens } : {}),
5993
6030
  attempts: 0,
5994
6031
  status: "pending",
5995
6032
  events: [],
@@ -6198,11 +6235,17 @@ function expandSubflows(
6198
6235
  for (const ns of nestedSteps) {
6199
6236
  const g = base + ns.group;
6200
6237
  maxGroup = Math.max(maxGroup, g);
6238
+ // The nested flow's own output limit holds for its steps (a step's
6239
+ // own still wins), as its file says (Codex review).
6240
+ const flowMax = ns.flowMaxOutputTokens ?? nested.maxOutputTokens;
6241
+ const maxOut = ns.maxOutputTokens ?? flowMax;
6201
6242
  out.push({
6202
6243
  ...ns,
6203
6244
  group: g,
6204
6245
  optional: ns.optional || step.optional,
6205
6246
  instruction: ns.instruction || step.instruction,
6247
+ ...(maxOut ? { maxOutputTokens: maxOut } : {}),
6248
+ ...(flowMax ? { flowMaxOutputTokens: flowMax } : {}),
6206
6249
  });
6207
6250
  }
6208
6251
  group = maxGroup;
package/src/scan.ts CHANGED
@@ -33,7 +33,7 @@ import { resolveNetwork } from "./network.ts";
33
33
  import { frontmatterProblems, schemaKindOf } from "./frontmatter-schema.ts";
34
34
  import { parseRemotes } from "./a2a-remotes.ts";
35
35
  import { isA2aPublished } from "./a2a-publish.ts";
36
- import { parseFlow, resolveEffort, type FlowStep } from "./store.ts";
36
+ import { parseFlow, resolveEffort, parseMaxOutputTokens, type FlowStep } from "./store.ts";
37
37
 
38
38
  export type ScanLevel = "error" | "warn" | "info";
39
39
  export type ScanCategory = "secret" | "security" | "content" | "supply-chain" | "config";
@@ -85,6 +85,10 @@ export interface ScanOptions {
85
85
  * (a `model:` word or id, an effort word), and where — or null when that
86
86
  * is not known here (the CLI, offline: it knows no account's choice). */
87
87
  effortRunsAs?: (model: string, effort: string) => { effort: string; model: string; on: string } | null;
88
+ /** The most one reply may be on the model this account's steps run on
89
+ * (a `model:` word or id) — the price list's ceiling on foldrun's
90
+ * models — or null when that is not known here. */
91
+ outputCeiling?: (model: string) => { ceiling: number; model: string; on: string } | null;
88
92
  }
89
93
 
90
94
  export const OWASP_URL = "https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026";
@@ -314,6 +318,16 @@ export const SCAN_RULES: readonly ScanRule[] = [
314
318
  "The step still runs, at the nearest level the model has, and the step's log says so. Write the level it has, or choose " +
315
319
  "a provider whose model has the one you want (Settings → Model provider).",
316
320
  },
321
+ {
322
+ id: "config/output-fitted",
323
+ category: "config",
324
+ level: "warn",
325
+ title: "A max_output_tokens above what the account's model allows",
326
+ help:
327
+ "On foldrun's models one reply may be at most the price list's ceiling for its model. The step still runs, with " +
328
+ "the ceiling as its limit, and the step's log says so. Write a number at or under the ceiling, or run the agent " +
329
+ "on your own key.",
330
+ },
317
331
  {
318
332
  id: "config/cron-never-fires",
319
333
  category: "config",
@@ -1079,6 +1093,65 @@ function scanEfforts(agents: AgentFacts[], flows: FlowFacts[], runsAs: NonNullab
1079
1093
  }
1080
1094
  }
1081
1095
 
1096
+ /**
1097
+ * A `max_output_tokens:` above the ceiling of the model a step will run on:
1098
+ * warned, not refused (the step runs at the ceiling). Resolved step → flow
1099
+ * → agent, the written value first, as scanEfforts does.
1100
+ */
1101
+ function scanOutputs(agents: AgentFacts[], flows: FlowFacts[], ceilingOf: NonNullable<ScanOptions["outputCeiling"]>, push: Push): void {
1102
+ const say = (file: string, line: number | undefined, asked: number, model: string, whence: string) => {
1103
+ const c = ceilingOf(model);
1104
+ if (!c || asked <= c.ceiling) return;
1105
+ push(
1106
+ "config/output-fitted",
1107
+ file,
1108
+ line,
1109
+ `config/output-fitted ${file} ${whence} ${asked} ${c.model}`,
1110
+ `max_output_tokens: ${asked}${whence} runs as ${c.ceiling} on ${c.on} (${c.model}) — the price list's ceiling for that model.`,
1111
+ );
1112
+ };
1113
+ const byName = new Map<string, { model: string; raw: unknown }>();
1114
+ const ownProvider = new Set<string>();
1115
+ for (const a of agents) {
1116
+ const model = typeof a.data.model === "string" && a.data.model.trim() ? a.data.model.trim() : "default";
1117
+ byName.set(a.name, { model, raw: a.data.max_output_tokens });
1118
+ if (a.data.provider) {
1119
+ ownProvider.add(a.name);
1120
+ continue;
1121
+ }
1122
+ const n = parseMaxOutputTokens(a.data.max_output_tokens);
1123
+ if (n) say(a.file, keyLine(a.lines, "max_output_tokens"), n, model, "");
1124
+ }
1125
+ for (const fl of flows) {
1126
+ let info: ReturnType<typeof parseFlow>;
1127
+ try {
1128
+ info = parseFlow(fl.file, fl.content);
1129
+ } catch {
1130
+ continue;
1131
+ }
1132
+ const steps = [...(info.steps ?? [])].sort((x, y) => (x.line ?? 0) - (y.line ?? 0));
1133
+ const flowLine = keyLine(fl.lines, "max_output_tokens");
1134
+ steps.forEach((st, i) => {
1135
+ if (st.subflow || ownProvider.has(st.agent)) return;
1136
+ const agent = byName.get(st.agent);
1137
+ const from = st.maxOutputTokens != null ? "step" : info.maxOutputTokens != null ? "flow" : "agent";
1138
+ const n = from === "step" ? st.maxOutputTokens : from === "flow" ? info.maxOutputTokens : parseMaxOutputTokens(agent?.raw);
1139
+ if (!n) return;
1140
+ const model = st.model ?? info.model ?? agent?.model ?? "default";
1141
+ if (from === "step") {
1142
+ const to = steps[i + 1]?.line ?? fl.lines.length + 1;
1143
+ let at: number | undefined;
1144
+ for (let k = st.line ?? 1; k < to; k++) if (/^\s+max_output_tokens\s*:/.test(fl.lines[k - 1] ?? "")) at = k;
1145
+ say(fl.file, at ?? st.line, n, model, ` (step ${st.agent})`);
1146
+ } else if (from === "flow") {
1147
+ say(fl.file, flowLine, n, model, ` (the flow's, on step ${st.agent})`);
1148
+ } else if (st.model || info.model) {
1149
+ say(fl.file, st.line, n, model, ` (${st.agent}'s own, on this step's model)`);
1150
+ }
1151
+ });
1152
+ }
1153
+ }
1154
+
1082
1155
  export function scanFiles(files: ScanFile[], options: ScanOptions = {}): ScanFinding[] {
1083
1156
  const want = options.only?.length ? new Set(options.only) : null;
1084
1157
  const enabled = (rule: string) => !want || want.has(rule) || want.has(scanRule(rule)?.category ?? "") || rule === "check/ignore-needs-reason";
@@ -1182,7 +1255,9 @@ export function scanFiles(files: ScanFile[], options: ScanOptions = {}): ScanFin
1182
1255
  scanPublishedFlows(flows, legs, push);
1183
1256
  // A workspace that names its own provider: does not run on the account's
1184
1257
  // choice, so the account's models say nothing about its efforts.
1185
- if (options.effortRunsAs && !(workspaceMd && frontOf(workspaceMd.content, "AGENTS.md")?.provider)) scanEfforts(agents, flows, options.effortRunsAs, push);
1258
+ const ownWorkspaceProvider = Boolean(workspaceMd && frontOf(workspaceMd.content, "AGENTS.md")?.provider);
1259
+ if (options.effortRunsAs && !ownWorkspaceProvider) scanEfforts(agents, flows, options.effortRunsAs, push);
1260
+ if (options.outputCeiling && !ownWorkspaceProvider) scanOutputs(agents, flows, options.outputCeiling, push);
1186
1261
  for (const m of more.values()) {
1187
1262
  findings.push({ rule: m.rule, level: m.level ?? scanRule(m.rule)?.level ?? "warn", file: m.file, message: `and ${m.n} more like this in this file, not listed`, fingerprint: m.hash.digest("hex").slice(0, 16), truncated: true });
1188
1263
  }
package/src/starter.ts CHANGED
@@ -467,6 +467,7 @@ Indented under a step, any of:
467
467
  | \`verify: judge: <claim>\` | a model grades the claim against the output |
468
468
  | \`verify: contains:\` / \`not-contains:\` / \`matches:\` / \`file:\` | the cheap checks, no shell |
469
469
  | \`model:\` / \`effort:\` | override the flow's default for this step |
470
+ | \`max_output_tokens:\` | the longest one reply may be, in tokens, for this step |
470
471
  | \`loop: 3\` / \`until: <condition>\` | repeat until it holds, at most 5 |
471
472
  | \`each: lines\` | run once per line of the previous result |
472
473
  | \`each: rows of <path>\` | run once per CSV row |
package/src/store.ts CHANGED
@@ -984,6 +984,8 @@ export interface AgentInfo {
984
984
  * the interface did not say so, so every consumer had to re-read the file
985
985
  * to show it. */
986
986
  effort: string | null;
987
+ /** `max_output_tokens:` — the longest one reply may be, when it says. */
988
+ maxOutputTokens?: number;
987
989
  tools: string[];
988
990
  apis: ApiSpec[];
989
991
  /** `remotes:` — the outside A2A agents it may call, the entries that read
@@ -1360,6 +1362,14 @@ export interface FlowStep {
1360
1362
  parallel?: number;
1361
1363
  /** `max_turns:` — the most model turns this step may take before it is
1362
1364
  * stopped, beside `budget:` (money) and `timeout:` (time). */
1365
+ /** `max_output_tokens:` — the longest one model reply may be, in tokens.
1366
+ * On a run's step: the step's own, else the flow's, snapshotted when the
1367
+ * run was created (createFlowRun); the agent's is read at the step. */
1368
+ maxOutputTokens?: number;
1369
+ /** The `max_output_tokens:` default of the flow this step was written in
1370
+ * (a nested flow's own, when it came from one): what a `delegate:`
1371
+ * chooser's picks are held to. Set by expansion and createFlowRun. */
1372
+ flowMaxOutputTokens?: number;
1363
1373
  maxTurns?: number;
1364
1374
  /** `limits: {web.search: 10}` — this step's call limits, over the agent's
1365
1375
  * (nearest wins per key). See limits.ts. */
@@ -1386,6 +1396,8 @@ export interface FlowInfo {
1386
1396
  model: string | null;
1387
1397
  /** Same, for effort. */
1388
1398
  effort: string | null;
1399
+ /** `max_output_tokens:` — every step's longest reply unless it says. */
1400
+ maxOutputTokens?: number;
1389
1401
  /** What a new fire does while a run of this flow is still live:
1390
1402
  * "skip" doesn't start one, "queue" starts it but the worker holds it
1391
1403
  * until the live run finishes. Unset keeps today's behaviour (runs may
@@ -1676,6 +1688,7 @@ export function listAgents(tenant: string, workspace: string): AgentInfo[] {
1676
1688
  ...resolveOwner(data.owner, workspaceFront.owner, accountFront.owner),
1677
1689
  model: data.model ?? "default",
1678
1690
  effort: data.effort ?? null,
1691
+ ...(parseMaxOutputTokens(data.max_output_tokens) ? { maxOutputTokens: parseMaxOutputTokens(data.max_output_tokens) } : {}),
1679
1692
  tools,
1680
1693
  apis: parseApis(data.apis),
1681
1694
  remotes: parseRemotes(data.remotes),
@@ -1734,7 +1747,7 @@ const OPTION_RE = /^(\s+)([a-z_-]+):(.*)$/;
1734
1747
  * swallowed as an unknown option, silently, along with any typo of a real
1735
1748
  * key. The consistency suite reads this list against the docs. */
1736
1749
  export const STEP_OPTION_KEYS: ReadonlySet<string> = new Set([
1737
- "approve", "ask", "case", "delegate", "each", "effort", "else", "limits", "loop", "max", "max_turns", "model",
1750
+ "approve", "ask", "case", "delegate", "each", "effort", "else", "limits", "loop", "max", "max_output_tokens", "max_turns", "model",
1738
1751
  "on-fail", "onfail", "output", "parallel", "preview", "retry", "schema", "timeout", "until", "verify", "wait", "when",
1739
1752
  ]);
1740
1753
 
@@ -1747,6 +1760,17 @@ const MARKDOWN_BLOCK_RE = /^(?:#{1,6}\s|[-*+]\s|>\s|\d+[.)]\s|\*\*|__|---|\|)/;
1747
1760
  /** The most fan-out instances `parallel:` may run at once — the fan-out's
1748
1761
  * own hard cap, since more slots than items is no cap. */
1749
1762
  export const PARALLEL_CAP = 20;
1763
+ /** The most `max_output_tokens:` may say — 2^20, above any model's own
1764
+ * limit today (Kimi's 1,048,576): a ceiling on typos, not on models. */
1765
+ export const MAX_OUTPUT_TOKENS_CAP = 1_048_576;
1766
+
1767
+ /** `max_output_tokens:` as a whole number of tokens, or undefined when it
1768
+ * is not one in range (YAML may hand over a number or a string). */
1769
+ export function parseMaxOutputTokens(v: unknown): number | undefined {
1770
+ const n = typeof v === "number" ? v : typeof v === "string" && /^\s*\d+\s*$/.test(v) ? Number(v) : NaN;
1771
+ return Number.isInteger(n) && n >= 1 && n <= MAX_OUTPUT_TOKENS_CAP ? n : undefined;
1772
+ }
1773
+
1750
1774
  /** The most turns `max_turns:` may allow. A turn is one model reply, tool
1751
1775
  * calls included; a step that needs more than this is not one step. */
1752
1776
  export const MAX_TURNS_CAP = 500;
@@ -2066,6 +2090,11 @@ export function parseFlow(file: string, raw: string): FlowInfo {
2066
2090
  if (n === undefined) problem(`a whole number of instances to run at once, 1 to ${PARALLEL_CAP}`);
2067
2091
  else step.parallel = n;
2068
2092
  }
2093
+ else if (key === "max_output_tokens") {
2094
+ const n = parseMaxOutputTokens(value);
2095
+ if (n === undefined) problem(`a whole number of tokens, 1 to ${MAX_OUTPUT_TOKENS_CAP}`);
2096
+ else step.maxOutputTokens = n;
2097
+ }
2069
2098
  else if (key === "max_turns") {
2070
2099
  const n = parseCount(value, 1, MAX_TURNS_CAP);
2071
2100
  if (n === undefined) problem(`a whole number of turns, 1 to ${MAX_TURNS_CAP}`);
@@ -2115,6 +2144,7 @@ export function parseFlow(file: string, raw: string): FlowInfo {
2115
2144
  timezone: data.timezone ?? null,
2116
2145
  model: data.model ?? null,
2117
2146
  effort: data.effort ?? null,
2147
+ ...(parseMaxOutputTokens(data.max_output_tokens) ? { maxOutputTokens: parseMaxOutputTokens(data.max_output_tokens) } : {}),
2118
2148
  overlap: data.overlap === "skip" || data.overlap === "queue" ? data.overlap : null,
2119
2149
  ...(data.issues === "auto-close" || data.issues === "stay-open" ? { issues: data.issues } : {}),
2120
2150
  live: data.live === true,
@@ -2388,7 +2418,7 @@ function updateFlowStepInstructionLF(raw: string, index: number, instruction: st
2388
2418
  function updateFlowStepLF(
2389
2419
  raw: string,
2390
2420
  index: number,
2391
- options: Partial<Record<"model" | "effort" | "retry" | "timeout" | "verify" | "when" | "case" | "else" | "loop" | "until" | "each" | "max" | "limits", string | number | null>>,
2421
+ options: Partial<Record<"model" | "effort" | "max_output_tokens" | "retry" | "timeout" | "verify" | "when" | "case" | "else" | "loop" | "until" | "each" | "max" | "limits", string | number | null>>,
2392
2422
  ): string {
2393
2423
  const { head, preamble, blocks } = splitFlowBlocks(raw);
2394
2424
  if (!Number.isInteger(index) || index < 0 || index >= blocks.length) {
@@ -2398,6 +2428,12 @@ function updateFlowStepLF(
2398
2428
  const clamp: Record<string, (v: string) => string | null> = {
2399
2429
  model: (v) => v || null,
2400
2430
  effort: (v) => resolveEffort(v) ?? null,
2431
+ max_output_tokens: (v) => {
2432
+ if (!v) return null;
2433
+ const n = parseMaxOutputTokens(v);
2434
+ if (n === undefined) throw new Error(`max_output_tokens: ${v} is not a whole number of tokens, 1 to ${MAX_OUTPUT_TOKENS_CAP}`);
2435
+ return String(n);
2436
+ },
2401
2437
  verify: (v) => v || null,
2402
2438
  when: (v) => v || null,
2403
2439
  case: (v) => v || null,
@@ -3580,6 +3616,9 @@ export interface StepRecord {
3580
3616
  schema?: Record<string, unknown> | boolean;
3581
3617
  schemaPath?: string;
3582
3618
  parallel?: number;
3619
+ maxOutputTokens?: number;
3620
+ /** See FlowStep: the default of the flow this step was written in. */
3621
+ flowMaxOutputTokens?: number;
3583
3622
  maxTurns?: number;
3584
3623
  limits?: Record<string, number>;
3585
3624
  /** The parsed JSON an `output: json` step returned. Kept beside the prose
@@ -4904,9 +4943,23 @@ export function providerEnvFor(spec: {
4904
4943
  }
4905
4944
  const lines = Object.entries(spec.headers).map(([k, v]) => `${k}: ${v}`);
4906
4945
  if (lines.length) env.ANTHROPIC_CUSTOM_HEADERS = lines.join("\n");
4946
+ // Claude Code puts an attribution line in every request's system prompt,
4947
+ // which means something to Anthropic only. Anywhere else it is prompt
4948
+ // text the provider is sent for nothing (e2e check, 3 Nov 2026).
4949
+ if (spec.baseUrl && !isAnthropicOrigin(spec.baseUrl)) env.CLAUDE_CODE_ATTRIBUTION_HEADER = "0";
4907
4950
  return env;
4908
4951
  }
4909
4952
 
4953
+ /** Whether a base URL is Anthropic's own API (where the SDK's own
4954
+ * attribution belongs). */
4955
+ function isAnthropicOrigin(baseUrl: string): boolean {
4956
+ try {
4957
+ return new URL(baseUrl).hostname.toLowerCase() === "api.anthropic.com";
4958
+ } catch {
4959
+ return false;
4960
+ }
4961
+ }
4962
+
4910
4963
  // The workspace tree, for history's first commit — see registerTreeReader.
4911
4964
  registerTreeReader((tenant, scope) => {
4912
4965
  if (scope === "@library" || !fs.existsSync(workspaceDir(tenant, scope))) return null;
@@ -46,7 +46,7 @@ export function checkOptions(tenant: string, workspace: string): ScanOptions {
46
46
  * and its tiers the platform knows). An account AGENTS.md provider: block
47
47
  * runs instead, and its own key's models are not the platform's to say.
48
48
  */
49
- function effortCheck(tenant: string, accountProvider: unknown): Pick<ScanOptions, "effortRunsAs"> {
49
+ function effortCheck(tenant: string, accountProvider: unknown): Pick<ScanOptions, "effortRunsAs" | "outputCeiling"> {
50
50
  if (parseProvider(accountProvider)?.baseUrl) return {};
51
51
  let answer: ReturnType<NonNullable<typeof platform.modelSupply>> | undefined;
52
52
  try {
@@ -65,6 +65,12 @@ function effortCheck(tenant: string, accountProvider: unknown): Pick<ScanOptions
65
65
  const runs = effortRunsAs(provider, id, effort);
66
66
  return runs ? { effort: runs, model: id, on } : null;
67
67
  },
68
+ outputCeiling: (model) => {
69
+ const tier = resolveTier(model);
70
+ const id = tier ? tiers[tier as "fast" | "default" | "max"] : model;
71
+ const ceiling = id ? answer.ceilings?.[id] : undefined;
72
+ return id && ceiling ? { ceiling, model: id, on } : null;
73
+ },
68
74
  };
69
75
  }
70
76