Skip to content

Commit f26ea1d

Browse files
terisukeclaude
andcommitted
fix(guardrails): stop run hanging on a socket stdin nobody closes
Upstream `run` reads a non-TTY stdin to EOF before it connects to its server, with no timeout (packages/cli/src/run/run.ts, 2.0.32 through dev). A caller that hands the CLI a socket it never closes, such as the stdio of a Node/libuv harness or an agent's shell tool, hangs `run` with no output: the private server starts and never receives a request. All 19 hangs logged on 2026-11-05/06 before the canary have that fingerprint; a never-closed socketpair reproduces it 4/4 and /dev/null 0/3. For a socket stdin the launcher now reads first. Input that starts within OPENCODE_GUARDRAILS_STDIN_WAIT_MS (default 1000) is read to EOF and passed on unchanged. With no input by then, the CLI gets an empty stdin and the launcher prints a one-line notice. Pipes, files and terminals are left to the CLI. Co-Authored-By: Claude Opus 5.5 <[email protected]> Agent-Lane: claude-code
1 parent 98256db commit f26ea1d

4 files changed

Lines changed: 207 additions & 1 deletion

File tree

‎packages/guardrails/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@ What the wrapper does on the 2.x CLI (since the 2026-10-19 re-platform, #343):
150150

151151
- **CLI binary**: `OPENCODE_BIN_PATH`, else the first `opencode` on `PATH` that is not a wrapper around this launcher. A monorepo checkout is not used (`bun install` does not fetch the `@opencode/cli-*` binaries).
152152
- **Private server**: server-backed commands get `--standalone` after the command leaf, and the TUI gets it first. Local configuration commands and server lifecycle commands pass through; `debug` leaves are checked against the selected CLI version. See [launcher arguments](./launcher-arguments.md). The background service retains its startup environment; `OPENCODE_GUARDRAILS_ALLOW_SERVICE=1` deliberately keeps that connection.
153+
- **`run` stdin**: upstream `run` reads a non-TTY stdin to EOF before it starts, so a socket nobody closes (the stdio of a Node/libuv harness or an agent's shell tool) would hang it. For a socket stdin, input that starts within `OPENCODE_GUARDRAILS_STDIN_WAIT_MS` (default 1000) is read to EOF and passed on unchanged; with none by then the CLI gets an empty stdin and the launcher prints a one-line notice. Pipes, files and terminals are left to the CLI. See `bin/run-stdin.js`.
153154
- **Config layering**: in 2.x `OPENCODE_CONFIG_DIR` _replaces_ the global config directory, so the user's global `opencode.json(c)` is handed back through `OPENCODE_CONFIG`. Extra plugin directories (for example the AIDD H17 control) go in `OPENCODE_GUARDRAILS_EXTRA_PLUGINS` (`:`-separated) and are merged into `OPENCODE_CONFIG_CONTENT`.
154155
- On this Mac the entry point is `~/.local/bin/opencode` → `opencode2` (claude-code-skills `opencode/launcher/opencode2`), which calls this wrapper from the main checkout.
155156

‎packages/guardrails/bin/opencode-guardrails‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import { applyCorLocalDefaults } from "./cor-local-env.js"
2424
import { applyZaiAuthDefaults } from "./zai-auth-env.js"
2525
import { withStandalone } from "./standalone-args.js"
2626
import { cliCommand } from "./cli-command.js"
27+
import { runInput } from "./run-stdin.js"
2728

2829
function fail(msg) {
2930
console.error(msg)
@@ -135,8 +136,11 @@ const [command, ...args] = cliCommand(
135136
target,
136137
process.env.OPENCODE_GUARDRAILS_ALLOW_SERVICE === "1" ? process.argv.slice(2) : withStandalone(process.argv.slice(2)),
137138
)
139+
// `run` reads a non-TTY stdin to EOF before it starts, so a socket nobody closes would hang it (bin/run-stdin.js)
140+
const input = await runInput(process.argv.slice(2))
138141
const out = spawnSync(command, args, {
139-
stdio: "inherit",
142+
stdio: input ? ["pipe", "inherit", "inherit"] : "inherit",
143+
input,
140144
env: childEnv,
141145
})
142146

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// stdin for `opencode run` (kept separate from bin/opencode-guardrails so its contract has its own file and tests).
2+
//
3+
// Upstream `run` reads a non-TTY stdin to EOF before it connects to its server, with no timeout
4+
// (packages/cli/src/run/run.ts `mergeInput(…, process.stdin.isTTY ? undefined : await readStdin())`, 2.0.32 through dev).
5+
// A caller that hands the CLI a socket it never closes — the stdio of a Node/libuv harness (`spawn(…, { stdio: "pipe" })`)
6+
// or of an agent's shell tool — therefore hangs `run` silently: its private server starts and never gets a request. All
7+
// 19 hangs logged on 2026-11-05/06 before the canary carry that fingerprint; a never-closed socketpair reproduces it 4/4,
8+
// /dev/null 0/3. For a socket stdin the launcher reads first: input that starts within OPENCODE_GUARDRAILS_STDIN_WAIT_MS
9+
// (default 1000) is read to EOF and passed on unchanged; no input by then is taken as none coming, and the CLI gets an
10+
// empty stdin. Pipes, files and terminals are left to the CLI, so a slow producer in a shell pipeline is still waited for.
11+
import fs from "node:fs"
12+
13+
/** The bytes to hand `run` on stdin, or undefined to let the CLI inherit the launcher's stdin. */
14+
export async function runInput(args, env = process.env) {
15+
if (args.find((a) => !a.startsWith("-")) !== "run" || !fs.fstatSync(0).isSocket()) return
16+
const wait = Number(env.OPENCODE_GUARDRAILS_STDIN_WAIT_MS || Number.NaN)
17+
const waitMs = Number.isInteger(wait) && wait >= 0 ? wait : 1000
18+
const input = await readStdin(waitMs)
19+
if (input) return input
20+
console.error(
21+
`opencode-guardrails: stdin is a socket with no input within ${waitMs} ms; running without piped input ` +
22+
"(OPENCODE_GUARDRAILS_STDIN_WAIT_MS sets the wait)",
23+
)
24+
return Buffer.alloc(0)
25+
}
26+
27+
/** stdin to EOF once it starts within waitMs; undefined when neither a byte nor EOF arrives in time. */
28+
function readStdin(waitMs) {
29+
const chunks = []
30+
return new Promise((resolve) => {
31+
const done = () => {
32+
clearTimeout(timer)
33+
resolve(Buffer.concat(chunks))
34+
}
35+
// pause rather than destroy: a writer that turns up later must not get EPIPE from the launcher itself
36+
const timer = setTimeout(() => {
37+
process.stdin.pause()
38+
resolve(undefined)
39+
}, waitMs)
40+
process.stdin.on("data", (chunk) => {
41+
clearTimeout(timer)
42+
chunks.push(chunk)
43+
})
44+
process.stdin.on("end", done)
45+
process.stdin.on("error", done)
46+
})
47+
}
Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
/**
2+
* `opencode run` with a socket stdin nobody closes (bin/run-stdin.js).
3+
*
4+
* Upstream `run` reads a non-TTY stdin to EOF before it connects to its server, with no timeout. The stub CLI below
5+
* does the same (`text(process.stdin)` for `run`), so a launcher that hands it a never-closed socket hangs exactly as
6+
* the real CLI does. The driver spawns the launcher from real Node with `stdio: "pipe"` — a libuv socketpair, the
7+
* stdio an agent harness or `child_process` caller gives a child — and kills the launcher's process group after 3 s.
8+
* Offline; no real CLI, credentials or model calls.
9+
*/
10+
import { describe, expect, test } from "bun:test"
11+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs"
12+
import { tmpdir } from "node:os"
13+
import path from "node:path"
14+
import { fileURLToPath } from "node:url"
15+
16+
const bin = fileURLToPath(new URL("../../bin/opencode-guardrails", import.meta.url))
17+
18+
const cli = `
19+
import { text } from "node:stream/consumers"
20+
const args = process.argv.slice(2)
21+
const piped = args[0] === "run" && !process.stdin.isTTY ? await text(process.stdin) : null
22+
process.stdout.write(JSON.stringify({ args, piped }))
23+
`
24+
25+
// <mode> <launcher> <args...>; modes: open (never written or closed), data, slow-end (written at once, closed later), late
26+
const driver = `
27+
import { spawn, spawnSync } from "node:child_process"
28+
const [mode, launcher, ...args] = process.argv.slice(2)
29+
const probe = spawnSync(process.execPath, ["-e", "process.stdout.write(String(require('node:fs').fstatSync(0).isSocket()))"], { stdio: ["pipe", "pipe", "inherit"] })
30+
const child = spawn(process.execPath, [launcher, ...args], { stdio: ["pipe", "pipe", "pipe"], detached: true })
31+
let stdout = ""
32+
let stderr = ""
33+
child.stdout.on("data", (chunk) => (stdout += chunk))
34+
child.stderr.on("data", (chunk) => (stderr += chunk))
35+
child.stdin.on("error", () => {})
36+
if (mode === "data") child.stdin.end("piped text")
37+
if (mode === "slow-end") {
38+
child.stdin.write("piped ")
39+
setTimeout(() => child.stdin.end("text"), 600)
40+
}
41+
if (mode === "late") setTimeout(() => child.stdin.end("late text"), 1000)
42+
const killer = setTimeout(() => process.kill(-child.pid, "SIGKILL"), 3000)
43+
child.on("close", (code, signal) => {
44+
clearTimeout(killer)
45+
process.stdout.write(JSON.stringify({ socket: probe.stdout.toString() === "true", code, signal, stdout, stderr }))
46+
process.exit(0)
47+
})
48+
`
49+
50+
function launch(mode: string, args: string[], env: Record<string, string>) {
51+
const dir = mkdtempSync(path.join(tmpdir(), "guardrails-run-stdin-"))
52+
try {
53+
writeFileSync(path.join(dir, "cli.mjs"), cli, { mode: 0o600 })
54+
writeFileSync(path.join(dir, "driver.mjs"), driver, { mode: 0o600 })
55+
const run = Bun.spawnSync(["node", path.join(dir, "driver.mjs"), mode, bin, ...args], {
56+
cwd: dir,
57+
timeout: 8_000,
58+
env: {
59+
PATH: process.env.PATH,
60+
HOME: dir,
61+
USERPROFILE: dir,
62+
OPENCODE_BIN_PATH: path.join(dir, "cli.mjs"),
63+
...env,
64+
},
65+
})
66+
const result = JSON.parse(new TextDecoder().decode(run.stdout)) as {
67+
socket: boolean
68+
code: number | null
69+
signal: string | null
70+
stdout: string
71+
stderr: string
72+
}
73+
return {
74+
...result,
75+
cli: result.code === 0 ? (JSON.parse(result.stdout) as { args: string[]; piped: string | null }) : undefined,
76+
}
77+
} finally {
78+
rmSync(dir, { recursive: true, force: true })
79+
}
80+
}
81+
82+
// A regression hangs until the driver kills the launcher at 3 s, past bun's 5 s default once spawns are added.
83+
const HANG = 10_000
84+
85+
// libuv socketpair stdio and POSIX sh are what these cases exercise; the guardrails job runs on ubuntu-latest.
86+
describe.skipIf(process.platform === "win32")("run with a socket stdin", () => {
87+
test(
88+
"a socket nobody closes no longer hangs run: the CLI gets an empty stdin and the launcher says so",
89+
() => {
90+
const result = launch("open", ["run", "hi"], { OPENCODE_GUARDRAILS_STDIN_WAIT_MS: "200" })
91+
expect(result.socket).toBe(true)
92+
expect(result.signal, result.stderr).toBeNull()
93+
expect(result.code, result.stderr).toBe(0)
94+
expect(result.cli).toEqual({ args: ["run", "--standalone", "hi"], piped: "" })
95+
expect(result.stderr).toContain("no input within 200 ms")
96+
},
97+
HANG,
98+
)
99+
100+
test("input written to the socket reaches the CLI unchanged", () => {
101+
const result = launch("data", ["run", "hi"], { OPENCODE_GUARDRAILS_STDIN_WAIT_MS: "200" })
102+
expect(result.code, result.stderr).toBe(0)
103+
expect(result.cli?.piped).toBe("piped text")
104+
expect(result.stderr).toBe("")
105+
})
106+
107+
test("once input starts, it is read to EOF however long the writer takes to close", () => {
108+
const result = launch("slow-end", ["run", "hi"], { OPENCODE_GUARDRAILS_STDIN_WAIT_MS: "200" })
109+
expect(result.code, result.stderr).toBe(0)
110+
expect(result.cli?.piped).toBe("piped text")
111+
})
112+
113+
test("input that starts after the wait is not passed on, and the launcher says so", () => {
114+
const result = launch("late", ["run", "hi"], { OPENCODE_GUARDRAILS_STDIN_WAIT_MS: "200" })
115+
expect(result.code, result.stderr).toBe(0)
116+
expect(result.cli?.piped).toBe("")
117+
expect(result.stderr).toContain("OPENCODE_GUARDRAILS_STDIN_WAIT_MS")
118+
})
119+
120+
test(
121+
"other commands keep the inherited stdin and do not wait on it",
122+
() => {
123+
const result = launch("open", ["models"], { OPENCODE_GUARDRAILS_STDIN_WAIT_MS: "20000" })
124+
expect(result.signal, result.stderr).toBeNull()
125+
expect(result.cli).toEqual({ args: ["models", "--standalone"], piped: null })
126+
},
127+
HANG,
128+
)
129+
130+
test("a pipe stdin is left to the CLI, so a slow producer is still waited for", () => {
131+
const dir = mkdtempSync(path.join(tmpdir(), "guardrails-run-pipe-"))
132+
try {
133+
writeFileSync(path.join(dir, "cli.mjs"), cli, { mode: 0o600 })
134+
const run = Bun.spawnSync(["sh", "-c", `(sleep 1; printf 'late text') | node "${bin}" run hi`], {
135+
cwd: dir,
136+
timeout: 8_000,
137+
env: {
138+
PATH: process.env.PATH,
139+
HOME: dir,
140+
USERPROFILE: dir,
141+
OPENCODE_BIN_PATH: path.join(dir, "cli.mjs"),
142+
OPENCODE_GUARDRAILS_STDIN_WAIT_MS: "200",
143+
},
144+
})
145+
expect(run.exitCode, new TextDecoder().decode(run.stderr)).toBe(0)
146+
expect(JSON.parse(new TextDecoder().decode(run.stdout))).toEqual({
147+
args: ["run", "--standalone", "hi"],
148+
piped: "late text",
149+
})
150+
} finally {
151+
rmSync(dir, { recursive: true, force: true })
152+
}
153+
})
154+
})

0 commit comments

Comments
 (0)