pi-langfuse 1.6.1 → 1.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +76 -2
- package/README_CN.md +49 -1
- package/index.ts +14 -2
- package/package.json +6 -3
- package/src/commands.ts +34 -2
- package/src/handlers/agent.ts +4 -2
- package/src/handlers/cache.ts +4 -2
- package/src/handlers/generation.ts +58 -53
- package/src/handlers/session.ts +71 -13
- package/src/handlers/system-state.ts +4 -1
- package/src/handlers/tool.ts +46 -13
- package/src/langfuse.ts +76 -65
- package/src/observation.ts +27 -0
- package/src/redaction.ts +145 -10
- package/src/session-lineage.ts +98 -0
- package/src/state.ts +7 -0
- package/src/types.ts +2 -0
- package/src/utils.ts +118 -19
package/src/redaction.ts
CHANGED
|
@@ -30,16 +30,107 @@ function defaultOptions(): RedactOptions {
|
|
|
30
30
|
};
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
const PRIVATE_KEY_RE = /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g;
|
|
33
|
+
const SENSITIVE_ASSIGNMENT_KEY_RE = /SECRET|TOKEN|PASSWORD|PASS|API[_-]?KEY|PRIVATE[_-]?KEY|AUTH|COOKIE/i;
|
|
34
|
+
const PRIVATE_KEY_RE = /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g;
|
|
36
35
|
const BEARER_RE = /\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi;
|
|
37
36
|
const KNOWN_TOKEN_RE =
|
|
38
37
|
/\b(?:sk-(?:lf|ant|proj|live|test)[A-Za-z0-9_-]*|pk-lf-[A-Za-z0-9_-]+|gh[pousr]_[A-Za-z0-9_]{20,}|npm_[A-Za-z0-9_-]{20,}|AKIA[0-9A-Z]{16})\b/g;
|
|
39
38
|
const ABSOLUTE_PATH_RE =
|
|
40
39
|
/(?:\/Users\/[^/\s]+|\/home\/[^/\s]+|\/private\/tmp|\/tmp|[A-Za-z]:\\Users\\[^\\\s]+)(?:[^\s"'`]*)/g;
|
|
41
|
-
const
|
|
42
|
-
|
|
40
|
+
const SENSITIVE_FIELDS = new Set([
|
|
41
|
+
"authorization", "cookie", "setcookie", "xapikey", "apikey", "token", "accesstoken",
|
|
42
|
+
"refreshtoken", "secret", "secretkey", "password", "passwd", "privatekey",
|
|
43
|
+
]);
|
|
44
|
+
const MAX_SENSITIVE_FIELD_LENGTH = Math.max(...[...SENSITIVE_FIELDS].map(key => key.length));
|
|
45
|
+
|
|
46
|
+
function isSensitiveField(key: string): boolean {
|
|
47
|
+
return SENSITIVE_FIELDS.has(key.replace(/[^a-zA-Z0-9]/g, "").toLowerCase());
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function inspectJsonFields(text: string, exceededBudget: () => boolean): boolean {
|
|
51
|
+
let inKey = false;
|
|
52
|
+
let validKey = true;
|
|
53
|
+
let normalizedKey = "";
|
|
54
|
+
const maskedValue = /\s*"\[REDACTED_SECRET\]"(?=\s*[,}\]]|\s*$)/y;
|
|
55
|
+
|
|
56
|
+
function appendKeyCharacter(char: string) {
|
|
57
|
+
// Keep one extra character to distinguish long, non-sensitive names.
|
|
58
|
+
if (normalizedKey.length <= MAX_SENSITIVE_FIELD_LENGTH && /[a-zA-Z0-9]/.test(char)) {
|
|
59
|
+
normalizedKey += char.toLowerCase();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Scan each candidate once. Interior escaped quotes share its closing quote;
|
|
64
|
+
// retrying from them after a failed match would rescan the same suffix.
|
|
65
|
+
// Reuse a closing quote as the next opener when it is not followed by a colon,
|
|
66
|
+
// so an unmatched prose quote cannot hide a later JSON field.
|
|
67
|
+
for (let index = 0; index < text.length; index++) {
|
|
68
|
+
const char = text[index];
|
|
69
|
+
if (!inKey) {
|
|
70
|
+
if (char !== '"') continue;
|
|
71
|
+
inKey = true;
|
|
72
|
+
validKey = true;
|
|
73
|
+
normalizedKey = "";
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (char === '"') {
|
|
77
|
+
let colon = index + 1;
|
|
78
|
+
while (colon < text.length && /\s/.test(text[colon])) colon++;
|
|
79
|
+
if (text[colon] === ":") {
|
|
80
|
+
if (exceededBudget()) return true;
|
|
81
|
+
if (validKey && SENSITIVE_FIELDS.has(normalizedKey)) {
|
|
82
|
+
maskedValue.lastIndex = colon + 1;
|
|
83
|
+
if (!maskedValue.test(text)) return true;
|
|
84
|
+
}
|
|
85
|
+
inKey = false;
|
|
86
|
+
index = colon;
|
|
87
|
+
}
|
|
88
|
+
validKey = true;
|
|
89
|
+
normalizedKey = "";
|
|
90
|
+
} else if (char === "\\") {
|
|
91
|
+
const escaped = text[++index];
|
|
92
|
+
if (escaped === undefined || /[\n\r\u2028\u2029]/.test(escaped)) {
|
|
93
|
+
inKey = false;
|
|
94
|
+
} else if (escaped === "u") {
|
|
95
|
+
const hex = text.slice(index + 1, index + 5);
|
|
96
|
+
if (/^[0-9a-f]{4}$/i.test(hex)) {
|
|
97
|
+
appendKeyCharacter(String.fromCharCode(parseInt(hex, 16)));
|
|
98
|
+
index += 4;
|
|
99
|
+
} else {
|
|
100
|
+
validKey = false;
|
|
101
|
+
}
|
|
102
|
+
} else if (!'"\\/bfnrt'.includes(escaped)) {
|
|
103
|
+
validKey = false;
|
|
104
|
+
}
|
|
105
|
+
} else if (char.charCodeAt(0) < 0x20) {
|
|
106
|
+
validKey = false;
|
|
107
|
+
} else {
|
|
108
|
+
appendKeyCharacter(char);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Recognize unmasked fields even when surrounding prose prevents parsing the JSON. */
|
|
115
|
+
export function hasUnredactedSensitiveJsonField(value: string): boolean {
|
|
116
|
+
const { maxDepth, maxNodes } = getLimits();
|
|
117
|
+
let nodes = 0;
|
|
118
|
+
function inspect(text: string, depth: number): boolean {
|
|
119
|
+
if (inspectJsonFields(text, () => ++nodes > maxNodes)) return true;
|
|
120
|
+
for (const match of text.matchAll(/"((?:\\[\s\S]?|[^"\\])*)("|$)/g)) {
|
|
121
|
+
if (++nodes > maxNodes) return true;
|
|
122
|
+
try {
|
|
123
|
+
const decoded: string = JSON.parse(match[0]);
|
|
124
|
+
if (decoded.includes('"') && (depth >= maxDepth || inspect(decoded, depth + 1))) return true;
|
|
125
|
+
} catch {
|
|
126
|
+
// Truncated or invalid escaping must not hide an embedded JSON credential.
|
|
127
|
+
if (match[1].includes("\\")) return true;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
return inspect(value, 0);
|
|
133
|
+
}
|
|
43
134
|
|
|
44
135
|
export function hashPath(path: string): string {
|
|
45
136
|
return `[PATH_HASH:${createHash("sha256").update(path).digest("hex").slice(0, 12)}]`;
|
|
@@ -49,13 +140,58 @@ function truncate(value: string, maxStringLength: number): string {
|
|
|
49
140
|
return value.length > maxStringLength ? `${value.slice(0, maxStringLength)}... [truncated]` : value;
|
|
50
141
|
}
|
|
51
142
|
|
|
143
|
+
function assignmentValueEnd(value: string, start: number): number {
|
|
144
|
+
let quote: string | undefined;
|
|
145
|
+
let quoteSlashes = 0;
|
|
146
|
+
let end = start;
|
|
147
|
+
while (end < value.length) {
|
|
148
|
+
const slashStart = end;
|
|
149
|
+
while (value[end] === "\\") end++;
|
|
150
|
+
const slashes = end - slashStart;
|
|
151
|
+
const char = value[end];
|
|
152
|
+
if (char === undefined) break;
|
|
153
|
+
if (quote) {
|
|
154
|
+
// JSON escapes double quotes, revealing their depth; single quotes stay ambiguous.
|
|
155
|
+
const closesQuote = quote === "'" ? slashes === quoteSlashes
|
|
156
|
+
: slashes % (2 * (quoteSlashes + 1)) === quoteSlashes;
|
|
157
|
+
if (char === quote && closesQuote) quote = undefined;
|
|
158
|
+
} else if (char === '"' || char === "'") {
|
|
159
|
+
quote = char;
|
|
160
|
+
quoteSlashes = slashes;
|
|
161
|
+
} else if (slashes === 0 && /\s|`/.test(char)) {
|
|
162
|
+
break;
|
|
163
|
+
}
|
|
164
|
+
end++;
|
|
165
|
+
}
|
|
166
|
+
// A missing closing quote keeps the remaining value secret.
|
|
167
|
+
return end;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function redactAssignments(value: string): string {
|
|
171
|
+
// Tokenize each key once; retrying sensitive fragments inside long keys is quadratic.
|
|
172
|
+
const keys = /(?<![\w-])([\w-]+)\s*=\s*/g;
|
|
173
|
+
const parts: string[] = [];
|
|
174
|
+
let cursor = 0;
|
|
175
|
+
let match: RegExpExecArray | null;
|
|
176
|
+
while ((match = keys.exec(value))) {
|
|
177
|
+
if (!SENSITIVE_ASSIGNMENT_KEY_RE.test(match[1])) continue;
|
|
178
|
+
const end = assignmentValueEnd(value, keys.lastIndex);
|
|
179
|
+
if (end === keys.lastIndex) continue;
|
|
180
|
+
parts.push(value.slice(cursor, match.index), `${match[1]}=${REDACTED}`);
|
|
181
|
+
cursor = keys.lastIndex = end;
|
|
182
|
+
}
|
|
183
|
+
parts.push(value.slice(cursor));
|
|
184
|
+
return parts.join("");
|
|
185
|
+
}
|
|
186
|
+
|
|
52
187
|
export function redactString(value: string, options: Partial<RedactOptions> = {}): string {
|
|
53
188
|
const merged = { ...defaultOptions(), ...options };
|
|
54
|
-
|
|
189
|
+
// Truncating first can make a known token too short for its recognizer.
|
|
190
|
+
const secretsRedacted = truncate(redactAssignments(value
|
|
55
191
|
.replace(PRIVATE_KEY_RE, REDACTED)
|
|
56
192
|
.replace(BEARER_RE, REDACTED)
|
|
57
|
-
.replace(KNOWN_TOKEN_RE, REDACTED)
|
|
58
|
-
|
|
193
|
+
.replace(KNOWN_TOKEN_RE, REDACTED)), merged.maxStringLength);
|
|
194
|
+
if (hasUnredactedSensitiveJsonField(secretsRedacted)) return REDACTED;
|
|
59
195
|
|
|
60
196
|
if (!merged.redactPaths) {
|
|
61
197
|
return secretsRedacted;
|
|
@@ -118,8 +254,7 @@ function visit(value: unknown, options: RedactOptions, depth: number, seen: Weak
|
|
|
118
254
|
const entries = Object.entries(value as Record<string, unknown>);
|
|
119
255
|
const output: Record<string, unknown> = {};
|
|
120
256
|
for (const [key, item] of entries.slice(0, options.maxObjectKeys)) {
|
|
121
|
-
|
|
122
|
-
output[key] = SENSITIVE_FIELD_RE.test(normalizedKey) ? REDACTED : visit(item, options, depth - 1, seen);
|
|
257
|
+
output[key] = isSensitiveField(key) ? REDACTED : visit(item, options, depth - 1, seen);
|
|
123
258
|
}
|
|
124
259
|
if (entries.length > options.maxObjectKeys) {
|
|
125
260
|
output.__truncatedKeys = entries.length - options.maxObjectKeys;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { closeSync, openSync, readSync } from "node:fs";
|
|
2
|
+
import { basename } from "node:path";
|
|
3
|
+
import { getSessionRunState } from "./state.js";
|
|
4
|
+
import { redactString } from "./redaction.js";
|
|
5
|
+
|
|
6
|
+
export interface SessionLineage {
|
|
7
|
+
parentSessionId?: string;
|
|
8
|
+
sessionKind?: "subagent" | "fork";
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// Pi names session files either "<timestamp>_<uuid>.jsonl" or "session.jsonl"
|
|
12
|
+
// (165 of 368 local files use the latter), so the id cannot be read from the
|
|
13
|
+
// name alone. The header line is short; reading a bounded prefix keeps a large
|
|
14
|
+
// transcript from being pulled into memory for one id.
|
|
15
|
+
const HEADER_READ_BYTES = 4096;
|
|
16
|
+
const SESSION_ID_PATTERN = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
17
|
+
|
|
18
|
+
function readSessionFileId(filePath: string): string | undefined {
|
|
19
|
+
let fd: number | undefined;
|
|
20
|
+
try {
|
|
21
|
+
fd = openSync(filePath, "r");
|
|
22
|
+
const buffer = Buffer.alloc(HEADER_READ_BYTES);
|
|
23
|
+
const bytesRead = readSync(fd, buffer, 0, HEADER_READ_BYTES, 0);
|
|
24
|
+
const firstLine = buffer.subarray(0, bytesRead).toString("utf8").split("\n", 1)[0];
|
|
25
|
+
const header: unknown = JSON.parse(firstLine);
|
|
26
|
+
const id = (header as { id?: unknown }).id;
|
|
27
|
+
return typeof id === "string" && id ? id : undefined;
|
|
28
|
+
} catch {
|
|
29
|
+
return undefined;
|
|
30
|
+
} finally {
|
|
31
|
+
if (fd !== undefined) {
|
|
32
|
+
try {
|
|
33
|
+
closeSync(fd);
|
|
34
|
+
} catch {
|
|
35
|
+
// Already-rotated file: the id stays unresolved, which only loses lineage.
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Session lineage from Pi's public session header (`SessionHeader.parentSession`).
|
|
43
|
+
* `sessionKind` is a best-effort guess: pi-subagents marks child processes with
|
|
44
|
+
* PI_SUBAGENT_CHILD, and that flag is not a contract this package owns, so a
|
|
45
|
+
* missing flag only degrades the label to "fork".
|
|
46
|
+
*/
|
|
47
|
+
export function resolveSessionLineage(
|
|
48
|
+
sessionManager: unknown,
|
|
49
|
+
env: Record<string, string | undefined> = process.env,
|
|
50
|
+
): SessionLineage {
|
|
51
|
+
const lineage: SessionLineage = {};
|
|
52
|
+
const parentSession = (sessionManager as { getHeader?: () => { parentSession?: unknown } | null } | undefined)
|
|
53
|
+
?.getHeader?.()?.parentSession;
|
|
54
|
+
|
|
55
|
+
if (typeof parentSession === "string" && parentSession) {
|
|
56
|
+
const parentSessionId = readSessionFileId(parentSession)
|
|
57
|
+
?? basename(parentSession).replace(/\.jsonl$/i, "").match(SESSION_ID_PATTERN)?.[0];
|
|
58
|
+
if (parentSessionId) {
|
|
59
|
+
lineage.parentSessionId = parentSessionId;
|
|
60
|
+
}
|
|
61
|
+
lineage.sessionKind = env.PI_SUBAGENT_CHILD === "1" ? "subagent" : "fork";
|
|
62
|
+
} else if (env.PI_SUBAGENT_CHILD === "1") {
|
|
63
|
+
lineage.sessionKind = "subagent";
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return lineage;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Resolves once per session and caches the result, including "no parent". */
|
|
70
|
+
export function bindSessionLineage(sessionManager?: unknown): void {
|
|
71
|
+
const sessionState = getSessionRunState();
|
|
72
|
+
if (sessionState.lineageResolved) {
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
// Without a header source the answer is unknown, not "root": leave the cache
|
|
76
|
+
// open so a later call that holds a real session manager can resolve it.
|
|
77
|
+
if (typeof (sessionManager as { getHeader?: unknown } | undefined)?.getHeader !== "function") {
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const lineage = resolveSessionLineage(sessionManager);
|
|
81
|
+
sessionState.parentSessionId = lineage.parentSessionId;
|
|
82
|
+
sessionState.sessionKind = lineage.sessionKind;
|
|
83
|
+
sessionState.lineageResolved = true;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Metadata for the active session; empty for a root session with no parent. */
|
|
87
|
+
export function sessionLineageMetadata(sessionManager?: unknown): Record<string, string> {
|
|
88
|
+
bindSessionLineage(sessionManager);
|
|
89
|
+
const sessionState = getSessionRunState();
|
|
90
|
+
const metadata: Record<string, string> = {};
|
|
91
|
+
if (sessionState.parentSessionId) {
|
|
92
|
+
metadata.parentSessionId = redactString(sessionState.parentSessionId);
|
|
93
|
+
}
|
|
94
|
+
if (sessionState.sessionKind) {
|
|
95
|
+
metadata.sessionKind = sessionState.sessionKind;
|
|
96
|
+
}
|
|
97
|
+
return metadata;
|
|
98
|
+
}
|
package/src/state.ts
CHANGED
|
@@ -13,6 +13,9 @@ export interface SessionRunState {
|
|
|
13
13
|
lastPromptStateHash?: string;
|
|
14
14
|
lastToolStateHash?: string;
|
|
15
15
|
lastActiveTools: string[];
|
|
16
|
+
parentSessionId?: string;
|
|
17
|
+
sessionKind?: "subagent" | "fork";
|
|
18
|
+
lineageResolved: boolean;
|
|
16
19
|
systemStateSequence: number;
|
|
17
20
|
seenSystemEntryIds: Set<string>;
|
|
18
21
|
seenUsageEntryIds: Set<string>;
|
|
@@ -34,6 +37,7 @@ function createSessionRunState(): SessionRunState {
|
|
|
34
37
|
tracingDisabled: false,
|
|
35
38
|
setupAttemptedThisSession: false,
|
|
36
39
|
lastActiveTools: [],
|
|
40
|
+
lineageResolved: false,
|
|
37
41
|
systemStateSequence: 0,
|
|
38
42
|
seenSystemEntryIds: new Set(),
|
|
39
43
|
seenUsageEntryIds: new Set(),
|
|
@@ -147,6 +151,9 @@ export function resetRunState(sessionId = getActiveSessionId()) {
|
|
|
147
151
|
lastPromptStateHash: previous?.lastPromptStateHash,
|
|
148
152
|
lastToolStateHash: previous?.lastToolStateHash,
|
|
149
153
|
lastActiveTools: previous?.lastActiveTools ?? [],
|
|
154
|
+
parentSessionId: previous?.parentSessionId,
|
|
155
|
+
sessionKind: previous?.sessionKind,
|
|
156
|
+
lineageResolved: previous?.lineageResolved ?? false,
|
|
150
157
|
systemStateSequence: previous?.systemStateSequence ?? 0,
|
|
151
158
|
seenSystemEntryIds: previous?.seenSystemEntryIds ?? new Set(),
|
|
152
159
|
seenUsageEntryIds: previous?.seenUsageEntryIds ?? new Set(),
|
package/src/types.ts
CHANGED
|
@@ -122,6 +122,7 @@ export interface GenerationState {
|
|
|
122
122
|
observation: LangfuseObservation;
|
|
123
123
|
requestKey: string;
|
|
124
124
|
ended: boolean;
|
|
125
|
+
errorStatus?: Pick<ObservationUpdate, "level" | "statusMessage">;
|
|
125
126
|
metadata: Record<string, unknown>;
|
|
126
127
|
modelParameters?: Record<string, string | number>;
|
|
127
128
|
ttftRecorded?: boolean;
|
|
@@ -133,6 +134,7 @@ export interface ToolState {
|
|
|
133
134
|
ended: boolean;
|
|
134
135
|
startedAt: number;
|
|
135
136
|
inputBytes: number;
|
|
137
|
+
parentToolCallId?: string;
|
|
136
138
|
}
|
|
137
139
|
|
|
138
140
|
export interface AgentState {
|
package/src/utils.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { getLimits } from "./limits.js";
|
|
2
2
|
import { getUsageOptions, type UsageOptions } from "./usage-options.js";
|
|
3
3
|
import { createCapturePolicy, redactOptionsFor, type CapturePolicy } from "./capture-policy.js";
|
|
4
|
-
import { redactValue } from "./redaction.js";
|
|
4
|
+
import { hasUnredactedSensitiveJsonField, redactString, redactValue } from "./redaction.js";
|
|
5
5
|
import { state } from "./state.js";
|
|
6
|
+
import type { ObservationUpdate } from "./types.js";
|
|
6
7
|
|
|
7
8
|
export function getCapturePolicy(): CapturePolicy {
|
|
8
9
|
return state.config?.capturePolicy ?? createCapturePolicy();
|
|
@@ -39,6 +40,7 @@ export function shapePayload(
|
|
|
39
40
|
maxObjectKeys?: number;
|
|
40
41
|
redact?: boolean;
|
|
41
42
|
parseJson?: boolean;
|
|
43
|
+
parseJsonPrefix?: boolean;
|
|
42
44
|
} = {},
|
|
43
45
|
): unknown {
|
|
44
46
|
const limits = getLimits();
|
|
@@ -48,6 +50,13 @@ export function shapePayload(
|
|
|
48
50
|
const maxArrayItems = options.maxArrayItems ?? limits.maxArrayItems;
|
|
49
51
|
const maxObjectKeys = options.maxObjectKeys ?? limits.maxObjectKeys;
|
|
50
52
|
const budget = { exhausted: false, nodeCount: 0 };
|
|
53
|
+
const redactionOptions = {
|
|
54
|
+
...redactOptionsFor(getCapturePolicy()),
|
|
55
|
+
maxDepth: depth,
|
|
56
|
+
maxStringLength: maxString,
|
|
57
|
+
maxArrayItems,
|
|
58
|
+
maxObjectKeys,
|
|
59
|
+
};
|
|
51
60
|
|
|
52
61
|
function visit(item: unknown, remainingDepth: number, seen: WeakSet<object>): unknown {
|
|
53
62
|
if (budget.exhausted) {
|
|
@@ -61,15 +70,31 @@ export function shapePayload(
|
|
|
61
70
|
}
|
|
62
71
|
|
|
63
72
|
if (typeof item === "string") {
|
|
73
|
+
const jsonStart = options.parseJsonPrefix ? item.search(/[\[{]/) : item.search(/^[\s]*[\[{]/);
|
|
74
|
+
// Truncated JSON loses field names needed for secret redaction.
|
|
75
|
+
if (options.parseJson !== false && jsonStart >= 0 && item.length > maxString) {
|
|
76
|
+
return PAYLOAD_TOO_LARGE;
|
|
77
|
+
}
|
|
64
78
|
const truncated = truncate(item, maxString);
|
|
65
79
|
if (options.parseJson === false) {
|
|
66
|
-
return truncated;
|
|
80
|
+
return options.redact === false ? truncated : redactString(item, redactionOptions);
|
|
81
|
+
}
|
|
82
|
+
const candidate = jsonStart > 0 ? truncated.slice(jsonStart) : truncated;
|
|
83
|
+
const parsed = tryParseJson(candidate);
|
|
84
|
+
if (parsed === candidate) {
|
|
85
|
+
// Native tool suffixes and bracketed prefixes can make JSON unparseable.
|
|
86
|
+
if (options.redact !== false && (
|
|
87
|
+
(options.parseJsonPrefix && /[\[{]\s*"/.test(truncated)) || hasUnredactedSensitiveJsonField(truncated)
|
|
88
|
+
)) return "[unparseable error payload]";
|
|
89
|
+
return options.redact === false ? truncated : redactString(item, redactionOptions);
|
|
67
90
|
}
|
|
68
|
-
const
|
|
69
|
-
if (
|
|
70
|
-
|
|
91
|
+
const shaped = visit(parsed, remainingDepth - 1, seen);
|
|
92
|
+
if (jsonStart > 0 && truncated.slice(0, jsonStart).trim()) {
|
|
93
|
+
// Pi/provider prefixes must not hide structured fields from redaction.
|
|
94
|
+
const safe = options.redact === false ? shaped : redactValue(shaped, redactionOptions);
|
|
95
|
+
return truncated.slice(0, jsonStart) + JSON.stringify(safe);
|
|
71
96
|
}
|
|
72
|
-
return
|
|
97
|
+
return shaped;
|
|
73
98
|
}
|
|
74
99
|
|
|
75
100
|
if (
|
|
@@ -106,11 +131,12 @@ export function shapePayload(
|
|
|
106
131
|
}
|
|
107
132
|
|
|
108
133
|
if (item instanceof Error) {
|
|
109
|
-
|
|
134
|
+
// The stack repeats the raw message; retain frames without that copy.
|
|
135
|
+
return visit({
|
|
110
136
|
name: item.name,
|
|
111
137
|
message: item.message,
|
|
112
|
-
stack: item.
|
|
113
|
-
};
|
|
138
|
+
stack: item.message ? item.stack?.replaceAll(item.message, "[error message]") : item.stack,
|
|
139
|
+
}, remainingDepth, seen);
|
|
114
140
|
}
|
|
115
141
|
|
|
116
142
|
if (typeof item === "object") {
|
|
@@ -140,13 +166,7 @@ export function shapePayload(
|
|
|
140
166
|
const shaped = visit(value, depth, new WeakSet<object>());
|
|
141
167
|
return options.redact === false
|
|
142
168
|
? shaped
|
|
143
|
-
: redactValue(shaped,
|
|
144
|
-
...redactOptionsFor(getCapturePolicy()),
|
|
145
|
-
maxDepth: depth,
|
|
146
|
-
maxStringLength: maxString,
|
|
147
|
-
maxArrayItems,
|
|
148
|
-
maxObjectKeys,
|
|
149
|
-
});
|
|
169
|
+
: redactValue(shaped, redactionOptions);
|
|
150
170
|
}
|
|
151
171
|
|
|
152
172
|
export function safeSerialize(value: unknown, maxLength = getLimits().maxToolPayload): string {
|
|
@@ -161,20 +181,38 @@ export function estimatePayloadBytes(value: unknown, maxLength = getLimits().max
|
|
|
161
181
|
return new TextEncoder().encode(safeSerialize(value, maxLength)).length;
|
|
162
182
|
}
|
|
163
183
|
|
|
164
|
-
export function extractTextContent(content: unknown, maxLength?: number): string | undefined {
|
|
184
|
+
export function extractTextContent(content: unknown, maxLength?: number, depth = 0): string | undefined {
|
|
165
185
|
if (typeof content === "string") {
|
|
166
186
|
return maxLength ? truncate(content, maxLength) : content;
|
|
167
187
|
}
|
|
168
188
|
|
|
169
189
|
if (!Array.isArray(content)) {
|
|
190
|
+
// Tool results arrive wrapped ({ content: [{ type: "text", text }] }, or with
|
|
191
|
+
// the payload under result/output/text). The wrapper alone stringifies to
|
|
192
|
+
// "[object Object]", so dig out the text the reader actually wants; the depth
|
|
193
|
+
// cap keeps a reference cycle from recursing forever.
|
|
194
|
+
if (content && typeof content === "object" && depth < 2) {
|
|
195
|
+
const wrapper = content as { content?: unknown; result?: unknown; output?: unknown; text?: unknown };
|
|
196
|
+
for (const nested of [wrapper.content, wrapper.result, wrapper.output, wrapper.text]) {
|
|
197
|
+
if (!nested || nested === content) {
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
const unwrapped = extractTextContent(nested, maxLength, depth + 1);
|
|
201
|
+
if (unwrapped) {
|
|
202
|
+
return unwrapped;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
170
206
|
return undefined;
|
|
171
207
|
}
|
|
172
208
|
|
|
173
209
|
const text = content
|
|
174
210
|
.map((item) => {
|
|
175
211
|
if (!item || typeof item !== "object") return "";
|
|
176
|
-
const block = item as { type?: string; text?:
|
|
177
|
-
return block.type === "text" && block.text
|
|
212
|
+
const block = item as { type?: string; text?: unknown };
|
|
213
|
+
return block.type === "text" && block.text
|
|
214
|
+
? typeof block.text === "string" ? block.text : safeSerialize(block.text, maxLength)
|
|
215
|
+
: "";
|
|
178
216
|
})
|
|
179
217
|
.filter(Boolean)
|
|
180
218
|
.join("\n");
|
|
@@ -186,6 +224,31 @@ export function extractTextContent(content: unknown, maxLength?: number): string
|
|
|
186
224
|
return maxLength ? truncate(text, maxLength) : text;
|
|
187
225
|
}
|
|
188
226
|
|
|
227
|
+
/**
|
|
228
|
+
* Human-readable text for an observation `statusMessage`: text blocks first, then
|
|
229
|
+
* the string, then JSON, so a structured error never lands as "[object Object]"
|
|
230
|
+
* or as a wall of escaped JSON. Shape and redact before extracting any text.
|
|
231
|
+
*/
|
|
232
|
+
export function toStatusMessage(value: unknown, maxLength = 1_000): string {
|
|
233
|
+
maxLength = Math.min(maxLength, getLimits().maxString);
|
|
234
|
+
const shaped = shapePayload(value instanceof Error ? value.message || String(value) : value, {
|
|
235
|
+
maxString: maxLength, parseJsonPrefix: true,
|
|
236
|
+
});
|
|
237
|
+
const text = extractTextContent(shaped, maxLength);
|
|
238
|
+
if (text) {
|
|
239
|
+
return text;
|
|
240
|
+
}
|
|
241
|
+
const message = (shaped as { message?: unknown } | null)?.message;
|
|
242
|
+
if (typeof message === "string" && message) {
|
|
243
|
+
return truncate(message, maxLength);
|
|
244
|
+
}
|
|
245
|
+
try {
|
|
246
|
+
return truncate(JSON.stringify(shaped) ?? String(shaped), maxLength);
|
|
247
|
+
} catch {
|
|
248
|
+
return "[unserializable error]";
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
189
252
|
export function normalizeContentForLangfuse(content: unknown, api?: string): unknown {
|
|
190
253
|
if (!Array.isArray(content)) {
|
|
191
254
|
return content;
|
|
@@ -410,6 +473,19 @@ export function extractModelParameters(payload: unknown): Record<string, string
|
|
|
410
473
|
return Object.keys(params).length > 0 ? params : undefined;
|
|
411
474
|
}
|
|
412
475
|
|
|
476
|
+
export function extractGenerationStatus(message: Record<string, unknown>): ObservationUpdate {
|
|
477
|
+
const reason = message.finishReason ?? message.stopReason;
|
|
478
|
+
if (reason !== "error" && reason !== "aborted") return {};
|
|
479
|
+
|
|
480
|
+
return {
|
|
481
|
+
level: reason === "error" ? "ERROR" : "WARNING",
|
|
482
|
+
statusMessage: toStatusMessage(
|
|
483
|
+
message.errorMessage || (reason === "error" ? "Generation failed" : "Generation aborted"),
|
|
484
|
+
getLimits().maxString,
|
|
485
|
+
),
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
|
|
413
489
|
export function getMessageFromEvent(event: Record<string, unknown>): Record<string, unknown> | undefined {
|
|
414
490
|
if (event.message && typeof event.message === "object") {
|
|
415
491
|
return event.message as Record<string, unknown>;
|
|
@@ -593,6 +669,29 @@ export function extractCostDetails(messageOrEvent: Record<string, unknown>): Rec
|
|
|
593
669
|
};
|
|
594
670
|
}
|
|
595
671
|
|
|
672
|
+
/** Accept both provider model ids and Pi Model objects without serializing the whole model. */
|
|
673
|
+
export function extractModelIdentity(value: unknown, provider?: unknown): { model?: string; provider?: string } {
|
|
674
|
+
const record = value && typeof value === "object" ? value as Record<string, unknown> : undefined;
|
|
675
|
+
const model = record?.id ?? record?.model ?? value;
|
|
676
|
+
const actualProvider = provider ?? record?.provider;
|
|
677
|
+
return {
|
|
678
|
+
...(typeof model === "string" && model ? { model } : {}),
|
|
679
|
+
...(typeof actualProvider === "string" && actualProvider ? { provider: actualProvider } : {}),
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
/** Tool hooks report own usage; transcript toolResult messages also include descendants' usage. */
|
|
684
|
+
export function extractToolUsage(event: Record<string, unknown>): {
|
|
685
|
+
usageDetails?: Record<string, number>;
|
|
686
|
+
costDetails?: Record<string, number>;
|
|
687
|
+
} {
|
|
688
|
+
const result = event.result && typeof event.result === "object"
|
|
689
|
+
? event.result as Record<string, unknown>
|
|
690
|
+
: {};
|
|
691
|
+
const source = { usage: event.usage ?? result.usage, cost: event.cost ?? result.cost };
|
|
692
|
+
return { usageDetails: extractUsage(source), costDetails: extractCostDetails(source) };
|
|
693
|
+
}
|
|
694
|
+
|
|
596
695
|
export function extractResponseMetadata(event: Record<string, unknown>): Record<string, unknown> {
|
|
597
696
|
return shapePayload(
|
|
598
697
|
{
|