Skip to content

Commit 3e54dba

Browse files
fix: every tool output that can pass a pipe's buffer writes whole
Covers text-mode `tool run` (a workspace tool's output has no cap), `tool context` and `tool schema`. Docs say to read stdout while the command runs. Tests now check the CLI's own exit code, cover failed writes and clean up. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01YNQjkaiykbC1WtASw6Yegs
1 parent 01b3b8d commit 3e54dba

3 files changed

Lines changed: 54 additions & 35 deletions

File tree

‎docs/docs/usage/tool.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ echo '{"query":"select 1"}' | altimate-code tool run sql_execute --args -
4545

4646
Arguments are validated against the tool's schema. An unknown tool, invalid arguments or a failing tool exits non-zero.
4747

48+
Read stdout while the command runs. The command writes all of its output before it exits, so a caller that waits for it to exit before reading can block forever on output larger than a pipe holds. A reader that closes the pipe early doesn't change the exit code. A write that fails, such as on a full disk, exits non-zero.
49+
4850
Only the data tools are exposed. Coding tools (`bash`, `read`, `edit`, ...), `dbt_pr_review` (use `altimate-code review`), memory and training tools are not available here.
4951

5052
## Permissions

‎packages/opencode/src/cli/cmd/tool.ts‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -159,8 +159,8 @@ const ToolContextCommand = cmd({
159159
await Registry.closeAll()
160160
}
161161
})
162-
if (args.json) console.log(JSON.stringify({ instructions, connections }, null, 2))
163-
else console.log(instructions)
162+
if (args.json) writeAll(JSON.stringify({ instructions, connections }, null, 2) + "\n")
163+
else writeAll(instructions + "\n")
164164
},
165165
})
166166

@@ -181,7 +181,7 @@ const ToolSchemaCommand = cmd({
181181
process.exitCode = 1
182182
return
183183
}
184-
console.log(JSON.stringify(tool, null, 2))
184+
writeAll(JSON.stringify(tool, null, 2) + "\n")
185185
},
186186
})
187187

@@ -237,7 +237,7 @@ const ToolRunCommand = cmd({
237237
} else if (result.status === "error") {
238238
console.error(result.output)
239239
} else {
240-
console.log(result.output)
240+
writeAll(result.output + "\n")
241241
}
242242
if (result.status === "error") process.exitCode = 1
243243
},
@@ -297,10 +297,9 @@ const ToolDaemonCommand = cmd({
297297
})
298298

299299
/**
300-
* All of a machine-read answer on stdout before returning. The CLI exits right after a command, and
301-
* console.log leaves what a pipe can't take yet in a buffer that exit throws away, which cuts off an
302-
* answer over the pipe's 64 KiB when its reader is slow. `tool run`'s `output` is capped, so there only
303-
* metadata gets that big.
300+
* All of an answer on stdout before returning. The CLI exits right after a command, and console.log leaves
301+
* what a pipe can't take yet in a buffer that exit throws away, which cuts off anything over the pipe's
302+
* 64 KiB when its reader is slow: `metadata`, the tool list, or a workspace tool's output, which has no cap.
304303
*/
305304
function writeAll(text: string) {
306305
const bytes = Buffer.from(text)

‎packages/opencode/test/altimate/tool-cli/cli.test.ts‎

Lines changed: 45 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { describe, expect, test } from "bun:test"
2-
import { mkdir, mkdtemp, writeFile } from "node:fs/promises"
1+
import { afterAll, describe, expect, test } from "bun:test"
2+
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"
33
import { tmpdir } from "node:os"
44
import path from "node:path"
55

@@ -8,9 +8,28 @@ const cliEnv = { ...process.env, ALTIMATE_TELEMETRY_DISABLED: "1", ALTIMATE_TOOL
88
// These drive the CLI through a shell pipeline, which is what makes the reader late.
99
const posixOnly = test.skipIf(process.platform === "win32")
1010

11+
const pipeDirs: string[] = []
12+
async function pipeDir() {
13+
const dir = await mkdtemp(path.join(tmpdir(), "tool-cli-"))
14+
pipeDirs.push(dir)
15+
return dir
16+
}
17+
afterAll(() => Promise.all(pipeDirs.map((dir) => rm(dir, { recursive: true, force: true }))))
18+
19+
/** Runs a shell line with the CLI as `"$0" --conditions=browser "$1"`, and returns the CLI's exit code from code.txt. */
20+
async function inShell(dir: string, line: string) {
21+
const proc = Bun.spawn(["sh", "-c", line, process.execPath, entry], { cwd: dir, stderr: "ignore", env: cliEnv, timeout: 50_000 })
22+
try {
23+
await proc.exited
24+
return Number((await Bun.file(path.join(dir, "code.txt")).text()).trim())
25+
} finally {
26+
proc.kill()
27+
}
28+
}
29+
1130
/** A manifest whose hub has 450 readers, so its `dbt_lineage` graph is far over a pipe's 64 KiB. */
1231
async function bigAnswerProject() {
13-
const dir = await mkdtemp(path.join(tmpdir(), "tool-cli-"))
32+
const dir = await pipeDir()
1433
const model = (name: string, deps: string[]) => ({
1534
resource_type: "model",
1635
unique_id: `model.shop.${name}`,
@@ -44,18 +63,11 @@ async function bigAnswerProject() {
4463
* Runs the CLI with a reader that waits for it to exit, up to 20 s, as a busy event loop can: the pipe is full
4564
* until then. A CLI that drops what the pipe can't take exits at once and leaves 64 KiB; one that writes it all waits.
4665
*/
47-
async function lateReader(dir: string, command: string) {
48-
const proc = Bun.spawn(
49-
[
50-
"sh",
51-
"-c",
52-
`{ "$0" --conditions=browser "$1" ${command}; touch done; } | { i=0; until [ -e done ] || [ $i -ge 200 ]; do sleep 0.1; i=$((i+1)); done; cat > out.json; }`,
53-
process.execPath,
54-
entry,
55-
],
56-
{ cwd: dir, stderr: "ignore", env: cliEnv },
66+
function lateReader(dir: string, command: string) {
67+
return inShell(
68+
dir,
69+
`{ "$0" --conditions=browser "$1" ${command}; echo $? > code.txt; touch done; } | { i=0; until [ -e done ] || [ $i -ge 200 ]; do sleep 0.1; i=$((i+1)); done; cat > out.json; }`,
5770
)
58-
return proc.exited
5971
}
6072

6173
async function cli(args: string[], stdin?: string) {
@@ -91,30 +103,36 @@ describe("tool CLI", () => {
91103
}, 60000)
92104

93105
posixOnly("tool list --json reaches a reader that starts late whole", async () => {
94-
const dir = await mkdtemp(path.join(tmpdir(), "tool-cli-"))
106+
const dir = await pipeDir()
95107
expect(await lateReader(dir, "tool list --json")).toBe(0)
96108
const stdout = await Bun.file(path.join(dir, "out.json")).text()
97-
expect(stdout.length).toBeGreaterThan(65_536)
109+
expect(stdout.endsWith("]\n")).toBe(true)
98110
expect((JSON.parse(stdout) as unknown[]).length).toBeGreaterThan(0)
99111
}, 60000)
100112

101113
posixOnly("a reader that leaves early is not an error", async () => {
102114
const dir = await bigAnswerProject()
103-
const proc = Bun.spawn(
104-
[
105-
"sh",
106-
"-c",
107-
`{ "$0" --conditions=browser "$1" tool run dbt_lineage --args - --json < args.json 2> err.txt; echo $? > code.txt; } | head -c 10 > /dev/null`,
108-
process.execPath,
109-
entry,
110-
],
111-
{ cwd: dir, stderr: "ignore", env: cliEnv },
115+
const code = await inShell(
116+
dir,
117+
`{ "$0" --conditions=browser "$1" tool run dbt_lineage --args - --json < args.json 2> err.txt; echo $? > code.txt; } | head -c 10 > /dev/null`,
112118
)
113-
await proc.exited
114-
expect((await Bun.file(path.join(dir, "code.txt")).text()).trim()).toBe("0")
119+
expect(code).toBe(0)
115120
expect(await Bun.file(path.join(dir, "err.txt")).text()).toBe("")
116121
}, 60000)
117122

123+
posixOnly("an error stays an error when the reader has left", async () => {
124+
const dir = await pipeDir()
125+
const code = await inShell(dir, `{ "$0" --conditions=browser "$1" tool run nope --args '{}' --json 2> err.txt; echo $? > code.txt; } | true`)
126+
expect(code).toBe(1)
127+
}, 60000)
128+
129+
posixOnly("a write that really fails exits non-zero and says why", async () => {
130+
const dir = await pipeDir()
131+
const code = await inShell(dir, `"$0" --conditions=browser "$1" tool list --json 1</dev/null 2> err.txt; echo $? > code.txt`)
132+
expect(code).toBe(1)
133+
expect(await Bun.file(path.join(dir, "err.txt")).text()).toContain("EBADF")
134+
}, 60000)
135+
118136
test("rejects --args - with empty stdin", async () => {
119137
const { stdout, code } = await cli(["tool", "run", "sql_format", "--args", "-", "--json"], "")
120138
expect(code).toBe(1)

0 commit comments

Comments
 (0)