@xzzpig/pi-subagents 0.24.2 → 0.25.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 +22 -0
- package/bundle/agent-management.js +4 -4
- package/bundle/agents.js +3 -3
- package/bundle/child-tool-plan.js +2 -2
- package/bundle/chunk-34TUUBRN.js +1107 -0
- package/bundle/{chunk-SW2VMNIU.js → chunk-5OD3OWTE.js} +2 -2
- package/bundle/{chunk-XWWUDWUW.js → chunk-5YEOWNSD.js} +371 -135
- package/bundle/{chunk-EUPJB4S7.js → chunk-5Z7JAORM.js} +196 -1219
- package/bundle/{chunk-LCDJWBVM.js → chunk-66JNFRFS.js} +1 -1
- package/bundle/{chunk-4UH4WS4G.js → chunk-6MNRKUHY.js} +23 -12
- package/bundle/{chunk-ED55MIC2.js → chunk-CGFF4WA3.js} +42 -19
- package/bundle/{chunk-TMHVDPYW.js → chunk-DLVPMML3.js} +263 -154
- package/bundle/chunk-HXRB42AF.js +108 -0
- package/bundle/{chunk-355ECEP2.js → chunk-IH7LQVEE.js} +29 -14
- package/bundle/{chunk-CYY5UMJU.js → chunk-IJWITCC6.js} +411 -249
- package/bundle/{chunk-RU522D5W.js → chunk-IKFKH5EL.js} +369 -50
- package/bundle/{chunk-Z6TFJ6BR.js → chunk-INWSUNI6.js} +1 -1
- package/bundle/{chunk-JEA2ZKUA.js → chunk-IUDEI6FJ.js} +35 -200
- package/bundle/{chunk-WW76JRIX.js → chunk-JAXVBXGF.js} +1 -1
- package/bundle/{chunk-ICNYIALB.js → chunk-JH5H4CYJ.js} +784 -474
- package/bundle/{chunk-35GII5EF.js → chunk-JWFLPSTP.js} +41 -117
- package/bundle/{chunk-224WMDIV.js → chunk-KCJFGKVK.js} +350 -123
- package/bundle/{chunk-RB4GELQA.js → chunk-LPJEKHOY.js} +1 -1
- package/bundle/chunk-LYKG4FKH.js +523 -0
- package/bundle/{chunk-X6LOM3Z4.js → chunk-LZ3HBDTR.js} +161 -78
- package/bundle/{chunk-FG6SQJAR.js → chunk-OGPOCGWX.js} +24 -6
- package/bundle/{chunk-BQ2OAB4Q.js → chunk-OSVXFWPG.js} +67 -30
- package/bundle/{chunk-FJWI64H7.js → chunk-RMSABUN3.js} +27 -13
- package/bundle/{chunk-H36HBZB2.js → chunk-SJPABBZG.js} +2 -2
- package/bundle/{chunk-3U633XDZ.js → chunk-U3ZDUUTM.js} +11 -3
- package/bundle/{chunk-LVWU2HOO.js → chunk-ULGMXABL.js} +16 -7
- package/bundle/{chunk-WPW4V6HM.js → chunk-W7ZA6TYD.js} +2 -2
- package/bundle/{chunk-V2KFIGFH.js → chunk-XAC2XNAP.js} +503 -304
- package/bundle/{chunk-O4D5PBVI.js → chunk-YWXILP5N.js} +3 -2
- package/bundle/control-channel.js +2 -2
- package/bundle/index.js +1 -1
- package/bundle/intercom-bridge.js +2 -2
- package/bundle/preflight.js +12 -10
- package/bundle/project-panes.js +3 -3
- package/bundle/workflow-resources.js +1 -1
- package/docs/agents.md +27 -6
- package/docs/configuration.md +20 -8
- package/docs/extension-api.md +18 -1
- package/docs/models.md +6 -2
- package/docs/observability.md +2 -0
- package/docs/tool-reference.md +7 -1
- package/docs/workflows.md +30 -2
- package/package.json +2 -2
- package/skills/pi-subagents/SKILL.md +15 -6
- package/skills/pi-subagents/references/prompting-and-roles.md +1 -0
- package/src/agents/agent-management.d.ts +1 -0
- package/src/agents/agent-management.js +46 -18
- package/src/agents/agent-memory.d.ts +1 -4
- package/src/agents/agent-memory.js +1 -4
- package/src/agents/agent-serializer.d.ts +2 -0
- package/src/agents/agent-serializer.js +1 -1
- package/src/agents/agents.d.ts +2 -3
- package/src/agents/agents.js +46 -20
- package/src/agents/frontmatter.js +1 -8
- package/src/agents/global-npm-root.d.ts +1 -0
- package/src/agents/global-npm-root.js +11 -3
- package/src/agents/skills.d.ts +0 -3
- package/src/agents/skills.js +0 -3
- package/src/api/preflight.d.ts +3 -1
- package/src/api/preflight.js +2 -0
- package/src/extension/config.d.ts +1 -0
- package/src/extension/config.js +13 -1
- package/src/extension/herdr-pi-bridge.js +10 -2
- package/src/extension/index.d.ts +0 -13
- package/src/extension/index.js +51 -37
- package/src/extension/public-execution.d.ts +1 -0
- package/src/extension/public-execution.js +4 -0
- package/src/extension/reply-workflow-script.js +24 -4
- package/src/extension/schemas.d.ts +12 -3
- package/src/extension/schemas.js +7 -3
- package/src/extension/session-switch.d.ts +25 -0
- package/src/extension/session-switch.js +138 -0
- package/src/extension/subagent-guide.d.ts +1 -1
- package/src/extension/subagent-guide.js +1 -1
- package/src/extension/subagent-launch-tool.d.ts +25 -0
- package/src/extension/subagent-launch-tool.js +48 -0
- package/src/extension/tool-activation.js +55 -15
- package/src/extension/tool-description.d.ts +1 -1
- package/src/extension/tool-description.js +14 -8
- package/src/inspectors/herdr/actions.d.ts +0 -1
- package/src/inspectors/herdr/actions.js +0 -1
- package/src/inspectors/session-roots-codec.d.ts +0 -1
- package/src/inspectors/session-roots-codec.js +0 -1
- package/src/inspectors/tmux/actions.d.ts +0 -1
- package/src/inspectors/tmux/actions.js +0 -1
- package/src/integrations/herdr-status.js +3 -8
- package/src/intercom/native-supervisor-channel.js +65 -9
- package/src/runs/background/async-execution.d.ts +7 -10
- package/src/runs/background/async-execution.js +66 -29
- package/src/runs/background/async-job-tracker.js +12 -0
- package/src/runs/background/async-resume.d.ts +2 -1
- package/src/runs/background/async-resume.js +114 -40
- package/src/runs/background/async-retention.d.ts +0 -2
- package/src/runs/background/async-retention.js +17 -6
- package/src/runs/background/async-status.d.ts +2 -0
- package/src/runs/background/async-status.js +4 -0
- package/src/runs/background/auto-drain.js +2 -1
- package/src/runs/background/boot-id.d.ts +1 -3
- package/src/runs/background/boot-id.js +1 -3
- package/src/runs/background/completion-batcher.d.ts +3 -4
- package/src/runs/background/completion-batcher.js +2 -3
- package/src/runs/background/control-channel.d.ts +0 -6
- package/src/runs/background/control-channel.js +0 -6
- package/src/runs/background/fleet-view.js +2 -3
- package/src/runs/background/notify.d.ts +0 -2
- package/src/runs/background/notify.js +0 -2
- package/src/runs/background/result-watcher.d.ts +1 -0
- package/src/runs/background/result-watcher.js +59 -29
- package/src/runs/background/resume-guidance.js +4 -2
- package/src/runs/background/retained-children.js +2 -1
- package/src/runs/background/run-child-session.d.ts +2 -3
- package/src/runs/background/run-child-session.js +5 -8
- package/src/runs/background/run-status.js +9 -7
- package/src/runs/background/runner-aliases.js +15 -0
- package/src/runs/background/scheduled-runs.d.ts +3 -1
- package/src/runs/background/scheduled-runs.js +13 -16
- package/src/runs/background/steering.d.ts +2 -11
- package/src/runs/background/steering.js +11 -6
- package/src/runs/background/subagent-runner.d.ts +2 -6
- package/src/runs/background/subagent-runner.js +88 -70
- package/src/runs/background/subagent-wait.js +12 -15
- package/src/runs/background/wait-config.d.ts +2 -0
- package/src/runs/background/wait-config.js +17 -3
- package/src/runs/background/wait-subscriptions.js +124 -12
- package/src/runs/background/wait-tool.js +4 -2
- package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
- package/src/runs/background/workflow-terminal-proof.js +0 -1
- package/src/runs/foreground/async-steering-action.js +24 -9
- package/src/runs/foreground/async-stop-action.d.ts +1 -1
- package/src/runs/foreground/async-stop-action.js +9 -1
- package/src/runs/foreground/execution.d.ts +0 -3
- package/src/runs/foreground/execution.js +56 -24
- package/src/runs/foreground/prompt-audit.js +1 -0
- package/src/runs/foreground/subagent-executor.d.ts +5 -10
- package/src/runs/foreground/subagent-executor.js +164 -49
- package/src/runs/shared/acceptance.js +69 -26
- package/src/runs/shared/async-status-projection.d.ts +2 -0
- package/src/runs/shared/async-status-projection.js +10 -0
- package/src/runs/shared/child-commands.js +15 -2
- package/src/runs/shared/child-hooks.d.ts +1 -7
- package/src/runs/shared/child-hooks.js +13 -5
- package/src/runs/shared/child-launch.js +6 -2
- package/src/runs/shared/child-runtime-config.d.ts +0 -1
- package/src/runs/shared/child-session.d.ts +6 -5
- package/src/runs/shared/child-session.js +85 -38
- package/src/runs/shared/child-tool-plan.d.ts +0 -1
- package/src/runs/shared/child-tool-plan.js +0 -1
- package/src/runs/shared/claude-code-adapter.js +11 -0
- package/src/runs/shared/external-cli-contract.d.ts +49 -0
- package/src/runs/shared/external-cli-contract.js +18 -13
- package/src/runs/shared/external-cli-runner.js +26 -6
- package/src/runs/shared/herdr-connection.js +2 -1
- package/src/runs/shared/herdr-pane-host.d.ts +2 -2
- package/src/runs/shared/herdr-pane-host.js +17 -1
- package/src/runs/shared/herdr-placed-run.js +51 -24
- package/src/runs/shared/lane-metadata.d.ts +0 -1
- package/src/runs/shared/lane-metadata.js +0 -1
- package/src/runs/shared/mcp-config-sources.d.ts +4 -1
- package/src/runs/shared/mcp-config-sources.js +1 -1
- package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -3
- package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -17
- package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
- package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
- package/src/runs/shared/model-resolution.d.ts +20 -5
- package/src/runs/shared/model-resolution.js +55 -50
- package/src/runs/shared/model-scope.d.ts +1 -5
- package/src/runs/shared/model-scope.js +1 -5
- package/src/runs/shared/mutation-evidence.d.ts +1 -1
- package/src/runs/shared/mutation-evidence.js +52 -7
- package/src/runs/shared/nested-events.d.ts +1 -0
- package/src/runs/shared/nested-events.js +1 -1
- package/src/runs/shared/parallel-utils.d.ts +0 -1
- package/src/runs/shared/permissions.js +5 -3
- package/src/runs/shared/placement-host.d.ts +5 -1
- package/src/runs/shared/rex-pane-host.d.ts +0 -1
- package/src/runs/shared/rex-pane-host.js +0 -2
- package/src/runs/shared/run-launch-folder.d.ts +12 -0
- package/src/runs/shared/run-launch-folder.js +21 -0
- package/src/runs/shared/runner-launcher.d.ts +12 -1
- package/src/runs/shared/runner-launcher.js +16 -0
- package/src/runs/shared/single-output.d.ts +3 -3
- package/src/runs/shared/single-output.js +5 -3
- package/src/runs/shared/structured-output.d.ts +8 -0
- package/src/runs/shared/structured-output.js +40 -5
- package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
- package/src/runs/shared/subagent-prompt-runtime.js +18 -4
- package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
- package/src/runs/shared/supervisor-wait-timer.js +61 -0
- package/src/runs/shared/tool-timeout.js +2 -1
- package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
- package/src/runs/shared/worktree-cleanup-plan.js +0 -1
- package/src/runs/shared/worktree.d.ts +3 -0
- package/src/runs/shared/worktree.js +20 -0
- package/src/shared/artifacts.d.ts +1 -0
- package/src/shared/artifacts.js +132 -22
- package/src/shared/capacity-resilient-json.d.ts +1 -1
- package/src/shared/child-cache-retention.d.ts +1 -2
- package/src/shared/child-cache-retention.js +1 -2
- package/src/shared/fleet-transcript-reader.d.ts +51 -0
- package/src/shared/fleet-transcript-reader.js +333 -0
- package/src/shared/formatters.d.ts +0 -18
- package/src/shared/formatters.js +0 -18
- package/src/shared/pruned-fork.js +2 -2
- package/src/shared/reported-progress.d.ts +1 -0
- package/src/shared/reported-progress.js +12 -0
- package/src/shared/session-succession.d.ts +16 -1
- package/src/shared/session-succession.js +41 -2
- package/src/shared/session-warnings.d.ts +7 -0
- package/src/shared/session-warnings.js +26 -0
- package/src/shared/settings.d.ts +0 -23
- package/src/shared/settings.js +3 -35
- package/src/shared/status-format.d.ts +1 -0
- package/src/shared/status-format.js +1 -1
- package/src/shared/types.d.ts +108 -59
- package/src/shared/types.js +0 -12
- package/src/shared/utils.d.ts +3 -15
- package/src/shared/utils.js +4 -22
- package/src/shared/wait-tool-name.d.ts +8 -0
- package/src/shared/wait-tool-name.js +13 -0
- package/src/slash/slash-commands.js +2 -1
- package/src/slash/subagent-cost.d.ts +3 -2
- package/src/slash/subagent-cost.js +22 -3
- package/src/slash/subagents-admin.js +0 -1
- package/src/tui/fleet-status.d.ts +0 -5
- package/src/tui/fleet-status.js +4 -24
- package/src/tui/fleet.js +6 -4
- package/src/tui/render.d.ts +0 -9
- package/src/tui/render.js +194 -68
- package/src/tui/subagent-messages.js +3 -2
- package/src/watchdog/model-selection.js +2 -2
- package/src/watchdog/permission-arbiter.js +1 -0
- package/src/watchdog/register-child.d.ts +2 -3
- package/src/watchdog/register-child.js +2 -3
- package/src/watchdog/review.d.ts +0 -5
- package/src/watchdog/review.js +4 -3
- package/src/watchdog/turn-delta.js +2 -1
- package/src/workflows/scripted-workflow.d.ts +2 -0
- package/src/workflows/scripted-workflow.js +344 -59
- package/src/workflows/structured-workflow-scripts.d.ts +4 -3
- package/src/workflows/structured-workflow-scripts.js +32 -11
- package/src/workflows/workflow-launch-record.d.ts +15 -6
- package/src/workflows/workflow-launch-record.js +30 -12
- package/src/workflows/workflow-receipt.js +36 -53
- package/src/workflows/workflow-resources.js +4 -4
- package/src/workflows/workflow-resume-claim.d.ts +2 -0
- package/src/workflows/workflow-resume-claim.js +3 -3
- package/src/workflows/workflow-resume.d.ts +1 -1
- package/src/workflows/workflow-resume.js +13 -8
- package/src/workflows/workflow-script-worker.d.ts +13 -0
- package/src/workflows/workflow-script-worker.js +81 -0
- package/workflow-script-process.cjs +36 -0
- package/workflow-script-worker.cjs +4 -1
- package/bundle/chunk-U4ODUYAG.js +0 -235
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { agentDefinitionDigest } from "../../shared/launch-contract.js";
|
|
2
|
+
export const REQUIRE_LAUNCHER_SHAPE_ERROR = "requireLauncher is supported only on a top-level single-agent call (agent + task); it cannot be combined with tasks, chain, workflow, an action, resume, or a workflow child.";
|
|
1
3
|
/** Own-property lookup, so an inherited object key can never select a command. */
|
|
2
4
|
export function lookupRunnerLauncher(runnerLaunchers, name) {
|
|
3
5
|
const argv = runnerLaunchers && Object.hasOwn(runnerLaunchers, name) ? runnerLaunchers[name] : undefined;
|
|
@@ -22,3 +24,17 @@ export function resolveAgentRunnerLauncher(agent, runnerLaunchers, machine) {
|
|
|
22
24
|
const launcher = lookupRunnerLauncher(runnerLaunchers, agent.launcher);
|
|
23
25
|
return launcher ? { launcher } : { error: `Agent '${agent.name}' uses launcher '${agent.launcher}', which is not defined in runnerLaunchers in the user subagent config.` };
|
|
24
26
|
}
|
|
27
|
+
/**
|
|
28
|
+
* Checks a call's launcher requirement against the agent and launcher a launch resolved. On a match it returns the
|
|
29
|
+
* digest it checked, so the launch can record that digest instead of hashing the agent file again.
|
|
30
|
+
*/
|
|
31
|
+
export function checkRequiredRunnerLauncher(agent, launcherName, required) {
|
|
32
|
+
if (launcherName === undefined)
|
|
33
|
+
return { error: `Agent '${agent.name}' has no launcher, but the call requires launcher '${required.name}'.` };
|
|
34
|
+
if (launcherName !== required.name)
|
|
35
|
+
return { error: `Agent '${agent.name}' uses launcher '${launcherName}', but the call requires launcher '${required.name}'.` };
|
|
36
|
+
const definitionDigest = agentDefinitionDigest(agent);
|
|
37
|
+
if (definitionDigest !== required.definitionDigest)
|
|
38
|
+
return { error: `Agent '${agent.name}' definition digest is ${definitionDigest}, but the call requires ${required.definitionDigest}; the agent definition changed after it was checked.` };
|
|
39
|
+
return { definitionDigest };
|
|
40
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Message } from "@earendil-works/pi-ai";
|
|
2
|
-
import type { OutputMode, SavedOutputReference } from "../../shared/types.ts";
|
|
2
|
+
import type { OutputMode, PlacementMachineReference, SavedOutputReference } from "../../shared/types.ts";
|
|
3
3
|
export interface SingleOutputSnapshot {
|
|
4
4
|
exists: boolean;
|
|
5
5
|
mtimeMs?: number;
|
|
@@ -27,7 +27,8 @@ export declare function outputPathMappingFromTask(task: string, savedPath: strin
|
|
|
27
27
|
requestedPath: string;
|
|
28
28
|
savedPath: string;
|
|
29
29
|
} | undefined;
|
|
30
|
-
|
|
30
|
+
/** A child on another machine cannot write the parent-side path; its final reply is saved there instead. */
|
|
31
|
+
export declare function injectSingleOutputInstruction(task: string, outputPath: string | undefined, capabilities?: OutputInstructionCapabilities, machine?: PlacementMachineReference): string;
|
|
31
32
|
export declare function formatSavedOutputReference(savedPath: string, fullOutput: string): SavedOutputReference;
|
|
32
33
|
/**
|
|
33
34
|
* Keeps at most INLINE_OUTPUT_HEAD_CHARS of a child's output inline and points to the file holding all of it.
|
|
@@ -78,7 +79,6 @@ export declare function finalizeSingleOutput(params: {
|
|
|
78
79
|
saveError?: string;
|
|
79
80
|
};
|
|
80
81
|
/**
|
|
81
|
-
* Determines whether an output resolution error represents an unrecoverable settlement failure.
|
|
82
82
|
* Returns true for fatal claim-path mismatches in any mode, or when required file-only output
|
|
83
83
|
* fails to persist without a savedPath. Inline and optional outputs remain nonfatal warnings.
|
|
84
84
|
*/
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
2
|
import * as path from "node:path";
|
|
3
|
+
import { isRexLocalMachine } from "./rex-machine.js";
|
|
3
4
|
const READ_ONLY_OUTPUT_TOOLS = new Set([
|
|
4
5
|
"read", "grep", "find", "ls", "web_search", "fetch_content", "get_search_content",
|
|
5
6
|
"source_check", "intercom", "contact_supervisor", "structured_output", "watchdog_diff",
|
|
@@ -98,10 +99,12 @@ export function outputPathMappingFromTask(task, savedPath) {
|
|
|
98
99
|
return undefined;
|
|
99
100
|
return { requestedPath, savedPath };
|
|
100
101
|
}
|
|
101
|
-
|
|
102
|
+
/** A child on another machine cannot write the parent-side path; its final reply is saved there instead. */
|
|
103
|
+
export function injectSingleOutputInstruction(task, outputPath, capabilities, machine) {
|
|
102
104
|
if (!outputPath)
|
|
103
105
|
return task;
|
|
104
|
-
const
|
|
106
|
+
const remote = machine !== undefined && !isRexLocalMachine(machine);
|
|
107
|
+
const delivery = !remote && (!capabilities || hasOutputWriteCapability(capabilities.tools, capabilities.mcpDirectTools))
|
|
105
108
|
? `Write your findings to exactly this path: ${outputPath}`
|
|
106
109
|
: [
|
|
107
110
|
"Return the complete artifact in your final response.",
|
|
@@ -339,7 +342,6 @@ export function finalizeSingleOutput(params) {
|
|
|
339
342
|
return { displayOutput };
|
|
340
343
|
}
|
|
341
344
|
/**
|
|
342
|
-
* Determines whether an output resolution error represents an unrecoverable settlement failure.
|
|
343
345
|
* Returns true for fatal claim-path mismatches in any mode, or when required file-only output
|
|
344
346
|
* fails to persist without a savedPath. Inline and optional outputs remain nonfatal warnings.
|
|
345
347
|
*/
|
|
@@ -38,6 +38,8 @@ interface JsonSchemaValidationError {
|
|
|
38
38
|
}
|
|
39
39
|
type CompileJsonSchema = (schema: unknown) => CompiledJsonSchema;
|
|
40
40
|
export declare function resolveCompileFromPackageRoot(packageRoot: string): Promise<CompileJsonSchema | undefined>;
|
|
41
|
+
/** Resolves once the validator has loaded or failed; a failure is reported by the structured_output call. */
|
|
42
|
+
export declare function structuredOutputValidatorReady(): Promise<void>;
|
|
41
43
|
export declare function assertJsonSchemaObject(schema: unknown, label?: string): asserts schema is JsonSchemaObject;
|
|
42
44
|
export declare function createStructuredOutputRuntime(schema: JsonSchemaObject, baseDir?: string, options?: {
|
|
43
45
|
acceptanceReport?: ResolvedAcceptanceReportMode;
|
|
@@ -48,6 +50,12 @@ export declare function validateStructuredOutputValue(schema: JsonSchemaObject,
|
|
|
48
50
|
status: "invalid";
|
|
49
51
|
message: string;
|
|
50
52
|
}>;
|
|
53
|
+
/**
|
|
54
|
+
* The tool's `prepareArguments` hook: checks the raw `value` before Pi converts tool arguments
|
|
55
|
+
* (Pi can turn `"x"` into `["x"]` or `null` into `"null"`), so only a value that already matches
|
|
56
|
+
* the schema is captured. Fails closed when the validator has not loaded.
|
|
57
|
+
*/
|
|
58
|
+
export declare function prepareStructuredOutputArguments(schema: JsonSchemaObject, args: unknown): unknown;
|
|
51
59
|
export declare function readStructuredOutput(runtime: StructuredOutputRuntime): Promise<{
|
|
52
60
|
value?: unknown;
|
|
53
61
|
error?: string;
|
|
@@ -152,6 +152,9 @@ export function createStructuredOutputToolParameters(schema, options = {}) {
|
|
|
152
152
|
};
|
|
153
153
|
}
|
|
154
154
|
let cachedCompile;
|
|
155
|
+
// prepareArguments is synchronous, so it can only use a compiler that has already loaded.
|
|
156
|
+
let loadedCompile;
|
|
157
|
+
let compileLoadError;
|
|
155
158
|
export async function resolveCompileFromPackageRoot(packageRoot) {
|
|
156
159
|
const requireFromRoot = createRequire(path.join(packageRoot, "package.json"));
|
|
157
160
|
const resolved = requireFromRoot.resolve("typebox/compile");
|
|
@@ -196,13 +199,21 @@ async function importCompile() {
|
|
|
196
199
|
}
|
|
197
200
|
function loadCompile() {
|
|
198
201
|
if (!cachedCompile) {
|
|
199
|
-
cachedCompile = importCompile().
|
|
202
|
+
cachedCompile = importCompile().then((compile) => {
|
|
203
|
+
loadedCompile = compile;
|
|
204
|
+
return compile;
|
|
205
|
+
}, (error) => {
|
|
200
206
|
cachedCompile = undefined;
|
|
207
|
+
compileLoadError = error;
|
|
201
208
|
throw error;
|
|
202
209
|
});
|
|
203
210
|
}
|
|
204
211
|
return cachedCompile;
|
|
205
212
|
}
|
|
213
|
+
/** Resolves once the validator has loaded or failed; a failure is reported by the structured_output call. */
|
|
214
|
+
export function structuredOutputValidatorReady() {
|
|
215
|
+
return loadCompile().then(() => undefined, () => undefined);
|
|
216
|
+
}
|
|
206
217
|
function jsonPointerTarget(root, pointer) {
|
|
207
218
|
if (pointer === "#")
|
|
208
219
|
return root;
|
|
@@ -379,7 +390,24 @@ export function createStructuredOutputRuntime(schema, baseDir, options = {}) {
|
|
|
379
390
|
};
|
|
380
391
|
}
|
|
381
392
|
export async function validateStructuredOutputValue(schema, value) {
|
|
382
|
-
|
|
393
|
+
return validateWithCompile(await loadCompile(), schema, value);
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* The tool's `prepareArguments` hook: checks the raw `value` before Pi converts tool arguments
|
|
397
|
+
* (Pi can turn `"x"` into `["x"]` or `null` into `"null"`), so only a value that already matches
|
|
398
|
+
* the schema is captured. Fails closed when the validator has not loaded.
|
|
399
|
+
*/
|
|
400
|
+
export function prepareStructuredOutputArguments(schema, args) {
|
|
401
|
+
if (!args || typeof args !== "object" || !("value" in args))
|
|
402
|
+
return args;
|
|
403
|
+
if (!loadedCompile)
|
|
404
|
+
throw compileLoadError ?? new Error("Structured output validator is still loading; call structured_output again.");
|
|
405
|
+
const validation = validateWithCompile(loadedCompile, schema, args.value);
|
|
406
|
+
if (validation.status === "invalid")
|
|
407
|
+
throw new Error(`Structured output validation failed: ${validation.message}`);
|
|
408
|
+
return args;
|
|
409
|
+
}
|
|
410
|
+
function validateWithCompile(compile, schema, value) {
|
|
383
411
|
let validator;
|
|
384
412
|
try {
|
|
385
413
|
validator = compile(schema);
|
|
@@ -387,9 +415,16 @@ export async function validateStructuredOutputValue(schema, value) {
|
|
|
387
415
|
catch (error) {
|
|
388
416
|
return { status: "invalid", message: `invalid outputSchema: ${error instanceof Error ? error.message : String(error)}` };
|
|
389
417
|
}
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
418
|
+
let originalErrors;
|
|
419
|
+
try {
|
|
420
|
+
if (validator.Check(value))
|
|
421
|
+
return { status: "valid" };
|
|
422
|
+
originalErrors = [...validator.Errors(value)];
|
|
423
|
+
}
|
|
424
|
+
catch (error) {
|
|
425
|
+
// A recursive $ref compiles but overflows the stack when checked.
|
|
426
|
+
return { status: "invalid", message: `outputSchema cannot be validated (cyclic or too deep): ${error instanceof Error ? error.message : String(error)}` };
|
|
427
|
+
}
|
|
393
428
|
const errors = [];
|
|
394
429
|
const uniqueErrors = new Set();
|
|
395
430
|
const seen = new Set();
|
|
@@ -85,6 +85,5 @@ export declare function stripParentOnlySubagentMessages(messages: unknown[], opt
|
|
|
85
85
|
}): unknown[];
|
|
86
86
|
export declare function formatSteerMessage(request: SteerRequest): string;
|
|
87
87
|
export declare function registerPermissionGate(pi: ExtensionAPI, permissions: ChildPermissions | undefined, childWatchdog: ChildWatchdogConfig | undefined, requestPermission?: (request: WatchdogPermissionRequest) => Promise<WatchdogPermissionResult>): void;
|
|
88
|
-
/** Register every child-side hook the prompt runtime owns for one child session. */
|
|
89
88
|
export default function registerSubagentPromptRuntime(pi: ExtensionAPI, config?: ChildRuntimeConfig, drainObservation?: import("./readonly-drain-observation.ts").ReadonlyDrainObservation): void;
|
|
90
89
|
export {};
|
|
@@ -5,7 +5,7 @@ import { declarationsEqual, getCurrentSystemMessage, getCurrentTools } from "@ea
|
|
|
5
5
|
import { registerNativeSupervisorClient } from "../../intercom/native-supervisor-channel.js";
|
|
6
6
|
import { permissionDecision } from "./permissions.js";
|
|
7
7
|
import { RUNTIME_EXTENSION_ACK_EVENT, isRuntimeAcknowledgedExtensionId } from "./runtime-acknowledged-extensions.js";
|
|
8
|
-
import { createStructuredOutputToolParameters, MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR, validateStructuredOutputValue } from "./structured-output.js";
|
|
8
|
+
import { createStructuredOutputToolParameters, MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR, prepareStructuredOutputArguments, validateStructuredOutputValue } from "./structured-output.js";
|
|
9
9
|
import { validateAcceptanceReport } from "./acceptance.js";
|
|
10
10
|
import { formatChildToolDiagnostic } from "./tool-availability.js";
|
|
11
11
|
import { shouldBlockToolForBudget, toolBudgetBlockedMessage, toolBudgetSoftNudge } from "./tool-budget.js";
|
|
@@ -20,6 +20,7 @@ import { inheritedNestedRouteOf } from "./nested-events.js";
|
|
|
20
20
|
import { registerWaitTool } from "../background/wait-tool.js";
|
|
21
21
|
import { drainOutstandingWork } from "../background/auto-drain.js";
|
|
22
22
|
import { MODEL_ONLY_TOOL } from "../../shared/extension-context.js";
|
|
23
|
+
import { DEFAULT_WAIT_TOOL_NAME, setWaitToolName } from "../../shared/wait-tool-name.js";
|
|
23
24
|
import { childSupervisorMetadata, evaluateChildToolDiagnostic, } from "./child-runtime-config.js";
|
|
24
25
|
const STRUCTURED_OUTPUT_INSTRUCTIONS = [
|
|
25
26
|
"This subagent step has a strict structured output contract.",
|
|
@@ -297,11 +298,19 @@ export function modelBefore(messages, forkedAt) {
|
|
|
297
298
|
* parent's prompt, so its own versions of these sections are not repeated in its task message.
|
|
298
299
|
*/
|
|
299
300
|
const LOADOUT_SECTIONS = new Set(["tools", "rules", "docs", "skills", "advertised_subagents", "mcp_servers", "project_context"]);
|
|
301
|
+
/** The `<project_instructions path="…">` blocks Pi writes into a `project_context` section, by path. */
|
|
302
|
+
function projectInstructionBlocks(section) {
|
|
303
|
+
const blocks = new Map();
|
|
304
|
+
for (const match of (section ?? "").matchAll(/<project_instructions\s+path=(["'])(.*?)\1\s*>[\s\S]*?<\/project_instructions>/gi))
|
|
305
|
+
blocks.set(match[2], match[0]);
|
|
306
|
+
return blocks;
|
|
307
|
+
}
|
|
300
308
|
/**
|
|
301
309
|
* The child's own instructions, which a fork sends in its task message instead of its system
|
|
302
310
|
* prompt: the text its own system messages (`own`) add, the sections it changed except the loadout
|
|
303
|
-
* ones, the
|
|
304
|
-
*
|
|
311
|
+
* ones, the project instruction files the parent's prompt lacks (a child that works in another
|
|
312
|
+
* folder has that folder's AGENTS.md), the tools it can call, and its boundary. `parent` is the
|
|
313
|
+
* inherited system messages and `child` the whole request.
|
|
305
314
|
*/
|
|
306
315
|
function forkInstructions(input) {
|
|
307
316
|
const parent = getCurrentSystemMessage(input.parent);
|
|
@@ -317,6 +326,10 @@ function forkInstructions(input) {
|
|
|
317
326
|
if (!LOADOUT_SECTIONS.has(name) && value && parent?.sections?.[name] !== value)
|
|
318
327
|
parts.push(value);
|
|
319
328
|
}
|
|
329
|
+
const parentFiles = projectInstructionBlocks(parent?.sections?.project_context);
|
|
330
|
+
const missingFiles = [...projectInstructionBlocks(child?.sections?.project_context)].filter(([filePath]) => !parentFiles.has(filePath)).map(([, block]) => block);
|
|
331
|
+
if (missingFiles.length > 0)
|
|
332
|
+
parts.push(["Project instructions for your working folder, which the parent's prompt does not include:", ...missingFiles].join("\n\n"));
|
|
320
333
|
if (input.boundary)
|
|
321
334
|
parts.push(input.boundary);
|
|
322
335
|
return `<subagent_instructions>\n${parts.join("\n\n")}\n</subagent_instructions>`;
|
|
@@ -593,6 +606,7 @@ function registerStructuredOutputTool(pi, structured) {
|
|
|
593
606
|
label: "Structured Output",
|
|
594
607
|
description: "Submit the required final structured output for this subagent step. This terminates the step.",
|
|
595
608
|
parameters,
|
|
609
|
+
prepareArguments: (args) => prepareStructuredOutputArguments(structured.schema, args),
|
|
596
610
|
async execute(_id, params) {
|
|
597
611
|
const validation = await validateStructuredOutputValue(structured.schema, params.value);
|
|
598
612
|
if (validation.status === "invalid") {
|
|
@@ -617,7 +631,6 @@ function registerStructuredOutputTool(pi, structured) {
|
|
|
617
631
|
},
|
|
618
632
|
});
|
|
619
633
|
}
|
|
620
|
-
/** Register every child-side hook the prompt runtime owns for one child session. */
|
|
621
634
|
export default function registerSubagentPromptRuntime(pi, config, drainObservation) {
|
|
622
635
|
// A path-based load has no ChildRuntimeConfig. This can happen if an
|
|
623
636
|
// ambient-extension discovery path finds the runtime module in addition to
|
|
@@ -655,6 +668,7 @@ export default function registerSubagentPromptRuntime(pi, config, drainObservati
|
|
|
655
668
|
};
|
|
656
669
|
const nestedRootRunId = inheritedNestedRouteOf(config)?.rootRunId;
|
|
657
670
|
// fanout-child assigns config.hasPendingSupervisorRequest after this hook registers, so read it per wait.
|
|
671
|
+
setWaitToolName(config.waitTool.name ?? DEFAULT_WAIT_TOOL_NAME);
|
|
658
672
|
if (typeof pi.registerTool === "function")
|
|
659
673
|
registerWaitTool(pi, waitState, config.waitTool.enabled, undefined, config.waitTool.defaultTimeoutMs, { nestedRootRunId }, () => config.hasPendingSupervisorRequest?.() === true);
|
|
660
674
|
const supervisorMetadata = childSupervisorMetadata(config);
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** A child making one of these calls is blocked on its supervisor's reply, not working. */
|
|
2
|
+
export declare function isBlockingSupervisorTool(toolName: string | undefined, args: unknown): boolean;
|
|
3
|
+
/** A one-shot timer whose countdown stops while any key holds it paused. */
|
|
4
|
+
export interface PausableTimer {
|
|
5
|
+
pause(key: string): void;
|
|
6
|
+
resume(key: string): void;
|
|
7
|
+
remainingMs(): number;
|
|
8
|
+
clear(): void;
|
|
9
|
+
}
|
|
10
|
+
export declare function startPausableTimer(delayMs: number, onFire: () => void): PausableTimer;
|
|
11
|
+
export declare function pauseForSupervisorWait(timer: PausableTimer | undefined, event: {
|
|
12
|
+
type?: string;
|
|
13
|
+
toolCallId?: unknown;
|
|
14
|
+
toolName?: string;
|
|
15
|
+
args?: unknown;
|
|
16
|
+
}): void;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/** A child making one of these calls is blocked on its supervisor's reply, not working. */
|
|
2
|
+
export function isBlockingSupervisorTool(toolName, args) {
|
|
3
|
+
if (!args || typeof args !== "object")
|
|
4
|
+
return false;
|
|
5
|
+
const call = args;
|
|
6
|
+
if (toolName === "contact_supervisor")
|
|
7
|
+
return call.reason === "need_decision" || call.reason === "interview_request";
|
|
8
|
+
return toolName === "intercom" && call.action === "ask";
|
|
9
|
+
}
|
|
10
|
+
export function startPausableTimer(delayMs, onFire) {
|
|
11
|
+
let remaining = Math.max(0, delayMs);
|
|
12
|
+
// Monotonic clock: a system clock change must not shorten or extend the budget.
|
|
13
|
+
let runningSince;
|
|
14
|
+
let timer;
|
|
15
|
+
let done = false;
|
|
16
|
+
const pausedBy = new Set();
|
|
17
|
+
const remainingMs = () => runningSince === undefined ? remaining : Math.max(0, remaining - (performance.now() - runningSince));
|
|
18
|
+
const run = () => {
|
|
19
|
+
runningSince = performance.now();
|
|
20
|
+
timer = setTimeout(() => {
|
|
21
|
+
done = true;
|
|
22
|
+
runningSince = undefined;
|
|
23
|
+
remaining = 0;
|
|
24
|
+
onFire();
|
|
25
|
+
}, remaining);
|
|
26
|
+
timer.unref?.();
|
|
27
|
+
};
|
|
28
|
+
const stop = () => {
|
|
29
|
+
clearTimeout(timer);
|
|
30
|
+
remaining = remainingMs();
|
|
31
|
+
runningSince = undefined;
|
|
32
|
+
};
|
|
33
|
+
run();
|
|
34
|
+
return {
|
|
35
|
+
pause(key) {
|
|
36
|
+
if (done)
|
|
37
|
+
return;
|
|
38
|
+
if (pausedBy.size === 0)
|
|
39
|
+
stop();
|
|
40
|
+
pausedBy.add(key);
|
|
41
|
+
},
|
|
42
|
+
resume(key) {
|
|
43
|
+
if (done || !pausedBy.delete(key) || pausedBy.size > 0)
|
|
44
|
+
return;
|
|
45
|
+
run();
|
|
46
|
+
},
|
|
47
|
+
remainingMs,
|
|
48
|
+
clear() {
|
|
49
|
+
done = true;
|
|
50
|
+
stop();
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
export function pauseForSupervisorWait(timer, event) {
|
|
55
|
+
if (!timer || typeof event.toolCallId !== "string")
|
|
56
|
+
return;
|
|
57
|
+
if (event.type === "tool_execution_start" && isBlockingSupervisorTool(event.toolName, event.args))
|
|
58
|
+
timer.pause(event.toolCallId);
|
|
59
|
+
else if (event.type === "tool_execution_end")
|
|
60
|
+
timer.resume(event.toolCallId);
|
|
61
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { waitToolName } from "../../shared/wait-tool-name.js";
|
|
1
2
|
export const TOOL_TIMEOUT_ENV = "PI_SUBAGENT_TOOL_TIMEOUT_MS";
|
|
2
3
|
/** Maximum delay a Node.js timer accepts without overflow. */
|
|
3
4
|
const MAX_TIMER_DELAY_MS = 2_147_483_647;
|
|
@@ -16,7 +17,7 @@ export const TOOL_TIMEOUT_EXEMPT_TOOLS = new Set(["contact_supervisor", "interco
|
|
|
16
17
|
// Backward-compatible export name for existing callers/tests.
|
|
17
18
|
export const TOOL_TIMEOUT_ALLOWLIST = TOOL_TIMEOUT_EXEMPT_TOOLS;
|
|
18
19
|
export function isToolTimeoutExempt(toolName) {
|
|
19
|
-
return toolName !== undefined && TOOL_TIMEOUT_EXEMPT_TOOLS.has(toolName);
|
|
20
|
+
return toolName !== undefined && (TOOL_TIMEOUT_EXEMPT_TOOLS.has(toolName) || toolName === waitToolName());
|
|
20
21
|
}
|
|
21
22
|
export function defaultToolTimeoutMs(toolName) {
|
|
22
23
|
return toolName !== undefined && DEFAULT_FAST_TOOL_TIMEOUT_TOOLS.has(toolName)
|
|
@@ -68,7 +68,6 @@ interface GitWorktreeRecord {
|
|
|
68
68
|
locked?: boolean;
|
|
69
69
|
}
|
|
70
70
|
declare function realpathExisting(candidate: string, nativeRealpath?: (filePath: string) => string, fallbackRealpath?: (filePath: string) => string): string;
|
|
71
|
-
/** Internal test seam; this is not part of the public subagent tool API. */
|
|
72
71
|
export declare const __testables: {
|
|
73
72
|
realpathExisting: typeof realpathExisting;
|
|
74
73
|
};
|
|
@@ -50,7 +50,6 @@ function realpathExisting(candidate, nativeRealpath = fs.realpathSync.native, fa
|
|
|
50
50
|
return fallbackRealpath(candidate);
|
|
51
51
|
}
|
|
52
52
|
}
|
|
53
|
-
/** Internal test seam; this is not part of the public subagent tool API. */
|
|
54
53
|
export const __testables = { realpathExisting };
|
|
55
54
|
function comparablePath(candidate) {
|
|
56
55
|
let current = path.resolve(candidate);
|
|
@@ -151,6 +151,9 @@ export declare class WorktreeSetupError extends Error {
|
|
|
151
151
|
}
|
|
152
152
|
/** Later async finalization owners wrap their synchronous diff/cleanup as ONE turn. */
|
|
153
153
|
export declare function withWorktreeTransaction<T>(action: () => T | Promise<T>): Promise<T>;
|
|
154
|
+
export declare function findListedWorktreeOnBranch(repoCwd: string, branch: string): string | undefined;
|
|
155
|
+
export declare function findListedWorktreeAgentCwd(repoCwd: string, branch: string): string | undefined;
|
|
156
|
+
export declare function isComparablePathInside(parent: string, child: string): boolean;
|
|
154
157
|
/** Validate a captured patch against the worktree index without changing either. */
|
|
155
158
|
export declare function validateWorktreePatch(worktreePath: string, patchPath: string): string | undefined;
|
|
156
159
|
export declare function validateWorktreePatchRepresentsCurrentWorktree(worktreePath: string, baseCommit: string, patchPath: string): string | undefined;
|
|
@@ -136,6 +136,26 @@ function runGitChecked(cwd, args) {
|
|
|
136
136
|
}
|
|
137
137
|
return result.stdout;
|
|
138
138
|
}
|
|
139
|
+
export function findListedWorktreeOnBranch(repoCwd, branch) {
|
|
140
|
+
let current;
|
|
141
|
+
for (const line of runGitChecked(repoCwd, ["worktree", "list", "--porcelain"]).split("\n")) {
|
|
142
|
+
if (line.startsWith("worktree "))
|
|
143
|
+
current = line.slice("worktree ".length);
|
|
144
|
+
else if (line === `branch refs/heads/${branch}` && current)
|
|
145
|
+
return normalizeComparableCwd(current);
|
|
146
|
+
}
|
|
147
|
+
return undefined;
|
|
148
|
+
}
|
|
149
|
+
export function findListedWorktreeAgentCwd(repoCwd, branch) {
|
|
150
|
+
const worktree = findListedWorktreeOnBranch(repoCwd, branch);
|
|
151
|
+
if (!worktree)
|
|
152
|
+
return undefined;
|
|
153
|
+
const cwdRelative = resolveRepoCwdRelative(repoCwd);
|
|
154
|
+
return cwdRelative ? path.join(worktree, cwdRelative) : worktree;
|
|
155
|
+
}
|
|
156
|
+
export function isComparablePathInside(parent, child) {
|
|
157
|
+
return isPathInside(normalizeComparableCwd(parent), normalizeComparableCwd(child));
|
|
158
|
+
}
|
|
139
159
|
/** Validate a captured patch against the worktree index without changing either. */
|
|
140
160
|
export function validateWorktreePatch(worktreePath, patchPath) {
|
|
141
161
|
const result = runGit(worktreePath, [...PATCH_VALIDATION_OPTIONS, patchPath]);
|
|
@@ -20,3 +20,4 @@ export declare function writeMetadata(filePath: string, metadata: object): void;
|
|
|
20
20
|
export declare function appendJsonl(filePath: string, line: string): void;
|
|
21
21
|
export declare function cleanupOldArtifacts(dir: string, maxAgeDays: number): void;
|
|
22
22
|
export declare function cleanupAllArtifactDirs(maxAgeDays: number): void;
|
|
23
|
+
export declare function missingForkCopyNote(sessionFile: string): string;
|
package/src/shared/artifacts.js
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
2
|
import * as path from "node:path";
|
|
3
|
-
import { CHAIN_RUNS_DIR, TEMP_ARTIFACTS_DIR } from "./types.js";
|
|
4
|
-
import { getAgentDir } from "./utils.js";
|
|
3
|
+
import { CHAIN_RUNS_DIR, DIRS, TEMP_ARTIFACTS_DIR } from "./types.js";
|
|
4
|
+
import { getAgentDir, readStatus } from "./utils.js";
|
|
5
|
+
import { acquireSessionLease } from "../runs/shared/session-lease.js";
|
|
5
6
|
const CLEANUP_MARKER_FILE = ".last-cleanup";
|
|
7
|
+
// Pi lists only directories under its sessions root, so a marker file there is invisible to it.
|
|
8
|
+
const FORK_CLEANUP_MARKER_FILE = ".pi-subagents-fork-cleanup";
|
|
9
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
10
|
+
// Kept worktrees can outlive cleanupDays; their handoff record and the patches it points to must stay with them.
|
|
11
|
+
const RETAINED_ARTIFACT_DIRS = new Set(["handoffs", "worktree-diffs"]);
|
|
6
12
|
export const PROJECT_SUBAGENTS_RELATIVE_DIR = ".pi/subagents";
|
|
7
13
|
const PROJECT_ARTIFACT_PATHS = [
|
|
8
14
|
`${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/output.md`,
|
|
@@ -221,30 +227,36 @@ export function cleanupOldArtifacts(dir, maxAgeDays) {
|
|
|
221
227
|
return;
|
|
222
228
|
const markerPath = path.join(dir, CLEANUP_MARKER_FILE);
|
|
223
229
|
const now = Date.now();
|
|
224
|
-
if (
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1000;
|
|
230
|
-
const cutoff = now - maxAgeMs;
|
|
231
|
-
for (const file of fs.readdirSync(dir)) {
|
|
232
|
-
if (file === CLEANUP_MARKER_FILE)
|
|
230
|
+
if (ranWithinDay(markerPath, now))
|
|
231
|
+
return;
|
|
232
|
+
const cutoff = now - maxAgeDays * DAY_MS;
|
|
233
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
234
|
+
if (entry.name === CLEANUP_MARKER_FILE || (entry.isDirectory() && RETAINED_ARTIFACT_DIRS.has(entry.name)))
|
|
233
235
|
continue;
|
|
234
|
-
|
|
235
|
-
try {
|
|
236
|
-
const stat = fs.statSync(filePath);
|
|
237
|
-
if (stat.mtimeMs < cutoff) {
|
|
238
|
-
fs.unlinkSync(filePath);
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
catch {
|
|
242
|
-
// Artifact cleanup is best-effort housekeeping. Skip files that disappear
|
|
243
|
-
// or become unreadable while scanning so one bad entry does not block the rest.
|
|
244
|
-
}
|
|
236
|
+
removeOldEntry(path.join(dir, entry.name), cutoff);
|
|
245
237
|
}
|
|
246
238
|
fs.writeFileSync(markerPath, String(now));
|
|
247
239
|
}
|
|
240
|
+
function removeOldEntry(entryPath, cutoff) {
|
|
241
|
+
try {
|
|
242
|
+
const stat = fs.lstatSync(entryPath);
|
|
243
|
+
// Read the folder's age before emptying it: removing its files makes it look new.
|
|
244
|
+
const old = stat.mtimeMs < cutoff;
|
|
245
|
+
if (!stat.isDirectory()) {
|
|
246
|
+
if (old)
|
|
247
|
+
fs.unlinkSync(entryPath);
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
for (const name of fs.readdirSync(entryPath))
|
|
251
|
+
removeOldEntry(path.join(entryPath, name), cutoff);
|
|
252
|
+
if (old && fs.readdirSync(entryPath).length === 0)
|
|
253
|
+
fs.rmdirSync(entryPath);
|
|
254
|
+
}
|
|
255
|
+
catch {
|
|
256
|
+
// Artifact cleanup is best-effort housekeeping. Skip entries that disappear
|
|
257
|
+
// or become unreadable while scanning so one bad entry does not block the rest.
|
|
258
|
+
}
|
|
259
|
+
}
|
|
248
260
|
export function cleanupAllArtifactDirs(maxAgeDays) {
|
|
249
261
|
cleanupOldArtifacts(TEMP_ARTIFACTS_DIR, maxAgeDays);
|
|
250
262
|
const sessionsBase = path.join(getAgentDir(), "sessions");
|
|
@@ -259,6 +271,9 @@ export function cleanupAllArtifactDirs(maxAgeDays) {
|
|
|
259
271
|
// skip cleanup instead of failing extension startup.
|
|
260
272
|
return;
|
|
261
273
|
}
|
|
274
|
+
const forkMarkerPath = path.join(sessionsBase, FORK_CLEANUP_MARKER_FILE);
|
|
275
|
+
const now = Date.now();
|
|
276
|
+
const pruneForks = maxAgeDays > 0 && !ranWithinDay(forkMarkerPath, now);
|
|
262
277
|
for (const dir of dirs) {
|
|
263
278
|
const artifactsDir = path.join(sessionsBase, dir, "subagent-artifacts");
|
|
264
279
|
try {
|
|
@@ -268,5 +283,100 @@ export function cleanupAllArtifactDirs(maxAgeDays) {
|
|
|
268
283
|
// Session cleanup is best-effort. Keep going so one unreadable session dir
|
|
269
284
|
// does not block cleanup for the rest.
|
|
270
285
|
}
|
|
286
|
+
if (pruneForks)
|
|
287
|
+
removeOldForkCopies(path.join(sessionsBase, dir), now - maxAgeDays * DAY_MS);
|
|
288
|
+
}
|
|
289
|
+
if (!pruneForks)
|
|
290
|
+
return;
|
|
291
|
+
try {
|
|
292
|
+
fs.writeFileSync(forkMarkerPath, String(now));
|
|
293
|
+
}
|
|
294
|
+
catch {
|
|
295
|
+
// Without the marker the next load scans again; cleanup must not fail startup.
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
function ranWithinDay(markerPath, now) {
|
|
299
|
+
try {
|
|
300
|
+
return now - fs.statSync(markerPath).mtimeMs < DAY_MS;
|
|
271
301
|
}
|
|
302
|
+
catch {
|
|
303
|
+
return false;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
function removeOldForkCopies(projectDir, cutoff) {
|
|
307
|
+
let sessions;
|
|
308
|
+
try {
|
|
309
|
+
sessions = fs.readdirSync(projectDir, { withFileTypes: true });
|
|
310
|
+
}
|
|
311
|
+
catch {
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
for (const session of sessions) {
|
|
315
|
+
if (!session.isDirectory())
|
|
316
|
+
continue;
|
|
317
|
+
const forksDir = path.join(projectDir, session.name, "forks");
|
|
318
|
+
let runIds;
|
|
319
|
+
try {
|
|
320
|
+
// Never follow a symlinked forks folder: the deletes below would land in its target.
|
|
321
|
+
if (!fs.lstatSync(forksDir).isDirectory())
|
|
322
|
+
continue;
|
|
323
|
+
runIds = fs.readdirSync(forksDir);
|
|
324
|
+
}
|
|
325
|
+
catch {
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
for (const runId of runIds) {
|
|
329
|
+
const runDir = path.join(forksDir, runId);
|
|
330
|
+
const leases = [];
|
|
331
|
+
try {
|
|
332
|
+
const sessionFiles = idleSessionFiles(runDir, cutoff);
|
|
333
|
+
if (!sessionFiles || asyncRunActive(runId))
|
|
334
|
+
continue;
|
|
335
|
+
// A resumed run writes into its old copy under a new run id and holds that file's session lease.
|
|
336
|
+
// Holding the leases while deleting means a resume elsewhere finds either the lease taken or the file gone.
|
|
337
|
+
for (const file of sessionFiles)
|
|
338
|
+
leases.push(acquireSessionLease({ sessionFile: file, runId: "fork-cleanup", sourceRunId: runId }));
|
|
339
|
+
fs.rmSync(runDir, { recursive: true, force: true });
|
|
340
|
+
}
|
|
341
|
+
catch {
|
|
342
|
+
// Best-effort like artifact cleanup: a leased copy, or an entry that vanishes or can't be read, is left for the next pass.
|
|
343
|
+
}
|
|
344
|
+
finally {
|
|
345
|
+
for (const lease of leases)
|
|
346
|
+
lease.release();
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
// Undefined when anything inside, including a nested fork's copy, was written since cutoff: that keeps the whole folder.
|
|
352
|
+
function idleSessionFiles(entryPath, cutoff, files = []) {
|
|
353
|
+
const stat = fs.lstatSync(entryPath);
|
|
354
|
+
if (stat.mtimeMs >= cutoff)
|
|
355
|
+
return undefined;
|
|
356
|
+
if (!stat.isDirectory()) {
|
|
357
|
+
if (stat.isFile() && entryPath.endsWith(".jsonl"))
|
|
358
|
+
files.push(entryPath);
|
|
359
|
+
return files;
|
|
360
|
+
}
|
|
361
|
+
for (const name of fs.readdirSync(entryPath)) {
|
|
362
|
+
if (!idleSessionFiles(path.join(entryPath, name), cutoff, files))
|
|
363
|
+
return undefined;
|
|
364
|
+
}
|
|
365
|
+
return files;
|
|
366
|
+
}
|
|
367
|
+
// An async run waiting on a long tool call or a reply can leave its session file untouched for a long time.
|
|
368
|
+
function asyncRunActive(runId) {
|
|
369
|
+
try {
|
|
370
|
+
const state = readStatus(path.join(DIRS.async, runId))?.state;
|
|
371
|
+
return state === "queued" || state === "running";
|
|
372
|
+
}
|
|
373
|
+
catch {
|
|
374
|
+
// A status that can't be read may still belong to a live run.
|
|
375
|
+
return true;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
export function missingForkCopyNote(sessionFile) {
|
|
379
|
+
if (path.basename(path.dirname(path.dirname(sessionFile))) !== "forks")
|
|
380
|
+
return "";
|
|
381
|
+
return ". It was a forked child's copy of the parent session; such copies are deleted once nothing has written to them for artifactConfig.cleanupDays days (default 7).";
|
|
272
382
|
}
|
|
@@ -3,7 +3,7 @@ type TimerApi = {
|
|
|
3
3
|
clearTimeout(handle: unknown): void;
|
|
4
4
|
};
|
|
5
5
|
export type CapacityResilientJsonWriterOptions = {
|
|
6
|
-
/**
|
|
6
|
+
/** It must be atomic for each target path. */
|
|
7
7
|
write?: (filePath: string, payload: object) => void;
|
|
8
8
|
/** Keep retry timers referenced by the event loop (needed by child runners). */
|
|
9
9
|
keepAlive?: boolean;
|
|
@@ -7,8 +7,7 @@ import type { StreamFn } from "@earendil-works/pi-agent-core";
|
|
|
7
7
|
* parent keeps `long`, the same split Claude Code makes between its main
|
|
8
8
|
* conversation and its subagents.
|
|
9
9
|
*
|
|
10
|
-
* Unset means children inherit the parent's retention
|
|
11
|
-
* before this setting existed.
|
|
10
|
+
* Unset means children inherit the parent's retention.
|
|
12
11
|
*/
|
|
13
12
|
export declare function childCacheRetention(env?: NodeJS.ProcessEnv): string | undefined;
|
|
14
13
|
/**
|
|
@@ -6,8 +6,7 @@
|
|
|
6
6
|
* parent keeps `long`, the same split Claude Code makes between its main
|
|
7
7
|
* conversation and its subagents.
|
|
8
8
|
*
|
|
9
|
-
* Unset means children inherit the parent's retention
|
|
10
|
-
* before this setting existed.
|
|
9
|
+
* Unset means children inherit the parent's retention.
|
|
11
10
|
*/
|
|
12
11
|
export function childCacheRetention(env = process.env) {
|
|
13
12
|
return env.PI_SUBAGENT_CACHE_RETENTION || undefined;
|