@operad-io/harness-pi 0.0.0-stage → 0.1.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,219 @@
1
+ /**
2
+ * Finds the user's installed pi (ADR 0023 D9).
3
+ * The `pi` command on PATH (or the `command` setting) is resolved to its real
4
+ * path; walking up from there reaches the package directory whose
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.
7
+ */
8
+
9
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
10
+ import { dirname, isAbsolute, join, resolve, sep } from "node:path";
11
+ import { pathToFileURL } from "node:url";
12
+ import { isRecord } from "@operad-io/engine";
13
+
14
+ /** The package the worker uses. */
15
+ export const PI_PACKAGE = "@earendil-works/pi-coding-agent";
16
+
17
+ /** The oldest pi the worker's calls are written for. */
18
+ export const PI_FLOOR = "1.5.0";
19
+
20
+ /** The command looked up on PATH when the `command` setting is unset. */
21
+ export const DEFAULT_PI_COMMAND = "pi";
22
+
23
+ /** pi could not be found, or is not one the worker can use; the message says why. */
24
+ export class PiInstallError extends Error {
25
+ constructor(message: string) {
26
+ super(message);
27
+ this.name = "PiInstallError";
28
+ }
29
+ }
30
+
31
+ /** Where a pi lives and what it is. */
32
+ export interface PiInstall {
33
+ /** The command as given. */
34
+ readonly command: string;
35
+ /** The real path the command resolved to. */
36
+ readonly realPath: string;
37
+ /** The package directory. */
38
+ readonly dir: string;
39
+ /** The version in the package's `package.json`. */
40
+ readonly version: string;
41
+ /** The absolute path of the file `exports["."]` names. */
42
+ readonly entry: string;
43
+ }
44
+
45
+ export interface FindPiOptions {
46
+ /** The PATH to search; defaults to the process's own. */
47
+ readonly path?: string | undefined;
48
+ readonly cwd?: string | undefined;
49
+ /** The floor to compare with; defaults to `PI_FLOOR`. */
50
+ readonly floor?: string | undefined;
51
+ }
52
+
53
+ function readJson(path: string): Record<string, unknown> | undefined {
54
+ try {
55
+ const value: unknown = JSON.parse(readFileSync(path, "utf8"));
56
+ return isRecord(value) ? value : undefined;
57
+ } catch {
58
+ return undefined;
59
+ }
60
+ }
61
+
62
+ /** The file of a command: a path as given, or the first match on PATH. */
63
+ function locate(command: string, options: FindPiOptions): string | undefined {
64
+ if (command.includes("/") || command.includes(sep)) {
65
+ const path = isAbsolute(command) ? command : resolve(options.cwd ?? process.cwd(), command);
66
+ return existsSync(path) ? path : undefined;
67
+ }
68
+ const found = Bun.which(command, {
69
+ PATH: options.path ?? process.env.PATH ?? "",
70
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
71
+ });
72
+ return found ?? undefined;
73
+ }
74
+
75
+ /** `exports["."]` as a file path relative to the package; undefined if none. */
76
+ export function entryOf(exportsField: unknown): string | undefined {
77
+ const pick = (value: unknown): string | undefined => {
78
+ if (typeof value === "string") return value;
79
+ if (Array.isArray(value)) {
80
+ for (const item of value) {
81
+ const found = pick(item);
82
+ if (found !== undefined) return found;
83
+ }
84
+ return undefined;
85
+ }
86
+ if (isRecord(value)) {
87
+ // Conditions, in the order a Bun import follows them.
88
+ for (const key of ["import", "bun", "default"]) {
89
+ if (key in value) {
90
+ const found = pick(value[key]);
91
+ if (found !== undefined) return found;
92
+ }
93
+ }
94
+ }
95
+ return undefined;
96
+ };
97
+ if (typeof exportsField === "string" || Array.isArray(exportsField)) return pick(exportsField);
98
+ if (isRecord(exportsField)) {
99
+ if ("." in exportsField) return pick(exportsField["."]);
100
+ // A conditions object stands for ".".
101
+ return pick(exportsField);
102
+ }
103
+ return undefined;
104
+ }
105
+
106
+ interface Semver {
107
+ readonly core: readonly [number, number, number];
108
+ readonly pre: readonly string[];
109
+ }
110
+
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
+ };
118
+ }
119
+
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}`);
126
+ }
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;
130
+ }
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
+ }
150
+ }
151
+ return 0;
152
+ }
153
+
154
+ /** Finds the installed pi and checks its version against the floor. */
155
+ export function findPi(command: string = DEFAULT_PI_COMMAND, options: FindPiOptions = {}): PiInstall {
156
+ const floor = options.floor ?? PI_FLOOR;
157
+ const located = locate(command, options);
158
+ if (located === undefined) {
159
+ 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})`,
162
+ );
163
+ }
164
+ let real: string;
165
+ try {
166
+ real = realpathSync(located);
167
+ } catch (error) {
168
+ throw new PiInstallError(`${located}: ${error instanceof Error ? error.message : String(error)}`);
169
+ }
170
+
171
+ let dir = dirname(real);
172
+ let packageDir: string | undefined;
173
+ let manifest: Record<string, unknown> | undefined;
174
+ for (;;) {
175
+ const candidate = readJson(join(dir, "package.json"));
176
+ if (candidate !== undefined && candidate.name === PI_PACKAGE) {
177
+ packageDir = dir;
178
+ manifest = candidate;
179
+ break;
180
+ }
181
+ const parent = dirname(dir);
182
+ if (parent === dir) break;
183
+ dir = parent;
184
+ }
185
+ if (packageDir === undefined || manifest === undefined) {
186
+ throw new PiInstallError(
187
+ `${command} resolves to ${real}, which is not inside a ${PI_PACKAGE} package ` +
188
+ `(a shell wrapper cannot be followed); set the pi "command" setting to the package's bin`,
189
+ );
190
+ }
191
+
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
+ }
201
+
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`);
209
+ }
210
+ return { command, realPath: real, dir: packageDir, version, entry };
211
+ }
212
+
213
+ /** The library's own module type, for the call sites. */
214
+ export type PiLibrary = typeof import("@earendil-works/pi-coding-agent");
215
+
216
+ /** Loads the library file of an install with a dynamic import. */
217
+ export async function loadPi(install: PiInstall): Promise<PiLibrary> {
218
+ return (await import(pathToFileURL(install.entry).href)) as PiLibrary;
219
+ }
@@ -0,0 +1,195 @@
1
+ /**
2
+ * The wire shapes of the pi child program. `README.md` holds the same tables;
3
+ * `test/protocol.test.ts` checks the program against them.
4
+ */
5
+
6
+ import { readProfile } from "@operad-io/access-match";
7
+ import { parseImageInputs, type ImageInput, type SharedLine } from "@operad-io/harness-process";
8
+ import { isRecord } from "@operad-io/engine";
9
+
10
+ /** The longest one bash call may run when the settings do not say, in seconds. */
11
+ export const DEFAULT_BASH_TIMEOUT_SECS = 1800;
12
+
13
+ export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
14
+ export type WorkerThinkingLevel = (typeof THINKING_LEVELS)[number];
15
+
16
+ /** What the program reads from stdin. */
17
+ export interface WorkerInput {
18
+ readonly prompt: string;
19
+ readonly cwd: string;
20
+ readonly authPath: string;
21
+ readonly modelsPath: string;
22
+ readonly agentDir: string;
23
+ /** The pi command (a name on PATH or a path); unset means `pi`. */
24
+ readonly piCommand?: string | undefined;
25
+ readonly sessionDir: string;
26
+ readonly resumeSession?: string | undefined;
27
+ readonly model?: string | undefined;
28
+ readonly thinkingLevel?: WorkerThinkingLevel | undefined;
29
+ readonly access?: Readonly<Record<string, unknown>> | undefined;
30
+ /** The longest one bash call may run, in seconds; unset means `DEFAULT_BASH_TIMEOUT_SECS`. */
31
+ readonly bashTimeoutSecs?: number | undefined;
32
+ /** Operad's own tools, registered with pi as custom tools that read this home. */
33
+ readonly operadTools?: { readonly home: string } | undefined;
34
+ /** Secret values of the operad secret store; a log line shows `***` where one appears. */
35
+ readonly secretValues?: readonly string[] | undefined;
36
+ /** Images given to pi with the prompt, read from these files. */
37
+ readonly images?: readonly ImageInput[] | undefined;
38
+ }
39
+
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
+ export type FailureReason = "invalid_input" | "session_missing" | "model_missing" | "model_error";
50
+
51
+ /** The last line of stdout. */
52
+ export interface WorkerResult {
53
+ readonly type: "result";
54
+ readonly result: WorkerResultName;
55
+ readonly sessionId: string | null;
56
+ readonly usage: WorkerUsage;
57
+ /** The priced part of the run; `incomplete` when some message had no price. */
58
+ readonly cost: { readonly micros: number; readonly incomplete?: true } | null;
59
+ readonly finalMessage: string | null;
60
+ readonly reason?: FailureReason;
61
+ readonly message?: string;
62
+ }
63
+
64
+ export type WorkerLine =
65
+ | {
66
+ readonly type: "message_end";
67
+ readonly role: "assistant";
68
+ /** The first 300 characters of the message's text, one paragraph; absent when it has none. */
69
+ readonly text?: string;
70
+ readonly stopReason: string;
71
+ readonly usage: Required<WorkerUsage>;
72
+ readonly cost: { readonly total: number } | null;
73
+ }
74
+ | SharedLine
75
+ | { readonly type: "agent_settled"; readonly aborted: boolean }
76
+ | WorkerResult;
77
+
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
+ export type ParsedInput =
98
+ | { readonly ok: true; readonly input: WorkerInput }
99
+ | { readonly ok: false; readonly message: string };
100
+
101
+ const REQUIRED_STRINGS = ["prompt", "cwd", "authPath", "modelsPath", "agentDir", "sessionDir"] as const;
102
+
103
+ /** Validates the decoded stdin object; the message names the field at fault. */
104
+ export function parseInput(value: unknown): ParsedInput {
105
+ if (!isRecord(value)) return { ok: false, message: "the input must be a JSON object" };
106
+
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)) {
132
+ return { ok: false, message: "model must look like provider/id" };
133
+ }
134
+
135
+ const level = value["thinkingLevel"];
136
+ let thinkingLevel: WorkerThinkingLevel | undefined;
137
+ if (level !== undefined) {
138
+ const known = THINKING_LEVELS.find((candidate) => candidate === level);
139
+ if (known === undefined) {
140
+ return { ok: false, message: `thinkingLevel must be one of ${THINKING_LEVELS.join(", ")}` };
141
+ }
142
+ thinkingLevel = known;
143
+ }
144
+
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
+ }
152
+
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
+ }
157
+
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
+ }
162
+
163
+ const images = parseImageInputs(value["images"]);
164
+ if (typeof images === "string") return { ok: false, message: images };
165
+
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
+ }
174
+
175
+ return {
176
+ ok: true,
177
+ 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,
187
+ thinkingLevel,
188
+ access,
189
+ bashTimeoutSecs,
190
+ operadTools: operadTools === undefined ? undefined : { home: String(operadTools["home"]) },
191
+ secretValues,
192
+ images: images.length === 0 ? undefined : images,
193
+ },
194
+ };
195
+ }