@prefactor/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.
Files changed (56) hide show
  1. package/README.md +226 -2
  2. package/dist/commands.d.ts +32 -0
  3. package/dist/commands.d.ts.map +1 -0
  4. package/dist/commands.js +395 -0
  5. package/dist/commands.js.map +1 -0
  6. package/dist/credentials.d.ts +67 -0
  7. package/dist/credentials.d.ts.map +1 -0
  8. package/dist/credentials.js +120 -0
  9. package/dist/credentials.js.map +1 -0
  10. package/dist/data-risk.d.ts +11 -0
  11. package/dist/data-risk.d.ts.map +1 -0
  12. package/dist/data-risk.js +125 -0
  13. package/dist/data-risk.js.map +1 -0
  14. package/dist/device-login.d.ts +45 -0
  15. package/dist/device-login.d.ts.map +1 -0
  16. package/dist/device-login.js +163 -0
  17. package/dist/device-login.js.map +1 -0
  18. package/dist/extension.d.ts +44 -0
  19. package/dist/extension.d.ts.map +1 -0
  20. package/dist/extension.js +204 -0
  21. package/dist/extension.js.map +1 -0
  22. package/dist/index.cjs +1805 -0
  23. package/dist/index.cjs.map +22 -0
  24. package/dist/index.d.ts +19 -0
  25. package/dist/index.d.ts.map +1 -0
  26. package/dist/index.js +1772 -0
  27. package/dist/index.js.map +22 -0
  28. package/dist/prefactor-api.d.ts +38 -0
  29. package/dist/prefactor-api.d.ts.map +1 -0
  30. package/dist/prefactor-api.js +63 -0
  31. package/dist/prefactor-api.js.map +1 -0
  32. package/dist/prefactor-session.d.ts +126 -0
  33. package/dist/prefactor-session.d.ts.map +1 -0
  34. package/dist/prefactor-session.js +274 -0
  35. package/dist/prefactor-session.js.map +1 -0
  36. package/dist/recorder.d.ts +54 -0
  37. package/dist/recorder.d.ts.map +1 -0
  38. package/dist/recorder.js +70 -0
  39. package/dist/recorder.js.map +1 -0
  40. package/dist/schema.d.ts +54 -0
  41. package/dist/schema.d.ts.map +1 -0
  42. package/dist/schema.js +220 -0
  43. package/dist/schema.js.map +1 -0
  44. package/dist/session-tracer.d.ts +144 -0
  45. package/dist/session-tracer.d.ts.map +1 -0
  46. package/dist/session-tracer.js +390 -0
  47. package/dist/session-tracer.js.map +1 -0
  48. package/dist/tool-definitions.d.ts +17 -0
  49. package/dist/tool-definitions.d.ts.map +1 -0
  50. package/dist/tool-definitions.js +69 -0
  51. package/dist/tool-definitions.js.map +1 -0
  52. package/dist/version.d.ts +3 -0
  53. package/dist/version.d.ts.map +1 -0
  54. package/dist/version.js +4 -0
  55. package/dist/version.js.map +1 -0
  56. package/package.json +54 -4
package/dist/index.cjs ADDED
@@ -0,0 +1,1805 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ function __accessProp(key) {
6
+ return this[key];
7
+ }
8
+ var __toCommonJS = (from) => {
9
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
10
+ if (entry)
11
+ return entry;
12
+ entry = __defProp({}, "__esModule", { value: true });
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (var key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(entry, key))
16
+ __defProp(entry, key, {
17
+ get: __accessProp.bind(from, key),
18
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
19
+ });
20
+ }
21
+ __moduleCache.set(from, entry);
22
+ return entry;
23
+ };
24
+ var __moduleCache;
25
+ var __returnValue = (v) => v;
26
+ function __exportSetter(name, newValue) {
27
+ this[name] = __returnValue.bind(null, newValue);
28
+ }
29
+ var __export = (target, all) => {
30
+ for (var name in all)
31
+ __defProp(target, name, {
32
+ get: all[name],
33
+ enumerable: true,
34
+ configurable: true,
35
+ set: __exportSetter.bind(all, name)
36
+ });
37
+ };
38
+
39
+ // packages/pi/src/index.ts
40
+ var exports_src = {};
41
+ __export(exports_src, {
42
+ default: () => src_default,
43
+ getCredentialsFilePath: () => getCredentialsFilePath,
44
+ prefactorExtension: () => prefactorExtension
45
+ });
46
+ module.exports = __toCommonJS(exports_src);
47
+
48
+ // packages/pi/src/extension.ts
49
+ var import_pi_coding_agent2 = require("@earendil-works/pi-coding-agent");
50
+ var import_core4 = require("@prefactor/core");
51
+
52
+ // packages/pi/src/commands.ts
53
+ var import_pi_tui = require("@earendil-works/pi-tui");
54
+
55
+ // packages/pi/src/credentials.ts
56
+ var import_promises = require("node:fs/promises");
57
+ var import_node_path = require("node:path");
58
+ var import_pi_coding_agent = require("@earendil-works/pi-coding-agent");
59
+ var DEFAULT_API_URL = "https://app.prefactorai.com";
60
+ var CREDENTIALS_FILE_NAME = "prefactor.json";
61
+ function getCredentialsFilePath() {
62
+ return import_node_path.join(import_pi_coding_agent.getAgentDir(), CREDENTIALS_FILE_NAME);
63
+ }
64
+ async function readCredentialsFile(path = getCredentialsFilePath()) {
65
+ let text;
66
+ try {
67
+ text = await import_promises.readFile(path, "utf8");
68
+ } catch (error) {
69
+ if (error.code === "ENOENT") {
70
+ return;
71
+ }
72
+ throw error;
73
+ }
74
+ const parsed = JSON.parse(text);
75
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
76
+ throw new Error(`${path} does not hold a JSON object`);
77
+ }
78
+ return parsed;
79
+ }
80
+ async function writeCredentialsFile(contents, path = getCredentialsFilePath()) {
81
+ await import_promises.mkdir(import_node_path.dirname(path), { recursive: true });
82
+ const temporaryPath = `${path}.${process.pid}.tmp`;
83
+ await import_promises.writeFile(temporaryPath, `${JSON.stringify(contents, null, 2)}
84
+ `, { mode: 384 });
85
+ await import_promises.chmod(temporaryPath, 384);
86
+ await import_promises.rename(temporaryPath, path);
87
+ }
88
+ async function deleteCredentialsFile(path = getCredentialsFilePath()) {
89
+ try {
90
+ await import_promises.rm(path);
91
+ return true;
92
+ } catch (error) {
93
+ if (error.code === "ENOENT") {
94
+ return false;
95
+ }
96
+ throw error;
97
+ }
98
+ }
99
+ async function resolveCredentials(options = {}, env = process.env, credentialsFilePath = getCredentialsFilePath()) {
100
+ const candidates = [
101
+ {
102
+ source: "options",
103
+ apiUrl: options.apiUrl,
104
+ apiToken: options.apiToken,
105
+ agentId: options.agentId
106
+ },
107
+ {
108
+ source: "environment",
109
+ apiUrl: env.PREFACTOR_API_URL,
110
+ apiToken: env.PREFACTOR_API_TOKEN,
111
+ agentId: env.PREFACTOR_AGENT_ID
112
+ }
113
+ ];
114
+ let chosenIndex = candidates.findIndex((candidate) => nonEmpty(candidate.apiToken));
115
+ const needsFile = chosenIndex === -1 || !candidates.slice(chosenIndex).some((c) => nonEmpty(c.apiUrl));
116
+ if (needsFile) {
117
+ const file = await readCredentialsFile(credentialsFilePath);
118
+ candidates.push({
119
+ source: "file",
120
+ apiUrl: file?.api_url,
121
+ apiToken: file?.api_token,
122
+ agentId: file?.agent_id
123
+ });
124
+ if (chosenIndex === -1) {
125
+ chosenIndex = candidates.findIndex((candidate) => nonEmpty(candidate.apiToken));
126
+ }
127
+ }
128
+ const chosen = candidates[chosenIndex];
129
+ if (!chosen?.apiToken) {
130
+ return;
131
+ }
132
+ const apiUrl = candidates.slice(chosenIndex).map((candidate) => candidate.apiUrl).find(nonEmpty) ?? DEFAULT_API_URL;
133
+ const agentId = nonEmpty(chosen.agentId) ? chosen.agentId : undefined;
134
+ return {
135
+ source: chosen.source,
136
+ apiUrl,
137
+ apiToken: chosen.apiToken,
138
+ ...agentId ? { agentId } : {}
139
+ };
140
+ }
141
+ function nonEmpty(value) {
142
+ return typeof value === "string" && value.trim().length > 0;
143
+ }
144
+
145
+ // packages/pi/src/device-login.ts
146
+ var import_node_child_process = require("node:child_process");
147
+ var import_node_os = require("node:os");
148
+ var SLOW_DOWN_EXTRA_MS = 5000;
149
+ var MAX_CLIENT_INFO_LENGTH = 64;
150
+
151
+ class LoginCancelledError extends Error {
152
+ constructor() {
153
+ super("Sign-in cancelled.");
154
+ this.name = "LoginCancelledError";
155
+ }
156
+ }
157
+ async function startDeviceLogin(apiUrl, clientVersion, deps = {}) {
158
+ const fetchImpl = deps.fetch ?? globalThis.fetch;
159
+ const host = import_node_os.hostname().trim();
160
+ const response = await fetchImpl(new URL("/cli/login/start", apiUrl), {
161
+ method: "POST",
162
+ headers: { "content-type": "application/json", accept: "application/json" },
163
+ body: JSON.stringify({
164
+ client_version: clientVersion.slice(0, MAX_CLIENT_INFO_LENGTH),
165
+ platform: `${process.platform}-${process.arch}`.slice(0, MAX_CLIENT_INFO_LENGTH),
166
+ ...host ? { hostname: host.slice(0, MAX_CLIENT_INFO_LENGTH) } : {}
167
+ })
168
+ });
169
+ if (response.status === 404) {
170
+ return "unsupported";
171
+ }
172
+ if (!response.ok) {
173
+ const code = await readErrorCode(response);
174
+ throw new Error(`Sign-in could not start (${code ?? `HTTP ${response.status}`}).`);
175
+ }
176
+ const body = await response.json();
177
+ if (!isDeviceLogin(body)) {
178
+ throw new Error("Sign-in start returned an unexpected response.");
179
+ }
180
+ return body;
181
+ }
182
+ async function pollForDeviceGrant(apiUrl, login, signal, deps = {}) {
183
+ const fetchImpl = deps.fetch ?? globalThis.fetch;
184
+ const sleep = deps.sleep ?? ((ms) => abortableSleep(ms, signal));
185
+ const now = deps.now ?? Date.now;
186
+ const deadline = now() + login.expires_in * 1000;
187
+ let intervalMs = Math.max(1, login.interval) * 1000;
188
+ while (now() < deadline) {
189
+ await sleep(intervalMs);
190
+ if (signal.aborted) {
191
+ throw new LoginCancelledError;
192
+ }
193
+ let response;
194
+ try {
195
+ response = await fetchImpl(new URL("/cli/login/token", apiUrl), {
196
+ method: "POST",
197
+ headers: { "content-type": "application/json", accept: "application/json" },
198
+ body: JSON.stringify({ login_token: login.login_token, device_code: login.device_code }),
199
+ signal
200
+ });
201
+ } catch (error) {
202
+ if (signal.aborted) {
203
+ throw new LoginCancelledError;
204
+ }
205
+ throw error;
206
+ }
207
+ if (response.ok) {
208
+ return readDeviceGrant(response);
209
+ }
210
+ const code = await readErrorCode(response);
211
+ if (code === "slow_down") {
212
+ intervalMs += SLOW_DOWN_EXTRA_MS;
213
+ continue;
214
+ }
215
+ if (code === "authorization_pending" || response.status === 429 || code === "rate_limited") {
216
+ continue;
217
+ }
218
+ if (code === "access_denied") {
219
+ throw new Error("The sign-in was denied in the browser.");
220
+ }
221
+ if (code === "expired_token") {
222
+ throw new Error("The sign-in expired. Run /prefactor setup again.");
223
+ }
224
+ throw new Error(`Sign-in failed (${code ?? `HTTP ${response.status}`}).`);
225
+ }
226
+ throw new Error("The sign-in expired. Run /prefactor setup again.");
227
+ }
228
+ function openBrowser(url) {
229
+ const command = process.platform === "darwin" ? { file: "open", args: [url] } : process.platform === "win32" ? { file: "rundll32", args: ["url.dll,FileProtocolHandler", url] } : { file: "xdg-open", args: [url] };
230
+ if (!/^https?:\/\//.test(url)) {
231
+ return;
232
+ }
233
+ const child = import_node_child_process.spawn(command.file, command.args, { detached: true, stdio: "ignore" });
234
+ child.on("error", () => {
235
+ return;
236
+ });
237
+ child.unref();
238
+ }
239
+ async function readDeviceGrant(response) {
240
+ const body = await response.json();
241
+ if (!body || typeof body.access_token !== "string" || body.access_token.length === 0) {
242
+ throw new Error("Sign-in approval returned an unexpected response.");
243
+ }
244
+ return {
245
+ access_token: body.access_token,
246
+ ...typeof body.account_id === "string" ? { account_id: body.account_id } : {},
247
+ ...typeof body.account_name === "string" ? { account_name: body.account_name } : {}
248
+ };
249
+ }
250
+ async function readErrorCode(response) {
251
+ const text = await response.text();
252
+ try {
253
+ const body = JSON.parse(text);
254
+ if (body && typeof body === "object" && typeof body.error === "string") {
255
+ return body.error;
256
+ }
257
+ } catch {}
258
+ return;
259
+ }
260
+ function isDeviceLogin(value) {
261
+ if (!value || typeof value !== "object") {
262
+ return false;
263
+ }
264
+ const login = value;
265
+ return typeof login.login_token === "string" && typeof login.device_code === "string" && typeof login.user_code === "string" && typeof login.verification_uri_complete === "string" && typeof login.expires_in === "number" && typeof login.interval === "number";
266
+ }
267
+ function abortableSleep(ms, signal) {
268
+ return new Promise((resolve) => {
269
+ const timer = setTimeout(done, ms);
270
+ function done() {
271
+ clearTimeout(timer);
272
+ signal.removeEventListener("abort", done);
273
+ resolve();
274
+ }
275
+ signal.addEventListener("abort", done, { once: true });
276
+ });
277
+ }
278
+
279
+ // packages/pi/src/prefactor-api.ts
280
+ class PrefactorApi {
281
+ client;
282
+ constructor(client) {
283
+ this.client = client;
284
+ }
285
+ async ping() {
286
+ const response = await this.client.request("/api/v1/ping", {
287
+ method: "GET"
288
+ });
289
+ return response.details ?? {};
290
+ }
291
+ listAgents() {
292
+ return this.listAll("/api/v1/agent", { role: "standard" });
293
+ }
294
+ async createAgent(name, description) {
295
+ const response = await this.client.request("/api/v1/agent", {
296
+ method: "POST",
297
+ body: { details: { name, description } }
298
+ });
299
+ return response.details;
300
+ }
301
+ listDeployments(agentId) {
302
+ return this.listAll("/api/v1/agent_deployment", { agent_id: agentId });
303
+ }
304
+ listEnvironments(accountId) {
305
+ return this.listAll("/api/v1/environment", { account_id: accountId });
306
+ }
307
+ async createDeploymentToken(agentId, environmentId) {
308
+ const response = await this.client.request("/api/v1/api_token", {
309
+ method: "POST",
310
+ body: {
311
+ details: {
312
+ token_scope: "agent_deployment",
313
+ agent_id: agentId,
314
+ environment_id: environmentId
315
+ }
316
+ }
317
+ });
318
+ if (!response.token) {
319
+ throw new Error("Creating the deployment token returned no token.");
320
+ }
321
+ return response.token;
322
+ }
323
+ async revokeToken(tokenId) {
324
+ await this.client.request(`/api/v1/api_token/${tokenId}/revoke`, { method: "POST", body: {} });
325
+ }
326
+ async listAll(path, query) {
327
+ const items = [];
328
+ let offset = 0;
329
+ while (offset !== null) {
330
+ const params = new URLSearchParams({ ...query, "pagination[offset]": String(offset) });
331
+ const response = await this.client.request(`${path}?${params}`, { method: "GET" });
332
+ items.push(...response.summaries ?? []);
333
+ offset = response.pagination?.next_page_offset ?? null;
334
+ }
335
+ return items;
336
+ }
337
+ }
338
+
339
+ // packages/pi/src/commands.ts
340
+ var DEFAULT_AGENT_NAME = "pi";
341
+ var DEFAULT_AGENT_DESCRIPTION = "pi coding agent sessions";
342
+ var DEPLOYMENT_TOKEN_TYPE = "api_session_agent_deployment_scope";
343
+ var LOGIN_WIDGET = "prefactor-login";
344
+ var SUBCOMMANDS = ["setup", "status", "logout"];
345
+ var SOURCE_LABELS = {
346
+ options: "extension options in code",
347
+ environment: "PREFACTOR_* environment variables",
348
+ file: "credentials file"
349
+ };
350
+ function registerPrefactorCommand(pi, host) {
351
+ pi.registerCommand("prefactor", {
352
+ description: "Connect pi to Prefactor: setup, status or logout",
353
+ getArgumentCompletions: (prefix) => {
354
+ const items = SUBCOMMANDS.filter((name) => name.startsWith(prefix.trim())).map((name) => ({
355
+ value: name,
356
+ label: name
357
+ }));
358
+ return items.length > 0 ? items : null;
359
+ },
360
+ handler: async (args, ctx) => {
361
+ const subcommand = args.trim().split(/\s+/)[0] || "status";
362
+ if (!ctx.hasUI) {
363
+ process.stderr.write(`/prefactor needs interactive or RPC mode. In print and JSON modes, set PREFACTOR_API_URL, PREFACTOR_API_TOKEN and PREFACTOR_AGENT_ID.
364
+ `);
365
+ return;
366
+ }
367
+ try {
368
+ if (subcommand === "setup") {
369
+ await setup(ctx, host);
370
+ } else if (subcommand === "status") {
371
+ await status(ctx, host);
372
+ } else if (subcommand === "logout") {
373
+ await logout(ctx, host);
374
+ } else {
375
+ ctx.ui.notify(`Unknown subcommand "${subcommand}". Use setup, status or logout.`, "error");
376
+ }
377
+ } catch (error) {
378
+ if (error instanceof LoginCancelledError) {
379
+ ctx.ui.notify("Prefactor setup cancelled. Nothing was saved.", "info");
380
+ return;
381
+ }
382
+ ctx.ui.notify(`Prefactor ${subcommand} failed: ${describe(error)}`, "error");
383
+ }
384
+ }
385
+ });
386
+ }
387
+ async function setup(ctx, host) {
388
+ const current = await host.resolveCredentials();
389
+ if (current) {
390
+ const replace = await ctx.ui.confirm("Replace Prefactor credentials?", `pi already has Prefactor credentials from the ${SOURCE_LABELS[current.source]}. Set up new credentials?`);
391
+ if (!replace) {
392
+ return;
393
+ }
394
+ }
395
+ const file = await readCredentialsFile();
396
+ const apiUrl = process.env.PREFACTOR_API_URL || file?.api_url || DEFAULT_API_URL;
397
+ const method = await ctx.ui.select("Connect pi to Prefactor", [
398
+ "Sign in with your browser",
399
+ "Paste an agent-deployment token"
400
+ ]);
401
+ if (method === undefined) {
402
+ return;
403
+ }
404
+ const saved = method === "Sign in with your browser" ? await setupWithBrowser(ctx, host, apiUrl) : await setupWithPastedToken(ctx, host, apiUrl);
405
+ if (!saved) {
406
+ return;
407
+ }
408
+ const active = await host.resolveCredentials();
409
+ if (active && active.source !== "file") {
410
+ ctx.ui.notify(`Saved, but the ${SOURCE_LABELS[active.source]} take precedence over the credentials file.`, "warning");
411
+ return;
412
+ }
413
+ await host.startRecording(ctx);
414
+ const recording = host.getRecording();
415
+ if (active && recording && recording.credentials.apiToken !== active.apiToken) {
416
+ ctx.ui.notify(recording.startState === "pending" ? "This session keeps the Prefactor recording it is starting, and switches to the new credentials only if that recording fails to start. New sessions use the new credentials." : `This session keeps recording to ${recording.credentials.apiUrl}, agent ${recording.credentials.agentId ?? "(read from its token)"}. New sessions use the new credentials.`, "info");
417
+ }
418
+ }
419
+ async function setupWithBrowser(ctx, host, apiUrl) {
420
+ const login = await startDeviceLogin(apiUrl, host.clientVersion, host.loginDeps);
421
+ if (login === "unsupported") {
422
+ ctx.ui.notify(`${apiUrl} does not offer browser sign-in. Paste a token instead.`, "warning");
423
+ return setupWithPastedToken(ctx, host, apiUrl);
424
+ }
425
+ const grant = await waitForApproval(ctx, host, apiUrl, login);
426
+ const accountApi = new PrefactorApi(host.createClient(apiUrl, grant.access_token));
427
+ try {
428
+ return await createDeploymentCredentials(ctx, host, apiUrl, grant, accountApi);
429
+ } finally {
430
+ await revokeAccountToken(ctx, accountApi);
431
+ }
432
+ }
433
+ async function waitForApproval(ctx, host, apiUrl, login) {
434
+ if (ctx.mode === "tui") {
435
+ ctx.ui.setWidget(LOGIN_WIDGET, (_tui, theme) => loginWidget(theme, login));
436
+ } else {
437
+ ctx.ui.setWidget(LOGIN_WIDGET, [login.verification_uri_complete]);
438
+ }
439
+ (host.openBrowser ?? openBrowser)(login.verification_uri_complete);
440
+ const polling = new AbortController;
441
+ const dialog = new AbortController;
442
+ ctx.ui.select(`Approve code ${login.user_code} in your browser`, ["Cancel sign-in"], {
443
+ signal: dialog.signal
444
+ }).then(() => {
445
+ if (!dialog.signal.aborted) {
446
+ polling.abort();
447
+ }
448
+ });
449
+ try {
450
+ return await pollForDeviceGrant(apiUrl, login, polling.signal, host.loginDeps);
451
+ } finally {
452
+ dialog.abort();
453
+ ctx.ui.setWidget(LOGIN_WIDGET, undefined);
454
+ }
455
+ }
456
+ function loginWidget(theme, login) {
457
+ const url = login.verification_uri_complete;
458
+ return {
459
+ render(width) {
460
+ return breakAtWidth(url, width).map((line) => theme.fg("mdLink", hyperlink(url, line)));
461
+ },
462
+ invalidate() {}
463
+ };
464
+ }
465
+ function hyperlink(url, text) {
466
+ return `\x1B]8;;${url}\x1B\\${text}\x1B]8;;\x1B\\`;
467
+ }
468
+ function breakAtWidth(text, width) {
469
+ const chars = [...text];
470
+ const step = Math.max(1, width);
471
+ const lines = [];
472
+ for (let start = 0;start < chars.length; start += step) {
473
+ lines.push(chars.slice(start, start + step).join(""));
474
+ }
475
+ return lines;
476
+ }
477
+ async function createDeploymentCredentials(ctx, host, apiUrl, grant, accountApi) {
478
+ if (!grant.account_id) {
479
+ throw new Error("The sign-in did not return an account id.");
480
+ }
481
+ const agent = await chooseAgent(ctx, accountApi);
482
+ if (!agent) {
483
+ return false;
484
+ }
485
+ const environmentId = await chooseEnvironment(ctx, accountApi, agent.id, grant.account_id);
486
+ if (!environmentId) {
487
+ return false;
488
+ }
489
+ const token = await accountApi.createDeploymentToken(agent.id, environmentId);
490
+ await checkDeploymentToken(host, apiUrl, token, agent.id);
491
+ await writeCredentialsFile({
492
+ api_url: apiUrl,
493
+ api_token: token,
494
+ agent_id: agent.id,
495
+ agent_name: agent.name,
496
+ environment_id: environmentId,
497
+ account_id: grant.account_id,
498
+ ...grant.account_name ? { account_name: grant.account_name } : {},
499
+ created_at: new Date().toISOString()
500
+ });
501
+ ctx.ui.notify(`Connected pi to the Prefactor agent "${agent.name}"${grant.account_name ? ` in ${grant.account_name}` : ""}.`, "info");
502
+ return true;
503
+ }
504
+ var CREATE_AGENT = "Create a new agent for pi";
505
+ var USE_EXISTING_AGENT = "Use an existing agent";
506
+ async function chooseAgent(ctx, api) {
507
+ const agents = await api.listAgents();
508
+ const choice = await ctx.ui.select("Which Prefactor agent should pi report to?", agents.length > 0 ? [CREATE_AGENT, USE_EXISTING_AGENT] : [CREATE_AGENT]);
509
+ if (choice === CREATE_AGENT) {
510
+ return createNamedAgent(ctx, api, agents);
511
+ }
512
+ if (choice === USE_EXISTING_AGENT) {
513
+ return chooseExistingAgent(ctx, agents);
514
+ }
515
+ return;
516
+ }
517
+ async function createNamedAgent(ctx, api, agents) {
518
+ const name = await ctx.ui.input(`Name for the new agent (default: ${DEFAULT_AGENT_NAME})`, DEFAULT_AGENT_NAME);
519
+ if (name === undefined) {
520
+ return;
521
+ }
522
+ const agentName = name.trim() || DEFAULT_AGENT_NAME;
523
+ const existing = agents.find((agent) => agent.name === agentName);
524
+ if (existing) {
525
+ const useExisting = await ctx.ui.confirm(`An agent named "${agentName}" already exists`, "Use the existing agent instead?");
526
+ return useExisting ? existing : undefined;
527
+ }
528
+ const description = await ctx.ui.input(`Description (optional, default: ${DEFAULT_AGENT_DESCRIPTION})`, DEFAULT_AGENT_DESCRIPTION);
529
+ if (description === undefined) {
530
+ return;
531
+ }
532
+ return api.createAgent(agentName, description.trim() || DEFAULT_AGENT_DESCRIPTION);
533
+ }
534
+ async function chooseExistingAgent(ctx, agents) {
535
+ const labels = agents.map((agent) => agents.filter((other) => other.name === agent.name).length > 1 ? `${agent.name} (${agent.id})` : agent.name);
536
+ const title = "Choose the agent pi reports to";
537
+ const choice = ctx.mode === "tui" ? await ctx.ui.custom((tui, theme, keybindings, done) => {
538
+ const filter = new import_pi_tui.Input({ placeholder: "Type to filter" });
539
+ filter.focused = true;
540
+ const list = new import_pi_tui.SelectList(labels.map((label) => ({ value: label, label })), Math.min(labels.length, 10), {
541
+ selectedPrefix: (text) => theme.fg("accent", text),
542
+ selectedText: (text) => theme.fg("accent", text),
543
+ description: (text) => theme.fg("muted", text),
544
+ scrollInfo: (text) => theme.fg("dim", text),
545
+ noMatch: () => theme.fg("warning", " No matching agents")
546
+ });
547
+ list.onSelect = (item) => done(item.value);
548
+ list.onCancel = () => done(undefined);
549
+ const container = new import_pi_tui.Container;
550
+ container.addChild(new import_pi_tui.Text(theme.fg("accent", title)));
551
+ container.addChild(filter);
552
+ container.addChild(list);
553
+ container.addChild(new import_pi_tui.Text(theme.fg("dim", "type to filter · ↑↓ navigate · enter select · esc cancel")));
554
+ const listKeys = [
555
+ "tui.select.up",
556
+ "tui.select.down",
557
+ "tui.select.pageUp",
558
+ "tui.select.pageDown",
559
+ "tui.select.confirm",
560
+ "tui.select.cancel"
561
+ ];
562
+ return {
563
+ render: (width) => container.render(width),
564
+ invalidate: () => container.invalidate(),
565
+ handleInput(data) {
566
+ if (listKeys.some((key) => keybindings.matches(data, key))) {
567
+ list.handleInput(data);
568
+ } else {
569
+ filter.handleInput(data);
570
+ list.setFilter(filter.getValue());
571
+ }
572
+ tui.requestRender();
573
+ }
574
+ };
575
+ }) : await ctx.ui.select(title, labels);
576
+ return choice === undefined ? undefined : agents[labels.indexOf(choice)];
577
+ }
578
+ async function chooseEnvironment(ctx, api, agentId, accountId) {
579
+ const deployments = await api.listDeployments(agentId);
580
+ if (deployments.length === 1) {
581
+ return deployments[0].environment_id;
582
+ }
583
+ const current = deployments.filter((deployment) => deployment.current_version_id !== null);
584
+ if (current.length === 1) {
585
+ return current[0].environment_id;
586
+ }
587
+ const environments = await api.listEnvironments(accountId);
588
+ const candidates = deployments.length > 0 ? environments.filter((environment) => deployments.some((deployment) => deployment.environment_id === environment.id)) : environments;
589
+ if (candidates.length === 0) {
590
+ throw new Error("The account has no environments. Create one in Prefactor first.");
591
+ }
592
+ if (candidates.length === 1) {
593
+ return candidates[0].id;
594
+ }
595
+ const labels = candidates.map((environment) => `${environment.name} (${environment.id})`);
596
+ const choice = await ctx.ui.select("Which environment should pi report to?", labels);
597
+ return choice === undefined ? undefined : candidates[labels.indexOf(choice)].id;
598
+ }
599
+ async function checkDeploymentToken(host, apiUrl, token, agentId) {
600
+ const details = await new PrefactorApi(host.createClient(apiUrl, token)).ping();
601
+ if (details.token_type !== DEPLOYMENT_TOKEN_TYPE || details.agent_id !== agentId) {
602
+ throw new Error("The new deployment token did not pass its check.");
603
+ }
604
+ }
605
+ async function revokeAccountToken(ctx, api) {
606
+ try {
607
+ const { api_token_id: tokenId } = await api.ping();
608
+ if (!tokenId) {
609
+ throw new Error("ping returned no api_token_id");
610
+ }
611
+ await api.revokeToken(tokenId);
612
+ } catch (error) {
613
+ ctx.ui.notify(`Could not revoke the sign-in token (${describe(error)}). Revoke it under Account settings in Prefactor.`, "warning");
614
+ }
615
+ }
616
+ async function setupWithPastedToken(ctx, host, apiUrl) {
617
+ ctx.ui.notify("The token you paste is visible on screen.", "warning");
618
+ const token = (await ctx.ui.input("Paste an agent-deployment token"))?.trim();
619
+ if (!token) {
620
+ return false;
621
+ }
622
+ const details = await new PrefactorApi(host.createClient(apiUrl, token)).ping();
623
+ if (details.token_type !== DEPLOYMENT_TOKEN_TYPE || !details.agent_id) {
624
+ throw new Error("That is not an agent-deployment token.");
625
+ }
626
+ await writeCredentialsFile({
627
+ api_url: apiUrl,
628
+ api_token: token,
629
+ agent_id: details.agent_id,
630
+ ...details.environment_id ? { environment_id: details.environment_id } : {},
631
+ ...details.account_id ? { account_id: details.account_id } : {},
632
+ created_at: new Date().toISOString()
633
+ });
634
+ ctx.ui.notify(`Connected pi to the Prefactor agent ${details.agent_id}.`, "info");
635
+ return true;
636
+ }
637
+ async function status(ctx, host) {
638
+ const recording = host.getRecording();
639
+ const credentials = await host.resolveCredentials();
640
+ const file = credentials?.source === "file" ? await readCredentialsFile() : undefined;
641
+ const lines = recording ? [
642
+ `This session records to ${recording.credentials.apiUrl}, agent ${recording.credentials.agentId ?? "(read from the token)"}, with credentials from the ${SOURCE_LABELS[recording.credentials.source]}.`,
643
+ recording.lastError ? `Last request to Prefactor failed: ${describe(recording.lastError)}` : "Last request to Prefactor succeeded."
644
+ ] : ["This session is not being recorded."];
645
+ if (credentials) {
646
+ lines.push(`New sessions use credentials from the ${SOURCE_LABELS[credentials.source]}${credentials.source === "file" ? ` (${getCredentialsFilePath()})` : ""}:`, ` API URL: ${credentials.apiUrl}`, ...file?.account_name || file?.account_id ? [` Account: ${file.account_name ?? file.account_id}`] : [], ` Agent: ${file?.agent_name ?? credentials.agentId ?? "(read from the token)"}`);
647
+ } else {
648
+ lines.push("Prefactor is not set up. Run /prefactor setup to connect pi to Prefactor.");
649
+ }
650
+ ctx.ui.notify(lines.join(`
651
+ `), "info");
652
+ }
653
+ async function logout(ctx, host) {
654
+ const deleted = await deleteCredentialsFile();
655
+ const remaining = await host.resolveCredentials();
656
+ const message = [
657
+ deleted ? `Deleted ${getCredentialsFilePath()}.` : `There is no credentials file at ${getCredentialsFilePath()}.`,
658
+ ...remaining ? [`Credentials from the ${SOURCE_LABELS[remaining.source]} are unaffected.`] : [],
659
+ ...host.getRecording() ? ["This session keeps recording until it ends."] : []
660
+ ];
661
+ ctx.ui.notify(message.join(" "), "info");
662
+ }
663
+ function describe(error) {
664
+ return error instanceof Error ? error.message : String(error);
665
+ }
666
+
667
+ // packages/pi/src/prefactor-session.ts
668
+ var import_core = require("@prefactor/core");
669
+ var logger = import_core.getLogger("pi");
670
+ var RETRY_ON_STATUS_CODES = [429, ...Array.from({ length: 100 }, (_, index) => 500 + index)];
671
+ var DEFAULT_SHUTDOWN_TIMEOUT_MS = 1e4;
672
+ function createHttpClient(apiUrl, apiToken, sdkHeaderEntry) {
673
+ const config = {
674
+ apiUrl,
675
+ apiToken,
676
+ agentIdentifier: "pi",
677
+ requestTimeout: 30000,
678
+ maxRetries: 3,
679
+ initialRetryDelay: 1000,
680
+ maxRetryDelay: 1e4,
681
+ retryMultiplier: 2,
682
+ retryOnStatusCodes: RETRY_ON_STATUS_CODES
683
+ };
684
+ return new import_core.HttpClient(config, {}, sdkHeaderEntry);
685
+ }
686
+ async function fetchAgentId(client) {
687
+ const response = await client.request("/api/v1/ping", { method: "GET" });
688
+ const agentId = response.details?.agent_id;
689
+ if (!agentId) {
690
+ throw new Error("GET /api/v1/ping did not return an agent_id for this token");
691
+ }
692
+ return agentId;
693
+ }
694
+
695
+ class PrefactorSession {
696
+ instanceClient;
697
+ spanClient;
698
+ instanceId;
699
+ tail = Promise.resolve();
700
+ onError;
701
+ shutdownTimeoutMs;
702
+ errorReported = false;
703
+ startState = "pending";
704
+ finished = false;
705
+ lastError = null;
706
+ constructor(options, httpClient) {
707
+ const client = this.trackRequests(httpClient ?? createHttpClient(options.apiUrl, options.apiToken, options.sdkHeaderEntry));
708
+ this.instanceClient = new import_core.AgentInstanceClient(client);
709
+ this.spanClient = new import_core.AgentSpanClient(client);
710
+ this.onError = options.onError;
711
+ this.shutdownTimeoutMs = options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;
712
+ const startedAt = new Date().toISOString();
713
+ this.instanceId = this.enqueue(async () => {
714
+ const registerPayload = {
715
+ agent_id: options.agentId ?? await fetchAgentId(client),
716
+ agent_version: {
717
+ ...options.agentVersion,
718
+ runtime_environment: import_core.buildRuntimeEnvironment(options.sdkHeaderEntry)
719
+ },
720
+ agent_schema_version: options.agentSchemaVersion,
721
+ ...options.externalIdentifier !== undefined ? { external_identifier: options.externalIdentifier } : {}
722
+ };
723
+ const response = await this.instanceClient.register(registerPayload);
724
+ const id = response.details.id;
725
+ await this.instanceClient.start(id, { timestamp: startedAt });
726
+ return id;
727
+ });
728
+ this.instanceId.then((id) => {
729
+ this.startState = id === null ? "failed" : "started";
730
+ });
731
+ }
732
+ getStartState() {
733
+ return this.startState;
734
+ }
735
+ async whenStartSettled() {
736
+ return await this.instanceId !== null;
737
+ }
738
+ getLastError() {
739
+ return this.lastError;
740
+ }
741
+ startSpan(options) {
742
+ const startedAt = options.startedAt ?? Date.now();
743
+ return {
744
+ startedAt,
745
+ id: this.enqueue(() => this.createSpan({
746
+ ...options,
747
+ startedAt,
748
+ status: "active",
749
+ finishedAt: null,
750
+ resultPayload: undefined
751
+ }))
752
+ };
753
+ }
754
+ recordSpan(options) {
755
+ const startedAt = options.startedAt ?? Date.now();
756
+ return { startedAt, id: this.enqueue(() => this.createSpan({ ...options, startedAt })) };
757
+ }
758
+ finishSpan(span, status2, resultPayload, finishedAt = Date.now()) {
759
+ const timestamp = new Date(Math.max(finishedAt, span.startedAt)).toISOString();
760
+ this.enqueue(async () => {
761
+ const id = await span.id;
762
+ if (!id) {
763
+ return;
764
+ }
765
+ await this.spanClient.finish(id, timestamp, {
766
+ status: status2,
767
+ result_payload: resultPayload
768
+ });
769
+ });
770
+ }
771
+ recordQuality(name, payload) {
772
+ const sent = snapshot(payload);
773
+ this.enqueue(async () => {
774
+ const instanceId = await this.instanceId;
775
+ if (instanceId) {
776
+ await this.instanceClient.recordQuality(instanceId, { name, payload: sent });
777
+ }
778
+ });
779
+ }
780
+ raiseAlert(name, severity, payload) {
781
+ const raisedAt = new Date().toISOString();
782
+ const sent = snapshot(payload);
783
+ this.enqueue(async () => {
784
+ const instanceId = await this.instanceId;
785
+ if (instanceId) {
786
+ await this.instanceClient.raiseAlert(instanceId, {
787
+ name,
788
+ severity,
789
+ payload: sent,
790
+ raised_at: raisedAt
791
+ });
792
+ }
793
+ });
794
+ }
795
+ async finish(status2 = "complete") {
796
+ if (this.finished) {
797
+ return;
798
+ }
799
+ this.finished = true;
800
+ const timestamp = new Date().toISOString();
801
+ const sent = this.enqueue(async () => {
802
+ const instanceId = await this.instanceId;
803
+ if (instanceId) {
804
+ await this.instanceClient.finish(instanceId, { status: status2, timestamp });
805
+ }
806
+ return true;
807
+ });
808
+ let timer;
809
+ const timedOut = new Promise((resolve) => {
810
+ timer = setTimeout(() => resolve(false), this.shutdownTimeoutMs);
811
+ timer.unref?.();
812
+ });
813
+ try {
814
+ if (await Promise.race([sent, timedOut]) === false) {
815
+ logger.debug(`Stopped waiting for Prefactor requests after ${this.shutdownTimeoutMs} ms at shutdown`);
816
+ }
817
+ } finally {
818
+ clearTimeout(timer);
819
+ }
820
+ }
821
+ async flush() {
822
+ await this.tail;
823
+ }
824
+ async createSpan(options) {
825
+ const instanceId = await this.instanceId;
826
+ const parentId = options.parent ? await options.parent.id : null;
827
+ if (!instanceId || options.parent && !parentId) {
828
+ return null;
829
+ }
830
+ const response = await this.spanClient.create({
831
+ details: {
832
+ agent_instance_id: instanceId,
833
+ schema_name: options.schemaName,
834
+ status: options.status,
835
+ payload: options.payload,
836
+ ...options.resultPayload ? { result_payload: options.resultPayload } : {},
837
+ parent_span_id: parentId,
838
+ started_at: new Date(options.startedAt ?? Date.now()).toISOString(),
839
+ finished_at: options.finishedAt === null ? null : new Date(options.finishedAt).toISOString()
840
+ }
841
+ });
842
+ return response.details.id;
843
+ }
844
+ enqueue(operation) {
845
+ const promise = this.tail.then(operation).then((value) => value, (error) => {
846
+ this.lastError = error;
847
+ logger.debug("Prefactor request failed", error);
848
+ if (!this.errorReported) {
849
+ this.errorReported = true;
850
+ try {
851
+ this.onError?.(error);
852
+ } catch (callbackError) {
853
+ logger.debug("Prefactor onError callback failed", callbackError);
854
+ }
855
+ }
856
+ return null;
857
+ });
858
+ this.tail = promise;
859
+ return promise;
860
+ }
861
+ trackRequests(client) {
862
+ return {
863
+ request: async (...args) => {
864
+ try {
865
+ const response = await client.request(...args);
866
+ this.lastError = null;
867
+ return response;
868
+ } catch (error) {
869
+ this.lastError = error;
870
+ throw error;
871
+ }
872
+ }
873
+ };
874
+ }
875
+ }
876
+ function snapshot(payload) {
877
+ return import_core.serializeValue(payload, null);
878
+ }
879
+
880
+ // packages/pi/src/recorder.ts
881
+ var import_core2 = require("@prefactor/core");
882
+ var logger2 = import_core2.getLogger("pi");
883
+ function createRecorder(session, tracer) {
884
+ let stopped = false;
885
+ let finishStatus = "complete";
886
+ const handles = new WeakMap;
887
+ const run = (name, action) => {
888
+ if (stopped) {
889
+ logger2.warn(`Prefactor ${name} called after the pi session shut down; nothing recorded`);
890
+ return;
891
+ }
892
+ try {
893
+ action();
894
+ } catch (error) {
895
+ logger2.warn(`Prefactor ${name} failed`, error);
896
+ }
897
+ };
898
+ const recorder = {
899
+ startSpan(options) {
900
+ let handle;
901
+ run("startSpan", () => {
902
+ const parent = options.parent;
903
+ handle = tracer.startCustomSpan({
904
+ schemaName: options.schemaName,
905
+ payload: options.payload ?? {},
906
+ ...parent && "toolCallId" in parent ? { toolCallId: parent.toolCallId } : { parent: parent ? handles.get(parent) : undefined }
907
+ });
908
+ });
909
+ const finish = (status2, result = {}) => run(status2 === "complete" ? "complete" : "fail", () => {
910
+ if (handle) {
911
+ tracer.finishCustomSpan(handle, status2, result);
912
+ }
913
+ });
914
+ const span = {
915
+ complete: (result) => finish("complete", result),
916
+ fail: (result) => finish("failed", result)
917
+ };
918
+ if (handle) {
919
+ handles.set(span, handle);
920
+ }
921
+ return span;
922
+ },
923
+ recordQuality(name, payload) {
924
+ run("recordQuality", () => session.recordQuality(name, payload));
925
+ },
926
+ raiseAlert(name, severity, payload) {
927
+ run("raiseAlert", () => session.raiseAlert(name, severity, payload));
928
+ },
929
+ setFinishStatus(status2) {
930
+ run("setFinishStatus", () => {
931
+ finishStatus = status2;
932
+ });
933
+ }
934
+ };
935
+ return {
936
+ recorder,
937
+ stop: () => {
938
+ stopped = true;
939
+ },
940
+ finishStatus: () => finishStatus
941
+ };
942
+ }
943
+
944
+ // packages/pi/src/data-risk.ts
945
+ function createDataCategories(classification, value) {
946
+ return {
947
+ classification,
948
+ personal_identifiers: value,
949
+ contact_information: value,
950
+ financial_information: value,
951
+ health_and_medical: value,
952
+ criminal_justice: value,
953
+ authentication_and_secrets: value,
954
+ organisational_confidential: value,
955
+ minors_data: value,
956
+ location_and_tracking: value,
957
+ behavioural_and_inferred: value,
958
+ gdpr_racial_or_ethnic_origin: value,
959
+ gdpr_political_opinions: value,
960
+ gdpr_religious_or_philosophical_beliefs: value,
961
+ gdpr_trade_union_membership: value,
962
+ gdpr_genetic_data: value,
963
+ gdpr_biometric_for_identification: value,
964
+ gdpr_sex_life_or_sexual_orientation: value
965
+ };
966
+ }
967
+ var UNKNOWN_ACTIONS = {
968
+ create_data: "unknown",
969
+ read_data: "unknown",
970
+ update_data: "unknown",
971
+ destroy_data: "unknown",
972
+ financial_transactions: "disallowed",
973
+ external_communication: "unknown"
974
+ };
975
+ var FILE_DATA_CATEGORIES = {
976
+ ...createDataCategories("confidential", "excluded"),
977
+ authentication_and_secrets: "included",
978
+ organisational_confidential: "included"
979
+ };
980
+ var SHELL_DATA_CATEGORIES = {
981
+ ...createDataCategories("restricted", "excluded"),
982
+ authentication_and_secrets: "included",
983
+ organisational_confidential: "included"
984
+ };
985
+ var CONFIDENTIAL_CONTENT_RISK = {
986
+ action_profile: UNKNOWN_ACTIONS,
987
+ params_data_categories: createDataCategories("confidential", "unknown"),
988
+ result_data_categories: createDataCategories("confidential", "unknown")
989
+ };
990
+ var MODEL_OUTPUT_RISK = {
991
+ action_profile: { ...UNKNOWN_ACTIONS, create_data: "allowed" },
992
+ params_data_categories: createDataCategories("confidential", "unknown"),
993
+ result_data_categories: createDataCategories("internal", "unknown")
994
+ };
995
+ var UNKNOWN_TOOL_RISK = {
996
+ action_profile: UNKNOWN_ACTIONS,
997
+ params_data_categories: createDataCategories("unknown", "unknown"),
998
+ result_data_categories: createDataCategories("unknown", "unknown")
999
+ };
1000
+ var DEFAULT_SPAN_TYPE_RISK = {
1001
+ "pi:session": {
1002
+ action_profile: { ...UNKNOWN_ACTIONS, create_data: "allowed" },
1003
+ params_data_categories: createDataCategories("internal", "unknown"),
1004
+ result_data_categories: createDataCategories("internal", "unknown")
1005
+ },
1006
+ "$agent:system_message": CONFIDENTIAL_CONTENT_RISK,
1007
+ "$agent:user_turn": CONFIDENTIAL_CONTENT_RISK,
1008
+ "$agent:user_message": CONFIDENTIAL_CONTENT_RISK,
1009
+ "$agent:assistant_turn": MODEL_OUTPUT_RISK,
1010
+ "$agent:llm_call": MODEL_OUTPUT_RISK,
1011
+ "$agent:assistant_message": MODEL_OUTPUT_RISK,
1012
+ "$agent:assistant_thinking": MODEL_OUTPUT_RISK,
1013
+ "$agent:tool:read": {
1014
+ action_profile: {
1015
+ create_data: "disallowed",
1016
+ read_data: "allowed",
1017
+ update_data: "disallowed",
1018
+ destroy_data: "disallowed",
1019
+ financial_transactions: "disallowed",
1020
+ external_communication: "disallowed"
1021
+ },
1022
+ params_data_categories: FILE_DATA_CATEGORIES,
1023
+ result_data_categories: FILE_DATA_CATEGORIES
1024
+ },
1025
+ "$agent:tool:write": {
1026
+ action_profile: {
1027
+ create_data: "allowed",
1028
+ read_data: "disallowed",
1029
+ update_data: "disallowed",
1030
+ destroy_data: "disallowed",
1031
+ financial_transactions: "disallowed",
1032
+ external_communication: "disallowed"
1033
+ },
1034
+ params_data_categories: { ...FILE_DATA_CATEGORIES, authentication_and_secrets: "unknown" },
1035
+ result_data_categories: { ...FILE_DATA_CATEGORIES, authentication_and_secrets: "unknown" }
1036
+ },
1037
+ "$agent:tool:edit": {
1038
+ action_profile: {
1039
+ create_data: "disallowed",
1040
+ read_data: "disallowed",
1041
+ update_data: "allowed",
1042
+ destroy_data: "disallowed",
1043
+ financial_transactions: "disallowed",
1044
+ external_communication: "disallowed"
1045
+ },
1046
+ params_data_categories: FILE_DATA_CATEGORIES,
1047
+ result_data_categories: FILE_DATA_CATEGORIES
1048
+ },
1049
+ "$agent:tool:bash": {
1050
+ action_profile: {
1051
+ create_data: "unknown",
1052
+ read_data: "allowed",
1053
+ update_data: "unknown",
1054
+ destroy_data: "unknown",
1055
+ financial_transactions: "disallowed",
1056
+ external_communication: "disallowed"
1057
+ },
1058
+ params_data_categories: SHELL_DATA_CATEGORIES,
1059
+ result_data_categories: SHELL_DATA_CATEGORIES
1060
+ }
1061
+ };
1062
+
1063
+ // packages/pi/src/tool-definitions.ts
1064
+ var TOOL_STATUS_SUFFIX = "{% if error %} (error){% endif %}";
1065
+ var SUPPORTED_TOOL_DEFINITIONS = {
1066
+ read: {
1067
+ description: "Read file contents from the filesystem",
1068
+ inputSchema: {
1069
+ type: "object",
1070
+ properties: {
1071
+ path: { type: "string", description: "Path to the file to read" },
1072
+ offset: { type: "number", description: "Line number to start reading from (1-indexed)" },
1073
+ limit: { type: "number", description: "Maximum number of lines to read" }
1074
+ },
1075
+ required: ["path"]
1076
+ },
1077
+ template: `read: {{ params.path | default: "(unknown file)" }}{% if params.offset %}:{{ params.offset }}{% endif %}{% if params.limit %} (limit {{ params.limit }}){% endif %}${TOOL_STATUS_SUFFIX}`
1078
+ },
1079
+ write: {
1080
+ description: "Write or create files on the filesystem",
1081
+ inputSchema: {
1082
+ type: "object",
1083
+ properties: {
1084
+ path: { type: "string", description: "Path to the file to write" },
1085
+ content: { type: "string", description: "Content to write to the file" }
1086
+ },
1087
+ required: ["path", "content"]
1088
+ },
1089
+ template: `write: {{ params.path | default: "(unknown file)" }}${TOOL_STATUS_SUFFIX}`
1090
+ },
1091
+ edit: {
1092
+ description: "Replace targeted text in a file",
1093
+ inputSchema: {
1094
+ type: "object",
1095
+ properties: {
1096
+ path: { type: "string", description: "Path to the file to edit" },
1097
+ edits: {
1098
+ type: "array",
1099
+ description: "Targeted replacements to apply",
1100
+ items: {
1101
+ type: "object",
1102
+ properties: {
1103
+ oldText: { type: "string", description: "Text to find" },
1104
+ newText: { type: "string", description: "Replacement text" }
1105
+ }
1106
+ }
1107
+ }
1108
+ },
1109
+ required: ["path"]
1110
+ },
1111
+ template: `edit: {{ params.path | default: "(unknown file)" }}{% if params.edits %} ({{ params.edits | size }} edits){% endif %}${TOOL_STATUS_SUFFIX}`
1112
+ },
1113
+ bash: {
1114
+ description: "Execute a shell command",
1115
+ inputSchema: {
1116
+ type: "object",
1117
+ properties: {
1118
+ command: { type: "string", description: "Shell command to execute" },
1119
+ timeout: { type: "number", description: "Timeout in seconds" }
1120
+ },
1121
+ required: ["command"]
1122
+ },
1123
+ template: `bash: \`{% assign cmd = params.command | default: "(no command)" %}{% if cmd.size > 60 %}{{ cmd | slice: 0, 60 }}...{% else %}{{ cmd }}{% endif %}\`${TOOL_STATUS_SUFFIX}`
1124
+ }
1125
+ };
1126
+
1127
+ // packages/pi/src/version.ts
1128
+ var PACKAGE_NAME = "@prefactor/pi";
1129
+ var PACKAGE_VERSION = "0.1.0";
1130
+
1131
+ // packages/pi/src/schema.ts
1132
+ var AGENT_SPAN_VERSION = 1;
1133
+ var TOOL_SPAN_PREFIX = "$agent:tool:";
1134
+ var FALLBACK_TOOL_SPAN_TYPE = `${TOOL_SPAN_PREFIX}pi:other`;
1135
+ function isReservedSpanType(name) {
1136
+ return name === "pi:session" || name.startsWith("$agent:");
1137
+ }
1138
+ function versioned(properties, required = Object.keys(properties)) {
1139
+ return {
1140
+ type: "object",
1141
+ properties: { _version: { const: AGENT_SPAN_VERSION }, ...properties },
1142
+ required: ["_version", ...required]
1143
+ };
1144
+ }
1145
+ var EMPTY_RESULT = versioned({});
1146
+ var TEXT_PARAMS = versioned({ text: { type: "string" } });
1147
+ var USAGE_SCHEMA = versioned({
1148
+ input_tokens: { type: "integer", minimum: 0 },
1149
+ output_tokens: { type: "integer", minimum: 0 },
1150
+ cache_read_input_tokens: { type: "integer", minimum: 0 },
1151
+ cache_creation_input_tokens: { type: "integer", minimum: 0 },
1152
+ reasoning_tokens: { type: "integer", minimum: 0 },
1153
+ total_tokens: { type: "integer", minimum: 0 }
1154
+ }, []);
1155
+ var COST_SCHEMA = {
1156
+ type: "object",
1157
+ description: "Cost reported by pi, in US dollars",
1158
+ properties: {
1159
+ input: { type: "number" },
1160
+ output: { type: "number" },
1161
+ cache_read: { type: "number" },
1162
+ cache_write: { type: "number" },
1163
+ total: { type: "number" }
1164
+ }
1165
+ };
1166
+ function toolSchema(tool, options = {}) {
1167
+ const spanType = `${TOOL_SPAN_PREFIX}${tool.name}`;
1168
+ const definition = Object.hasOwn(SUPPORTED_TOOL_DEFINITIONS, tool.name) ? SUPPORTED_TOOL_DEFINITIONS[tool.name] : undefined;
1169
+ return {
1170
+ name: spanType,
1171
+ title: options.title ?? tool.name,
1172
+ description: options.description ?? definition?.description ?? tool.description ?? `The ${tool.name} tool`,
1173
+ template: options.template ?? definition?.template ?? `${tool.name}{% if error %} (error){% endif %}`,
1174
+ params_schema: versioned({
1175
+ tool_use_id: { type: "string", description: "Tool call id assigned by the model" },
1176
+ params: options.params_schema ?? definition?.inputSchema ?? { type: "object" }
1177
+ }),
1178
+ result_schema: versioned({
1179
+ result: {
1180
+ type: "object",
1181
+ properties: {
1182
+ content: { type: "array", description: "Content returned to the model" },
1183
+ details: options.result_schema ?? {
1184
+ description: "Structured details returned by the tool"
1185
+ }
1186
+ }
1187
+ },
1188
+ error: { type: "string" }
1189
+ }, []),
1190
+ data_risk: options.data_risk ?? DEFAULT_SPAN_TYPE_RISK[spanType] ?? UNKNOWN_TOOL_RISK
1191
+ };
1192
+ }
1193
+ function registeredToolNames(tools, toolSchemas = {}) {
1194
+ return [...new Set([...tools.map((tool) => tool.name), ...Object.keys(toolSchemas)])];
1195
+ }
1196
+ function buildAgentSchemaVersion(tools, extensions = {}) {
1197
+ const toolSchemas = registeredToolNames(tools, extensions.toolSchemas).map((name) => toolSchema(tools.find((tool) => tool.name === name) ?? { name }, extensions.toolSchemas?.[name]));
1198
+ return {
1199
+ external_identifier: `prefactor-pi-${PACKAGE_VERSION}`,
1200
+ span_type_schemas: [
1201
+ {
1202
+ name: "pi:session",
1203
+ title: "pi session",
1204
+ description: "One pi session, from session start to shutdown",
1205
+ template: 'pi session in {{ cwd | default: "(unknown directory)" }}',
1206
+ params_schema: {
1207
+ type: "object",
1208
+ properties: {
1209
+ session_id: { type: "string" },
1210
+ cwd: { type: "string", description: "Working directory of the session" },
1211
+ mode: { type: "string", description: "pi run mode: tui, rpc, json or print" },
1212
+ reason: { type: "string", description: "Why the session started" },
1213
+ provider: { type: "string" },
1214
+ model: { type: "string" }
1215
+ },
1216
+ required: ["session_id", "cwd"]
1217
+ },
1218
+ result_schema: {
1219
+ type: "object",
1220
+ properties: { reason: { type: "string", description: "Why the session shut down" } }
1221
+ },
1222
+ data_risk: DEFAULT_SPAN_TYPE_RISK["pi:session"]
1223
+ },
1224
+ {
1225
+ name: "$agent:system_message",
1226
+ title: "System message",
1227
+ description: "The system prompt, recorded when a run starts with a changed prompt",
1228
+ template: "System message: {{ text }}",
1229
+ params_schema: TEXT_PARAMS,
1230
+ result_schema: EMPTY_RESULT,
1231
+ data_risk: DEFAULT_SPAN_TYPE_RISK["$agent:system_message"]
1232
+ },
1233
+ {
1234
+ name: "$agent:user_turn",
1235
+ title: "User turn",
1236
+ description: "One user turn",
1237
+ template: "User turn {{ turn }}",
1238
+ params_schema: versioned({
1239
+ turn: { type: "integer", description: "Number of the user turn in this session" }
1240
+ }),
1241
+ result_schema: EMPTY_RESULT,
1242
+ data_risk: DEFAULT_SPAN_TYPE_RISK["$agent:user_turn"]
1243
+ },
1244
+ {
1245
+ name: "$agent:user_message",
1246
+ title: "User message",
1247
+ description: "A user message: a prompt, steering message or follow-up message",
1248
+ template: "User message: {{ text }}",
1249
+ params_schema: TEXT_PARAMS,
1250
+ result_schema: EMPTY_RESULT,
1251
+ data_risk: DEFAULT_SPAN_TYPE_RISK["$agent:user_message"]
1252
+ },
1253
+ {
1254
+ name: "$agent:assistant_turn",
1255
+ title: "Assistant turn",
1256
+ description: "The assistant responses and tool calls that follow a user turn",
1257
+ template: "Assistant turn{% if stop_reason %} -> {{ stop_reason }}{% endif %}",
1258
+ params_schema: versioned({}),
1259
+ result_schema: versioned({ stop_reason: { type: "string" }, usage: USAGE_SCHEMA }, []),
1260
+ data_risk: DEFAULT_SPAN_TYPE_RISK["$agent:assistant_turn"]
1261
+ },
1262
+ {
1263
+ name: "$agent:llm_call",
1264
+ title: "LLM call",
1265
+ description: "One LLM response",
1266
+ template: "{{ request.provider_name }}/{{ request.model }}{% if response.stop_reason %} -> {{ response.stop_reason }}{% endif %}{% if response.usage.total_tokens %} ({{ response.usage.total_tokens }} tokens){% endif %}",
1267
+ params_schema: versioned({
1268
+ request: versioned({
1269
+ model: { type: "string" },
1270
+ provider_name: { type: "string" },
1271
+ api: { type: "string", description: "pi API used to call the provider" }
1272
+ }, ["model", "provider_name"])
1273
+ }),
1274
+ result_schema: versioned({
1275
+ response: versioned({
1276
+ id: { type: "string" },
1277
+ model: { type: "string", description: "Model that answered" },
1278
+ provider_name: { type: "string" },
1279
+ stop_reason: { type: "string" },
1280
+ usage: USAGE_SCHEMA,
1281
+ cost: COST_SCHEMA,
1282
+ timestamp_started: { type: "string", format: "date-time" },
1283
+ timestamp_completed: { type: "string", format: "date-time" }
1284
+ }, ["model", "provider_name"]),
1285
+ error: { type: "string" }
1286
+ }, []),
1287
+ data_risk: DEFAULT_SPAN_TYPE_RISK["$agent:llm_call"]
1288
+ },
1289
+ {
1290
+ name: "$agent:assistant_message",
1291
+ title: "Assistant message",
1292
+ description: "Assistant text produced by the model",
1293
+ template: "Assistant message: {{ text }}",
1294
+ params_schema: TEXT_PARAMS,
1295
+ result_schema: EMPTY_RESULT,
1296
+ data_risk: DEFAULT_SPAN_TYPE_RISK["$agent:assistant_message"]
1297
+ },
1298
+ {
1299
+ name: "$agent:assistant_thinking",
1300
+ title: "Assistant thinking",
1301
+ description: "Model reasoning",
1302
+ template: "Thinking: {{ text }}",
1303
+ params_schema: versioned({
1304
+ text: { type: "string" },
1305
+ type: { type: "string", enum: ["opaque", "transparent"] }
1306
+ }),
1307
+ result_schema: EMPTY_RESULT,
1308
+ data_risk: DEFAULT_SPAN_TYPE_RISK["$agent:assistant_thinking"]
1309
+ },
1310
+ ...toolSchemas,
1311
+ {
1312
+ ...toolSchema({ name: "pi:other" }),
1313
+ title: "Other tool",
1314
+ description: "Execution of a pi tool added after the session started",
1315
+ template: '{{ tool_name | default: "(unknown tool)" }}{% if error %} (error){% endif %}',
1316
+ params_schema: versioned({
1317
+ tool_use_id: { type: "string", description: "Tool call id assigned by the model" },
1318
+ tool_name: { type: "string", description: "Name of the pi tool" },
1319
+ params: { type: "object" }
1320
+ })
1321
+ },
1322
+ ...extensions.spanTypeSchemas ?? []
1323
+ ],
1324
+ ...extensions.qualitySchemas?.length ? { quality_schemas: extensions.qualitySchemas } : {},
1325
+ ...extensions.alertSchemas?.length ? { alert_schemas: extensions.alertSchemas } : {}
1326
+ };
1327
+ }
1328
+
1329
+ // packages/pi/src/session-tracer.ts
1330
+ var import_core3 = require("@prefactor/core");
1331
+ class SessionTracer {
1332
+ session;
1333
+ limits;
1334
+ sessionSpan = null;
1335
+ assistantTurn = null;
1336
+ userTurns = 0;
1337
+ recordedSystemPrompt = null;
1338
+ toolNames = new Set;
1339
+ lastTimestamp = 0;
1340
+ toolSpans = new Map;
1341
+ customSpans = new Set;
1342
+ constructor(session, limits) {
1343
+ this.session = session;
1344
+ this.limits = limits;
1345
+ }
1346
+ sessionStart(info) {
1347
+ this.toolNames = new Set(info.toolNames);
1348
+ this.sessionSpan = this.session.startSpan({
1349
+ schemaName: "pi:session",
1350
+ startedAt: this.timestamp(),
1351
+ payload: {
1352
+ session_id: info.sessionId,
1353
+ cwd: info.cwd,
1354
+ mode: info.mode,
1355
+ reason: info.reason,
1356
+ ...info.provider ? { provider: info.provider } : {},
1357
+ ...info.model ? { model: info.model } : {}
1358
+ }
1359
+ });
1360
+ }
1361
+ agentStart(systemPrompt) {
1362
+ this.endAssistantTurn("cancelled");
1363
+ if (systemPrompt === this.recordedSystemPrompt) {
1364
+ return;
1365
+ }
1366
+ this.recordedSystemPrompt = systemPrompt;
1367
+ const at = this.timestamp();
1368
+ this.session.recordSpan({
1369
+ schemaName: "$agent:system_message",
1370
+ parent: this.sessionSpan,
1371
+ startedAt: at,
1372
+ finishedAt: at,
1373
+ status: "complete",
1374
+ payload: { _version: AGENT_SPAN_VERSION, text: this.input(systemPrompt) },
1375
+ resultPayload: { _version: AGENT_SPAN_VERSION }
1376
+ });
1377
+ }
1378
+ agentEnd() {
1379
+ this.endAssistantTurn();
1380
+ }
1381
+ userMessage(message) {
1382
+ this.endAssistantTurn();
1383
+ this.userTurns += 1;
1384
+ const turnAt = this.timestamp();
1385
+ const messageAt = this.timestamp();
1386
+ const turn = this.session.recordSpan({
1387
+ schemaName: "$agent:user_turn",
1388
+ parent: this.sessionSpan,
1389
+ startedAt: turnAt,
1390
+ finishedAt: messageAt,
1391
+ status: "complete",
1392
+ payload: { _version: AGENT_SPAN_VERSION, turn: this.userTurns },
1393
+ resultPayload: { _version: AGENT_SPAN_VERSION }
1394
+ });
1395
+ this.session.recordSpan({
1396
+ schemaName: "$agent:user_message",
1397
+ parent: turn,
1398
+ startedAt: messageAt,
1399
+ finishedAt: messageAt,
1400
+ status: "complete",
1401
+ payload: { _version: AGENT_SPAN_VERSION, text: this.input(textOf(message.content)) },
1402
+ resultPayload: { _version: AGENT_SPAN_VERSION }
1403
+ });
1404
+ }
1405
+ assistantMessage(message) {
1406
+ const turn = this.openAssistantTurn(message.timestamp);
1407
+ turn.lastMessage = message;
1408
+ if (message.usage) {
1409
+ turn.usage = turn.usage ? addUsage(turn.usage, message.usage) : message.usage;
1410
+ }
1411
+ const startedAt = this.timestamp(message.timestamp);
1412
+ const finishedAt = this.timestamp(message.durationMs === undefined ? Date.now() : message.timestamp + message.durationMs);
1413
+ const status2 = statusFromStopReason(message.stopReason);
1414
+ this.session.recordSpan({
1415
+ schemaName: "$agent:llm_call",
1416
+ parent: turn.span,
1417
+ startedAt,
1418
+ finishedAt,
1419
+ status: status2,
1420
+ payload: {
1421
+ _version: AGENT_SPAN_VERSION,
1422
+ request: {
1423
+ _version: AGENT_SPAN_VERSION,
1424
+ model: message.model,
1425
+ provider_name: message.provider,
1426
+ ...message.api ? { api: message.api } : {}
1427
+ }
1428
+ },
1429
+ resultPayload: {
1430
+ _version: AGENT_SPAN_VERSION,
1431
+ response: {
1432
+ _version: AGENT_SPAN_VERSION,
1433
+ ...message.responseId ? { id: message.responseId } : {},
1434
+ model: message.responseModel ?? message.model,
1435
+ provider_name: message.provider,
1436
+ ...message.stopReason ? { stop_reason: message.stopReason } : {},
1437
+ ...message.usage ? { usage: canonicalUsage(message.usage) } : {},
1438
+ ...message.usage?.cost ? { cost: costOutputs(message.usage.cost) } : {},
1439
+ timestamp_started: new Date(startedAt).toISOString(),
1440
+ timestamp_completed: new Date(finishedAt).toISOString()
1441
+ },
1442
+ ...status2 === "failed" ? { error: message.errorMessage ?? "The model call failed." } : {}
1443
+ }
1444
+ });
1445
+ for (const block of message.content) {
1446
+ this.recordContentBlock(turn.span, block);
1447
+ }
1448
+ }
1449
+ toolStart(event) {
1450
+ const parent = (event.parentToolCallId ? this.toolSpans.get(event.parentToolCallId) : undefined) ?? this.assistantTurn?.span ?? this.sessionSpan;
1451
+ const registered = this.toolNames.has(event.toolName);
1452
+ const span = this.session.startSpan({
1453
+ schemaName: registered ? `${TOOL_SPAN_PREFIX}${event.toolName}` : FALLBACK_TOOL_SPAN_TYPE,
1454
+ parent,
1455
+ startedAt: this.timestamp(),
1456
+ payload: {
1457
+ _version: AGENT_SPAN_VERSION,
1458
+ tool_use_id: event.toolCallId,
1459
+ ...registered ? {} : { tool_name: event.toolName },
1460
+ params: this.input(event.args)
1461
+ }
1462
+ });
1463
+ this.toolSpans.set(event.toolCallId, span);
1464
+ }
1465
+ toolEnd(event) {
1466
+ const span = this.toolSpans.get(event.toolCallId);
1467
+ if (!span) {
1468
+ return;
1469
+ }
1470
+ this.toolSpans.delete(event.toolCallId);
1471
+ const result = event.result ?? {};
1472
+ if (event.isError) {
1473
+ this.session.finishSpan(span, "failed", { _version: AGENT_SPAN_VERSION, error: this.output(errorText(result.content)) }, this.timestamp());
1474
+ return;
1475
+ }
1476
+ this.session.finishSpan(span, "complete", {
1477
+ _version: AGENT_SPAN_VERSION,
1478
+ result: {
1479
+ ...result.content !== undefined ? { content: this.output(result.content) } : {},
1480
+ ...result.details !== undefined ? { details: this.output(result.details) } : {}
1481
+ }
1482
+ }, this.timestamp());
1483
+ }
1484
+ startCustomSpan(options) {
1485
+ const span = this.session.startSpan({
1486
+ schemaName: options.schemaName,
1487
+ parent: options.parent ?? (options.toolCallId ? this.toolSpans.get(options.toolCallId) : undefined) ?? this.assistantTurn?.span ?? this.sessionSpan,
1488
+ startedAt: this.timestamp(),
1489
+ payload: this.input(options.payload)
1490
+ });
1491
+ this.customSpans.add(span);
1492
+ return span;
1493
+ }
1494
+ finishCustomSpan(span, status2, result) {
1495
+ if (!this.customSpans.has(span)) {
1496
+ return;
1497
+ }
1498
+ const resultPayload = this.output(result);
1499
+ this.session.finishSpan(span, status2, resultPayload, this.timestamp());
1500
+ this.customSpans.delete(span);
1501
+ }
1502
+ sessionShutdown(reason) {
1503
+ for (const span of [...this.customSpans].reverse()) {
1504
+ this.session.finishSpan(span, "cancelled", {}, this.timestamp());
1505
+ }
1506
+ this.customSpans.clear();
1507
+ for (const span of [...this.toolSpans.values()].reverse()) {
1508
+ this.session.finishSpan(span, "cancelled", { _version: AGENT_SPAN_VERSION, error: "The session ended before the tool finished." }, this.timestamp());
1509
+ }
1510
+ this.toolSpans.clear();
1511
+ this.endAssistantTurn("cancelled");
1512
+ if (this.sessionSpan) {
1513
+ this.session.finishSpan(this.sessionSpan, "complete", { reason }, this.timestamp());
1514
+ this.sessionSpan = null;
1515
+ }
1516
+ }
1517
+ openAssistantTurn(at) {
1518
+ if (!this.assistantTurn) {
1519
+ this.assistantTurn = {
1520
+ span: this.session.startSpan({
1521
+ schemaName: "$agent:assistant_turn",
1522
+ parent: this.sessionSpan,
1523
+ startedAt: this.timestamp(at),
1524
+ payload: { _version: AGENT_SPAN_VERSION }
1525
+ }),
1526
+ lastMessage: null,
1527
+ usage: null
1528
+ };
1529
+ }
1530
+ return this.assistantTurn;
1531
+ }
1532
+ endAssistantTurn(status2) {
1533
+ const turn = this.assistantTurn;
1534
+ if (!turn) {
1535
+ return;
1536
+ }
1537
+ this.assistantTurn = null;
1538
+ const stopReason = turn.lastMessage?.stopReason;
1539
+ this.session.finishSpan(turn.span, status2 ?? statusFromStopReason(stopReason), {
1540
+ _version: AGENT_SPAN_VERSION,
1541
+ ...stopReason ? { stop_reason: stopReason } : {},
1542
+ ...turn.usage ? { usage: canonicalUsage(turn.usage) } : {}
1543
+ }, this.timestamp());
1544
+ }
1545
+ recordContentBlock(parent, block) {
1546
+ if (typeof block !== "object" || block === null) {
1547
+ return;
1548
+ }
1549
+ const part = block;
1550
+ let span = null;
1551
+ if (part.type === "text" && typeof part.text === "string" && part.text !== "") {
1552
+ span = {
1553
+ schemaName: "$agent:assistant_message",
1554
+ payload: { _version: AGENT_SPAN_VERSION, text: this.output(part.text) }
1555
+ };
1556
+ } else if (part.type === "thinking" && part.redacted === true) {
1557
+ span = {
1558
+ schemaName: "$agent:assistant_thinking",
1559
+ payload: { _version: AGENT_SPAN_VERSION, type: "opaque", text: "[redacted]" }
1560
+ };
1561
+ } else if (part.type === "thinking" && typeof part.thinking === "string" && part.thinking !== "") {
1562
+ span = {
1563
+ schemaName: "$agent:assistant_thinking",
1564
+ payload: {
1565
+ _version: AGENT_SPAN_VERSION,
1566
+ type: "transparent",
1567
+ text: this.output(part.thinking)
1568
+ }
1569
+ };
1570
+ }
1571
+ if (!span) {
1572
+ return;
1573
+ }
1574
+ const at = this.timestamp();
1575
+ this.session.recordSpan({
1576
+ ...span,
1577
+ parent,
1578
+ startedAt: at,
1579
+ finishedAt: at,
1580
+ status: "complete",
1581
+ resultPayload: { _version: AGENT_SPAN_VERSION }
1582
+ });
1583
+ }
1584
+ timestamp(at = Date.now()) {
1585
+ this.lastTimestamp = Math.max(at, this.lastTimestamp + 1);
1586
+ return this.lastTimestamp;
1587
+ }
1588
+ input(value) {
1589
+ return import_core3.serializeValue(value, this.limits.maxInputLength);
1590
+ }
1591
+ output(value) {
1592
+ return import_core3.serializeValue(value, this.limits.maxOutputLength);
1593
+ }
1594
+ }
1595
+ function statusFromStopReason(stopReason) {
1596
+ if (stopReason === "error") {
1597
+ return "failed";
1598
+ }
1599
+ if (stopReason === "aborted") {
1600
+ return "cancelled";
1601
+ }
1602
+ return "complete";
1603
+ }
1604
+ function textOf(content) {
1605
+ if (typeof content === "string") {
1606
+ return content;
1607
+ }
1608
+ if (!Array.isArray(content)) {
1609
+ return "";
1610
+ }
1611
+ return content.filter((part) => typeof part === "object" && part !== null && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("");
1612
+ }
1613
+ function errorText(content) {
1614
+ return textOf(content) || "The tool failed.";
1615
+ }
1616
+ function addUsage(total, usage) {
1617
+ const reasoning = total.reasoning === undefined && usage.reasoning === undefined ? undefined : (total.reasoning ?? 0) + (usage.reasoning ?? 0);
1618
+ return {
1619
+ input: total.input + usage.input,
1620
+ output: total.output + usage.output,
1621
+ cacheRead: total.cacheRead + usage.cacheRead,
1622
+ cacheWrite: total.cacheWrite + usage.cacheWrite,
1623
+ ...reasoning === undefined ? {} : { reasoning },
1624
+ totalTokens: total.totalTokens + usage.totalTokens
1625
+ };
1626
+ }
1627
+ function canonicalUsage(usage) {
1628
+ return {
1629
+ _version: AGENT_SPAN_VERSION,
1630
+ input_tokens: usage.input,
1631
+ output_tokens: usage.output,
1632
+ cache_read_input_tokens: usage.cacheRead,
1633
+ cache_creation_input_tokens: usage.cacheWrite,
1634
+ ...usage.reasoning !== undefined ? { reasoning_tokens: usage.reasoning } : {},
1635
+ total_tokens: usage.totalTokens
1636
+ };
1637
+ }
1638
+ function costOutputs(cost) {
1639
+ return {
1640
+ input: cost.input,
1641
+ output: cost.output,
1642
+ cache_read: cost.cacheRead,
1643
+ cache_write: cost.cacheWrite,
1644
+ total: cost.total
1645
+ };
1646
+ }
1647
+
1648
+ // packages/pi/src/extension.ts
1649
+ var logger3 = import_core4.getLogger("pi");
1650
+ var SDK_HEADER_ENTRY = `${PACKAGE_NAME}@${PACKAGE_VERSION} @earendil-works/pi-coding-agent@${import_pi_coding_agent2.VERSION}`;
1651
+ var setupNoticeShown = false;
1652
+ function prefactorExtension(options = {}) {
1653
+ const reserved = (options.spanTypeSchemas ?? []).filter((schema) => isReservedSpanType(schema.name));
1654
+ if (reserved.length > 0) {
1655
+ throw new Error(`spanTypeSchemas cannot redefine the extension's span types: ${reserved.map((schema) => schema.name).join(", ")}. Use toolSchemas to describe a tool's span type.`);
1656
+ }
1657
+ return (pi) => {
1658
+ let recording = null;
1659
+ const endRecording = () => {
1660
+ const current = recording;
1661
+ recording = null;
1662
+ current?.stopRecorder();
1663
+ return current;
1664
+ };
1665
+ const guard = (name, handler) => async (...args) => {
1666
+ try {
1667
+ await handler(...args);
1668
+ } catch (error) {
1669
+ logger3.warn(`Error handling pi ${name} event`, error);
1670
+ }
1671
+ };
1672
+ const startRecording = (ctx, reason, credentials) => {
1673
+ const config = import_core4.createConfig();
1674
+ const tools = pi.getAllTools();
1675
+ const session = new PrefactorSession({
1676
+ apiUrl: credentials.apiUrl,
1677
+ apiToken: credentials.apiToken,
1678
+ agentId: credentials.agentId,
1679
+ agentVersion: { external_identifier: options.agentVersion ?? import_pi_coding_agent2.VERSION },
1680
+ agentSchemaVersion: buildAgentSchemaVersion(tools, options),
1681
+ externalIdentifier: resolveExternalIdentifier(options.externalIdentifier, ctx),
1682
+ sdkHeaderEntry: SDK_HEADER_ENTRY,
1683
+ onError: (error) => notify(ctx, `Prefactor could not record this session: ${describe2(error)}`)
1684
+ });
1685
+ const tracer = new SessionTracer(session, {
1686
+ maxInputLength: config.maxInputLength,
1687
+ maxOutputLength: config.maxOutputLength
1688
+ });
1689
+ tracer.sessionStart({
1690
+ sessionId: ctx.sessionManager.getSessionId(),
1691
+ cwd: ctx.cwd,
1692
+ mode: ctx.mode,
1693
+ reason,
1694
+ provider: ctx.model?.provider,
1695
+ model: ctx.model?.id,
1696
+ toolNames: registeredToolNames(tools, options.toolSchemas)
1697
+ });
1698
+ const { recorder, stop, finishStatus } = createRecorder(session, tracer);
1699
+ recording = { credentials, session, tracer, stopRecorder: stop, finishStatus };
1700
+ if (options.onSessionStart) {
1701
+ const reportFailure = (error) => logger3.warn("The onSessionStart callback failed", error);
1702
+ try {
1703
+ Promise.resolve(options.onSessionStart(recorder, ctx)).catch(reportFailure);
1704
+ } catch (error) {
1705
+ reportFailure(error);
1706
+ }
1707
+ }
1708
+ };
1709
+ const replaceRecording = async (ctx) => {
1710
+ endRecording();
1711
+ const credentials = await resolveCredentials(options);
1712
+ if (credentials) {
1713
+ startRecording(ctx, "setup", credentials);
1714
+ }
1715
+ };
1716
+ pi.on("session_start", guard("session_start", async (event, ctx) => {
1717
+ const credentials = await loadCredentials(options, ctx);
1718
+ if (credentials) {
1719
+ startRecording(ctx, event.reason, credentials);
1720
+ }
1721
+ }));
1722
+ registerPrefactorCommand(pi, {
1723
+ resolveCredentials: () => resolveCredentials(options),
1724
+ getRecording: () => recording ? {
1725
+ credentials: recording.credentials,
1726
+ lastError: recording.session.getLastError(),
1727
+ startState: recording.session.getStartState()
1728
+ } : null,
1729
+ startRecording: async (ctx) => {
1730
+ const current = recording;
1731
+ const state = current?.session.getStartState();
1732
+ if (!current || state === "failed") {
1733
+ await replaceRecording(ctx);
1734
+ return;
1735
+ }
1736
+ if (state === "pending") {
1737
+ current.session.whenStartSettled().then(async (started) => {
1738
+ if (!started && recording === current) {
1739
+ await replaceRecording(ctx);
1740
+ }
1741
+ }).catch((error) => logger3.warn("Could not start recording with the saved credentials", error));
1742
+ }
1743
+ },
1744
+ createClient: (apiUrl, apiToken) => createHttpClient(apiUrl, apiToken, SDK_HEADER_ENTRY),
1745
+ clientVersion: `${PACKAGE_NAME}@${PACKAGE_VERSION}`
1746
+ });
1747
+ pi.on("agent_start", guard("agent_start", (_event, ctx) => recording?.tracer.agentStart(ctx.getSystemPrompt())));
1748
+ pi.on("agent_end", guard("agent_end", () => recording?.tracer.agentEnd()));
1749
+ pi.on("message_end", guard("message_end", (event) => {
1750
+ if (event.message.role === "user") {
1751
+ recording?.tracer.userMessage(event.message);
1752
+ } else if (event.message.role === "assistant") {
1753
+ recording?.tracer.assistantMessage(event.message);
1754
+ }
1755
+ }));
1756
+ pi.on("tool_execution_start", guard("tool_execution_start", (event) => recording?.tracer.toolStart(event)));
1757
+ pi.on("tool_execution_end", guard("tool_execution_end", (event) => recording?.tracer.toolEnd(event)));
1758
+ pi.on("session_shutdown", guard("session_shutdown", async (event) => {
1759
+ const current = endRecording();
1760
+ current?.tracer.sessionShutdown(event.reason);
1761
+ await current?.session.finish(current.finishStatus());
1762
+ }));
1763
+ };
1764
+ }
1765
+ function resolveExternalIdentifier(option, ctx) {
1766
+ if (typeof option !== "function") {
1767
+ return option;
1768
+ }
1769
+ try {
1770
+ return option(ctx);
1771
+ } catch (error) {
1772
+ logger3.warn("The externalIdentifier callback failed; the session has no external identifier", error);
1773
+ return;
1774
+ }
1775
+ }
1776
+ async function loadCredentials(options, ctx) {
1777
+ let credentials;
1778
+ try {
1779
+ credentials = await resolveCredentials(options);
1780
+ } catch (error) {
1781
+ notify(ctx, `Prefactor could not read its credentials: ${describe2(error)}`);
1782
+ return;
1783
+ }
1784
+ if (!credentials && !setupNoticeShown) {
1785
+ setupNoticeShown = true;
1786
+ notify(ctx, ctx.hasUI ? "Prefactor is not set up. Run /prefactor setup to connect pi to Prefactor." : "Prefactor is not set up, so this session is not recorded. Set PREFACTOR_API_URL, " + "PREFACTOR_API_TOKEN and PREFACTOR_AGENT_ID, or run /prefactor setup in interactive pi.");
1787
+ }
1788
+ return credentials;
1789
+ }
1790
+ function notify(ctx, message) {
1791
+ if (ctx.hasUI) {
1792
+ ctx.ui.notify(message, "warning");
1793
+ return;
1794
+ }
1795
+ process.stderr.write(`${message}
1796
+ `);
1797
+ }
1798
+ function describe2(error) {
1799
+ return error instanceof Error ? error.message : String(error);
1800
+ }
1801
+
1802
+ // packages/pi/src/index.ts
1803
+ var src_default = prefactorExtension();
1804
+
1805
+ //# debugId=E8974D033DD1A66864756E2164756E21