@xzzpig/pi-subagents 0.7.0 → 0.9.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 +456 -4
- package/README.md +3 -3
- package/agents/claude-code-writer.md +15 -0
- package/agents/claude-code.md +15 -0
- package/agents/codex-exec-writer.md +15 -0
- package/agents/codex-exec.md +15 -0
- package/agents/cursor-agent-writer.md +14 -0
- package/agents/cursor-agent.md +14 -0
- package/agents/reviewer.md +13 -3
- package/agents/scout.md +1 -1
- package/docs/agents.md +154 -42
- package/docs/configuration.md +85 -26
- package/docs/extension-api.md +81 -16
- package/docs/missions.md +2 -0
- package/docs/models.md +75 -11
- package/docs/observability.md +34 -21
- package/docs/tool-reference.md +142 -18
- package/docs/watchdog.md +92 -114
- package/docs/workflows.md +148 -4
- package/index.ts +10 -1
- package/install.mjs +1 -1
- package/package.json +7 -6
- package/prompts/council.md +19 -7
- package/prompts/parallel-review.md +5 -1
- package/prompts/review-loop.md +11 -7
- package/skills/council-mode/SKILL.md +44 -215
- package/skills/council-mode/references/pass-contracts.md +150 -0
- package/skills/pi-subagents/SKILL.md +90 -32
- package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
- package/skills/pi-subagents/references/execution-controls.md +104 -19
- package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
- package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
- package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
- package/skills/pi-subagents/references/review-and-validation.md +73 -0
- package/src/agents/agent-management.ts +471 -114
- package/src/agents/agent-refinements.ts +4 -4
- package/src/agents/agent-serializer.ts +16 -4
- package/src/agents/agents.ts +1076 -351
- package/src/agents/builtin-names.ts +6 -0
- package/src/agents/runtime-agent-events.ts +70 -0
- package/src/agents/runtime-agent-registry.ts +31 -20
- package/src/api/agents.ts +10 -5
- package/src/api/background-work.ts +12 -3
- package/src/api/capability-ceiling.ts +0 -1
- package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
- package/src/api/delegation.ts +0 -7
- package/src/api/external-job-provider.ts +10 -1
- package/src/api/external-runs.ts +67 -4
- package/src/api/preflight.ts +97 -34
- package/src/api/project-panes.ts +2 -0
- package/src/api/shared-types.ts +6 -0
- package/src/extension/config.ts +90 -0
- package/src/extension/doctor.ts +15 -13
- package/src/extension/fanout-child.ts +17 -16
- package/src/extension/index.ts +139 -41
- package/src/extension/public-execution.ts +113 -22
- package/src/extension/rpc.ts +182 -13
- package/src/extension/schemas.ts +63 -21
- package/src/extension/tool-description.ts +48 -23
- package/src/extension/tool-result.ts +19 -0
- package/src/inspectors/herdr/actions.ts +2 -1
- package/src/inspectors/herdr/client.ts +3 -3
- package/src/inspectors/herdr/focus.ts +55 -0
- package/src/inspectors/herdr/inspector-runner.ts +21 -23
- package/src/inspectors/herdr/project-panes.ts +228 -44
- package/src/inspectors/herdr/session-roots-codec.ts +42 -0
- package/src/integrations/herdr-status.ts +75 -5
- package/src/intercom/native-supervisor-channel.ts +138 -60
- package/src/intercom/result-intercom.ts +2 -0
- package/src/intercom/supervisor-ui.ts +243 -0
- package/src/profiles/profiles.ts +5 -6
- package/src/runs/background/active-async-capacity.ts +103 -18
- package/src/runs/background/async-execution.ts +492 -125
- package/src/runs/background/async-job-tracker.ts +127 -28
- package/src/runs/background/async-resume.ts +67 -29
- package/src/runs/background/async-retention.ts +21 -4
- package/src/runs/background/async-status-snapshot.ts +23 -261
- package/src/runs/background/async-status.ts +199 -14
- package/src/runs/background/auto-drain.ts +1 -1
- package/src/runs/background/chain-append.ts +8 -3
- package/src/runs/background/chain-root-attachment.ts +79 -8
- package/src/runs/background/control-channel.ts +101 -214
- package/src/runs/background/fleet-view.ts +38 -22
- package/src/runs/background/inspect-rpc.ts +8 -8
- package/src/runs/background/notify.ts +295 -8
- package/src/runs/background/process-terminal.ts +16 -0
- package/src/runs/background/result-delivery-ownership.ts +45 -0
- package/src/runs/background/result-files.ts +28 -14
- package/src/runs/background/result-watcher.ts +43 -19
- package/src/runs/background/resume-guidance.ts +2 -2
- package/src/runs/background/retained-children.ts +1 -1
- package/src/runs/background/run-child-session.ts +613 -0
- package/src/runs/background/run-status.ts +99 -18
- package/src/runs/background/runner-aliases.ts +125 -0
- package/src/runs/background/runner-child-sessions.ts +31 -0
- package/src/runs/background/scheduled-runs.ts +174 -18
- package/src/runs/background/stale-run-reconciler.ts +13 -4
- package/src/runs/background/steering.ts +8 -15
- package/src/runs/background/subagent-runner.ts +959 -1159
- package/src/runs/background/subagent-wait.ts +86 -31
- package/src/runs/background/terminal-run-index.ts +1 -1
- package/src/runs/background/wait-completions.ts +45 -2
- package/src/runs/background/wait-config.ts +23 -9
- package/src/runs/background/wait-tool.ts +27 -19
- package/src/runs/foreground/async-steering-action.ts +3 -19
- package/src/runs/foreground/async-stop-action.ts +23 -2
- package/src/runs/foreground/execution.ts +585 -481
- package/src/runs/foreground/foreground-control.ts +13 -0
- package/src/runs/foreground/foreground-history.ts +26 -3
- package/src/runs/foreground/subagent-executor.ts +1549 -410
- package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
- package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
- package/src/runs/shared/abort-recovery.ts +119 -0
- package/src/runs/shared/acceptance.ts +147 -39
- package/src/runs/shared/agent-contract.ts +1 -1
- package/src/runs/shared/async-status-projection.ts +565 -0
- package/src/runs/shared/background-process-options.ts +9 -0
- package/src/runs/shared/capability-ceiling.ts +2 -2
- package/src/runs/shared/child-hooks.ts +25 -0
- package/src/runs/shared/child-identity.ts +62 -0
- package/src/runs/shared/child-launch-plan.ts +151 -0
- package/src/runs/shared/child-launch.ts +314 -0
- package/src/runs/shared/child-lifecycle.ts +25 -0
- package/src/runs/shared/child-runtime-config.ts +126 -0
- package/src/runs/shared/child-session.ts +342 -0
- package/src/runs/shared/child-tool-plan.ts +540 -0
- package/src/runs/shared/claude-code-adapter.ts +133 -0
- package/src/runs/shared/codex-exec-adapter.ts +129 -0
- package/src/runs/shared/completion-evidence.ts +89 -0
- package/src/runs/shared/completion-guard.ts +57 -6
- package/src/runs/shared/cursor-agent-adapter.ts +114 -0
- package/src/runs/shared/dynamic-fanout.ts +4 -4
- package/src/runs/shared/extension-bindings.ts +78 -0
- package/src/runs/shared/external-cli-contract.ts +167 -0
- package/src/runs/shared/external-cli-preflight.ts +138 -0
- package/src/runs/shared/external-cli-runner.ts +349 -54
- package/src/runs/shared/external-job-bridge.ts +53 -37
- package/src/runs/shared/external-job-runner.ts +126 -23
- package/src/runs/shared/fast-mode-extension.ts +10 -0
- package/src/runs/shared/host-step-status.ts +231 -0
- package/src/runs/shared/lane-metadata.ts +126 -0
- package/src/runs/shared/launch-cwd.ts +16 -0
- package/src/runs/shared/long-running-guard.ts +2 -1
- package/src/runs/shared/mcp-config-sources.ts +422 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
- package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
- package/src/runs/shared/model-exclusions.ts +141 -10
- package/src/runs/shared/model-fallback.ts +187 -33
- package/src/runs/shared/model-scope.ts +106 -39
- package/src/runs/shared/mutation-evidence.ts +199 -0
- package/src/runs/shared/nested-events.ts +38 -48
- package/src/runs/shared/nested-path.ts +0 -14
- package/src/runs/shared/nested-render.ts +9 -5
- package/src/runs/shared/orca-progress-tabs.ts +83 -16
- package/src/runs/shared/parallel-handoff.ts +423 -7
- package/src/runs/shared/parallel-utils.ts +28 -5
- package/src/runs/shared/permissions.ts +1 -14
- package/src/runs/shared/pi-spawn.ts +69 -35
- package/src/runs/shared/process-signal.ts +16 -0
- package/src/runs/shared/run-fanout-budget.ts +0 -13
- package/src/runs/shared/run-history.ts +21 -1
- package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
- package/src/runs/shared/single-output.ts +89 -22
- package/src/runs/shared/structured-output.ts +61 -7
- package/src/runs/shared/subagent-control.ts +6 -2
- package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
- package/src/runs/shared/task-intent.ts +21 -7
- package/src/runs/shared/tool-availability.ts +18 -64
- package/src/runs/shared/tool-budget.ts +0 -14
- package/src/runs/shared/tool-timeout.ts +1 -1
- package/src/runs/shared/workflow-graph.ts +16 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
- package/src/runs/shared/worktree.ts +571 -62
- package/src/shared/atomic-json.ts +3 -1
- package/src/shared/child-session-name.ts +46 -0
- package/src/shared/extension-context.ts +24 -0
- package/src/shared/fork-context.ts +21 -12
- package/src/shared/fork-session-cwd.ts +27 -0
- package/src/shared/formatters.ts +18 -3
- package/src/shared/jsonl-writer.ts +11 -0
- package/src/shared/launch-contract.ts +20 -6
- package/src/shared/pruned-fork.ts +450 -0
- package/src/shared/session-file-trust.ts +19 -0
- package/src/shared/session-tokens.ts +14 -3
- package/src/shared/settings.ts +21 -102
- package/src/shared/shortcuts.ts +17 -0
- package/src/shared/thinking-ceiling.ts +46 -0
- package/src/shared/types.ts +644 -75
- package/src/shared/utils.ts +60 -93
- package/src/shared/workflow-child-permit.ts +207 -0
- package/src/slash/delegation-adapters.ts +1 -9
- package/src/slash/delegation-request.ts +0 -4
- package/src/slash/prompt-template-bridge.ts +37 -1
- package/src/slash/slash-bridge.ts +1 -2
- package/src/slash/slash-commands.ts +383 -116
- package/src/slash/slash-live-state.ts +22 -11
- package/src/slash/subagents-admin.ts +29 -12
- package/src/tui/fleet-native-transcript.ts +4 -0
- package/src/tui/fleet-status.ts +278 -90
- package/src/tui/fleet-transcript.ts +11 -5
- package/src/tui/fleet.ts +54 -28
- package/src/tui/render-helpers.ts +31 -0
- package/src/tui/render.ts +1433 -166
- package/src/watchdog/change-signature.ts +40 -1
- package/src/watchdog/child-status.ts +54 -34
- package/src/watchdog/diff-tool.ts +77 -0
- package/src/watchdog/emission-guard.ts +5 -3
- package/src/watchdog/guidance.ts +20 -0
- package/src/watchdog/permission-arbiter.ts +59 -52
- package/src/watchdog/register-child.ts +28 -25
- package/src/watchdog/register-main.ts +10 -9
- package/src/watchdog/render.ts +4 -5
- package/src/watchdog/review.ts +15 -4
- package/src/watchdog/rules.ts +70 -0
- package/src/watchdog/runtime.ts +75 -92
- package/src/watchdog/scope.ts +0 -11
- package/src/watchdog/settings.ts +48 -104
- package/src/watchdog/turn-delta.ts +1 -1
- package/src/watchdog/types.ts +18 -32
- package/src/watchdog/warning-format.ts +0 -1
- package/src/workflows/chat-progress.ts +7 -3
- package/src/workflows/host-command.ts +235 -0
- package/src/workflows/scripted-workflow.ts +1142 -69
- package/src/workflows/workflow-checklist.ts +439 -0
- package/src/workflows/workflow-child-summary.ts +121 -0
- package/src/workflows/workflow-preflight.ts +297 -0
- package/src/workflows/workflow-receipt.ts +232 -6
- package/src/workflows/workflow-resources.ts +150 -0
- package/src/workflows/workflow-settlement.ts +246 -0
- package/src/runs/shared/child-protocol.ts +0 -401
- package/src/runs/shared/pi-args.ts +0 -858
- package/src/runs/shared/subagent-startup-retry.ts +0 -116
- package/src/runs/shared/turn-budget.ts +0 -98
- package/src/shared/post-exit-stdio-guard.ts +0 -85
|
@@ -5,9 +5,7 @@ export type PermissionDecision = "allow" | "ask" | "deny";
|
|
|
5
5
|
export type PermissionRules = Record<string, PermissionDecision>;
|
|
6
6
|
export interface PermissionConfig { rules?: PermissionRules }
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
export const PERMISSION_AUDIT_PATH_ENV = "PI_SUBAGENT_PERMISSION_AUDIT_PATH";
|
|
10
|
-
const INTERNAL_TOOLS = new Set(["contact_supervisor", "intercom", "subagent_wait", "structured_output"]);
|
|
8
|
+
const INTERNAL_TOOLS = new Set(["contact_supervisor", "intercom", "bg_wait", "structured_output"]);
|
|
11
9
|
const DECISIONS = new Set<PermissionDecision>(["allow", "ask", "deny"]);
|
|
12
10
|
const MAX_POLICY_BYTES = 16 * 1024;
|
|
13
11
|
const MAX_PREVIEW_BYTES = 2048;
|
|
@@ -52,17 +50,6 @@ export function permissionDecision(rules: PermissionRules | undefined, toolName:
|
|
|
52
50
|
return rules?.[toolName] ?? "allow";
|
|
53
51
|
}
|
|
54
52
|
|
|
55
|
-
export function encodePermissionRules(rules: PermissionRules | undefined): string | undefined {
|
|
56
|
-
if (!rules || Object.keys(rules).length === 0) return undefined;
|
|
57
|
-
const encoded = JSON.stringify(rules);
|
|
58
|
-
if (Buffer.byteLength(encoded, "utf-8") > MAX_POLICY_BYTES) throw new Error("Resolved permission policy is too large.");
|
|
59
|
-
return encoded;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
export function decodePermissionRules(encoded: string | undefined): PermissionRules | undefined {
|
|
63
|
-
if (!encoded?.trim()) return undefined;
|
|
64
|
-
return validatePermissionRules(JSON.parse(encoded), PERMISSION_POLICY_ENV);
|
|
65
|
-
}
|
|
66
53
|
|
|
67
54
|
function redact(value: unknown, key = "", depth = 0): unknown {
|
|
68
55
|
if (SECRET_KEY.test(key)) return "[redacted]";
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
2
|
import * as path from "node:path";
|
|
3
3
|
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../../shared/utils.ts";
|
|
4
5
|
|
|
5
6
|
export const PI_CODING_AGENT_PACKAGE = "@earendil-works/pi-coding-agent";
|
|
6
7
|
export const PI_SUBAGENT_PI_BINARY_ENV = "PI_SUBAGENT_PI_BINARY";
|
|
@@ -23,9 +24,13 @@ export function findPiPackageRootFromEntry(
|
|
|
23
24
|
}
|
|
24
25
|
|
|
25
26
|
export function resolveInstalledPiPackageRoot(): string | undefined {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
27
|
+
try {
|
|
28
|
+
return findPiPackageRootFromEntry(
|
|
29
|
+
fileURLToPath(import.meta.resolve(PI_CODING_AGENT_PACKAGE)),
|
|
30
|
+
);
|
|
31
|
+
} catch {
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
29
34
|
}
|
|
30
35
|
|
|
31
36
|
export function resolvePiPackageRoot(): string | undefined {
|
|
@@ -58,12 +63,21 @@ interface PiSpawnCommand {
|
|
|
58
63
|
args: string[];
|
|
59
64
|
}
|
|
60
65
|
|
|
66
|
+
interface PiPackageJson {
|
|
67
|
+
name?: unknown;
|
|
68
|
+
bin?: string | Record<string, string>;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function isNodeScriptPath(filePath: string): boolean {
|
|
72
|
+
return /\.(?:mjs|cjs|js)$/i.test(filePath);
|
|
73
|
+
}
|
|
74
|
+
|
|
61
75
|
function isRunnableNodeScript(
|
|
62
76
|
filePath: string,
|
|
63
77
|
existsSync: (filePath: string) => boolean,
|
|
64
78
|
): boolean {
|
|
65
79
|
if (!existsSync(filePath)) return false;
|
|
66
|
-
return
|
|
80
|
+
return isNodeScriptPath(filePath);
|
|
67
81
|
}
|
|
68
82
|
|
|
69
83
|
function normalizePath(filePath: string): string {
|
|
@@ -75,6 +89,23 @@ function isStandalonePiExecutable(execPath: string): boolean {
|
|
|
75
89
|
return /^pi(?:\.exe)?$/i.test(executableName ?? "");
|
|
76
90
|
}
|
|
77
91
|
|
|
92
|
+
function resolvePiCliScriptFromPackageJson(
|
|
93
|
+
packageJsonPath: string,
|
|
94
|
+
readFileSync: (filePath: string, encoding: "utf-8") => string,
|
|
95
|
+
existsSync: (filePath: string) => boolean,
|
|
96
|
+
): string | undefined {
|
|
97
|
+
const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8")) as PiPackageJson;
|
|
98
|
+
if (packageJson.name !== PI_CODING_AGENT_PACKAGE) return undefined;
|
|
99
|
+
const binField = packageJson.bin;
|
|
100
|
+
const binPath =
|
|
101
|
+
typeof binField === "string"
|
|
102
|
+
? binField
|
|
103
|
+
: (binField?.pi ?? Object.values(binField ?? {})[0]);
|
|
104
|
+
if (!binPath) return undefined;
|
|
105
|
+
const candidate = path.resolve(path.dirname(packageJsonPath), binPath);
|
|
106
|
+
return isRunnableNodeScript(candidate, existsSync) ? candidate : undefined;
|
|
107
|
+
}
|
|
108
|
+
|
|
78
109
|
export function resolvePiCliScript(
|
|
79
110
|
deps: PiSpawnDeps = {},
|
|
80
111
|
): string | undefined {
|
|
@@ -84,6 +115,7 @@ export function resolvePiCliScript(
|
|
|
84
115
|
deps.readFileSync ??
|
|
85
116
|
((filePath, encoding) => fs.readFileSync(filePath, encoding));
|
|
86
117
|
const argv1 = deps.argv1 ?? process.argv[1];
|
|
118
|
+
const env = deps.env ?? process.env;
|
|
87
119
|
|
|
88
120
|
if (argv1) {
|
|
89
121
|
const argvPath = normalizePath(argv1);
|
|
@@ -99,38 +131,28 @@ export function resolvePiCliScript(
|
|
|
99
131
|
}
|
|
100
132
|
}
|
|
101
133
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
typeof binField === "string"
|
|
124
|
-
? binField
|
|
125
|
-
: (binField?.pi ?? Object.values(binField ?? {})[0]);
|
|
126
|
-
if (!binPath) return undefined;
|
|
127
|
-
const candidate = path.resolve(path.dirname(packageJsonPath), binPath);
|
|
128
|
-
if (isRunnableNodeScript(candidate, existsSync)) {
|
|
129
|
-
return candidate;
|
|
134
|
+
const packageJsonCandidates: Array<() => string | undefined> = [];
|
|
135
|
+
if (deps.resolvePackageJson) packageJsonCandidates.push(deps.resolvePackageJson);
|
|
136
|
+
for (const root of [deps.piPackageRoot, env[PI_CODING_AGENT_PACKAGE_ROOT_ENV], resolvePiPackageRoot()]) {
|
|
137
|
+
const trimmed = root?.trim();
|
|
138
|
+
if (trimmed) packageJsonCandidates.push(() => path.join(trimmed, "package.json"));
|
|
139
|
+
}
|
|
140
|
+
packageJsonCandidates.push(() => {
|
|
141
|
+
const packageRoot = deps.resolvePackageEntry
|
|
142
|
+
? findPiPackageRootFromEntry(deps.resolvePackageEntry())
|
|
143
|
+
: resolveInstalledPiPackageRoot();
|
|
144
|
+
return packageRoot ? path.join(packageRoot, "package.json") : undefined;
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
for (const candidatePackageJson of packageJsonCandidates) {
|
|
148
|
+
try {
|
|
149
|
+
const packageJsonPath = candidatePackageJson();
|
|
150
|
+
if (!packageJsonPath) continue;
|
|
151
|
+
const candidate = resolvePiCliScriptFromPackageJson(packageJsonPath, readFileSync, existsSync);
|
|
152
|
+
if (candidate) return candidate;
|
|
153
|
+
} catch {
|
|
154
|
+
// Keep resolving; callers decide whether a PATH fallback is safe.
|
|
130
155
|
}
|
|
131
|
-
} catch {
|
|
132
|
-
// Verified CLI resolution is optional; falling back to `pi` lets PATH handle execution.
|
|
133
|
-
return undefined;
|
|
134
156
|
}
|
|
135
157
|
|
|
136
158
|
return undefined;
|
|
@@ -140,9 +162,16 @@ export function getPiSpawnCommand(
|
|
|
140
162
|
args: string[],
|
|
141
163
|
deps: PiSpawnDeps = {},
|
|
142
164
|
): PiSpawnCommand {
|
|
165
|
+
const platform = deps.platform ?? process.platform;
|
|
143
166
|
const env = deps.env ?? process.env;
|
|
144
167
|
const piBinary = env[PI_SUBAGENT_PI_BINARY_ENV]?.trim();
|
|
145
168
|
if (piBinary) {
|
|
169
|
+
if (platform === "win32" && isNodeScriptPath(piBinary)) {
|
|
170
|
+
return {
|
|
171
|
+
command: deps.execPath ?? process.execPath,
|
|
172
|
+
args: [piBinary, ...args],
|
|
173
|
+
};
|
|
174
|
+
}
|
|
146
175
|
return { command: piBinary, args };
|
|
147
176
|
}
|
|
148
177
|
|
|
@@ -158,6 +187,11 @@ export function getPiSpawnCommand(
|
|
|
158
187
|
args: [piCliPath, ...args],
|
|
159
188
|
};
|
|
160
189
|
}
|
|
190
|
+
if (platform === "win32") {
|
|
191
|
+
throw new Error(
|
|
192
|
+
`Could not resolve the Pi CLI on Windows. Set ${PI_SUBAGENT_PI_BINARY_ENV} or ensure ${PI_CODING_AGENT_PACKAGE} is installed.`,
|
|
193
|
+
);
|
|
194
|
+
}
|
|
161
195
|
|
|
162
196
|
return { command: "pi", args };
|
|
163
197
|
}
|
|
@@ -2,6 +2,22 @@ export function formatProcessSignalError(signal: string): string {
|
|
|
2
2
|
return `Subagent process terminated by signal ${signal}.`;
|
|
3
3
|
}
|
|
4
4
|
|
|
5
|
+
export function formatMidToolExitError(input: {
|
|
6
|
+
toolName: string;
|
|
7
|
+
exitCode?: number | null;
|
|
8
|
+
processSignal?: string | null;
|
|
9
|
+
}): string {
|
|
10
|
+
if (input.exitCode === undefined && !input.processSignal) {
|
|
11
|
+
return `Subagent session ended during '${input.toolName}' tool execution before the tool completed. Earlier assistant output is not a terminal result.`;
|
|
12
|
+
}
|
|
13
|
+
const terminal = [`exit ${input.exitCode ?? "unknown"}`, ...(input.processSignal ? [`signal ${input.processSignal}`] : [])].join(", ");
|
|
14
|
+
return `Subagent process exited during '${input.toolName}' tool execution (${terminal}) before the tool completed. Earlier assistant output is not a terminal result.`;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function isOrdinaryToolForMidToolExit(toolName: string): boolean {
|
|
18
|
+
return toolName !== "intercom" && toolName !== "contact_supervisor";
|
|
19
|
+
}
|
|
20
|
+
|
|
5
21
|
export function isUnexplainedProcessSignal(input: {
|
|
6
22
|
processSignal?: string | null;
|
|
7
23
|
interrupted?: boolean;
|
|
@@ -9,7 +9,6 @@ import {
|
|
|
9
9
|
type RunFanoutRejection,
|
|
10
10
|
} from "../../shared/types.ts";
|
|
11
11
|
|
|
12
|
-
export const RUN_FANOUT_BUDGET_ENV = "PI_SUBAGENT_RUN_FANOUT_BUDGET";
|
|
13
12
|
const RUN_FANOUT_ROOT = path.join(TEMP_ROOT_DIR, "run-fanout-budgets");
|
|
14
13
|
|
|
15
14
|
interface ManifestV1 {
|
|
@@ -124,18 +123,6 @@ export function readRunFanoutBudgetDescriptor(asyncDir: string | undefined): Run
|
|
|
124
123
|
}
|
|
125
124
|
}
|
|
126
125
|
|
|
127
|
-
export function encodeRunFanoutBudgetDescriptor(descriptor: RunFanoutBudgetDescriptor): string {
|
|
128
|
-
return Buffer.from(JSON.stringify(validateRunFanoutBudgetDescriptor(descriptor)), "utf-8").toString("base64url");
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
export function decodeRunFanoutBudgetDescriptor(encoded: string | undefined): RunFanoutBudgetDescriptor | undefined {
|
|
132
|
-
if (!encoded) return undefined;
|
|
133
|
-
try {
|
|
134
|
-
return validateRunFanoutBudgetDescriptor(JSON.parse(Buffer.from(encoded, "base64url").toString("utf-8")));
|
|
135
|
-
} catch (error) {
|
|
136
|
-
throw new Error(`Invalid inherited run fan-out budget: ${error instanceof Error ? error.message : String(error)}`);
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
126
|
|
|
140
127
|
interface AdmissionLockOwner {
|
|
141
128
|
pid: number;
|
|
@@ -2,6 +2,9 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
3
|
import * as path from "node:path";
|
|
4
4
|
import { getAgentDir } from "../../shared/utils.ts";
|
|
5
|
+
import { isUnexplainedProcessSignal } from "./process-signal.ts";
|
|
6
|
+
|
|
7
|
+
export type RunOutcome = "completed" | "failed" | "timed_out" | "stopped" | "interrupted";
|
|
5
8
|
|
|
6
9
|
export interface RunEntry {
|
|
7
10
|
agent: string;
|
|
@@ -9,6 +12,7 @@ export interface RunEntry {
|
|
|
9
12
|
taskHash?: string;
|
|
10
13
|
ts: number;
|
|
11
14
|
status: "ok" | "error";
|
|
15
|
+
outcome?: RunOutcome;
|
|
12
16
|
duration: number;
|
|
13
17
|
exit?: number;
|
|
14
18
|
}
|
|
@@ -129,14 +133,30 @@ function appendPrivateHistoryLine(historyPath: string, line: string): void {
|
|
|
129
133
|
}
|
|
130
134
|
}
|
|
131
135
|
|
|
132
|
-
export function recordRun(
|
|
136
|
+
export function recordRun(
|
|
137
|
+
agent: string,
|
|
138
|
+
task: string,
|
|
139
|
+
exitCode: number,
|
|
140
|
+
durationMs: number,
|
|
141
|
+
terminal: { interrupted?: boolean; processSignal?: string | null; stopped?: boolean; timedOut?: boolean; turnBudgetExceeded?: boolean } = {},
|
|
142
|
+
): void {
|
|
133
143
|
try {
|
|
144
|
+
const outcome: RunOutcome = terminal.stopped
|
|
145
|
+
? "stopped"
|
|
146
|
+
: terminal.interrupted
|
|
147
|
+
? "interrupted"
|
|
148
|
+
: terminal.timedOut
|
|
149
|
+
? "timed_out"
|
|
150
|
+
: exitCode !== 0 && isUnexplainedProcessSignal(terminal)
|
|
151
|
+
? "stopped"
|
|
152
|
+
: exitCode === 0 ? "completed" : "failed";
|
|
134
153
|
const entry: RunEntry = {
|
|
135
154
|
agent,
|
|
136
155
|
task: REDACTED_TASK,
|
|
137
156
|
taskHash: hashTask(task),
|
|
138
157
|
ts: Math.floor(Date.now() / 1000),
|
|
139
158
|
status: exitCode === 0 ? "ok" : "error",
|
|
159
|
+
outcome,
|
|
140
160
|
duration: durationMs,
|
|
141
161
|
...(exitCode !== 0 ? { exit: exitCode } : {}),
|
|
142
162
|
};
|
|
@@ -1,13 +1,8 @@
|
|
|
1
|
-
import * as fs from "node:fs";
|
|
2
|
-
import * as path from "node:path";
|
|
3
1
|
import type { RuntimeAcknowledgedChildExtensionsV1 } from "../../shared/types.ts";
|
|
4
2
|
|
|
5
3
|
export const RUNTIME_EXTENSION_ACK_EVENT = "subagent:acknowledge-extension";
|
|
6
|
-
export const RUNTIME_EXTENSION_ACK_PATH_ENV = "PI_SUBAGENT_RUNTIME_ACKNOWLEDGED_EXTENSIONS";
|
|
7
4
|
export const MAX_RUNTIME_ACKNOWLEDGED_EXTENSION_IDS = 32;
|
|
8
5
|
export const MAX_RUNTIME_ACKNOWLEDGED_EXTENSION_ID_LENGTH = 128;
|
|
9
|
-
// Generous bound for a valid capture (32 ids x 128 chars plus envelope); larger files are child misbehavior.
|
|
10
|
-
export const MAX_RUNTIME_ACKNOWLEDGED_EXTENSION_FILE_BYTES = 64 * 1024;
|
|
11
6
|
|
|
12
7
|
export function isRuntimeAcknowledgedExtensionId(value: unknown): value is string {
|
|
13
8
|
return typeof value === "string"
|
|
@@ -47,25 +42,3 @@ export function sanitizeRuntimeAcknowledgedExtensions(value: unknown): RuntimeAc
|
|
|
47
42
|
: 0;
|
|
48
43
|
return { ...projected, omitted: projected.omitted + omitted };
|
|
49
44
|
}
|
|
50
|
-
|
|
51
|
-
export function readRuntimeAcknowledgedExtensions(filePath: string | undefined): RuntimeAcknowledgedChildExtensionsV1 | undefined {
|
|
52
|
-
if (!filePath) return undefined;
|
|
53
|
-
try {
|
|
54
|
-
if (fs.statSync(filePath).size > MAX_RUNTIME_ACKNOWLEDGED_EXTENSION_FILE_BYTES) return undefined;
|
|
55
|
-
const parsed = JSON.parse(fs.readFileSync(filePath, "utf-8")) as unknown;
|
|
56
|
-
return sanitizeRuntimeAcknowledgedExtensions(parsed);
|
|
57
|
-
} catch {
|
|
58
|
-
return undefined;
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
export function writeRuntimeAcknowledgedExtensions(filePath: string, ids: Iterable<unknown>): void {
|
|
63
|
-
const projection = projectRuntimeAcknowledgedExtensions(ids);
|
|
64
|
-
try {
|
|
65
|
-
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
66
|
-
if (projection) fs.writeFileSync(filePath, JSON.stringify(projection), { mode: 0o600 });
|
|
67
|
-
else fs.rmSync(filePath, { force: true });
|
|
68
|
-
} catch {
|
|
69
|
-
// Runtime acknowledgement is best-effort observability only.
|
|
70
|
-
}
|
|
71
|
-
}
|
|
@@ -8,6 +8,17 @@ export interface SingleOutputSnapshot {
|
|
|
8
8
|
exists: boolean;
|
|
9
9
|
mtimeMs?: number;
|
|
10
10
|
size?: number;
|
|
11
|
+
error?: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function missingFileStatError(error: unknown): boolean {
|
|
15
|
+
const code = (error as NodeJS.ErrnoException | undefined)?.code;
|
|
16
|
+
return code === "ENOENT" || code === "ENOTDIR";
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function snapshotFromStatError(error: unknown): SingleOutputSnapshot {
|
|
20
|
+
if (missingFileStatError(error)) return { exists: false };
|
|
21
|
+
return { exists: false, error: error instanceof Error ? error.message : String(error) };
|
|
11
22
|
}
|
|
12
23
|
|
|
13
24
|
/**
|
|
@@ -96,6 +107,23 @@ function formatOutputPathInstruction(outputPath: string, capabilities?: OutputIn
|
|
|
96
107
|
].join("\n");
|
|
97
108
|
}
|
|
98
109
|
|
|
110
|
+
export function requestedOutputPathFromTask(task: string): string | undefined {
|
|
111
|
+
for (const line of task.split(/\r?\n/).reverse()) {
|
|
112
|
+
const match = line.match(/^\s*(?:Write your findings to(?: exactly this path)?:|The runtime will persist it to exactly this path:)\s*(.+?)\s*$/i);
|
|
113
|
+
if (!match?.[1]) continue;
|
|
114
|
+
const requested = match[1].trim();
|
|
115
|
+
return requested.startsWith("`") && requested.endsWith("`") ? requested.slice(1, -1) : requested;
|
|
116
|
+
}
|
|
117
|
+
return undefined;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function outputPathMappingFromTask(task: string, savedPath: string | undefined): { requestedPath: string; savedPath: string } | undefined {
|
|
121
|
+
const requestedPath = requestedOutputPathFromTask(task);
|
|
122
|
+
if (!requestedPath || !savedPath) return undefined;
|
|
123
|
+
if (path.isAbsolute(requestedPath) && path.normalize(requestedPath) === path.normalize(savedPath)) return undefined;
|
|
124
|
+
return { requestedPath, savedPath };
|
|
125
|
+
}
|
|
126
|
+
|
|
99
127
|
export function injectSingleOutputInstruction(task: string, outputPath: string | undefined, capabilities?: OutputInstructionCapabilities): string {
|
|
100
128
|
if (!outputPath) return task;
|
|
101
129
|
return `${task}\n\n---\n**Output:**\n${formatOutputPathInstruction(outputPath, capabilities)}`;
|
|
@@ -144,23 +172,67 @@ export function validateFileOnlyOutputMode(outputMode: OutputMode | undefined, o
|
|
|
144
172
|
return undefined;
|
|
145
173
|
}
|
|
146
174
|
|
|
175
|
+
export function resolveSingleOutputClaimPath(outputPath: string): string {
|
|
176
|
+
let existing = path.resolve(outputPath);
|
|
177
|
+
const missingSegments: string[] = [];
|
|
178
|
+
while (!fs.existsSync(existing)) {
|
|
179
|
+
missingSegments.unshift(path.basename(existing));
|
|
180
|
+
const parent = path.dirname(existing);
|
|
181
|
+
if (parent === existing) break;
|
|
182
|
+
existing = parent;
|
|
183
|
+
}
|
|
184
|
+
return path.join(fs.realpathSync(existing), ...missingSegments);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function outputClaimError(outputPath: string, expectedClaimPath: string | undefined): string | undefined {
|
|
188
|
+
if (expectedClaimPath && resolveSingleOutputClaimPath(outputPath) !== expectedClaimPath) return "Output path changed after it was claimed.";
|
|
189
|
+
return undefined;
|
|
190
|
+
}
|
|
191
|
+
|
|
147
192
|
export function captureSingleOutputSnapshot(outputPath: string | undefined): SingleOutputSnapshot | undefined {
|
|
148
193
|
if (!outputPath) return undefined;
|
|
149
194
|
try {
|
|
150
195
|
const stat = fs.statSync(outputPath);
|
|
151
196
|
return { exists: true, mtimeMs: stat.mtimeMs, size: stat.size };
|
|
152
|
-
} catch {
|
|
153
|
-
|
|
154
|
-
|
|
197
|
+
} catch (error) {
|
|
198
|
+
return snapshotFromStatError(error);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function inspectSingleOutputChange(
|
|
203
|
+
outputPath: string,
|
|
204
|
+
beforeRun: SingleOutputSnapshot | undefined,
|
|
205
|
+
): { changed: boolean; error?: string } {
|
|
206
|
+
if (beforeRun?.error) return { changed: false, error: beforeRun.error };
|
|
207
|
+
try {
|
|
208
|
+
const stat = fs.statSync(outputPath);
|
|
209
|
+
return {
|
|
210
|
+
changed: !beforeRun?.exists || stat.mtimeMs !== beforeRun.mtimeMs || stat.size !== beforeRun.size,
|
|
211
|
+
};
|
|
212
|
+
} catch (error) {
|
|
213
|
+
if (missingFileStatError(error)) return { changed: false };
|
|
214
|
+
return { changed: false, error: error instanceof Error ? error.message : String(error) };
|
|
155
215
|
}
|
|
156
216
|
}
|
|
157
217
|
|
|
218
|
+
export function hasSingleOutputChangedSinceSnapshot(
|
|
219
|
+
outputPath: string | undefined,
|
|
220
|
+
beforeRun: SingleOutputSnapshot | undefined,
|
|
221
|
+
): boolean | undefined {
|
|
222
|
+
if (!outputPath) return undefined;
|
|
223
|
+
const inspected = inspectSingleOutputChange(outputPath, beforeRun);
|
|
224
|
+
return inspected.error ? undefined : inspected.changed;
|
|
225
|
+
}
|
|
226
|
+
|
|
158
227
|
function persistSingleOutput(
|
|
159
228
|
outputPath: string | undefined,
|
|
160
229
|
fullOutput: string,
|
|
161
|
-
|
|
230
|
+
expectedClaimPath?: string,
|
|
231
|
+
): { savedPath?: string; error?: string; fatalError?: boolean } {
|
|
162
232
|
if (!outputPath) return {};
|
|
163
233
|
try {
|
|
234
|
+
const claimError = outputClaimError(outputPath, expectedClaimPath);
|
|
235
|
+
if (claimError) return { error: claimError, fatalError: true };
|
|
164
236
|
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
|
|
165
237
|
fs.writeFileSync(outputPath, fullOutput, "utf-8");
|
|
166
238
|
return { savedPath: outputPath };
|
|
@@ -173,26 +245,21 @@ export function resolveSingleOutput(
|
|
|
173
245
|
outputPath: string | undefined,
|
|
174
246
|
fallbackOutput: string,
|
|
175
247
|
beforeRun: SingleOutputSnapshot | undefined,
|
|
176
|
-
|
|
248
|
+
expectedClaimPath?: string,
|
|
249
|
+
): { fullOutput: string; savedPath?: string; saveError?: string; fatalError?: boolean } {
|
|
177
250
|
if (!outputPath) return { fullOutput: fallbackOutput };
|
|
251
|
+
const claimError = outputClaimError(outputPath, expectedClaimPath);
|
|
252
|
+
if (claimError) return { fullOutput: fallbackOutput, saveError: claimError, fatalError: true };
|
|
178
253
|
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
} catch (error) {
|
|
186
|
-
const code = error && typeof error === "object" && "code" in error ? (error as { code?: unknown }).code : undefined;
|
|
187
|
-
if (code !== "ENOENT" && code !== "ENOTDIR") {
|
|
188
|
-
return {
|
|
189
|
-
fullOutput: fallbackOutput,
|
|
190
|
-
saveError: `Failed to inspect output file: ${error instanceof Error ? error.message : String(error)}`,
|
|
191
|
-
};
|
|
192
|
-
}
|
|
254
|
+
const changedSinceStart = inspectSingleOutputChange(outputPath, beforeRun);
|
|
255
|
+
if (changedSinceStart.error) {
|
|
256
|
+
return {
|
|
257
|
+
fullOutput: fallbackOutput,
|
|
258
|
+
saveError: `Failed to inspect output file: ${changedSinceStart.error}`,
|
|
259
|
+
};
|
|
193
260
|
}
|
|
194
261
|
|
|
195
|
-
if (changedSinceStart) {
|
|
262
|
+
if (changedSinceStart.changed) {
|
|
196
263
|
try {
|
|
197
264
|
return { fullOutput: fs.readFileSync(outputPath, "utf-8"), savedPath: outputPath };
|
|
198
265
|
} catch (error) {
|
|
@@ -203,9 +270,9 @@ export function resolveSingleOutput(
|
|
|
203
270
|
}
|
|
204
271
|
}
|
|
205
272
|
|
|
206
|
-
const save = persistSingleOutput(outputPath, fallbackOutput);
|
|
273
|
+
const save = persistSingleOutput(outputPath, fallbackOutput, expectedClaimPath);
|
|
207
274
|
if (save.savedPath) return { fullOutput: fallbackOutput, savedPath: save.savedPath };
|
|
208
|
-
return { fullOutput: fallbackOutput, saveError: save.error };
|
|
275
|
+
return { fullOutput: fallbackOutput, saveError: save.error, ...(save.fatalError ? { fatalError: true } : {}) };
|
|
209
276
|
}
|
|
210
277
|
|
|
211
278
|
export function finalizeSingleOutput(params: {
|
|
@@ -5,15 +5,17 @@ import * as path from "node:path";
|
|
|
5
5
|
import { pathToFileURL } from "node:url";
|
|
6
6
|
import { PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../../shared/utils.ts";
|
|
7
7
|
import type { JsonSchemaObject } from "../../shared/types.ts";
|
|
8
|
+
import type { ResolvedAcceptanceReportMode } from "./acceptance.ts";
|
|
8
9
|
|
|
9
|
-
export const STRUCTURED_OUTPUT_SCHEMA_ENV = "PI_SUBAGENT_STRUCTURED_OUTPUT_SCHEMA";
|
|
10
|
-
export const STRUCTURED_OUTPUT_CAPTURE_ENV = "PI_SUBAGENT_STRUCTURED_OUTPUT_CAPTURE";
|
|
11
10
|
export const MISSING_STRUCTURED_OUTPUT_CALL_ERROR = "Missing structured_output call; this step has outputSchema and must finish by calling structured_output.";
|
|
11
|
+
export const MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR = "Missing acceptanceReport in structured_output call; acceptance.report is \"on\".";
|
|
12
12
|
|
|
13
13
|
export interface StructuredOutputRuntime {
|
|
14
14
|
schema: JsonSchemaObject;
|
|
15
15
|
schemaPath: string;
|
|
16
16
|
outputPath: string;
|
|
17
|
+
acceptanceReportPath?: string;
|
|
18
|
+
acceptanceReportRequired?: boolean;
|
|
17
19
|
}
|
|
18
20
|
|
|
19
21
|
const SCHEMA_MAP_KEYWORDS = ["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"] as const;
|
|
@@ -59,11 +61,14 @@ function rewriteLocalJsonPointerRefs(schema: unknown, pointerPrefix: string, inh
|
|
|
59
61
|
return rewritten;
|
|
60
62
|
}
|
|
61
63
|
|
|
62
|
-
export function createStructuredOutputToolParameters(schema: JsonSchemaObject): JsonSchemaObject {
|
|
64
|
+
export function createStructuredOutputToolParameters(schema: JsonSchemaObject, options: { acceptanceReport?: "optional" | "required" } = {}): JsonSchemaObject {
|
|
63
65
|
return {
|
|
64
66
|
type: "object",
|
|
65
|
-
properties: {
|
|
66
|
-
|
|
67
|
+
properties: {
|
|
68
|
+
value: rewriteLocalJsonPointerRefs(schema, "#/properties/value"),
|
|
69
|
+
...(options.acceptanceReport ? { acceptanceReport: { type: "object" } } : {}),
|
|
70
|
+
},
|
|
71
|
+
required: ["value", ...(options.acceptanceReport === "required" ? ["acceptanceReport"] : [])],
|
|
67
72
|
additionalProperties: false,
|
|
68
73
|
};
|
|
69
74
|
}
|
|
@@ -124,7 +129,7 @@ export function assertJsonSchemaObject(schema: unknown, label = "outputSchema"):
|
|
|
124
129
|
}
|
|
125
130
|
}
|
|
126
131
|
|
|
127
|
-
export function createStructuredOutputRuntime(schema: JsonSchemaObject, baseDir?: string): StructuredOutputRuntime {
|
|
132
|
+
export function createStructuredOutputRuntime(schema: JsonSchemaObject, baseDir?: string, options: { acceptanceReport?: ResolvedAcceptanceReportMode } = {}): StructuredOutputRuntime {
|
|
128
133
|
assertJsonSchemaObject(schema);
|
|
129
134
|
const rootDir = baseDir ?? os.tmpdir();
|
|
130
135
|
fs.mkdirSync(rootDir, { recursive: true });
|
|
@@ -132,7 +137,14 @@ export function createStructuredOutputRuntime(schema: JsonSchemaObject, baseDir?
|
|
|
132
137
|
const schemaPath = path.join(dir, "schema.json");
|
|
133
138
|
const outputPath = path.join(dir, "output.json");
|
|
134
139
|
fs.writeFileSync(schemaPath, JSON.stringify(schema), { mode: 0o600 });
|
|
135
|
-
return {
|
|
140
|
+
return {
|
|
141
|
+
schema,
|
|
142
|
+
schemaPath,
|
|
143
|
+
outputPath,
|
|
144
|
+
...(options.acceptanceReport && options.acceptanceReport !== "off"
|
|
145
|
+
? { acceptanceReportPath: path.join(dir, "acceptance-report.json"), acceptanceReportRequired: options.acceptanceReport === "required" }
|
|
146
|
+
: {}),
|
|
147
|
+
};
|
|
136
148
|
}
|
|
137
149
|
|
|
138
150
|
export async function validateStructuredOutputValue(schema: JsonSchemaObject, value: unknown): Promise<{ status: "valid" } | { status: "invalid"; message: string }> {
|
|
@@ -172,6 +184,48 @@ export async function readStructuredOutput(runtime: StructuredOutputRuntime): Pr
|
|
|
172
184
|
return { value };
|
|
173
185
|
}
|
|
174
186
|
|
|
187
|
+
export function readStructuredOutputAcceptanceReport(runtime: StructuredOutputRuntime): { value?: unknown; error?: string } {
|
|
188
|
+
if (!runtime.acceptanceReportPath) return {};
|
|
189
|
+
if (!fs.existsSync(runtime.acceptanceReportPath)) {
|
|
190
|
+
return runtime.acceptanceReportRequired ? { error: MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR } : {};
|
|
191
|
+
}
|
|
192
|
+
try {
|
|
193
|
+
return { value: JSON.parse(fs.readFileSync(runtime.acceptanceReportPath, "utf-8")) as unknown };
|
|
194
|
+
} catch (error) {
|
|
195
|
+
return { error: `Failed to read structured output acceptance report: ${error instanceof Error ? error.message : String(error)}` };
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Capture callback that persists the structured output (and acceptance report)
|
|
201
|
+
* to the runtime's files, for hosts that read the value back from disk.
|
|
202
|
+
*/
|
|
203
|
+
export function createStructuredOutputFileCapture(runtime: StructuredOutputRuntime): (value: unknown, acceptanceReport: unknown | undefined) => void {
|
|
204
|
+
return (value, acceptanceReport) => {
|
|
205
|
+
fs.mkdirSync(path.dirname(runtime.outputPath), { recursive: true });
|
|
206
|
+
if (runtime.acceptanceReportPath && acceptanceReport !== undefined) {
|
|
207
|
+
fs.mkdirSync(path.dirname(runtime.acceptanceReportPath), { recursive: true });
|
|
208
|
+
fs.writeFileSync(runtime.acceptanceReportPath, JSON.stringify(acceptanceReport), { mode: 0o600 });
|
|
209
|
+
} else if (runtime.acceptanceReportPath && fs.existsSync(runtime.acceptanceReportPath)) {
|
|
210
|
+
fs.unlinkSync(runtime.acceptanceReportPath);
|
|
211
|
+
}
|
|
212
|
+
fs.writeFileSync(runtime.outputPath, JSON.stringify(value), { mode: 0o600 });
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function clearStructuredOutputCaptures(runtime: StructuredOutputRuntime): string | undefined {
|
|
217
|
+
let cleanupError: string | undefined;
|
|
218
|
+
for (const filePath of [runtime.outputPath, runtime.acceptanceReportPath]) {
|
|
219
|
+
if (!filePath) continue;
|
|
220
|
+
try {
|
|
221
|
+
if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
|
|
222
|
+
} catch (error) {
|
|
223
|
+
cleanupError ??= `Failed to clear stale structured output capture ${filePath}: ${error instanceof Error ? error.message : String(error)}`;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return cleanupError;
|
|
227
|
+
}
|
|
228
|
+
|
|
175
229
|
export function cleanupStructuredOutputRuntime(runtime: StructuredOutputRuntime | undefined): void {
|
|
176
230
|
if (!runtime) return;
|
|
177
231
|
try {
|
|
@@ -45,11 +45,12 @@ export function resolveControlConfig(
|
|
|
45
45
|
const enabled = override?.enabled ?? globalConfig?.enabled ?? DEFAULT_CONTROL_CONFIG.enabled;
|
|
46
46
|
const overrideNeedsAttentionAfterMs = parsePositiveInt(override?.needsAttentionAfterMs);
|
|
47
47
|
const globalNeedsAttentionAfterMs = parsePositiveInt(globalConfig?.needsAttentionAfterMs);
|
|
48
|
+
const globalNeedsAttentionAfterMsIsExplicit = (globalConfig as Partial<ResolvedControlConfig> | undefined)?.needsAttentionAfterMsIsExplicit ?? globalNeedsAttentionAfterMs !== undefined;
|
|
48
49
|
const needsAttentionAfterMs = overrideNeedsAttentionAfterMs
|
|
49
50
|
?? globalNeedsAttentionAfterMs
|
|
50
51
|
?? DEFAULT_CONTROL_CONFIG.needsAttentionAfterMs;
|
|
51
52
|
const needsAttentionAfterMsIsExplicit = overrideNeedsAttentionAfterMs !== undefined
|
|
52
|
-
||
|
|
53
|
+
|| globalNeedsAttentionAfterMsIsExplicit;
|
|
53
54
|
const activeNoticeAfterMs = parsePositiveInt(override?.activeNoticeAfterMs)
|
|
54
55
|
?? parsePositiveInt(globalConfig?.activeNoticeAfterMs)
|
|
55
56
|
?? DEFAULT_CONTROL_CONFIG.activeNoticeAfterMs;
|
|
@@ -98,11 +99,12 @@ export function deriveActivityState(input: {
|
|
|
98
99
|
config: ResolvedControlConfig;
|
|
99
100
|
startedAt: number;
|
|
100
101
|
lastActivityAt?: number;
|
|
102
|
+
turnCount?: number;
|
|
101
103
|
currentTool?: string;
|
|
102
104
|
thinking?: string | false;
|
|
103
105
|
now?: number;
|
|
104
106
|
}): ActivityState | undefined {
|
|
105
|
-
if (!input.config.enabled || input.currentTool) return undefined;
|
|
107
|
+
if (!input.config.enabled || input.currentTool || (input.turnCount ?? 0) === 0) return undefined;
|
|
106
108
|
const now = input.now ?? Date.now();
|
|
107
109
|
const lastActivity = input.lastActivityAt ?? input.startedAt;
|
|
108
110
|
const ageMs = Math.max(0, now - lastActivity);
|
|
@@ -136,6 +138,7 @@ export function buildControlEvent(input: {
|
|
|
136
138
|
tokens?: number;
|
|
137
139
|
toolCount?: number;
|
|
138
140
|
currentTool?: string;
|
|
141
|
+
toolCallId?: string;
|
|
139
142
|
currentToolDurationMs?: number;
|
|
140
143
|
currentPath?: string;
|
|
141
144
|
elapsedMs?: number;
|
|
@@ -168,6 +171,7 @@ export function buildControlEvent(input: {
|
|
|
168
171
|
...(input.tokens !== undefined ? { tokens: input.tokens } : {}),
|
|
169
172
|
...(input.toolCount !== undefined ? { toolCount: input.toolCount } : {}),
|
|
170
173
|
...(input.currentTool ? { currentTool: input.currentTool } : {}),
|
|
174
|
+
...(input.toolCallId ? { toolCallId: input.toolCallId } : {}),
|
|
171
175
|
...(input.currentToolDurationMs !== undefined ? { currentToolDurationMs: input.currentToolDurationMs } : {}),
|
|
172
176
|
...(input.currentPath ? { currentPath: input.currentPath } : {}),
|
|
173
177
|
...(elapsedMs !== undefined ? { elapsedMs } : {}),
|