@xzzpig/pi-subagents 0.16.0 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +164 -1
- package/README.md +5 -3
- package/agents/claude-code-writer.md +1 -0
- package/agents/codex-exec-writer.md +1 -0
- package/agents/cursor-agent-writer.md +1 -0
- package/agents/reviewer.md +3 -2
- package/agents/worker.md +3 -2
- package/docs/agents.md +17 -10
- package/docs/configuration.md +21 -3
- package/docs/extension-api.md +70 -4
- package/docs/models.md +5 -3
- package/docs/observability.md +23 -13
- package/docs/standalone-background.md +4 -4
- package/docs/tool-reference.md +40 -19
- package/docs/watchdog.md +2 -0
- package/docs/workflows.md +57 -3
- package/inspector-runner.mjs +1 -1
- package/package.json +14 -8
- package/prompts/council.md +6 -3
- package/runner-peer-loader.mjs +4 -7
- package/runner-peer-preload.mjs +5 -7
- package/skills/pi-subagents/SKILL.md +1 -0
- package/skills/pi-subagents/references/constraints-and-recipes.md +5 -2
- package/skills/pi-subagents/references/execution-controls.md +6 -4
- package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
- package/skills/pi-subagents/references/multi-lane-orchestration.md +8 -0
- package/skills/pi-subagents/references/prompting-and-roles.md +16 -15
- package/src/agents/agent-eject.ts +3 -3
- package/src/agents/agent-management.ts +61 -52
- package/src/agents/agent-memory.ts +90 -3
- package/src/agents/agent-serializer.ts +4 -4
- package/src/agents/agents.ts +125 -51
- package/src/agents/global-npm-root.ts +58 -0
- package/src/agents/proactive-skills.ts +4 -1
- package/src/agents/runtime-agent-registry.ts +14 -11
- package/src/agents/skills.ts +42 -9
- package/src/api/delegation.ts +15 -0
- package/src/api/inspectors.ts +27 -0
- package/src/api/preflight.ts +60 -60
- package/src/extension/doctor.ts +9 -4
- package/src/extension/fanout-child.ts +8 -0
- package/src/extension/index.ts +101 -48
- package/src/extension/rpc.ts +10 -1
- package/src/extension/schemas.ts +12 -6
- package/src/extension/subagent-guide.ts +12 -4
- package/src/extension/tool-activation.ts +197 -0
- package/src/extension/tool-description.ts +1 -1
- package/src/inspectors/ghostty/plugin.ts +13 -1
- package/src/inspectors/plugins.ts +70 -3
- package/src/intercom/intercom-bridge.ts +2 -0
- package/src/intercom/native-supervisor-channel.ts +22 -15
- package/src/intercom/result-intercom.ts +4 -0
- package/src/runs/background/active-async-capacity.ts +3 -25
- package/src/runs/background/async-execution.ts +100 -140
- package/src/runs/background/async-job-tracker.ts +28 -34
- package/src/runs/background/async-resume.ts +16 -8
- package/src/runs/background/async-status.ts +2 -0
- package/src/runs/background/binary-bootstrap.ts +34 -6
- package/src/runs/background/fleet-view.ts +51 -7
- package/src/runs/background/notify.ts +93 -7
- package/src/runs/background/pid-namespace.ts +18 -0
- package/src/runs/background/process-terminal-candidate.ts +98 -0
- package/src/runs/background/process-terminal.ts +17 -96
- package/src/runs/background/result-watcher.ts +1 -1
- package/src/runs/background/retained-children.ts +3 -2
- package/src/runs/background/run-child-session.ts +16 -5
- package/src/runs/background/run-id-resolver.ts +10 -5
- package/src/runs/background/run-status.ts +10 -4
- package/src/runs/background/runner-aliases.ts +25 -15
- package/src/runs/background/runner-child-launch.ts +1 -2
- package/src/runs/background/runner-startup-failure.ts +56 -0
- package/src/runs/background/stale-run-reconciler.ts +19 -3
- package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
- package/src/runs/background/subagent-runner.ts +96 -287
- package/src/runs/background/wait-tool.ts +2 -0
- package/src/runs/background/workflow-terminal-proof.ts +68 -0
- package/src/runs/foreground/execution.ts +217 -250
- package/src/runs/foreground/prompt-audit.ts +3 -9
- package/src/runs/foreground/subagent-executor.ts +377 -119
- package/src/runs/shared/acceptance.ts +167 -68
- package/src/runs/shared/capability-ceiling.ts +4 -1
- package/src/runs/shared/child-hooks.ts +1 -16
- package/src/runs/shared/child-launch.ts +22 -14
- package/src/runs/shared/child-runtime-config.ts +3 -0
- package/src/runs/shared/child-session.ts +52 -2
- package/src/runs/shared/child-tool-plan.ts +23 -113
- package/src/runs/shared/dynamic-fanout.ts +1 -1
- package/src/runs/shared/external-cli-runner.ts +3 -1
- package/src/runs/shared/external-job-bridge.ts +54 -0
- package/src/runs/shared/git-environment.ts +29 -0
- package/src/runs/shared/mcp-config-sources.ts +3 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +1 -1
- package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
- package/src/runs/shared/model-resolution.ts +6 -1
- package/src/runs/shared/nested-events.ts +67 -55
- package/src/runs/shared/orca-progress-tabs.ts +3 -2
- package/src/runs/shared/parallel-utils.ts +2 -1
- package/src/runs/shared/pi-spawn.ts +92 -6
- package/src/runs/shared/single-output.ts +11 -2
- package/src/runs/shared/structured-output.ts +227 -7
- package/src/runs/shared/subagent-control.ts +2 -16
- package/src/runs/shared/subagent-prompt-runtime.ts +27 -5
- package/src/runs/shared/tool-availability.ts +2 -2
- package/src/runs/shared/tool-budget.ts +21 -0
- package/src/runs/shared/usage-reconciliation.ts +73 -0
- package/src/runs/shared/worktree.ts +35 -8
- package/src/shared/child-session-name.ts +4 -2
- package/src/shared/fork-context.ts +11 -4
- package/src/shared/launch-contract.ts +1 -1
- package/src/shared/pruned-fork.ts +69 -56
- package/src/shared/types.ts +52 -16
- package/src/slash/delegation-adapters.ts +25 -1
- package/src/slash/prompt-template-bridge.ts +16 -1
- package/src/slash/prompt-workflows.ts +12 -1
- package/src/slash/slash-commands.ts +7 -241
- package/src/slash/subagent-cost.ts +313 -0
- package/src/slash/subagents-admin.ts +28 -29
- package/src/tui/fleet-status.ts +24 -2
- package/src/tui/fleet.ts +7 -4
- package/src/tui/render.ts +53 -19
- package/src/watchdog/diff-tool.ts +24 -3
- package/src/watchdog/permission-arbiter.ts +13 -15
- package/src/watchdog/register-child.ts +10 -2
- package/src/watchdog/review.ts +14 -14
- package/src/watchdog/runtime.ts +2 -1
- package/src/watchdog/turn-delta.ts +11 -5
- package/src/workflows/scripted-workflow.ts +109 -23
- package/src/workflows/workflow-child-summary.ts +4 -2
- package/src/workflows/workflow-settlement.ts +4 -1
- package/src/runs/shared/completion-evidence.ts +0 -89
- package/src/runs/shared/completion-guard.ts +0 -255
- package/src/runs/shared/llm-intent-arbiter.ts +0 -321
- package/src/runs/shared/task-intent.ts +0 -244
|
@@ -4,8 +4,7 @@ import { dirname, resolve as resolvePath } from "node:path";
|
|
|
4
4
|
import { Worker } from "node:worker_threads";
|
|
5
5
|
import { DEFAULT_GLOBAL_CONCURRENCY_LIMIT, Semaphore } from "../runs/shared/parallel-utils.ts";
|
|
6
6
|
import { HOST_STEP_MAX_COUNT } from "../runs/shared/host-step-status.ts";
|
|
7
|
-
import {
|
|
8
|
-
import { describeGateAcceptanceConflict } from "../runs/shared/acceptance.ts";
|
|
7
|
+
import { describeGateAcceptanceConflict, parseGateInput } from "../runs/shared/acceptance.ts";
|
|
9
8
|
import type { AcceptanceRecoveryMetadata, HostStepNode, SingleResult } from "../shared/types.ts";
|
|
10
9
|
import { normalizeWorkflowHostCommandParams, type WorkflowHostCommandParams, type WorkflowHostCommandResult } from "./host-command.ts";
|
|
11
10
|
|
|
@@ -384,8 +383,8 @@ function laneStageRecord(stageKey, child, forcedState) {
|
|
|
384
383
|
const ok = result?.ok === true;
|
|
385
384
|
const verdict = laneStageVerdict(result);
|
|
386
385
|
const blocked = laneStageIsBlocked(result);
|
|
387
|
-
const state = forcedState ?? (result?.stopped ? "stopped" : result?.detached ? "detached" : ok ? blocked ? "blocked" : "completed" : "failed");
|
|
388
|
-
const error = state !== "completed"
|
|
386
|
+
const state = forcedState ?? (result?.state === "running" ? "running" : result?.stopped ? "stopped" : result?.detached ? "detached" : ok ? blocked ? "blocked" : "completed" : "failed");
|
|
387
|
+
const error = state !== "completed" && state !== "running"
|
|
389
388
|
? state === "blocked" && blocked
|
|
390
389
|
? "Stage returned a blocked verdict."
|
|
391
390
|
: typeof result?.error === "string"
|
|
@@ -633,6 +632,24 @@ function validateLaneMetadata(value, label, workflowKey) {
|
|
|
633
632
|
}
|
|
634
633
|
}
|
|
635
634
|
|
|
635
|
+
// Mirrors parseGateInput in src/runs/shared/acceptance.ts; the sandbox cannot import it.
|
|
636
|
+
function describeGateShapeError(gate) {
|
|
637
|
+
const shape = "gate must be a non-empty command string or { command, output?: \"json\", schema?, timeoutMs? }.";
|
|
638
|
+
if (typeof gate === "string") return gate.trim() ? undefined : shape;
|
|
639
|
+
if (!gate || typeof gate !== "object" || Array.isArray(gate)) return shape;
|
|
640
|
+
for (const key of Object.keys(gate)) {
|
|
641
|
+
if (!["command", "output", "schema", "timeoutMs"].includes(key)) return "gate." + key + " is not supported.";
|
|
642
|
+
}
|
|
643
|
+
if (typeof gate.command !== "string" || !gate.command.trim()) return shape;
|
|
644
|
+
if (gate.output !== undefined && gate.output !== "json") return "gate.output must be \"json\" when present.";
|
|
645
|
+
if (gate.schema !== undefined) {
|
|
646
|
+
if (gate.output !== "json") return "gate.schema requires gate.output: \"json\".";
|
|
647
|
+
if (!gate.schema || typeof gate.schema !== "object" || Array.isArray(gate.schema)) return "gate.schema must be a JSON Schema object.";
|
|
648
|
+
}
|
|
649
|
+
if (gate.timeoutMs !== undefined && (!Number.isInteger(gate.timeoutMs) || gate.timeoutMs < 1)) return "gate.timeoutMs must be an integer >= 1.";
|
|
650
|
+
return undefined;
|
|
651
|
+
}
|
|
652
|
+
|
|
636
653
|
function describeGateAcceptanceConflict(gate, acceptance) {
|
|
637
654
|
const render = (value) => {
|
|
638
655
|
let encoded;
|
|
@@ -658,7 +675,10 @@ function validateRunCall(key, params, label, fingerprints) {
|
|
|
658
675
|
if (params.worktree !== undefined && typeof params.worktree !== "boolean") throw new Error(label + " worktree must be true or false.");
|
|
659
676
|
if (params.baseRef !== undefined && (typeof params.baseRef !== "string" || !validGitRef(params.baseRef))) throw new Error(label + " baseRef must be a valid Git ref: use HEAD or a supported named ref (for example, refs/heads/main). Full 40/64-character commit IDs and revision expressions are unsupported.");
|
|
660
677
|
validateLaneMetadata(params.lane, label + " lane", key);
|
|
661
|
-
if (params.gate !== undefined
|
|
678
|
+
if (params.gate !== undefined) {
|
|
679
|
+
const gateError = describeGateShapeError(params.gate);
|
|
680
|
+
if (gateError) throw new Error(label + " " + gateError);
|
|
681
|
+
}
|
|
662
682
|
if (params.gate !== undefined && params.acceptance !== undefined && params.acceptance !== false) throw new Error(label + " gate cannot be combined with acceptance; use one gate command or acceptance.verify." + describeGateAcceptanceConflict(params.gate, params.acceptance));
|
|
663
683
|
if (params.gate !== undefined && params.resume !== undefined) throw new Error(label + " gate is not supported with retained resume.");
|
|
664
684
|
if (params.extensionBindings !== undefined && params.resume !== undefined) throw new Error(label + " extensionBindings is not supported with retained resume; resume uses the original retained child binding.");
|
|
@@ -1061,7 +1081,11 @@ parentPort.on("message", async (message) => {
|
|
|
1061
1081
|
|
|
1062
1082
|
export interface WorkflowScriptChildResult {
|
|
1063
1083
|
key: string;
|
|
1084
|
+
/** True only for successfully completed child work, never for a launch receipt. */
|
|
1064
1085
|
ok: boolean;
|
|
1086
|
+
/** An explicit async launch returned before a final child result was available. */
|
|
1087
|
+
state?: "running";
|
|
1088
|
+
asyncDir?: string;
|
|
1065
1089
|
lane?: import("../shared/types.ts").WorkflowLaneMetadata;
|
|
1066
1090
|
terminalOutcome?: import("../shared/types.ts").WorkflowTerminalOutcome;
|
|
1067
1091
|
stopped?: boolean;
|
|
@@ -1076,6 +1100,8 @@ export interface WorkflowScriptChildResult {
|
|
|
1076
1100
|
requestedContext?: "fresh" | "fork";
|
|
1077
1101
|
resolvedContext?: "fresh" | "fork" | "mixed";
|
|
1078
1102
|
outputReference?: string;
|
|
1103
|
+
/** A file produced by the child runtime (output or worktree handoff), not its job directory. */
|
|
1104
|
+
outputArtifactPath?: string;
|
|
1079
1105
|
recovery?: AcceptanceRecoveryMetadata;
|
|
1080
1106
|
outputPathMapping?: { requestedPath: string; savedPath: string };
|
|
1081
1107
|
externalAdapter?: import("../shared/types.ts").ExternalCliReceiptMetadata;
|
|
@@ -1354,8 +1380,7 @@ function isExplicitReadOnlyRecoveryReview(params: Record<string, unknown>): bool
|
|
|
1354
1380
|
&& !RECOVERY_REVIEW_DELEGATION_PATTERN.test(taskMutationText)
|
|
1355
1381
|
&& !RECOVERY_REVIEW_ANAPHORIC_MUTATION_PATTERN.test(taskMutationText)
|
|
1356
1382
|
&& !RECOVERY_REVIEW_DESTRUCTIVE_COMMAND_PATTERN.test(taskMutationText)
|
|
1357
|
-
&& !RECOVERY_REVIEW_DASH_LIVE_ACTION_PATTERN.test(taskDashLiveActionText)
|
|
1358
|
-
&& classifyTaskMutationIntent(agent, task).kind === "read-only";
|
|
1383
|
+
&& !RECOVERY_REVIEW_DASH_LIVE_ACTION_PATTERN.test(taskDashLiveActionText);
|
|
1359
1384
|
}
|
|
1360
1385
|
|
|
1361
1386
|
function recoveryBarrierMessage(sourceKey: string, target: string): string {
|
|
@@ -1442,7 +1467,7 @@ function workflowReturnRecoveryHint(children: WorkflowScriptChildResult[]): stri
|
|
|
1442
1467
|
const fields = [child.runId ? `runId=${child.runId.slice(0, 500)}` : undefined, child.outputReference ? `outputReference=${child.outputReference.slice(0, 500)}` : undefined, child.artifactPaths[0] ? `artifact=${child.artifactPaths[0].slice(0, 500)}` : undefined].filter((field): field is string => field !== undefined);
|
|
1443
1468
|
return `'${child.key}'${fields.length > 0 ? ` (${fields.join(", ")})` : ""}`;
|
|
1444
1469
|
});
|
|
1445
|
-
return ` Child work completed before return serialization failed. Recover outputs from: ${references.join(", ")}${children.length > references.length ? `, and ${children.length - references.length} more` : ""}. Return a plain projection such as { runId: child.runId, ok: child.ok, outputReference: child.outputReference }.`;
|
|
1470
|
+
return ` ${children.some((child) => child.state === "running") ? "Child calls returned before return serialization failed; launch receipts do not prove completion." : "Child work completed before return serialization failed."} Recover outputs from: ${references.join(", ")}${children.length > references.length ? `, and ${children.length - references.length} more` : ""}. Return a plain projection such as { runId: child.runId, ok: child.ok, outputReference: child.outputReference }.`;
|
|
1446
1471
|
}
|
|
1447
1472
|
|
|
1448
1473
|
export interface SimpleWorkflowRunPreview {
|
|
@@ -1568,6 +1593,62 @@ function walkAst(node: unknown, visit: (node: AstNode) => void, includeNestedFun
|
|
|
1568
1593
|
}
|
|
1569
1594
|
}
|
|
1570
1595
|
|
|
1596
|
+
function bindingPatternContainsName(node: unknown, name: string): boolean {
|
|
1597
|
+
if (!astNode(node)) return false;
|
|
1598
|
+
if (node.type === "Identifier") return node.name === name;
|
|
1599
|
+
if (node.type === "RestElement") return bindingPatternContainsName(node.argument, name);
|
|
1600
|
+
if (node.type === "AssignmentPattern") return bindingPatternContainsName(node.left, name);
|
|
1601
|
+
if (node.type === "ArrayPattern" && Array.isArray(node.elements)) return node.elements.some((element) => bindingPatternContainsName(element, name));
|
|
1602
|
+
if (node.type === "ObjectPattern" && Array.isArray(node.properties)) return node.properties.some((property) => {
|
|
1603
|
+
if (!astNode(property)) return false;
|
|
1604
|
+
return property.type === "RestElement"
|
|
1605
|
+
? bindingPatternContainsName(property.argument, name)
|
|
1606
|
+
: property.type === "Property" && bindingPatternContainsName(property.value, name);
|
|
1607
|
+
});
|
|
1608
|
+
return false;
|
|
1609
|
+
}
|
|
1610
|
+
|
|
1611
|
+
function definitelyReassignsBinding(node: unknown, name: string): boolean {
|
|
1612
|
+
let assignment = node;
|
|
1613
|
+
while (astNode(assignment) && assignment.type === "AssignmentExpression" && assignment.operator !== "&&=" && assignment.operator !== "||=" && assignment.operator !== "??=") {
|
|
1614
|
+
if (bindingPatternContainsName(assignment.left, name)) return true;
|
|
1615
|
+
assignment = assignment.right;
|
|
1616
|
+
}
|
|
1617
|
+
return false;
|
|
1618
|
+
}
|
|
1619
|
+
|
|
1620
|
+
function lexicalDeclarationContainsName(node: unknown, name: string): boolean {
|
|
1621
|
+
if (!astNode(node)) return false;
|
|
1622
|
+
if (node.type === "VariableDeclaration" && node.kind !== "var" && Array.isArray(node.declarations)) {
|
|
1623
|
+
return node.declarations.some((declaration) => astNode(declaration) && bindingPatternContainsName(declaration.id, name));
|
|
1624
|
+
}
|
|
1625
|
+
return (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") && bindingPatternContainsName(node.id, name);
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
function scopeShadowsIdentifier(node: AstNode, name: string): boolean {
|
|
1629
|
+
if (node.type === "BlockStatement" && Array.isArray(node.body)) return node.body.some((statement) => lexicalDeclarationContainsName(statement, name));
|
|
1630
|
+
if (node.type === "CatchClause") return bindingPatternContainsName(node.param, name);
|
|
1631
|
+
if (node.type === "ForStatement") return lexicalDeclarationContainsName(node.init, name);
|
|
1632
|
+
if (node.type === "ForInStatement" || node.type === "ForOfStatement") return lexicalDeclarationContainsName(node.left, name);
|
|
1633
|
+
if (node.type === "SwitchStatement" && Array.isArray(node.cases)) {
|
|
1634
|
+
return node.cases.some((entry) => astNode(entry) && Array.isArray(entry.consequent) && entry.consequent.some((statement) => lexicalDeclarationContainsName(statement, name)));
|
|
1635
|
+
}
|
|
1636
|
+
return false;
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
function walkAstWithoutShadowedIdentifier(node: unknown, name: string, visit: (node: AstNode) => void): void {
|
|
1640
|
+
if (Array.isArray(node)) {
|
|
1641
|
+
for (const item of node) walkAstWithoutShadowedIdentifier(item, name, visit);
|
|
1642
|
+
return;
|
|
1643
|
+
}
|
|
1644
|
+
if (!astNode(node) || scopeShadowsIdentifier(node, name)) return;
|
|
1645
|
+
visit(node);
|
|
1646
|
+
if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") return;
|
|
1647
|
+
for (const [key, child] of Object.entries(node)) {
|
|
1648
|
+
if (!AST_LOCATION_KEYS.has(key)) walkAstWithoutShadowedIdentifier(child, name, visit);
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
|
|
1571
1652
|
function definitelyNonJson(node: AstNode, normalizeUndefined = false): string | undefined {
|
|
1572
1653
|
if (node.type === "Literal") {
|
|
1573
1654
|
if (typeof node.bigint === "string") return "BigInt values are not JSON-representable";
|
|
@@ -1830,16 +1911,20 @@ export function validateWorkflowScript(script: string, options: WorkflowScriptVa
|
|
|
1830
1911
|
for (const declaration of statement.declarations) {
|
|
1831
1912
|
if (!astNode(declaration) || !astNode(declaration.id) || declaration.id.type !== "Identifier" || !astNode(declaration.init) || declaration.init.type !== "AwaitExpression" || !astNode(declaration.init.argument) || !directRunsCall(declaration.init.argument, "all")) continue;
|
|
1832
1913
|
const name = declaration.id.name as string;
|
|
1914
|
+
const laterStatements = workflowBody.body.slice(statementIndex + 1);
|
|
1833
1915
|
const keys = new Set(directRunsAllKeys(declaration.init.argument).map((entry) => entry.key));
|
|
1834
1916
|
if (keys.size === 0) continue;
|
|
1835
1917
|
const args = Array.isArray(declaration.init.argument.arguments) ? declaration.init.argument.arguments : [];
|
|
1836
1918
|
const itemCount = astNode(args[0]) && args[0].type === "ArrayExpression" && Array.isArray(args[0].elements) ? args[0].elements.length : 0;
|
|
1837
1919
|
const arrayResultShape = Array.from({ length: itemCount });
|
|
1838
|
-
for (const later of
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1920
|
+
for (const later of laterStatements) {
|
|
1921
|
+
walkAstWithoutShadowedIdentifier(later, name, (node) => {
|
|
1922
|
+
if (node.type !== "MemberExpression" || !astNode(node.object) || node.object.type !== "Identifier" || node.object.name !== name) return;
|
|
1923
|
+
const property = node.computed === true ? literalString(node.property) : astNode(node.property) && node.property.type === "Identifier" ? node.property.name as string : undefined;
|
|
1924
|
+
if (property && keys.has(property) && !(property in arrayResultShape)) errors.push({ message: `runs.all returns an ordered array; '${name}.${property}' is keyed access. Use an index, destructuring, or map(...).`, ...nodeLocation(node) });
|
|
1925
|
+
});
|
|
1926
|
+
if (statement.kind !== "const" && astNode(later) && later.type === "ExpressionStatement" && definitelyReassignsBinding(later.expression, name)) break;
|
|
1927
|
+
}
|
|
1843
1928
|
}
|
|
1844
1929
|
}
|
|
1845
1930
|
}
|
|
@@ -1905,11 +1990,11 @@ function isZeroUsage(usage: unknown): boolean {
|
|
|
1905
1990
|
}
|
|
1906
1991
|
|
|
1907
1992
|
function setupAbortResumeParams(params: Record<string, unknown>, result: WorkflowScriptChildResult, signal: AbortSignal): Record<string, unknown> | undefined {
|
|
1908
|
-
if (signal.aborted || result.ok || result.stopped || result.interrupted || !result.runId) return undefined;
|
|
1993
|
+
if (signal.aborted || result.state === "running" || result.ok || result.stopped || result.interrupted || !result.runId) return undefined;
|
|
1909
1994
|
const childResult = Array.isArray(result.results) && result.results.length === 1 && isRecord(result.results[0]) ? result.results[0] : undefined;
|
|
1910
1995
|
const error = typeof childResult?.error === "string" ? childResult.error : result.error;
|
|
1911
1996
|
if (error !== "This operation was aborted" || !isZeroUsage(childResult?.usage)) return undefined;
|
|
1912
|
-
const messages = Array.isArray(childResult?.messages) ? childResult.messages : [];
|
|
1997
|
+
const messages: unknown[] = Array.isArray(childResult?.messages) ? childResult.messages : [];
|
|
1913
1998
|
const message = messages.findLast((entry) => isRecord(entry) && entry.role === "assistant");
|
|
1914
1999
|
if (message !== undefined) {
|
|
1915
2000
|
if (!isRecord(message)) return undefined;
|
|
@@ -2052,7 +2137,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
2052
2137
|
return true;
|
|
2053
2138
|
};
|
|
2054
2139
|
const notifyChildSettled = (key: string, result: WorkflowScriptChildResult): void => {
|
|
2055
|
-
if (!options.onChildSettled || !options.workflowRunId) return;
|
|
2140
|
+
if (result.state === "running" || !options.onChildSettled || !options.workflowRunId) return;
|
|
2056
2141
|
const outcome: WorkflowChildSettledOutcome = result.ok
|
|
2057
2142
|
? "completed"
|
|
2058
2143
|
: result.stopped
|
|
@@ -2060,7 +2145,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
2060
2145
|
: result.detached
|
|
2061
2146
|
? "paused"
|
|
2062
2147
|
: "failed";
|
|
2063
|
-
const outputReference = result.outputReference ?? result.
|
|
2148
|
+
const outputReference = result.outputReference ?? result.outputArtifactPath;
|
|
2064
2149
|
try {
|
|
2065
2150
|
options.onChildSettled({
|
|
2066
2151
|
workflowRunId: options.workflowRunId,
|
|
@@ -2387,7 +2472,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
2387
2472
|
: promise.then((result) => {
|
|
2388
2473
|
const recoverableAcceptanceMetadata = result.recovery?.status === "available-for-review"
|
|
2389
2474
|
&& result.recovery.reason === "acceptance-metadata-rejected";
|
|
2390
|
-
if (!result.ok && !result.stopped && !recoverableAcceptanceMetadata) {
|
|
2475
|
+
if (!result.ok && result.state !== "running" && !result.stopped && !recoverableAcceptanceMetadata) {
|
|
2391
2476
|
const childError = new Error(result.detached ? `Run '${key}' detached: ${result.error ?? result.output}` : `Run '${key}' failed: ${result.error ?? result.output}`) as Error & { workflowErrorKind?: "detached-child" };
|
|
2392
2477
|
if (result.detached) childError.workflowErrorKind = "detached-child";
|
|
2393
2478
|
throw childError;
|
|
@@ -2418,8 +2503,9 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
2418
2503
|
if (params.baseRef !== undefined && (typeof params.baseRef !== "string" || !validGitRef(params.baseRef))) {
|
|
2419
2504
|
return respond(Promise.reject(new Error(`runs.run('${key}') ${BASE_REF_VALIDATION_ERROR}`)));
|
|
2420
2505
|
}
|
|
2421
|
-
if (params.gate !== undefined
|
|
2422
|
-
|
|
2506
|
+
if (params.gate !== undefined) {
|
|
2507
|
+
const parsedGate = parseGateInput(params.gate);
|
|
2508
|
+
if (!parsedGate.ok) return respond(Promise.reject(new Error(`runs.run('${key}') ${parsedGate.error}`)));
|
|
2423
2509
|
}
|
|
2424
2510
|
if (params.gate !== undefined && params.acceptance !== undefined && params.acceptance !== false) {
|
|
2425
2511
|
return respond(Promise.reject(new Error(`runs.run('${key}') gate cannot be combined with acceptance; use one gate command or acceptance.verify.` + describeGateAcceptanceConflict(params.gate, params.acceptance))));
|
|
@@ -2517,7 +2603,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
2517
2603
|
const reason = childController.signal.reason;
|
|
2518
2604
|
return stoppedChildResult(key, reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Workflow script aborted.");
|
|
2519
2605
|
}).then((result) => {
|
|
2520
|
-
let normalized = !result.ok && !result.error ? { ...result, error: result.output } : result;
|
|
2606
|
+
let normalized = !result.ok && result.state !== "running" && !result.error ? { ...result, error: result.output } : result;
|
|
2521
2607
|
if (resolvedResumeLineage?.length && normalized.runId) {
|
|
2522
2608
|
normalized = { ...normalized, continuation: { runIds: [...new Set([...resolvedResumeLineage, normalized.runId])] } };
|
|
2523
2609
|
}
|
|
@@ -2525,8 +2611,8 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
|
|
|
2525
2611
|
if (stoppedLaunches.has(key)) return children.get(key) ?? normalized;
|
|
2526
2612
|
children.set(key, normalized);
|
|
2527
2613
|
recordAcceptanceRecoveryBarrier(key, normalized);
|
|
2528
|
-
const state = normalized.ok ? "completed" : normalized.stopped ? "stopped" : normalized.detached ? "detached" : "failed";
|
|
2529
|
-
trace.push({ operation: "run", key, state, durationMs: Date.now() - startedAt, ...workflowStringMetadata(params), ...(generatedLaneKey ? { generatedLaneKey } : {}), ...(normalized.agent ? { agent: normalized.agent } : {}), ...(normalized.runId ? { runId: normalized.runId } : {}), ...(!normalized.ok ? { error: normalized.error ?? normalized.output } : {}) });
|
|
2614
|
+
const state = normalized.state === "running" ? "started" : normalized.ok ? "completed" : normalized.stopped ? "stopped" : normalized.detached ? "detached" : "failed";
|
|
2615
|
+
trace.push({ operation: "run", key, state, durationMs: Date.now() - startedAt, ...workflowStringMetadata(params), ...(generatedLaneKey ? { generatedLaneKey } : {}), ...(normalized.agent ? { agent: normalized.agent } : {}), ...(normalized.runId ? { runId: normalized.runId } : {}), ...(!normalized.ok && normalized.state !== "running" ? { error: normalized.error ?? normalized.output } : {}) });
|
|
2530
2616
|
traceChanged();
|
|
2531
2617
|
notifyChildSettled(key, normalized);
|
|
2532
2618
|
return normalized;
|
|
@@ -61,6 +61,7 @@ export function workflowChildSummary(input: {
|
|
|
61
61
|
progress?: ReadonlyMap<string, WorkflowChildLiveProgress>;
|
|
62
62
|
}): WorkflowChildSummary {
|
|
63
63
|
const rows = new Map<string, WorkflowChildSummary["children"][number]>();
|
|
64
|
+
const runningAsyncKeys = new Set(input.children?.filter((child) => child.state === "running").map((child) => child.key));
|
|
64
65
|
for (const entry of input.trace ?? []) {
|
|
65
66
|
if (entry.operation !== "run" || !KEY_PATTERN.test(entry.key)) continue;
|
|
66
67
|
const previous = rows.get(entry.key);
|
|
@@ -82,6 +83,7 @@ export function workflowChildSummary(input: {
|
|
|
82
83
|
for (const step of input.steps ?? []) {
|
|
83
84
|
const key = step.workflowKey;
|
|
84
85
|
if (!key || !KEY_PATTERN.test(key)) continue;
|
|
86
|
+
if (step.async && step.runId && step.status === "running") runningAsyncKeys.add(key);
|
|
85
87
|
const state = step.status === "complete" || step.status === "completed" ? "completed"
|
|
86
88
|
: step.status === "failed" ? "failed"
|
|
87
89
|
: step.status === "paused" ? "paused"
|
|
@@ -102,7 +104,7 @@ export function workflowChildSummary(input: {
|
|
|
102
104
|
for (const child of input.children ?? []) {
|
|
103
105
|
if (!KEY_PATTERN.test(child.key)) continue;
|
|
104
106
|
const result = Array.isArray(child.results) ? child.results.find((value) => value && typeof value === "object") as Record<string, unknown> | undefined : undefined;
|
|
105
|
-
const state = child.detached ? "detached" : child.stopped ? "stopped" : child.interrupted ? "paused" : child.ok ? "completed" : result?.acceptance && typeof result.acceptance === "object" && (result.acceptance as { status?: unknown }).status === "rejected" ? "rejected" : "failed";
|
|
107
|
+
const state = child.state === "running" ? "running" : child.detached ? "detached" : child.stopped ? "stopped" : child.interrupted ? "paused" : child.ok ? "completed" : result?.acceptance && typeof result.acceptance === "object" && (result.acceptance as { status?: unknown }).status === "rejected" ? "rejected" : "failed";
|
|
106
108
|
rows.set(child.key, {
|
|
107
109
|
childId: child.key,
|
|
108
110
|
state,
|
|
@@ -115,7 +117,7 @@ export function workflowChildSummary(input: {
|
|
|
115
117
|
}
|
|
116
118
|
if (input.inventoryComplete) {
|
|
117
119
|
for (const [key, row] of rows) {
|
|
118
|
-
if (!TERMINAL_STATES.has(row.state)) rows.set(key, { ...row, state: input.workflowState === "stopped" ? "stopped" : "failed" });
|
|
120
|
+
if (!TERMINAL_STATES.has(row.state) && !runningAsyncKeys.has(key)) rows.set(key, { ...row, state: input.workflowState === "stopped" ? "stopped" : "failed" });
|
|
119
121
|
}
|
|
120
122
|
}
|
|
121
123
|
for (const [key, progress] of input.progress ?? []) {
|
|
@@ -28,7 +28,10 @@ export interface WorkflowPublicChild {
|
|
|
28
28
|
output: string;
|
|
29
29
|
outputState: "present" | "absent";
|
|
30
30
|
structuredOutput?: unknown;
|
|
31
|
-
|
|
31
|
+
/** Omitted for running launch receipts. */
|
|
32
|
+
success?: boolean;
|
|
33
|
+
state?: "running";
|
|
34
|
+
asyncDir?: string;
|
|
32
35
|
terminalOutcome?: WorkflowTerminalOutcome;
|
|
33
36
|
outputReference?: string;
|
|
34
37
|
outputPathMapping?: { requestedPath: string; savedPath: string };
|
|
@@ -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
|
-
}
|