@operad-io/harness-pi 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.
@@ -0,0 +1,478 @@
1
+ /**
2
+ * The model list `pi --list-models` prints, kept as a file under the operad
3
+ * home. Reading it is synchronous, but asking pi never is: a stale list starts
4
+ * one background refresh that concurrent readers share, and a reader that
5
+ * needs a list before one exists can wait for that refresh.
6
+ */
7
+
8
+ import { readFileSync, statSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ import { isRecord, type HarnessModelCapability, type HarnessModelInfo } from "@operad-io/engine";
11
+ import { writeJsonAtomic } from "@operad-io/engine/platform";
12
+
13
+ /** How long `pi --list-models` may take before pi counts as not answering. */
14
+ export const PI_LIST_TIMEOUT_MS = 10_000;
15
+
16
+ /** How old the kept list may get before a read starts a background refresh. */
17
+ export const PI_LIST_CACHE_MS = 10 * 60_000;
18
+
19
+ /** How soon a failed refresh is tried again. */
20
+ export const PI_LIST_RETRY_MS = 60_000;
21
+
22
+ const MODEL_LIST_FILE = "model-list.json";
23
+
24
+ /** The file under the operad home that keeps pi's model list. */
25
+ export function piModelListPath(home: string): string {
26
+ return join(home, "harness", "pi", MODEL_LIST_FILE);
27
+ }
28
+
29
+ /** One row of `pi --list-models`: the model's provider/id and what its columns say. */
30
+ export interface PiCatalogueRow {
31
+ /** The provider/id a chat stores. */
32
+ readonly name: string;
33
+ /** A display name, when the table has a name column. */
34
+ readonly displayName?: string | undefined;
35
+ readonly provider?: string | undefined;
36
+ readonly window?: number | undefined;
37
+ readonly capabilities?: readonly HarnessModelCapability[] | undefined;
38
+ }
39
+
40
+ /** A human token count from pi's table (`400K`, `1M`, `1.5M`) as a whole number. */
41
+ export function parsePiTokenCount(value: string | undefined): number | undefined {
42
+ const found = value === undefined ? null : /^(\d+(?:\.\d+)?)([KM])?$/i.exec(value);
43
+ if (found === null) return undefined;
44
+ const count = Number(found[1]);
45
+ const unit = found[2]?.toUpperCase();
46
+ if (!Number.isFinite(count) || count <= 0) return undefined;
47
+ const tokens = unit === "M" ? count * 1_000_000 : unit === "K" ? count * 1_000 : count;
48
+ return Math.round(tokens);
49
+ }
50
+
51
+ const CAPABILITY_COLUMNS: readonly [string, HarnessModelCapability][] = [
52
+ ["thinking", "reasoning"],
53
+ ["images", "vision"],
54
+ ["tools", "tools"],
55
+ ["web", "web"],
56
+ ];
57
+
58
+ /** The rows of `pi --list-models`, with every column whose header names it. */
59
+ export function parsePiCatalogueModels(output: string): readonly PiCatalogueRow[] {
60
+ const found: PiCatalogueRow[] = [];
61
+ const names = new Set<string>();
62
+ let header: readonly string[] | undefined;
63
+ for (const line of output.split("\n")) {
64
+ const cells = line.trim().split(/\s+/);
65
+ const providerAt = cells.indexOf("provider");
66
+ const modelAt = cells.indexOf("model");
67
+ if (providerAt >= 0 && modelAt >= 0) {
68
+ header = cells.map((cell) => cell.toLowerCase());
69
+ continue;
70
+ }
71
+ if (header === undefined) continue;
72
+ const at = (name: string): number => header?.indexOf(name) ?? -1;
73
+ const provider = cells[at("provider")] ?? cells[0];
74
+ const id = cells[at("model")] ?? cells[1];
75
+ if (provider === undefined || id === undefined || provider.length === 0 || id.length === 0) continue;
76
+ const name = `${provider}/${id}`;
77
+ if (names.has(name)) continue;
78
+ names.add(name);
79
+ const contextColumn = at("context");
80
+ const window = parsePiTokenCount(contextColumn >= 0 ? cells[contextColumn] : cells[2]);
81
+ const displayName = at("name") >= 0 ? cells[at("name")] : undefined;
82
+ const capabilities: HarnessModelCapability[] = [];
83
+ for (const [column, capability] of CAPABILITY_COLUMNS) {
84
+ const value = at(column) >= 0 ? cells[at(column)]?.toLowerCase() : undefined;
85
+ if (value === "yes" || value === "true" || value === "1") capabilities.push(capability);
86
+ }
87
+ found.push({
88
+ name,
89
+ ...(displayName === undefined || displayName.length === 0 ? {} : { displayName }),
90
+ provider,
91
+ ...(window === undefined ? {} : { window }),
92
+ ...(capabilities.length === 0 ? {} : { capabilities }),
93
+ });
94
+ }
95
+ return found;
96
+ }
97
+
98
+ /** The rows of `pi --list-models`: provider/id, and the context column when it is a token count. */
99
+ export function parsePiCatalogueRows(output: string): readonly PiCatalogueRow[] {
100
+ return parsePiCatalogueModels(output).map((row) =>
101
+ row.window === undefined ? { name: row.name } : { name: row.name, window: row.window },
102
+ );
103
+ }
104
+
105
+ /**
106
+ * The rows of `pi --list-models` as provider/id: the first two columns of each
107
+ * row after the header row. Anything that is not such a row is skipped.
108
+ */
109
+ export function parsePiCatalogue(output: string): readonly string[] {
110
+ return parsePiCatalogueModels(output).map((row) => row.name);
111
+ }
112
+
113
+ /** What a file under the home holds: when it was read, the rows and their windows. */
114
+ interface KeptList {
115
+ readonly at: number;
116
+ readonly list: readonly string[];
117
+ readonly windows?: Readonly<Record<string, number>> | undefined;
118
+ readonly info?: Readonly<Record<string, HarnessModelInfo>> | undefined;
119
+ }
120
+
121
+ /** Where the list comes from and what a refresh may use. */
122
+ export interface PiModelListOptions {
123
+ readonly home: string;
124
+ readonly command: string;
125
+ readonly now: () => number;
126
+ readonly timeoutMs?: number | undefined;
127
+ readonly log?: ((message: string) => void) | undefined;
128
+ /** pi's registry store, beside its models file; the display names come from it. */
129
+ readonly registryPath?: string | undefined;
130
+ /** Test seam: reads a file as text; defaults to `readFileSync(path, "utf8")`. */
131
+ readonly readFile?: ((path: string) => string) | undefined;
132
+ }
133
+
134
+ interface KeptRead {
135
+ readonly at: number;
136
+ readonly list: readonly string[];
137
+ readonly windows?: Readonly<Record<string, number>> | undefined;
138
+ readonly info?: Readonly<Record<string, HarnessModelInfo>> | undefined;
139
+ }
140
+
141
+ const MODEL_CAPABILITY_ORDER = ["vision", "reasoning", "tools", "web"] as const;
142
+
143
+ function readCapabilities(value: unknown): readonly HarnessModelCapability[] | undefined {
144
+ if (!Array.isArray(value)) return undefined;
145
+ const found: HarnessModelCapability[] = [];
146
+ for (const item of value) {
147
+ if (item === "vision" || item === "reasoning" || item === "tools" || item === "web") found.push(item);
148
+ }
149
+ return found.length === 0 ? undefined : found;
150
+ }
151
+
152
+ function readInfo(value: unknown): Readonly<Record<string, HarnessModelInfo>> | undefined {
153
+ if (!isRecord(value)) return undefined;
154
+ const info: Record<string, HarnessModelInfo> = {};
155
+ for (const [id, raw] of Object.entries(value)) {
156
+ if (!isRecord(raw)) continue;
157
+ const name = raw["name"];
158
+ const provider = raw["provider"];
159
+ const window = raw["window"];
160
+ const capabilities = readCapabilities(raw["capabilities"]);
161
+ info[id] = {
162
+ id,
163
+ ...(typeof name === "string" && name.length > 0 ? { name } : {}),
164
+ ...(typeof provider === "string" && provider.length > 0 ? { provider } : {}),
165
+ ...(typeof window === "number" && Number.isInteger(window) && window > 0 ? { window } : {}),
166
+ ...(capabilities === undefined ? {} : { capabilities }),
167
+ };
168
+ }
169
+ return Object.keys(info).length === 0 ? undefined : info;
170
+ }
171
+
172
+ /**
173
+ * What pi's registry store says about each model, by provider/id. A model's
174
+ * `name`, `reasoning` and its `input` list are the registry's own fields;
175
+ * nothing is guessed when one is absent.
176
+ */
177
+ export function parsePiRegistry(value: unknown): Readonly<Record<string, HarnessModelInfo>> {
178
+ const info: Record<string, HarnessModelInfo> = {};
179
+ const add = (providerId: string, raw: unknown): void => {
180
+ if (!isRecord(raw)) return;
181
+ const id = raw["id"];
182
+ if (typeof id !== "string" || id.length === 0) return;
183
+ const provider =
184
+ typeof raw["provider"] === "string" && raw["provider"].length > 0 ? raw["provider"] : providerId;
185
+ if (provider.length === 0) return;
186
+ const name = raw["name"];
187
+ const window = raw["contextWindow"];
188
+ const capabilities: HarnessModelCapability[] = [];
189
+ const input = raw["input"];
190
+ if (Array.isArray(input) && input.includes("image")) capabilities.push("vision");
191
+ if (raw["reasoning"] === true) capabilities.push("reasoning");
192
+ const key = `${provider}/${id}`;
193
+ info[key] = {
194
+ id: key,
195
+ ...(typeof name === "string" && name.length > 0 ? { name } : {}),
196
+ provider,
197
+ ...(typeof window === "number" && Number.isInteger(window) && window > 0 ? { window } : {}),
198
+ ...(capabilities.length === 0 ? {} : { capabilities }),
199
+ };
200
+ };
201
+ if (!isRecord(value)) return info;
202
+ const providers = isRecord(value["providers"]) ? value["providers"] : value;
203
+ for (const [providerId, raw] of Object.entries(providers)) {
204
+ if (!isRecord(raw)) continue;
205
+ const models = raw["models"];
206
+ if (!Array.isArray(models)) continue;
207
+ for (const model of models) add(providerId, model);
208
+ }
209
+ return info;
210
+ }
211
+
212
+ interface RegistryCache {
213
+ readonly mtimeMs: number;
214
+ readonly size: number;
215
+ readonly info: Readonly<Record<string, HarnessModelInfo>>;
216
+ }
217
+
218
+ const registryCache = new Map<string, RegistryCache>();
219
+
220
+ function readText(options: PiModelListOptions, path: string): string {
221
+ return (options.readFile ?? ((file: string) => readFileSync(file, "utf8")))(path);
222
+ }
223
+
224
+ function registryOf(options: PiModelListOptions): Readonly<Record<string, HarnessModelInfo>> {
225
+ if (options.registryPath === undefined) return {};
226
+ const path = options.registryPath;
227
+ try {
228
+ const stat = statSync(path);
229
+ const kept = registryCache.get(path);
230
+ if (kept !== undefined && kept.mtimeMs === stat.mtimeMs && kept.size === stat.size) {
231
+ return kept.info;
232
+ }
233
+ const info = parsePiRegistry(JSON.parse(readText(options, path)));
234
+ registryCache.set(path, { mtimeMs: stat.mtimeMs, size: stat.size, info });
235
+ return info;
236
+ } catch {
237
+ registryCache.delete(path);
238
+ return {};
239
+ }
240
+ }
241
+
242
+ function mergeInfo(base: HarnessModelInfo | undefined, found: HarnessModelInfo): HarnessModelInfo {
243
+ const capabilities = new Set<HarnessModelCapability>([
244
+ ...(base?.capabilities ?? []),
245
+ ...(found.capabilities ?? []),
246
+ ]);
247
+ return {
248
+ id: found.id,
249
+ ...(found.name !== undefined || base?.name !== undefined
250
+ ? { name: found.name ?? base?.name }
251
+ : {}),
252
+ ...(found.provider !== undefined || base?.provider !== undefined
253
+ ? { provider: found.provider ?? base?.provider }
254
+ : {}),
255
+ ...(found.window !== undefined || base?.window !== undefined
256
+ ? { window: found.window ?? base?.window }
257
+ : {}),
258
+ ...(capabilities.size === 0
259
+ ? {}
260
+ : { capabilities: MODEL_CAPABILITY_ORDER.filter((capability) => capabilities.has(capability)) }),
261
+ };
262
+ }
263
+
264
+ function keptOf(value: unknown): KeptList | undefined {
265
+ if (!isRecord(value)) return undefined;
266
+ const at = value["at"];
267
+ const list = value["list"];
268
+ if (typeof at !== "number" || !Number.isFinite(at) || at < 0) return undefined;
269
+ if (!Array.isArray(list)) return undefined;
270
+ if (!list.every((item): item is string => typeof item === "string")) return undefined;
271
+ const windows: Record<string, number> = {};
272
+ const raw = value["windows"];
273
+ if (isRecord(raw)) {
274
+ for (const [name, window] of Object.entries(raw)) {
275
+ if (typeof window === "number" && Number.isInteger(window) && window > 0) windows[name] = window;
276
+ }
277
+ }
278
+ const info = readInfo(value["info"]);
279
+ return {
280
+ at,
281
+ list,
282
+ ...(Object.keys(windows).length === 0 ? {} : { windows }),
283
+ ...(info === undefined ? {} : { info }),
284
+ };
285
+ }
286
+
287
+ /** The list the home keeps for this command, or undefined when there is none. */
288
+ export function readPiModelList(options: PiModelListOptions): KeptRead | undefined {
289
+ try {
290
+ const value: unknown = JSON.parse(readText(options, piModelListPath(options.home)));
291
+ const kept = keptOf(value);
292
+ return kept === undefined
293
+ ? undefined
294
+ : {
295
+ at: kept.at,
296
+ list: kept.list,
297
+ ...(kept.windows === undefined ? {} : { windows: kept.windows }),
298
+ ...(kept.info === undefined ? {} : { info: kept.info }),
299
+ };
300
+ } catch {
301
+ return undefined;
302
+ }
303
+ }
304
+
305
+ const refreshing = new Map<string, Promise<readonly string[]>>();
306
+ const failedAt = new Map<string, number>();
307
+ const failedLogged = new Set<string>();
308
+
309
+ function keyOf(options: PiModelListOptions): string {
310
+ return `${options.home}\u0000${options.command}`;
311
+ }
312
+
313
+ function unref(timer: unknown): void {
314
+ if (typeof timer === "object" && timer !== null && "unref" in timer) {
315
+ (timer as { unref(): void }).unref();
316
+ }
317
+ }
318
+
319
+ async function textOf(stream: unknown): Promise<string> {
320
+ return stream instanceof ReadableStream ? await new Response(stream).text() : "";
321
+ }
322
+
323
+ /** Asks pi once. Undefined means it failed, was killed, or answered with an error. */
324
+ async function probe(options: PiModelListOptions): Promise<readonly PiCatalogueRow[] | undefined> {
325
+ let child: ReturnType<typeof Bun.spawn>;
326
+ try {
327
+ child = Bun.spawn([options.command, "--list-models"], {
328
+ stdin: "ignore",
329
+ stdout: "pipe",
330
+ stderr: "pipe",
331
+ });
332
+ } catch {
333
+ return undefined;
334
+ }
335
+ // A refresh from a short command must not keep that command alive.
336
+ child.unref();
337
+ let timedOut = false;
338
+ const timer = setTimeout(() => {
339
+ timedOut = true;
340
+ child.kill("SIGKILL");
341
+ }, options.timeoutMs ?? PI_LIST_TIMEOUT_MS);
342
+ unref(timer);
343
+ try {
344
+ const [out, err, exitCode] = await Promise.all([
345
+ textOf(child.stdout),
346
+ textOf(child.stderr),
347
+ child.exited,
348
+ ]);
349
+ if (timedOut || exitCode !== 0) return undefined;
350
+ return parsePiCatalogueModels(out.trim() === "" ? err : out);
351
+ } catch {
352
+ return undefined;
353
+ } finally {
354
+ clearTimeout(timer);
355
+ if (child.exitCode === null) child.kill("SIGKILL");
356
+ }
357
+ }
358
+
359
+ async function writeKept(
360
+ options: PiModelListOptions,
361
+ rows: readonly PiCatalogueRow[],
362
+ at: number,
363
+ ): Promise<void> {
364
+ const path = piModelListPath(options.home);
365
+ const windows: Record<string, number> = {};
366
+ const info: Record<string, HarnessModelInfo> = {};
367
+ for (const row of rows) {
368
+ if (row.window !== undefined) windows[row.name] = row.window;
369
+ info[row.name] = {
370
+ id: row.name,
371
+ ...(row.displayName === undefined ? {} : { name: row.displayName }),
372
+ ...(row.provider === undefined ? {} : { provider: row.provider }),
373
+ ...(row.window === undefined ? {} : { window: row.window }),
374
+ ...(row.capabilities === undefined ? {} : { capabilities: row.capabilities }),
375
+ };
376
+ }
377
+ const kept: KeptList = {
378
+ at,
379
+ list: rows.map((row) => row.name),
380
+ ...(Object.keys(windows).length === 0 ? {} : { windows }),
381
+ ...(Object.keys(info).length === 0 ? {} : { info }),
382
+ };
383
+ await writeJsonAtomic(path, kept);
384
+ }
385
+
386
+ /**
387
+ * Asks pi for its list in the background. Concurrent callers share one ask; a
388
+ * failed or timed-out ask keeps the previous file and is not tried again until
389
+ * `PI_LIST_RETRY_MS` passes. It is logged once until an ask succeeds.
390
+ */
391
+ export function refreshPiModelList(options: PiModelListOptions): Promise<readonly string[]> {
392
+ const key = keyOf(options);
393
+ const pending = refreshing.get(key);
394
+ if (pending !== undefined) return pending;
395
+ const failed = failedAt.get(key);
396
+ if (failed !== undefined && options.now() - failed < PI_LIST_RETRY_MS) {
397
+ return Promise.resolve(readPiModelList(options)?.list ?? []);
398
+ }
399
+ const loading = probe(options)
400
+ .then(async (rows) => {
401
+ if (rows === undefined) {
402
+ failedAt.set(key, options.now());
403
+ if (!failedLogged.has(key)) {
404
+ failedLogged.add(key);
405
+ options.log?.(
406
+ `pi: \`${options.command} --list-models\` did not answer; the kept model list is used until a later refresh`,
407
+ );
408
+ }
409
+ return readPiModelList(options)?.list ?? [];
410
+ }
411
+ failedAt.delete(key);
412
+ failedLogged.delete(key);
413
+ const at = options.now();
414
+ await writeKept(options, rows, at).catch(() => undefined);
415
+ return rows.map((row) => row.name);
416
+ })
417
+ .finally(() => {
418
+ refreshing.delete(key);
419
+ });
420
+ refreshing.set(key, loading);
421
+ return loading;
422
+ }
423
+
424
+ /**
425
+ * The kept list, starting a background refresh when it is old enough. This
426
+ * never waits for pi: a missing list is empty and a refresh fills it later.
427
+ */
428
+ export function piModelList(
429
+ options: PiModelListOptions,
430
+ known: KeptRead | null = readPiModelList(options) ?? null,
431
+ ): readonly string[] {
432
+ if (known !== null && options.now() - known.at < PI_LIST_CACHE_MS) return known.list;
433
+ void refreshPiModelList(options).catch(() => undefined);
434
+ return known?.list ?? [];
435
+ }
436
+
437
+ /**
438
+ * The kept list, waiting for one refresh only when there is none yet. A list
439
+ * that exists is returned at once; an old one starts its refresh in the
440
+ * background and the kept rows answer meanwhile.
441
+ */
442
+ export async function piModelListReady(
443
+ options: PiModelListOptions,
444
+ known: KeptRead | null = readPiModelList(options) ?? null,
445
+ ): Promise<readonly string[]> {
446
+ if (known !== null) {
447
+ if (options.now() - known.at >= PI_LIST_CACHE_MS) {
448
+ void refreshPiModelList(options).catch(() => undefined);
449
+ }
450
+ return known.list;
451
+ }
452
+ return await refreshPiModelList(options);
453
+ }
454
+
455
+ /** The context windows of the kept model list, by provider/id; empty when none are kept. */
456
+ export function piModelWindows(
457
+ options: PiModelListOptions,
458
+ known: KeptRead | null = readPiModelList(options) ?? null,
459
+ ): Readonly<Record<string, number>> {
460
+ return known?.windows ?? {};
461
+ }
462
+
463
+ /**
464
+ * What the kept model list and pi's registry say about each model, by
465
+ * provider/id; the kept list wins where both know a field. Empty when neither
466
+ * knows any model.
467
+ */
468
+ export function piModelInfo(
469
+ options: PiModelListOptions,
470
+ known: KeptRead | null = readPiModelList(options) ?? null,
471
+ ): Readonly<Record<string, HarnessModelInfo>> {
472
+ const kept = known?.info ?? {};
473
+ const registry = registryOf(options);
474
+ const info: Record<string, HarnessModelInfo> = {};
475
+ for (const [id, model] of Object.entries(registry)) info[id] = mergeInfo(undefined, model);
476
+ for (const [id, model] of Object.entries(kept)) info[id] = mergeInfo(info[id], { ...model, id });
477
+ return info;
478
+ }