@ziptie-soft/orca-local-decider 0.0.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/gateway.ts ADDED
@@ -0,0 +1,289 @@
1
+ import { readControlToken } from './launcher/local-token.ts';
2
+ import { gatewaySocketPathForEnv } from './launcher/socket-path.ts';
3
+ /**
4
+ * A small fail-open client of the local-decider gateway: `POST /v1/decide/command-risk` and
5
+ * `GET /health`. Every call has a hard timeout and resolves to `null` on any failure (gateway down,
6
+ * slow, redirected, non-2xx, bad JSON), so the hook falls back to Orca's own behaviour. It never
7
+ * throws, and never puts the token in a result or a log line.
8
+ */
9
+ import { socketFetch } from './launcher/transport.ts';
10
+
11
+ /** A decision request (`command-risk`, `routing`), as `packages/core/src/decision.ts` `DecideRequest` accepts it. */
12
+ export interface DecideBody {
13
+ readonly harness: 'orca';
14
+ readonly sessionId?: string;
15
+ readonly input: Readonly<Record<string, unknown>>;
16
+ readonly workspace?: { readonly cwd: string };
17
+ readonly call?: { readonly id: string };
18
+ /** The agent turn, so the gateway shares one answer with the hooks (see `turnKeyOfPane`). */
19
+ readonly turn?: { readonly key: string };
20
+ /** Routing only: the model the launch asks for, `<agent>/<model>`, for savings stats. */
21
+ readonly models?: { readonly requested: string };
22
+ }
23
+
24
+ export interface Decision {
25
+ readonly decisionId: string;
26
+ readonly mode: string;
27
+ readonly action: string;
28
+ readonly enforced: boolean;
29
+ readonly answers: Readonly<Record<string, unknown>>;
30
+ readonly error?: string;
31
+ /** Routing only: the config.yaml preset target for a `route:<preset>` action; not validated. */
32
+ readonly route?: unknown;
33
+ }
34
+
35
+ /** The gateway answered with HTTP 4xx: it runs, but refuses this request (old, or wrong token). */
36
+ export interface Rejected {
37
+ readonly rejected: number;
38
+ }
39
+ export type DecideReply = Decision | Rejected | null;
40
+
41
+ export function isDecision(reply: DecideReply): reply is Decision {
42
+ return reply !== null && !('rejected' in reply);
43
+ }
44
+
45
+ /** 408 and 429 mean "busy", not "refused", so they count as unreachable. */
46
+ function isRefusal(status: number): boolean {
47
+ return status >= 400 && status < 500 && status !== 408 && status !== 429;
48
+ }
49
+
50
+ /** `/health` fields the plugin shows; every field but `status` is optional. */
51
+ export interface GatewayHealth {
52
+ readonly status: string;
53
+ readonly version?: string;
54
+ readonly engine?: string;
55
+ readonly model?: string;
56
+ readonly engineState?: string;
57
+ readonly p50Ms?: number;
58
+ readonly p95Ms?: number;
59
+ }
60
+
61
+ export type PolicyMode = 'off' | 'shadow' | 'act';
62
+ export type ControlResult =
63
+ | { readonly ok: true }
64
+ | { readonly ok: false; readonly status?: number; readonly message: string };
65
+
66
+ export interface GatewayClient {
67
+ /** The decision; null when the gateway is unreachable; `Rejected` on a 4xx refusal. */
68
+ decide(policy: string, body: DecideBody, timeoutMs: number): Promise<DecideReply>;
69
+ /** The gateway's `/health` (`status` is `ok`, `degraded`, `down`), or null when unreachable. */
70
+ health(timeoutMs: number): Promise<GatewayHealth | null>;
71
+ /** The mode of `policy` from `GET /v1/policies`, or `unknown` on any failure. */
72
+ policyMode(policy: string, timeoutMs: number): Promise<PolicyMode | 'unknown'>;
73
+ /** `POST /v1/policies/:id/mode`. Gateway-wide; needs the local control token. */
74
+ setPolicyMode(policy: string, mode: PolicyMode, timeoutMs: number): Promise<ControlResult>;
75
+ /** `POST /v1/engine/load` or `/unload`; 200 and 202 are ok. */
76
+ engineLoad(action: 'load' | 'unload', timeoutMs: number): Promise<ControlResult>;
77
+ /** `GET /v1/stats?days=`: the rows, or null. */
78
+ stats(days: number, timeoutMs: number): Promise<unknown[] | null>;
79
+ /** Whether control calls can be sent: `remote` URLs never get the control token. */
80
+ control(): 'ok' | 'no-token' | 'remote';
81
+ }
82
+
83
+ export interface ClientOptions {
84
+ readonly url: string;
85
+ readonly defaultEndpoint: boolean;
86
+ readonly clientId: string;
87
+ readonly env: NodeJS.ProcessEnv;
88
+ readonly token?: string | undefined;
89
+ readonly fetch?: typeof fetch;
90
+ /** The control token, read per call; defaults to the gateway's config directory. */
91
+ readonly controlToken?: () => string | undefined;
92
+ }
93
+
94
+ const DECISION_ID = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
95
+ /** Kept back from the call's timeout so the gateway answers before the client gives up. */
96
+ const ROUND_TRIP_MS = 300;
97
+ const MESSAGE_CHARS = 200;
98
+ const CONTROL_HEADER = 'x-local-decider-control';
99
+ const POLICY_MODES: readonly string[] = ['off', 'shadow', 'act'];
100
+
101
+ function baseOf(raw: string): URL | null {
102
+ if (!URL.canParse(raw)) return null;
103
+ const url = new URL(raw);
104
+ const usable =
105
+ (url.protocol === 'http:' || url.protocol === 'https:') &&
106
+ url.username === '' &&
107
+ url.password === '';
108
+ return usable ? url : null;
109
+ }
110
+
111
+ function isLoopback(host: string): boolean {
112
+ return host === 'localhost' || host === '[::1]' || /^127(?:\.\d{1,3}){3}$/.test(host);
113
+ }
114
+
115
+ /** The bearer token goes only to an https URL or a loopback host. */
116
+ function tokenFor(base: URL, token: string | undefined): string | undefined {
117
+ if (token === undefined || token === '') return undefined;
118
+ return base.protocol === 'https:' || isLoopback(base.hostname) ? token : undefined;
119
+ }
120
+
121
+ function asDecision(value: unknown): Decision | null {
122
+ if (typeof value !== 'object' || value === null) return null;
123
+ const v = value as Record<string, unknown>;
124
+ const ok =
125
+ typeof v['decisionId'] === 'string' &&
126
+ DECISION_ID.test(v['decisionId']) &&
127
+ typeof v['mode'] === 'string' &&
128
+ typeof v['action'] === 'string' &&
129
+ typeof v['enforced'] === 'boolean' &&
130
+ typeof v['answers'] === 'object' &&
131
+ v['answers'] !== null &&
132
+ (v['error'] === undefined || typeof v['error'] === 'string');
133
+ return ok ? (v as unknown as Decision) : null;
134
+ }
135
+
136
+ function str(v: unknown): string | undefined {
137
+ return typeof v === 'string' ? v : undefined;
138
+ }
139
+
140
+ function num(v: unknown): number | undefined {
141
+ return typeof v === 'number' && Number.isFinite(v) ? v : undefined;
142
+ }
143
+
144
+ function asHealth(value: unknown): GatewayHealth | null {
145
+ if (typeof value !== 'object' || value === null) return null;
146
+ const v = value as Record<string, unknown>;
147
+ const status = str(v['status']);
148
+ if (status === undefined) return null;
149
+ const optional = {
150
+ version: str(v['version']),
151
+ engine: str(v['engine']),
152
+ model: str(v['model']),
153
+ engineState: str(v['engineState']),
154
+ p50Ms: num(v['p50Ms']),
155
+ p95Ms: num(v['p95Ms']),
156
+ };
157
+ const known = Object.entries(optional).filter(([, x]) => x !== undefined);
158
+ return { status, ...Object.fromEntries(known) };
159
+ }
160
+
161
+ function modeIn(rows: unknown, policy: string): PolicyMode | 'unknown' {
162
+ if (!Array.isArray(rows)) return 'unknown';
163
+ const row = (rows as unknown[]).find(
164
+ (r) => typeof r === 'object' && r !== null && (r as Record<string, unknown>)['id'] === policy,
165
+ ) as Record<string, unknown> | undefined;
166
+ const mode = row?.['mode'];
167
+ return typeof mode === 'string' && POLICY_MODES.includes(mode) ? (mode as PolicyMode) : 'unknown';
168
+ }
169
+
170
+ /** The gateway's error text, with every copy of the control token taken out. */
171
+ function errorText(body: unknown, secret: string): string {
172
+ const text =
173
+ typeof body === 'object' && body !== null
174
+ ? str((body as { error?: unknown }).error)
175
+ : undefined;
176
+ const clean = (text ?? 'the gateway refused the request').replaceAll(secret, '[redacted]');
177
+ return clean.slice(0, MESSAGE_CHARS);
178
+ }
179
+
180
+ interface Reply {
181
+ readonly status: number;
182
+ readonly body: unknown;
183
+ }
184
+
185
+ interface CallOptions {
186
+ readonly body?: unknown;
187
+ readonly headers?: Readonly<Record<string, string>>;
188
+ /** Read the body of a non-2xx reply too, for its error text. */
189
+ readonly errorBody?: boolean;
190
+ }
191
+
192
+ export function createGatewayClient(options: ClientOptions): GatewayClient {
193
+ const base = baseOf(options.url);
194
+ const socket = options.defaultEndpoint ? gatewaySocketPathForEnv(options.env) : null;
195
+ const send = options.fetch ?? (socket === null ? globalThis.fetch : socketFetch(socket));
196
+ const token = base === null ? undefined : tokenFor(base, options.token);
197
+ const prefix = base === null ? '' : `${base.origin}${base.pathname.replace(/\/+$/, '')}`;
198
+
199
+ const controlToken =
200
+ options.controlToken ?? ((): string | undefined => readControlToken(options.env));
201
+ const local = socket !== null || (base !== null && isLoopback(base.hostname));
202
+
203
+ function requestHeaders(opts: CallOptions): Headers {
204
+ const headers = new Headers({
205
+ 'accept': 'application/json',
206
+ 'x-local-decider-client': options.clientId,
207
+ ...opts.headers,
208
+ });
209
+ if (opts.body !== undefined) headers.set('content-type', 'application/json');
210
+ if (token !== undefined) headers.set('authorization', `Bearer ${token}`);
211
+ return headers;
212
+ }
213
+
214
+ async function call(
215
+ path: string,
216
+ timeoutMs: number,
217
+ opts: CallOptions = {},
218
+ ): Promise<Reply | null> {
219
+ if (base === null) return null;
220
+ try {
221
+ const res = await send(prefix + path, {
222
+ method: opts.body === undefined ? 'GET' : 'POST',
223
+ headers: requestHeaders(opts),
224
+ redirect: 'error',
225
+ signal: AbortSignal.timeout(timeoutMs),
226
+ ...(opts.body === undefined ? {} : { body: JSON.stringify(opts.body) }),
227
+ });
228
+ if (!res.ok && opts.errorBody !== true) return { status: res.status, body: undefined };
229
+ return { status: res.status, body: await res.json().catch(() => undefined) };
230
+ } catch {
231
+ return null;
232
+ }
233
+ }
234
+
235
+ function control(): 'ok' | 'no-token' | 'remote' {
236
+ if (!local) return 'remote';
237
+ return controlToken() === undefined ? 'no-token' : 'ok';
238
+ }
239
+
240
+ async function controlCall(
241
+ path: string,
242
+ body: unknown,
243
+ timeoutMs: number,
244
+ ): Promise<ControlResult> {
245
+ const state = control();
246
+ if (state === 'remote') return { ok: false, message: 'needs a local gateway' };
247
+ const secret = controlToken();
248
+ if (state === 'no-token' || secret === undefined) {
249
+ return { ok: false, message: 'needs the local control token' };
250
+ }
251
+ const reply = await call(path, timeoutMs, {
252
+ body,
253
+ headers: { [CONTROL_HEADER]: secret },
254
+ errorBody: true,
255
+ });
256
+ if (reply === null) return { ok: false, message: 'gateway unreachable' };
257
+ if (reply.status >= 200 && reply.status < 300) return { ok: true };
258
+ return { ok: false, status: reply.status, message: errorText(reply.body, secret) };
259
+ }
260
+
261
+ return {
262
+ async decide(policy, body, timeoutMs) {
263
+ const budgetMs = timeoutMs - ROUND_TRIP_MS;
264
+ const payload = budgetMs > 0 ? { ...body, budgetMs } : body;
265
+ const reply = await call(`/v1/decide/${encodeURIComponent(policy)}`, timeoutMs, {
266
+ body: payload,
267
+ });
268
+ if (reply !== null && isRefusal(reply.status)) return { rejected: reply.status };
269
+ return asDecision(reply?.body);
270
+ },
271
+ async health(timeoutMs) {
272
+ return asHealth((await call('/health', timeoutMs))?.body);
273
+ },
274
+ async policyMode(policy, timeoutMs) {
275
+ return modeIn((await call('/v1/policies', timeoutMs))?.body, policy);
276
+ },
277
+ setPolicyMode(policy, mode, timeoutMs) {
278
+ return controlCall(`/v1/policies/${encodeURIComponent(policy)}/mode`, { mode }, timeoutMs);
279
+ },
280
+ engineLoad(action, timeoutMs) {
281
+ return controlCall(`/v1/engine/${action}`, {}, timeoutMs);
282
+ },
283
+ async stats(days, timeoutMs) {
284
+ const rows = (await call(`/v1/stats?days=${Math.trunc(days)}`, timeoutMs))?.body;
285
+ return Array.isArray(rows) ? (rows as unknown[]) : null;
286
+ },
287
+ control,
288
+ };
289
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * What the deterministic guard says about a shell command, as an Orca hook result. The tool gate
3
+ * (`agent.tool.before`) and the terminal send guard (`terminal.send`) share it, so both refuse
4
+ * with the same reason.
5
+ */
6
+ import { guardCommand, MAX_COMMAND_CHARS, OVERSIZE_COMMAND, type GuardHit } from './core/guard.ts';
7
+ import type { Settings } from './settings.ts';
8
+
9
+ export const PREFIX = 'local-decider';
10
+ const DETAIL_CHARS = 120;
11
+
12
+ /** A hook's deny, or undefined to pass; the shape of both hooks' results. */
13
+ export type DenyResult = { readonly deny: string } | undefined;
14
+
15
+ export function oneLine(text: string): string {
16
+ const flat = text.replace(/[\p{Cc}\p{Cf}\s]+/gu, ' ').trim();
17
+ return flat.length > DETAIL_CHARS ? `${flat.slice(0, DETAIL_CHARS - 1)}…` : flat;
18
+ }
19
+
20
+ export function guardHit(command: string): GuardHit | null {
21
+ return command.length > MAX_COMMAND_CHARS ? OVERSIZE_COMMAND : guardCommand(command);
22
+ }
23
+
24
+ /** A deny for a guard hit, or undefined when the hit only asks and asks pass. */
25
+ export function guardResult(hit: GuardHit, settings: Settings): DenyResult {
26
+ if (hit.ask === true && settings.askAction === 'pass') return undefined;
27
+ return { deny: `${PREFIX} guard: ${oneLine(hit.reason)}. Ask the user before retrying.` };
28
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Says when a launched agent's hooks never arrive. A PTY wrapper in the shell's start-up files
3
+ * puts its own PTY between the pane and the agent, and Orca then drops that agent's hooks: the
4
+ * plugin sees the launch but never an `agent.status.changed` from the terminal. After a grace
5
+ * period the terminal is logged once and counted for the panel, until a status arrives from it.
6
+ * It holds terminal ids only: never terminal text, commands, prompts or tokens.
7
+ */
8
+ import { addBounded, setBounded } from './bounded.ts';
9
+
10
+ /** How long a launched agent may stay silent before it is reported. */
11
+ export const HOOK_WAIT_MS = 60_000;
12
+
13
+ export interface HookWatchDeps {
14
+ /** Runs `fn` after `ms`; returns a cancel function. */
15
+ readonly after: (fn: () => void, ms: number) => () => void;
16
+ readonly log: (message: string) => void;
17
+ /** The count of silent terminals changed. */
18
+ readonly onChange: () => void;
19
+ }
20
+
21
+ export interface HookWatch {
22
+ /** A Claude Code agent was launched in `terminalId`. Never throws. */
23
+ launched(terminalId: string): void;
24
+ /** An agent status arrived from `terminalId`. Never throws. */
25
+ seen(terminalId: string): void;
26
+ /** Launched agents whose hooks have not been seen after the wait. */
27
+ silent(): number;
28
+ /** Cancel every timer. */
29
+ dispose(): void;
30
+ }
31
+
32
+ function warning(terminalId: string): string {
33
+ return `local-decider: no agent status from terminal ${terminalId} after 60 s; a PTY wrapper in the shell start-up may hide its hooks (see README, Troubleshooting)`;
34
+ }
35
+
36
+ export function createHookWatch(deps: HookWatchDeps): HookWatch {
37
+ /** Terminals waiting for their first status, with the cancel function of their timer. */
38
+ const waiting = new Map<string, () => void>();
39
+ const silent = new Set<string>();
40
+ const logged = new Set<string>();
41
+
42
+ function expire(terminalId: string): void {
43
+ if (!waiting.delete(terminalId)) return;
44
+ addBounded(silent, terminalId);
45
+ if (!logged.has(terminalId)) {
46
+ addBounded(logged, terminalId);
47
+ deps.log(warning(terminalId));
48
+ }
49
+ deps.onChange();
50
+ }
51
+
52
+ return {
53
+ launched(terminalId) {
54
+ try {
55
+ waiting.get(terminalId)?.();
56
+ setBounded(
57
+ waiting,
58
+ terminalId,
59
+ deps.after(() => expire(terminalId), HOOK_WAIT_MS),
60
+ );
61
+ } catch {
62
+ // a failing timer never reaches the launch
63
+ }
64
+ },
65
+ seen(terminalId) {
66
+ waiting.get(terminalId)?.();
67
+ waiting.delete(terminalId);
68
+ if (silent.delete(terminalId)) deps.onChange();
69
+ },
70
+ silent: () => silent.size,
71
+ dispose() {
72
+ for (const cancel of waiting.values()) cancel();
73
+ waiting.clear();
74
+ },
75
+ };
76
+ }
@@ -0,0 +1,274 @@
1
+ /**
2
+ * The agent command Orca is about to run (`agent.launch.before` `command`), read and rewritten
3
+ * just enough to route a launch: find the prompt, set the model and the reasoning effort. Orca
4
+ * writes it as a binary followed by single-quoted words (`claude '--model' 'haiku' '--' 'Fix…'`).
5
+ * Anything else (double quotes, `$`, `;`, a newline outside quotes, …) is not parsed, so a command
6
+ * this module does not fully understand is never changed. Permission flags are never touched.
7
+ */
8
+
9
+ /** One shell word: what the shell passes on, and how it was written. */
10
+ interface Word {
11
+ readonly value: string;
12
+ readonly raw: string;
13
+ }
14
+
15
+ /** Longest command this module reads; a longer one is launched unchanged. */
16
+ export const MAX_COMMAND_CHARS = 200_000;
17
+ const BARE = /^[A-Za-z0-9_\-./:=@%+,]$/;
18
+ /** Model ids and effort levels written into the command; anything else is refused. */
19
+ const SAFE_VALUE = /^[A-Za-z0-9][A-Za-z0-9_\-.:[\]]{0,127}$/;
20
+ const EFFORT_KEY = 'model_reasoning_effort';
21
+
22
+ /** Codex options that take a value, so the word after one is never the prompt. */
23
+ const CODEX_VALUE_FLAGS = new Set([
24
+ '-c',
25
+ '--config',
26
+ '-m',
27
+ '--model',
28
+ '-p',
29
+ '--profile',
30
+ '-s',
31
+ '--sandbox',
32
+ '-a',
33
+ '--ask-for-approval',
34
+ '-C',
35
+ '--cd',
36
+ '-i',
37
+ '--image',
38
+ '--add-dir',
39
+ '--local-provider',
40
+ '--enable',
41
+ '--disable',
42
+ '--remote',
43
+ '--remote-auth-token-env',
44
+ ]);
45
+
46
+ /** Codex options that take no value, so the word after one can be the prompt. */
47
+ const CODEX_BOOLEAN_FLAGS = new Set([
48
+ '--full-auto',
49
+ '--dangerously-bypass-approvals-and-sandbox',
50
+ '--oss',
51
+ '--search',
52
+ '--no-alt-screen',
53
+ ]);
54
+
55
+ /** Reads one single-quoted span starting at `i` (the opening quote). */
56
+ function quoted(text: string, i: number): { value: string; end: number } | null {
57
+ const close = text.indexOf("'", i + 1);
58
+ return close === -1 ? null : { value: text.slice(i + 1, close), end: close + 1 };
59
+ }
60
+
61
+ /** The word starting at `start`, or null when it uses anything but bare text, `'…'` and `\'`. */
62
+ function wordAt(text: string, start: number): { word: Word; end: number } | null {
63
+ let value = '';
64
+ let i = start;
65
+ while (i < text.length && text[i] !== ' ') {
66
+ const c = text[i] ?? '';
67
+ if (c === "'") {
68
+ const span = quoted(text, i);
69
+ if (span === null) return null;
70
+ value += span.value;
71
+ i = span.end;
72
+ } else if (c === '\\' && text[i + 1] === "'") {
73
+ value += "'";
74
+ i += 2;
75
+ } else if (BARE.test(c)) {
76
+ value += c;
77
+ i += 1;
78
+ } else {
79
+ return null;
80
+ }
81
+ }
82
+ return { word: { value, raw: text.slice(start, i) }, end: i };
83
+ }
84
+
85
+ /** The command's words, or null when it is not a plain, fully quoted word list. */
86
+ export function splitCommand(command: string): Word[] | null {
87
+ if (command.length > MAX_COMMAND_CHARS) return null;
88
+ const words: Word[] = [];
89
+ let i = 0;
90
+ while (i < command.length) {
91
+ if (command[i] === ' ') {
92
+ i += 1;
93
+ continue;
94
+ }
95
+ const next = wordAt(command, i);
96
+ if (next === null) return null;
97
+ words.push(next.word);
98
+ i = next.end;
99
+ }
100
+ return words.length === 0 ? null : words;
101
+ }
102
+
103
+ /** `value` as one single-quoted shell word. */
104
+ export function quoteWord(value: string): string {
105
+ return `'${value.replaceAll("'", "'\\''")}'`;
106
+ }
107
+
108
+ function word(value: string): Word {
109
+ return { value, raw: quoteWord(value) };
110
+ }
111
+
112
+ export function joinCommand(words: readonly Word[]): string {
113
+ return words.map((w) => w.raw).join(' ');
114
+ }
115
+
116
+ /** Where the prompt is: its index, and where new options go (before it, or before `--`). */
117
+ interface PromptSlot {
118
+ readonly index: number;
119
+ readonly insertAt: number;
120
+ }
121
+
122
+ function claudeSlot(words: readonly Word[]): PromptSlot | null {
123
+ const dashes = words.findIndex((w, i) => i > 0 && w.value === '--');
124
+ return dashes === -1 || dashes !== words.length - 2
125
+ ? null
126
+ : { index: dashes + 1, insertAt: dashes };
127
+ }
128
+
129
+ /** True when the word at `index` ends what comes before a positional Codex prompt. */
130
+ function endsOptions(words: readonly Word[], index: number): boolean {
131
+ const before = words[index]?.value ?? '';
132
+ if (index === 0 || before === '--' || CODEX_BOOLEAN_FLAGS.has(before)) return true;
133
+ if (before.startsWith('-')) return before.startsWith('--') && before.includes('=');
134
+ return CODEX_VALUE_FLAGS.has(words[index - 1]?.value ?? '');
135
+ }
136
+
137
+ /** The last word is the prompt only when what precedes it is known not to take it as a value. */
138
+ function codexSlot(words: readonly Word[]): PromptSlot | null {
139
+ const last = words.length - 1;
140
+ const prompt = words[last]?.value ?? '';
141
+ if (last < 1 || prompt.startsWith('-') || !endsOptions(words, last - 1)) return null;
142
+ return { index: last, insertAt: last };
143
+ }
144
+
145
+ /** The agents whose launch command this module can route. */
146
+ export type RoutableAgent = 'claude' | 'codex';
147
+
148
+ export function routableAgent(agent: string): RoutableAgent | null {
149
+ if (agent === 'claude' || agent === 'claude-code') return 'claude';
150
+ return agent === 'codex' ? 'codex' : null;
151
+ }
152
+
153
+ /** A parsed launch: its words, the agent, and where the prompt is. */
154
+ export interface Launch {
155
+ readonly agent: RoutableAgent;
156
+ readonly words: readonly Word[];
157
+ readonly slot: PromptSlot;
158
+ }
159
+
160
+ export function parseLaunch(agent: RoutableAgent, command: string): Launch | null {
161
+ const words = splitCommand(command);
162
+ if (words === null) return null;
163
+ const slot = agent === 'claude' ? claudeSlot(words) : codexSlot(words);
164
+ if (slot === null || (words[slot.index]?.value.trim() ?? '') === '') return null;
165
+ return { agent, words, slot };
166
+ }
167
+
168
+ export function promptOf(launch: Launch): string {
169
+ return launch.words[launch.slot.index]?.value ?? '';
170
+ }
171
+
172
+ /** Where an option's value is: its word, and the option's name when it is written `--name=value`. */
173
+ interface ValueSlot {
174
+ readonly index: number;
175
+ readonly inline: string | undefined;
176
+ }
177
+
178
+ /** The slot of the last one of `flags` before `end` (as in the CLIs), or null. */
179
+ function valueSlot(
180
+ words: readonly Word[],
181
+ end: number,
182
+ flags: ReadonlySet<string>,
183
+ ): ValueSlot | null {
184
+ let found: ValueSlot | null = null;
185
+ for (let i = 1; i < end; i += 1) {
186
+ const text = words[i]?.value ?? '';
187
+ const eq = text.startsWith('--') ? text.indexOf('=') : -1;
188
+ if (flags.has(text) && i < end - 1) found = { index: i + 1, inline: undefined };
189
+ else if (eq > 0 && flags.has(text.slice(0, eq)))
190
+ found = { index: i, inline: text.slice(0, eq) };
191
+ }
192
+ return found;
193
+ }
194
+
195
+ /** The value in `slot`: the word, or what follows `=` in a `--name=value` word. */
196
+ function valueIn(words: readonly Word[], slot: ValueSlot): string | undefined {
197
+ const text = words[slot.index]?.value;
198
+ return slot.inline === undefined ? text : text?.slice(slot.inline.length + 1);
199
+ }
200
+
201
+ /** The slot of the last `-c model_reasoning_effort=…` value before `end`, or null. */
202
+ function effortSlot(words: readonly Word[], end: number): ValueSlot | null {
203
+ let found: ValueSlot | null = null;
204
+ for (let i = 1; i < end - 1; i += 1) {
205
+ const flag = words[i]?.value ?? '';
206
+ const value = words[i + 1]?.value ?? '';
207
+ if ((flag === '-c' || flag === '--config') && value.startsWith(`${EFFORT_KEY}=`)) {
208
+ found = { index: i + 1, inline: undefined };
209
+ }
210
+ }
211
+ return found;
212
+ }
213
+
214
+ const CLAUDE_MODEL = new Set(['--model']);
215
+ const CLAUDE_EFFORT = new Set(['--effort']);
216
+ const CODEX_MODEL = new Set(['--model', '-m']);
217
+
218
+ /** The model the command asks for, or undefined when it names none. */
219
+ export function modelOf(launch: Launch): string | undefined {
220
+ const flags = launch.agent === 'claude' ? CLAUDE_MODEL : CODEX_MODEL;
221
+ const slot = valueSlot(launch.words, launch.slot.insertAt, flags);
222
+ return slot === null ? undefined : valueIn(launch.words, slot);
223
+ }
224
+
225
+ /**
226
+ * Set the value in `slot` (keeping a `--name=value` word in that form), or insert `insert` before
227
+ * the prompt when there is no slot.
228
+ */
229
+ function setValue(
230
+ launch: Launch,
231
+ slot: ValueSlot | null,
232
+ insert: readonly Word[],
233
+ value: string,
234
+ ): Launch {
235
+ const words = [...launch.words];
236
+ if (slot !== null) {
237
+ words[slot.index] = word(slot.inline === undefined ? value : `${slot.inline}=${value}`);
238
+ return { ...launch, words };
239
+ }
240
+ words.splice(launch.slot.insertAt, 0, ...insert);
241
+ const shift = insert.length;
242
+ return {
243
+ ...launch,
244
+ words,
245
+ slot: { index: launch.slot.index + shift, insertAt: launch.slot.insertAt + shift },
246
+ };
247
+ }
248
+
249
+ export function isSafeValue(value: string): boolean {
250
+ return SAFE_VALUE.test(value);
251
+ }
252
+
253
+ /** The launch with its model set to `model` (an id `isSafeValue` accepts). */
254
+ export function withModel(launch: Launch, model: string): Launch {
255
+ const flags = launch.agent === 'claude' ? CLAUDE_MODEL : CODEX_MODEL;
256
+ const slot = valueSlot(launch.words, launch.slot.insertAt, flags);
257
+ const flag = launch.agent === 'claude' ? '--model' : '-m';
258
+ return setValue(launch, slot, [word(flag), word(model)], model);
259
+ }
260
+
261
+ /** The launch with its reasoning effort set to `effort` (a level `isSafeValue` accepts). */
262
+ export function withEffort(launch: Launch, effort: string): Launch {
263
+ if (launch.agent === 'claude') {
264
+ const slot = valueSlot(launch.words, launch.slot.insertAt, CLAUDE_EFFORT);
265
+ return setValue(launch, slot, [word('--effort'), word(effort)], effort);
266
+ }
267
+ const value = `${EFFORT_KEY}=${effort}`;
268
+ return setValue(
269
+ launch,
270
+ effortSlot(launch.words, launch.slot.insertAt),
271
+ [word('-c'), word(value)],
272
+ value,
273
+ );
274
+ }