@xzzpig/pi-subagents 0.8.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 +443 -0
- package/README.md +2 -2
- 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 +1 -1
- package/agents/scout.md +1 -1
- package/docs/agents.md +151 -39
- package/docs/configuration.md +81 -22
- package/docs/extension-api.md +69 -14
- package/docs/missions.md +2 -0
- package/docs/models.md +32 -9
- package/docs/observability.md +22 -20
- package/docs/tool-reference.md +123 -14
- package/docs/watchdog.md +92 -114
- package/docs/workflows.md +142 -4
- package/install.mjs +1 -1
- package/package.json +5 -4
- package/prompts/review-loop.md +2 -2
- package/skills/council-mode/SKILL.md +48 -243
- package/skills/council-mode/references/pass-contracts.md +150 -0
- package/skills/pi-subagents/SKILL.md +89 -35
- package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
- package/skills/pi-subagents/references/execution-controls.md +91 -15
- package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
- package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
- package/skills/pi-subagents/references/review-and-validation.md +73 -0
- package/src/agents/agent-management.ts +370 -114
- package/src/agents/agent-refinements.ts +4 -4
- package/src/agents/agent-serializer.ts +12 -2
- package/src/agents/agents.ts +919 -372
- 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-runs.ts +67 -4
- package/src/api/preflight.ts +48 -18
- package/src/api/shared-types.ts +6 -0
- package/src/extension/config.ts +90 -0
- package/src/extension/doctor.ts +5 -13
- package/src/extension/fanout-child.ts +14 -14
- package/src/extension/index.ts +115 -37
- package/src/extension/public-execution.ts +103 -15
- package/src/extension/rpc.ts +120 -25
- package/src/extension/schemas.ts +57 -21
- package/src/extension/tool-description.ts +48 -26
- package/src/inspectors/herdr/actions.ts +2 -1
- package/src/inspectors/herdr/inspector-runner.ts +21 -23
- package/src/inspectors/herdr/session-roots-codec.ts +42 -0
- package/src/integrations/herdr-status.ts +51 -3
- 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 +366 -128
- package/src/runs/background/async-job-tracker.ts +95 -15
- package/src/runs/background/async-resume.ts +45 -28
- package/src/runs/background/async-retention.ts +20 -3
- package/src/runs/background/async-status-snapshot.ts +23 -261
- package/src/runs/background/async-status.ts +189 -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 +74 -8
- package/src/runs/background/control-channel.ts +4 -205
- package/src/runs/background/fleet-view.ts +38 -22
- package/src/runs/background/inspect-rpc.ts +8 -8
- package/src/runs/background/notify.ts +238 -12
- 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 +39 -16
- 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 +84 -17
- 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 +10 -4
- package/src/runs/background/steering.ts +8 -15
- package/src/runs/background/subagent-runner.ts +676 -1161
- 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 +43 -2
- package/src/runs/background/wait-config.ts +23 -9
- package/src/runs/background/wait-tool.ts +26 -19
- package/src/runs/foreground/async-steering-action.ts +3 -19
- package/src/runs/foreground/execution.ts +468 -499
- package/src/runs/foreground/foreground-control.ts +13 -0
- package/src/runs/foreground/foreground-history.ts +23 -1
- package/src/runs/foreground/subagent-executor.ts +1172 -400
- package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
- 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 +138 -36
- 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 +32 -6
- 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 +6 -5
- package/src/runs/shared/cursor-agent-adapter.ts +114 -0
- package/src/runs/shared/dynamic-fanout.ts +3 -3
- 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 +348 -55
- package/src/runs/shared/fast-mode-extension.ts +5 -5
- 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 +139 -9
- package/src/runs/shared/model-fallback.ts +142 -14
- package/src/runs/shared/mutation-evidence.ts +57 -3
- 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 +12 -7
- package/src/runs/shared/parallel-handoff.ts +423 -7
- package/src/runs/shared/parallel-utils.ts +15 -7
- 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 +49 -9
- package/src/runs/shared/subagent-control.ts +6 -2
- package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
- package/src/runs/shared/task-intent.ts +21 -7
- package/src/runs/shared/tool-availability.ts +18 -62
- 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 +8 -1
- 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 +19 -105
- package/src/shared/shortcuts.ts +17 -0
- package/src/shared/thinking-ceiling.ts +0 -6
- package/src/shared/types.ts +524 -70
- 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 +217 -82
- 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 +1429 -163
- 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/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 +988 -59
- 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 -935
- 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
|
@@ -2,6 +2,7 @@ import * as fs from "node:fs";
|
|
|
2
2
|
import * as path from "node:path";
|
|
3
3
|
import { splitKnownThinkingSuffix } from "../../shared/model-info.ts";
|
|
4
4
|
import { TEMP_ROOT_DIR } from "../../shared/types.ts";
|
|
5
|
+
import { getAgentDir } from "../../shared/utils.ts";
|
|
5
6
|
|
|
6
7
|
export const EXCLUSIONS_PATH_ENV = "PI_MODEL_EXCLUSIONS_PATH";
|
|
7
8
|
|
|
@@ -20,14 +21,67 @@ type RecordModelFailureOptions = ModelExclusionTarget & {
|
|
|
20
21
|
|
|
21
22
|
let exclusions: ModelExclusion[] = [];
|
|
22
23
|
let loaded = false;
|
|
23
|
-
|
|
24
|
+
/** Default duration for a new model exclusion when no per-record TTL is supplied. */
|
|
25
|
+
export const DEFAULT_MODEL_EXCLUSION_TTL_MS = 24 * 60 * 60_000;
|
|
26
|
+
/** Keeps a new expiry safely below JavaScript's maximum Date timestamp. */
|
|
27
|
+
export const MAX_MODEL_EXCLUSION_TTL_MS = 8_000_000_000_000_000;
|
|
28
|
+
const MAX_DATE_TIMESTAMP_MS = 8_640_000_000_000_000;
|
|
29
|
+
let defaultTTLMs = DEFAULT_MODEL_EXCLUSION_TTL_MS;
|
|
30
|
+
let loadedTTLCeilingMs: number | undefined;
|
|
24
31
|
let persistTimer: ReturnType<typeof setTimeout> | null = null;
|
|
25
32
|
let persistSeq = 0;
|
|
26
33
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
34
|
+
const AUTH_FAILURE_PATTERNS = [
|
|
35
|
+
/auth(?:entication)?/i,
|
|
36
|
+
/unauthori[sz]ed/i,
|
|
37
|
+
/forbidden/i,
|
|
38
|
+
/api key/i,
|
|
39
|
+
/token expired/i,
|
|
40
|
+
/invalid key/i,
|
|
41
|
+
];
|
|
42
|
+
|
|
43
|
+
function isAuthModelExclusion(entry: ModelExclusion): boolean {
|
|
44
|
+
const reason = entry.reason;
|
|
45
|
+
return typeof reason === "string" && AUTH_FAILURE_PATTERNS.some((pattern) => pattern.test(reason));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function getAuthStoreMtimeMs(): number | undefined {
|
|
49
|
+
const authStorePath = path.join(getAgentDir(), "auth.json");
|
|
50
|
+
try {
|
|
51
|
+
const stats = fs.statSync(authStorePath);
|
|
52
|
+
return stats.isFile() && Number.isFinite(stats.mtimeMs) ? stats.mtimeMs : undefined;
|
|
53
|
+
} catch (error) {
|
|
54
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
|
|
55
|
+
console.error(`[model-exclusions] Failed to stat Pi auth store at ${authStorePath}; preserving auth-related exclusions:`, error);
|
|
56
|
+
}
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function invalidateAuthExclusions(): void {
|
|
62
|
+
if (!exclusions.some(isAuthModelExclusion)) return;
|
|
63
|
+
const authStoreMtimeMs = getAuthStoreMtimeMs();
|
|
64
|
+
if (authStoreMtimeMs === undefined) return;
|
|
65
|
+
const retained = exclusions.filter((entry) => !isAuthModelExclusion(entry) || authStoreMtimeMs <= entry.recordedAt);
|
|
66
|
+
if (retained.length === exclusions.length) return;
|
|
67
|
+
exclusions = retained;
|
|
68
|
+
schedulePersist();
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Override the default TTL applied to newly recorded model exclusions.
|
|
73
|
+
*
|
|
74
|
+
* @param ms Duration in milliseconds. Must be finite and positive.
|
|
75
|
+
* @returns Nothing.
|
|
76
|
+
*/
|
|
77
|
+
// TEST:test/unit/model-exclusions.test.ts[model exclusions — TTL expiry]
|
|
78
|
+
export function setDefaultTTL(ms: number, options?: { shortenExisting?: boolean }): void {
|
|
79
|
+
if (!Number.isFinite(ms) || ms <= 0 || ms > MAX_MODEL_EXCLUSION_TTL_MS) {
|
|
80
|
+
throw new Error(`Default model exclusion TTL must be a finite positive number no greater than ${MAX_MODEL_EXCLUSION_TTL_MS}.`);
|
|
81
|
+
}
|
|
30
82
|
defaultTTLMs = ms;
|
|
83
|
+
loadedTTLCeilingMs = options?.shortenExisting ? ms : undefined;
|
|
84
|
+
if (loaded && loadedTTLCeilingMs !== undefined && shortenExclusionsToTTL(exclusions, loadedTTLCeilingMs, Date.now())) schedulePersist();
|
|
31
85
|
}
|
|
32
86
|
|
|
33
87
|
/**
|
|
@@ -78,10 +132,24 @@ function ensureLoaded(): void {
|
|
|
78
132
|
const raw = fs.readFileSync(getExclusionsFilePath(), "utf-8");
|
|
79
133
|
const data = JSON.parse(raw);
|
|
80
134
|
if (data.version === 1) {
|
|
135
|
+
if (!Array.isArray(data.exclusions)) throw new Error("Model exclusion store version 1 must contain an exclusions array.");
|
|
81
136
|
const now = Date.now();
|
|
82
|
-
|
|
137
|
+
let droppedInvalid = false;
|
|
138
|
+
exclusions = data.exclusions.flatMap((entry: unknown, index: number) => {
|
|
139
|
+
const result = readPersistedExclusion(entry, index);
|
|
140
|
+
if (!result.ok) {
|
|
141
|
+
droppedInvalid = true;
|
|
142
|
+
console.warn(`[model-exclusions] Ignoring invalid exclusion: ${result.message}`);
|
|
143
|
+
return [];
|
|
144
|
+
}
|
|
145
|
+
return [result.exclusion];
|
|
146
|
+
}).filter((e: ModelExclusion) => e.expiresAt > now);
|
|
147
|
+
const shortened = loadedTTLCeilingMs !== undefined && shortenExclusionsToTTL(exclusions, loadedTTLCeilingMs, now);
|
|
83
148
|
exclusions = deduplicate(exclusions);
|
|
149
|
+
if (droppedInvalid) flushPersist();
|
|
150
|
+
else if (shortened) schedulePersist();
|
|
84
151
|
}
|
|
152
|
+
invalidateAuthExclusions();
|
|
85
153
|
} catch (error) {
|
|
86
154
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
|
|
87
155
|
console.error(`[model-exclusions] Failed to load exclusions from ${getExclusionsFilePath()}:`, error);
|
|
@@ -89,6 +157,32 @@ function ensureLoaded(): void {
|
|
|
89
157
|
}
|
|
90
158
|
}
|
|
91
159
|
|
|
160
|
+
type PersistedExclusionRead =
|
|
161
|
+
| { ok: true; exclusion: ModelExclusion }
|
|
162
|
+
| { ok: false; message: string };
|
|
163
|
+
|
|
164
|
+
function invalidPersistedExclusion(index: number, message: string): PersistedExclusionRead {
|
|
165
|
+
return { ok: false, message: `Model exclusion store entry ${index} ${message}.` };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function readPersistedExclusion(entry: unknown, index: number): PersistedExclusionRead {
|
|
169
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) return invalidPersistedExclusion(index, "must be an object");
|
|
170
|
+
const candidate = entry as { modelId?: unknown; provider?: unknown; reason?: unknown; recordedAt?: unknown; expiresAt?: unknown };
|
|
171
|
+
const { modelId, provider, reason } = candidate;
|
|
172
|
+
if (modelId !== undefined && (typeof modelId !== "string" || modelId.length === 0)) return invalidPersistedExclusion(index, "has an invalid modelId");
|
|
173
|
+
if (provider !== undefined && (typeof provider !== "string" || provider.length === 0)) return invalidPersistedExclusion(index, "has an invalid provider");
|
|
174
|
+
if (reason !== undefined && typeof reason !== "string") return invalidPersistedExclusion(index, "has an invalid reason");
|
|
175
|
+
const { recordedAt, expiresAt } = candidate;
|
|
176
|
+
if (typeof recordedAt !== "number" || !Number.isFinite(recordedAt) || recordedAt <= 0 || recordedAt > MAX_DATE_TIMESTAMP_MS) return invalidPersistedExclusion(index, "has an invalid recordedAt");
|
|
177
|
+
if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt) || expiresAt <= 0 || expiresAt > MAX_DATE_TIMESTAMP_MS) return invalidPersistedExclusion(index, "has an invalid expiresAt");
|
|
178
|
+
const metadata = { ...(reason === undefined ? {} : { reason }), recordedAt, expiresAt };
|
|
179
|
+
if (modelId === undefined) {
|
|
180
|
+
if (provider === undefined) return invalidPersistedExclusion(index, "must include modelId or provider");
|
|
181
|
+
return { ok: true, exclusion: { provider, ...metadata } };
|
|
182
|
+
}
|
|
183
|
+
return { ok: true, exclusion: { modelId, ...(provider === undefined ? {} : { provider }), ...metadata } };
|
|
184
|
+
}
|
|
185
|
+
|
|
92
186
|
function dedupKey(entry: ModelExclusion): string {
|
|
93
187
|
return `${entry.provider ?? ""}|${entry.modelId ?? ""}`;
|
|
94
188
|
}
|
|
@@ -135,6 +229,7 @@ export function recordModelFailure(options: RecordModelFailureOptions): void {
|
|
|
135
229
|
*/
|
|
136
230
|
export function clearExpiredExclusions(): void {
|
|
137
231
|
ensureLoaded();
|
|
232
|
+
invalidateAuthExclusions();
|
|
138
233
|
prune(exclusions, Date.now());
|
|
139
234
|
schedulePersist();
|
|
140
235
|
}
|
|
@@ -160,7 +255,7 @@ export function clearExclusions(): void {
|
|
|
160
255
|
*/
|
|
161
256
|
function entryMatches(entry: ModelExclusion, candidateModelId: string, candidateProvider: string | undefined, now: number): boolean {
|
|
162
257
|
if (entry.expiresAt <= now) return false;
|
|
163
|
-
if (entry.modelId) {
|
|
258
|
+
if (entry.modelId !== undefined) {
|
|
164
259
|
if (entry.modelId !== candidateModelId) return false;
|
|
165
260
|
return !entry.provider || !candidateProvider || entry.provider === candidateProvider;
|
|
166
261
|
}
|
|
@@ -172,9 +267,23 @@ function entryMatches(entry: ModelExclusion, candidateModelId: string, candidate
|
|
|
172
267
|
*/
|
|
173
268
|
export function isExcluded(modelId: string, provider: string): boolean {
|
|
174
269
|
ensureLoaded();
|
|
270
|
+
invalidateAuthExclusions();
|
|
175
271
|
return exclusions.some((entry) => entryMatches(entry, modelId, provider, Date.now()));
|
|
176
272
|
}
|
|
177
273
|
|
|
274
|
+
/**
|
|
275
|
+
* Return the active exclusion matching a full model id, if any.
|
|
276
|
+
*
|
|
277
|
+
* The caller uses this for hard-fail diagnostics; fallback filtering should
|
|
278
|
+
* continue to use {@link filterFallbackCandidates}.
|
|
279
|
+
*/
|
|
280
|
+
export function findModelExclusion(fullId: string, now = Date.now()): Readonly<ModelExclusion> | undefined {
|
|
281
|
+
ensureLoaded();
|
|
282
|
+
invalidateAuthExclusions();
|
|
283
|
+
const { provider, modelId } = parseModelKey(fullId);
|
|
284
|
+
return exclusions.find((entry) => entryMatches(entry, modelId, provider, now));
|
|
285
|
+
}
|
|
286
|
+
|
|
178
287
|
/**
|
|
179
288
|
* Number of live (non-expired) exclusions.
|
|
180
289
|
*/
|
|
@@ -205,16 +314,23 @@ export function parseModelKey(fullId: string): { provider?: string; modelId: str
|
|
|
205
314
|
* Filter a list of candidate fullIds, removing excluded models/providers and
|
|
206
315
|
* duplicates while preserving order.
|
|
207
316
|
*/
|
|
208
|
-
export function filterFallbackCandidates(candidates: string[], opts?: {
|
|
317
|
+
export function filterFallbackCandidates(candidates: string[], opts?: {
|
|
318
|
+
now?: number;
|
|
319
|
+
onExcluded?: (candidate: string, exclusion: Readonly<ModelExclusion>) => void;
|
|
320
|
+
}): string[] {
|
|
209
321
|
ensureLoaded();
|
|
322
|
+
invalidateAuthExclusions();
|
|
210
323
|
const timestamp = opts?.now ?? Date.now();
|
|
211
324
|
const seen = new Set<string>();
|
|
212
325
|
const filtered: string[] = [];
|
|
213
326
|
for (const raw of candidates) {
|
|
214
327
|
if (!raw || seen.has(raw)) continue;
|
|
215
328
|
const { provider: candidateProvider, modelId: candidateModelId } = parseModelKey(raw);
|
|
216
|
-
const
|
|
217
|
-
if (
|
|
329
|
+
const exclusion = exclusions.find((entry) => entryMatches(entry, candidateModelId, candidateProvider, timestamp));
|
|
330
|
+
if (exclusion) {
|
|
331
|
+
opts?.onExcluded?.(raw, exclusion);
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
218
334
|
seen.add(raw);
|
|
219
335
|
filtered.push(raw);
|
|
220
336
|
}
|
|
@@ -241,3 +357,17 @@ function prune(items: ModelExclusion[], now: number): void {
|
|
|
241
357
|
}
|
|
242
358
|
items.length = write;
|
|
243
359
|
}
|
|
360
|
+
|
|
361
|
+
function shortenExclusionsToTTL(items: ModelExclusion[], ttlMs: number, now: number): boolean {
|
|
362
|
+
let changed = false;
|
|
363
|
+
for (const entry of items) {
|
|
364
|
+
const configuredExpiry = entry.recordedAt + ttlMs;
|
|
365
|
+
if (entry.expiresAt > configuredExpiry) {
|
|
366
|
+
entry.expiresAt = configuredExpiry;
|
|
367
|
+
changed = true;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
const previousLength = items.length;
|
|
371
|
+
prune(items, now);
|
|
372
|
+
return changed || items.length !== previousLength;
|
|
373
|
+
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { splitKnownThinkingSuffix, type ModelInfo as AvailableModelInfo } from "../../shared/model-info.ts";
|
|
2
2
|
import type { Usage } from "../../shared/types.ts";
|
|
3
|
-
import { filterFallbackCandidates, parseModelKey, recordModelFailure } from "./model-exclusions.ts";
|
|
3
|
+
import { filterFallbackCandidates, findModelExclusion, parseModelKey, recordModelFailure } from "./model-exclusions.ts";
|
|
4
4
|
import { checkModelScope, type ModelScopeCheckRule, type ModelScopeViolation, type ModelSource } from "./model-scope.ts";
|
|
5
|
+
import { redactSecretValues } from "./permissions.ts";
|
|
5
6
|
|
|
6
7
|
export type { AvailableModelInfo };
|
|
7
8
|
|
|
@@ -23,7 +24,12 @@ export function formatSubagentModelVerificationError(expectedModel: string, obse
|
|
|
23
24
|
const observedBase = splitThinkingSuffix(observedModel).baseModel;
|
|
24
25
|
if (expectedBase === observedBase) return undefined;
|
|
25
26
|
const expectedEntry = availableModels.find((entry) => entry.fullId === expectedBase);
|
|
26
|
-
if (expectedEntry
|
|
27
|
+
if (expectedEntry) {
|
|
28
|
+
if (expectedEntry.id === observedBase) return undefined;
|
|
29
|
+
const expectedIdLeaf = expectedEntry.id.slice(expectedEntry.id.lastIndexOf("/") + 1);
|
|
30
|
+
const expectedFullIdLeaf = expectedEntry.fullId.slice(expectedEntry.fullId.lastIndexOf("/") + 1);
|
|
31
|
+
if (expectedIdLeaf === observedBase || expectedFullIdLeaf === observedBase) return undefined;
|
|
32
|
+
}
|
|
27
33
|
return `model_verification_failed: child reported a different model than the launch candidate. Expected '${expectedModel}' but observed '${observedModel}'.`;
|
|
28
34
|
}
|
|
29
35
|
|
|
@@ -278,6 +284,39 @@ function enforceModelScopes(
|
|
|
278
284
|
for (const violation of violations) (onWarn ?? defaultScopeWarn)(violation);
|
|
279
285
|
}
|
|
280
286
|
|
|
287
|
+
const MODEL_EXCLUSION_DIAGNOSTIC_MAX_LENGTH = 240;
|
|
288
|
+
const MODEL_EXCLUSION_DIAGNOSTIC_MAX_ENTRIES = 20;
|
|
289
|
+
|
|
290
|
+
function sanitizeModelExclusionDiagnostic(value: string | undefined, fallback: string): string {
|
|
291
|
+
const normalized = typeof value === "string"
|
|
292
|
+
? value.replace(/[\u0000-\u001f\u007f\u2028\u2029]+/g, " ").trim()
|
|
293
|
+
: "";
|
|
294
|
+
return redactSecretValues(normalized || fallback).slice(0, MODEL_EXCLUSION_DIAGNOSTIC_MAX_LENGTH);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function formatModelExclusionExpiry(expiresAt: number): string {
|
|
298
|
+
if (!Number.isFinite(expiresAt)) return "unknown";
|
|
299
|
+
const date = new Date(expiresAt);
|
|
300
|
+
return Number.isNaN(date.getTime()) ? "unknown" : date.toISOString();
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function formatExcludedCandidateEvidence(candidate: string, exclusion: NonNullable<ReturnType<typeof findModelExclusion>>): string {
|
|
304
|
+
const { provider, modelId } = parseModelKey(candidate);
|
|
305
|
+
const displayCandidate = sanitizeModelExclusionDiagnostic(candidate, "unknown");
|
|
306
|
+
const displayModel = sanitizeModelExclusionDiagnostic(modelId, "unknown");
|
|
307
|
+
const displayProvider = sanitizeModelExclusionDiagnostic(provider ?? exclusion.provider, "unspecified");
|
|
308
|
+
const reason = sanitizeModelExclusionDiagnostic(exclusion.reason, "runtime-failure");
|
|
309
|
+
return `${displayCandidate} — model: ${displayModel}; provider: ${displayProvider}; reason: ${reason}; expires: ${formatModelExclusionExpiry(exclusion.expiresAt)}`;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function throwForExplicitModelExclusion(model: string): void {
|
|
313
|
+
const exclusion = findModelExclusion(model);
|
|
314
|
+
if (!exclusion) return;
|
|
315
|
+
const reason = redactSecretValues((exclusion.reason ?? "runtime-failure").replace(/[\u0000-\u001f\u007f]+/g, " ")).slice(0, 240);
|
|
316
|
+
const expiry = Number.isFinite(exclusion.expiresAt) ? `; expires: ${new Date(exclusion.expiresAt).toISOString()}` : "";
|
|
317
|
+
throw new Error(`Requested subagent model '${model}' is excluded and cannot be replaced by a fallback (reason: ${reason}${expiry}).`);
|
|
318
|
+
}
|
|
319
|
+
|
|
281
320
|
/**
|
|
282
321
|
* Resolve the `--model` override passed to a spawned subagent.
|
|
283
322
|
*
|
|
@@ -307,12 +346,23 @@ export function resolveSubagentModelOverride(
|
|
|
307
346
|
const explicit = trimmed && trimmed !== INHERIT_MODEL ? trimmed : undefined;
|
|
308
347
|
if (!parentModel) throwForUnresolvedEnforcedInheritScope(options?.scope, explicit === undefined || options?.source === "inherited");
|
|
309
348
|
let resolved: string | undefined;
|
|
349
|
+
let resolvedFromRegistry = explicit === undefined;
|
|
310
350
|
if (explicit === undefined) {
|
|
311
351
|
resolved = parentModel ? `${parentModel.provider}/${parentModel.id}` : undefined;
|
|
312
352
|
} else {
|
|
313
|
-
|
|
353
|
+
const candidate = resolveSubagentModelCandidate(explicit, availableModels, preferredProvider);
|
|
354
|
+
if (options?.source === "explicit") {
|
|
355
|
+
resolved = candidate ?? resolveRequiredSubagentModelCandidate(explicit, availableModels, preferredProvider);
|
|
356
|
+
throwForExplicitModelExclusion(resolved);
|
|
357
|
+
resolvedFromRegistry = true;
|
|
358
|
+
} else if (candidate) {
|
|
359
|
+
resolved = candidate;
|
|
360
|
+
resolvedFromRegistry = true;
|
|
361
|
+
} else {
|
|
362
|
+
resolved = explicit;
|
|
363
|
+
}
|
|
314
364
|
}
|
|
315
|
-
if (resolved && options?.scope) {
|
|
365
|
+
if (resolved && options?.scope && resolvedFromRegistry) {
|
|
316
366
|
const source: ModelSource = explicit === undefined ? "inherited" : (options.source ?? "inherited");
|
|
317
367
|
enforceModelScopes(resolved, options.scope, source, options.onWarn);
|
|
318
368
|
}
|
|
@@ -325,14 +375,15 @@ export function resolveEffectiveSubagentModel(
|
|
|
325
375
|
parentModel: ParentModel | undefined,
|
|
326
376
|
availableModels: AvailableModelInfo[] | undefined,
|
|
327
377
|
preferredProvider?: string,
|
|
328
|
-
options?:
|
|
378
|
+
options?: ResolveSubagentModelOverrideOptions,
|
|
329
379
|
): string | undefined {
|
|
380
|
+
const source = options?.source ?? (explicitModel !== undefined ? "explicit" : "inherited");
|
|
330
381
|
const resolved = resolveSubagentModelOverride(
|
|
331
382
|
explicitModel ?? agentModel,
|
|
332
383
|
parentModel,
|
|
333
384
|
availableModels,
|
|
334
385
|
preferredProvider,
|
|
335
|
-
{ ...options, source
|
|
386
|
+
{ ...options, source },
|
|
336
387
|
);
|
|
337
388
|
if (resolved || explicitModel === undefined) return resolved;
|
|
338
389
|
return resolveSubagentModelOverride(
|
|
@@ -340,16 +391,37 @@ export function resolveEffectiveSubagentModel(
|
|
|
340
391
|
parentModel,
|
|
341
392
|
availableModels,
|
|
342
393
|
preferredProvider,
|
|
343
|
-
{ ...options, source: "inherited" },
|
|
394
|
+
{ ...options, source: options?.source ?? "inherited" },
|
|
344
395
|
);
|
|
345
396
|
}
|
|
346
397
|
|
|
398
|
+
export type ModelOrigin = ModelSource | "configured";
|
|
399
|
+
|
|
347
400
|
export interface BuildModelCandidatesOptions {
|
|
348
401
|
/** Fallback models warn by default and throw when strict scope enforcement is enabled. */
|
|
349
402
|
scope?: ModelScopeCheckRule | ModelScopeCheckRule[];
|
|
350
403
|
onWarn?: (violation: ModelScopeViolation) => void;
|
|
351
404
|
/** The primary model came from the running parent session, not configuration. */
|
|
352
405
|
primaryModelFromParent?: boolean;
|
|
406
|
+
/** How the primary model was selected. Explicit stays strict and does not rotate to fallbacks. */
|
|
407
|
+
origin?: ModelOrigin;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
const ZERO_USABLE_MODEL_CANDIDATES_ERROR =
|
|
411
|
+
"No usable subagent models remain after registry, scope, and cached-exclusion filtering.";
|
|
412
|
+
|
|
413
|
+
export function resolveModelOrigin(input: {
|
|
414
|
+
explicitModel?: string | boolean;
|
|
415
|
+
agentModel?: string | boolean;
|
|
416
|
+
parentModel?: ParentModel;
|
|
417
|
+
fromParent?: boolean;
|
|
418
|
+
storedOrigin?: ModelOrigin;
|
|
419
|
+
}): ModelOrigin {
|
|
420
|
+
if (input.storedOrigin) return input.storedOrigin;
|
|
421
|
+
if (input.fromParent) return "inherited";
|
|
422
|
+
if (inheritsParentModel(input.explicitModel, input.agentModel, input.parentModel)) return "inherited";
|
|
423
|
+
const trimmed = typeof input.explicitModel === "string" ? input.explicitModel.trim() : "";
|
|
424
|
+
return trimmed && trimmed !== INHERIT_MODEL ? "explicit" : "configured";
|
|
353
425
|
}
|
|
354
426
|
|
|
355
427
|
export function inheritsParentModel(
|
|
@@ -370,31 +442,69 @@ export function buildModelCandidates(
|
|
|
370
442
|
options?: BuildModelCandidatesOptions,
|
|
371
443
|
): string[] {
|
|
372
444
|
if (!primaryModel) throwForUnresolvedEnforcedInheritScope(options?.scope, true);
|
|
445
|
+
const origin = options?.origin ?? (options?.primaryModelFromParent ? "inherited" : "configured");
|
|
446
|
+
const scopes = configuredScopes(options?.scope);
|
|
447
|
+
type ExcludedCandidate = { candidate: string; exclusion: NonNullable<ReturnType<typeof findModelExclusion>> };
|
|
448
|
+
const excludedCandidates: ExcludedCandidate[] = [];
|
|
449
|
+
let excludedCandidateCount = 0;
|
|
450
|
+
const warnCachedExclusion = (candidate: string, exclusion: NonNullable<ReturnType<typeof findModelExclusion>>) => {
|
|
451
|
+
excludedCandidateCount++;
|
|
452
|
+
if (excludedCandidates.length < MODEL_EXCLUSION_DIAGNOSTIC_MAX_ENTRIES) excludedCandidates.push({ candidate, exclusion });
|
|
453
|
+
const displayCandidate = sanitizeModelExclusionDiagnostic(candidate, "unknown");
|
|
454
|
+
const reason = sanitizeModelExclusionDiagnostic(exclusion.reason, "runtime-failure");
|
|
455
|
+
console.warn(`[pi-subagents] Skipping model '${displayCandidate}' due to a cached exclusion (reason: ${reason}; expires: ${formatModelExclusionExpiry(exclusion.expiresAt)}).`);
|
|
456
|
+
};
|
|
457
|
+
if (origin === "explicit" && primaryModel) {
|
|
458
|
+
const normalized = resolveRequiredSubagentModelCandidate(primaryModel.trim(), availableModels, preferredProvider);
|
|
459
|
+
throwForExplicitModelExclusion(normalized);
|
|
460
|
+
enforceModelScopes(normalized, scopes, "explicit", options?.onWarn);
|
|
461
|
+
primaryModel = normalized;
|
|
462
|
+
}
|
|
373
463
|
const seen = new Set<string>();
|
|
374
464
|
const candidates: string[] = [];
|
|
375
465
|
const rawCandidates = [primaryModel, ...(fallbackModels ?? [])];
|
|
466
|
+
let skippedPrimary: string | undefined;
|
|
467
|
+
let skippedFallback: string | undefined;
|
|
376
468
|
for (let index = 0; index < rawCandidates.length; index++) {
|
|
377
469
|
const raw = rawCandidates[index];
|
|
378
470
|
if (!raw) continue;
|
|
379
471
|
const model = raw.trim();
|
|
380
|
-
const normalized = index === 0
|
|
381
|
-
?
|
|
382
|
-
? model
|
|
383
|
-
: resolveRequiredSubagentModelCandidate(model, availableModels, preferredProvider)
|
|
472
|
+
const normalized = index === 0 && (origin === "inherited" || origin === "explicit" || options?.primaryModelFromParent)
|
|
473
|
+
? model
|
|
384
474
|
: resolveSubagentModelCandidate(model, availableModels, preferredProvider);
|
|
385
475
|
if (!normalized) {
|
|
386
|
-
|
|
476
|
+
if (index === 0) skippedPrimary = model;
|
|
477
|
+
else {
|
|
478
|
+
skippedFallback ??= model;
|
|
479
|
+
console.warn(`[pi-subagents] Skipping fallback model '${model}' because it is unavailable in this environment.`);
|
|
480
|
+
}
|
|
387
481
|
continue;
|
|
388
482
|
}
|
|
389
483
|
if (seen.has(normalized)) continue;
|
|
390
|
-
const scopes = configuredScopes(options?.scope);
|
|
391
484
|
if (index > 0 || scopes.some((scope) => scope.enforce === true && scope.strict === true)) {
|
|
392
485
|
enforceModelScopes(normalized, scopes, "inherited", options?.onWarn);
|
|
393
486
|
}
|
|
394
487
|
seen.add(normalized);
|
|
395
488
|
candidates.push(normalized);
|
|
396
489
|
}
|
|
397
|
-
|
|
490
|
+
const resolved = filterFallbackCandidates(candidates, { onExcluded: warnCachedExclusion });
|
|
491
|
+
if (resolved.length === 0) {
|
|
492
|
+
if (skippedPrimary) resolveRequiredSubagentModelCandidate(skippedPrimary, availableModels, preferredProvider);
|
|
493
|
+
if (candidates.length === 0 && skippedFallback) resolveRequiredSubagentModelCandidate(skippedFallback, availableModels, preferredProvider);
|
|
494
|
+
if (candidates.length > 0) {
|
|
495
|
+
const shownExclusions = excludedCandidates;
|
|
496
|
+
const omittedExclusions = excludedCandidateCount - shownExclusions.length;
|
|
497
|
+
const evidence = shownExclusions.length > 0
|
|
498
|
+
? ` (excluded: ${shownExclusions.map(({ candidate, exclusion }) => formatExcludedCandidateEvidence(candidate, exclusion)).join("; ")}${omittedExclusions > 0 ? `; ... and ${omittedExclusions} more` : ""})`
|
|
499
|
+
: "";
|
|
500
|
+
throw new Error(`${ZERO_USABLE_MODEL_CANDIDATES_ERROR}${evidence}`);
|
|
501
|
+
}
|
|
502
|
+
return resolved;
|
|
503
|
+
}
|
|
504
|
+
if (skippedPrimary) {
|
|
505
|
+
console.warn(`[pi-subagents] Skipping primary model '${skippedPrimary}' because it is unavailable in this environment.`);
|
|
506
|
+
}
|
|
507
|
+
return resolved;
|
|
398
508
|
}
|
|
399
509
|
|
|
400
510
|
const RETRYABLE_MODEL_FAILURE_PATTERNS = [
|
|
@@ -419,6 +529,7 @@ const RETRYABLE_MODEL_FAILURE_PATTERNS = [
|
|
|
419
529
|
/overloaded/i,
|
|
420
530
|
/service unavailable/i,
|
|
421
531
|
/temporar(?:ily)? unavailable/i,
|
|
532
|
+
/connection\s+(?:error|reset|closed|aborted)/i,
|
|
422
533
|
/connection refused/i,
|
|
423
534
|
/fetch failed/i,
|
|
424
535
|
/network error/i,
|
|
@@ -427,9 +538,11 @@ const RETRYABLE_MODEL_FAILURE_PATTERNS = [
|
|
|
427
538
|
/upstream/i,
|
|
428
539
|
/timed? out/i,
|
|
429
540
|
/timeout/i,
|
|
541
|
+
/\b500\b/,
|
|
430
542
|
/\b502\b/,
|
|
431
543
|
/\b503\b/,
|
|
432
544
|
/\b504\b/,
|
|
545
|
+
/internal server error/i,
|
|
433
546
|
/cold.?start/i,
|
|
434
547
|
/empty response/i,
|
|
435
548
|
/no output/i,
|
|
@@ -451,6 +564,21 @@ export function isRetryableModelFailure(error: string | undefined): boolean {
|
|
|
451
564
|
return RETRYABLE_MODEL_FAILURE_PATTERNS.some((pattern) => pattern.test(error));
|
|
452
565
|
}
|
|
453
566
|
|
|
567
|
+
function messageError(message: unknown): string | undefined {
|
|
568
|
+
if (!message || typeof message !== "object") return undefined;
|
|
569
|
+
const value = (message as { errorMessage?: unknown }).errorMessage;
|
|
570
|
+
return typeof value === "string" ? value : undefined;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
export function isRetryableModelFailureAttempt(input: { error: string | undefined; messages?: readonly unknown[]; toolCount?: number }): boolean {
|
|
574
|
+
if (!isRetryableModelFailure(input.error)) return false;
|
|
575
|
+
if ((input.toolCount ?? 0) > 0) return false;
|
|
576
|
+
if (input.error === "Subagent produced no output (possible model cold-start or empty response)." || /^Subagent produced no output after terminal assistant stopReason "[^"]+"\.$/.test(input.error ?? "")) return true;
|
|
577
|
+
if ((input.toolCount ?? 0) === 0 && (input.messages?.length ?? 0) === 0) return true;
|
|
578
|
+
const error = input.error?.trim();
|
|
579
|
+
return Boolean(error && input.messages?.some((message) => messageError(message)?.trim() === error));
|
|
580
|
+
}
|
|
581
|
+
|
|
454
582
|
export function recordRetryableModelFailure(model: string | undefined, error: string | undefined): void {
|
|
455
583
|
if (!model || !isRetryableModelFailure(error)) return;
|
|
456
584
|
const { provider, modelId } = parseModelKey(model);
|
|
@@ -3,14 +3,19 @@ import { createHash } from "node:crypto";
|
|
|
3
3
|
import * as fs from "node:fs";
|
|
4
4
|
import * as os from "node:os";
|
|
5
5
|
import * as path from "node:path";
|
|
6
|
-
import type { ArtifactPaths, TimeoutRecoverySummary, TrackedMutationEvidence, TrackedMutationFingerprint, TrackedMutationSnapshot } from "../../shared/types.ts";
|
|
6
|
+
import type { ArtifactPaths, TimeoutRecoveryProjection, TimeoutRecoverySummary, TrackedMutationEvidence, TrackedMutationFingerprint, TrackedMutationSnapshot } from "../../shared/types.ts";
|
|
7
7
|
|
|
8
8
|
const MAX_TRACKED_PATHS = 500;
|
|
9
9
|
const MAX_HASH_BYTES = 1024 * 1024;
|
|
10
10
|
const MAX_TIMEOUT_FILES = 20;
|
|
11
11
|
|
|
12
|
+
function gitArguments(args: string[]): string[] {
|
|
13
|
+
// Mutation evidence must not block child startup on a stale fsmonitor daemon.
|
|
14
|
+
return ["-c", "core.fsmonitor=false", ...args];
|
|
15
|
+
}
|
|
16
|
+
|
|
12
17
|
function gitOutput(cwd: string, args: string[], maxBuffer = MAX_HASH_BYTES): string {
|
|
13
|
-
return execFileSync("git", args, { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"], maxBuffer });
|
|
18
|
+
return execFileSync("git", gitArguments(args), { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"], maxBuffer, windowsHide: true });
|
|
14
19
|
}
|
|
15
20
|
|
|
16
21
|
function splitNul(output: string): string[] {
|
|
@@ -21,7 +26,7 @@ function hashLargeDiff(cwd: string, relativePath: string): string {
|
|
|
21
26
|
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagents-tracked-diff-"));
|
|
22
27
|
const diffPath = path.join(tempDir, "diff.patch");
|
|
23
28
|
try {
|
|
24
|
-
execFileSync("git", ["diff", "--no-ext-diff", "--binary", `--output=${diffPath}`, "HEAD", "--", relativePath], { cwd, stdio: "ignore" });
|
|
29
|
+
execFileSync("git", gitArguments(["diff", "--no-ext-diff", "--binary", `--output=${diffPath}`, "HEAD", "--", relativePath]), { cwd, stdio: "ignore", windowsHide: true });
|
|
25
30
|
const hash = createHash("sha256");
|
|
26
31
|
const buffer = Buffer.allocUnsafe(64 * 1024);
|
|
27
32
|
const fd = fs.openSync(diffPath, "r");
|
|
@@ -105,9 +110,48 @@ function formatPathList(paths: string[]): string {
|
|
|
105
110
|
return paths.length > MAX_TIMEOUT_FILES ? `${shown}, ... (${paths.length - MAX_TIMEOUT_FILES} more)` : shown;
|
|
106
111
|
}
|
|
107
112
|
|
|
113
|
+
/** Keep status and completion details to bounded routing evidence, not raw output or effects. */
|
|
114
|
+
export function projectTimeoutRecovery(value: unknown): TimeoutRecoveryProjection | undefined {
|
|
115
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
116
|
+
const source = value as Record<string, unknown>;
|
|
117
|
+
const termination = source.termination === "timed-out" || source.termination === "stopped" ? source.termination : undefined;
|
|
118
|
+
if (!termination || !Array.isArray(source.changedFiles)) return undefined;
|
|
119
|
+
const allChangedFiles = source.changedFiles.filter((file): file is string => typeof file === "string");
|
|
120
|
+
const changedFiles = allChangedFiles.slice(0, MAX_TIMEOUT_FILES);
|
|
121
|
+
const reportStatus = source.reportStatus === "missing"
|
|
122
|
+
|| source.reportStatus === "written"
|
|
123
|
+
|| source.reportStatus === "not-requested"
|
|
124
|
+
|| source.reportStatus === "unknown"
|
|
125
|
+
? source.reportStatus
|
|
126
|
+
: undefined;
|
|
127
|
+
return {
|
|
128
|
+
termination,
|
|
129
|
+
changedFiles,
|
|
130
|
+
...(source.truncated === true || allChangedFiles.length > changedFiles.length ? { truncated: true } : {}),
|
|
131
|
+
...(source.recoveryNeeded === true ? { recoveryNeeded: true } : {}),
|
|
132
|
+
...(source.reason === "timed-out-with-dirty-worktree" ? { reason: source.reason } : {}),
|
|
133
|
+
...(reportStatus ? { reportStatus } : {}),
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Render only the bounded recovery route needed by a parent/operator. */
|
|
138
|
+
export function formatTimeoutRecoveryLines(value: unknown, indent = ""): string[] {
|
|
139
|
+
const recovery = projectTimeoutRecovery(value);
|
|
140
|
+
if (!recovery?.recoveryNeeded) return [];
|
|
141
|
+
const changedFiles = recovery.changedFiles.length > 0
|
|
142
|
+
? `${recovery.changedFiles.join(", ")}${recovery.truncated ? ", …" : ""}`
|
|
143
|
+
: "none";
|
|
144
|
+
const changedFileCount = recovery.changedFiles.length > 0 ? `${recovery.changedFiles.length}${recovery.truncated ? "+" : ""}` : "0";
|
|
145
|
+
return [
|
|
146
|
+
`${indent}Recovery needed: review the diff and artifacts before resuming or launching dependent stages.`,
|
|
147
|
+
`${indent}Recovery evidence: requested report: ${recovery.reportStatus ?? "unknown"}; changed tracked files: ${changedFiles} (${changedFileCount}); classification: ${recovery.reason ?? recovery.termination}`,
|
|
148
|
+
];
|
|
149
|
+
}
|
|
150
|
+
|
|
108
151
|
export function buildTimeoutRecoverySummary(input: {
|
|
109
152
|
termination: "timed-out" | "stopped";
|
|
110
153
|
evidence: TrackedMutationEvidence;
|
|
154
|
+
requiredOutputMissing?: boolean;
|
|
111
155
|
currentTool?: string;
|
|
112
156
|
currentToolArgs?: string;
|
|
113
157
|
currentPath?: string;
|
|
@@ -117,11 +161,19 @@ export function buildTimeoutRecoverySummary(input: {
|
|
|
117
161
|
}): TimeoutRecoverySummary {
|
|
118
162
|
const warning = "Inspect partial changes before retrying or resuming the child.";
|
|
119
163
|
const changedFiles = input.evidence.changedFiles.slice(0, MAX_TIMEOUT_FILES);
|
|
164
|
+
let reportStatus: "missing" | "written" | "not-requested" = "not-requested";
|
|
165
|
+
if (input.requiredOutputMissing === true) reportStatus = "missing";
|
|
166
|
+
else if (input.requiredOutputMissing === false) reportStatus = "written";
|
|
167
|
+
const recoveryNeeded = input.termination === "timed-out"
|
|
168
|
+
&& reportStatus === "missing"
|
|
169
|
+
&& input.evidence.changedFiles.length > 0;
|
|
120
170
|
const lines = [
|
|
121
171
|
"Recovery summary:",
|
|
122
172
|
`- termination: ${input.termination}`,
|
|
123
173
|
`- changed tracked files: ${input.evidence.unavailable ? `unavailable (${input.evidence.unavailable})` : formatPathList(input.evidence.changedFiles)}`,
|
|
124
174
|
];
|
|
175
|
+
if (input.requiredOutputMissing !== undefined) lines.push(`- requested report: ${reportStatus}`);
|
|
176
|
+
if (recoveryNeeded) lines.push("- Recovery needed: review the diff and artifacts before resuming or launching dependent stages.");
|
|
125
177
|
if (input.currentTool) lines.push(`- active tool: ${input.currentTool}${input.currentToolArgs ? ` — ${input.currentToolArgs}` : ""}`);
|
|
126
178
|
if (input.currentPath) lines.push(`- active path: ${input.currentPath}`);
|
|
127
179
|
if (input.sessionFile) lines.push(`- session file: ${input.sessionFile}`);
|
|
@@ -133,6 +185,8 @@ export function buildTimeoutRecoverySummary(input: {
|
|
|
133
185
|
termination: input.termination,
|
|
134
186
|
changedFiles,
|
|
135
187
|
truncated: input.evidence.changedFiles.length > changedFiles.length || input.evidence.truncated || undefined,
|
|
188
|
+
...(recoveryNeeded ? { recoveryNeeded: true, reason: "timed-out-with-dirty-worktree" as const } : {}),
|
|
189
|
+
reportStatus,
|
|
136
190
|
currentTool: input.currentTool,
|
|
137
191
|
currentToolArgs: input.currentToolArgs,
|
|
138
192
|
currentPath: input.currentPath,
|