@xzzpig/pi-subagents 0.1.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 +1621 -0
- package/LICENSE +21 -0
- package/README.md +118 -0
- package/agents/delegate.md +14 -0
- package/agents/oracle.md +74 -0
- package/agents/researcher.md +52 -0
- package/agents/reviewer.md +79 -0
- package/agents/scout.md +50 -0
- package/agents/worker.md +58 -0
- package/index.ts +1 -0
- package/inspector-runner.mjs +11 -0
- package/install.mjs +93 -0
- package/package.json +105 -0
- package/prompts/gather-context-and-clarify.md +13 -0
- package/prompts/parallel-cleanup.md +59 -0
- package/prompts/parallel-research.md +50 -0
- package/prompts/parallel-review.md +54 -0
- package/prompts/review-loop.md +43 -0
- package/skills/pi-subagents/SKILL.md +41 -0
- package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
- package/skills/pi-subagents/references/execution-controls.md +428 -0
- package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
- package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
- package/src/agents/agent-management.ts +1256 -0
- package/src/agents/agent-memory.ts +254 -0
- package/src/agents/agent-refinements.ts +624 -0
- package/src/agents/agent-scope.ts +6 -0
- package/src/agents/agent-selection.ts +25 -0
- package/src/agents/agent-serializer.ts +163 -0
- package/src/agents/agents.ts +1889 -0
- package/src/agents/chain-serializer.ts +280 -0
- package/src/agents/frontmatter.ts +149 -0
- package/src/agents/identity.ts +30 -0
- package/src/agents/proactive-skills.ts +194 -0
- package/src/agents/skills.ts +761 -0
- package/src/api/background-work.ts +197 -0
- package/src/api/capability-ceiling.ts +17 -0
- package/src/api/control-channel.ts +4 -0
- package/src/api/delegation.ts +119 -0
- package/src/api/external-runs.ts +129 -0
- package/src/api/intercom-bridge.ts +3 -0
- package/src/api/pi-args.ts +5 -0
- package/src/api/preflight.ts +403 -0
- package/src/api/shared-types.ts +19 -0
- package/src/extension/config.ts +76 -0
- package/src/extension/control-notices.ts +58 -0
- package/src/extension/doctor.ts +230 -0
- package/src/extension/fanout-child.ts +201 -0
- package/src/extension/index.ts +805 -0
- package/src/extension/public-execution.ts +71 -0
- package/src/extension/rpc.ts +653 -0
- package/src/extension/schemas.ts +375 -0
- package/src/extension/steering-notices.ts +35 -0
- package/src/extension/tool-description.ts +164 -0
- package/src/inspectors/herdr/actions.ts +229 -0
- package/src/inspectors/herdr/client.ts +130 -0
- package/src/inspectors/herdr/inspector-runner.ts +141 -0
- package/src/inspectors/herdr/project-panes.ts +154 -0
- package/src/integrations/herdr-status.ts +330 -0
- package/src/intercom/intercom-bridge.ts +187 -0
- package/src/intercom/native-supervisor-channel.ts +715 -0
- package/src/intercom/result-intercom.ts +421 -0
- package/src/missions/actions.ts +410 -0
- package/src/missions/goal-driver.ts +162 -0
- package/src/missions/lifecycle.ts +346 -0
- package/src/missions/store.ts +507 -0
- package/src/missions/types.ts +157 -0
- package/src/missions/workflow-state.ts +250 -0
- package/src/policy/authority.ts +46 -0
- package/src/profiles/profiles.ts +661 -0
- package/src/runs/background/async-execution.ts +1574 -0
- package/src/runs/background/async-job-tracker.ts +511 -0
- package/src/runs/background/async-resume.ts +539 -0
- package/src/runs/background/async-status.ts +542 -0
- package/src/runs/background/auto-drain.ts +67 -0
- package/src/runs/background/chain-append.ts +328 -0
- package/src/runs/background/chain-root-attachment.ts +199 -0
- package/src/runs/background/completion-batcher.ts +168 -0
- package/src/runs/background/completion-dedupe.ts +54 -0
- package/src/runs/background/control-channel.ts +692 -0
- package/src/runs/background/fleet-view.ts +540 -0
- package/src/runs/background/notify.ts +332 -0
- package/src/runs/background/parallel-groups.ts +45 -0
- package/src/runs/background/process-terminal.ts +280 -0
- package/src/runs/background/result-watcher.ts +414 -0
- package/src/runs/background/retained-children.ts +68 -0
- package/src/runs/background/run-id-resolver.ts +167 -0
- package/src/runs/background/run-status.ts +504 -0
- package/src/runs/background/scheduled-runs.ts +753 -0
- package/src/runs/background/stale-run-reconciler.ts +396 -0
- package/src/runs/background/steering.ts +239 -0
- package/src/runs/background/subagent-runner.ts +4718 -0
- package/src/runs/background/subagent-wait.ts +661 -0
- package/src/runs/background/top-level-async.ts +14 -0
- package/src/runs/background/wait-completions.ts +112 -0
- package/src/runs/background/wait-config.ts +36 -0
- package/src/runs/background/wait-subscriptions.ts +253 -0
- package/src/runs/background/wait-tool.ts +34 -0
- package/src/runs/foreground/async-steering-action.ts +256 -0
- package/src/runs/foreground/async-stop-action.ts +65 -0
- package/src/runs/foreground/chain-clarify.ts +1354 -0
- package/src/runs/foreground/chain-execution.ts +1527 -0
- package/src/runs/foreground/execution.ts +1868 -0
- package/src/runs/foreground/foreground-control.ts +132 -0
- package/src/runs/foreground/subagent-executor.ts +5532 -0
- package/src/runs/shared/acceptance.ts +1365 -0
- package/src/runs/shared/agent-contract.ts +38 -0
- package/src/runs/shared/capability-ceiling.ts +209 -0
- package/src/runs/shared/chain-outputs.ts +118 -0
- package/src/runs/shared/child-protocol.ts +401 -0
- package/src/runs/shared/completion-guard.ts +95 -0
- package/src/runs/shared/context-mode.ts +44 -0
- package/src/runs/shared/dynamic-fanout.ts +297 -0
- package/src/runs/shared/external-cli-runner.ts +130 -0
- package/src/runs/shared/long-running-guard.ts +220 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
- package/src/runs/shared/model-fallback.ts +336 -0
- package/src/runs/shared/model-scope.ts +128 -0
- package/src/runs/shared/nested-events.ts +1076 -0
- package/src/runs/shared/nested-path.ts +52 -0
- package/src/runs/shared/nested-render.ts +123 -0
- package/src/runs/shared/parallel-handoff.ts +238 -0
- package/src/runs/shared/parallel-utils.ts +256 -0
- package/src/runs/shared/permissions.ts +95 -0
- package/src/runs/shared/pi-args.ts +808 -0
- package/src/runs/shared/pi-spawn.ts +163 -0
- package/src/runs/shared/process-signal.ts +19 -0
- package/src/runs/shared/run-history.ts +181 -0
- package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
- package/src/runs/shared/session-lease.ts +299 -0
- package/src/runs/shared/single-output.ts +235 -0
- package/src/runs/shared/spawn-budget.ts +128 -0
- package/src/runs/shared/structured-output.ts +182 -0
- package/src/runs/shared/subagent-control.ts +231 -0
- package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
- package/src/runs/shared/subagent-startup-retry.ts +104 -0
- package/src/runs/shared/task-intent.ts +181 -0
- package/src/runs/shared/tool-availability.ts +83 -0
- package/src/runs/shared/tool-budget.ts +80 -0
- package/src/runs/shared/turn-budget.ts +98 -0
- package/src/runs/shared/usage-budget.ts +65 -0
- package/src/runs/shared/workflow-graph.ts +231 -0
- package/src/runs/shared/worktree.ts +759 -0
- package/src/shared/accessible-dir.ts +47 -0
- package/src/shared/artifacts.ts +285 -0
- package/src/shared/atomic-json.ts +61 -0
- package/src/shared/child-transcript.ts +264 -0
- package/src/shared/file-coalescer.ts +40 -0
- package/src/shared/file-system-retry.ts +47 -0
- package/src/shared/fork-context.ts +213 -0
- package/src/shared/formatters.ts +133 -0
- package/src/shared/jsonl-writer.ts +81 -0
- package/src/shared/launch-contract.ts +124 -0
- package/src/shared/model-info.ts +81 -0
- package/src/shared/post-exit-stdio-guard.ts +85 -0
- package/src/shared/session-identity.ts +10 -0
- package/src/shared/session-tokens.ts +44 -0
- package/src/shared/settings.ts +501 -0
- package/src/shared/status-format.ts +55 -0
- package/src/shared/types.ts +2069 -0
- package/src/shared/utils.ts +613 -0
- package/src/slash/delegation-adapters.ts +434 -0
- package/src/slash/delegation-json.ts +108 -0
- package/src/slash/delegation-request.ts +166 -0
- package/src/slash/prompt-template-bridge.ts +383 -0
- package/src/slash/prompt-workflows.ts +300 -0
- package/src/slash/selector.ts +147 -0
- package/src/slash/slash-bridge.ts +192 -0
- package/src/slash/slash-commands.ts +994 -0
- package/src/slash/slash-live-state.ts +296 -0
- package/src/slash/subagents-admin.ts +432 -0
- package/src/tui/fleet-status.ts +564 -0
- package/src/tui/fleet-transcript.ts +577 -0
- package/src/tui/fleet.ts +879 -0
- package/src/tui/render-helpers.ts +80 -0
- package/src/tui/render.ts +2029 -0
- package/src/types/pi-runtime-compat.d.ts +8 -0
- package/src/watchdog/change-signature.ts +220 -0
- package/src/watchdog/child-status.ts +205 -0
- package/src/watchdog/emission-guard.ts +123 -0
- package/src/watchdog/lsp-diagnostics.ts +537 -0
- package/src/watchdog/model-selection.ts +167 -0
- package/src/watchdog/permission-arbiter.ts +145 -0
- package/src/watchdog/register-child.ts +117 -0
- package/src/watchdog/register-main.ts +440 -0
- package/src/watchdog/render.ts +54 -0
- package/src/watchdog/review.ts +302 -0
- package/src/watchdog/runtime.ts +868 -0
- package/src/watchdog/scope.ts +62 -0
- package/src/watchdog/settings.ts +568 -0
- package/src/watchdog/tool-actions.ts +155 -0
- package/src/watchdog/turn-delta.ts +161 -0
- package/src/watchdog/types.ts +198 -0
- package/src/watchdog/warning-format.ts +73 -0
- package/src/workflows/chat-progress.ts +140 -0
- package/src/workflows/scripted-workflow.ts +506 -0
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type { Usage } from "../../shared/types.ts";
|
|
2
|
+
import { formatProcessSignalError } from "./process-signal.ts";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Retry delays for child processes that exit before any model or tool activity.
|
|
6
|
+
* The schedule is intentionally short and bounded to avoid amplifying persistent
|
|
7
|
+
* launch failures while allowing concurrent Pi startup locks to clear.
|
|
8
|
+
*/
|
|
9
|
+
export const SUBAGENT_STARTUP_RETRY_DELAYS_MS = [250, 750, 1500] as const;
|
|
10
|
+
|
|
11
|
+
/** A genuine startup race should fail well before a model request can complete. */
|
|
12
|
+
export const MAX_SUBAGENT_STARTUP_FAILURE_DURATION_MS = 2000;
|
|
13
|
+
|
|
14
|
+
const SIGKILL_PROCESS_SIGNAL_ERROR = formatProcessSignalError("SIGKILL");
|
|
15
|
+
|
|
16
|
+
export interface SubagentStartupFailureEvidence {
|
|
17
|
+
exitCode: number | null | undefined;
|
|
18
|
+
error?: string;
|
|
19
|
+
finalOutput?: string;
|
|
20
|
+
messageCount: number;
|
|
21
|
+
toolCount: number;
|
|
22
|
+
usage: Usage;
|
|
23
|
+
durationMs: number;
|
|
24
|
+
protocolError?: unknown;
|
|
25
|
+
processSignal?: string | null;
|
|
26
|
+
observedMutationAttempt?: boolean;
|
|
27
|
+
detached?: boolean;
|
|
28
|
+
interrupted?: boolean;
|
|
29
|
+
timedOut?: boolean;
|
|
30
|
+
stopped?: boolean;
|
|
31
|
+
turnBudgetExceeded?: boolean;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function hasUsage(usage: Usage): boolean {
|
|
35
|
+
return usage.input !== 0
|
|
36
|
+
|| usage.output !== 0
|
|
37
|
+
|| usage.cacheRead !== 0
|
|
38
|
+
|| usage.cacheWrite !== 0
|
|
39
|
+
|| usage.cost !== 0
|
|
40
|
+
|| usage.turns !== 0;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Classify only unexplained, zero-activity child exits as startup failures.
|
|
45
|
+
* This intentionally fails closed: any model output, tool activity, usage,
|
|
46
|
+
* mutation evidence, diagnostic, or lifecycle interruption prevents a retry.
|
|
47
|
+
*/
|
|
48
|
+
export function isRetryableSubagentStartupFailure(evidence: SubagentStartupFailureEvidence): boolean {
|
|
49
|
+
return evidence.exitCode !== undefined
|
|
50
|
+
&& evidence.exitCode !== null
|
|
51
|
+
&& evidence.exitCode !== 0
|
|
52
|
+
&& (!evidence.error?.trim() || evidence.error === SIGKILL_PROCESS_SIGNAL_ERROR)
|
|
53
|
+
&& !evidence.finalOutput?.trim()
|
|
54
|
+
&& evidence.messageCount === 0
|
|
55
|
+
&& evidence.toolCount === 0
|
|
56
|
+
&& !hasUsage(evidence.usage)
|
|
57
|
+
&& evidence.durationMs >= 0
|
|
58
|
+
&& evidence.durationMs <= MAX_SUBAGENT_STARTUP_FAILURE_DURATION_MS
|
|
59
|
+
&& evidence.protocolError === undefined
|
|
60
|
+
&& (evidence.processSignal === undefined || evidence.processSignal === null || evidence.processSignal === "SIGKILL")
|
|
61
|
+
&& evidence.observedMutationAttempt !== true
|
|
62
|
+
&& evidence.detached !== true
|
|
63
|
+
&& evidence.interrupted !== true
|
|
64
|
+
&& evidence.timedOut !== true
|
|
65
|
+
&& evidence.stopped !== true
|
|
66
|
+
&& evidence.turnBudgetExceeded !== true;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function formatSubagentStartupRetryNote(input: {
|
|
70
|
+
model: string;
|
|
71
|
+
attempt: number;
|
|
72
|
+
maxAttempts: number;
|
|
73
|
+
delayMs: number;
|
|
74
|
+
}): string {
|
|
75
|
+
return `[startup-retry] ${input.model} exited before model or tool activity (attempt ${input.attempt}/${input.maxAttempts}). Retrying the same model in ${input.delayMs}ms.`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function formatSubagentStartupRetryExhaustedError(input: {
|
|
79
|
+
model: string;
|
|
80
|
+
attempts: number;
|
|
81
|
+
}): string {
|
|
82
|
+
return `Subagent failed to start after ${input.attempts} attempts on ${input.model}; no model, tool, output, usage, or diagnostic activity was observed. This may be a concurrent Pi startup race. Retry the run or temporarily lower subagent concurrency.`;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Wait for a retry delay, returning false when any lifecycle signal aborts it. */
|
|
86
|
+
export async function waitForSubagentStartupRetry(delayMs: number, signals: Array<AbortSignal | undefined>): Promise<boolean> {
|
|
87
|
+
const activeSignals = signals.filter((signal): signal is AbortSignal => Boolean(signal));
|
|
88
|
+
if (activeSignals.some((signal) => signal.aborted)) return false;
|
|
89
|
+
if (delayMs <= 0) return true;
|
|
90
|
+
|
|
91
|
+
return await new Promise<boolean>((resolve) => {
|
|
92
|
+
let settled = false;
|
|
93
|
+
const finish = (shouldRetry: boolean): void => {
|
|
94
|
+
if (settled) return;
|
|
95
|
+
settled = true;
|
|
96
|
+
clearTimeout(timer);
|
|
97
|
+
for (const signal of activeSignals) signal.removeEventListener("abort", abort);
|
|
98
|
+
resolve(shouldRetry);
|
|
99
|
+
};
|
|
100
|
+
const abort = (): void => finish(false);
|
|
101
|
+
const timer = setTimeout(() => finish(true), delayMs);
|
|
102
|
+
for (const signal of activeSignals) signal.addEventListener("abort", abort, { once: true });
|
|
103
|
+
});
|
|
104
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared task mutation-intent classifier.
|
|
3
|
+
*
|
|
4
|
+
* Single authority for reading a task's wording, answering two different
|
|
5
|
+
* questions from one prohibition analysis:
|
|
6
|
+
*
|
|
7
|
+
* - `classifyTaskMutationIntent` / `expectsImplementationMutation`: does the
|
|
8
|
+
* task REQUIRE file changes? Consumed by the completion mutation guard,
|
|
9
|
+
* which blocks completion, so its vocabulary is deliberately narrow.
|
|
10
|
+
* - `taskMayMutate`: COULD the task plausibly change files? Consumed by
|
|
11
|
+
* acceptance level inference, which only raises evidence gates, so its
|
|
12
|
+
* vocabulary is deliberately broad (any bare write verb).
|
|
13
|
+
*
|
|
14
|
+
* Explicit read-only wording ("do not modify", "review only") is a task-level
|
|
15
|
+
* intent only when no write imperative survives outside those phrases. A task
|
|
16
|
+
* like "Do not modify tests; implement the fix" is an implementation task with
|
|
17
|
+
* a scoped constraint, not a read-only task.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
const REVIEW_ONLY_PATTERNS = [
|
|
21
|
+
/\breview only\b/i,
|
|
22
|
+
/\bsuggest fixes only\b/i,
|
|
23
|
+
/\bonly return findings\b/i,
|
|
24
|
+
/\breturn findings only\b/i,
|
|
25
|
+
];
|
|
26
|
+
|
|
27
|
+
const REVIEWER_REQUIRED_EDIT_PATTERNS = [
|
|
28
|
+
/\bmust\s+(?:edit|modify|change|fix|patch|apply|implement)\b/i,
|
|
29
|
+
/\brequired\s+to\s+(?:edit|modify|change|fix|patch|apply|implement)\b/i,
|
|
30
|
+
/(?:^|[.!?\n]\s*)implement\s+(?:the\s+)?(?:approved|requested|specified|file|code|source|fix(?:es)?|changes?)\b/i,
|
|
31
|
+
/\bregardless\s+of\s+findings\b/i,
|
|
32
|
+
/\balways\s+(?:edit|modify|change|fix|patch|apply|implement)\b/i,
|
|
33
|
+
/\bapply\s+(?:the\s+)?fix(?:es)?\s+directly\b/i,
|
|
34
|
+
/\bmake\s+(?:the\s+)?code\s+changes\b/i,
|
|
35
|
+
];
|
|
36
|
+
|
|
37
|
+
// The prohibition's object ends at punctuation or at a coordinating word
|
|
38
|
+
// (but/and/then), so a follow-on clause like "but implement the fix" stays in
|
|
39
|
+
// the text for write-intent testing instead of being swallowed as the object.
|
|
40
|
+
const NO_EDIT_PROHIBITION_PATTERN = /\b(?:do not|don't|must not)\s+(?:edit|modify|write(?:\s+to)?|touch|change)\b((?:(?!\b(?:but|and|then)\b)[^.;,:!?\n–—-])*)/gi;
|
|
41
|
+
|
|
42
|
+
/** Objects of a no-edit prohibition that mean "the codebase in general" rather than a named scope. */
|
|
43
|
+
const GENERIC_PROHIBITION_OBJECT = /^\s*(?:(?:any|all|the|these|those|your|our|existing|project|product|source|sources|config|configs|repo|repository)[\s/,-]*)*(?:files?|code|codebase|sources?|anything|repo(?:sitory)?)?\s*$/i;
|
|
44
|
+
|
|
45
|
+
const SCOPED_NO_EDIT_CONSTRAINT_PATTERNS = [
|
|
46
|
+
/\bdo not edit files?\s+outside\b/i,
|
|
47
|
+
/\bdo not edit\s+outside\b/i,
|
|
48
|
+
/\bdo not edit\s+unrelated files?\b/i,
|
|
49
|
+
/\bdo not change\s+unrelated files?\b/i,
|
|
50
|
+
/\bdo not modify\s+unrelated files?\b/i,
|
|
51
|
+
];
|
|
52
|
+
|
|
53
|
+
const NO_TOOL_INTENT_PATTERNS = [
|
|
54
|
+
/\bno tools? needed\b/i,
|
|
55
|
+
/\bno tools? required\b/i,
|
|
56
|
+
/\bwithout using tools\b/i,
|
|
57
|
+
/\bdo not use tools\b/i,
|
|
58
|
+
/\bdon't use tools\b/i,
|
|
59
|
+
];
|
|
60
|
+
|
|
61
|
+
const READ_ONLY_DELIVERABLE_PATTERNS = [
|
|
62
|
+
/\b(?:draft|write|compose|prepare|produce)\s+(?:(?:a|an|the)\s+)?(?:github\s+)?(?:issue|bug report|issue draft|issue body|proposal|plan|report|summary|findings?|analysis|recommendations?)\b/i,
|
|
63
|
+
/\b(?:issue|bug report)\s+(?:draft|body|template)\b/i,
|
|
64
|
+
/\b(?:return|provide|produce)\s+(?:text|markdown|answer|findings?|recommendations?)\s+only\b/i,
|
|
65
|
+
];
|
|
66
|
+
|
|
67
|
+
const RESEARCH_AGENT_PATTERNS = [
|
|
68
|
+
/\binvestigate\b/i,
|
|
69
|
+
/\bscout\b/i,
|
|
70
|
+
/\bresearch(?:er)?\b/i,
|
|
71
|
+
];
|
|
72
|
+
|
|
73
|
+
const FIX_OR_PATCH_IMPLEMENTATION_PATTERN = /\b(?:fix|patch)\s+(?:(?:it|this|that|them|each|any|all|these|those)\b|(?:(?:a|an|the|any|all)\s+)?(?:(?:failing|failed|broken|flaky|red|cold|start|current|existing|reported|approved|known|regression|unit|integration|e2e|source|typescript|type-?script|ts|type-?check|compiler)\s+)*(?:bug|defect|issues?|problems?|failures?|regressions?|tests?|errors?|items?|typos?|code|source|implementation|component|function|module|class|method|logic|file|files|readme|docs?|changelog|package\.json|config|manifest|extension|prompt|command|lint(?:ing)?|build|ci|type-?check|type\s+checking)\b)/i;
|
|
74
|
+
|
|
75
|
+
const WORKER_IMPLEMENTATION_PATTERNS = [
|
|
76
|
+
/\b(?:implement|edit|modify|refactor|delete)\b/i,
|
|
77
|
+
FIX_OR_PATCH_IMPLEMENTATION_PATTERN,
|
|
78
|
+
/\b(?:update|add|remove|replace|create)\b(?!\s+(?:(?:a|an|the)\s+)?(?:report|summary|findings?)(?:\b|$))/i,
|
|
79
|
+
/\bapply\s+(?:the\s+)?(?:(?:suggested|proposed|recommended)\s+)?(?:changes?|fix(?:es)?|patch)\b/i,
|
|
80
|
+
/\bmake\s+(?:the\s+)?changes\b/i,
|
|
81
|
+
/\bdo those fixes\b/i,
|
|
82
|
+
];
|
|
83
|
+
|
|
84
|
+
const GENERAL_IMPLEMENTATION_PATTERNS = [
|
|
85
|
+
/\b(?:implement|edit|modify|refactor)\b/i,
|
|
86
|
+
FIX_OR_PATCH_IMPLEMENTATION_PATTERN,
|
|
87
|
+
/\bapply\s+(?:the\s+)?(?:(?:suggested|proposed|recommended)\s+)?(?:changes?|fix(?:es)?|patch)\b/i,
|
|
88
|
+
/\bmake\s+(?:the\s+)?changes\b/i,
|
|
89
|
+
/\bdo those fixes\b/i,
|
|
90
|
+
/\b(?:update|add|remove|replace|delete|create)\s+(?:the\s+)?(?:file|files|code|source|implementation|test|tests|component|function|module|class|method|logic|import|imports|readme|docs?|changelog|package\.json|config|manifest|extension|prompt|command)\b/i,
|
|
91
|
+
];
|
|
92
|
+
|
|
93
|
+
export type TaskMutationIntent = { kind: "implementation" } | { kind: "read-only" } | { kind: "unknown" };
|
|
94
|
+
|
|
95
|
+
function stripFrameworkInstructions(task: string): string {
|
|
96
|
+
return task
|
|
97
|
+
.split("\n")
|
|
98
|
+
.filter((line) => !/^\s*\[(?:Write to|Read from):/i.test(line))
|
|
99
|
+
.filter((line) => !/^\s*(?:Create and maintain progress at:|Update progress at:|\*\*Output:\*\*|Write your findings to(?: exactly this path)?:|Return the complete artifact in your final response\.|The runtime will persist it to exactly this path:|Do not call contact_supervisor merely because no write-capable tool is available\.|This path is authoritative for this run\.|Ignore any other output filename or output path mentioned elsewhere)/i.test(line))
|
|
100
|
+
.join("\n");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function stripPatterns(task: string, patterns: RegExp[]): string {
|
|
104
|
+
let stripped = task;
|
|
105
|
+
for (const pattern of patterns) {
|
|
106
|
+
const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
|
|
107
|
+
stripped = stripped.replace(new RegExp(pattern.source, flags), " ");
|
|
108
|
+
}
|
|
109
|
+
return stripped;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
interface NoEditProhibitionAnalysis {
|
|
113
|
+
/** True when any prohibition (or review-only/no-tool wording) is present. */
|
|
114
|
+
present: boolean;
|
|
115
|
+
/** True when a prohibition covers files/code in general; such wording wins over write verbs. */
|
|
116
|
+
blanket: boolean;
|
|
117
|
+
/** Task text with prohibition phrases and their objects removed, for write-intent testing. */
|
|
118
|
+
strippedText: string;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function analyzeNoEditProhibitions(taskText: string): NoEditProhibitionAnalysis {
|
|
122
|
+
let present = REVIEW_ONLY_PATTERNS.some((pattern) => pattern.test(taskText))
|
|
123
|
+
|| NO_TOOL_INTENT_PATTERNS.some((pattern) => pattern.test(taskText));
|
|
124
|
+
let blanket = present;
|
|
125
|
+
let strippedText = stripPatterns(taskText, [...REVIEW_ONLY_PATTERNS, ...NO_TOOL_INTENT_PATTERNS]);
|
|
126
|
+
strippedText = strippedText.replace(new RegExp(NO_EDIT_PROHIBITION_PATTERN.source, NO_EDIT_PROHIBITION_PATTERN.flags), (_match, object: string) => {
|
|
127
|
+
present = true;
|
|
128
|
+
if (GENERIC_PROHIBITION_OBJECT.test(object)) blanket = true;
|
|
129
|
+
return " ";
|
|
130
|
+
});
|
|
131
|
+
return { present, blanket, strippedText };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function taskHasReadOnlyDeliverable(taskText: string): boolean {
|
|
135
|
+
return READ_ONLY_DELIVERABLE_PATTERNS.some((pattern) => pattern.test(taskText));
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function isReviewerStyleAgent(agent: string): boolean {
|
|
139
|
+
return /\b(?:advisor|reviewer|oracle)\b/i.test(agent);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function hasImplementationIntent(agent: string, taskText: string): boolean {
|
|
143
|
+
if (isReviewerStyleAgent(agent)) return REVIEWER_REQUIRED_EDIT_PATTERNS.some((pattern) => pattern.test(taskText));
|
|
144
|
+
if (agent === "worker") return WORKER_IMPLEMENTATION_PATTERNS.some((pattern) => pattern.test(taskText));
|
|
145
|
+
return GENERAL_IMPLEMENTATION_PATTERNS.some((pattern) => pattern.test(taskText));
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function classifyTaskMutationIntent(agent: string, task: string): TaskMutationIntent {
|
|
149
|
+
const taskText = stripFrameworkInstructions(task);
|
|
150
|
+
const taskTextWithoutScopedConstraints = stripPatterns(taskText, SCOPED_NO_EDIT_CONSTRAINT_PATTERNS);
|
|
151
|
+
const prohibitions = analyzeNoEditProhibitions(taskTextWithoutScopedConstraints);
|
|
152
|
+
if (prohibitions.present) {
|
|
153
|
+
if (prohibitions.blanket) return { kind: "read-only" };
|
|
154
|
+
return hasImplementationIntent(agent, prohibitions.strippedText) ? { kind: "implementation" } : { kind: "read-only" };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
if (RESEARCH_AGENT_PATTERNS.some((pattern) => pattern.test(agent))) return { kind: "read-only" };
|
|
158
|
+
if (hasImplementationIntent(agent, taskText)) return { kind: "implementation" };
|
|
159
|
+
if (isReviewerStyleAgent(agent)) return { kind: "read-only" };
|
|
160
|
+
return taskHasReadOnlyDeliverable(taskTextWithoutScopedConstraints) ? { kind: "read-only" } : { kind: "unknown" };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function expectsImplementationMutation(agent: string, task: string): boolean {
|
|
164
|
+
return classifyTaskMutationIntent(agent, task).kind === "implementation";
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Bare write verbs that make a task write-capable for acceptance inference. */
|
|
168
|
+
const MAY_MUTATE_VERB_PATTERN = /\b(?:fix|implement|update|write|edit|modify|migrate|delete|remove|refactor|commit)\b/i;
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Whether the task could plausibly change files. Blanket prohibitions win;
|
|
172
|
+
* write verbs inside a scoped prohibition's object or a read-only deliverable
|
|
173
|
+
* phrase ("write a summary report") do not count; any other bare write verb
|
|
174
|
+
* does.
|
|
175
|
+
*/
|
|
176
|
+
export function taskMayMutate(task: string): boolean {
|
|
177
|
+
const taskText = stripPatterns(stripFrameworkInstructions(task), SCOPED_NO_EDIT_CONSTRAINT_PATTERNS);
|
|
178
|
+
const prohibitions = analyzeNoEditProhibitions(taskText);
|
|
179
|
+
if (prohibitions.blanket) return false;
|
|
180
|
+
return MAY_MUTATE_VERB_PATTERN.test(stripPatterns(prohibitions.strippedText, READ_ONLY_DELIVERABLE_PATTERNS));
|
|
181
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
|
|
4
|
+
export const REQUIRED_CHILD_TOOLS_ENV = "PI_SUBAGENT_REQUIRED_TOOLS";
|
|
5
|
+
export const MCP_DIRECT_CHILD_TOOLS_ENV = "PI_SUBAGENT_MCP_DIRECT_TOOLS";
|
|
6
|
+
export const CHILD_TOOL_DIAGNOSTIC_PATH_ENV = "PI_SUBAGENT_TOOL_DIAGNOSTIC_PATH";
|
|
7
|
+
|
|
8
|
+
export interface ChildToolDiagnostic {
|
|
9
|
+
agent?: string;
|
|
10
|
+
required: string[];
|
|
11
|
+
available: string[];
|
|
12
|
+
missing: string[];
|
|
13
|
+
missingMcpDirectTools?: string[];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const PI_CORE_CHILD_TOOLS = new Set(["bash", "edit", "find", "grep", "ls", "read", "write"]);
|
|
17
|
+
|
|
18
|
+
export function writeChildToolDiagnostic(
|
|
19
|
+
filePath: string,
|
|
20
|
+
required: string[],
|
|
21
|
+
available: string[],
|
|
22
|
+
agent?: string,
|
|
23
|
+
mcpDirectTools?: string[],
|
|
24
|
+
): ChildToolDiagnostic | undefined {
|
|
25
|
+
const availableNames = new Set([...available, ...PI_CORE_CHILD_TOOLS]);
|
|
26
|
+
const missing = required.filter((name) => !availableNames.has(name));
|
|
27
|
+
if (missing.length === 0) {
|
|
28
|
+
fs.rmSync(filePath, { force: true });
|
|
29
|
+
return undefined;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const missingMcpDirectTools = mcpDirectTools?.length
|
|
33
|
+
? missing.filter((name) => mcpDirectTools.includes(name))
|
|
34
|
+
: [];
|
|
35
|
+
const diagnostic: ChildToolDiagnostic = {
|
|
36
|
+
agent,
|
|
37
|
+
required,
|
|
38
|
+
available,
|
|
39
|
+
missing,
|
|
40
|
+
...(missingMcpDirectTools.length > 0 ? { missingMcpDirectTools } : {}),
|
|
41
|
+
};
|
|
42
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
43
|
+
fs.writeFileSync(filePath, JSON.stringify(diagnostic), { mode: 0o600 });
|
|
44
|
+
return diagnostic;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function readChildToolDiagnostic(filePath: string | undefined): ChildToolDiagnostic | undefined {
|
|
48
|
+
if (!filePath || !fs.existsSync(filePath)) return undefined;
|
|
49
|
+
const parsed = JSON.parse(fs.readFileSync(filePath, "utf-8")) as Partial<ChildToolDiagnostic>;
|
|
50
|
+
const stringArray = (value: unknown): value is string[] => Array.isArray(value) && value.every((entry) => typeof entry === "string" && entry.length > 0);
|
|
51
|
+
if (!stringArray(parsed.required) || !stringArray(parsed.available) || !stringArray(parsed.missing) || (parsed.agent !== undefined && typeof parsed.agent !== "string") || (parsed.missingMcpDirectTools !== undefined && !stringArray(parsed.missingMcpDirectTools))) {
|
|
52
|
+
throw new Error(`Malformed child tool diagnostic at '${filePath}'.`);
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
...(parsed.agent ? { agent: parsed.agent } : {}),
|
|
56
|
+
required: parsed.required,
|
|
57
|
+
available: parsed.available,
|
|
58
|
+
missing: parsed.missing,
|
|
59
|
+
...(parsed.missingMcpDirectTools ? { missingMcpDirectTools: parsed.missingMcpDirectTools } : {}),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function formatChildToolDiagnostic(diagnostic: ChildToolDiagnostic): string {
|
|
64
|
+
const subject = diagnostic.agent ? `Agent '${diagnostic.agent}'` : "Subagent";
|
|
65
|
+
return [
|
|
66
|
+
`${subject} requested unavailable child tools: ${diagnostic.missing.join(", ")}.`,
|
|
67
|
+
"The `tools` field is a strict allowlist; it does not load extension code.",
|
|
68
|
+
...(diagnostic.missingMcpDirectTools?.length
|
|
69
|
+
? [`Resolved MCP direct tools missing from the child registry: ${diagnostic.missingMcpDirectTools.join(", ")}. This indicates a host/pi-mcp-adapter registration problem, not a tool-call failure.`]
|
|
70
|
+
: []),
|
|
71
|
+
"For extension tools, add the provider path to `subagentOnlyExtensions` (child-only), `extensions`, or as a path-like entry in `tools`, while keeping each registered tool name in `tools`.",
|
|
72
|
+
"For MCP tools, verify the MCP adapter configuration and selected tool names. For builtin tools, verify the name against the installed Pi version.",
|
|
73
|
+
].join("\n");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function readChildToolDiagnosticError(filePath: string | undefined): string | undefined {
|
|
77
|
+
try {
|
|
78
|
+
const diagnostic = readChildToolDiagnostic(filePath);
|
|
79
|
+
return diagnostic ? formatChildToolDiagnostic(diagnostic) : undefined;
|
|
80
|
+
} catch (error) {
|
|
81
|
+
return `Failed to read child tool availability diagnostic: ${error instanceof Error ? error.message : String(error)}`;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import type { ResolvedToolBudget, ToolBudgetConfig, ToolBudgetState } from "../../shared/types.ts";
|
|
2
|
+
|
|
3
|
+
export const DEFAULT_TOOL_BUDGET_BLOCK = ["read", "grep", "find", "ls"] as const;
|
|
4
|
+
export const TOOL_BUDGET_ENV = "PI_SUBAGENT_TOOL_BUDGET";
|
|
5
|
+
export const TOOL_BUDGET_ZERO_AUTH_ENV = "PI_SUBAGENT_TOOL_BUDGET_ZERO_AUTH";
|
|
6
|
+
|
|
7
|
+
export function normalizeToolBudgetBlock(block: ToolBudgetConfig["block"] | undefined): "*" | string[] {
|
|
8
|
+
if (block === "*") return "*";
|
|
9
|
+
if (block === undefined) return [...DEFAULT_TOOL_BUDGET_BLOCK];
|
|
10
|
+
return [...new Set(block.map((tool) => tool.trim()).filter(Boolean))];
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function validateToolBudgetConfig(
|
|
14
|
+
raw: unknown,
|
|
15
|
+
label = "toolBudget",
|
|
16
|
+
options: { minimumHard?: 0 | 1 } = {},
|
|
17
|
+
): { budget?: ResolvedToolBudget; error?: string } {
|
|
18
|
+
if (raw === undefined) return {};
|
|
19
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { error: `${label} must be an object with hard and optional soft/block.` };
|
|
20
|
+
const value = raw as ToolBudgetConfig;
|
|
21
|
+
const minimumHard = options.minimumHard ?? 1;
|
|
22
|
+
if (typeof value.hard !== "number" || !Number.isInteger(value.hard) || value.hard < minimumHard) {
|
|
23
|
+
return { error: `${label}.hard must be an integer >= ${minimumHard}.` };
|
|
24
|
+
}
|
|
25
|
+
if (value.soft !== undefined && (typeof value.soft !== "number" || !Number.isInteger(value.soft) || value.soft < 1)) {
|
|
26
|
+
return { error: `${label}.soft must be an integer >= 1 when provided.` };
|
|
27
|
+
}
|
|
28
|
+
if (value.soft !== undefined && value.soft > value.hard) {
|
|
29
|
+
return { error: `${label}.soft must be <= ${label}.hard.` };
|
|
30
|
+
}
|
|
31
|
+
if (value.block !== undefined && value.block !== "*") {
|
|
32
|
+
if (!Array.isArray(value.block)) return { error: `${label}.block must be "*" or an array of tool names.` };
|
|
33
|
+
if (value.block.length === 0) return { error: `${label}.block must contain at least one tool name.` };
|
|
34
|
+
for (const item of value.block) {
|
|
35
|
+
if (typeof item !== "string" || !item.trim()) return { error: `${label}.block must contain non-empty tool names.` };
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return { budget: { hard: value.hard, ...(value.soft !== undefined ? { soft: value.soft } : {}), block: normalizeToolBudgetBlock(value.block) } };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function initialToolBudgetState(budget: ResolvedToolBudget): ToolBudgetState {
|
|
42
|
+
return { ...budget, toolCount: 0, outcome: "within-budget" };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function toolBudgetState(budget: ResolvedToolBudget, toolCount: number, blockedTool?: string): ToolBudgetState {
|
|
46
|
+
const overHard = toolCount > budget.hard;
|
|
47
|
+
const overSoft = budget.soft !== undefined && toolCount >= budget.soft;
|
|
48
|
+
return {
|
|
49
|
+
...budget,
|
|
50
|
+
toolCount,
|
|
51
|
+
outcome: overHard ? "hard-blocked" : overSoft ? "soft-reached" : "within-budget",
|
|
52
|
+
...(overSoft ? { softReachedAt: budget.soft } : {}),
|
|
53
|
+
...(overHard ? { hardReachedAt: budget.hard, blockedTool } : {}),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function shouldBlockToolForBudget(budget: ResolvedToolBudget, toolName: string, nextToolCount: number): boolean {
|
|
58
|
+
if (nextToolCount <= budget.hard) return false;
|
|
59
|
+
return budget.block === "*" || budget.block.includes(toolName);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function toolBudgetSoftNudge(budget: ResolvedToolBudget, toolCount: number): string {
|
|
63
|
+
return `Tool budget soft limit reached after ${toolCount} tool call${toolCount === 1 ? "" : "s"} (soft ${budget.soft}, hard ${budget.hard}). Stop starting new browsing/search work and finalize from the context you already have.`;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function toolBudgetBlockedMessage(budget: ResolvedToolBudget, toolName: string, toolCount: number): string {
|
|
67
|
+
return `Tool budget hard limit reached after ${toolCount} tool call${toolCount === 1 ? "" : "s"} (hard ${budget.hard}). The '${toolName}' tool is blocked so you can finalize from the context you already have.`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function encodeToolBudgetEnv(budget: ResolvedToolBudget | undefined): string | undefined {
|
|
71
|
+
return budget ? JSON.stringify(budget) : undefined;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function decodeToolBudgetEnv(value: string | undefined, options: { allowZero?: boolean } = {}): ResolvedToolBudget | undefined {
|
|
75
|
+
if (!value?.trim()) return undefined;
|
|
76
|
+
const parsed = JSON.parse(value) as unknown;
|
|
77
|
+
const normalized = validateToolBudgetConfig(parsed, TOOL_BUDGET_ENV, options.allowZero ? { minimumHard: 0 } : undefined);
|
|
78
|
+
if (normalized.error) throw new Error(normalized.error);
|
|
79
|
+
return normalized.budget;
|
|
80
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { ResolvedTurnBudget, TurnBudgetState } from "../../shared/types.ts";
|
|
2
|
+
|
|
3
|
+
export const DEFAULT_TURN_BUDGET_GRACE_TURNS = 1;
|
|
4
|
+
|
|
5
|
+
export function resolveTurnBudgetConfig(
|
|
6
|
+
raw: unknown,
|
|
7
|
+
label = "turnBudget",
|
|
8
|
+
): { turnBudget?: ResolvedTurnBudget; error?: string } {
|
|
9
|
+
if (raw === undefined) return {};
|
|
10
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
11
|
+
return { error: `${label} must be an object with maxTurns and optional graceTurns.` };
|
|
12
|
+
}
|
|
13
|
+
const unknownField = Object.keys(raw).find((key) => key !== "maxTurns" && key !== "graceTurns");
|
|
14
|
+
if (unknownField) return { error: `${label}.${unknownField} is not supported.` };
|
|
15
|
+
const budget = raw as { maxTurns?: unknown; graceTurns?: unknown };
|
|
16
|
+
if (typeof budget.maxTurns !== "number" || !Number.isInteger(budget.maxTurns) || budget.maxTurns < 1) {
|
|
17
|
+
return { error: `${label}.maxTurns must be an integer >= 1.` };
|
|
18
|
+
}
|
|
19
|
+
const graceTurns = budget.graceTurns ?? DEFAULT_TURN_BUDGET_GRACE_TURNS;
|
|
20
|
+
if (typeof graceTurns !== "number" || !Number.isInteger(graceTurns) || graceTurns < 0) {
|
|
21
|
+
return { error: `${label}.graceTurns must be an integer >= 0.` };
|
|
22
|
+
}
|
|
23
|
+
return { turnBudget: { maxTurns: budget.maxTurns, graceTurns } };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function appendTurnBudgetSystemPrompt(systemPrompt: string, budget: { maxTurns: number; graceTurns?: number } | undefined): string {
|
|
27
|
+
if (!budget) return systemPrompt;
|
|
28
|
+
const graceTurns = budget.graceTurns ?? DEFAULT_TURN_BUDGET_GRACE_TURNS;
|
|
29
|
+
const grace = graceTurns === 1 ? "1 additional assistant turn" : `${graceTurns} additional assistant turns`;
|
|
30
|
+
const block = [
|
|
31
|
+
"## Turn budget",
|
|
32
|
+
`This child run has a soft budget of ${budget.maxTurns} assistant turn${budget.maxTurns === 1 ? "" : "s"}.`,
|
|
33
|
+
`After that, ${grace} may be allowed only for a final wrap-up.`,
|
|
34
|
+
"When you approach or reach the soft budget, stop starting new tool work and return the final answer immediately.",
|
|
35
|
+
"This runner uses process-mode execution, so live steering after launch may be unavailable; treat this instruction as the wrap-up request.",
|
|
36
|
+
"If you continue past the soft budget plus grace turns, the supervisor may abort the process and return only partial output.",
|
|
37
|
+
].join("\n");
|
|
38
|
+
return systemPrompt.trim() ? `${systemPrompt.trim()}\n\n${block}` : block;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function turnBudgetSoftNote(budget: ResolvedTurnBudget, turnCount: number): string {
|
|
42
|
+
return `Turn budget wrap-up was requested after ${turnCount} assistant turn${turnCount === 1 ? "" : "s"} (soft limit ${budget.maxTurns}, grace ${budget.graceTurns}). Process-mode live steering is unavailable, so the child was warned at launch to wrap up by this budget. Output may be partial.`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function turnBudgetExceededMessage(budget: ResolvedTurnBudget, turnCount: number): string {
|
|
46
|
+
return `Subagent exceeded turn budget after ${turnCount} assistant turn${turnCount === 1 ? "" : "s"} (soft limit ${budget.maxTurns} + grace ${budget.graceTurns}).`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function turnBudgetDeferredNote(budget: ResolvedTurnBudget, turnCount: number): string {
|
|
50
|
+
return `Turn-budget termination was deferred at ${turnCount} assistant turn${turnCount === 1 ? "" : "s"} (soft limit ${budget.maxTurns} + grace ${budget.graceTurns}) because the assistant started tool work. The run ended before another safe assistant boundary; output may be partial.`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function formatTurnBudgetOutput(message: string, output: string): string {
|
|
54
|
+
return output.trim()
|
|
55
|
+
? `${message}\n\nPartial output before turn-budget abort:\n${output}`
|
|
56
|
+
: message;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function initialTurnBudgetState(budget: { maxTurns: number; graceTurns?: number }): TurnBudgetState {
|
|
60
|
+
return { maxTurns: budget.maxTurns, graceTurns: budget.graceTurns ?? DEFAULT_TURN_BUDGET_GRACE_TURNS, outcome: "within-budget", turnCount: 0 };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function turnBudgetState(budget: ResolvedTurnBudget, turnCount: number, exceeded: boolean): TurnBudgetState {
|
|
64
|
+
return {
|
|
65
|
+
...budget,
|
|
66
|
+
turnCount,
|
|
67
|
+
outcome: exceeded ? "exceeded" : "wrap-up-requested",
|
|
68
|
+
wrapUpRequestedAtTurn: budget.maxTurns,
|
|
69
|
+
...(exceeded ? { exceededAtTurn: turnCount } : {}),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function turnBudgetDeferredState(
|
|
74
|
+
budget: ResolvedTurnBudget,
|
|
75
|
+
turnCount: number,
|
|
76
|
+
terminationDeferredAtTurn = turnCount,
|
|
77
|
+
): TurnBudgetState {
|
|
78
|
+
return {
|
|
79
|
+
...budget,
|
|
80
|
+
turnCount,
|
|
81
|
+
outcome: "termination-deferred",
|
|
82
|
+
wrapUpRequestedAtTurn: budget.maxTurns,
|
|
83
|
+
terminationDeferredAtTurn,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function turnBudgetDecision(
|
|
88
|
+
budget: ResolvedTurnBudget,
|
|
89
|
+
turnCount: number,
|
|
90
|
+
terminalAssistantStop: boolean,
|
|
91
|
+
toolWorkActiveOrStarting: boolean,
|
|
92
|
+
enforceHardLimit = false,
|
|
93
|
+
): "continue" | "defer" | "abort" {
|
|
94
|
+
const hardLimit = budget.maxTurns + budget.graceTurns;
|
|
95
|
+
if (terminalAssistantStop || turnCount < hardLimit) return "continue";
|
|
96
|
+
if (toolWorkActiveOrStarting && !enforceHardLimit) return "defer";
|
|
97
|
+
return "abort";
|
|
98
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { CostSummary, UsageBudgetConfig, UsageBudgetLimitConfig, UsageBudgetState } from "../../shared/types.ts";
|
|
2
|
+
|
|
3
|
+
function validateLimit(value: unknown, label: string): { limit?: UsageBudgetLimitConfig; error?: string } {
|
|
4
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return { error: `${label} must be an object.` };
|
|
5
|
+
const raw = value as Record<string, unknown>;
|
|
6
|
+
const unknown = Object.keys(raw).find((key) => key !== "soft" && key !== "hard");
|
|
7
|
+
if (unknown) return { error: `${label}.${unknown} is not supported.` };
|
|
8
|
+
if (typeof raw.hard !== "number" || !Number.isFinite(raw.hard) || raw.hard <= 0) return { error: `${label}.hard must be a positive number.` };
|
|
9
|
+
if (raw.soft !== undefined && (typeof raw.soft !== "number" || !Number.isFinite(raw.soft) || raw.soft <= 0)) return { error: `${label}.soft must be a positive number.` };
|
|
10
|
+
if (typeof raw.soft === "number" && raw.soft > raw.hard) return { error: `${label}.soft must be less than or equal to ${label}.hard.` };
|
|
11
|
+
return { limit: { ...(typeof raw.soft === "number" ? { soft: raw.soft } : {}), hard: raw.hard } };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function validateUsageBudgetConfig(value: unknown, label = "usageBudget"): { budget?: UsageBudgetConfig; error?: string } {
|
|
15
|
+
if (value === undefined) return {};
|
|
16
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return { error: `${label} must be an object.` };
|
|
17
|
+
const raw = value as Record<string, unknown>;
|
|
18
|
+
const unknown = Object.keys(raw).find((key) => key !== "tokens" && key !== "costUsd");
|
|
19
|
+
if (unknown) return { error: `${label}.${unknown} is not supported.` };
|
|
20
|
+
const budget: UsageBudgetConfig = {};
|
|
21
|
+
if (raw.tokens !== undefined) {
|
|
22
|
+
const tokens = validateLimit(raw.tokens, `${label}.tokens`);
|
|
23
|
+
if (tokens.error) return { error: tokens.error };
|
|
24
|
+
budget.tokens = tokens.limit;
|
|
25
|
+
}
|
|
26
|
+
if (raw.costUsd !== undefined) {
|
|
27
|
+
const costUsd = validateLimit(raw.costUsd, `${label}.costUsd`);
|
|
28
|
+
if (costUsd.error) return { error: costUsd.error };
|
|
29
|
+
budget.costUsd = costUsd.limit;
|
|
30
|
+
}
|
|
31
|
+
if (!budget.tokens && !budget.costUsd) return { error: `${label} must include tokens or costUsd.` };
|
|
32
|
+
return { budget };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function metricState(limit: UsageBudgetLimitConfig | undefined, used: number): UsageBudgetState["tokens"] {
|
|
36
|
+
if (!limit) return undefined;
|
|
37
|
+
return {
|
|
38
|
+
...limit,
|
|
39
|
+
used,
|
|
40
|
+
outcome: used >= limit.hard ? "hard-exceeded" : limit.soft !== undefined && used >= limit.soft ? "soft-exceeded" : "within-budget",
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function usageBudgetState(config: UsageBudgetConfig | undefined, totals: CostSummary | undefined): UsageBudgetState | undefined {
|
|
45
|
+
if (!config) return undefined;
|
|
46
|
+
const inputTokens = totals?.inputTokens ?? 0;
|
|
47
|
+
const outputTokens = totals?.outputTokens ?? 0;
|
|
48
|
+
const tokens = metricState(config.tokens, inputTokens + outputTokens);
|
|
49
|
+
const costUsd = metricState(config.costUsd, totals?.costUsd ?? 0);
|
|
50
|
+
const reason = tokens?.outcome === "hard-exceeded" ? "tokens" : costUsd?.outcome === "hard-exceeded" ? "costUsd" : undefined;
|
|
51
|
+
return {
|
|
52
|
+
version: 1,
|
|
53
|
+
source: "reported",
|
|
54
|
+
...(tokens ? { tokens } : {}),
|
|
55
|
+
...(costUsd ? { costUsd } : {}),
|
|
56
|
+
exhausted: reason !== undefined,
|
|
57
|
+
...(reason ? { reason } : {}),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function usageBudgetExceededMessage(state: UsageBudgetState): string {
|
|
62
|
+
if (state.reason === "tokens" && state.tokens) return `Usage budget exhausted: reported tokens ${state.tokens.used} reached hard limit ${state.tokens.hard}.`;
|
|
63
|
+
if (state.reason === "costUsd" && state.costUsd) return `Usage budget exhausted: reported cost $${state.costUsd.used.toFixed(6)} reached hard limit $${state.costUsd.hard.toFixed(6)}.`;
|
|
64
|
+
return "Usage budget exhausted.";
|
|
65
|
+
}
|