GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(core): make shell the only Code Mode shell tool, pinned and annotated by jlongster · Pull Request #64335 · anomalyco/opencode

feat(core): make shell the only Code Mode shell tool, pinned and annotated #64335

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
jlongster merged 6 commits into dev from codemode-shell-only
Nov 17, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

feat(core): make shell the only Code Mode shell tool, pinned and annotated #64335

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
6 commits
Select commit Hold shift + click to select a range
e7cdd89
feat(core): extend Code Mode shell foreground wait
jlongster Nov 16, 2026
2835242
feat(core): pin Code Mode shell and describe its result in its fields
jlongster Nov 17, 2026
fae129e
refactor(core): one annotated shell result for Code Mode and direct c…
jlongster Nov 17, 2026
aa891ab
refactor(core): keep the shell command description in Code Mode
jlongster Nov 17, 2026
309acb6
refactor(core): use the full shell description in Code Mode
jlongster Nov 17, 2026
4c7d255
refactor(core): drop the background parameter from Code Mode shell
jlongster Nov 17, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

78 changes: 52 additions & 26 deletions 78 packages/core/src/tool/plugin/shell.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { toolFailure } from "../runtime.js"

export const name = "shell"
export const DEFAULT_TIMEOUT_MS = 2 * 60 * 1_000
const CODE_MODE_TIMEOUT_MS = 10 * 60 * 1_000
// How long a call the user interrupted waits for its stopped command to exit before settling with the output so far.
const INTERRUPT_WAIT = "500 millis"

Expand All @@ -39,7 +40,7 @@ const OS =
: process.platform === "linux"
? "Linux"
: process.platform
const description = (shell?: string) =>
const description = (shell?: string, codeMode = false) =>
[
"Execute a shell command and return its output.",
...(shell ? [`Commands run on ${OS} using ${shell}.`] : []),
Expand All @@ -48,33 +49,55 @@ const description = (shell?: string) =>
"When output is large, the full result is saved to a file and a truncated preview is returned.",
"Rely on automatic truncation unless filtering the output is more useful.",
"Commands still running after their timeout move to the background.",
"Background commands return immediately, and you will be notified when they complete.",
// Code Mode has no background parameter.
...(codeMode ? [] : ["Background commands return immediately, and you will be notified when they complete."]),
"The current session ID is available in the OPENCODE_SESSION_ID environment variable.",
].join(" ")

const timeoutInput = (foreground: number) =>
Schema.optionalKey(NonNegativeInt).annotate({
description: `Optional timeout in milliseconds (default ${foreground}). When it expires, a foreground command moves to the background and a background command is stopped.`,
})

export const Input = Schema.Struct({
command: Schema.String.annotate({ description: "Shell command string to execute" }),
workdir: Schema.optionalKey(Schema.String).annotate({
description:
"Working directory to execute the command in. Defaults to the current working directory. When possible, avoid changing directories in the command and set the working directory here instead.",
}),
timeout: Schema.optionalKey(NonNegativeInt).annotate({
description: `Optional timeout in milliseconds (default ${DEFAULT_TIMEOUT_MS}). When it expires, a foreground command moves to the background and a background command is stopped.`,
}),
timeout: timeoutInput(DEFAULT_TIMEOUT_MS),
background: Schema.optionalKey(Schema.Boolean).annotate({
description:
"Run the command in the background and return immediately (useful for dev servers and long-running builds). You do not need to use '&' at the end of the command when using this parameter. You will be notified when it completes. DO NOT poll for completion.",
}),
})

const CodeModeInput = Schema.Struct({
Comment thread

@opencodejr opencodejr Bot Nov 17, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With background gone, Code Mode has no way to start a dev server or watcher in the background. The call holds execute open until the 10-minute default runs out, unless the model knows to pass a short timeout. A model used to the direct tool may still pass background: true, and input decoding drops unknown keys silently, so that call blocks for 10 minutes with no error to react to. Could Code Mode either keep background, or reject the key so the model learns to use timeout instead?

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
...Struct.omit(Input.fields, ["background"]),
timeout: timeoutInput(CODE_MODE_TIMEOUT_MS),
})

const StructuredOutput = Schema.Struct({
output: Schema.String,
exitCode: Schema.NullOr(Schema.Number),
wallTimeSeconds: Schema.Number,
outputPath: Schema.optionalKey(Schema.String),
signal: Schema.optionalKey(Schema.String),
shellID: Schema.optionalKey(Schema.String),
pid: Schema.optionalKey(NonNegativeInt),
shellID: Schema.optionalKey(Schema.String).annotate({
description:
"Present only while the command is still running in the background. You will be notified when it exits. A result without shellID is final.",
}),
exitCode: Schema.NullOr(Schema.Number).annotate({
description:
"The exit code once the command has exited: 0 means success. null while it is still running, or when a signal ended it.",
}),
signal: Schema.optionalKey(Schema.String).annotate({ description: "The signal that ended the command, if any" }),
output: Schema.String.annotate({
description:
"Combined stdout and stderr as one string; there are no separate stdout or stderr fields. While shellID is present it is a notice instead, and the output streams to outputPath.",
}),
outputPath: Schema.optionalKey(Schema.String).annotate({
description: "File with the full output, when output was truncated or the command is running in the background",
}),
pid: Schema.optionalKey(NonNegativeInt).annotate({
description: "Process ID while the command is running in the background",
}),
wallTimeSeconds: Schema.Number.annotate({ description: "Seconds since the command started" }),
})

type Output = ReturnType<typeof ShellResult.output> & {
Expand Down Expand Up @@ -287,7 +310,6 @@ export const Plugin = {
// Internal plugins are not re-run on config changes, so reload the tool transform instead.
const loaded = yield* ConfigEntryObserver.observe(config, ctx.event, ctx.tool.reload())
const flags = yield* Flag.Service
const fullCodeMode = () => flags.resolve(loaded.entries).full_codemode.enabled

const prepare = Effect.fn("ShellTool.prepare")(function* (invocation: ShellCreateBefore, context: Tool.Context) {
const target = yield* access.resolve({ path: invocation.cwd, kind: "directory" })
Expand Down Expand Up @@ -351,18 +373,22 @@ export const Plugin = {
})

yield* ctx.tool
.transform((editor) =>
.transform((editor) => {
const codeMode = flags.resolve(loaded.entries).full_codemode.enabled
editor.add({
name,
// With full_codemode, shell is called as `tools.shell` inside `execute` instead of as a direct tool.
options: { codemode: fullCodeMode() },
description: description(),
input: Input,
// With full_codemode, shell is called as `tools.shell` inside `execute` instead of as a direct tool, and is
// pinned so the Code Mode catalog always lists it, however many other tools there are.
options: codeMode ? { codemode: true, pinned: true } : { codemode: false },
description: description(undefined, codeMode),
input: codeMode ? CodeModeInput : Input,
output: StructuredOutput,
execute: (input, context) => {
// Code Mode input has no background parameter.
const background = "background" in input && input.background === true
// A foreground timeout of 0 falls back to the default, so a call can't block until the command exits.
const foreground = input.timeout || DEFAULT_TIMEOUT_MS
const timeout = input.background === true ? (input.timeout ?? 0) : foreground
const foreground = input.timeout || (codeMode ? CODE_MODE_TIMEOUT_MS : DEFAULT_TIMEOUT_MS)
const timeout = background ? (input.timeout ?? 0) : foreground
let finalTimeout = timeout
// Uninterruptible from spawning to blocking, so an interrupt cannot orphan a started command.
return Effect.uninterruptibleMask((restore) =>
Expand All @@ -385,7 +411,7 @@ export const Plugin = {
timeout,
shell: yield* compatibleShell,
metadata: { sessionID: context.sessionID },
waited: input.background !== true,
waited: !background,
toolCall: {
sessionID: context.sessionID,
assistantMessageID: context.messageID,
Expand All @@ -412,7 +438,7 @@ export const Plugin = {
),
)
// A foreground timeout moves the command to the background instead of stopping it.
if (input.background !== true) invocation.timeout = 0
if (!background) invocation.timeout = 0
}),
)
yield* context.progress({ shellID: info.id })
Expand All @@ -425,7 +451,7 @@ export const Plugin = {
// Stopped while the command was starting: stop it now.
if (yield* Deferred.isDone(stopped)) return yield* cancelled(info, job.id)

if (input.background === true) {
if (background) {
yield* jobs.background(job.id)
yield* notifyWhenDone(context.sessionID, job.id, info.id, info.command, settled)
return backgroundResult(info, yield* Clock.currentTimeMillis)
Expand Down Expand Up @@ -482,14 +508,14 @@ export const Plugin = {
// Shell spans, including the job that waits for a backgrounded command, name the call that started them.
Effect.annotateSpans({
"gen_ai.tool.call.id": context.id,
...(input.background === true ? { "opencode.shell.background": true } : {}),
...(background ? { "opencode.shell.background": true } : {}),
}),
Effect.map((output) => toolResult(output, finalTimeout)),
Effect.mapError(toolFailure(`Unable to execute command: ${input.command}`)),
)
},
}),
)
})
})
.pipe(Effect.orDie)

const hook = (event: SessionHooks["context"]) =>
Expand Down
77 changes: 74 additions & 3 deletions 77 packages/core/test/tool-shell.test.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ 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"
Expand Down Expand Up @@ -177,9 +178,9 @@ const replacements = [
PersistentPty.node.replace(disabledPersistentPtyLayer),
] satisfies LayerNode.Replacements
const productionIt = testEffect(AppNodeBuilder.build(nodes, replacements))
const it = testEffect(
AppNodeBuilder.build(nodes, [...replacements, PluginSupervisor.node.replace(shellPluginSupervisor)]),
)
const shellLayer = AppNodeBuilder.build(nodes, [...replacements, PluginSupervisor.node.replace(shellPluginSupervisor)])
const it = testEffect(shellLayer)
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)]),
Expand Down Expand Up @@ -890,6 +891,76 @@ describe("ShellTool", () => {
}),
)

codeModeIt.live("runs parallel Code Mode shells with the long default and notifies after a shorter timeout", () =>
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)).toEqual(["shell"])
expect(pinned[0]!.line).toContain("600000")
expect(pinned[0]!.line).toContain("Execute a shell command and return its output.")
// No background parameter in Code Mode.
expect(pinned[0]!.line).not.toContain("background?: boolean")
expect(pinned[0]!.line).not.toContain("Background commands return immediately")
expect(pinned[0]!.line).toContain("A result without shellID is final")
expect(pinned[0]!.line).toContain("there are no separate stdout or stderr fields")
const timeouts: number[] = []
const hooks = yield* PluginHooks.Service
yield* hooks.register("shell", "create.before", (event) =>
Effect.sync(() => {
timeouts.push(event.timeout)
}),
)
const bus = yield* Bus.Service
const notice = 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 quick = JSON.stringify({ command: bodyExitCommand })
const long = JSON.stringify({ command: progressOverflowCommand(6, "release"), timeout: 10 })
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(${quick}), tools.shell(${long})])` },
},
}).pipe(Effect.timeout("3 seconds"))
expect(result.status).toBe("completed")
const [completed, running] = JSON.parse(result.output.output)
expect(completed).toEqual({
output: "body",
exitCode: 7,
wallTimeSeconds: expect.any(Number),
})
expect(running).toEqual({
output: expect.stringContaining("did not finish within its timeout of 0.01 seconds"),
exitCode: null,
shellID: expect.stringMatching(/^sh_/),
pid: expect.any(Number),
outputPath: expect.any(String),
wallTimeSeconds: expect.any(Number),
})
expect(timeouts.toSorted((a, b) => a - b)).toEqual([10, 600_000])
yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), ""))
expect((yield* Fiber.join(notice)).valueOrUndefined?.data.item.payload).toMatchObject({
text: expect.stringContaining("xxxxxx"),
metadata: { source: "shell", shellID: running.shellID, state: "completed", exit: 0 },
})
}),
)
}),
)

productionIt.live(
"registers and returns real successful output from the active Location",
() =>
Expand Down
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.