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