diff --git a/bin/adlc-cli.mjs b/bin/adlc-cli.mjs index 6bd84bb..5e81b69 100755 --- a/bin/adlc-cli.mjs +++ b/bin/adlc-cli.mjs @@ -1,5 +1,8 @@ #!/usr/bin/env node -import { main } from "../src/cli.mjs"; +import { main, flushStdio } from "../src/cli.mjs"; const exitCode = await main(process.argv.slice(2), { mode: "cli" }); +// process.exit() would drop writes still queued in libuv — stdout to a pipe +// is asynchronous on POSIX, so large output can be truncated (see src/cli.mjs). +await flushStdio(); process.exit(exitCode); diff --git a/bin/adlc-skills-cli.mjs b/bin/adlc-skills-cli.mjs index 765aef3..ca14c37 100755 --- a/bin/adlc-skills-cli.mjs +++ b/bin/adlc-skills-cli.mjs @@ -1,5 +1,8 @@ #!/usr/bin/env node -import { main } from "../src/cli.mjs"; +import { main, flushStdio } from "../src/cli.mjs"; const exitCode = await main(process.argv.slice(2), { mode: "legacy" }); +// process.exit() would drop writes still queued in libuv — stdout to a pipe +// is asynchronous on POSIX, so large output can be truncated (see src/cli.mjs). +await flushStdio(); process.exit(exitCode); diff --git a/src/cli.mjs b/src/cli.mjs index 234bcb8..3de17ee 100644 --- a/src/cli.mjs +++ b/src/cli.mjs @@ -6,3 +6,29 @@ export async function main(argv = process.argv.slice(2), opts = {}) { const exitCode = await dispatch(argv, opts.mode ?? "legacy"); return exitCode; } + +/** + * Wait for queued stdout/stderr writes to reach the OS. + * + * `process.exit()` terminates immediately and drops writes still queued in + * libuv. stdout connected to a pipe is asynchronous on POSIX, so a bin that + * prints and exits can lose the tail of its output when the pipe buffer is + * small — macOS truncated the last panels of `workflow help` in Publish run + * 42608148983. Bins await this before calling `process.exit()`. + */ +export async function flushStdio() { + await Promise.all([flushStream(process.stdout), flushStream(process.stderr)]); +} + +function flushStream(stream) { + return new Promise((resolve) => { + if (!stream || stream.writableLength === 0) return resolve(); + try { + // The empty write queues behind pending chunks; its callback fires once + // they have all been handed to the OS. + stream.write("", () => resolve()); + } catch { + resolve(); + } + }); +} diff --git a/src/dispatcher.mjs b/src/dispatcher.mjs index 7ffdaa1..3a9af6f 100644 --- a/src/dispatcher.mjs +++ b/src/dispatcher.mjs @@ -24,7 +24,7 @@ // 2. Body path (superpowers model): output the skill's markdown body // (frontmatter stripped). LLM-interpreted orientation/instructions. -import { readFileSync, writeFileSync, readSync, existsSync, readdirSync, statSync, accessSync, constants, realpathSync } from "node:fs"; +import { readFileSync, writeFileSync, writeSync, readSync, existsSync, readdirSync, statSync, accessSync, constants, realpathSync } from "node:fs"; import { spawnSync } from "node:child_process"; import { isatty } from "node:tty"; import { join, resolve, dirname, sep, delimiter, relative, isAbsolute, posix, win32 } from "node:path"; @@ -128,22 +128,40 @@ function main() { // - "suppress": emit nothing (strict-JSON agents on non-injectable events). // - JSON envelopes: emit a single-line JSON object, only when text is // non-empty (an empty additionalContext is useless noise). +// Write to stdout synchronously. The dispatcher exits right after writing +// (process.exit drops writes still queued in libuv), and a skill body can be +// larger than the pipe buffer — a body-path injection would be silently +// truncated, dropping instructions the agent was supposed to receive. A sync +// write to fd 1 completes before the exit; failures stay fail-open because a +// closed stdout must never break the agent session. +function writeStdout(text) { + const buf = Buffer.from(text, "utf-8"); + let offset = 0; + try { + while (offset < buf.length) { + offset += writeSync(1, buf, offset, buf.length - offset); + } + } catch { + // fail-open: stdout closed or broken — emit nothing rather than throw + } +} + function writeOutput(text, envelope) { if (!text) return; if (envelope === "suppress") return; if (envelope === "hookSpecificOutput") { - process.stdout.write(JSON.stringify({ hookSpecificOutput: { additionalContext: text } }) + "\n"); + writeStdout(JSON.stringify({ hookSpecificOutput: { additionalContext: text } }) + "\n"); return; } if (envelope === "additionalContext") { - process.stdout.write(JSON.stringify({ additionalContext: text }) + "\n"); + writeStdout(JSON.stringify({ additionalContext: text }) + "\n"); return; } if (envelope === "additional_context") { - process.stdout.write(JSON.stringify({ additional_context: text }) + "\n"); + writeStdout(JSON.stringify({ additional_context: text }) + "\n"); return; } - process.stdout.write(text); + writeStdout(text); } function parseEnvelope(arg) { diff --git a/tests/bins.test.mjs b/tests/bins.test.mjs index ccfb990..b254002 100644 --- a/tests/bins.test.mjs +++ b/tests/bins.test.mjs @@ -27,3 +27,30 @@ test("version output matches package.json (no drift)", async () => { const { stdout } = await exec(process.execPath, ["bin/adlc-cli.mjs", "version"]); assert.equal(stdout.trim(), `adlc-cli ${pkg.version}`); }); + +// process.exit() terminates immediately and drops writes still queued in +// libuv: stdout to a pipe is asynchronous on POSIX. Both bins print, then +// exit, so without a flush the tail of a large output can be lost on a +// platform whose pipe buffer is small (Publish run 42608148983: macOS lost +// the last two panels of `workflow help`). This pins the contract the bins +// rely on: flush before process.exit. +test("flushStdio drains queued stdout before process.exit", async () => { + const cliUrl = new URL("../src/cli.mjs", import.meta.url).href; + const lines = 20000; // ~1.4 MB — far past any pipe buffer + const script = ` + const { flushStdio } = await import(process.env.ADLC_CLI_URL); + for (let i = 0; i < ${lines}; i++) { + process.stdout.write("line-" + i + " " + "x".repeat(60) + "\\n"); + } + await flushStdio(); + process.exit(0); + `; + const { stdout } = await exec( + process.execPath, + ["--input-type=module", "-e", script], + { maxBuffer: 16 * 1024 * 1024, env: { ...process.env, ADLC_CLI_URL: cliUrl } }, + ); + const expected = Array.from({ length: lines }, (_, i) => `line-${i} ${"x".repeat(60)}\n`).join(""); + assert.equal(stdout.length, expected.length, "stdout was truncated before exit"); + assert.ok(stdout.endsWith(`line-${lines - 1} ${"x".repeat(60)}\n`), "tail of stdout missing"); +}); diff --git a/tests/events.test.mjs b/tests/events.test.mjs index 7821be7..7f3def0 100644 --- a/tests/events.test.mjs +++ b/tests/events.test.mjs @@ -986,6 +986,41 @@ describe("Dispatcher: execution paths", () => { } }); + it("body path: a body larger than the pipe buffer is delivered whole", () => { + // process.exit() drops writes still queued in libuv. A body larger than + // the pipe buffer (200 KB here) makes that visible: the tail vanishes + // unless the writer drains stdout before exiting. Skill bodies routinely + // run tens of KB, and a truncated injection silently drops instructions. + const projectRoot = mkdtempSync(join(tmpdir(), "adlc-bigbody-")); + try { + const skillsDir = join(projectRoot, ".agents", "skills"); + mkdirSync(join(skillsDir, "big-body"), { recursive: true }); + const filler = "0123456789abcdef".repeat((200 * 1024) / 16); + writeFileSync( + join(skillsDir, "big-body", "SKILL.md"), + `---\nname: big-body\ndescription: oversized body\n---\n\nBEGIN-MARKER\n${filler}\nEND-MARKER\n`, + "utf-8", + ); + installDispatcher(projectRoot); + const dispatcher = join(projectRoot, DISPATCHER_REL); + + const result = spawnSync("node", [dispatcher, "session_start", "big-body", skillsDir, "10"], { + encoding: "utf-8", + cwd: projectRoot, + maxBuffer: 16 * 1024 * 1024, + }); + + assert.equal(result.status, 0, `dispatcher exited ${result.status}: ${result.stderr}`); + assert.ok(result.stdout.includes("BEGIN-MARKER"), "body head missing"); + assert.ok( + result.stdout.includes("END-MARKER"), + `body truncated at ${result.stdout.length} bytes (expected > 200 KB)`, + ); + } finally { + rmSync(projectRoot, { recursive: true, force: true }); + } + }); + it("script path: runs skill's script when scripts: present", () => { const projectRoot = mkdtempSync(join(tmpdir(), "adlc-script-")); try {