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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.7.0
4
+
5
+ - **Per-subagent process-tree resource limits (#13)**: Cap each subagent (agent calls and command calls) across its entire process tree via global `config.json` `limits` (live-reloaded) or per-call / run-level `limits` (`{ memoryMb?, maxProcesses?, cpuPercent?, graceMs?, strict? }`, merged field-by-field):
6
+ - **Layer 1 (all platforms — process-tree monitor & circuit breaker)**: Collects RSS with zero extra syscalls/subprocesses across Linux (`/proc/<pid>/stat`), macOS (`ps -o rss=`) and Windows (`Win32_Process.WorkingSetSize`); aggregates whole-tree RSS, process count (excluding internal command harnesses) and CPU % with snapshot `capturedAt` deduplication; waits `graceMs` (default 5000 ms) before appending durable `resource-limit` / `command-resource-limit` evidence with top-3 memory processes, fencing the process tree, and sealing `failed` deterministically without retrying or rerunning (`rerun: true` never re-executes).
7
+ - **Layer 2 (OS kernel hard limits & `strict` mode)**: On Linux with delegated unified cgroup v2, wraps agent and command launches in transient `systemd-run --user --scope` units (`MemoryMax`, `MemorySwapMax=0`, `CPUQuota`) and detects `Result=oom-kill` (with `reset-failed` cleanup); on Windows, extends `DsaJob.exe` (`DSAJOB2`) with `JOB_OBJECT_LIMIT_JOB_MEMORY` (+64 MiB wrapper headroom), `JOB_OBJECT_LIMIT_ACTIVE_PROCESS`, `JobObjectCpuRateControlInformation` hard cap and I/O Completion Port `JOB_OBJECT_MSG_JOB_MEMORY_LIMIT` detection. Hosts without kernel enforcement transparently fall back to Layer 1 unless `strict: true` is set, which fails the call before launch.
8
+ - **Observability**: Checkpoints live/peak memory, process count and CPU % onto agent `time` entries (surfaced in `status`, `compactWorkflow` and `statusBrief.memory`) and reports local kernel limit capabilities in `pi-durable-subagents doctor`.
9
+
10
+ ## 1.6.1
11
+
12
+ - **Standalone `pi` binary safety (#11, #7)**: When `pi` runs as a standalone compiled Bun/SEA binary (`process.execPath` points to `pi` rather than `node`), `launchOrchestrator`, `install-service`, Windows shim unwrapping and `npmCommand` now resolve a real Node.js runtime (`DSA_NODE_BIN` -> verified Node `process.execPath` -> `node`/`nodejs` on `PATH`, preferring `.exe`/`.com` on Windows and wrapping `.cmd` shims through `cmd.exe`), refuse any runtime resolving to `pi` while keeping multi-call shims (`mise`/`volta`/`asdf`) working, and add a hard `DSA_ORCHESTRATOR_LAUNCH` self-spawn guard inside the extension so a misconfigured launch exits immediately instead of spawning recursive headless `pi` sessions.
13
+ - **`pi` 1.5.1+ / 1.6.0 cache-warming compatibility**:
14
+ - Ignore 1-token `CacheWarmer` payloads in exact-fork request capture, exact-child request splicing and `live.json` waiting-state tracking, and stop cache warming inside exact children via `cache_warming_decision`.
15
+ - Account for standalone `type: "usage"` (`cache_warm`) session entries across session usage folds, live `entry_appended` observation, child usage reporting and execution `evidence()` (deduplicated by entry id and scoped to the call's own execution segment).
16
+
3
17
  ## 1.6.0
4
18
 
5
19
  - **Native Windows support** (Node.js 22.19+ and 24, no WSL or POSIX tools required; based on #4):
package/README.md CHANGED
@@ -1283,12 +1283,31 @@ State lives in `~/.pi/durable-subagents`; set `DSA_HOME` to move it.
1283
1283
  }
1284
1284
  },
1285
1285
  "memory": { "reserveMb": 2048, "perChildMb": 300 },
1286
+ "limits": { "memoryMb": 4096, "maxProcesses": 64, "cpuPercent": 400, "graceMs": 5000, "strict": false },
1286
1287
  "writerLock": "queue",
1287
1288
  "askRequireDecision": false,
1288
1289
  "exactCapture": true
1289
1290
  }
1290
1291
  ```
1291
1292
 
1293
+ - **Per-subagent resource limits (`limits`):** caps each call's entire process
1294
+ tree (the subagent plus every tool/build/test child it spawns). Set global
1295
+ defaults in `config.json` (`limits`, live-reloaded) and override any field
1296
+ per call via `limits: { memoryMb?, maxProcesses?, cpuPercent?, graceMs?, strict? }`
1297
+ on agent calls, command calls, or `tasks`/`chain` defaults:
1298
+ - `memoryMb`: max total resident memory (RSS / WorkingSet) in MiB.
1299
+ - `maxProcesses`: max concurrent processes in the call's tree.
1300
+ - `cpuPercent`: max CPU usage across the tree (% of one core; e.g. `200` = 2 cores).
1301
+ - `graceMs`: consecutive ms a limit may stay exceeded before fencing (default `5000`).
1302
+ - `strict`: when `true`, refuse to start unless OS kernel hard limits cover the requested caps.
1303
+ - **Two-layer enforcement:** Layer 1 monitors the process tree on Linux, macOS
1304
+ and Windows, fences the whole tree on a sustained breach, and seals the call
1305
+ `failed` with the peak usage and top processes (never retried as a loss).
1306
+ Layer 2 automatically adds OS kernel hard limits where available — Linux
1307
+ transient user scopes via `systemd-run --user --scope` under delegated
1308
+ unified cgroup v2 (`MemoryMax` + `CPUQuota`), and Windows Job Object limits
1309
+ (`JobMemoryLimit`, `ActiveProcessLimit`, `CpuRateControl`) for command calls.
1310
+ Run `pi-durable-subagents doctor` to see which backend is active on your host.
1292
1311
  - **Pools:** a model can name a pool (the `model` of a call, a `run --spec`
1293
1312
  file or a model send). The first candidate with a free slot is
1294
1313
  used, and a candidate that keeps failing is skipped for 10 minutes. The
@@ -1,6 +1,7 @@
1
1
  // Upgrade safety (robustness.md layer 3, AC5): probe every pi surface we use before registering anything.
2
2
  // A missing tier-0 surface disables Durable Subagents with one exact message; a missing UI surface disables only
3
3
  // the UI. Never a silent failure, never a crash of pi.
4
+ import { isNodeProcess, resolveNode, resolvePi } from "../platform/launch.js";
4
5
  export const SURFACES = [
5
6
  ...["on", "registerTool", "appendEntry", "sendMessage", "setModel", "setThinkingLevel"].map(name => ({ tier: 0, where: "ExtensionAPI", name })),
6
7
  { tier: 0, where: "@earendil-works/pi-coding-agent", name: "defineTool" },
@@ -15,23 +16,29 @@ export const SURFACES = [
15
16
  * native implementation for these platforms; anywhere else every call would fail at spawn, so execution is disabled
16
17
  * at load instead. Windows uses PowerShell/CIM for the process table and handle-verified Win32 termination for fencing. */
17
18
  export const SUPPORTED_PLATFORMS = ["linux", "darwin", "win32"];
18
- /** AC5, P21, issue #1: Check the platform and the surfaces present in pi's modules and extension API; produce exact
19
- * degradation messages. */
20
- export function checkCapabilities(modules, api, version, platform = process.platform) {
19
+ export function checkCapabilities(modules, api, version, platform = process.platform, runtime = {}) {
21
20
  const has = (s) => s.where === "ExtensionAPI" ? typeof api[s.name] === "function" : modules[s.where]?.[s.name] !== undefined;
22
21
  const missing = SURFACES.filter(s => !has(s));
23
22
  const name = (list) => list.map(s => `${s.where}.${s.name}`).join(", ");
24
23
  const pi = version ? `pi ${version}` : "this pi version";
24
+ const os = SUPPORTED_PLATFORMS.includes(platform);
25
25
  // The evaluator's CPU limit needs worker.cpuUsage and process.threadCpuUsage (Node 22.19); without them a runaway
26
26
  // script would never be stopped, so an older Node disables execution rather than run unguarded.
27
- const node = typeof process.threadCpuUsage === "function";
28
- const os = SUPPORTED_PLATFORMS.includes(platform);
29
- const execution = os && node && !missing.some(s => s.tier === 0), ui = execution && !missing.some(s => s.tier === 2);
27
+ // When pi itself is a standalone compiled binary (e.g. Bun via mise, #11), process.execPath is pi rather than node:
28
+ // check that a real Node.js executable can be resolved via DSA_NODE_BIN or PATH so the orchestrator can start.
29
+ const hostIsNode = runtime.isNode ?? isNodeProcess();
30
+ const node = hostIsNode ? (runtime.hasThreadCpuUsage ?? typeof process.threadCpuUsage === "function") : true;
31
+ const probeEnv = runtime.env ?? process.env;
32
+ const externalNode = os && !hostIsNode ? resolveNode(probeEnv, { platform, versions: { bun: "standalone" }, piPath: runtime.piPath ?? resolvePi(probeEnv, platform).path ?? process.execPath }) : undefined;
33
+ const hasNode = hostIsNode ? node : Boolean(externalNode?.path);
34
+ const execution = os && hasNode && !missing.some(s => s.tier === 0), ui = execution && !missing.some(s => s.tier === 2);
30
35
  const messages = [];
31
36
  if (!os)
32
37
  messages.push(`Durable Subagents disabled: it runs only on Linux, macOS and Windows (this is ${platform}); its process layer (process tracking, file locks, command calls) has no ${platform} implementation.`);
33
- else if (!node)
38
+ else if (hostIsNode && !node)
34
39
  messages.push(`Durable Subagents disabled: it needs Node.js 22.19 or later (this is ${process.version}).`);
40
+ else if (!hostIsNode && !externalNode?.path)
41
+ messages.push(`Durable Subagents disabled: pi is running as a standalone binary, so it needs Node.js 22.19 or later on PATH (or DSA_NODE_BIN) to run the orchestrator (${externalNode?.problem}).`);
35
42
  else if (!execution)
36
43
  messages.push(`Durable Subagents disabled: ${pi} no longer provides ${name(missing.filter(s => s.tier === 0))}. Running workflows are untouched; run \`pi-durable-subagents smoke\` for details.`);
37
44
  else if (!ui)
@@ -5,6 +5,7 @@
5
5
  import { renameSync, writeFileSync } from "node:fs";
6
6
  import { replacePathSync } from "../../kernel/fsx.js";
7
7
  import { dirname, join } from "node:path";
8
+ import { isCacheWarmingPayload } from "../exact/capture.js";
8
9
  export const LIVE_FILE = "live.json";
9
10
  const TAIL = 4000, EVERY_MS = 250;
10
11
  const tail = (text) => text.length > TAIL ? text.slice(-TAIL) : text;
@@ -44,7 +45,13 @@ export function registerLive(pi, enabled) {
44
45
  const waiting = (_event, ctx) => { if (state?.phase !== "waiting")
45
46
  since = Date.now(); publish(ctx, { phase: "waiting", since }); };
46
47
  pi.on("turn_start", waiting);
47
- pi.on("before_provider_request", waiting);
48
+ // Ignore pi 1.5.1+ CacheWarmer refreshes: they fire before_provider_request without a matching message_end,
49
+ // which would leave live.json stuck in "waiting" while a tool is running.
50
+ pi.on("before_provider_request", (event, ctx) => {
51
+ if (isCacheWarmingPayload(event?.payload))
52
+ return;
53
+ waiting(event, ctx);
54
+ });
48
55
  pi.on("message_update", (event, ctx) => {
49
56
  const m = event.message;
50
57
  if (m.role !== "assistant" || !Array.isArray(m.content))
@@ -35,7 +35,7 @@ export function usage(entries, call) {
35
35
  own = call === undefined || String(e.data?.exec ?? '').startsWith(`${call}#`) || !/#\d+\.\d+$/.test(String(e.data?.exec ?? ''));
36
36
  if (!own)
37
37
  continue;
38
- const u = e.type === 'message' && e.message?.role === 'assistant' ? e.message.usage : undefined;
38
+ const u = e.type === 'message' && e.message?.role === 'assistant' ? e.message.usage : e.type === 'usage' ? e.usage : undefined;
39
39
  if (!u || (e.id && seen.has(e.id)))
40
40
  continue;
41
41
  if (e.id)
@@ -119,3 +119,22 @@ export function exactCaptureEnabled(config) {
119
119
  }
120
120
  /** The identity of a capture's payload: the sha256 of its serialized bytes. */
121
121
  export const payloadHash = (payload) => contentHash(payload);
122
+ /** Whether a provider payload is pi's 1-token cache-warming refresh (pi 1.5.1+ CacheWarmer).
123
+ * CacheWarmer replays the last request with maxTokens: 1 (clamped to 16 on OpenAI Responses); real turns
124
+ * use the model's maxTokens (thousands). */
125
+ export function isCacheWarmingPayload(payload) {
126
+ if (!payload || typeof payload !== "object")
127
+ return false;
128
+ const p = payload;
129
+ if (p.max_tokens === 1 || p.max_completion_tokens === 1 || p.maxTokens === 1)
130
+ return true;
131
+ if (p.max_output_tokens === 16 || p.max_output_tokens === 1)
132
+ return true;
133
+ const gen = p.generationConfig;
134
+ if (gen && typeof gen === "object" && gen.maxOutputTokens === 1)
135
+ return true;
136
+ const inf = p.inferenceConfig;
137
+ if (inf && typeof inf === "object" && inf.maxTokens === 1)
138
+ return true;
139
+ return false;
140
+ }
@@ -13,6 +13,7 @@
13
13
  import { readFile } from "node:fs/promises";
14
14
  import fs from "node:fs";
15
15
  import { CT, ENV } from "../../types.js";
16
+ import { isCacheWarmingPayload } from "./capture.js";
16
17
  import { splicePayload } from "./splice.js";
17
18
  /** Every refused tool result starts with this text (EX4). */
18
19
  export const EXACT_REFUSAL = "tool refused in exact fork:";
@@ -95,10 +96,16 @@ export function registerExactChild(pi, exact) {
95
96
  }
96
97
  ctx.abort();
97
98
  };
99
+ // pi 1.5.1+ CacheWarmer replays requests with maxTokens: 1 through before_provider_request; splicing the parent's
100
+ // max_tokens over a warm refresh would turn it into a full-length generation. Stop warming inside exact children
101
+ // (no-op on older pi versions that never emit this event).
102
+ pi.on("cache_warming_decision", () => ({ action: "stop" }));
98
103
  // EX4: the request the child would send is replaced by the parent's fields and the concatenated conversation.
99
104
  pi.on("before_provider_request", async (event, ctx) => {
100
105
  const payload = event.payload;
101
- if (!payload || typeof payload !== "object")
106
+ // Defense in depth: even if another extension overrides cache_warming_decision, never splice parent.max_tokens
107
+ // onto a 1-token cache-warming payload.
108
+ if (!payload || typeof payload !== "object" || isCacheWarmingPayload(payload))
102
109
  return;
103
110
  const capture = await captureOf();
104
111
  if (!capture)
@@ -10,7 +10,7 @@
10
10
  import { readFile } from "node:fs/promises";
11
11
  import { join } from "node:path";
12
12
  import { dsaHome } from "../../paths.js";
13
- import { writeCapture } from "./capture.js";
13
+ import { isCacheWarmingPayload, writeCapture } from "./capture.js";
14
14
  import { clone } from "./splice.js";
15
15
  /** The home of the dsa state (the captures live under it): $DSA_HOME or the default state root. */
16
16
  export const homeOf = (env = process.env) => dsaHome(env);
@@ -36,7 +36,9 @@ export async function registerCapture(pi, home) {
36
36
  let writing = Promise.resolve();
37
37
  pi.on("before_provider_request", (event, ctx) => {
38
38
  const payload = event.payload;
39
- if (!payload || typeof payload !== "object")
39
+ // pi 1.5.1+ CacheWarmer replays the last request with maxTokens: 1 (16 on OpenAI Responses) through this hook;
40
+ // never overwrite the real capture with a cache-warming payload or exact children would inherit a 1-token cap.
41
+ if (!payload || typeof payload !== "object" || isCacheWarmingPayload(payload))
40
42
  return;
41
43
  const sessionId = ctx.sessionManager?.getSessionId?.();
42
44
  if (!sessionId)
@@ -15,12 +15,25 @@ const LOADED = Symbol.for("pi-durable-subagents.loaded");
15
15
  /** P21: A child (DSA_EXEC set) without its execution surfaces cannot do its call; it reports the exact message on
16
16
  * stderr and exits 3, so the executor records the message per call and counts a loss (failed after K2) instead of
17
17
  * waiting on a child that will never act. Returns the stderr text, or undefined when the child may proceed. */
18
+ /** Issue #11: Defense in depth against a standalone compiled pi binary ever spawning itself as the orchestrator.
19
+ * launchOrchestrator sets DSA_ORCHESTRATOR_LAUNCH=1; a real Node.js orchestrator deletes it at startup, so seeing
20
+ * it inside the pi extension means pi itself was launched in place of node. */
21
+ export function orchestratorLaunchRefusal(env = process.env) {
22
+ if (!env[ENV.orchestratorLaunch])
23
+ return undefined;
24
+ return "Durable Subagents: refusing to run inside a pi process spawned as the orchestrator (set DSA_NODE_BIN to a Node.js 22.19+ executable or put node on PATH).";
25
+ }
18
26
  export function childRefusal(report, env) {
19
27
  if (!env[ENV.exec] || report.execution)
20
28
  return undefined;
21
29
  return report.messages.join("\n");
22
30
  }
23
31
  export default async function (pi) {
32
+ const loopRefusal = orchestratorLaunchRefusal(process.env);
33
+ if (loopRefusal !== undefined) {
34
+ writeSync(2, `${loopRefusal}\n`);
35
+ process.exit(4);
36
+ }
24
37
  const modules = { "@earendil-works/pi-coding-agent": coding, "@earendil-works/pi-tui": tui, "@earendil-works/pi-ai": ai };
25
38
  const report = checkCapabilities(modules, pi, typeof coding.VERSION === "string" ? String(coding.VERSION) : undefined);
26
39
  if (process.env.DSA_PROBE) {
@@ -1,8 +1,8 @@
1
1
  // The subagents tool's parameter schema. Kept apart from tool.ts because it needs the optional pi peer
2
2
  // package, which the CLI (sharing tool.ts) must not import: it runs from the package directory.
3
3
  import { Type } from "@earendil-works/pi-ai";
4
- const stepsDoc = "Call specs {agent, task, model?, cwd?, timeoutMs?, output?, schema?, gate?, isolation?, context?, budget?, once?, tools?, skills?, writer?, key?} " +
5
- "or command specs {command, cwd?, timeoutMs?, env?, rerun?, writer?, key?}; " +
4
+ const stepsDoc = "Call specs {agent, task, model?, cwd?, timeoutMs?, output?, schema?, gate?, isolation?, context?, budget?, limits?, once?, tools?, skills?, writer?, key?} " +
5
+ "or command specs {command, cwd?, timeoutMs?, limits?, env?, rerun?, writer?, key?}; " +
6
6
  "each call is addressed as '<wid>/<key>', where key is the step's own unique key or else 'tasks:<i>' / 'chain:<i>'.";
7
7
  export const parameters = Type.Object({
8
8
  action: Type.Optional(Type.Union(["run", "agents", "send", "stop", "revise", "status", "resume", "drain", "restart"].map(v => Type.Literal(v)))),
@@ -23,6 +23,13 @@ export const parameters = Type.Object({
23
23
  name: Type.Optional(Type.String()),
24
24
  labels: Type.Optional(Type.Record(Type.String(), Type.String(), { description: "run: your labels, e.g. {node, attempt}: at most 32 keys [A-Za-z0-9_.:-]{1,64}, string values of at most 256 characters, 4096 bytes of JSON; part of the request's content (spec_digest), shown by describe and on its events." })),
25
25
  timeoutMs: Type.Optional(Type.Number({ description: "Per-call limit on active time in milliseconds (a number; a command call: wall-clock time since it started). Omit unless a hard limit is needed; prefer budgets." })),
26
+ limits: Type.Optional(Type.Object({
27
+ memoryMb: Type.Optional(Type.Number({ exclusiveMinimum: 0, description: "Max resident memory (MiB) across the call's process tree." })),
28
+ maxProcesses: Type.Optional(Type.Integer({ minimum: 1, description: "Max concurrent processes in the call's process tree." })),
29
+ cpuPercent: Type.Optional(Type.Number({ exclusiveMinimum: 0, description: "Max CPU usage across the call's process tree (% of one core, e.g. 200 = 2 cores)." })),
30
+ graceMs: Type.Optional(Type.Number({ minimum: 0, description: "Consecutive ms a limit may be exceeded before fencing (default 5000)." })),
31
+ strict: Type.Optional(Type.Boolean({ description: "Refuse to launch if OS kernel hard limits (Linux cgroup v2 / Windows Job Object) are unavailable." })),
32
+ }, { additionalProperties: false, description: "Per-call process-tree resource limits (overrides config.json limits)." })),
26
33
  key: Type.Optional(Type.String({ description: "A single agent/task run: the call's key. status with wid: that call's full result." })),
27
34
  tail: Type.Optional(Type.Integer({ minimum: 1, description: "status with wid: the last N lines of each call's result (unclipped, at most 4000 characters per call)." })),
28
35
  grep: Type.Optional(Type.String({ description: "status with wid: only the lines of each call's result matching this case-sensitive JS regular expression, run in-process: avoid nested quantifiers such as (a+)+; it tests the first 2000 characters of a line and the last 5000 lines (with tail: grep first, then the last N)." })),
@@ -9,9 +9,9 @@ import { validateCallSpec } from "../../compat/spec.js";
9
9
  import { compileFanout } from "../../compat/fanout.js";
10
10
  import { checkLabels } from "../../events/labels.js";
11
11
  /** Call fields a tasks/chain run applies to every step that does not set its own. */
12
- export const stepDefaults = ["agent", "model", "timeoutMs", "budget", "isolation", "context", "tools", "skills", "once", "writer", "env", "rerun"];
12
+ export const stepDefaults = ["agent", "model", "timeoutMs", "budget", "limits", "isolation", "context", "tools", "skills", "once", "writer", "env", "rerun"];
13
13
  /** The run-level defaults a command step takes; agent steps take the others (env and rerun belong to command calls). */
14
- const commandDefaults = new Set(["timeoutMs", "writer", "env", "rerun"]), agentOnly = new Set(["env", "rerun"]);
14
+ const commandDefaults = new Set(["timeoutMs", "limits", "writer", "env", "rerun"]), agentOnly = new Set(["env", "rerun"]);
15
15
  /** The run-level defaults that apply to one step: a command step skips agent-only fields, an agent step skips env/rerun. */
16
16
  function defaultsFor(step, defaults) {
17
17
  const command = step.command !== undefined;
@@ -511,7 +511,7 @@ export function registerMain(pi, ui) {
511
511
  pi.registerTool(defineTool({
512
512
  name: "subagents", label: "Subagents", description: [
513
513
  "Durable asynchronous subagents; run returns {wid} when created (or {submitted:{rid}} while pending). A finished workflow (its notice carries every agent's result) or a question wakes you, so after starting work end your turn: never poll with sleep or repeated status. Crash recovery resumes sessions, not external side effects. Background helper processes (orchestrator, evaluator) exit by themselves about 10 s after all work ends: never kill processes or delete files to 'clean up'. When the user quits pi, this session's running workflows pause (nothing is spent); resume continues them.",
514
- "run (action optional for exactly one launch form): agent+task; command (a command call); tasks:[call specs] parallel; chain:[call specs] sequential ({previous}); workflow:'./script.js' or source (runs.run(key,spec), runs.all([...]), emit(value), args, runs.input(name)). Optional name, cwd, usageBudget, maxCalls, inputs, labels. With tasks/chain, top-level agent (without task), model, timeoutMs, budget, isolation, context, tools, skills, once, writer are defaults for every step (a step's own value wins); a workflow/source script sets them per runs.run call. timeoutMs is milliseconds of active time (a number); omit it unless a hard limit is needed. A command call {command:[argv] or 'sh string', cwd?, timeoutMs? (wall-clock), env?, rerun?, writer?} runs a process instead of an agent: no model, slot or tokens; it keeps running across orchestrator restarts and a quit pi, and wakes you like any call; result ok on exit 0 else failed, data {exitCode, signal, durationMs}, output = last 16 KiB of stdout+stderr; only stop controls it. Run-level env/rerun apply to command steps, agent-only defaults skip them; in a chain an agent step after a command step gets its output as {previous}. Explicit unknown agents are rejected BEFORE creation, with available names; unknown script agents fail only their call.",
514
+ "run (action optional for exactly one launch form): agent+task; command (a command call); tasks:[call specs] parallel; chain:[call specs] sequential ({previous}); workflow:'./script.js' or source (runs.run(key,spec), runs.all([...]), emit(value), args, runs.input(name)). Optional name, cwd, usageBudget, maxCalls, inputs, labels. With tasks/chain, top-level agent (without task), model, timeoutMs, budget, limits, isolation, context, tools, skills, once, writer are defaults for every step (a step's own value wins); a workflow/source script sets them per runs.run call. timeoutMs is milliseconds of active time (a number); omit it unless a hard limit is needed. limits:{memoryMb?, maxProcesses?, cpuPercent?, graceMs?, strict?} caps each call's process tree (merges over config.json limits; fences and seals failed without retrying on sustained breach, plus OS cgroup v2 / Windows Job Object hard limits when available). A command call {command:[argv] or 'sh string', cwd?, timeoutMs? (wall-clock), limits?, env?, rerun?, writer?} runs a process instead of an agent: no model, slot or tokens; it keeps running across orchestrator restarts and a quit pi, and wakes you like any call; result ok on exit 0 else failed, data {exitCode, signal, durationMs}, output = last 16 KiB of stdout+stderr; only stop controls it. Run-level env/rerun apply to command steps, agent-only defaults skip them; in a chain an agent step after a command step gets its output as {previous}. Explicit unknown agents are rejected BEFORE creation, with available names; unknown script agents fail only their call.",
515
515
  "agents: list names, descriptions, default models and source for this cwd; use these names for run.",
516
516
  "send to:'<wid>/<key>' (bare '<wid>' only for a single-call workflow): steer on a running call delivers at the next safe point (receipt in status/UI); a steer to a call waiting on its question interrupts the question and the subagent usually asks again — use answer to answer it; sealed → finished:<status> — use kind 'follow-up'. notify tells a call a decision without disturbing it; the reply's delivery says how: steered (running: it gets the note at its next safe point), held-until-answer (waiting on its question: never interrupts it, delivered after the answer) or noted (not running: nothing starts; the note is recorded and the call's next follow-up opens with every pending note; status shows notesPending). to may list several calls for steer, notify, follow-up and model: one request per call, each decided on its own, one result line per target (request:<id> sends <id>:1...<id>:n; a retry with the same list is safe). follow-up continues a sealed call as generation g+1 (reply generation) or queues after a running turn (reply delivery forwarded; if that turn ends without taking it, it opens g+1); follow-up model:'provider/id' or a pool name runs that generation on it. answer: give the qid (or just the call, or nothing when one question is open); to and rev are filled in. A question that needs the user's decision goes to the user; if you answer one yourself, tell the user what you chose. model ('provider/id' or a pool name — its first model not used up): a running call switches at its next provider request; an asking, hibernated or queued call launches on it when it runs again; the reply's model/effect (next-request|next-execution|next-generation) says which. status model = model actually used by the last request; switching = requested, not used yet; switchFailed = refused. A provider content refusal (ToS/usage policy) fails the call at once, not retried. Unknown targets list valid addresses. replaces:[rid] supersedes an earlier send.",
517
517
  "stop target:<wid|<wid>/<key>> is terminal stopped (usage and partial edits kept); a sealed call → already-sealed:<status>, a finished workflow → terminal:<status>. drain holds existing workflows reversibly (new runs unaffected); resume [wid] releases held workflows. restart (after an update) replaces the orchestrator with the installed version: refused with busy:<running executions> while any runs. Never force without the user's explicit approval: show the user the refusal's list first, then supply force:'<token>' and reason. Subagents cannot force; hibernated askers and queued calls do not block it. Never kill the orchestrator process. Commands that need the machine (benchmarks, timing) take a lease: tell the subagent to run them as `pi-durable-subagents hold machine [--shared] -- <command>` (FIFO; `hold <name> --slots N` admits N at a time; status lists lease holders and waiters). status: without wid, what runs (with its run labels, clipped), asks (with its answer address; hibernated:true holds no slot) or failed, writerWait: a call queued for its git worktree's writer lock (one call whose tools include edit/write runs per worktree; spec writer:false or isolation:'worktree' opts out), sharedWorktree names calls sharing observed edit/write roots (reminder), lease: a call holding or waiting for a resource lease, queued: why a queued call does not start (orchestrator starting while it recovers after a start, a used-up provider, a writer lock, full providers; absent when not known), finished workflows one line each, provider slots held/limit, the config in effect and providers whose usage window is used up (avoided until a probe finds them answering again), and the orchestrator version (with ', starting <age>' while it recovers; versionNote when it differs from the loaded one); wid: one workflow, outputs clipped; wid+tail:N: the last N lines of each call's result, wid+grep:'<regex>': only its matching lines (a JS regex run in-process: avoid nested quantifiers like (a+)+; first 2000 chars of a line, last 5000 lines; both: grep, then tail; at most 4000 chars per call); wid+key: one call's full result; full:true: everything. A run reply names calls already queued behind a writer lock (writerWait). A run's rid from {submitted:{rid}} works wherever a wid is expected. revise wid + workflow/source/args starts a revision.",
@@ -8,6 +8,7 @@ import { readJournalSnapshot } from "../kernel/journal.js";
8
8
  import { reduceLifecycle } from "../kernel/lifecycle.js";
9
9
  import { scanInbox } from "../kernel/mailbox.js";
10
10
  import { OsLock } from "../platform/lock.js";
11
+ import { describeKernelLimits, probeKernelLimits } from "../platform/limits.js";
11
12
  import { journalPath, orchInbox, orchLedger, orchLock } from "../paths.js";
12
13
  import { runningStats, snapshotFromEntries } from "../orchestrator/snapshot.js";
13
14
  import { emptyLedger, foldLedger } from "../orchestrator/ledger.js";
@@ -52,7 +53,7 @@ export async function doctor(home, env = process.env, now = Date.now()) {
52
53
  const ledger = readJournalSnapshot(orchLedger(home));
53
54
  const pruned = new Set(ledger.filter(e => e.type === "pruned").map(e => String(e.wid)));
54
55
  const report = { home, bytes: await diskUsage(home), workflows: {}, ledger: { entries: ledger.length, bytes: await diskUsage(orchLedger(home)) },
55
- largestJournals: [], parked: [], attention: [], fenceFailed: [], orphanStaging: [], tmpFiles: [], orchestrator: await lockHeld(home), service: "unavailable", findings: [], ...runningStats(home) };
56
+ largestJournals: [], parked: [], attention: [], fenceFailed: [], orphanStaging: [], tmpFiles: [], orchestrator: await lockHeld(home), service: "unavailable", resourceLimits: describeKernelLimits(probeKernelLimits({ env })), findings: [], ...runningStats(home) };
56
57
  const last = foldLedger(emptyLedger(), ledger), o = last.orchestrator;
57
58
  if (o && o.pi !== undefined)
58
59
  report.pi = o.pi;
@@ -164,6 +165,7 @@ export function renderDoctor(r) {
164
165
  `orchestrator: ${r.orchestrator === "running" ? "running (holds the lock)" : r.orchestrator}${r.lastExit ? `; ${exitLine(r.lastExit)}` : ""}${r.orchestratorStats ? `; ${statsLine(r.orchestratorStats)}` : ""}`,
165
166
  ...(r.pi !== undefined ? [`pi: ${r.pi ?? "not found (subagents launch \`pi\` from PATH; set DSA_PI_BIN)"}`] : []),
166
167
  `service: ${r.service}`,
168
+ `resource limits: ${r.resourceLimits}`,
167
169
  ...(r.findings.length ? [`${r.findings.length} actionable finding(s):`, ...r.findings.flatMap(f => [` ${f.kind}: ${f.detail}`, ` ${f.command}`])] : ["nothing actionable"]),
168
170
  ].join("\n");
169
171
  }
package/dist/cli/main.js CHANGED
@@ -14,7 +14,7 @@ import { doctor, renderDoctor, size } from "./doctor.js";
14
14
  import { smoke } from "./smoke.js";
15
15
  import { serviceFiles, manageService } from "./service.js";
16
16
  import { leaseLines, leaseState } from "../platform/lease.js";
17
- import { resolvePi } from "../platform/launch.js";
17
+ import { resolveNode, resolvePi } from "../platform/launch.js";
18
18
  import { currentOrchestrator, decidedBy, legacyRestart, cliInitiator, waitExit, waitSuccessor } from "./restart.js";
19
19
  import { restartInputError } from "../orchestrator/restart.js";
20
20
  import { packageVersion } from "../version.js";
@@ -331,7 +331,12 @@ export async function main(args = process.argv.slice(2), options = {}) {
331
331
  const pi = command === "install-service" ? resolvePi(env) : {};
332
332
  if (command === "install-service" && !pi.path)
333
333
  write(`note: ${pi.problem}; the service can start an orchestrator only once DSA_PI_BIN is set in it`);
334
- const files = serviceFiles(env.HOME ?? homedir(), home, entry, process.platform, process.execPath, pi.path);
334
+ const nodeRes = resolveNode(env, { piPath: pi.path });
335
+ if (command === "install-service" && !nodeRes.path) {
336
+ (options.write ?? (line => console.error(line)))(`cannot install starter service: ${nodeRes.problem}. Set DSA_NODE_BIN to the absolute path of Node.js 22.19+, or put node on PATH`);
337
+ return 1;
338
+ }
339
+ const files = serviceFiles(env.HOME ?? homedir(), home, entry, process.platform, nodeRes.path ?? process.execPath, pi.path);
335
340
  await manageService(files, command === "install-service", { dryRun, runner: options.serviceRunner, write });
336
341
  files.forEach(f => write(`${command}: ${f.path}`));
337
342
  return 0;
@@ -4,7 +4,7 @@ import { homedir } from "node:os";
4
4
  import { execFileSync } from "node:child_process";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { parseFrontmatter, parseFrontmatterList } from "./frontmatter.js";
7
- import { shimScript } from "../platform/launch.js";
7
+ import { resolveNode, shimScript } from "../platform/launch.js";
8
8
  import { comspec } from "../platform/windows.js";
9
9
  import { cacheDir, dsaHome } from "../paths.js";
10
10
  const stamp = (p) => { if (!p)
@@ -51,8 +51,9 @@ function npmCommand(npm, node, env, platform) {
51
51
  if (platform !== "win32")
52
52
  return { command: "npm", args: ["root", "-g"] };
53
53
  const { cli } = npmLayout(npm, platform);
54
- if (cli)
55
- return { command: node ?? process.execPath, args: [cli, "root", "-g"] };
54
+ const runtime = node ?? resolveNode(env, { platform, peOnly: true }).path;
55
+ if (cli && runtime)
56
+ return { command: runtime, args: [cli, "root", "-g"] };
56
57
  if (!/\.(?:cmd|bat)$/i.test(npm))
57
58
  return { command: npm, args: ["root", "-g"] };
58
59
  return { command: comspec(env), args: ["/d", "/s", "/c", `""${npm}" root -g"`], verbatim: true };
@@ -1,7 +1,7 @@
1
1
  import { schemaProblems } from "../agent/child/schema.js";
2
- const fields = new Set(["agent", "task", "model", "cwd", "timeoutMs", "output", "schema", "gate", "isolation", "context", "budget", "once", "tools", "skills", "key", "writer", "command", "env", "rerun"]);
2
+ const fields = new Set(["agent", "task", "model", "cwd", "timeoutMs", "output", "schema", "gate", "isolation", "context", "budget", "once", "tools", "skills", "key", "writer", "command", "env", "rerun", "limits"]);
3
3
  /** Fields a command call takes; every other known field belongs to agent calls. */
4
- export const COMMAND_FIELDS = ["command", "cwd", "timeoutMs", "env", "rerun", "writer", "key"];
4
+ export const COMMAND_FIELDS = ["command", "cwd", "timeoutMs", "env", "rerun", "writer", "key", "limits"];
5
5
  const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
6
6
  const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
7
7
  const positive = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
@@ -36,6 +36,21 @@ function budget(value) {
36
36
  errors.push(`budget.${k} must be a positive number${got(value[k])}`);
37
37
  return errors;
38
38
  }
39
+ function limits(value) {
40
+ if (!isObject(value))
41
+ return ["limits must be an object {memoryMb?, maxProcesses?, cpuPercent?, graceMs?, strict?}"];
42
+ const errors = unknown(value, ["memoryMb", "maxProcesses", "cpuPercent", "graceMs", "strict"], "limits.");
43
+ for (const k of ["memoryMb", "cpuPercent"])
44
+ if (value[k] !== undefined && !positive(value[k]))
45
+ errors.push(`limits.${k} must be a positive number${got(value[k])}`);
46
+ if (value.maxProcesses !== undefined && (!Number.isSafeInteger(value.maxProcesses) || Number(value.maxProcesses) < 1))
47
+ errors.push(`limits.maxProcesses must be a positive integer${got(value.maxProcesses)}`);
48
+ if (value.graceMs !== undefined && !(typeof value.graceMs === "number" && Number.isFinite(value.graceMs) && value.graceMs >= 0))
49
+ errors.push(`limits.graceMs must be a nonnegative number${got(value.graceMs)}`);
50
+ if (value.strict !== undefined && typeof value.strict !== "boolean")
51
+ errors.push(`limits.strict must be a boolean${got(value.strict)}`);
52
+ return errors;
53
+ }
39
54
  /** P34, P24, T2/T3/T4: Validate a call spec at submission; `key` is accepted only for tasks/chain steps. Empty = valid. */
40
55
  export function validateCallSpec(spec, options = {}) {
41
56
  if (!isObject(spec))
@@ -73,6 +88,8 @@ export function validateCallSpec(spec, options = {}) {
73
88
  errors.push(`context must be "fresh", "fork" or "exact"${got(s.context)}`);
74
89
  if (has("budget"))
75
90
  errors.push(...budget(s.budget));
91
+ if (has("limits"))
92
+ errors.push(...limits(s.limits));
76
93
  if (has("once") && typeof s.once !== "boolean")
77
94
  errors.push(`once must be a boolean${got(s.once)}`);
78
95
  if (has("writer") && typeof s.writer !== "boolean")
@@ -117,6 +134,8 @@ function commandProblems(s, options) {
117
134
  for (const k of ["rerun", "writer"])
118
135
  if (has(k) && typeof s[k] !== "boolean")
119
136
  errors.push(`${k} must be a boolean${got(s[k])}`);
137
+ if (has("limits"))
138
+ errors.push(...limits(s.limits));
120
139
  if (options.fanout && has("key") && !text(s.key))
121
140
  errors.push("key must be a non-empty string");
122
141
  return errors;
@@ -9,7 +9,7 @@ import { readFile } from "node:fs/promises";
9
9
  import { join } from "node:path";
10
10
  import { contentHash } from "../kernel/ids.js";
11
11
  /** The keys the orchestrator reads; config.json also holds pi-side settings (ui, onQuit) that it ignores. */
12
- const KEYS = ["defaultModel", "pools", "providers", "memory", "writerLock", "askRequireDecision", "exactCapture", "k"];
12
+ const KEYS = ["defaultModel", "pools", "providers", "memory", "limits", "writerLock", "askRequireDecision", "exactCapture", "k"];
13
13
  const K = ["lossBound", "checkpointMs", "stallMs", "progressMs", "switchTimeoutMs", "idleExitMs", "trackerMs", "hibernateMs", "spawnBudget", "probeMs", "eventRetentionMs", "waitCheckMs", "resumeSpillMs"];
14
14
  export const configPath = (home) => join(home, "config.json");
15
15
  /** The orchestrator's part of a parsed config.json. */
@@ -24,7 +24,7 @@ const count = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
24
24
  export function configProblem(raw) {
25
25
  if (!record(raw))
26
26
  return "config.json must be a JSON object";
27
- const { defaultModel, pools, providers, memory, writerLock, askRequireDecision, exactCapture, k } = raw;
27
+ const { defaultModel, pools, providers, memory, limits, writerLock, askRequireDecision, exactCapture, k } = raw;
28
28
  if (askRequireDecision !== undefined && typeof askRequireDecision !== "boolean")
29
29
  return 'askRequireDecision must be a boolean';
30
30
  if (exactCapture !== undefined && typeof exactCapture !== "boolean")
@@ -94,6 +94,24 @@ export function configProblem(raw) {
94
94
  if (memory[key] !== undefined && !count(memory[key]))
95
95
  return `memory.${key} must be a nonnegative number`;
96
96
  }
97
+ if (limits !== undefined) {
98
+ if (!record(limits))
99
+ return "limits must be { memoryMb?, maxProcesses?, cpuPercent?, graceMs?, strict? }";
100
+ for (const key of Object.keys(limits)) {
101
+ if (!["memoryMb", "maxProcesses", "cpuPercent", "graceMs", "strict"].includes(key))
102
+ return `limits.${key} is not a limits key (memoryMb, maxProcesses, cpuPercent, graceMs, strict)`;
103
+ }
104
+ for (const key of ["memoryMb", "cpuPercent"]) {
105
+ if (limits[key] !== undefined && !(count(limits[key]) && Number(limits[key]) > 0))
106
+ return `limits.${key} must be a positive number`;
107
+ }
108
+ if (limits.maxProcesses !== undefined && (!Number.isSafeInteger(limits.maxProcesses) || Number(limits.maxProcesses) < 1))
109
+ return "limits.maxProcesses must be a positive integer";
110
+ if (limits.graceMs !== undefined && !count(limits.graceMs))
111
+ return "limits.graceMs must be a nonnegative number";
112
+ if (limits.strict !== undefined && typeof limits.strict !== "boolean")
113
+ return "limits.strict must be a boolean";
114
+ }
97
115
  if (k !== undefined) {
98
116
  if (!record(k))
99
117
  return "k must map K-parameters to numbers";
@@ -23,6 +23,7 @@ export const COMMAND_INTENT = "command-intent";
23
23
  export const COMMAND_STARTED = "command-started";
24
24
  export const COMMAND_SPAWN_FAILED = "command-spawn-failed";
25
25
  export const COMMAND_TIMEOUT = "command-timeout";
26
+ export const COMMAND_RESOURCE_LIMIT = "command-resource-limit";
26
27
  export const COMMAND_WITHDRAWN = "command-withdrawn";
27
28
  /** The attempt id (and process tag DSA_EXEC) of attempt `n` of a command call. */
28
29
  export const commandId = (call, n) => `command:${call}#${n}`;
@@ -4,7 +4,7 @@
4
4
  // equals what the whole-array function it replaces computes over the same entries (see the tests).
5
5
  import { CT, askFields } from "../../types.js";
6
6
  import { askOf, cutAskResult, receiptId } from "./session.js";
7
- import { messageUsage } from "./usage.js";
7
+ import { entryUsage } from "./usage.js";
8
8
  export const answerKey = (qid, rev) => JSON.stringify([qid, rev]);
9
9
  /** D2: the questions an answer receipt superseded (`details.superseded`: the blocked or hibernated asker's question). */
10
10
  export function supersededBy(details) {
@@ -42,7 +42,7 @@ export class SessionFold {
42
42
  this.own = typeof e.data?.exec === "string" && e.data.exec.startsWith(`${this.call}#`);
43
43
  s.execAt.set(e.data?.exec, i);
44
44
  }
45
- const u = this.own && e.message && messageUsage(e.message);
45
+ const u = this.own && entryUsage(e);
46
46
  if (u)
47
47
  s.usage.push(u);
48
48
  const rid = receiptId(e);