import fs from "fs/promises" import { realpathSync, watch } from "node:fs" import os from "os" import path from "path" import { describe, expect } from "bun:test" import { Cause, Deferred, Duration, Effect, Exit, Fiber, Layer, Queue, Schedule, Scope, Stream, Tracer } from "effect" import { TestClock } from "effect/testing" import { Money } from "@opencode/schema/money" import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" import { LayerNode } from "@opencode/util/effect/layer-node" import { makeGlobalNode, makeLocationNode } from "@opencode/util/effect/app-node" import { filesystem } from "@opencode/util/effect/app-node-platform" import { Database } from "@opencode/core/database/database" import { Bus } from "@opencode/core/bus" import { CodeModeCatalog } from "@opencode/core/codemode/catalog" import { Config } from "@opencode/core/config" import { Environment } from "@opencode/core/environment/index" import { FSUtil } from "@opencode/util/fs-util" import { Global } from "@opencode/util/global" import { Location } from "@opencode/core/location" import { FileAccess } from "@opencode/core/file-access" import { Flag } from "@opencode/core/flag" import { LocationServiceMap } from "@opencode/core/location-service-map" import { Model } from "@opencode/core/model" import { Provider } from "@opencode/core/provider" import { AbsolutePath } from "@opencode/core/schema" import { Agent } from "@opencode/core/agent" import { Automation } from "@opencode/schema/automation" import { Job } from "@opencode/core/job" import { Session } from "@opencode/core/session" import { SessionEvent } from "@opencode/core/session/event" import { SessionExecution } from "@opencode/core/session/execution" import { SessionMessage } from "@opencode/core/session/message" import { SessionStore } from "@opencode/core/session/store" import { Permission } from "@opencode/core/permission" import { PermissionSaved } from "@opencode/core/permission/saved" import { Plugin } from "@opencode/core/plugin" import { PluginSupervisor } from "@opencode/core/plugin/supervisor" import { Shell } from "@opencode/core/shell" import { ShellSelect } from "@opencode/core/shell/select" import { ShellResult } from "@opencode/core/shell/result" import { ID } from "@opencode/schema/shell" import { ShellTool } from "@opencode/core/tool/plugin/shell" import { StopTool } from "@opencode/core/tool/plugin/stop" import { ToolOutput } from "@opencode/core/tool-output" import { Tool } from "@opencode/core/tool" import { PluginHooks } from "@opencode/core/plugin/hooks" import { SessionStep } from "@opencode/core/session/runner/step" import { PersistentPty } from "@opencode/core/persistent-pty" import { disabledPersistentPtyLayer } from "./fixture/persistent-pty" import { fakeDaemon } from "./fixture/persistent-pty-daemon" import { tmpdir, tmpdirScoped, withTempDir } from "./fixture/tmpdir" import { tempGlobalLayer } from "./fixture/global" import { offlineModels } from "./fixture/models" import { testEffect } from "./lib/effect" import { permissionLayer } from "./lib/permission" import { Expected } from "./lib/session-message" import { toolIdentity, executeTool, registerToolPlugin, toolDefinitions } from "./lib/tool" const sessionID = Session.ID.make("ses_shell_tool_test") const sessionModel = Model.Ref.make({ id: Model.ID.make("test"), providerID: Provider.ID.make("test") }) const assertions: Permission.AssertInput[] = [] let denyAction: string | undefined let afterPermission = (_input: Permission.AssertInput): Effect.Effect => Effect.void const permission = permissionLayer({ assert: (input) => Effect.sync(() => assertions.push(input)).pipe( Effect.andThen(Effect.suspend(() => afterPermission(input))), Effect.andThen( input.action === denyAction ? Effect.fail( new Permission.BlockedError({ rules: [], permission: input.action, resources: input.resources, }), ) : Effect.void, ), ), }) const reset = () => { assertions.length = 0 denyAction = undefined afterPermission = () => Effect.void } const executionNode = makeGlobalNode({ service: SessionExecution.Service, layer: Layer.effect( SessionExecution.Service, Effect.gen(function* () { const bus = yield* Bus.Service const store = yield* SessionStore.Service const complete = Effect.fn("ShellTest.complete")(function* (id: Session.ID) { const session = yield* store.get(id) if (!session) return const assistantMessageID = SessionMessage.ID.create() yield* bus.publish(SessionEvent.Step.Started, { sessionID: id, assistantMessageID, agent: session.agent ?? Agent.ID.make("code"), model: sessionModel, started: 0, }) yield* bus.publish(SessionEvent.Text.Started, { sessionID: id, assistantMessageID, ordinal: 0, }) yield* bus.publish(SessionEvent.Text.Ended, { sessionID: id, assistantMessageID, ordinal: 0, text: "ok", }) yield* bus.publish(SessionEvent.Step.Ended, { sessionID: id, assistantMessageID, finish: "stop", cost: Money.USD.zero, tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, }) }) return SessionExecution.Service.of({ active: Effect.succeed(new Set()), isActive: () => Effect.succeed(false), resume: complete, wake: () => Effect.void, interrupt: () => Effect.succeed(false), awaitIdle: (id) => complete(id).pipe(Effect.exit, Effect.asVoid), }) }), ), deps: [Bus.node, SessionStore.node], }) const shellPluginSupervisor = makeLocationNode({ name: "test/shell-plugins", layer: Layer.effectDiscard( registerToolPlugin(ShellTool.Plugin).pipe(Effect.andThen(registerToolPlugin(StopTool.Plugin))), ), deps: [ Agent.node, Config.node, Environment.node, FileAccess.node, Flag.node, Permission.node, Session.node, Job.node, Location.node, Shell.node, Shell.daemonNode, ShellSelect.node, Bus.node, Tool.node, ], }) const nodes = LayerNode.group([ PersistentPty.node, Shell.daemonNode, Database.node, Bus.node, Job.node, Session.node, SessionExecution.node, LocationServiceMap.node, filesystem, FSUtil.node, Global.node, ]) const daemonReplacements = [ SessionExecution.node.replace(executionNode), Permission.node.replace(permission), Global.node.replace(tempGlobalLayer), offlineModels, ] satisfies LayerNode.Replacements // Most suites spawn commands from the server, so CI starts no daemon for them; `parity` runs a subset on both. const replacements = [ ...daemonReplacements, PersistentPty.node.replace(disabledPersistentPtyLayer), ] satisfies LayerNode.Replacements const noFlagOverrides = Layer.succeed(Flag.Overrides, undefined) const productionIt = testEffect(AppNodeBuilder.build(nodes, replacements).pipe(Layer.provide(noFlagOverrides))) const shellLayer = AppNodeBuilder.build(nodes, [...replacements, PluginSupervisor.node.replace(shellPluginSupervisor)]) const it = testEffect(shellLayer.pipe(Layer.provideMerge(noFlagOverrides))) const codeModeIt = testEffect(shellLayer.pipe(Layer.provide(Layer.succeed(Flag.Overrides, "full_codemode")))) // On the real process daemon (when its binary is compatible; otherwise this falls back to spawning). const daemonIt = testEffect( AppNodeBuilder.build(nodes, [...daemonReplacements, PluginSupervisor.node.replace(shellPluginSupervisor)]).pipe( Layer.provide(noFlagOverrides), ), ) const parity = { live: (name: string, body: Parameters[1], options?: Parameters[2]) => { it.live(`${name} (spawned)`, body, options) daemonIt.live(`${name} (daemon)`, body, options) }, skip: (name: string, body: Parameters[1], options?: Parameters[2]) => it.live.skip(name, body, options), } // On an in-process fake daemon, so daemon-only behavior is covered without the real binary. let fake: Effect.Success> | undefined const fakeDaemonIt = testEffect( AppNodeBuilder.build(nodes, [ ...daemonReplacements, PluginSupervisor.node.replace(shellPluginSupervisor), PersistentPty.node.replace( makeGlobalNode({ service: PersistentPty.Service, layer: Layer.unwrap( fakeDaemon().pipe( Effect.map((daemon) => { fake = daemon return PersistentPty.layerWith(daemon.options) }), ), ), deps: [Bus.node, Global.node], }), ), ]).pipe(Layer.provide(noFlagOverrides)), ) const permissionIt = testEffect( AppNodeBuilder.build(LayerNode.group([nodes, PermissionSaved.node]), [ SessionExecution.node.replace(executionNode), Global.node.replace(tempGlobalLayer), PluginSupervisor.node.replace(shellPluginSupervisor), PersistentPty.node.replace(disabledPersistentPtyLayer), offlineModels, ]).pipe(Layer.provide(noFlagOverrides)), ) const call = (input: typeof ShellTool.Input.Type, id = "call-shell") => ({ sessionID, ...toolIdentity, call: { type: "tool-call" as const, id, name: "shell", input }, }) // A full Code Mode call: a top-level call to a tool only offered in Code Mode runs as one. const codeModeCall = (input: Record, id = "call-shell", name = "shell") => ({ sessionID, ...toolIdentity, call: { type: "tool-call" as const, id, name, input }, }) // Notifications admitted to the test session. const syntheticNotices = Effect.gen(function* () { const bus = yield* Bus.Service const notices = yield* Queue.unbounded() yield* bus.subscribe(SessionEvent.InboxEnqueued).pipe( Stream.filter((event) => event.data.sessionID === sessionID && event.data.item.type === "synthetic"), Stream.runForEach((event) => Queue.offer(notices, event.data.item.payload)), Effect.forkScoped({ startImmediately: true }), ) return notices }) // Every background job's outbox row is gone. Polls on real time, since some tests drive a TestClock. const outboxCleared = Effect.gen(function* () { const jobs = yield* Job.Service for (let attempt = 0; attempt < 500; attempt++) { if ((yield* jobs.pendingBackground).length === 0) return yield* Effect.promise(() => Bun.sleep(10)) } throw new Error("background outbox rows remain") }) const isWindows = process.platform === "win32" 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 ? "[Console]::Error.Write('stderr only'); Start-Sleep -Milliseconds 100" : "printf 'stderr only' >&2" const mixedOutputCommand = isWindows ? "[Console]::Out.Write('stdout'); Start-Sleep -Milliseconds 50; [Console]::Error.Write('stderr'); Start-Sleep -Milliseconds 100" : "printf stdout; sleep 0.05; printf stderr >&2" const idleCommand = isWindows ? "Start-Sleep -Seconds 60" : "sleep 60" const startingCommand = isWindows ? "[Console]::Out.Write('server starting'); Start-Sleep -Seconds 60" : "printf 'server starting'; sleep 60" // A timeout kills the process group with SIGTERM, which the result reports as 128 + 15 and its name. const timedOutExit = isWindows ? ".+" : "143 \\(SIGTERM\\)" const bodyExitCommand = isWindows ? "[Console]::Out.Write('body'); Start-Sleep -Milliseconds 100; exit 7" : "printf body && exit 7" const overflowCommand = (bytes: number) => isWindows ? `[Console]::Out.Write('output-start' + ('x' * ${bytes}) + 'output-end'); Start-Sleep -Milliseconds 100` : `printf output-start; head -c ${bytes} /dev/zero | tr '\\0' 'x'; printf output-end` const lineOverflowCommand = isWindows ? "[Console]::Out.Write('one' + [Environment]::NewLine + 'two' + [Environment]::NewLine + 'three')" : "printf 'one\\ntwo\\nthree'" // Streams a file's exact bytes, so tests control line lengths and UTF-8 boundaries on every platform. const catCommand = (file: string) => isWindows ? `$bytes = [IO.File]::ReadAllBytes('${file}'); $out = [Console]::OpenStandardOutput(); $out.Write($bytes, 0, $bytes.Length); $out.Flush()` : `cat '${file}'` const progressOverflowCommand = (bytes: number, release: string) => isWindows ? `[Console]::Out.Write(('x' * ${bytes})); while (!(Test-Path -LiteralPath '${release}')) { Start-Sleep -Milliseconds 50 }` : `head -c ${bytes} /dev/zero | tr '\\0' 'x'; while [ ! -e '${release}' ]; do sleep 0.05; done` const withSession = (directory: string, body: (registry: Tool.Interface) => Effect.Effect) => Effect.gen(function* () { const sessions = yield* Session.Service const location = Location.Ref.make({ directory: AbsolutePath.make(directory) }) yield* sessions.create({ id: sessionID, title: "shell test", location, model: sessionModel, }) const locations = yield* LocationServiceMap.Service const locationLayer = locations.get(location) return yield* Effect.gen(function* () { const plugins = yield* Plugin.Service yield* plugins.awaitActivation const registry = yield* Tool.Service return yield* body(registry) }).pipe(Effect.provide(locationLayer), Effect.ensuring(locations.invalidate(location))) }) const withScanner = ( body: (registry: Tool.Interface, fixture: { active: string; outside: string }) => Effect.Effect, shell = "sh", ) => withTempDir((tmp) => Effect.gen(function* () { const fixture = { active: path.join(tmp.path, "active"), outside: path.join(tmp.path, "outside") } yield* Effect.promise(() => Promise.all([fs.mkdir(fixture.active), fs.mkdir(fixture.outside)])) return yield* withSession(fixture.active, (registry) => Effect.gen(function* () { const selection = yield* ShellSelect.Service yield* selection.transform((editor) => editor.configure(shell)) const agents = yield* Agent.Service yield* agents.transform((editor) => editor.update(toolIdentity.agent, (agent) => { agent.permissions = [] }), ) return yield* body(registry, fixture) }), ) }), ) // The timeout catches a hung permission flow, not slowness: PowerShell commands on loaded Windows runners have exceeded 5s. const runPermissionCommand = ( registry: Tool.Interface, command: string, marker: string, replies: ReadonlyArray, ) => Effect.gen(function* () { const permission = yield* Permission.Service const bus = yield* Bus.Service const queue = yield* Queue.unbounded() yield* bus.subscribe(Permission.Event.Asked).pipe( Stream.runForEach((event) => Queue.offer(queue, event.data)), Effect.forkScoped({ startImmediately: true }), ) const execution = yield* executeTool(registry, call({ command }, `call-${Permission.ID.create()}`)).pipe( Effect.forkScoped, ) const requests = yield* Effect.forEach(replies, (reply) => Effect.gen(function* () { const request = yield* Queue.take(queue) expect(yield* permission.forSession(sessionID)).toEqual([request]) expect(yield* Effect.promise(() => Bun.file(marker).exists())).toBe(false) yield* permission.reply({ requestID: request.id, reply }) return request }), ) const exit = yield* Fiber.await(execution) expect(yield* permission.list()).toEqual([]) expect(yield* Queue.size(queue)).toBe(0) return { exit, requests } }).pipe(Effect.scoped, Effect.timeout(Duration.seconds(15))) describe("ShellTool scanner permissions", () => { const test = isWindows || !Bun.which("sh") ? permissionIt.live.skip : permissionIt.live test("declarations reuse approvals while substitutions retain reject/once/always behavior", () => withScanner((registry, fixture) => Effect.gen(function* () { const saved = yield* PermissionSaved.Service const location = yield* Location.Service yield* saved.add({ projectID: location.project.id, action: "shell", resources: ["printf *"] }) const marker = path.join(fixture.active, "marker") const approved = yield* runPermissionCommand( registry, "export SCAN_TEST=hello; unset SCAN_TEST; printf hello > marker", marker, [], ) expect(approved.requests).toEqual([]) expect(approved.exit).toMatchObject({ _tag: "Success", value: { status: "completed", metadata: { exit: 0 } }, }) expect(yield* Effect.promise(() => Bun.file(marker).text())).toBe("hello") expect((yield* saved.list()).map((item) => item.resource)).toEqual(["printf *"]) yield* Effect.forEach(yield* saved.list(), (item) => saved.remove(item.id)) const command = 'export SCAN_TEST=$(printf hello); printf %s "$SCAN_TEST" > marker' const prompts: Permission.Request[] = [] for (const reply of ["reject", "once", "always", undefined] as const) { yield* Effect.promise(() => fs.rm(marker, { force: true })) const result = yield* runPermissionCommand(registry, command, marker, reply ? [reply] : []) prompts.push(...result.requests) if (reply === "reject") { expect(Exit.isFailure(result.exit)).toBe(true) if (Exit.isFailure(result.exit)) expect( result.exit.cause.reasons.some( (reason) => Cause.isDieReason(reason) && reason.defect instanceof Permission.DeclinedError, ), ).toBe(true) expect(yield* Effect.promise(() => Bun.file(marker).exists())).toBe(false) continue } expect(result.exit).toMatchObject({ _tag: "Success", value: { status: "completed", metadata: { exit: 0 } }, }) expect(yield* Effect.promise(() => Bun.file(marker).text())).toBe("hello") if (reply === "once") expect(yield* saved.list()).toEqual([]) } expect(prompts).toHaveLength(3) for (const request of prompts) { expect(request).toMatchObject({ action: "shell", resources: ["printf hello", 'printf %s "$SCAN_TEST" > marker'], save: ["printf *", "printf *"], }) } expect((yield* saved.list()).map((item) => item.resource)).toEqual(["printf *"]) const agents = yield* Agent.Service yield* agents.transform((editor) => editor.update(toolIdentity.agent, (agent) => { agent.permissions = [{ action: "shell", resource: "printf hello", effect: "deny" }] }), ) yield* Effect.promise(() => fs.rm(marker)) const denied = yield* runPermissionCommand(registry, command, marker, []) expect(denied.exit).toMatchObject({ _tag: "Success", value: { status: "error", error: { message: expect.stringContaining("Permission denied: shell") } }, }) expect(yield* Effect.promise(() => Bun.file(marker).exists())).toBe(false) }), )) test("unanalyzable commands run under allow-all rules", () => withScanner((registry, fixture) => Effect.gen(function* () { const agents = yield* Agent.Service yield* agents.transform((editor) => editor.update(toolIdentity.agent, (agent) => { agent.permissions = [{ action: "*", resource: "*", effect: "allow" }] }), ) const marker = path.join(fixture.active, "marker") const result = yield* runPermissionCommand(registry, "alias p=true; printf hello > marker", marker, []) expect(result.requests).toEqual([]) expect(result.exit).toMatchObject({ _tag: "Success", value: { status: "completed", metadata: { exit: 0 } } }) expect(yield* Effect.promise(() => Bun.file(marker).text())).toBe("hello") }), )) test("unanalyzable commands are denied when a shell deny rule could be bypassed", () => withScanner((registry, fixture) => Effect.gen(function* () { const agents = yield* Agent.Service yield* agents.transform((editor) => editor.update(toolIdentity.agent, (agent) => { agent.permissions = [ { action: "*", resource: "*", effect: "allow" }, { action: "shell", resource: "rm *", effect: "deny" }, ] }), ) const marker = path.join(fixture.active, "marker") const result = yield* runPermissionCommand(registry, "alias p=true; printf hello > marker", marker, []) expect(result.requests).toEqual([]) expect(result.exit).toMatchObject({ _tag: "Success", value: { status: "error", error: { message: expect.stringContaining( "Portable shell scanner cannot analyze command: dynamic-execution. A shell deny rule is configured", ), }, }, }) expect(yield* Effect.promise(() => Bun.file(marker).exists())).toBe(false) }), )) test("unanalyzable commands ask for the exact command and any directory without saving", () => withScanner((registry, fixture) => Effect.gen(function* () { const saved = yield* PermissionSaved.Service const agents = yield* Agent.Service yield* agents.transform((editor) => editor.update(toolIdentity.agent, (agent) => { agent.permissions = [ { action: "shell", resource: "alias *", effect: "allow" }, { action: "external_directory", resource: path.join(fixture.outside, "*"), effect: "allow" }, ] }), ) const marker = path.join(fixture.active, "marker") const command = "alias p=true; printf hello > marker" const approved = yield* runPermissionCommand(registry, command, marker, ["always"]) expect(approved.requests).toMatchObject([{ action: "external_directory", resources: ["*"] }]) expect(approved.exit).toMatchObject({ _tag: "Success", value: { status: "completed", metadata: { exit: 0 } } }) expect(yield* Effect.promise(() => Bun.file(marker).text())).toBe("hello") yield* agents.transform((editor) => editor.update(toolIdentity.agent, (agent) => { agent.permissions = [{ action: "external_directory", resource: "*", effect: "allow" }] }), ) yield* Effect.promise(() => fs.rm(marker)) const asked = yield* runPermissionCommand(registry, command, marker, ["always"]) expect(asked.requests).toMatchObject([ { action: "shell", resources: [command], metadata: { reason: "dynamic-execution" } }, ]) expect(asked.requests.map((request) => request.save)).toEqual([undefined]) expect(yield* Effect.promise(() => Bun.file(marker).text())).toBe("hello") expect(yield* saved.list()).toEqual([]) yield* Effect.promise(() => fs.rm(marker)) const repeat = yield* runPermissionCommand(registry, command, marker, ["reject"]) expect(repeat.requests).toHaveLength(1) expect(Exit.isFailure(repeat.exit)).toBe(true) expect(yield* Effect.promise(() => Bun.file(marker).exists())).toBe(false) }), )) test("pipeline redirect keeps the redirect target visible to exact approval and denial", () => withScanner((registry, fixture) => Effect.gen(function* () { const saved = yield* PermissionSaved.Service const location = yield* Location.Service yield* saved.add({ projectID: location.project.id, action: "shell", resources: ["printf hello", "cat"] }) const marker = path.join(fixture.active, "marker") const command = "printf hello | cat > marker" const unapprovedRedirect = yield* runPermissionCommand(registry, command, marker, ["reject"]) expect(unapprovedRedirect.requests).toMatchObject([ { action: "shell", resources: ["printf hello", "cat > marker"], save: ["printf *", "cat *"] }, ]) expect(yield* Effect.promise(() => Bun.file(marker).exists())).toBe(false) yield* saved.add({ projectID: location.project.id, action: "shell", resources: ["cat > marker"] }) const exact = yield* runPermissionCommand(registry, command, marker, []) expect(exact.requests).toEqual([]) expect(exact.exit).toMatchObject({ _tag: "Success", value: { status: "completed", metadata: { exit: 0 } } }) expect(yield* Effect.promise(() => Bun.file(marker).text())).toBe("hello") yield* saved.add({ projectID: location.project.id, action: "shell", resources: ["printf *", "cat *"] }) yield* Effect.promise(() => fs.rm(marker)) const broad = yield* runPermissionCommand(registry, command, marker, []) expect(broad.requests).toEqual([]) expect(broad.exit).toMatchObject({ _tag: "Success", value: { status: "completed", metadata: { exit: 0 } } }) expect(yield* Effect.promise(() => Bun.file(marker).text())).toBe("hello") const agents = yield* Agent.Service yield* agents.transform((editor) => editor.update(toolIdentity.agent, (agent) => { agent.permissions = [{ action: "shell", resource: "* > marker", effect: "deny" }] }), ) yield* Effect.promise(() => fs.rm(marker)) const denied = yield* runPermissionCommand(registry, command, marker, []) expect(denied.requests).toEqual([]) expect(denied.exit).toMatchObject({ _tag: "Success", value: { status: "error", error: { message: expect.stringContaining("Permission denied: shell") } }, }) expect(yield* Effect.promise(() => Bun.file(marker).exists())).toBe(false) }), )) test("external-directory rejection stops execution before a workspace marker is written", () => withScanner((registry, fixture) => Effect.gen(function* () { const agents = yield* Agent.Service yield* agents.transform((editor) => editor.update(toolIdentity.agent, (agent) => { agent.permissions = [{ action: "shell", resource: "*", effect: "allow" }] }), ) const marker = path.join(fixture.active, "marker") const command = `cd '${fixture.outside}' && pwd -P && printf reached > '${marker}'` for (const reply of ["reject", "once"] as const) { const result = yield* runPermissionCommand(registry, command, marker, [reply]) expect(result.requests).toMatchObject([ { action: "external_directory", resources: [path.join(fixture.outside, "*")] }, ]) if (reply === "reject") { expect(Exit.isFailure(result.exit)).toBe(true) if (Exit.isFailure(result.exit)) expect( result.exit.cause.reasons.some( (reason) => Cause.isDieReason(reason) && reason.defect instanceof Permission.DeclinedError, ), ).toBe(true) expect(yield* Effect.promise(() => Bun.file(marker).exists())).toBe(false) continue } expect(result.exit).toMatchObject({ _tag: "Success", value: { status: "completed", metadata: { exit: 0 }, content: [{ type: "text", text: `${fixture.outside}\n` }], }, }) expect(yield* Effect.promise(() => Bun.file(marker).text())).toBe("reached") } }), )) test("a numeric symlink operand still reaches outside without an external-directory prompt", () => withScanner((registry, fixture) => Effect.gen(function* () { yield* Effect.promise(() => fs.symlink(fixture.outside, path.join(fixture.active, "123"))) const agents = yield* Agent.Service yield* agents.transform((editor) => editor.update(toolIdentity.agent, (agent) => { agent.permissions = [ { action: "shell", resource: "*", effect: "allow" }, { action: "external_directory", resource: "*", effect: "deny" }, ] }), ) const marker = path.join(fixture.active, "marker") const result = yield* runPermissionCommand( registry, `cd 123 && pwd -P && printf reached > '${marker}'`, marker, [], ) expect(result.requests).toEqual([]) expect(result.exit).toMatchObject({ _tag: "Success", value: { status: "completed", metadata: { exit: 0 }, content: [{ type: "text", text: `${fixture.outside}\n` }], }, }) expect(yield* Effect.promise(() => Bun.file(marker).text())).toBe("reached") }), )) test("a continued directory operand resolves to the destination and enforces external-directory deny", () => withScanner((registry, fixture) => Effect.gen(function* () { const agents = yield* Agent.Service yield* agents.transform((editor) => editor.update(toolIdentity.agent, (agent) => { agent.permissions = [ { action: "shell", resource: "*", effect: "allow" }, { action: "external_directory", resource: path.join(fixture.outside, "*"), effect: "deny" }, ] }), ) const marker = path.join(fixture.active, "marker") const command = `cd ../out\\\nside && pwd -P && printf reached > '${marker}'` const denied = yield* runPermissionCommand(registry, command, marker, []) expect(denied.requests).toEqual([]) expect(denied.exit).toMatchObject({ _tag: "Success", value: { status: "error", error: { message: expect.stringContaining("Permission denied: external_directory") }, }, }) expect(yield* Effect.promise(() => Bun.file(marker).exists())).toBe(false) }), )) }) describe("ShellTool conditional process substitution", () => { const test = isWindows || !Bun.which("bash") ? permissionIt.live.skip : permissionIt.live test("a nested deny prevents the substitution from running", () => withScanner( (registry, directory) => Effect.gen(function* () { const agents = yield* Agent.Service yield* agents.transform((editor) => editor.update(toolIdentity.agent, (agent) => { agent.permissions = [ { action: "shell", resource: "*", effect: "allow" }, { action: "shell", resource: "printf *", effect: "deny" }, ] }), ) const marker = path.join(directory.active, "marker") const result = yield* runPermissionCommand( registry, '[[ -n <(printf reached > marker) ]]; wait "$!"', marker, [], ) expect(result.exit).toMatchObject({ _tag: "Success", value: { status: "error", error: { message: expect.stringContaining("Permission denied: shell") } }, }) expect(yield* Effect.promise(() => Bun.file(marker).exists())).toBe(false) }), "bash", )) for (const reply of ["reject", "once", "always"] as const) { test(`conditional substitutions respect ${reply}`, () => withScanner( (registry, directory) => Effect.gen(function* () { const saved = yield* PermissionSaved.Service const location = yield* Location.Service yield* saved.add({ projectID: location.project.id, action: "shell", resources: ["wait *"] }) const marker = path.join(directory.active, "marker") const command = '[[ -n <(printf reached > marker) ]]; wait "$!"' const result = yield* runPermissionCommand(registry, command, marker, [reply]) expect(result.requests).toMatchObject([ { action: "shell", resources: ["printf reached > marker", 'wait "$!"'], save: ["printf *", "wait *"] }, ]) if (reply === "reject") { expect(Exit.isFailure(result.exit)).toBe(true) expect(yield* Effect.promise(() => Bun.file(marker).exists())).toBe(false) return } expect(result.exit).toMatchObject({ _tag: "Success", value: { status: "completed", metadata: { exit: 0 } }, }) expect(yield* Effect.promise(() => Bun.file(marker).text())).toBe("reached") yield* Effect.promise(() => fs.unlink(marker)) const repeat = yield* runPermissionCommand(registry, command, marker, reply === "always" ? [] : ["reject"]) expect(repeat.requests).toHaveLength(reply === "always" ? 0 : 1) expect(yield* Effect.promise(() => Bun.file(marker).exists())).toBe(reply === "always") }), "bash", )) } }) describe("ShellTool compound syntax approval compatibility", () => { for (const fixture of [ { shell: "zsh", command: 'for value (a b) printf %s "$value"', output: "ab", saved: ["printf *"], }, { shell: "zsh", command: 'for value (a b) { printf %s "$value"; }', output: "ab", saved: ["printf *"], }, { shell: "zsh", command: 'for value ($(printf a)) do printf %s "$value"; done', output: "a", saved: ["printf *"], }, { shell: "bash", command: 'probe() for value in a b; do printf %s "$value"; done; probe', output: "ab", saved: ["printf *", "probe *"], }, { shell: "bash", command: 'printf %s "$(probe() case value in (value) printf hello;; esac; probe)"', output: "hello", saved: ["printf *", "probe *"], }, ]) { const test = isWindows || !Bun.which(fixture.shell) ? permissionIt.live.skip : permissionIt.live test(`${fixture.shell}: ${fixture.command}`, () => withScanner( (registry, directory) => Effect.gen(function* () { const saved = yield* PermissionSaved.Service const location = yield* Location.Service yield* saved.add({ projectID: location.project.id, action: "shell", resources: fixture.saved }) const result = yield* runPermissionCommand( registry, fixture.command, path.join(directory.active, "marker"), [], ) expect(result.requests).toEqual([]) expect(result.exit).toMatchObject({ _tag: "Success", value: { status: "completed", metadata: { exit: 0 }, content: [{ type: "text", text: fixture.output }], }, }) }), fixture.shell, )) } }) describe("ShellTool ordinary shell syntax", () => { for (const shell of ["bash", "zsh"]) { const test = isWindows || !Bun.which(shell) ? permissionIt.live.skip : permissionIt.live for (const fixture of [ { name: "quoted heredoc", command: "cat <<'EOF'\nhello\nEOF", output: "hello\n", saved: ["cat *"] }, { name: "heredoc substitution", command: "cat < withScanner( (registry, directory) => Effect.gen(function* () { const saved = yield* PermissionSaved.Service const location = yield* Location.Service yield* saved.add({ projectID: location.project.id, action: "shell", resources: fixture.saved }) const result = yield* runPermissionCommand( registry, fixture.command, path.join(directory.active, "marker"), [], ) expect(result.requests).toEqual([]) expect(result.exit).toMatchObject({ _tag: "Success", value: { status: "completed", metadata: { exit: 0 }, content: [{ type: "text", text: fixture.output }], }, }) }), shell, )) } test(`${shell}: a loop body deny prevents execution`, () => withScanner( (registry, directory) => Effect.gen(function* () { const agents = yield* Agent.Service yield* agents.transform((editor) => editor.update(toolIdentity.agent, (agent) => { agent.permissions = [ { action: "shell", resource: "*", effect: "allow" }, { action: "shell", resource: "printf *", effect: "deny" }, ] }), ) const marker = path.join(directory.active, "marker") const result = yield* runPermissionCommand( registry, "for value in a; do printf body > marker; done", marker, [], ) expect(result.exit).toMatchObject({ _tag: "Success", value: { status: "error", error: { message: expect.stringContaining("Permission denied: shell") } }, }) expect(yield* Effect.promise(() => Bun.file(marker).exists())).toBe(false) }), shell, )) } const pwsh = process.env.SHELL_SCAN_PWSH ?? Bun.which("pwsh") ?? Bun.which("powershell") const test = pwsh ? permissionIt.live : permissionIt.live.skip for (const command of [ 'Write-Output "$(Write-Output hello)"', '$value = "hello"; Write-Output $value', "if ($true) { Write-Output hello } else { Write-Output other }", "foreach ($value in @('hello')) { Write-Output $value }", "ForEach-Object { Write-Output hello }", "function Show-Value { Write-Output hello }; Show-Value", "Write-Output `\n hello", "Write-Output @'\nhello\n'@", ]) { test(`PowerShell: ordinary syntax reuses approvals: ${command}`, () => withScanner( (registry, directory) => Effect.gen(function* () { const saved = yield* PermissionSaved.Service const location = yield* Location.Service yield* saved.add({ projectID: location.project.id, action: "shell", resources: ["Write-Output *", "Show-Value *"], }) const result = yield* runPermissionCommand(registry, command, path.join(directory.active, "marker"), []) expect(result.requests).toEqual([]) expect(result.exit).toMatchObject({ _tag: "Success", value: { status: "completed", metadata: { exit: 0 } }, }) if (Exit.isSuccess(result.exit)) expect(result.exit.value.content?.[0]).toEqual(Expected.text(isWindows ? "hello\r\n" : "hello\n")) }), pwsh ?? "pwsh", )) } for (const [command, pattern] of [ ["Write-Output\thello", "Write-Output\t*"], ["& 'Write-Output' hello", "& 'Write-Output' *"], ["Write-Output `\n hello", "Write-Output *"], ]) { test(`PowerShell: always allow covers repeat execution and preserves exact deny: ${command}`, () => withScanner( (registry, directory) => Effect.gen(function* () { const marker = path.join(directory.active, "marker") const first = yield* runPermissionCommand(registry, command, marker, ["always"]) expect(first.requests).toMatchObject([{ action: "shell", resources: [command], save: [pattern] }]) expect(first.exit).toMatchObject({ _tag: "Success", value: { status: "completed", metadata: { exit: 0 } } }) const repeat = yield* runPermissionCommand(registry, command, marker, []) expect(repeat.requests).toEqual([]) expect(repeat.exit).toMatchObject({ _tag: "Success", value: { status: "completed", metadata: { exit: 0 } }, }) const agents = yield* Agent.Service yield* agents.transform((editor) => editor.update(toolIdentity.agent, (agent) => { agent.permissions = [{ action: "shell", resource: command, effect: "deny" }] }), ) const denied = yield* runPermissionCommand(registry, command, marker, []) expect(denied.exit).toMatchObject({ _tag: "Success", value: { status: "error", error: { message: expect.stringContaining("Permission denied: shell") } }, }) }), pwsh ?? "pwsh", )) } }) describe("ShellTool", () => { it.live("returns both parallel CodeMode shell results", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { yield* registry.transform((editor) => editor.update("shell", (tool) => { tool.options = { ...tool.options, codemode: true } }), ) const command = isWindows ? helloCommand : `${helloCommand}; sleep 0.1` const inputs = ["one", "two"].map((text) => JSON.stringify({ command: command.replace("hello", text) })) const result = yield* executeTool(registry, { sessionID, ...toolIdentity, call: { type: "tool-call", id: "call-parallel-shells", name: "execute", input: { code: `return await Promise.all([tools.shell(${inputs[0]}), tools.shell(${inputs[1]})])` }, }, }).pipe(Effect.timeout("3 seconds")) expect(result.status).toBe("completed") expect(JSON.parse(result.output.output)).toEqual([ { output: "one", exitCode: 0, wallTimeSeconds: expect.any(Number) }, { output: "two", exitCode: 0, wallTimeSeconds: expect.any(Number) }, ]) }), ) }), ) it.live( "keeps a CodeMode shell result's exit code and output path when the execute output is truncated", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { yield* registry.transform((editor) => editor.update("shell", (tool) => { tool.options = { ...tool.options, codemode: true } }), ) const command = `${overflowCommand(ToolOutput.MAX_BYTES + 1024)}${isWindows ? "; exit 3" : " && exit 3"}` const result = yield* executeTool(registry, { sessionID, ...toolIdentity, call: { type: "tool-call", id: "call-truncated-shell", name: "execute", input: { code: `return await tools.shell(${JSON.stringify({ command })})` }, }, }) expect(result.status).toBe("completed") const toolOutput = yield* ToolOutput.Service const truncated = yield* toolOutput.truncate({ content: result.content!, metadata: result.metadata }) expect(truncated.metadata?.truncated).toBe(true) const text = truncated.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n") const shell = JSON.parse(result.output.output) expect(text).toStartWith( `{"exitCode":3,"outputPath":${JSON.stringify(shell.outputPath)},"wallTimeSeconds":${shell.wallTimeSeconds},"output":"`, ) }), ) }), { timeout: 15_000 }, ) codeModeIt.live("lists shell and shell_read pinned, with yield_ms and no background", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const snapshot = yield* registry.snapshot() // Pinned: listed even when the catalog has no room for other tools, with the result contract in the field // annotations. const pinned = CodeModeCatalog.summarize(snapshot.codeModeCatalog!, { budget: 0 }).namespaces.flatMap( (namespace) => namespace.entries, ) expect(pinned.map((entry) => entry.path).toSorted()).toEqual(["shell", "shell_read", "stop"]) const shell = pinned.find((entry) => entry.path === "shell")!.line expect(shell).toContain("Execute a shell command and return its output.") expect(shell).toContain("yield_ms") expect(shell).toContain("default 30000") expect(shell).toContain("Nothing is reported automatically when it exits") expect(shell).toContain("the command is stopped when it expires") expect(shell).not.toContain("background?: boolean") expect(shell).not.toContain("Background commands return immediately") expect(shell).not.toContain("you will be notified") expect(shell).toContain("A result without shellID is final") expect(shell).toContain("there are no separate stdout or stderr fields") expect(pinned.find((entry) => entry.path === "shell_read")!.line).toContain("wait_ms") }), ) }), ) codeModeIt.effect( "returns a command still running after 30 seconds with its shell ID, and reports nothing when it exits", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const notices = yield* syntheticNotices const timeouts: number[] = [] const hooks = yield* PluginHooks.Service yield* hooks.register("shell", "create.before", (event) => Effect.sync(() => { timeouts.push(event.timeout) }), ) const running = yield* executeTool( registry, codeModeCall({ command: progressOverflowCommand(6, "release") }), ).pipe(Effect.forkScoped({ startImmediately: true })) // The wait starts only after the command spawns, so keep advancing the clock until the call returns. const result = yield* Fiber.join(running).pipe( Effect.raceFirst( Effect.forever( Effect.promise(() => Bun.sleep(20)).pipe(Effect.andThen(TestClock.adjust("10 seconds"))), ), ), ) expect(result.status).toBe("completed") const id = ID.make(String(result.output.shellID)) const shell = yield* Shell.Service const info = yield* shell.get(id) expect(info.status).toBe("running") expect(result.output).toEqual({ shellID: id, pid: info.pid, outputPath: info.file, exitCode: null, output: expect.stringContaining("xxxxxx"), wallTimeSeconds: expect.any(Number), }) expect(result.output.output).toContain(`[Still running after 30s as shell ${id}`) expect(result.output.output).toContain(`tools.shell_read({shellID: "${id}"})`) // No timeout: the command isn't stopped. expect(timeouts).toEqual([0]) yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), "")) expect(yield* shell.wait(id)).toMatchObject({ status: "exited", exit: 0 }) yield* outboxCleared expect(yield* Queue.size(notices)).toBe(0) }), ) }), ) codeModeIt.effect("waits until the command exits with yield_ms 0", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const running = yield* executeTool( registry, codeModeCall({ command: `${progressOverflowCommand(0, "release")}; printf done`, yield_ms: 0 }), ).pipe(Effect.forkScoped({ startImmediately: true })) for (let minute = 0; minute < 5; minute++) { yield* Effect.promise(() => Bun.sleep(20)) yield* TestClock.adjust("1 minute") } expect(running.pollUnsafe()).toBeUndefined() yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), "")) const result = yield* Fiber.join(running) expect(result.output).toEqual({ output: "done", exitCode: 0, outputPath: expect.any(String), wallTimeSeconds: expect.any(Number), }) }), ) }), ) codeModeIt.live("gives every result its output path, and stops a command at its timeout", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const failed = yield* executeTool(registry, codeModeCall({ command: bodyExitCommand })) expect(failed.output).toEqual({ output: "body", exitCode: 7, outputPath: expect.any(String), wallTimeSeconds: expect.any(Number), }) expect(yield* Effect.promise(() => fs.readFile(failed.output.outputPath, "utf8"))).toBe("body") const stopped = yield* executeTool(registry, codeModeCall({ command: startingCommand, timeout: 300 })) const written = yield* Effect.promise(() => fs.readFile(String(stopped.output.outputPath), "utf8")) expect(written).toBe("server starting") expect(stopped.output).toMatchObject({ output: expect.stringContaining("server starting"), exitCode: null, killed: "Stopped when its timeout of 0.3 seconds expired.", outputPath: expect.any(String), }) expect(stopped.output).not.toHaveProperty("shellID") const shell = yield* Shell.Service expect(yield* shell.list()).toEqual([]) }), ) }), ) codeModeIt.live( "shell_read returns new output since the last read, and waits for the exit", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const release = (name: string) => Effect.promise(() => Bun.write(path.join(tmp.path, name), "")) const command = isWindows ? "[Console]::Out.Write('first'); while (!(Test-Path one)) { Start-Sleep -Milliseconds 50 }; [Console]::Out.Write('second'); while (!(Test-Path two)) { Start-Sleep -Milliseconds 50 }; exit 3" : "printf first; while [ ! -e one ]; do sleep 0.05; done; printf second; while [ ! -e two ]; do sleep 0.05; done; exit 3" const started = yield* executeTool(registry, codeModeCall({ command, yield_ms: 500 })) const shellID = String(started.output.shellID) expect(started.output.output).toStartWith("first\n\n[Still running after 0.5s") let calls = 0 const read = (input: Record) => executeTool(registry, codeModeCall(input, `call-read-${calls++}`, ShellTool.readName)) // The yield already returned what was printed. expect((yield* read({ shellID, wait_ms: 0 })).output).toEqual({ shellID, running: true, exitCode: null, output: "", outputPath: started.output.outputPath, }) yield* release("one") let output = "" for (let attempt = 0; attempt < 100 && output !== "second"; attempt++) { const result = yield* read({ shellID, wait_ms: 20 }) expect(result.output.running).toBe(true) output += result.output.output } expect(output).toBe("second") // Returns at the exit, well before its wait. const waiting = yield* read({ shellID, wait_ms: 60_000 }).pipe( Effect.forkScoped({ startImmediately: true }), ) yield* Effect.promise(() => Bun.sleep(100)) expect(waiting.pollUnsafe()).toBeUndefined() yield* release("two") const exited = yield* Fiber.join(waiting).pipe(Effect.timeout("10 seconds")) expect(exited.output).toEqual({ shellID, running: false, exitCode: 3, output: "", outputPath: started.output.outputPath, }) expect(exited.content).toEqual([{ type: "text", text: "Exited with code 3." }]) expect((yield* read({ shellID })).output).toMatchObject({ running: false, exitCode: 3, output: "" }) const unknown = yield* read({ shellID: "sh_missing" }) expect(unknown.status).toBe("error") expect(unknown.error?.message).toContain("sh_missing is not a shell command of this session.") }), ) }), { timeout: 20_000 }, ) codeModeIt.live("a background command shell_read saw exit is not notified again", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const notices = yield* syntheticNotices // A direct background command, which is notified when it exits. const started = yield* executeTool( registry, call({ command: progressOverflowCommand(0, "release"), background: true }), { tools: { direct: new Set(["shell"]) } }, ) const shellID = String(started.metadata?.shellID) const waiting = yield* executeTool( registry, codeModeCall({ shellID, wait_ms: 60_000 }, "call-read", ShellTool.readName), ).pipe(Effect.forkScoped({ startImmediately: true })) yield* Effect.promise(() => Bun.sleep(100)) yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), "")) expect((yield* Fiber.join(waiting)).output).toMatchObject({ shellID, running: false, exitCode: 0 }) yield* outboxCleared expect(yield* Queue.size(notices)).toBe(0) }), ) }), ) codeModeIt.live("stop kills a yielded command and reports what it stopped", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const notices = yield* syntheticNotices const started = yield* executeTool(registry, codeModeCall({ command: idleCommand, yield_ms: 50 })) const shellID = ID.make(String(started.output.shellID)) const stop = (ids: string[], id: string) => executeTool(registry, codeModeCall({ ids }, id, StopTool.name)) const stopped = yield* stop([shellID, "sh_missing"], "call-stop") expect(stopped.output).toEqual({ stopped: [shellID], notRunning: ["sh_missing"] }) expect(stopped.content).toEqual([ { type: "text", text: `Stopped ${shellID}.\nNot running background work of this session: sh_missing.`, }, ]) const shell = yield* Shell.Service expect((yield* shell.wait(shellID)).status).toBe("killed") yield* outboxCleared expect((yield* stop([shellID], "call-stop-again")).output).toEqual({ stopped: [], notRunning: [shellID] }) // A shell_read waiting on the command doesn't hold the stop up, and sees the command end. const other = yield* executeTool(registry, codeModeCall({ command: idleCommand, yield_ms: 50 }, "call-other")) const otherID = String(other.output.shellID) const reading = yield* executeTool( registry, codeModeCall({ shellID: otherID, wait_ms: 60_000 }, "call-read", ShellTool.readName), ).pipe(Effect.forkScoped({ startImmediately: true })) yield* Effect.promise(() => Bun.sleep(100)) expect((yield* stop([otherID], "call-stop-read").pipe(Effect.timeout("3 seconds"))).output).toEqual({ stopped: [otherID], notRunning: [], }) expect((yield* Fiber.join(reading).pipe(Effect.timeout("3 seconds"))).output).toMatchObject({ running: false, exitCode: null, }) yield* outboxCleared expect(yield* Queue.size(notices)).toBe(0) }), ) }), ) productionIt.live( "registers and returns real successful output from the active Location", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const definitions = yield* toolDefinitions(registry) const definition = definitions.find((tool) => tool.name === "shell") expect(definition?.description).toStartWith("Execute a shell command and return its output.") expect(definition?.inputSchema).not.toHaveProperty("properties.timeout.maximum") // Code Mode receives the declared output schema, including the command output text. expect(definition?.outputSchema).toHaveProperty("properties.output") expect( (yield* toolDefinitions(registry, [{ action: "shell", resource: "*", effect: "deny" }])).map( (tool) => tool.name, ), ).not.toContain("shell") const settled = yield* executeTool(registry, call({ command: helloCommand })) expect(settled.status).toBe("completed") expect(settled.metadata).toMatchObject({ exit: 0, truncated: false }) expect(settled.content).toEqual([{ type: "text", text: "hello" }]) expect(assertions).toMatchObject([ { sessionID, action: "shell", resources: isWindows ? ["[Console]::Out.Write('hello')", "Start-Sleep -Milliseconds 100"] : [helloCommand], agent: toolIdentity.agent, source: { type: "tool", messageID: toolIdentity.messageID, id: "call-shell" }, }, ]) expect(assertions[0]?.save).toEqual(isWindows ? ["[Console]::Out.Write(*", "Start-Sleep *"] : ["printf *"]) }), ) }), { timeout: 15_000 }, ) productionIt.live( "uses the session environment instead of the server environment", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const sessions = yield* Session.Service yield* sessions.environment({ sessionID, variables: { OPENCODE_SESSION_ENV_TEST: "from-session" }, }) const command = isWindows ? "[Console]::Out.Write($env:OPENCODE_SESSION_ENV_TEST)" : 'printf %s "$OPENCODE_SESSION_ENV_TEST"' const settled = yield* executeTool(registry, call({ command })) expect(settled.status).toBe("completed") expect(settled.content?.[0]).toEqual({ type: "text", text: "from-session" }) }), ) }), { timeout: 15_000 }, ) productionIt.live( "identifies agent shell commands without inheriting a stale session ID", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const sessions = yield* Session.Service yield* sessions.environment({ sessionID, variables: { AGENT: "0", OPENCODE: "0", AI_AGENT: "", OPENCODE_SESSION_ID: "stale" }, }) const command = isWindows ? '[Console]::Out.Write("$env:AGENT|$env:OPENCODE|$env:AI_AGENT|$env:OPENCODE_SESSION_ID")' : 'printf %s "$AGENT|$OPENCODE|$AI_AGENT|$OPENCODE_SESSION_ID"' const settled = yield* executeTool(registry, call({ command })) expect(settled.status).toBe("completed") expect(settled.content?.[0]).toEqual({ type: "text", text: `1|1|opencode|${sessionID}` }) }), ) }), { timeout: 15_000 }, ) productionIt.live( "preserves an outer AI_AGENT marker in agent shell commands", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const sessions = yield* Session.Service yield* sessions.environment({ sessionID, variables: { AI_AGENT: "outer-agent" } }) const command = isWindows ? "[Console]::Out.Write($env:AI_AGENT)" : 'printf %s "$AI_AGENT"' const settled = yield* executeTool(registry, call({ command })) expect(settled.status).toBe("completed") expect(settled.content?.[0]).toEqual({ type: "text", text: "outer-agent" }) }), ) }), { timeout: 15_000 }, ) it.live("resolves a relative workdir from the active Location", () => withTempDir((tmp) => { reset() return Effect.promise(() => fs.mkdir(path.join(tmp.path, "src"))).pipe( Effect.andThen( withSession(tmp.path, (registry) => executeTool(registry, call({ command: cwdCommand, workdir: "src" }))), ), Effect.andThen((settled) => Effect.sync(() => expect(settled.content?.[0]).toMatchObject( Expected.text(expect.stringContaining(realpathSync(path.join(tmp.path, "src")))), ), ), ), ) }), ) it.live("reports a missing workdir", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => executeTool(registry, call({ command: cwdCommand, workdir: "missing" })), ).pipe( Effect.andThen((settled) => Effect.sync(() => expect(settled).toEqual({ status: "error", error: { type: "unknown", message: `Working directory does not exist: ${path.join(tmp.path, "missing")}`, }, }), ), ), ) }), ) it.live( "permissions compound commands separately", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => executeTool(registry, call({ command: "printf one && printf two" }, "call-compound")), ).pipe( Effect.andThen( Effect.sync(() => { expect(assertions).toHaveLength(1) expect(assertions[0]).toMatchObject({ resources: ["printf one", "printf two"], save: ["printf *", "printf *"], }) }), ), ) }), { timeout: 15_000 }, ) it.live( "captures stderr-only and mixed stdout/stderr output", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const stderr = yield* executeTool(registry, call({ command: stderrCommand }, "call-stderr")) expect(stderr.metadata).toMatchObject({ exit: 0, truncated: false }) expect(stderr.content?.[0]).toEqual({ type: "text", text: "stderr only" }) const mixed = yield* executeTool(registry, call({ command: mixedOutputCommand }, "call-mixed")) expect(mixed.metadata).toMatchObject({ exit: 0, truncated: false }) const output = mixed.content?.[0]?.type === "text" ? mixed.content[0].text : "" expect(output).toContain("stdout") expect(output).toContain("stderr") }), ) }), { timeout: 15_000 }, ) it.live("rejects a workdir that stops being a directory during approval", () => withTempDir((tmp) => { reset() const workdir = path.join(tmp.path, "src") afterPermission = (input) => input.action === "shell" ? Effect.promise(async () => { await fs.rm(workdir, { recursive: true }) await fs.writeFile(workdir, "not a directory") }).pipe(Effect.orDie) : Effect.void return Effect.promise(() => fs.mkdir(workdir)).pipe( Effect.andThen( withSession(tmp.path, (registry) => executeTool(registry, call({ command: cwdCommand, workdir: "src" }))), ), Effect.andThen((settled) => Effect.sync(() => { expect(settled).toMatchObject({ status: "error", error: { message: `Working directory is not a directory: ${workdir}` }, }) expect(assertions.map((input) => input.action)).toEqual(["shell"]) }), ), ) }), ) it.live( "approves an explicit external workdir before shell execution", () => Effect.acquireUseRelease( Effect.promise(() => Promise.all([tmpdir(), tmpdir()])), ([active, outside]) => { reset() return withSession(active.path, (registry) => executeTool(registry, call({ command: cwdCommand, workdir: outside.path })), ).pipe( Effect.andThen( Effect.sync(() => { expect(assertions.map((item) => item.action)).toEqual(["external_directory", "shell"]) expect(assertions[0]).toMatchObject({ resources: [path.join(realpathSync(outside.path), "*").replaceAll("\\", "/")], }) }), ), ) }, ([active, outside]) => Effect.promise(() => Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined), ), ), { timeout: 15_000 }, ) it.live( "deduplicates external directory approvals across workdir and directory-change commands", () => Effect.acquireUseRelease( Effect.promise(() => Promise.all([tmpdir(), tmpdir()])), ([active, outside]) => { const command = isWindows ? `Set-Location -LiteralPath '${outside.path}'; (Get-Location).Path` : `cd '${outside.path}' && pwd` return withSession(active.path, (registry) => Effect.forEach([{ command }, { command, workdir: outside.path }], (input) => Effect.gen(function* () { reset() const settled = yield* executeTool(registry, call(input, "call-external-cd")) expect(settled).toMatchObject({ status: "completed" }) expect(assertions.map((item) => item.action)).toEqual(["external_directory", "shell"]) expect(assertions[0]).toMatchObject({ resources: [path.join(realpathSync(outside.path), "*").replaceAll("\\", "/")], sessionID, agent: toolIdentity.agent, source: { type: "tool", messageID: toolIdentity.messageID, id: "call-external-cd" }, }) }), ), ) }, ([active, outside]) => Effect.promise(() => Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined), ), ), { timeout: 15_000 }, ) it.live("approves an expanded external home directory", () => withTempDir((tmp) => { reset() const command = isWindows ? "Set-Location $HOME; (Get-Location).Path" : "cd ~ && pwd" return withSession(tmp.path, (registry) => executeTool(registry, call({ command }, "call-external-home"))).pipe( Effect.andThen( Effect.sync(() => { expect(assertions.map((item) => item.action)).toEqual(["external_directory", "shell"]) expect(assertions[0]?.resources[0]).toStartWith(os.homedir().replaceAll("\\", "/")) }), ), ) }), ) it.live( "does not execute after external-directory or shell denial", () => Effect.acquireUseRelease( Effect.promise(() => Promise.all([tmpdir(), tmpdir()])), ([active, outside]) => Effect.gen(function* () { reset() denyAction = "external_directory" yield* withSession(active.path, (registry) => executeTool(registry, call({ command: cwdCommand, workdir: outside.path })), ) expect(assertions.map((item) => item.action)).toEqual(["external_directory"]) reset() denyAction = "shell" yield* withSession(active.path, (registry) => executeTool(registry, call({ command: cwdCommand }))) expect(assertions.map((item) => item.action)).toEqual(["shell"]) }), ([active, outside]) => Effect.promise(() => Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined), ), ), { timeout: 15_000 }, ) it.live("asks for malformed syntax across channels without partial execution", () => Effect.gen(function* () { if (isWindows) return for (const channel of ["local", "dev", "latest"] as const) { const channelSupervisor = makeLocationNode({ name: `test/shell-plugins-${channel}`, layer: Layer.effectDiscard( registerToolPlugin(ShellTool.Plugin, { app: { name: "opencode", version: "test", channel }, }), ), deps: [ Agent.node, Config.node, Environment.node, FileAccess.node, Flag.node, Permission.node, Session.node, Job.node, Location.node, Shell.node, Shell.daemonNode, ShellSelect.node, Bus.node, Tool.node, ], }) yield* withTempDir((tmp) => Effect.gen(function* () { reset() denyAction = "shell" const command = 'printf hello > marker\necho "' const settled = yield* withSession(tmp.path, (registry) => Effect.gen(function* () { const selection = yield* ShellSelect.Service yield* selection.transform((editor) => editor.configure("sh")) return yield* executeTool(registry, call({ command }, `call-channel-${channel}`)) }), ) expect(settled).toMatchObject({ status: "error", error: { message: expect.stringContaining("Permission denied: shell") }, }) expect(assertions).toMatchObject([ { action: "external_directory", resources: ["*"], save: undefined }, { action: "shell", resources: [command], save: undefined, metadata: { reason: "unterminated-quote" } }, ]) expect(yield* Effect.promise(() => Bun.file(path.join(tmp.path, "marker")).exists())).toBe(false) }).pipe( Effect.provide( AppNodeBuilder.build(nodes, [...replacements, PluginSupervisor.node.replace(channelSupervisor)]), ), ), ) } }), ) for (const shell of ["sh", "zsh"]) { const test = isWindows || !Bun.which(shell) ? it.live.skip : it.live test( `preserves arithmetic and directory permissions in ${shell}`, () => withTempDir((tmp) => Effect.gen(function* () { reset() yield* Effect.promise(() => fs.mkdir(path.join(tmp.path, "one", "two"), { recursive: true })) yield* withSession(tmp.path, (registry) => Effect.gen(function* () { const selection = yield* ShellSelect.Service yield* selection.transform((editor) => editor.configure(shell)) for (const [command, output] of [ ["echo $((1 + 1))", "2\n"], ["cd ~ && pwd", `${realpathSync(os.homedir())}\n`], ["cd one&&cd two&&pwd", `${path.join(tmp.path, "one", "two")}\n`], ]) { const settled = yield* executeTool(registry, call({ command }, `call-parity-${command}`)) expect(settled.status).toBe("completed") expect(settled.metadata).toMatchObject({ exit: 0 }) expect(settled.content?.[0]).toMatchObject({ type: "text", text: output }) } }), ) expect(assertions.map((item) => item.action)).toEqual(["shell", "external_directory", "shell", "shell"]) expect(assertions[1]?.resources).toEqual([path.join(realpathSync(os.homedir()), "*")]) expect(assertions[0]).toMatchObject({ resources: ["echo $((1 + 1))"], save: ["echo *"] }) expect(assertions[2]).toMatchObject({ resources: ["pwd"], save: ["pwd *"] }) expect(assertions[3]).toMatchObject({ resources: ["pwd"], save: ["pwd *"] }) }), ), { timeout: 15_000 }, ) } parity.live("keeps non-zero exits useful", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => executeTool(registry, call({ command: bodyExitCommand }, "call-nonzero")), ).pipe( Effect.andThen((settled) => Effect.sync(() => { expect(settled.status).toBe("completed") expect(settled.metadata).toMatchObject({ exit: 7, truncated: false }) expect(settled.content).toEqual([ { type: "text", text: "body" }, { type: "text", text: "Exit code: 7" }, ]) }), ), ) }), ) it.live( "puts the exit status after the truncation marker when overflowing output fails", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => executeTool( registry, call( { command: `${overflowCommand(ToolOutput.MAX_BYTES + 1024)}${isWindows ? "; exit 3" : " && exit 3"}` }, "call-overflow-nonzero", ), ), ).pipe( Effect.andThen((settled) => Effect.sync(() => { expect(settled.metadata).toMatchObject({ exit: 3, truncated: true, }) expect(settled.output).toEqual({ output: expect.stringContaining(`full output saved to ${settled.output.outputPath}]`), outputPath: expect.any(String), exitCode: 3, wallTimeSeconds: expect.any(Number), }) expect(settled.content).toEqual([ Expected.text( expect.stringMatching( /output-end[^]*\[showing the last 50 KB of line 1 \(51 KB\); full output saved to [^\]]+\]$/, ), ), { type: "text", text: "Exit code: 3" }, ]) }), ), ) }), { timeout: 15_000 }, ) it.live("moves a foreground timeout to the background and delivers its original process result once", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const bus = yield* Bus.Service const notices = yield* Queue.unbounded() yield* bus.subscribe(SessionEvent.InboxEnqueued).pipe( Stream.filter((event) => event.data.sessionID === sessionID && event.data.item.type === "synthetic"), Stream.runForEach((event) => Queue.offer(notices, event.data.item.payload)), Effect.forkScoped({ startImmediately: true }), ) const result = yield* executeTool( registry, call({ command: progressOverflowCommand(6, "release"), timeout: 10 }, "call-auto-background"), ) const id = ID.make(String(result.metadata?.shellID)) const shell = yield* Shell.Service const info = yield* shell.get(id) expect(result.status).toBe("completed") expect(info.pid).toBeGreaterThan(0) expect(result.metadata).toMatchObject({ status: "running", shellID: id, pid: info.pid, truncated: false, }) expect(result.output).toEqual({ shellID: id, pid: info.pid, outputPath: info.file, exitCode: null, output: expect.any(String), wallTimeSeconds: expect.any(Number), }) expect(result.output.wallTimeSeconds).toBeGreaterThanOrEqual(0.01) expect(result.metadata).not.toHaveProperty("timeout") expect(result.content?.[0]).toEqual({ type: "text", text: `Command moved to the background (shell ID: ${id}).\nPID: ${info.pid}\nOutput is streaming to: ${info.file}\n\nThe command did not finish within its timeout of 0.01 seconds and was moved to the background. Do not start another copy while it is running.`, }) expect(info.status).toBe("running") expect((yield* shell.list()).map((item) => item.id)).toEqual([id]) yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), "")) const finished = yield* shell.wait(id) expect(finished).toMatchObject({ status: "exited", exit: 0, pid: info.pid, }) expect(yield* Queue.take(notices)).toMatchObject({ text: expect.stringContaining("xxxxxx"), metadata: { source: "shell", shellID: id, state: "completed", exit: 0, }, }) expect(yield* Queue.size(notices)).toBe(0) expect(yield* shell.list()).toEqual([]) }), ) }), ) it.live("returns a fast foreground result directly", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const result = yield* executeTool(registry, call({ command: helloCommand, timeout: 10_000 })) expect(result.metadata).toMatchObject({ status: "completed", exit: 0 }) expect(result.content).toEqual([{ type: "text", text: "hello" }]) const jobs = yield* Job.Service expect(yield* jobs.runningBackground).toEqual([]) }), ) }), ) it.live("preserves a timeout-promoted command's eventual failure", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const bus = yield* Bus.Service const admitted = yield* bus.subscribe(SessionEvent.InboxEnqueued).pipe( Stream.filter((event) => event.data.sessionID === sessionID && event.data.item.type === "synthetic"), Stream.runHead, Effect.forkScoped({ startImmediately: true }), ) const result = yield* executeTool( registry, call({ command: `${progressOverflowCommand(0, "release")}; exit 7`, timeout: 10 }), ) const id = ID.make(String(result.metadata?.shellID)) yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), "")) const shell = yield* Shell.Service expect(yield* shell.wait(id)).toMatchObject({ status: "exited", exit: 7 }) expect((yield* Fiber.join(admitted)).valueOrUndefined?.data.item.payload).toMatchObject({ text: expect.stringContaining("Exit code: 7"), metadata: { source: "shell", shellID: id, state: "completed", exit: 7 }, }) }), ) }), ) it.effect("treats a foreground timeout of zero as the default timeout", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const running = yield* executeTool( registry, call({ command: progressOverflowCommand(0, "release"), timeout: 0 }, "call-zero-timeout"), ).pipe(Effect.forkScoped({ startImmediately: true })) // The wait starts only after the command spawns, so keep advancing the clock until the call returns. const result = yield* Fiber.join(running).pipe( Effect.raceFirst( Effect.forever(Effect.promise(() => Bun.sleep(20)).pipe(Effect.andThen(TestClock.adjust("2 minutes")))), ), ) expect(result.content?.[0]).toMatchObject({ type: "text", text: expect.stringContaining("did not finish within its timeout of 120 seconds"), }) const id = ID.make(String(result.metadata?.shellID)) const shell = yield* Shell.Service expect((yield* shell.get(id)).status).toBe("running") yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), "")) expect(yield* shell.wait(id)).toMatchObject({ status: "exited", exit: 0 }) }), ) }), ) it.live("still cancels a timeout-promoted shell through its existing job handle", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const result = yield* executeTool( registry, call({ command: progressOverflowCommand(0, "release"), timeout: 10 }), ) const id = ID.make(String(result.metadata?.shellID)) const shell = yield* Shell.Service expect((yield* shell.get(id)).status).toBe("running") const jobs = yield* Job.Service expect(yield* jobs.cancel(id)).toMatchObject({ id, status: "cancelled" }) // Cancelling stops the command and keeps it, output file included. expect((yield* shell.wait(id)).status).toBe("killed") expect(yield* shell.list()).toEqual([]) }), ) }), ) it.live("stops a background command when its explicit timeout expires", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const result = yield* executeTool(registry, call({ command: idleCommand, background: true, timeout: 50 })) const id = ID.make(String(result.metadata?.shellID)) const shell = yield* Shell.Service expect((yield* shell.wait(id)).status).toBe("timeout") }), ) }), ) // Runs a program the way an automation does: no model, and the automation named on each tool call. const runAutomationCode = (registry: Tool.Interface, code: string) => Effect.gen(function* () { yield* registry.transform((editor) => editor.update("shell", (tool) => { tool.options = { ...tool.options, codemode: true } }), ) return yield* registry.check({ code, tools: ["shell"], bindings: {}, policy: Permission.Policy.fromRules([{ action: "*", resource: "*", effect: "allow" }]), limits: { timeoutMs: 30_000, maxOutputBytes: 32 * 1024 }, context: { sessionID, ...toolIdentity, progress: () => Effect.void, automation: { id: Automation.ID.make("aut_shell_test") }, }, }) }) it.live("stops an automation's command at its timeout and fails the call", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const result = yield* runAutomationCode( registry, `try { await tools.shell({ command: ${JSON.stringify(idleCommand)}, timeout: 50 }); return "finished" } catch (error) { return error.message }`, ) expect(result).toMatchObject({ ok: true, value: expect.stringMatching( new RegExp(`Command timed out after 0\\.05 seconds\\. [^\\n]+\\nExit code: ${timedOutExit}`), ), }) const shell = yield* Shell.Service expect(yield* shell.list()).toEqual([]) }), ) }), ) it.live("keeps an automation's command out of reach of the session's move to the background", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const command = JSON.stringify(progressOverflowCommand(0, "release")) const running = yield* runAutomationCode( registry, `return await tools.shell({ command: ${command}, timeout: 10000 })`, ).pipe(Effect.forkScoped({ startImmediately: true })) const shell = yield* Shell.Service const [started] = yield* shell .list() .pipe( Effect.repeat({ until: (shells) => shells.length > 0, schedule: Schedule.spaced("10 millis") }), Effect.timeout("10 seconds"), ) const jobs = yield* Job.Service expect(yield* jobs.backgroundAll({ sessionID })).toEqual([]) yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), "")) expect(yield* Fiber.join(running)).toMatchObject({ ok: true, value: { exitCode: 0 } }) // A finished job stays listed, so this proves the command never had one for the session to take. expect(yield* jobs.get(started!.id)).toBeUndefined() }), ) }), ) it.live( "truncates the model view and points at the saved output file when output overflows", () => withTempDir((tmp) => { reset() const bytes = ToolOutput.MAX_BYTES + 1024 return withSession(tmp.path, (registry) => executeTool(registry, call({ command: overflowCommand(bytes) }, "call-overflow")), ).pipe( Effect.andThen((settled) => Effect.sync(() => { expect(settled.metadata).toMatchObject({ exit: 0, truncated: true }) const content = settled.content?.[0] if (!content || content.type !== "text") throw new Error("Expected text content") expect(settled.content).toHaveLength(1) expect(content.text.includes("output-start")).toBe(false) expect(content.text.includes("output-end")).toBe(true) expect(content).toMatchObject(Expected.text(expect.stringContaining("full output saved to "))) }), ), ) }), { timeout: 15_000 }, ) parity.live("uses configured line limits", () => withTempDir((tmp) => { reset() return Effect.gen(function* () { yield* Effect.promise(() => Bun.write( path.join(tmp.path, "opencode.json"), JSON.stringify({ tool_output: { max_lines: 2, max_bytes: 1_000 } }), ), ) const settled = yield* withSession(tmp.path, (registry) => executeTool(registry, call({ command: lineOverflowCommand }, "call-line-overflow")), ) expect(settled.metadata).toMatchObject({ exit: 0, truncated: true }) const content = settled.content?.[0] if (!content || content.type !== "text") throw new Error("Expected text content") expect(content.text).not.toContain("one") // Windows shells emit CRLF; the assertion targets line limits, not line endings. expect(content.text.replaceAll("\r\n", "\n")).toStartWith("two\nthree") expect(content.text).toContain("full output saved to ") }) }), ) const truncatedText = (tmp: string, contents: string | Uint8Array, callID: string) => Effect.gen(function* () { const file = path.join(tmp, `${callID}.txt`) yield* Effect.promise(() => Bun.write(file, contents)) const settled = yield* withSession(tmp, (registry) => executeTool(registry, call({ command: catCommand(file) }, callID)), ) expect(settled.metadata).toMatchObject({ exit: 0, truncated: true }) const content = settled.content?.[0] if (!content || content.type !== "text") throw new Error("Expected text content") return content.text }) it.live("drops the partial first line so the truncation note counts only whole lines", () => withTempDir((tmp) => { reset() const lines = Array.from({ length: 10 }, (_, index) => `${index + 1}`.padEnd(10 * 1024, "x")) return truncatedText(tmp.path, lines.join("\n") + "\n", "call-long-lines").pipe( Effect.andThen((text) => Effect.sync(() => { expect(text).toStartWith(`7xxx`) expect(text).toContain(`${lines[9]}\n\n[showing lines 7-10 of 10; full output saved to `) }), ), ) }), ) it.live("says how much of a single long line is shown", () => withTempDir((tmp) => { reset() return truncatedText(tmp.path, "head\n" + "x".repeat(200 * 1024), "call-long-line").pipe( Effect.andThen((text) => Effect.sync(() => { expect(text).toStartWith("x".repeat(ToolOutput.MAX_BYTES) + "\n\n") expect(text).toContain("[showing the last 50 KB of line 2 (200 KB); full output saved to ") }), ), ) }), ) it.live("starts the truncated view on a whole UTF-8 character", () => withTempDir((tmp) => { reset() // The window starts on the last byte of the three-byte euro sign. const contents = "a".repeat(100) + "€" + "b".repeat(ToolOutput.MAX_BYTES - 1) return truncatedText(tmp.path, contents, "call-utf8-cut").pipe( Effect.andThen((text) => Effect.sync(() => { expect(text).toStartWith("b".repeat(ToolOutput.MAX_BYTES - 1) + "\n\n") expect(text).not.toContain("\uFFFD") }), ), ) }), ) it.live("numbers lines exactly when the line limit truncates", () => withTempDir((tmp) => { reset() const lines = Array.from({ length: 2500 }, (_, index) => `line ${index + 1}`) return truncatedText(tmp.path, lines.join("\n") + "\n", "call-many-lines").pipe( Effect.andThen((text) => Effect.sync(() => { expect(text).toStartWith("line 501\n") expect(text).toContain("line 2500\n\n[showing lines 501-2500 of 2500; full output saved to ") }), ), ) }), ) it.live( "reports the shell ID for a running command", () => withTempDir((tmp) => { reset() const release = "shell-progress-release" const releasePath = path.join(tmp.path, release) return withSession(tmp.path, (registry) => Effect.gen(function* () { const observed = yield* Deferred.make() yield* executeTool(registry, { ...call({ command: progressOverflowCommand(ToolOutput.MAX_BYTES + 1024, release) }, "call-progress"), progress: (update) => Effect.gen(function* () { if (typeof update.shellID !== "string") return yield* Deferred.succeed(observed, update.shellID) yield* Effect.promise(() => fs.writeFile(releasePath, "")) }), }) expect(yield* Deferred.await(observed)).toMatch(/^sh_/) }).pipe(Effect.ensuring(Effect.promise(() => fs.writeFile(releasePath, "")).pipe(Effect.ignore))), ) }), { timeout: 15_000 }, ) it.live( "reports shell ID progress once", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const updates: Tool.Metadata[] = [] yield* executeTool(registry, { ...call({ command: helloCommand }, "call-shell-id-progress"), progress: (update) => Effect.sync(() => updates.push(update)), }) expect(updates).toHaveLength(1) expect(updates[0]?.shellID).toMatch(/^sh_/) }), ) }), { timeout: 15_000 }, ) it.live("names the tool call and background on the spans of the shell it starts", () => withTempDir((tmp) => { reset() const spans: Tracer.NativeSpan[] = [] const tracer = Tracer.make({ span(options) { const span = new Tracer.NativeSpan(options) spans.push(span) return span }, }) return withSession(tmp.path, (registry) => Effect.gen(function* () { yield* executeTool(registry, call({ command: bodyExitCommand }, "call-traced")) yield* executeTool(registry, call({ command: helloCommand, background: true }, "call-traced-background")) }), ).pipe( Effect.withTracer(tracer), Effect.andThen( Effect.sync(() => { const attributes = (name: string, callID: string) => spans .filter((span) => span.name === name && span.attributes.get("gen_ai.tool.call.id") === callID) .map((span) => Object.fromEntries(span.attributes)) expect(attributes("Shell.create", "call-traced")).toEqual([ expect.objectContaining({ "session.id": sessionID, "opencode.shell.command": bodyExitCommand }), ]) expect(attributes("Shell.create", "call-traced")[0]).not.toHaveProperty("opencode.shell.background") expect(attributes("Shell.result", "call-traced")).toEqual([ expect.objectContaining({ "session.id": sessionID, "process.exit.code": 7 }), ]) expect(attributes("Shell.create", "call-traced-background")).toEqual([ expect.objectContaining({ "session.id": sessionID, "opencode.shell.background": true }), ]) }), ), ) }), ) fakeDaemonIt.live("keeps a background daemon command's job across a Location reload and reports how it ended", () => withTempDir((tmp) => Effect.gen(function* () { reset() const sessions = yield* Session.Service const jobs = yield* Job.Service const bus = yield* Bus.Service const locations = yield* LocationServiceMap.Service const location = Location.Ref.make({ directory: AbsolutePath.make(tmp.path) }) yield* sessions.create({ id: sessionID, title: "shell test", location, model: sessionModel }) const admitted = yield* bus.subscribe(SessionEvent.InboxEnqueued).pipe( Stream.filter((event) => event.data.sessionID === sessionID && event.data.item.type === "synthetic"), Stream.take(2), Stream.runCollect, Effect.forkScoped({ startImmediately: true }), ) const started = yield* Effect.gen(function* () { const plugins = yield* Plugin.Service yield* plugins.awaitActivation const registry = yield* Tool.Service const shell = yield* Shell.Service const run = (id: string) => Effect.gen(function* () { const settled = yield* executeTool(registry, call({ command: "work", background: true }, id)) return yield* shell.get(ID.make(String(settled.metadata?.shellID))) }) return { finishing: yield* run("call-finishing"), cancelled: yield* run("call-cancelled") } }).pipe(Effect.provide(locations.get(location))) const process = (info: { file: string }) => { const found = fake?.processes.find((item) => item.pipe?.output_path === info.file) if (!found) throw new Error("no daemon process for the command") return found.id } // A reload closes the Location and boots its replacement, which takes the commands back. yield* locations.invalidate(location) const replacement = yield* Effect.gen(function* () { return yield* Shell.Service }).pipe(Effect.provide(locations.get(location))) expect((yield* replacement.list()).map((info) => info.id).toSorted()).toEqual( [started.finishing.id, started.cancelled.id].toSorted(), ) expect((yield* jobs.get(started.finishing.id))?.status).toBe("running") // Cancelling the session's job still stops its command. yield* jobs.cancel(started.cancelled.id) while (!fake?.ops.includes("signal")) yield* Effect.promise(() => Bun.sleep(2)) expect(fake?.requests).toContainEqual( expect.objectContaining({ op: "signal", id: process(started.cancelled), signal: "SIGTERM" }), ) fake?.output(process(started.finishing), "done\n") fake?.exit(process(started.finishing), 0) const notices = Array.from(yield* Fiber.join(admitted)).map((event) => event.data.item.payload) expect(notices).toContainEqual( expect.objectContaining({ text: expect.stringContaining("done"), metadata: expect.objectContaining({ shellID: started.finishing.id, state: "completed", exit: 0 }), }), ) expect(notices).toContainEqual( expect.objectContaining({ metadata: expect.objectContaining({ shellID: started.cancelled.id, state: "cancelled" }), }), ) expect((yield* jobs.get(started.finishing.id))?.status).toBe("completed") expect((yield* replacement.get(started.finishing.id)).status).toBe("exited") yield* locations.invalidate(location) }), ), ) parity.live("returns the shell id and PID for a background command", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const bus = yield* Bus.Service const admitted = yield* bus.subscribe(SessionEvent.InboxEnqueued).pipe( Stream.filter((event) => event.data.sessionID === sessionID && event.data.item.type === "synthetic"), Stream.runHead, Effect.forkScoped({ startImmediately: true }), ) const settled = yield* executeTool(registry, call({ command: idleCommand, timeout: 50, background: true })) const shellID = typeof settled.metadata?.shellID === "string" ? settled.metadata.shellID : undefined expect(settled.metadata).toMatchObject({ truncated: false }) expect(shellID).toStartWith("sh_") const shell = yield* Shell.Service if (!shellID) return const id = ID.make(shellID) const info = yield* shell.get(id) expect(info.pid).toBeGreaterThan(0) expect(settled.metadata).toMatchObject({ pid: info.pid }) expect(settled.output).toMatchObject({ shellID, pid: info.pid }) expect(settled.content).toEqual([ { type: "text", text: `Command moved to the background (shell ID: ${shellID}).\nPID: ${info.pid}\nOutput is streaming to: ${info.file}`, }, { type: "text", text: "You will be notified automatically when the command finishes. The notification will include the command's output. Unless the user explicitly asks otherwise, DO NOT poll for completion, even if you need the final result to continue. Repeatedly sleeping and reading or searching the output file is polling, not useful work. You may read the current output if it lets you do useful work now, but do not repeatedly check it while waiting for the command to finish. Keep working on anything that does not depend on the result. If you have nothing else to do, end your response; you will be resumed automatically when the command finishes.", }, ]) expect((yield* shell.list()).map((info) => info.id)).toContain(id) const timedOut = yield* shell.wait(id) expect(timedOut.status).toBe("timeout") // The timeout keeps its status but still records how the killed process exited. expect(timedOut.exit !== undefined || timedOut.signal !== undefined).toBe(true) if (!isWindows) expect(timedOut).toMatchObject({ signal: "SIGTERM" }) expect((yield* Fiber.join(admitted)).valueOrUndefined?.data.item.payload).toMatchObject({ text: expect.stringMatching( new RegExp( `\\nCommand timed out after 0\\.05 seconds\\. If it needs longer and isn't waiting for input, rerun with a larger timeout\\.\\nExit code: ${timedOutExit}\\n$`, ), ), description: idleCommand, metadata: { source: "shell", shellID, state: "completed", timeout: true, truncated: false, }, }) }), ) }), ) it.live("preserves a background command's non-zero exit", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const bus = yield* Bus.Service const admitted = yield* bus.subscribe(SessionEvent.InboxEnqueued).pipe( Stream.filter((event) => event.data.sessionID === sessionID && event.data.item.type === "synthetic"), Stream.runHead, Effect.forkScoped({ startImmediately: true }), ) const settled = yield* executeTool( registry, call({ command: bodyExitCommand, background: true }, "call-background-nonzero"), ) const shellID = settled.metadata?.shellID expect(typeof shellID).toBe("string") expect((yield* Fiber.join(admitted)).valueOrUndefined?.data.item.payload).toMatchObject({ text: `\nbody\n\nExit code: 7\n`, description: bodyExitCommand, metadata: { source: "shell", jobID: shellID, shellID, state: "completed", exit: 7, truncated: false, }, }) }), ) }), ) it.live("persists a silent command that finishes before backgrounding", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const bus = yield* Bus.Service const jobs = yield* Job.Service const shell = yield* Shell.Service const persisted = yield* Deferred.make() yield* bus.project(SessionEvent.InboxEnqueued, (event) => event.data.sessionID === sessionID && event.data.item.type === "synthetic" ? jobs.pendingBackground.pipe( Effect.flatMap((background) => Deferred.succeed(persisted, background)), Effect.asVoid, ) : Effect.void, ) const settled = yield* executeTool(registry, { ...call({ command: "exit 7", background: true }, "call-background-silent-nonzero"), // The command can finish while its initial progress update is being published. progress: (update) => typeof update.shellID === "string" ? shell.wait(ID.make(update.shellID)).pipe(Effect.orDie, Effect.asVoid) : Effect.void, }) expect(yield* Deferred.await(persisted)).toMatchObject([ { id: settled.metadata?.shellID, status: "completed", output: "(no output)\n\nExit code: 7", }, ]) }), ) }), ) it.live( "updates and clears a running shell timeout", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const shell = yield* Shell.Service const timed = yield* executeTool( registry, call({ command: idleCommand, background: true }, "call-updated-timeout"), ) const timedID = timed.metadata?.shellID expect(typeof timedID).toBe("string") if (typeof timedID !== "string") return const timedShellID = ID.make(timedID) yield* shell.timeout(timedShellID, 50) expect((yield* shell.wait(timedShellID)).status).toBe("timeout") const cleared = yield* executeTool( registry, call({ command: idleCommand, timeout: 50, background: true }, "call-cleared-timeout"), ) const clearedID = cleared.metadata?.shellID expect(typeof clearedID).toBe("string") if (typeof clearedID !== "string") return const clearedShellID = ID.make(clearedID) yield* shell.timeout(clearedShellID, 0) yield* Effect.sleep(Duration.millis(100)) expect((yield* shell.get(clearedShellID)).status).toBe("running") yield* shell.remove(clearedShellID) }), ) }), { timeout: 15_000 }, ) const signalParity = isWindows ? parity.skip : parity.live signalParity( "escalates a shell timeout when the ready process ignores SIGTERM", () => Effect.gen(function* () { const tmp = yield* tmpdirScoped() const ready = yield* Deferred.make() yield* Effect.acquireRelease( Effect.sync(() => watch(tmp.path, (_event, filename) => { if (filename === "ready") Deferred.doneUnsafe(ready, Exit.void) }), ), (watcher) => Effect.sync(() => watcher.close()), ) yield* withSession(tmp.path, () => Effect.gen(function* () { const shell = yield* Shell.Service yield* Effect.acquireUseRelease( // Arm the timeout only after the child announces that SIGTERM is ignored. shell.create({ shell: "/bin/sh", command: "trap '' TERM; : > ready; while :; do sleep 60; done", timeout: 0, }), (info) => Effect.gen(function* () { yield* Deferred.await(ready).pipe(Effect.timeout("5 seconds")) yield* shell.timeout(info.id, 1) // Completion must reap the process, not only mark the command as timed out. expect(yield* shell.wait(info.id).pipe(Effect.timeout("10 seconds"))).toMatchObject({ status: "timeout", signal: "SIGKILL", }) const pid = info.pid if (pid === undefined) throw new Error("Expected shell PID") expect(() => process.kill(pid, 0)).toThrow(expect.objectContaining({ code: "ESRCH" })) }), (info) => Effect.try(() => { if (info.pid !== undefined) process.kill(-info.pid, "SIGKILL") }).pipe( Effect.catch(() => Effect.void), Effect.andThen(shell.remove(info.id)), ), ) }), ) }), { timeout: 30_000 }, ) it.live("words the status as an exit code", () => Effect.sync(() => { expect(ShellResult.notice({ exit: 0 })).toBeUndefined() expect(ShellResult.notice({ exit: 7 })).toBe("Exit code: 7") expect(ShellResult.notice({ exit: 143 })).toBe("Exit code: 143") expect(ShellResult.notice({ signal: "SIGTERM" })).toBe("Exit code: 143 (SIGTERM)") expect(ShellResult.notice({ signal: "SIGKILL" })).toBe("Exit code: 137 (SIGKILL)") expect(ShellResult.notice({ signal: "SIGNOPE" })).toBe("Exit code: unknown") expect(ShellResult.notice({ signal: "SIGTERM", timeout: true }, 120_000)).toBe( "Command timed out after 120 seconds. If it needs longer and isn't waiting for input, rerun with a larger timeout.\nExit code: 143 (SIGTERM)", ) expect(ShellResult.notice({ timeout: true })).toBe( "Command timed out. If it needs longer and isn't waiting for input, rerun with a larger timeout.\nExit code: unknown", ) }), ) if (!isWindows) { it.live("settles a shell terminated by an external signal", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const shell = yield* Shell.Service const settled = yield* executeTool( registry, call({ command: idleCommand, background: true }, "call-external-signal"), ) const shellID = settled.metadata?.shellID expect(typeof shellID).toBe("string") if (typeof shellID !== "string") return const id = ID.make(shellID) const info = yield* shell.get(id) expect(typeof info.pid).toBe("number") if (info.pid === undefined) return process.kill(-info.pid, "SIGTERM") const result = yield* shell.wait(id).pipe(Effect.timeoutOption(Duration.seconds(1))) expect(result._tag).toBe("Some") if (result._tag === "Some") expect(result.value).toMatchObject({ status: "exited", signal: "SIGTERM" }) expect((yield* shell.list()).map((item) => item.id)).not.toContain(id) }), ) }), ) } parity.live("backgrounds a foreground command when the session is signaled", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const jobs = yield* Job.Service const scope = yield* Scope.Scope const waiting = yield* executeTool( registry, call({ command: idleCommand, timeout: 50 }, "call-background-signal"), ).pipe(Effect.forkIn(scope, { startImmediately: true })) const backgroundWhenReady = (remaining = 1000): Effect.Effect => Effect.gen(function* () { const backgrounded = yield* jobs.backgroundAll({ sessionID }) if (backgrounded.length > 0) return backgrounded if (remaining <= 0) return yield* Effect.fail(new Error("Timed out waiting for foreground shell job")) yield* Effect.promise(() => Bun.sleep(1)) return yield* backgroundWhenReady(remaining - 1) }) const backgrounded = yield* backgroundWhenReady() const settled = yield* Fiber.join(waiting) const shellID = typeof settled.metadata?.shellID === "string" ? settled.metadata.shellID : undefined expect(backgrounded).toMatchObject([{ id: shellID, type: "shell" }]) expect(settled.metadata).toMatchObject({ truncated: false }) expect(shellID).toStartWith("sh_") const shell = yield* Shell.Service if (!shellID) return const id = ID.make(shellID) const info = yield* shell.get(id) expect(settled.content?.[0]).toEqual({ type: "text", text: `Command moved to the background (shell ID: ${shellID}).\nPID: ${info.pid}\nOutput is streaming to: ${info.file}`, }) expect(settled.content?.[1]).toEqual({ type: "text", text: "You will be notified automatically when the command finishes. The notification will include the command's output. Unless the user explicitly asks otherwise, DO NOT poll for completion, even if you need the final result to continue. Repeatedly sleeping and reading or searching the output file is polling, not useful work. You may read the current output if it lets you do useful work now, but do not repeatedly check it while waiting for the command to finish. Keep working on anything that does not depend on the result. If you have nothing else to do, end your response; you will be resumed automatically when the command finishes.", }) yield* Effect.sleep(Duration.millis(100)) expect((yield* shell.get(id)).status).toBe("running") expect((yield* shell.list()).map((info) => info.id)).toContain(id) yield* shell.remove(id) }), ) }), ) }) describe("ShellTool stopped", () => { // Runs a foreground call the way a session step does, then stops it as the user does (through `cancel`), or // interrupts it as a server shutdown does. const stopCall = ( registry: Tool.Interface, command: string, id: string, how: "cancel" | "interrupt", waitForOutput = true, ) => Effect.gen(function* () { const shell = yield* Shell.Service const cancel = yield* Deferred.make() const started = yield* Deferred.make() const fiber = yield* executeTool(registry, { ...call({ command }, id), progress: (update) => typeof update.shellID === "string" ? Deferred.succeed(started, update.shellID).pipe(Effect.asVoid) : Effect.void, cancel: Deferred.await(cancel), }).pipe(Effect.forkChild({ startImmediately: true })) const shellID = ID.make(yield* Deferred.await(started)) while (waitForOutput && (yield* shell.output(shellID, { cursor: Number.MAX_SAFE_INTEGER })).size === 0) yield* Effect.sleep(Duration.millis(10)) if (how === "cancel") yield* Deferred.succeed(cancel, undefined) if (how === "interrupt") yield* Fiber.interrupt(fiber) const exit = yield* Fiber.await(fiber) return { shellID, exit, result: Exit.isSuccess(exit) ? exit.value : undefined } }) parity.live( "stops a command the user stopped, keeps its file and fails the call with the tail, file and shell ID", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const shell = yield* Shell.Service const jobs = yield* Job.Service const { shellID, result } = yield* stopCall( registry, isWindows ? "[Console]::Out.Write('first' + [char]10 + 'second' + [char]10); Start-Sleep -Seconds 60" : "printf 'first\\nsecond\\n'; sleep 60", "call-stopped", "cancel", ) const info = yield* shell.get(shellID) expect(info.status).toBe("killed") expect(yield* Effect.promise(() => fs.readFile(info.file, "utf8"))).toBe("first\nsecond\n") expect(result).toEqual({ status: "error", error: { type: "tool.execution", message: `first\nsecond\n\n[full output saved to ${info.file}]\n\nCommand interrupted by the user (shell ID: ${shellID}).`, }, }) expect((yield* jobs.get(shellID))?.status).not.toBe("running") }), ) }), ) parity.live("ends a call the user stopped before its command started, without starting it", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const shell = yield* Shell.Service const result = yield* executeTool(registry, { ...call({ command: "echo started > started" }, "call-early-stop"), // Already stopped, as when the user stops the step while the call waits for permission. cancel: Effect.void, }) expect(result.error?.message).toContain("Command interrupted by the user before it started.") expect(yield* shell.list()).toEqual([]) expect(yield* Effect.promise(() => Bun.file(path.join(tmp.path, "started")).exists())).toBe(false) }), ) }), ) // Resolving a working directory can be slow (an external one in a cold remote workspace); here it never finishes. const resolving = Deferred.makeUnsafe() const stuckResolveIt = testEffect( AppNodeBuilder.build(nodes, [ ...replacements, PluginSupervisor.node.replace(shellPluginSupervisor), FileAccess.node.replace( Layer.mock(FileAccess.Service, { resolve: () => Deferred.succeed(resolving, undefined).pipe(Effect.andThen(Effect.never)), }), ), ]).pipe(Layer.provide(noFlagOverrides)), ) stuckResolveIt.live("ends a call the user stopped while its working directory resolved, without starting it", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const shell = yield* Shell.Service const cancel = yield* Deferred.make() const fiber = yield* executeTool(registry, { ...call({ command: "echo started > started" }, "call-stop-resolving"), cancel: Deferred.await(cancel), }).pipe(Effect.forkChild({ startImmediately: true })) yield* Deferred.await(resolving) yield* Deferred.succeed(cancel, undefined) const result = yield* Fiber.join(fiber) expect(result.error?.message).toContain("Command interrupted by the user before it started.") expect(yield* shell.list()).toEqual([]) expect(yield* Effect.promise(() => Bun.file(path.join(tmp.path, "started")).exists())).toBe(false) }), ) }), ) parity.live("says once that a stopped command wrote nothing", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const shell = yield* Shell.Service const { shellID, result } = yield* stopCall(registry, idleCommand, "call-silent", "cancel", false) const info = yield* shell.get(shellID) // The call settles after a bounded wait for the kill, which a loaded Windows runner can outlast. expect(result?.error?.message?.replace("; it is still being stopped", "")).toBe( `[no output; output file: ${info.file}]\n\nCommand interrupted by the user (shell ID: ${shellID}).`, ) }), ) }), ) // Windows signals terminate the job immediately; a process cannot ignore SIGTERM there. const ignoresTerm = isWindows ? parity.skip : parity.live ignoresTerm( "settles a stopped call without waiting for a command that ignores SIGTERM", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const shell = yield* Shell.Service const started = Date.now() const { shellID, result } = yield* stopCall( registry, "trap '' TERM; printf 'kept\\n'; while :; do sleep 1; done", "call-stubborn", "cancel", ) // Bounded by the short wait, not by the 3 s grace before SIGKILL. expect(Date.now() - started).toBeLessThan(2_500) const info = yield* shell.get(shellID) expect(result?.error?.message).toBe( `kept\n\n[full output saved to ${info.file}]\n\nCommand interrupted by the user (shell ID: ${shellID}); it is still being stopped.`, ) // The stop still ends it. expect((yield* shell.wait(shellID)).status).toBe("killed") }), ) }), { timeout: 15_000 }, ) // Starts a call whose daemon command is slow to be created, and returns once the daemon was asked for it. const startSlowCall = (registry: Tool.Interface, id: string) => Effect.gen(function* () { let release = () => {} if (fake) fake.holdCreate.until = new Promise((resolve) => (release = resolve)) // The step's own gate: a stop goes through `cancel` only if the tool is awaiting it. const cancel = SessionStep.makeCancel() const fiber = yield* executeTool(registry, { ...call({ command: idleCommand }, id), cancel: cancel.effect, }).pipe(Effect.forkChild({ startImmediately: true })) while (!fake?.ops.includes("create_pipe")) yield* Effect.promise(() => Bun.sleep(2)) return { fiber, stop: Effect.sync(() => cancel.trigger()), release: Effect.sync(() => { if (fake) fake.holdCreate.until = undefined release() }), } }) fakeDaemonIt.live("stops a command the user stopped while it was being created", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const jobs = yield* Job.Service const shell = yield* Shell.Service const call = yield* startSlowCall(registry, "call-slow-create") // The tool already listens while its command is being created, so the step would not interrupt it. expect(yield* call.stop).toBe(true) yield* call.release const result = yield* Fiber.join(call.fiber) expect(result.error?.message).toContain("Command interrupted by the user") const process = fake?.processes[0] expect(fake?.requests).toContainEqual( expect.objectContaining({ op: "signal", id: process?.id, signal: "SIGTERM" }), ) expect(process?.lifecycle.status).toBe("exited") expect(yield* shell.list()).toEqual([]) expect((yield* jobs.get(String(process?.pipe?.metadata.id)))?.status).not.toBe("running") }), ) }), ) fakeDaemonIt.live("stops a command the user stopped after its Location reloaded", () => withTempDir((tmp) => Effect.gen(function* () { reset() const sessions = yield* Session.Service const locations = yield* LocationServiceMap.Service const location = Location.Ref.make({ directory: AbsolutePath.make(tmp.path) }) yield* sessions.create({ id: sessionID, title: "shell test", location, model: sessionModel }) yield* Effect.gen(function* () { const plugins = yield* Plugin.Service yield* plugins.awaitActivation const registry = yield* Tool.Service const jobs = yield* Job.Service const cancel = SessionStep.makeCancel() const started = yield* Deferred.make() const fiber = yield* executeTool(registry, { ...call({ command: idleCommand }, "call-reloaded"), progress: (update) => typeof update.shellID === "string" ? Deferred.succeed(started, update.shellID).pipe(Effect.asVoid) : Effect.void, cancel: cancel.effect, }).pipe(Effect.forkChild({ startImmediately: true })) const shellID = yield* Deferred.await(started) // The call still holds the old Location when a reload closes it. yield* locations.invalidate(location) expect(cancel.trigger()).toBe(true) const result = yield* Fiber.join(fiber) expect(result.error?.message).toContain(`Command interrupted by the user (shell ID: ${shellID})`) expect(fake?.processes[0]?.lifecycle.status).toBe("exited") expect((yield* jobs.get(shellID))?.status).not.toBe("running") }).pipe(Effect.provide(locations.get(location))) yield* locations.invalidate(location) }), ), ) for (const handoff of [false, true]) for (const starting of [true, false]) fakeDaemonIt.live( `${handoff ? "leaves a command running" : "stops a command"} when an interrupt ${handoff ? "during a handoff " : ""}cuts its call off while it ${starting ? "starts" : "runs"}`, () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const jobs = yield* Job.Service const pty = yield* PersistentPty.Service const call = yield* startSlowCall(registry, "call-interrupted") if (handoff) expect(yield* pty.handoff()).not.toBeNull() if (!starting) { yield* call.release while (fake!.waiters(fake!.processes[0]?.id ?? -1) === 0) yield* Effect.sleep(2) } const interrupting = yield* Fiber.interrupt(call.fiber).pipe( Effect.forkChild({ startImmediately: true }), ) if (starting) yield* call.release yield* Fiber.join(interrupting) expect(Exit.hasInterrupts(yield* Fiber.await(call.fiber))).toBe(true) const process = fake?.processes[0] const shellID = String(process?.pipe?.metadata.id) if (handoff) { // Nothing stopped it: the next server takes it over through its recorded tool call. expect(process?.lifecycle.status).toBe("running") expect(process?.pipe?.metadata).toMatchObject({ toolCall: { callID: "call-interrupted" } }) expect(fake?.ops).not.toContain("signal") expect((yield* jobs.get(shellID))?.status).toBe("running") yield* jobs.cancel(shellID) return } // Nothing will take it over, so it is stopped and its job ends. const shell = yield* Shell.Service expect((yield* shell.wait(ID.make(shellID))).status).toBe("killed") expect(fake?.requests).toContainEqual( expect.objectContaining({ op: "signal", id: process?.id, signal: "SIGTERM" }), ) expect(process?.lifecycle.status).toBe("exited") expect((yield* jobs.get(shellID))?.status).toBe("cancelled") }), ) }), ) fakeDaemonIt.live("records which call waits on a daemon command, and keeps no timeout for a restart", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const { shellID } = yield* stopCall(registry, idleCommand, "call-recorded", "interrupt", false) const request = fake?.requests.find((item) => item.op === "create_pipe") expect(request?.metadata).toMatchObject({ id: shellID, toolCall: { sessionID, callID: "call-recorded" }, }) // The call's timeout applies to this server only: a restart moves the command to the background. expect(request?.metadata).not.toHaveProperty("timeoutDeadline") }), ) }), ) parity.live("lets an execute.after hook replace a stopped call's failure", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const hooks = yield* PluginHooks.Service const seen: unknown[] = [] yield* hooks.register("tool", "execute.after", (event) => Effect.sync(() => { if (event.status !== "error") return seen.push(event.error.metadata) event.error = new Tool.Error({ message: "rewritten by a plugin" }) }), ) const { shellID, result } = yield* stopCall(registry, startingCommand, "call-hooked", "cancel") expect(seen).toEqual([ { interrupted: true, truncated: false, shellID, notice: expect.stringContaining("Command interrupted by the user"), }, ]) expect(result?.error?.message).toBe("rewritten by a plugin") }), ) }), ) parity.live("stops a command whose call an interrupt cut off, with no handoff to take it over", () => withTempDir((tmp) => { reset() return withSession(tmp.path, (registry) => Effect.gen(function* () { const shell = yield* Shell.Service const jobs = yield* Job.Service const { shellID, exit } = yield* stopCall(registry, startingCommand, "call-teardown", "interrupt") expect(Exit.hasInterrupts(exit)).toBe(true) expect((yield* shell.wait(shellID)).status).toBe("killed") expect((yield* jobs.get(shellID))?.status).toBe("cancelled") }), ) }), ) })