@operad-io/harness-pi 0.1.0 → 0.2.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/pi-install.ts CHANGED
@@ -1,11 +1,15 @@
1
1
  /**
2
- * Finds the user's installed pi (ADR 0023 D9).
2
+ * Finds the installed pi (ADR 0023 D9).
3
3
  * The `pi` command on PATH (or the `command` setting) is resolved to its real
4
4
  * path; walking up from there reaches the package directory whose
5
5
  * `package.json` is `@earendil-works/pi-coding-agent`, and the file its
6
- * `exports["."]` names is the library. Nothing here installs or bundles pi.
6
+ * `exports["."]` names is the library. When there is no such command, the pi
7
+ * operad installed in the home's plugin project is used instead. Nothing here
8
+ * installs or bundles pi; the CLI installs it when the plugin is enabled.
7
9
  */
8
10
 
11
+ import { messageOf, readVersionText } from "@operad-io/engine";
12
+ import { strictVersionCompare } from "@operad-io/harness-process";
9
13
  import { existsSync, readFileSync, realpathSync } from "node:fs";
10
14
  import { dirname, isAbsolute, join, resolve, sep } from "node:path";
11
15
  import { pathToFileURL } from "node:url";
@@ -14,6 +18,9 @@ import { isRecord } from "@operad-io/engine";
14
18
  /** The package the worker uses. */
15
19
  export const PI_PACKAGE = "@earendil-works/pi-coding-agent";
16
20
 
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";
23
+
17
24
  /** The oldest pi the worker's calls are written for. */
18
25
  export const PI_FLOOR = "1.5.0";
19
26
 
@@ -48,6 +55,11 @@ export interface FindPiOptions {
48
55
  readonly cwd?: string | undefined;
49
56
  /** The floor to compare with; defaults to `PI_FLOOR`. */
50
57
  readonly floor?: string | undefined;
58
+ /**
59
+ * The operad home: when the default `pi` command is not on PATH, the pi
60
+ * operad installed into the home's plugin project is used (ADR 0023 D9).
61
+ */
62
+ readonly home?: string | undefined;
51
63
  }
52
64
 
53
65
  function readJson(path: string): Record<string, unknown> | undefined {
@@ -103,52 +115,51 @@ export function entryOf(exportsField: unknown): string | undefined {
103
115
  return undefined;
104
116
  }
105
117
 
106
- interface Semver {
107
- readonly core: readonly [number, number, number];
108
- readonly pre: readonly string[];
118
+ /** Negative, zero or positive as `a` is below, equal to or above `b`. */
119
+ export const compareVersions = strictVersionCompare((version) => new PiInstallError(`not a version: ${version}`));
120
+
121
+ /** The home's Bun project, where operad installs a plugin's package (ADR 0012 D4). */
122
+ const HOME_PLUGIN_PROJECT = "plugins";
123
+
124
+ /** The package directory operad installs into the home's Bun project. */
125
+ export function homePiPackageDir(home: string): string {
126
+ return join(home, HOME_PLUGIN_PROJECT, "node_modules", PI_PACKAGE);
109
127
  }
110
128
 
111
- function parseSemver(version: string): Semver | undefined {
112
- const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/.exec(version.trim());
113
- if (match === null) return undefined;
114
- return {
115
- core: [Number(match[1]), Number(match[2]), Number(match[3])],
116
- pre: match[4] === undefined ? [] : match[4].split("."),
117
- };
129
+ /** The `pi` command of an installed package, for `pi --list-models`. */
130
+ function packageCommand(packageDir: string, manifest: Record<string, unknown>): string {
131
+ const bin = join(dirname(dirname(packageDir)), ".bin", "pi");
132
+ if (existsSync(bin)) return bin;
133
+ const declared = manifest.bin;
134
+ const relative = typeof declared === "string" ? declared : isRecord(declared) ? declared.pi : undefined;
135
+ return typeof relative === "string" ? join(packageDir, relative) : packageDir;
118
136
  }
119
137
 
120
- /** Negative, zero or positive as `a` is below, equal to or above `b`. */
121
- export function compareVersions(a: string, b: string): number {
122
- const left = parseSemver(a);
123
- const right = parseSemver(b);
124
- if (left === undefined || right === undefined) {
125
- throw new PiInstallError(`not a version: ${left === undefined ? a : b}`);
138
+ /** Checks a package directory and describes it. */
139
+ function installAt(packageDir: string, command: string, realPath: string, floor: string): PiInstall {
140
+ const manifest = readJson(join(packageDir, "package.json"));
141
+ if (manifest === undefined || manifest.name !== PI_PACKAGE) {
142
+ throw new PiInstallError(`${packageDir} is not a ${PI_PACKAGE} package`);
126
143
  }
127
- for (let at = 0; at < 3; at += 1) {
128
- const diff = (left.core[at] ?? 0) - (right.core[at] ?? 0);
129
- if (diff !== 0) return diff;
144
+ const version = manifest.version;
145
+ if (typeof version !== "string" || readVersionText(version) === undefined) {
146
+ throw new PiInstallError(`${join(packageDir, "package.json")}: version is missing or not a version`);
130
147
  }
131
- // A prerelease is below its release.
132
- if (left.pre.length === 0 && right.pre.length === 0) return 0;
133
- if (left.pre.length === 0) return 1;
134
- if (right.pre.length === 0) return -1;
135
- for (let at = 0; at < Math.max(left.pre.length, right.pre.length); at += 1) {
136
- const l = left.pre[at];
137
- const r = right.pre[at];
138
- if (l === undefined) return -1;
139
- if (r === undefined) return 1;
140
- const ln = /^\d+$/.test(l);
141
- const rn = /^\d+$/.test(r);
142
- if (ln && rn) {
143
- const diff = Number(l) - Number(r);
144
- if (diff !== 0) return diff;
145
- } else if (ln !== rn) {
146
- return ln ? -1 : 1;
147
- } else if (l !== r) {
148
- return l < r ? -1 : 1;
149
- }
148
+ if (compareVersions(version, floor) < 0) {
149
+ throw new PiInstallError(
150
+ `pi ${version} at ${packageDir} is older than the floor ${floor}; upgrade pi (${PI_PACKAGE} ${floor} or newer)`,
151
+ );
152
+ }
153
+
154
+ const relative = entryOf(manifest.exports);
155
+ if (relative === undefined) {
156
+ throw new PiInstallError(`${join(packageDir, "package.json")}: exports["."] names no file`);
150
157
  }
151
- return 0;
158
+ const entry = resolve(packageDir, relative);
159
+ if (!entry.startsWith(packageDir + sep) || !existsSync(entry)) {
160
+ throw new PiInstallError(`${join(packageDir, "package.json")}: exports["."] names ${relative}, which is not a file in the package`);
161
+ }
162
+ return { command, realPath, dir: packageDir, version, entry };
152
163
  }
153
164
 
154
165
  /** Finds the installed pi and checks its version against the floor. */
@@ -156,58 +167,78 @@ export function findPi(command: string = DEFAULT_PI_COMMAND, options: FindPiOpti
156
167
  const floor = options.floor ?? PI_FLOOR;
157
168
  const located = locate(command, options);
158
169
  if (located === undefined) {
170
+ if (command === DEFAULT_PI_COMMAND && options.home !== undefined) {
171
+ const install = findHomePi(options.home, floor);
172
+ if (install !== undefined) return install;
173
+ }
159
174
  throw new PiInstallError(
160
- `no ${command === DEFAULT_PI_COMMAND ? "pi command" : `"${command}"`} was found on PATH; ` +
161
- `pi needs ${PI_PACKAGE} ${floor} or newer installed (bun add -g ${PI_PACKAGE}, or npm i -g ${PI_PACKAGE})`,
175
+ `no ${command === DEFAULT_PI_COMMAND ? "pi command" : `"${command}"`} was found on PATH` +
176
+ (options.home === undefined ? "" : " and the home has no pi installed") +
177
+ `; pi needs ${PI_PACKAGE} ${floor} or newer installed (bun add -g ${PI_PACKAGE}, or npm i -g ${PI_PACKAGE}), ` +
178
+ "or run `operad plugin enable pi` to install operad's own",
162
179
  );
163
180
  }
164
181
  let real: string;
165
182
  try {
166
183
  real = realpathSync(located);
167
184
  } catch (error) {
168
- throw new PiInstallError(`${located}: ${error instanceof Error ? error.message : String(error)}`);
185
+ throw new PiInstallError(`${located}: ${messageOf(error)}`);
169
186
  }
170
187
 
171
188
  let dir = dirname(real);
172
189
  let packageDir: string | undefined;
173
- let manifest: Record<string, unknown> | undefined;
174
190
  for (;;) {
175
191
  const candidate = readJson(join(dir, "package.json"));
176
192
  if (candidate !== undefined && candidate.name === PI_PACKAGE) {
177
193
  packageDir = dir;
178
- manifest = candidate;
179
194
  break;
180
195
  }
181
196
  const parent = dirname(dir);
182
197
  if (parent === dir) break;
183
198
  dir = parent;
184
199
  }
185
- if (packageDir === undefined || manifest === undefined) {
200
+ if (packageDir === undefined) {
186
201
  throw new PiInstallError(
187
202
  `${command} resolves to ${real}, which is not inside a ${PI_PACKAGE} package ` +
188
203
  `(a shell wrapper cannot be followed); set the pi "command" setting to the package's bin`,
189
204
  );
190
205
  }
206
+ return installAt(packageDir, command, real, floor);
207
+ }
191
208
 
192
- const version = manifest.version;
193
- if (typeof version !== "string" || parseSemver(version) === undefined) {
194
- throw new PiInstallError(`${join(packageDir, "package.json")}: version is missing or not a version`);
195
- }
196
- if (compareVersions(version, floor) < 0) {
197
- throw new PiInstallError(
198
- `pi ${version} at ${packageDir} is older than the floor ${floor}; upgrade pi (${PI_PACKAGE} ${floor} or newer)`,
199
- );
200
- }
209
+ /** The pi operad installed in the home, or undefined when the home has none. */
210
+ export function findHomePi(home: string, floor: string = PI_FLOOR): PiInstall | undefined {
211
+ const dir = homePiPackageDir(home);
212
+ const manifest = readJson(join(dir, "package.json"));
213
+ if (manifest === undefined || manifest.name !== PI_PACKAGE) return undefined;
214
+ return installAt(dir, packageCommand(dir, manifest), dir, floor);
215
+ }
201
216
 
202
- const relative = entryOf(manifest.exports);
203
- if (relative === undefined) {
204
- throw new PiInstallError(`${join(packageDir, "package.json")}: exports["."] names no file`);
205
- }
206
- const entry = resolve(packageDir, relative);
207
- if (!entry.startsWith(packageDir + sep) || !existsSync(entry)) {
208
- throw new PiInstallError(`${join(packageDir, "package.json")}: exports["."] names ${relative}, which is not a file in the package`);
217
+ /** The arguments of pi's own ChatGPT login, the `openai-codex` provider. */
218
+ const CHATGPT_LOGIN_ARGS = "auth login openai-codex";
219
+
220
+ /** A command as a shell takes it: quoted only when it has a character a shell splits on. */
221
+ function shellWord(word: string): string {
222
+ return /^[A-Za-z0-9_.:@%+=,\/-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`;
223
+ }
224
+
225
+ /**
226
+ * The command a person runs to log in to their ChatGPT plan with pi itself:
227
+ * `pi auth login openai-codex` when `pi` is on PATH (or the `command` setting
228
+ * names a command), else the full command of the pi operad installed in the
229
+ * home. operad never starts that login (ADR 0023 D11); it only reads pi's
230
+ * auth file afterwards.
231
+ */
232
+ export function chatgptLoginCommand(command: string = DEFAULT_PI_COMMAND, options: FindPiOptions = {}): string {
233
+ if (locate(command, options) === undefined && command === DEFAULT_PI_COMMAND && options.home !== undefined) {
234
+ try {
235
+ const own = findHomePi(options.home);
236
+ if (own !== undefined) return `${shellWord(own.command)} ${CHATGPT_LOGIN_ARGS}`;
237
+ } catch {
238
+ // A home pi that cannot be used is not one to name.
239
+ }
209
240
  }
210
- return { command, realPath: real, dir: packageDir, version, entry };
241
+ return `${shellWord(command)} ${CHATGPT_LOGIN_ARGS}`;
211
242
  }
212
243
 
213
244
  /** The library's own module type, for the call sites. */
package/src/protocol.ts CHANGED
@@ -3,16 +3,35 @@
3
3
  * `test/protocol.test.ts` checks the program against them.
4
4
  */
5
5
 
6
- import { readProfile } from "@operad-io/access-match";
7
- import { parseImageInputs, type ImageInput, type SharedLine } from "@operad-io/harness-process";
6
+ import {
7
+ readAccess,
8
+ readBoolean,
9
+ readImages,
10
+ readKeep,
11
+ readOperadTools,
12
+ readOptionalString,
13
+ readPositiveInteger,
14
+ readRequiredStrings,
15
+ readSecrets,
16
+ readStringList,
17
+ type ImageInput,
18
+ type SharedLine,
19
+ type WorkerKeep,
20
+ type WorkerResultName,
21
+ type WorkerUsage,
22
+ } from "@operad-io/harness-process";
8
23
  import { isRecord } from "@operad-io/engine";
9
24
 
25
+ export type { AskAck, GrantAck, WorkerResultName, WorkerUsage } from "@operad-io/harness-process";
26
+
10
27
  /** The longest one bash call may run when the settings do not say, in seconds. */
11
28
  export const DEFAULT_BASH_TIMEOUT_SECS = 1800;
12
29
 
13
30
  export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
14
31
  export type WorkerThinkingLevel = (typeof THINKING_LEVELS)[number];
15
32
 
33
+ export type { WorkerKeep } from "@operad-io/harness-process";
34
+
16
35
  /** What the program reads from stdin. */
17
36
  export interface WorkerInput {
18
37
  readonly prompt: string;
@@ -22,6 +41,8 @@ export interface WorkerInput {
22
41
  readonly agentDir: string;
23
42
  /** The pi command (a name on PATH or a path); unset means `pi`. */
24
43
  readonly piCommand?: string | undefined;
44
+ /** The operad home: its plugin project may hold the pi operad installed (ADR 0023 D9). */
45
+ readonly piHome?: string | undefined;
25
46
  readonly sessionDir: string;
26
47
  readonly resumeSession?: string | undefined;
27
48
  readonly model?: string | undefined;
@@ -35,17 +56,16 @@ export interface WorkerInput {
35
56
  readonly secretValues?: readonly string[] | undefined;
36
57
  /** Images given to pi with the prompt, read from these files. */
37
58
  readonly images?: readonly ImageInput[] | undefined;
59
+ /** Skill directories to load; with the own-settings switch off, no other skills are discovered. */
60
+ readonly skills?: readonly string[] | undefined;
61
+ /** Load the owner's own pi settings and resources (ADR 0023 D3); off unless true. */
62
+ readonly useOwnSettings?: boolean | undefined;
63
+ /** Retry a failed model request with pi's own bounded backoff; off unless true. */
64
+ readonly retry?: boolean | undefined;
65
+ /** Set by a chat reply: the worker may serve the next reply and then end itself. */
66
+ readonly keep?: WorkerKeep | undefined;
38
67
  }
39
68
 
40
- export interface WorkerUsage {
41
- input?: number;
42
- output?: number;
43
- cache_read?: number;
44
- cache_write?: number;
45
- }
46
-
47
- export type WorkerResultName = "done" | "failed" | "cancelled";
48
-
49
69
  export type FailureReason = "invalid_input" | "session_missing" | "model_missing" | "model_error";
50
70
 
51
71
  /** The last line of stdout. */
@@ -57,6 +77,8 @@ export interface WorkerResult {
57
77
  /** The priced part of the run; `incomplete` when some message had no price. */
58
78
  readonly cost: { readonly micros: number; readonly incomplete?: true } | null;
59
79
  readonly finalMessage: string | null;
80
+ /** The context after the last model call, when one ran. */
81
+ readonly context?: { readonly used: number; readonly window?: number } | undefined;
60
82
  readonly reason?: FailureReason;
61
83
  readonly message?: string;
62
84
  }
@@ -75,25 +97,6 @@ export type WorkerLine =
75
97
  | { readonly type: "agent_settled"; readonly aborted: boolean }
76
98
  | WorkerResult;
77
99
 
78
- /**
79
- * A stdin line after the input: the host's answer to an `ask_call` line.
80
- * `allow` lets this one call run; `deny` refuses it; `stop` means the wait
81
- * ended and the program is about to be ended: it holds the call.
82
- */
83
- export interface AskAck {
84
- readonly type: "ask_ack";
85
- readonly id: number;
86
- readonly decision: "allow" | "deny" | "stop";
87
- readonly reason?: string;
88
- }
89
-
90
- /** A stdin line after the input: the host's answer to a `grant_use` line. */
91
- export interface GrantAck {
92
- readonly type: "grant_ack";
93
- readonly id: number;
94
- readonly used: boolean;
95
- }
96
-
97
100
  export type ParsedInput =
98
101
  | { readonly ok: true; readonly input: WorkerInput }
99
102
  | { readonly ok: false; readonly message: string };
@@ -104,31 +107,18 @@ const REQUIRED_STRINGS = ["prompt", "cwd", "authPath", "modelsPath", "agentDir",
104
107
  export function parseInput(value: unknown): ParsedInput {
105
108
  if (!isRecord(value)) return { ok: false, message: "the input must be a JSON object" };
106
109
 
107
- const strings: Record<string, string> = {};
108
- for (const field of REQUIRED_STRINGS) {
109
- const field_ = value[field];
110
- if (field_ === undefined) return { ok: false, message: `${field} is required` };
111
- if (typeof field_ !== "string" || field_.length === 0) {
112
- return { ok: false, message: `${field} must be a non-empty string` };
113
- }
114
- strings[field] = field_;
115
- }
116
-
117
- const optional = (field: "resumeSession" | "model" | "piCommand"): string | undefined | Error => {
118
- const field_ = value[field];
119
- if (field_ === undefined) return undefined;
120
- if (typeof field_ !== "string" || field_.length === 0) {
121
- return new Error(`${field} must be a non-empty string`);
122
- }
123
- return field_;
124
- };
125
- const resumeSession = optional("resumeSession");
126
- if (resumeSession instanceof Error) return { ok: false, message: resumeSession.message };
127
- const piCommand = optional("piCommand");
128
- if (piCommand instanceof Error) return { ok: false, message: piCommand.message };
129
- const model = optional("model");
130
- if (model instanceof Error) return { ok: false, message: model.message };
131
- if (model !== undefined && !/^[^/]+\/.+$/.test(model)) {
110
+ const required = readRequiredStrings(value, REQUIRED_STRINGS);
111
+ if (!required.ok) return required;
112
+
113
+ const resumeSession = readOptionalString(value, "resumeSession");
114
+ if (!resumeSession.ok) return resumeSession;
115
+ const piCommand = readOptionalString(value, "piCommand");
116
+ if (!piCommand.ok) return piCommand;
117
+ const piHome = readOptionalString(value, "piHome");
118
+ if (!piHome.ok) return piHome;
119
+ const model = readOptionalString(value, "model");
120
+ if (!model.ok) return model;
121
+ if (model.value !== undefined && !/^[^/]+\/.+$/.test(model.value)) {
132
122
  return { ok: false, message: "model must look like provider/id" };
133
123
  }
134
124
 
@@ -142,54 +132,56 @@ export function parseInput(value: unknown): ParsedInput {
142
132
  thinkingLevel = known;
143
133
  }
144
134
 
145
- const bashTimeoutSecs = value["bashTimeoutSecs"];
146
- if (
147
- bashTimeoutSecs !== undefined &&
148
- (typeof bashTimeoutSecs !== "number" || !Number.isInteger(bashTimeoutSecs) || bashTimeoutSecs < 1)
149
- ) {
150
- return { ok: false, message: "bashTimeoutSecs must be a positive integer" };
151
- }
135
+ const bashTimeoutSecs = readPositiveInteger(value, "bashTimeoutSecs");
136
+ if (!bashTimeoutSecs.ok) return bashTimeoutSecs;
152
137
 
153
- const operadTools = value["operadTools"];
154
- if (operadTools !== undefined && (!isRecord(operadTools) || typeof operadTools["home"] !== "string" || operadTools["home"].length === 0)) {
155
- return { ok: false, message: "operadTools must be an object with a home" };
156
- }
138
+ const operadTools = readOperadTools(value);
139
+ if (!operadTools.ok) return operadTools;
157
140
 
158
- const secretValues = value["secretValues"];
159
- if (secretValues !== undefined && (!Array.isArray(secretValues) || !secretValues.every((v): v is string => typeof v === "string"))) {
160
- return { ok: false, message: "secretValues must be an array of strings" };
161
- }
141
+ const secretValues = readSecrets(value);
142
+ if (!secretValues.ok) return secretValues;
162
143
 
163
- const images = parseImageInputs(value["images"]);
164
- if (typeof images === "string") return { ok: false, message: images };
144
+ const images = readImages(value);
145
+ if (!images.ok) return images;
165
146
 
166
- const access = value["access"];
167
- if (access !== undefined && !isRecord(access)) {
168
- return { ok: false, message: "access must be an object" };
169
- }
170
- if (access !== undefined) {
171
- const profile = readProfile(access);
172
- if (!profile.ok) return { ok: false, message: `access.${profile.message}` };
173
- }
147
+ const skills = readStringList(value, "skills");
148
+ if (!skills.ok) return skills;
149
+
150
+ const useOwnSettings = readBoolean(value, "useOwnSettings");
151
+ if (!useOwnSettings.ok) return useOwnSettings;
152
+
153
+ const retry = readBoolean(value, "retry");
154
+ if (!retry.ok) return retry;
155
+
156
+ const access = readAccess(value);
157
+ if (!access.ok) return access;
158
+
159
+ const keep = readKeep(value);
160
+ if (!keep.ok) return keep;
174
161
 
175
162
  return {
176
163
  ok: true,
177
164
  input: {
178
- prompt: strings["prompt"] ?? "",
179
- cwd: strings["cwd"] ?? "",
180
- authPath: strings["authPath"] ?? "",
181
- modelsPath: strings["modelsPath"] ?? "",
182
- agentDir: strings["agentDir"] ?? "",
183
- sessionDir: strings["sessionDir"] ?? "",
184
- resumeSession,
185
- piCommand,
186
- model,
165
+ prompt: required.value["prompt"] ?? "",
166
+ cwd: required.value["cwd"] ?? "",
167
+ authPath: required.value["authPath"] ?? "",
168
+ modelsPath: required.value["modelsPath"] ?? "",
169
+ agentDir: required.value["agentDir"] ?? "",
170
+ sessionDir: required.value["sessionDir"] ?? "",
171
+ resumeSession: resumeSession.value,
172
+ piCommand: piCommand.value,
173
+ piHome: piHome.value,
174
+ model: model.value,
187
175
  thinkingLevel,
188
- access,
189
- bashTimeoutSecs,
190
- operadTools: operadTools === undefined ? undefined : { home: String(operadTools["home"]) },
191
- secretValues,
192
- images: images.length === 0 ? undefined : images,
176
+ access: access.value,
177
+ bashTimeoutSecs: bashTimeoutSecs.value,
178
+ operadTools: operadTools.value,
179
+ secretValues: secretValues.value,
180
+ images: images.value.length === 0 ? undefined : images.value,
181
+ skills: skills.value === undefined || skills.value.length === 0 ? undefined : skills.value,
182
+ useOwnSettings: useOwnSettings.value,
183
+ retry: retry.value,
184
+ keep: keep.value,
193
185
  },
194
186
  };
195
187
  }