@operad-io/harness-pi 0.0.0-stage → 0.0.1
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 +282 -2
- package/package.json +27 -4
- package/src/index.ts +599 -0
- package/src/pi-install.ts +219 -0
- package/src/protocol.ts +195 -0
- package/src/worker.ts +863 -0
package/src/worker.ts
ADDED
|
@@ -0,0 +1,863 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The pi child program (docs/backlog/operad-harness-pi.md decisions 2, 3, 5, 6).
|
|
3
|
+
*
|
|
4
|
+
* Reads one JSON object from stdin, runs one prompt in pi and writes one JSON
|
|
5
|
+
* object per line to stdout, the last a Result. `README.md` holds the tables.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { existsSync, mkdirSync } from "node:fs";
|
|
9
|
+
import {
|
|
10
|
+
findGrant,
|
|
11
|
+
firstErrorLine,
|
|
12
|
+
REFUSED_IN_LOG,
|
|
13
|
+
match,
|
|
14
|
+
messageSummary,
|
|
15
|
+
readProfile,
|
|
16
|
+
summarizeCall,
|
|
17
|
+
type AccessProfile,
|
|
18
|
+
} from "@operad-io/access-match";
|
|
19
|
+
import type {
|
|
20
|
+
AgentSessionEvent,
|
|
21
|
+
ExtensionFactory,
|
|
22
|
+
ModelRuntime,
|
|
23
|
+
} from "@earendil-works/pi-coding-agent";
|
|
24
|
+
import { openMcpTools, type McpTools } from "@operad-io/mcp";
|
|
25
|
+
import {
|
|
26
|
+
maskSecrets,
|
|
27
|
+
messageText,
|
|
28
|
+
readImage,
|
|
29
|
+
toolOutputLines,
|
|
30
|
+
type CallAnswer,
|
|
31
|
+
} from "@operad-io/harness-process";
|
|
32
|
+
import { findPi, loadPi } from "./pi-install.ts";
|
|
33
|
+
import {
|
|
34
|
+
DEFAULT_BASH_TIMEOUT_SECS,
|
|
35
|
+
parseInput,
|
|
36
|
+
type FailureReason,
|
|
37
|
+
type WorkerInput,
|
|
38
|
+
type WorkerLine,
|
|
39
|
+
type WorkerResult,
|
|
40
|
+
type WorkerUsage,
|
|
41
|
+
} from "./protocol.ts";
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The timeout, in seconds, a bash call runs under. pi's bash tool has no default
|
|
45
|
+
* timeout and takes the model's own `timeout`; a call without one, or with a
|
|
46
|
+
* longer one, gets the limit. Anything else (a bad value) is left for pi to refuse.
|
|
47
|
+
*/
|
|
48
|
+
export function boundedTimeout(requested: unknown, limitSecs: number): number | undefined {
|
|
49
|
+
if (requested === undefined || requested === null) return limitSecs;
|
|
50
|
+
if (typeof requested === "number" && Number.isFinite(requested) && requested > limitSecs) return limitSecs;
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export const EXIT_FAILED = 1;
|
|
55
|
+
export const EXIT_INVALID_INPUT = 2;
|
|
56
|
+
export const EXIT_CANCELLED = 143;
|
|
57
|
+
|
|
58
|
+
/** Where the program writes. Lines are written whole, in order. */
|
|
59
|
+
export interface WorkerIo {
|
|
60
|
+
line(line: WorkerLine): void;
|
|
61
|
+
/** Free text for humans; never parsed. */
|
|
62
|
+
log(text: string): void;
|
|
63
|
+
/**
|
|
64
|
+
* Asks the host to use up a one-time permission. True when it did and the
|
|
65
|
+
* call may run. Absent when the host cannot answer; no grant then applies.
|
|
66
|
+
*/
|
|
67
|
+
useGrant?(waitId: string): Promise<boolean>;
|
|
68
|
+
/**
|
|
69
|
+
* Asks the host to ask a person whether one call may run, and resolves with
|
|
70
|
+
* the answer. Absent when the host cannot answer; a call that must ask is then
|
|
71
|
+
* refused.
|
|
72
|
+
*/
|
|
73
|
+
ask?(call: {
|
|
74
|
+
readonly kind: "command" | "path";
|
|
75
|
+
readonly value: string;
|
|
76
|
+
readonly tool?: string;
|
|
77
|
+
readonly shown: string;
|
|
78
|
+
readonly session: string | null;
|
|
79
|
+
}): Promise<CallAnswer>;
|
|
80
|
+
/**
|
|
81
|
+
* Hands each message the host sends mid-run to `handler`, those that came
|
|
82
|
+
* before the call first. Absent when the host cannot send any.
|
|
83
|
+
*/
|
|
84
|
+
onMessage?(handler: (text: string) => void): void;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface WorkerHooks {
|
|
88
|
+
/** Registers extra model providers; the tests use it for the fake model. */
|
|
89
|
+
registerProviders?(runtime: ModelRuntime): void;
|
|
90
|
+
/** The clock for tool call times, in epoch milliseconds; the tests inject one. */
|
|
91
|
+
now?: () => number;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Where the program talks to the world; the process entry points them at stdout and stderr. */
|
|
95
|
+
export interface WorkerPorts {
|
|
96
|
+
write(text: string): void;
|
|
97
|
+
log(text: string): void;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The text of an assistant message, thinking and tool calls left out. */
|
|
101
|
+
function textOf(content: unknown, join = " "): string {
|
|
102
|
+
if (typeof content === "string") return content;
|
|
103
|
+
if (!Array.isArray(content)) return "";
|
|
104
|
+
return content
|
|
105
|
+
.map((block: unknown) =>
|
|
106
|
+
typeof block === "object" && block !== null && Reflect.get(block, "type") === "text"
|
|
107
|
+
? String(Reflect.get(block, "text") ?? "")
|
|
108
|
+
: "",
|
|
109
|
+
)
|
|
110
|
+
.join(join);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function finite(value: unknown): number | null {
|
|
114
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The price of one message in USD, or null when pi gave none. */
|
|
118
|
+
function priceOf(usage: unknown): number | null {
|
|
119
|
+
if (typeof usage !== "object" || usage === null) return null;
|
|
120
|
+
const cost: unknown = Reflect.get(usage, "cost");
|
|
121
|
+
if (typeof cost !== "object" || cost === null) return null;
|
|
122
|
+
return finite(Reflect.get(cost, "total"));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
class Tally {
|
|
126
|
+
readonly usage: WorkerUsage = {};
|
|
127
|
+
#total = 0;
|
|
128
|
+
#priced = 0;
|
|
129
|
+
#unpriced = 0;
|
|
130
|
+
lastStop: string | undefined;
|
|
131
|
+
lastError: string | undefined;
|
|
132
|
+
|
|
133
|
+
add(message: Extract<AgentSessionEvent, { type: "message_end" }>["message"]): WorkerLine | undefined {
|
|
134
|
+
if (message.role !== "assistant") return undefined;
|
|
135
|
+
const usage = message.usage;
|
|
136
|
+
const counts = {
|
|
137
|
+
input: finite(usage.input) ?? 0,
|
|
138
|
+
output: finite(usage.output) ?? 0,
|
|
139
|
+
cache_read: finite(usage.cacheRead) ?? 0,
|
|
140
|
+
cache_write: finite(usage.cacheWrite) ?? 0,
|
|
141
|
+
};
|
|
142
|
+
for (const key of ["input", "output", "cache_read", "cache_write"] as const) {
|
|
143
|
+
this.usage[key] = (this.usage[key] ?? 0) + counts[key];
|
|
144
|
+
}
|
|
145
|
+
const price = priceOf(usage);
|
|
146
|
+
if (price === null) this.#unpriced += 1;
|
|
147
|
+
else {
|
|
148
|
+
this.#priced += 1;
|
|
149
|
+
this.#total += price;
|
|
150
|
+
}
|
|
151
|
+
this.lastStop = message.stopReason;
|
|
152
|
+
this.lastError = message.stopReason === "error" ? (message.errorMessage ?? "the model failed") : undefined;
|
|
153
|
+
const said = messageSummary(textOf(message.content));
|
|
154
|
+
return {
|
|
155
|
+
type: "message_end",
|
|
156
|
+
role: "assistant",
|
|
157
|
+
...(said === undefined ? {} : { text: said }),
|
|
158
|
+
stopReason: message.stopReason,
|
|
159
|
+
usage: counts,
|
|
160
|
+
cost: price === null ? null : { total: price },
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* The price of the messages that had one; `incomplete` when some did not.
|
|
166
|
+
* Null when no message had a price.
|
|
167
|
+
*/
|
|
168
|
+
get cost(): { micros: number; incomplete?: true } | null {
|
|
169
|
+
if (this.#priced === 0) return null;
|
|
170
|
+
const micros = Math.round(this.#total * 1e6);
|
|
171
|
+
return this.#unpriced > 0 ? { micros, incomplete: true } : { micros };
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** How often one stream writes an increment line at most, in milliseconds. */
|
|
176
|
+
const FLUSH_MS = 100;
|
|
177
|
+
|
|
178
|
+
/** The spellings `maskSecrets` masks for one value: the value and, if it differs, its JSON text. */
|
|
179
|
+
function spellingsOf(secret: string): readonly string[] {
|
|
180
|
+
if (secret.length === 0) return [];
|
|
181
|
+
const escaped = JSON.stringify(secret).slice(1, -1);
|
|
182
|
+
return escaped === secret ? [secret] : [secret, escaped];
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Splits an increment so that no line ends inside a secret: the longest suffix
|
|
187
|
+
* of `text` that is a proper prefix of a secret value is held back and joined
|
|
188
|
+
* to the next increment, where the completed secret is masked. A secret that
|
|
189
|
+
* is wholly in the emitted part is masked there. Both the value as written and
|
|
190
|
+
* its JSON-escaped spelling count, as `maskSecrets` masks both.
|
|
191
|
+
*/
|
|
192
|
+
function splitSecretPrefix(
|
|
193
|
+
text: string,
|
|
194
|
+
secrets: readonly string[],
|
|
195
|
+
): { readonly emit: string; readonly held: string } {
|
|
196
|
+
let held = 0;
|
|
197
|
+
for (const secret of secrets.flatMap(spellingsOf)) {
|
|
198
|
+
const longest = Math.min(secret.length - 1, text.length);
|
|
199
|
+
for (let length = longest; length > held; length -= 1) {
|
|
200
|
+
if (text.endsWith(secret.slice(0, length))) {
|
|
201
|
+
held = length;
|
|
202
|
+
break;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (held === 0) return { emit: text, held: "" };
|
|
207
|
+
return { emit: text.slice(0, text.length - held), held: text.slice(text.length - held) };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Assistant text and thinking as they stream. A line carries the new text
|
|
212
|
+
* only, and each stream writes at most one per `FLUSH_MS`: a message that
|
|
213
|
+
* arrives faster is grouped. The tail that is still buffered when a block or a
|
|
214
|
+
* message ends is left to the full line that follows (`text_end`,
|
|
215
|
+
* `thinking_end`), so no increment goes out closer than `FLUSH_MS` to the one
|
|
216
|
+
* before it. Secret values are masked in every line.
|
|
217
|
+
*/
|
|
218
|
+
class Increments {
|
|
219
|
+
#text = "";
|
|
220
|
+
#thinking = "";
|
|
221
|
+
#textAt: number | undefined;
|
|
222
|
+
#thinkingAt: number | undefined;
|
|
223
|
+
|
|
224
|
+
constructor(
|
|
225
|
+
private readonly io: WorkerIo,
|
|
226
|
+
private readonly now: () => number,
|
|
227
|
+
private readonly secrets: readonly string[],
|
|
228
|
+
) {}
|
|
229
|
+
|
|
230
|
+
text(delta: string): void {
|
|
231
|
+
if (delta.length === 0) return;
|
|
232
|
+
this.#text += delta;
|
|
233
|
+
const at = this.now();
|
|
234
|
+
if (this.#textAt === undefined || at - this.#textAt >= FLUSH_MS) this.#writeText(at);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
thinking(delta: string): void {
|
|
238
|
+
if (delta.length === 0) return;
|
|
239
|
+
this.#thinking += delta;
|
|
240
|
+
const at = this.now();
|
|
241
|
+
if (this.#thinkingAt === undefined || at - this.#thinkingAt >= FLUSH_MS) this.#writeThinking(at);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
#writeText(at: number): void {
|
|
245
|
+
const { emit, held } = splitSecretPrefix(this.#text, this.secrets);
|
|
246
|
+
if (emit.length > 0) {
|
|
247
|
+
this.io.line({ type: "text_delta", text: maskSecrets(emit, this.secrets) });
|
|
248
|
+
}
|
|
249
|
+
this.#text = held;
|
|
250
|
+
this.#textAt = at;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
#writeThinking(at: number): void {
|
|
254
|
+
const { emit, held } = splitSecretPrefix(this.#thinking, this.secrets);
|
|
255
|
+
if (emit.length > 0) {
|
|
256
|
+
this.io.line({ type: "thinking_delta", text: maskSecrets(emit, this.secrets) });
|
|
257
|
+
}
|
|
258
|
+
this.#thinking = held;
|
|
259
|
+
this.#thinkingAt = at;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** A thinking block finished: its full text follows the increments. */
|
|
263
|
+
endThinking(text: string): void {
|
|
264
|
+
this.#thinking = "";
|
|
265
|
+
this.#thinkingAt = undefined;
|
|
266
|
+
if (text.length > 0) this.io.line({ type: "thinking_end", text: maskSecrets(text, this.secrets) });
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** An assistant message finished: its full text follows the increments. */
|
|
270
|
+
endMessage(text: string): void {
|
|
271
|
+
if (text.length > 0) {
|
|
272
|
+
this.#text = "";
|
|
273
|
+
this.#textAt = undefined;
|
|
274
|
+
this.io.line({ type: "text_end", text: maskSecrets(text, this.secrets) });
|
|
275
|
+
} else if (this.#text.length > 0) {
|
|
276
|
+
this.#writeText(this.now());
|
|
277
|
+
}
|
|
278
|
+
// A thinking block that ended wrote its own full text; anything left is
|
|
279
|
+
// a block the run stopped in, and the increments are all it has.
|
|
280
|
+
if (this.#thinking.length > 0) this.#writeThinking(this.now());
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* The stream is ending and no later text can complete a held prefix: write
|
|
285
|
+
* it now, masked when it holds a whole secret. Every end path calls this
|
|
286
|
+
* before its Result, so a stopped reply keeps what it had reached.
|
|
287
|
+
*/
|
|
288
|
+
release(): void {
|
|
289
|
+
if (this.#text.length > 0) {
|
|
290
|
+
this.io.line({ type: "text_delta", text: maskSecrets(this.#text, this.secrets) });
|
|
291
|
+
this.#text = "";
|
|
292
|
+
this.#textAt = undefined;
|
|
293
|
+
}
|
|
294
|
+
if (this.#thinking.length > 0) {
|
|
295
|
+
this.io.line({ type: "thinking_delta", text: maskSecrets(this.#thinking, this.secrets) });
|
|
296
|
+
this.#thinking = "";
|
|
297
|
+
this.#thinkingAt = undefined;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function failure(reason: FailureReason, message: string): WorkerResult {
|
|
303
|
+
return { type: "result", result: "failed", sessionId: null, usage: {}, cost: null, finalMessage: null, reason, message };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Runs one prompt and returns the exit code. `cancel` is the SIGTERM signal;
|
|
308
|
+
* the Result is written before the code is returned.
|
|
309
|
+
*/
|
|
310
|
+
export async function runWorker(
|
|
311
|
+
input: WorkerInput,
|
|
312
|
+
io: WorkerIo,
|
|
313
|
+
cancel: AbortSignal,
|
|
314
|
+
hooks: WorkerHooks = {},
|
|
315
|
+
): Promise<number> {
|
|
316
|
+
if (input.resumeSession !== undefined && !existsSync(input.resumeSession)) {
|
|
317
|
+
io.line(failure("session_missing", `resumeSession does not exist: ${input.resumeSession}`));
|
|
318
|
+
return EXIT_FAILED;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// pi is the user's own install: found at start, never bundled.
|
|
322
|
+
let pi: Awaited<ReturnType<typeof loadPi>>;
|
|
323
|
+
try {
|
|
324
|
+
const install = findPi(input.piCommand);
|
|
325
|
+
io.log(`pi ${install.version} loaded from ${install.dir}`);
|
|
326
|
+
pi = await loadPi(install);
|
|
327
|
+
} catch (error) {
|
|
328
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
329
|
+
io.line(failure("model_error", message));
|
|
330
|
+
return EXIT_FAILED;
|
|
331
|
+
}
|
|
332
|
+
const { createAgentSession, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager } = pi;
|
|
333
|
+
|
|
334
|
+
mkdirSync(input.agentDir, { recursive: true });
|
|
335
|
+
mkdirSync(input.sessionDir, { recursive: true });
|
|
336
|
+
|
|
337
|
+
const runtime = await ModelRuntime.create({
|
|
338
|
+
authPath: input.authPath,
|
|
339
|
+
modelsPath: input.modelsPath,
|
|
340
|
+
refreshOnCreate: false,
|
|
341
|
+
});
|
|
342
|
+
hooks.registerProviders?.(runtime);
|
|
343
|
+
|
|
344
|
+
let model: ReturnType<ModelRuntime["getModel"]>;
|
|
345
|
+
if (input.model !== undefined) {
|
|
346
|
+
const slash = input.model.indexOf("/");
|
|
347
|
+
model = runtime.getModel(input.model.slice(0, slash), input.model.slice(slash + 1));
|
|
348
|
+
if (model === undefined) {
|
|
349
|
+
io.line(failure("model_missing", `model is not known to pi: ${input.model}`));
|
|
350
|
+
return EXIT_FAILED;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
const sessionManager =
|
|
355
|
+
input.resumeSession !== undefined
|
|
356
|
+
? SessionManager.open(input.resumeSession, input.sessionDir)
|
|
357
|
+
: SessionManager.create(input.cwd, input.sessionDir);
|
|
358
|
+
|
|
359
|
+
// The one extension operad loads. Its tool_call handler asks the access
|
|
360
|
+
// matcher; a refusal blocks the call and the agent goes on.
|
|
361
|
+
const bashTimeoutSecs = input.bashTimeoutSecs ?? DEFAULT_BASH_TIMEOUT_SECS;
|
|
362
|
+
const access = readProfile(input.access ?? {});
|
|
363
|
+
const profile: AccessProfile = access.ok ? access.profile : {};
|
|
364
|
+
const blockedCalls = new Set<string>();
|
|
365
|
+
// What a late answer continues; known once the session exists.
|
|
366
|
+
let sessionFile: string | null = null;
|
|
367
|
+
const operadExtension: ExtensionFactory = (pi) => {
|
|
368
|
+
pi.on("tool_call", async (event) => {
|
|
369
|
+
io.log(`tool_call ${event.toolName}`);
|
|
370
|
+
if (event.toolName === "bash") {
|
|
371
|
+
// The timeout kills the command; pi gives the model a tool error and the run goes on.
|
|
372
|
+
const bounded = boundedTimeout(Reflect.get(event.input, "timeout"), bashTimeoutSecs);
|
|
373
|
+
if (bounded !== undefined) Reflect.set(event.input, "timeout", bounded);
|
|
374
|
+
}
|
|
375
|
+
const verdict = match(profile, { tool: event.toolName, input: event.input, cwd: input.cwd });
|
|
376
|
+
if (verdict.allow) return undefined;
|
|
377
|
+
// A one-time permission covers one exact call that would be refused. The
|
|
378
|
+
// host writes the fact before it answers, so a crash after it cannot
|
|
379
|
+
// give the permission twice.
|
|
380
|
+
const call = { tool: event.toolName, input: event.input, cwd: input.cwd };
|
|
381
|
+
const grant = findGrant(profile, call);
|
|
382
|
+
if (grant !== undefined && io.useGrant !== undefined) {
|
|
383
|
+
let used = false;
|
|
384
|
+
try {
|
|
385
|
+
used = await io.useGrant(grant.waitId);
|
|
386
|
+
} catch {
|
|
387
|
+
used = false;
|
|
388
|
+
}
|
|
389
|
+
if (used) return undefined;
|
|
390
|
+
}
|
|
391
|
+
// A call the profile says must ask goes to a person. A deny wins over an
|
|
392
|
+
// ask, so a call that was denied never gets here with `ask`.
|
|
393
|
+
let reason = verdict.reason;
|
|
394
|
+
if (verdict.ask === true && io.ask !== undefined) {
|
|
395
|
+
let answer: CallAnswer;
|
|
396
|
+
if ((input.secretValues ?? []).some((secret) => secret.length > 0 && verdict.value.includes(secret))) {
|
|
397
|
+
// A value that holds a secret is never asked about: no fact may hold it.
|
|
398
|
+
answer = { decision: "deny", reason: "the call holds a secret value, so nobody is asked about it" };
|
|
399
|
+
} else {
|
|
400
|
+
const shown = summarizeCall(profile, event.toolName, event.input, input.cwd, { secrets: input.secretValues });
|
|
401
|
+
try {
|
|
402
|
+
answer = await io.ask({ kind: verdict.kind, value: verdict.value, ...(verdict.tool === undefined ? {} : { tool: verdict.tool }), shown: shown ?? verdict.value, session: sessionFile });
|
|
403
|
+
} catch {
|
|
404
|
+
answer = { decision: "deny", reason: "the question could not be asked" };
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
if (answer.decision === "allow") return undefined;
|
|
408
|
+
if (answer.decision === "stop") {
|
|
409
|
+
// The wait ended: the host ends this program next. Hold the call until it does.
|
|
410
|
+
await new Promise<void>((resolve) => {
|
|
411
|
+
if (cancel.aborted) resolve();
|
|
412
|
+
cancel.addEventListener("abort", () => resolve(), { once: true });
|
|
413
|
+
});
|
|
414
|
+
reason = "waiting for an answer";
|
|
415
|
+
} else {
|
|
416
|
+
reason = `${verdict.reason}; ${answer.reason ?? "a person refused it"}`;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
blockedCalls.add(event.toolCallId);
|
|
420
|
+
io.line({ type: "blocked", toolName: event.toolName, reason: REFUSED_IN_LOG });
|
|
421
|
+
return { block: true, reason };
|
|
422
|
+
});
|
|
423
|
+
};
|
|
424
|
+
|
|
425
|
+
const settingsManager = SettingsManager.inMemory({
|
|
426
|
+
compaction: { enabled: false },
|
|
427
|
+
retry: { enabled: false },
|
|
428
|
+
});
|
|
429
|
+
const resourceLoader = new DefaultResourceLoader({
|
|
430
|
+
cwd: input.cwd,
|
|
431
|
+
agentDir: input.agentDir,
|
|
432
|
+
settingsManager,
|
|
433
|
+
noExtensions: true,
|
|
434
|
+
noSkills: true,
|
|
435
|
+
noPromptTemplates: true,
|
|
436
|
+
noThemes: true,
|
|
437
|
+
noContextFiles: true,
|
|
438
|
+
extensionFactories: [{ name: "operad", factory: operadExtension, hidden: true }],
|
|
439
|
+
});
|
|
440
|
+
await resourceLoader.reload();
|
|
441
|
+
|
|
442
|
+
// Operad's tools, as pi's own custom tools; each call runs against the home.
|
|
443
|
+
let operad: McpTools | undefined;
|
|
444
|
+
if (input.operadTools !== undefined) {
|
|
445
|
+
operad = await openMcpTools({
|
|
446
|
+
home: input.operadTools.home,
|
|
447
|
+
cwd: input.cwd,
|
|
448
|
+
onLog: (message) => io.log(message),
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
const mcp = operad;
|
|
452
|
+
const customTools =
|
|
453
|
+
mcp === undefined
|
|
454
|
+
? undefined
|
|
455
|
+
: mcp.tools.map((tool) => ({
|
|
456
|
+
name: `operad_${tool.name}`,
|
|
457
|
+
label: `operad ${tool.name}`,
|
|
458
|
+
description: tool.description,
|
|
459
|
+
// The same JSON Schema the MCP server states; pi checks arguments against it.
|
|
460
|
+
parameters: { ...tool.inputSchema },
|
|
461
|
+
async execute(_id: string, params: Record<string, unknown>) {
|
|
462
|
+
const outcome = await mcp.call(tool.name, params);
|
|
463
|
+
const text = outcome.content.map((block) => block.text).join("\n");
|
|
464
|
+
if (outcome.isError === true) throw new Error(text);
|
|
465
|
+
return { content: [{ type: "text" as const, text }], details: outcome.structuredContent ?? {} };
|
|
466
|
+
},
|
|
467
|
+
}));
|
|
468
|
+
|
|
469
|
+
const { session } = await createAgentSession({
|
|
470
|
+
...(customTools === undefined ? {} : { customTools }),
|
|
471
|
+
cwd: input.cwd,
|
|
472
|
+
agentDir: input.agentDir,
|
|
473
|
+
modelRuntime: runtime,
|
|
474
|
+
resourceLoader,
|
|
475
|
+
sessionManager,
|
|
476
|
+
settingsManager,
|
|
477
|
+
...(model !== undefined ? { model } : {}),
|
|
478
|
+
...(input.thinkingLevel !== undefined ? { thinkingLevel: input.thinkingLevel } : {}),
|
|
479
|
+
});
|
|
480
|
+
|
|
481
|
+
sessionFile = session.sessionFile ?? null;
|
|
482
|
+
const tally = new Tally();
|
|
483
|
+
const now = hooks.now ?? Date.now;
|
|
484
|
+
const increments = new Increments(io, now, input.secretValues ?? []);
|
|
485
|
+
const started = new Map<string, number>();
|
|
486
|
+
let settle: () => void = () => {};
|
|
487
|
+
const settled = new Promise<void>((resolve) => {
|
|
488
|
+
settle = resolve;
|
|
489
|
+
});
|
|
490
|
+
session.subscribe((event) => {
|
|
491
|
+
switch (event.type) {
|
|
492
|
+
case "message_update": {
|
|
493
|
+
const update = event.assistantMessageEvent;
|
|
494
|
+
switch (update.type) {
|
|
495
|
+
case "text_delta":
|
|
496
|
+
increments.text(update.delta);
|
|
497
|
+
break;
|
|
498
|
+
case "thinking_delta":
|
|
499
|
+
increments.thinking(update.delta);
|
|
500
|
+
break;
|
|
501
|
+
case "thinking_end":
|
|
502
|
+
increments.endThinking(update.content);
|
|
503
|
+
break;
|
|
504
|
+
default:
|
|
505
|
+
break;
|
|
506
|
+
}
|
|
507
|
+
break;
|
|
508
|
+
}
|
|
509
|
+
case "message_end": {
|
|
510
|
+
if (event.message.role === "assistant") increments.endMessage(textOf(event.message.content, ""));
|
|
511
|
+
const line = tally.add(event.message);
|
|
512
|
+
if (line !== undefined) io.line(line);
|
|
513
|
+
break;
|
|
514
|
+
}
|
|
515
|
+
case "tool_execution_start": {
|
|
516
|
+
const startedAt = now();
|
|
517
|
+
started.set(event.toolCallId, startedAt);
|
|
518
|
+
const summary = summarizeCall(profile, event.toolName, event.args, input.cwd, { secrets: input.secretValues, keepLines: true });
|
|
519
|
+
io.line({
|
|
520
|
+
type: "tool_execution_start",
|
|
521
|
+
toolCallId: event.toolCallId,
|
|
522
|
+
toolName: event.toolName,
|
|
523
|
+
at: startedAt,
|
|
524
|
+
...(summary === undefined ? {} : { input: summary }),
|
|
525
|
+
});
|
|
526
|
+
break;
|
|
527
|
+
}
|
|
528
|
+
case "tool_execution_end": {
|
|
529
|
+
const begun = started.get(event.toolCallId);
|
|
530
|
+
started.delete(event.toolCallId);
|
|
531
|
+
const blocked = blockedCalls.has(event.toolCallId);
|
|
532
|
+
const content =
|
|
533
|
+
typeof event.result === "object" && event.result !== null
|
|
534
|
+
? Reflect.get(event.result, "content")
|
|
535
|
+
: event.result;
|
|
536
|
+
// A refused call printed nothing; its result is the refusal the model
|
|
537
|
+
// already gets, and only the end line names it.
|
|
538
|
+
if (!blocked) {
|
|
539
|
+
const output = textOf(content, "");
|
|
540
|
+
if (output.length > 0) {
|
|
541
|
+
for (const part of toolOutputLines(output, input.secretValues ?? [])) {
|
|
542
|
+
io.line({ type: "tool_output", toolCallId: event.toolCallId, text: part.text });
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
const firstLine = blocked
|
|
547
|
+
? REFUSED_IN_LOG
|
|
548
|
+
: event.isError
|
|
549
|
+
? firstErrorLine(textOf(content), { secrets: input.secretValues })
|
|
550
|
+
: undefined;
|
|
551
|
+
io.line({
|
|
552
|
+
type: "tool_execution_end",
|
|
553
|
+
toolCallId: event.toolCallId,
|
|
554
|
+
toolName: event.toolName,
|
|
555
|
+
isError: event.isError,
|
|
556
|
+
durationMs: begun === undefined ? (event.durationMs ?? 0) : Math.max(0, now() - begun),
|
|
557
|
+
...(firstLine === undefined ? {} : { error: firstLine }),
|
|
558
|
+
});
|
|
559
|
+
break;
|
|
560
|
+
}
|
|
561
|
+
case "agent_settled":
|
|
562
|
+
io.line({ type: "agent_settled", aborted: event.aborted });
|
|
563
|
+
settle();
|
|
564
|
+
break;
|
|
565
|
+
default:
|
|
566
|
+
break;
|
|
567
|
+
}
|
|
568
|
+
});
|
|
569
|
+
|
|
570
|
+
const result = (name: "done" | "cancelled"): WorkerResult => ({
|
|
571
|
+
type: "result",
|
|
572
|
+
result: name,
|
|
573
|
+
sessionId: session.sessionFile ?? null,
|
|
574
|
+
usage: tally.usage,
|
|
575
|
+
cost: tally.cost,
|
|
576
|
+
finalMessage: session.getLastAssistantText() ?? null,
|
|
577
|
+
});
|
|
578
|
+
|
|
579
|
+
// Every way this run ends writes its Result here: text still held back as a
|
|
580
|
+
// possible secret prefix is released first.
|
|
581
|
+
const finish = (line: WorkerResult, code: number): number => {
|
|
582
|
+
increments.release();
|
|
583
|
+
io.line(line);
|
|
584
|
+
return code;
|
|
585
|
+
};
|
|
586
|
+
|
|
587
|
+
// A message the host sends mid-run steers the agent: pi delivers it after
|
|
588
|
+
// the tool call that is running.
|
|
589
|
+
io.onMessage?.((text) => {
|
|
590
|
+
io.log("a message from the host is given to pi");
|
|
591
|
+
session.prompt(text, { streamingBehavior: "steer" }).catch((error: unknown) => {
|
|
592
|
+
io.log(`a message to pi was not delivered: ${error instanceof Error ? error.message : String(error)}`);
|
|
593
|
+
});
|
|
594
|
+
});
|
|
595
|
+
|
|
596
|
+
let cancelled = cancel.aborted;
|
|
597
|
+
const onCancel = (): void => {
|
|
598
|
+
cancelled = true;
|
|
599
|
+
void session.abort();
|
|
600
|
+
};
|
|
601
|
+
cancel.addEventListener("abort", onCancel, { once: true });
|
|
602
|
+
|
|
603
|
+
try {
|
|
604
|
+
if (!cancelled) {
|
|
605
|
+
try {
|
|
606
|
+
const images = await Promise.all((input.images ?? []).map((image) => readImage(image)));
|
|
607
|
+
await session.prompt(
|
|
608
|
+
input.prompt,
|
|
609
|
+
images.length === 0
|
|
610
|
+
? undefined
|
|
611
|
+
: { images: images.map((image) => ({ type: "image" as const, data: image.data, mimeType: image.mediaType })) },
|
|
612
|
+
);
|
|
613
|
+
} catch (error) {
|
|
614
|
+
if (!cancelled) {
|
|
615
|
+
return finish(
|
|
616
|
+
{
|
|
617
|
+
...failure("model_error", error instanceof Error ? error.message : String(error)),
|
|
618
|
+
sessionId: session.sessionFile ?? null,
|
|
619
|
+
usage: tally.usage,
|
|
620
|
+
cost: tally.cost,
|
|
621
|
+
},
|
|
622
|
+
EXIT_FAILED,
|
|
623
|
+
);
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
if (!cancelled) await settled;
|
|
627
|
+
}
|
|
628
|
+
if (cancelled) {
|
|
629
|
+
await session.abort();
|
|
630
|
+
return finish(result("cancelled"), EXIT_CANCELLED);
|
|
631
|
+
}
|
|
632
|
+
if (tally.lastError !== undefined) {
|
|
633
|
+
return finish(
|
|
634
|
+
{
|
|
635
|
+
...failure("model_error", tally.lastError),
|
|
636
|
+
sessionId: session.sessionFile ?? null,
|
|
637
|
+
usage: tally.usage,
|
|
638
|
+
cost: tally.cost,
|
|
639
|
+
finalMessage: session.getLastAssistantText() ?? null,
|
|
640
|
+
},
|
|
641
|
+
EXIT_FAILED,
|
|
642
|
+
);
|
|
643
|
+
}
|
|
644
|
+
return finish(result("done"), 0);
|
|
645
|
+
} finally {
|
|
646
|
+
cancel.removeEventListener("abort", onCancel);
|
|
647
|
+
session.dispose();
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
/**
|
|
652
|
+
* Stdin as lines. The first line (or all of stdin when it has no newline) is the
|
|
653
|
+
* input; later lines are the host's answers.
|
|
654
|
+
*/
|
|
655
|
+
class StdinLines {
|
|
656
|
+
readonly #reader: AsyncIterator<Uint8Array>;
|
|
657
|
+
readonly #decoder = new TextDecoder();
|
|
658
|
+
#buffer = "";
|
|
659
|
+
#done = false;
|
|
660
|
+
|
|
661
|
+
constructor(stream: AsyncIterable<Uint8Array>) {
|
|
662
|
+
this.#reader = stream[Symbol.asyncIterator]();
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/** Stops reading; a read that waits ends as if stdin had ended. */
|
|
666
|
+
close(): void {
|
|
667
|
+
void this.#reader.return?.()?.catch(() => undefined);
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
async #more(): Promise<boolean> {
|
|
671
|
+
if (this.#done) return false;
|
|
672
|
+
const chunk = await this.#reader.next();
|
|
673
|
+
if (chunk.done) {
|
|
674
|
+
this.#done = true;
|
|
675
|
+
this.#buffer += this.#decoder.decode();
|
|
676
|
+
return false;
|
|
677
|
+
}
|
|
678
|
+
this.#buffer += this.#decoder.decode(chunk.value, { stream: true });
|
|
679
|
+
return true;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/** The next line, or what is left at the end of stdin; undefined when nothing is. */
|
|
683
|
+
async next(): Promise<string | undefined> {
|
|
684
|
+
for (;;) {
|
|
685
|
+
const newline = this.#buffer.indexOf("\n");
|
|
686
|
+
if (newline !== -1) {
|
|
687
|
+
const line = this.#buffer.slice(0, newline);
|
|
688
|
+
this.#buffer = this.#buffer.slice(newline + 1);
|
|
689
|
+
if (line.trim().length === 0) continue;
|
|
690
|
+
return line;
|
|
691
|
+
}
|
|
692
|
+
if (!(await this.#more())) {
|
|
693
|
+
const rest = this.#buffer;
|
|
694
|
+
this.#buffer = "";
|
|
695
|
+
return rest.trim().length === 0 ? undefined : rest;
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
async first(): Promise<string> {
|
|
701
|
+
return (await this.next()) ?? "";
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* The program without the process around it: reads the input and the host's
|
|
707
|
+
* answers from `stdin`, writes lines through `ports`, and returns the exit
|
|
708
|
+
* code. `cancel` is the SIGTERM signal.
|
|
709
|
+
*/
|
|
710
|
+
export async function serveWorker(
|
|
711
|
+
stdinStream: AsyncIterable<Uint8Array>,
|
|
712
|
+
ports: WorkerPorts,
|
|
713
|
+
cancel: AbortSignal,
|
|
714
|
+
hooks: WorkerHooks = {},
|
|
715
|
+
): Promise<number> {
|
|
716
|
+
const write = ports.write;
|
|
717
|
+
const stdin = new StdinLines(stdinStream);
|
|
718
|
+
const waiting = new Map<number, (used: boolean) => void>();
|
|
719
|
+
const questions = new Map<number, (answer: CallAnswer) => void>();
|
|
720
|
+
let nextAsk = 1;
|
|
721
|
+
const early: string[] = [];
|
|
722
|
+
let onMessage: ((text: string) => void) | undefined;
|
|
723
|
+
let nextGrant = 1;
|
|
724
|
+
let hostGone = false;
|
|
725
|
+
const io: WorkerIo = {
|
|
726
|
+
line: (line) => write(`${JSON.stringify(line)}\n`),
|
|
727
|
+
onMessage: (handler) => {
|
|
728
|
+
onMessage = handler;
|
|
729
|
+
for (const text of early.splice(0)) handler(text);
|
|
730
|
+
},
|
|
731
|
+
log: (text) => ports.log(text),
|
|
732
|
+
useGrant: (waitId) =>
|
|
733
|
+
new Promise<boolean>((resolve) => {
|
|
734
|
+
if (hostGone) {
|
|
735
|
+
resolve(false);
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
const id = nextGrant;
|
|
739
|
+
nextGrant += 1;
|
|
740
|
+
waiting.set(id, resolve);
|
|
741
|
+
write(`${JSON.stringify({ type: "grant_use", id, waitId })}\n`);
|
|
742
|
+
}),
|
|
743
|
+
ask: (call) =>
|
|
744
|
+
new Promise<CallAnswer>((resolve) => {
|
|
745
|
+
if (hostGone) {
|
|
746
|
+
resolve({ decision: "deny", reason: "the host is gone" });
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
const id = nextAsk;
|
|
750
|
+
nextAsk += 1;
|
|
751
|
+
questions.set(id, (answer) => {
|
|
752
|
+
// The line that closes the question, so the host's stall timer runs again.
|
|
753
|
+
write(`${JSON.stringify({ type: "ask_resolved", id })}\n`);
|
|
754
|
+
resolve(answer);
|
|
755
|
+
});
|
|
756
|
+
write(`${JSON.stringify({ type: "ask_call", id, ...call })}\n`);
|
|
757
|
+
}),
|
|
758
|
+
};
|
|
759
|
+
let code: number;
|
|
760
|
+
try {
|
|
761
|
+
const text = await stdin.first();
|
|
762
|
+
let decoded: unknown;
|
|
763
|
+
let parsedOk = true;
|
|
764
|
+
try {
|
|
765
|
+
decoded = JSON.parse(text);
|
|
766
|
+
} catch {
|
|
767
|
+
parsedOk = false;
|
|
768
|
+
}
|
|
769
|
+
const parsed = parsedOk ? parseInput(decoded) : ({ ok: false, message: "the input is not valid JSON" } as const);
|
|
770
|
+
if (!parsed.ok) {
|
|
771
|
+
io.line(failure("invalid_input", parsed.message));
|
|
772
|
+
code = EXIT_INVALID_INPUT;
|
|
773
|
+
} else {
|
|
774
|
+
// Later stdin lines answer `grant_use` lines.
|
|
775
|
+
void (async () => {
|
|
776
|
+
for (;;) {
|
|
777
|
+
const line = await stdin.next();
|
|
778
|
+
if (line === undefined) break;
|
|
779
|
+
const said = messageText(line);
|
|
780
|
+
if (said !== undefined) {
|
|
781
|
+
if (onMessage === undefined) early.push(said);
|
|
782
|
+
else onMessage(said);
|
|
783
|
+
continue;
|
|
784
|
+
}
|
|
785
|
+
try {
|
|
786
|
+
const ack: unknown = JSON.parse(line);
|
|
787
|
+
if (typeof ack === "object" && ack !== null && Reflect.get(ack, "type") === "ask_ack") {
|
|
788
|
+
const id: unknown = Reflect.get(ack, "id");
|
|
789
|
+
const decision: unknown = Reflect.get(ack, "decision");
|
|
790
|
+
const reason: unknown = Reflect.get(ack, "reason");
|
|
791
|
+
if (typeof id === "number") {
|
|
792
|
+
questions.get(id)?.({
|
|
793
|
+
decision: decision === "allow" || decision === "stop" ? decision : "deny",
|
|
794
|
+
...(typeof reason === "string" ? { reason } : {}),
|
|
795
|
+
});
|
|
796
|
+
questions.delete(id);
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
if (typeof ack === "object" && ack !== null && Reflect.get(ack, "type") === "grant_ack") {
|
|
800
|
+
const id: unknown = Reflect.get(ack, "id");
|
|
801
|
+
const used: unknown = Reflect.get(ack, "used");
|
|
802
|
+
if (typeof id === "number") {
|
|
803
|
+
waiting.get(id)?.(used === true);
|
|
804
|
+
waiting.delete(id);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
} catch {
|
|
808
|
+
// Not a line the program understands; it is ignored.
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
// The host is gone: nothing more will be granted.
|
|
812
|
+
hostGone = true;
|
|
813
|
+
for (const resolve of waiting.values()) resolve(false);
|
|
814
|
+
waiting.clear();
|
|
815
|
+
for (const resolve of questions.values()) resolve({ decision: "deny", reason: "the host is gone" });
|
|
816
|
+
questions.clear();
|
|
817
|
+
})();
|
|
818
|
+
code = await runWorker(parsed.input, io, cancel, hooks);
|
|
819
|
+
}
|
|
820
|
+
} catch (error) {
|
|
821
|
+
io.log(error instanceof Error ? (error.stack ?? error.message) : String(error));
|
|
822
|
+
io.line(failure("model_error", error instanceof Error ? error.message : String(error)));
|
|
823
|
+
code = EXIT_FAILED;
|
|
824
|
+
}
|
|
825
|
+
stdin.close();
|
|
826
|
+
return code;
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
/** The process entry: stdin in, stdout lines out, exit code out. */
|
|
830
|
+
export async function main(hooks: WorkerHooks = {}): Promise<never> {
|
|
831
|
+
const flush = (): Promise<void> =>
|
|
832
|
+
new Promise((resolve) => {
|
|
833
|
+
process.stdout.write("", () => resolve());
|
|
834
|
+
});
|
|
835
|
+
// Anything that prints to stdout by accident would corrupt the protocol.
|
|
836
|
+
console.log = (...args: unknown[]): void => {
|
|
837
|
+
process.stderr.write(`${args.map(String).join(" ")}\n`);
|
|
838
|
+
};
|
|
839
|
+
|
|
840
|
+
// pi runs bash non-interactively (`bash -c`): no aliases or functions from the
|
|
841
|
+
// user's rc files. BASH_ENV and ENV are the two ways a non-interactive shell
|
|
842
|
+
// is made to read a file, so the agent's shell does not get them.
|
|
843
|
+
delete process.env["BASH_ENV"];
|
|
844
|
+
delete process.env["ENV"];
|
|
845
|
+
|
|
846
|
+
const controller = new AbortController();
|
|
847
|
+
process.on("SIGTERM", () => controller.abort());
|
|
848
|
+
const code = await serveWorker(
|
|
849
|
+
Bun.stdin.stream(),
|
|
850
|
+
{
|
|
851
|
+
write: (text) => {
|
|
852
|
+
process.stdout.write(text);
|
|
853
|
+
},
|
|
854
|
+
log: (text) => process.stderr.write(`${text}\n`),
|
|
855
|
+
},
|
|
856
|
+
controller.signal,
|
|
857
|
+
hooks,
|
|
858
|
+
);
|
|
859
|
+
await flush();
|
|
860
|
+
process.exit(code);
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
if (import.meta.main) await main();
|