@operad-io/harness-codex 0.1.1 → 0.3.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/install.ts CHANGED
@@ -1,16 +1,48 @@
1
1
  /**
2
- * The user's own `codex-acp` and Codex: found, never bundled
3
- * (ADR 0022 D6, D8). `inspectCodex` is what
4
- * `operad plugin check` runs: `codex-acp --version`, `codex --version` and
5
- * `codex login status`. Credentials are the user's own Codex (ChatGPT) login;
6
- * operad never reads or writes them.
2
+ * The user's own Codex: found, never bundled (ADR 0022 D6, D8). `inspectCodex`
3
+ * is what `operad plugin check` runs: it asks the configured command for its
4
+ * help (which proves the app-server exists), reads `codex --version`, refuses
5
+ * a Codex older than the protocol this client was built against, and reads
6
+ * `codex login status`. Credentials are the user's own Codex login; operad
7
+ * never reads or writes them.
7
8
  */
8
9
 
9
- import { readFileSync, realpathSync } from "node:fs";
10
+ import { closeSync, openSync, readSync, realpathSync } from "node:fs";
11
+ import { fileURLToPath } from "node:url";
12
+ import type { HarnessModelCapability, HarnessModelInfo, HarnessModels } from "@operad-io/engine";
13
+ import { versionAtLeast } from "@operad-io/harness-process";
14
+
15
+ export { versionAtLeast };
10
16
 
11
17
  /** How long one probe may take. */
12
18
  const PROBE_TIMEOUT_MS = 30_000;
13
19
 
20
+ /** How long the app-server inside the model probe has to answer `model/list`. */
21
+ const MODELS_PROBE_TIMEOUT_MS = 8_000;
22
+
23
+ /** How long `codex login status` may take when a client asks for the login state. */
24
+ export const SIGNED_IN_PROBE_TIMEOUT_MS = 10_000;
25
+
26
+ /** How long a non-empty model list from the app-server is kept. */
27
+ export const MODELS_CACHE_MS = 30_000;
28
+
29
+ /**
30
+ * How soon an empty model list is tried again. An empty answer is not kept for
31
+ * `MODELS_CACHE_MS`: a Codex that was missing or busy at the last read gets
32
+ * another chance soon.
33
+ */
34
+ export const MODELS_EMPTY_RETRY_MS = 2_000;
35
+
36
+ /** The probe that speaks enough app-server to read the model list. */
37
+ const MODELS_PROBE = fileURLToPath(new URL("./models-probe.ts", import.meta.url));
38
+
39
+ /**
40
+ * The oldest Codex this client was built against. The protocol was read from
41
+ * codex-cli 0.166.0; an older Codex may not have the app-server at all, or may
42
+ * speak a different shape of it.
43
+ */
44
+ export const CODEX_FLOOR = "0.166.0";
45
+
14
46
  /** The check could not pass; the message says what to do. */
15
47
  export class CodexInstallError extends Error {
16
48
  constructor(message: string) {
@@ -20,21 +52,33 @@ export class CodexInstallError extends Error {
20
52
  }
21
53
 
22
54
  /**
23
- * The command that starts codex-acp when the `command` setting is unset: the
24
- * `bun` of PATH runs the real path of the `codex-acp` of PATH. codex-acp's
25
- * shebang is `#!/usr/bin/env node`, which finds a node only in a shell that
26
- * set one up (fnm), never in the process operad runs under.
55
+ * The command that starts the user's app-server when the `command` setting is
56
+ * unset: the `codex` of PATH with `app-server`. Codex's script has a
57
+ * `#!/usr/bin/env node` shebang, which finds a node only in a shell that set
58
+ * one up (fnm), so a script is run by the `bun` of PATH, or by this bun.
27
59
  */
28
60
  export function defaultCommand(path: string | undefined = process.env.PATH): readonly string[] {
29
- const bun = Bun.which("bun", { PATH: path ?? "" });
30
- if (bun === null) throw new CodexInstallError("no `bun` was found on PATH; codex-acp is started with it");
31
- const acp = Bun.which("codex-acp", { PATH: path ?? "" });
32
- if (acp === null) {
61
+ const key = path ?? "";
62
+ // Look codex up on every read: under fnm an upgrade moves it into a new node
63
+ // version directory, so a path remembered for the process would outlive it.
64
+ const found = Bun.which("codex", { PATH: key });
65
+ if (found === null) {
33
66
  throw new CodexInstallError(
34
- "no `codex-acp` was found on PATH; install it (bun add -g @agentclientprotocol/codex-acp) or set the command setting",
67
+ "no `codex` was found on PATH; install Codex (https://developers.openai.com/codex) or set the command setting",
35
68
  );
36
69
  }
37
- return [bun, realpathSync(acp)];
70
+ const real = realpathSync(found);
71
+ let command: readonly string[] = [real, "app-server"];
72
+ try {
73
+ const head = codexFileHead(real).split("\n")[0] ?? "";
74
+ if (head.startsWith("#!") && head.includes("node")) {
75
+ const bun = Bun.which("bun", { PATH: key }) ?? process.execPath;
76
+ command = [bun, real, "app-server"];
77
+ }
78
+ } catch {
79
+ // A native binary is not text.
80
+ }
81
+ return command;
38
82
  }
39
83
 
40
84
  /** The argv of the `command` setting, or the default one. */
@@ -49,6 +93,7 @@ export function commandOf(setting: unknown, path: string | undefined = process.e
49
93
  interface Ran {
50
94
  readonly exitCode: number | null;
51
95
  readonly stdout: string;
96
+ readonly stderr: string;
52
97
  }
53
98
 
54
99
  function run(argv: readonly string[], args: readonly string[]): Ran {
@@ -57,22 +102,41 @@ function run(argv: readonly string[], args: readonly string[]): Ran {
57
102
  stdin: "ignore",
58
103
  env: { ...process.env },
59
104
  stdout: "pipe",
60
- stderr: "ignore",
105
+ stderr: "pipe",
61
106
  timeout: PROBE_TIMEOUT_MS,
62
107
  });
63
- return { exitCode: ran.exitCode, stdout: ran.stdout.toString("utf8") };
108
+ return {
109
+ exitCode: ran.exitCode,
110
+ stdout: ran.stdout.toString("utf8"),
111
+ stderr: ran.stderr.toString("utf8"),
112
+ };
64
113
  } catch {
65
- return { exitCode: null, stdout: "" };
114
+ return { exitCode: null, stdout: "", stderr: "" };
115
+ }
116
+ }
117
+
118
+ /** How much of a command's file is read to see whether its shebang names node. */
119
+ export const CODEX_HEAD_BYTES = 128;
120
+
121
+ /** The first bytes of a command's file, enough for its shebang line. */
122
+ export function codexFileHead(path: string): string {
123
+ const descriptor = openSync(path, "r");
124
+ try {
125
+ const bytes = Buffer.alloc(CODEX_HEAD_BYTES);
126
+ const read = readSync(descriptor, bytes, 0, CODEX_HEAD_BYTES, 0);
127
+ return bytes.subarray(0, read).toString("utf8");
128
+ } finally {
129
+ closeSync(descriptor);
66
130
  }
67
131
  }
68
132
 
69
- /** The Codex command: its script run by the same bun when its shebang names node. */
133
+ /** The Codex command: its script run by bun when its shebang names node. */
70
134
  export function codexCommand(bun: string, path: string | undefined = process.env.PATH): readonly string[] | undefined {
71
135
  const found = Bun.which("codex", { PATH: path ?? "" });
72
136
  if (found === null) return undefined;
73
137
  const real = realpathSync(found);
74
138
  try {
75
- const head = readFileSync(real, "utf8").slice(0, 120).split("\n")[0] ?? "";
139
+ const head = codexFileHead(real).split("\n")[0] ?? "";
76
140
  if (head.startsWith("#!") && head.includes("node")) return [bun, real];
77
141
  } catch {
78
142
  // A native binary is not text.
@@ -94,32 +158,289 @@ function loginKind(stdout: string): string {
94
158
  return found?.[1] ?? "unknown login";
95
159
  }
96
160
 
161
+ /**
162
+ * Whether the user's Codex is signed in, from `codex login status`: true on a
163
+ * zero exit, false on a non-zero one, undefined when codex is absent or cannot
164
+ * be asked. It never blocks the event loop and reads no account detail.
165
+ */
166
+ export async function codexSignedIn(codex: readonly string[] | undefined): Promise<boolean | undefined> {
167
+ if (codex === undefined) return undefined;
168
+ const signal = AbortSignal.timeout(SIGNED_IN_PROBE_TIMEOUT_MS);
169
+ let child: ReturnType<typeof Bun.spawn>;
170
+ try {
171
+ child = Bun.spawn([...codex, "login", "status"], {
172
+ stdin: "ignore",
173
+ env: { ...process.env },
174
+ stdout: "ignore",
175
+ stderr: "ignore",
176
+ signal,
177
+ });
178
+ } catch {
179
+ return undefined;
180
+ }
181
+ try {
182
+ const exitCode = await child.exited;
183
+ if (signal.aborted || exitCode === null) return undefined;
184
+ return exitCode === 0;
185
+ } catch {
186
+ return undefined;
187
+ }
188
+ }
189
+
97
190
  /** What `operad plugin check` learns about the install. */
98
191
  export interface CodexInstall {
99
- readonly acpVersion: string;
100
192
  readonly codexVersion: string | undefined;
101
193
  /** The login kind, such as `ChatGPT`; undefined when Codex could not be asked. */
102
194
  readonly login: string | undefined;
103
195
  }
104
196
 
105
197
  /**
106
- * Starts codex-acp with `--version` and asks Codex about the login. Throws
107
- * `CodexInstallError` with what to do when codex-acp cannot start or Codex is
108
- * not logged in. A Codex that cannot be asked is reported as unknown.
198
+ * Proves the configured command has an app-server, reads the installed Codex
199
+ * version, refuses one older than `CODEX_FLOOR`, and asks the login kind.
200
+ * Throws `CodexInstallError` with what to do when the app-server cannot start,
201
+ * Codex is too old, or Codex is not logged in. A Codex that cannot be asked is
202
+ * reported as unknown.
109
203
  */
110
204
  export function inspectCodex(command: readonly string[], codex: readonly string[] | undefined): CodexInstall {
111
- const acp = run(command, ["--version"]);
112
- if (acp.exitCode !== 0) {
113
- throw new CodexInstallError(`\`${command.join(" ")} --version\` did not run; codex-acp cannot start`);
205
+ const help = run(command, ["--help"]);
206
+ if (help.exitCode !== 0) {
207
+ throw new CodexInstallError(
208
+ `\`${command.join(" ")} --help\` did not run; the installed Codex has no app-server ` +
209
+ `(this harness was built against codex-cli ${CODEX_FLOOR}); upgrade Codex or set the command setting`,
210
+ );
114
211
  }
115
- const acpVersion = versionOf(acp.stdout) ?? "unknown";
116
- if (codex === undefined) return { acpVersion, codexVersion: undefined, login: undefined };
212
+ if (codex === undefined) return { codexVersion: undefined, login: undefined };
117
213
  const version = run(codex, ["--version"]);
118
214
  const codexVersion = version.exitCode === 0 ? versionOf(version.stdout) : undefined;
215
+ if (codexVersion !== undefined && !versionAtLeast(codexVersion, CODEX_FLOOR)) {
216
+ throw new CodexInstallError(
217
+ `Codex ${codexVersion} is too old; this harness needs codex-cli ${CODEX_FLOOR} or newer ` +
218
+ `(its app-server protocol was read from ${CODEX_FLOOR})`,
219
+ );
220
+ }
119
221
  const status = run(codex, ["login", "status"]);
120
- if (status.exitCode === null) return { acpVersion, codexVersion, login: undefined };
222
+ if (status.exitCode === null) return { codexVersion, login: undefined };
121
223
  if (status.exitCode !== 0) {
122
224
  throw new CodexInstallError("Codex is not logged in; run `codex login` first");
123
225
  }
124
- return { acpVersion, codexVersion, login: loginKind(status.stdout) };
226
+ // `codex login status` writes its line to stderr, not stdout.
227
+ return { codexVersion, login: loginKind(`${status.stdout}${status.stderr}`) };
228
+ }
229
+
230
+ interface ModelsCache {
231
+ readonly at: number;
232
+ readonly value: HarnessModels;
233
+ }
234
+
235
+ const modelsCache = new Map<string, ModelsCache>();
236
+ const modelsLoading = new Map<string, Promise<HarnessModels>>();
237
+
238
+ /** What a probe of the app-server's model list prints: id, whether it is the default, and what it knows. */
239
+ interface ModelChoice {
240
+ readonly id: string;
241
+ readonly isDefault: boolean;
242
+ readonly contextWindow?: number | undefined;
243
+ readonly name?: string | undefined;
244
+ readonly provider?: string | undefined;
245
+ readonly capabilities?: readonly HarnessModelCapability[] | undefined;
246
+ }
247
+
248
+ function textField(record: Record<string, unknown>, ...names: readonly string[]): string | undefined {
249
+ for (const name of names) {
250
+ const value = record[name];
251
+ if (typeof value === "string" && value.length > 0) return value;
252
+ }
253
+ return undefined;
254
+ }
255
+
256
+ function capabilityFlag(record: Record<string, unknown>, name: string): boolean | undefined {
257
+ const capabilities = record["capabilities"];
258
+ if (typeof capabilities === "object" && capabilities !== null && !Array.isArray(capabilities)) {
259
+ const on = (capabilities as Record<string, unknown>)[name];
260
+ if (on === true) return true;
261
+ if (on === false) return false;
262
+ }
263
+ const direct = record[name];
264
+ if (typeof direct === "boolean") return direct;
265
+ return undefined;
266
+ }
267
+
268
+ function listField(record: Record<string, unknown>, ...names: readonly string[]): readonly string[] | undefined {
269
+ for (const name of names) {
270
+ const value = record[name];
271
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) {
272
+ return value as readonly string[];
273
+ }
274
+ }
275
+ return undefined;
276
+ }
277
+
278
+ function capabilitiesOf(record: Record<string, unknown>): readonly HarnessModelCapability[] | undefined {
279
+ const found: HarnessModelCapability[] = [];
280
+ const input = listField(record, "input", "inputModalities", "imageInput");
281
+ if (
282
+ input?.some((item) => item === "image" || item === "image_url" || item === "vision") === true ||
283
+ capabilityFlag(record, "vision") === true ||
284
+ record["supportsImages"] === true
285
+ ) {
286
+ found.push("vision");
287
+ }
288
+ if (capabilityFlag(record, "reasoning") === true || record["supportsReasoning"] === true) {
289
+ found.push("reasoning");
290
+ }
291
+ if (capabilityFlag(record, "tools") === true || record["supportsTools"] === true) {
292
+ found.push("tools");
293
+ }
294
+ if (
295
+ capabilityFlag(record, "web") === true ||
296
+ record["webSearch"] === true ||
297
+ record["supportsWebSearch"] === true
298
+ ) {
299
+ found.push("web");
300
+ }
301
+ return found.length === 0 ? undefined : found;
302
+ }
303
+
304
+ function emptyModels(): HarnessModels {
305
+ return { list: [], default: null };
306
+ }
307
+
308
+ function parseModels(stdout: string): readonly ModelChoice[] {
309
+ let value: unknown;
310
+ try {
311
+ value = JSON.parse(stdout);
312
+ } catch {
313
+ return [];
314
+ }
315
+ if (!Array.isArray(value)) return [];
316
+ const choices: ModelChoice[] = [];
317
+ for (const entry of value) {
318
+ if (typeof entry !== "object" || entry === null) continue;
319
+ const record = entry as Record<string, unknown>;
320
+ const id = record["id"];
321
+ if (typeof id === "string" && id.length > 0) {
322
+ const window = record["contextWindow"] ?? record["modelContextWindow"];
323
+ const name = textField(record, "displayName", "name");
324
+ const provider = textField(record, "provider", "modelProvider");
325
+ const capabilities = capabilitiesOf(record);
326
+ choices.push({
327
+ id,
328
+ isDefault: record["isDefault"] === true,
329
+ ...(typeof window === "number" && Number.isInteger(window) && window > 0
330
+ ? { contextWindow: window }
331
+ : {}),
332
+ ...(name === undefined ? {} : { name }),
333
+ ...(provider === undefined ? {} : { provider }),
334
+ ...(capabilities === undefined ? {} : { capabilities }),
335
+ });
336
+ }
337
+ }
338
+ return choices;
339
+ }
340
+
341
+ /** Asks a short-lived app-server for its model list; empty when it cannot answer. */
342
+ async function probeModels(command: readonly string[], timeoutMs: number): Promise<HarnessModels> {
343
+ let child: ReturnType<typeof Bun.spawn>;
344
+ try {
345
+ child = Bun.spawn([process.execPath, MODELS_PROBE, "--timeout-ms", String(timeoutMs), ...command], {
346
+ stdin: "ignore",
347
+ env: { ...process.env },
348
+ stdout: "pipe",
349
+ stderr: "ignore",
350
+ });
351
+ } catch {
352
+ return emptyModels();
353
+ }
354
+ // The backstop is above the probe's own timeout: it answers by then.
355
+ const timer = setTimeout(() => {
356
+ child.kill("SIGKILL");
357
+ }, timeoutMs + PROBE_TIMEOUT_MS);
358
+ try {
359
+ const stream = child.stdout;
360
+ if (!(stream instanceof ReadableStream)) {
361
+ await child.exited;
362
+ return emptyModels();
363
+ }
364
+ const [stdout, exitCode] = await Promise.all([
365
+ new Response(stream).text(),
366
+ child.exited,
367
+ ]);
368
+ if (exitCode !== 0) return emptyModels();
369
+ const choices = parseModels(stdout);
370
+ const list = choices.map((choice) => choice.id);
371
+ const fallback = choices.find((choice) => choice.isDefault)?.id ?? list[0] ?? null;
372
+ const windows: Record<string, number> = {};
373
+ const info: Record<string, HarnessModelInfo> = {};
374
+ for (const choice of choices) {
375
+ if (choice.contextWindow !== undefined) windows[choice.id] = choice.contextWindow;
376
+ if (
377
+ choice.name !== undefined ||
378
+ choice.provider !== undefined ||
379
+ choice.contextWindow !== undefined ||
380
+ choice.capabilities !== undefined
381
+ ) {
382
+ info[choice.id] = {
383
+ id: choice.id,
384
+ ...(choice.name === undefined ? {} : { name: choice.name }),
385
+ ...(choice.provider === undefined ? {} : { provider: choice.provider }),
386
+ ...(choice.contextWindow === undefined ? {} : { window: choice.contextWindow }),
387
+ ...(choice.capabilities === undefined ? {} : { capabilities: choice.capabilities }),
388
+ };
389
+ }
390
+ }
391
+ return {
392
+ list,
393
+ default: fallback,
394
+ ...(Object.keys(windows).length === 0 ? {} : { windows }),
395
+ ...(Object.keys(info).length === 0 ? {} : { info }),
396
+ };
397
+ } catch {
398
+ return emptyModels();
399
+ } finally {
400
+ clearTimeout(timer);
401
+ if (child.exitCode === null) child.kill("SIGKILL");
402
+ }
403
+ }
404
+
405
+ /**
406
+ * Refreshes the `model` choices from the app-server's own `model/list` (the
407
+ * same list the user's Codex shows). The read is asynchronous so a slow or
408
+ * missing Codex never holds up `serve`; concurrent reads share one probe.
409
+ */
410
+ export function refreshCodexModels(
411
+ command: readonly string[],
412
+ at: number = Date.now(),
413
+ timeoutMs: number = MODELS_PROBE_TIMEOUT_MS,
414
+ ): Promise<HarnessModels> {
415
+ const key = command.join("\u0000");
416
+ const pending = modelsLoading.get(key);
417
+ if (pending !== undefined) return pending;
418
+ const loading = probeModels(command, timeoutMs)
419
+ .then((value) => {
420
+ modelsCache.set(key, { at, value });
421
+ return value;
422
+ })
423
+ .finally(() => {
424
+ modelsLoading.delete(key);
425
+ });
426
+ modelsLoading.set(key, loading);
427
+ return loading;
428
+ }
429
+
430
+ function fresh(kept: ModelsCache, now: number): boolean {
431
+ const ttl = kept.value.list.length === 0 ? MODELS_EMPTY_RETRY_MS : MODELS_CACHE_MS;
432
+ return now - kept.at < ttl;
433
+ }
434
+
435
+ /**
436
+ * The `model` choices a chat may pick, from the cache. A missing or stale cache
437
+ * is refreshed in the background; this call returns the last answer (or none)
438
+ * at once, so it never blocks the event loop.
439
+ */
440
+ export function codexModels(command: readonly string[], now: number = Date.now()): HarnessModels {
441
+ const key = command.join("\u0000");
442
+ const kept = modelsCache.get(key);
443
+ if (kept !== undefined && fresh(kept, now)) return kept.value;
444
+ void refreshCodexModels(command, now).catch(() => undefined);
445
+ return kept?.value ?? emptyModels();
125
446
  }