@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.
- package/LICENSE +21 -0
- package/README.md +12 -2
- package/package.json +27 -4
- package/src/index.ts +600 -0
- package/src/pi-install.ts +219 -0
- package/src/protocol.ts +195 -0
- package/src/worker.ts +863 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Yinghai Zhao
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,13 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @operad-io/harness-pi
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**The pi harness.** Runs a prompt with the pi coding agent library you installed.
|
|
4
|
+
|
|
5
|
+
This package is part of [operad](https://github.com/operad-io/operad). Most people install only [`@operad-io/cli`](https://www.npmjs.com/package/@operad-io/cli).
|
|
6
|
+
|
|
7
|
+
## Documentation
|
|
8
|
+
|
|
9
|
+
- User guide: [docs/user/dev.md](https://github.com/operad-io/operad/blob/main/docs/user/dev.md)
|
|
10
|
+
- Website: <https://operad.io>
|
|
11
|
+
- Developer reference: `REFERENCE.md` in this directory
|
|
12
|
+
|
|
13
|
+
MIT licensed.
|
package/package.json
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@operad-io/harness-pi",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"exports": {
|
|
6
|
+
".": "./src/index.ts"
|
|
7
|
+
},
|
|
8
|
+
"dependencies": {
|
|
9
|
+
"@operad-io/access-match": "0.1.0",
|
|
10
|
+
"@operad-io/engine": "0.1.0",
|
|
11
|
+
"@operad-io/harness-process": "0.1.0",
|
|
12
|
+
"@operad-io/mcp": "0.1.0"
|
|
13
|
+
},
|
|
14
|
+
"devDependencies": {
|
|
15
|
+
"@earendil-works/pi-coding-agent": "1.5.0"
|
|
16
|
+
},
|
|
17
|
+
"description": "operad: the pi harness, a client of the pi coding agent library",
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/operad-io/operad.git",
|
|
21
|
+
"directory": "packages/harness/pi"
|
|
22
|
+
},
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"files": [
|
|
25
|
+
"src",
|
|
26
|
+
"README.md",
|
|
27
|
+
"LICENSE"
|
|
28
|
+
]
|
|
29
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,600 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The pi harness, hub side: one `agent` step that starts the child program
|
|
3
|
+
* `worker.ts` under Bun, writes one JSON object to its stdin and reads the last
|
|
4
|
+
* `result` line of its stdout, plus the `pi:prompt` flow. The step has
|
|
5
|
+
* the params, result names and facts of `radian/agent`, so a flow
|
|
6
|
+
* changes harness by changing `use`. pi's library is imported only by the child
|
|
7
|
+
* program, never by the hub.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import pkg from "../package.json" with { type: "json" };
|
|
11
|
+
import { secretValuesOf } from "@operad-io/access-match";
|
|
12
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
13
|
+
import { mkdir } from "node:fs/promises";
|
|
14
|
+
import { homedir } from "node:os";
|
|
15
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
16
|
+
import { fileURLToPath } from "node:url";
|
|
17
|
+
import {
|
|
18
|
+
isRecord,
|
|
19
|
+
paramsObject,
|
|
20
|
+
defineFlow,
|
|
21
|
+
definePlugin,
|
|
22
|
+
type PluginStepResult,
|
|
23
|
+
type StepContext,
|
|
24
|
+
} from "@operad-io/engine";
|
|
25
|
+
import {
|
|
26
|
+
ALLOW_ALWAYS,
|
|
27
|
+
accessWithAlwaysAllow,
|
|
28
|
+
alwaysAllowFromGrant,
|
|
29
|
+
appendAlwaysAllow,
|
|
30
|
+
answerGrant,
|
|
31
|
+
askToolEvent,
|
|
32
|
+
canAsk,
|
|
33
|
+
createCallAsker,
|
|
34
|
+
CONCURRENCY_SETTING,
|
|
35
|
+
eventNote,
|
|
36
|
+
askNote,
|
|
37
|
+
flagValue,
|
|
38
|
+
hasGrants,
|
|
39
|
+
inboxOf,
|
|
40
|
+
imageInputsOf,
|
|
41
|
+
operadToolsOf,
|
|
42
|
+
JsonlLog,
|
|
43
|
+
deliverLine,
|
|
44
|
+
modelLimit,
|
|
45
|
+
standardUsage,
|
|
46
|
+
type UsageSource,
|
|
47
|
+
directoryError,
|
|
48
|
+
optionalText,
|
|
49
|
+
parseResult,
|
|
50
|
+
parseStepFlags,
|
|
51
|
+
personStarted,
|
|
52
|
+
readAlwaysAllow,
|
|
53
|
+
resultFor,
|
|
54
|
+
secs,
|
|
55
|
+
stringListParam,
|
|
56
|
+
text,
|
|
57
|
+
type StepFlagSpec,
|
|
58
|
+
runAgent,
|
|
59
|
+
systemClock,
|
|
60
|
+
type Clock,
|
|
61
|
+
type ToolEvent,
|
|
62
|
+
} from "@operad-io/harness-process";
|
|
63
|
+
import { DEFAULT_PI_COMMAND, findPi, PI_FLOOR } from "./pi-install.ts";
|
|
64
|
+
import {
|
|
65
|
+
DEFAULT_BASH_TIMEOUT_SECS,
|
|
66
|
+
THINKING_LEVELS,
|
|
67
|
+
type WorkerResult,
|
|
68
|
+
type WorkerThinkingLevel,
|
|
69
|
+
} from "./protocol.ts";
|
|
70
|
+
|
|
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;
|
|
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;
|
|
79
|
+
|
|
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;
|
|
82
|
+
|
|
83
|
+
export const DEFAULT_AUTH_PATH = "~/.pi/agent/auth.json";
|
|
84
|
+
export const DEFAULT_MODELS_PATH = "~/.pi/agent/models.json";
|
|
85
|
+
|
|
86
|
+
const WORKER_PATH = fileURLToPath(new URL("./worker.ts", import.meta.url));
|
|
87
|
+
|
|
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
|
+
/** What a test injects: the clock and the program the step starts. */
|
|
107
|
+
export interface PiHarnessOptions {
|
|
108
|
+
readonly clock?: Clock | undefined;
|
|
109
|
+
/** The executable; defaults to the running Bun. */
|
|
110
|
+
readonly command?: string | undefined;
|
|
111
|
+
/** The arguments before the worker input; defaults to `worker.ts`. */
|
|
112
|
+
readonly args?: readonly string[] | undefined;
|
|
113
|
+
/** The time now in milliseconds; defaults to `Date.now`. It ages the cached catalogue. */
|
|
114
|
+
readonly now?: (() => number) | undefined;
|
|
115
|
+
/** How long `pi --list-models` may take; defaults to `PI_LIST_TIMEOUT_MS`. */
|
|
116
|
+
readonly listTimeoutMs?: number | undefined;
|
|
117
|
+
/** pi's settings file, where its default model is; defaults to `~/.pi/agent/settings.json`. */
|
|
118
|
+
readonly piSettingsPath?: string | undefined;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** How long `pi --list-models` may take before pi counts as not answering. */
|
|
122
|
+
export const PI_LIST_TIMEOUT_MS = 10_000;
|
|
123
|
+
|
|
124
|
+
/** How long a catalogue pi gave (or failed to give) is kept. */
|
|
125
|
+
export const PI_LIST_CACHE_MS = 60_000;
|
|
126
|
+
|
|
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;
|
|
147
|
+
}
|
|
148
|
+
|
|
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;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
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;
|
|
168
|
+
|
|
169
|
+
/** The settings a config.json section may set for this plugin. */
|
|
170
|
+
const PLUGIN_SETTINGS = {
|
|
171
|
+
type: "object" as const,
|
|
172
|
+
properties: {
|
|
173
|
+
model: {
|
|
174
|
+
type: "string" as const,
|
|
175
|
+
minLength: 3,
|
|
176
|
+
description: "The model as provider/id; unset uses pi's default model.",
|
|
177
|
+
},
|
|
178
|
+
models: {
|
|
179
|
+
type: "array" as const,
|
|
180
|
+
items: { type: "string" as const, minLength: 3 },
|
|
181
|
+
description:
|
|
182
|
+
"The models a chat may pick, as provider/id; unset offers every model pi lists.",
|
|
183
|
+
},
|
|
184
|
+
thinkingLevel: {
|
|
185
|
+
type: "string" as const,
|
|
186
|
+
enum: THINKING_LEVELS,
|
|
187
|
+
description: "The reasoning level; unset uses pi's default.",
|
|
188
|
+
},
|
|
189
|
+
command: {
|
|
190
|
+
type: "string" as const,
|
|
191
|
+
minLength: 1,
|
|
192
|
+
default: DEFAULT_PI_COMMAND,
|
|
193
|
+
description:
|
|
194
|
+
"The pi command: a name on PATH or a path. It must lead into an installed @earendil-works/pi-coding-agent; point it at the package's bin when `pi` is a wrapper script.",
|
|
195
|
+
},
|
|
196
|
+
authPath: {
|
|
197
|
+
type: "string" as const,
|
|
198
|
+
minLength: 1,
|
|
199
|
+
default: DEFAULT_AUTH_PATH,
|
|
200
|
+
description: "pi's credentials file.",
|
|
201
|
+
},
|
|
202
|
+
modelsPath: {
|
|
203
|
+
type: "string" as const,
|
|
204
|
+
minLength: 1,
|
|
205
|
+
default: DEFAULT_MODELS_PATH,
|
|
206
|
+
description: "pi's custom models file.",
|
|
207
|
+
},
|
|
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
|
+
},
|
|
221
|
+
bashTimeoutSecs: {
|
|
222
|
+
type: "integer" as const,
|
|
223
|
+
minimum: 1,
|
|
224
|
+
default: DEFAULT_BASH_TIMEOUT_SECS,
|
|
225
|
+
description:
|
|
226
|
+
"The longest one bash call may run, in seconds. A longer call is stopped and the model gets an error; the run goes on.",
|
|
227
|
+
},
|
|
228
|
+
concurrency: CONCURRENCY_SETTING,
|
|
229
|
+
},
|
|
230
|
+
additionalProperties: false as const,
|
|
231
|
+
};
|
|
232
|
+
|
|
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
|
+
/** The spelling of this harness's step `args`; the parsing is harness-process's. */
|
|
242
|
+
const STEP_FLAGS: StepFlagSpec<WorkerThinkingLevel> = {
|
|
243
|
+
levelFlag: "--thinking",
|
|
244
|
+
levels: THINKING_LEVELS,
|
|
245
|
+
modelHint: "<provider/id>",
|
|
246
|
+
dashValues: true,
|
|
247
|
+
modelProblem: (value) =>
|
|
248
|
+
/^[^/\s]+\/\S+$/.test(value) ? undefined : `args: "--model ${value}": the value must be provider/id`,
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
/** Expands a leading `~` to the user's home directory. */
|
|
252
|
+
function expandHome(path: string): string {
|
|
253
|
+
if (path === "~") return homedir();
|
|
254
|
+
if (path.startsWith("~/")) return join(homedir(), path.slice(2));
|
|
255
|
+
return isAbsolute(path) ? path : resolve(path);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Creates the pi harness plugin. Its worker is `worker.ts` under the running
|
|
260
|
+
* Bun; a test replaces the program with a fake that prints fixed lines.
|
|
261
|
+
*/
|
|
262
|
+
export function createPiHarnessPlugin(options: PiHarnessOptions = {}) {
|
|
263
|
+
const clock = options.clock ?? systemClock;
|
|
264
|
+
const command = options.command ?? process.execPath;
|
|
265
|
+
const commandArgs = options.args ?? [WORKER_PATH];
|
|
266
|
+
const now = options.now ?? Date.now;
|
|
267
|
+
const listTimeoutMs = options.listTimeoutMs ?? PI_LIST_TIMEOUT_MS;
|
|
268
|
+
const piSettingsPath =
|
|
269
|
+
options.piSettingsPath ?? join(homedir(), ".pi", "agent", "settings.json");
|
|
270
|
+
|
|
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;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function stringList(value: unknown): readonly string[] | undefined {
|
|
297
|
+
return Array.isArray(value) && value.every((item) => typeof item === "string")
|
|
298
|
+
? (value as readonly string[])
|
|
299
|
+
: undefined;
|
|
300
|
+
}
|
|
301
|
+
|
|
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);
|
|
307
|
+
const wanted =
|
|
308
|
+
typeof settings.model === "string" && settings.model !== ""
|
|
309
|
+
? settings.model
|
|
310
|
+
: piDefaultModel(piSettingsPath);
|
|
311
|
+
return { list, default: wanted !== undefined && list.includes(wanted) ? wanted : null };
|
|
312
|
+
}
|
|
313
|
+
|
|
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
|
+
});
|
|
348
|
+
|
|
349
|
+
return definePlugin({
|
|
350
|
+
name: "pi",
|
|
351
|
+
kind: "harness",
|
|
352
|
+
version: pkg.version,
|
|
353
|
+
models: piModels,
|
|
354
|
+
efforts: PI_EFFORTS,
|
|
355
|
+
settings: PLUGIN_SETTINGS,
|
|
356
|
+
steps: [
|
|
357
|
+
{
|
|
358
|
+
name: "agent",
|
|
359
|
+
// A question's answer comes back as `resumeSession` and `askAnswer`.
|
|
360
|
+
resumable: true,
|
|
361
|
+
// `waiting`: a question about a call was not answered within the grace.
|
|
362
|
+
results: ["done", "failed", "interrupted", "waiting"],
|
|
363
|
+
// The deny and ask fields are applied in the worker's tool_call hook.
|
|
364
|
+
enforces: ["denyPaths", "denyCommands", "askCommands", "askPaths", "readPaths", "alwaysAllow"],
|
|
365
|
+
timeoutSecs: STEP_TIMEOUT_SECS,
|
|
366
|
+
// The model the step uses: its `--model` argument, else the setting.
|
|
367
|
+
limit: modelLimit("pi", (params, settings) => {
|
|
368
|
+
const fromArgs = isRecord(params)
|
|
369
|
+
? flagValue(params.args, "--model")
|
|
370
|
+
: undefined;
|
|
371
|
+
const model = fromArgs ?? settings.model;
|
|
372
|
+
return typeof model === "string" && model.length > 0 ? model : undefined;
|
|
373
|
+
}),
|
|
374
|
+
async run(ctx: StepContext, params: unknown): Promise<PluginStepResult> {
|
|
375
|
+
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`,
|
|
495
|
+
);
|
|
496
|
+
}
|
|
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
|
+
}
|
|
505
|
+
const stdin: Record<string, unknown> = {
|
|
506
|
+
prompt: promptWithNote,
|
|
507
|
+
cwd,
|
|
508
|
+
authPath,
|
|
509
|
+
modelsPath,
|
|
510
|
+
agentDir,
|
|
511
|
+
sessionDir,
|
|
512
|
+
...(piCommand === undefined ? {} : { piCommand }),
|
|
513
|
+
...(resumeSession === undefined ? {} : { resumeSession }),
|
|
514
|
+
...(model === undefined ? {} : { model }),
|
|
515
|
+
...(thinkingLevel === undefined ? {} : { thinkingLevel }),
|
|
516
|
+
...(bashTimeoutSecs === undefined ? {} : { bashTimeoutSecs }),
|
|
517
|
+
...(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 }),
|
|
523
|
+
};
|
|
524
|
+
|
|
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({
|
|
542
|
+
command,
|
|
543
|
+
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]),
|
|
552
|
+
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
|
+
},
|
|
563
|
+
});
|
|
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
|
+
},
|
|
582
|
+
},
|
|
583
|
+
],
|
|
584
|
+
flows: [promptFlow],
|
|
585
|
+
async check(ctx) {
|
|
586
|
+
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
|
+
}
|
|
595
|
+
return `pi ${pi.version} at ${pi.dir} (floor ${PI_FLOOR}); the worker program is available`;
|
|
596
|
+
},
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
export default createPiHarnessPlugin();
|