pi-durable-subagents 1.6.0 → 1.6.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.
- package/CHANGELOG.md +7 -0
- package/dist/agent/capabilities.js +14 -7
- package/dist/agent/child/live.js +8 -1
- package/dist/agent/child.js +1 -1
- package/dist/agent/exact/capture.js +19 -0
- package/dist/agent/exact/child.js +8 -1
- package/dist/agent/exact/session.js +4 -2
- package/dist/agent/extension.js +13 -0
- package/dist/cli/main.js +7 -2
- package/dist/compat/agents.js +4 -3
- package/dist/orchestrator/executor/digest.js +2 -2
- package/dist/orchestrator/executor/observe.js +6 -1
- package/dist/orchestrator/executor/session.js +6 -1
- package/dist/orchestrator/executor/usage.js +19 -5
- package/dist/platform/launch.js +113 -14
- package/dist/types.js +1 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.6.1
|
|
4
|
+
|
|
5
|
+
- **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.
|
|
6
|
+
- **`pi` 1.5.1+ / 1.6.0 cache-warming compatibility**:
|
|
7
|
+
- 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`.
|
|
8
|
+
- 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).
|
|
9
|
+
|
|
3
10
|
## 1.6.0
|
|
4
11
|
|
|
5
12
|
- **Native Windows support** (Node.js 22.19+ and 24, no WSL or POSIX tools required; based on #4):
|
|
@@ -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
|
-
|
|
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
|
-
|
|
28
|
-
|
|
29
|
-
const
|
|
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)
|
package/dist/agent/child/live.js
CHANGED
|
@@ -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.
|
|
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))
|
package/dist/agent/child.js
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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)
|
package/dist/agent/extension.js
CHANGED
|
@@ -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) {
|
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
|
|
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;
|
package/dist/compat/agents.js
CHANGED
|
@@ -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
|
-
|
|
55
|
-
|
|
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 };
|
|
@@ -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 {
|
|
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 &&
|
|
45
|
+
const u = this.own && entryUsage(e);
|
|
46
46
|
if (u)
|
|
47
47
|
s.usage.push(u);
|
|
48
48
|
const rid = receiptId(e);
|
|
@@ -11,7 +11,7 @@ import { monotoneTime } from "../../kernel/guards.js";
|
|
|
11
11
|
import { readSession } from "./session.js";
|
|
12
12
|
import { entriesOf } from "./indexes.js";
|
|
13
13
|
import { ActiveTime, activeTotal } from "./time.js";
|
|
14
|
-
import { observation, reached, sessionUsage, totalUsage } from "./usage.js";
|
|
14
|
+
import { entryUsage, observation, reached, sessionUsage, totalUsage } from "./usage.js";
|
|
15
15
|
const UPDATE = '{"type":"tool_execution_update",';
|
|
16
16
|
export const sessionChanged = (name) => name === null || String(name) === "session.jsonl" || String(name) === "inbox";
|
|
17
17
|
/** A tool call's command for a status line: bash's command, else its arguments, on one line and clipped. */
|
|
@@ -162,6 +162,11 @@ export async function observeExecution(d) {
|
|
|
162
162
|
const args = event.args;
|
|
163
163
|
if (event.type === "tool_execution_start" && (event.toolName === "edit" || event.toolName === "write") && typeof args?.path === "string")
|
|
164
164
|
await d.wrote?.(args.path);
|
|
165
|
+
if (event.type === "entry_appended" && event.entry && typeof event.entry === "object") {
|
|
166
|
+
const u = entryUsage(event.entry);
|
|
167
|
+
if (u && event.entry.type === "usage")
|
|
168
|
+
await d.recordUsage([u]);
|
|
169
|
+
}
|
|
165
170
|
const slim = observation(event);
|
|
166
171
|
if (slim) {
|
|
167
172
|
await serial(() => t.journal.append("observation", { exec, event: slim }));
|
|
@@ -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
|
-
|
|
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 &&
|
|
34
|
+
const u = own && entryUsage(e);
|
|
21
35
|
return u ? [u] : [];
|
|
22
36
|
});
|
|
23
37
|
}
|
package/dist/platform/launch.js
CHANGED
|
@@ -7,9 +7,10 @@
|
|
|
7
7
|
// end it. Without lingering the user manager stops its scopes at logout, while a plain detached process survives it
|
|
8
8
|
// (KillUserProcesses=no, the usual default): it starts as a plain detached process then.
|
|
9
9
|
import { spawn } from "node:child_process";
|
|
10
|
-
import { accessSync, closeSync, constants, existsSync, mkdirSync, openSync, readFileSync, statSync } from "node:fs";
|
|
10
|
+
import { accessSync, closeSync, constants, existsSync, mkdirSync, openSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
11
11
|
import { userInfo } from "node:os";
|
|
12
12
|
import { delimiter, dirname, extname, isAbsolute, join, normalize, resolve, win32 } from "node:path";
|
|
13
|
+
import { ENV } from "../types.js";
|
|
13
14
|
import { comspec, envValue, IS_WINDOWS, winTagArg } from "./windows.js";
|
|
14
15
|
const WINDOWS_EXECUTABLE = new Set([".exe", ".com", ".cmd", ".bat"]);
|
|
15
16
|
/** Whether `path` is a regular file this process may execute. On Windows only a PE image or a batch file is directly
|
|
@@ -94,8 +95,11 @@ export function execTarget(command, args, options = {}) {
|
|
|
94
95
|
if (!/\.(cmd|bat)$/i.test(resolved))
|
|
95
96
|
return { command: resolved, args: [...args] };
|
|
96
97
|
const script = shimScript(resolved);
|
|
97
|
-
if (script)
|
|
98
|
-
|
|
98
|
+
if (script) {
|
|
99
|
+
const node = resolveNode(env, { platform, peOnly: true }).path;
|
|
100
|
+
if (node)
|
|
101
|
+
return { command: node, args: [script, ...args] };
|
|
102
|
+
}
|
|
99
103
|
// Outer quotes satisfy `cmd.exe /s /c`, which unconditionally strips the first and last `"` from the command string,
|
|
100
104
|
// leaving `"path" "arg1" ...` intact for cmd.exe and batch `%*` forwarding. Callers pass `windowsVerbatimArguments: true`.
|
|
101
105
|
const inner = [quoteCmdBatchArg(resolved), ...args.map(quoteCmdBatchArg)].join(" ");
|
|
@@ -134,19 +138,97 @@ export function shellTarget(command, exec, platform = process.platform) {
|
|
|
134
138
|
? { command: exec ? `(if 0==1 echo ${winTagArg("DSA_EXEC", exec)} ) & ${command}` : command, args: [], shell: true }
|
|
135
139
|
: { command: "/bin/sh", args: ["-c", command] };
|
|
136
140
|
}
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
const
|
|
141
|
+
const NODE_BASENAME = /^node(?:js)?(?:[-._]?v?\d[\d._-]*)?(?:\.exe)?$/i;
|
|
142
|
+
const NODE_SHIM_BASENAME = /^node(?:js)?(?:[-._]?v?\d[\d._-]*)?(?:\.(?:exe|com|cmd|bat))?$/i;
|
|
143
|
+
const SHIM_DISPATCHERS = new Set(["mise", "mise.exe", "volta", "volta.exe", "volta-shim", "volta-shim.exe", "asdf", "asdf.exe", "proto-shim", "proto-shim.exe", "rtx", "rtx.exe", "anyenv", "nodenv", "fnm", "fnm.exe"]);
|
|
144
|
+
const basenameOf = (filePath) => filePath.replace(/^.*[\\/]/, "");
|
|
145
|
+
const realPathOf = (filePath) => { try {
|
|
146
|
+
return (realpathSync.native ?? realpathSync)(filePath);
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
return filePath;
|
|
150
|
+
} };
|
|
151
|
+
const normFile = (filePath, platform) => platform === "win32" ? win32.normalize(filePath).toLowerCase() : filePath;
|
|
152
|
+
/** Whether this process itself is a standalone Node.js runtime (not a compiled Bun or SEA pi binary where
|
|
153
|
+
* process.execPath points to pi and running `execPath main.js` would open a recursive pi session, #11). */
|
|
154
|
+
export function isNodeProcess(options = {}) {
|
|
155
|
+
const versions = options.versions ?? process.versions;
|
|
156
|
+
if (versions.bun)
|
|
157
|
+
return false;
|
|
158
|
+
const releaseName = options.releaseName ?? process.release?.name;
|
|
159
|
+
if (releaseName !== "node")
|
|
160
|
+
return false;
|
|
161
|
+
const execPath = options.execPath ?? process.execPath;
|
|
162
|
+
return NODE_BASENAME.test(basenameOf(execPath));
|
|
163
|
+
}
|
|
164
|
+
/** Whether `nodePath` and `piPath` invoke the same program. Multi-call version-manager shims (mise, volta, asdf, ...)
|
|
165
|
+
* share one realpath dispatcher binary across `shims/node` and `shims/pi` and dispatch on argv[0]; allow distinct
|
|
166
|
+
* paths only when the shared target is a known shim dispatcher, so a symlink to a versioned `pi-real` binary is
|
|
167
|
+
* still refused. */
|
|
168
|
+
export function isSameProgram(nodePath, piPath, platform = process.platform) {
|
|
169
|
+
if (!piPath)
|
|
170
|
+
return false;
|
|
171
|
+
if (normFile(nodePath, platform) === normFile(piPath, platform))
|
|
172
|
+
return true;
|
|
173
|
+
const realNode = realPathOf(nodePath), realPi = realPathOf(piPath);
|
|
174
|
+
if (normFile(realNode, platform) !== normFile(realPi, platform))
|
|
175
|
+
return false;
|
|
176
|
+
const nodeName = basenameOf(nodePath), piName = basenameOf(piPath), targetName = basenameOf(realNode).toLowerCase();
|
|
177
|
+
if (NODE_SHIM_BASENAME.test(nodeName) && !NODE_SHIM_BASENAME.test(piName) && SHIM_DISPATCHERS.has(targetName))
|
|
178
|
+
return false;
|
|
179
|
+
return true;
|
|
180
|
+
}
|
|
181
|
+
/** Resolve a Node.js executable for launching the orchestrator and JS helpers (#11):
|
|
182
|
+
* 1. DSA_NODE_BIN when set (must be an absolute path to an executable file, and not pi itself);
|
|
183
|
+
* 2. process.execPath when this process is a real Node.js runtime (not a compiled Bun/standalone pi binary);
|
|
184
|
+
* 3. `node` (or `nodejs` on POSIX) on PATH, preferring PE binaries (.exe/.com) over .cmd/.bat shims on Windows. */
|
|
185
|
+
export function resolveNode(env, options = {}) {
|
|
186
|
+
const platform = options.platform ?? process.platform;
|
|
187
|
+
const isPe = (p) => /\.(?:exe|com)$/i.test(p);
|
|
188
|
+
const given = env.DSA_NODE_BIN;
|
|
189
|
+
if (given) {
|
|
190
|
+
if (!absolute(given, platform) || !executableFile(given, platform))
|
|
191
|
+
return { problem: `DSA_NODE_BIN=${given} is not an absolute path to an executable file` };
|
|
192
|
+
if (platform === "win32" && options.peOnly && !isPe(given))
|
|
193
|
+
return { problem: `DSA_NODE_BIN=${given} is not a Windows .exe/.com Node executable` };
|
|
194
|
+
if (isSameProgram(given, options.piPath, platform))
|
|
195
|
+
return { problem: `DSA_NODE_BIN=${given} resolves to the pi executable (${options.piPath})` };
|
|
196
|
+
return { path: given, source: "DSA_NODE_BIN" };
|
|
197
|
+
}
|
|
198
|
+
const execPath = options.execPath ?? process.execPath;
|
|
199
|
+
if (isNodeProcess({ execPath, versions: options.versions, releaseName: options.releaseName }) && !isSameProgram(execPath, options.piPath, platform)) {
|
|
200
|
+
return { path: execPath, source: "execPath" };
|
|
201
|
+
}
|
|
202
|
+
const PATH = platform === "win32" ? envValue(env, "PATH") : env.PATH;
|
|
203
|
+
const pathext = platform === "win32" ? envValue(env, "PATHEXT") : undefined;
|
|
204
|
+
const found = platform === "win32"
|
|
205
|
+
? findOnPath("node", PATH, { platform, pathext: ".EXE;.COM" }) ?? (options.peOnly ? undefined : findOnPath("node", PATH, { platform, pathext }))
|
|
206
|
+
: findOnPath("node", PATH, { platform }) ?? findOnPath("nodejs", PATH, { platform });
|
|
207
|
+
if (found) {
|
|
208
|
+
if (isSameProgram(found, options.piPath, platform))
|
|
209
|
+
return { problem: `node on PATH (${found}) resolves to the pi executable (${options.piPath})` };
|
|
210
|
+
return { path: found, source: "PATH" };
|
|
211
|
+
}
|
|
212
|
+
return { problem: `node was not found on PATH (${PATH || "unset"}) and DSA_NODE_BIN is not set` };
|
|
213
|
+
}
|
|
214
|
+
/** The starter cannot start an orchestrator without a Node.js runtime (#11). */
|
|
215
|
+
export class NodeNotFound extends Error {
|
|
216
|
+
constructor(problem) {
|
|
217
|
+
super(`cannot start the orchestrator: ${problem}. Set DSA_NODE_BIN to the absolute path of Node.js 22.19+, or put node on PATH`);
|
|
218
|
+
this.name = "NodeNotFound";
|
|
219
|
+
}
|
|
220
|
+
}
|
|
140
221
|
/** The `pi` the orchestrator launches subagents with: DSA_PI_BIN when set (it must be an executable file), else the
|
|
141
222
|
* first `pi` on PATH. `problem` says why there is none. */
|
|
142
|
-
export function resolvePi(env) {
|
|
223
|
+
export function resolvePi(env, platform = process.platform) {
|
|
143
224
|
const given = env.DSA_PI_BIN;
|
|
144
225
|
if (given) {
|
|
145
|
-
if (
|
|
226
|
+
if (absolute(given, platform) && executableFile(given, platform))
|
|
146
227
|
return { path: given, source: "DSA_PI_BIN" };
|
|
147
228
|
return { problem: `DSA_PI_BIN=${given} is not an absolute path to an executable file` };
|
|
148
229
|
}
|
|
149
|
-
const PATH =
|
|
230
|
+
const PATH = platform === "win32" ? envValue(env, "PATH") : env.PATH;
|
|
231
|
+
const found = findOnPath("pi", PATH, { platform, pathext: platform === "win32" ? envValue(env, "PATHEXT") : undefined });
|
|
150
232
|
return found ? { path: found, source: "PATH" } : { problem: `pi was not found on PATH (${PATH || "unset"}) and DSA_PI_BIN is not set` };
|
|
151
233
|
}
|
|
152
234
|
/** The starter cannot start an orchestrator that could launch no subagent. */
|
|
@@ -224,7 +306,7 @@ function orchestratorStdio(env) {
|
|
|
224
306
|
/** The variables the executor sets for one call's processes (a subagent, a command call, a gate). An orchestrator
|
|
225
307
|
* started from inside a call (its CLI, a command that runs `start`) never carries them: with the call's DSA_EXEC it
|
|
226
308
|
* would be one of that call's processes, and the call's fence (its end, a stop) would kill it. */
|
|
227
|
-
export const PER_CALL_ENV = ["DSA_SESSION", "DSA_EXEC", "DSA_CALL", "DSA_INBOX", "DSA_JOURNAL", "DSA_SCHEMA", "DSA_BUDGET", "DSA_MODEL", "DSA_RESULT", "DSA_OUTPUT", "DSA_PROBE"];
|
|
309
|
+
export const PER_CALL_ENV = ["DSA_SESSION", "DSA_EXEC", "DSA_CALL", "DSA_INBOX", "DSA_JOURNAL", "DSA_SCHEMA", "DSA_BUDGET", "DSA_MODEL", "DSA_RESULT", "DSA_OUTPUT", "DSA_PROBE", ENV.orchestratorLaunch];
|
|
228
310
|
/** `env` without PER_CALL_ENV. */
|
|
229
311
|
export function orchestratorEnv(env) {
|
|
230
312
|
const rest = { ...env };
|
|
@@ -236,11 +318,25 @@ export function orchestratorEnv(env) {
|
|
|
236
318
|
* session) and every other per-call variable (PER_CALL_ENV) plus DSA_HOME and the resolved DSA_PI_BIN. In its own systemd scope when one is available (the scope execs
|
|
237
319
|
* the command: same environment, and the pid is the orchestrator's), else a plain detached process. */
|
|
238
320
|
export async function launchOrchestrator(entry, env, options) {
|
|
239
|
-
const
|
|
321
|
+
const platform = options.platform ?? process.platform;
|
|
322
|
+
const pi = resolvePi(env, platform);
|
|
240
323
|
if (!pi.path && options.requirePi)
|
|
241
324
|
throw new PiNotFound(pi.problem);
|
|
242
|
-
const
|
|
243
|
-
|
|
325
|
+
const piPath = pi.path ?? (isNodeProcess() ? undefined : process.execPath);
|
|
326
|
+
let node;
|
|
327
|
+
if (options.node !== undefined) {
|
|
328
|
+
if (isSameProgram(options.node, piPath, platform))
|
|
329
|
+
throw new NodeNotFound(`orchestrator runtime ${options.node} resolves to the pi executable (${piPath})`);
|
|
330
|
+
node = options.node;
|
|
331
|
+
}
|
|
332
|
+
else {
|
|
333
|
+
const resolved = resolveNode(env, { platform, piPath });
|
|
334
|
+
if (!resolved.path)
|
|
335
|
+
throw new NodeNotFound(resolved.problem);
|
|
336
|
+
node = resolved.path;
|
|
337
|
+
}
|
|
338
|
+
const childEnv = { ...orchestratorEnv(env), DSA_HOME: options.home, [ENV.orchestratorLaunch]: "1", ...(pi.path ? { DSA_PI_BIN: pi.path } : {}) };
|
|
339
|
+
const run = options.spawn ?? spawn;
|
|
244
340
|
const runner = await scopeRunner(env, options);
|
|
245
341
|
const diagnostic = orchestratorStdio(childEnv);
|
|
246
342
|
// The child holds its own copies of the descriptors; ours are closed once it has started (a failed start closes them).
|
|
@@ -260,7 +356,10 @@ export async function launchOrchestrator(entry, env, options) {
|
|
|
260
356
|
}
|
|
261
357
|
catch { /* fall back to a plain detached process */ }
|
|
262
358
|
}
|
|
263
|
-
const
|
|
359
|
+
const target = platform === "win32" && /\.(?:cmd|bat)$/i.test(node)
|
|
360
|
+
? execTarget(node, [entry], { env: childEnv, platform })
|
|
361
|
+
: { command: node, args: [entry] };
|
|
362
|
+
const child = run(target.command, target.args, { detached: true, stdio: diagnostic.stdio, env: childEnv, ...(target.verbatim ? { windowsVerbatimArguments: true } : {}) });
|
|
264
363
|
await started(child);
|
|
265
364
|
child.unref();
|
|
266
365
|
return { pid: child.pid, scope: false, ...(pi.path ? { pi: pi.path } : {}) };
|
package/dist/types.js
CHANGED
|
@@ -88,4 +88,5 @@ export const ENV = {
|
|
|
88
88
|
exhaustedPatterns: "DSA_EXHAUSTED_PATTERNS", // JSON provider -> regex strings, snapshotted at execution start (XP1)
|
|
89
89
|
exactCapture: "DSA_EXACT_CAPTURE", // path of the pinned parent capture of an exact child (EX2)
|
|
90
90
|
exactTools: "DSA_EXACT_TOOLS", // JSON array of the tool names an exact child may run (EX3/EX4)
|
|
91
|
+
orchestratorLaunch: "DSA_ORCHESTRATOR_LAUNCH", // sentinel set by launchOrchestrator so a mislaunched pi refuses to recurse (#11)
|
|
91
92
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-durable-subagents",
|
|
3
|
-
"version": "1.6.
|
|
3
|
+
"version": "1.6.1",
|
|
4
4
|
"description": "Subagents for pi that never lose work and never do it twice. Crash-safe workflows, automatic recovery, and a live view just like the main agent.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|