@@ -39,6 +39,8 @@ type Input = { |
39 | 39 | /** True when the client is attached to a shared server rather than an exclusive in-process one. */ |
40 | 40 | attached: boolean |
41 | 41 | compatibility?: "v1" |
| 42 | + /** How long running background shells keep the run open after the model's last reply. */ |
| 43 | + backgroundShellWait?: number |
42 | 44 | renderTool: (part: SessionMessageAssistantTool) => Promise<void> |
43 | 45 | renderToolError: (part: SessionMessageAssistantTool) => Promise<void> |
44 | 46 | } |
@@ -70,6 +72,10 @@ const GLOBAL_FORM_SESSION_ID = "global" |
70 | 72 | const QUESTION_CANCELLED_FEEDBACK = |
71 | 73 | "This non-interactive run cannot ask the user questions, so the question was cancelled. Continue without an answer; make reasonable assumptions and state them." |
72 | 74 |
|
| 75 | +// A finishing test or build wakes the model well within this. A server left running on purpose never |
| 76 | +// finishes, so after this long the run stops it and exits. Subagents and images always finish. |
| 77 | +const BACKGROUND_SHELL_WAIT_MS = 10 * 60 * 1000 |
| 78 | + |
73 | 79 | const PERMISSION_REJECTED_FEEDBACK = |
74 | 80 | "This non-interactive run cannot ask the user for permission, so the request was rejected. Continue without this action." |
75 | 81 |
|
@@ -97,6 +103,8 @@ export async function runNonInteractivePrompt(input: Input) { |
97 | 103 | let v1InvalidOutput = false |
98 | 104 | let prePromotionError: { message: string; [key: string]: unknown } | undefined |
99 | 105 | let finalizing = false |
| 106 | + const shellWaitMs = input.backgroundShellWait ?? BACKGROUND_SHELL_WAIT_MS |
| 107 | + let shellWait: { timer: ReturnType<typeof setTimeout>; expired: Promise<"expired"> } | undefined |
100 | 108 | let admission: AbortController | undefined |
101 | 109 | let pendingStep: { timestamp: number; part: Record<string, unknown>; label: string } | undefined |
102 | 110 |
|
@@ -158,6 +166,40 @@ export async function runNonInteractivePrompt(input: Input) { |
158 | 166 | return result |
159 | 167 | } |
160 | 168 |
|
| 169 | + // Only this session's own jobs hold the run open. A subagent reports back through its job here, so |
| 170 | + // work it leaves behind, such as a dev server it tested against, never keeps the run alive. |
| 171 | + const pendingBackground = async (): Promise<"none" | "work" | "shells"> => { |
| 172 | + if (input.compatibility === "v1" || interrupted || permissionRejected || formCancelled || emittedError) |
| 173 | + return "none" |
| 174 | + const jobs = await input.client.experimental.job.list({ sessionID: input.sessionID }).catch(() => []) |
| 175 | + if (jobs.length > 0) |
| 176 | + return jobs.every((job) => job.kind === "shell" && job.status === "running") ? "shells" : "work" |
| 177 | + // A finished job wakes this session before its row is removed, so a wake that raced the |
| 178 | + // list above shows up as an active session or a queued inbox item. |
| 179 | + const [active, inbox] = await Promise.all([ |
| 180 | + input.client.session.active().catch(() => ({})), |
| 181 | + input.client.session.inbox.list({ sessionID: input.sessionID }).catch(() => []), |
| 182 | + ]) |
| 183 | + return input.sessionID in active || inbox.length > 0 ? "work" : "none" |
| 184 | + } |
| 185 | + |
| 186 | + const stopShells = async () => { |
| 187 | + const shells = (await input.client.experimental.job.list({ sessionID: input.sessionID }).catch(() => [])).flatMap( |
| 188 | + (job) => (job.kind === "shell" && job.status === "running" ? [job.shellID] : []), |
| 189 | + ) |
| 190 | + await Promise.all( |
| 191 | + shells.map((id) => |
| 192 | + input.client.shell.remove({ id, location: { directory: input.location.directory } }).catch(() => {}), |
| 193 | + ), |
| 194 | + ) |
| 195 | + if (shells.length > 0 && input.format !== "json") |
| 196 | + UI.println( |
| 197 | + UI.Style.TEXT_WARNING_BOLD + "!", |
| 198 | + UI.Style.TEXT_NORMAL + |
| 199 | + `stopped ${shells.length} background command${shells.length === 1 ? "" : "s"} still running ${Math.round(shellWaitMs / 60_000)} minutes after the last reply`, |
| 200 | + ) |
| 201 | + } |
| 202 | + |
161 | 203 | const replyPermission = async (request: { |
162 | 204 | id: string |
163 | 205 | sessionID: string |
@@ -209,14 +251,32 @@ export async function runNonInteractivePrompt(input: Input) { |
209 | 251 | if (input.compatibility !== "v1") process.exitCode = 1 |
210 | 252 | } |
211 | 253 |
|
212 | | - const consume = async () => { |
| 254 | + const consume = () => consumeEvents().finally(() => clearTimeout(shellWait?.timer)) |
| 255 | + |
| 256 | + const consumeEvents = async () => { |
| 257 | + const aborted = new Promise<{ done: true; value: undefined }>((resolve) => { |
| 258 | + if (controller.signal.aborted) resolve({ done: true, value: undefined }) |
| 259 | + else controller.signal.addEventListener("abort", () => resolve({ done: true, value: undefined }), { once: true }) |
| 260 | + }) |
| 261 | + const never = new Promise<never>(() => {}) |
| 262 | + // Kept across loop turns so an event read while the shell wait expires is not dropped. |
| 263 | + let pending: ReturnType<typeof stream.next> | undefined |
213 | 264 | while (!controller.signal.aborted) { |
214 | | - const next = await stream.next().catch((error) => { |
215 | | - if (!emittedError) throw error |
| 265 | + pending ??= stream.next() |
| 266 | + const next = await Promise.race([pending, aborted, shellWait?.expired ?? never]).catch((error) => { |
| 267 | + if (!emittedError && !interrupted) throw error |
216 | 268 | return { done: true as const, value: undefined } |
217 | 269 | }) |
| 270 | + if (next === "expired") { |
| 271 | + shellWait = undefined |
| 272 | + const background = await pendingBackground() |
| 273 | + if (background === "work") continue |
| 274 | + if (background === "shells") await stopShells() |
| 275 | + return |
| 276 | + } |
| 277 | + pending = undefined |
218 | 278 | if (next.done) { |
219 | | - if (emittedError) return |
| 279 | + if (emittedError || interrupted) return |
220 | 280 | throw new Error("Event stream disconnected during prompt execution") |
221 | 281 | } |
222 | 282 | const event = next.value |
@@ -546,7 +606,18 @@ export async function runNonInteractivePrompt(input: Input) { |
546 | 606 | } |
547 | 607 | return |
548 | 608 | } |
549 | | - if (event.type === "session.execution.succeeded") return |
| 609 | + if (event.type === "session.execution.succeeded") { |
| 610 | + const background = await pendingBackground() |
| 611 | + if (background === "none") return |
| 612 | + // Each reply restarts the wait; subagents and images hold the run until they report. |
| 613 | + clearTimeout(shellWait?.timer) |
| 614 | + shellWait = undefined |
| 615 | + if (background === "shells") { |
| 616 | + const { promise, resolve } = Promise.withResolvers<"expired">() |
| 617 | + shellWait = { timer: setTimeout(() => resolve("expired"), shellWaitMs), expired: promise } |
| 618 | + } |
| 619 | + continue |
| 620 | + } |
550 | 621 | } |
551 | 622 | } |
552 | 623 |
|
@@ -711,7 +782,28 @@ export async function runNonInteractivePrompt(input: Input) { |
711 | 782 | interrupted = true |
712 | 783 | process.exitCode = 130 |
713 | 784 | admission?.abort() |
714 | | - void input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {}) |
| 785 | + if (input.compatibility !== "v1") { |
| 786 | + void input.client.experimental.job |
| 787 | + .list({ sessionID: input.sessionID, descendants: true }) |
| 788 | + .then((jobs) => |
| 789 | + Promise.all( |
| 790 | + jobs.map((job) => |
| 791 | + input.client.session |
| 792 | + .interrupt({ sessionID: job.kind === "subagent" ? job.childSessionID : job.sessionID }) |
| 793 | + .catch(() => {}), |
| 794 | + ), |
| 795 | + ), |
| 796 | + ) |
| 797 | + .catch(() => {}) |
| 798 | + } |
| 799 | + void input.client.session |
| 800 | + .interrupt({ sessionID: input.sessionID }) |
| 801 | + .then((result) => { |
| 802 | + if (!result.interrupted) controller.abort() |
| 803 | + }) |
| 804 | + .catch(() => { |
| 805 | + controller.abort() |
| 806 | + }) |
715 | 807 | } |
716 | 808 | process.on("SIGINT", interrupt) |
717 | 809 |
|
@@ -790,7 +882,15 @@ export async function runNonInteractivePrompt(input: Input) { |
790 | 882 | return |
791 | 883 | } |
792 | 884 |
|
793 | | - const waiting = input.client.experimental.session.wait({ sessionID: input.sessionID }) |
| 885 | + const waitUntilIdle = async () => { |
| 886 | + await input.client.experimental.session.wait({ sessionID: input.sessionID }) |
| 887 | + if ((await pendingBackground()) === "none") return |
| 888 | + await completed |
| 889 | + if (!interrupted && !permissionRejected && !formCancelled && !emittedError) { |
| 890 | + await input.client.experimental.session.wait({ sessionID: input.sessionID }) |
| 891 | + } |
| 892 | + } |
| 893 | + const waiting = waitUntilIdle() |
794 | 894 | await Promise.race([waiting, completed.then(() => waiting)]) |
795 | 895 | finalizing = true |
796 | 896 | const projected = await reconcile() |
|