@xzzpig/pi-subagents 0.16.0 → 0.18.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 +164 -1
- package/README.md +5 -3
- package/agents/claude-code-writer.md +1 -0
- package/agents/codex-exec-writer.md +1 -0
- package/agents/cursor-agent-writer.md +1 -0
- package/agents/reviewer.md +3 -2
- package/agents/worker.md +3 -2
- package/docs/agents.md +17 -10
- package/docs/configuration.md +21 -3
- package/docs/extension-api.md +70 -4
- package/docs/models.md +5 -3
- package/docs/observability.md +23 -13
- package/docs/standalone-background.md +4 -4
- package/docs/tool-reference.md +40 -19
- package/docs/watchdog.md +2 -0
- package/docs/workflows.md +57 -3
- package/inspector-runner.mjs +1 -1
- package/package.json +14 -8
- package/prompts/council.md +6 -3
- package/runner-peer-loader.mjs +4 -7
- package/runner-peer-preload.mjs +5 -7
- package/skills/pi-subagents/SKILL.md +1 -0
- package/skills/pi-subagents/references/constraints-and-recipes.md +5 -2
- package/skills/pi-subagents/references/execution-controls.md +6 -4
- package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
- package/skills/pi-subagents/references/multi-lane-orchestration.md +8 -0
- package/skills/pi-subagents/references/prompting-and-roles.md +16 -15
- package/src/agents/agent-eject.ts +3 -3
- package/src/agents/agent-management.ts +61 -52
- package/src/agents/agent-memory.ts +90 -3
- package/src/agents/agent-serializer.ts +4 -4
- package/src/agents/agents.ts +125 -51
- package/src/agents/global-npm-root.ts +58 -0
- package/src/agents/proactive-skills.ts +4 -1
- package/src/agents/runtime-agent-registry.ts +14 -11
- package/src/agents/skills.ts +42 -9
- package/src/api/delegation.ts +15 -0
- package/src/api/inspectors.ts +27 -0
- package/src/api/preflight.ts +60 -60
- package/src/extension/doctor.ts +9 -4
- package/src/extension/fanout-child.ts +8 -0
- package/src/extension/index.ts +101 -48
- package/src/extension/rpc.ts +10 -1
- package/src/extension/schemas.ts +12 -6
- package/src/extension/subagent-guide.ts +12 -4
- package/src/extension/tool-activation.ts +197 -0
- package/src/extension/tool-description.ts +1 -1
- package/src/inspectors/ghostty/plugin.ts +13 -1
- package/src/inspectors/plugins.ts +70 -3
- package/src/intercom/intercom-bridge.ts +2 -0
- package/src/intercom/native-supervisor-channel.ts +22 -15
- package/src/intercom/result-intercom.ts +4 -0
- package/src/runs/background/active-async-capacity.ts +3 -25
- package/src/runs/background/async-execution.ts +100 -140
- package/src/runs/background/async-job-tracker.ts +28 -34
- package/src/runs/background/async-resume.ts +16 -8
- package/src/runs/background/async-status.ts +2 -0
- package/src/runs/background/binary-bootstrap.ts +34 -6
- package/src/runs/background/fleet-view.ts +51 -7
- package/src/runs/background/notify.ts +93 -7
- package/src/runs/background/pid-namespace.ts +18 -0
- package/src/runs/background/process-terminal-candidate.ts +98 -0
- package/src/runs/background/process-terminal.ts +17 -96
- package/src/runs/background/result-watcher.ts +1 -1
- package/src/runs/background/retained-children.ts +3 -2
- package/src/runs/background/run-child-session.ts +16 -5
- package/src/runs/background/run-id-resolver.ts +10 -5
- package/src/runs/background/run-status.ts +10 -4
- package/src/runs/background/runner-aliases.ts +25 -15
- package/src/runs/background/runner-child-launch.ts +1 -2
- package/src/runs/background/runner-startup-failure.ts +56 -0
- package/src/runs/background/stale-run-reconciler.ts +19 -3
- package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
- package/src/runs/background/subagent-runner.ts +96 -287
- package/src/runs/background/wait-tool.ts +2 -0
- package/src/runs/background/workflow-terminal-proof.ts +68 -0
- package/src/runs/foreground/execution.ts +217 -250
- package/src/runs/foreground/prompt-audit.ts +3 -9
- package/src/runs/foreground/subagent-executor.ts +377 -119
- package/src/runs/shared/acceptance.ts +167 -68
- package/src/runs/shared/capability-ceiling.ts +4 -1
- package/src/runs/shared/child-hooks.ts +1 -16
- package/src/runs/shared/child-launch.ts +22 -14
- package/src/runs/shared/child-runtime-config.ts +3 -0
- package/src/runs/shared/child-session.ts +52 -2
- package/src/runs/shared/child-tool-plan.ts +23 -113
- package/src/runs/shared/dynamic-fanout.ts +1 -1
- package/src/runs/shared/external-cli-runner.ts +3 -1
- package/src/runs/shared/external-job-bridge.ts +54 -0
- package/src/runs/shared/git-environment.ts +29 -0
- package/src/runs/shared/mcp-config-sources.ts +3 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +1 -1
- package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
- package/src/runs/shared/model-resolution.ts +6 -1
- package/src/runs/shared/nested-events.ts +67 -55
- package/src/runs/shared/orca-progress-tabs.ts +3 -2
- package/src/runs/shared/parallel-utils.ts +2 -1
- package/src/runs/shared/pi-spawn.ts +92 -6
- package/src/runs/shared/single-output.ts +11 -2
- package/src/runs/shared/structured-output.ts +227 -7
- package/src/runs/shared/subagent-control.ts +2 -16
- package/src/runs/shared/subagent-prompt-runtime.ts +27 -5
- package/src/runs/shared/tool-availability.ts +2 -2
- package/src/runs/shared/tool-budget.ts +21 -0
- package/src/runs/shared/usage-reconciliation.ts +73 -0
- package/src/runs/shared/worktree.ts +35 -8
- package/src/shared/child-session-name.ts +4 -2
- package/src/shared/fork-context.ts +11 -4
- package/src/shared/launch-contract.ts +1 -1
- package/src/shared/pruned-fork.ts +69 -56
- package/src/shared/types.ts +52 -16
- package/src/slash/delegation-adapters.ts +25 -1
- package/src/slash/prompt-template-bridge.ts +16 -1
- package/src/slash/prompt-workflows.ts +12 -1
- package/src/slash/slash-commands.ts +7 -241
- package/src/slash/subagent-cost.ts +313 -0
- package/src/slash/subagents-admin.ts +28 -29
- package/src/tui/fleet-status.ts +24 -2
- package/src/tui/fleet.ts +7 -4
- package/src/tui/render.ts +53 -19
- package/src/watchdog/diff-tool.ts +24 -3
- package/src/watchdog/permission-arbiter.ts +13 -15
- package/src/watchdog/register-child.ts +10 -2
- package/src/watchdog/review.ts +14 -14
- package/src/watchdog/runtime.ts +2 -1
- package/src/watchdog/turn-delta.ts +11 -5
- package/src/workflows/scripted-workflow.ts +109 -23
- package/src/workflows/workflow-child-summary.ts +4 -2
- package/src/workflows/workflow-settlement.ts +4 -1
- package/src/runs/shared/completion-evidence.ts +0 -89
- package/src/runs/shared/completion-guard.ts +0 -255
- package/src/runs/shared/llm-intent-arbiter.ts +0 -321
- package/src/runs/shared/task-intent.ts +0 -244
|
@@ -225,16 +225,6 @@ export function formatControlNudge(event: ControlEvent): string {
|
|
|
225
225
|
|
|
226
226
|
export function formatControlNoticeMessage(event: ControlEvent, childIntercomTarget?: string): string {
|
|
227
227
|
const runTarget = event.runId;
|
|
228
|
-
if (event.reason === "completion_guard") {
|
|
229
|
-
return [
|
|
230
|
-
`Subagent failed: ${event.agent}`,
|
|
231
|
-
`Run: ${runTarget}${event.index !== undefined ? ` step ${event.index + 1}` : ""}`,
|
|
232
|
-
`Signal: ${event.message}`,
|
|
233
|
-
"Next: read the output artifact or session from the subagent result, then retry with a more explicit implementation prompt or handle the fix directly.",
|
|
234
|
-
childIntercomTarget ? `Run intercom target (may be inactive): ${childIntercomTarget}` : undefined,
|
|
235
|
-
].filter((line): line is string => Boolean(line)).join("\n");
|
|
236
|
-
}
|
|
237
|
-
|
|
238
228
|
const nudgeMessage = formatControlNudge(event);
|
|
239
229
|
const steerCommand = `subagent({ action: "steer", id: "${runTarget}", ${event.index !== undefined ? `index: ${event.index}, ` : ""}message: ${JSON.stringify(nudgeMessage)} })`;
|
|
240
230
|
const nestedResumeCommand = `subagent({ action: "resume", id: "${runTarget}", message: ${JSON.stringify(nudgeMessage)} })`;
|
|
@@ -275,17 +265,13 @@ export function formatControlNoticeMessage(event: ControlEvent, childIntercomTar
|
|
|
275
265
|
}
|
|
276
266
|
|
|
277
267
|
export function formatControlIntercomMessage(event: ControlEvent, childIntercomTarget?: string): string {
|
|
278
|
-
const statusLabel = event.
|
|
279
|
-
? "subagent failed"
|
|
280
|
-
: event.type === "active_long_running"
|
|
268
|
+
const statusLabel = event.type === "active_long_running"
|
|
281
269
|
? "subagent active but long-running"
|
|
282
270
|
: "subagent needs attention";
|
|
283
271
|
return [
|
|
284
272
|
statusLabel,
|
|
285
273
|
"",
|
|
286
|
-
event.
|
|
287
|
-
? `${event.agent} failed in run ${event.runId}.`
|
|
288
|
-
: event.type === "active_long_running"
|
|
274
|
+
event.type === "active_long_running"
|
|
289
275
|
? `${event.agent} is still active but long-running in run ${event.runId}.`
|
|
290
276
|
: `${event.agent} needs attention in run ${event.runId}.`,
|
|
291
277
|
"",
|
|
@@ -11,12 +11,14 @@ import { validateAcceptanceReport } from "./acceptance.ts";
|
|
|
11
11
|
import { formatChildToolDiagnostic } from "./tool-availability.ts";
|
|
12
12
|
import { shouldBlockToolForBudget, toolBudgetBlockedMessage, toolBudgetSoftNudge } from "./tool-budget.ts";
|
|
13
13
|
import type { ResolvedToolBudget, SubagentState } from "../../shared/types.ts";
|
|
14
|
+
import { INTERCOM_SESSION_IDENTITY_EVENT } from "../../shared/types.ts";
|
|
14
15
|
import { resolveCurrentSessionId } from "../../shared/session-identity.ts";
|
|
15
16
|
import { getAgentDir } from "../../shared/utils.ts";
|
|
16
17
|
import { registerChildWatchdog } from "../../watchdog/register-child.ts";
|
|
17
18
|
import type { ChildWatchdogConfig } from "../../watchdog/child-status.ts";
|
|
18
19
|
import { requestWatchdogPermission, type WatchdogPermissionRequest, type WatchdogPermissionResult } from "../../watchdog/permission-arbiter.ts";
|
|
19
20
|
import { SUBAGENT_WATCHDOG_WARNING_TYPE } from "../../watchdog/types.ts";
|
|
21
|
+
import { captureWatchdogDiffBaseline, createWatchdogDiffTool, WATCHDOG_DIFF_TOOL_NAME } from "../../watchdog/diff-tool.ts";
|
|
20
22
|
import { inheritedNestedRouteOf } from "./nested-events.ts";
|
|
21
23
|
import { registerWaitTool } from "../background/wait-tool.ts";
|
|
22
24
|
import { drainOutstandingWork } from "../background/auto-drain.ts";
|
|
@@ -403,6 +405,7 @@ function registerToolBudget(pi: ExtensionAPI, budget: ResolvedToolBudget | undef
|
|
|
403
405
|
}
|
|
404
406
|
|
|
405
407
|
function registerStructuredOutputTool(pi: ExtensionAPI, structured: NonNullable<ChildRuntimeConfig["structuredOutput"]>): void {
|
|
408
|
+
const terminalState = structured.terminalState ??= { captured: false };
|
|
406
409
|
const required = structured.acceptanceReport === "required";
|
|
407
410
|
const parameters = createStructuredOutputToolParameters(structured.schema, { acceptanceReport: structured.acceptanceReport });
|
|
408
411
|
const registerTool = pi.registerTool as unknown as (tool: {
|
|
@@ -432,6 +435,7 @@ function registerStructuredOutputTool(pi: ExtensionAPI, structured: NonNullable<
|
|
|
432
435
|
}
|
|
433
436
|
}
|
|
434
437
|
structured.capture(params.value, structured.acceptanceReport ? params.acceptanceReport : undefined);
|
|
438
|
+
terminalState.captured = true;
|
|
435
439
|
return {
|
|
436
440
|
content: [{ type: "text", text: "Structured output captured." }],
|
|
437
441
|
details: {},
|
|
@@ -451,7 +455,15 @@ export default function registerSubagentPromptRuntime(pi: ExtensionAPI, config?:
|
|
|
451
455
|
registerRuntimeExtensionAcknowledgements(pi, config.runtimeAcknowledgements);
|
|
452
456
|
registerPermissionGate(pi, config.permissions, config.childWatchdog);
|
|
453
457
|
registerToolBudget(pi, config.toolBudget);
|
|
454
|
-
|
|
458
|
+
if (config.structuredOutput && !config.structuredOutput.terminalState) config.structuredOutput.terminalState = { captured: false };
|
|
459
|
+
registerChildWatchdog(pi, config.childWatchdog, config.watchdogStatus, config.structuredOutput?.terminalState);
|
|
460
|
+
const requestedWatchdogDiff = config.requiredTools?.includes(WATCHDOG_DIFF_TOOL_NAME);
|
|
461
|
+
const reviewerLaunchBaseline = requestedWatchdogDiff && config.cwd
|
|
462
|
+
? captureWatchdogDiffBaseline(config.cwd)
|
|
463
|
+
: undefined;
|
|
464
|
+
if (requestedWatchdogDiff && typeof pi.registerTool === "function") {
|
|
465
|
+
pi.registerTool(createWatchdogDiffTool(reviewerLaunchBaseline, { workingTreeAtLaunch: true }));
|
|
466
|
+
}
|
|
455
467
|
const waitState = config.runtimeState ?? {
|
|
456
468
|
baseCwd: "",
|
|
457
469
|
currentSessionId: null,
|
|
@@ -516,13 +528,23 @@ export default function registerSubagentPromptRuntime(pi: ExtensionAPI, config?:
|
|
|
516
528
|
return { messages };
|
|
517
529
|
});
|
|
518
530
|
|
|
531
|
+
// pi-intercom asks at session start for this session's intercom ID. Claiming
|
|
532
|
+
// the route there frees the session name for the readable label. An older
|
|
533
|
+
// pi-intercom never asks and routes by name, so the route stays the name.
|
|
534
|
+
const routingName = config.intercomSessionName;
|
|
535
|
+
let intercomIdClaimed = false;
|
|
536
|
+
if (routingName) {
|
|
537
|
+
pi.events.on(INTERCOM_SESSION_IDENTITY_EVENT, (request: unknown) => {
|
|
538
|
+
if (!request || typeof request !== "object" || !("version" in request) || request.version !== 1 || !("claim" in request) || typeof request.claim !== "function") return;
|
|
539
|
+
request.claim(routingName);
|
|
540
|
+
intercomIdClaimed = true;
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
|
|
519
544
|
onRuntimeEvent("before_agent_start", async (event: unknown) => {
|
|
520
545
|
if (!event || typeof event !== "object" || !("systemPrompt" in event) || typeof event.systemPrompt !== "string") return undefined;
|
|
521
546
|
registerNativeSupervisorClientOnce();
|
|
522
|
-
|
|
523
|
-
// name (agent + task excerpt, computed by the parent at launch) only
|
|
524
|
-
// applies when the bridge is not addressing this child.
|
|
525
|
-
const childSessionName = config.intercomSessionName || config.sessionName;
|
|
547
|
+
const childSessionName = intercomIdClaimed ? config.sessionName || routingName : routingName || config.sessionName;
|
|
526
548
|
if (childSessionName && typeof pi.setSessionName === "function") {
|
|
527
549
|
pi.setSessionName(childSessionName);
|
|
528
550
|
}
|
|
@@ -21,7 +21,7 @@ export function formatChildToolDiagnostic(diagnostic: ChildToolDiagnostic, optio
|
|
|
21
21
|
...(diagnostic.missingMcpDirectTools?.length
|
|
22
22
|
? [`MCP direct tools missing from the child registry: ${diagnostic.missingMcpDirectTools.join(", ")}.`]
|
|
23
23
|
: []),
|
|
24
|
-
"
|
|
24
|
+
"MCP tools require background children (`async: true`) because only they load ambient extensions.",
|
|
25
25
|
"For extension tools a foreground child can load, add the provider path to `subagentOnlyExtensions` (child-only), `extensions`, or as a path-like entry in `tools`, while keeping each registered tool name in `tools`.",
|
|
26
26
|
].join("\n");
|
|
27
27
|
}
|
|
@@ -29,7 +29,7 @@ export function formatChildToolDiagnostic(diagnostic: ChildToolDiagnostic, optio
|
|
|
29
29
|
`${subject} requested unavailable child tools: ${diagnostic.missing.join(", ")}.`,
|
|
30
30
|
"The `tools` field is a strict allowlist; it does not load extension code.",
|
|
31
31
|
...(diagnostic.missingMcpDirectTools?.length
|
|
32
|
-
? [`Resolved MCP direct tools missing from the child registry: ${diagnostic.missingMcpDirectTools.join(", ")}.
|
|
32
|
+
? [`Resolved MCP direct tools missing from the child registry: ${diagnostic.missingMcpDirectTools.join(", ")}. Resolved names must match what the host or pi-mcp-adapter registers; check the MCP direct-tool registration before treating this as a tool-call failure.`]
|
|
33
33
|
: []),
|
|
34
34
|
"For extension tools, add the provider path to `subagentOnlyExtensions` (child-only), `extensions`, or as a path-like entry in `tools`, while keeping each registered tool name in `tools`.",
|
|
35
35
|
"For MCP tools, verify the MCP adapter configuration and selected tool names. For builtin tools, verify the name against the installed Pi version.",
|
|
@@ -64,3 +64,24 @@ export function toolBudgetSoftNudge(budget: ResolvedToolBudget, toolCount: numbe
|
|
|
64
64
|
export function toolBudgetBlockedMessage(budget: ResolvedToolBudget, toolName: string, toolCount: number): string {
|
|
65
65
|
return `Tool budget hard limit reached after ${toolCount} tool call${toolCount === 1 ? "" : "s"} (hard ${budget.hard}). The '${toolName}' tool is blocked so you can finalize from the context you already have.`;
|
|
66
66
|
}
|
|
67
|
+
|
|
68
|
+
const TOOL_BUDGET_BLOCKED_MESSAGE = /^Tool budget hard limit reached after (\d+) tool calls? \(hard (\d+)\)\. The '([^']+)' tool is blocked so you can finalize from the context you already have\.$/;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Recognizes a hard-block reason generated by toolBudgetBlockedMessage for this exact budget
|
|
72
|
+
* and tool. A tool result only counts as a budget block when the entire message matches the
|
|
73
|
+
* runtime format and the embedded hard limit and tool name belong to this run; incidental
|
|
74
|
+
* occurrences of the phrase inside ordinary tool output are rejected.
|
|
75
|
+
*/
|
|
76
|
+
export function isToolBudgetBlockedMessage(
|
|
77
|
+
budget: ResolvedToolBudget,
|
|
78
|
+
resultText: string,
|
|
79
|
+
blockedTool: string | undefined,
|
|
80
|
+
): boolean {
|
|
81
|
+
const tool = blockedTool?.trim();
|
|
82
|
+
if (!tool) return false;
|
|
83
|
+
const match = TOOL_BUDGET_BLOCKED_MESSAGE.exec(resultText.trim());
|
|
84
|
+
if (!match) return false;
|
|
85
|
+
const [, blockedToolCount, hard, namedTool] = match;
|
|
86
|
+
return Number(hard) === budget.hard && Number(blockedToolCount) > budget.hard && namedTool === tool;
|
|
87
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { Usage } from "../../shared/types.ts";
|
|
2
|
+
|
|
3
|
+
type UsageMessage = { role?: unknown; timestamp?: unknown; usage?: object };
|
|
4
|
+
|
|
5
|
+
const usageFields = ["input", "output", "cacheRead", "cacheWrite", "cost"] as const;
|
|
6
|
+
type UsageField = typeof usageFields[number];
|
|
7
|
+
|
|
8
|
+
const aliases: Record<Exclude<UsageField, "cost">, readonly string[]> = {
|
|
9
|
+
input: ["input", "inputTokens"],
|
|
10
|
+
output: ["output", "outputTokens"],
|
|
11
|
+
cacheRead: ["cacheRead", "cacheReadTokens"],
|
|
12
|
+
cacheWrite: ["cacheWrite", "cacheWriteTokens"],
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
function validNumber(value: unknown): number | undefined {
|
|
16
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function fieldValue(usage: object | undefined, field: UsageField): number | undefined {
|
|
20
|
+
if (!usage) return undefined;
|
|
21
|
+
const values = usage as Record<string, unknown>;
|
|
22
|
+
if (field === "cost") {
|
|
23
|
+
const direct = validNumber(values.cost);
|
|
24
|
+
if (direct !== undefined) return direct;
|
|
25
|
+
const cost = values.cost;
|
|
26
|
+
return cost && typeof cost === "object" && !Array.isArray(cost)
|
|
27
|
+
? validNumber((cost as { total?: unknown }).total)
|
|
28
|
+
: undefined;
|
|
29
|
+
}
|
|
30
|
+
for (const name of aliases[field]) {
|
|
31
|
+
const value = validNumber(values[name]);
|
|
32
|
+
if (value !== undefined) return value;
|
|
33
|
+
}
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function validTimestamp(message: UsageMessage): string | number | undefined {
|
|
38
|
+
const value = message.timestamp;
|
|
39
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
40
|
+
if (typeof value === "string" && value.length > 0) return value;
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function reconcileAttemptUsage(live: Usage, messages: readonly UsageMessage[], baseline: number): Usage {
|
|
45
|
+
if (!Number.isInteger(baseline) || baseline < 0 || messages.length < baseline) return { ...live };
|
|
46
|
+
|
|
47
|
+
const persisted: Usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
|
|
48
|
+
const complete: Record<UsageField, boolean> = { input: true, output: true, cacheRead: true, cacheWrite: true, cost: true };
|
|
49
|
+
let previous: UsageMessage | undefined;
|
|
50
|
+
for (let index = baseline; index < messages.length; index++) {
|
|
51
|
+
const message = messages[index]!;
|
|
52
|
+
if (message.role === "assistant") {
|
|
53
|
+
const timestamp = validTimestamp(message);
|
|
54
|
+
const duplicate = previous?.role === "assistant" && timestamp !== undefined && validTimestamp(previous) === timestamp;
|
|
55
|
+
if (!duplicate) {
|
|
56
|
+
persisted.turns++;
|
|
57
|
+
for (const field of usageFields) {
|
|
58
|
+
const value = fieldValue(message.usage, field);
|
|
59
|
+
if (value === undefined) complete[field] = false;
|
|
60
|
+
else persisted[field] += value;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
previous = message;
|
|
65
|
+
}
|
|
66
|
+
if (persisted.turns === 0) return { ...live };
|
|
67
|
+
|
|
68
|
+
const reconciled = { ...live, turns: persisted.turns };
|
|
69
|
+
for (const field of usageFields) {
|
|
70
|
+
if (complete[field] && Number.isFinite(persisted[field])) reconciled[field] = persisted[field];
|
|
71
|
+
}
|
|
72
|
+
return reconciled;
|
|
73
|
+
}
|
|
@@ -439,9 +439,14 @@ function shortWorktreeHash(value: string): string {
|
|
|
439
439
|
}
|
|
440
440
|
|
|
441
441
|
function truncateUtf8(value: string, maxBytes: number): string {
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
442
|
+
const bytes = Buffer.from(value, "utf-8");
|
|
443
|
+
if (bytes.length <= maxBytes) return value;
|
|
444
|
+
// Back off to a code-point boundary before decoding: cutting mid-sequence
|
|
445
|
+
// emits U+FFFD (3 bytes per dangling byte), which can push the re-encoded
|
|
446
|
+
// result beyond maxBytes (e.g. a 256-byte cap yields a 258-byte string).
|
|
447
|
+
let end = maxBytes;
|
|
448
|
+
while (end > 0 && (bytes[end]! & 0xc0) === 0x80) end -= 1;
|
|
449
|
+
return bytes.subarray(0, end).toString("utf-8");
|
|
445
450
|
}
|
|
446
451
|
|
|
447
452
|
/** Convert an arbitrary label to a single safe filesystem/branch component. */
|
|
@@ -743,13 +748,35 @@ export function resolveExpectedWorktreeAgentCwd(cwd: string, runId: string, inde
|
|
|
743
748
|
function linkNodeModulesIfPresent(toplevel: string, worktreePath: string): boolean {
|
|
744
749
|
const nodeModulesPath = path.join(toplevel, "node_modules");
|
|
745
750
|
const nodeModulesLinkPath = path.join(worktreePath, "node_modules");
|
|
746
|
-
|
|
751
|
+
const hasDirectoryEntry = (candidate: string): boolean => {
|
|
752
|
+
try { fs.lstatSync(candidate); return true; }
|
|
753
|
+
catch (error) {
|
|
754
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;
|
|
755
|
+
throw error;
|
|
756
|
+
}
|
|
757
|
+
};
|
|
747
758
|
try {
|
|
748
|
-
|
|
759
|
+
if (hasDirectoryEntry(nodeModulesLinkPath)) return false;
|
|
760
|
+
let sourceRealPath: string;
|
|
761
|
+
try {
|
|
762
|
+
if (!fs.statSync(nodeModulesPath).isDirectory()) throw new Error("source node_modules is not a directory");
|
|
763
|
+
sourceRealPath = fs.realpathSync.native(nodeModulesPath);
|
|
764
|
+
} catch (error) {
|
|
765
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;
|
|
766
|
+
throw error;
|
|
767
|
+
}
|
|
768
|
+
fs.symlinkSync(nodeModulesPath, nodeModulesLinkPath, process.platform === "win32" ? "junction" : "dir");
|
|
769
|
+
if (!fs.lstatSync(nodeModulesLinkPath).isSymbolicLink()
|
|
770
|
+
|| fs.realpathSync.native(nodeModulesLinkPath) !== sourceRealPath) {
|
|
771
|
+
throw new Error("created link does not resolve to the source node_modules");
|
|
772
|
+
}
|
|
749
773
|
return true;
|
|
750
|
-
} catch {
|
|
751
|
-
|
|
752
|
-
|
|
774
|
+
} catch (error) {
|
|
775
|
+
const code = error instanceof Error && "code" in error && typeof error.code === "string" ? `${error.code}: ` : "";
|
|
776
|
+
throw new Error(
|
|
777
|
+
`failed to link node_modules from ${nodeModulesPath} to ${nodeModulesLinkPath}: ${code}${error instanceof Error ? error.message : String(error)}`,
|
|
778
|
+
{ cause: error },
|
|
779
|
+
);
|
|
753
780
|
}
|
|
754
781
|
}
|
|
755
782
|
|
|
@@ -13,8 +13,10 @@ import { PROMPT_REDACTED } from "./utils.ts";
|
|
|
13
13
|
* rendering the parent stream can label each child row.
|
|
14
14
|
*
|
|
15
15
|
* The name is display-only metadata. When the intercom bridge is active the
|
|
16
|
-
* child
|
|
17
|
-
* name
|
|
16
|
+
* child claims its machine intercom target as its pi-intercom session ID and
|
|
17
|
+
* keeps this readable name. With a pi-intercom that does not support the claim,
|
|
18
|
+
* the target stays the session name because it routes by name
|
|
19
|
+
* (see subagent-prompt-runtime).
|
|
18
20
|
*/
|
|
19
21
|
|
|
20
22
|
/** Longest task excerpt kept in the name; the full string is capped below. */
|
|
@@ -16,6 +16,8 @@ interface BranchSessionEntry {
|
|
|
16
16
|
cwd?: string;
|
|
17
17
|
parentId?: string | null;
|
|
18
18
|
timestamp?: string;
|
|
19
|
+
targetId?: string;
|
|
20
|
+
replacement?: { content?: unknown } | null;
|
|
19
21
|
message?: {
|
|
20
22
|
role?: string;
|
|
21
23
|
content?: unknown;
|
|
@@ -110,11 +112,16 @@ function isUnsafeAnthropicThinkingBlock(message: BranchSessionEntry["message"],
|
|
|
110
112
|
|
|
111
113
|
function sanitizeUnsafeThinkingBlocks(entries: BranchSessionEntry[]): boolean {
|
|
112
114
|
let sanitized = false;
|
|
115
|
+
const entriesById = new Map(entries.flatMap((entry) => entry.id ? [[entry.id, entry] as const] : []));
|
|
113
116
|
for (const entry of entries) {
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
entry.
|
|
117
|
+
const targetMessage = entry.type === "context_edit" && entry.targetId
|
|
118
|
+
? entriesById.get(entry.targetId)?.message
|
|
119
|
+
: entry.message;
|
|
120
|
+
const contentOwner = entry.type === "context_edit" ? entry.replacement : targetMessage;
|
|
121
|
+
if (targetMessage?.role !== "assistant" || !contentOwner || !Array.isArray(contentOwner.content)) continue;
|
|
122
|
+
const filtered = contentOwner.content.filter((block) => !isUnsafeAnthropicThinkingBlock(targetMessage, block));
|
|
123
|
+
if (filtered.length === contentOwner.content.length) continue;
|
|
124
|
+
contentOwner.content = filtered;
|
|
118
125
|
sanitized = true;
|
|
119
126
|
}
|
|
120
127
|
return sanitized;
|
|
@@ -55,6 +55,7 @@ export function projectAgentDefinition(agent: AgentConfig): Record<string, unkno
|
|
|
55
55
|
tools: agent.tools,
|
|
56
56
|
excludeTools: agent.excludeTools,
|
|
57
57
|
allowNestedSubagents: agent.allowNestedSubagents,
|
|
58
|
+
allowedAgents: agent.allowedAgents,
|
|
58
59
|
mcpDirectTools: agent.mcpDirectTools,
|
|
59
60
|
extensions: agent.extensions,
|
|
60
61
|
subagentOnlyExtensions: agent.subagentOnlyExtensions,
|
|
@@ -72,7 +73,6 @@ export function projectAgentDefinition(agent: AgentConfig): Record<string, unkno
|
|
|
72
73
|
acceptanceRole: agent.acceptanceRole,
|
|
73
74
|
interactive: agent.interactive,
|
|
74
75
|
maxSubagentDepth: agent.maxSubagentDepth,
|
|
75
|
-
completionGuard: agent.completionGuard,
|
|
76
76
|
toolBudget: agent.toolBudget,
|
|
77
77
|
sandbox: agent.sandbox,
|
|
78
78
|
permissionProfile: agent.permissionProfile,
|
|
@@ -3,7 +3,6 @@ import { createHash } from "node:crypto";
|
|
|
3
3
|
import * as fs from "node:fs";
|
|
4
4
|
import * as path from "node:path";
|
|
5
5
|
import type { TextContent } from "@earendil-works/pi-ai";
|
|
6
|
-
import { completeSimple } from "@earendil-works/pi-ai/compat";
|
|
7
6
|
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
8
7
|
import { resolveModelCandidate } from "../runs/shared/model-resolution.ts";
|
|
9
8
|
import { splitKnownThinkingSuffix, toModelInfo } from "./model-info.ts";
|
|
@@ -30,6 +29,8 @@ type SessionEntry = Record<string, unknown> & {
|
|
|
30
29
|
id?: string;
|
|
31
30
|
parentId?: string | null;
|
|
32
31
|
timestamp?: string;
|
|
32
|
+
targetId?: string;
|
|
33
|
+
replacement?: { content?: unknown } | null;
|
|
33
34
|
message?: Record<string, unknown>;
|
|
34
35
|
};
|
|
35
36
|
|
|
@@ -115,27 +116,36 @@ function stringsInValue(value: unknown): string[] {
|
|
|
115
116
|
return [];
|
|
116
117
|
}
|
|
117
118
|
|
|
119
|
+
function pushContentStrings(strings: string[], role: unknown, content: unknown): void {
|
|
120
|
+
if (role === "toolResult") strings.push(...textBlocks(content).map(({ block }) => block.text as string));
|
|
121
|
+
if (role === "assistant" && Array.isArray(content)) {
|
|
122
|
+
for (const blockValue of content) {
|
|
123
|
+
if (!blockValue || typeof blockValue !== "object" || Array.isArray(blockValue)) continue;
|
|
124
|
+
const block = blockValue as Record<string, unknown>;
|
|
125
|
+
if (block.type === "text" && typeof block.text === "string") strings.push(block.text);
|
|
126
|
+
else if (block.type === "thinking" && typeof block.thinking === "string") strings.push(block.thinking);
|
|
127
|
+
else if (block.type === "toolCall") strings.push(stableJson(block.arguments ?? {}), ...stringsInValue(block.arguments));
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (role === "user") {
|
|
131
|
+
if (typeof content === "string") strings.push(content);
|
|
132
|
+
else strings.push(...textBlocks(content).map(({ block }) => block.text as string));
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
118
136
|
function modelFacingStrings(entries: SessionEntry[]): string[] {
|
|
119
137
|
const strings: string[] = [];
|
|
138
|
+
const entriesById = new Map(entries.flatMap((entry) => entry.id ? [[entry.id, entry] as const] : []));
|
|
120
139
|
for (const entry of entries) {
|
|
121
140
|
const message = entry.type === "message" && entry.message && typeof entry.message === "object" ? entry.message : undefined;
|
|
122
|
-
if (message
|
|
123
|
-
if (
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
if (block.type === "text" && typeof block.text === "string") strings.push(block.text);
|
|
128
|
-
else if (block.type === "thinking" && typeof block.thinking === "string") strings.push(block.thinking);
|
|
129
|
-
else if (block.type === "toolCall") strings.push(stableJson(block.arguments ?? {}), ...stringsInValue(block.arguments));
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
if (message?.role === "user") {
|
|
133
|
-
if (typeof message.content === "string") strings.push(message.content);
|
|
134
|
-
else strings.push(...textBlocks(message.content).map(({ block }) => block.text as string));
|
|
141
|
+
if (message) pushContentStrings(strings, message.role, message.content);
|
|
142
|
+
if (entry.type === "context_edit" && entry.replacement && entry.targetId) {
|
|
143
|
+
const target = entriesById.get(entry.targetId);
|
|
144
|
+
const role = target?.type === "custom_message" ? "user" : target?.message?.role;
|
|
145
|
+
pushContentStrings(strings, role, entry.replacement.content);
|
|
135
146
|
}
|
|
136
147
|
if (entry.type === "custom_message") {
|
|
137
|
-
|
|
138
|
-
else strings.push(...textBlocks(entry.content).map(({ block }) => block.text as string));
|
|
148
|
+
pushContentStrings(strings, "user", entry.content);
|
|
139
149
|
}
|
|
140
150
|
if ((entry.type === "compaction" || entry.type === "branch_summary") && typeof entry.summary === "string") strings.push(entry.summary);
|
|
141
151
|
}
|
|
@@ -186,23 +196,25 @@ function collectOverflowItems(entries: SessionEntry[]): OverflowItem[] {
|
|
|
186
196
|
apply,
|
|
187
197
|
});
|
|
188
198
|
};
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
199
|
+
const collectContent = (
|
|
200
|
+
entry: SessionEntry,
|
|
201
|
+
source: Record<string, unknown>,
|
|
202
|
+
owner: Record<string, unknown>,
|
|
203
|
+
userLabel = "User:",
|
|
204
|
+
): boolean => {
|
|
205
|
+
if (source.role === "toolResult") {
|
|
206
|
+
const toolCallId = typeof source.toolCallId === "string" ? source.toolCallId : undefined;
|
|
207
|
+
const toolName = typeof source.toolName === "string" ? source.toolName : undefined;
|
|
208
|
+
for (const { block } of textBlocks(owner.content)) {
|
|
197
209
|
const body = block.text as string;
|
|
198
|
-
add(entry, "tool-result", `Tool result: ${toolName ?? "unknown"}${toolCallId ? ` ${toolCallId}` : ""}${
|
|
210
|
+
add(entry, "tool-result", `Tool result: ${toolName ?? "unknown"}${toolCallId ? ` ${toolCallId}` : ""}${source.isError === true ? " (error)" : ""}`, body, (summary, ref) => {
|
|
199
211
|
block.text = `${summary}\nRecovery ref: ${ref}`;
|
|
200
|
-
}, { toolCallId, toolName, isError:
|
|
212
|
+
}, { toolCallId, toolName, isError: source.isError === true });
|
|
201
213
|
}
|
|
202
|
-
|
|
214
|
+
return true;
|
|
203
215
|
}
|
|
204
|
-
if (role === "assistant" &&
|
|
205
|
-
for (const blockValue of
|
|
216
|
+
if (source.role === "assistant" && Array.isArray(owner.content)) {
|
|
217
|
+
for (const blockValue of owner.content) {
|
|
206
218
|
if (!blockValue || typeof blockValue !== "object" || Array.isArray(blockValue)) continue;
|
|
207
219
|
const block = blockValue as Record<string, unknown>;
|
|
208
220
|
if (block.type === "text" && typeof block.text === "string") {
|
|
@@ -218,30 +230,36 @@ function collectOverflowItems(entries: SessionEntry[]): OverflowItem[] {
|
|
|
218
230
|
}, { toolCallId: block.id, toolName: block.name });
|
|
219
231
|
}
|
|
220
232
|
}
|
|
221
|
-
|
|
233
|
+
return true;
|
|
222
234
|
}
|
|
223
|
-
if (role
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
235
|
+
if (source.role !== "user") return false;
|
|
236
|
+
if (typeof owner.content === "string") {
|
|
237
|
+
const body = owner.content;
|
|
238
|
+
add(entry, "user-text", userLabel, body, (summary, ref) => { owner.content = `${summary}\nRecovery ref: ${ref}`; });
|
|
239
|
+
} else {
|
|
240
|
+
for (const { block } of textBlocks(owner.content)) {
|
|
241
|
+
const body = block.text as string;
|
|
242
|
+
add(entry, "user-text", userLabel, body, (summary, ref) => { block.text = `${summary}\nRecovery ref: ${ref}`; });
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return true;
|
|
246
|
+
};
|
|
247
|
+
const entriesById = new Map(entries.flatMap((entry) => entry.id ? [[entry.id, entry] as const] : []));
|
|
248
|
+
|
|
249
|
+
for (const entry of entries) {
|
|
250
|
+
const message = entry.type === "message" && entry.message && typeof entry.message === "object" ? entry.message : undefined;
|
|
251
|
+
if (message && collectContent(entry, message, message)) continue;
|
|
252
|
+
if (entry.type === "context_edit" && entry.replacement && entry.targetId) {
|
|
253
|
+
const target = entriesById.get(entry.targetId);
|
|
254
|
+
if (target?.type === "custom_message") {
|
|
255
|
+
collectContent(entry, { role: "user" }, entry.replacement, `Extension message: ${String(target.customType ?? "unknown")}`);
|
|
256
|
+
} else if (target?.message) {
|
|
257
|
+
collectContent(entry, target.message, entry.replacement);
|
|
232
258
|
}
|
|
233
259
|
continue;
|
|
234
260
|
}
|
|
235
261
|
if (entry.type === "custom_message") {
|
|
236
|
-
|
|
237
|
-
const body = entry.content;
|
|
238
|
-
add(entry, "user-text", `Extension message: ${String(entry.customType ?? "unknown")}`, body, (summary, ref) => { entry.content = `${summary}\nRecovery ref: ${ref}`; });
|
|
239
|
-
} else {
|
|
240
|
-
for (const { block } of textBlocks(entry.content)) {
|
|
241
|
-
const body = block.text as string;
|
|
242
|
-
add(entry, "user-text", `Extension message: ${String(entry.customType ?? "unknown")}`, body, (summary, ref) => { block.text = `${summary}\nRecovery ref: ${ref}`; });
|
|
243
|
-
}
|
|
244
|
-
}
|
|
262
|
+
collectContent(entry, { role: "user" }, entry, `Extension message: ${String(entry.customType ?? "unknown")}`);
|
|
245
263
|
continue;
|
|
246
264
|
}
|
|
247
265
|
if ((entry.type === "compaction" || entry.type === "branch_summary") && typeof entry.summary === "string") {
|
|
@@ -403,7 +421,7 @@ function splitProviderModel(value: string): { provider: string; id: string } | u
|
|
|
403
421
|
}
|
|
404
422
|
|
|
405
423
|
export async function createPrunedForkSessionWriter(
|
|
406
|
-
ctx: ExtensionContext,
|
|
424
|
+
ctx: Pick<ExtensionContext, "modelRegistry" | "model">,
|
|
407
425
|
config: ForkContextConfig | undefined,
|
|
408
426
|
signal?: AbortSignal,
|
|
409
427
|
): Promise<(sessionFile: string) => Promise<void>> {
|
|
@@ -417,22 +435,17 @@ export async function createPrunedForkSessionWriter(
|
|
|
417
435
|
if (!named) throw new Error(`Pruned fork model '${config.model}' must resolve to provider/model.`);
|
|
418
436
|
const model = ctx.modelRegistry.find(named.provider, named.id);
|
|
419
437
|
if (!model) throw new Error(`Pruned fork model '${config.model}' was not found as '${baseModel}'.`);
|
|
420
|
-
const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
|
|
421
|
-
if (auth.ok === false) throw new Error(`Pruned fork model auth failed for ${baseModel}: ${auth.error}`);
|
|
422
438
|
|
|
423
439
|
let sharedSummary: Promise<string> | undefined;
|
|
424
440
|
const summarize: SummaryFunction = async (payload) => {
|
|
425
441
|
sharedSummary ??= (async () => {
|
|
426
|
-
const response = await
|
|
442
|
+
const response = await ctx.modelRegistry.streamSimple(model, {
|
|
427
443
|
systemPrompt: SYSTEM_PROMPT,
|
|
428
444
|
messages: [{ role: "user", content: [{ type: "text", text: payload }], timestamp: Date.now() }],
|
|
429
445
|
}, {
|
|
430
|
-
apiKey: auth.apiKey,
|
|
431
|
-
headers: auth.headers,
|
|
432
|
-
env: auth.env,
|
|
433
446
|
maxTokens: Math.min(MAX_SUMMARY_TOKENS, typeof model.maxTokens === "number" && model.maxTokens > 0 ? model.maxTokens : MAX_SUMMARY_TOKENS),
|
|
434
447
|
signal,
|
|
435
|
-
});
|
|
448
|
+
}).result();
|
|
436
449
|
if (response.stopReason === "error" || response.stopReason === "aborted") {
|
|
437
450
|
throw new Error(`Pruned fork summarization stopped with ${response.stopReason}${response.errorMessage ? `: ${response.errorMessage}` : ""}`);
|
|
438
451
|
}
|