Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion bin/adlc-cli.mjs
Original file line number Diff line number Diff line change
@@ -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);
5 changes: 4 additions & 1 deletion bin/adlc-skills-cli.mjs
Original file line number Diff line number Diff line change
@@ -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);
26 changes: 26 additions & 0 deletions src/cli.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
});
}
28 changes: 23 additions & 5 deletions src/dispatcher.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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) {
Expand Down
27 changes: 27 additions & 0 deletions tests/bins.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});
35 changes: 35 additions & 0 deletions tests/events.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading