Skip to content

Commit 253f4a3

Browse files
authored
refactor(agents): trim exec runtime exports (#106358)
1 parent 462e1e9 commit 253f4a3

3 files changed

Lines changed: 80 additions & 137 deletions

File tree

‎scripts/deadcode-exports.baseline.mjs‎

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -893,16 +893,6 @@ export const KNIP_UNUSED_EXPORT_BASELINE = [
893893
"src/agents/bash-tools.exec-approval-followup.ts: buildExecApprovalFollowupPrompt",
894894
"src/agents/bash-tools.exec-approval-request.ts: registerExecApprovalRequest",
895895
"src/agents/bash-tools.exec-approval-request.ts: registerExecApprovalRequestForHost",
896-
"src/agents/bash-tools.exec-runtime.ts: buildExecExitOutcome",
897-
"src/agents/bash-tools.exec-runtime.ts: detectCursorKeyMode",
898-
"src/agents/bash-tools.exec-runtime.ts: ExecProcessFailureKind",
899-
"src/agents/bash-tools.exec-runtime.ts: findPathKey",
900-
"src/agents/bash-tools.exec-runtime.ts: formatExecFailureReason",
901-
"src/agents/bash-tools.exec-runtime.ts: normalizeExecAsk",
902-
"src/agents/bash-tools.exec-runtime.ts: normalizeExecHost",
903-
"src/agents/bash-tools.exec-runtime.ts: normalizeExecSecurity",
904-
"src/agents/bash-tools.exec-runtime.ts: normalizeExecTarget",
905-
"src/agents/bash-tools.exec-runtime.ts: renderExecUpdateText",
906896
"src/agents/bash-tools.exec.ts: testing",
907897
"src/agents/bootstrap-cache.ts: clearAllBootstrapSnapshots",
908898
"src/agents/bootstrap-files.ts: resetBootstrapWarningCacheForTest",

‎src/agents/bash-tools.exec-runtime.test.ts‎

Lines changed: 75 additions & 114 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,6 @@ vi.mock("../process/supervisor/index.js", () => ({
3434
let markBackgrounded: typeof import("./bash-process-registry.js").markBackgrounded;
3535
let getActiveBackgroundExecSessionCount: typeof import("./bash-process-registry.js").getActiveBackgroundExecSessionCount;
3636
let resetProcessRegistryForTests: typeof import("./bash-process-registry.js").resetProcessRegistryForTests;
37-
let buildExecExitOutcome: typeof import("./bash-tools.exec-runtime.js").buildExecExitOutcome;
38-
let detectCursorKeyMode: typeof import("./bash-tools.exec-runtime.js").detectCursorKeyMode;
39-
let formatExecFailureReason: typeof import("./bash-tools.exec-runtime.js").formatExecFailureReason;
40-
let renderExecUpdateText: typeof import("./bash-tools.exec-runtime.js").renderExecUpdateText;
4137
let resolveExecTarget: typeof import("./bash-tools.exec-runtime.js").resolveExecTarget;
4238
let runExecProcess: typeof import("./bash-tools.exec-runtime.js").runExecProcess;
4339
let prepareGatewaySuspend: typeof import("../infra/gateway-suspend-coordinator.js").prepareGatewaySuspend;
@@ -47,14 +43,7 @@ let resumeGatewaySuspend: typeof import("../infra/gateway-suspend-coordinator.js
4743
beforeAll(async () => {
4844
({ getActiveBackgroundExecSessionCount, markBackgrounded, resetProcessRegistryForTests } =
4945
await import("./bash-process-registry.js"));
50-
({
51-
buildExecExitOutcome,
52-
detectCursorKeyMode,
53-
formatExecFailureReason,
54-
renderExecUpdateText,
55-
resolveExecTarget,
56-
runExecProcess,
57-
} = await import("./bash-tools.exec-runtime.js"));
46+
({ resolveExecTarget, runExecProcess } = await import("./bash-tools.exec-runtime.js"));
5847
({ prepareGatewaySuspend, resetGatewaySuspendCoordinatorForTest, resumeGatewaySuspend } =
5948
await import("../infra/gateway-suspend-coordinator.js"));
6049
});
@@ -82,6 +71,40 @@ function createDeferred<T>() {
8271
return { promise, reject, resolve };
8372
}
8473

74+
async function runExecWithExit(params: {
75+
exit: RunExit;
76+
stdout?: string;
77+
timeoutSec?: number | null;
78+
usePty?: boolean;
79+
}) {
80+
supervisorMock.spawn.mockImplementationOnce(
81+
async (input: { onStdout?: (chunk: string) => void }) => {
82+
if (params.stdout) {
83+
input.onStdout?.(params.stdout);
84+
}
85+
return {
86+
runId: "run-exit",
87+
startedAtMs: Date.now(),
88+
pid: 123,
89+
wait: async () => params.exit,
90+
cancel: vi.fn(),
91+
};
92+
},
93+
);
94+
const run = await runExecProcess({
95+
command: "test-command",
96+
workdir: "/tmp",
97+
env: {},
98+
usePty: params.usePty ?? false,
99+
warnings: [],
100+
maxOutput: 1000,
101+
pendingMaxOutput: 1000,
102+
notifyOnExit: false,
103+
timeoutSec: params.timeoutSec ?? null,
104+
});
105+
return { run, outcome: await run.promise };
106+
}
107+
85108
function prepareSuspension(requestId: string) {
86109
// This test owns only the background-exec registry. Other process-global
87110
// activity counters may legitimately stay busy in the non-isolated suite.
@@ -140,31 +163,29 @@ function requireHeartbeatCall(): Record<string, unknown> {
140163
return call[0] as Record<string, unknown>;
141164
}
142165

143-
describe("detectCursorKeyMode", () => {
144-
it("returns null when no toggle found", () => {
145-
expect(detectCursorKeyMode("hello world")).toBe(null);
146-
expect(detectCursorKeyMode("")).toBe(null);
147-
});
148-
149-
it("detects smkx (application mode)", () => {
150-
expect(detectCursorKeyMode("\x1b[?1h")).toBe("application");
151-
expect(detectCursorKeyMode("\x1b[?1h\x1b=")).toBe("application");
152-
expect(detectCursorKeyMode("before \x1b[?1h after")).toBe("application");
153-
});
154-
155-
it("detects rmkx (normal mode)", () => {
156-
expect(detectCursorKeyMode("\x1b[?1l")).toBe("normal");
157-
expect(detectCursorKeyMode("\x1b[?1l\x1b>")).toBe("normal");
158-
expect(detectCursorKeyMode("before \x1b[?1l after")).toBe("normal");
159-
});
166+
describe("runExecProcess cursor tracking", () => {
167+
it.each([
168+
{ raw: "hello world", expected: "unknown" },
169+
{ raw: "\x1b[?1h", expected: "application" },
170+
{ raw: "\x1b[?1h\x1b[?1l", expected: "normal" },
171+
{ raw: "\x1b[?1l\x1b[?1h", expected: "application" },
172+
])("tracks the last cursor-mode toggle as $expected", async ({ raw, expected }) => {
173+
const { run } = await runExecWithExit({
174+
stdout: raw,
175+
usePty: true,
176+
exit: {
177+
reason: "exit",
178+
exitCode: 0,
179+
exitSignal: null,
180+
durationMs: 1,
181+
stdout: "",
182+
stderr: "",
183+
timedOut: false,
184+
noOutputTimedOut: false,
185+
},
186+
});
160187

161-
it("last toggle wins when both present", () => {
162-
// smkx first, then rmkx - should be normal
163-
expect(detectCursorKeyMode("\x1b[?1h\x1b[?1l")).toBe("normal");
164-
// rmkx first, then smkx - should be application
165-
expect(detectCursorKeyMode("\x1b[?1l\x1b[?1h")).toBe("application");
166-
// Multiple toggles - last one wins
167-
expect(detectCursorKeyMode("\x1b[?1h\x1b[?1l\x1b[?1h")).toBe("application");
188+
expect(run.session.cursorKeyMode).toBe(expected);
168189
});
169190
});
170191

@@ -419,28 +440,6 @@ describe("resolveExecTarget", () => {
419440
});
420441
});
421442

422-
describe("renderExecUpdateText", () => {
423-
it("uses a non-empty placeholder when an exec update has no output", () => {
424-
expect(renderExecUpdateText({ tailText: "", warnings: [] })).toBe("(no output)");
425-
});
426-
427-
it("preserves non-empty exec output", () => {
428-
expect(renderExecUpdateText({ tailText: "hello", warnings: [] })).toBe("hello");
429-
});
430-
431-
it("keeps warnings while still avoiding empty output text", () => {
432-
expect(renderExecUpdateText({ tailText: "", warnings: ["Warning: retrying"] })).toBe(
433-
"Warning: retrying\n\n(no output)",
434-
);
435-
});
436-
437-
it("combines warnings with non-empty output", () => {
438-
expect(renderExecUpdateText({ tailText: "hello", warnings: ["Warning: retrying"] })).toBe(
439-
"Warning: retrying\n\nhello",
440-
);
441-
});
442-
});
443-
444443
describe("exec notifyOnExit suppression", () => {
445444
async function runBackgroundedExit(params: {
446445
reason: "manual-cancel" | "overall-timeout";
@@ -684,43 +683,10 @@ describe("sandbox exec finalization suspension", () => {
684683
);
685684
});
686685

687-
describe("formatExecFailureReason", () => {
688-
it("formats timeout guidance with the configured timeout", () => {
689-
expect(
690-
formatExecFailureReason({
691-
failureKind: "overall-timeout",
692-
exitSignal: "SIGKILL",
693-
timeoutSec: 45,
694-
}),
695-
).toContain("45 seconds");
696-
});
697-
698-
it("points long-running work to registered exec backgrounding", () => {
699-
const reason = formatExecFailureReason({
700-
failureKind: "overall-timeout",
701-
exitSignal: "SIGKILL",
702-
timeoutSec: 45,
703-
});
704-
705-
expect(reason).toContain("background=true");
706-
expect(reason).toContain("yieldMs");
707-
expect(reason).toContain("Do not rely on shell backgrounding");
708-
});
709-
710-
it("formats shell failures without timeout-specific guidance", () => {
711-
expect(
712-
formatExecFailureReason({
713-
failureKind: "shell-command-not-found",
714-
exitSignal: null,
715-
timeoutSec: 45,
716-
}),
717-
).toBe("Command not found");
718-
});
719-
});
720-
721-
describe("buildExecExitOutcome", () => {
722-
it("keeps non-zero normal exits in the completed path", () => {
723-
const outcome = buildExecExitOutcome({
686+
describe("runExecProcess exit outcomes", () => {
687+
it("keeps non-zero normal exits in the completed path", async () => {
688+
const { outcome } = await runExecWithExit({
689+
stdout: "done",
724690
exit: {
725691
reason: "exit",
726692
exitCode: 1,
@@ -731,8 +697,6 @@ describe("buildExecExitOutcome", () => {
731697
timedOut: false,
732698
noOutputTimedOut: false,
733699
},
734-
aggregated: "done",
735-
durationMs: 123,
736700
timeoutSec: 30,
737701
});
738702
expect(outcome.status).toBe("completed");
@@ -743,8 +707,8 @@ describe("buildExecExitOutcome", () => {
743707
expect(outcome.aggregated).toBe("done\n\n(Command exited with code 1)");
744708
});
745709

746-
it("classifies timed out exits as failures with a reason", () => {
747-
const outcome = buildExecExitOutcome({
710+
it("classifies timed out exits with registered-background guidance", async () => {
711+
const { outcome } = await runExecWithExit({
748712
exit: {
749713
reason: "overall-timeout",
750714
exitCode: null,
@@ -755,8 +719,6 @@ describe("buildExecExitOutcome", () => {
755719
timedOut: true,
756720
noOutputTimedOut: false,
757721
},
758-
aggregated: "",
759-
durationMs: 123,
760722
timeoutSec: 30,
761723
});
762724
expect(outcome.status).toBe("failed");
@@ -766,32 +728,31 @@ describe("buildExecExitOutcome", () => {
766728
expect(outcome.failureKind).toBe("overall-timeout");
767729
expect(outcome.timedOut).toBe(true);
768730
expect(outcome.reason).toContain("30 seconds");
731+
expect(outcome.reason).toContain("background=true");
732+
expect(outcome.reason).toContain("yieldMs");
733+
expect(outcome.reason).toContain("Do not rely on shell backgrounding");
769734
});
770735

771-
it("keeps timed out shell-backgrounded commands on the failed path", () => {
772-
const outcome = buildExecExitOutcome({
736+
it("classifies missing shell commands without timeout guidance", async () => {
737+
const { outcome } = await runExecWithExit({
773738
exit: {
774-
reason: "overall-timeout",
775-
exitCode: null,
776-
exitSignal: "SIGKILL",
739+
reason: "exit",
740+
exitCode: 127,
741+
exitSignal: null,
777742
durationMs: 123,
778743
stdout: "",
779744
stderr: "",
780-
timedOut: true,
745+
timedOut: false,
781746
noOutputTimedOut: false,
782747
},
783-
aggregated: "started worker",
784-
durationMs: 123,
785748
timeoutSec: 30,
786749
});
787750

788751
if (outcome.status !== "failed") {
789-
throw new Error(`Expected timeout to fail, got ${outcome.status}`);
752+
throw new Error(`Expected shell failure, got ${outcome.status}`);
790753
}
791-
expect(outcome.failureKind).toBe("overall-timeout");
792-
expect(outcome.timedOut).toBe(true);
793-
expect(outcome.reason).toContain("background=true");
794-
expect(outcome.reason).toContain("Do not rely on shell backgrounding");
754+
expect(outcome.failureKind).toBe("shell-command-not-found");
755+
expect(outcome.reason).toBe("Command not found");
795756
});
796757
});
797758

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

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,7 @@ import type { ProcessSession } from "./bash-process-registry.js";
2828
import type { ExecToolDetails } from "./bash-tools.exec-types.js";
2929
import type { BashSandboxConfig } from "./bash-tools.shared.js";
3030
import type { AgentToolResult } from "./runtime/index.js";
31-
export { applyPathPrepend, findPathKey, normalizePathPrepend } from "../infra/path-prepend.js";
32-
export {
33-
normalizeExecAsk,
34-
normalizeExecHost,
35-
normalizeExecSecurity,
36-
normalizeExecTarget,
37-
} from "../infra/exec-approvals.js";
31+
export { applyPathPrepend, normalizePathPrepend } from "../infra/path-prepend.js";
3832
import { logWarn } from "../logger.js";
3933
import type { ManagedRun } from "../process/supervisor/index.js";
4034
import { getProcessSupervisor } from "../process/supervisor/index.js";
@@ -80,7 +74,7 @@ function resolveExecTimeoutMs(timeoutSec: number | null | undefined): number | u
8074
* Returns "application" if smkx is the last toggle, "normal" if rmkx is last,
8175
* or null if no toggle is found.
8276
*/
83-
export function detectCursorKeyMode(raw: string): "application" | "normal" | null {
77+
function detectCursorKeyMode(raw: string): "application" | "normal" | null {
8478
const lastSmkx = raw.lastIndexOf(SMKX);
8579
const lastRmkx = raw.lastIndexOf(RMKX);
8680
if (lastSmkx === -1 && lastRmkx === -1) {
@@ -118,7 +112,7 @@ const DEFAULT_APPROVAL_RUNNING_NOTICE_MS = 10_000;
118112
const APPROVAL_SLUG_LENGTH = 8;
119113

120114
/** Failure categories used to explain exec process exits. */
121-
export type ExecProcessFailureKind =
115+
type ExecProcessFailureKind =
122116
| "shell-command-not-found"
123117
| "shell-not-executable"
124118
| "overall-timeout"
@@ -420,8 +414,6 @@ export function resolveApprovalRunningNoticeMs(value?: number) {
420414
return Math.floor(value);
421415
}
422416

423-
export { renderExecUpdateText } from "./bash-tools.exec-output.js";
424-
425417
function joinExecFailureOutput(aggregated: string, reason: string) {
426418
return aggregated ? `${aggregated}\n\n${reason}` : reason;
427419
}
@@ -448,7 +440,7 @@ function classifyExecFailureKind(params: {
448440
}
449441

450442
/** Formats a user-facing reason for a failed exec process exit. */
451-
export function formatExecFailureReason(params: {
443+
function formatExecFailureReason(params: {
452444
failureKind: ExecExitFailureKind;
453445
exitSignal: NodeJS.Signals | number | null;
454446
timeoutSec: number | null | undefined;
@@ -473,7 +465,7 @@ export function formatExecFailureReason(params: {
473465
}
474466

475467
/** Converts a supervisor exit record into a normalized exec process outcome. */
476-
export function buildExecExitOutcome(params: {
468+
function buildExecExitOutcome(params: {
477469
exit: RunExit;
478470
aggregated: string;
479471
durationMs: number;

0 commit comments

Comments
 (0)