@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.
package/src/index.ts CHANGED
@@ -8,101 +8,82 @@
8
8
  */
9
9
 
10
10
  import pkg from "../package.json" with { type: "json" };
11
- import { secretValuesOf } from "@operad-io/access-match";
12
- import { existsSync, readFileSync } from "node:fs";
11
+ import { readFileSync } from "node:fs";
13
12
  import { mkdir } from "node:fs/promises";
14
13
  import { homedir } from "node:os";
15
- import { isAbsolute, join, resolve } from "node:path";
14
+ import { dirname, isAbsolute, join, resolve } from "node:path";
16
15
  import { fileURLToPath } from "node:url";
17
16
  import {
18
17
  isRecord,
19
- paramsObject,
20
- defineFlow,
21
18
  definePlugin,
19
+ type HarnessEfforts,
20
+ type HarnessModelContext,
21
+ type HarnessModelInfo,
22
22
  type PluginStepResult,
23
23
  type StepContext,
24
24
  } from "@operad-io/engine";
25
25
  import {
26
- ALLOW_ALWAYS,
27
- accessWithAlwaysAllow,
28
- alwaysAllowFromGrant,
29
- appendAlwaysAllow,
30
- answerGrant,
31
- askToolEvent,
32
- canAsk,
33
- createCallAsker,
26
+ assertWorkerAvailable,
34
27
  CONCURRENCY_SETTING,
35
- eventNote,
36
- askNote,
28
+ DEFAULT_STALL_SECS,
29
+ DEFAULT_WALL_TIME_SECS,
37
30
  flagValue,
38
- hasGrants,
39
- inboxOf,
40
31
  imageInputsOf,
41
- operadToolsOf,
42
- JsonlLog,
43
- deliverLine,
32
+ keepKeyOf,
33
+ MAX_WALL_TIME_SECS,
44
34
  modelLimit,
45
- standardUsage,
46
- type UsageSource,
47
- directoryError,
35
+ operadToolsOf,
36
+ optionalPositive,
48
37
  optionalText,
49
- parseResult,
50
38
  parseStepFlags,
51
- personStarted,
52
- readAlwaysAllow,
53
- resultFor,
54
- secs,
39
+ promptFlowOf,
40
+ readAgentStep,
41
+ runWorkerStep,
42
+ STALL_SETTING,
43
+ STEP_TIMEOUT_SECS,
55
44
  stringListParam,
56
- text,
57
- type StepFlagSpec,
58
- runAgent,
59
45
  systemClock,
46
+ text,
47
+ toolExecutionEvent,
48
+ WALL_TIME_SETTING,
60
49
  type Clock,
61
- type ToolEvent,
50
+ type KeptRunOptions,
51
+ type StepFlagSpec,
62
52
  } from "@operad-io/harness-process";
63
- import { DEFAULT_PI_COMMAND, findPi, PI_FLOOR } from "./pi-install.ts";
53
+ import { authFileHasCredential } from "./auth-file.ts";
54
+ import {
55
+ PI_LIST_TIMEOUT_MS,
56
+ piModelInfo,
57
+ piModelList,
58
+ piModelListReady,
59
+ piModelWindows,
60
+ readPiModelList,
61
+ } from "./model-list.ts";
62
+ import { DEFAULT_PI_COMMAND, findPi, PI_FLOOR, PI_VERSION } from "./pi-install.ts";
63
+ import { runLoginStep, type LoginRunOptions } from "./login.ts";
64
64
  import {
65
65
  DEFAULT_BASH_TIMEOUT_SECS,
66
66
  THINKING_LEVELS,
67
- type WorkerResult,
68
67
  type WorkerThinkingLevel,
69
68
  } from "./protocol.ts";
70
69
 
71
- /** How long an agent may run before the step stops it. */
72
- export const DEFAULT_WALL_TIME_SECS = 3600;
73
-
74
- /** How long an agent may go without a new output line. */
75
- export const DEFAULT_STALL_SECS = 600;
70
+ export {
71
+ DEFAULT_STALL_SECS,
72
+ DEFAULT_WALL_TIME_SECS,
73
+ MAX_WALL_TIME_SECS,
74
+ STEP_TIMEOUT_SECS,
75
+ };
76
76
 
77
- /** One run of the step may take this long; it is above every allowed wall time. */
78
- export const STEP_TIMEOUT_SECS = 8 * 3600;
77
+ export { PI_PACKAGE, PI_VERSION } from "./pi-install.ts";
79
78
 
80
- /** The longest wall time a run may ask for: the step timeout minus a margin. */
81
- export const MAX_WALL_TIME_SECS = STEP_TIMEOUT_SECS - 300;
79
+ /** The tool call one pi line starts or settles, or undefined for another line. */
80
+ export { toolExecutionEvent as piToolEvent } from "@operad-io/harness-process";
82
81
 
83
82
  export const DEFAULT_AUTH_PATH = "~/.pi/agent/auth.json";
84
83
  export const DEFAULT_MODELS_PATH = "~/.pi/agent/models.json";
85
84
 
86
85
  const WORKER_PATH = fileURLToPath(new URL("./worker.ts", import.meta.url));
87
86
 
88
- /**
89
- * Reads one worker line and reports the tool call it starts or settles. The
90
- * worker writes pi's `tool_execution_start` and `tool_execution_end` under
91
- * `type`.
92
- */
93
- export function piToolEvent(line: string): ToolEvent | undefined {
94
- let value: unknown;
95
- try {
96
- value = JSON.parse(line);
97
- } catch {
98
- return undefined;
99
- }
100
- if (!isRecord(value)) return undefined;
101
- if (value.type === "tool_execution_start") return "tool-start";
102
- if (value.type === "tool_execution_end") return "tool-end";
103
- return undefined;
104
- }
105
-
106
87
  /** What a test injects: the clock and the program the step starts. */
107
88
  export interface PiHarnessOptions {
108
89
  readonly clock?: Clock | undefined;
@@ -110,61 +91,79 @@ export interface PiHarnessOptions {
110
91
  readonly command?: string | undefined;
111
92
  /** The arguments before the worker input; defaults to `worker.ts`. */
112
93
  readonly args?: readonly string[] | undefined;
94
+ /** Test seam: the executable of a login; defaults to the running Bun. */
95
+ readonly loginCommand?: string | undefined;
96
+ /** Test seam: the arguments before a login's input; defaults to `login-worker.ts`. */
97
+ readonly loginArgs?: readonly string[] | undefined;
98
+ /** Test seam: how long a login may take; defaults to `LOGIN_TIMEOUT_MS`. */
99
+ readonly loginTimeoutMs?: number | undefined;
113
100
  /** The time now in milliseconds; defaults to `Date.now`. It ages the cached catalogue. */
114
101
  readonly now?: (() => number) | undefined;
115
102
  /** How long `pi --list-models` may take; defaults to `PI_LIST_TIMEOUT_MS`. */
116
103
  readonly listTimeoutMs?: number | undefined;
117
104
  /** pi's settings file, where its default model is; defaults to `~/.pi/agent/settings.json`. */
118
105
  readonly piSettingsPath?: string | undefined;
106
+ /** Test seam: how long a chat's worker is kept after a reply. */
107
+ readonly keepMs?: number | undefined;
108
+ /** Test seam: how long a kept worker may take to answer its first line. */
109
+ readonly keptFirstLineMs?: number | undefined;
110
+ /** Test seam: how many workers one home keeps. */
111
+ readonly maxKept?: number | undefined;
112
+ /** Test seam: reads a file as text; defaults to `readFileSync(path, "utf8")`. */
113
+ readonly readFile?: ((path: string) => string) | undefined;
119
114
  }
120
115
 
121
- /** How long `pi --list-models` may take before pi counts as not answering. */
122
- export const PI_LIST_TIMEOUT_MS = 10_000;
116
+ /** pi's settings file as an object; undefined when it cannot be read. */
117
+ function readPiSettings(
118
+ settingsPath: string,
119
+ readFile: (path: string) => string,
120
+ ): Readonly<Record<string, unknown>> | undefined {
121
+ try {
122
+ const value: unknown = JSON.parse(readFile(settingsPath));
123
+ return isRecord(value) ? value : undefined;
124
+ } catch {
125
+ return undefined;
126
+ }
127
+ }
123
128
 
124
- /** How long a catalogue pi gave (or failed to give) is kept. */
125
- export const PI_LIST_CACHE_MS = 60_000;
129
+ /** pi's own default model, from its settings; undefined when it names none. */
130
+ function piDefaultModel(settings: Readonly<Record<string, unknown>> | undefined): string | undefined {
131
+ if (settings === undefined) return undefined;
132
+ const { defaultProvider, defaultModel } = settings;
133
+ if (typeof defaultProvider !== "string" || typeof defaultModel !== "string") return undefined;
134
+ return defaultProvider === "" || defaultModel === "" ? undefined : `${defaultProvider}/${defaultModel}`;
135
+ }
126
136
 
127
- /**
128
- * The rows of `pi --list-models` as provider/id: the first two columns of each
129
- * row after the header row. Anything that is not such a row is skipped.
130
- */
131
- export function parsePiCatalogue(output: string): readonly string[] {
132
- const found: string[] = [];
133
- let header = false;
134
- for (const line of output.split("\n")) {
135
- const [provider, id] = line.trim().split(/\s+/);
136
- if (provider === undefined || id === undefined) continue;
137
- // Rows count only after the header; a status sentence has none.
138
- if (provider === "provider" && id === "model") {
139
- header = true;
140
- continue;
141
- }
142
- if (!header) continue;
143
- const name = `${provider}/${id}`;
144
- if (!found.includes(name)) found.push(name);
145
- }
146
- return found;
137
+ /** One of pi's thinking levels, or undefined for anything else. */
138
+ function thinkingLevelOf(value: unknown): WorkerThinkingLevel | undefined {
139
+ return typeof value === "string"
140
+ ? THINKING_LEVELS.find((level) => level === value)
141
+ : undefined;
147
142
  }
148
143
 
149
- /** pi's own default model, from its settings file; undefined when it names none. */
150
- function piDefaultModel(settingsPath: string): string | undefined {
151
- try {
152
- const value: unknown = JSON.parse(readFileSync(settingsPath, "utf8"));
153
- if (!isRecord(value)) return undefined;
154
- const { defaultProvider, defaultModel } = value;
155
- if (typeof defaultProvider !== "string" || typeof defaultModel !== "string") return undefined;
156
- return defaultProvider === "" || defaultModel === "" ? undefined : `${defaultProvider}/${defaultModel}`;
157
- } catch {
158
- return undefined;
144
+ /** pi's own default thinking level, from its settings; undefined when it names none. */
145
+ function piDefaultThinkingLevel(
146
+ settings: Readonly<Record<string, unknown>> | undefined,
147
+ ): WorkerThinkingLevel | undefined {
148
+ return settings === undefined ? undefined : thinkingLevelOf(settings.defaultThinkingLevel);
149
+ }
150
+
151
+ /** What pi is likely to use: the model's provider, else its settings' default provider. */
152
+ function piProvider(
153
+ model: unknown,
154
+ settings: Readonly<Record<string, unknown>> | undefined,
155
+ ): string | undefined {
156
+ if (typeof model === "string" && model.includes("/")) {
157
+ const provider = model.slice(0, model.indexOf("/"));
158
+ if (provider.length > 0) return provider;
159
159
  }
160
+ return typeof settings?.defaultProvider === "string" && settings.defaultProvider.length > 0
161
+ ? settings.defaultProvider
162
+ : undefined;
160
163
  }
161
164
 
162
- /** The efforts a chat may pick with this agent, mapped to its thinking levels. */
163
- export const PI_EFFORTS = {
164
- list: THINKING_LEVELS,
165
- default: "medium",
166
- flag: "--thinking",
167
- } as const;
165
+ /** pi's documented built-in thinking level, used when neither operad nor pi names one. */
166
+ export const PI_BUILTIN_THINKING_LEVEL = "medium" satisfies WorkerThinkingLevel;
168
167
 
169
168
  /** The settings a config.json section may set for this plugin. */
170
169
  const PLUGIN_SETTINGS = {
@@ -172,22 +171,26 @@ const PLUGIN_SETTINGS = {
172
171
  properties: {
173
172
  model: {
174
173
  type: "string" as const,
174
+ title: "Model",
175
175
  minLength: 3,
176
176
  description: "The model as provider/id; unset uses pi's default model.",
177
177
  },
178
178
  models: {
179
179
  type: "array" as const,
180
+ title: "Model choices",
180
181
  items: { type: "string" as const, minLength: 3 },
181
182
  description:
182
183
  "The models a chat may pick, as provider/id; unset offers every model pi lists.",
183
184
  },
184
185
  thinkingLevel: {
185
186
  type: "string" as const,
187
+ title: "Effort",
186
188
  enum: THINKING_LEVELS,
187
189
  description: "The reasoning level; unset uses pi's default.",
188
190
  },
189
191
  command: {
190
192
  type: "string" as const,
193
+ title: "Pi command",
191
194
  minLength: 1,
192
195
  default: DEFAULT_PI_COMMAND,
193
196
  description:
@@ -195,31 +198,23 @@ const PLUGIN_SETTINGS = {
195
198
  },
196
199
  authPath: {
197
200
  type: "string" as const,
201
+ title: "Credentials file",
198
202
  minLength: 1,
199
203
  default: DEFAULT_AUTH_PATH,
200
204
  description: "pi's credentials file.",
201
205
  },
202
206
  modelsPath: {
203
207
  type: "string" as const,
208
+ title: "Models file",
204
209
  minLength: 1,
205
210
  default: DEFAULT_MODELS_PATH,
206
211
  description: "pi's custom models file.",
207
212
  },
208
- wallTimeSecs: {
209
- type: "number" as const,
210
- minimum: 1,
211
- maximum: MAX_WALL_TIME_SECS,
212
- default: DEFAULT_WALL_TIME_SECS,
213
- description: "The longest one agent run may take.",
214
- },
215
- stallSecs: {
216
- type: "number" as const,
217
- minimum: 1,
218
- default: DEFAULT_STALL_SECS,
219
- description: "How long an agent may be silent while no tool call is open.",
220
- },
213
+ wallTimeSecs: WALL_TIME_SETTING,
214
+ stallSecs: STALL_SETTING,
221
215
  bashTimeoutSecs: {
222
216
  type: "integer" as const,
217
+ title: "Bash timeout",
223
218
  minimum: 1,
224
219
  default: DEFAULT_BASH_TIMEOUT_SECS,
225
220
  description:
@@ -230,14 +225,6 @@ const PLUGIN_SETTINGS = {
230
225
  additionalProperties: false as const,
231
226
  };
232
227
 
233
- function optionalPositiveInteger(value: unknown, at: string): number | undefined {
234
- if (value === undefined) return undefined;
235
- if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
236
- throw new Error(`${at}: must be a positive integer`);
237
- }
238
- return value;
239
- }
240
-
241
228
  /** The spelling of this harness's step `args`; the parsing is harness-process's. */
242
229
  const STEP_FLAGS: StepFlagSpec<WorkerThinkingLevel> = {
243
230
  levelFlag: "--thinking",
@@ -255,6 +242,14 @@ function expandHome(path: string): string {
255
242
  return isAbsolute(path) ? path : resolve(path);
256
243
  }
257
244
 
245
+ /** The models a pi chat may pick, with what pi's kept list says about each. */
246
+ export interface PiDeclaredModels {
247
+ list: readonly string[];
248
+ default: string | null;
249
+ windows?: Readonly<Record<string, number>> | undefined;
250
+ info?: Readonly<Record<string, HarnessModelInfo>> | undefined;
251
+ }
252
+
258
253
  /**
259
254
  * Creates the pi harness plugin. Its worker is `worker.ts` under the running
260
255
  * Bun; a test replaces the program with a fake that prints fixed lines.
@@ -264,33 +259,37 @@ export function createPiHarnessPlugin(options: PiHarnessOptions = {}) {
264
259
  const command = options.command ?? process.execPath;
265
260
  const commandArgs = options.args ?? [WORKER_PATH];
266
261
  const now = options.now ?? Date.now;
262
+ const loginOptions: LoginRunOptions = {
263
+ command: options.loginCommand ?? process.execPath,
264
+ ...(options.loginArgs === undefined ? {} : { args: options.loginArgs }),
265
+ ...(options.loginTimeoutMs === undefined ? {} : { timeoutMs: options.loginTimeoutMs }),
266
+ now,
267
+ };
267
268
  const listTimeoutMs = options.listTimeoutMs ?? PI_LIST_TIMEOUT_MS;
269
+ const readFile = options.readFile ?? ((path: string) => readFileSync(path, "utf8"));
268
270
  const piSettingsPath =
269
271
  options.piSettingsPath ?? join(homedir(), ".pi", "agent", "settings.json");
270
272
 
271
- // What `pi --list-models` printed, by command, kept for a while. It is asked
272
- // when the list is first needed, never at load, and prints nothing itself.
273
- const catalogues = new Map<string, { readonly at: number; readonly list: readonly string[] }>();
274
- function catalogue(piCommand: string): readonly string[] {
275
- const kept = catalogues.get(piCommand);
276
- if (kept !== undefined && now() - kept.at < PI_LIST_CACHE_MS) return kept.list;
277
- let list: readonly string[] = [];
278
- try {
279
- const asked = Bun.spawnSync([piCommand, "--list-models"], {
280
- stdin: "ignore",
281
- stdout: "pipe",
282
- stderr: "pipe",
283
- timeout: listTimeoutMs,
284
- });
285
- if (asked.exitCode === 0 && !asked.exitedDueToTimeout) {
286
- const out = asked.stdout.toString();
287
- list = parsePiCatalogue(out.trim() === "" ? asked.stderr.toString() : out);
288
- }
289
- } catch {
290
- list = [];
291
- }
292
- catalogues.set(piCommand, { at: now(), list });
293
- return list;
273
+ function modelsPathOf(settings: Readonly<Record<string, unknown>>): string {
274
+ return typeof settings.modelsPath === "string" && settings.modelsPath !== ""
275
+ ? settings.modelsPath
276
+ : DEFAULT_MODELS_PATH;
277
+ }
278
+
279
+ function listOptions(
280
+ piCommand: string,
281
+ context: HarnessModelContext,
282
+ modelsPath: string = DEFAULT_MODELS_PATH,
283
+ ) {
284
+ return {
285
+ home: context.home,
286
+ command: piCommand,
287
+ now,
288
+ timeoutMs: listTimeoutMs,
289
+ log: context.log,
290
+ registryPath: join(dirname(expandHome(modelsPath)), "models-store.json"),
291
+ readFile,
292
+ };
294
293
  }
295
294
 
296
295
  function stringList(value: unknown): readonly string[] | undefined {
@@ -299,61 +298,144 @@ export function createPiHarnessPlugin(options: PiHarnessOptions = {}) {
299
298
  : undefined;
300
299
  }
301
300
 
302
- /** The models a chat may pick and the default among them. */
303
- function piModels(settings: Readonly<Record<string, unknown>>): { list: readonly string[]; default: string | null } {
304
- const command = typeof settings.command === "string" && settings.command !== "" ? settings.command : DEFAULT_PI_COMMAND;
305
- const configured = stringList(settings.models);
306
- const list = configured ?? catalogue(command);
301
+ function piCommandOf(settings: Readonly<Record<string, unknown>>): string {
302
+ return typeof settings.command === "string" && settings.command !== ""
303
+ ? settings.command
304
+ : DEFAULT_PI_COMMAND;
305
+ }
306
+
307
+ /**
308
+ * The command an install is reached by: the setting as it is; when it is the
309
+ * default `pi`, the pi operad installed in the home is used if PATH has none.
310
+ */
311
+ function piCommandFor(settings: Readonly<Record<string, unknown>>, home: string): string {
312
+ const command = piCommandOf(settings);
313
+ if (command !== DEFAULT_PI_COMMAND) return command;
314
+ try {
315
+ return findPi(command, { home }).command;
316
+ } catch {
317
+ return command;
318
+ }
319
+ }
320
+
321
+ /** The context windows pi's kept list gives for the models this chat may pick. */
322
+ function windowsOf(
323
+ options: ReturnType<typeof listOptions>,
324
+ kept: ReturnType<typeof readPiModelList> | null,
325
+ list: readonly string[],
326
+ ): Readonly<Record<string, number>> | undefined {
327
+ const known = piModelWindows(options, kept);
328
+ const windows: Record<string, number> = {};
329
+ for (const model of list) {
330
+ const window = known[model];
331
+ if (window !== undefined) windows[model] = window;
332
+ }
333
+ return Object.keys(windows).length === 0 ? undefined : windows;
334
+ }
335
+
336
+ /** What pi's kept list says about the models this chat may pick. */
337
+ function infoOf(
338
+ options: ReturnType<typeof listOptions>,
339
+ kept: ReturnType<typeof readPiModelList> | null,
340
+ list: readonly string[],
341
+ ): Readonly<Record<string, HarnessModelInfo>> | undefined {
342
+ const known = piModelInfo(options, kept);
343
+ const info: Record<string, HarnessModelInfo> = {};
344
+ for (const model of list) {
345
+ const found = known[model];
346
+ if (found !== undefined) info[model] = found;
347
+ }
348
+ return Object.keys(info).length === 0 ? undefined : info;
349
+ }
350
+
351
+ /** The models a chat may pick and the default among them, from one kept read. */
352
+ function declaredModels(
353
+ settings: Readonly<Record<string, unknown>>,
354
+ options: ReturnType<typeof listOptions>,
355
+ kept: ReturnType<typeof readPiModelList> | null,
356
+ list: readonly string[],
357
+ ): PiDeclaredModels {
307
358
  const wanted =
308
359
  typeof settings.model === "string" && settings.model !== ""
309
360
  ? settings.model
310
- : piDefaultModel(piSettingsPath);
311
- return { list, default: wanted !== undefined && list.includes(wanted) ? wanted : null };
361
+ : piDefaultModel(readPiSettings(piSettingsPath, readFile));
362
+ const windows = windowsOf(options, kept, list);
363
+ const info = infoOf(options, kept, list);
364
+ return {
365
+ list,
366
+ default: wanted !== undefined && list.includes(wanted) ? wanted : null,
367
+ ...(windows === undefined ? {} : { windows }),
368
+ ...(info === undefined ? {} : { info }),
369
+ };
312
370
  }
313
371
 
314
- const promptFlow = defineFlow({
315
- name: "pi:prompt",
316
- entry: "agent",
317
- steps: [
318
- {
319
- id: "agent",
320
- kind: "plugin",
321
- params: { use: "pi/agent", params: {} },
322
- replay: "unsafe",
323
- next: { done: "done", failed: "failed", interrupted: "cancelled", waiting: "person" },
324
- },
325
- {
326
- // A question about a call ran out of grace. The answer sends the run
327
- // back to the agent, which continues the session with it.
328
- id: "person",
329
- kind: "wait_person",
330
- params: {
331
- prompt: "The agent asked about a call.",
332
- choices: ["allow_once", "reject_once"],
333
- lateChoices: ["allow_always"],
334
- },
335
- replay: "safe",
336
- next: {
337
- allow_once: "agent",
338
- allow_always: "agent",
339
- reject_once: "agent",
340
- interrupted: "cancelled",
341
- },
342
- },
343
- { id: "done", kind: "end", params: { status: "done" }, replay: "safe" },
344
- { id: "failed", kind: "end", params: { status: "failed" }, replay: "safe" },
345
- { id: "cancelled", kind: "end", params: { status: "cancelled" }, replay: "safe" },
346
- ],
347
- });
372
+ /** The models a chat may pick, from the kept list; `ready` waits for a first list. */
373
+ function piModels(
374
+ settings: Readonly<Record<string, unknown>>,
375
+ context: HarnessModelContext,
376
+ ): PiDeclaredModels;
377
+ function piModels(
378
+ settings: Readonly<Record<string, unknown>>,
379
+ context: HarnessModelContext,
380
+ ready: true,
381
+ ): Promise<PiDeclaredModels>;
382
+ function piModels(
383
+ settings: Readonly<Record<string, unknown>>,
384
+ context: HarnessModelContext,
385
+ ready = false,
386
+ ): PiDeclaredModels | Promise<PiDeclaredModels> {
387
+ 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),
394
+ );
395
+ }
396
+
397
+ /**
398
+ * The efforts a chat may pick, and the one it starts with: operad's
399
+ * `thinkingLevel` when it sets one, else pi's own `defaultThinkingLevel`,
400
+ * else pi's documented built-in level.
401
+ */
402
+ function piEfforts(settings: Readonly<Record<string, unknown>>): HarnessEfforts {
403
+ const wanted =
404
+ thinkingLevelOf(settings.thinkingLevel) ??
405
+ piDefaultThinkingLevel(readPiSettings(piSettingsPath, readFile)) ??
406
+ PI_BUILTIN_THINKING_LEVEL;
407
+ return { list: THINKING_LEVELS, default: wanted, flag: "--thinking" };
408
+ }
409
+
410
+ const promptFlow = promptFlowOf("pi:prompt", "pi/agent");
348
411
 
349
412
  return definePlugin({
350
413
  name: "pi",
351
414
  kind: "harness",
352
415
  version: pkg.version,
353
416
  models: piModels,
354
- efforts: PI_EFFORTS,
417
+ modelsReady: (settings, context) => piModels(settings, context, true),
418
+ efforts: piEfforts,
419
+ capabilities: { loadsSkills: true, takesMessagesMidRun: true, accessLevels: ["plan", "ask", "edits", "full"] },
420
+ signedIn: async (settings) => {
421
+ const authPath = expandHome(
422
+ typeof settings.authPath === "string" ? settings.authPath : DEFAULT_AUTH_PATH,
423
+ );
424
+ return authFileHasCredential(
425
+ authPath,
426
+ piProvider(settings.model, readPiSettings(piSettingsPath, readFile)),
427
+ );
428
+ },
355
429
  settings: PLUGIN_SETTINGS,
356
430
  steps: [
431
+ {
432
+ name: "login",
433
+ // A login asks a person and writes pi's own credential; it returns the
434
+ // model they chose (ADR 0023 D11).
435
+ results: ["done", "failed"],
436
+ timeoutSecs: 660,
437
+ run: (ctx: StepContext) => runLoginStep(ctx, loginOptions),
438
+ },
357
439
  {
358
440
  name: "agent",
359
441
  // A question's answer comes back as `resumeSession` and `askAnswer`.
@@ -361,7 +443,7 @@ export function createPiHarnessPlugin(options: PiHarnessOptions = {}) {
361
443
  // `waiting`: a question about a call was not answered within the grace.
362
444
  results: ["done", "failed", "interrupted", "waiting"],
363
445
  // The deny and ask fields are applied in the worker's tool_call hook.
364
- enforces: ["denyPaths", "denyCommands", "askCommands", "askPaths", "readPaths", "alwaysAllow"],
446
+ enforces: ["level", "denyPaths", "denyCommands", "askCommands", "askPaths", "readPaths", "alwaysAllow"],
365
447
  timeoutSecs: STEP_TIMEOUT_SECS,
366
448
  // The model the step uses: its `--model` argument, else the setting.
367
449
  limit: modelLimit("pi", (params, settings) => {
@@ -373,225 +455,155 @@ export function createPiHarnessPlugin(options: PiHarnessOptions = {}) {
373
455
  }),
374
456
  async run(ctx: StepContext, params: unknown): Promise<PluginStepResult> {
375
457
  const at = "pi/agent";
376
- const input = paramsObject(params, at);
377
- const flow = isRecord(ctx.params) ? ctx.params : {};
378
-
379
- const prompt = text(input.prompt ?? flow.prompt, `${at}: params.prompt`);
380
- const note = eventNote(ctx.trigger);
381
- const rawAskAnswer = input.askAnswer ?? flow.askAnswer;
382
- const answerNote = askNote(rawAskAnswer);
383
- const promptWithNote = [prompt, note, answerNote]
384
- .filter((part): part is string => part !== undefined)
385
- .join("\n\n");
386
- const cwd = text(input.cwd ?? flow.cwd, `${at}: params.cwd`);
387
- const flags = parseStepFlags(
388
- stringListParam(input.args === undefined ? flow.args : input.args, `${at}: params.args`),
389
- STEP_FLAGS,
390
- );
391
- // The model the step will use, known before anything can fail.
392
- const knownModel =
393
- typeof flags === "string"
394
- ? flagValue(input.args === undefined ? flow.args : input.args, "--model") ??
395
- (typeof ctx.settings.model === "string" ? ctx.settings.model : undefined)
396
- : (flags.model ??
397
- (typeof ctx.settings.model === "string" ? ctx.settings.model : undefined));
398
- const early: UsageSource = { harness: "pi", model: knownModel ?? null };
399
- if (typeof flags === "string") {
400
- const message = `${at}: ${flags}`;
401
- const log = await ctx.logger.write(message);
402
- return {
403
- result: "failed",
404
- data: {
405
- reason: "invalid_args",
406
- message,
407
- exitCode: null,
408
- signal: null,
409
- sessionId: null,
410
- finalMessage: null,
411
- usage: standardUsage(early, undefined, null),
412
- log,
413
- durationMs: 0,
414
- stderr: [message],
415
- },
416
- };
417
- }
418
- const resumeSession = optionalText(
419
- input.resumeSession ?? flow.resumeSession,
420
- `${at}: params.resumeSession`,
421
- );
422
- const wallTimeSecs = secs(
423
- input.wallTimeSecs ?? ctx.settings.wallTimeSecs ?? DEFAULT_WALL_TIME_SECS,
424
- `${at}: params.wallTimeSecs`,
425
- );
426
- if (wallTimeSecs > MAX_WALL_TIME_SECS) {
427
- throw new Error(`${at}: params.wallTimeSecs: must be at most ${MAX_WALL_TIME_SECS}`);
428
- }
429
- const stallSecs = secs(
430
- input.stallSecs ?? ctx.settings.stallSecs ?? DEFAULT_STALL_SECS,
431
- `${at}: params.stallSecs`,
432
- );
433
- const bashTimeoutSecs = optionalPositiveInteger(
434
- ctx.settings.bashTimeoutSecs,
435
- `${at}: settings.bashTimeoutSecs`,
436
- );
437
- const model =
438
- flags.model ?? optionalText(ctx.settings.model, `${at}: settings.model`);
439
- const thinkingLevel =
440
- flags.level ??
441
- optionalText(input.effort, `${at}: params.effort`) ??
442
- optionalText(ctx.settings.thinkingLevel, `${at}: settings.thinkingLevel`);
443
- const authPath = expandHome(
444
- text(ctx.settings.authPath ?? DEFAULT_AUTH_PATH, `${at}: settings.authPath`),
445
- );
446
- const modelsPath = expandHome(
447
- text(ctx.settings.modelsPath ?? DEFAULT_MODELS_PATH, `${at}: settings.modelsPath`),
448
- );
449
-
450
- const piCommand = optionalText(ctx.settings.command, `${at}: settings.command`);
451
- // A configured model pi does not list is reported once, here.
452
- const configured = stringList(ctx.settings.models);
453
- if (configured !== undefined && model !== undefined && configured.includes(model)) {
454
- const listed = catalogue(piCommand ?? DEFAULT_PI_COMMAND);
455
- if (listed.length > 0 && !listed.includes(model)) {
456
- await ctx.logger.write(`pi/agent: the model "${model}" is in settings.models but pi does not list it`);
457
- }
458
- }
459
-
460
- const cwdProblem = await directoryError(cwd);
461
- if (cwdProblem !== undefined) {
462
- const log = await ctx.logger.write(cwdProblem);
463
- return {
464
- result: "failed",
465
- data: {
466
- reason: "cwd",
467
- message: cwdProblem,
468
- exitCode: null,
469
- signal: null,
470
- sessionId: null,
471
- finalMessage: null,
472
- usage: standardUsage(early, undefined, null),
473
- log,
474
- durationMs: 0,
475
- stderr: [cwdProblem],
476
- },
477
- };
478
- }
479
-
480
- const agentDir = join(ctx.home, "harness", "pi");
481
- const sessionDir = join(agentDir, "sessions");
482
- await mkdir(sessionDir, { recursive: true });
483
-
484
- const operadTools = operadToolsOf(input.operadTools ?? flow.operadTools);
485
- const storeSecrets = await secretValuesOf(ctx.secrets);
486
- const allowAlways = personStarted(ctx.trigger);
487
- if (allowAlways && isRecord(rawAskAnswer) && rawAskAnswer["choice"] === ALLOW_ALWAYS) {
488
- const entry = alwaysAllowFromGrant(ctx.access, cwd);
489
- if (entry !== undefined) {
490
- try {
491
- await appendAlwaysAllow(ctx.home, entry);
492
- } catch (error) {
493
- await ctx.logger.write(
494
- `allow_always could not be written to the user access file: ${String(error)}; this call runs once`,
458
+ let authPath = "";
459
+ let modelsPath = "";
460
+ let bashTimeoutSecs: number | undefined;
461
+ let piCommand: string | undefined;
462
+ let operadTools: ReturnType<typeof operadToolsOf>;
463
+ let skills: readonly string[] = [];
464
+ let ownSettings: unknown;
465
+ let retry: unknown;
466
+ let images: ReturnType<typeof imageInputsOf> = [];
467
+
468
+ const step = await readAgentStep(ctx, params, {
469
+ at,
470
+ harness: "pi",
471
+ flags: STEP_FLAGS,
472
+ defaultWallTimeSecs: DEFAULT_WALL_TIME_SECS,
473
+ defaultStallSecs: DEFAULT_STALL_SECS,
474
+ maxWallTimeSecs: MAX_WALL_TIME_SECS,
475
+ levelSetting: "thinkingLevel",
476
+ now,
477
+ async beforeDirectory(read) {
478
+ bashTimeoutSecs = optionalPositive(
479
+ ctx.settings.bashTimeoutSecs,
480
+ `${at}: settings.bashTimeoutSecs`,
481
+ true,
482
+ );
483
+ authPath = expandHome(
484
+ text(ctx.settings.authPath ?? DEFAULT_AUTH_PATH, `${at}: settings.authPath`),
485
+ );
486
+ modelsPath = expandHome(
487
+ text(ctx.settings.modelsPath ?? DEFAULT_MODELS_PATH, `${at}: settings.modelsPath`),
488
+ );
489
+
490
+ piCommand = optionalText(ctx.settings.command, `${at}: settings.command`);
491
+ // A configured model pi does not list is reported once, here.
492
+ const configured = stringList(ctx.settings.models);
493
+ if (configured !== undefined && read.model !== undefined && configured.includes(read.model)) {
494
+ const listed = piModelList(
495
+ listOptions(
496
+ piCommandFor(ctx.settings, ctx.home),
497
+ {
498
+ home: ctx.home,
499
+ log: (message) => {
500
+ void ctx.logger.write(message);
501
+ },
502
+ },
503
+ typeof ctx.settings.modelsPath === "string"
504
+ ? ctx.settings.modelsPath
505
+ : DEFAULT_MODELS_PATH,
506
+ ),
495
507
  );
508
+ if (listed.length > 0 && !listed.includes(read.model)) {
509
+ await ctx.logger.write(
510
+ `pi/agent: the model "${read.model}" is in settings.models but pi does not list it`,
511
+ );
512
+ }
513
+ }
514
+ },
515
+ async afterDirectory(read) {
516
+ const agentDir = join(ctx.home, "harness", "pi");
517
+ const sessionDir = join(agentDir, "sessions");
518
+ await mkdir(sessionDir, { recursive: true });
519
+
520
+ operadTools = operadToolsOf(read.input.operadTools ?? read.flow.operadTools);
521
+ skills = stringListParam(
522
+ read.input.skills === undefined ? read.flow.skills : read.input.skills,
523
+ `${at}: params.skills`,
524
+ );
525
+ ownSettings = read.input.useOwnSettings ?? read.flow.useOwnSettings;
526
+ if (ownSettings !== undefined && typeof ownSettings !== "boolean") {
527
+ throw new Error(`${at}: params.useOwnSettings: must be a boolean`);
496
528
  }
497
- }
498
- }
499
- let runAccess = accessWithAlwaysAllow(ctx.access, [], false);
500
- if (allowAlways) {
501
- const user = await readAlwaysAllow(ctx.home);
502
- if (user.problem !== undefined) await ctx.logger.write(user.problem);
503
- runAccess = accessWithAlwaysAllow(ctx.access, user.entries, true);
504
- }
529
+ retry = read.input.retry ?? read.flow.retry;
530
+ if (retry !== undefined && typeof retry !== "boolean") {
531
+ throw new Error(`${at}: params.retry: must be a boolean`);
532
+ }
533
+ images = imageInputsOf(read.input.images ?? read.flow.images);
534
+ },
535
+ });
536
+ if ("refused" in step) return step.refused;
537
+
538
+ const { values, access } = step;
539
+ const { resumeSession, wallTimeSecs, stallSecs, level: thinkingLevel } = values;
540
+ // With the own-settings switch off the child's settings are in memory
541
+ // and hold no default model (D3), so pi's own default is resolved here
542
+ // and named to it (D4). A child told no model selects none.
543
+ const model = values.model ?? piDefaultModel(readPiSettings(piSettingsPath, readFile));
544
+ const runValues = model === undefined ? values : { ...values, model };
545
+ const agentDir = join(ctx.home, "harness", "pi");
546
+ const sessionDir = join(agentDir, "sessions");
547
+
505
548
  const stdin: Record<string, unknown> = {
506
- prompt: promptWithNote,
507
- cwd,
549
+ prompt: values.promptWithNote,
550
+ cwd: values.cwd,
508
551
  authPath,
509
552
  modelsPath,
510
553
  agentDir,
511
554
  sessionDir,
555
+ piHome: ctx.home,
512
556
  ...(piCommand === undefined ? {} : { piCommand }),
513
557
  ...(resumeSession === undefined ? {} : { resumeSession }),
514
558
  ...(model === undefined ? {} : { model }),
515
559
  ...(thinkingLevel === undefined ? {} : { thinkingLevel }),
516
560
  ...(bashTimeoutSecs === undefined ? {} : { bashTimeoutSecs }),
517
561
  ...(operadTools === undefined ? {} : { operadTools }),
518
- ...(imageInputsOf(input.images ?? flow.images).length === 0
519
- ? {}
520
- : { images: imageInputsOf(input.images ?? flow.images) }),
521
- ...(runAccess === undefined ? {} : { access: runAccess }),
522
- ...(storeSecrets.length === 0 ? {} : { secretValues: storeSecrets }),
562
+ ...(images.length === 0 ? {} : { images }),
563
+ ...(skills.length === 0 ? {} : { skills }),
564
+ ...(ownSettings === true ? { useOwnSettings: true } : {}),
565
+ ...(retry === true ? { retry: true } : {}),
566
+ ...(access.runAccess === undefined ? {} : { access: access.runAccess }),
567
+ ...(access.secrets.length === 0 ? {} : { secretValues: access.secrets }),
523
568
  };
524
569
 
525
- const inbox = inboxOf(params);
526
- const started = Date.now();
527
- const jsonl = new JsonlLog(ctx.logger, clock);
528
- let result: WorkerResult | undefined;
529
- // Ends the program when a question about a call runs out of grace.
530
- const stopper = new AbortController();
531
- const asker = createCallAsker({
532
- ask: (request) => ctx.ask(request),
533
- onStop: () => stopper.abort(),
534
- secrets: storeSecrets,
535
- ...(allowAlways ? { alwaysAllow: { home: ctx.home, cwd } } : {}),
536
- onLog: (message) => {
537
- void ctx.logger.write(message);
538
- },
539
- });
540
-
541
- const outcome = await runAgent({
570
+ const keep: KeptRunOptions | undefined =
571
+ values.input.keepWorker === true && ctx.object !== undefined
572
+ ? {
573
+ home: ctx.home,
574
+ name: "pi",
575
+ scope: `${ctx.object.type}:${ctx.object.id}`,
576
+ key: keepKeyOf({
577
+ ...stdin,
578
+ mcpServers: values.input.mcpServers ?? values.flow.mcpServers,
579
+ }),
580
+ ...(options.keepMs === undefined ? {} : { timeoutMs: options.keepMs }),
581
+ ...(options.keptFirstLineMs === undefined ? {} : { firstLineMs: options.keptFirstLineMs }),
582
+ ...(options.maxKept === undefined ? {} : { max: options.maxKept }),
583
+ }
584
+ : undefined;
585
+
586
+ return await runWorkerStep({
587
+ values: runValues,
588
+ access,
542
589
  command,
543
590
  args: commandArgs,
544
- cwd,
545
- stdin: JSON.stringify(stdin),
546
- // The program may ask to use a one-time permission; it needs a reply.
547
- interactive: hasGrants(ctx.access) || canAsk(ctx.access) || inbox !== undefined,
548
- inbox,
549
- wallMs: wallTimeSecs * 1000,
550
- stallMs: stallSecs * 1000,
551
- signal: AbortSignal.any([ctx.signal, stopper.signal]),
591
+ stdin,
592
+ keep,
552
593
  clock,
553
- toolEvent: (line) => piToolEvent(line) ?? askToolEvent(line),
554
- async onLine(line, reply) {
555
- await answerGrant(line, (waitId) => ctx.useGrant(waitId), reply);
556
- await asker.handle(line, reply);
557
- const writing = jsonl.push(line);
558
- deliverLine(ctx.receiver, line, storeSecrets);
559
- const parsed = parseResult<WorkerResult>(line);
560
- if (parsed !== undefined) result = parsed;
561
- return writing;
562
- },
594
+ now,
595
+ toolEvent: toolExecutionEvent,
563
596
  });
564
- await jsonl.end();
565
-
566
- // The grace passed with a question open: the program was ended on
567
- // purpose. The kernel turns this into the result `waiting`, and the
568
- // answer comes back with the session and a one-time grant.
569
- const unanswered = asker.stopped();
570
- if (unanswered !== undefined && !ctx.signal.aborted) throw unanswered.error;
571
-
572
- return resultFor(
573
- { harness: "pi", model: model ?? null },
574
- outcome,
575
- result,
576
- ctx.logger.path,
577
- Date.now() - started,
578
- { wallTimeSecs, stallSecs },
579
- command,
580
- );
581
597
  },
582
598
  },
583
599
  ],
584
600
  flows: [promptFlow],
585
601
  async check(ctx) {
586
602
  const piCommand = optionalText(ctx.settings.command, "pi: settings.command");
587
- // The user's own pi: found and version-checked, not loaded.
588
- const pi = findPi(piCommand ?? DEFAULT_PI_COMMAND);
589
- if (options.command === undefined && !existsSync(process.execPath)) {
590
- throw new Error("bun was not found");
591
- }
592
- if (options.args === undefined && !existsSync(WORKER_PATH)) {
593
- throw new Error(`the worker program is missing: ${WORKER_PATH}`);
594
- }
603
+ // The user's own pi, or the one operad installed in the home: found and
604
+ // version-checked, not loaded.
605
+ const pi = findPi(piCommand ?? DEFAULT_PI_COMMAND, { home: ctx.home });
606
+ assertWorkerAvailable({ command: options.command, args: options.args, workerPath: WORKER_PATH });
595
607
  return `pi ${pi.version} at ${pi.dir} (floor ${PI_FLOOR}); the worker program is available`;
596
608
  },
597
609
  });