@xzzpig/pi-subagents 0.16.0 → 0.19.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 +233 -1
- package/README.md +5 -3
- package/agents/claude-code-writer.md +1 -0
- package/agents/codex-exec-writer.md +1 -0
- package/agents/cursor-agent-writer.md +1 -0
- package/agents/reviewer.md +3 -2
- package/agents/worker.md +3 -2
- package/docs/agents.md +34 -21
- package/docs/configuration.md +82 -7
- package/docs/extension-api.md +75 -8
- package/docs/missions.md +13 -13
- package/docs/models.md +7 -5
- package/docs/observability.md +23 -13
- package/docs/standalone-background.md +5 -5
- package/docs/tool-reference.md +98 -100
- package/docs/watchdog.md +2 -0
- package/docs/workflows.md +214 -162
- package/inspector-runner.mjs +1 -1
- package/node_modules/@xzzpig/pi-components/package.json +4 -4
- package/package.json +15 -9
- package/prompts/council.md +6 -3
- package/prompts/review-loop.md +1 -1
- package/runner-peer-loader.mjs +4 -7
- package/runner-peer-preload.mjs +5 -7
- package/skills/council-mode/SKILL.md +1 -1
- package/skills/pi-subagents/SKILL.md +13 -5
- package/skills/pi-subagents/references/constraints-and-recipes.md +8 -5
- package/skills/pi-subagents/references/execution-controls.md +72 -69
- package/skills/pi-subagents/references/management-authoring-rpc.md +4 -4
- package/skills/pi-subagents/references/multi-lane-orchestration.md +9 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +52 -54
- package/src/agents/advertised-agent-prompt.ts +21 -41
- package/src/agents/agent-eject.ts +3 -3
- package/src/agents/agent-management.ts +63 -54
- package/src/agents/agent-memory.ts +90 -3
- package/src/agents/agent-serializer.ts +4 -4
- package/src/agents/agents.ts +132 -51
- package/src/agents/global-npm-root.ts +58 -0
- package/src/agents/proactive-skills.ts +4 -1
- package/src/agents/runtime-agent-registry.ts +14 -11
- package/src/agents/skills.ts +42 -9
- package/src/api/delegation.ts +15 -0
- package/src/api/inspectors.ts +27 -0
- package/src/api/preflight.ts +7 -2
- package/src/extension/config.ts +12 -4
- package/src/extension/control-notices.ts +3 -0
- package/src/extension/doctor.ts +10 -4
- package/src/extension/fanout-child.ts +20 -3
- package/src/extension/herdr-pi-bridge.ts +2 -0
- package/src/extension/index.ts +168 -206
- package/src/extension/public-execution.ts +69 -35
- package/src/extension/reply-workflow-script.ts +58 -0
- package/src/extension/rpc.ts +39 -11
- package/src/extension/schemas.ts +47 -138
- package/src/extension/subagent-guide.ts +12 -4
- package/src/extension/tool-activation.ts +146 -0
- package/src/extension/tool-description.ts +62 -27
- package/src/extension/upgrade-notice.ts +40 -0
- package/src/inspectors/ghostty/plugin.ts +13 -1
- package/src/inspectors/plugins.ts +70 -3
- package/src/integrations/herdr-status.ts +19 -3
- package/src/intercom/intercom-bridge.ts +2 -0
- package/src/intercom/native-supervisor-channel.ts +26 -16
- package/src/intercom/result-intercom.ts +4 -0
- package/src/runs/background/active-async-capacity.ts +3 -25
- package/src/runs/background/async-execution.ts +60 -95
- package/src/runs/background/async-job-tracker.ts +91 -56
- package/src/runs/background/async-resume.ts +16 -8
- package/src/runs/background/async-retention.ts +46 -16
- package/src/runs/background/async-status.ts +2 -0
- package/src/runs/background/await-async-run.ts +76 -0
- package/src/runs/background/binary-bootstrap.ts +34 -6
- package/src/runs/background/chain-root-attachment.ts +4 -4
- package/src/runs/background/control-channel.ts +18 -2
- package/src/runs/background/fleet-view.ts +51 -7
- package/src/runs/background/notify.ts +98 -7
- package/src/runs/background/pid-namespace.ts +18 -0
- package/src/runs/background/process-terminal-candidate.ts +98 -0
- package/src/runs/background/process-terminal.ts +17 -96
- package/src/runs/background/result-watcher.ts +1 -1
- package/src/runs/background/retained-children.ts +3 -2
- package/src/runs/background/run-child-session.ts +20 -6
- package/src/runs/background/run-id-resolver.ts +10 -5
- package/src/runs/background/run-status.ts +16 -4
- package/src/runs/background/runner-aliases.ts +54 -16
- package/src/runs/background/runner-child-launch.ts +4 -2
- package/src/runs/background/runner-startup-failure.ts +56 -0
- package/src/runs/background/scheduled-runs.ts +5 -5
- package/src/runs/background/stale-run-reconciler.ts +19 -3
- package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
- package/src/runs/background/subagent-runner.ts +111 -288
- package/src/runs/background/wait-tool.ts +2 -0
- package/src/runs/background/workflow-terminal-proof.ts +68 -0
- package/src/runs/foreground/async-stop-action.ts +17 -3
- package/src/runs/foreground/execution.ts +111 -139
- package/src/runs/foreground/prompt-audit.ts +3 -9
- package/src/runs/foreground/subagent-executor.ts +715 -258
- package/src/runs/shared/acceptance.ts +167 -68
- package/src/runs/shared/async-status-projection.ts +5 -0
- package/src/runs/shared/capability-ceiling.ts +4 -1
- package/src/runs/shared/child-hooks.ts +1 -16
- package/src/runs/shared/child-launch.ts +37 -16
- package/src/runs/shared/child-runtime-config.ts +3 -0
- package/src/runs/shared/child-session.ts +144 -8
- package/src/runs/shared/child-tool-plan.ts +38 -116
- package/src/runs/shared/dynamic-fanout.ts +1 -1
- package/src/runs/shared/external-cli-runner.ts +3 -1
- package/src/runs/shared/external-job-bridge.ts +54 -0
- package/src/runs/shared/git-environment.ts +29 -0
- package/src/runs/shared/mcp-config-sources.ts +5 -1
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -12
- package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
- package/src/runs/shared/model-resolution.ts +35 -10
- package/src/runs/shared/model-scope.ts +28 -9
- package/src/runs/shared/nested-events.ts +12 -0
- package/src/runs/shared/orca-progress-tabs.ts +3 -2
- package/src/runs/shared/parallel-utils.ts +4 -1
- package/src/runs/shared/pi-spawn.ts +1 -3
- package/src/runs/shared/single-output.ts +11 -2
- package/src/runs/shared/structured-output.ts +227 -7
- package/src/runs/shared/subagent-control.ts +2 -16
- package/src/runs/shared/subagent-prompt-runtime.ts +29 -5
- package/src/runs/shared/tool-availability.ts +2 -2
- package/src/runs/shared/tool-budget.ts +21 -0
- package/src/runs/shared/usage-reconciliation.ts +73 -0
- package/src/runs/shared/worktree.ts +36 -9
- package/src/shared/child-session-name.ts +4 -2
- package/src/shared/disabled-features.ts +123 -0
- package/src/shared/extension-context.ts +13 -0
- package/src/shared/fork-context.ts +11 -4
- package/src/shared/launch-contract.ts +1 -1
- package/src/shared/model-info.ts +9 -0
- package/src/shared/pruned-fork.ts +69 -56
- package/src/shared/settings.ts +1 -1
- package/src/shared/types.ts +73 -16
- package/src/slash/delegation-adapters.ts +25 -1
- package/src/slash/prompt-template-bridge.ts +18 -3
- package/src/slash/prompt-workflows.ts +12 -1
- package/src/slash/slash-commands.ts +17 -246
- package/src/slash/subagent-cost.ts +313 -0
- package/src/slash/subagents-admin.ts +4 -5
- package/src/tui/fleet-status.ts +38 -8
- package/src/tui/fleet.ts +21 -6
- package/src/tui/render.ts +166 -71
- package/src/tui/running-tone.ts +28 -0
- package/src/watchdog/diff-tool.ts +47 -12
- package/src/watchdog/permission-arbiter.ts +13 -15
- package/src/watchdog/register-child.ts +13 -5
- package/src/watchdog/register-main.ts +3 -3
- package/src/watchdog/review.ts +16 -16
- package/src/watchdog/runtime.ts +2 -1
- package/src/watchdog/turn-delta.ts +12 -6
- package/src/workflows/chat-progress.ts +2 -2
- package/src/workflows/scripted-workflow.ts +225 -59
- package/src/workflows/structured-workflow-scripts.ts +177 -0
- package/src/workflows/workflow-checklist.ts +6 -0
- package/src/workflows/workflow-child-summary.ts +4 -2
- package/src/workflows/workflow-receipt.ts +8 -2
- package/src/workflows/workflow-resources.ts +37 -12
- package/src/workflows/workflow-reuse.ts +120 -0
- package/src/workflows/workflow-revival.ts +123 -0
- package/src/workflows/workflow-settlement.ts +4 -1
- package/src/runs/shared/completion-evidence.ts +0 -89
- package/src/runs/shared/completion-guard.ts +0 -255
- package/src/runs/shared/llm-intent-arbiter.ts +0 -321
- package/src/runs/shared/task-intent.ts +0 -244
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
FileMutationEffect,
|
|
3
|
-
SettlementDiagnostic,
|
|
4
|
-
TrackedMutationEvidence,
|
|
5
|
-
} from "../../shared/types.ts";
|
|
6
|
-
import type { CompletionMutationGuardResult } from "./completion-guard.ts";
|
|
7
|
-
|
|
8
|
-
export const MISSING_IMPLEMENTATION_MUTATION_MESSAGE = "Subagent completed without making edits for an implementation task.";
|
|
9
|
-
export const MISSING_IMPLEMENTATION_MUTATION_ERROR = `${MISSING_IMPLEMENTATION_MUTATION_MESSAGE}\nIt appears to have returned planning or scratchpad output instead of applying changes.`;
|
|
10
|
-
|
|
11
|
-
export interface CompletionEvidencePlan {
|
|
12
|
-
guardTriggered: boolean;
|
|
13
|
-
guardBlocked: boolean;
|
|
14
|
-
mutationExpected: boolean;
|
|
15
|
-
mutationAttempted: boolean;
|
|
16
|
-
fileMutation?: FileMutationEffect;
|
|
17
|
-
legacyFailureError?: string;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
export function planCompletionEvidence(input: {
|
|
21
|
-
guard?: CompletionMutationGuardResult;
|
|
22
|
-
guardTriggered?: boolean;
|
|
23
|
-
completionGuardEnabled: boolean;
|
|
24
|
-
mutationCapable: boolean;
|
|
25
|
-
implementationMutationExpected: boolean;
|
|
26
|
-
mutationAttemptObserved: boolean;
|
|
27
|
-
mutationEvidence?: TrackedMutationEvidence;
|
|
28
|
-
arbiterRescued?: boolean;
|
|
29
|
-
agentContractEnabled: boolean;
|
|
30
|
-
}): CompletionEvidencePlan {
|
|
31
|
-
const guardBlocked = input.guard?.blocked === true;
|
|
32
|
-
const guardTriggered = input.guardTriggered
|
|
33
|
-
?? (input.guard?.triggered === true && !input.mutationAttemptObserved);
|
|
34
|
-
const mutationExpected = input.guard?.expectedMutation
|
|
35
|
-
?? (input.completionGuardEnabled && input.mutationCapable && input.implementationMutationExpected);
|
|
36
|
-
const mutationAttempted = input.guard?.attemptedMutation === true || input.mutationAttemptObserved;
|
|
37
|
-
const fileMutation = input.guard
|
|
38
|
-
? {
|
|
39
|
-
status: guardBlocked
|
|
40
|
-
? "blocked" as const
|
|
41
|
-
: input.guard.expectedMutation
|
|
42
|
-
? guardTriggered
|
|
43
|
-
? "missing" as const
|
|
44
|
-
: input.arbiterRescued
|
|
45
|
-
? "not-applicable" as const
|
|
46
|
-
: "observed" as const
|
|
47
|
-
: "not-applicable" as const,
|
|
48
|
-
expected: input.guard.expectedMutation,
|
|
49
|
-
attempted: guardBlocked ? false : mutationAttempted,
|
|
50
|
-
...(input.mutationEvidence ? { evidence: input.mutationEvidence } : {}),
|
|
51
|
-
...(guardBlocked && input.guard.message ? { message: input.guard.message } : {}),
|
|
52
|
-
...(guardTriggered ? { message: MISSING_IMPLEMENTATION_MUTATION_MESSAGE } : {}),
|
|
53
|
-
...(input.arbiterRescued ? { resolvedBy: "llm-intent-arbiter" as const } : {}),
|
|
54
|
-
}
|
|
55
|
-
: undefined;
|
|
56
|
-
return {
|
|
57
|
-
guardTriggered,
|
|
58
|
-
guardBlocked,
|
|
59
|
-
mutationExpected,
|
|
60
|
-
mutationAttempted,
|
|
61
|
-
fileMutation,
|
|
62
|
-
legacyFailureError: guardTriggered && !input.agentContractEnabled
|
|
63
|
-
? MISSING_IMPLEMENTATION_MUTATION_ERROR
|
|
64
|
-
: undefined,
|
|
65
|
-
};
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
export function projectSettlementDiagnostic(
|
|
69
|
-
plan: Pick<CompletionEvidencePlan, "guardTriggered" | "guardBlocked" | "mutationExpected" | "mutationAttempted">,
|
|
70
|
-
input: {
|
|
71
|
-
terminalFailed: boolean;
|
|
72
|
-
finalTextPresent: boolean;
|
|
73
|
-
mutationObserved: boolean;
|
|
74
|
-
requiredOutput?: SettlementDiagnostic["requiredOutput"];
|
|
75
|
-
afterCompactionSettlement?: boolean;
|
|
76
|
-
},
|
|
77
|
-
): SettlementDiagnostic | undefined {
|
|
78
|
-
if (!input.terminalFailed && !plan.guardTriggered && !plan.guardBlocked) return undefined;
|
|
79
|
-
return {
|
|
80
|
-
finalTextPresent: input.finalTextPresent,
|
|
81
|
-
mutation: {
|
|
82
|
-
expected: plan.mutationExpected,
|
|
83
|
-
attempted: plan.mutationAttempted,
|
|
84
|
-
observed: input.mutationObserved,
|
|
85
|
-
},
|
|
86
|
-
...(input.requiredOutput ? { requiredOutput: input.requiredOutput } : {}),
|
|
87
|
-
afterCompactionSettlement: input.afterCompactionSettlement === true,
|
|
88
|
-
};
|
|
89
|
-
}
|
|
@@ -1,255 +0,0 @@
|
|
|
1
|
-
import type { Message } from "@earendil-works/pi-ai";
|
|
2
|
-
import type { AcceptanceRole, TrackedMutationEvidence } from "../../shared/types.ts";
|
|
3
|
-
import { isMutatingTool } from "./long-running-guard.ts";
|
|
4
|
-
import { classifyTaskMutationIntent, expectsImplementationMutation, taskMayMutate } from "./task-intent.ts";
|
|
5
|
-
|
|
6
|
-
export { expectsImplementationMutation };
|
|
7
|
-
|
|
8
|
-
const READ_ONLY_BUILTIN_TOOLS = new Set([
|
|
9
|
-
"read",
|
|
10
|
-
"grep",
|
|
11
|
-
"find",
|
|
12
|
-
"ls",
|
|
13
|
-
"web_search",
|
|
14
|
-
"fetch_content",
|
|
15
|
-
"get_search_content",
|
|
16
|
-
"source_check",
|
|
17
|
-
"intercom",
|
|
18
|
-
"contact_supervisor",
|
|
19
|
-
"structured_output",
|
|
20
|
-
]);
|
|
21
|
-
|
|
22
|
-
// Cursor native edit/write often land as thinking traces (inactive_trace /
|
|
23
|
-
// transcript_trace) rather than toolCall parts when native tool replay is off
|
|
24
|
-
// or the tool is inactive in context. Match pi-cursor-sdk display labels.
|
|
25
|
-
const CURSOR_FILE_MUTATION_THINKING =
|
|
26
|
-
/(?:^|\n)\s*Cursor (?:edit|write)\s*:/i;
|
|
27
|
-
|
|
28
|
-
const REVIVED_TASK_PREFIX = /^You are reviving a previous subagent conversation\.\n\nOriginal run: .+\nOriginal agent: .+(?:\nOriginal session file: .+)?\n\nUse the stored session context as background\. Answer the orchestrator's follow-up below\. Do not assume the original child session is still running\.\n\nFollow-up:\n/;
|
|
29
|
-
const IMPLEMENTATION_CHALLENGE_FOLLOW_UP_PATTERN = /^(?:Run )?implementation challenge pass (?:one|two|\d+)(?:\s+and implement any better current[- ]scope change\.?|\s+for the accepted candidate\.\s+Reconsider it and implement any better current[- ]scope change\.?)?$/i;
|
|
30
|
-
const NO_BETTER_CHANGE_NEEDED_PATTERN = /^\s*no (?:better|further|additional) (?:current[- ]scope )?(?:code |source |file )?(?:change|changes|edit|edits|patch|patches) (?:is|are) needed\b/i;
|
|
31
|
-
const KEPT_CURRENT_IMPLEMENTATION_PATTERN = /\b(?:kept (?:the )?current (?:implementation|candidate|shape)|(?:the )?current (?:implementation|candidate|shape) was kept)\b/i;
|
|
32
|
-
const NO_CHANGE_MADE_PATTERN = /\bno (?:new )?(?:(?:code|source|file|test)(?:\s*(?:,\s*or|,|\/|or)\s*(?:code|source|file|test))* changes?|changes?) (?:were|was) made\b/i;
|
|
33
|
-
const NO_BETTER_CHANGE_QUALIFIER_PATTERN = /\b(?:do\s+not|don't|dont|not|never|cannot|can't|cant|unable|uncertain|unsure|unclear|disagree|wrong|false|reject|rejected|rejecting|maybe|might|may|\w+n['’]t)\b/i;
|
|
34
|
-
const REPORT_SENTENCE_PATTERN = /[^.!?]+(?:[.!?]+(?=(?:["”'’]?\s)|["”'’]?$)|$)/g;
|
|
35
|
-
const QUOTED_CLAIM_PATTERN = /["“]([^"”]+)["”]([.!?]?\s*[^.!?]*)/g;
|
|
36
|
-
const QUOTED_CLAIM_REFERENCE_PATTERN = /\b(?:that|this|it|claim|report|message|disagree)\b/i;
|
|
37
|
-
const CLAIM_CONTRADICTION_PATTERN = /\bbut\b[^.!?]*\b(?:uncertain|unsure|unclear|disagree|wrong|false|reject|rejected|rejecting)\b/i;
|
|
38
|
-
const IMPLEMENTATION_RETRACTION_PATTERN = /\b(?:found|identified)\s+(?:(?:a|an|the)\s+)?(?:required|necessary|additional|better)?\s*(?:(?:code|source|file|test)\s+)?(?:changes?|edits?|patches?)\b|\b(?:(?:implementation|code|source|file|test)\s+)?work\s+(?:remains?|is\s+(?:needed|required))\b|\b(?:(?:a|an|the)\s+)?(?:(?:code|source|file|test)\s+)?(?:changes?|edits?|patches?)\s+(?:are|is)\s+(?:needed|required)\b|\b(?:required|necessary|additional|better)\s+(?:(?:code|source|file|test)\s+)?(?:changes?|edits?|patches?)\b|\b(?:I|we)?\s*need\s+(?:(?:code|source|file|test)\s+)?(?:changes?|edits?|patches?)\b|\b(?:need|needs|require|requires)\s+(?:to\s+)?(?:implement|make|apply)\b/i;
|
|
39
|
-
const IMPLEMENTATION_RETRACTION_GLOBAL_PATTERN = new RegExp(IMPLEMENTATION_RETRACTION_PATTERN.source, "gi");
|
|
40
|
-
const DIRECT_CLAIM_RETRACTION_PATTERN = /^\s*(?:I\s+)?(?:disagree|reject|retract)\b|\b(?:disagree|retract|retracted|retracting|reject|rejected|rejecting)\b[^.!?]*\b(?:that|this|it|claim|report|message)\b|\b(?:that|this|it|claim|report|message)\b[^.!?]*\b(?:is|was)\s+(?:rejected|retracted)\b/i;
|
|
41
|
-
const NEGATED_RETRACTION_PREFIX_PATTERN = /\b(?:no|not|\w+n['’]t)\b(?:\s+\w+){0,2}\s*$/i;
|
|
42
|
-
const REPORTED_CLAIM_PREFIX_PATTERN = /["“]|\b(?:prior|previous)\s+(?:message|report)\b|\b(?:said|stated|reported)\b/i;
|
|
43
|
-
const POST_CLAIM_SEPARATOR_PATTERN = /^[\s,;:.—–'"“‘’-]+/;
|
|
44
|
-
|
|
45
|
-
interface CompletionMutationGuardInput {
|
|
46
|
-
agent: string;
|
|
47
|
-
task: string;
|
|
48
|
-
messages: Message[];
|
|
49
|
-
tools?: string[];
|
|
50
|
-
mcpDirectTools?: string[];
|
|
51
|
-
mutationTools?: string[];
|
|
52
|
-
toolAvailabilityError?: string;
|
|
53
|
-
mutationEvidence?: TrackedMutationEvidence;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
export interface CompletionMutationGuardResult {
|
|
57
|
-
expectedMutation: boolean;
|
|
58
|
-
attemptedMutation: boolean;
|
|
59
|
-
triggered: boolean;
|
|
60
|
-
blocked: boolean;
|
|
61
|
-
message?: string;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
interface ReportSentence {
|
|
65
|
-
text: string;
|
|
66
|
-
offset: number;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
export function hasMutationToolCapability(tools: string[] | undefined, mcpDirectTools: string[] | undefined): boolean {
|
|
70
|
-
if ((mcpDirectTools?.length ?? 0) > 0) return true;
|
|
71
|
-
if (tools === undefined) return true;
|
|
72
|
-
return !tools.every((tool) => READ_ONLY_BUILTIN_TOOLS.has(tool));
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
function hasBuiltinMutationTool(tools: string[] | undefined): boolean {
|
|
76
|
-
return tools === undefined || tools.some((tool) => !READ_ONLY_BUILTIN_TOOLS.has(tool));
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
function isWriterRole(agent: string, acceptanceRole: AcceptanceRole | undefined): boolean {
|
|
80
|
-
return acceptanceRole === "writer"
|
|
81
|
-
|| (acceptanceRole === undefined && /\bworker\b/i.test(agent));
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
const WRITER_DELIVERY_PATTERN = /\b(?:address|resolve|work)\s+(?:backlog\s+)?(?:item|issue)\b|\b(?:land|ship)\s+(?:the\s+)?(?:change|changes|fix|feature|implementation)\b/i;
|
|
85
|
-
|
|
86
|
-
export function validateImplementationToolContract(input: {
|
|
87
|
-
agent: string;
|
|
88
|
-
task: string;
|
|
89
|
-
tools?: string[];
|
|
90
|
-
mcpDirectTools?: string[];
|
|
91
|
-
configuredExtensions?: string[];
|
|
92
|
-
requestedTools?: string[];
|
|
93
|
-
acceptanceRole?: AcceptanceRole;
|
|
94
|
-
completionGuard?: boolean;
|
|
95
|
-
}): string | undefined {
|
|
96
|
-
if (input.completionGuard === false) return undefined;
|
|
97
|
-
const requestedMutationTools = input.requestedTools?.filter((tool) => !READ_ONLY_BUILTIN_TOOLS.has(tool)) ?? [];
|
|
98
|
-
const declaredMutationToolsWereRemoved = requestedMutationTools.length > 0 && !hasBuiltinMutationTool(input.tools);
|
|
99
|
-
const configuredExtensionCapability = (input.configuredExtensions?.length ?? 0) > 0 && !declaredMutationToolsWereRemoved;
|
|
100
|
-
if (hasMutationToolCapability(input.tools, input.mcpDirectTools) || configuredExtensionCapability) return undefined;
|
|
101
|
-
const intent = classifyTaskMutationIntent(input.acceptanceRole === "writer" ? "worker" : input.agent, input.task);
|
|
102
|
-
if (intent.kind === "read-only") return undefined;
|
|
103
|
-
const writerTaskMayMutate = input.acceptanceRole === "writer"
|
|
104
|
-
? true
|
|
105
|
-
: isWriterRole(input.agent, input.acceptanceRole)
|
|
106
|
-
&& (taskMayMutate(input.task) || WRITER_DELIVERY_PATTERN.test(input.task));
|
|
107
|
-
if (intent.kind !== "implementation" && !writerTaskMayMutate && !declaredMutationToolsWereRemoved) return undefined;
|
|
108
|
-
return `Agent '${input.agent}' was given an implementation task, but its tool allowlist has no mutation-capable tools. Add bash, edit, write, or another mutation-capable tool to the agent, or use a read-only task/agent.`;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
function hasCheckpointMutationEvidence(message: Message): boolean {
|
|
112
|
-
const record = message as unknown as {
|
|
113
|
-
role?: string;
|
|
114
|
-
type?: string;
|
|
115
|
-
customType?: unknown;
|
|
116
|
-
data?: unknown;
|
|
117
|
-
details?: unknown;
|
|
118
|
-
};
|
|
119
|
-
if ((record.role !== "custom" && record.type !== "custom") || record.customType !== "pi-checkpoint") return false;
|
|
120
|
-
const details = typeof record.details === "object" && record.details !== null && !Array.isArray(record.details)
|
|
121
|
-
? record.details as Record<string, unknown>
|
|
122
|
-
: undefined;
|
|
123
|
-
const data = typeof record.data === "object" && record.data !== null && !Array.isArray(record.data)
|
|
124
|
-
? record.data as Record<string, unknown>
|
|
125
|
-
: typeof details?.beforeCommit === "string" || typeof details?.afterCommit === "string"
|
|
126
|
-
? details
|
|
127
|
-
: details?.data && typeof details.data === "object" && !Array.isArray(details.data)
|
|
128
|
-
? details.data as Record<string, unknown>
|
|
129
|
-
: undefined;
|
|
130
|
-
return typeof data?.beforeCommit === "string"
|
|
131
|
-
&& typeof data.afterCommit === "string"
|
|
132
|
-
&& data.beforeCommit !== data.afterCommit;
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
export function hasMutationToolCall(messages: Message[], mutationTools?: readonly string[]): boolean {
|
|
136
|
-
for (const message of messages) {
|
|
137
|
-
if (hasCheckpointMutationEvidence(message)) return true;
|
|
138
|
-
if (message.role !== "assistant") continue;
|
|
139
|
-
for (const part of message.content) {
|
|
140
|
-
if (part.type === "thinking" && CURSOR_FILE_MUTATION_THINKING.test(part.thinking)) return true;
|
|
141
|
-
if (part.type !== "toolCall") continue;
|
|
142
|
-
const args = typeof part.arguments === "object" && part.arguments !== null && !Array.isArray(part.arguments)
|
|
143
|
-
? part.arguments as Record<string, unknown>
|
|
144
|
-
: {};
|
|
145
|
-
if (isMutatingTool(part.name, args, mutationTools)) return true;
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
return false;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
function hasImplementationRetraction(text: string): boolean {
|
|
152
|
-
return Array.from(text.matchAll(IMPLEMENTATION_RETRACTION_GLOBAL_PATTERN)).some((retraction) =>
|
|
153
|
-
!NEGATED_RETRACTION_PREFIX_PATTERN.test(text.slice(0, retraction.index!)));
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
function hasDirectClaimRetraction(text: string): boolean {
|
|
157
|
-
return DIRECT_CLAIM_RETRACTION_PATTERN.test(text.replace(POST_CLAIM_SEPARATOR_PATTERN, ""));
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
function isInsideQuotedText(report: string, index: number): boolean {
|
|
161
|
-
let quote: "double" | "single" | undefined;
|
|
162
|
-
for (const char of report.slice(0, index)) {
|
|
163
|
-
if (quote === "double") {
|
|
164
|
-
if (char === "\"" || char === "”") quote = undefined;
|
|
165
|
-
} else if (quote === "single") {
|
|
166
|
-
if (char === "’") quote = undefined;
|
|
167
|
-
} else if (char === "\"" || char === "“") {
|
|
168
|
-
quote = "double";
|
|
169
|
-
} else if (char === "‘") {
|
|
170
|
-
quote = "single";
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
return quote !== undefined;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
function unqualifiedClaimIndex(report: string, sentences: ReportSentence[], pattern: RegExp): number {
|
|
177
|
-
return sentences.findIndex((sentence) => {
|
|
178
|
-
const claim = sentence.text.match(pattern);
|
|
179
|
-
if (claim === null) return false;
|
|
180
|
-
const before = sentence.text.slice(0, claim.index!);
|
|
181
|
-
const after = sentence.text.slice(claim.index! + claim[0].length);
|
|
182
|
-
const previous = before.trimEnd().at(-1);
|
|
183
|
-
return previous !== "'"
|
|
184
|
-
&& previous !== "‘"
|
|
185
|
-
&& !isInsideQuotedText(report, sentence.offset + claim.index!)
|
|
186
|
-
&& !REPORTED_CLAIM_PREFIX_PATTERN.test(before)
|
|
187
|
-
&& !NO_BETTER_CHANGE_QUALIFIER_PATTERN.test(before)
|
|
188
|
-
&& !CLAIM_CONTRADICTION_PATTERN.test(after)
|
|
189
|
-
&& !hasImplementationRetraction(after)
|
|
190
|
-
&& !hasDirectClaimRetraction(after);
|
|
191
|
-
});
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
function hasLaterClaimRetraction(sentences: ReportSentence[], claimIndex: number): boolean {
|
|
195
|
-
return sentences.slice(claimIndex + 1).some((sentence) => hasImplementationRetraction(sentence.text)
|
|
196
|
-
|| hasDirectClaimRetraction(sentence.text));
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
function explicitlyRejectsQuotedClaim(report: string): boolean {
|
|
200
|
-
for (const [, claim, response] of report.matchAll(QUOTED_CLAIM_PATTERN)) {
|
|
201
|
-
if ((KEPT_CURRENT_IMPLEMENTATION_PATTERN.test(claim!) || NO_CHANGE_MADE_PATTERN.test(claim!))
|
|
202
|
-
&& NO_BETTER_CHANGE_QUALIFIER_PATTERN.test(response!)
|
|
203
|
-
&& QUOTED_CLAIM_REFERENCE_PATTERN.test(response!)) return true;
|
|
204
|
-
}
|
|
205
|
-
return false;
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
function isImplementationChallengeTask(task: string): boolean {
|
|
209
|
-
const followUp = task.replace(REVIVED_TASK_PREFIX, "");
|
|
210
|
-
return followUp !== task && IMPLEMENTATION_CHALLENGE_FOLLOW_UP_PATTERN.test(followUp.trim());
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
function reportsNoBetterChallengeChange(messages: Message[]): boolean {
|
|
214
|
-
const report = messages
|
|
215
|
-
.filter((message) => message.role === "assistant")
|
|
216
|
-
.flatMap((message) => message.content)
|
|
217
|
-
.flatMap((part) => part.type === "text" ? [part.text] : [])
|
|
218
|
-
.join("\n");
|
|
219
|
-
if (explicitlyRejectsQuotedClaim(report)) return false;
|
|
220
|
-
const sentences = Array.from(report.matchAll(REPORT_SENTENCE_PATTERN), (match) => ({
|
|
221
|
-
text: match[0],
|
|
222
|
-
offset: match.index!,
|
|
223
|
-
}));
|
|
224
|
-
const noBetterIndex = unqualifiedClaimIndex(report, sentences, NO_BETTER_CHANGE_NEEDED_PATTERN);
|
|
225
|
-
if (noBetterIndex >= 0) return !hasLaterClaimRetraction(sentences, noBetterIndex);
|
|
226
|
-
const keptIndex = unqualifiedClaimIndex(report, sentences, KEPT_CURRENT_IMPLEMENTATION_PATTERN);
|
|
227
|
-
const noChangeIndex = unqualifiedClaimIndex(report, sentences, NO_CHANGE_MADE_PATTERN);
|
|
228
|
-
return keptIndex >= 0
|
|
229
|
-
&& noChangeIndex >= 0
|
|
230
|
-
&& !hasLaterClaimRetraction(sentences, Math.min(keptIndex, noChangeIndex));
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
export function evaluateCompletionMutationGuard(input: CompletionMutationGuardInput): CompletionMutationGuardResult {
|
|
234
|
-
if (input.toolAvailabilityError && expectsImplementationMutation(input.agent, input.task)) {
|
|
235
|
-
return {
|
|
236
|
-
expectedMutation: true,
|
|
237
|
-
attemptedMutation: false,
|
|
238
|
-
triggered: false,
|
|
239
|
-
blocked: true,
|
|
240
|
-
message: input.toolAvailabilityError,
|
|
241
|
-
};
|
|
242
|
-
}
|
|
243
|
-
const expectedMutation = hasMutationToolCapability(input.tools, input.mcpDirectTools)
|
|
244
|
-
? expectsImplementationMutation(input.agent, input.task)
|
|
245
|
-
: false;
|
|
246
|
-
const attemptedMutation = hasMutationToolCall(input.messages, input.mutationTools) || input.mutationEvidence?.attemptedMutation === true;
|
|
247
|
-
const noEditChallengeComplete = isImplementationChallengeTask(input.task)
|
|
248
|
-
&& reportsNoBetterChallengeChange(input.messages);
|
|
249
|
-
return {
|
|
250
|
-
expectedMutation,
|
|
251
|
-
attemptedMutation,
|
|
252
|
-
triggered: expectedMutation && !attemptedMutation && !noEditChallengeComplete,
|
|
253
|
-
blocked: false,
|
|
254
|
-
};
|
|
255
|
-
}
|
|
@@ -1,321 +0,0 @@
|
|
|
1
|
-
import { createHash } from "node:crypto";
|
|
2
|
-
import type { Agent, AgentTool, StreamFn } from "@earendil-works/pi-agent-core";
|
|
3
|
-
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
4
|
-
import type { ProviderHeaders } from "@earendil-works/pi-ai";
|
|
5
|
-
import { Type, type Static } from "typebox";
|
|
6
|
-
import { agentStreamOptions } from "../../shared/agent-stream-options.ts";
|
|
7
|
-
import { opencodeSessionHeaders } from "../../shared/opencode-session-headers.ts";
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* LLM intent arbiter for the completion mutation guard.
|
|
11
|
-
*
|
|
12
|
-
* The regex classifier (task-intent.ts) is deliberately narrow, so exotic
|
|
13
|
-
* review wording can still look like an implementation task ("to fix this,
|
|
14
|
-
* compare the outputs", verbs inside URLs or quoted text). When the guard is
|
|
15
|
-
* about to hard-fail a run that made no edits, this arbiter asks a model
|
|
16
|
-
* whether the task actually instructed file changes. It can only downgrade a
|
|
17
|
-
* failure to a pass; every error, timeout, or non-read-only verdict keeps the
|
|
18
|
-
* guard's original behavior.
|
|
19
|
-
*
|
|
20
|
-
* Enabled by default; set PI_SUBAGENTS_LLM_INTENT_ARBITER=0 to disable.
|
|
21
|
-
*/
|
|
22
|
-
|
|
23
|
-
const COMPLETION_GUARD_ERROR_PREFIX =
|
|
24
|
-
"Subagent completed without making edits for an implementation task.";
|
|
25
|
-
|
|
26
|
-
export type TaskMutationVerdict = "read-only" | "implementation" | "unavailable";
|
|
27
|
-
|
|
28
|
-
export type TaskMutationArbiter = (task: string) => Promise<TaskMutationVerdict>;
|
|
29
|
-
|
|
30
|
-
const DecisionParams = Type.Object(
|
|
31
|
-
{
|
|
32
|
-
classification: Type.String({ enum: ["read_only", "implementation"] }),
|
|
33
|
-
confidence: Type.String({
|
|
34
|
-
enum: ["low", "medium", "high"],
|
|
35
|
-
description: "Confidence in the classification. Only read_only with high confidence rescues a failed run.",
|
|
36
|
-
}),
|
|
37
|
-
reason: Type.String({ description: "One concise reason for this classification." }),
|
|
38
|
-
},
|
|
39
|
-
{ additionalProperties: false },
|
|
40
|
-
);
|
|
41
|
-
|
|
42
|
-
type DecisionParams = Static<typeof DecisionParams>;
|
|
43
|
-
|
|
44
|
-
/** Map a model decision to a verdict. Only a high-confidence read_only rescues. */
|
|
45
|
-
export function mapArbiterDecision(
|
|
46
|
-
decision: { classification?: string; confidence?: string } | undefined,
|
|
47
|
-
): TaskMutationVerdict {
|
|
48
|
-
if (!decision) return "unavailable";
|
|
49
|
-
if (decision.classification === "read_only" && decision.confidence === "high") return "read-only";
|
|
50
|
-
return "implementation";
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
interface ArbiterRuntime {
|
|
54
|
-
model: NonNullable<RegistryModel>;
|
|
55
|
-
/** Explicit override; it always wins over a registered provider stream. */
|
|
56
|
-
explicitStreamFn?: StreamFn;
|
|
57
|
-
/** Registered provider stream, usable only when its api matches the model. */
|
|
58
|
-
registeredStreamFn?: StreamFn;
|
|
59
|
-
registeredApi?: string;
|
|
60
|
-
/** Session id for OpenCode session-routing headers, when the caller has one. */
|
|
61
|
-
sessionId?: string;
|
|
62
|
-
timeoutMs: number;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
interface ArbiterAuth {
|
|
66
|
-
apiKey?: string;
|
|
67
|
-
headers?: ProviderHeaders;
|
|
68
|
-
env?: Record<string, string>;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
export interface TaskMutationArbiterOptions {
|
|
72
|
-
/** Explicit "provider/id" model override (tests, config). */
|
|
73
|
-
model?: string;
|
|
74
|
-
/** Injectable stream function (tests). */
|
|
75
|
-
streamFn?: StreamFn;
|
|
76
|
-
timeoutMs?: number;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
const DEFAULT_ARBITER_TIMEOUT_MS = 10_000;
|
|
80
|
-
|
|
81
|
-
type RegistryModel = ReturnType<NonNullable<ExtensionContext["modelRegistry"]["find"]>>;
|
|
82
|
-
/** Model services the arbiter needs, plus the caller's session id for OpenCode session-routing headers. */
|
|
83
|
-
export type ArbiterModelContext = Pick<ExtensionContext, "model" | "modelRegistry"> & {
|
|
84
|
-
/** Session id the headers attach to (the child's, captured by detached runners; the parent's, passed by foreground callers). */
|
|
85
|
-
sessionId?: string;
|
|
86
|
-
};
|
|
87
|
-
|
|
88
|
-
function resolveArbiterModel(
|
|
89
|
-
ctx: ArbiterModelContext,
|
|
90
|
-
options?: TaskMutationArbiterOptions,
|
|
91
|
-
): NonNullable<RegistryModel> | null {
|
|
92
|
-
const registry = ctx.modelRegistry as {
|
|
93
|
-
find?: (provider: string, modelId: string) => RegistryModel | undefined;
|
|
94
|
-
getAvailable?: () => Array<{ provider?: string; id?: string }>;
|
|
95
|
-
};
|
|
96
|
-
const explicit = options?.model?.trim();
|
|
97
|
-
if (explicit) {
|
|
98
|
-
const [provider, id] = explicit.split("/");
|
|
99
|
-
if (provider && id) return registry.find?.(provider, id) ?? null;
|
|
100
|
-
return null;
|
|
101
|
-
}
|
|
102
|
-
if (ctx.model) return ctx.model as NonNullable<RegistryModel>;
|
|
103
|
-
const first = registry.getAvailable?.()[0];
|
|
104
|
-
if (first?.provider && first.id) return registry.find?.(first.provider, first.id) ?? null;
|
|
105
|
-
return null;
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
function resolveArbiterRuntime(
|
|
109
|
-
ctx: ArbiterModelContext,
|
|
110
|
-
options?: TaskMutationArbiterOptions,
|
|
111
|
-
): ArbiterRuntime | null {
|
|
112
|
-
const model = resolveArbiterModel(ctx, options);
|
|
113
|
-
if (!model?.provider || !model.id) return null;
|
|
114
|
-
const registry = ctx.modelRegistry as {
|
|
115
|
-
getRegisteredProviderConfig?: (provider: string) => { api?: string; streamSimple?: StreamFn } | undefined;
|
|
116
|
-
};
|
|
117
|
-
const registered = registry.getRegisteredProviderConfig?.(model.provider);
|
|
118
|
-
return {
|
|
119
|
-
model,
|
|
120
|
-
explicitStreamFn: options?.streamFn,
|
|
121
|
-
registeredStreamFn: registered?.streamSimple,
|
|
122
|
-
registeredApi: registered?.api,
|
|
123
|
-
sessionId: ctx.sessionId,
|
|
124
|
-
timeoutMs: options?.timeoutMs ?? DEFAULT_ARBITER_TIMEOUT_MS,
|
|
125
|
-
};
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
async function resolveArbiterAuth(
|
|
129
|
-
ctx: ArbiterModelContext,
|
|
130
|
-
model: RegistryModel,
|
|
131
|
-
): Promise<ArbiterAuth | undefined> {
|
|
132
|
-
const registry = ctx.modelRegistry as {
|
|
133
|
-
getApiKeyAndHeaders?: (m: RegistryModel) => Promise<{
|
|
134
|
-
ok: boolean;
|
|
135
|
-
apiKey?: string;
|
|
136
|
-
headers?: ProviderHeaders;
|
|
137
|
-
env?: Record<string, string>;
|
|
138
|
-
error?: string;
|
|
139
|
-
}>;
|
|
140
|
-
};
|
|
141
|
-
// Call as a METHOD on the registry: the host ModelRegistry implementation
|
|
142
|
-
// is a class whose method reads instance state (this.runtime), so a
|
|
143
|
-
// detached call silently fails auth. Same shape as the watchdog.
|
|
144
|
-
if (!registry.getApiKeyAndHeaders) return {};
|
|
145
|
-
try {
|
|
146
|
-
const auth = await registry.getApiKeyAndHeaders(model);
|
|
147
|
-
if (auth.ok === false) return undefined;
|
|
148
|
-
return {
|
|
149
|
-
...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
|
|
150
|
-
...(auth.headers ? { headers: auth.headers } : {}),
|
|
151
|
-
...(auth.env ? { env: auth.env } : {}),
|
|
152
|
-
};
|
|
153
|
-
} catch {
|
|
154
|
-
return undefined;
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
/** Build the effective stream function with resolved credentials wrapped in (watchdog pattern). */
|
|
159
|
-
function authWrappedStreamFn(
|
|
160
|
-
base: StreamFn,
|
|
161
|
-
auth: ArbiterAuth,
|
|
162
|
-
sessionId: string | undefined,
|
|
163
|
-
): StreamFn {
|
|
164
|
-
return (model, context, streamOptions) => base(model, context, {
|
|
165
|
-
...(streamOptions ?? {}),
|
|
166
|
-
...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
|
|
167
|
-
...(auth.env || streamOptions?.env ? { env: { ...(auth.env ?? {}), ...(streamOptions?.env ?? {}) } } : {}),
|
|
168
|
-
headers: { ...opencodeSessionHeaders(model, sessionId), ...(streamOptions?.headers ?? {}), ...(auth.headers ?? {}) },
|
|
169
|
-
});
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
async function runArbitration(
|
|
173
|
-
runtime: ArbiterRuntime,
|
|
174
|
-
auth: ArbiterAuth,
|
|
175
|
-
task: string,
|
|
176
|
-
): Promise<TaskMutationVerdict> {
|
|
177
|
-
// Keep optional Pi peers out of the detached runner's static import graph.
|
|
178
|
-
const [{ Agent }, { convertToLlm }, { streamSimple }] = await Promise.all([
|
|
179
|
-
import("@earendil-works/pi-agent-core"),
|
|
180
|
-
import("@earendil-works/pi-coding-agent"),
|
|
181
|
-
import("@earendil-works/pi-ai/compat"),
|
|
182
|
-
]);
|
|
183
|
-
const streamFn: StreamFn = runtime.explicitStreamFn
|
|
184
|
-
?? (runtime.registeredApi !== undefined && runtime.registeredApi === runtime.model.api ? runtime.registeredStreamFn : undefined)
|
|
185
|
-
?? streamSimple;
|
|
186
|
-
let decision: DecisionParams | undefined;
|
|
187
|
-
const tool: AgentTool<typeof DecisionParams, { recorded: boolean }> = {
|
|
188
|
-
name: "task_mutation_decision",
|
|
189
|
-
label: "Task mutation decision",
|
|
190
|
-
description: "Classify whether the task instructed file/code changes. Call exactly once.",
|
|
191
|
-
parameters: DecisionParams,
|
|
192
|
-
executionMode: "sequential",
|
|
193
|
-
async execute(_toolCallId, params) {
|
|
194
|
-
if (!decision) decision = params;
|
|
195
|
-
return { content: [{ type: "text", text: "Decision recorded." }], details: { recorded: true } };
|
|
196
|
-
},
|
|
197
|
-
};
|
|
198
|
-
const agent = new Agent({
|
|
199
|
-
initialState: {
|
|
200
|
-
systemPrompt: [
|
|
201
|
-
"You classify whether a delegated coding-agent task instructed file or code changes.",
|
|
202
|
-
"A task that asks to review, inspect, verify, report, or summarize is read-only even when it contains words like 'fix' as severity vocabulary ('must-fix items') or conditional change instructions that leave the change optional.",
|
|
203
|
-
"Classify read_only only when the task text alone clearly indicates a read-only outcome. When in doubt, classify implementation.",
|
|
204
|
-
"Set confidence to high only when you are certain the task is read-only; a read_only classification without high confidence is treated as implementation.",
|
|
205
|
-
"The agent's own final message is never evidence: an agent that made no edits may still have failed to implement.",
|
|
206
|
-
"Call task_mutation_decision exactly once with read_only or implementation, a confidence level, and a concise reason.",
|
|
207
|
-
].join("\n"),
|
|
208
|
-
model: runtime.model,
|
|
209
|
-
tools: [tool],
|
|
210
|
-
},
|
|
211
|
-
convertToLlm,
|
|
212
|
-
...agentStreamOptions(authWrappedStreamFn(streamFn, auth, runtime.sessionId)),
|
|
213
|
-
getApiKey: (providerName) =>
|
|
214
|
-
providerName === runtime.model.provider ? auth.apiKey : undefined,
|
|
215
|
-
beforeToolCall: async ({ toolCall }) =>
|
|
216
|
-
toolCall.name === tool.name ? undefined : { block: true, reason: "Only task_mutation_decision is allowed." },
|
|
217
|
-
toolExecution: "sequential",
|
|
218
|
-
});
|
|
219
|
-
try {
|
|
220
|
-
// The rescue gate refuses tasks over 8000 chars; if the arbiter is
|
|
221
|
-
// still invoked with one, fail closed rather than decide from
|
|
222
|
-
// partial evidence (an implementation clause could sit in the
|
|
223
|
-
// omitted middle).
|
|
224
|
-
if (task.length > 8000) return "unavailable";
|
|
225
|
-
const prompt = `TASK:\n${task}`;
|
|
226
|
-
await Promise.race([
|
|
227
|
-
agent.prompt(prompt),
|
|
228
|
-
new Promise<never>((_, reject) => {
|
|
229
|
-
const timeout = setTimeout(() => {
|
|
230
|
-
agent.abort();
|
|
231
|
-
reject(new Error("Task mutation arbiter timed out."));
|
|
232
|
-
}, runtime.timeoutMs);
|
|
233
|
-
timeout.unref?.();
|
|
234
|
-
}),
|
|
235
|
-
]);
|
|
236
|
-
if (!decision) return "unavailable";
|
|
237
|
-
return mapArbiterDecision(decision);
|
|
238
|
-
} catch {
|
|
239
|
-
return "unavailable";
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
/** Create a memoized arbiter bound to the supplied model services, or undefined when disabled/unavailable. */
|
|
244
|
-
export function createTaskMutationArbiter(
|
|
245
|
-
ctx: ArbiterModelContext,
|
|
246
|
-
options?: TaskMutationArbiterOptions,
|
|
247
|
-
): TaskMutationArbiter | undefined {
|
|
248
|
-
if (process.env.PI_SUBAGENTS_LLM_INTENT_ARBITER === "0") return undefined;
|
|
249
|
-
const runtime = resolveArbiterRuntime(ctx, options);
|
|
250
|
-
if (!runtime) return undefined;
|
|
251
|
-
const cache = new Map<string, TaskMutationVerdict>();
|
|
252
|
-
return async (task) => {
|
|
253
|
-
const key = createHash("sha256").update(task).digest("base64url");
|
|
254
|
-
const cached = cache.get(key);
|
|
255
|
-
if (cached) return cached;
|
|
256
|
-
const auth = await resolveArbiterAuth(ctx, runtime.model);
|
|
257
|
-
const verdict = auth ? await runArbitration(runtime, auth, task) : "unavailable";
|
|
258
|
-
if (cache.size > 200) cache.clear();
|
|
259
|
-
cache.set(key, verdict);
|
|
260
|
-
return verdict;
|
|
261
|
-
};
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
export function isCompletionGuardFailure(result: { error?: string }): boolean {
|
|
265
|
-
return result.error?.startsWith(COMPLETION_GUARD_ERROR_PREFIX) === true;
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
export async function arbitrateCompletionGuardRescue(input: {
|
|
269
|
-
guardTriggered: boolean;
|
|
270
|
-
task: string;
|
|
271
|
-
arbiter?: TaskMutationArbiter;
|
|
272
|
-
}): Promise<{ triggered: boolean; rescued: boolean }> {
|
|
273
|
-
if (!input.guardTriggered || !input.arbiter) {
|
|
274
|
-
return { triggered: input.guardTriggered, rescued: false };
|
|
275
|
-
}
|
|
276
|
-
// Never decide from partial evidence: refuse tasks over 8000 chars before
|
|
277
|
-
// even consulting the model.
|
|
278
|
-
if (input.task.length > 8000) {
|
|
279
|
-
return { triggered: true, rescued: false };
|
|
280
|
-
}
|
|
281
|
-
try {
|
|
282
|
-
const verdict = await input.arbiter(input.task);
|
|
283
|
-
if (verdict === "read-only") return { triggered: false, rescued: true };
|
|
284
|
-
return { triggered: true, rescued: false };
|
|
285
|
-
} catch {
|
|
286
|
-
return { triggered: true, rescued: false };
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
/**
|
|
291
|
-
* When the completion guard hard-failed a run and the arbiter classifies the
|
|
292
|
-
* task as read-only, clear the failure. Returns true when rescued. All other
|
|
293
|
-
* verdicts and every failure mode keep the original guard behavior.
|
|
294
|
-
*
|
|
295
|
-
* Classification uses the task text only: the agent's own final message is
|
|
296
|
-
* never evidence, so a child that failed to implement cannot talk its way
|
|
297
|
-
* out of the guard by claiming the work was read-only.
|
|
298
|
-
*/
|
|
299
|
-
export async function maybeRescueCompletionGuardFailure(
|
|
300
|
-
result: { exitCode?: number; error?: string },
|
|
301
|
-
task: string,
|
|
302
|
-
arbiter: TaskMutationArbiter | undefined,
|
|
303
|
-
): Promise<boolean> {
|
|
304
|
-
if (!arbiter || !isCompletionGuardFailure(result)) return false;
|
|
305
|
-
const verdict = await arbitrateWithGuard(arbiter, task);
|
|
306
|
-
if (verdict !== "read-only") return false;
|
|
307
|
-
result.exitCode = 0;
|
|
308
|
-
delete result.error;
|
|
309
|
-
return true;
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
async function arbitrateWithGuard(
|
|
313
|
-
arbiter: TaskMutationArbiter,
|
|
314
|
-
task: string,
|
|
315
|
-
): Promise<TaskMutationVerdict> {
|
|
316
|
-
try {
|
|
317
|
-
return await arbiter(task);
|
|
318
|
-
} catch {
|
|
319
|
-
return "unavailable";
|
|
320
|
-
}
|
|
321
|
-
}
|