@ponythewhite/base-context 1.0.13 → 1.0.14
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 +9 -0
- package/dist/base-context-runtime/pyproject.toml +1 -1
- package/dist/base-context-runtime/uv.lock +1 -1
- package/dist/build-info.json +1 -1
- package/dist/bundle/amazon-bedrock.js +3 -3
- package/dist/bundle/{anthropic-BJVPUMPB.js → anthropic-AXUXEET7.js} +1 -1
- package/dist/bundle/{azure-openai-responses-ERRMAXK6.js → azure-openai-responses-J3NTJKEO.js} +2 -2
- package/dist/bundle/{bundled-modules-URKVA3UB.js → bundled-modules-UODO7ZR7.js} +5 -5
- package/dist/bundle/{chunk-FOGKLC7V.js → chunk-72LSQYUV.js} +1 -1
- package/dist/bundle/{chunk-MUFZODP5.js → chunk-EGFIZABJ.js} +1 -1
- package/dist/bundle/{chunk-AEMRBMI2.js → chunk-IEM74GZ5.js} +9 -9
- package/dist/bundle/{chunk-25VYRAC6.js → chunk-JKKXN6JE.js} +72 -0
- package/dist/bundle/{chunk-TXVF6Q5H.js → chunk-NLRWERWA.js} +37 -32
- package/dist/bundle/{chunk-TKOBEJ5E.js → chunk-SX7CAXWU.js} +22 -4
- package/dist/bundle/{chunk-Q6UAHLII.js → chunk-V6LOBH6X.js} +2 -2
- package/dist/bundle/{cli-main-ZTJM5EEH.js → cli-main-6GXXIMQQ.js} +4 -4
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/{google-4GA4YMUX.js → google-QLKV2ZLC.js} +2 -2
- package/dist/bundle/{google-vertex-7AMALD7D.js → google-vertex-UGLUZV6B.js} +2 -2
- package/dist/bundle/{main-53I74INO.js → main-HF64B4HM.js} +5 -5
- package/dist/bundle/{mistral-74BXMNRM.js → mistral-2ITSLHYF.js} +1 -1
- package/dist/bundle/{openai-codex-responses-COXNC4IH.js → openai-codex-responses-FRREQXS3.js} +5 -4
- package/dist/bundle/{openai-completions-BCSA5Q6S.js → openai-completions-HF6UPPLW.js} +1 -1
- package/dist/bundle/{openai-responses-ONCIZSJS.js → openai-responses-LRTMBDFW.js} +2 -2
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +6 -1
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/autonomous.d.ts +2 -0
- package/dist/core/autonomous.d.ts.map +1 -1
- package/dist/core/autonomous.js +4 -0
- package/dist/core/autonomous.js.map +1 -1
- package/dist/core/canonical-context.d.ts.map +1 -1
- package/dist/core/canonical-context.js +7 -0
- package/dist/core/canonical-context.js.map +1 -1
- package/dist/core/public-context.d.ts.map +1 -1
- package/dist/core/public-context.js +2 -0
- package/dist/core/public-context.js.map +1 -1
- package/dist/core/view-units.d.ts.map +1 -1
- package/dist/core/view-units.js +3 -0
- package/dist/core/view-units.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +1 -1
- package/dist/main.js.map +1 -1
- package/dist/modes/daemon/daemon-mode.d.ts.map +1 -1
- package/dist/modes/daemon/daemon-mode.js +4 -3
- package/dist/modes/daemon/daemon-mode.js.map +1 -1
- package/dist/modes/daemon/daemon-supervisor.d.ts.map +1 -1
- package/dist/modes/daemon/daemon-supervisor.js +11 -5
- package/dist/modes/daemon/daemon-supervisor.js.map +1 -1
- package/dist/modes/daemon/daemon-worker-protocol.d.ts +3 -0
- package/dist/modes/daemon/daemon-worker-protocol.d.ts.map +1 -1
- package/dist/modes/daemon/daemon-worker-protocol.js +2 -0
- package/dist/modes/daemon/daemon-worker-protocol.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +24 -21
- package/dist/modes/print-mode.js.map +1 -1
- package/docs/json.md +14 -1
- package/docs/long-running-agents.md +23 -2
- package/docs/providers.md +17 -0
- package/package.json +4 -4
|
@@ -75,6 +75,8 @@ export declare function addAutonomousContinuation(state: AutonomousRuntimeState)
|
|
|
75
75
|
export declare function nextAutonomousContinuation(state: AutonomousRuntimeState, message: AssistantMessage, options?: AutonomousOperationOptions, now?: number): Promise<UserMessage | undefined>;
|
|
76
76
|
export declare function shouldAutonomouslyContinue(state: AutonomousRuntimeState, message: AssistantMessage, options?: AutonomousOperationOptions, now?: number): Promise<AutonomousDecision>;
|
|
77
77
|
export declare function autonomousLimitReason(state: AutonomousLimitState, now?: number): AutonomousLimitReason | undefined;
|
|
78
|
+
/** Work limits also apply between native tool turns, not only injected continuations. */
|
|
79
|
+
export declare function autonomousRunLimitReason(state: AutonomousLimitState, now?: number): Exclude<AutonomousLimitReason, "maxContinuations"> | undefined;
|
|
78
80
|
export declare function refreshAutonomousQualityGates(state: AutonomousRuntimeState, options?: AutonomousOperationOptions): Promise<AutonomousGateResult | undefined>;
|
|
79
81
|
export declare function buildAutonomousGateFailureContinuation(failure: AgentAutonomousGateFailure, maxRetries: number, timestamp?: number): string;
|
|
80
82
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"autonomous.d.ts","sourceRoot":"","sources":["../../src/core/autonomous.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAK1F,MAAM,WAAW,qBAAqB;IACrC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,KAAK,CAAC,EAAE,yBAAyB,CAAC;CAClC;AAED,MAAM,WAAW,yBAAyB;IACzC,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,0BAA0B;IAC1C,OAAO,EAAE,MAAM,C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AAyB,CAAC,KAAK,EAAE,sBAAsB,GAAG,IAAI,CAK7E;AAYD,wBAAsB,0BAA0B,CAC/C,KAAK,EAAE,sBAAsB,EAC7B,OAAO,EAAE,gBAAgB,EACzB,OAAO,GAAE,0BAA+B,EACxC,GAAG,SAAa,GACd,OAAO,CAAC,WAAW,GAAG,SAAS,CAAC,CAwBlC;AAED,wBAAsB,0BAA0B,CAC/C,KAAK,EAAE,sBAAsB,EAC7B,OAAO,EAAE,gBAAgB,EACzB,OAAO,GAAE,0BAA+B,EACxC,GAAG,SAAa,GACd,OAAO,CAAC,kBAAkB,CAAC,CAoB7B;AAED,wBAAgB,qBAAqB,CACpC,KAAK,EAAE,oBAAoB,EAC3B,GAAG,SAAa,GACd,qBAAqB,GAAG,SAAS,CAcnC;AAED,wBAAsB,6BAA6B,CAClD,KAAK,EAAE,sBAAsB,EAC7B,OAAO,GAAE,0BAA+B,GACtC,OAAO,CAAC,oBAAoB,GAAG,SAAS,CAAC,CAM3C;AAoED,wBAAgB,sCAAsC,CACrD,OAAO,EAAE,0BAA0B,EACnC,UAAU,EAAE,MAAM,EAClB,SAAS,SAAa,GACpB,MAAM,CAMR","sourcesContent":["import { spawn } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { createReadStream } from \"node:fs\";\nimport { lstat, readlink } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport type { AssistantMessage, Usage, UserMessage } from \"@ponythewhite/base-context-ai\";\nimport { waitForChildProcess } from \"../utils/child-process.js\";\nimport { killProcessTree, trackDetachedChildPid, untrackDetachedChildPid } from \"../utils/shell.js\";\nimport { captureOrphanProcessJournalOwner } from \"./orphan-process-journal.js\";\n\nexport interface AgentAutonomousConfig {\n\tenabled?: boolean;\n\tmaxContinuations?: number;\n\tmaxTurns?: number;\n\tmaxTokens?: number;\n\ttimeoutMs?: number;\n\tcontinuationPrompt?: string;\n\tgates?: AgentAutonomousGateConfig;\n}\n\nexport interface AgentAutonomousGateConfig {\n\tcommands?: string[];\n\tmaxRetries?: number;\n\ttimeoutMs?: number;\n}\n\nexport interface AgentAutonomousGateFailure {\n\tcommand: string;\n\tattempt: number;\n\texitText: string;\n\toutput: string;\n}\n\nexport interface AgentAutonomousStatus {\n\tenabled: boolean;\n\tcontinuationsUsed: number;\n\tturnsUsed: number;\n\ttokensUsed: number;\n\tstartedAt?: number;\n\tlimits: Required<Omit<AgentAutonomousConfig, \"enabled\" | \"continuationPrompt\" | \"gates\">>;\n\tgates: Required<AgentAutonomousGateConfig>;\n\tgateAttempts: Record<string, number>;\n\tlastGateFailure?: AgentAutonomousGateFailure;\n}\n\nexport const DEFAULT_AUTONOMOUS_CONTINUATION_PROMPT =\n\t\"No human input is available in autonomous mode. Continue the requested task within its scope and configured autonomous limits. Use the checks requested by the user or configured gates; do not add proof artifacts, self-certification, or repeated validation loops. If input is missing, make reasonable assumptions only within existing permissions. If blocked, state the concrete blocker briefly and work on independent unblocked tasks. Required approvals remain required. Configured gates and limits control continuation.\";\n\nexport const DEFAULT_AUTONOMOUS_LIMITS: Required<\n\tOmit<AgentAutonomousConfig, \"enabled\" | \"continuationPrompt\" | \"gates\">\n> = {\n\tmaxContinuations: 3,\n\tmaxTurns: 12,\n\tmaxTokens: 80_000,\n\ttimeoutMs: 30 * 60 * 1000,\n};\n\nexport const DEFAULT_AUTONOMOUS_GATES: Required<AgentAutonomousGateConfig> = {\n\tcommands: [],\n\tmaxRetries: 3,\n\ttimeoutMs: 5 * 60 * 1000,\n};\n\nconst MAX_GATE_OUTPUT_CHARS = 6000;\nconst MAX_CHILD_PROCESS_OUTPUT_CHARS = 1024 * 1024;\n\nexport interface AutonomousRuntimeState {\n\tenabled: boolean;\n\tcontinuationsUsed: number;\n\tturnsUsed: number;\n\ttokensUsed: number;\n\tstartedAt?: number;\n\tlimits: Required<Omit<AgentAutonomousConfig, \"enabled\" | \"continuationPrompt\" | \"gates\">>;\n\tcontinuationPrompt: string;\n\tgates: Required<AgentAutonomousGateConfig>;\n\tgateAttempts: Record<string, number>;\n\tlastGateFailure?: GateFailure;\n\tlastGateFailureSnapshot?: GitWorktreeSnapshot;\n}\n\nexport type AutonomousLimitReason = \"maxContinuations\" | \"maxTurns\" | \"maxTokens\" | \"timeoutMs\";\nexport type AutonomousGateResult = \"passed\" | \"failed\" | \"retry_exhausted\";\n\ntype AutonomousLimitState = Pick<\n\tAgentAutonomousStatus,\n\t\"continuationsUsed\" | \"turnsUsed\" | \"tokensUsed\" | \"startedAt\" | \"limits\"\n>;\n\nexport interface AutonomousDecision {\n\tshouldContinue: boolean;\n\treason: \"missing_terminal_evidence\" | \"gate_failed\" | \"not_needed\" | \"limit_reached\";\n}\n\ninterface GitWorktreeSnapshot {\n\tstatus: string;\n\tdiff: string;\n\tuntrackedHash: string;\n}\n\ninterface AutonomousOperationOptions {\n\tcwd?: string;\n\tsignal?: AbortSignal;\n}\n\ntype GateFailure = AgentAutonomousGateFailure;\n\nexport function createAutonomousRuntimeState(\n\tconfig?: AgentAutonomousConfig,\n\t_options: { cwd?: string } = {},\n): AutonomousRuntimeState {\n\tconst enabled = config?.enabled === true;\n\treturn {\n\t\tenabled,\n\t\tcontinuationsUsed: 0,\n\t\tturnsUsed: 0,\n\t\ttokensUsed: 0,\n\t\tstartedAt: enabled ? Date.now() : undefined,\n\t\tlimits: {\n\t\t\tmaxContinuations: normalizeLimit(config?.maxContinuations, DEFAULT_AUTONOMOUS_LIMITS.maxContinuations),\n\t\t\tmaxTurns: normalizeLimit(config?.maxTurns, DEFAULT_AUTONOMOUS_LIMITS.maxTurns),\n\t\t\tmaxTokens: normalizeLimit(config?.maxTokens, DEFAULT_AUTONOMOUS_LIMITS.maxTokens),\n\t\t\ttimeoutMs: normalizeLimit(config?.timeoutMs, DEFAULT_AUTONOMOUS_LIMITS.timeoutMs),\n\t\t},\n\t\tcontinuationPrompt: config?.continuationPrompt?.trim() || DEFAULT_AUTONOMOUS_CONTINUATION_PROMPT,\n\t\tgates: {\n\t\t\tcommands: [...(config?.gates?.commands ?? DEFAULT_AUTONOMOUS_GATES.commands)],\n\t\t\tmaxRetries: normalizeLimit(config?.gates?.maxRetries, DEFAULT_AUTONOMOUS_GATES.maxRetries),\n\t\t\ttimeoutMs: normalizeLimit(config?.gates?.timeoutMs, DEFAULT_AUTONOMOUS_GATES.timeoutMs),\n\t\t},\n\t\tgateAttempts: {},\n\t\tlastGateFailure: undefined,\n\t\tlastGateFailureSnapshot: undefined,\n\t};\n}\n\nexport function setAutonomousEnabled(\n\tstate: AutonomousRuntimeState,\n\tenabled: boolean,\n\t_options: { cwd?: string } = {},\n): void {\n\tstate.enabled = enabled;\n\tif (enabled) {\n\t\tstate.continuationsUsed = 0;\n\t\tstate.turnsUsed = 0;\n\t\tstate.tokensUsed = 0;\n\t\tstate.startedAt = Date.now();\n\t\tstate.gateAttempts = {};\n\t\tstate.lastGateFailure = undefined;\n\t\tstate.lastGateFailureSnapshot = undefined;\n\t} else {\n\t\tstate.startedAt = undefined;\n\t\tstate.gateAttempts = {};\n\t\tstate.lastGateFailure = undefined;\n\t\tstate.lastGateFailureSnapshot = undefined;\n\t}\n}\n\nexport function autonomousStatus(state: AutonomousRuntimeState): AgentAutonomousStatus {\n\treturn {\n\t\tenabled: state.enabled,\n\t\tcontinuationsUsed: state.continuationsUsed,\n\t\tturnsUsed: state.turnsUsed,\n\t\ttokensUsed: state.tokensUsed,\n\t\tstartedAt: state.startedAt,\n\t\tlimits: { ...state.limits },\n\t\tgates: { ...state.gates, commands: [...state.gates.commands] },\n\t\tgateAttempts: { ...state.gateAttempts },\n\t\tlastGateFailure: state.lastGateFailure ? { ...state.lastGateFailure } : undefined,\n\t};\n}\n\nexport function addAutonomousUsage(state: AutonomousRuntimeState, usage: Usage | undefined): void {\n\tif (!state.enabled) {\n\t\treturn;\n\t}\n\tstate.turnsUsed++;\n\tstate.tokensUsed += autonomousTokenDelta(usage);\n}\n\nexport function addAutonomousContinuation(state: AutonomousRuntimeState): void {\n\tif (!state.enabled) {\n\t\treturn;\n\t}\n\tstate.continuationsUsed++;\n}\n\nfunction autonomousTokenDelta(usage: Usage | undefined): number {\n\tif (!usage) {\n\t\treturn 0;\n\t}\n\t// Cache-read tokens are repeated context served from provider cache. Counting them\n\t// cumulatively makes long autonomous verifier loops exhaust their host-side token\n\t// budget far before the non-cached work reaches the configured cap.\n\treturn usage.input + usage.output + usage.cacheWrite;\n}\n\nexport async function nextAutonomousContinuation(\n\tstate: AutonomousRuntimeState,\n\tmessage: AssistantMessage,\n\toptions: AutonomousOperationOptions = {},\n\tnow = Date.now(),\n): Promise<UserMessage | undefined> {\n\toptions.signal?.throwIfAborted();\n\tif (!state.enabled) {\n\t\treturn undefined;\n\t}\n\tconst decision = await shouldAutonomouslyContinue(state, message, options, now);\n\toptions.signal?.throwIfAborted();\n\tif (!decision.shouldContinue) {\n\t\treturn undefined;\n\t}\n\tstate.continuationsUsed++;\n\treturn {\n\t\trole: \"user\",\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext:\n\t\t\t\t\tdecision.reason === \"gate_failed\"\n\t\t\t\t\t\t? (buildGateFailureContinuation(state, now) ?? state.continuationPrompt)\n\t\t\t\t\t\t: state.continuationPrompt,\n\t\t\t},\n\t\t],\n\t\ttimestamp: now,\n\t};\n}\n\nexport async function shouldAutonomouslyContinue(\n\tstate: AutonomousRuntimeState,\n\tmessage: AssistantMessage,\n\toptions: AutonomousOperationOptions = {},\n\tnow = Date.now(),\n): Promise<AutonomousDecision> {\n\toptions.signal?.throwIfAborted();\n\tif (!state.enabled || message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\treturn { shouldContinue: false, reason: \"not_needed\" };\n\t}\n\tconst gateResult = await refreshAutonomousQualityGates(state, options);\n\toptions.signal?.throwIfAborted();\n\tif (gateResult) {\n\t\tif (gateResult === \"passed\") {\n\t\t\treturn { shouldContinue: false, reason: \"not_needed\" };\n\t\t}\n\t\tif (gateResult === \"retry_exhausted\" || autonomousLimitReason(state, now)) {\n\t\t\treturn { shouldContinue: false, reason: \"limit_reached\" };\n\t\t}\n\t\treturn { shouldContinue: true, reason: \"gate_failed\" };\n\t}\n\tif (autonomousLimitReason(state, now)) {\n\t\treturn { shouldContinue: false, reason: \"limit_reached\" };\n\t}\n\treturn { shouldContinue: true, reason: \"missing_terminal_evidence\" };\n}\n\nexport function autonomousLimitReason(\n\tstate: AutonomousLimitState,\n\tnow = Date.now(),\n): AutonomousLimitReason | undefined {\n\tif (state.continuationsUsed >= state.limits.maxContinuations) {\n\t\treturn \"maxContinuations\";\n\t}\n\tif (state.turnsUsed >= state.limits.maxTurns) {\n\t\treturn \"maxTurns\";\n\t}\n\tif (state.tokensUsed >= state.limits.maxTokens) {\n\t\treturn \"maxTokens\";\n\t}\n\tif (state.startedAt !== undefined && now - state.startedAt >= state.limits.timeoutMs) {\n\t\treturn \"timeoutMs\";\n\t}\n\treturn undefined;\n}\n\nexport async function refreshAutonomousQualityGates(\n\tstate: AutonomousRuntimeState,\n\toptions: AutonomousOperationOptions = {},\n): Promise<AutonomousGateResult | undefined> {\n\toptions.signal?.throwIfAborted();\n\tif (!state.enabled || state.gates.commands.length === 0) {\n\t\treturn undefined;\n\t}\n\treturn await runAutonomousQualityGates(state, options.cwd, options.signal);\n}\n\nasync function runAutonomousQualityGates(\n\tstate: AutonomousRuntimeState,\n\tcwd: string | undefined,\n\tsignal: AbortSignal | undefined,\n): Promise<AutonomousGateResult> {\n\tsignal?.throwIfAborted();\n\tif (!cwd) {\n\t\treturn \"failed\";\n\t}\n\tfor (const command of state.gates.commands) {\n\t\tconst currentSnapshot = await captureGitWorktreeSnapshot(cwd, signal);\n\t\tsignal?.throwIfAborted();\n\t\tif (\n\t\t\tstate.lastGateFailure?.command === command &&\n\t\t\tstate.lastGateFailureSnapshot &&\n\t\t\tgitWorktreeSnapshotsEqual(currentSnapshot, state.lastGateFailureSnapshot)\n\t\t) {\n\t\t\tconst attempt = (state.gateAttempts[command] ?? state.lastGateFailure.attempt) + 1;\n\t\t\tstate.gateAttempts[command] = attempt;\n\t\t\tstate.lastGateFailure = {\n\t\t\t\t...state.lastGateFailure,\n\t\t\t\tattempt,\n\t\t\t\texitText: \"not rerun: workspace unchanged since previous failed gate\",\n\t\t\t\toutput:\n\t\t\t\t\t\"The autonomous gate was not rerun because the workspace has not changed since this failure. Edit source files, tests, or a blocker artifact before attempting to finish again.\",\n\t\t\t};\n\t\t\treturn attempt > state.gates.maxRetries ? \"retry_exhausted\" : \"failed\";\n\t\t}\n\t\tconst result = await runChildProcess(command, [], {\n\t\t\tcwd,\n\t\t\tshell: true,\n\t\t\ttimeoutMs: state.gates.timeoutMs,\n\t\t\tmaxOutputChars: MAX_GATE_OUTPUT_CHARS,\n\t\t\tsignal,\n\t\t});\n\t\tsignal?.throwIfAborted();\n\t\tconst postRunSnapshot = await captureGitWorktreeSnapshot(cwd, signal);\n\t\tsignal?.throwIfAborted();\n\t\tif (result.status === 0 && !result.error && !result.timedOut) {\n\t\t\tstate.gateAttempts[command] = 0;\n\t\t\tif (state.lastGateFailure?.command === command) {\n\t\t\t\tstate.lastGateFailure = undefined;\n\t\t\t\tstate.lastGateFailureSnapshot = undefined;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst attempt = (state.gateAttempts[command] ?? 0) + 1;\n\t\tstate.gateAttempts[command] = attempt;\n\t\tconst exitText = formatProcessExit(result);\n\t\tstate.lastGateFailure = {\n\t\t\tcommand,\n\t\t\tattempt,\n\t\t\texitText,\n\t\t\toutput: truncateGateOutput(\n\t\t\t\t[result.stdout, result.stderr].filter(Boolean).join(\"\\n\").trim(),\n\t\t\t\tresult.outputTruncated,\n\t\t\t),\n\t\t};\n\t\tstate.lastGateFailureSnapshot = postRunSnapshot;\n\t\treturn attempt > state.gates.maxRetries ? \"retry_exhausted\" : \"failed\";\n\t}\n\tstate.lastGateFailure = undefined;\n\tstate.lastGateFailureSnapshot = undefined;\n\treturn \"passed\";\n}\n\nexport function buildAutonomousGateFailureContinuation(\n\tfailure: AgentAutonomousGateFailure,\n\tmaxRetries: number,\n\ttimestamp = Date.now(),\n): string {\n\treturn (\n\t\t`Autonomous quality gate failed (attempt ${failure.attempt}/${maxRetries}): \\`${failure.command}\\` ${failure.exitText}.\\n` +\n\t\t(failure.output ? `\\nOutput:\\n${failure.output}\\n` : \"\\n\") +\n\t\t`\\nContinue working. Fix the failure, then produce terminal evidence. Timestamp: ${new Date(timestamp).toISOString()}.`\n\t);\n}\n\nfunction buildGateFailureContinuation(state: AutonomousRuntimeState, timestamp: number): string | undefined {\n\tconst failure = state.lastGateFailure;\n\tif (!failure) {\n\t\treturn undefined;\n\t}\n\treturn buildAutonomousGateFailureContinuation(failure, state.gates.maxRetries, timestamp);\n}\n\nfunction gitWorktreeSnapshotsEqual(a: GitWorktreeSnapshot | undefined, b: GitWorktreeSnapshot | undefined): boolean {\n\treturn !!a && !!b && a.status === b.status && a.diff === b.diff && a.untrackedHash === b.untrackedHash;\n}\n\nasync function captureGitWorktreeSnapshot(\n\tcwd: string | undefined,\n\tsignal?: AbortSignal,\n): Promise<GitWorktreeSnapshot | undefined> {\n\tsignal?.throwIfAborted();\n\tif (!cwd) {\n\t\treturn undefined;\n\t}\n\tconst pathspec = [\n\t\t\"--\",\n\t\t\".\",\n\t\t\":(exclude)verification\",\n\t\t\":(exclude)target\",\n\t\t\":(exclude).vf-prime-agent\",\n\t\t\":(exclude)Cargo.lock\",\n\t\t\":(exclude)submission.tar.gz\",\n\t\t\":(exclude)runner_args.log\",\n\t];\n\tconst status = await runChildProcess(\n\t\t\"git\",\n\t\t[\"--no-optional-locks\", \"status\", \"--porcelain=v1\", \"-z\", \"-uall\", \"--no-renames\", ...pathspec],\n\t\t{\n\t\t\tcwd,\n\t\t\ttimeoutMs: 10_000,\n\t\t\tsignal,\n\t\t},\n\t);\n\tsignal?.throwIfAborted();\n\tif (status.status !== 0 || status.error || status.timedOut || status.outputTruncated) {\n\t\treturn undefined;\n\t}\n\tconst diff = await runChildProcess(\n\t\t\"git\",\n\t\t[\"--no-optional-locks\", \"diff\", \"--no-ext-diff\", \"--binary\", \"HEAD\", ...pathspec],\n\t\t{\n\t\t\tcwd,\n\t\t\ttimeoutMs: 10_000,\n\t\t\tsignal,\n\t\t},\n\t);\n\tsignal?.throwIfAborted();\n\tif (diff.status !== 0 || diff.error || diff.timedOut || diff.outputTruncated) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tstatus: status.stdout,\n\t\tdiff: diff.stdout,\n\t\tuntrackedHash: await hashUntrackedFiles(cwd, status.stdout, signal),\n\t};\n}\n\nfunction untrackedPathsFromStatus(status: string): string[] {\n\treturn status\n\t\t.split(\"\\0\")\n\t\t.filter((entry) => entry.startsWith(\"?? \"))\n\t\t.map((entry) => entry.slice(3))\n\t\t.sort();\n}\n\nasync function hashUntrackedFiles(cwd: string, status: string, signal?: AbortSignal): Promise<string> {\n\tconst aggregate = createHash(\"sha256\");\n\tfor (const path of untrackedPathsFromStatus(status)) {\n\t\tsignal?.throwIfAborted();\n\t\taggregate.update(path);\n\t\taggregate.update(\"\\0\");\n\t\taggregate.update(await hashUntrackedPath(resolve(cwd, path), signal));\n\t\taggregate.update(\"\\0\");\n\t}\n\tsignal?.throwIfAborted();\n\treturn aggregate.digest(\"hex\");\n}\n\nasync function hashUntrackedPath(path: string, signal?: AbortSignal): Promise<string> {\n\ttry {\n\t\tsignal?.throwIfAborted();\n\t\tconst stat = await lstat(path);\n\t\tsignal?.throwIfAborted();\n\t\tif (stat.isSymbolicLink()) {\n\t\t\tconst target = await readlink(path);\n\t\t\tsignal?.throwIfAborted();\n\t\t\treturn `symlink:${target}`;\n\t\t}\n\t\tif (!stat.isFile()) {\n\t\t\treturn `other:${stat.mode}:${stat.size}:${stat.mtimeMs}`;\n\t\t}\n\t\tconst hash = createHash(\"sha256\");\n\t\tfor await (const chunk of createReadStream(path, { signal })) {\n\t\t\thash.update(chunk);\n\t\t}\n\t\tsignal?.throwIfAborted();\n\t\treturn `file:${hash.digest(\"hex\")}`;\n\t} catch (error) {\n\t\tsignal?.throwIfAborted();\n\t\treturn `error:${error instanceof Error ? error.message : String(error)}`;\n\t}\n}\n\ninterface ChildProcessResult {\n\tstatus: number | null;\n\tsignal: NodeJS.Signals | null;\n\tstdout: string;\n\tstderr: string;\n\terror?: Error;\n\ttimedOut?: boolean;\n\toutputTruncated: boolean;\n}\n\nfunction runChildProcess(\n\tcommand: string,\n\targs: string[],\n\toptions: {\n\t\tcwd?: string;\n\t\tshell?: boolean;\n\t\ttimeoutMs?: number;\n\t\tmaxOutputChars?: number;\n\t\tsignal?: AbortSignal;\n\t} = {},\n): Promise<ChildProcessResult> {\n\toptions.signal?.throwIfAborted();\n\tconst orphanOwner = captureOrphanProcessJournalOwner();\n\treturn new Promise((resolve, reject) => {\n\t\tconst child = spawn(command, args, {\n\t\t\tcwd: options.cwd,\n\t\t\tdetached: process.platform !== \"win32\",\n\t\t\tshell: options.shell === true,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t});\n\t\tlet registrationError: Error | undefined;\n\t\tlet error: Error | undefined;\n\t\tlet stdout = \"\";\n\t\tlet stderr = \"\";\n\t\tlet timedOut = false;\n\t\tlet outputTruncated = false;\n\t\tlet settled = false;\n\t\tconst maxOutputChars = options.maxOutputChars ?? MAX_CHILD_PROCESS_OUTPUT_CHARS;\n\t\tconst finish = (result: Pick<ChildProcessResult, \"status\" | \"signal\">) => {\n\t\t\tif (settled) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsettled = true;\n\t\t\tif (timer) {\n\t\t\t\tclearTimeout(timer);\n\t\t\t}\n\t\t\toptions.signal?.removeEventListener(\"abort\", abort);\n\t\t\tconst retirementError = child.pid ? untrackDetachedChildPid(child.pid) : undefined;\n\t\t\tconst completed: ChildProcessResult = { ...result, stdout, stderr, error, timedOut, outputTruncated };\n\t\t\tconst trackingError = registrationError ?? retirementError;\n\t\t\tif (trackingError) {\n\t\t\t\tconst failures = [\n\t\t\t\t\ttrackingError,\n\t\t\t\t\t...(error ? [error] : []),\n\t\t\t\t\t...(registrationError && retirementError ? [retirementError] : []),\n\t\t\t\t];\n\t\t\t\t// Reject only after the owned child settled and controls were cleaned. A gate\n\t\t\t\t// retry or an unavailable Git snapshot must not consume tracking uncertainty.\n\t\t\t\treject(\n\t\t\t\t\tnew AggregateError(\n\t\t\t\t\t\tfailures,\n\t\t\t\t\t\t`Spawned command exited with status ${completed.status} and signal ${completed.signal}; tracking is unknown: ${failures.map((failure) => failure.message).join(\"; \")}`,\n\t\t\t\t\t\t{ cause: completed },\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresolve(completed);\n\t\t};\n\t\tconst timer = options.timeoutMs\n\t\t\t? setTimeout(() => {\n\t\t\t\t\ttimedOut = true;\n\t\t\t\t\tif (child.pid) {\n\t\t\t\t\t\tkillProcessTree(child.pid);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchild.kill(\"SIGKILL\");\n\t\t\t\t\t}\n\t\t\t\t}, options.timeoutMs)\n\t\t\t: undefined;\n\t\tconst abort = () => {\n\t\t\tif (child.pid) {\n\t\t\t\tkillProcessTree(child.pid);\n\t\t\t} else {\n\t\t\t\tchild.kill(\"SIGKILL\");\n\t\t\t}\n\t\t};\n\t\toptions.signal?.addEventListener(\"abort\", abort, { once: true });\n\t\tif (options.signal?.aborted) {\n\t\t\tabort();\n\t\t}\n\t\tchild.stdout?.setEncoding(\"utf8\");\n\t\tchild.stderr?.setEncoding(\"utf8\");\n\t\tchild.stdout?.on(\"data\", (chunk: string) => {\n\t\t\tconst remaining = maxOutputChars - stdout.length;\n\t\t\tif (remaining > 0) {\n\t\t\t\tstdout += chunk.slice(0, remaining);\n\t\t\t}\n\t\t\toutputTruncated ||= chunk.length > remaining;\n\t\t});\n\t\tchild.stderr?.on(\"data\", (chunk: string) => {\n\t\t\tconst remaining = maxOutputChars - stderr.length;\n\t\t\tif (remaining > 0) {\n\t\t\t\tstderr += chunk.slice(0, remaining);\n\t\t\t}\n\t\t\toutputTruncated ||= chunk.length > remaining;\n\t\t});\n\t\tvoid waitForChildProcess(child).then(\n\t\t\t(status) => finish({ status, signal: child.signalCode }),\n\t\t\t(err: Error) => {\n\t\t\t\terror = err;\n\t\t\t\tfinish({ status: child.exitCode, signal: child.signalCode });\n\t\t\t},\n\t\t);\n\t\t// Install all existing controls before the synchronous journal bridge can block.\n\t\tregistrationError = child.pid ? trackDetachedChildPid(child.pid, orphanOwner) : undefined;\n\t});\n}\n\nfunction formatProcessExit(result: ChildProcessResult): string {\n\tif (result.timedOut) {\n\t\treturn \"timed out\";\n\t}\n\tif (result.error) {\n\t\treturn result.error.message;\n\t}\n\treturn result.signal ? `terminated by ${result.signal}` : `exited ${result.status ?? \"unknown\"}`;\n}\n\nfunction truncateGateOutput(output: string, outputAlreadyTruncated = false, maxChars = MAX_GATE_OUTPUT_CHARS): string {\n\tif (output.length <= maxChars && !outputAlreadyTruncated) {\n\t\treturn output;\n\t}\n\treturn `${output.slice(0, maxChars)}\\n... [truncated]`;\n}\n\nfunction normalizeLimit(value: number | undefined, fallback: number): number {\n\tif (!Number.isFinite(value) || value === undefined || value <= 0) {\n\t\treturn fallback;\n\t}\n\treturn Math.trunc(value);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"autonomous.d.ts","sourceRoot":"","sources":["../../src/core/autonomous.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAK1F,MAAM,WAAW,qBAAqB;IACrC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,KAAK,CAAC,EAAE,yBAAyB,CA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AC7B,IAAI,CAgBN;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,sBAAsB,GAAG,qBAAqB,CAYrF;AAED,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,sBAAsB,EAAE,KAAK,EAAE,KAAK,GAAG,SAAS,GAAG,IAAI,CAMhG;AAED,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,sBAAsB,GAAG,IAAI,CAK7E;AAYD,wBAAsB,0BAA0B,CAC/C,KAAK,EAAE,sBAAsB,EAC7B,OAAO,EAAE,gBAAgB,EACzB,OAAO,GAAE,0BAA+B,EACxC,GAAG,SAAa,GACd,OAAO,CAAC,WAAW,GAAG,SAAS,CAAC,CAwBlC;AAED,wBAAsB,0BAA0B,CAC/C,KAAK,EAAE,sBAAsB,EAC7B,OAAO,EAAE,gBAAgB,EACzB,OAAO,GAAE,0BAA+B,EACxC,GAAG,SAAa,GACd,OAAO,CAAC,kBAAkB,CAAC,CAoB7B;AAED,wBAAgB,qBAAqB,CACpC,KAAK,EAAE,oBAAoB,EAC3B,GAAG,SAAa,GACd,qBAAqB,GAAG,SAAS,CAKnC;AAED,yFAAyF;AACzF,wBAAgB,wBAAwB,CACvC,KAAK,EAAE,oBAAoB,EAC3B,GAAG,SAAa,GACd,OAAO,CAAC,qBAAqB,EAAE,kBAAkB,CAAC,GAAG,SAAS,CAWhE;AAED,wBAAsB,6BAA6B,CAClD,KAAK,EAAE,sBAAsB,EAC7B,OAAO,GAAE,0BAA+B,GACtC,OAAO,CAAC,oBAAoB,GAAG,SAAS,CAAC,CAM3C;AAoED,wBAAgB,sCAAsC,CACrD,OAAO,EAAE,0BAA0B,EACnC,UAAU,EAAE,MAAM,EAClB,SAAS,SAAa,GACpB,MAAM,CAMR","sourcesContent":["import { spawn } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { createReadStream } from \"node:fs\";\nimport { lstat, readlink } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport type { AssistantMessage, Usage, UserMessage } from \"@ponythewhite/base-context-ai\";\nimport { waitForChildProcess } from \"../utils/child-process.js\";\nimport { killProcessTree, trackDetachedChildPid, untrackDetachedChildPid } from \"../utils/shell.js\";\nimport { captureOrphanProcessJournalOwner } from \"./orphan-process-journal.js\";\n\nexport interface AgentAutonomousConfig {\n\tenabled?: boolean;\n\tmaxContinuations?: number;\n\tmaxTurns?: number;\n\tmaxTokens?: number;\n\ttimeoutMs?: number;\n\tcontinuationPrompt?: string;\n\tgates?: AgentAutonomousGateConfig;\n}\n\nexport interface AgentAutonomousGateConfig {\n\tcommands?: string[];\n\tmaxRetries?: number;\n\ttimeoutMs?: number;\n}\n\nexport interface AgentAutonomousGateFailure {\n\tcommand: string;\n\tattempt: number;\n\texitText: string;\n\toutput: string;\n}\n\nexport interface AgentAutonomousStatus {\n\tenabled: boolean;\n\tcontinuationsUsed: number;\n\tturnsUsed: number;\n\ttokensUsed: number;\n\tstartedAt?: number;\n\tlimits: Required<Omit<AgentAutonomousConfig, \"enabled\" | \"continuationPrompt\" | \"gates\">>;\n\tgates: Required<AgentAutonomousGateConfig>;\n\tgateAttempts: Record<string, number>;\n\tlastGateFailure?: AgentAutonomousGateFailure;\n}\n\nexport const DEFAULT_AUTONOMOUS_CONTINUATION_PROMPT =\n\t\"No human input is available in autonomous mode. Continue the requested task within its scope and configured autonomous limits. Use the checks requested by the user or configured gates; do not add proof artifacts, self-certification, or repeated validation loops. If input is missing, make reasonable assumptions only within existing permissions. If blocked, state the concrete blocker briefly and work on independent unblocked tasks. Required approvals remain required. Configured gates and limits control continuation.\";\n\nexport const DEFAULT_AUTONOMOUS_LIMITS: Required<\n\tOmit<AgentAutonomousConfig, \"enabled\" | \"continuationPrompt\" | \"gates\">\n> = {\n\tmaxContinuations: 3,\n\tmaxTurns: 12,\n\tmaxTokens: 80_000,\n\ttimeoutMs: 30 * 60 * 1000,\n};\n\nexport const DEFAULT_AUTONOMOUS_GATES: Required<AgentAutonomousGateConfig> = {\n\tcommands: [],\n\tmaxRetries: 3,\n\ttimeoutMs: 5 * 60 * 1000,\n};\n\nconst MAX_GATE_OUTPUT_CHARS = 6000;\nconst MAX_CHILD_PROCESS_OUTPUT_CHARS = 1024 * 1024;\n\nexport interface AutonomousRuntimeState {\n\tenabled: boolean;\n\tcontinuationsUsed: number;\n\tturnsUsed: number;\n\ttokensUsed: number;\n\tstartedAt?: number;\n\tlimits: Required<Omit<AgentAutonomousConfig, \"enabled\" | \"continuationPrompt\" | \"gates\">>;\n\tcontinuationPrompt: string;\n\tgates: Required<AgentAutonomousGateConfig>;\n\tgateAttempts: Record<string, number>;\n\tlastGateFailure?: GateFailure;\n\tlastGateFailureSnapshot?: GitWorktreeSnapshot;\n}\n\nexport type AutonomousLimitReason = \"maxContinuations\" | \"maxTurns\" | \"maxTokens\" | \"timeoutMs\";\nexport type AutonomousGateResult = \"passed\" | \"failed\" | \"retry_exhausted\";\n\ntype AutonomousLimitState = Pick<\n\tAgentAutonomousStatus,\n\t\"continuationsUsed\" | \"turnsUsed\" | \"tokensUsed\" | \"startedAt\" | \"limits\"\n>;\n\nexport interface AutonomousDecision {\n\tshouldContinue: boolean;\n\treason: \"missing_terminal_evidence\" | \"gate_failed\" | \"not_needed\" | \"limit_reached\";\n}\n\ninterface GitWorktreeSnapshot {\n\tstatus: string;\n\tdiff: string;\n\tuntrackedHash: string;\n}\n\ninterface AutonomousOperationOptions {\n\tcwd?: string;\n\tsignal?: AbortSignal;\n}\n\ntype GateFailure = AgentAutonomousGateFailure;\n\nexport function createAutonomousRuntimeState(\n\tconfig?: AgentAutonomousConfig,\n\t_options: { cwd?: string } = {},\n): AutonomousRuntimeState {\n\tconst enabled = config?.enabled === true;\n\treturn {\n\t\tenabled,\n\t\tcontinuationsUsed: 0,\n\t\tturnsUsed: 0,\n\t\ttokensUsed: 0,\n\t\tstartedAt: enabled ? Date.now() : undefined,\n\t\tlimits: {\n\t\t\tmaxContinuations: normalizeLimit(config?.maxContinuations, DEFAULT_AUTONOMOUS_LIMITS.maxContinuations),\n\t\t\tmaxTurns: normalizeLimit(config?.maxTurns, DEFAULT_AUTONOMOUS_LIMITS.maxTurns),\n\t\t\tmaxTokens: normalizeLimit(config?.maxTokens, DEFAULT_AUTONOMOUS_LIMITS.maxTokens),\n\t\t\ttimeoutMs: normalizeLimit(config?.timeoutMs, DEFAULT_AUTONOMOUS_LIMITS.timeoutMs),\n\t\t},\n\t\tcontinuationPrompt: config?.continuationPrompt?.trim() || DEFAULT_AUTONOMOUS_CONTINUATION_PROMPT,\n\t\tgates: {\n\t\t\tcommands: [...(config?.gates?.commands ?? DEFAULT_AUTONOMOUS_GATES.commands)],\n\t\t\tmaxRetries: normalizeLimit(config?.gates?.maxRetries, DEFAULT_AUTONOMOUS_GATES.maxRetries),\n\t\t\ttimeoutMs: normalizeLimit(config?.gates?.timeoutMs, DEFAULT_AUTONOMOUS_GATES.timeoutMs),\n\t\t},\n\t\tgateAttempts: {},\n\t\tlastGateFailure: undefined,\n\t\tlastGateFailureSnapshot: undefined,\n\t};\n}\n\nexport function setAutonomousEnabled(\n\tstate: AutonomousRuntimeState,\n\tenabled: boolean,\n\t_options: { cwd?: string } = {},\n): void {\n\tstate.enabled = enabled;\n\tif (enabled) {\n\t\tstate.continuationsUsed = 0;\n\t\tstate.turnsUsed = 0;\n\t\tstate.tokensUsed = 0;\n\t\tstate.startedAt = Date.now();\n\t\tstate.gateAttempts = {};\n\t\tstate.lastGateFailure = undefined;\n\t\tstate.lastGateFailureSnapshot = undefined;\n\t} else {\n\t\tstate.startedAt = undefined;\n\t\tstate.gateAttempts = {};\n\t\tstate.lastGateFailure = undefined;\n\t\tstate.lastGateFailureSnapshot = undefined;\n\t}\n}\n\nexport function autonomousStatus(state: AutonomousRuntimeState): AgentAutonomousStatus {\n\treturn {\n\t\tenabled: state.enabled,\n\t\tcontinuationsUsed: state.continuationsUsed,\n\t\tturnsUsed: state.turnsUsed,\n\t\ttokensUsed: state.tokensUsed,\n\t\tstartedAt: state.startedAt,\n\t\tlimits: { ...state.limits },\n\t\tgates: { ...state.gates, commands: [...state.gates.commands] },\n\t\tgateAttempts: { ...state.gateAttempts },\n\t\tlastGateFailure: state.lastGateFailure ? { ...state.lastGateFailure } : undefined,\n\t};\n}\n\nexport function addAutonomousUsage(state: AutonomousRuntimeState, usage: Usage | undefined): void {\n\tif (!state.enabled) {\n\t\treturn;\n\t}\n\tstate.turnsUsed++;\n\tstate.tokensUsed += autonomousTokenDelta(usage);\n}\n\nexport function addAutonomousContinuation(state: AutonomousRuntimeState): void {\n\tif (!state.enabled) {\n\t\treturn;\n\t}\n\tstate.continuationsUsed++;\n}\n\nfunction autonomousTokenDelta(usage: Usage | undefined): number {\n\tif (!usage) {\n\t\treturn 0;\n\t}\n\t// Cache-read tokens are repeated context served from provider cache. Counting them\n\t// cumulatively makes long autonomous verifier loops exhaust their host-side token\n\t// budget far before the non-cached work reaches the configured cap.\n\treturn usage.input + usage.output + usage.cacheWrite;\n}\n\nexport async function nextAutonomousContinuation(\n\tstate: AutonomousRuntimeState,\n\tmessage: AssistantMessage,\n\toptions: AutonomousOperationOptions = {},\n\tnow = Date.now(),\n): Promise<UserMessage | undefined> {\n\toptions.signal?.throwIfAborted();\n\tif (!state.enabled) {\n\t\treturn undefined;\n\t}\n\tconst decision = await shouldAutonomouslyContinue(state, message, options, now);\n\toptions.signal?.throwIfAborted();\n\tif (!decision.shouldContinue) {\n\t\treturn undefined;\n\t}\n\tstate.continuationsUsed++;\n\treturn {\n\t\trole: \"user\",\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext:\n\t\t\t\t\tdecision.reason === \"gate_failed\"\n\t\t\t\t\t\t? (buildGateFailureContinuation(state, now) ?? state.continuationPrompt)\n\t\t\t\t\t\t: state.continuationPrompt,\n\t\t\t},\n\t\t],\n\t\ttimestamp: now,\n\t};\n}\n\nexport async function shouldAutonomouslyContinue(\n\tstate: AutonomousRuntimeState,\n\tmessage: AssistantMessage,\n\toptions: AutonomousOperationOptions = {},\n\tnow = Date.now(),\n): Promise<AutonomousDecision> {\n\toptions.signal?.throwIfAborted();\n\tif (!state.enabled || message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\treturn { shouldContinue: false, reason: \"not_needed\" };\n\t}\n\tconst gateResult = await refreshAutonomousQualityGates(state, options);\n\toptions.signal?.throwIfAborted();\n\tif (gateResult) {\n\t\tif (gateResult === \"passed\") {\n\t\t\treturn { shouldContinue: false, reason: \"not_needed\" };\n\t\t}\n\t\tif (gateResult === \"retry_exhausted\" || autonomousLimitReason(state, now)) {\n\t\t\treturn { shouldContinue: false, reason: \"limit_reached\" };\n\t\t}\n\t\treturn { shouldContinue: true, reason: \"gate_failed\" };\n\t}\n\tif (autonomousLimitReason(state, now)) {\n\t\treturn { shouldContinue: false, reason: \"limit_reached\" };\n\t}\n\treturn { shouldContinue: true, reason: \"missing_terminal_evidence\" };\n}\n\nexport function autonomousLimitReason(\n\tstate: AutonomousLimitState,\n\tnow = Date.now(),\n): AutonomousLimitReason | undefined {\n\tif (state.continuationsUsed >= state.limits.maxContinuations) {\n\t\treturn \"maxContinuations\";\n\t}\n\treturn autonomousRunLimitReason(state, now);\n}\n\n/** Work limits also apply between native tool turns, not only injected continuations. */\nexport function autonomousRunLimitReason(\n\tstate: AutonomousLimitState,\n\tnow = Date.now(),\n): Exclude<AutonomousLimitReason, \"maxContinuations\"> | undefined {\n\tif (state.turnsUsed >= state.limits.maxTurns) {\n\t\treturn \"maxTurns\";\n\t}\n\tif (state.tokensUsed >= state.limits.maxTokens) {\n\t\treturn \"maxTokens\";\n\t}\n\tif (state.startedAt !== undefined && now - state.startedAt >= state.limits.timeoutMs) {\n\t\treturn \"timeoutMs\";\n\t}\n\treturn undefined;\n}\n\nexport async function refreshAutonomousQualityGates(\n\tstate: AutonomousRuntimeState,\n\toptions: AutonomousOperationOptions = {},\n): Promise<AutonomousGateResult | undefined> {\n\toptions.signal?.throwIfAborted();\n\tif (!state.enabled || state.gates.commands.length === 0) {\n\t\treturn undefined;\n\t}\n\treturn await runAutonomousQualityGates(state, options.cwd, options.signal);\n}\n\nasync function runAutonomousQualityGates(\n\tstate: AutonomousRuntimeState,\n\tcwd: string | undefined,\n\tsignal: AbortSignal | undefined,\n): Promise<AutonomousGateResult> {\n\tsignal?.throwIfAborted();\n\tif (!cwd) {\n\t\treturn \"failed\";\n\t}\n\tfor (const command of state.gates.commands) {\n\t\tconst currentSnapshot = await captureGitWorktreeSnapshot(cwd, signal);\n\t\tsignal?.throwIfAborted();\n\t\tif (\n\t\t\tstate.lastGateFailure?.command === command &&\n\t\t\tstate.lastGateFailureSnapshot &&\n\t\t\tgitWorktreeSnapshotsEqual(currentSnapshot, state.lastGateFailureSnapshot)\n\t\t) {\n\t\t\tconst attempt = (state.gateAttempts[command] ?? state.lastGateFailure.attempt) + 1;\n\t\t\tstate.gateAttempts[command] = attempt;\n\t\t\tstate.lastGateFailure = {\n\t\t\t\t...state.lastGateFailure,\n\t\t\t\tattempt,\n\t\t\t\texitText: \"not rerun: workspace unchanged since previous failed gate\",\n\t\t\t\toutput:\n\t\t\t\t\t\"The autonomous gate was not rerun because the workspace has not changed since this failure. Edit source files, tests, or a blocker artifact before attempting to finish again.\",\n\t\t\t};\n\t\t\treturn attempt > state.gates.maxRetries ? \"retry_exhausted\" : \"failed\";\n\t\t}\n\t\tconst result = await runChildProcess(command, [], {\n\t\t\tcwd,\n\t\t\tshell: true,\n\t\t\ttimeoutMs: state.gates.timeoutMs,\n\t\t\tmaxOutputChars: MAX_GATE_OUTPUT_CHARS,\n\t\t\tsignal,\n\t\t});\n\t\tsignal?.throwIfAborted();\n\t\tconst postRunSnapshot = await captureGitWorktreeSnapshot(cwd, signal);\n\t\tsignal?.throwIfAborted();\n\t\tif (result.status === 0 && !result.error && !result.timedOut) {\n\t\t\tstate.gateAttempts[command] = 0;\n\t\t\tif (state.lastGateFailure?.command === command) {\n\t\t\t\tstate.lastGateFailure = undefined;\n\t\t\t\tstate.lastGateFailureSnapshot = undefined;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst attempt = (state.gateAttempts[command] ?? 0) + 1;\n\t\tstate.gateAttempts[command] = attempt;\n\t\tconst exitText = formatProcessExit(result);\n\t\tstate.lastGateFailure = {\n\t\t\tcommand,\n\t\t\tattempt,\n\t\t\texitText,\n\t\t\toutput: truncateGateOutput(\n\t\t\t\t[result.stdout, result.stderr].filter(Boolean).join(\"\\n\").trim(),\n\t\t\t\tresult.outputTruncated,\n\t\t\t),\n\t\t};\n\t\tstate.lastGateFailureSnapshot = postRunSnapshot;\n\t\treturn attempt > state.gates.maxRetries ? \"retry_exhausted\" : \"failed\";\n\t}\n\tstate.lastGateFailure = undefined;\n\tstate.lastGateFailureSnapshot = undefined;\n\treturn \"passed\";\n}\n\nexport function buildAutonomousGateFailureContinuation(\n\tfailure: AgentAutonomousGateFailure,\n\tmaxRetries: number,\n\ttimestamp = Date.now(),\n): string {\n\treturn (\n\t\t`Autonomous quality gate failed (attempt ${failure.attempt}/${maxRetries}): \\`${failure.command}\\` ${failure.exitText}.\\n` +\n\t\t(failure.output ? `\\nOutput:\\n${failure.output}\\n` : \"\\n\") +\n\t\t`\\nContinue working. Fix the failure, then produce terminal evidence. Timestamp: ${new Date(timestamp).toISOString()}.`\n\t);\n}\n\nfunction buildGateFailureContinuation(state: AutonomousRuntimeState, timestamp: number): string | undefined {\n\tconst failure = state.lastGateFailure;\n\tif (!failure) {\n\t\treturn undefined;\n\t}\n\treturn buildAutonomousGateFailureContinuation(failure, state.gates.maxRetries, timestamp);\n}\n\nfunction gitWorktreeSnapshotsEqual(a: GitWorktreeSnapshot | undefined, b: GitWorktreeSnapshot | undefined): boolean {\n\treturn !!a && !!b && a.status === b.status && a.diff === b.diff && a.untrackedHash === b.untrackedHash;\n}\n\nasync function captureGitWorktreeSnapshot(\n\tcwd: string | undefined,\n\tsignal?: AbortSignal,\n): Promise<GitWorktreeSnapshot | undefined> {\n\tsignal?.throwIfAborted();\n\tif (!cwd) {\n\t\treturn undefined;\n\t}\n\tconst pathspec = [\n\t\t\"--\",\n\t\t\".\",\n\t\t\":(exclude)verification\",\n\t\t\":(exclude)target\",\n\t\t\":(exclude).vf-prime-agent\",\n\t\t\":(exclude)Cargo.lock\",\n\t\t\":(exclude)submission.tar.gz\",\n\t\t\":(exclude)runner_args.log\",\n\t];\n\tconst status = await runChildProcess(\n\t\t\"git\",\n\t\t[\"--no-optional-locks\", \"status\", \"--porcelain=v1\", \"-z\", \"-uall\", \"--no-renames\", ...pathspec],\n\t\t{\n\t\t\tcwd,\n\t\t\ttimeoutMs: 10_000,\n\t\t\tsignal,\n\t\t},\n\t);\n\tsignal?.throwIfAborted();\n\tif (status.status !== 0 || status.error || status.timedOut || status.outputTruncated) {\n\t\treturn undefined;\n\t}\n\tconst diff = await runChildProcess(\n\t\t\"git\",\n\t\t[\"--no-optional-locks\", \"diff\", \"--no-ext-diff\", \"--binary\", \"HEAD\", ...pathspec],\n\t\t{\n\t\t\tcwd,\n\t\t\ttimeoutMs: 10_000,\n\t\t\tsignal,\n\t\t},\n\t);\n\tsignal?.throwIfAborted();\n\tif (diff.status !== 0 || diff.error || diff.timedOut || diff.outputTruncated) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tstatus: status.stdout,\n\t\tdiff: diff.stdout,\n\t\tuntrackedHash: await hashUntrackedFiles(cwd, status.stdout, signal),\n\t};\n}\n\nfunction untrackedPathsFromStatus(status: string): string[] {\n\treturn status\n\t\t.split(\"\\0\")\n\t\t.filter((entry) => entry.startsWith(\"?? \"))\n\t\t.map((entry) => entry.slice(3))\n\t\t.sort();\n}\n\nasync function hashUntrackedFiles(cwd: string, status: string, signal?: AbortSignal): Promise<string> {\n\tconst aggregate = createHash(\"sha256\");\n\tfor (const path of untrackedPathsFromStatus(status)) {\n\t\tsignal?.throwIfAborted();\n\t\taggregate.update(path);\n\t\taggregate.update(\"\\0\");\n\t\taggregate.update(await hashUntrackedPath(resolve(cwd, path), signal));\n\t\taggregate.update(\"\\0\");\n\t}\n\tsignal?.throwIfAborted();\n\treturn aggregate.digest(\"hex\");\n}\n\nasync function hashUntrackedPath(path: string, signal?: AbortSignal): Promise<string> {\n\ttry {\n\t\tsignal?.throwIfAborted();\n\t\tconst stat = await lstat(path);\n\t\tsignal?.throwIfAborted();\n\t\tif (stat.isSymbolicLink()) {\n\t\t\tconst target = await readlink(path);\n\t\t\tsignal?.throwIfAborted();\n\t\t\treturn `symlink:${target}`;\n\t\t}\n\t\tif (!stat.isFile()) {\n\t\t\treturn `other:${stat.mode}:${stat.size}:${stat.mtimeMs}`;\n\t\t}\n\t\tconst hash = createHash(\"sha256\");\n\t\tfor await (const chunk of createReadStream(path, { signal })) {\n\t\t\thash.update(chunk);\n\t\t}\n\t\tsignal?.throwIfAborted();\n\t\treturn `file:${hash.digest(\"hex\")}`;\n\t} catch (error) {\n\t\tsignal?.throwIfAborted();\n\t\treturn `error:${error instanceof Error ? error.message : String(error)}`;\n\t}\n}\n\ninterface ChildProcessResult {\n\tstatus: number | null;\n\tsignal: NodeJS.Signals | null;\n\tstdout: string;\n\tstderr: string;\n\terror?: Error;\n\ttimedOut?: boolean;\n\toutputTruncated: boolean;\n}\n\nfunction runChildProcess(\n\tcommand: string,\n\targs: string[],\n\toptions: {\n\t\tcwd?: string;\n\t\tshell?: boolean;\n\t\ttimeoutMs?: number;\n\t\tmaxOutputChars?: number;\n\t\tsignal?: AbortSignal;\n\t} = {},\n): Promise<ChildProcessResult> {\n\toptions.signal?.throwIfAborted();\n\tconst orphanOwner = captureOrphanProcessJournalOwner();\n\treturn new Promise((resolve, reject) => {\n\t\tconst child = spawn(command, args, {\n\t\t\tcwd: options.cwd,\n\t\t\tdetached: process.platform !== \"win32\",\n\t\t\tshell: options.shell === true,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t});\n\t\tlet registrationError: Error | undefined;\n\t\tlet error: Error | undefined;\n\t\tlet stdout = \"\";\n\t\tlet stderr = \"\";\n\t\tlet timedOut = false;\n\t\tlet outputTruncated = false;\n\t\tlet settled = false;\n\t\tconst maxOutputChars = options.maxOutputChars ?? MAX_CHILD_PROCESS_OUTPUT_CHARS;\n\t\tconst finish = (result: Pick<ChildProcessResult, \"status\" | \"signal\">) => {\n\t\t\tif (settled) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsettled = true;\n\t\t\tif (timer) {\n\t\t\t\tclearTimeout(timer);\n\t\t\t}\n\t\t\toptions.signal?.removeEventListener(\"abort\", abort);\n\t\t\tconst retirementError = child.pid ? untrackDetachedChildPid(child.pid) : undefined;\n\t\t\tconst completed: ChildProcessResult = { ...result, stdout, stderr, error, timedOut, outputTruncated };\n\t\t\tconst trackingError = registrationError ?? retirementError;\n\t\t\tif (trackingError) {\n\t\t\t\tconst failures = [\n\t\t\t\t\ttrackingError,\n\t\t\t\t\t...(error ? [error] : []),\n\t\t\t\t\t...(registrationError && retirementError ? [retirementError] : []),\n\t\t\t\t];\n\t\t\t\t// Reject only after the owned child settled and controls were cleaned. A gate\n\t\t\t\t// retry or an unavailable Git snapshot must not consume tracking uncertainty.\n\t\t\t\treject(\n\t\t\t\t\tnew AggregateError(\n\t\t\t\t\t\tfailures,\n\t\t\t\t\t\t`Spawned command exited with status ${completed.status} and signal ${completed.signal}; tracking is unknown: ${failures.map((failure) => failure.message).join(\"; \")}`,\n\t\t\t\t\t\t{ cause: completed },\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresolve(completed);\n\t\t};\n\t\tconst timer = options.timeoutMs\n\t\t\t? setTimeout(() => {\n\t\t\t\t\ttimedOut = true;\n\t\t\t\t\tif (child.pid) {\n\t\t\t\t\t\tkillProcessTree(child.pid);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchild.kill(\"SIGKILL\");\n\t\t\t\t\t}\n\t\t\t\t}, options.timeoutMs)\n\t\t\t: undefined;\n\t\tconst abort = () => {\n\t\t\tif (child.pid) {\n\t\t\t\tkillProcessTree(child.pid);\n\t\t\t} else {\n\t\t\t\tchild.kill(\"SIGKILL\");\n\t\t\t}\n\t\t};\n\t\toptions.signal?.addEventListener(\"abort\", abort, { once: true });\n\t\tif (options.signal?.aborted) {\n\t\t\tabort();\n\t\t}\n\t\tchild.stdout?.setEncoding(\"utf8\");\n\t\tchild.stderr?.setEncoding(\"utf8\");\n\t\tchild.stdout?.on(\"data\", (chunk: string) => {\n\t\t\tconst remaining = maxOutputChars - stdout.length;\n\t\t\tif (remaining > 0) {\n\t\t\t\tstdout += chunk.slice(0, remaining);\n\t\t\t}\n\t\t\toutputTruncated ||= chunk.length > remaining;\n\t\t});\n\t\tchild.stderr?.on(\"data\", (chunk: string) => {\n\t\t\tconst remaining = maxOutputChars - stderr.length;\n\t\t\tif (remaining > 0) {\n\t\t\t\tstderr += chunk.slice(0, remaining);\n\t\t\t}\n\t\t\toutputTruncated ||= chunk.length > remaining;\n\t\t});\n\t\tvoid waitForChildProcess(child).then(\n\t\t\t(status) => finish({ status, signal: child.signalCode }),\n\t\t\t(err: Error) => {\n\t\t\t\terror = err;\n\t\t\t\tfinish({ status: child.exitCode, signal: child.signalCode });\n\t\t\t},\n\t\t);\n\t\t// Install all existing controls before the synchronous journal bridge can block.\n\t\tregistrationError = child.pid ? trackDetachedChildPid(child.pid, orphanOwner) : undefined;\n\t});\n}\n\nfunction formatProcessExit(result: ChildProcessResult): string {\n\tif (result.timedOut) {\n\t\treturn \"timed out\";\n\t}\n\tif (result.error) {\n\t\treturn result.error.message;\n\t}\n\treturn result.signal ? `terminated by ${result.signal}` : `exited ${result.status ?? \"unknown\"}`;\n}\n\nfunction truncateGateOutput(output: string, outputAlreadyTruncated = false, maxChars = MAX_GATE_OUTPUT_CHARS): string {\n\tif (output.length <= maxChars && !outputAlreadyTruncated) {\n\t\treturn output;\n\t}\n\treturn `${output.slice(0, maxChars)}\\n... [truncated]`;\n}\n\nfunction normalizeLimit(value: number | undefined, fallback: number): number {\n\tif (!Number.isFinite(value) || value === undefined || value <= 0) {\n\t\treturn fallback;\n\t}\n\treturn Math.trunc(value);\n}\n"]}
|
package/dist/core/autonomous.js
CHANGED
|
@@ -147,6 +147,10 @@ export function autonomousLimitReason(state, now = Date.now()) {
|
|
|
147
147
|
if (state.continuationsUsed >= state.limits.maxContinuations) {
|
|
148
148
|
return "maxContinuations";
|
|
149
149
|
}
|
|
150
|
+
return autonomousRunLimitReason(state, now);
|
|
151
|
+
}
|
|
152
|
+
/** Work limits also apply between native tool turns, not only injected continuations. */
|
|
153
|
+
export function autonomousRunLimitReason(state, now = Date.now()) {
|
|
150
154
|
if (state.turnsUsed >= state.limits.maxTurns) {
|
|
151
155
|
return "maxTurns";
|
|
152
156
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"autonomous.js","sourceRoot":"","sources":["../../src/core/autonomous.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAC3C,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AACpG,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAqC/E,MAAM,CAAC,MAAM,sCAAsC,GAClD,ygBAAygB,CAAC;AAE3gB,MAAM,CAAC,MAAM,yBAAyB,GAElC;IACH,gBAAgB,EAAE,CAAC;IACnB,QAAQ,EAAE,EAAE;IACZ,SAAS,EAAE,MAAM;IACjB,SAAS,EAAE,EAAE,GAAG,EAAE,GAAG,IAAI;CACzB,CAAC;AAEF,M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,iFAAiF;QACjF,iBAAiB,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,qBAAqB,CAAC,KAAK,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAAA,CAC1F,CAAC,CAAC;AAAA,CACH;AAED,SAAS,iBAAiB,CAAC,MAA0B,EAAU;IAC9D,IAAI,MAAM,CAAC,QAAQ,EAAE,CAAC;QACrB,OAAO,WAAW,CAAC;IACpB,CAAC;IACD,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;QAClB,OAAO,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC;IAC7B,CAAC;IACD,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,iBAAiB,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,UAAU,MAAM,CAAC,MAAM,IAAI,SAAS,EAAE,CAAC;AAAA,CACjG;AAED,SAAS,kBAAkB,CAAC,MAAc,EAAE,sBAAsB,GAAG,KAAK,EAAE,QAAQ,GAAG,qBAAqB,EAAU;IACrH,IAAI,MAAM,CAAC,MAAM,IAAI,QAAQ,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAC1D,OAAO,MAAM,CAAC;IACf,CAAC;IACD,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,mBAAmB,CAAC;AAAA,CACvD;AAED,SAAS,cAAc,CAAC,KAAyB,EAAE,QAAgB,EAAU;IAC5E,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,IAAI,CAAC,EAAE,CAAC;QAClE,OAAO,QAAQ,CAAC;IACjB,CAAC;IACD,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAAA,CACzB","sourcesContent":["import { spawn } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { createReadStream } from \"node:fs\";\nimport { lstat, readlink } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport type { AssistantMessage, Usage, UserMessage } from \"@ponythewhite/base-context-ai\";\nimport { waitForChildProcess } from \"../utils/child-process.js\";\nimport { killProcessTree, trackDetachedChildPid, untrackDetachedChildPid } from \"../utils/shell.js\";\nimport { captureOrphanProcessJournalOwner } from \"./orphan-process-journal.js\";\n\nexport interface AgentAutonomousConfig {\n\tenabled?: boolean;\n\tmaxContinuations?: number;\n\tmaxTurns?: number;\n\tmaxTokens?: number;\n\ttimeoutMs?: number;\n\tcontinuationPrompt?: string;\n\tgates?: AgentAutonomousGateConfig;\n}\n\nexport interface AgentAutonomousGateConfig {\n\tcommands?: string[];\n\tmaxRetries?: number;\n\ttimeoutMs?: number;\n}\n\nexport interface AgentAutonomousGateFailure {\n\tcommand: string;\n\tattempt: number;\n\texitText: string;\n\toutput: string;\n}\n\nexport interface AgentAutonomousStatus {\n\tenabled: boolean;\n\tcontinuationsUsed: number;\n\tturnsUsed: number;\n\ttokensUsed: number;\n\tstartedAt?: number;\n\tlimits: Required<Omit<AgentAutonomousConfig, \"enabled\" | \"continuationPrompt\" | \"gates\">>;\n\tgates: Required<AgentAutonomousGateConfig>;\n\tgateAttempts: Record<string, number>;\n\tlastGateFailure?: AgentAutonomousGateFailure;\n}\n\nexport const DEFAULT_AUTONOMOUS_CONTINUATION_PROMPT =\n\t\"No human input is available in autonomous mode. Continue the requested task within its scope and configured autonomous limits. Use the checks requested by the user or configured gates; do not add proof artifacts, self-certification, or repeated validation loops. If input is missing, make reasonable assumptions only within existing permissions. If blocked, state the concrete blocker briefly and work on independent unblocked tasks. Required approvals remain required. Configured gates and limits control continuation.\";\n\nexport const DEFAULT_AUTONOMOUS_LIMITS: Required<\n\tOmit<AgentAutonomousConfig, \"enabled\" | \"continuationPrompt\" | \"gates\">\n> = {\n\tmaxContinuations: 3,\n\tmaxTurns: 12,\n\tmaxTokens: 80_000,\n\ttimeoutMs: 30 * 60 * 1000,\n};\n\nexport const DEFAULT_AUTONOMOUS_GATES: Required<AgentAutonomousGateConfig> = {\n\tcommands: [],\n\tmaxRetries: 3,\n\ttimeoutMs: 5 * 60 * 1000,\n};\n\nconst MAX_GATE_OUTPUT_CHARS = 6000;\nconst MAX_CHILD_PROCESS_OUTPUT_CHARS = 1024 * 1024;\n\nexport interface AutonomousRuntimeState {\n\tenabled: boolean;\n\tcontinuationsUsed: number;\n\tturnsUsed: number;\n\ttokensUsed: number;\n\tstartedAt?: number;\n\tlimits: Required<Omit<AgentAutonomousConfig, \"enabled\" | \"continuationPrompt\" | \"gates\">>;\n\tcontinuationPrompt: string;\n\tgates: Required<AgentAutonomousGateConfig>;\n\tgateAttempts: Record<string, number>;\n\tlastGateFailure?: GateFailure;\n\tlastGateFailureSnapshot?: GitWorktreeSnapshot;\n}\n\nexport type AutonomousLimitReason = \"maxContinuations\" | \"maxTurns\" | \"maxTokens\" | \"timeoutMs\";\nexport type AutonomousGateResult = \"passed\" | \"failed\" | \"retry_exhausted\";\n\ntype AutonomousLimitState = Pick<\n\tAgentAutonomousStatus,\n\t\"continuationsUsed\" | \"turnsUsed\" | \"tokensUsed\" | \"startedAt\" | \"limits\"\n>;\n\nexport interface AutonomousDecision {\n\tshouldContinue: boolean;\n\treason: \"missing_terminal_evidence\" | \"gate_failed\" | \"not_needed\" | \"limit_reached\";\n}\n\ninterface GitWorktreeSnapshot {\n\tstatus: string;\n\tdiff: string;\n\tuntrackedHash: string;\n}\n\ninterface AutonomousOperationOptions {\n\tcwd?: string;\n\tsignal?: AbortSignal;\n}\n\ntype GateFailure = AgentAutonomousGateFailure;\n\nexport function createAutonomousRuntimeState(\n\tconfig?: AgentAutonomousConfig,\n\t_options: { cwd?: string } = {},\n): AutonomousRuntimeState {\n\tconst enabled = config?.enabled === true;\n\treturn {\n\t\tenabled,\n\t\tcontinuationsUsed: 0,\n\t\tturnsUsed: 0,\n\t\ttokensUsed: 0,\n\t\tstartedAt: enabled ? Date.now() : undefined,\n\t\tlimits: {\n\t\t\tmaxContinuations: normalizeLimit(config?.maxContinuations, DEFAULT_AUTONOMOUS_LIMITS.maxContinuations),\n\t\t\tmaxTurns: normalizeLimit(config?.maxTurns, DEFAULT_AUTONOMOUS_LIMITS.maxTurns),\n\t\t\tmaxTokens: normalizeLimit(config?.maxTokens, DEFAULT_AUTONOMOUS_LIMITS.maxTokens),\n\t\t\ttimeoutMs: normalizeLimit(config?.timeoutMs, DEFAULT_AUTONOMOUS_LIMITS.timeoutMs),\n\t\t},\n\t\tcontinuationPrompt: config?.continuationPrompt?.trim() || DEFAULT_AUTONOMOUS_CONTINUATION_PROMPT,\n\t\tgates: {\n\t\t\tcommands: [...(config?.gates?.commands ?? DEFAULT_AUTONOMOUS_GATES.commands)],\n\t\t\tmaxRetries: normalizeLimit(config?.gates?.maxRetries, DEFAULT_AUTONOMOUS_GATES.maxRetries),\n\t\t\ttimeoutMs: normalizeLimit(config?.gates?.timeoutMs, DEFAULT_AUTONOMOUS_GATES.timeoutMs),\n\t\t},\n\t\tgateAttempts: {},\n\t\tlastGateFailure: undefined,\n\t\tlastGateFailureSnapshot: undefined,\n\t};\n}\n\nexport function setAutonomousEnabled(\n\tstate: AutonomousRuntimeState,\n\tenabled: boolean,\n\t_options: { cwd?: string } = {},\n): void {\n\tstate.enabled = enabled;\n\tif (enabled) {\n\t\tstate.continuationsUsed = 0;\n\t\tstate.turnsUsed = 0;\n\t\tstate.tokensUsed = 0;\n\t\tstate.startedAt = Date.now();\n\t\tstate.gateAttempts = {};\n\t\tstate.lastGateFailure = undefined;\n\t\tstate.lastGateFailureSnapshot = undefined;\n\t} else {\n\t\tstate.startedAt = undefined;\n\t\tstate.gateAttempts = {};\n\t\tstate.lastGateFailure = undefined;\n\t\tstate.lastGateFailureSnapshot = undefined;\n\t}\n}\n\nexport function autonomousStatus(state: AutonomousRuntimeState): AgentAutonomousStatus {\n\treturn {\n\t\tenabled: state.enabled,\n\t\tcontinuationsUsed: state.continuationsUsed,\n\t\tturnsUsed: state.turnsUsed,\n\t\ttokensUsed: state.tokensUsed,\n\t\tstartedAt: state.startedAt,\n\t\tlimits: { ...state.limits },\n\t\tgates: { ...state.gates, commands: [...state.gates.commands] },\n\t\tgateAttempts: { ...state.gateAttempts },\n\t\tlastGateFailure: state.lastGateFailure ? { ...state.lastGateFailure } : undefined,\n\t};\n}\n\nexport function addAutonomousUsage(state: AutonomousRuntimeState, usage: Usage | undefined): void {\n\tif (!state.enabled) {\n\t\treturn;\n\t}\n\tstate.turnsUsed++;\n\tstate.tokensUsed += autonomousTokenDelta(usage);\n}\n\nexport function addAutonomousContinuation(state: AutonomousRuntimeState): void {\n\tif (!state.enabled) {\n\t\treturn;\n\t}\n\tstate.continuationsUsed++;\n}\n\nfunction autonomousTokenDelta(usage: Usage | undefined): number {\n\tif (!usage) {\n\t\treturn 0;\n\t}\n\t// Cache-read tokens are repeated context served from provider cache. Counting them\n\t// cumulatively makes long autonomous verifier loops exhaust their host-side token\n\t// budget far before the non-cached work reaches the configured cap.\n\treturn usage.input + usage.output + usage.cacheWrite;\n}\n\nexport async function nextAutonomousContinuation(\n\tstate: AutonomousRuntimeState,\n\tmessage: AssistantMessage,\n\toptions: AutonomousOperationOptions = {},\n\tnow = Date.now(),\n): Promise<UserMessage | undefined> {\n\toptions.signal?.throwIfAborted();\n\tif (!state.enabled) {\n\t\treturn undefined;\n\t}\n\tconst decision = await shouldAutonomouslyContinue(state, message, options, now);\n\toptions.signal?.throwIfAborted();\n\tif (!decision.shouldContinue) {\n\t\treturn undefined;\n\t}\n\tstate.continuationsUsed++;\n\treturn {\n\t\trole: \"user\",\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext:\n\t\t\t\t\tdecision.reason === \"gate_failed\"\n\t\t\t\t\t\t? (buildGateFailureContinuation(state, now) ?? state.continuationPrompt)\n\t\t\t\t\t\t: state.continuationPrompt,\n\t\t\t},\n\t\t],\n\t\ttimestamp: now,\n\t};\n}\n\nexport async function shouldAutonomouslyContinue(\n\tstate: AutonomousRuntimeState,\n\tmessage: AssistantMessage,\n\toptions: AutonomousOperationOptions = {},\n\tnow = Date.now(),\n): Promise<AutonomousDecision> {\n\toptions.signal?.throwIfAborted();\n\tif (!state.enabled || message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\treturn { shouldContinue: false, reason: \"not_needed\" };\n\t}\n\tconst gateResult = await refreshAutonomousQualityGates(state, options);\n\toptions.signal?.throwIfAborted();\n\tif (gateResult) {\n\t\tif (gateResult === \"passed\") {\n\t\t\treturn { shouldContinue: false, reason: \"not_needed\" };\n\t\t}\n\t\tif (gateResult === \"retry_exhausted\" || autonomousLimitReason(state, now)) {\n\t\t\treturn { shouldContinue: false, reason: \"limit_reached\" };\n\t\t}\n\t\treturn { shouldContinue: true, reason: \"gate_failed\" };\n\t}\n\tif (autonomousLimitReason(state, now)) {\n\t\treturn { shouldContinue: false, reason: \"limit_reached\" };\n\t}\n\treturn { shouldContinue: true, reason: \"missing_terminal_evidence\" };\n}\n\nexport function autonomousLimitReason(\n\tstate: AutonomousLimitState,\n\tnow = Date.now(),\n): AutonomousLimitReason | undefined {\n\tif (state.continuationsUsed >= state.limits.maxContinuations) {\n\t\treturn \"maxContinuations\";\n\t}\n\tif (state.turnsUsed >= state.limits.maxTurns) {\n\t\treturn \"maxTurns\";\n\t}\n\tif (state.tokensUsed >= state.limits.maxTokens) {\n\t\treturn \"maxTokens\";\n\t}\n\tif (state.startedAt !== undefined && now - state.startedAt >= state.limits.timeoutMs) {\n\t\treturn \"timeoutMs\";\n\t}\n\treturn undefined;\n}\n\nexport async function refreshAutonomousQualityGates(\n\tstate: AutonomousRuntimeState,\n\toptions: AutonomousOperationOptions = {},\n): Promise<AutonomousGateResult | undefined> {\n\toptions.signal?.throwIfAborted();\n\tif (!state.enabled || state.gates.commands.length === 0) {\n\t\treturn undefined;\n\t}\n\treturn await runAutonomousQualityGates(state, options.cwd, options.signal);\n}\n\nasync function runAutonomousQualityGates(\n\tstate: AutonomousRuntimeState,\n\tcwd: string | undefined,\n\tsignal: AbortSignal | undefined,\n): Promise<AutonomousGateResult> {\n\tsignal?.throwIfAborted();\n\tif (!cwd) {\n\t\treturn \"failed\";\n\t}\n\tfor (const command of state.gates.commands) {\n\t\tconst currentSnapshot = await captureGitWorktreeSnapshot(cwd, signal);\n\t\tsignal?.throwIfAborted();\n\t\tif (\n\t\t\tstate.lastGateFailure?.command === command &&\n\t\t\tstate.lastGateFailureSnapshot &&\n\t\t\tgitWorktreeSnapshotsEqual(currentSnapshot, state.lastGateFailureSnapshot)\n\t\t) {\n\t\t\tconst attempt = (state.gateAttempts[command] ?? state.lastGateFailure.attempt) + 1;\n\t\t\tstate.gateAttempts[command] = attempt;\n\t\t\tstate.lastGateFailure = {\n\t\t\t\t...state.lastGateFailure,\n\t\t\t\tattempt,\n\t\t\t\texitText: \"not rerun: workspace unchanged since previous failed gate\",\n\t\t\t\toutput:\n\t\t\t\t\t\"The autonomous gate was not rerun because the workspace has not changed since this failure. Edit source files, tests, or a blocker artifact before attempting to finish again.\",\n\t\t\t};\n\t\t\treturn attempt > state.gates.maxRetries ? \"retry_exhausted\" : \"failed\";\n\t\t}\n\t\tconst result = await runChildProcess(command, [], {\n\t\t\tcwd,\n\t\t\tshell: true,\n\t\t\ttimeoutMs: state.gates.timeoutMs,\n\t\t\tmaxOutputChars: MAX_GATE_OUTPUT_CHARS,\n\t\t\tsignal,\n\t\t});\n\t\tsignal?.throwIfAborted();\n\t\tconst postRunSnapshot = await captureGitWorktreeSnapshot(cwd, signal);\n\t\tsignal?.throwIfAborted();\n\t\tif (result.status === 0 && !result.error && !result.timedOut) {\n\t\t\tstate.gateAttempts[command] = 0;\n\t\t\tif (state.lastGateFailure?.command === command) {\n\t\t\t\tstate.lastGateFailure = undefined;\n\t\t\t\tstate.lastGateFailureSnapshot = undefined;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst attempt = (state.gateAttempts[command] ?? 0) + 1;\n\t\tstate.gateAttempts[command] = attempt;\n\t\tconst exitText = formatProcessExit(result);\n\t\tstate.lastGateFailure = {\n\t\t\tcommand,\n\t\t\tattempt,\n\t\t\texitText,\n\t\t\toutput: truncateGateOutput(\n\t\t\t\t[result.stdout, result.stderr].filter(Boolean).join(\"\\n\").trim(),\n\t\t\t\tresult.outputTruncated,\n\t\t\t),\n\t\t};\n\t\tstate.lastGateFailureSnapshot = postRunSnapshot;\n\t\treturn attempt > state.gates.maxRetries ? \"retry_exhausted\" : \"failed\";\n\t}\n\tstate.lastGateFailure = undefined;\n\tstate.lastGateFailureSnapshot = undefined;\n\treturn \"passed\";\n}\n\nexport function buildAutonomousGateFailureContinuation(\n\tfailure: AgentAutonomousGateFailure,\n\tmaxRetries: number,\n\ttimestamp = Date.now(),\n): string {\n\treturn (\n\t\t`Autonomous quality gate failed (attempt ${failure.attempt}/${maxRetries}): \\`${failure.command}\\` ${failure.exitText}.\\n` +\n\t\t(failure.output ? `\\nOutput:\\n${failure.output}\\n` : \"\\n\") +\n\t\t`\\nContinue working. Fix the failure, then produce terminal evidence. Timestamp: ${new Date(timestamp).toISOString()}.`\n\t);\n}\n\nfunction buildGateFailureContinuation(state: AutonomousRuntimeState, timestamp: number): string | undefined {\n\tconst failure = state.lastGateFailure;\n\tif (!failure) {\n\t\treturn undefined;\n\t}\n\treturn buildAutonomousGateFailureContinuation(failure, state.gates.maxRetries, timestamp);\n}\n\nfunction gitWorktreeSnapshotsEqual(a: GitWorktreeSnapshot | undefined, b: GitWorktreeSnapshot | undefined): boolean {\n\treturn !!a && !!b && a.status === b.status && a.diff === b.diff && a.untrackedHash === b.untrackedHash;\n}\n\nasync function captureGitWorktreeSnapshot(\n\tcwd: string | undefined,\n\tsignal?: AbortSignal,\n): Promise<GitWorktreeSnapshot | undefined> {\n\tsignal?.throwIfAborted();\n\tif (!cwd) {\n\t\treturn undefined;\n\t}\n\tconst pathspec = [\n\t\t\"--\",\n\t\t\".\",\n\t\t\":(exclude)verification\",\n\t\t\":(exclude)target\",\n\t\t\":(exclude).vf-prime-agent\",\n\t\t\":(exclude)Cargo.lock\",\n\t\t\":(exclude)submission.tar.gz\",\n\t\t\":(exclude)runner_args.log\",\n\t];\n\tconst status = await runChildProcess(\n\t\t\"git\",\n\t\t[\"--no-optional-locks\", \"status\", \"--porcelain=v1\", \"-z\", \"-uall\", \"--no-renames\", ...pathspec],\n\t\t{\n\t\t\tcwd,\n\t\t\ttimeoutMs: 10_000,\n\t\t\tsignal,\n\t\t},\n\t);\n\tsignal?.throwIfAborted();\n\tif (status.status !== 0 || status.error || status.timedOut || status.outputTruncated) {\n\t\treturn undefined;\n\t}\n\tconst diff = await runChildProcess(\n\t\t\"git\",\n\t\t[\"--no-optional-locks\", \"diff\", \"--no-ext-diff\", \"--binary\", \"HEAD\", ...pathspec],\n\t\t{\n\t\t\tcwd,\n\t\t\ttimeoutMs: 10_000,\n\t\t\tsignal,\n\t\t},\n\t);\n\tsignal?.throwIfAborted();\n\tif (diff.status !== 0 || diff.error || diff.timedOut || diff.outputTruncated) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tstatus: status.stdout,\n\t\tdiff: diff.stdout,\n\t\tuntrackedHash: await hashUntrackedFiles(cwd, status.stdout, signal),\n\t};\n}\n\nfunction untrackedPathsFromStatus(status: string): string[] {\n\treturn status\n\t\t.split(\"\\0\")\n\t\t.filter((entry) => entry.startsWith(\"?? \"))\n\t\t.map((entry) => entry.slice(3))\n\t\t.sort();\n}\n\nasync function hashUntrackedFiles(cwd: string, status: string, signal?: AbortSignal): Promise<string> {\n\tconst aggregate = createHash(\"sha256\");\n\tfor (const path of untrackedPathsFromStatus(status)) {\n\t\tsignal?.throwIfAborted();\n\t\taggregate.update(path);\n\t\taggregate.update(\"\\0\");\n\t\taggregate.update(await hashUntrackedPath(resolve(cwd, path), signal));\n\t\taggregate.update(\"\\0\");\n\t}\n\tsignal?.throwIfAborted();\n\treturn aggregate.digest(\"hex\");\n}\n\nasync function hashUntrackedPath(path: string, signal?: AbortSignal): Promise<string> {\n\ttry {\n\t\tsignal?.throwIfAborted();\n\t\tconst stat = await lstat(path);\n\t\tsignal?.throwIfAborted();\n\t\tif (stat.isSymbolicLink()) {\n\t\t\tconst target = await readlink(path);\n\t\t\tsignal?.throwIfAborted();\n\t\t\treturn `symlink:${target}`;\n\t\t}\n\t\tif (!stat.isFile()) {\n\t\t\treturn `other:${stat.mode}:${stat.size}:${stat.mtimeMs}`;\n\t\t}\n\t\tconst hash = createHash(\"sha256\");\n\t\tfor await (const chunk of createReadStream(path, { signal })) {\n\t\t\thash.update(chunk);\n\t\t}\n\t\tsignal?.throwIfAborted();\n\t\treturn `file:${hash.digest(\"hex\")}`;\n\t} catch (error) {\n\t\tsignal?.throwIfAborted();\n\t\treturn `error:${error instanceof Error ? error.message : String(error)}`;\n\t}\n}\n\ninterface ChildProcessResult {\n\tstatus: number | null;\n\tsignal: NodeJS.Signals | null;\n\tstdout: string;\n\tstderr: string;\n\terror?: Error;\n\ttimedOut?: boolean;\n\toutputTruncated: boolean;\n}\n\nfunction runChildProcess(\n\tcommand: string,\n\targs: string[],\n\toptions: {\n\t\tcwd?: string;\n\t\tshell?: boolean;\n\t\ttimeoutMs?: number;\n\t\tmaxOutputChars?: number;\n\t\tsignal?: AbortSignal;\n\t} = {},\n): Promise<ChildProcessResult> {\n\toptions.signal?.throwIfAborted();\n\tconst orphanOwner = captureOrphanProcessJournalOwner();\n\treturn new Promise((resolve, reject) => {\n\t\tconst child = spawn(command, args, {\n\t\t\tcwd: options.cwd,\n\t\t\tdetached: process.platform !== \"win32\",\n\t\t\tshell: options.shell === true,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t});\n\t\tlet registrationError: Error | undefined;\n\t\tlet error: Error | undefined;\n\t\tlet stdout = \"\";\n\t\tlet stderr = \"\";\n\t\tlet timedOut = false;\n\t\tlet outputTruncated = false;\n\t\tlet settled = false;\n\t\tconst maxOutputChars = options.maxOutputChars ?? MAX_CHILD_PROCESS_OUTPUT_CHARS;\n\t\tconst finish = (result: Pick<ChildProcessResult, \"status\" | \"signal\">) => {\n\t\t\tif (settled) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsettled = true;\n\t\t\tif (timer) {\n\t\t\t\tclearTimeout(timer);\n\t\t\t}\n\t\t\toptions.signal?.removeEventListener(\"abort\", abort);\n\t\t\tconst retirementError = child.pid ? untrackDetachedChildPid(child.pid) : undefined;\n\t\t\tconst completed: ChildProcessResult = { ...result, stdout, stderr, error, timedOut, outputTruncated };\n\t\t\tconst trackingError = registrationError ?? retirementError;\n\t\t\tif (trackingError) {\n\t\t\t\tconst failures = [\n\t\t\t\t\ttrackingError,\n\t\t\t\t\t...(error ? [error] : []),\n\t\t\t\t\t...(registrationError && retirementError ? [retirementError] : []),\n\t\t\t\t];\n\t\t\t\t// Reject only after the owned child settled and controls were cleaned. A gate\n\t\t\t\t// retry or an unavailable Git snapshot must not consume tracking uncertainty.\n\t\t\t\treject(\n\t\t\t\t\tnew AggregateError(\n\t\t\t\t\t\tfailures,\n\t\t\t\t\t\t`Spawned command exited with status ${completed.status} and signal ${completed.signal}; tracking is unknown: ${failures.map((failure) => failure.message).join(\"; \")}`,\n\t\t\t\t\t\t{ cause: completed },\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresolve(completed);\n\t\t};\n\t\tconst timer = options.timeoutMs\n\t\t\t? setTimeout(() => {\n\t\t\t\t\ttimedOut = true;\n\t\t\t\t\tif (child.pid) {\n\t\t\t\t\t\tkillProcessTree(child.pid);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchild.kill(\"SIGKILL\");\n\t\t\t\t\t}\n\t\t\t\t}, options.timeoutMs)\n\t\t\t: undefined;\n\t\tconst abort = () => {\n\t\t\tif (child.pid) {\n\t\t\t\tkillProcessTree(child.pid);\n\t\t\t} else {\n\t\t\t\tchild.kill(\"SIGKILL\");\n\t\t\t}\n\t\t};\n\t\toptions.signal?.addEventListener(\"abort\", abort, { once: true });\n\t\tif (options.signal?.aborted) {\n\t\t\tabort();\n\t\t}\n\t\tchild.stdout?.setEncoding(\"utf8\");\n\t\tchild.stderr?.setEncoding(\"utf8\");\n\t\tchild.stdout?.on(\"data\", (chunk: string) => {\n\t\t\tconst remaining = maxOutputChars - stdout.length;\n\t\t\tif (remaining > 0) {\n\t\t\t\tstdout += chunk.slice(0, remaining);\n\t\t\t}\n\t\t\toutputTruncated ||= chunk.length > remaining;\n\t\t});\n\t\tchild.stderr?.on(\"data\", (chunk: string) => {\n\t\t\tconst remaining = maxOutputChars - stderr.length;\n\t\t\tif (remaining > 0) {\n\t\t\t\tstderr += chunk.slice(0, remaining);\n\t\t\t}\n\t\t\toutputTruncated ||= chunk.length > remaining;\n\t\t});\n\t\tvoid waitForChildProcess(child).then(\n\t\t\t(status) => finish({ status, signal: child.signalCode }),\n\t\t\t(err: Error) => {\n\t\t\t\terror = err;\n\t\t\t\tfinish({ status: child.exitCode, signal: child.signalCode });\n\t\t\t},\n\t\t);\n\t\t// Install all existing controls before the synchronous journal bridge can block.\n\t\tregistrationError = child.pid ? trackDetachedChildPid(child.pid, orphanOwner) : undefined;\n\t});\n}\n\nfunction formatProcessExit(result: ChildProcessResult): string {\n\tif (result.timedOut) {\n\t\treturn \"timed out\";\n\t}\n\tif (result.error) {\n\t\treturn result.error.message;\n\t}\n\treturn result.signal ? `terminated by ${result.signal}` : `exited ${result.status ?? \"unknown\"}`;\n}\n\nfunction truncateGateOutput(output: string, outputAlreadyTruncated = false, maxChars = MAX_GATE_OUTPUT_CHARS): string {\n\tif (output.length <= maxChars && !outputAlreadyTruncated) {\n\t\treturn output;\n\t}\n\treturn `${output.slice(0, maxChars)}\\n... [truncated]`;\n}\n\nfunction normalizeLimit(value: number | undefined, fallback: number): number {\n\tif (!Number.isFinite(value) || value === undefined || value <= 0) {\n\t\treturn fallback;\n\t}\n\treturn Math.trunc(value);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"autonomous.js","sourceRoot":"","sources":["../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C;QAClB,OAAO,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC;IAC7B,CAAC;IACD,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,iBAAiB,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,UAAU,MAAM,CAAC,MAAM,IAAI,SAAS,EAAE,CAAC;AAAA,CACjG;AAED,SAAS,kBAAkB,CAAC,MAAc,EAAE,sBAAsB,GAAG,KAAK,EAAE,QAAQ,GAAG,qBAAqB,EAAU;IACrH,IAAI,MAAM,CAAC,MAAM,IAAI,QAAQ,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAC1D,OAAO,MAAM,CAAC;IACf,CAAC;IACD,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,mBAAmB,CAAC;AAAA,CACvD;AAED,SAAS,cAAc,CAAC,KAAyB,EAAE,QAAgB,EAAU;IAC5E,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,IAAI,CAAC,EAAE,CAAC;QAClE,OAAO,QAAQ,CAAC;IACjB,CAAC;IACD,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAAA,CACzB","sourcesContent":["import { spawn } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { createReadStream } from \"node:fs\";\nimport { lstat, readlink } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport type { AssistantMessage, Usage, UserMessage } from \"@ponythewhite/base-context-ai\";\nimport { waitForChildProcess } from \"../utils/child-process.js\";\nimport { killProcessTree, trackDetachedChildPid, untrackDetachedChildPid } from \"../utils/shell.js\";\nimport { captureOrphanProcessJournalOwner } from \"./orphan-process-journal.js\";\n\nexport interface AgentAutonomousConfig {\n\tenabled?: boolean;\n\tmaxContinuations?: number;\n\tmaxTurns?: number;\n\tmaxTokens?: number;\n\ttimeoutMs?: number;\n\tcontinuationPrompt?: string;\n\tgates?: AgentAutonomousGateConfig;\n}\n\nexport interface AgentAutonomousGateConfig {\n\tcommands?: string[];\n\tmaxRetries?: number;\n\ttimeoutMs?: number;\n}\n\nexport interface AgentAutonomousGateFailure {\n\tcommand: string;\n\tattempt: number;\n\texitText: string;\n\toutput: string;\n}\n\nexport interface AgentAutonomousStatus {\n\tenabled: boolean;\n\tcontinuationsUsed: number;\n\tturnsUsed: number;\n\ttokensUsed: number;\n\tstartedAt?: number;\n\tlimits: Required<Omit<AgentAutonomousConfig, \"enabled\" | \"continuationPrompt\" | \"gates\">>;\n\tgates: Required<AgentAutonomousGateConfig>;\n\tgateAttempts: Record<string, number>;\n\tlastGateFailure?: AgentAutonomousGateFailure;\n}\n\nexport const DEFAULT_AUTONOMOUS_CONTINUATION_PROMPT =\n\t\"No human input is available in autonomous mode. Continue the requested task within its scope and configured autonomous limits. Use the checks requested by the user or configured gates; do not add proof artifacts, self-certification, or repeated validation loops. If input is missing, make reasonable assumptions only within existing permissions. If blocked, state the concrete blocker briefly and work on independent unblocked tasks. Required approvals remain required. Configured gates and limits control continuation.\";\n\nexport const DEFAULT_AUTONOMOUS_LIMITS: Required<\n\tOmit<AgentAutonomousConfig, \"enabled\" | \"continuationPrompt\" | \"gates\">\n> = {\n\tmaxContinuations: 3,\n\tmaxTurns: 12,\n\tmaxTokens: 80_000,\n\ttimeoutMs: 30 * 60 * 1000,\n};\n\nexport const DEFAULT_AUTONOMOUS_GATES: Required<AgentAutonomousGateConfig> = {\n\tcommands: [],\n\tmaxRetries: 3,\n\ttimeoutMs: 5 * 60 * 1000,\n};\n\nconst MAX_GATE_OUTPUT_CHARS = 6000;\nconst MAX_CHILD_PROCESS_OUTPUT_CHARS = 1024 * 1024;\n\nexport interface AutonomousRuntimeState {\n\tenabled: boolean;\n\tcontinuationsUsed: number;\n\tturnsUsed: number;\n\ttokensUsed: number;\n\tstartedAt?: number;\n\tlimits: Required<Omit<AgentAutonomousConfig, \"enabled\" | \"continuationPrompt\" | \"gates\">>;\n\tcontinuationPrompt: string;\n\tgates: Required<AgentAutonomousGateConfig>;\n\tgateAttempts: Record<string, number>;\n\tlastGateFailure?: GateFailure;\n\tlastGateFailureSnapshot?: GitWorktreeSnapshot;\n}\n\nexport type AutonomousLimitReason = \"maxContinuations\" | \"maxTurns\" | \"maxTokens\" | \"timeoutMs\";\nexport type AutonomousGateResult = \"passed\" | \"failed\" | \"retry_exhausted\";\n\ntype AutonomousLimitState = Pick<\n\tAgentAutonomousStatus,\n\t\"continuationsUsed\" | \"turnsUsed\" | \"tokensUsed\" | \"startedAt\" | \"limits\"\n>;\n\nexport interface AutonomousDecision {\n\tshouldContinue: boolean;\n\treason: \"missing_terminal_evidence\" | \"gate_failed\" | \"not_needed\" | \"limit_reached\";\n}\n\ninterface GitWorktreeSnapshot {\n\tstatus: string;\n\tdiff: string;\n\tuntrackedHash: string;\n}\n\ninterface AutonomousOperationOptions {\n\tcwd?: string;\n\tsignal?: AbortSignal;\n}\n\ntype GateFailure = AgentAutonomousGateFailure;\n\nexport function createAutonomousRuntimeState(\n\tconfig?: AgentAutonomousConfig,\n\t_options: { cwd?: string } = {},\n): AutonomousRuntimeState {\n\tconst enabled = config?.enabled === true;\n\treturn {\n\t\tenabled,\n\t\tcontinuationsUsed: 0,\n\t\tturnsUsed: 0,\n\t\ttokensUsed: 0,\n\t\tstartedAt: enabled ? Date.now() : undefined,\n\t\tlimits: {\n\t\t\tmaxContinuations: normalizeLimit(config?.maxContinuations, DEFAULT_AUTONOMOUS_LIMITS.maxContinuations),\n\t\t\tmaxTurns: normalizeLimit(config?.maxTurns, DEFAULT_AUTONOMOUS_LIMITS.maxTurns),\n\t\t\tmaxTokens: normalizeLimit(config?.maxTokens, DEFAULT_AUTONOMOUS_LIMITS.maxTokens),\n\t\t\ttimeoutMs: normalizeLimit(config?.timeoutMs, DEFAULT_AUTONOMOUS_LIMITS.timeoutMs),\n\t\t},\n\t\tcontinuationPrompt: config?.continuationPrompt?.trim() || DEFAULT_AUTONOMOUS_CONTINUATION_PROMPT,\n\t\tgates: {\n\t\t\tcommands: [...(config?.gates?.commands ?? DEFAULT_AUTONOMOUS_GATES.commands)],\n\t\t\tmaxRetries: normalizeLimit(config?.gates?.maxRetries, DEFAULT_AUTONOMOUS_GATES.maxRetries),\n\t\t\ttimeoutMs: normalizeLimit(config?.gates?.timeoutMs, DEFAULT_AUTONOMOUS_GATES.timeoutMs),\n\t\t},\n\t\tgateAttempts: {},\n\t\tlastGateFailure: undefined,\n\t\tlastGateFailureSnapshot: undefined,\n\t};\n}\n\nexport function setAutonomousEnabled(\n\tstate: AutonomousRuntimeState,\n\tenabled: boolean,\n\t_options: { cwd?: string } = {},\n): void {\n\tstate.enabled = enabled;\n\tif (enabled) {\n\t\tstate.continuationsUsed = 0;\n\t\tstate.turnsUsed = 0;\n\t\tstate.tokensUsed = 0;\n\t\tstate.startedAt = Date.now();\n\t\tstate.gateAttempts = {};\n\t\tstate.lastGateFailure = undefined;\n\t\tstate.lastGateFailureSnapshot = undefined;\n\t} else {\n\t\tstate.startedAt = undefined;\n\t\tstate.gateAttempts = {};\n\t\tstate.lastGateFailure = undefined;\n\t\tstate.lastGateFailureSnapshot = undefined;\n\t}\n}\n\nexport function autonomousStatus(state: AutonomousRuntimeState): AgentAutonomousStatus {\n\treturn {\n\t\tenabled: state.enabled,\n\t\tcontinuationsUsed: state.continuationsUsed,\n\t\tturnsUsed: state.turnsUsed,\n\t\ttokensUsed: state.tokensUsed,\n\t\tstartedAt: state.startedAt,\n\t\tlimits: { ...state.limits },\n\t\tgates: { ...state.gates, commands: [...state.gates.commands] },\n\t\tgateAttempts: { ...state.gateAttempts },\n\t\tlastGateFailure: state.lastGateFailure ? { ...state.lastGateFailure } : undefined,\n\t};\n}\n\nexport function addAutonomousUsage(state: AutonomousRuntimeState, usage: Usage | undefined): void {\n\tif (!state.enabled) {\n\t\treturn;\n\t}\n\tstate.turnsUsed++;\n\tstate.tokensUsed += autonomousTokenDelta(usage);\n}\n\nexport function addAutonomousContinuation(state: AutonomousRuntimeState): void {\n\tif (!state.enabled) {\n\t\treturn;\n\t}\n\tstate.continuationsUsed++;\n}\n\nfunction autonomousTokenDelta(usage: Usage | undefined): number {\n\tif (!usage) {\n\t\treturn 0;\n\t}\n\t// Cache-read tokens are repeated context served from provider cache. Counting them\n\t// cumulatively makes long autonomous verifier loops exhaust their host-side token\n\t// budget far before the non-cached work reaches the configured cap.\n\treturn usage.input + usage.output + usage.cacheWrite;\n}\n\nexport async function nextAutonomousContinuation(\n\tstate: AutonomousRuntimeState,\n\tmessage: AssistantMessage,\n\toptions: AutonomousOperationOptions = {},\n\tnow = Date.now(),\n): Promise<UserMessage | undefined> {\n\toptions.signal?.throwIfAborted();\n\tif (!state.enabled) {\n\t\treturn undefined;\n\t}\n\tconst decision = await shouldAutonomouslyContinue(state, message, options, now);\n\toptions.signal?.throwIfAborted();\n\tif (!decision.shouldContinue) {\n\t\treturn undefined;\n\t}\n\tstate.continuationsUsed++;\n\treturn {\n\t\trole: \"user\",\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext:\n\t\t\t\t\tdecision.reason === \"gate_failed\"\n\t\t\t\t\t\t? (buildGateFailureContinuation(state, now) ?? state.continuationPrompt)\n\t\t\t\t\t\t: state.continuationPrompt,\n\t\t\t},\n\t\t],\n\t\ttimestamp: now,\n\t};\n}\n\nexport async function shouldAutonomouslyContinue(\n\tstate: AutonomousRuntimeState,\n\tmessage: AssistantMessage,\n\toptions: AutonomousOperationOptions = {},\n\tnow = Date.now(),\n): Promise<AutonomousDecision> {\n\toptions.signal?.throwIfAborted();\n\tif (!state.enabled || message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\treturn { shouldContinue: false, reason: \"not_needed\" };\n\t}\n\tconst gateResult = await refreshAutonomousQualityGates(state, options);\n\toptions.signal?.throwIfAborted();\n\tif (gateResult) {\n\t\tif (gateResult === \"passed\") {\n\t\t\treturn { shouldContinue: false, reason: \"not_needed\" };\n\t\t}\n\t\tif (gateResult === \"retry_exhausted\" || autonomousLimitReason(state, now)) {\n\t\t\treturn { shouldContinue: false, reason: \"limit_reached\" };\n\t\t}\n\t\treturn { shouldContinue: true, reason: \"gate_failed\" };\n\t}\n\tif (autonomousLimitReason(state, now)) {\n\t\treturn { shouldContinue: false, reason: \"limit_reached\" };\n\t}\n\treturn { shouldContinue: true, reason: \"missing_terminal_evidence\" };\n}\n\nexport function autonomousLimitReason(\n\tstate: AutonomousLimitState,\n\tnow = Date.now(),\n): AutonomousLimitReason | undefined {\n\tif (state.continuationsUsed >= state.limits.maxContinuations) {\n\t\treturn \"maxContinuations\";\n\t}\n\treturn autonomousRunLimitReason(state, now);\n}\n\n/** Work limits also apply between native tool turns, not only injected continuations. */\nexport function autonomousRunLimitReason(\n\tstate: AutonomousLimitState,\n\tnow = Date.now(),\n): Exclude<AutonomousLimitReason, \"maxContinuations\"> | undefined {\n\tif (state.turnsUsed >= state.limits.maxTurns) {\n\t\treturn \"maxTurns\";\n\t}\n\tif (state.tokensUsed >= state.limits.maxTokens) {\n\t\treturn \"maxTokens\";\n\t}\n\tif (state.startedAt !== undefined && now - state.startedAt >= state.limits.timeoutMs) {\n\t\treturn \"timeoutMs\";\n\t}\n\treturn undefined;\n}\n\nexport async function refreshAutonomousQualityGates(\n\tstate: AutonomousRuntimeState,\n\toptions: AutonomousOperationOptions = {},\n): Promise<AutonomousGateResult | undefined> {\n\toptions.signal?.throwIfAborted();\n\tif (!state.enabled || state.gates.commands.length === 0) {\n\t\treturn undefined;\n\t}\n\treturn await runAutonomousQualityGates(state, options.cwd, options.signal);\n}\n\nasync function runAutonomousQualityGates(\n\tstate: AutonomousRuntimeState,\n\tcwd: string | undefined,\n\tsignal: AbortSignal | undefined,\n): Promise<AutonomousGateResult> {\n\tsignal?.throwIfAborted();\n\tif (!cwd) {\n\t\treturn \"failed\";\n\t}\n\tfor (const command of state.gates.commands) {\n\t\tconst currentSnapshot = await captureGitWorktreeSnapshot(cwd, signal);\n\t\tsignal?.throwIfAborted();\n\t\tif (\n\t\t\tstate.lastGateFailure?.command === command &&\n\t\t\tstate.lastGateFailureSnapshot &&\n\t\t\tgitWorktreeSnapshotsEqual(currentSnapshot, state.lastGateFailureSnapshot)\n\t\t) {\n\t\t\tconst attempt = (state.gateAttempts[command] ?? state.lastGateFailure.attempt) + 1;\n\t\t\tstate.gateAttempts[command] = attempt;\n\t\t\tstate.lastGateFailure = {\n\t\t\t\t...state.lastGateFailure,\n\t\t\t\tattempt,\n\t\t\t\texitText: \"not rerun: workspace unchanged since previous failed gate\",\n\t\t\t\toutput:\n\t\t\t\t\t\"The autonomous gate was not rerun because the workspace has not changed since this failure. Edit source files, tests, or a blocker artifact before attempting to finish again.\",\n\t\t\t};\n\t\t\treturn attempt > state.gates.maxRetries ? \"retry_exhausted\" : \"failed\";\n\t\t}\n\t\tconst result = await runChildProcess(command, [], {\n\t\t\tcwd,\n\t\t\tshell: true,\n\t\t\ttimeoutMs: state.gates.timeoutMs,\n\t\t\tmaxOutputChars: MAX_GATE_OUTPUT_CHARS,\n\t\t\tsignal,\n\t\t});\n\t\tsignal?.throwIfAborted();\n\t\tconst postRunSnapshot = await captureGitWorktreeSnapshot(cwd, signal);\n\t\tsignal?.throwIfAborted();\n\t\tif (result.status === 0 && !result.error && !result.timedOut) {\n\t\t\tstate.gateAttempts[command] = 0;\n\t\t\tif (state.lastGateFailure?.command === command) {\n\t\t\t\tstate.lastGateFailure = undefined;\n\t\t\t\tstate.lastGateFailureSnapshot = undefined;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst attempt = (state.gateAttempts[command] ?? 0) + 1;\n\t\tstate.gateAttempts[command] = attempt;\n\t\tconst exitText = formatProcessExit(result);\n\t\tstate.lastGateFailure = {\n\t\t\tcommand,\n\t\t\tattempt,\n\t\t\texitText,\n\t\t\toutput: truncateGateOutput(\n\t\t\t\t[result.stdout, result.stderr].filter(Boolean).join(\"\\n\").trim(),\n\t\t\t\tresult.outputTruncated,\n\t\t\t),\n\t\t};\n\t\tstate.lastGateFailureSnapshot = postRunSnapshot;\n\t\treturn attempt > state.gates.maxRetries ? \"retry_exhausted\" : \"failed\";\n\t}\n\tstate.lastGateFailure = undefined;\n\tstate.lastGateFailureSnapshot = undefined;\n\treturn \"passed\";\n}\n\nexport function buildAutonomousGateFailureContinuation(\n\tfailure: AgentAutonomousGateFailure,\n\tmaxRetries: number,\n\ttimestamp = Date.now(),\n): string {\n\treturn (\n\t\t`Autonomous quality gate failed (attempt ${failure.attempt}/${maxRetries}): \\`${failure.command}\\` ${failure.exitText}.\\n` +\n\t\t(failure.output ? `\\nOutput:\\n${failure.output}\\n` : \"\\n\") +\n\t\t`\\nContinue working. Fix the failure, then produce terminal evidence. Timestamp: ${new Date(timestamp).toISOString()}.`\n\t);\n}\n\nfunction buildGateFailureContinuation(state: AutonomousRuntimeState, timestamp: number): string | undefined {\n\tconst failure = state.lastGateFailure;\n\tif (!failure) {\n\t\treturn undefined;\n\t}\n\treturn buildAutonomousGateFailureContinuation(failure, state.gates.maxRetries, timestamp);\n}\n\nfunction gitWorktreeSnapshotsEqual(a: GitWorktreeSnapshot | undefined, b: GitWorktreeSnapshot | undefined): boolean {\n\treturn !!a && !!b && a.status === b.status && a.diff === b.diff && a.untrackedHash === b.untrackedHash;\n}\n\nasync function captureGitWorktreeSnapshot(\n\tcwd: string | undefined,\n\tsignal?: AbortSignal,\n): Promise<GitWorktreeSnapshot | undefined> {\n\tsignal?.throwIfAborted();\n\tif (!cwd) {\n\t\treturn undefined;\n\t}\n\tconst pathspec = [\n\t\t\"--\",\n\t\t\".\",\n\t\t\":(exclude)verification\",\n\t\t\":(exclude)target\",\n\t\t\":(exclude).vf-prime-agent\",\n\t\t\":(exclude)Cargo.lock\",\n\t\t\":(exclude)submission.tar.gz\",\n\t\t\":(exclude)runner_args.log\",\n\t];\n\tconst status = await runChildProcess(\n\t\t\"git\",\n\t\t[\"--no-optional-locks\", \"status\", \"--porcelain=v1\", \"-z\", \"-uall\", \"--no-renames\", ...pathspec],\n\t\t{\n\t\t\tcwd,\n\t\t\ttimeoutMs: 10_000,\n\t\t\tsignal,\n\t\t},\n\t);\n\tsignal?.throwIfAborted();\n\tif (status.status !== 0 || status.error || status.timedOut || status.outputTruncated) {\n\t\treturn undefined;\n\t}\n\tconst diff = await runChildProcess(\n\t\t\"git\",\n\t\t[\"--no-optional-locks\", \"diff\", \"--no-ext-diff\", \"--binary\", \"HEAD\", ...pathspec],\n\t\t{\n\t\t\tcwd,\n\t\t\ttimeoutMs: 10_000,\n\t\t\tsignal,\n\t\t},\n\t);\n\tsignal?.throwIfAborted();\n\tif (diff.status !== 0 || diff.error || diff.timedOut || diff.outputTruncated) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tstatus: status.stdout,\n\t\tdiff: diff.stdout,\n\t\tuntrackedHash: await hashUntrackedFiles(cwd, status.stdout, signal),\n\t};\n}\n\nfunction untrackedPathsFromStatus(status: string): string[] {\n\treturn status\n\t\t.split(\"\\0\")\n\t\t.filter((entry) => entry.startsWith(\"?? \"))\n\t\t.map((entry) => entry.slice(3))\n\t\t.sort();\n}\n\nasync function hashUntrackedFiles(cwd: string, status: string, signal?: AbortSignal): Promise<string> {\n\tconst aggregate = createHash(\"sha256\");\n\tfor (const path of untrackedPathsFromStatus(status)) {\n\t\tsignal?.throwIfAborted();\n\t\taggregate.update(path);\n\t\taggregate.update(\"\\0\");\n\t\taggregate.update(await hashUntrackedPath(resolve(cwd, path), signal));\n\t\taggregate.update(\"\\0\");\n\t}\n\tsignal?.throwIfAborted();\n\treturn aggregate.digest(\"hex\");\n}\n\nasync function hashUntrackedPath(path: string, signal?: AbortSignal): Promise<string> {\n\ttry {\n\t\tsignal?.throwIfAborted();\n\t\tconst stat = await lstat(path);\n\t\tsignal?.throwIfAborted();\n\t\tif (stat.isSymbolicLink()) {\n\t\t\tconst target = await readlink(path);\n\t\t\tsignal?.throwIfAborted();\n\t\t\treturn `symlink:${target}`;\n\t\t}\n\t\tif (!stat.isFile()) {\n\t\t\treturn `other:${stat.mode}:${stat.size}:${stat.mtimeMs}`;\n\t\t}\n\t\tconst hash = createHash(\"sha256\");\n\t\tfor await (const chunk of createReadStream(path, { signal })) {\n\t\t\thash.update(chunk);\n\t\t}\n\t\tsignal?.throwIfAborted();\n\t\treturn `file:${hash.digest(\"hex\")}`;\n\t} catch (error) {\n\t\tsignal?.throwIfAborted();\n\t\treturn `error:${error instanceof Error ? error.message : String(error)}`;\n\t}\n}\n\ninterface ChildProcessResult {\n\tstatus: number | null;\n\tsignal: NodeJS.Signals | null;\n\tstdout: string;\n\tstderr: string;\n\terror?: Error;\n\ttimedOut?: boolean;\n\toutputTruncated: boolean;\n}\n\nfunction runChildProcess(\n\tcommand: string,\n\targs: string[],\n\toptions: {\n\t\tcwd?: string;\n\t\tshell?: boolean;\n\t\ttimeoutMs?: number;\n\t\tmaxOutputChars?: number;\n\t\tsignal?: AbortSignal;\n\t} = {},\n): Promise<ChildProcessResult> {\n\toptions.signal?.throwIfAborted();\n\tconst orphanOwner = captureOrphanProcessJournalOwner();\n\treturn new Promise((resolve, reject) => {\n\t\tconst child = spawn(command, args, {\n\t\t\tcwd: options.cwd,\n\t\t\tdetached: process.platform !== \"win32\",\n\t\t\tshell: options.shell === true,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t});\n\t\tlet registrationError: Error | undefined;\n\t\tlet error: Error | undefined;\n\t\tlet stdout = \"\";\n\t\tlet stderr = \"\";\n\t\tlet timedOut = false;\n\t\tlet outputTruncated = false;\n\t\tlet settled = false;\n\t\tconst maxOutputChars = options.maxOutputChars ?? MAX_CHILD_PROCESS_OUTPUT_CHARS;\n\t\tconst finish = (result: Pick<ChildProcessResult, \"status\" | \"signal\">) => {\n\t\t\tif (settled) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsettled = true;\n\t\t\tif (timer) {\n\t\t\t\tclearTimeout(timer);\n\t\t\t}\n\t\t\toptions.signal?.removeEventListener(\"abort\", abort);\n\t\t\tconst retirementError = child.pid ? untrackDetachedChildPid(child.pid) : undefined;\n\t\t\tconst completed: ChildProcessResult = { ...result, stdout, stderr, error, timedOut, outputTruncated };\n\t\t\tconst trackingError = registrationError ?? retirementError;\n\t\t\tif (trackingError) {\n\t\t\t\tconst failures = [\n\t\t\t\t\ttrackingError,\n\t\t\t\t\t...(error ? [error] : []),\n\t\t\t\t\t...(registrationError && retirementError ? [retirementError] : []),\n\t\t\t\t];\n\t\t\t\t// Reject only after the owned child settled and controls were cleaned. A gate\n\t\t\t\t// retry or an unavailable Git snapshot must not consume tracking uncertainty.\n\t\t\t\treject(\n\t\t\t\t\tnew AggregateError(\n\t\t\t\t\t\tfailures,\n\t\t\t\t\t\t`Spawned command exited with status ${completed.status} and signal ${completed.signal}; tracking is unknown: ${failures.map((failure) => failure.message).join(\"; \")}`,\n\t\t\t\t\t\t{ cause: completed },\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresolve(completed);\n\t\t};\n\t\tconst timer = options.timeoutMs\n\t\t\t? setTimeout(() => {\n\t\t\t\t\ttimedOut = true;\n\t\t\t\t\tif (child.pid) {\n\t\t\t\t\t\tkillProcessTree(child.pid);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchild.kill(\"SIGKILL\");\n\t\t\t\t\t}\n\t\t\t\t}, options.timeoutMs)\n\t\t\t: undefined;\n\t\tconst abort = () => {\n\t\t\tif (child.pid) {\n\t\t\t\tkillProcessTree(child.pid);\n\t\t\t} else {\n\t\t\t\tchild.kill(\"SIGKILL\");\n\t\t\t}\n\t\t};\n\t\toptions.signal?.addEventListener(\"abort\", abort, { once: true });\n\t\tif (options.signal?.aborted) {\n\t\t\tabort();\n\t\t}\n\t\tchild.stdout?.setEncoding(\"utf8\");\n\t\tchild.stderr?.setEncoding(\"utf8\");\n\t\tchild.stdout?.on(\"data\", (chunk: string) => {\n\t\t\tconst remaining = maxOutputChars - stdout.length;\n\t\t\tif (remaining > 0) {\n\t\t\t\tstdout += chunk.slice(0, remaining);\n\t\t\t}\n\t\t\toutputTruncated ||= chunk.length > remaining;\n\t\t});\n\t\tchild.stderr?.on(\"data\", (chunk: string) => {\n\t\t\tconst remaining = maxOutputChars - stderr.length;\n\t\t\tif (remaining > 0) {\n\t\t\t\tstderr += chunk.slice(0, remaining);\n\t\t\t}\n\t\t\toutputTruncated ||= chunk.length > remaining;\n\t\t});\n\t\tvoid waitForChildProcess(child).then(\n\t\t\t(status) => finish({ status, signal: child.signalCode }),\n\t\t\t(err: Error) => {\n\t\t\t\terror = err;\n\t\t\t\tfinish({ status: child.exitCode, signal: child.signalCode });\n\t\t\t},\n\t\t);\n\t\t// Install all existing controls before the synchronous journal bridge can block.\n\t\tregistrationError = child.pid ? trackDetachedChildPid(child.pid, orphanOwner) : undefined;\n\t});\n}\n\nfunction formatProcessExit(result: ChildProcessResult): string {\n\tif (result.timedOut) {\n\t\treturn \"timed out\";\n\t}\n\tif (result.error) {\n\t\treturn result.error.message;\n\t}\n\treturn result.signal ? `terminated by ${result.signal}` : `exited ${result.status ?? \"unknown\"}`;\n}\n\nfunction truncateGateOutput(output: string, outputAlreadyTruncated = false, maxChars = MAX_GATE_OUTPUT_CHARS): string {\n\tif (output.length <= maxChars && !outputAlreadyTruncated) {\n\t\treturn output;\n\t}\n\treturn `${output.slice(0, maxChars)}\\n... [truncated]`;\n}\n\nfunction normalizeLimit(value: number | undefined, fallback: number): number {\n\tif (!Number.isFinite(value) || value === undefined || value <= 0) {\n\t\treturn fallback;\n\t}\n\treturn Math.trunc(value);\n}\n"]}
|