Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

feat(runner): serve several agents from one runner (#193)

Croff0b969ee5e4a4
diff --git a/packages/runner/README.md b/packages/runner/README.md
index b80012ef..026ec6d5 100644
--- a/packages/runner/README.md
+++ b/packages/runner/README.md
@@ -3,7 +3,7 @@
[It's a Plan](https://itsaplan.dev) is a self-hosted, open-source issue tracker. An AI
agent in it is a project member: it has a role, permissions, and its own issues.
-This package runs one such agent on your own machine.
+This package runs such agents on your own machine — one, or several at once.
- Polls your instance for the agent's queued runs. Runs each one with a coding agent CLI.
Reports the result.
@@ -63,20 +63,21 @@ or mention it in a comment. The task then starts in your terminal.
`agent` names a CLI that the runner knows. The runner then builds the command itself: the
flags for an unattended run, and the session resume.
-| Agent | Runs | Keeps a chat session |
-| ---------- | ------------------------ | -------------------- |
-| `claude` | Claude Code | yes |
-| `codex` | Codex CLI | yes |
-| `opencode` | opencode | yes |
-| `gemini` | Gemini CLI | no |
-| `copilot` | GitHub Copilot CLI | no |
+| Agent | Runs | Keeps a chat session |
+| ---------- | ------------------ | -------------------- |
+| `claude` | Claude Code | yes |
+| `codex` | Codex CLI | yes |
+| `opencode` | opencode | yes |
+| `gemini` | Gemini CLI | no |
+| `copilot` | GitHub Copilot CLI | no |
Each preset needs the CLI's own MCP config.
[Coding agent setup](https://github.com/croffasia/itsaplan/blob/main/docs/runner.md) holds
that file, and the notes for each CLI.
-`--agent` on the command line has priority over the file. The runner appends the
-arguments after `--` to the ones from the preset:
+`--agent` on the command line has priority over the file, except over an `agents` entry
+that names its own. The runner appends the arguments after `--` to the ones from the
+preset:
```bash
npx -y @itsaplan/runner --agent claude -- --model opus
@@ -99,6 +100,52 @@ Your arguments come after the preset's own. A repeated flag thus replaces its va
`command` replaces the preset with your own shell command. The command receives the task
on stdin. The runner keeps no session for it, because it does not know how to resume one.
+## Several agents on one runner
+
+One key is one agent. A runner set up the way you want it can serve several of them at
+once: it polls for each key on its own, and every agent uses the coding agent, the working
+directory and the arguments the file already gives.
+
+```json
+{
+ "url": "http://localhost:3000",
+ "agent": "claude",
+ "cwd": "/Users/me/work/my-repo",
+ "apiKeys": ["the first agent's key", "the second agent's key"]
+}
+```
+
+Nothing else changes: the runner gives each command its own `ITSAPLAN_API_KEY`, so the one
+MCP config in that folder works for all of them.
+
+Use `agents` instead of `apiKeys` where an agent needs something of its own. A field an
+entry sets replaces the shared one, and it inherits every field it leaves out, except its
+`apiKey`, which every entry sets itself. `name` is what the runner's log lines call that
+agent; without it they number the agents `#1`, `#2` in the order of the file.
+
+```json
+{
+ "url": "http://localhost:3000",
+ "agent": "claude",
+ "cwd": "/Users/me/work/my-repo",
+ "agents": [
+ { "apiKey": "the first agent's key", "name": "planner" },
+ {
+ "apiKey": "the second agent's key",
+ "cwd": "/Users/me/work/other-repo",
+ "args": ["--model", "opus"]
+ }
+ ]
+}
+```
+
+`concurrency` counts per agent and per feed, so a runner with three agents at
+`concurrency: 2` can have six queued runs in flight and six chat answers alongside them,
+each one a coding agent CLI of its own. The environment variables and the command-line
+options describe every agent at once; an entry has priority over them.
+
+An agent whose key the instance refuses stops on its own, and the others keep working.
+
## Settings
The runner reads `./itsaplan-runner.json`. For a different file, give the path as an
@@ -109,21 +156,23 @@ npx -y @itsaplan/runner /path/to/config.json
```
The environment variables have priority over the file. The command-line options have
-priority over both.
-
-| Field | Environment variable | Default | What it does |
-| ---------------- | --------------------------- | ------------------ | ----------------------------------- |
-| `url` | `ITSAPLAN_URL` | required | Your Itsaplan instance |
-| `apiKey` | `ITSAPLAN_API_KEY` | required | The external agent's key |
-| `agent` | `ITSAPLAN_AGENT` | — | The coding agent to run |
-| `args` | | `[]` | Arguments added after the preset's |
-| `command` | `ITSAPLAN_COMMAND` | — | Your own command, instead of `agent` |
-| `cwd` | `ITSAPLAN_CWD` | where you start it | Working directory for the command |
-| `env` | | `{}` | Extra variables for the command |
-| `concurrency` | `ITSAPLAN_CONCURRENCY` | `1` | Tasks at once. Queued runs and chat answers count apart |
-| `pollIntervalMs` | `ITSAPLAN_POLL_INTERVAL_MS` | `3000` | Wait after an empty queue. Minimum 1000 |
-| `timeoutMs` | `ITSAPLAN_TIMEOUT_MS` | `1800000` | Time before the runner stops a task |
-| `outputFormat` | `ITSAPLAN_OUTPUT_FORMAT` | the preset's | How the runner reads a chat answer |
+priority over both. An `agents` entry has priority over all three, for the fields it sets.
+
+| Field | Environment variable | Default | What it does |
+| ---------------- | --------------------------- | ------------------ | ------------------------------------------------------------------ |
+| `url` | `ITSAPLAN_URL` | required | Your Itsaplan instance |
+| `apiKey` | `ITSAPLAN_API_KEY` | required | The external agent's key. Replaced by `apiKeys` or `agents` |
+| `apiKeys` | | — | Several keys, all with these settings. Not with `agents` |
+| `agents` | | — | Several agents, each with its own key and settings. Not with `apiKeys` |
+| `agent` | `ITSAPLAN_AGENT` | — | The coding agent to run |
+| `args` | | `[]` | Arguments added after the preset's |
+| `command` | `ITSAPLAN_COMMAND` | — | Your own command, instead of `agent` |
+| `cwd` | `ITSAPLAN_CWD` | where you start it | Working directory for the command |
+| `env` | | `{}` | Extra variables for the command |
+| `concurrency` | `ITSAPLAN_CONCURRENCY` | `1` | Tasks at once, per agent. Queued runs and chat answers count apart |
+| `pollIntervalMs` | `ITSAPLAN_POLL_INTERVAL_MS` | `3000` | Wait after an empty queue. Minimum 1000 |
+| `timeoutMs` | `ITSAPLAN_TIMEOUT_MS` | `1800000` | Time before the runner stops a task |
+| `outputFormat` | `ITSAPLAN_OUTPUT_FORMAT` | the preset's | How the runner reads a chat answer |
Set `agent` or `command`. With the environment you need no file at all:
@@ -148,12 +197,12 @@ sends `$ITSAPLAN_API_KEY` as a bearer token, and acts as its own user with its r
Every run holds these variables:
-| Variable | What it holds |
-| ------------------------ | ---------------------------------------------------------------- |
-| `ITSAPLAN_URL` | the instance that sent the task |
-| `ITSAPLAN_API_KEY` | the agent's key, for the API and the MCP server |
-| `ITSAPLAN_TRIGGER` | `mention`, `delegation`, `schedule`, `manual`, or `chat` |
-| `ITSAPLAN_SYSTEM_PROMPT` | the context of the run, for a command that takes a system prompt |
+| Variable | What it holds |
+| ------------------------ | ----------------------------------------------------------------- |
+| `ITSAPLAN_URL` | the instance that sent the task |
+| `ITSAPLAN_API_KEY` | the agent's key, for the API and the MCP server |
+| `ITSAPLAN_TRIGGER` | `mention`, `delegation`, `field`, `schedule`, `manual`, or `chat` |
+| `ITSAPLAN_SYSTEM_PROMPT` | the context of the run, for a command that takes a system prompt |
A queued run adds three more:
@@ -165,11 +214,11 @@ A queued run adds three more:
A chat message adds three others in their place, and `ITSAPLAN_TRIGGER` is `chat`:
-| Variable | What it holds |
-| ---------------------- | ---------------------------------------------------------------- |
-| `ITSAPLAN_THREAD_ID` | the conversation's id |
-| `ITSAPLAN_MESSAGE_ID` | the id of the message to answer |
-| `ITSAPLAN_SESSION_ID` | the coding agent's session to resume. Empty for the first message |
+| Variable | What it holds |
+| --------------------- | ----------------------------------------------------------------- |
+| `ITSAPLAN_THREAD_ID` | the conversation's id |
+| `ITSAPLAN_MESSAGE_ID` | the id of the message to answer |
+| `ITSAPLAN_SESSION_ID` | the coding agent's session to resume. Empty for the first message |
The task text of a chat message includes the conversation, unless a session holds it. See
Sessions below.
diff --git a/packages/runner/src/__tests__/config.test.ts b/packages/runner/src/__tests__/config.test.ts
new file mode 100644
index 00000000..e3174a64
--- /dev/null
+++ b/packages/runner/src/__tests__/config.test.ts
@@ -0,0 +1,128 @@
+import { describe, it, expect, beforeEach, afterAll } from 'bun:test';
+import { mkdtemp, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { loadConfig } from '../config';
+
+// The config is what decides which agents a runner serves and what each one runs, and a
+// wrong merge is silent: the runner starts, it just works for the wrong agent or with the
+// wrong CLI.
+
+const ITSAPLAN_VARS = Object.keys(process.env).filter((name) => name.startsWith('ITSAPLAN_'));
+const saved = Object.fromEntries(ITSAPLAN_VARS.map((name) => [name, process.env[name]]));
+
+let dir: string;
+
+beforeEach(async () => {
+ for (const name of Object.keys(process.env).filter((name) => name.startsWith('ITSAPLAN_'))) {
+ delete process.env[name];
+ }
+ dir = await mkdtemp(join(tmpdir(), 'itsaplan-runner-'));
+});
+
+afterAll(() => {
+ Object.assign(process.env, saved);
+});
+
+async function load(file: Record<string, unknown>, overrides = {}) {
+ const path = join(dir, 'itsaplan-runner.json');
+ await writeFile(path, JSON.stringify(file));
+ return loadConfig(path, overrides);
+}
+
+const base = { url: 'http://localhost:3000/', agent: 'claude' };
+
+describe('one agent', () => {
+ it('reads the file, with no name to put in front of its log lines', async () => {
+ const [config] = await load({ ...base, apiKey: 'key-a', concurrency: 4 });
+ expect(config).toMatchObject({
+ name: '',
+ url: 'http://localhost:3000',
+ apiKey: 'key-a',
+ agent: 'claude',
+ concurrency: 4,
+ });
+ });
+
+ it('takes the key from the environment, so it stays out of the file', async () => {
+ process.env.ITSAPLAN_API_KEY = 'key-env';
+ const [config] = await load(base);
+ expect(config.apiKey).toBe('key-env');
+ });
+});
+
+describe('several agents', () => {
+ it('runs the shared setup under each key in apiKeys', async () => {
+ const configs = await load({ ...base, cwd: '/work/repo', apiKeys: ['key-a', 'key-b'] });
+ expect(configs.map((config) => config.apiKey)).toEqual(['key-a', 'key-b']);
+ expect(configs.map((config) => config.name)).toEqual(['#1', '#2']);
+ for (const config of configs) {
+ expect(config).toMatchObject({ agent: 'claude', cwd: '/work/repo' });
+ }
+ });
+
+ it('lets an entry replace what it names and inherit the rest', async () => {
+ const [shared, own] = await load({
+ ...base,
+ cwd: '/work/repo',
+ concurrency: 2,
+ agents: [
+ { apiKey: 'key-a', name: 'planner' },
+ { apiKey: 'key-b', cwd: '/work/other', concurrency: 1, args: ['--model', 'opus'] },
+ ],
+ });
+ expect(shared).toMatchObject({ name: 'planner', cwd: '/work/repo', concurrency: 2, args: [] });
+ expect(own).toMatchObject({
+ name: '#2',
+ cwd: '/work/other',
+ concurrency: 1,
+ args: ['--model', 'opus'],
+ agent: 'claude',
+ });
+ });
+
+ it('drops the shared command when an entry names an agent, and the other way round', async () => {
+ const [preset, own] = await load({
+ url: base.url,
+ command: 'my-agent',
+ outputFormat: 'text',
+ agents: [{ apiKey: 'key-a', agent: 'codex' }, { apiKey: 'key-b' }],
+ });
+ // The shared format described the command, so the entry that replaced it reads codex's
+ // own stream instead of being handed 'text'.
+ expect(preset).toMatchObject({
+ agent: 'codex',
+ command: undefined,
+ outputFormat: 'codex-jsonl',
+ });
+ expect(own).toMatchObject({ agent: undefined, command: 'my-agent', outputFormat: 'text' });
+
+ const [entry] = await load({
+ ...base,
+ agents: [{ apiKey: 'key-a', command: 'my-agent', outputFormat: 'text' }],
+ });
+ expect(entry).toMatchObject({ agent: undefined, command: 'my-agent' });
+ });
+
+ it('gives an entry priority over the environment, which describes them all', async () => {
+ process.env.ITSAPLAN_AGENT = 'codex';
+ process.env.ITSAPLAN_API_KEY = 'key-env';
+ const [shared, own] = await load({
+ url: base.url,
+ agents: [{ apiKey: 'key-a' }, { apiKey: 'key-b', agent: 'gemini' }],
+ });
+ expect(shared).toMatchObject({ apiKey: 'key-a', agent: 'codex' });
+ expect(own).toMatchObject({ apiKey: 'key-b', agent: 'gemini' });
+ });
+
+ it('refuses a config that says both, or that lists no agent at all', async () => {
+ await expect(
+ load({ ...base, apiKeys: ['key-a'], agents: [{ apiKey: 'key-b' }] }),
+ ).rejects.toThrow('either apiKeys or agents');
+ await expect(load({ ...base, apiKeys: [] })).rejects.toThrow('cannot be empty');
+ // The shared key would be inherited, and both entries would poll as the one agent.
+ await expect(
+ load({ ...base, apiKey: 'key-shared', agents: [{ name: 'no key' }] }),
+ ).rejects.toThrow('each with its own apiKey');
+ });
+});
diff --git a/packages/runner/src/cli.ts b/packages/runner/src/cli.ts
index b8f76078..6a043adf 100755
--- a/packages/runner/src/cli.ts
+++ b/packages/runner/src/cli.ts
@@ -8,19 +8,26 @@ import { execute } from './execute';
// The runner holds no state — the queue is the server's — so stopping it mid-task only
// means that task's lease expires and another runner picks it up.
//
-// Two feeds are drained side by side: triggered runs, polled, and chat messages, claimed
-// by a call that waits on the server for one.
+// Two feeds are drained side by side per agent: triggered runs, polled, and chat
+// messages, claimed by a call that waits on the server for one. A config that lists
+// several agents runs that pair for each of them, in the one process.
const HEARTBEAT_MS = 60_000;
const ERROR_BACKOFF_MS = 5_000;
+type Log = (message: string) => void;
+
+function prefixOf(name: string): string {
+ return name ? `[itsaplan-runner ${name}]` : '[itsaplan-runner]';
+}
+
function log(message: string): void {
- console.log(`[itsaplan-runner] ${message}`);
+ console.log(`${prefixOf('')} ${message}`);
}
// A task can take much longer than the server's lease; without this it would be handed
// out again mid-flight.
-async function withHeartbeat<T>(beat: () => Promise<void>, work: Promise<T>): Promise<T> {
+async function withHeartbeat<T>(log: Log, beat: () => Promise<void>, work: Promise<T>): Promise<T> {
const timer = setInterval(() => {
beat().catch((err) => log(`heartbeat failed: ${String(err)}`));
}, HEARTBEAT_MS);
@@ -45,11 +52,12 @@ function taskOf(run: Run) {
};
}
-async function handle(config: RunnerConfig, client: Client, run: Run): Promise<void> {
+async function handle(config: RunnerConfig, client: Client, log: Log, run: Run): Promise<void> {
const label = run.issueIdentifier ?? `run ${run.id}`;
log(`${label}: started (${run.trigger})`);
try {
const outcome = await withHeartbeat(
+ log,
() => client.heartbeat(run.id),
execute(config, taskOf(run)),
);
@@ -67,11 +75,16 @@ async function handle(config: RunnerConfig, client: Client, run: Run): Promise<v
async function handleChat(
config: RunnerConfig,
client: Client,
+ log: Log,
message: ChatMessage,
): Promise<void> {
log(`chat ${message.id}: answering`);
try {
- await withHeartbeat(() => client.chatHeartbeat(message.id), answer(config, client, message));
+ await withHeartbeat(
+ log,
+ () => client.chatHeartbeat(message.id),
+ answer(config, client, message),
+ );
log(`chat ${message.id}: answered`);
} catch (err) {
// Without a reported failure the chat waits for an answer that is no longer coming.
@@ -86,6 +99,7 @@ async function handleChat(
// false to give the feed up entirely.
async function drain<T>(
state: { stopping: boolean },
+ log: Log,
concurrency: number,
take: () => Promise<T | null>,
run: (item: T) => Promise<void>,
@@ -145,28 +159,12 @@ function parseArgv(argv: string[]): { configPath?: string; agent?: string; args:
return parsed;
}
-async function main(): Promise<void> {
- const cli = parseArgv(process.argv.slice(2));
- const configPath =
- cli.configPath ?? process.env.ITSAPLAN_RUNNER_CONFIG ?? './itsaplan-runner.json';
- const config = await loadConfig(configPath, { agent: cli.agent, args: cli.args });
+// Everything one agent needs: the two feeds, until the runner is stopped or the server
+// refuses its key.
+async function serve(state: { stopping: boolean }, config: RunnerConfig): Promise<void> {
const client = new Client(config);
- const state = { stopping: false };
-
- for (const signal of ['SIGINT', 'SIGTERM'] as const) {
- process.on(signal, () => {
- // The commands run in their own process groups, so quitting now leaves them running
- // with nobody to report their result: the lease expires and the run is handed out
- // again.
- if (state.stopping) {
- log('quitting now — the commands in flight keep running, their runs are retried');
- process.exit(1);
- }
- state.stopping = true;
- log('stopping — finishing the tasks in flight, press again to quit now');
- });
- }
-
+ const prefix = prefixOf(config.name);
+ const log: Log = (message) => console.log(`${prefix} ${message}`);
log(
`running ${config.agent ?? 'the configured command'}, polling ${config.url} every ` +
`${config.pollIntervalMs}ms, up to ${config.concurrency} at once`,
@@ -175,9 +173,10 @@ async function main(): Promise<void> {
await Promise.all([
drain<Run>(
state,
+ log,
config.concurrency,
() => client.claim(),
- (run) => handle(config, client, run),
+ (run) => handle(config, client, log, run),
async () => {
await sleep(config.pollIntervalMs);
return true;
@@ -188,6 +187,7 @@ async function main(): Promise<void> {
// answers 404, and that loop ends rather than asking forever.
drain<ChatMessage>(
state,
+ log,
config.concurrency,
async () => {
try {
@@ -201,12 +201,50 @@ async function main(): Promise<void> {
throw err;
}
},
- (message) => handleChat(config, client, message),
+ (message) => handleChat(config, client, log, message),
() => Promise.resolve(chatSupported),
),
]);
}
+async function main(): Promise<void> {
+ const cli = parseArgv(process.argv.slice(2));
+ const configPath =
+ cli.configPath ?? process.env.ITSAPLAN_RUNNER_CONFIG ?? './itsaplan-runner.json';
+ const configs = await loadConfig(configPath, { agent: cli.agent, args: cli.args });
+ const state = { stopping: false };
+
+ for (const signal of ['SIGINT', 'SIGTERM'] as const) {
+ process.on(signal, () => {
+ // The commands run in their own process groups, so quitting now leaves them running
+ // with nobody to report their result: the lease expires and the run is handed out
+ // again.
+ if (state.stopping) {
+ log('quitting now — the commands in flight keep running, their runs are retried');
+ process.exit(1);
+ }
+ state.stopping = true;
+ log('stopping — finishing the tasks in flight, press again to quit now');
+ });
+ }
+
+ // One agent's key being refused says nothing about the others, so it does not take them
+ // down with it; the runner still exits non-zero once they are all finished.
+ const served = await Promise.all(
+ configs.map((config) =>
+ serve(state, config).then(
+ () => true,
+ (err: unknown) => {
+ const message = err instanceof Error ? err.message : String(err);
+ console.error(`${prefixOf(config.name)} stopped — ${message}`);
+ return false;
+ },
+ ),
+ ),
+ );
+ if (served.includes(false)) process.exit(1);
+}
+
main().catch((err) => {
console.error(`[itsaplan-runner] ${err instanceof Error ? err.message : String(err)}`);
process.exit(1);
diff --git a/packages/runner/src/client.ts b/packages/runner/src/client.ts
index 0f9efaea..9b3eb6cf 100644
--- a/packages/runner/src/client.ts
+++ b/packages/runner/src/client.ts
@@ -6,7 +6,7 @@ import type { RunnerConfig } from './config';
export interface Run {
id: number;
- trigger: 'mention' | 'delegation' | 'schedule' | 'manual';
+ trigger: 'mention' | 'delegation' | 'field' | 'schedule' | 'manual';
prompt: string;
systemPrompt: string;
issueId: number | null;
diff --git a/packages/runner/src/config.ts b/packages/runner/src/config.ts
index f52ab1e6..1f98bb43 100644
--- a/packages/runner/src/config.ts
+++ b/packages/runner/src/config.ts
@@ -5,8 +5,14 @@ import { PRESETS, PRESET_NAMES, isPresetName, type Preset, type PresetName } fro
// the runner builds the invocation, which is what lets it resume that CLI's sessions.
// `command` is a shell command the operator writes themselves, and no session is kept for
// it. `command` wins where both are set.
+//
+// One runner serves one agent per key, and a config may list several: `apiKeys` runs the
+// same setup under each key, `agents` is the same list where an entry can also change what
+// that agent runs. Loading a config therefore yields one of these per agent.
export interface RunnerConfig {
+ // What the runner's log lines say this agent is. Empty when only one is configured.
+ name: string;
url: string;
apiKey: string;
agent?: PresetName;
@@ -51,6 +57,11 @@ const DEFAULTS = {
// saves its operator.
const MIN_POLL_INTERVAL_MS = 1000;
+function textOf(value: unknown): string | undefined {
+ const text = typeof value === 'string' ? value.trim() : '';
+ return text || undefined;
+}
+
function intFrom(value: unknown, fallback: number): number {
const parsed = typeof value === 'string' ? Number.parseInt(value, 10) : value;
return typeof parsed === 'number' && Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
@@ -58,7 +69,7 @@ function intFrom(value: unknown, fallback: number): number {
// The preset's own format unless the operator names one.
function outputFormatFrom(value: unknown, preset: Preset | undefined): OutputFormat {
- const name = typeof value === 'string' ? value.trim() : '';
+ const name = textOf(value);
if (!name) return preset?.outputFormat ?? 'text';
const format = OUTPUT_FORMATS.find((candidate) => candidate === name);
if (!format) {
@@ -68,7 +79,7 @@ function outputFormatFrom(value: unknown, preset: Preset | undefined): OutputFor
}
function agentFrom(value: unknown): PresetName | undefined {
- const name = typeof value === 'string' ? value.trim() : '';
+ const name = textOf(value);
if (!name) return undefined;
if (!isPresetName(name)) {
throw new Error(`agent must be one of ${PRESET_NAMES.join(', ')}`);
@@ -85,7 +96,7 @@ function argsFrom(value: unknown): string[] {
}
function required(value: unknown, field: string): string {
- const text = typeof value === 'string' ? value.trim() : '';
+ const text = textOf(value);
if (!text) throw new Error(`${field} is required — set it in the config file or the environment`);
return text;
}
@@ -113,39 +124,124 @@ export interface ConfigOverrides {
args?: string[];
}
-// ITSAPLAN_* environment variables win over the file, so the key can stay out of it, and
-// the command line wins over both.
-export async function loadConfig(
- path: string,
- overrides: ConfigOverrides = {},
-): Promise<RunnerConfig> {
- const raw = await readConfigFile(path);
- const env = process.env;
- const agent = agentFrom(overrides.agent ?? env.ITSAPLAN_AGENT ?? raw.agent);
- const command =
- (env.ITSAPLAN_COMMAND ?? (raw.command as string | undefined))?.trim() || undefined;
+type Fields = Record<string, unknown>;
+
+// The list of agents to serve. `apiKeys` is the short form of an `agents` list that
+// changes nothing but the key; without either there is one agent, described by the file
+// itself.
+function agentFieldsFrom(file: Fields): Fields[] {
+ if (file.apiKeys !== undefined && file.agents !== undefined) {
+ throw new Error('set either apiKeys or agents, not both');
+ }
+ if (file.apiKeys !== undefined) {
+ const keys = file.apiKeys;
+ if (!Array.isArray(keys) || keys.some((key) => typeof key !== 'string')) {
+ throw new Error('apiKeys must be an array of strings');
+ }
+ return (keys as string[]).map((apiKey) => ({ apiKey }));
+ }
+ if (file.agents === undefined) return [{}];
+ const agents = file.agents;
+ // Without its own key an entry inherits the shared one, and two entries then poll as the
+ // same agent under different names, each with its own concurrency.
+ if (
+ !Array.isArray(agents) ||
+ agents.some(
+ (entry) =>
+ typeof entry !== 'object' ||
+ entry === null ||
+ Array.isArray(entry) ||
+ !textOf((entry as Fields).apiKey),
+ )
+ ) {
+ throw new Error('agents must be an array of objects, each with its own apiKey');
+ }
+ return agents as Fields[];
+}
+
+// The narrower side replaces the fields it sets, so `agent` and `command` — two ways to
+// say the same thing — never end up one from each side, where `command` would silently win
+// over the agent that was named. A format the wider side asked for described the mode it
+// named, so a narrower side that names another one drops it too and the new mode's preset
+// decides the format again.
+function merge(shared: Fields, own: Fields): Fields {
+ const merged = { ...shared, ...own };
+ const mode = textOf(own.agent) ?? textOf(own.command);
+ const changesMode =
+ mode !== undefined && mode !== (textOf(shared.agent) ?? textOf(shared.command));
+ if (textOf(own.agent)) delete merged.command;
+ else if (textOf(own.command)) delete merged.agent;
+ if (changesMode && !textOf(own.outputFormat)) delete merged.outputFormat;
+ return merged;
+}
+
+function nameOf(entry: Fields, index: number, total: number): string {
+ if (total === 1) return '';
+ return textOf(entry.name) ?? `#${index + 1}`;
+}
+
+function configFrom(fields: Fields, name: string, extraArgs: string[]): RunnerConfig {
+ const agent = agentFrom(fields.agent);
+ const command = textOf(fields.command);
if (!agent && !command) {
throw new Error(
`set either agent (one of ${PRESET_NAMES.join(', ')}) or command in the config file or the environment`,
);
}
return {
- url: required(env.ITSAPLAN_URL ?? raw.url, 'url').replace(/\/+$/, ''),
- apiKey: required(env.ITSAPLAN_API_KEY ?? raw.apiKey, 'apiKey'),
+ name,
+ url: required(fields.url, 'url').replace(/\/+$/, ''),
+ apiKey: required(fields.apiKey, 'apiKey'),
agent,
command,
- args: [...argsFrom(raw.args), ...(overrides.args ?? [])],
- cwd: (env.ITSAPLAN_CWD ?? (raw.cwd as string | undefined))?.replace(/^~/, env.HOME ?? '~'),
- env: (raw.env as Record<string, string> | undefined) ?? {},
- concurrency: intFrom(env.ITSAPLAN_CONCURRENCY ?? raw.concurrency, DEFAULTS.concurrency),
+ args: [...argsFrom(fields.args), ...extraArgs],
+ cwd: textOf(fields.cwd)?.replace(/^~/, process.env.HOME ?? '~'),
+ env: (fields.env as Record<string, string> | undefined) ?? {},
+ concurrency: intFrom(fields.concurrency, DEFAULTS.concurrency),
pollIntervalMs: Math.max(
- intFrom(env.ITSAPLAN_POLL_INTERVAL_MS ?? raw.pollIntervalMs, DEFAULTS.pollIntervalMs),
+ intFrom(fields.pollIntervalMs, DEFAULTS.pollIntervalMs),
MIN_POLL_INTERVAL_MS,
),
- timeoutMs: intFrom(env.ITSAPLAN_TIMEOUT_MS ?? raw.timeoutMs, DEFAULTS.timeoutMs),
- outputFormat: outputFormatFrom(
- env.ITSAPLAN_OUTPUT_FORMAT ?? raw.outputFormat,
- presetOf({ agent, command }),
- ),
+ timeoutMs: intFrom(fields.timeoutMs, DEFAULTS.timeoutMs),
+ outputFormat: outputFormatFrom(fields.outputFormat, presetOf({ agent, command })),
+ };
+}
+
+// Whatever the environment and the command line said, which is what the file's shared
+// fields are read through. An agent entry then wins over all three: it is the only place
+// that can describe one agent among several.
+function sharedFields(file: Fields, overrides: ConfigOverrides): Fields {
+ const env = process.env;
+ const outside: Fields = {
+ url: env.ITSAPLAN_URL,
+ apiKey: env.ITSAPLAN_API_KEY,
+ agent: overrides.agent ?? env.ITSAPLAN_AGENT,
+ command: env.ITSAPLAN_COMMAND,
+ cwd: env.ITSAPLAN_CWD,
+ concurrency: env.ITSAPLAN_CONCURRENCY,
+ pollIntervalMs: env.ITSAPLAN_POLL_INTERVAL_MS,
+ timeoutMs: env.ITSAPLAN_TIMEOUT_MS,
+ outputFormat: env.ITSAPLAN_OUTPUT_FORMAT,
};
+ // A variable that is not set says nothing about the field, so it must not overwrite it.
+ for (const [field, value] of Object.entries(outside)) {
+ if (!textOf(value)) delete outside[field];
+ }
+ return merge(file, outside);
+}
+
+// One config per agent the file lists, in its order.
+export async function loadConfig(
+ path: string,
+ overrides: ConfigOverrides = {},
+): Promise<RunnerConfig[]> {
+ const file = await readConfigFile(path);
+ const entries = agentFieldsFrom(file);
+ if (entries.length === 0) {
+ throw new Error('no agents configured — apiKeys and agents cannot be empty');
+ }
+ const shared = sharedFields(file, overrides);
+ return entries.map((entry, index) =>
+ configFrom(merge(shared, entry), nameOf(entry, index, entries.length), overrides.args ?? []),
+ );
}