From 592a5ce0eded552a5f98d350a5aa49e2bf25048e Mon Sep 17 00:00:00 2001 From: James Long Date: Thu, 5 Nov 2026 00:23:26 +0000 Subject: [PATCH] feat(core): run local shell commands in the process daemon --- packages/core/src/file-retention.ts | 3 + packages/core/src/shell.ts | 556 ++++++++++++++++--- packages/core/src/tool/plugin/shell.ts | 5 + packages/core/test/fixture/persistent-pty.ts | 8 + packages/core/test/shell-cleanup.test.ts | 5 +- packages/core/test/shell-retention.test.ts | 3 + packages/core/test/tool-shell.test.ts | 27 +- 7 files changed, 538 insertions(+), 69 deletions(-) create mode 100644 packages/core/test/fixture/persistent-pty.ts diff --git a/packages/core/src/file-retention.ts b/packages/core/src/file-retention.ts index a325f2165fc..ee9f486e219 100644 --- a/packages/core/src/file-retention.ts +++ b/packages/core/src/file-retention.ts @@ -7,6 +7,8 @@ export const cleanup = Effect.fn("FileRetention.cleanup")(function* ( fs: FSUtil.Interface, files: ReadonlyArray, retention: Duration.Input, + // Runs before an expired file is removed. + beforeRemove?: (file: string) => Effect.Effect, ) { const cutoff = Date.now() - Duration.toMillis(retention) yield* Effect.forEach( @@ -16,6 +18,7 @@ export const cleanup = Effect.fn("FileRetention.cleanup")(function* ( const info = yield* fs.stat(file).pipe(Effect.orElseSucceed(() => undefined)) const mtime = info && Option.getOrUndefined(info.mtime) if (!mtime || mtime.getTime() >= cutoff) return + if (beforeRemove) yield* beforeRemove(file) yield* fs.remove(file).pipe(Effect.ignore) }), { concurrency: 8, discard: true }, diff --git a/packages/core/src/shell.ts b/packages/core/src/shell.ts index 6b118188d68..d35445c16e4 100644 --- a/packages/core/src/shell.ts +++ b/packages/core/src/shell.ts @@ -1,7 +1,20 @@ export * as Shell from "./shell.js" import path from "path" -import { Context, Deferred, Duration, Effect, Fiber, Latch, Layer, Schema, Schedule, Stream } from "effect" +import { + Context, + Deferred, + Duration, + Effect, + Exit, + Fiber, + Latch, + Layer, + Option, + Schema, + Schedule, + Stream, +} from "effect" import { ChildProcess } from "effect/process" import { produce } from "immer" import { Shell } from "@opencode/schema/shell" @@ -14,6 +27,7 @@ import { Environment } from "./environment/index.js" import { FileRetention } from "./file-retention.js" import { Location } from "./location.js" import { Global } from "@opencode/util/global" +import { PersistentPty } from "./persistent-pty.js" import { ShellSelect } from "./shell/select.js" import type { ShellCreateBefore } from "@opencode/plugin/effect/shell" import { PluginHooks } from "./plugin/hooks.js" @@ -32,17 +46,55 @@ export class NotFoundError extends Schema.TaggedError()("Shell.No const EXITED_LIMIT = 25 export const RETENTION = Duration.days(7) export const DIRECTORY = "shell" +const STOP_GRACE = Duration.seconds(3) type Info = Shell.Info export type StopReason = "timeout" | "killed" + +/** The tool call that started a command, so a server that took over can settle it. */ +export const ToolCall = Schema.Struct({ + sessionID: Schema.String, + assistantMessageID: Schema.String, + callID: Schema.String, +}) +export type ToolCall = typeof ToolCall.Type + type CreateInput = Shell.CreateInput & { shell?: string + toolCall?: ToolCall +} + +// What the server needs to take a daemon-run command back after a restart, kept in the daemon's metadata. +const Stored = Schema.Struct({ + id: Shell.ID, + command: Schema.String, + shell: Schema.String, + location: Schema.Struct({ directory: Schema.String, workspaceID: Schema.optionalKey(Schema.String) }), + metadata: Shell.Metadata, + toolCall: Schema.optional(ToolCall), + timeoutDeadline: Schema.optional(Schema.Number), + stopReason: Schema.optional(Schema.Literals(["timeout", "killed"])), + backgroundedAtShutdown: Schema.optional(Schema.Boolean), +}) +type Stored = typeof Stored.Type +const decodeStored = Schema.decodeUnknownOption(Stored) + +// A command run by the process daemon, which writes and counts its output file. +type Daemon = { + id: number + stored: Stored + // From the exit: newlines in the file, and why the daemon stopped writing it early. + outputLines?: number + outputError?: string + wait?: Fiber.Fiber + kill?: Fiber.Fiber } type Active = { // Immutable snapshot; lifecycle updates replace it via immer `produce`. info: Info file: string + // Spawned commands only: bytes and newlines written so far. The daemon's file is the only count for its commands. size: number newlines: number // Resolves with the terminal Info once the command exits, times out, or is killed. A wait @@ -53,6 +105,7 @@ type Active = { stop?: (reason: StopReason) => Effect.Effect // Whether the process can outlive this server (run by the process daemon). Spawned commands cannot. detachable: boolean + daemon?: Daemon } type Ended = { @@ -65,10 +118,13 @@ type Ended = { /** * Location-owned non-interactive shell command process service. * - * Each `create` spawns one shell command, captures combined stdout/stderr to a + * Each `create` starts one shell command, captures combined stdout/stderr to a * file, and returns an ID. Clients poll `get` for status and `output` for * file-backed output by cursor. No session, message, or permission state lives * here; callers (e.g. `ShellTool`) own that association and store the shell ID. + * + * Local commands run in the process daemon when it is available, so they survive a planned server + * restart; this service takes them back when it starts. Elsewhere they are spawned by the server. */ export interface Interface { readonly create: ( @@ -92,6 +148,11 @@ export interface Interface { readonly stop: (id: Shell.ID, reason: StopReason) => Effect.Effect // Whether the command's process can outlive this server, so a planned shutdown leaves it running. readonly detachable: (id: Shell.ID) => boolean + // Records in the daemon that a planned shutdown moved this running command to the background, clearing + // its timeout, so the next server neither times it out nor waits on it. Best effort; spawned commands ignore it. + readonly backgroundAtShutdown: (id: Shell.ID) => Effect.Effect + // The command a tool call started, while it is still known here (including one taken back after a restart). + readonly byToolCall: (call: ToolCall) => Effect.Effect readonly output: (id: Shell.ID, input?: Shell.OutputInput) => Effect.Effect readonly remove: (id: Shell.ID) => Effect.Effect } @@ -101,6 +162,7 @@ export class Service extends Context.Service()("@opencode/Sh export const cleanup = Effect.fn("Shell.cleanup")(function* () { const fs = yield* FSUtil.Service const global = yield* Global.Service + const pty = yield* PersistentPty.Service const directory = path.join(global.data, DIRECTORY) const projects = yield* fs.readDirectoryEntries(directory).pipe( Effect.map((entries) => entries.filter((entry) => entry.type === "Directory")), @@ -121,7 +183,19 @@ export const cleanup = Effect.fn("Shell.cleanup")(function* () { ), { concurrency: 8 }, ) - yield* FileRetention.cleanup(fs, files.flat(), RETENTION) + // Never starts the daemon. A command it still runs keeps its file; a finished one is forgotten before deletion. + const processes = new Map( + (yield* pty.listPipes().pipe(Effect.orElseSucceed(() => []))).map((process) => [process.outputPath, process]), + ) + yield* FileRetention.cleanup( + fs, + files.flat().filter((file) => processes.get(file)?.lifecycle.status !== "running"), + RETENTION, + (file) => { + const process = processes.get(file) + return process ? pty.terminatePipe(process.id).pipe(Effect.ignore) : Effect.void + }, + ) }) const cleanupLayer = Layer.effectDiscard( @@ -131,7 +205,7 @@ const cleanupLayer = Layer.effectDiscard( const cleanupNode = makeGlobalNode({ name: "shell-output-cleanup", layer: cleanupLayer, - deps: [FSUtil.node, Global.node], + deps: [FSUtil.node, Global.node, PersistentPty.node], }) const layer = () => @@ -146,13 +220,17 @@ const layer = () => const hooks = yield* PluginHooks.Service const environments = yield* SessionEnvironment.Service const config = yield* Config.Service + const pty = yield* PersistentPty.Service const context = yield* Effect.context() const runFork = Effect.runForkWith(context) const commands = new Map() const exitOrder: Shell.ID[] = [] + // Remote workspaces and Windows keep spawning commands from the server. + const daemonEnabled = + location.workspaceID === undefined && process.platform !== "win32" && PersistentPty.available const outputDir = path.join(global.data, DIRECTORY, location.project.id) - const { mkdir, unlink } = yield* Effect.promise(() => import("fs/promises")) + const { mkdir, unlink, open } = yield* Effect.promise(() => import("fs/promises")) const { createWriteStream, createReadStream } = yield* Effect.promise(() => import("fs")) yield* Effect.promise(() => mkdir(outputDir, { recursive: true })) @@ -160,6 +238,9 @@ const layer = () => Effect.gen(function* () { for (const command of commands.values()) { if (command.timeoutFiber) yield* Fiber.interrupt(command.timeoutFiber) + // Daemon commands are only detached from: their processes keep running for the next owner. + if (command.daemon?.kill) yield* Fiber.interrupt(command.daemon.kill) + if (command.daemon?.wait) yield* Fiber.interrupt(command.daemon.wait) // Teardown interrupts pending commands; it is not a terminal command failure. It never stops or // removes a command itself: a spawned process dies with its handle's scope once `done` settles. yield* Deferred.interrupt(command.done) @@ -182,14 +263,60 @@ const layer = () => if (!command) return commands.delete(id) if (command.timeoutFiber) yield* Fiber.interrupt(command.timeoutFiber) - // Unblock any wait still pending when the command is removed before it terminated. - yield* Deferred.fail(command.done, new NotFoundError({ id })) - yield* Effect.promise(() => unlink(command.file).catch(() => {})) + if (command.daemon) { + if (command.daemon.kill) yield* Fiber.interrupt(command.daemon.kill) + // Forget the process before deleting its file; its pending `wait` then ends as terminated. + yield* pty.terminatePipe(command.daemon.id).pipe(Effect.ignore) + yield* Effect.promise(() => unlink(command.file).catch(() => {})) + yield* Deferred.fail(command.done, new NotFoundError({ id })) + } + if (!command.daemon) { + // Unblock any wait still pending when the command is removed before it terminated. + yield* Deferred.fail(command.done, new NotFoundError({ id })) + yield* Effect.promise(() => unlink(command.file).catch(() => {})) + } // Every shell reports exactly one exit; removing a running one ends it as killed. if (command.info.status === "running") yield* bus.publish(Shell.Event.Exited, { id, status: "killed" }) yield* bus.publish(Shell.Event.Deleted, { id }) }) + const evict = Effect.fnUntraced(function* () { + while (exitOrder.length > EXITED_LIMIT) { + const oldest = exitOrder[0] + if (!oldest) break + yield* removeCommand(oldest) + } + }) + + // Records how a command ended, once, unless it was removed meanwhile. + const finish = Effect.fnUntraced(function* (command: Active, outcome: Ended) { + const id = command.info.id + // A removed command already failed its waiters and published its exit and deletion. + if (commands.get(id) !== command) return + command.info = produce(command.info, (draft) => { + draft.status = outcome.status + if (outcome.exit !== undefined) draft.exit = outcome.exit + if (outcome.signal !== undefined) draft.signal = outcome.signal + draft.time.completed = outcome.completed + }) + // Resolve waiters before retention eviction, so an evicted command still reports its + // terminal Info rather than the removal NotFoundError. + yield* Deferred.succeed(command.done, command.info) + yield* bus.publish(Shell.Event.Exited, { + id, + ...(outcome.exit !== undefined ? { exit: outcome.exit } : {}), + status: outcome.status, + }) + exitOrder.push(id) + yield* evict() + // Keep exited history data-only. + const timeoutFiber = command.timeoutFiber + command.timeout = undefined + command.stop = undefined + command.timeoutFiber = undefined + if (timeoutFiber) yield* Fiber.interrupt(timeoutFiber) + }) + const remove = Effect.fn("Shell.remove")(function* (id: Shell.ID) { yield* require(id) yield* removeCommand(id) @@ -225,36 +352,123 @@ const layer = () => const detachable = (id: Shell.ID) => commands.get(id)?.detachable ?? false + const backgroundAtShutdown = Effect.fn("Shell.backgroundAtShutdown")(function* (id: Shell.ID) { + const command = commands.get(id) + const daemon = command?.daemon + if (!command || !daemon || command.info.status !== "running") return + if (command.timeoutFiber) yield* Fiber.interrupt(command.timeoutFiber) + command.timeoutFiber = undefined + yield* store(daemon, { backgroundedAtShutdown: true, timeoutDeadline: undefined }) + }) + + const byToolCall = Effect.fn("Shell.byToolCall")(function* (call: ToolCall) { + return Array.from(commands.values()).find((command) => { + const stored = command.daemon?.stored.toolCall + return ( + stored?.sessionID === call.sessionID && + stored.assistantMessageID === call.assistantMessageID && + stored.callID === call.callID + ) + })?.info + }) + + const readSpawned = (file: string, start: number, length: number) => + length <= 0 + ? Effect.succeed(Buffer.alloc(0)) + : Effect.promise( + () => + new Promise((resolve) => { + const buffer = Buffer.alloc(length) + const stream = createReadStream(file, { start, end: start + length - 1 }) + let offset = 0 + stream.on("data", (chunk: string | Buffer) => { + const bytes = Buffer.from(chunk) + bytes.copy(buffer, offset) + offset += bytes.length + }) + stream.on("end", () => resolve(buffer.subarray(0, offset))) + stream.on("error", () => resolve(Buffer.alloc(0))) + }), + ) + + // Reads a daemon command's file, which is the only record of its output. `size` comes from the same open + // handle; a missing file reads as empty. + const readFile = (file: string, start: (size: number) => number, limit: number) => + Effect.promise(async () => { + const handle = await open(file, "r").catch(() => undefined) + if (!handle) return { size: 0, start: 0, bytes: Buffer.alloc(0) } + try { + const size = (await handle.stat()).size + const from = Math.max(0, start(size)) + if (from >= size) return { size, start: from, bytes: Buffer.alloc(0) } + const buffer = Buffer.alloc(Math.min(limit, size - from)) + const read = await handle.read(buffer, 0, buffer.length, from) + return { size, start: from, bytes: buffer.subarray(0, read.bytesRead) } + } catch { + return { size: 0, start: 0, bytes: Buffer.alloc(0) } + } finally { + await handle.close() + } + }) + const output = Effect.fnUntraced(function* (id: Shell.ID, input?: Shell.OutputInput) { const command = yield* require(id) const cursor = input?.cursor ?? 0 const limit = input?.limit ?? 65536 + if (command.daemon) { + const page = yield* readFile(command.file, () => cursor, limit) + if (cursor >= page.size) return { output: "", cursor: page.size, size: page.size, truncated: false } + return { + output: page.bytes.toString("utf8"), + cursor: page.start + page.bytes.length, + size: page.size, + truncated: false, + } + } if (cursor >= command.size) return { output: "", cursor: command.size, size: command.size, truncated: false } const start = Math.max(0, cursor) - const length = Math.min(limit, command.size - start) - const buffer = Buffer.alloc(length) - const bytesRead = yield* Effect.promise( - () => - new Promise((resolve) => { - const stream = createReadStream(command.file, { start, end: start + length - 1 }) - let offset = 0 - stream.on("data", (chunk: string | Buffer) => { - const bytes = Buffer.from(chunk) - bytes.copy(buffer, offset) - offset += bytes.length - }) - stream.on("end", () => resolve(offset)) - stream.on("error", () => resolve(0)) - }), - ) + const bytes = yield* readSpawned(command.file, start, Math.min(limit, command.size - start)) return { - output: buffer.subarray(0, bytesRead).toString("utf8"), - cursor: start + bytesRead, + output: bytes.toString("utf8"), + cursor: start + bytes.length, size: command.size, truncated: false, } }) + // Only for a command whose exit report was lost; the daemon counts newlines otherwise. + const countNewlines = (file: string) => + Effect.promise( + () => + new Promise((resolve) => { + let count = 0 + const stream = createReadStream(file) + stream.on("data", (chunk: string | Buffer) => { + const bytes = Buffer.from(chunk) + for (let index = bytes.indexOf(10); index !== -1; index = bytes.indexOf(10, index + 1)) count++ + }) + stream.on("end", () => resolve(count)) + stream.on("error", () => resolve(count)) + }), + ) + + // The last `maxBytes` of a finished command's output, the file's size and its newline count. + const tail = Effect.fnUntraced(function* (command: Active, maxBytes: number) { + if (!command.daemon) { + const start = Math.max(0, command.size - maxBytes) + const bytes = yield* readSpawned(command.file, start, command.size - start) + return { text: bytes.toString("utf8"), size: command.size, newlines: command.newlines, error: undefined } + } + const page = yield* readFile(command.file, (size) => size - maxBytes, maxBytes) + return { + text: page.bytes.toString("utf8"), + size: page.size, + // The daemon's count, unless the command ended without its exit report (the daemon went away). + newlines: command.daemon.outputLines ?? (yield* countNewlines(command.file)), + error: command.daemon.outputError, + } + }) + const result = Effect.fn("Shell.result")(function* (started: Shell.Info) { const info = yield* wait(started.id).pipe( Effect.catchTag("Shell.NotFoundError", () => @@ -265,21 +479,225 @@ const layer = () => const limits = Config.latest(yield* config.entries(), "tool_output") const maxLines = limits?.max_lines ?? ToolOutput.MAX_LINES const maxBytes = limits?.max_bytes ?? ToolOutput.MAX_BYTES - const latest = yield* output(info.id, { cursor: Number.MAX_SAFE_INTEGER }) - const page = yield* output(info.id, { cursor: Math.max(0, latest.size - maxBytes), limit: maxBytes }) - const lines = page.output.split("\n") - if (page.output.endsWith("\n")) lines.pop() - const truncated = latest.size > maxBytes || lines.length > maxLines - const text = lines.length > maxLines ? lines.slice(-maxLines).join("\n") : page.output - const empty = latest.size === 0 - const total = empty ? 0 : (yield* require(info.id)).newlines + (page.output.endsWith("\n") ? 0 : 1) + const page = yield* tail(yield* require(info.id), maxBytes) + const lines = page.text.split("\n") + if (page.text.endsWith("\n")) lines.pop() + const truncated = page.size > maxBytes || lines.length > maxLines + const text = lines.length > maxLines ? lines.slice(-maxLines).join("\n") : page.text + const empty = page.size === 0 const shown = empty ? 0 : Math.min(lines.length, maxLines) + const total = empty ? 0 : Math.max(page.newlines + (page.text.endsWith("\n") ? 0 : 1), shown) const notice = truncated ? `\n\n${ShellResult.savedNotice({ shown, total }, info.file)}` : "" - return { output: `${text || "(no output)"}${notice}`, truncated, lines: { shown, total } } + const error = page.error ? `\n\n[output file ${info.file} stopped early: ${page.error}]` : "" + return { output: `${text || "(no output)"}${notice}${error}`, truncated, lines: { shown, total } } }).pipe(Effect.catchTag("Shell.NotFoundError", () => Effect.succeed(undefined))) return { info, capture } }) + // Replaces the command's daemon metadata, so a restart sees its latest timeout and stop reason. + // Cleared fields are left out of the JSON. + const store = (daemon: Daemon, patch: Partial) => { + daemon.stored = { ...daemon.stored, ...patch } + return pty + .setPipeMetadata(daemon.id, daemon.stored) + .pipe( + Effect.catch((error) => + Effect.logWarning("failed to update shell command metadata", { + id: daemon.stored.id, + error: error.message, + }), + ), + ) + } + + // Watches a command the daemon runs: its exit, timeout (in ms from now, none if undefined) and graceful + // stop. Used for new commands and for running ones taken back after a restart. + const attach = (command: Active, daemon: Daemon, timeout: number | undefined) => { + const stopping = (reason: StopReason) => + Effect.gen(function* () { + yield* store(daemon, { stopReason: reason, timeoutDeadline: undefined }) + yield* pty.signalPipe(daemon.id, "SIGTERM").pipe(Effect.ignore) + const ended = yield* Deferred.await(command.done).pipe(Effect.timeoutOption(STOP_GRACE), Effect.exit) + if (Exit.isSuccess(ended) && Option.isNone(ended.value)) + yield* pty.signalPipe(daemon.id, "SIGKILL").pipe(Effect.ignore) + }) + + // Detached, so interrupting the caller (a timer being retimed, removed or torn down) never cancels a + // recorded stop. Only removal and teardown interrupt it. + const stop = (reason: StopReason) => + Effect.sync(() => { + if (daemon.stored.stopReason !== undefined) return + daemon.stored = { ...daemon.stored, stopReason: reason } + daemon.kill = runFork(stopping(reason)) + }) + command.stop = stop + + const arm = (duration: number) => { + command.timeoutFiber = runFork(Effect.sleep(Duration.millis(duration)).pipe(Effect.andThen(stop("timeout")))) + } + + command.timeout = (duration) => + Effect.gen(function* () { + if (daemon.stored.stopReason !== undefined) return + if (command.timeoutFiber) yield* Fiber.interrupt(command.timeoutFiber) + command.timeoutFiber = undefined + yield* store(daemon, { timeoutDeadline: duration === 0 ? undefined : Date.now() + duration }) + if (duration !== 0) arm(duration) + }) + + daemon.wait = runFork( + pty.waitPipe(daemon.id).pipe( + Effect.map((exit): Ended => { + daemon.outputLines = exit.outputLines + daemon.outputError = exit.outputError + const reason = daemon.stored.stopReason + // A stopped command reports its reason, not the signal it was stopped with, as spawned ones do. + if (reason) return { status: reason, completed: exit.exitedAt } + return { + status: "exited", + ...(exit.exitCode !== undefined ? { exit: exit.exitCode } : {}), + ...(exit.signal !== undefined ? { signal: exit.signal } : {}), + completed: exit.exitedAt, + } + }), + // The daemon went away (and its processes with it), or forgot the process: it was killed. + Effect.catch((error) => + Effect.logWarning("lost a shell command's process", { id: command.info.id, error: error.message }).pipe( + Effect.as({ status: "killed", completed: Date.now() }), + ), + ), + Effect.flatMap((outcome) => finish(command, outcome)), + ), + ) + + // A stop interrupted by a restart lost its grace period: kill now. + if (daemon.stored.stopReason !== undefined) { + daemon.kill = runFork(pty.signalPipe(daemon.id, "SIGKILL").pipe(Effect.ignore)) + return + } + if (timeout === undefined) return + if (timeout > 0) return arm(timeout) + runFork(stop("timeout")) + } + + const daemonCommand = (info: Info, daemon: Daemon): Active => ({ + info, + file: info.file, + size: 0, + newlines: 0, + done: Deferred.makeUnsafe(), + detachable: true, + daemon, + }) + + // Runs the command in the daemon. Fails with `UnavailableError` only when the daemon could not be reached + // or started, so the request never ran and spawning it here instead is safe. + const createInDaemon = Effect.fnUntraced(function* ( + info: Info, + invocation: ShellCreateBefore, + args: string[], + toolCall: ToolCall | undefined, + ) { + const stored: Stored = { + id: info.id, + command: info.command, + shell: info.shell, + location: { + directory: location.directory, + ...(location.workspaceID !== undefined ? { workspaceID: location.workspaceID } : {}), + }, + metadata: info.metadata, + ...(toolCall ? { toolCall } : {}), + ...(invocation.timeout > 0 ? { timeoutDeadline: info.time.started + invocation.timeout } : {}), + } + const created = yield* pty.createPipe({ + program: invocation.shell, + args, + cwd: path.resolve(location.directory, invocation.cwd), + // The daemon replaces the environment, so variables removed by hooks stay removed, like the spawner. + env: Object.fromEntries( + Object.entries(invocation.env).filter((entry): entry is [string, string] => entry[1] !== undefined), + ), + groupID: location.project.id, + outputPath: info.file, + metadata: stored, + }) + const daemon: Daemon = { id: created.id, stored } + const command = daemonCommand( + produce(info, (draft) => { + if (created.pid !== undefined) draft.pid = created.pid + }), + daemon, + ) + commands.set(info.id, command) + // Timed from now: starting the daemon may have taken a while. + attach(command, daemon, invocation.timeout > 0 ? invocation.timeout : undefined) + yield* bus.publish(Shell.Event.Created, { info: command.info }) + return command.info + }) + + // Takes back this Location's daemon commands, left by a previous server or an evicted Location. + // Two Locations can share a project's output directory, so match the Location itself. + const recover = Effect.fnUntraced(function* () { + const processes = yield* pty + .listPipes() + .pipe( + Effect.catch((error) => + Effect.logWarning("failed to list shell commands to recover", { error: error.message }).pipe( + Effect.as([]), + ), + ), + ) + const finished: { id: Shell.ID; exitedAt: number }[] = [] + for (const process of processes) { + const stored = Option.getOrUndefined(decodeStored(process.metadata)) + if ( + !stored || + stored.location.directory !== location.directory || + stored.location.workspaceID !== location.workspaceID || + path.dirname(process.outputPath) !== outputDir || + commands.has(stored.id) + ) + continue + const running = process.lifecycle.status === "running" + const exited = process.lifecycle.status === "exited" ? process.lifecycle : undefined + const status = running ? "running" : (stored.stopReason ?? (exited ? "exited" : "killed")) + const info: Info = { + id: stored.id, + status, + command: stored.command, + cwd: process.cwd, + shell: stored.shell, + file: process.outputPath, + ...(process.pid !== undefined ? { pid: process.pid } : {}), + ...(status === "exited" && exited?.exitCode !== undefined ? { exit: exited.exitCode } : {}), + ...(status === "exited" && exited?.signal !== undefined ? { signal: exited.signal } : {}), + metadata: stored.metadata, + time: { + started: process.startedAt, + ...(running ? {} : { completed: process.exitedAt ?? process.startedAt }), + }, + } + const daemon: Daemon = { + id: process.id, + stored, + ...(running ? {} : { outputLines: process.outputLines, outputError: process.outputError }), + } + const command = daemonCommand(info, daemon) + commands.set(stored.id, command) + if (running) { + // A command moved to the background at shutdown has no timeout; an expired deadline fires at once. + const deadline = stored.backgroundedAtShutdown ? undefined : stored.timeoutDeadline + attach(command, daemon, deadline === undefined ? undefined : Math.max(0, deadline - Date.now())) + continue + } + yield* Deferred.succeed(command.done, info) + finished.push({ id: stored.id, exitedAt: info.time.completed ?? 0 }) + } + exitOrder.push(...finished.toSorted((a, b) => a.exitedAt - b.exitedAt).map((item) => item.id)) + yield* evict() + }) + const create = Effect.fn("Shell.create")(function* ( input: CreateInput, before?: (input: ShellCreateBefore) => Effect.Effect, @@ -318,6 +736,22 @@ const layer = () => time: { started: Date.now() }, } + if (daemonEnabled) { + const created = yield* createInDaemon(info, invocation, args, input.toolCall).pipe( + Effect.map(Option.some), + Effect.catchTags({ + "PersistentPty.UnavailableError": (error) => + Effect.logWarning("process daemon unavailable; spawning shell command instead", { + error: error.message, + }).pipe(Effect.as(Option.none())), + // The daemon may have run it: never run it again here. + "PersistentPty.RequestError": (cause) => + Effect.fail(new AppProcess.AppProcessError({ command: invocation.command, cause })), + }), + ) + if (Option.isSome(created)) return created.value + } + // Spawn through the Environment and stream combined output to the file. The handle is scope-bound, so // the managing fiber keeps its scope open until the command terminates (it awaits `done` at the // end). `create` returns once `ready` resolves with the registered command. @@ -332,7 +766,7 @@ const layer = () => env: invocation.env, stdin: "ignore", detached: process.platform !== "win32", - forceKillAfter: Duration.seconds(3), + forceKillAfter: STOP_GRACE, }), ) .pipe( @@ -393,7 +827,7 @@ const layer = () => const stop = (reason: StopReason) => Effect.gen(function* () { if (!(yield* end({ status: reason }))) return - runFork(handle.kill({ forceKillAfter: Duration.seconds(3) }).pipe(Effect.catch(() => Effect.void))) + runFork(handle.kill({ forceKillAfter: STOP_GRACE }).pipe(Effect.catch(() => Effect.void))) }).pipe(Effect.uninterruptible) command.stop = stop @@ -427,34 +861,7 @@ const layer = () => // Report the terminal status only once captured output is complete, so a reader that // sees it never reads a partial file. yield* outputDone.await - // A removed command already failed its waiters and published its exit and deletion. - if (commands.get(id) !== command) return - command.info = produce(command.info, (draft) => { - draft.status = outcome.status - if (outcome.exit !== undefined) draft.exit = outcome.exit - if (outcome.signal !== undefined) draft.signal = outcome.signal - draft.time.completed = outcome.completed - }) - // Resolve waiters before retention eviction, so an evicted command still reports its - // terminal Info rather than the removal NotFoundError. - yield* Deferred.succeed(command.done, command.info) - yield* bus.publish(Shell.Event.Exited, { - id, - ...(outcome.exit !== undefined ? { exit: outcome.exit } : {}), - status: outcome.status, - }) - exitOrder.push(id) - while (exitOrder.length > EXITED_LIMIT) { - const oldest = exitOrder[0] - if (!oldest) break - yield* removeCommand(oldest) - } - // Keep exited history data-only. - const timeoutFiber = command.timeoutFiber - command.timeout = undefined - command.stop = undefined - command.timeoutFiber = undefined - if (timeoutFiber) yield* Fiber.interrupt(timeoutFiber) + yield* finish(command, outcome) }), ) @@ -471,7 +878,23 @@ const layer = () => return command.info }) - return Service.of({ create, list, get, wait, result, timeout, stop, detachable, output, remove }) + // Taken back before the service is returned, so session restart recovery sees them. + if (daemonEnabled) yield* recover() + + return Service.of({ + create, + list, + get, + wait, + result, + timeout, + stop, + detachable, + backgroundAtShutdown, + byToolCall, + output, + remove, + }) }), ) @@ -487,6 +910,7 @@ export const node = makeLocationNode({ PluginHooks.node, SessionEnvironment.node, Config.node, + PersistentPty.node, cleanupNode, ], }) diff --git a/packages/core/src/tool/plugin/shell.ts b/packages/core/src/tool/plugin/shell.ts index 1cd135acfb4..6441924ebc1 100644 --- a/packages/core/src/tool/plugin/shell.ts +++ b/packages/core/src/tool/plugin/shell.ts @@ -233,6 +233,11 @@ export const Plugin = { timeout, shell: yield* compatibleShell, metadata: { sessionID: context.sessionID }, + toolCall: { + sessionID: context.sessionID, + assistantMessageID: context.messageID, + callID: context.id, + }, }, (invocation) => Effect.gen(function* () { diff --git a/packages/core/test/fixture/persistent-pty.ts b/packages/core/test/fixture/persistent-pty.ts new file mode 100644 index 00000000000..c81232f00e0 --- /dev/null +++ b/packages/core/test/fixture/persistent-pty.ts @@ -0,0 +1,8 @@ +import { Effect, Layer } from "effect" +import { PersistentPty } from "@opencode/core/persistent-pty" + +// No process daemon: shell commands fall back to the Environment's spawner, and nothing is ever running in it. +export const disabledPersistentPtyLayer = Layer.mock(PersistentPty.Service, { + createPipe: () => Effect.fail(new PersistentPty.UnavailableError({ message: "process daemon disabled" })), + listPipes: () => Effect.succeed([]), +}) diff --git a/packages/core/test/shell-cleanup.test.ts b/packages/core/test/shell-cleanup.test.ts index 9af9ca64af2..a807b69d830 100644 --- a/packages/core/test/shell-cleanup.test.ts +++ b/packages/core/test/shell-cleanup.test.ts @@ -6,13 +6,16 @@ import { Shell } from "@opencode/core/shell" import { LayerNode } from "@opencode/util/effect/layer-node" import { FSUtil } from "@opencode/util/fs-util" import { Global } from "@opencode/util/global" +import { PersistentPty } from "@opencode/core/persistent-pty" +import { disabledPersistentPtyLayer } from "./fixture/persistent-pty" import { withTempDir } from "./fixture/tmpdir" import { it } from "./lib/effect" const withStore = (body: (fs: FSUtil.Interface, root: string) => Effect.Effect) => withTempDir((tmp) => { - const layer = AppNodeBuilder.build(LayerNode.group([FSUtil.node, Global.node]), [ + const layer = AppNodeBuilder.build(LayerNode.group([FSUtil.node, Global.node, PersistentPty.node]), [ Global.node.replace(Global.layerWith({ data: tmp.path })), + PersistentPty.node.replace(disabledPersistentPtyLayer), ]) return Effect.gen(function* () { const fs = yield* FSUtil.Service diff --git a/packages/core/test/shell-retention.test.ts b/packages/core/test/shell-retention.test.ts index 3f776e4bb27..e650568496d 100644 --- a/packages/core/test/shell-retention.test.ts +++ b/packages/core/test/shell-retention.test.ts @@ -10,6 +10,8 @@ import { AbsolutePath } from "@opencode/core/schema" import { Shell } from "@opencode/core/shell" import { Workspace } from "@opencode/core/workspace" import { Global } from "@opencode/util/global" +import { PersistentPty } from "@opencode/core/persistent-pty" +import { disabledPersistentPtyLayer } from "./fixture/persistent-pty" import { hostEnvironmentLayer } from "./fixture/environment" import { tempGlobalLayer } from "./fixture/global" import { location, tempLocationLayer } from "./fixture/location" @@ -95,6 +97,7 @@ it.live("eviction makes progress past an already-removed shell", () => Global.node.replace(tempGlobalLayer), Config.node.replace(Config.testLayer()), Environment.node.replace(environment), + PersistentPty.node.replace(disabledPersistentPtyLayer), ]), ), ) diff --git a/packages/core/test/tool-shell.test.ts b/packages/core/test/tool-shell.test.ts index 08c90ba34ab..f2429986c75 100644 --- a/packages/core/test/tool-shell.test.ts +++ b/packages/core/test/tool-shell.test.ts @@ -37,6 +37,8 @@ import { Shell } from "@opencode/core/shell" import { ShellSelect } from "@opencode/core/shell/select" import { ID } from "@opencode/schema/shell" import { ShellTool } from "@opencode/core/tool/plugin/shell" +import { PersistentPty } from "@opencode/core/persistent-pty" +import { disabledPersistentPtyLayer } from "./fixture/persistent-pty" import { ToolOutput } from "@opencode/core/tool-output" import { Tool } from "@opencode/core/tool" import { ToolInterrupted } from "@opencode/core/tool/interrupted" @@ -167,6 +169,14 @@ const productionIt = testEffect(AppNodeBuilder.build(nodes, replacements)) const it = testEffect( AppNodeBuilder.build(nodes, [...replacements, PluginSupervisor.node.replace(shellPluginSupervisor)]), ) +// Without the process daemon, so commands are spawned by the server. +const spawnerIt = testEffect( + AppNodeBuilder.build(nodes, [ + ...replacements, + PluginSupervisor.node.replace(shellPluginSupervisor), + PersistentPty.node.replace(disabledPersistentPtyLayer), + ]), +) const permissionIt = testEffect( AppNodeBuilder.build(LayerNode.group([nodes, PermissionSaved.node]), [ SessionExecution.node.replace(executionNode), @@ -208,6 +218,19 @@ const call = (input: typeof ShellTool.Input.Type, id = "call-shell") => ({ }) const isWindows = process.platform === "win32" + +// The process daemon keeps a finished command's zombie until the command is forgotten. +const running = (pid: number) => { + try { + process.kill(pid, 0) + } catch { + return false + } + return !Bun.spawnSync(["ps", "-o", "stat=", "-p", String(pid)]) + .stdout.toString() + .trim() + .startsWith("Z") +} const cwdCommand = isWindows ? "(Get-Location).Path; Start-Sleep -Milliseconds 100" : "pwd" const helloCommand = isWindows ? "[Console]::Out.Write('hello'); Start-Sleep -Milliseconds 100" : "printf hello" const stderrCommand = isWindows @@ -1574,7 +1597,7 @@ describe("ShellTool", () => { expect((yield* shell.wait(info.id).pipe(Effect.timeout("10 seconds"))).status).toBe("timeout") const pid = info.pid if (pid === undefined) throw new Error("Expected shell PID") - expect(() => process.kill(pid, 0)).toThrow() + expect(running(pid)).toBe(false) }), (info) => Effect.try(() => { @@ -1719,7 +1742,7 @@ describe("ShellTool", () => { }), ) - it.live("leaves a spawned command's interrupt unchanged while detaching", () => + spawnerIt.live("leaves a spawned command's interrupt unchanged while detaching", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) =>