@operad-io/harness-pi 0.4.0 → 0.5.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/package.json CHANGED
@@ -1,18 +1,18 @@
1
1
  {
2
2
  "name": "@operad-io/harness-pi",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./src/index.ts"
7
7
  },
8
8
  "dependencies": {
9
- "@operad-io/access-match": "0.4.0",
10
- "@operad-io/engine": "0.4.0",
11
- "@operad-io/harness-process": "0.4.0",
12
- "@operad-io/mcp": "0.4.0"
9
+ "@operad-io/access-match": "0.5.0",
10
+ "@operad-io/engine": "0.5.0",
11
+ "@operad-io/harness-process": "0.5.0",
12
+ "@operad-io/mcp": "0.5.0"
13
13
  },
14
14
  "peerDependencies": {
15
- "@earendil-works/pi-coding-agent": "1.6.0"
15
+ "@earendil-works/pi-coding-agent": "1.7.0"
16
16
  },
17
17
  "peerDependenciesMeta": {
18
18
  "@earendil-works/pi-coding-agent": {
@@ -20,9 +20,9 @@
20
20
  }
21
21
  },
22
22
  "devDependencies": {
23
- "@earendil-works/pi-coding-agent": "1.6.0"
23
+ "@earendil-works/pi-coding-agent": "1.7.0"
24
24
  },
25
- "description": "operad: the pi harness, a client of the pi coding agent library",
25
+ "description": "chats and tasks run by the pi coding agent",
26
26
  "repository": {
27
27
  "type": "git",
28
28
  "url": "git+https://github.com/operad-io/operad.git",
@@ -31,6 +31,7 @@
31
31
  "license": "MIT",
32
32
  "files": [
33
33
  "src",
34
+ "skills",
34
35
  "README.md",
35
36
  "LICENSE"
36
37
  ]
@@ -0,0 +1,31 @@
1
+ ---
2
+ name: setup-pi
3
+ description: Setup Pi. Get the pi agent working in operad, which means having a pi library, logging in to a model and checking again.
4
+ ---
5
+
6
+ I want operad's `pi` agent to work on this machine. Reply in the language I write to you in.
7
+ I do the installing and the logging in myself: give me the command, wait until I say it is
8
+ done, and do not run a login for me or ask me for a password, token or key. Do not edit
9
+ operad's `config.json`.
10
+
11
+ Take the steps for the missing items listed above, in this order.
12
+
13
+ - `enable` (the plugin is off): ask me to run `operad plugin enable pi`, or to turn it on
14
+ where I see operad's plugins. With no `pi` on my `PATH`, this also installs operad's own pi
15
+ and needs the network once.
16
+ - `agent` (pi is not installed): ask me to run `operad plugin enable pi`, which installs
17
+ operad's own pi even when the plugin is already on. I may instead install pi myself, with
18
+ `bun add -g @earendil-works/pi-coding-agent`. If `pi` works in my terminal and is still
19
+ reported missing, `operad serve` has an older `PATH`: ask me to stop it
20
+ (`operad serve stop`) and start it again from that terminal.
21
+ - `check` (the check failed): read what it says. When pi is too old, ask me to update it.
22
+ When it names the `command` setting of the `pi` section of `config.json`, ask me whether
23
+ that path is right.
24
+
25
+ The check does not cover the login to a model. Once nothing is missing, ask me whether I am
26
+ logged in; if not, I run `operad bot:login <bot>`. It asks for an API key, and for a ChatGPT
27
+ plan it shows the command line I run myself, which works with operad's own pi too.
28
+
29
+ After each step, check again: call the operad `command` tool with plugin `bot`, verb `setup`
30
+ and the arguments `{bot}` and `pi`. Stop when it says nothing is missing. If an item stays,
31
+ tell me what the check says and do not claim it is set up.
package/src/index.ts CHANGED
@@ -23,6 +23,7 @@ import {
23
23
  type StepContext,
24
24
  } from "@operad-io/engine";
25
25
  import {
26
+ agentNotSetUp,
26
27
  assertWorkerAvailable,
27
28
  CONCURRENCY_SETTING,
28
29
  DEFAULT_STALL_SECS,
@@ -49,17 +50,28 @@ import {
49
50
  type Clock,
50
51
  type KeptRunOptions,
51
52
  type StepFlagSpec,
53
+ shellWord,
52
54
  } from "@operad-io/harness-process";
53
55
  import { authFileHasCredential } from "./auth-file.ts";
54
56
  import {
55
57
  PI_LIST_TIMEOUT_MS,
58
+ type PiListFiles,
56
59
  piModelInfo,
57
60
  piModelList,
58
61
  piModelListReady,
59
62
  piModelWindows,
60
63
  readPiModelList,
64
+ refreshPiModelList,
61
65
  } from "./model-list.ts";
62
- import { DEFAULT_PI_COMMAND, findPi, PI_FLOOR, PI_VERSION } from "./pi-install.ts";
66
+ import {
67
+ DEFAULT_PI_COMMAND,
68
+ findPi,
69
+ PI_FLOOR,
70
+ PI_VERSION,
71
+ piPresent,
72
+ PiTooOldError,
73
+ type PiInstall,
74
+ } from "./pi-install.ts";
63
75
  import { runLoginStep, type LoginRunOptions } from "./login.ts";
64
76
  import {
65
77
  DEFAULT_BASH_TIMEOUT_SECS,
@@ -91,6 +103,8 @@ export interface PiHarnessOptions {
91
103
  readonly command?: string | undefined;
92
104
  /** The arguments before the worker input; defaults to `worker.ts`. */
93
105
  readonly args?: readonly string[] | undefined;
106
+ /** Test seam: where the worker program is; defaults to this package's `worker.ts`. */
107
+ readonly workerPath?: string | undefined;
94
108
  /** Test seam: the executable of a login; defaults to the running Bun. */
95
109
  readonly loginCommand?: string | undefined;
96
110
  /** Test seam: the arguments before a login's input; defaults to `login-worker.ts`. */
@@ -101,6 +115,8 @@ export interface PiHarnessOptions {
101
115
  readonly now?: (() => number) | undefined;
102
116
  /** How long `pi --list-models` may take; defaults to `PI_LIST_TIMEOUT_MS`. */
103
117
  readonly listTimeoutMs?: number | undefined;
118
+ /** Test seam: pi's own agent folder; defaults to `PI_CODING_AGENT_DIR`, else `~/.pi/agent`. */
119
+ readonly piAgentDir?: string | undefined;
104
120
  /** pi's settings file, where its default model is; defaults to `~/.pi/agent/settings.json`. */
105
121
  readonly piSettingsPath?: string | undefined;
106
122
  /** Test seam: how long a chat's worker is kept after a reply. */
@@ -250,6 +266,9 @@ export interface PiDeclaredModels {
250
266
  info?: Readonly<Record<string, HarnessModelInfo>> | undefined;
251
267
  }
252
268
 
269
+ /** The `SKILL.md` a bot follows to set this agent up (ADR 0010 D7). */
270
+ const SETUP_GUIDE = fileURLToPath(new URL("../skills/setup/SKILL.md", import.meta.url));
271
+
253
272
  /**
254
273
  * Creates the pi harness plugin. Its worker is `worker.ts` under the running
255
274
  * Bun; a test replaces the program with a fake that prints fixed lines.
@@ -257,7 +276,8 @@ export interface PiDeclaredModels {
257
276
  export function createPiHarnessPlugin(options: PiHarnessOptions = {}) {
258
277
  const clock = options.clock ?? systemClock;
259
278
  const command = options.command ?? process.execPath;
260
- const commandArgs = options.args ?? [WORKER_PATH];
279
+ const workerPath = options.workerPath ?? WORKER_PATH;
280
+ const commandArgs = options.args ?? [workerPath];
261
281
  const now = options.now ?? Date.now;
262
282
  const loginOptions: LoginRunOptions = {
263
283
  command: options.loginCommand ?? process.execPath,
@@ -276,18 +296,36 @@ export function createPiHarnessPlugin(options: PiHarnessOptions = {}) {
276
296
  : DEFAULT_MODELS_PATH;
277
297
  }
278
298
 
279
- function listOptions(
280
- piCommand: string,
281
- context: HarnessModelContext,
282
- modelsPath: string = DEFAULT_MODELS_PATH,
283
- ) {
299
+ /**
300
+ * The files the model list is read from, which a login and a step use too.
301
+ * Undefined when they are the two in pi's own folder (the one
302
+ * `PI_CODING_AGENT_DIR` may name), where pi finds them itself.
303
+ */
304
+ function listFilesOf(settings: Readonly<Record<string, unknown>>): PiListFiles | undefined {
305
+ const agentDir = expandHome(
306
+ options.piAgentDir ?? (process.env.PI_CODING_AGENT_DIR || dirname(DEFAULT_AUTH_PATH)),
307
+ );
308
+ const authPath = expandHome(
309
+ typeof settings.authPath === "string" && settings.authPath !== ""
310
+ ? settings.authPath
311
+ : DEFAULT_AUTH_PATH,
312
+ );
313
+ const modelsPath = expandHome(modelsPathOf(settings));
314
+ const piFindsThem =
315
+ resolve(authPath) === resolve(agentDir, "auth.json") &&
316
+ resolve(modelsPath) === resolve(agentDir, "models.json");
317
+ return piFindsThem ? undefined : { agentDir, authPath, modelsPath };
318
+ }
319
+
320
+ function listOptions(settings: Readonly<Record<string, unknown>>, context: HarnessModelContext) {
284
321
  return {
285
322
  home: context.home,
286
- command: piCommand,
323
+ command: piCommandFor(settings, context.home),
324
+ files: listFilesOf(settings),
287
325
  now,
288
326
  timeoutMs: listTimeoutMs,
289
327
  log: context.log,
290
- registryPath: join(dirname(expandHome(modelsPath)), "models-store.json"),
328
+ registryPath: join(dirname(expandHome(modelsPathOf(settings))), "models-store.json"),
291
329
  readFile,
292
330
  };
293
331
  }
@@ -385,12 +423,12 @@ export function createPiHarnessPlugin(options: PiHarnessOptions = {}) {
385
423
  ready = false,
386
424
  ): PiDeclaredModels | Promise<PiDeclaredModels> {
387
425
  const configured = stringList(settings.models);
388
- const options = listOptions(piCommandFor(settings, context.home), context, modelsPathOf(settings));
389
- const first = readPiModelList(options) ?? null;
390
- if (configured !== undefined) return declaredModels(settings, options, first, configured);
391
- if (!ready) return declaredModels(settings, options, first, piModelList(options, first));
392
- return piModelListReady(options, first).then((list) =>
393
- declaredModels(settings, options, first ?? readPiModelList(options) ?? null, list),
426
+ const asked = listOptions(settings, context);
427
+ const first = readPiModelList(asked) ?? null;
428
+ if (configured !== undefined) return declaredModels(settings, asked, first, configured);
429
+ if (!ready) return declaredModels(settings, asked, first, piModelList(asked, first));
430
+ return piModelListReady(asked, first).then((list) =>
431
+ declaredModels(settings, asked, first ?? readPiModelList(asked) ?? null, list),
394
432
  );
395
433
  }
396
434
 
@@ -416,7 +454,20 @@ export function createPiHarnessPlugin(options: PiHarnessOptions = {}) {
416
454
  models: piModels,
417
455
  modelsReady: (settings, context) => piModels(settings, context, true),
418
456
  efforts: piEfforts,
457
+ // The setting's pi, or the one operad installed when PATH has none.
458
+ interactiveCommand: (settings, context) => {
459
+ const command = piCommandFor(settings, context.home);
460
+ return command === DEFAULT_PI_COMMAND ? undefined : shellWord(command);
461
+ },
419
462
  capabilities: { loadsSkills: true, takesMessagesMidRun: true, accessLevels: ["plan", "ask", "edits", "full"] },
463
+ // A command the owner set, or a replaced worker, is the check's to judge.
464
+ agentMissing: (settings, context) =>
465
+ options.command !== undefined ||
466
+ options.loginCommand !== undefined ||
467
+ (settings.command !== undefined && settings.command !== DEFAULT_PI_COMMAND) ||
468
+ piPresent(context.home)
469
+ ? undefined
470
+ : "pi is not installed; run `operad plugin enable pi` to install operad's own",
420
471
  signedIn: async (settings) => {
421
472
  const authPath = expandHome(
422
473
  typeof settings.authPath === "string" ? settings.authPath : DEFAULT_AUTH_PATH,
@@ -426,6 +477,8 @@ export function createPiHarnessPlugin(options: PiHarnessOptions = {}) {
426
477
  piProvider(settings.model, readPiSettings(piSettingsPath, readFile)),
427
478
  );
428
479
  },
480
+ // Setup Pi (ADR 0022 D14): the guide a bot follows for what the check reports missing.
481
+ guide: SETUP_GUIDE,
429
482
  settings: PLUGIN_SETTINGS,
430
483
  steps: [
431
484
  {
@@ -434,7 +487,16 @@ export function createPiHarnessPlugin(options: PiHarnessOptions = {}) {
434
487
  // model they chose (ADR 0023 D11).
435
488
  results: ["done", "failed"],
436
489
  timeoutSecs: 660,
437
- run: (ctx: StepContext) => runLoginStep(ctx, loginOptions),
490
+ run: (ctx: StepContext) =>
491
+ runLoginStep(ctx, {
492
+ ...loginOptions,
493
+ // A list kept from before the login lacks the models it opens.
494
+ afterLogin: async () => {
495
+ if (stringList(ctx.settings.models) !== undefined) return;
496
+ const context = { home: ctx.home, log: (message: string) => void ctx.logger.write(message) };
497
+ await refreshPiModelList(listOptions(ctx.settings, context));
498
+ },
499
+ }),
438
500
  },
439
501
  {
440
502
  name: "agent",
@@ -493,18 +555,12 @@ export function createPiHarnessPlugin(options: PiHarnessOptions = {}) {
493
555
  const configured = stringList(ctx.settings.models);
494
556
  if (configured !== undefined && read.model !== undefined && configured.includes(read.model)) {
495
557
  const listed = piModelList(
496
- listOptions(
497
- piCommandFor(ctx.settings, ctx.home),
498
- {
499
- home: ctx.home,
500
- log: (message) => {
501
- void ctx.logger.write(message);
502
- },
558
+ listOptions(ctx.settings, {
559
+ home: ctx.home,
560
+ log: (message) => {
561
+ void ctx.logger.write(message);
503
562
  },
504
- typeof ctx.settings.modelsPath === "string"
505
- ? ctx.settings.modelsPath
506
- : DEFAULT_MODELS_PATH,
507
- ),
563
+ }),
508
564
  );
509
565
  if (listed.length > 0 && !listed.includes(read.model)) {
510
566
  await ctx.logger.write(
@@ -605,8 +661,15 @@ export function createPiHarnessPlugin(options: PiHarnessOptions = {}) {
605
661
  const piCommand = optionalText(ctx.settings.command, "pi: settings.command");
606
662
  // The user's own pi, or the one operad installed in the home: found and
607
663
  // version-checked, not loaded.
608
- const pi = findPi(piCommand ?? DEFAULT_PI_COMMAND, { home: ctx.home });
609
- assertWorkerAvailable({ command: options.command, args: options.args, workerPath: WORKER_PATH });
664
+ // A missing worker program fails the check whatever the pi is.
665
+ assertWorkerAvailable({ command: options.command, args: options.args, workerPath });
666
+ let pi: PiInstall;
667
+ try {
668
+ pi = findPi(piCommand ?? DEFAULT_PI_COMMAND, { home: ctx.home });
669
+ } catch (error) {
670
+ if (error instanceof PiTooOldError) return agentNotSetUp(error.message);
671
+ throw error;
672
+ }
610
673
  return `pi ${pi.version} at ${pi.dir} (floor ${PI_FLOOR}); the worker program is available`;
611
674
  },
612
675
  });
package/src/login.ts CHANGED
@@ -50,6 +50,8 @@ export interface LoginRunOptions {
50
50
  readonly timeoutMs?: number | undefined;
51
51
  /** The time now in milliseconds; defaults to `Date.now`. */
52
52
  readonly now?: (() => number) | undefined;
53
+ /** Runs once the credential is written, before the model choice. */
54
+ readonly afterLogin?: (() => Promise<void>) | undefined;
53
55
  }
54
56
 
55
57
  /** A failure that ends the login without a person's answer. */
@@ -223,7 +225,7 @@ async function chooseProvider(
223
225
  providers: readonly LoginProvider[],
224
226
  deadline: number,
225
227
  now: () => number,
226
- hint: string,
228
+ command: string,
227
229
  ): Promise<LoginRoute | undefined> {
228
230
  const routes = routesOf(providers);
229
231
  if (routes.length === 0) throw new LoginFailure("no provider of pi can log in");
@@ -236,7 +238,8 @@ async function chooseProvider(
236
238
  choiceInfo[route.provider] = { label: routeLabel(provider) };
237
239
  }
238
240
  const answer = await ctx.ask({
239
- prompt: `Choose a provider to log in with. ${hint}`,
241
+ prompt: "Choose a provider to log in with an API key. For a ChatGPT plan, run the command below instead; operad picks it up once it is done.",
242
+ command,
240
243
  choices,
241
244
  choiceInfo,
242
245
  graceSecs: remainingSecs(deadline, now),
@@ -368,8 +371,8 @@ export async function runLoginStep(
368
371
  if (first.type !== "providers") {
369
372
  return failed("the login program did not report its providers");
370
373
  }
371
- const hint = `For your ChatGPT plan, run \`${chatgptLoginCommand(input.command, { home: ctx.home, cwd: ctx.cwd })}\`; operad picks it up once it is done.`;
372
- const route = await chooseProvider(ctx, first.providers, child.deadline, now, hint);
374
+ const command = chatgptLoginCommand(input.command, { home: ctx.home, cwd: ctx.cwd });
375
+ const route = await chooseProvider(ctx, first.providers, child.deadline, now, command);
373
376
  if (route === undefined) return failed("the login was cancelled");
374
377
  child.send({ type: "login", provider: route.provider, auth: route.auth });
375
378
  for (;;) {
@@ -383,6 +386,7 @@ export async function runLoginStep(
383
386
  if (answer !== "") child.send({ type: "answer", id: line.id, value: answer });
384
387
  }
385
388
  }
389
+ await options.afterLogin?.();
386
390
  const model = await chooseModel(ctx, route.provider);
387
391
  if (model === undefined) return failed("the login finished but no model was chosen");
388
392
  return { result: "done", data: { provider: route.provider, model } };
package/src/model-list.ts CHANGED
@@ -5,8 +5,17 @@
5
5
  * needs a list before one exists can wait for that refresh.
6
6
  */
7
7
 
8
- import { readFileSync, statSync } from "node:fs";
9
- import { join } from "node:path";
8
+ import {
9
+ existsSync,
10
+ mkdirSync,
11
+ readdirSync,
12
+ readFileSync,
13
+ readlinkSync,
14
+ rmSync,
15
+ statSync,
16
+ symlinkSync,
17
+ } from "node:fs";
18
+ import { dirname, join } from "node:path";
10
19
  import { isRecord, type HarnessModelCapability, type HarnessModelInfo } from "@operad-io/engine";
11
20
  import { writeJsonAtomic } from "@operad-io/engine/platform";
12
21
 
@@ -129,6 +138,16 @@ export interface PiModelListOptions {
129
138
  readonly registryPath?: string | undefined;
130
139
  /** Test seam: reads a file as text; defaults to `readFileSync(path, "utf8")`. */
131
140
  readonly readFile?: ((path: string) => string) | undefined;
141
+ /** The files pi is made to read; absent when pi's own folder holds them. */
142
+ readonly files?: PiListFiles | undefined;
143
+ }
144
+
145
+ /** What `pi --list-models` reads when pi's own folder is not where they are. */
146
+ export interface PiListFiles {
147
+ /** pi's own agent folder, which holds its settings and extensions. */
148
+ readonly agentDir: string;
149
+ readonly authPath: string;
150
+ readonly modelsPath: string;
132
151
  }
133
152
 
134
153
  interface KeptRead {
@@ -320,11 +339,85 @@ async function textOf(stream: unknown): Promise<string> {
320
339
  return stream instanceof ReadableStream ? await new Response(stream).text() : "";
321
340
  }
322
341
 
342
+ const RELINK_ATTEMPTS = 5;
343
+
344
+ function leadsTo(at: string, target: string): boolean {
345
+ try {
346
+ return readlinkSync(at) === target;
347
+ } catch {
348
+ // Nothing is there, or it is not a link.
349
+ return false;
350
+ }
351
+ }
352
+
353
+ /**
354
+ * Makes `at` a link to `target`; a link that already leads there stays. Another
355
+ * process may be doing the same in this folder, so a name taken between the
356
+ * removal and the link is looked at again. `link` is a test seam.
357
+ */
358
+ export function relink(
359
+ target: string,
360
+ at: string,
361
+ link: (target: string, at: string) => void = symlinkSync,
362
+ ): void {
363
+ for (let attempt = 1; !leadsTo(at, target); attempt += 1) {
364
+ // Removes a link or what pi made here, never what a link leads to.
365
+ rmSync(at, { recursive: true, force: true });
366
+ try {
367
+ link(target, at);
368
+ return;
369
+ } catch (error) {
370
+ const taken = error instanceof Error && "code" in error && error.code === "EEXIST";
371
+ if (!taken || attempt >= RELINK_ATTEMPTS) throw error;
372
+ }
373
+ }
374
+ }
375
+
376
+ /**
377
+ * pi has no option for its credentials file, only for the folder it reads
378
+ * everything from (`PI_CODING_AGENT_DIR`). This makes such a folder under the
379
+ * operad home: links to what pi's own folder holds, with the credentials file,
380
+ * the models file and the registry store beside it replaced by the configured
381
+ * ones. pi locks and writes a linked file as the file it leads to, and creates
382
+ * a missing one there. Locks in pi's own folder are not linked, and a link
383
+ * whose entry has left that folder is removed.
384
+ */
385
+ function listAgentDir(home: string, files: PiListFiles): string {
386
+ const dir = join(home, "harness", "pi", "list-agent");
387
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
388
+ const configured: Readonly<Record<string, string>> = {
389
+ "auth.json": files.authPath,
390
+ "models.json": files.modelsPath,
391
+ "models-store.json": join(dirname(files.modelsPath), "models-store.json"),
392
+ };
393
+ const own = existsSync(files.agentDir) ? readdirSync(files.agentDir) : [];
394
+ const shared = new Set(
395
+ own.filter((name) => !name.endsWith(".lock") && !Object.hasOwn(configured, name)),
396
+ );
397
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
398
+ // Only links are operad's to remove; a lock pi holds here is a folder.
399
+ const wanted = shared.has(entry.name) || Object.hasOwn(configured, entry.name);
400
+ if (entry.isSymbolicLink() && !wanted) rmSync(join(dir, entry.name), { force: true });
401
+ }
402
+ for (const name of shared) relink(join(files.agentDir, name), join(dir, name));
403
+ for (const [name, target] of Object.entries(configured)) {
404
+ // Writing through a link to a missing file needs the file's folder.
405
+ if (existsSync(dirname(target))) relink(target, join(dir, name));
406
+ else rmSync(join(dir, name), { force: true });
407
+ }
408
+ return dir;
409
+ }
410
+
323
411
  /** Asks pi once. Undefined means it failed, was killed, or answered with an error. */
324
412
  async function probe(options: PiModelListOptions): Promise<readonly PiCatalogueRow[] | undefined> {
325
413
  let child: ReturnType<typeof Bun.spawn>;
326
414
  try {
415
+ const env =
416
+ options.files === undefined
417
+ ? undefined
418
+ : { ...process.env, PI_CODING_AGENT_DIR: listAgentDir(options.home, options.files) };
327
419
  child = Bun.spawn([options.command, "--list-models"], {
420
+ ...(env === undefined ? {} : { env }),
328
421
  stdin: "ignore",
329
422
  stdout: "pipe",
330
423
  stderr: "pipe",
package/src/pi-install.ts CHANGED
@@ -19,7 +19,7 @@ import { isRecord } from "@operad-io/engine";
19
19
  export const PI_PACKAGE = "@earendil-works/pi-coding-agent";
20
20
 
21
21
  /** The version operad installs into the home; it moves with an operad release (ADR 0023 D9). */
22
- export const PI_VERSION = "1.6.0";
22
+ export const PI_VERSION = "1.7.0";
23
23
 
24
24
  /** The oldest pi the worker's calls are written for. */
25
25
  export const PI_FLOOR = "1.5.0";
@@ -35,6 +35,14 @@ export class PiInstallError extends Error {
35
35
  }
36
36
  }
37
37
 
38
+ /** The pi is there, and the person has to upgrade it first. */
39
+ export class PiTooOldError extends PiInstallError {
40
+ constructor(message: string) {
41
+ super(message);
42
+ this.name = "PiTooOldError";
43
+ }
44
+ }
45
+
38
46
  /** Where a pi lives and what it is. */
39
47
  export interface PiInstall {
40
48
  /** The command as given. */
@@ -126,6 +134,14 @@ export function homePiPackageDir(home: string): string {
126
134
  return join(home, HOME_PLUGIN_PROJECT, "node_modules", PI_PACKAGE);
127
135
  }
128
136
 
137
+ /** True when there is a pi to look at: the command on PATH, or the home's install. */
138
+ export function piPresent(home: string, path: string = process.env.PATH ?? ""): boolean {
139
+ return (
140
+ Bun.which(DEFAULT_PI_COMMAND, { PATH: path }) !== null ||
141
+ existsSync(join(homePiPackageDir(home), "package.json"))
142
+ );
143
+ }
144
+
129
145
  /** The `pi` command of an installed package, for `pi --list-models`. */
130
146
  function packageCommand(packageDir: string, manifest: Record<string, unknown>): string {
131
147
  const bin = join(dirname(dirname(packageDir)), ".bin", "pi");
@@ -146,7 +162,7 @@ function installAt(packageDir: string, command: string, realPath: string, floor:
146
162
  throw new PiInstallError(`${join(packageDir, "package.json")}: version is missing or not a version`);
147
163
  }
148
164
  if (compareVersions(version, floor) < 0) {
149
- throw new PiInstallError(
165
+ throw new PiTooOldError(
150
166
  `pi ${version} at ${packageDir} is older than the floor ${floor}; upgrade pi (${PI_PACKAGE} ${floor} or newer)`,
151
167
  );
152
168
  }