Compare commits

..

1 Commits

Author SHA1 Message Date
diegosouzapw
b9da3156d0 fix(sse): route shell-reported Auggie CLI-not-found through the actionable message (#12645)
The `close` handlers in AuggieExecutor.runStreaming() and
runNonStreaming() only ever checked the child's spawn-level `error`
event against isEnoentLike()/cliNotFoundMessage(). On win32 (and any
POSIX shell reporting via a non-zero exit instead of a Node spawn
error), a missing `auggie` binary is reported as a normal process
exit with "is not recognized..."/"not found" text on stderr, which
close handlers surfaced verbatim instead of the existing friendly
install-guidance message.

Add isCliNotFoundText() to recognize these shell-reported shapes and
route them through cliNotFoundMessage() in both close handlers.
2026-09-10 15:21:59 -03:00
6 changed files with 136 additions and 149 deletions

View File

@@ -35,24 +35,16 @@ export function resolveOpencodeTarget(opts = {}) {
baseUrl = `http://localhost:${Number(opts.port ?? process.env.PORT ?? 20128) || 20128}`;
}
// Precedence: explicit --api-key flag > OMNIROUTE_API_KEY env var > active
// context's management token. A context's accessToken/apiKey is a CLI
// management credential (oma_live_...) with no /v1/* inference scope — it
// must never silently outrank a real inference key the caller supplied
// either as a flag or via the ambient env var (mirrors the explicit >
// ambient-env > context precedence documented in bin/cli/api.mjs's
// buildHeaders()). Only fall back to the context token when neither an
// explicit flag nor the env var is set.
let apiKey = opts.apiKey ?? opts["api-key"];
if (!apiKey) apiKey = process.env.OMNIROUTE_API_KEY || "";
if (!apiKey) {
try {
const c = resolveActiveContext(opts.context ?? process.env.OMNIROUTE_CONTEXT);
apiKey = c?.accessToken || c?.apiKey || "";
apiKey = c?.accessToken || c?.apiKey;
} catch {
/* no context auth */
}
}
if (!apiKey) apiKey = process.env.OMNIROUTE_API_KEY || "";
return { baseUrl: baseUrl.replace(/\/+$/, ""), apiKey };
}
@@ -185,17 +177,8 @@ export function registerSetupOpencode(program) {
"--allow-container-write",
"Write even when the target is inside a container and not mounted from the host"
)
.action(async (opts, cmd) => {
// Commander parses the ancestor program's own global --api-key option
// (bin/cli/program.mjs, bound to .env("OMNIROUTE_API_KEY")) against any
// occurrence of the flag in argv, so it wins the value even when the
// user typed --api-key AFTER `setup-opencode` — this local option's own
// `opts.apiKey` never sees it. cmd.optsWithGlobals() resolves to the
// correct value either way ("globals overwrite locals" is exactly the
// outcome we want here, since the global option is where the value
// always actually lands).
const resolvedOpts = { ...opts, apiKey: cmd.optsWithGlobals().apiKey ?? opts.apiKey };
const code = await runSetupOpencodeCommand(resolvedOpts);
.action(async (opts) => {
const code = await runSetupOpencodeCommand(opts);
if (code !== 0) process.exit(code);
});
}

View File

@@ -0,0 +1 @@
- fix(sse): surface the actionable "Auggie CLI not found" message when the shell reports a missing `auggie` binary via exit code instead of a spawn error (#12645)

View File

@@ -1 +0,0 @@
- fix(cli): setup-opencode no longer sends an active context's management token to `/v1/models` when `--api-key`/`OMNIROUTE_API_KEY` is supplied — an explicit flag or the env var now always outranks the context's token, and the flag itself is no longer swallowed by the parent program's global `--api-key` option (#12783)

View File

@@ -294,6 +294,24 @@ function isEnoentLike(message: string): boolean {
return message.includes("ENOENT") || message.includes("not found");
}
// Windows cmd.exe and POSIX shells never raise a Node `spawn` 'error' event for a
// missing binary when `shell: true` is used (see buildAuggieSpawnOptions) — they
// report it as a normal non-zero exit with the "not found" text on stderr instead.
// Recognize that shape too so the `close` handlers give the same actionable
// cliNotFoundMessage() as the `error` handlers already do. See #12645.
const CLI_NOT_FOUND_STDERR_PATTERNS = [
/is not recognized as an internal or external command/i,
/command not found/i,
// dash/POSIX `sh` shells report a missing executable as `<name>: not found`
// (no literal "command"), e.g. "sh: 1: auggie: not found".
/:\s*not found\s*$/im,
/No such file or directory/i,
];
function isCliNotFoundText(stderrTail: string): boolean {
return CLI_NOT_FOUND_STDERR_PATTERNS.some((pattern) => pattern.test(stderrTail));
}
export type AuggieCliVersionCheck = { ok: boolean; version?: string; error?: string };
/**
@@ -580,9 +598,11 @@ export class AuggieExecutor extends BaseExecutor {
if (finished) return;
if (code !== 0) {
emitError(
sanitizeErrorMessage(
`Auggie CLI exited with code ${code}${stderrTail ? `: ${stderrTail}` : ""}`
)
isCliNotFoundText(stderrTail)
? cliNotFoundMessage(auggieBin)
: sanitizeErrorMessage(
`Auggie CLI exited with code ${code}${stderrTail ? `: ${stderrTail}` : ""}`
)
);
return;
}
@@ -664,9 +684,11 @@ export class AuggieExecutor extends BaseExecutor {
if (code !== 0) {
settle(
buildAuggieErrorResponse(
sanitizeErrorMessage(
`Auggie CLI exited with code ${code}${stderrTail ? `: ${stderrTail}` : ""}`
)
isCliNotFoundText(stderrTail)
? cliNotFoundMessage(auggieBin)
: sanitizeErrorMessage(
`Auggie CLI exited with code ${code}${stderrTail ? `: ${stderrTail}` : ""}`
)
)
);
return;

View File

@@ -0,0 +1,103 @@
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { ExecuteInput } from "@omniroute/open-sse/executors/base";
const { AuggieExecutor, __resetAuggieModels } = await import(
"@omniroute/open-sse/executors/auggie"
);
function makeFakeAuggieBin(dir: string, stderrLine: string): string {
const fakeBin = path.join(dir, "fake-auggie.sh");
fs.writeFileSync(fakeBin, `#!/bin/sh\necho "${stderrLine}" 1>&2\nexit 1\n`);
fs.chmodSync(fakeBin, 0o755);
return fakeBin;
}
async function withFakeAuggieBin<T>(
stderrLine: string,
fn: (dir: string) => Promise<T>
): Promise<T> {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "auggie-probe-"));
const fakeBin = makeFakeAuggieBin(dir, stderrLine);
const prevBin = process.env.AUGGIE_BIN;
process.env.AUGGIE_BIN = fakeBin;
__resetAuggieModels();
try {
return await fn(dir);
} finally {
if (prevBin === undefined) delete process.env.AUGGIE_BIN;
else process.env.AUGGIE_BIN = prevBin;
__resetAuggieModels();
fs.rmSync(dir, { recursive: true, force: true });
}
}
test("Auggie CLI-not-found surfaced via shell exit code (non-streaming) gets the actionable cliNotFoundMessage", async () => {
await withFakeAuggieBin(
"'auggie' is not recognized as an internal or external command,",
async () => {
const executor = new AuggieExecutor();
const { response } = await executor.execute({
model: "",
body: { messages: [{ role: "user", content: "hi" }] },
stream: false,
credentials: {} as never,
} satisfies ExecuteInput);
const json = await response.json();
const message: string = json?.error?.message ?? "";
// sanitizeErrorMessage() redacts the absolute bin path (and anything the
// path-redaction tokenizer folds into it) — see errorPathRedaction.ts —
// so the assertion mirrors the existing precedent in
// auggie-executor.test.ts: assert the actionable prefix routed through
// cliNotFoundMessage(), and that the raw, confusing shell text from
// #12645 is gone.
assert.match(
message,
/Auggie CLI not found/,
`expected the actionable 'Auggie CLI not found' message, but got: ${message}`
);
assert.doesNotMatch(
message,
/is not recognized as an internal or external command/i,
`expected the raw shell text to be replaced, but got: ${message}`
);
}
);
});
test("Auggie CLI-not-found surfaced via shell exit code (streaming) gets the actionable cliNotFoundMessage", async () => {
await withFakeAuggieBin("sh: 1: auggie: not found", async () => {
const executor = new AuggieExecutor();
const { response } = await executor.execute({
model: "",
body: { messages: [{ role: "user", content: "hi" }] },
stream: true,
credentials: {} as never,
} satisfies ExecuteInput);
const text = await response.text();
const dataLine = text
.split("\n")
.find((line) => line.startsWith("data: ") && line.includes('"error"'));
assert.ok(dataLine, `expected an SSE error frame, got body: ${text}`);
const payload = JSON.parse(dataLine!.slice("data: ".length));
const message: string = payload?.error?.message ?? "";
assert.match(
message,
/Auggie CLI not found/,
`expected the actionable 'Auggie CLI not found' message, but got: ${message}`
);
assert.doesNotMatch(
message,
/exited with code/i,
`expected the raw shell exit-code text to be replaced, but got: ${message}`
);
});
});

View File

@@ -1,121 +0,0 @@
import assert from "node:assert/strict";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";
import { resolveOpencodeTarget } from "../../bin/cli/commands/setup-opencode.mjs";
/** Point OMNIROUTE_CONTEXT config resolution at an isolated, throwaway DATA_DIR. */
function withIsolatedContext(contextConfig, fn) {
const dir = mkdtempSync(join(tmpdir(), "omniroute-setup-opencode-test-"));
const originalDataDir = process.env.DATA_DIR;
process.env.DATA_DIR = dir;
writeFileSync(
join(dir, "config.json"),
JSON.stringify({
version: 1,
currentContext: "remote",
contexts: { remote: contextConfig },
})
);
try {
return fn();
} finally {
if (originalDataDir === undefined) delete process.env.DATA_DIR;
else process.env.DATA_DIR = originalDataDir;
rmSync(dir, { recursive: true, force: true });
}
}
function withEnvApiKey(value, fn) {
const original = process.env.OMNIROUTE_API_KEY;
if (value === undefined) delete process.env.OMNIROUTE_API_KEY;
else process.env.OMNIROUTE_API_KEY = value;
try {
return fn();
} finally {
if (original === undefined) delete process.env.OMNIROUTE_API_KEY;
else process.env.OMNIROUTE_API_KEY = original;
}
}
test("setup-opencode: --api-key typed AFTER the subcommand name is not stolen by the parent program's global option", async () => {
const { createProgram } = await import("../../bin/cli/program.mjs");
const program = createProgram();
const setupOpencode = program.commands.find((c) => c.name() === "setup-opencode");
assert.ok(setupOpencode, "setup-opencode subcommand must be registered");
let capturedApiKey;
setupOpencode._actionHandler = null; // avoid the real network-calling action
setupOpencode.action((opts, cmd) => {
capturedApiKey = cmd.optsWithGlobals().apiKey ?? opts.apiKey;
});
await program.parseAsync(
[
"node",
"omniroute",
"setup-opencode",
"--remote",
"http://100.64.0.1:20128",
"--api-key",
"sk-TESTKEY123",
],
{ from: "node" }
);
assert.equal(
capturedApiKey,
"sk-TESTKEY123",
"the CLI-supplied --api-key value must reach the setup-opencode action handler"
);
});
test("resolveOpencodeTarget: (a) explicit --api-key flag wins over an active context's management token", () => {
withEnvApiKey(undefined, () => {
withIsolatedContext(
{ baseUrl: "http://100.64.0.1:20128", accessToken: "oma_live_CONTEXT_TOKEN" },
() => {
const { apiKey } = resolveOpencodeTarget({ apiKey: "sk-FLAG", context: "remote" });
assert.equal(apiKey, "sk-FLAG");
}
);
});
});
test("resolveOpencodeTarget: (b) OMNIROUTE_API_KEY env wins over an active context's management token when no flag is passed", () => {
withEnvApiKey("sk-ENVKEY", () => {
withIsolatedContext(
{ baseUrl: "http://100.64.0.1:20128", accessToken: "oma_live_CONTEXT_TOKEN" },
() => {
const { apiKey } = resolveOpencodeTarget({ context: "remote" });
assert.equal(apiKey, "sk-ENVKEY");
}
);
});
});
test("resolveOpencodeTarget: (c) the context's token is used only when neither a flag nor the env var is set", () => {
withEnvApiKey(undefined, () => {
withIsolatedContext(
{ baseUrl: "http://100.64.0.1:20128", accessToken: "oma_live_CONTEXT_TOKEN" },
() => {
const { apiKey } = resolveOpencodeTarget({ context: "remote" });
assert.equal(apiKey, "oma_live_CONTEXT_TOKEN");
}
);
});
});
test("resolveOpencodeTarget: falls back to '' when neither a flag, env var, nor a resolvable context is present", () => {
withEnvApiKey(undefined, () => {
withIsolatedContext({ baseUrl: "http://100.64.0.1:20128" }, () => {
const { apiKey } = resolveOpencodeTarget({
remote: "http://100.64.0.1:20128",
context: "__no-such-context__",
});
assert.equal(apiKey, "");
});
});
});