@foldrun/core 22.4.0 → 23.0.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.
@@ -1,4 +1,12 @@
1
1
  export type Limits = Record<string, number>;
2
+ /** Every step's limits unless the account, workspace, agent or step sets the
3
+ * key itself (13 Nov 2026, owner): a model that keeps calling — the same
4
+ * call, or anything at all — is stopped, not paid for until its timeout.
5
+ * Seen on prod: one stuck step made 2,008 calls in 3.5 minutes. */
6
+ export declare const DEFAULT_STEP_LIMITS: Limits;
7
+ /** Refused calls after which the step is ended as failed: a model that is
8
+ * told "no" this often is not going to stop by itself. */
9
+ export declare const REFUSALS_BEFORE_STOP = 20;
2
10
  /** The key that caps every call in the step. */
3
11
  export declare const TOTAL_KEY = "calls";
4
12
  /** The key that caps one identical call: a model asking the same tool the
@@ -24,6 +24,14 @@ import crypto from "node:crypto";
24
24
  import { WEB_ACTIONS } from "./providers.js";
25
25
  import { DELEGATE_TOOLS } from "./subagents.js";
26
26
  import { A2A_SERVER, A2A_LIMIT_KEY, A2A_LIMIT_ACTIONS } from "./a2a-remotes.js";
27
+ /** Every step's limits unless the account, workspace, agent or step sets the
28
+ * key itself (13 Nov 2026, owner): a model that keeps calling — the same
29
+ * call, or anything at all — is stopped, not paid for until its timeout.
30
+ * Seen on prod: one stuck step made 2,008 calls in 3.5 minutes. */
31
+ export const DEFAULT_STEP_LIMITS = { calls: 1000, repeat: 25 };
32
+ /** Refused calls after which the step is ended as failed: a model that is
33
+ * told "no" this often is not going to stop by itself. */
34
+ export const REFUSALS_BEFORE_STOP = 20;
27
35
  /** The key that caps every call in the step. */
28
36
  export const TOTAL_KEY = "calls";
29
37
  /** The key that caps one identical call: a model asking the same tool the
@@ -2,7 +2,7 @@
2
2
  // account's content (FOL-121).
3
3
  //
4
4
  // A hosted pod's stdout and stderr leave the cluster: they are our
5
- // operations log (Grafana Cloud, through Alloy), read by us, not by the
5
+ // operations log (CloudWatch Logs on the hosted platform), read by us, not by the
6
6
  // account whose run it was. An account's prompts, replies, files, tool
7
7
  // arguments and the words of its errors belong in that account's own run
8
8
  // trace — never here.
@@ -118,8 +118,8 @@ export declare function runWideEvent(tenant: string, workspace: string, run: Run
118
118
  /** Seconds between two marks of an event, or null when either is missing
119
119
  * (or the later reads earlier: two clocks). */
120
120
  export declare function funnelSecs(ev: Pick<RunWideEvent, "at">, from: FunnelMark, to: FunnelMark): number | null;
121
- /** The ops-log fields an ops span may carry — the collector's allowlist
122
- * (foldrun-infra alloy-config.yaml) is held to this list by its test. */
121
+ /** The ops-log fields an ops span may carry: the whole list, so whatever
122
+ * collects the ops trace can be held to it. */
123
123
  export declare const OPS_SPAN_FIELDS: readonly ["runId", "tenant", "workspace", "flow", "agent", "kind", "outcome", "errorClass", "verdict", "reason", "image", "size", "model", "usd", "step", "attempt", "phase", "ms"];
124
124
  /** Every name an ops span may have. */
125
125
  export declare const OPS_SPAN_NAMES: readonly ["run", "submit", "queue.wait", "drive", "pod.start", "sandbox.start", "first_output", ...("startup.applied" | "startup.driver" | "startup.files" | "startup.go" | "startup.imports" | "startup.ready" | "startup.room" | "startup.services" | "startup.shim" | "startup.system" | "startup.tools")[]];
@@ -319,8 +319,8 @@ export function funnelSecs(ev, from, to) {
319
319
  // rule a log line leaving the cluster keeps (FOL-121). Span names are
320
320
  // fixed. No status message, no events, no links: a failure is its class
321
321
  // (`error.type`, one of ERROR_CLASSES).
322
- /** The ops-log fields an ops span may carry — the collector's allowlist
323
- * (foldrun-infra alloy-config.yaml) is held to this list by its test. */
322
+ /** The ops-log fields an ops span may carry: the whole list, so whatever
323
+ * collects the ops trace can be held to it. */
324
324
  export const OPS_SPAN_FIELDS = [
325
325
  "runId", "tenant", "workspace", "flow", "agent", "kind", "outcome", "errorClass", "verdict",
326
326
  "reason", "image", "size", "model", "usd", "step", "attempt", "phase", "ms",
@@ -15,7 +15,7 @@ import os from "node:os";
15
15
  import path from "node:path";
16
16
  import matter, { parseLenient, configMatter } from "./matter.js";
17
17
  import { knownPrice, executeStep, extractJson, stepCeiling, stepCeilingFor } from "./step-exec.js";
18
- import { cascadeLimits, toolOwners } from "./limits.js";
18
+ import { cascadeLimits, toolOwners, DEFAULT_STEP_LIMITS } from "./limits.js";
19
19
  import { resolveAgentPath } from "./confine.js";
20
20
  import { browserPodLine, podLossDecision, RERAN_ON_FULL } from "./browser-pod.js";
21
21
  import { eventUrl } from "./webhook.js";
@@ -2797,10 +2797,12 @@ conversation) {
2797
2797
  }
2798
2798
  if (step.maxTurns)
2799
2799
  push("info", `max_turns: ${step.maxTurns}`);
2800
- // `limits:` — account, workspace, agent, then this step's option;
2801
- // nearest wins per key. Enforced in the model loop's hook, on either
2800
+ // `limits:` — the platform's defaults (limits.ts DEFAULT_STEP_LIMITS),
2801
+ // then account, workspace, agent, then this step's option; nearest wins
2802
+ // per key. Enforced in the model loop's hook, on either
2802
2803
  // path (step-exec.ts), so it is resolved here as plain values.
2803
2804
  const stepLimits = cascadeLimits([
2805
+ DEFAULT_STEP_LIMITS,
2804
2806
  readAgentsMd(accountDir(tenant))?.data?.limits,
2805
2807
  readAgentsMd(workspaceRootOf(agentDir))?.data?.limits,
2806
2808
  front.limits,
@@ -21,7 +21,7 @@ import { checkPaths, checkBash, isFilesystemTool, linkWorkspace, workspaceLinkEn
21
21
  import { DELEGATE_TOOLS, subagentGuard, toAgentDefinitions } from "./subagents.js";
22
22
  import { hostSafeEnv } from "./host-env.js";
23
23
  import { validateSchema, describeSchemaErrors, looksLikeSchema } from "./json-schema.js";
24
- import { CallCounter, callKeysFor } from "./limits.js";
24
+ import { CallCounter, callKeysFor, REFUSALS_BEFORE_STOP } from "./limits.js";
25
25
  import { classifyCall, podAt, readPodEvents } from "./browser-pod.js";
26
26
  /** The four counts from one SDK usage object (snake_case, as the API
27
27
  * reports it). The API counts fresh input apart from the cache's; here
@@ -331,6 +331,10 @@ async function executeStepInner(opts, runQuery) {
331
331
  const refusal = counter.take(callKeysFor(hookInput.tool_name, hookInput.tool_input, opts.toolOwners));
332
332
  if (refusal) {
333
333
  emit("info", `${refusal.message} (${hookInput.tool_name} refused)`, via ? { subagent: via } : undefined);
334
+ // A model that keeps calling past its limits is stuck: end the
335
+ // step rather than let it loop on refusals until its timeout.
336
+ if (counter.refused >= REFUSALS_BEFORE_STOP)
337
+ endWith("limits");
334
338
  return { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: refusal.message } };
335
339
  }
336
340
  }
@@ -799,6 +803,10 @@ async function executeStepInner(opts, runQuery) {
799
803
  emit("error", "stopped by a person mid-step");
800
804
  status = "failed";
801
805
  }
806
+ else if (ended === "limits") {
807
+ emit("error", `stopped: ${counter.refused} calls were refused by this step's limits and the model kept calling — it is stuck (raise them with \`limits:\` if the work really needs more calls)`);
808
+ status = "failed";
809
+ }
802
810
  else if (ended === "pod-lost") {
803
811
  // The runner says what happens next — a re-run on the full image, or a
804
812
  // failure naming what was written. Not an error of the step's own.
@@ -72,6 +72,9 @@ const S = processState("workspace-revisions", () => ({
72
72
  unjournalled: new Set(),
73
73
  repairing: new Set(),
74
74
  retryAt: new Map(),
75
+ /** Retry timers not yet fired, and the reset generation (tests only move it). */
76
+ retryTimers: new Set(),
77
+ generation: 0,
75
78
  wantPrune: new Set(),
76
79
  prunedAt: new Map(),
77
80
  frozen: new Map(),
@@ -303,10 +306,14 @@ function drain(k) {
303
306
  // until it is done (the gate is read now, so a drain started BEFORE it is
304
307
  // never behind it — that is what lets the lifecycle wait for those).
305
308
  const gate = frozen.get(k);
309
+ const gen = S.generation;
306
310
  const next = (chains.get(k) ?? Promise.resolve())
307
311
  .catch(() => { })
308
312
  .then(() => gate)
309
- .then(() => drainOne(k));
313
+ // A link queued before resetJournalForTests belongs to the "process" that
314
+ // reset ended: it must not drain beside the new one (the replay test saw
315
+ // two loops share one queue under load and publish out of order).
316
+ .then(() => (gen === S.generation ? drainOne(k) : undefined));
310
317
  chains.set(k, next);
311
318
  return next;
312
319
  }
@@ -353,8 +360,12 @@ async function drainOne(k) {
353
360
  const attempts = (retryAt.get(k) ?? 0) + 1;
354
361
  retryAt.set(k, attempts);
355
362
  const wait = Math.min(30_000, 1_000 * 2 ** Math.min(5, attempts - 1));
356
- const t = setTimeout(() => void drain(k), wait);
363
+ const t = setTimeout(() => {
364
+ S.retryTimers.delete(t);
365
+ void drain(k);
366
+ }, wait);
357
367
  t.unref?.();
368
+ S.retryTimers.add(t);
358
369
  return;
359
370
  }
360
371
  }
@@ -398,6 +409,11 @@ export async function flushRevisions(only) {
398
409
  /** Tests: forget every queued change and pending retry (journal FILES stay:
399
410
  * that is what a crash leaves). */
400
411
  export function resetJournalForTests() {
412
+ // As a crash would: no retry of the old process fires, no link of it drains.
413
+ for (const t of S.retryTimers)
414
+ clearTimeout(t);
415
+ S.retryTimers.clear();
416
+ S.generation++;
401
417
  queues.clear();
402
418
  chains.clear();
403
419
  marked.clear();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "22.4.0",
3
+ "version": "23.0.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",
package/src/limits.ts CHANGED
@@ -28,6 +28,16 @@ import { A2A_SERVER, A2A_LIMIT_KEY, A2A_LIMIT_ACTIONS } from "./a2a-remotes.ts";
28
28
 
29
29
  export type Limits = Record<string, number>;
30
30
 
31
+ /** Every step's limits unless the account, workspace, agent or step sets the
32
+ * key itself (13 Nov 2026, owner): a model that keeps calling — the same
33
+ * call, or anything at all — is stopped, not paid for until its timeout.
34
+ * Seen on prod: one stuck step made 2,008 calls in 3.5 minutes. */
35
+ export const DEFAULT_STEP_LIMITS: Limits = { calls: 1000, repeat: 25 };
36
+
37
+ /** Refused calls after which the step is ended as failed: a model that is
38
+ * told "no" this often is not going to stop by itself. */
39
+ export const REFUSALS_BEFORE_STOP = 20;
40
+
31
41
  /** The key that caps every call in the step. */
32
42
  export const TOTAL_KEY = "calls";
33
43
 
package/src/ops-log.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  // account's content (FOL-121).
3
3
  //
4
4
  // A hosted pod's stdout and stderr leave the cluster: they are our
5
- // operations log (Grafana Cloud, through Alloy), read by us, not by the
5
+ // operations log (CloudWatch Logs on the hosted platform), read by us, not by the
6
6
  // account whose run it was. An account's prompts, replies, files, tool
7
7
  // arguments and the words of its errors belong in that account's own run
8
8
  // trace — never here.
package/src/run-event.ts CHANGED
@@ -397,8 +397,8 @@ export function funnelSecs(ev: Pick<RunWideEvent, "at">, from: FunnelMark, to: F
397
397
  // fixed. No status message, no events, no links: a failure is its class
398
398
  // (`error.type`, one of ERROR_CLASSES).
399
399
 
400
- /** The ops-log fields an ops span may carry — the collector's allowlist
401
- * (foldrun-infra alloy-config.yaml) is held to this list by its test. */
400
+ /** The ops-log fields an ops span may carry: the whole list, so whatever
401
+ * collects the ops trace can be held to it. */
402
402
  export const OPS_SPAN_FIELDS = [
403
403
  "runId", "tenant", "workspace", "flow", "agent", "kind", "outcome", "errorClass", "verdict",
404
404
  "reason", "image", "size", "model", "usd", "step", "attempt", "phase", "ms",
package/src/runner.ts CHANGED
@@ -17,7 +17,7 @@ import path from "node:path";
17
17
  import matter, { parseLenient, configMatter } from "./matter.ts";
18
18
  import {
19
19
  knownPrice, executeStep, extractJson, stepCeiling, stepCeilingFor, type EventExtra } from "./step-exec.ts";
20
- import { cascadeLimits, toolOwners } from "./limits.ts";
20
+ import { cascadeLimits, toolOwners, DEFAULT_STEP_LIMITS } from "./limits.ts";
21
21
  import { resolveAgentPath } from "./confine.ts";
22
22
  import { browserPodLine, podLossDecision, RERAN_ON_FULL } from "./browser-pod.ts";
23
23
  import { eventUrl } from "./webhook.ts";
@@ -3004,10 +3004,12 @@ async function runStepBody(
3004
3004
  throw new Error(`schema: ${step.schemaPath} — not a readable JSON or YAML schema under the workspace`);
3005
3005
  }
3006
3006
  if (step.maxTurns) push("info", `max_turns: ${step.maxTurns}`);
3007
- // `limits:` — account, workspace, agent, then this step's option;
3008
- // nearest wins per key. Enforced in the model loop's hook, on either
3007
+ // `limits:` — the platform's defaults (limits.ts DEFAULT_STEP_LIMITS),
3008
+ // then account, workspace, agent, then this step's option; nearest wins
3009
+ // per key. Enforced in the model loop's hook, on either
3009
3010
  // path (step-exec.ts), so it is resolved here as plain values.
3010
3011
  const stepLimits = cascadeLimits([
3012
+ DEFAULT_STEP_LIMITS,
3011
3013
  readAgentsMd(accountDir(tenant))?.data?.limits,
3012
3014
  readAgentsMd(workspaceRootOf(agentDir))?.data?.limits,
3013
3015
  front.limits,
package/src/step-exec.ts CHANGED
@@ -25,7 +25,7 @@ import { checkPaths, checkBash, isFilesystemTool, linkWorkspace, workspaceLinkEn
25
25
  import { DELEGATE_TOOLS, subagentGuard, toAgentDefinitions, type SubagentSpec } from "./subagents.ts";
26
26
  import { hostSafeEnv } from "./host-env.ts";
27
27
  import { validateSchema, describeSchemaErrors, looksLikeSchema } from "./json-schema.ts";
28
- import { CallCounter, callKeysFor, type Limits } from "./limits.ts";
28
+ import { CallCounter, callKeysFor, REFUSALS_BEFORE_STOP, type Limits } from "./limits.ts";
29
29
  import { classifyCall, podAt, readPodEvents, type BrowserPodOutcome, type CallKind, type ClassifyContext } from "./browser-pod.ts";
30
30
 
31
31
  export interface ExecUsage {
@@ -539,6 +539,9 @@ async function executeStepInner(opts: ExecOptions, runQuery: QueryFn): Promise<E
539
539
  const refusal = counter.take(callKeysFor(hookInput.tool_name, hookInput.tool_input as Record<string, unknown>, opts.toolOwners));
540
540
  if (refusal) {
541
541
  emit("info", `${refusal.message} (${hookInput.tool_name} refused)`, via ? { subagent: via } : undefined);
542
+ // A model that keeps calling past its limits is stuck: end the
543
+ // step rather than let it loop on refusals until its timeout.
544
+ if (counter.refused >= REFUSALS_BEFORE_STOP) endWith("limits");
542
545
  return { hookSpecificOutput: { hookEventName: "PreToolUse" as const, permissionDecision: "deny" as const, permissionDecisionReason: refusal.message } };
543
546
  }
544
547
  }
@@ -649,10 +652,10 @@ async function executeStepInner(opts: ExecOptions, runQuery: QueryFn): Promise<E
649
652
  // call — a crawl, a build — sailed past its timeout: with no message there
650
653
  // was nothing to check it against. The backstop timer fires regardless,
651
654
  // and a stop is read on a clock rather than between groups.
652
- let ended: "timeout" | "stopped" | "pod-lost" | null = null;
655
+ let ended: "timeout" | "stopped" | "pod-lost" | "limits" | null = null;
653
656
  const startedAt = Date.now();
654
657
  const timers: NodeJS.Timeout[] = [];
655
- const endWith = (why: "timeout" | "stopped" | "pod-lost") => {
658
+ const endWith = (why: "timeout" | "stopped" | "pod-lost" | "limits") => {
656
659
  if (ended) return;
657
660
  ended = why;
658
661
  void q.interrupt().catch(() => {});
@@ -972,6 +975,9 @@ async function executeStepInner(opts: ExecOptions, runQuery: QueryFn): Promise<E
972
975
  } else if (ended === "stopped") {
973
976
  emit("error", "stopped by a person mid-step");
974
977
  status = "failed";
978
+ } else if (ended === "limits") {
979
+ emit("error", `stopped: ${counter.refused} calls were refused by this step's limits and the model kept calling — it is stuck (raise them with \`limits:\` if the work really needs more calls)`);
980
+ status = "failed";
975
981
  } else if (ended === "pod-lost") {
976
982
  // The runner says what happens next — a re-run on the full image, or a
977
983
  // failure naming what was written. Not an error of the step's own.
@@ -93,6 +93,9 @@ const S = processState("workspace-revisions", () => ({
93
93
  unjournalled: new Set<string>(),
94
94
  repairing: new Set<string>(),
95
95
  retryAt: new Map<string, number>(),
96
+ /** Retry timers not yet fired, and the reset generation (tests only move it). */
97
+ retryTimers: new Set<ReturnType<typeof setTimeout>>(),
98
+ generation: 0,
96
99
  wantPrune: new Set<string>(),
97
100
  prunedAt: new Map<string, number>(),
98
101
  frozen: new Map<string, Promise<void>>(),
@@ -416,10 +419,14 @@ function drain(k: string): Promise<void> {
416
419
  // until it is done (the gate is read now, so a drain started BEFORE it is
417
420
  // never behind it — that is what lets the lifecycle wait for those).
418
421
  const gate = frozen.get(k);
422
+ const gen = S.generation;
419
423
  const next = (chains.get(k) ?? Promise.resolve())
420
424
  .catch(() => {})
421
425
  .then(() => gate)
422
- .then(() => drainOne(k));
426
+ // A link queued before resetJournalForTests belongs to the "process" that
427
+ // reset ended: it must not drain beside the new one (the replay test saw
428
+ // two loops share one queue under load and publish out of order).
429
+ .then(() => (gen === S.generation ? drainOne(k) : undefined));
423
430
  chains.set(k, next);
424
431
  return next;
425
432
  }
@@ -465,8 +472,12 @@ async function drainOne(k: string): Promise<void> {
465
472
  const attempts = (retryAt.get(k) ?? 0) + 1;
466
473
  retryAt.set(k, attempts);
467
474
  const wait = Math.min(30_000, 1_000 * 2 ** Math.min(5, attempts - 1));
468
- const t = setTimeout(() => void drain(k), wait);
475
+ const t = setTimeout(() => {
476
+ S.retryTimers.delete(t);
477
+ void drain(k);
478
+ }, wait);
469
479
  t.unref?.();
480
+ S.retryTimers.add(t);
470
481
  return;
471
482
  }
472
483
  }
@@ -508,6 +519,10 @@ export async function flushRevisions(only?: { tenant: string; workspace: string
508
519
  /** Tests: forget every queued change and pending retry (journal FILES stay:
509
520
  * that is what a crash leaves). */
510
521
  export function resetJournalForTests(): void {
522
+ // As a crash would: no retry of the old process fires, no link of it drains.
523
+ for (const t of S.retryTimers) clearTimeout(t);
524
+ S.retryTimers.clear();
525
+ S.generation++;
511
526
  queues.clear();
512
527
  chains.clear();
513
528
  marked.clear();