@narumitw/pi-otel 0.0.0-stage → 0.55.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/CHANGELOG.md +170 -0
- package/LICENSE +21 -0
- package/README.md +371 -2
- package/dist/chunks/chunk-IXR5MVGN.ts +156 -0
- package/dist/chunks/chunk-IXR5MVGN.ts.map +7 -0
- package/dist/chunks/runtime-KWIFBNQ2.ts +404 -0
- package/dist/chunks/runtime-KWIFBNQ2.ts.map +7 -0
- package/dist/config.d.ts +36 -0
- package/dist/durable-projection.d.ts +9 -0
- package/dist/durable-recorder.d.ts +57 -0
- package/dist/durable-state.d.ts +43 -0
- package/dist/durable.d.ts +25 -0
- package/dist/durable.js +897 -0
- package/dist/durable.js.map +7 -0
- package/dist/git.d.ts +5 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1736 -0
- package/dist/index.js.map +7 -0
- package/dist/index.ts +1878 -0
- package/dist/index.ts.map +7 -0
- package/dist/library-chunks/chunk-BBL32ZV5.js +84 -0
- package/dist/library-chunks/chunk-BBL32ZV5.js.map +7 -0
- package/dist/library-chunks/chunk-ROM6FIM7.js +78 -0
- package/dist/library-chunks/chunk-ROM6FIM7.js.map +7 -0
- package/dist/library-chunks/chunk-ZCEZBO2T.js +158 -0
- package/dist/library-chunks/chunk-ZCEZBO2T.js.map +7 -0
- package/dist/library-chunks/runtime-7TSAKORH.js +406 -0
- package/dist/library-chunks/runtime-7TSAKORH.js.map +7 -0
- package/dist/otel.d.ts +13 -0
- package/dist/otlp-settings.d.ts +9 -0
- package/dist/pi-session.d.ts +43 -0
- package/dist/public-api.d.ts +2 -0
- package/dist/runtime-api.d.ts +6 -0
- package/dist/runtime-core.d.ts +26 -0
- package/dist/runtime-defaults.d.ts +1 -0
- package/dist/runtime.d.ts +26 -0
- package/dist/sanitizer.d.ts +2 -0
- package/dist/tracing.d.ts +199 -0
- package/docs/durable.md +128 -0
- package/package.json +87 -4
- package/src/config.ts +330 -0
- package/src/durable-projection.ts +112 -0
- package/src/durable-recorder.ts +539 -0
- package/src/durable-state.ts +135 -0
- package/src/durable.ts +364 -0
- package/src/git.ts +64 -0
- package/src/index.ts +12 -0
- package/src/otel.ts +397 -0
- package/src/otlp-settings.ts +80 -0
- package/src/pi-session.ts +570 -0
- package/src/public-api.ts +13 -0
- package/src/runtime-api.ts +16 -0
- package/src/runtime-core.ts +114 -0
- package/src/runtime-defaults.ts +1 -0
- package/src/runtime.ts +509 -0
- package/src/sanitizer.ts +157 -0
- package/src/tracing.ts +946 -0
package/dist/index.ts
ADDED
|
@@ -0,0 +1,1878 @@
|
|
|
1
|
+
// @generated by scripts/build-runtime.mjs; do not edit.
|
|
2
|
+
// @ts-nocheck -- the generated entry uses a .ts extension for Pi's Jiti loader.
|
|
3
|
+
import {
|
|
4
|
+
DEFAULT_BASE_URL,
|
|
5
|
+
createLangfuseRuntimeFromBackend,
|
|
6
|
+
getLangfuseRuntimeInternal,
|
|
7
|
+
normalizeOtlpConnection,
|
|
8
|
+
otlpSecrets
|
|
9
|
+
} from "./chunks/chunk-IXR5MVGN.ts";
|
|
10
|
+
|
|
11
|
+
// src/otel.ts
|
|
12
|
+
import { stripVTControlCharacters } from "node:util";
|
|
13
|
+
|
|
14
|
+
// src/config.ts
|
|
15
|
+
import { randomUUID } from "node:crypto";
|
|
16
|
+
import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
17
|
+
import { dirname, join } from "node:path";
|
|
18
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
19
|
+
var CONFIG_FILE_NAME = "pi-otel.json";
|
|
20
|
+
var LEGACY_CONFIG_FILE_NAME = "pi-langfuse.json";
|
|
21
|
+
function otelSettingsPath() {
|
|
22
|
+
return join(getAgentDir(), CONFIG_FILE_NAME);
|
|
23
|
+
}
|
|
24
|
+
var configSaveQueues = /* @__PURE__ */ new Map();
|
|
25
|
+
function writeLangfuseConfig(patch, path = otelSettingsPath()) {
|
|
26
|
+
const previous = configSaveQueues.get(path) ?? Promise.resolve();
|
|
27
|
+
const operation = previous.then(() => writeLangfuseConfigNow(patch, path));
|
|
28
|
+
const tail = operation.then(
|
|
29
|
+
() => void 0,
|
|
30
|
+
() => void 0
|
|
31
|
+
);
|
|
32
|
+
configSaveQueues.set(path, tail);
|
|
33
|
+
void tail.then(() => {
|
|
34
|
+
if (configSaveQueues.get(path) === tail) configSaveQueues.delete(path);
|
|
35
|
+
});
|
|
36
|
+
return operation;
|
|
37
|
+
}
|
|
38
|
+
async function writeLangfuseConfigNow(patch, path) {
|
|
39
|
+
const currentDocument = await readLangfuseDocumentForUpdate(path);
|
|
40
|
+
const normalized = normalizeLangfuseConfig({ ...currentDocument, ...patch });
|
|
41
|
+
if (!normalized.ok) throw new Error(normalized.reason);
|
|
42
|
+
const {
|
|
43
|
+
publicKey: _publicKey,
|
|
44
|
+
secretKey: _secretKey,
|
|
45
|
+
baseUrl: _baseUrl,
|
|
46
|
+
environment: _environment,
|
|
47
|
+
release: _release,
|
|
48
|
+
userId: _userId,
|
|
49
|
+
captureContent: _captureContent,
|
|
50
|
+
...unknownFields
|
|
51
|
+
} = currentDocument;
|
|
52
|
+
const nextDocument = { ...unknownFields, ...normalized.config };
|
|
53
|
+
await mkdir(dirname(path), { recursive: true, mode: 448 });
|
|
54
|
+
const tempPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
55
|
+
try {
|
|
56
|
+
await writeFile(tempPath, `${JSON.stringify(nextDocument, null, 2)}
|
|
57
|
+
`, {
|
|
58
|
+
encoding: "utf8",
|
|
59
|
+
mode: 384
|
|
60
|
+
});
|
|
61
|
+
await chmod(tempPath, 384);
|
|
62
|
+
await rename(tempPath, path);
|
|
63
|
+
return normalized.config;
|
|
64
|
+
} catch (error) {
|
|
65
|
+
await rm(tempPath, { force: true }).catch(() => void 0);
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
async function readLangfuseDocumentForUpdate(path) {
|
|
70
|
+
let parsed;
|
|
71
|
+
try {
|
|
72
|
+
parsed = JSON.parse(await readFile(path, "utf8"));
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if (isNodeError(error) && error.code === "ENOENT") return {};
|
|
75
|
+
throw new Error(
|
|
76
|
+
`Cannot update ${CONFIG_FILE_NAME} because the existing file is malformed or unreadable; repair it first.`
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
const normalized = normalizeLangfuseConfig(parsed);
|
|
80
|
+
if (!normalized.ok) {
|
|
81
|
+
throw new Error(
|
|
82
|
+
`Cannot update ${CONFIG_FILE_NAME} because the existing file has invalid recognized fields; repair it first.`
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
return { ...parsed };
|
|
86
|
+
}
|
|
87
|
+
async function loadSettings(path = otelSettingsPath()) {
|
|
88
|
+
const current = await readSettings(path, normalizeSettings);
|
|
89
|
+
if (!current.missing || path !== otelSettingsPath()) return current;
|
|
90
|
+
const legacy = await readSettings(join(dirname(path), LEGACY_CONFIG_FILE_NAME), normalizeLangfuseConfig);
|
|
91
|
+
const latest = await readSettings(path, normalizeSettings);
|
|
92
|
+
return latest.missing && !legacy.missing ? { ...legacy, legacy: true } : latest;
|
|
93
|
+
}
|
|
94
|
+
async function readSettings(path, normalize) {
|
|
95
|
+
await configSaveQueues.get(path);
|
|
96
|
+
const warnings = [];
|
|
97
|
+
const permissionFailure = await ensurePrivatePermissions(path, warnings);
|
|
98
|
+
if (permissionFailure) {
|
|
99
|
+
return {
|
|
100
|
+
ok: false,
|
|
101
|
+
path,
|
|
102
|
+
warnings,
|
|
103
|
+
reason: `Refusing to load credentials: ${permissionFailure}`
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
let text;
|
|
107
|
+
try {
|
|
108
|
+
text = await readFile(path, "utf8");
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (isNodeError(error) && error.code === "ENOENT") {
|
|
111
|
+
return { ok: false, path, warnings, missing: true, reason: `Configuration file not found: ${path}` };
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
ok: false,
|
|
115
|
+
path,
|
|
116
|
+
warnings,
|
|
117
|
+
reason: `Failed to read ${path}: ${formatError(error)}`
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
let parsed;
|
|
121
|
+
try {
|
|
122
|
+
parsed = JSON.parse(text);
|
|
123
|
+
} catch {
|
|
124
|
+
return {
|
|
125
|
+
ok: false,
|
|
126
|
+
path,
|
|
127
|
+
warnings,
|
|
128
|
+
reason: `Failed to parse ${path} as JSON; repair the file before retrying.`
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
const normalized = normalize(parsed);
|
|
132
|
+
if (!normalized.ok) return { ok: false, path, warnings, reason: normalized.reason };
|
|
133
|
+
return { ok: true, config: normalized.config, path, warnings };
|
|
134
|
+
}
|
|
135
|
+
function normalizeSettings(value) {
|
|
136
|
+
if (!isSettingsObject(value) || value.backend !== "otlp") return normalizeLangfuseConfig(value);
|
|
137
|
+
if (value.publicKey !== void 0 || value.secretKey !== void 0 || value.baseUrl !== void 0) {
|
|
138
|
+
return { ok: false, reason: "OTLP settings cannot contain Langfuse credentials or a Langfuse baseUrl." };
|
|
139
|
+
}
|
|
140
|
+
const common = normalizeCommonSettings(value, false);
|
|
141
|
+
if (!common.ok) return common;
|
|
142
|
+
try {
|
|
143
|
+
return { ok: true, config: { backend: "otlp", ...normalizeOtlpConnection(value), ...common.config } };
|
|
144
|
+
} catch (error) {
|
|
145
|
+
return { ok: false, reason: formatError(error) };
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
function normalizeLangfuseConfig(value) {
|
|
149
|
+
if (!isSettingsObject(value)) {
|
|
150
|
+
return { ok: false, reason: `${CONFIG_FILE_NAME} must contain a JSON object.` };
|
|
151
|
+
}
|
|
152
|
+
const input = value;
|
|
153
|
+
if (input.backend !== void 0 && input.backend !== "langfuse") {
|
|
154
|
+
return { ok: false, reason: 'Expected a Langfuse configuration with backend "langfuse" or no backend.' };
|
|
155
|
+
}
|
|
156
|
+
const publicKey = normalizeString(input.publicKey);
|
|
157
|
+
const secretKey = normalizeString(input.secretKey);
|
|
158
|
+
if (!publicKey) {
|
|
159
|
+
return { ok: false, reason: "Langfuse settings require a literal publicKey string." };
|
|
160
|
+
}
|
|
161
|
+
if (!secretKey) {
|
|
162
|
+
return { ok: false, reason: "Langfuse settings require a literal secretKey string." };
|
|
163
|
+
}
|
|
164
|
+
if (isInterpolation(publicKey)) {
|
|
165
|
+
return {
|
|
166
|
+
ok: false,
|
|
167
|
+
reason: "Langfuse publicKey must be literal; environment and command interpolation are not supported."
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
if (isInterpolation(secretKey)) {
|
|
171
|
+
return {
|
|
172
|
+
ok: false,
|
|
173
|
+
reason: "Langfuse secretKey must be literal; environment and command interpolation are not supported."
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
const rawBaseUrl = input.baseUrl === void 0 ? DEFAULT_BASE_URL : normalizeString(input.baseUrl);
|
|
177
|
+
if (!rawBaseUrl) {
|
|
178
|
+
return { ok: false, reason: "Langfuse baseUrl must be a non-empty string." };
|
|
179
|
+
}
|
|
180
|
+
const baseUrl = normalizeBaseUrl(rawBaseUrl);
|
|
181
|
+
if (!baseUrl) {
|
|
182
|
+
return {
|
|
183
|
+
ok: false,
|
|
184
|
+
reason: "Langfuse baseUrl must use HTTP or HTTPS without credentials, a query, or a fragment."
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
const common = normalizeCommonSettings(input, true);
|
|
188
|
+
if (!common.ok) return common;
|
|
189
|
+
const environment = optionalString(input.environment, "environment");
|
|
190
|
+
if (!environment.ok) return environment;
|
|
191
|
+
if (environment.value && (environment.value.length > 40 || !/^(?!langfuse)[a-z0-9_-]+$/u.test(environment.value))) {
|
|
192
|
+
return {
|
|
193
|
+
ok: false,
|
|
194
|
+
reason: "Langfuse environment must be at most 40 lowercase letters, numbers, hyphens, or underscores and must not start with langfuse."
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
const release = optionalString(input.release, "release");
|
|
198
|
+
if (!release.ok) return release;
|
|
199
|
+
return {
|
|
200
|
+
ok: true,
|
|
201
|
+
config: {
|
|
202
|
+
publicKey,
|
|
203
|
+
secretKey,
|
|
204
|
+
baseUrl,
|
|
205
|
+
...environment.value ? { environment: environment.value } : {},
|
|
206
|
+
...release.value ? { release: release.value } : {},
|
|
207
|
+
...common.config
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
function normalizeCommonSettings(input, captureByDefault) {
|
|
212
|
+
if (input.captureContent !== void 0 && typeof input.captureContent !== "boolean") {
|
|
213
|
+
return { ok: false, reason: "captureContent must be a boolean." };
|
|
214
|
+
}
|
|
215
|
+
const userId = optionalString(input.userId, "userId");
|
|
216
|
+
if (!userId.ok) return userId;
|
|
217
|
+
if (userId.value && userId.value.length > 200) {
|
|
218
|
+
return { ok: false, reason: "userId must be at most 200 characters." };
|
|
219
|
+
}
|
|
220
|
+
return {
|
|
221
|
+
ok: true,
|
|
222
|
+
config: {
|
|
223
|
+
captureContent: input.captureContent ?? captureByDefault,
|
|
224
|
+
...userId.value ? { userId: userId.value } : {}
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
function isSettingsObject(value) {
|
|
229
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
230
|
+
}
|
|
231
|
+
async function ensurePrivatePermissions(path, warnings) {
|
|
232
|
+
try {
|
|
233
|
+
const file = await stat(path);
|
|
234
|
+
if ((file.mode & 511) !== 384) {
|
|
235
|
+
await chmod(path, 384);
|
|
236
|
+
const repaired = await stat(path);
|
|
237
|
+
if ((repaired.mode & 511) !== 384) {
|
|
238
|
+
throw new Error(`permissions remained ${(repaired.mode & 511).toString(8)}`);
|
|
239
|
+
}
|
|
240
|
+
warnings.push(`Restricted ${path} permissions to 0600.`);
|
|
241
|
+
}
|
|
242
|
+
} catch (error) {
|
|
243
|
+
if (isNodeError(error) && error.code === "ENOENT") return void 0;
|
|
244
|
+
const failure = `Failed to enforce 0600 permissions for ${path}: ${formatError(error)}`;
|
|
245
|
+
warnings.push(failure);
|
|
246
|
+
return failure;
|
|
247
|
+
}
|
|
248
|
+
return void 0;
|
|
249
|
+
}
|
|
250
|
+
function normalizeBaseUrl(value) {
|
|
251
|
+
try {
|
|
252
|
+
const url = new URL(value);
|
|
253
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") return void 0;
|
|
254
|
+
if (url.username || url.password || url.search || url.hash) return void 0;
|
|
255
|
+
return url.toString().replace(/\/+$/, "");
|
|
256
|
+
} catch {
|
|
257
|
+
return void 0;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
function optionalString(value, name) {
|
|
261
|
+
if (value === void 0) return { ok: true };
|
|
262
|
+
const normalized = normalizeString(value);
|
|
263
|
+
return normalized ? { ok: true, value: normalized } : { ok: false, reason: `${name} must be a non-empty string.` };
|
|
264
|
+
}
|
|
265
|
+
function normalizeString(value) {
|
|
266
|
+
return typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
267
|
+
}
|
|
268
|
+
function isInterpolation(value) {
|
|
269
|
+
return value.startsWith("$") || value.startsWith("!");
|
|
270
|
+
}
|
|
271
|
+
function isNodeError(error) {
|
|
272
|
+
return error instanceof Error && "code" in error;
|
|
273
|
+
}
|
|
274
|
+
function formatError(error) {
|
|
275
|
+
return error instanceof Error ? error.message : String(error);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// src/git.ts
|
|
279
|
+
var GIT_LOOKUP_TIMEOUT_MS = 1e3;
|
|
280
|
+
var GIT_LOOKUP_MAX_BUFFER = 4 * 1024;
|
|
281
|
+
var MAX_GIT_BRANCH_LENGTH = 256;
|
|
282
|
+
async function resolveGitMetadata(exec, cwd) {
|
|
283
|
+
const [branchResult, commit] = await Promise.all([resolveGitBranch(exec, cwd), resolveGitCommit(exec, cwd)]);
|
|
284
|
+
if (!branchResult.resolved) return void 0;
|
|
285
|
+
if (branchResult.branch) {
|
|
286
|
+
return {
|
|
287
|
+
branch: branchResult.branch,
|
|
288
|
+
...commit ? { commit } : {},
|
|
289
|
+
detached: false
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
return commit ? { commit, detached: true } : void 0;
|
|
293
|
+
}
|
|
294
|
+
async function resolveGitBranch(exec, cwd) {
|
|
295
|
+
try {
|
|
296
|
+
const result = await exec("git", ["symbolic-ref", "--quiet", "--short", "HEAD"], {
|
|
297
|
+
cwd,
|
|
298
|
+
timeout: GIT_LOOKUP_TIMEOUT_MS,
|
|
299
|
+
maxBuffer: GIT_LOOKUP_MAX_BUFFER
|
|
300
|
+
});
|
|
301
|
+
if (result.truncated || result.killed) return { resolved: false };
|
|
302
|
+
if (result.code === 1) return { resolved: true };
|
|
303
|
+
if (result.code !== 0) return { resolved: false };
|
|
304
|
+
const branch = normalizeGitBranch(result.stdout);
|
|
305
|
+
return branch ? { resolved: true, branch } : { resolved: false };
|
|
306
|
+
} catch {
|
|
307
|
+
return { resolved: false };
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
async function resolveGitCommit(exec, cwd) {
|
|
311
|
+
try {
|
|
312
|
+
const result = await exec("git", ["rev-parse", "--verify", "--short=12", "HEAD"], {
|
|
313
|
+
cwd,
|
|
314
|
+
timeout: GIT_LOOKUP_TIMEOUT_MS,
|
|
315
|
+
maxBuffer: GIT_LOOKUP_MAX_BUFFER
|
|
316
|
+
});
|
|
317
|
+
if (result.truncated || result.killed || result.code !== 0) return void 0;
|
|
318
|
+
const commit = result.stdout.trim();
|
|
319
|
+
return /^[0-9a-f]{4,64}$/iu.test(commit) ? commit.toLowerCase() : void 0;
|
|
320
|
+
} catch {
|
|
321
|
+
return void 0;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
function normalizeGitBranch(value) {
|
|
325
|
+
const branch = value.trim();
|
|
326
|
+
if (!branch || branch.length > MAX_GIT_BRANCH_LENGTH) return void 0;
|
|
327
|
+
for (const character of branch) {
|
|
328
|
+
const code = character.codePointAt(0) ?? 0;
|
|
329
|
+
if (code <= 31 || code === 127) return void 0;
|
|
330
|
+
}
|
|
331
|
+
return branch;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// src/sanitizer.ts
|
|
335
|
+
var MAX_CAPTURE_BYTES = 64 * 1024;
|
|
336
|
+
var MAX_STRING_LENGTH = 5e4;
|
|
337
|
+
var MAX_COLLECTION_LENGTH = 200;
|
|
338
|
+
var MAX_DEPTH = 12;
|
|
339
|
+
var TRUNCATED = "[truncated: content budget exceeded]";
|
|
340
|
+
var BASE64_DATA_URI = /data:[^,\s"'`]*;base64,[^\s"'`]*/gi;
|
|
341
|
+
var BASE64_DATA_URI_OMITTED = "[base64 data URI omitted]";
|
|
342
|
+
var OPAQUE_SIGNATURE_KEYS = /* @__PURE__ */ new Set(["thinkingSignature", "textSignature", "thoughtSignature"]);
|
|
343
|
+
function sanitizeTraceValue(value, redactCredentialFields = false) {
|
|
344
|
+
const budget = { remaining: MAX_CAPTURE_BYTES, redactCredentialFields };
|
|
345
|
+
const sanitized = sanitize(value, /* @__PURE__ */ new WeakSet(), 0, budget);
|
|
346
|
+
return serializedBytes(sanitized) <= MAX_CAPTURE_BYTES ? sanitized : TRUNCATED;
|
|
347
|
+
}
|
|
348
|
+
function sanitize(value, active, depth, budget) {
|
|
349
|
+
if (budget.remaining <= byteLength(TRUNCATED)) return TRUNCATED;
|
|
350
|
+
if (value === null || typeof value === "number" || typeof value === "boolean") {
|
|
351
|
+
return consume(value, budget);
|
|
352
|
+
}
|
|
353
|
+
if (typeof value === "string") {
|
|
354
|
+
return consume(sanitizeString(value, Math.min(MAX_STRING_LENGTH, budget.remaining)), budget);
|
|
355
|
+
}
|
|
356
|
+
if (typeof value === "bigint") return consume(value.toString(), budget);
|
|
357
|
+
if (typeof value === "undefined" || typeof value === "function" || typeof value === "symbol") {
|
|
358
|
+
return void 0;
|
|
359
|
+
}
|
|
360
|
+
if (value instanceof Date) {
|
|
361
|
+
return consume(Number.isNaN(value.getTime()) ? "[invalid date]" : value.toISOString(), budget);
|
|
362
|
+
}
|
|
363
|
+
if (value instanceof Error) {
|
|
364
|
+
return sanitize({ name: value.name, message: value.message }, active, depth, budget);
|
|
365
|
+
}
|
|
366
|
+
if (depth >= MAX_DEPTH) return consume("[maximum depth reached]", budget);
|
|
367
|
+
if (active.has(value)) return consume("[circular]", budget);
|
|
368
|
+
active.add(value);
|
|
369
|
+
let result;
|
|
370
|
+
if (Array.isArray(value)) {
|
|
371
|
+
const items = [];
|
|
372
|
+
for (const item of value.slice(0, MAX_COLLECTION_LENGTH)) {
|
|
373
|
+
if (budget.remaining <= byteLength(TRUNCATED)) break;
|
|
374
|
+
items.push(sanitize(item, active, depth + 1, budget));
|
|
375
|
+
}
|
|
376
|
+
if (items.length < value.length) items.push(`[${value.length - items.length} items omitted]`);
|
|
377
|
+
result = items;
|
|
378
|
+
} else {
|
|
379
|
+
const record = value;
|
|
380
|
+
const output = {};
|
|
381
|
+
const objectType = readProperty(record, "type").value;
|
|
382
|
+
const redactData = objectType === "image" || objectType === "base64";
|
|
383
|
+
let visited = 0;
|
|
384
|
+
let processed = 0;
|
|
385
|
+
let omitted = false;
|
|
386
|
+
try {
|
|
387
|
+
for (const key in record) {
|
|
388
|
+
if (visited >= MAX_COLLECTION_LENGTH || budget.remaining <= byteLength(TRUNCATED)) {
|
|
389
|
+
omitted = true;
|
|
390
|
+
break;
|
|
391
|
+
}
|
|
392
|
+
visited += 1;
|
|
393
|
+
if (!Object.hasOwn(record, key) || OPAQUE_SIGNATURE_KEYS.has(key)) continue;
|
|
394
|
+
const keyBudget = Math.min(MAX_STRING_LENGTH, Math.max(0, budget.remaining - 4));
|
|
395
|
+
if (key.length > keyBudget) {
|
|
396
|
+
omitted = true;
|
|
397
|
+
break;
|
|
398
|
+
}
|
|
399
|
+
const keyBytes = byteLength(key);
|
|
400
|
+
if (keyBytes > keyBudget) {
|
|
401
|
+
omitted = true;
|
|
402
|
+
break;
|
|
403
|
+
}
|
|
404
|
+
const sanitizedKey = sanitizeString(key, keyBudget);
|
|
405
|
+
budget.remaining -= byteLength(sanitizedKey) + 4;
|
|
406
|
+
const property = readProperty(record, key);
|
|
407
|
+
if (budget.redactCredentialFields && /^(?:(?:x[-_])?api[-_]?(?:key|token|secret)|authorization|proxy[-_]?authorization|cookies?|password|credentials?|secret|token|bearer|client[-_]?secret|private[-_]?key|secret[-_]?key|public[-_]?key|access[-_]?token|refresh[-_]?token)$/iu.test(
|
|
408
|
+
key
|
|
409
|
+
)) {
|
|
410
|
+
output[sanitizedKey] = consume("[credential field omitted]", budget);
|
|
411
|
+
} else if (redactData && key === "data") {
|
|
412
|
+
output[sanitizedKey] = consume("[base64 omitted]", budget);
|
|
413
|
+
} else if (!property.ok) output[sanitizedKey] = consume("[unreadable property]", budget);
|
|
414
|
+
else output[sanitizedKey] = sanitize(property.value, active, depth + 1, budget);
|
|
415
|
+
processed += 1;
|
|
416
|
+
}
|
|
417
|
+
} catch {
|
|
418
|
+
if (processed === 0) {
|
|
419
|
+
active.delete(value);
|
|
420
|
+
return consume("[unreadable object]", budget);
|
|
421
|
+
}
|
|
422
|
+
omitted = true;
|
|
423
|
+
}
|
|
424
|
+
if (omitted) output.$truncated = "additional object entries omitted";
|
|
425
|
+
result = output;
|
|
426
|
+
}
|
|
427
|
+
active.delete(value);
|
|
428
|
+
return result;
|
|
429
|
+
}
|
|
430
|
+
function readProperty(record, key) {
|
|
431
|
+
try {
|
|
432
|
+
return { ok: true, value: record[key] };
|
|
433
|
+
} catch {
|
|
434
|
+
return { ok: false };
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
function consume(value, budget) {
|
|
438
|
+
const size = serializedBytes(value);
|
|
439
|
+
if (size > budget.remaining) {
|
|
440
|
+
budget.remaining -= byteLength(TRUNCATED);
|
|
441
|
+
return TRUNCATED;
|
|
442
|
+
}
|
|
443
|
+
budget.remaining -= size;
|
|
444
|
+
return value;
|
|
445
|
+
}
|
|
446
|
+
function sanitizeString(value, maxBytes) {
|
|
447
|
+
return truncateString(value, maxBytes).replace(BASE64_DATA_URI, BASE64_DATA_URI_OMITTED);
|
|
448
|
+
}
|
|
449
|
+
function truncateString(value, maxBytes) {
|
|
450
|
+
const boundedPrefix = value.slice(0, maxBytes);
|
|
451
|
+
if (boundedPrefix.length === value.length && byteLength(boundedPrefix) <= maxBytes) {
|
|
452
|
+
return boundedPrefix;
|
|
453
|
+
}
|
|
454
|
+
const suffix = "\u2026 [truncated]";
|
|
455
|
+
const target = Math.max(0, maxBytes - byteLength(suffix) - 2);
|
|
456
|
+
let bytes = 0;
|
|
457
|
+
let output = "";
|
|
458
|
+
for (const character of boundedPrefix) {
|
|
459
|
+
const size = byteLength(character);
|
|
460
|
+
if (bytes + size > target) break;
|
|
461
|
+
output += character;
|
|
462
|
+
bytes += size;
|
|
463
|
+
}
|
|
464
|
+
return `${output}${suffix}`;
|
|
465
|
+
}
|
|
466
|
+
function serializedBytes(value) {
|
|
467
|
+
return byteLength(JSON.stringify(value) ?? "null");
|
|
468
|
+
}
|
|
469
|
+
function byteLength(value) {
|
|
470
|
+
return Buffer.byteLength(value, "utf8");
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
// src/tracing.ts
|
|
474
|
+
var TRACE_SCHEMA_VERSION = "2";
|
|
475
|
+
var MAX_HEADER_VALUE_LENGTH = 1024;
|
|
476
|
+
var CONTENT_DISABLED = "[content capture disabled]";
|
|
477
|
+
var ALLOWED_RESPONSE_HEADERS = /* @__PURE__ */ new Set([
|
|
478
|
+
"anthropic-ratelimit-requests-limit",
|
|
479
|
+
"anthropic-ratelimit-requests-remaining",
|
|
480
|
+
"anthropic-ratelimit-requests-reset",
|
|
481
|
+
"anthropic-ratelimit-tokens-limit",
|
|
482
|
+
"anthropic-ratelimit-tokens-remaining",
|
|
483
|
+
"anthropic-ratelimit-tokens-reset",
|
|
484
|
+
"cf-ray",
|
|
485
|
+
"openai-request-id",
|
|
486
|
+
"request-id",
|
|
487
|
+
"retry-after",
|
|
488
|
+
"x-amzn-requestid",
|
|
489
|
+
"x-request-id",
|
|
490
|
+
"x-ratelimit-limit-requests",
|
|
491
|
+
"x-ratelimit-limit-tokens",
|
|
492
|
+
"x-ratelimit-remaining-requests",
|
|
493
|
+
"x-ratelimit-remaining-tokens",
|
|
494
|
+
"x-ratelimit-reset-requests",
|
|
495
|
+
"x-ratelimit-reset-tokens"
|
|
496
|
+
]);
|
|
497
|
+
var TraceRecorder = class {
|
|
498
|
+
constructor(backend, context) {
|
|
499
|
+
this.backend = backend;
|
|
500
|
+
this.context = context;
|
|
501
|
+
}
|
|
502
|
+
backend;
|
|
503
|
+
context;
|
|
504
|
+
root;
|
|
505
|
+
attempt;
|
|
506
|
+
attemptIndex;
|
|
507
|
+
turn;
|
|
508
|
+
turnIndex;
|
|
509
|
+
generation;
|
|
510
|
+
tools = /* @__PURE__ */ new Map();
|
|
511
|
+
duplicateToolIds = /* @__PURE__ */ new Set();
|
|
512
|
+
compaction;
|
|
513
|
+
lastOutput;
|
|
514
|
+
lastAssistant;
|
|
515
|
+
lastAttemptOutcome;
|
|
516
|
+
unresolvedToolErrors = 0;
|
|
517
|
+
startSnapshot;
|
|
518
|
+
counters = emptyCounters();
|
|
519
|
+
startObservation(name, attributes, options) {
|
|
520
|
+
const { sessionId, userId } = this.context;
|
|
521
|
+
return this.backend.start(name, { ...attributes, sessionId, ...userId ? { userId } : {} }, options);
|
|
522
|
+
}
|
|
523
|
+
hasActiveTrace() {
|
|
524
|
+
return this.root !== void 0;
|
|
525
|
+
}
|
|
526
|
+
hasActiveAttempt() {
|
|
527
|
+
return this.attempt !== void 0;
|
|
528
|
+
}
|
|
529
|
+
beginAgent(input) {
|
|
530
|
+
if (this.root) this.closeActiveTrace("Interrupted by a new Pi run.", void 0, "interrupted");
|
|
531
|
+
this.lastOutput = void 0;
|
|
532
|
+
this.lastAssistant = void 0;
|
|
533
|
+
this.lastAttemptOutcome = void 0;
|
|
534
|
+
this.unresolvedToolErrors = 0;
|
|
535
|
+
this.duplicateToolIds.clear();
|
|
536
|
+
this.startSnapshot = input.snapshot;
|
|
537
|
+
this.counters = emptyCounters();
|
|
538
|
+
const traceInput = this.capture({
|
|
539
|
+
prompt: input.prompt,
|
|
540
|
+
...hasItems(input.images) ? { images: input.images } : {}
|
|
541
|
+
});
|
|
542
|
+
const metadata = {
|
|
543
|
+
...customTraceMetadata(this.context.metadata),
|
|
544
|
+
"pi.cwd": this.context.cwd,
|
|
545
|
+
...input.git?.branch ? { "pi.git.branch": input.git.branch } : {},
|
|
546
|
+
...input.git?.commit ? { "pi.git.commit": input.git.commit } : {},
|
|
547
|
+
...input.git ? { "pi.git.detached": input.git.detached } : {},
|
|
548
|
+
"pi.mode": this.context.mode,
|
|
549
|
+
...input.model?.id ? { "pi.model": input.model.id } : {},
|
|
550
|
+
...input.model?.provider ? { "pi.provider": input.model.provider } : {},
|
|
551
|
+
...input.requestId ? { "pi.request.id": input.requestId } : {},
|
|
552
|
+
"pi.session.id": this.context.sessionId,
|
|
553
|
+
"pi.trace.schema_version": Number(TRACE_SCHEMA_VERSION),
|
|
554
|
+
...snapshotMetadata("start", input.snapshot)
|
|
555
|
+
};
|
|
556
|
+
const attributes = { input: traceInput, metadata, version: TRACE_SCHEMA_VERSION };
|
|
557
|
+
const gitTag = input.git?.branch ? `branch:${input.git.branch}` : input.git?.detached ? "git:detached" : void 0;
|
|
558
|
+
this.root = this.startObservation("pi.agent", attributes, { asType: "agent" });
|
|
559
|
+
this.root.updateTrace?.({
|
|
560
|
+
name: normalizeTraceName(this.context.traceName),
|
|
561
|
+
sessionId: this.context.sessionId,
|
|
562
|
+
...this.context.userId ? { userId: this.context.userId } : {},
|
|
563
|
+
version: TRACE_SCHEMA_VERSION,
|
|
564
|
+
input: traceInput,
|
|
565
|
+
metadata,
|
|
566
|
+
tags: traceTags(this.context.tags, gitTag)
|
|
567
|
+
});
|
|
568
|
+
const traceId = this.root.traceId;
|
|
569
|
+
if (traceId && this.context.onTraceId) {
|
|
570
|
+
try {
|
|
571
|
+
void Promise.resolve(this.context.onTraceId(traceId)).catch(() => void 0);
|
|
572
|
+
} catch {
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
beginAttempt(input = {}) {
|
|
577
|
+
if (!this.root) return;
|
|
578
|
+
if (this.attempt) {
|
|
579
|
+
this.closeAttempt(void 0, "Interrupted by the next Pi attempt.", "interrupted");
|
|
580
|
+
}
|
|
581
|
+
const index = this.counters.attempts;
|
|
582
|
+
this.counters.attempts += 1;
|
|
583
|
+
this.lastAssistant = void 0;
|
|
584
|
+
this.unresolvedToolErrors = 0;
|
|
585
|
+
this.attemptIndex = index;
|
|
586
|
+
this.attempt = this.startObservation(
|
|
587
|
+
"pi.attempt",
|
|
588
|
+
{
|
|
589
|
+
metadata: {
|
|
590
|
+
"pi.attempt.index": index,
|
|
591
|
+
...input.reason ? { "pi.attempt.reason": input.reason } : {}
|
|
592
|
+
},
|
|
593
|
+
version: TRACE_SCHEMA_VERSION
|
|
594
|
+
},
|
|
595
|
+
{ asType: "span", parent: this.root }
|
|
596
|
+
);
|
|
597
|
+
}
|
|
598
|
+
finishAttempt(message) {
|
|
599
|
+
if (message?.role === "assistant") this.finishAssistant(message);
|
|
600
|
+
if (!this.attempt) return;
|
|
601
|
+
const outcome = this.unresolvedToolErrors > 0 ? "error" : classifyOutcome(message);
|
|
602
|
+
this.closeAttempt(
|
|
603
|
+
message,
|
|
604
|
+
this.unresolvedToolErrors > 0 ? "Pi attempt ended after a tool failure." : void 0,
|
|
605
|
+
outcome
|
|
606
|
+
);
|
|
607
|
+
}
|
|
608
|
+
beginTurn(turnIndex) {
|
|
609
|
+
if (!this.root) return;
|
|
610
|
+
if (this.turn) this.closeTurn("Interrupted by the next Pi turn.", "ERROR");
|
|
611
|
+
this.counters.turns += 1;
|
|
612
|
+
this.turnIndex = turnIndex;
|
|
613
|
+
this.turn = this.startObservation(
|
|
614
|
+
"pi.turn",
|
|
615
|
+
{ metadata: { "pi.turn.index": turnIndex }, version: TRACE_SCHEMA_VERSION },
|
|
616
|
+
{ asType: "span", parent: this.attempt ?? this.root }
|
|
617
|
+
);
|
|
618
|
+
}
|
|
619
|
+
finishTurn(turnIndex, result) {
|
|
620
|
+
if (!this.turn) return;
|
|
621
|
+
this.closeGeneration("Turn ended without a finalized assistant message.");
|
|
622
|
+
this.closeTools("Tool span ended when the Pi turn finished.");
|
|
623
|
+
const mismatched = this.turnIndex !== turnIndex;
|
|
624
|
+
const outcome = classifyOutcome(result.message);
|
|
625
|
+
this.turn.update({
|
|
626
|
+
metadata: {
|
|
627
|
+
"pi.turn.index": this.turnIndex ?? turnIndex,
|
|
628
|
+
"pi.turn.tool_result_count": result.toolResultCount,
|
|
629
|
+
...result.message.stopReason ? { "pi.turn.stop_reason": result.message.stopReason } : {}
|
|
630
|
+
},
|
|
631
|
+
...mismatched && outcome === "success" ? {
|
|
632
|
+
level: "WARNING",
|
|
633
|
+
statusMessage: `Turn ${turnIndex} ended while turn ${this.turnIndex} was active.`
|
|
634
|
+
} : severityForOutcome(outcome, this.captureErrorMessage(result.message.errorMessage))
|
|
635
|
+
});
|
|
636
|
+
this.turn.end();
|
|
637
|
+
this.turn = void 0;
|
|
638
|
+
this.turnIndex = void 0;
|
|
639
|
+
}
|
|
640
|
+
beginGeneration(input = {}) {
|
|
641
|
+
if (!this.root) return;
|
|
642
|
+
this.closeGeneration("Interrupted by the next provider request.");
|
|
643
|
+
if (this.unresolvedToolErrors > 0) {
|
|
644
|
+
this.counters.recoveredErrors += this.unresolvedToolErrors;
|
|
645
|
+
this.unresolvedToolErrors = 0;
|
|
646
|
+
}
|
|
647
|
+
this.counters.generations += 1;
|
|
648
|
+
const requestMetadata = {
|
|
649
|
+
...input.payloadStage ? { "pi.request.payload_stage": input.payloadStage } : {},
|
|
650
|
+
...input.model?.provider ? { "pi.request.provider": input.model.provider } : {},
|
|
651
|
+
...input.model?.id ? { "pi.request.model": input.model.id } : {},
|
|
652
|
+
...input.model?.api ? { "pi.request.api": input.model.api } : {},
|
|
653
|
+
...input.thinkingLevel ? { "pi.request.thinking_level": input.thinkingLevel } : {}
|
|
654
|
+
};
|
|
655
|
+
const observation = this.startObservation(
|
|
656
|
+
"pi.llm",
|
|
657
|
+
{
|
|
658
|
+
...input.payload !== void 0 ? { input: this.capture(input.payload) } : {},
|
|
659
|
+
...input.model?.id ? { model: input.model.id } : {},
|
|
660
|
+
...input.thinkingLevel ? { modelParameters: { thinking_level: input.thinkingLevel } } : {},
|
|
661
|
+
...Object.keys(requestMetadata).length > 0 ? { metadata: requestMetadata } : {},
|
|
662
|
+
version: TRACE_SCHEMA_VERSION
|
|
663
|
+
},
|
|
664
|
+
{
|
|
665
|
+
asType: "generation",
|
|
666
|
+
parent: this.turn ?? this.attempt ?? this.root,
|
|
667
|
+
...input.startedAt === void 0 ? {} : { startTime: new Date(input.startedAt) }
|
|
668
|
+
}
|
|
669
|
+
);
|
|
670
|
+
this.generation = {
|
|
671
|
+
observation,
|
|
672
|
+
requestMetadata,
|
|
673
|
+
statuses: [],
|
|
674
|
+
headers: {}
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
recordProviderResponse(status, headers = {}) {
|
|
678
|
+
if (!this.generation) return;
|
|
679
|
+
this.generation.statuses.push(status);
|
|
680
|
+
Object.assign(this.generation.headers, allowlistedResponseHeaders(headers));
|
|
681
|
+
}
|
|
682
|
+
markGenerationFirstOutput(timestamp = Date.now()) {
|
|
683
|
+
if (this.generation && this.generation.completionStartTime === void 0) {
|
|
684
|
+
this.generation.completionStartTime = timestamp;
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
markGenerationEnd(endTime = Date.now()) {
|
|
688
|
+
if (this.generation && this.generation.endTime === void 0) {
|
|
689
|
+
this.generation.endTime = endTime;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
finishAssistant(message) {
|
|
693
|
+
if (message.role !== "assistant") return;
|
|
694
|
+
this.lastAssistant = message;
|
|
695
|
+
this.lastOutput = this.capture(message.content);
|
|
696
|
+
if (!this.generation) return;
|
|
697
|
+
const state = this.generation;
|
|
698
|
+
const usageDetails = numericRecord({
|
|
699
|
+
input: message.usage?.input,
|
|
700
|
+
output: message.usage?.output,
|
|
701
|
+
cache_read_input_tokens: message.usage?.cacheRead,
|
|
702
|
+
cache_creation_input_tokens: message.usage?.cacheWrite,
|
|
703
|
+
total: message.usage?.totalTokens
|
|
704
|
+
});
|
|
705
|
+
const costDetails = knownCostDetails(message.usage?.cost);
|
|
706
|
+
const outcome = classifyOutcome(message);
|
|
707
|
+
const responseModel = message.responseModel ?? message.model;
|
|
708
|
+
const httpMetadata = generationHttpMetadata(state);
|
|
709
|
+
const recoveredStatuses = state.statuses.filter((status) => status >= 400).length;
|
|
710
|
+
if (outcome === "success" && recoveredStatuses > 0) {
|
|
711
|
+
this.counters.recoveredErrors += recoveredStatuses;
|
|
712
|
+
}
|
|
713
|
+
state.observation.update({
|
|
714
|
+
output: this.lastOutput,
|
|
715
|
+
...state.completionStartTime !== void 0 ? { completionStartTime: new Date(state.completionStartTime) } : {},
|
|
716
|
+
...responseModel ? { model: responseModel } : {},
|
|
717
|
+
...Object.keys(usageDetails).length > 0 ? { usageDetails } : {},
|
|
718
|
+
...Object.keys(costDetails).length > 0 ? { costDetails } : {},
|
|
719
|
+
metadata: {
|
|
720
|
+
...state.requestMetadata,
|
|
721
|
+
...httpMetadata,
|
|
722
|
+
...message.provider ? { "pi.provider": message.provider, "pi.response.provider": message.provider } : {},
|
|
723
|
+
...message.api ? { "pi.response.api": message.api } : {},
|
|
724
|
+
...responseModel ? { "pi.response.model": responseModel } : {},
|
|
725
|
+
...message.responseId ? { "pi.response.id": message.responseId } : {},
|
|
726
|
+
...message.responseModel && message.model && message.responseModel !== message.model ? { "pi.requested_model": message.model } : {},
|
|
727
|
+
...message.stopReason ? { "pi.stop_reason": message.stopReason } : {},
|
|
728
|
+
...typeof message.usage?.cost?.totalFromProvider === "boolean" ? { "pi.usage.cost.total_from_provider": message.usage.cost.totalFromProvider } : {},
|
|
729
|
+
...finiteNumber(message.usage?.reasoning) ? { "pi.usage.reasoning_tokens": message.usage.reasoning } : {},
|
|
730
|
+
...finiteNumber(message.usage?.cacheWrite1h) ? { "pi.usage.cache_write_1h_tokens": message.usage.cacheWrite1h } : {}
|
|
731
|
+
},
|
|
732
|
+
...severityForOutcome(outcome, this.captureErrorMessage(message.errorMessage))
|
|
733
|
+
});
|
|
734
|
+
state.observation.end(state.endTime);
|
|
735
|
+
this.generation = void 0;
|
|
736
|
+
}
|
|
737
|
+
beginTool(toolCallId, toolName, args, startedAt = Date.now()) {
|
|
738
|
+
if (!this.root) return;
|
|
739
|
+
this.counters.tools += 1;
|
|
740
|
+
if (this.duplicateToolIds.has(toolCallId)) {
|
|
741
|
+
this.counters.toolErrors += 1;
|
|
742
|
+
const duplicate = this.startToolObservation(toolCallId, toolName, args);
|
|
743
|
+
duplicate.update({
|
|
744
|
+
level: "ERROR",
|
|
745
|
+
statusMessage: "Duplicate tool call ID cannot be correlated safely."
|
|
746
|
+
});
|
|
747
|
+
duplicate.end();
|
|
748
|
+
return;
|
|
749
|
+
}
|
|
750
|
+
const existing = this.tools.get(toolCallId);
|
|
751
|
+
if (existing) {
|
|
752
|
+
existing.observation.update({
|
|
753
|
+
level: "ERROR",
|
|
754
|
+
statusMessage: "Duplicate tool execution started."
|
|
755
|
+
});
|
|
756
|
+
existing.observation.end();
|
|
757
|
+
this.tools.delete(toolCallId);
|
|
758
|
+
this.counters.toolErrors += 2;
|
|
759
|
+
const duplicate = this.startToolObservation(toolCallId, toolName, args);
|
|
760
|
+
duplicate.update({
|
|
761
|
+
level: "ERROR",
|
|
762
|
+
statusMessage: "Duplicate tool call ID cannot be correlated safely."
|
|
763
|
+
});
|
|
764
|
+
duplicate.end();
|
|
765
|
+
this.duplicateToolIds.add(toolCallId);
|
|
766
|
+
return;
|
|
767
|
+
}
|
|
768
|
+
this.tools.set(toolCallId, {
|
|
769
|
+
observation: this.startToolObservation(toolCallId, toolName, args),
|
|
770
|
+
startedAt,
|
|
771
|
+
progressUpdates: 0
|
|
772
|
+
});
|
|
773
|
+
}
|
|
774
|
+
recordToolInput(toolCallId, input) {
|
|
775
|
+
if (input === void 0 || this.duplicateToolIds.has(toolCallId)) return;
|
|
776
|
+
this.tools.get(toolCallId)?.observation.update({ input: this.capture(input) });
|
|
777
|
+
}
|
|
778
|
+
recordToolProgress(toolCallId, timestamp = Date.now()) {
|
|
779
|
+
const tool = this.tools.get(toolCallId);
|
|
780
|
+
if (!tool) return;
|
|
781
|
+
tool.progressUpdates += 1;
|
|
782
|
+
tool.firstProgressAt ??= timestamp;
|
|
783
|
+
}
|
|
784
|
+
finishTool(toolCallId, result) {
|
|
785
|
+
if (this.duplicateToolIds.has(toolCallId)) return;
|
|
786
|
+
const tool = this.tools.get(toolCallId);
|
|
787
|
+
if (!tool) return;
|
|
788
|
+
if (result.isError) {
|
|
789
|
+
this.counters.toolErrors += 1;
|
|
790
|
+
this.unresolvedToolErrors += 1;
|
|
791
|
+
}
|
|
792
|
+
tool.observation.update({
|
|
793
|
+
output: this.capture({ content: result.content, details: result.details }),
|
|
794
|
+
metadata: {
|
|
795
|
+
"pi.tool.progress_update_count": tool.progressUpdates,
|
|
796
|
+
...tool.firstProgressAt !== void 0 ? {
|
|
797
|
+
"pi.tool.time_to_first_progress_ms": Math.max(0, tool.firstProgressAt - tool.startedAt)
|
|
798
|
+
} : {}
|
|
799
|
+
},
|
|
800
|
+
...result.isError ? { level: "ERROR", statusMessage: "Pi tool execution failed." } : {}
|
|
801
|
+
});
|
|
802
|
+
tool.observation.end();
|
|
803
|
+
this.tools.delete(toolCallId);
|
|
804
|
+
}
|
|
805
|
+
beginCompaction(input) {
|
|
806
|
+
if (!this.root) return;
|
|
807
|
+
this.closeCompaction("Interrupted by another Pi compaction.");
|
|
808
|
+
this.counters.compactions += 1;
|
|
809
|
+
this.compaction = {
|
|
810
|
+
observation: this.startObservation(
|
|
811
|
+
"pi.compaction",
|
|
812
|
+
{
|
|
813
|
+
metadata: {
|
|
814
|
+
"pi.compaction.reason": input.reason,
|
|
815
|
+
"pi.compaction.will_retry": input.willRetry,
|
|
816
|
+
...finiteNumber(input.tokensBefore) ? { "pi.compaction.tokens_before": input.tokensBefore } : {},
|
|
817
|
+
"pi.compaction.messages_to_summarize": input.messagesToSummarize,
|
|
818
|
+
"pi.compaction.turn_prefix_messages": input.turnPrefixMessages,
|
|
819
|
+
"pi.compaction.branch_entries": input.branchEntries,
|
|
820
|
+
"pi.compaction.is_split_turn": input.isSplitTurn
|
|
821
|
+
},
|
|
822
|
+
version: TRACE_SCHEMA_VERSION
|
|
823
|
+
},
|
|
824
|
+
{ asType: "span", parent: this.root }
|
|
825
|
+
)
|
|
826
|
+
};
|
|
827
|
+
}
|
|
828
|
+
finishCompaction(input) {
|
|
829
|
+
if (!this.compaction) return;
|
|
830
|
+
const details = structuralCompactionDetails(input.details);
|
|
831
|
+
const usage = numericRecord({
|
|
832
|
+
input: input.usage?.input,
|
|
833
|
+
output: input.usage?.output,
|
|
834
|
+
cache_read: input.usage?.cacheRead,
|
|
835
|
+
cache_write: input.usage?.cacheWrite,
|
|
836
|
+
total: input.usage?.totalTokens
|
|
837
|
+
});
|
|
838
|
+
const cost = knownCostDetails(input.usage?.cost);
|
|
839
|
+
this.compaction.observation.update({
|
|
840
|
+
metadata: {
|
|
841
|
+
"pi.compaction.reason": input.reason,
|
|
842
|
+
"pi.compaction.will_retry": input.willRetry,
|
|
843
|
+
"pi.compaction.from_extension": input.fromExtension,
|
|
844
|
+
...finiteNumber(input.tokensBefore) ? { "pi.compaction.tokens_before": input.tokensBefore } : {},
|
|
845
|
+
...details,
|
|
846
|
+
...prefixRecord("pi.compaction.usage", usage),
|
|
847
|
+
...prefixRecord("pi.compaction.cost", cost),
|
|
848
|
+
...typeof input.usage?.cost?.totalFromProvider === "boolean" ? { "pi.compaction.cost.total_from_provider": input.usage.cost.totalFromProvider } : {}
|
|
849
|
+
}
|
|
850
|
+
});
|
|
851
|
+
this.compaction.observation.end();
|
|
852
|
+
this.compaction = void 0;
|
|
853
|
+
}
|
|
854
|
+
settle(snapshot) {
|
|
855
|
+
this.closeActiveTrace(void 0, snapshot);
|
|
856
|
+
}
|
|
857
|
+
interrupt(statusMessage, snapshot) {
|
|
858
|
+
this.closeActiveTrace(statusMessage, snapshot, "interrupted");
|
|
859
|
+
}
|
|
860
|
+
dispose(statusMessage = "Pi session ended before the active trace settled.", snapshot) {
|
|
861
|
+
this.closeActiveTrace(statusMessage, snapshot, "interrupted");
|
|
862
|
+
}
|
|
863
|
+
closeActiveTrace(statusMessage, snapshot, forcedOutcome) {
|
|
864
|
+
this.closeTurn(statusMessage ?? "Pi turn ended when the agent run settled.");
|
|
865
|
+
this.closeAttempt(void 0, statusMessage, forcedOutcome ?? "interrupted");
|
|
866
|
+
this.closeCompaction(statusMessage ?? "Pi compaction ended when the agent run settled.");
|
|
867
|
+
if (!this.root) return;
|
|
868
|
+
const baseOutcome = forcedOutcome ?? this.lastAttemptOutcome ?? classifyOutcome(this.lastAssistant);
|
|
869
|
+
const recoveredErrorCount = this.counters.recoveredErrors + (baseOutcome === "success" ? this.counters.failedAttempts : 0);
|
|
870
|
+
const traceOutcome = baseOutcome === "success" && recoveredErrorCount > 0 ? "recovered_success" : baseOutcome;
|
|
871
|
+
const finalMetadata = {
|
|
872
|
+
"pi.trace.schema_version": Number(TRACE_SCHEMA_VERSION),
|
|
873
|
+
"pi.trace.outcome": traceOutcome,
|
|
874
|
+
...this.lastAssistant?.stopReason ? { "pi.trace.stop_reason": this.lastAssistant.stopReason } : {},
|
|
875
|
+
"pi.trace.attempt_count": this.counters.attempts,
|
|
876
|
+
"pi.trace.turn_count": this.counters.turns,
|
|
877
|
+
"pi.trace.generation_count": this.counters.generations,
|
|
878
|
+
"pi.trace.tool_count": this.counters.tools,
|
|
879
|
+
"pi.trace.tool_error_count": this.counters.toolErrors,
|
|
880
|
+
"pi.trace.compaction_count": this.counters.compactions,
|
|
881
|
+
"pi.trace.recovered_error_count": recoveredErrorCount,
|
|
882
|
+
...snapshotMetadata("start", this.startSnapshot),
|
|
883
|
+
...snapshotMetadata("end", snapshot)
|
|
884
|
+
};
|
|
885
|
+
const finalAttributes = {
|
|
886
|
+
...this.lastOutput !== void 0 ? { output: this.lastOutput } : {},
|
|
887
|
+
metadata: finalMetadata,
|
|
888
|
+
...severityForOutcome(baseOutcome, statusMessage ?? this.captureErrorMessage(this.lastAssistant?.errorMessage))
|
|
889
|
+
};
|
|
890
|
+
this.root.update(finalAttributes);
|
|
891
|
+
this.root.updateTrace?.({
|
|
892
|
+
...this.lastOutput !== void 0 ? { output: this.lastOutput } : {},
|
|
893
|
+
metadata: finalMetadata,
|
|
894
|
+
version: TRACE_SCHEMA_VERSION
|
|
895
|
+
});
|
|
896
|
+
this.root.end();
|
|
897
|
+
this.root = void 0;
|
|
898
|
+
this.lastOutput = void 0;
|
|
899
|
+
this.lastAssistant = void 0;
|
|
900
|
+
this.lastAttemptOutcome = void 0;
|
|
901
|
+
this.unresolvedToolErrors = 0;
|
|
902
|
+
this.duplicateToolIds.clear();
|
|
903
|
+
this.startSnapshot = void 0;
|
|
904
|
+
}
|
|
905
|
+
closeAttempt(message, statusMessage, forcedOutcome) {
|
|
906
|
+
if (!this.attempt) return;
|
|
907
|
+
this.closeTurn(statusMessage ?? "Pi turn ended when the attempt finished.");
|
|
908
|
+
const outcome = forcedOutcome ?? classifyOutcome(message);
|
|
909
|
+
if (outcome === "error") this.counters.failedAttempts += 1;
|
|
910
|
+
this.lastAttemptOutcome = outcome;
|
|
911
|
+
this.attempt.update({
|
|
912
|
+
...message?.content !== void 0 ? { output: this.capture(message.content) } : {},
|
|
913
|
+
metadata: {
|
|
914
|
+
"pi.attempt.index": this.attemptIndex ?? Math.max(0, this.counters.attempts - 1),
|
|
915
|
+
"pi.attempt.outcome": outcome,
|
|
916
|
+
...message?.stopReason ? { "pi.attempt.stop_reason": message.stopReason } : {}
|
|
917
|
+
},
|
|
918
|
+
...severityForOutcome(outcome, statusMessage ?? this.captureErrorMessage(message?.errorMessage))
|
|
919
|
+
});
|
|
920
|
+
this.attempt.end();
|
|
921
|
+
this.attempt = void 0;
|
|
922
|
+
this.attemptIndex = void 0;
|
|
923
|
+
this.unresolvedToolErrors = 0;
|
|
924
|
+
}
|
|
925
|
+
startToolObservation(toolCallId, toolName, args) {
|
|
926
|
+
return this.startObservation(
|
|
927
|
+
`pi.tool.${toolName}`,
|
|
928
|
+
{
|
|
929
|
+
...args !== void 0 ? { input: this.capture(args) } : {},
|
|
930
|
+
metadata: { "pi.tool.call_id": toolCallId, "pi.tool.name": toolName },
|
|
931
|
+
version: TRACE_SCHEMA_VERSION
|
|
932
|
+
},
|
|
933
|
+
{ asType: "tool", parent: this.turn ?? this.attempt ?? this.root }
|
|
934
|
+
);
|
|
935
|
+
}
|
|
936
|
+
closeTurn(statusMessage, generationLevel = "WARNING") {
|
|
937
|
+
this.closeGeneration(statusMessage, generationLevel);
|
|
938
|
+
this.closeTools(statusMessage);
|
|
939
|
+
if (!this.turn) return;
|
|
940
|
+
this.turn.update({ level: "WARNING", statusMessage });
|
|
941
|
+
this.turn.end();
|
|
942
|
+
this.turn = void 0;
|
|
943
|
+
this.turnIndex = void 0;
|
|
944
|
+
}
|
|
945
|
+
closeTools(statusMessage) {
|
|
946
|
+
for (const tool of this.tools.values()) {
|
|
947
|
+
tool.observation.update({
|
|
948
|
+
level: "WARNING",
|
|
949
|
+
statusMessage,
|
|
950
|
+
metadata: {
|
|
951
|
+
"pi.tool.progress_update_count": tool.progressUpdates,
|
|
952
|
+
...tool.firstProgressAt !== void 0 ? {
|
|
953
|
+
"pi.tool.time_to_first_progress_ms": Math.max(0, tool.firstProgressAt - tool.startedAt)
|
|
954
|
+
} : {}
|
|
955
|
+
}
|
|
956
|
+
});
|
|
957
|
+
tool.observation.end();
|
|
958
|
+
}
|
|
959
|
+
this.tools.clear();
|
|
960
|
+
}
|
|
961
|
+
closeGeneration(statusMessage, level = "ERROR") {
|
|
962
|
+
if (!this.generation) return;
|
|
963
|
+
this.generation.observation.update({
|
|
964
|
+
level,
|
|
965
|
+
statusMessage,
|
|
966
|
+
metadata: {
|
|
967
|
+
...this.generation.requestMetadata,
|
|
968
|
+
...generationHttpMetadata(this.generation)
|
|
969
|
+
}
|
|
970
|
+
});
|
|
971
|
+
this.generation.observation.end(this.generation.endTime);
|
|
972
|
+
this.generation = void 0;
|
|
973
|
+
}
|
|
974
|
+
closeCompaction(statusMessage) {
|
|
975
|
+
if (!this.compaction) return;
|
|
976
|
+
this.compaction.observation.update({ level: "WARNING", statusMessage });
|
|
977
|
+
this.compaction.observation.end();
|
|
978
|
+
this.compaction = void 0;
|
|
979
|
+
}
|
|
980
|
+
captureErrorMessage(message) {
|
|
981
|
+
if (!this.context.captureContent || typeof message !== "string") return void 0;
|
|
982
|
+
return String(sanitizeTraceValue(message));
|
|
983
|
+
}
|
|
984
|
+
capture(value) {
|
|
985
|
+
return this.context.captureContent ? sanitizeTraceValue(value) : CONTENT_DISABLED;
|
|
986
|
+
}
|
|
987
|
+
};
|
|
988
|
+
function normalizeTraceName(value) {
|
|
989
|
+
return typeof value === "string" && value.trim() ? value.trim() : "pi.trace";
|
|
990
|
+
}
|
|
991
|
+
function traceTags(customTags, gitTag) {
|
|
992
|
+
const tags = ["pi", ...gitTag ? [gitTag] : [], ...customTags ?? []];
|
|
993
|
+
return [...new Set(tags.map(sanitizeTraceTag).filter((tag) => tag !== void 0))];
|
|
994
|
+
}
|
|
995
|
+
function sanitizeTraceTag(value) {
|
|
996
|
+
if (typeof value !== "string" || !value.trim()) return void 0;
|
|
997
|
+
const sanitized = sanitizeTraceValue(value.trim());
|
|
998
|
+
return typeof sanitized === "string" && sanitized.trim() ? sanitized.trim() : void 0;
|
|
999
|
+
}
|
|
1000
|
+
function customTraceMetadata(metadata) {
|
|
1001
|
+
if (!metadata) return {};
|
|
1002
|
+
const sanitized = sanitizeTraceValue(metadata);
|
|
1003
|
+
if (!sanitized || typeof sanitized !== "object" || Array.isArray(sanitized)) return {};
|
|
1004
|
+
return Object.fromEntries(Object.entries(sanitized).filter(([key]) => !key.startsWith("pi.")));
|
|
1005
|
+
}
|
|
1006
|
+
function generationHttpMetadata(state) {
|
|
1007
|
+
const finalStatus = state.statuses.at(-1);
|
|
1008
|
+
return {
|
|
1009
|
+
...state.statuses.length > 0 ? {
|
|
1010
|
+
"http.response.status_codes": [...state.statuses],
|
|
1011
|
+
"http.response.status_code": finalStatus,
|
|
1012
|
+
"http.response.attempt_count": state.statuses.length,
|
|
1013
|
+
"http.response.retry_count": Math.max(0, state.statuses.length - 1)
|
|
1014
|
+
} : {},
|
|
1015
|
+
...Object.keys(state.headers).length > 0 ? { "http.response.headers": { ...state.headers } } : {}
|
|
1016
|
+
};
|
|
1017
|
+
}
|
|
1018
|
+
function allowlistedResponseHeaders(headers) {
|
|
1019
|
+
const output = {};
|
|
1020
|
+
for (const [rawName, rawValue] of Object.entries(headers)) {
|
|
1021
|
+
const name = rawName.toLowerCase();
|
|
1022
|
+
if (!ALLOWED_RESPONSE_HEADERS.has(name) || typeof rawValue !== "string") continue;
|
|
1023
|
+
output[name] = truncateString2(rawValue, MAX_HEADER_VALUE_LENGTH);
|
|
1024
|
+
}
|
|
1025
|
+
return output;
|
|
1026
|
+
}
|
|
1027
|
+
function structuralCompactionDetails(details) {
|
|
1028
|
+
if (!details || typeof details !== "object" || Array.isArray(details)) return {};
|
|
1029
|
+
const record = details;
|
|
1030
|
+
return {
|
|
1031
|
+
...Array.isArray(record.readFiles) ? { "pi.compaction.read_file_count": record.readFiles.length } : {},
|
|
1032
|
+
...Array.isArray(record.modifiedFiles) ? { "pi.compaction.modified_file_count": record.modifiedFiles.length } : {}
|
|
1033
|
+
};
|
|
1034
|
+
}
|
|
1035
|
+
function snapshotMetadata(prefix, snapshot) {
|
|
1036
|
+
if (!snapshot) return {};
|
|
1037
|
+
return {
|
|
1038
|
+
...snapshot.leafId ? { [`pi.trace.${prefix}_leaf_id`]: snapshot.leafId } : {},
|
|
1039
|
+
...snapshot.contextUsage ? {
|
|
1040
|
+
...finiteNumber(snapshot.contextUsage.tokens) ? { [`pi.trace.${prefix}_context_tokens`]: snapshot.contextUsage.tokens } : {},
|
|
1041
|
+
[`pi.trace.${prefix}_context_window`]: snapshot.contextUsage.contextWindow,
|
|
1042
|
+
...finiteNumber(snapshot.contextUsage.percent) ? { [`pi.trace.${prefix}_context_percent`]: snapshot.contextUsage.percent } : {}
|
|
1043
|
+
} : {}
|
|
1044
|
+
};
|
|
1045
|
+
}
|
|
1046
|
+
function classifyOutcome(message) {
|
|
1047
|
+
if (message?.role !== "assistant") return "interrupted";
|
|
1048
|
+
if (message.stopReason === "error" || message.errorMessage) return "error";
|
|
1049
|
+
if (message.stopReason === "aborted") return "aborted";
|
|
1050
|
+
if (message.stopReason === "length") return "length";
|
|
1051
|
+
return "success";
|
|
1052
|
+
}
|
|
1053
|
+
function severityForOutcome(outcome, statusMessage) {
|
|
1054
|
+
if (outcome === "success") return {};
|
|
1055
|
+
if (outcome === "error") {
|
|
1056
|
+
return {
|
|
1057
|
+
level: "ERROR",
|
|
1058
|
+
statusMessage: statusMessage ?? "The Pi operation failed."
|
|
1059
|
+
};
|
|
1060
|
+
}
|
|
1061
|
+
return {
|
|
1062
|
+
level: "WARNING",
|
|
1063
|
+
statusMessage: statusMessage ?? (outcome === "aborted" ? "The Pi operation was aborted." : outcome === "length" ? "The model reached its output limit." : "The Pi operation was interrupted.")
|
|
1064
|
+
};
|
|
1065
|
+
}
|
|
1066
|
+
function prefixRecord(prefix, values) {
|
|
1067
|
+
return Object.fromEntries(Object.entries(values).map(([key, value]) => [`${prefix}.${key}`, value]));
|
|
1068
|
+
}
|
|
1069
|
+
function truncateString2(value, maxBytes) {
|
|
1070
|
+
const boundedPrefix = value.slice(0, maxBytes);
|
|
1071
|
+
if (boundedPrefix.length === value.length && byteLength2(boundedPrefix) <= maxBytes) {
|
|
1072
|
+
return boundedPrefix;
|
|
1073
|
+
}
|
|
1074
|
+
const suffix = "\u2026 [truncated]";
|
|
1075
|
+
const target = Math.max(0, maxBytes - byteLength2(suffix) - 2);
|
|
1076
|
+
let bytes = 0;
|
|
1077
|
+
let output = "";
|
|
1078
|
+
for (const character of boundedPrefix) {
|
|
1079
|
+
const size = byteLength2(character);
|
|
1080
|
+
if (bytes + size > target) break;
|
|
1081
|
+
output += character;
|
|
1082
|
+
bytes += size;
|
|
1083
|
+
}
|
|
1084
|
+
return `${output}${suffix}`;
|
|
1085
|
+
}
|
|
1086
|
+
function byteLength2(value) {
|
|
1087
|
+
return Buffer.byteLength(value, "utf8");
|
|
1088
|
+
}
|
|
1089
|
+
function numericRecord(values) {
|
|
1090
|
+
return Object.fromEntries(
|
|
1091
|
+
Object.entries(values).filter((entry) => finiteNumber(entry[1]))
|
|
1092
|
+
);
|
|
1093
|
+
}
|
|
1094
|
+
function knownCostDetails(cost) {
|
|
1095
|
+
const values = {
|
|
1096
|
+
input: cost?.input,
|
|
1097
|
+
output: cost?.output,
|
|
1098
|
+
cache_read: cost?.cacheRead,
|
|
1099
|
+
cache_write: cost?.cacheWrite,
|
|
1100
|
+
total: cost?.total
|
|
1101
|
+
};
|
|
1102
|
+
return Object.fromEntries(
|
|
1103
|
+
Object.entries(values).filter(
|
|
1104
|
+
(entry) => finiteNumber(entry[1]) && (entry[1] > 0 || entry[0] === "total" && entry[1] === 0 && cost?.totalFromProvider === true)
|
|
1105
|
+
)
|
|
1106
|
+
);
|
|
1107
|
+
}
|
|
1108
|
+
function finiteNumber(value) {
|
|
1109
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
1110
|
+
}
|
|
1111
|
+
function hasItems(value) {
|
|
1112
|
+
return Array.isArray(value) ? value.length > 0 : value !== void 0;
|
|
1113
|
+
}
|
|
1114
|
+
function emptyCounters() {
|
|
1115
|
+
return {
|
|
1116
|
+
attempts: 0,
|
|
1117
|
+
turns: 0,
|
|
1118
|
+
generations: 0,
|
|
1119
|
+
tools: 0,
|
|
1120
|
+
toolErrors: 0,
|
|
1121
|
+
compactions: 0,
|
|
1122
|
+
recoveredErrors: 0,
|
|
1123
|
+
failedAttempts: 0
|
|
1124
|
+
};
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
// src/pi-session.ts
|
|
1128
|
+
function createPiLangfuseSession(runtime, options = {}) {
|
|
1129
|
+
const sessionOptions = snapshotSessionOptions(options);
|
|
1130
|
+
return createPiLangfuseSessionController({
|
|
1131
|
+
resolveSession: async () => ({ runtime, options: sessionOptions })
|
|
1132
|
+
});
|
|
1133
|
+
}
|
|
1134
|
+
function createPiLangfuseSessionController(options) {
|
|
1135
|
+
let binding;
|
|
1136
|
+
let runtimeForShutdown;
|
|
1137
|
+
let ownerRegistration;
|
|
1138
|
+
let pendingInitialization;
|
|
1139
|
+
const outstandingInitializations = /* @__PURE__ */ new Set();
|
|
1140
|
+
let disposePromise;
|
|
1141
|
+
let disposed = false;
|
|
1142
|
+
let sessionGeneration = 0;
|
|
1143
|
+
let requestId;
|
|
1144
|
+
let requestIdRevision = 0;
|
|
1145
|
+
let nextAttemptReason;
|
|
1146
|
+
let lastSnapshot;
|
|
1147
|
+
let pendingProviderGeneration;
|
|
1148
|
+
const controller = {
|
|
1149
|
+
extension(pi) {
|
|
1150
|
+
if (disposed) throw new Error("A disposed Pi Langfuse session controller cannot be bound.");
|
|
1151
|
+
registerHooks(pi);
|
|
1152
|
+
},
|
|
1153
|
+
setRequestId(value) {
|
|
1154
|
+
requestId = normalizeOptionalString(value);
|
|
1155
|
+
requestIdRevision += 1;
|
|
1156
|
+
},
|
|
1157
|
+
dispose() {
|
|
1158
|
+
if (disposePromise) return disposePromise;
|
|
1159
|
+
disposed = true;
|
|
1160
|
+
const initializations = invalidateAllInitializations("disposed");
|
|
1161
|
+
ownerRegistration = void 0;
|
|
1162
|
+
sessionGeneration += 1;
|
|
1163
|
+
closeBinding(binding, "Pi Langfuse session controller was disposed.", lastSnapshot);
|
|
1164
|
+
runtimeForShutdown = void 0;
|
|
1165
|
+
disposePromise = joinInitializations(initializations);
|
|
1166
|
+
return disposePromise;
|
|
1167
|
+
},
|
|
1168
|
+
get active() {
|
|
1169
|
+
return binding !== void 0;
|
|
1170
|
+
},
|
|
1171
|
+
get runtime() {
|
|
1172
|
+
return binding?.runtime;
|
|
1173
|
+
},
|
|
1174
|
+
async flush() {
|
|
1175
|
+
const runtime = binding?.runtime;
|
|
1176
|
+
if (!runtime) throw new Error("Langfuse tracing is not enabled for this session.");
|
|
1177
|
+
await runtime.flush();
|
|
1178
|
+
}
|
|
1179
|
+
};
|
|
1180
|
+
function closeBinding(target, statusMessage, snapshot) {
|
|
1181
|
+
if (!target) return;
|
|
1182
|
+
const wasCurrent = binding === target;
|
|
1183
|
+
if (wasCurrent) {
|
|
1184
|
+
binding = void 0;
|
|
1185
|
+
pendingProviderGeneration = void 0;
|
|
1186
|
+
}
|
|
1187
|
+
target.releaseRuntime();
|
|
1188
|
+
target.recorder.dispose(statusMessage, snapshot);
|
|
1189
|
+
if (wasCurrent) nextAttemptReason = void 0;
|
|
1190
|
+
}
|
|
1191
|
+
function invalidatePendingInitialization(reason) {
|
|
1192
|
+
if (!pendingInitialization) return;
|
|
1193
|
+
pendingInitialization.current = false;
|
|
1194
|
+
pendingInitialization.reason = reason;
|
|
1195
|
+
pendingInitialization = void 0;
|
|
1196
|
+
}
|
|
1197
|
+
function invalidateAllInitializations(reason) {
|
|
1198
|
+
const initializations = [...outstandingInitializations];
|
|
1199
|
+
for (const initialization of initializations) {
|
|
1200
|
+
initialization.current = false;
|
|
1201
|
+
initialization.reason = reason;
|
|
1202
|
+
}
|
|
1203
|
+
pendingInitialization = void 0;
|
|
1204
|
+
return initializations;
|
|
1205
|
+
}
|
|
1206
|
+
function createPendingInitialization() {
|
|
1207
|
+
let complete;
|
|
1208
|
+
const completion = new Promise((resolve) => {
|
|
1209
|
+
complete = resolve;
|
|
1210
|
+
});
|
|
1211
|
+
const initialization = { current: true, completion, complete };
|
|
1212
|
+
outstandingInitializations.add(initialization);
|
|
1213
|
+
return initialization;
|
|
1214
|
+
}
|
|
1215
|
+
async function joinInitializations(initializations) {
|
|
1216
|
+
const results = await Promise.all(initializations.map(({ completion }) => completion));
|
|
1217
|
+
const errors = results.flatMap((result) => result.ok ? [] : [result.error]);
|
|
1218
|
+
if (errors.length === 1) throw errors[0];
|
|
1219
|
+
if (errors.length > 1) throw new AggregateError(errors, "Pi Langfuse session initialization cleanup failed.");
|
|
1220
|
+
}
|
|
1221
|
+
async function initializeSession(registration, initialization, ctx) {
|
|
1222
|
+
const generation = ++sessionGeneration;
|
|
1223
|
+
closeBinding(binding, "Pi session was replaced before shutdown completed.", lastSnapshot);
|
|
1224
|
+
lastSnapshot = contextSnapshot(ctx);
|
|
1225
|
+
nextAttemptReason = void 0;
|
|
1226
|
+
options.onSessionStart?.();
|
|
1227
|
+
const isCurrent = () => !disposed && initialization.current && ownerRegistration === registration && generation === sessionGeneration;
|
|
1228
|
+
let resolved;
|
|
1229
|
+
try {
|
|
1230
|
+
resolved = await options.resolveSession(ctx, isCurrent);
|
|
1231
|
+
} catch (error) {
|
|
1232
|
+
if (isCurrent()) options.onInitializationError?.(error, ctx);
|
|
1233
|
+
return;
|
|
1234
|
+
}
|
|
1235
|
+
if (!isCurrent()) {
|
|
1236
|
+
const reason = initialization.reason ?? "replaced";
|
|
1237
|
+
if (resolved && options.shutdownRuntimeOnQuit && reason !== "quit" && reason !== "disposed" && (!runtimeForShutdown || runtimeForShutdown.closed)) {
|
|
1238
|
+
runtimeForShutdown = resolved.runtime;
|
|
1239
|
+
}
|
|
1240
|
+
await resolved?.releaseIfStale?.(reason);
|
|
1241
|
+
return;
|
|
1242
|
+
}
|
|
1243
|
+
if (!resolved) {
|
|
1244
|
+
options.onSessionUnavailable?.();
|
|
1245
|
+
return;
|
|
1246
|
+
}
|
|
1247
|
+
try {
|
|
1248
|
+
const internal = getLangfuseRuntimeInternal(resolved.runtime);
|
|
1249
|
+
const recorderOptions = createRecorderOptions(ctx, resolved.options);
|
|
1250
|
+
const recorder = new TraceRecorder(internal.backend, recorderOptions);
|
|
1251
|
+
const nextBinding = {};
|
|
1252
|
+
const releaseRuntime = internal.registerSession((statusMessage) => {
|
|
1253
|
+
closeBinding(nextBinding, statusMessage, lastSnapshot);
|
|
1254
|
+
});
|
|
1255
|
+
Object.assign(nextBinding, { registration, recorder, runtime: resolved.runtime, releaseRuntime });
|
|
1256
|
+
if (!isCurrent()) {
|
|
1257
|
+
releaseRuntime();
|
|
1258
|
+
return;
|
|
1259
|
+
}
|
|
1260
|
+
binding = nextBinding;
|
|
1261
|
+
if (options.shutdownRuntimeOnQuit) runtimeForShutdown = resolved.runtime;
|
|
1262
|
+
options.onSessionReady?.(resolved);
|
|
1263
|
+
} catch (error) {
|
|
1264
|
+
if (isCurrent()) options.onInitializationError?.(error, ctx);
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
function registerHooks(pi) {
|
|
1268
|
+
const registration = {};
|
|
1269
|
+
const activeRecorder = () => activeRecorderFor(registration);
|
|
1270
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
1271
|
+
if (disposed) return;
|
|
1272
|
+
pendingProviderGeneration = void 0;
|
|
1273
|
+
if (ownerRegistration && ownerRegistration !== registration) {
|
|
1274
|
+
options.onInitializationError?.(
|
|
1275
|
+
new Error("A Pi Langfuse session controller cannot manage multiple active Pi sessions."),
|
|
1276
|
+
ctx
|
|
1277
|
+
);
|
|
1278
|
+
return;
|
|
1279
|
+
}
|
|
1280
|
+
invalidatePendingInitialization("replaced");
|
|
1281
|
+
ownerRegistration = registration;
|
|
1282
|
+
const initialization = createPendingInitialization();
|
|
1283
|
+
pendingInitialization = initialization;
|
|
1284
|
+
let result = { ok: true };
|
|
1285
|
+
try {
|
|
1286
|
+
await initializeSession(registration, initialization, ctx);
|
|
1287
|
+
} catch (error) {
|
|
1288
|
+
result = { ok: false, error };
|
|
1289
|
+
throw error;
|
|
1290
|
+
} finally {
|
|
1291
|
+
initialization.complete(result);
|
|
1292
|
+
outstandingInitializations.delete(initialization);
|
|
1293
|
+
if (pendingInitialization === initialization) pendingInitialization = void 0;
|
|
1294
|
+
}
|
|
1295
|
+
});
|
|
1296
|
+
pi.on("before_agent_start", async (event, ctx) => {
|
|
1297
|
+
pendingProviderGeneration = void 0;
|
|
1298
|
+
const active = ownerRegistration === registration ? binding : void 0;
|
|
1299
|
+
if (!active || active.runtime.closed) return;
|
|
1300
|
+
nextAttemptReason = void 0;
|
|
1301
|
+
const git = await (options.resolveGitMetadata ? options.resolveGitMetadata(pi, ctx.cwd) : resolveGitMetadata((command, args, execOptions) => pi.exec(command, args, execOptions), ctx.cwd)).catch(() => void 0);
|
|
1302
|
+
if (ownerRegistration !== registration || binding !== active || active.runtime.closed) return;
|
|
1303
|
+
lastSnapshot = contextSnapshot(ctx);
|
|
1304
|
+
startRootTrace((nextRequestId) => {
|
|
1305
|
+
active.recorder.beginAgent({
|
|
1306
|
+
prompt: event.messageType === "custom" ? event.message.content : event.prompt,
|
|
1307
|
+
images: event.messageType === "custom" ? void 0 : event.images,
|
|
1308
|
+
model: ctx.model ? { provider: ctx.model.provider, id: ctx.model.id, api: ctx.model.api } : void 0,
|
|
1309
|
+
git,
|
|
1310
|
+
snapshot: lastSnapshot,
|
|
1311
|
+
...nextRequestId ? { requestId: nextRequestId } : {}
|
|
1312
|
+
});
|
|
1313
|
+
});
|
|
1314
|
+
});
|
|
1315
|
+
pi.on("agent_start", () => {
|
|
1316
|
+
const recorder = activeRecorder();
|
|
1317
|
+
if (!recorder) return;
|
|
1318
|
+
recorder.beginAttempt(nextAttemptReason ? { reason: nextAttemptReason } : void 0);
|
|
1319
|
+
nextAttemptReason = void 0;
|
|
1320
|
+
});
|
|
1321
|
+
pi.on("turn_start", (event, ctx) => {
|
|
1322
|
+
const recorder = activeRecorder();
|
|
1323
|
+
if (!recorder) return;
|
|
1324
|
+
lastSnapshot = contextSnapshot(ctx);
|
|
1325
|
+
ensureActiveRun(recorder, ctx, startRootTrace);
|
|
1326
|
+
recorder.beginTurn(event.turnIndex);
|
|
1327
|
+
});
|
|
1328
|
+
pi.on("before_provider_request", (event, ctx) => {
|
|
1329
|
+
if (!activeRecorder()) return;
|
|
1330
|
+
lastSnapshot = contextSnapshot(ctx);
|
|
1331
|
+
pendingProviderGeneration = {
|
|
1332
|
+
startedAt: Date.now(),
|
|
1333
|
+
payload: event.payload,
|
|
1334
|
+
model: ctx.model ? { provider: ctx.model.provider, id: ctx.model.id, api: ctx.model.api } : void 0,
|
|
1335
|
+
thinkingLevel: pi.getThinkingLevel(),
|
|
1336
|
+
responses: []
|
|
1337
|
+
};
|
|
1338
|
+
});
|
|
1339
|
+
pi.on("after_provider_response", (event) => {
|
|
1340
|
+
pendingProviderGeneration?.responses.push({ status: event.status, headers: event.headers });
|
|
1341
|
+
});
|
|
1342
|
+
pi.on("message_start", (event, ctx) => {
|
|
1343
|
+
if (event.message.role === "assistant") claimPendingProviderGeneration(ctx, activeRecorder());
|
|
1344
|
+
});
|
|
1345
|
+
pi.on("message_update", (event, ctx) => {
|
|
1346
|
+
if (!isRealOutputDelta(event.assistantMessageEvent)) return;
|
|
1347
|
+
const recorder = activeRecorder();
|
|
1348
|
+
claimPendingProviderGeneration(ctx, recorder);
|
|
1349
|
+
recorder?.markGenerationFirstOutput();
|
|
1350
|
+
});
|
|
1351
|
+
pi.on("message_end", (event, ctx) => {
|
|
1352
|
+
if (event.message.role !== "assistant") return;
|
|
1353
|
+
const recorder = activeRecorder();
|
|
1354
|
+
claimPendingProviderGeneration(ctx, recorder);
|
|
1355
|
+
recorder?.markGenerationEnd();
|
|
1356
|
+
});
|
|
1357
|
+
pi.on("turn_end", (event, ctx) => {
|
|
1358
|
+
const recorder = activeRecorder();
|
|
1359
|
+
if (!recorder) return;
|
|
1360
|
+
if (event.message.role === "assistant") claimPendingProviderGeneration(ctx, recorder);
|
|
1361
|
+
lastSnapshot = contextSnapshot(ctx);
|
|
1362
|
+
if (event.message.role === "assistant") recorder.finishAssistant(event.message);
|
|
1363
|
+
recorder.finishTurn(event.turnIndex, {
|
|
1364
|
+
message: event.message,
|
|
1365
|
+
toolResultCount: event.toolResults.length
|
|
1366
|
+
});
|
|
1367
|
+
});
|
|
1368
|
+
pi.on("tool_execution_start", (event) => {
|
|
1369
|
+
activeRecorder()?.beginTool(event.toolCallId, event.toolName, event.args);
|
|
1370
|
+
});
|
|
1371
|
+
pi.on("tool_execution_update", (event) => {
|
|
1372
|
+
activeRecorder()?.recordToolProgress(event.toolCallId);
|
|
1373
|
+
});
|
|
1374
|
+
pi.on("tool_result", (event) => {
|
|
1375
|
+
activeRecorder()?.recordToolInput(event.toolCallId, event.input);
|
|
1376
|
+
});
|
|
1377
|
+
pi.on("tool_execution_end", (event) => {
|
|
1378
|
+
activeRecorder()?.finishTool(event.toolCallId, {
|
|
1379
|
+
content: event.result.content,
|
|
1380
|
+
details: event.result.details,
|
|
1381
|
+
isError: event.isError
|
|
1382
|
+
});
|
|
1383
|
+
});
|
|
1384
|
+
pi.on("agent_end", (event) => {
|
|
1385
|
+
const message = findLastAssistant(event.messages);
|
|
1386
|
+
activeRecorder()?.finishAttempt(message);
|
|
1387
|
+
});
|
|
1388
|
+
pi.on("session_before_compact", (event) => {
|
|
1389
|
+
activeRecorder()?.beginCompaction({
|
|
1390
|
+
reason: event.reason,
|
|
1391
|
+
willRetry: event.willRetry,
|
|
1392
|
+
tokensBefore: event.preparation.tokensBefore,
|
|
1393
|
+
messagesToSummarize: event.preparation.messagesToSummarize.length,
|
|
1394
|
+
turnPrefixMessages: event.preparation.turnPrefixMessages.length,
|
|
1395
|
+
branchEntries: event.branchEntries.length,
|
|
1396
|
+
isSplitTurn: event.preparation.isSplitTurn
|
|
1397
|
+
});
|
|
1398
|
+
});
|
|
1399
|
+
pi.on("session_compact", (event) => {
|
|
1400
|
+
const recorder = activeRecorder();
|
|
1401
|
+
const entry = event.compactionEntry;
|
|
1402
|
+
recorder?.finishCompaction({
|
|
1403
|
+
reason: event.reason,
|
|
1404
|
+
willRetry: event.willRetry,
|
|
1405
|
+
fromExtension: event.fromExtension,
|
|
1406
|
+
tokensBefore: entry.tokensBefore,
|
|
1407
|
+
details: entry.details,
|
|
1408
|
+
usage: entry.usage
|
|
1409
|
+
});
|
|
1410
|
+
if (event.willRetry && recorder?.hasActiveTrace()) nextAttemptReason = "post_compaction";
|
|
1411
|
+
});
|
|
1412
|
+
pi.on("agent_settled", (_event, ctx) => {
|
|
1413
|
+
const recorder = activeRecorder();
|
|
1414
|
+
if (!recorder) return;
|
|
1415
|
+
lastSnapshot = contextSnapshot(ctx);
|
|
1416
|
+
recorder.settle(lastSnapshot);
|
|
1417
|
+
pendingProviderGeneration = void 0;
|
|
1418
|
+
nextAttemptReason = void 0;
|
|
1419
|
+
});
|
|
1420
|
+
pi.on("session_shutdown", async (event, ctx) => {
|
|
1421
|
+
if (ownerRegistration !== registration) return;
|
|
1422
|
+
const initializations = invalidateAllInitializations(event.reason);
|
|
1423
|
+
ownerRegistration = void 0;
|
|
1424
|
+
const generation = ++sessionGeneration;
|
|
1425
|
+
options.onSessionShutdown?.();
|
|
1426
|
+
const active = binding?.registration === registration ? binding : void 0;
|
|
1427
|
+
const runtime = active?.runtime ?? runtimeForShutdown;
|
|
1428
|
+
lastSnapshot = active ? contextSnapshot(ctx) : lastSnapshot;
|
|
1429
|
+
closeBinding(
|
|
1430
|
+
active,
|
|
1431
|
+
event.reason === "quit" ? "Pi shut down before the active trace settled." : `Pi session ended before settlement (${event.reason}).`,
|
|
1432
|
+
lastSnapshot
|
|
1433
|
+
);
|
|
1434
|
+
let beforeDisposeFailure;
|
|
1435
|
+
try {
|
|
1436
|
+
await options.beforeSessionDispose?.();
|
|
1437
|
+
} catch (error) {
|
|
1438
|
+
beforeDisposeFailure = { error };
|
|
1439
|
+
}
|
|
1440
|
+
try {
|
|
1441
|
+
await joinInitializations(initializations);
|
|
1442
|
+
if (disposed || generation !== sessionGeneration) return;
|
|
1443
|
+
if (beforeDisposeFailure) throw beforeDisposeFailure.error;
|
|
1444
|
+
if (runtime) {
|
|
1445
|
+
if (event.reason === "quit" && options.shutdownRuntimeOnQuit) await runtime.shutdown();
|
|
1446
|
+
else if (options.flushOnReplacement) await runtime.flush();
|
|
1447
|
+
}
|
|
1448
|
+
} catch (error) {
|
|
1449
|
+
if (!disposed && generation === sessionGeneration) options.onShutdownError?.(error, ctx);
|
|
1450
|
+
}
|
|
1451
|
+
});
|
|
1452
|
+
}
|
|
1453
|
+
function claimPendingProviderGeneration(ctx, recorder) {
|
|
1454
|
+
const pending = pendingProviderGeneration;
|
|
1455
|
+
if (!pending || !recorder) return;
|
|
1456
|
+
pendingProviderGeneration = void 0;
|
|
1457
|
+
ensureActiveRun(recorder, ctx, startRootTrace);
|
|
1458
|
+
recorder.beginGeneration({
|
|
1459
|
+
startedAt: pending.startedAt,
|
|
1460
|
+
payload: pending.payload,
|
|
1461
|
+
payloadStage: "before_provider_request",
|
|
1462
|
+
model: pending.model,
|
|
1463
|
+
thinkingLevel: pending.thinkingLevel
|
|
1464
|
+
});
|
|
1465
|
+
for (const response of pending.responses) recorder.recordProviderResponse(response.status, response.headers);
|
|
1466
|
+
}
|
|
1467
|
+
function startRootTrace(start) {
|
|
1468
|
+
const revision = requestIdRevision;
|
|
1469
|
+
const nextRequestId = requestId;
|
|
1470
|
+
start(nextRequestId);
|
|
1471
|
+
if (requestIdRevision === revision) requestId = void 0;
|
|
1472
|
+
}
|
|
1473
|
+
function activeRecorderFor(registration) {
|
|
1474
|
+
return ownerRegistration === registration && binding?.registration === registration && !binding.runtime.closed ? binding.recorder : void 0;
|
|
1475
|
+
}
|
|
1476
|
+
return controller;
|
|
1477
|
+
}
|
|
1478
|
+
function createRecorderOptions(ctx, options = {}) {
|
|
1479
|
+
const userId = normalizeUserId(options.userId);
|
|
1480
|
+
return {
|
|
1481
|
+
sessionId: normalizeOptionalString(options.sessionId) ?? ctx.sessionManager.getSessionId(),
|
|
1482
|
+
...userId ? { userId } : {},
|
|
1483
|
+
cwd: ctx.cwd,
|
|
1484
|
+
mode: ctx.mode,
|
|
1485
|
+
captureContent: options.captureContent ?? true,
|
|
1486
|
+
...normalizeOptionalString(options.traceName) ? { traceName: normalizeOptionalString(options.traceName) } : {},
|
|
1487
|
+
...options.tags ? { tags: [...options.tags] } : {},
|
|
1488
|
+
...options.metadata ? { metadata: { ...options.metadata } } : {},
|
|
1489
|
+
...options.onTraceId ? { onTraceId: options.onTraceId } : {}
|
|
1490
|
+
};
|
|
1491
|
+
}
|
|
1492
|
+
function snapshotSessionOptions(options) {
|
|
1493
|
+
normalizeUserId(options.userId);
|
|
1494
|
+
return {
|
|
1495
|
+
...options,
|
|
1496
|
+
...options.tags ? { tags: [...options.tags] } : {},
|
|
1497
|
+
...options.metadata ? { metadata: { ...options.metadata } } : {}
|
|
1498
|
+
};
|
|
1499
|
+
}
|
|
1500
|
+
function ensureActiveRun(recorder, ctx, startRootTrace) {
|
|
1501
|
+
if (!recorder.hasActiveTrace()) {
|
|
1502
|
+
startRootTrace((nextRequestId) => {
|
|
1503
|
+
recorder.beginAgent({
|
|
1504
|
+
prompt: "[automatic continuation]",
|
|
1505
|
+
model: ctx.model ? { provider: ctx.model.provider, id: ctx.model.id, api: ctx.model.api } : void 0,
|
|
1506
|
+
snapshot: contextSnapshot(ctx),
|
|
1507
|
+
...nextRequestId ? { requestId: nextRequestId } : {}
|
|
1508
|
+
});
|
|
1509
|
+
});
|
|
1510
|
+
}
|
|
1511
|
+
if (!recorder.hasActiveAttempt()) recorder.beginAttempt();
|
|
1512
|
+
}
|
|
1513
|
+
function contextSnapshot(ctx) {
|
|
1514
|
+
return {
|
|
1515
|
+
leafId: typeof ctx.sessionManager.getLeafId === "function" ? ctx.sessionManager.getLeafId() : void 0,
|
|
1516
|
+
contextUsage: ctx.getContextUsage()
|
|
1517
|
+
};
|
|
1518
|
+
}
|
|
1519
|
+
function findLastAssistant(messages) {
|
|
1520
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
1521
|
+
const message = messages[index];
|
|
1522
|
+
if (message?.role === "assistant") return message;
|
|
1523
|
+
}
|
|
1524
|
+
return void 0;
|
|
1525
|
+
}
|
|
1526
|
+
function isRealOutputDelta(event) {
|
|
1527
|
+
return (event.type === "text_delta" || event.type === "thinking_delta" || event.type === "toolcall_delta") && typeof event.delta === "string" && event.delta.length > 0;
|
|
1528
|
+
}
|
|
1529
|
+
function normalizeUserId(value) {
|
|
1530
|
+
const userId = normalizeOptionalString(value);
|
|
1531
|
+
if (userId && userId.length > 200) throw new Error("Langfuse userId must be at most 200 characters.");
|
|
1532
|
+
return userId;
|
|
1533
|
+
}
|
|
1534
|
+
function normalizeOptionalString(value) {
|
|
1535
|
+
if (typeof value !== "string" || !value.trim()) return void 0;
|
|
1536
|
+
const sanitized = sanitizeTraceValue(value.trim());
|
|
1537
|
+
return typeof sanitized === "string" && sanitized.trim() ? sanitized.trim() : void 0;
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1540
|
+
// src/otel.ts
|
|
1541
|
+
var FLUSH_ACTION = "Flush completed traces for this session";
|
|
1542
|
+
var SET_UP_ACTION = "Set up Langfuse for this Pi agent directory (restart required)";
|
|
1543
|
+
var UPDATE_ACTION = "Update Langfuse for this Pi agent directory (restart required)";
|
|
1544
|
+
var HELP_ACTION = "Show setup and privacy help";
|
|
1545
|
+
function createOtelExtension(dependencies = {}) {
|
|
1546
|
+
const loadConfig = dependencies.loadConfig ?? loadSettings;
|
|
1547
|
+
const writeConfig = dependencies.writeConfig ?? writeLangfuseConfig;
|
|
1548
|
+
const resolveInjectedGitMetadata = dependencies.resolveGitMetadata;
|
|
1549
|
+
return function otel(pi) {
|
|
1550
|
+
let activeConfig;
|
|
1551
|
+
let loadingConfig;
|
|
1552
|
+
let runtimeConfigForShutdown;
|
|
1553
|
+
let shutdownConfig;
|
|
1554
|
+
let configPath;
|
|
1555
|
+
let initializationError;
|
|
1556
|
+
let storedBackend;
|
|
1557
|
+
let configurationNotice;
|
|
1558
|
+
let sessionGeneration = 0;
|
|
1559
|
+
let menuController = new AbortController();
|
|
1560
|
+
let configWriteQueue = Promise.resolve();
|
|
1561
|
+
const tracing = createPiLangfuseSessionController({
|
|
1562
|
+
onSessionStart() {
|
|
1563
|
+
sessionGeneration += 1;
|
|
1564
|
+
menuController.abort(new DOMException("Pi OTel session replaced", "AbortError"));
|
|
1565
|
+
menuController = new AbortController();
|
|
1566
|
+
activeConfig = void 0;
|
|
1567
|
+
loadingConfig = void 0;
|
|
1568
|
+
shutdownConfig = void 0;
|
|
1569
|
+
configPath = void 0;
|
|
1570
|
+
initializationError = void 0;
|
|
1571
|
+
storedBackend = void 0;
|
|
1572
|
+
configurationNotice = void 0;
|
|
1573
|
+
},
|
|
1574
|
+
onSessionShutdown() {
|
|
1575
|
+
sessionGeneration += 1;
|
|
1576
|
+
menuController.abort(new DOMException("Pi OTel session shut down", "AbortError"));
|
|
1577
|
+
shutdownConfig = activeConfig ?? runtimeConfigForShutdown ?? loadingConfig;
|
|
1578
|
+
activeConfig = void 0;
|
|
1579
|
+
},
|
|
1580
|
+
async resolveSession(ctx, isCurrent) {
|
|
1581
|
+
await configWriteQueue;
|
|
1582
|
+
if (!isCurrent()) return void 0;
|
|
1583
|
+
const result = await loadConfig();
|
|
1584
|
+
if (!isCurrent()) return void 0;
|
|
1585
|
+
configPath = result.path;
|
|
1586
|
+
for (const warning of result.warnings) ctx.ui.notify(stripVTControlCharacters(warning), "warning");
|
|
1587
|
+
if (!result.ok) {
|
|
1588
|
+
initializationError = formatConfigError(result);
|
|
1589
|
+
if (!result.missing) ctx.ui.notify(initializationError, "warning");
|
|
1590
|
+
return void 0;
|
|
1591
|
+
}
|
|
1592
|
+
storedBackend = result.config.backend ?? "langfuse";
|
|
1593
|
+
loadingConfig = result.config;
|
|
1594
|
+
const createBackend = dependencies.createBackend;
|
|
1595
|
+
const ownsRuntime = createBackend !== void 0;
|
|
1596
|
+
const config = result.config;
|
|
1597
|
+
let runtime;
|
|
1598
|
+
if (createBackend) {
|
|
1599
|
+
runtime = createLangfuseRuntimeFromBackend(await createBackend(config));
|
|
1600
|
+
} else {
|
|
1601
|
+
const { createLangfuseRuntime: createLangfuseRuntime2, createOtelRuntime: createOtelRuntime2 } = await import("./chunks/runtime-KWIFBNQ2.ts");
|
|
1602
|
+
if (!isCurrent()) return void 0;
|
|
1603
|
+
runtime = await (config.backend === "otlp" ? createOtelRuntime2(config) : createLangfuseRuntime2({ config, env: false }));
|
|
1604
|
+
}
|
|
1605
|
+
if (isCurrent() || !runtimeConfigForShutdown) runtimeConfigForShutdown = result.config;
|
|
1606
|
+
if (isCurrent()) {
|
|
1607
|
+
activeConfig = result.config;
|
|
1608
|
+
loadingConfig = void 0;
|
|
1609
|
+
}
|
|
1610
|
+
return {
|
|
1611
|
+
runtime,
|
|
1612
|
+
releaseIfStale: async (reason) => {
|
|
1613
|
+
if (ownsRuntime || reason === "quit") await runtime.shutdown();
|
|
1614
|
+
},
|
|
1615
|
+
options: {
|
|
1616
|
+
...result.config.userId ? { userId: result.config.userId } : {},
|
|
1617
|
+
captureContent: result.config.captureContent
|
|
1618
|
+
}
|
|
1619
|
+
};
|
|
1620
|
+
},
|
|
1621
|
+
...resolveInjectedGitMetadata ? { resolveGitMetadata: (_pi, cwd) => resolveInjectedGitMetadata(cwd) } : {},
|
|
1622
|
+
onInitializationError(error, ctx) {
|
|
1623
|
+
const config = loadingConfig;
|
|
1624
|
+
loadingConfig = void 0;
|
|
1625
|
+
initializationError = `${backendLabel(config)} tracing could not start: ${formatError2(error, config)}`;
|
|
1626
|
+
ctx.ui.notify(initializationError, "warning");
|
|
1627
|
+
},
|
|
1628
|
+
beforeSessionDispose: async () => {
|
|
1629
|
+
await configWriteQueue;
|
|
1630
|
+
},
|
|
1631
|
+
onShutdownError(error, ctx) {
|
|
1632
|
+
ctx.ui.notify(
|
|
1633
|
+
`${backendLabel(shutdownConfig)} shutdown export failed: ${formatError2(error, shutdownConfig)}`,
|
|
1634
|
+
"error"
|
|
1635
|
+
);
|
|
1636
|
+
},
|
|
1637
|
+
flushOnReplacement: true,
|
|
1638
|
+
shutdownRuntimeOnQuit: true
|
|
1639
|
+
});
|
|
1640
|
+
async function showMenu(ctx) {
|
|
1641
|
+
if (!ctx.hasUI) {
|
|
1642
|
+
throw new Error(formatNonInteractiveStatus(activeConfig, configPath, initializationError));
|
|
1643
|
+
}
|
|
1644
|
+
const menuGeneration = sessionGeneration;
|
|
1645
|
+
const menuSignal = menuController.signal;
|
|
1646
|
+
const isCurrent = () => menuGeneration === sessionGeneration && !menuSignal.aborted;
|
|
1647
|
+
const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
|
|
1648
|
+
if (!isCurrent()) return;
|
|
1649
|
+
const menu = defineMenu({
|
|
1650
|
+
start: "main",
|
|
1651
|
+
screens: {
|
|
1652
|
+
main: () => ({
|
|
1653
|
+
kind: "actions",
|
|
1654
|
+
title: "Pi OTel",
|
|
1655
|
+
lines: formatMenuDetails(activeConfig, configPath, initializationError, configurationNotice),
|
|
1656
|
+
items: [
|
|
1657
|
+
...tracing.active ? [{ id: "flush", label: FLUSH_ACTION, action: "flush" }] : [],
|
|
1658
|
+
...storedBackend !== "otlp" ? [
|
|
1659
|
+
{
|
|
1660
|
+
id: "configure",
|
|
1661
|
+
label: storedBackend ? UPDATE_ACTION : SET_UP_ACTION,
|
|
1662
|
+
action: "configure"
|
|
1663
|
+
}
|
|
1664
|
+
] : [],
|
|
1665
|
+
{ id: "settings", label: "Settings (edit private file)", action: "settings" },
|
|
1666
|
+
{ id: "help", label: HELP_ACTION, action: "help" }
|
|
1667
|
+
],
|
|
1668
|
+
hint: "close"
|
|
1669
|
+
})
|
|
1670
|
+
},
|
|
1671
|
+
actions: {
|
|
1672
|
+
flush: async () => {
|
|
1673
|
+
const menuConfig = activeConfig;
|
|
1674
|
+
const label = backendLabel(menuConfig);
|
|
1675
|
+
if (!tracing.active) {
|
|
1676
|
+
ctx.ui.notify(`${label} tracing is not enabled for this session.`, "warning");
|
|
1677
|
+
return { kind: "close" };
|
|
1678
|
+
}
|
|
1679
|
+
try {
|
|
1680
|
+
await tracing.flush();
|
|
1681
|
+
if (!isCurrent()) return { kind: "close" };
|
|
1682
|
+
ctx.ui.notify(`${label} traces flushed for this session.`, "info");
|
|
1683
|
+
} catch (error) {
|
|
1684
|
+
if (!isCurrent()) return { kind: "close" };
|
|
1685
|
+
ctx.ui.notify(`${label} flush failed: ${formatError2(error, menuConfig)}`, "error");
|
|
1686
|
+
}
|
|
1687
|
+
return { kind: "close" };
|
|
1688
|
+
},
|
|
1689
|
+
configure: async () => {
|
|
1690
|
+
const loaded = await loadConfig();
|
|
1691
|
+
if (!isCurrent()) return { kind: "close" };
|
|
1692
|
+
configPath = loaded.path;
|
|
1693
|
+
const current = loaded.ok ? loaded.config : void 0;
|
|
1694
|
+
storedBackend = current ? current.backend ?? "langfuse" : void 0;
|
|
1695
|
+
if (loaded.legacy || current?.backend === "otlp") {
|
|
1696
|
+
ctx.ui.notify(formatSettingsNotice(configPath, loaded.legacy), "info");
|
|
1697
|
+
return { kind: "close" };
|
|
1698
|
+
}
|
|
1699
|
+
const next = await promptForConfig(ctx, current, menuSignal);
|
|
1700
|
+
if (!next || !isCurrent()) return { kind: "close" };
|
|
1701
|
+
try {
|
|
1702
|
+
const write = configWriteQueue.then(() => writeConfig(next, loaded.path));
|
|
1703
|
+
configWriteQueue = write.then(
|
|
1704
|
+
() => void 0,
|
|
1705
|
+
() => void 0
|
|
1706
|
+
);
|
|
1707
|
+
await write;
|
|
1708
|
+
if (!isCurrent()) return { kind: "close" };
|
|
1709
|
+
storedBackend = "langfuse";
|
|
1710
|
+
configurationNotice = "Saved; restart each Pi process to use it in subsequent sessions.";
|
|
1711
|
+
ctx.ui.notify(
|
|
1712
|
+
`Saved Langfuse config to ${stripVTControlCharacters(loaded.path)} for this Pi agent directory. Restart each Pi process to apply it to subsequent sessions.`,
|
|
1713
|
+
"info"
|
|
1714
|
+
);
|
|
1715
|
+
} catch (error) {
|
|
1716
|
+
if (!isCurrent()) return { kind: "close" };
|
|
1717
|
+
ctx.ui.notify(`Failed to save Langfuse config: ${formatError2(error, { ...current, ...next })}`, "error");
|
|
1718
|
+
}
|
|
1719
|
+
return { kind: "close" };
|
|
1720
|
+
},
|
|
1721
|
+
settings: async () => {
|
|
1722
|
+
ctx.ui.notify(formatSettingsNotice(configPath), "info");
|
|
1723
|
+
return { kind: "close" };
|
|
1724
|
+
},
|
|
1725
|
+
help: async () => {
|
|
1726
|
+
ctx.ui.notify(formatHelp(configPath), "info");
|
|
1727
|
+
return { kind: "close" };
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
});
|
|
1731
|
+
await runMenu(ctx, menu, {
|
|
1732
|
+
getState: () => void 0,
|
|
1733
|
+
signal: menuSignal,
|
|
1734
|
+
isCurrent
|
|
1735
|
+
});
|
|
1736
|
+
}
|
|
1737
|
+
pi.registerCommand("otel", {
|
|
1738
|
+
description: "Show OpenTelemetry tracing status, settings, and export controls",
|
|
1739
|
+
handler: async (args, ctx) => {
|
|
1740
|
+
if (args.trim()) throw new Error("/otel takes no arguments.");
|
|
1741
|
+
await showMenu(ctx);
|
|
1742
|
+
}
|
|
1743
|
+
});
|
|
1744
|
+
pi.registerCommand("langfuse", {
|
|
1745
|
+
description: "Deprecated: use /otel instead",
|
|
1746
|
+
handler: async (_args, ctx) => {
|
|
1747
|
+
if (ctx.hasUI) ctx.ui.notify("/langfuse is deprecated. Use /otel instead.", "warning");
|
|
1748
|
+
await showMenu(ctx);
|
|
1749
|
+
}
|
|
1750
|
+
});
|
|
1751
|
+
tracing.extension(pi);
|
|
1752
|
+
};
|
|
1753
|
+
}
|
|
1754
|
+
async function promptForConfig(ctx, current, signal) {
|
|
1755
|
+
const secretKey = await ctx.ui.input("Langfuse secret key (leave blank to keep existing):", void 0, { signal });
|
|
1756
|
+
if (signal.aborted) return void 0;
|
|
1757
|
+
if (secretKey === void 0) {
|
|
1758
|
+
ctx.ui.notify("Cancelled", "info");
|
|
1759
|
+
return void 0;
|
|
1760
|
+
}
|
|
1761
|
+
const publicKey = await ctx.ui.input("Langfuse public key (leave blank to keep existing):", void 0, { signal });
|
|
1762
|
+
if (signal.aborted) return void 0;
|
|
1763
|
+
if (publicKey === void 0) {
|
|
1764
|
+
ctx.ui.notify("Cancelled", "info");
|
|
1765
|
+
return void 0;
|
|
1766
|
+
}
|
|
1767
|
+
const baseUrl = await ctx.ui.input(
|
|
1768
|
+
`Langfuse base URL (leave blank for default ${DEFAULT_BASE_URL}):`,
|
|
1769
|
+
DEFAULT_BASE_URL,
|
|
1770
|
+
{ signal }
|
|
1771
|
+
);
|
|
1772
|
+
if (signal.aborted) return void 0;
|
|
1773
|
+
if (baseUrl === void 0) {
|
|
1774
|
+
ctx.ui.notify("Cancelled", "info");
|
|
1775
|
+
return void 0;
|
|
1776
|
+
}
|
|
1777
|
+
const patch = {
|
|
1778
|
+
...publicKey.trim() ? { publicKey: publicKey.trim() } : {},
|
|
1779
|
+
...secretKey.trim() ? { secretKey: secretKey.trim() } : {},
|
|
1780
|
+
baseUrl: baseUrl.trim() || DEFAULT_BASE_URL
|
|
1781
|
+
};
|
|
1782
|
+
const normalized = normalizeLangfuseConfig({ ...current, ...patch });
|
|
1783
|
+
if (!normalized.ok) {
|
|
1784
|
+
ctx.ui.notify(`Invalid Langfuse config: ${normalized.reason}`, "error");
|
|
1785
|
+
return void 0;
|
|
1786
|
+
}
|
|
1787
|
+
return patch;
|
|
1788
|
+
}
|
|
1789
|
+
function formatMenuDetails(activeConfig, configPath, initializationError, configurationNotice) {
|
|
1790
|
+
const lines = ["Current session:", ` Tracing: ${activeConfig ? "enabled" : "disabled"}`];
|
|
1791
|
+
if (activeConfig) {
|
|
1792
|
+
lines.push(...connectionDetails(activeConfig));
|
|
1793
|
+
} else if (configurationNotice) {
|
|
1794
|
+
lines.push(" State: tracing remains disabled until Pi restarts.");
|
|
1795
|
+
} else if (initializationError) {
|
|
1796
|
+
lines.push(` Reason: ${initializationError}`);
|
|
1797
|
+
}
|
|
1798
|
+
lines.push(
|
|
1799
|
+
"",
|
|
1800
|
+
"Agent-directory configuration:",
|
|
1801
|
+
` Configuration: ${displaySettingsPath(configPath)}`,
|
|
1802
|
+
" Scope: this Pi agent directory; restart each Pi process to apply changes."
|
|
1803
|
+
);
|
|
1804
|
+
if (configurationNotice) lines.push(` Pending: ${configurationNotice}`);
|
|
1805
|
+
lines.push("", "What do you want to do?");
|
|
1806
|
+
return lines;
|
|
1807
|
+
}
|
|
1808
|
+
function formatNonInteractiveStatus(activeConfig, configPath, initializationError) {
|
|
1809
|
+
return [
|
|
1810
|
+
"/otel requires interactive UI.",
|
|
1811
|
+
`Current session tracing: ${activeConfig ? "enabled" : "disabled"}`,
|
|
1812
|
+
...activeConfig ? connectionDetails(activeConfig) : initializationError ? [`Reason: ${initializationError}`] : [],
|
|
1813
|
+
`Configuration: ${displaySettingsPath(configPath)}`,
|
|
1814
|
+
"Edit the private config manually, then restart each Pi process to apply it to subsequent sessions."
|
|
1815
|
+
].join("\n");
|
|
1816
|
+
}
|
|
1817
|
+
function backendLabel(config) {
|
|
1818
|
+
return config?.backend === "otlp" ? "OTLP" : "Langfuse";
|
|
1819
|
+
}
|
|
1820
|
+
function connectionDetails(settings) {
|
|
1821
|
+
const otlp = settings.backend === "otlp";
|
|
1822
|
+
return [
|
|
1823
|
+
`Backend: ${backendLabel(settings)}`,
|
|
1824
|
+
otlp ? `Endpoint origin: ${new URL(settings.endpoint).origin}` : `Endpoint: ${settings.baseUrl}`,
|
|
1825
|
+
...otlp && Object.keys(settings.headers).length ? ["Export headers: settings file"] : [],
|
|
1826
|
+
`Content capture: ${settings.captureContent ? "enabled" : "disabled"}`
|
|
1827
|
+
];
|
|
1828
|
+
}
|
|
1829
|
+
function displaySettingsPath(path = otelSettingsPath()) {
|
|
1830
|
+
return stripVTControlCharacters(path);
|
|
1831
|
+
}
|
|
1832
|
+
function formatSettingsNotice(path, legacy = false) {
|
|
1833
|
+
const canonical = displaySettingsPath();
|
|
1834
|
+
return legacy ? `Read-only legacy settings: ${displaySettingsPath(path)}. Move the file to ${canonical} before editing it.` : `Edit the private settings file: ${canonical}. Restart each Pi process to change its export connection.`;
|
|
1835
|
+
}
|
|
1836
|
+
function formatHelp(configPath) {
|
|
1837
|
+
return [
|
|
1838
|
+
"Pi OTel setup and privacy:",
|
|
1839
|
+
'For an OTLP collector, set backend to "otlp" and enter the full traces endpoint in the settings file.',
|
|
1840
|
+
"For Langfuse, use the setup action in /otel or edit the settings file manually.",
|
|
1841
|
+
`Configuration: ${displaySettingsPath(configPath)}`,
|
|
1842
|
+
"The file belongs to this Pi agent directory; restart each Pi process after changing it.",
|
|
1843
|
+
"Trace content may contain prompts, responses, tool arguments, tool results, and source code.",
|
|
1844
|
+
"Git branch, commit, cwd, model, and usage remain in metadata when content capture is disabled.",
|
|
1845
|
+
'Use "captureContent": false in the private config to export metadata only.'
|
|
1846
|
+
].join("\n");
|
|
1847
|
+
}
|
|
1848
|
+
function formatConfigError(result) {
|
|
1849
|
+
const setupHint = result.missing || result.reason.startsWith("Configuration file not found:") ? " Run /otel and choose Set up Langfuse, or configure an OTLP endpoint in pi-otel.json." : "";
|
|
1850
|
+
return `Tracing is disabled: ${stripVTControlCharacters(result.reason)}${setupHint}`;
|
|
1851
|
+
}
|
|
1852
|
+
function formatError2(error, config) {
|
|
1853
|
+
let message = error instanceof Error ? error.message : String(error);
|
|
1854
|
+
const otlp = config?.backend === "otlp";
|
|
1855
|
+
const secrets = otlp ? [config.endpoint, ...otlpSecrets(config.headers)].sort((left, right) => right.length - left.length) : [config?.publicKey, config?.secretKey].filter((secret) => Boolean(secret)).sort((left, right) => right.length - left.length);
|
|
1856
|
+
for (const secret of secrets) {
|
|
1857
|
+
message = message.replaceAll(secret, otlp ? "[OTLP_SECRET_REDACTED]" : "[LANGFUSE_KEY_REDACTED]");
|
|
1858
|
+
}
|
|
1859
|
+
return stripVTControlCharacters(message);
|
|
1860
|
+
}
|
|
1861
|
+
var otel_default = createOtelExtension();
|
|
1862
|
+
|
|
1863
|
+
// src/runtime-api.ts
|
|
1864
|
+
async function createLangfuseRuntime(options = {}) {
|
|
1865
|
+
const runtime = await import("./chunks/runtime-KWIFBNQ2.ts");
|
|
1866
|
+
return runtime.createLangfuseRuntime(options);
|
|
1867
|
+
}
|
|
1868
|
+
async function createOtelRuntime(config) {
|
|
1869
|
+
const runtime = await import("./chunks/runtime-KWIFBNQ2.ts");
|
|
1870
|
+
return runtime.createOtelRuntime(config);
|
|
1871
|
+
}
|
|
1872
|
+
export {
|
|
1873
|
+
createLangfuseRuntime,
|
|
1874
|
+
createOtelRuntime,
|
|
1875
|
+
createPiLangfuseSession,
|
|
1876
|
+
otel_default as default
|
|
1877
|
+
};
|
|
1878
|
+
//# sourceMappingURL=index.ts.map
|