Skip to content

Commit c3ec166

Browse files
committed
fix: repair code mode preflight failures
1 parent 8f18edf commit c3ec166

20 files changed

Lines changed: 338 additions & 105 deletions

‎src/agents/agent-tools.before-tool-call.wrapper.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ import {
8484
formatToolExecutionErrorMessage,
8585
isTrustedToolExecutionPreflightError,
8686
protectNetworkToolExecutionError,
87+
registerTrustedToolNoStartError,
8788
} from "./tool-result-error.js";
8889
import { copyToolTerminalPresentation } from "./tool-terminal-presentation.js";
8990
import type { AnyAgentTool } from "./tools/common.js";
@@ -174,6 +175,7 @@ class BeforeToolCallFailureError extends Error {
174175
function tagBeforeToolCallFailure(
175176
error: unknown,
176177
signal?: AbortSignal,
178+
stage?: "tool_preparation" | "before_tool_call",
177179
): BeforeToolCallFailureError {
178180
try {
179181
if (error instanceof BeforeToolCallFailureError) {
@@ -184,7 +186,11 @@ function tagBeforeToolCallFailure(
184186
}
185187
const message = formatToolExecutionErrorMessage(error, "before_tool_call failed");
186188
const disposition = resolveToolErrorDiagnostic(error, signal).terminalReason;
187-
return new BeforeToolCallFailureError(message, disposition, error);
189+
const tagged = new BeforeToolCallFailureError(message, disposition, error);
190+
if (stage === "tool_preparation" && isTrustedToolExecutionPreflightError(error)) {
191+
registerTrustedToolNoStartError(tagged);
192+
}
193+
return tagged;
188194
}
189195

190196
/** Return the closed terminal disposition carried by a before-tool failure. */
@@ -427,7 +433,7 @@ export function wrapToolWithBeforeToolCallHook(
427433
});
428434
} catch (error) {
429435
recordPreExecutionError(error, params, "tool_preparation");
430-
throw tagBeforeToolCallFailure(error, signal);
436+
throw tagBeforeToolCallFailure(error, signal, "tool_preparation");
431437
}
432438
const hookParams = normalizeCodeModeExecBeforeHookParams({ tool, params: preparedParams });
433439
const hookMetadata = getCodeModeExecBeforeHookMetadata({ tool, params: preparedParams });
@@ -444,7 +450,7 @@ export function wrapToolWithBeforeToolCallHook(
444450
});
445451
} catch (error) {
446452
recordPreExecutionError(error, hookParams, "before_tool_call");
447-
throw tagBeforeToolCallFailure(error, signal);
453+
throw tagBeforeToolCallFailure(error, signal, "before_tool_call");
448454
}
449455
if (outcome.blocked) {
450456
if (outcome.kind !== "veto") {
@@ -487,7 +493,7 @@ export function wrapToolWithBeforeToolCallHook(
487493
});
488494
} catch (error) {
489495
recordPreExecutionError(error, outcome.params ?? hookParams, "tool_preparation");
490-
throw tagBeforeToolCallFailure(error, signal);
496+
throw tagBeforeToolCallFailure(error, signal, "tool_preparation");
491497
}
492498
let onImplementationStart: (() => void) | undefined;
493499
if (prepareControl) {

‎src/agents/bash-tools.exec-request-preparation.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import { buildSandboxEnv, coerceEnv } from "./bash-tools.shared.js";
2626
import type { BashSandboxConfig } from "./bash-tools.shared.js";
2727
import { prepareGitHubToolEnvironment } from "./github-tool-identity.js";
2828
import { sanitizeEnvVars } from "./sandbox/sanitize-env-vars.js";
29+
import { ToolInputError } from "./tools/common.js";
2930

3031
export type ExecToolArgs = Record<string, unknown> & {
3132
command: string;
@@ -74,6 +75,14 @@ const XML_ARG_VALUE_EXEC_PARAM_KEYS = [
7475
"node",
7576
] as const;
7677

78+
export function assertSupportedExecParams(args: unknown): void {
79+
if (isRecord(args) && Object.hasOwn(args, "timeout")) {
80+
throw new ToolInputError(
81+
'exec parameter "timeout" is unsupported; use "timeoutSeconds" instead',
82+
);
83+
}
84+
}
85+
7786
function buildSubprocessChannelContext(
7887
channelContext: PluginHookChannelContext | undefined,
7988
): PluginHookChannelContext | undefined {
@@ -286,6 +295,7 @@ export function createExecRequestPreparation(params: {
286295
args: unknown,
287296
context: { hookContext?: unknown },
288297
): Promise<ExecToolArgs> => {
298+
assertSupportedExecParams(args);
289299
const execParams = await prepareParamsWithResolvedExecWorkdir(args);
290300
const workdirState = getResolvedExecWorkdirPreparedState(execParams);
291301
if (workdirState?.resolution.kind === "unavailable") {

‎src/agents/bash-tools.exec-run.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import { describeExecTool } from "./bash-tools.descriptions.js";
3232
import { processGatewayAllowlist } from "./bash-tools.exec-host-gateway.js";
3333
import { executeNodeHostCommand } from "./bash-tools.exec-host-node.js";
3434
import {
35+
assertSupportedExecParams,
3536
createExecRequestPreparation,
3637
type ExecToolArgs,
3738
resolveExecPreparedRunEnvironment,
@@ -176,9 +177,7 @@ export function createExecTool(
176177
finalizeBeforeToolCallParams: requestPreparation.finalizeBeforeToolCallParams,
177178
execute: async (toolCallId, args, signal, onUpdate) => {
178179
signal?.throwIfAborted();
179-
if (Object.hasOwn(args, "timeout")) {
180-
throw new Error('exec parameter "timeout" is unsupported; use "timeoutSeconds" instead');
181-
}
180+
assertSupportedExecParams(args);
182181
// Review cancellation belongs to this execution, never another call on the shared tool.
183182
const autoReviewer =
184183
defaults?.autoReviewer ??

‎src/agents/code-mode-bridge.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@ import {
2626
SWARM_CODE_MODE_REQUEST_FINGERPRINT,
2727
} from "./subagents/swarm/swarm-code-mode.js";
2828
import { resolveSwarmConfig } from "./subagents/swarm/swarm-config.js";
29+
import {
30+
consumeTrustedToolNoStartError,
31+
registerTrustedToolNoStartError,
32+
} from "./tool-result-error.js";
2933
import { ToolSearchRuntime, type ToolSearchToolContext } from "./tool-search.js";
3034
import {
3135
waitForCollectorCompletion,
@@ -579,10 +583,14 @@ export async function runBridgeRequest(params: {
579583
value: boundCodeModeValue(value, params.maxOutputBytes),
580584
};
581585
} catch (error) {
582-
return {
586+
const settled: SettledBridgeRequest = {
583587
id: params.request.id,
584588
ok: false,
585589
error: redactCodeModeCatalogIds(formatErrorMessage(error), catalogProjection.bindings),
586590
};
591+
if (consumeTrustedToolNoStartError(error)) {
592+
registerTrustedToolNoStartError(settled);
593+
}
594+
return settled;
587595
}
588596
}

‎src/agents/code-mode-execution.ts‎

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
createCodeModeNamespaceRuntime,
1111
type CodeModeNamespaceRuntime,
1212
} from "./code-mode-namespaces.js";
13+
import { registerRepairableCodeModeFailure } from "./code-mode-repair-provenance.js";
1314
import {
1415
CODE_MODE_WORKER_WATCHDOG_GRACE_MS,
1516
codeModeFailureCode,
@@ -31,8 +32,10 @@ import {
3132
cancelPendingBridgeStates,
3233
cancelPendingBridgeStatesById,
3334
codeModeWaitingReason,
35+
createCodeModeBridgeDispatchState,
3436
createPendingBridgeStates,
3537
disposeCodeModeRun,
38+
isCodeModeBridgeRepairEligible,
3639
pendingBridgeRequestsReplaySafe,
3740
pendingBridgeStatesForSettlement,
3841
pendingToolCalls,
@@ -46,6 +49,7 @@ import {
4649
telemetry,
4750
waitForPendingBridgeSettlement,
4851
type PendingBridgeState,
52+
type CodeModeBridgeDispatchState,
4953
} from "./code-mode-state.js";
5054
import { normalizeCodeModeWorkerResult, runCodeModeWorker } from "./code-mode-worker.js";
5155
import type { AgentToolUpdateCallback } from "./runtime/index.js";
@@ -74,9 +78,11 @@ export async function runCodeModeExec(params: {
7478
if (config.enabled === false) {
7579
throw new ToolInputError("code mode is disabled.");
7680
}
77-
const runtime = new ToolSearchRuntime(params.ctx, toToolSearchConfig(config));
81+
const runtime = new ToolSearchRuntime(params.ctx, toToolSearchConfig(config), {
82+
validateInput: true,
83+
});
7884
params.onRuntime?.(runtime);
79-
const bridgeDispatch = { started: false };
85+
const bridgeDispatch = createCodeModeBridgeDispatchState();
8086
if (params.signal?.aborted) {
8187
return {
8288
status: "failed" as const,
@@ -241,7 +247,7 @@ async function settleCodeModeResult(params: {
241247
pending?: PendingBridgeState[];
242248
activeRunId?: string;
243249
reservedActiveRunSlot?: boolean;
244-
bridgeDispatch: { started: boolean };
250+
bridgeDispatch: CodeModeBridgeDispatchState;
245251
signal?: AbortSignal;
246252
onUpdate?: AgentToolUpdateCallback;
247253
}) {
@@ -320,11 +326,6 @@ async function settleCodeModeResult(params: {
320326
const newPendingRequests = result.pendingRequests.filter(
321327
(request) => !pendingIds.has(request.id),
322328
);
323-
if (newPendingRequests.some((request) => request.method !== "sleep")) {
324-
// createPendingBridgeStates starts host calls synchronously. Flip the
325-
// evidence first so every later failure is permanently non-retryable.
326-
params.bridgeDispatch.started = true;
327-
}
328329
pending.push(
329330
...createPendingBridgeStates({
330331
pendingRequests: newPendingRequests,
@@ -339,6 +340,7 @@ async function settleCodeModeResult(params: {
339340
ctx: params.ctx,
340341
signal: params.signal,
341342
onUpdate: params.onUpdate,
343+
bridgeDispatch: params.bridgeDispatch,
342344
}),
343345
);
344346
const ready = await waitForPending(
@@ -375,6 +377,7 @@ async function settleCodeModeResult(params: {
375377
namespaceRuntime: params.namespaceRuntime,
376378
output,
377379
deliveredOutputCount,
380+
bridgeDispatch: params.bridgeDispatch,
378381
});
379382
}
380383
// Deliver the settled frontier only. Unresolved sibling promises remain
@@ -458,9 +461,6 @@ async function settleCodeModeResult(params: {
458461
const newPendingRequests = result.pendingRequests.filter(
459462
(request) => !pendingIds.has(request.id),
460463
);
461-
if (newPendingRequests.some((request) => request.method !== "sleep")) {
462-
params.bridgeDispatch.started = true;
463-
}
464464
pending.push(
465465
...createPendingBridgeStates({
466466
pendingRequests: newPendingRequests,
@@ -475,6 +475,7 @@ async function settleCodeModeResult(params: {
475475
ctx: params.ctx,
476476
signal: params.signal,
477477
onUpdate: params.onUpdate,
478+
bridgeDispatch: params.bridgeDispatch,
478479
}),
479480
);
480481
return storeSnapshotState({
@@ -492,6 +493,7 @@ async function settleCodeModeResult(params: {
492493
namespaceRuntime: params.namespaceRuntime,
493494
output,
494495
deliveredOutputCount,
496+
bridgeDispatch: params.bridgeDispatch,
495497
});
496498
} catch (error) {
497499
cancelPendingBridgeStates(pending);
@@ -500,9 +502,6 @@ async function settleCodeModeResult(params: {
500502
releaseReservation?.();
501503
}
502504
}
503-
if (result.pendingRequests.some((request) => request.method !== "sleep")) {
504-
params.bridgeDispatch.started = true;
505-
}
506505
return snapshotState({
507506
pendingRequests: result.pendingRequests,
508507
snapshotBytes: result.snapshotBytes,
@@ -521,6 +520,7 @@ async function settleCodeModeResult(params: {
521520
settlementMode: result.settlementMode,
522521
signal: params.signal,
523522
onUpdate: params.onUpdate,
523+
bridgeDispatch: params.bridgeDispatch,
524524
});
525525
}
526526
// Defensive cleanup covers aborts or terminal failures; successful runs have
@@ -531,7 +531,7 @@ async function settleCodeModeResult(params: {
531531
...(result.status === "completed" ? { value: result.value } : {}),
532532
maxOutputBytes: params.config.maxOutputBytes,
533533
});
534-
return {
534+
const finalized = {
535535
...result,
536536
...(result.status === "completed" ? { value: bounded.value } : {}),
537537
...(result.status === "failed"
@@ -544,6 +544,10 @@ async function settleCodeModeResult(params: {
544544
replaySafe: params.replaySafe,
545545
telemetry: telemetry(params.runtime),
546546
};
547+
if (finalized.status === "failed" && isCodeModeBridgeRepairEligible(params.bridgeDispatch)) {
548+
registerRepairableCodeModeFailure(finalized);
549+
}
550+
return finalized;
547551
}
548552

549553
export async function runWait(params: {
@@ -596,7 +600,7 @@ export async function runWait(params: {
596600
error: "code mode execution aborted",
597601
code: "aborted" as const,
598602
failurePhase: "bridge" as const,
599-
bridgeDispatchStarted: true,
603+
bridgeDispatchStarted: state.bridgeDispatch.started,
600604
output: takeUndeliveredCodeModeRunOutput(state),
601605
replaySafe: state.replaySafe,
602606
telemetry: telemetry(state.runtime),
@@ -657,7 +661,7 @@ export async function runWait(params: {
657661
runtime: state.runtime,
658662
catalogProjection: state.catalogProjection,
659663
namespaceRuntime: state.namespaceRuntime,
660-
bridgeDispatch: { started: true },
664+
bridgeDispatch: state.bridgeDispatch,
661665
deliveredOutputCount: outputTruncated ? 0 : state.deliveredOutputCount,
662666
pending,
663667
activeRunId: state.runId,
@@ -676,7 +680,7 @@ export async function runWait(params: {
676680
error: codeModeFailureMessage(error),
677681
code: codeModeFailureCode(error),
678682
failurePhase: "bridge" as const,
679-
bridgeDispatchStarted: true,
683+
bridgeDispatchStarted: state.bridgeDispatch.started,
680684
output: takeUndeliveredCodeModeRunOutput(state),
681685
replaySafe: state.replaySafe,
682686
telemetry: telemetry(state.runtime),

‎src/agents/code-mode-headless.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import {
3030
} from "./code-mode-runtime.js";
3131
import {
3232
cancelPendingBridgeStates,
33+
createCodeModeBridgeDispatchState,
3334
createPendingBridgeStates,
3435
pendingBridgeStatesForSettlement,
3536
settledBridgeRequestsInCompletionOrder,
@@ -217,7 +218,10 @@ export async function runCodeModeScriptHeadless(params: {
217218
// Headless runs publish no resumable snapshot/handle, so collector globals stay unavailable.
218219
const swarmEnabled = false;
219220
const codeModeRunId = `cm_headless_${randomUUID()}`;
220-
const runtime = new ToolSearchRuntime(params.ctx, toToolSearchConfig(config));
221+
const runtime = new ToolSearchRuntime(params.ctx, toToolSearchConfig(config), {
222+
validateInput: true,
223+
});
224+
const bridgeDispatch = createCodeModeBridgeDispatchState();
221225
const namespaceCatalog = runtime.namespaceEntries();
222226
const namespaceRuntime = createCodeModeNamespaceRuntime(namespaceCatalog);
223227
const preparedSource = await awaitCodeModeDeadline({
@@ -310,6 +314,7 @@ export async function runCodeModeScriptHeadless(params: {
310314
deadlineMs: deadline,
311315
ctx: params.ctx,
312316
signal: abortScope.signal,
317+
bridgeDispatch,
313318
}),
314319
);
315320
// Preserve the waiting frontier before the lazy deadline callback;
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
const repairableFailureDetails = new WeakSet<object>();
2+
3+
/** Attach host-only repair authority to one finalized Code Mode failure payload. */
4+
export function registerRepairableCodeModeFailure(details: object): void {
5+
repairableFailureDetails.add(details);
6+
}
7+
8+
/** Consume repair authority from the exact host-created failure payload. */
9+
export function consumeRepairableCodeModeFailure(details: unknown): boolean {
10+
return (
11+
typeof details === "object" && details !== null && repairableFailureDetails.delete(details)
12+
);
13+
}

0 commit comments

Comments
 (0)