pi-durable-subagents 1.6.0 → 1.7.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.
@@ -29,6 +29,7 @@
29
29
  import { mkdir, open, readdir, readFile, realpath, rm, stat, unlink, writeFile } from "node:fs/promises";
30
30
  import { watch } from "node:fs";
31
31
  import { setTimeout as delay } from "node:timers/promises";
32
+ import { performance } from "node:perf_hooks";
32
33
  import { homedir } from "node:os";
33
34
  import { delimiter, dirname, join } from "node:path";
34
35
  import { fileURLToPath } from "node:url";
@@ -66,9 +67,13 @@ import { failedModel, modelFailures, MODEL_RETRY_MS, parentPinned, spillCandidat
66
67
  import { PENDING_NOTE, UNDELIVERED_FOLLOW_UP } from "../notes.js";
67
68
  import { COMMAND_LOG, exitMeaning, prepareCancelled, prepareCommand as stageCommand, readExitRecord, readTail, spawnCommand } from "../../platform/command.js";
68
69
  import { captureStart } from "../../platform/proctable.js";
69
- import { IS_WINDOWS, sameCreation } from "../../platform/windows.js";
70
+ import { IS_WINDOWS, sameCreation, scannedCommand } from "../../platform/windows.js";
71
+ import { commandLine } from "../../platform/cmdline.js";
72
+ import { checkLinuxScopeOom, kernelLimitsSatisfied, mergeLimits, probeKernelLimits, wrapLinuxScope } from "../../platform/limits.js";
73
+ import { readJobLimitExceeded } from "../../platform/job.js";
70
74
  import { heldIn } from "../snapshot.js";
71
- import { COMMAND_INTENT, COMMAND_SPAWN_FAILED, COMMAND_STARTED, COMMAND_TIMEOUT, COMMAND_WITHDRAWN, commandDirName, commandEnvironment, commandId, retiredCommandAttempts } from "./command.js";
75
+ import { COMMAND_INTENT, COMMAND_RESOURCE_LIMIT, COMMAND_SPAWN_FAILED, COMMAND_STARTED, COMMAND_TIMEOUT, COMMAND_WITHDRAWN, commandDirName, commandEnvironment, commandId, retiredCommandAttempts } from "./command.js";
76
+ import { formatResourceViolation, ResourceMonitor } from "./resources.js";
72
77
  const MEM_RECORD_MS = 30000;
73
78
  /** How long the processes of a stopped or timed-out command get between SIGTERM and SIGKILL. */
74
79
  const COMMAND_GRACE_MS = 2000;
@@ -1333,9 +1338,9 @@ export default function createExecutor(ledgers, options = {}) {
1333
1338
  };
1334
1339
  /** The processes of an attempt: tagged with its id, the wrapper while it lives, and their live descendants. A scan that
1335
1340
  * fails transiently is not an empty result (`undefined`): an attempt is never called gone because the observer failed. */
1336
- async function commandProcesses(id, known) {
1341
+ async function commandProcesses(id, known, scanOptions = { fresh: true }) {
1337
1342
  try {
1338
- return (await containment.scan(new Map([[id, known]]), { fresh: true })).get(id) ?? [];
1343
+ return (await containment.scan(new Map([[id, known]]), scanOptions)).get(id) ?? [];
1339
1344
  }
1340
1345
  catch (error) {
1341
1346
  if (closed)
@@ -1412,6 +1417,7 @@ export default function createExecutor(ledgers, options = {}) {
1412
1417
  throw shutdownError();
1413
1418
  const started = entriesFor(journal, call).findLast(e => e.type === COMMAND_STARTED && e.id === id);
1414
1419
  let { status, error } = outcome;
1420
+ const limitHit = entriesFor(journal, call).findLast(e => e.type === COMMAND_RESOURCE_LIMIT && e.id === id);
1415
1421
  if (hasStopIntent(journal, call)) {
1416
1422
  status = "stopped";
1417
1423
  error = undefined;
@@ -1420,6 +1426,10 @@ export default function createExecutor(ledgers, options = {}) {
1420
1426
  status = "timeout";
1421
1427
  error = `Command timed out after ${t.spec.timeoutMs} ms`;
1422
1428
  }
1429
+ else if (limitHit) {
1430
+ status = "failed";
1431
+ error = String(limitHit.message ?? "Resource limit exceeded");
1432
+ }
1423
1433
  const durationMs = started ? Math.max(0, Math.round((outcome.at ?? Date.now()) - started.ts)) : 0;
1424
1434
  const result = { ...buildCallResult({ key: t.key, gen: t.gen, status, output, ...(error ? { error } : {}) }),
1425
1435
  data: { exitCode: outcome.exitCode ?? null, signal: outcome.signal ?? null, durationMs }, usage: { input: 0, output: 0, costUsd: 0 } };
@@ -1509,8 +1519,9 @@ export default function createExecutor(ledgers, options = {}) {
1509
1519
  refused = "withdrawn";
1510
1520
  return refused === undefined;
1511
1521
  };
1522
+ const limits = mergeLimits(settings().limits, t.spec.limits);
1512
1523
  const result = await spawnCommand({ command: t.spec.command, cwd: t.cwd, dir, proceed, exec: id,
1513
- ...(prepared ? { prepared } : {}), env: commandEnvironment(home, id, t.callId, t.spec.env) });
1524
+ ...(limits ? { limits } : {}), ...(prepared ? { prepared } : {}), env: commandEnvironment(home, id, t.callId, t.spec.env) });
1514
1525
  if (!result) {
1515
1526
  if (refused === "withdrawn")
1516
1527
  await serial(() => t.journal.append(COMMAND_WITHDRAWN, { call: t.callId, id }));
@@ -1525,7 +1536,7 @@ export default function createExecutor(ledgers, options = {}) {
1525
1536
  return undefined;
1526
1537
  }
1527
1538
  await serial(() => t.journal.append(COMMAND_STARTED, { call: t.callId, id, pid: spawned.pid, start: spawned.start, dir,
1528
- ...(spawned.group ? { group: spawned.group } : {}), ...(spawned.uncertain ? { uncertain: spawned.uncertain } : {}) }));
1539
+ ...(spawned.group ? { group: spawned.group } : {}), ...(spawned.scopeUnit ? { scopeUnit: spawned.scopeUnit } : {}), ...(spawned.uncertain ? { uncertain: spawned.uncertain } : {}) }));
1529
1540
  return spawned;
1530
1541
  }
1531
1542
  /** Run, adopt or settle a command call (see the journal records at the top). One attempt runs at a time; a lost first
@@ -1549,10 +1560,17 @@ export default function createExecutor(ledgers, options = {}) {
1549
1560
  const blocked = commandBlocked(a);
1550
1561
  if (blocked)
1551
1562
  return { blocked };
1563
+ const env = commandEnvironment(home, id, call, t.spec.env);
1564
+ const limits = mergeLimits(settings().limits, t.spec.limits);
1565
+ if (limits?.strict) {
1566
+ const problem = kernelLimitsSatisfied(limits, probeKernelLimits({ kind: "command", env }));
1567
+ if (problem)
1568
+ return { failure: problem };
1569
+ }
1552
1570
  let prepared;
1553
1571
  try {
1554
1572
  prepared = await prepareStart({ command: t.spec.command, cwd: t.cwd, dir, exec: id,
1555
- env: commandEnvironment(home, id, call, t.spec.env), signal: a.controller.signal });
1573
+ ...(limits ? { limits } : {}), env, signal: a.controller.signal });
1556
1574
  }
1557
1575
  catch (error) {
1558
1576
  // The revocation is the cause, so it decides the attempt: the rejection cannot be told apart from one the abort
@@ -1667,10 +1685,30 @@ export default function createExecutor(ledgers, options = {}) {
1667
1685
  throw error;
1668
1686
  }
1669
1687
  };
1670
- const settleExit = async (exit, known, deadline) => {
1688
+ const monitor = new ResourceMonitor(mergeLimits(settings().limits, t.spec.limits));
1689
+ const settleExit = async (exit, known, deadline, scopeUnit) => {
1671
1690
  // Processes the command left behind (background ones included) end with it, as a call's processes always do.
1672
1691
  if (!closed)
1673
1692
  await endCommand(id, known);
1693
+ if (exit.status !== 0 && !entriesFor(journal, call).some(e => e.type === COMMAND_RESOURCE_LIMIT && e.id === id)) {
1694
+ const lim = mergeLimits(settings().limits, t.spec.limits);
1695
+ const winHit = IS_WINDOWS ? await readJobLimitExceeded(dir) : undefined;
1696
+ if (winHit) {
1697
+ const peakMb = Math.round((winHit.peakBytes / (1024 * 1024)) * 10) / 10;
1698
+ const message = `Resource limit exceeded: killed by Windows Job Object ${winHit.kind} limit (memoryMb limit: ${lim?.memoryMb ?? "?"} MiB${peakMb > 0 ? `, peak ${peakMb} MiB` : ""})`;
1699
+ await serial(async () => {
1700
+ if (!entriesFor(journal, call).some(e => e.type === COMMAND_RESOURCE_LIMIT && e.id === id))
1701
+ await journal.append(COMMAND_RESOURCE_LIMIT, { call, id, kind: winHit.kind, limit: lim?.memoryMb, peak: peakMb, message });
1702
+ });
1703
+ }
1704
+ else if (scopeUnit && await checkLinuxScopeOom(scopeUnit)) {
1705
+ const message = `Resource limit exceeded: killed by Linux cgroup OOM (memoryMb limit: ${lim?.memoryMb ?? "?"} MiB)`;
1706
+ await serial(async () => {
1707
+ if (!entriesFor(journal, call).some(e => e.type === COMMAND_RESOURCE_LIMIT && e.id === id))
1708
+ await journal.append(COMMAND_RESOURCE_LIMIT, { call, id, kind: "memory", limit: lim?.memoryMb, message });
1709
+ });
1710
+ }
1711
+ }
1674
1712
  // An exit after the deadline (seen late: the orchestrator was down) is a timeout, with the record's data.
1675
1713
  const late = deadline !== undefined && exit.at > deadline;
1676
1714
  return await sealCommand(journal, t, id, { status: late ? "timeout" : exit.status === 0 ? "ok" : "failed", ...exitResult(exit.status),
@@ -1679,12 +1717,13 @@ export default function createExecutor(ledgers, options = {}) {
1679
1717
  try {
1680
1718
  for (;;) {
1681
1719
  const started = entriesFor(journal, call).findLast(e => e.type === COMMAND_STARTED && e.id === id), known = commandKnown(started);
1720
+ const scopeUnit = typeof started?.scopeUnit === "string" ? started.scopeUnit : undefined;
1682
1721
  // The timeout is wall clock from the start (command-started, else the intent: a crash before the started record),
1683
1722
  // downtime included.
1684
1723
  const deadline = t.spec.timeoutMs !== undefined ? (started ?? intent).ts + t.spec.timeoutMs : undefined;
1685
1724
  const exit = await readExit();
1686
1725
  if (exit)
1687
- return await settleExit(exit, known, deadline);
1726
+ return await settleExit(exit, known, deadline, scopeUnit);
1688
1727
  if (closed)
1689
1728
  throw shutdownError();
1690
1729
  if (a.retired || retiredCall(journal, call)) {
@@ -1701,16 +1740,63 @@ export default function createExecutor(ledgers, options = {}) {
1701
1740
  await endCommand(id, known);
1702
1741
  return await sealCommand(journal, t, id, { status: "timeout" }, dir);
1703
1742
  }
1743
+ const priorLimit = entriesFor(journal, call).findLast(e => e.type === COMMAND_RESOURCE_LIMIT && e.id === id);
1744
+ if (priorLimit) {
1745
+ await endCommand(id, known);
1746
+ return await sealCommand(journal, t, id, { status: "failed", error: String(priorLimit.message ?? "Resource limit exceeded") }, dir);
1747
+ }
1748
+ const limits = mergeLimits(settings().limits, t.spec.limits);
1704
1749
  const observedStart = started?.start ? await captureStart(Number(started.pid)).catch(() => "") : "";
1705
1750
  const wrapper = !!started?.start && (IS_WINDOWS ? sameCreation(observedStart, String(started.start)) : observedStart === started.start);
1706
1751
  // A failed observation is not a loss: the attempt stays tracked and is watched again (never started over).
1707
- const live = wrapper ? undefined : await commandProcesses(id, known);
1752
+ const live = wrapper
1753
+ ? (limits ? await commandProcesses(id, known, { maxAgeMs: commandTick() }) : undefined)
1754
+ : await commandProcesses(id, known);
1755
+ if (limits && live && live.length) {
1756
+ monitor.setLimits(limits);
1757
+ const overhead = new Set(known.map(p => p.pid));
1758
+ const { violation } = monitor.sample(live, performance.now(), overhead);
1759
+ if (violation) {
1760
+ const byPid = new Map(live.map(p => [p.pid, p]));
1761
+ const ctl = new AbortController();
1762
+ const timer = setTimeout(() => ctl.abort(), 500);
1763
+ let top = violation.top;
1764
+ try {
1765
+ top = await Promise.all(violation.top.map(async (item) => {
1766
+ const p = byPid.get(item.pid);
1767
+ const scanned = p ? scannedCommand(p) : undefined;
1768
+ const cmd = scanned !== undefined ? scanned : await commandLine(item.pid, ctl.signal).catch(() => "");
1769
+ return cmd ? { ...item, command: cmd } : item;
1770
+ }));
1771
+ }
1772
+ finally {
1773
+ clearTimeout(timer);
1774
+ }
1775
+ const message = formatResourceViolation({ ...violation, top });
1776
+ await serial(async () => {
1777
+ if (!entriesFor(journal, call).some(e => e.type === COMMAND_RESOURCE_LIMIT && e.id === id)) {
1778
+ await journal.append(COMMAND_RESOURCE_LIMIT, { call, id, kind: violation.kind, limit: violation.limit,
1779
+ observed: violation.observed, peak: violation.peak, processes: violation.processes, top, message });
1780
+ }
1781
+ });
1782
+ await endCommand(id, known);
1783
+ return await sealCommand(journal, t, id, { status: "failed", error: message }, dir);
1784
+ }
1785
+ }
1708
1786
  if (!wrapper && live !== undefined && !live.length) {
1709
1787
  // The wrapper may have written its record just before it ended (or a Windows scanner may briefly hold it).
1710
1788
  const late = await readExit();
1711
- if (!late)
1712
- return "lost";
1713
- return await settleExit(late, known, deadline);
1789
+ if (late)
1790
+ return await settleExit(late, known, deadline, scopeUnit);
1791
+ if (scopeUnit && await checkLinuxScopeOom(scopeUnit)) {
1792
+ const message = `Resource limit exceeded: killed by Linux cgroup OOM (memoryMb limit: ${limits?.memoryMb ?? "?"} MiB)`;
1793
+ await serial(async () => {
1794
+ if (!entriesFor(journal, call).some(e => e.type === COMMAND_RESOURCE_LIMIT && e.id === id))
1795
+ await journal.append(COMMAND_RESOURCE_LIMIT, { call, id, kind: "memory", limit: limits?.memoryMb, message });
1796
+ });
1797
+ return await sealCommand(journal, t, id, { status: "failed", error: message }, dir);
1798
+ }
1799
+ return "lost";
1714
1800
  }
1715
1801
  const wait = Math.max(1, Math.min(commandTick(), deadline !== undefined ? deadline - Date.now() : Infinity));
1716
1802
  await new Promise(resolve => { const timer = setTimeout(resolve, wait); a.wake = () => { clearTimeout(timer); resolve(); }; });
@@ -1873,6 +1959,9 @@ export default function createExecutor(ledgers, options = {}) {
1873
1959
  return finish(journal, t.callId, exec, makeResult("timeout"));
1874
1960
  if (ev.budget || reached(totalUsage(journal.entries(), t.callId), t.spec.budget))
1875
1961
  return finish(journal, t.callId, exec, makeResult("budget"));
1962
+ const limitHit = entriesOf(journal, "resource-limit", exec).at(-1);
1963
+ if (limitHit)
1964
+ return finish(journal, t.callId, exec, makeResult("failed", "", String(limitHit.message ?? "Resource limit exceeded")));
1876
1965
  const textFailure = entries.findLast(e => e.type === "custom" && e.customType === CT.exhausted && e.data?.exec === exec)?.data;
1877
1966
  if (textFailure) {
1878
1967
  const provider = String(textFailure.provider), text = String(textFailure.text).slice(0, 200);
@@ -1956,6 +2045,15 @@ export default function createExecutor(ledgers, options = {}) {
1956
2045
  await fence(journal, exec, { park: a });
1957
2046
  return finish(journal, t.callId, exec, makeResult("failed", "", "workflow budget reached"));
1958
2047
  }
2048
+ const effectiveLimits = () => mergeLimits(settings().limits, t.spec.limits);
2049
+ const launchLimits = effectiveLimits();
2050
+ if (launchLimits?.strict) {
2051
+ const problem = kernelLimitsSatisfied(launchLimits, probeKernelLimits({ kind: "agent" }));
2052
+ if (problem) {
2053
+ await fence(journal, exec, { park: a });
2054
+ return finish(journal, t.callId, exec, makeResult("failed", "", problem));
2055
+ }
2056
+ }
1959
2057
  let decision;
1960
2058
  try {
1961
2059
  decision = await acquire(a, exec, () => launchModel(t, entries, previous), writer ??= await writerRoot(t, cwd));
@@ -2026,9 +2124,15 @@ export default function createExecutor(ledgers, options = {}) {
2026
2124
  // PATH without node (a service's). execTarget resolves a bare `pi` on this PATH too, not on the orchestrator's: the
2027
2125
  // shim it must run may be the call's own.
2028
2126
  const childEnv = { DSA_HOME: home, PATH: [binDir(home), dirname(process.execPath), process.env.PATH].filter(Boolean).join(delimiter), DSA_EXEC: exec, DSA_CALL: t.callId, DSA_INBOX: inbox(t.callId), DSA_JOURNAL: journal.path, DSA_ASK_REQUIRE_DECISION: String(config.askRequireDecision ?? false), ...(Object.keys(patterns).length ? { DSA_EXHAUSTED_PATTERNS: JSON.stringify(patterns) } : {}), ...(t.spec.schema !== undefined ? { DSA_SCHEMA: schema } : {}), ...(t.spec.budget ? { DSA_BUDGET: JSON.stringify(t.spec.budget) } : {}), ...(model.provider && model.id ? { DSA_MODEL: `${model.provider}/${model.id}` } : {}), ...(exactTools && t.exactCapture ? { DSA_EXACT_CAPTURE: t.exactCapture.path, DSA_EXACT_TOOLS: JSON.stringify(exactTools) } : {}) };
2127
+ let scopeUnit;
2128
+ const fullChildEnv = { ...process.env, ...childEnv };
2029
2129
  try {
2030
2130
  const target = execTarget(piCommand, [...buildPiArgs(t.agent, t.spec, { sessionPath: session, systemPromptPath: prompt, continuation: decision.continuation, controlTools: t.spec.schema === undefined ? ["ask"] : ["ask", "report"], ...(model.id ? { model } : {}), ...(t.exactMode?.mode === "exact" ? { thinking: (await readPinnedCapture(t.exactCapture?.path))?.thinking ?? false } : {}) }), "-e", extension], { env: childEnv });
2031
- child = await containment.spawn({ exec, command: target.command, args: target.args, cwd, env: childEnv, ...(target.verbatim ? { windowsVerbatimArguments: true } : {}) });
2131
+ const wrapped = launchLimits && process.platform === "linux"
2132
+ ? wrapLinuxScope(exec, target.command, target.args, launchLimits, probeKernelLimits({ platform: "linux", env: fullChildEnv, kind: "agent" }))
2133
+ : { command: target.command, args: target.args };
2134
+ scopeUnit = wrapped.unit;
2135
+ child = await containment.spawn({ exec, command: wrapped.command, args: wrapped.args, cwd, env: childEnv, ...(target.verbatim && !wrapped.unit ? { windowsVerbatimArguments: true } : {}) });
2032
2136
  }
2033
2137
  catch (error) {
2034
2138
  const environment = environmentSpawnError(error);
@@ -2089,7 +2193,16 @@ export default function createExecutor(ledgers, options = {}) {
2089
2193
  cacheWrite: usage.cacheWrite ?? 0, output: usage.output ?? 0, costUsd: usage.cost?.total ?? 0 }));
2090
2194
  },
2091
2195
  switched: event => switched(exec, journal, event), answered: event => answered(t, exec, event), pendingSwitch: () => pendingSwitch(exec),
2092
- });
2196
+ limits: effectiveLimits, });
2197
+ if (scopeUnit && !has(journal, "resource-limit", exec) && await checkLinuxScopeOom(scopeUnit, fullChildEnv)) {
2198
+ const lim = effectiveLimits();
2199
+ const message = `Resource limit exceeded: killed by Linux cgroup OOM (memoryMb limit: ${lim?.memoryMb ?? "?"} MiB)`;
2200
+ await serial(async () => {
2201
+ if (!has(journal, "resource-limit", exec)) {
2202
+ await journal.append("resource-limit", { exec, call: t.callId, kind: "memory", limit: lim?.memoryMb, message });
2203
+ }
2204
+ });
2205
+ }
2093
2206
  }
2094
2207
  finally {
2095
2208
  await fence(journal, exec, { child, park: a });
@@ -6,12 +6,15 @@ import { stat as fileStat } from "node:fs/promises";
6
6
  import { performance } from "node:perf_hooks";
7
7
  import { createInterface } from "node:readline";
8
8
  import { CT, JT, attentionEntries } from "../../types.js";
9
+ import { commandLine } from "../../platform/cmdline.js";
10
+ import { scannedCommand } from "../../platform/windows.js";
9
11
  import { callDir, callSession } from "../../paths.js";
10
12
  import { monotoneTime } from "../../kernel/guards.js";
11
13
  import { readSession } from "./session.js";
12
14
  import { entriesOf } from "./indexes.js";
13
15
  import { ActiveTime, activeTotal } from "./time.js";
14
- import { observation, reached, sessionUsage, totalUsage } from "./usage.js";
16
+ import { formatResourceViolation, ResourceMonitor } from "./resources.js";
17
+ import { entryUsage, observation, reached, sessionUsage, totalUsage } from "./usage.js";
15
18
  const UPDATE = '{"type":"tool_execution_update",';
16
19
  export const sessionChanged = (name) => name === null || String(name) === "session.jsonl" || String(name) === "inbox";
17
20
  /** A tool call's command for a status line: bash's command, else its arguments, on one line and clipped. */
@@ -25,6 +28,7 @@ export function toolCommand(args) {
25
28
  export async function observeExecution(d) {
26
29
  const { home, config, ticket: t, exec, child, serial } = d;
27
30
  const session = callSession(home, t.wid, t.key, t.gen), clock = new ActiveTime(), started = clock.last;
31
+ const monitor = new ResourceMonitor(d.limits?.());
28
32
  let progress = started, providerError;
29
33
  // Diagnostic metadata only: checkpoint the latest received stream update, never its content.
30
34
  let lastStream;
@@ -43,7 +47,8 @@ export async function observeExecution(d) {
43
47
  const previous = entriesOf(t.journal, "time", exec).at(-1);
44
48
  if (!monotoneTime({ active: Number(previous?.active ?? 0) }, { active: clock.active }))
45
49
  throw new Error("Nonmonotone active time");
46
- await t.journal.append("time", { exec, active: clock.active, ...(lastStream ? { lastStream } : {}) });
50
+ const resources = monitor.latest();
51
+ await t.journal.append("time", { exec, active: clock.active, ...(lastStream ? { lastStream } : {}), ...(resources ? { resources } : {}) });
47
52
  });
48
53
  const limits = async () => {
49
54
  if (t.spec.timeoutMs !== undefined && prior + clock.active >= t.spec.timeoutMs) {
@@ -162,6 +167,11 @@ export async function observeExecution(d) {
162
167
  const args = event.args;
163
168
  if (event.type === "tool_execution_start" && (event.toolName === "edit" || event.toolName === "write") && typeof args?.path === "string")
164
169
  await d.wrote?.(args.path);
170
+ if (event.type === "entry_appended" && event.entry && typeof event.entry === "object") {
171
+ const u = entryUsage(event.entry);
172
+ if (u && event.entry.type === "usage")
173
+ await d.recordUsage([u]);
174
+ }
165
175
  const slim = observation(event);
166
176
  if (slim) {
167
177
  await serial(() => t.journal.append("observation", { exec, event: slim }));
@@ -196,9 +206,11 @@ export async function observeExecution(d) {
196
206
  // 2 s deadline right after the orchestrator was stopped or the machine slept (seen on CI as a spurious loss and
197
207
  // a rerun). Only a scan that keeps failing for a minute ends the observation.
198
208
  // Measured in elapsed time: the scan period is fixed at start while k.trackerMs can be reloaded.
209
+ let procs;
199
210
  try {
200
211
  if (processes) {
201
- clock.scan(await d.track());
212
+ procs = await d.track();
213
+ clock.scan(procs);
202
214
  failingSince = undefined;
203
215
  }
204
216
  }
@@ -207,6 +219,37 @@ export async function observeExecution(d) {
207
219
  if (performance.now() - failingSince >= 60_000)
208
220
  throw error;
209
221
  }
222
+ if (procs) {
223
+ monitor.setLimits(d.limits?.());
224
+ const { violation } = monitor.sample(procs, performance.now());
225
+ if (violation && !ending && !has("resource-limit")) {
226
+ const byPid = new Map(procs.map(p => [p.pid, p]));
227
+ const readCmd = d.readCommand ?? commandLine;
228
+ const ctl = new AbortController();
229
+ const timer = setTimeout(() => ctl.abort(), 500);
230
+ let top = violation.top;
231
+ try {
232
+ top = await Promise.all(violation.top.map(async (item) => {
233
+ const p = byPid.get(item.pid);
234
+ const scanned = p ? scannedCommand(p) : undefined;
235
+ const cmd = scanned !== undefined ? scanned : await readCmd(item.pid, ctl.signal).catch(() => "");
236
+ return cmd ? { ...item, command: cmd } : item;
237
+ }));
238
+ }
239
+ finally {
240
+ clearTimeout(timer);
241
+ }
242
+ const message = formatResourceViolation({ ...violation, top });
243
+ await serial(async () => {
244
+ if (!has("resource-limit")) {
245
+ await t.journal.append("resource-limit", { exec, call: t.callId, kind: violation.kind, limit: violation.limit,
246
+ observed: violation.observed, peak: violation.peak, processes: violation.processes, top, message });
247
+ }
248
+ });
249
+ signal();
250
+ return;
251
+ }
252
+ }
210
253
  const nextSize = (await fileStat(session).catch(() => ({ size: 0 }))).size;
211
254
  if (nextSize > size) {
212
255
  clock.evidence();
@@ -0,0 +1,144 @@
1
+ import { snapshotCapturedAt } from "../../platform/proctable.js";
2
+ /** Default consecutive ms a resource limit must be exceeded before fencing (avoids killing brief compilation spikes). */
3
+ export const DEFAULT_RESOURCE_GRACE_MS = 5_000;
4
+ /** Minimum interval between samples before computing a CPU % delta (avoids noisy spikes on sub-200ms back-to-back scans). */
5
+ const MIN_CPU_DELTA_MS = 200;
6
+ const round1 = (n) => Math.round(n * 10) / 10;
7
+ const bytesToMb = (bytes) => bytes / (1024 * 1024);
8
+ /** Format a human-readable error message for a sealed resource-limit failure. */
9
+ export function formatResourceViolation(v) {
10
+ const topText = v.top.length
11
+ ? `; top: ${v.top.map(p => `pid ${p.pid} ${round1(p.rssMb)} MiB${p.command ? ` \`${p.command.slice(0, 60)}\`` : ""}`).join(", ")}`
12
+ : "";
13
+ if (v.kind === "memory") {
14
+ return `Resource limit exceeded: memory ${round1(v.observed)} MiB > ${v.limit} MiB limit (peak ${round1(v.peak)} MiB across ${v.processes} process${v.processes === 1 ? "" : "es"}${topText})`;
15
+ }
16
+ if (v.kind === "processes") {
17
+ return `Resource limit exceeded: ${v.observed} processes > ${v.limit} maxProcesses limit (peak ${v.peak}${topText})`;
18
+ }
19
+ return `Resource limit exceeded: CPU ${Math.round(v.observed)}% > ${v.limit}% limit (peak ${Math.round(v.peak)}% across ${v.processes} process${v.processes === 1 ? "" : "es"}${topText})`;
20
+ }
21
+ /** Tracks live & peak memory, process count, and CPU % for one execution's entire process tree. */
22
+ export class ResourceMonitor {
23
+ limits;
24
+ peakMemoryMb = 0;
25
+ peakProcesses = 0;
26
+ peakCpuPercent;
27
+ lastStats;
28
+ lastSampleAt;
29
+ prevAt;
30
+ prevCpu = new Map();
31
+ exceededSince = {};
32
+ constructor(limits) {
33
+ this.limits = limits;
34
+ }
35
+ /** Update active limits in place (e.g. after a live config.json reload). */
36
+ setLimits(limits) {
37
+ this.limits = limits;
38
+ if (!limits?.memoryMb)
39
+ this.exceededSince.memory = undefined;
40
+ if (!limits?.maxProcesses)
41
+ this.exceededSince.processes = undefined;
42
+ if (!limits?.cpuPercent)
43
+ this.exceededSince.cpu = undefined;
44
+ }
45
+ /** Most recently computed stats, if at least one sample has been recorded. */
46
+ latest() {
47
+ return this.lastStats ? { ...this.lastStats } : undefined;
48
+ }
49
+ /** Feed one process-tree snapshot and current monotonic/wall timestamp in ms.
50
+ * `overheadPids` (command wrapper / Windows job host) are excluded from `processes` and `rssBytes` so
51
+ * `maxProcesses: 1` allows a single user command without counting internal harness processes. */
52
+ sample(procs, nowMs, overheadPids) {
53
+ // Deduplicate cached ProcessTable snapshots so repeated reads of the same scan never reset CPU % to 0,
54
+ // inflate the next real scan's CPU delta, or advance grace timers on stale spikes.
55
+ const sampleAt = snapshotCapturedAt(procs) ?? nowMs;
56
+ if (this.lastSampleAt !== undefined && sampleAt <= this.lastSampleAt && this.lastStats) {
57
+ return { stats: { ...this.lastStats } };
58
+ }
59
+ this.lastSampleAt = sampleAt;
60
+ const counted = overheadPids?.size ? procs.filter(p => !overheadPids.has(p.pid)) : procs;
61
+ let totalRssBytes = 0;
62
+ for (const p of counted) {
63
+ if (typeof p.rssBytes === "number" && Number.isFinite(p.rssBytes) && p.rssBytes > 0) {
64
+ totalRssBytes += p.rssBytes;
65
+ }
66
+ }
67
+ const memoryMb = round1(bytesToMb(totalRssBytes));
68
+ const processes = counted.length;
69
+ if (memoryMb > this.peakMemoryMb)
70
+ this.peakMemoryMb = memoryMb;
71
+ if (processes > this.peakProcesses)
72
+ this.peakProcesses = processes;
73
+ let cpuPercent;
74
+ const nextCpu = new Map();
75
+ for (const p of counted) {
76
+ if (typeof p.cpuMs === "number" && Number.isFinite(p.cpuMs) && p.cpuMs >= 0) {
77
+ nextCpu.set(`${p.pid}:${p.start}`, p.cpuMs);
78
+ }
79
+ }
80
+ if (this.prevAt !== undefined) {
81
+ const dt = sampleAt - this.prevAt;
82
+ if (dt >= MIN_CPU_DELTA_MS) {
83
+ let deltaCpuMs = 0;
84
+ for (const [id, cpu] of nextCpu) {
85
+ const prev = this.prevCpu.get(id);
86
+ // Count delta for surviving processes and full observed cpuMs for freshly spawned children in this interval.
87
+ deltaCpuMs += prev !== undefined ? Math.max(0, cpu - prev) : cpu;
88
+ }
89
+ cpuPercent = round1((deltaCpuMs / dt) * 100);
90
+ if (this.peakCpuPercent === undefined || cpuPercent > this.peakCpuPercent) {
91
+ this.peakCpuPercent = cpuPercent;
92
+ }
93
+ this.prevAt = sampleAt;
94
+ this.prevCpu = nextCpu;
95
+ }
96
+ else {
97
+ cpuPercent = this.lastStats?.cpuPercent;
98
+ }
99
+ }
100
+ else {
101
+ this.prevAt = sampleAt;
102
+ this.prevCpu = nextCpu;
103
+ }
104
+ const stats = {
105
+ memoryMb,
106
+ peakMemoryMb: this.peakMemoryMb,
107
+ processes,
108
+ peakProcesses: this.peakProcesses,
109
+ ...(cpuPercent !== undefined ? { cpuPercent } : {}),
110
+ ...(this.peakCpuPercent !== undefined ? { peakCpuPercent: this.peakCpuPercent } : {}),
111
+ };
112
+ this.lastStats = stats;
113
+ const limits = this.limits;
114
+ if (!limits)
115
+ return { stats };
116
+ const graceMs = limits.graceMs ?? DEFAULT_RESOURCE_GRACE_MS;
117
+ const top = () => [...counted]
118
+ .filter(p => typeof p.rssBytes === "number" && p.rssBytes > 0)
119
+ .sort((a, b) => (b.rssBytes ?? 0) - (a.rssBytes ?? 0))
120
+ .slice(0, 3)
121
+ .map(p => ({ pid: p.pid, rssMb: round1(bytesToMb(p.rssBytes)) }));
122
+ const check = (kind, observed, limit, peak) => {
123
+ if (limit === undefined || observed === undefined) {
124
+ this.exceededSince[kind] = undefined;
125
+ return undefined;
126
+ }
127
+ if (observed > limit) {
128
+ this.exceededSince[kind] ??= sampleAt;
129
+ if (sampleAt - this.exceededSince[kind] >= graceMs) {
130
+ return { kind, limit, observed, peak, graceMs, processes, top: top() };
131
+ }
132
+ }
133
+ else {
134
+ this.exceededSince[kind] = undefined;
135
+ }
136
+ return undefined;
137
+ };
138
+ // Priority: memory -> processes -> cpu (memory OOM is the most urgent threat to host stability).
139
+ const violation = check("memory", memoryMb, limits.memoryMb, this.peakMemoryMb) ??
140
+ check("processes", processes, limits.maxProcesses, this.peakProcesses) ??
141
+ check("cpu", cpuPercent, limits.cpuPercent, this.peakCpuPercent ?? 0);
142
+ return violation ? { stats, violation } : { stats };
143
+ }
144
+ }
@@ -125,10 +125,15 @@ export function evidence(entries, exec) {
125
125
  if (value.trim())
126
126
  text = value;
127
127
  }
128
- usage.input += m.usage?.input ?? 0;
128
+ usage.input += (m.usage?.input ?? 0) + (m.usage?.cacheRead ?? 0) + (m.usage?.cacheWrite ?? 0);
129
129
  usage.output += m.usage?.output ?? 0;
130
130
  usage.costUsd += m.usage?.cost?.total ?? 0;
131
131
  }
132
+ else if (e.type === "usage" && e.usage) {
133
+ usage.input += (e.usage.input ?? 0) + (e.usage.cacheRead ?? 0) + (e.usage.cacheWrite ?? 0);
134
+ usage.output += e.usage.output ?? 0;
135
+ usage.costUsd += e.usage.cost?.total ?? 0;
136
+ }
132
137
  // P28: an ask cut off by shutdown or abort while its question waited keeps an unknown outcome, like one with no result.
133
138
  if (m?.role === "toolResult" && m.toolCallId && !(asked.has(m.toolCallId) && cutAskResult(m)))
134
139
  tools.delete(m.toolCallId);
@@ -2,22 +2,36 @@
2
2
  import { contentHash } from "../../kernel/ids.js";
3
3
  import { budgets } from "../../kernel/guards.js";
4
4
  import { CT } from "../../types.js";
5
+ function normalizeUsage(raw) {
6
+ return {
7
+ input: (raw.input ?? 0) + (raw.cacheRead ?? 0) + (raw.cacheWrite ?? 0),
8
+ output: raw.output ?? 0,
9
+ costUsd: raw.cost?.total ?? 0,
10
+ };
11
+ }
5
12
  /** P31: Use the provider message identity, or native timestamp/content identity when pi omits an id. */
6
13
  export function messageUsage(message) {
7
14
  if (message.role !== "assistant" || !message.usage)
8
15
  return;
9
16
  const raw = message.usage;
10
- return { id: String(message.id ?? message.timestamp ?? contentHash(message)), usage: {
11
- input: (raw.input ?? 0) + (raw.cacheRead ?? 0) + (raw.cacheWrite ?? 0), output: raw.output ?? 0, costUsd: raw.cost?.total ?? 0,
12
- } };
17
+ return { id: String(message.id ?? message.timestamp ?? contentHash(message)), usage: normalizeUsage(raw) };
18
+ }
19
+ /** P31: Extract usage from either an assistant message entry or a standalone pi `usage` entry (e.g. `cache_warm`). */
20
+ export function entryUsage(entry) {
21
+ if (entry.message)
22
+ return messageUsage(entry.message);
23
+ if (entry.type === "usage" && entry.usage) {
24
+ return { id: String(entry.id ?? entry.timestamp ?? contentHash(entry)), usage: normalizeUsage(entry.usage) };
25
+ }
26
+ return undefined;
13
27
  }
14
- /** P31: Charge only messages in segments opened by this call, excluding inherited context. */
28
+ /** P31: Charge only messages and usage entries in segments opened by this call, excluding inherited context. */
15
29
  export function sessionUsage(entries, call) {
16
30
  let own = false;
17
31
  return entries.flatMap(e => {
18
32
  if (e.type === "custom" && e.customType === CT.exec)
19
33
  own = typeof e.data?.exec === "string" && e.data.exec.startsWith(`${call}#`);
20
- const u = own && e.message && messageUsage(e.message);
34
+ const u = own && entryUsage(e);
21
35
  return u ? [u] : [];
22
36
  });
23
37
  }
@@ -397,6 +397,11 @@ function snapshotReducer(wid, entries) {
397
397
  call.selectedModel = call.model;
398
398
  }
399
399
  }
400
+ else if (e.type === "time" && e.resources && typeof e.resources === "object") {
401
+ const call = byExec.get(String(e.exec));
402
+ if (call)
403
+ call.resources = e.resources;
404
+ }
400
405
  else if (e.type === "observation") {
401
406
  // Only what the agent did counts as activity; tracker scans and time checkpoints are bookkeeping.
402
407
  const call = byExec.get(String(e.exec));
@@ -1339,7 +1344,7 @@ export function compactWorkflow(wf, leases) {
1339
1344
  const r = c.result, last = r?.output?.split("\n").map(l => l.trim()).filter(Boolean).at(-1);
1340
1345
  return { key: c.key, gen: c.gen, callId: c.callId, phase: c.phase, ...modelStatus(c), ...commandStatus(c), ...(r ? { status: r.status, ok: r.ok } : {}),
1341
1346
  ...(c.sharedWorktree ? { sharedWorktree: c.sharedWorktree } : {}),
1342
- ...(c.model ? { model: c.model } : {}), ...(c.tools ? { tools: c.tools } : {}), ...(c.pending ? { pending: c.pending } : {}), ...(c.switching ? { switching: c.switching } : {}), ...(c.switchFailed ? { switchFailed: c.switchFailed } : {}), ...(nonzero(c.usage) ? { usage: c.usage } : {}),
1347
+ ...(c.model ? { model: c.model } : {}), ...(c.tools ? { tools: c.tools } : {}), ...(c.pending ? { pending: c.pending } : {}), ...(c.switching ? { switching: c.switching } : {}), ...(c.switchFailed ? { switchFailed: c.switchFailed } : {}), ...(nonzero(c.usage) ? { usage: c.usage } : {}), ...(c.resources ? { resources: c.resources } : {}),
1343
1348
  ...(last ? { lastLine: clip(last, 200) } : {}), ...(r?.error ? { error: clip(r.error, 300) } : {}), ...(c.hibernated ? { hibernated: true } : {}),
1344
1349
  ...(c.answered ? { answered: c.answered } : {}), ...(c.answerForwarded ? { answerForwarded: c.answerForwarded } : {}), ...(c.writerWait && !r ? { writerWait: c.writerWait } : {}), ...(!r && leases?.get(c.callId) ? { lease: leases.get(c.callId) } : {}),
1345
1350
  ...(c.notesPending ? { notesPending: c.notesPending } : {}), ...(c.queuedFor && !r && !wf.paused ? { queued: queuedText(c.queuedFor) } : {}), ...(c.exact ? { exact: c.exact } : {}) };
@@ -1560,6 +1565,7 @@ export function statusBrief(home, options = {}) {
1560
1565
  ...(live && c.startedAt !== undefined ? { for: age(now - c.startedAt) } : {}),
1561
1566
  ...(agent && live && c.phase !== "asking" && quiet !== undefined && quiet >= 60_000 ? { quiet: age(quiet) } : {}),
1562
1567
  ...(agent && live && c.startedAt !== undefined ? { tokens: tokens(c.usage) } : {}),
1568
+ ...(live && c.resources && c.resources.peakMemoryMb > 0 ? { memory: `${Math.round(c.resources.memoryMb)} MiB (peak ${Math.round(c.resources.peakMemoryMb)} MiB, ${c.resources.processes} proc${c.resources.processes === 1 ? "" : "s"})` } : {}),
1563
1569
  ...(c.result ? { status: c.result.status, ...(c.result.error ? { error: clip(c.result.error, 200) } : {}) } : {}),
1564
1570
  ...(c.hibernated ? { hibernated: true } : {}), ...(c.answered ? { answered: c.answered } : {}), ...(c.answerForwarded ? { answerForwarded: c.answerForwarded } : {}), ...(live && c.writerWait ? { writerWait: c.writerWait } : {}),
1565
1571
  ...(live && byCall.get(c.callId) ? { lease: byCall.get(c.callId) } : {}),