Skip to content
Open
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
7 changes: 6 additions & 1 deletion docs-site/docs/getting-started/cli.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ request.
## Prerequisites

- Bun installed locally.
- An org API key created in Settings.
- An org API key created in Settings, API keys (`/settings#apikeys` on the web app).
- The hosted base URL for the environment you intend to use.

Keep the key in the environment. Do not put it in a JSONL task file, command
Expand All @@ -24,6 +24,11 @@ export USEAGENT_API_KEY="uak_example_replace_me"
export USEAGENT_BASE_URL="https://useagent.example.com"
```

If `USEAGENT_API_KEY` is missing, or the server does not accept it (HTTP 401), the
CLI exits 1 with a link to Settings, API keys on the server it called. Create a key
there and export it. An HTTP 403 means the key was accepted but its account cannot
reach that workspace, so a new key will not help.

## Run one task

The CLI package is private and unpublished. Run its checked-in entrypoint from
Expand Down
9 changes: 6 additions & 3 deletions packages/agent-client/src/fleet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,12 @@ export interface DispatchedRun {
readonly url: string;
}

/** Per-task result of a fan-out: never throws, so one bad task cannot sink the batch. */
/** Per-task result of a fan-out: never throws, so one bad task cannot sink the batch.
* A failure carries the HTTP status when the server answered, so a caller can tell a
* rejected key (401) from a bad task without reading the message. */
export type DispatchOutcome =
| { readonly ok: true; readonly task: FleetTask; readonly run: DispatchedRun }
| { readonly ok: false; readonly task: FleetTask; readonly error: string };
| { readonly ok: false; readonly task: FleetTask; readonly error: string; readonly status?: number };

export interface DispatchManyOptions {
/** Max in-flight dispatches (default 4). Clamped to >= 1. */
Expand Down Expand Up @@ -333,7 +335,8 @@ export function createFleetClient(config: FleetClientConfig): FleetClient {
try {
return { ok: true, task: keyed, run: await dispatch(keyed) } as const;
} catch (e) {
return { ok: false, task: keyed, error: errorMessage(e) } as const;
const status = e instanceof AgentClientError ? e.status : undefined;
return { ok: false, task: keyed, error: errorMessage(e), ...(status === undefined ? {} : { status }) } as const;
}
});
}
Expand Down
15 changes: 15 additions & 0 deletions packages/agent-client/test/fleet.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,11 +142,26 @@ describe("createFleetClient.dispatchMany", () => {
expect(out.map((o) => o.ok)).toEqual([true, false, true]);
const failed = out[1] as Extract<DispatchOutcome, { ok: false }>;
expect(failed.error).toContain("HTTP 500");
expect(failed.status).toBe(500);
expect(failed.task.prompt).toBe("boom");
const first = out[0] as Extract<DispatchOutcome, { ok: true }>;
expect(first.run.runId).toBe("ok_a");
});

test("leaves the status off a failure that never reached the server", async () => {
const client = createFleetClient({
...CONFIG,
fetch: async () => {
throw new Error("connection refused");
},
});
const [failed] = (await client.dispatchMany([{ prompt: "a" }])) as Extract<DispatchOutcome, { ok: false }>[];

expect(failed!.ok).toBe(false);
expect(failed!.error).toContain("connection refused");
expect(failed!.status).toBeUndefined();
});

test("applies idempotencyPrefix per index but never overrides an explicit key", async () => {
const keys: (string | undefined)[] = [];
const client = createFleetClient({
Expand Down
5 changes: 5 additions & 0 deletions packages/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ The key is sent verbatim as `Authorization: Bearer <key>` on every request. The
hosted origin lives in one place - the `DEFAULT_BASE_URL` constant - so run `useagent
--help` to see the current value.

Keys are made in the web app under Settings, API keys (`<base url>/settings#apikeys`).
When the key is missing, or the server answers 401, the CLI prints that link and exits 1.
A 403 means the server accepted the key but refused the request, so check the key's
workspace instead of replacing it. The MCP tools return the same messages.

## Commands

### `useagent run "<prompt>"`
Expand Down
13 changes: 5 additions & 8 deletions packages/cli/src/bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@

import process from "node:process";
import { readFile, writeFile } from "node:fs/promises";
import { CliError } from "./errors";
import { toCliError } from "./errors";
import { USAGE, parseFanArgs, parseRunArgs, parseStatusArgs } from "./args";
import { clientFromEnv } from "./config";
import { clientFromEnv, resolveBaseUrl } from "./config";
import { fanCommand, runCommand, statusCommand, type CommandIO } from "./commands";
import { runMcpServer } from "./mcp";

Expand Down Expand Up @@ -49,10 +49,7 @@ async function main(argv: readonly string[]): Promise<number> {
main(process.argv.slice(2))
.then((code) => process.exit(code))
.catch((error: unknown) => {
if (error instanceof CliError) {
process.stderr.write(`error: ${error.message}\n`);
process.exit(error.exitCode);
}
process.stderr.write(`error: ${error instanceof Error ? error.message : String(error)}\n`);
process.exit(1);
const failure = toCliError(error, resolveBaseUrl(process.env));
process.stderr.write(`error: ${failure.message}\n`);
process.exit(failure.exitCode);
});
8 changes: 8 additions & 0 deletions packages/cli/src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { FanArgs, RunArgs, StatusArgs } from "./args";
import { serializeResults, type FanResultLine } from "./jsonl";
import { parseTasksJsonl } from "./jsonl";
import { formatFanSummary } from "./format";
import { apiKeyFailure } from "./errors";

function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
Expand Down Expand Up @@ -63,6 +64,13 @@ export async function fanCommand(client: FleetClient, args: FanArgs, io: Command
io.err(`dispatching ${tasks.length} task(s), parallelism ${args.parallel}${args.qc ? ", QC on" : ""}...`);

const outcomes = await client.dispatchMany(tasks, { concurrency: args.parallel });
// A refused key fails every dispatch the same way: say so once, with the next step,
// instead of writing one result line per task.
const failures = outcomes.flatMap((outcome) => (outcome.ok ? [] : [outcome]));
if (failures.length === outcomes.length) {
const refused = failures.map((failure) => apiKeyFailure(failure.status, client.baseUrl)).find(Boolean);
if (refused) throw refused;
}
const results: FanResultLine[] = await Promise.all(
outcomes.map(async (outcome): Promise<FanResultLine> => {
if (!outcome.ok) {
Expand Down
18 changes: 14 additions & 4 deletions packages/cli/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,29 @@
// out) so it is unit-testable; clientFromEnv wires it to the fleet client.

import { createFleetClient, DEFAULT_BASE_URL, type FleetClient } from "@useagent/agent-client/fleet";
import { CliError } from "./errors";
import { apiKeysUrl, CliError } from "./errors";

export interface CliConfig {
readonly baseUrl: string;
readonly apiKey: string;
}

/** USEAGENT_BASE_URL (optional), defaulted to the hosted origin. */
export function resolveBaseUrl(env: Record<string, string | undefined>): string {
return env.USEAGENT_BASE_URL?.trim() || DEFAULT_BASE_URL;
}

/** Read USEAGENT_API_KEY (required) + USEAGENT_BASE_URL (optional, defaulted). Throws a
* terse CliError naming the missing variable exactly. */
* terse CliError naming the missing variable exactly, and where to make a key. */
export function resolveConfig(env: Record<string, string | undefined>): CliConfig {
const baseUrl = resolveBaseUrl(env);
const apiKey = env.USEAGENT_API_KEY?.trim();
if (!apiKey) throw new CliError("USEAGENT_API_KEY is not set", 1);
const baseUrl = env.USEAGENT_BASE_URL?.trim() || DEFAULT_BASE_URL;
if (!apiKey) {
throw new CliError(
`USEAGENT_API_KEY is not set. Create a key in Settings, API keys (${apiKeysUrl(baseUrl)}), then export USEAGENT_API_KEY=<key>`,
1,
);
}
return { baseUrl, apiKey };
}

Expand Down
35 changes: 35 additions & 0 deletions packages/cli/src/errors.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { AgentClientError } from "@useagent/agent-client/api";

/** A user-facing CLI failure. `exitCode` is the process code the bin exits with
* (2 for a usage error, 1 for an operational/config error). The message is terse
* and actionable - it names the missing env or the malformed input exactly. */
Expand All @@ -10,3 +12,36 @@ export class CliError extends Error {
this.name = "CliError";
}
}

/** Where a person makes an API key: the API keys section of Settings on the server the
* CLI talks to (the web app and the API share one origin). */
export function apiKeysUrl(baseUrl: string): string {
return `${baseUrl.replace(/\/+$/, "")}/settings#apikeys`;
}

/** The next step for a request the server refused over its credentials, or null for any
* other status. A 401 means the server did not accept the key (mistyped, revoked, or
* made on another server). A 403 means the key was accepted but its account may not do
* this, so the message never calls the key invalid. */
export function apiKeyFailure(status: number | undefined, baseUrl: string): CliError | null {
if (status === 401) {
return new CliError(
`${baseUrl} did not accept USEAGENT_API_KEY (HTTP 401). If it was revoked, mistyped or made on another server, create a key in Settings, API keys (${apiKeysUrl(baseUrl)}) and export it as USEAGENT_API_KEY`,
);
}
if (status === 403) {
return new CliError(
`${baseUrl} accepted USEAGENT_API_KEY but refused the request (HTTP 403). Check that the key's account is still a member of the workspace it was made in`,
);
}
return null;
}

/** Any failure as the CliError the bin prints: a CliError as it is, a refused key with its
* next step, and anything else with its own message and exit code 1. */
export function toCliError(error: unknown, baseUrl: string): CliError {
if (error instanceof CliError) return error;
const refused = error instanceof AgentClientError ? apiKeyFailure(error.status, baseUrl) : null;
if (refused) return refused;
return new CliError(error instanceof Error ? error.message : String(error));
}
9 changes: 8 additions & 1 deletion packages/cli/src/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
MAX_FLEET_TASKS,
type FleetClient,
} from "@useagent/agent-client/fleet";
import { toCliError } from "./errors";
import { coerceTask } from "./task";

const TASK_SHAPE: Tool["inputSchema"] = {
Expand Down Expand Up @@ -237,6 +238,12 @@ export async function handleToolCall(
}
}

/** A tool call that threw, as an error result. A refused key reaches the local agent
* with the next step, not just a status code. */
export function toolFailure(client: FleetClient, name: string, error: unknown): CallToolResult {
return errorResult(`tool ${name} failed: ${toCliError(error, client.baseUrl).message}`);
}

export function createFleetMcpServer(client: FleetClient): Server {
const server = new Server(
{ name: "useagent-fleet", version: "0.0.0" },
Expand All @@ -247,7 +254,7 @@ export function createFleetMcpServer(client: FleetClient): Server {
try {
return await handleToolCall(client, request.params.name, request.params.arguments ?? {});
} catch (e) {
return errorResult(`tool ${request.params.name} failed: ${e instanceof Error ? e.message : String(e)}`);
return toolFailure(client, request.params.name, e);
}
});
return server;
Expand Down
60 changes: 60 additions & 0 deletions packages/cli/test/commands.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { describe, expect, test } from "bun:test";
import { AgentClientError } from "@useagent/agent-client/api";
import { fanCommand, runCommand, statusCommand, type CommandIO } from "../src/commands";
import { CliError, toCliError } from "../src/errors";
import { fakeClient, makeApiRun } from "./fake-client";

function captureIO(files: Record<string, string> = {}): CommandIO & { stdout: string[]; stderr: string[]; written: Record<string, string> } {
Expand Down Expand Up @@ -47,6 +49,50 @@ describe("runCommand", () => {
});
});

describe("a refused API key", () => {
const rejected = (status: number) => async () => {
throw new AgentClientError("http_error", `POST /api/runs -> HTTP ${status}`, status);
};

test("run fails with the rejected-key message and exit 1 on a 401", async () => {
const io = captureIO();
const error = await runCommand(fakeClient({ dispatch: rejected(401) }), { prompt: "hi", repos: [], watch: false }, io).catch(
(e: unknown) => e,
);
const failure = toCliError(error, "https://fleet.test");

expect(failure.exitCode).toBe(1);
expect(failure.message).toContain("did not accept USEAGENT_API_KEY (HTTP 401)");
expect(failure.message).toContain("Settings, API keys (https://fleet.test/settings#apikeys)");
expect(io.stdout).toEqual([]);
});

test("status reports a 403 as refused access, not a bad key", async () => {
const error = await statusCommand(fakeClient({ getRun: rejected(403) }), { runId: "run_7" }, captureIO()).catch(
(e: unknown) => e,
);
const failure = toCliError(error, "https://fleet.test");

expect(failure.exitCode).toBe(1);
expect(failure.message).toContain("accepted USEAGENT_API_KEY but refused the request (HTTP 403)");
expect(failure.message).not.toContain("Create a key");
});

test("fan fails once with the rejected-key message when every dispatch got a 401", async () => {
const io = captureIO({ "tasks.jsonl": '{"prompt":"a"}\n{"prompt":"b"}\n' });
const client = fakeClient({
dispatchMany: async (tasks) =>
tasks.map((task) => ({ ok: false as const, task, error: "POST /api/runs -> HTTP 401", status: 401 })),
});
const error = await fanCommand(client, { file: "tasks.jsonl", parallel: 2 }, io).catch((e: unknown) => e);

expect(error).toBeInstanceOf(CliError);
expect((error as CliError).exitCode).toBe(1);
expect((error as CliError).message).toContain("Settings, API keys (https://fleet.test/settings#apikeys)");
expect(io.stdout).toEqual([]);
});
});

describe("statusCommand", () => {
test("prints status + url + answer for a known run", async () => {
const io = captureIO();
Expand Down Expand Up @@ -100,6 +146,20 @@ describe("fanCommand", () => {
expect(JSON.parse(printed[1]!)).toMatchObject({ status: "dispatch_error", error: "GET /api/runs -> HTTP 500" });
});

test("keeps the results of a batch where only some dispatches got a 401", async () => {
const io = captureIO(tasksFile);
const client = fakeClient({
dispatchMany: async (tasks) => [
{ ok: true, task: tasks[0]!, run: { runId: "run_0", status: "queued", url: "u0" } },
{ ok: false, task: tasks[1]!, error: "POST /api/runs -> HTTP 401", status: 401 },
],
});
const code = await fanCommand(client, { file: "tasks.jsonl", parallel: 2 }, io);
expect(code).toBe(1);
const rows = io.stdout.join("\n").trimEnd().split("\n").map((line) => JSON.parse(line));
expect(rows.map((row) => row.status)).toEqual(["completed", "dispatch_error"]);
});

test("preserves every result when one settle call fails", async () => {
const io = captureIO(tasksFile);
const client = fakeClient({
Expand Down
9 changes: 9 additions & 0 deletions packages/cli/test/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,13 @@ describe("resolveConfig", () => {
expect(() => resolveConfig({})).toThrow("USEAGENT_API_KEY is not set");
expect(() => resolveConfig({ USEAGENT_API_KEY: " " })).toThrow("USEAGENT_API_KEY is not set");
});

test("says where to make a key, on the server the CLI talks to", () => {
expect(() => resolveConfig({})).toThrow(
`USEAGENT_API_KEY is not set. Create a key in Settings, API keys (${DEFAULT_BASE_URL}/settings#apikeys), then export USEAGENT_API_KEY=<key>`,
);
expect(() => resolveConfig({ USEAGENT_BASE_URL: "https://agents.acme.dev/" })).toThrow(
"Settings, API keys (https://agents.acme.dev/settings#apikeys)",
);
});
});
55 changes: 55 additions & 0 deletions packages/cli/test/errors.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { describe, expect, test } from "bun:test";
import { AgentClientError } from "@useagent/agent-client/api";
import { apiKeyFailure, apiKeysUrl, CliError, toCliError } from "../src/errors";

describe("apiKeysUrl", () => {
test("points at the API keys section of Settings, with or without a trailing slash", () => {
expect(apiKeysUrl("https://app.example.com")).toBe("https://app.example.com/settings#apikeys");
expect(apiKeysUrl("https://app.example.com//")).toBe("https://app.example.com/settings#apikeys");
});
});

describe("apiKeyFailure", () => {
test("a 401 names the server and where to make a new key", () => {
const failure = apiKeyFailure(401, "https://app.example.com");
expect(failure?.message).toBe(
"https://app.example.com did not accept USEAGENT_API_KEY (HTTP 401). If it was revoked, mistyped or made on another server, create a key in Settings, API keys (https://app.example.com/settings#apikeys) and export it as USEAGENT_API_KEY",
);
expect(failure?.exitCode).toBe(1);
});

test("a 403 is refused access and never calls the key invalid", () => {
const failure = apiKeyFailure(403, "https://app.example.com");
expect(failure?.message).toContain("accepted USEAGENT_API_KEY but refused the request (HTTP 403)");
expect(failure?.message).not.toContain("did not accept");
expect(failure?.exitCode).toBe(1);
});

test("any other status, or none, is not about the key", () => {
for (const status of [undefined, 400, 404, 429, 500]) {
expect(apiKeyFailure(status, "https://app.example.com")).toBeNull();
}
});
});

describe("toCliError", () => {
test("passes a CliError through with its exit code", () => {
const usage = new CliError("unknown flag: --nope", 2);
expect(toCliError(usage, "https://app.example.com")).toBe(usage);
});

test("explains a refused key from the client", () => {
const failure = toCliError(
new AgentClientError("http_error", "POST /api/runs -> HTTP 401", 401),
"https://app.example.com",
);
expect(failure.message).toContain("Settings, API keys (https://app.example.com/settings#apikeys)");
expect(failure.exitCode).toBe(1);
});

test("keeps any other failure's message and exits 1", () => {
const server = toCliError(new AgentClientError("http_error", "GET /x -> HTTP 500", 500), "https://app.example.com");
expect([server.message, server.exitCode]).toEqual(["GET /x -> HTTP 500", 1]);
expect(toCliError("boom", "https://app.example.com").message).toBe("boom");
});
});
Loading
Loading