pi-langfuse 1.7.0 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +87 -5
- package/README_CN.md +63 -5
- package/dist/index.d.ts +14 -0
- package/dist/index.js +216 -0
- package/dist/src/capture-policy.d.ts +43 -0
- package/dist/src/capture-policy.js +125 -0
- package/dist/src/commands.d.ts +25 -0
- package/dist/src/commands.js +374 -0
- package/dist/src/config.d.ts +13 -0
- package/dist/src/config.js +157 -0
- package/dist/src/constants.d.ts +9 -0
- package/dist/src/constants.js +11 -0
- package/dist/src/handlers/agent.d.ts +18 -0
- package/dist/src/handlers/agent.js +310 -0
- package/dist/src/handlers/cache.d.ts +5 -0
- package/dist/src/handlers/cache.js +134 -0
- package/dist/src/handlers/generation.d.ts +9 -0
- package/dist/src/handlers/generation.js +249 -0
- package/dist/src/handlers/session.d.ts +4 -0
- package/dist/src/handlers/session.js +121 -0
- package/dist/src/handlers/system-state.d.ts +3 -0
- package/dist/src/handlers/system-state.js +185 -0
- package/dist/src/handlers/tool.d.ts +3 -0
- package/dist/src/handlers/tool.js +168 -0
- package/dist/src/handlers/turn.d.ts +2 -0
- package/dist/src/handlers/turn.js +48 -0
- package/dist/src/langfuse.d.ts +42 -0
- package/dist/src/langfuse.js +837 -0
- package/dist/src/limits.d.ts +43 -0
- package/dist/src/limits.js +63 -0
- package/dist/src/observation.d.ts +24 -0
- package/dist/src/observation.js +24 -0
- package/dist/src/redaction.d.ts +14 -0
- package/dist/src/redaction.js +254 -0
- package/dist/src/session-lineage.d.ts +15 -0
- package/dist/src/session-lineage.js +87 -0
- package/dist/src/source-metadata.d.ts +2 -0
- package/dist/src/source-metadata.js +55 -0
- package/dist/src/state.d.ts +52 -0
- package/dist/src/state.js +144 -0
- package/dist/src/types.d.ts +157 -0
- package/dist/src/types.js +1 -0
- package/dist/src/usage-options.d.ts +27 -0
- package/dist/src/usage-options.js +21 -0
- package/dist/src/utils.d.ts +61 -0
- package/dist/src/utils.js +600 -0
- package/dist/src/workflow.d.ts +24 -0
- package/dist/src/workflow.js +62 -0
- package/examples/workflow-sdk.mjs +56 -0
- package/index.ts +47 -13
- package/package.json +16 -2
- package/src/commands.ts +48 -5
- package/src/config.ts +1 -1
- package/src/handlers/agent.ts +63 -33
- package/src/handlers/cache.ts +14 -10
- package/src/handlers/generation.ts +21 -43
- package/src/handlers/session.ts +71 -13
- package/src/handlers/tool.ts +12 -8
- package/src/langfuse.ts +110 -80
- package/src/observation.ts +31 -0
- package/src/redaction.ts +145 -10
- package/src/session-lineage.ts +98 -0
- package/src/state.ts +19 -2
- package/src/types.ts +2 -1
- package/src/utils.ts +95 -19
- package/src/workflow.ts +78 -0
package/src/observation.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { getSessionRunState } from "./state.js";
|
|
1
2
|
import type { LangfuseObservation, LangfuseRuntime, ObservationUpdate } from "./types.js";
|
|
2
3
|
|
|
3
4
|
export async function startChildObservation({
|
|
@@ -17,5 +18,35 @@ export async function startChildObservation({
|
|
|
17
18
|
return parent.startObservation(name, body, { asType });
|
|
18
19
|
}
|
|
19
20
|
|
|
21
|
+
if (getSessionRunState().runBinding?.parent) {
|
|
22
|
+
throw new Error("Cannot attach child observation to its workflow parent");
|
|
23
|
+
}
|
|
20
24
|
return (await runtime()).startObservation(name, body, { asType });
|
|
21
25
|
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Starts a top-level observation for a session-scoped event that arrives when no
|
|
29
|
+
* agent run is active (e.g. recovery compaction after a failed generation).
|
|
30
|
+
*
|
|
31
|
+
* Attributes must be passed explicitly: `propagateAttributes` only seeds the OTel
|
|
32
|
+
* context for the duration of its callback, so a root observation created outside
|
|
33
|
+
* a run would be written without `session.id` or `langfuse.trace.name` and would
|
|
34
|
+
* drop out of every session filter in Langfuse v4.
|
|
35
|
+
*/
|
|
36
|
+
export async function startSessionObservation({
|
|
37
|
+
runtime,
|
|
38
|
+
name,
|
|
39
|
+
body,
|
|
40
|
+
asType,
|
|
41
|
+
attributes,
|
|
42
|
+
}: {
|
|
43
|
+
runtime: () => Promise<LangfuseRuntime>;
|
|
44
|
+
name: string;
|
|
45
|
+
body?: ObservationUpdate;
|
|
46
|
+
asType: "event" | "generation" | "tool" | "span";
|
|
47
|
+
attributes: Parameters<LangfuseRuntime["propagateAttributes"]>[0];
|
|
48
|
+
}): Promise<LangfuseObservation> {
|
|
49
|
+
const rt = await runtime();
|
|
50
|
+
const create = () => rt.propagateAttributes(attributes, () => rt.startObservation(name, body, { asType }));
|
|
51
|
+
return rt.withRootContext ? rt.withRootContext(create) : create();
|
|
52
|
+
}
|
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
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
2
|
import type { Config, AgentState } from "./types.js";
|
|
3
|
+
import type { WorkflowBinding } from "./workflow.js";
|
|
3
4
|
|
|
4
5
|
export interface SessionRunState {
|
|
6
|
+
instance: symbol;
|
|
7
|
+
startupBinding?: WorkflowBinding;
|
|
8
|
+
runBinding?: WorkflowBinding;
|
|
9
|
+
startingRun?: Promise<void>;
|
|
10
|
+
finishingRun?: boolean;
|
|
11
|
+
workflowWarnings?: Set<string>;
|
|
5
12
|
currentModel: string;
|
|
6
13
|
currentProvider: string;
|
|
7
14
|
agentState: AgentState | null;
|
|
@@ -13,6 +20,9 @@ export interface SessionRunState {
|
|
|
13
20
|
lastPromptStateHash?: string;
|
|
14
21
|
lastToolStateHash?: string;
|
|
15
22
|
lastActiveTools: string[];
|
|
23
|
+
parentSessionId?: string;
|
|
24
|
+
sessionKind?: "subagent" | "fork";
|
|
25
|
+
lineageResolved: boolean;
|
|
16
26
|
systemStateSequence: number;
|
|
17
27
|
seenSystemEntryIds: Set<string>;
|
|
18
28
|
seenUsageEntryIds: Set<string>;
|
|
@@ -23,8 +33,9 @@ const DEFAULT_SESSION_ID = "__pi_langfuse_default_session__";
|
|
|
23
33
|
let activeSessionId = DEFAULT_SESSION_ID;
|
|
24
34
|
const sessionScope = new AsyncLocalStorage<string>();
|
|
25
35
|
|
|
26
|
-
function createSessionRunState(): SessionRunState {
|
|
36
|
+
function createSessionRunState(instance = Symbol("Pi session")): SessionRunState {
|
|
27
37
|
return {
|
|
38
|
+
instance,
|
|
28
39
|
currentModel: "",
|
|
29
40
|
currentProvider: "",
|
|
30
41
|
agentState: null,
|
|
@@ -34,6 +45,7 @@ function createSessionRunState(): SessionRunState {
|
|
|
34
45
|
tracingDisabled: false,
|
|
35
46
|
setupAttemptedThisSession: false,
|
|
36
47
|
lastActiveTools: [],
|
|
48
|
+
lineageResolved: false,
|
|
37
49
|
systemStateSequence: 0,
|
|
38
50
|
seenSystemEntryIds: new Set(),
|
|
39
51
|
seenUsageEntryIds: new Set(),
|
|
@@ -142,11 +154,16 @@ export function resetRunState(sessionId = getActiveSessionId()) {
|
|
|
142
154
|
const normalizedSessionId = normalizeSessionId(sessionId);
|
|
143
155
|
const previous = state.sessionStates.get(normalizedSessionId);
|
|
144
156
|
state.sessionStates.set(normalizedSessionId, {
|
|
145
|
-
...createSessionRunState(),
|
|
157
|
+
...createSessionRunState(previous?.instance),
|
|
158
|
+
startupBinding: previous?.startupBinding,
|
|
159
|
+
workflowWarnings: previous?.workflowWarnings,
|
|
146
160
|
setupAttemptedThisSession: previous?.setupAttemptedThisSession ?? false,
|
|
147
161
|
lastPromptStateHash: previous?.lastPromptStateHash,
|
|
148
162
|
lastToolStateHash: previous?.lastToolStateHash,
|
|
149
163
|
lastActiveTools: previous?.lastActiveTools ?? [],
|
|
164
|
+
parentSessionId: previous?.parentSessionId,
|
|
165
|
+
sessionKind: previous?.sessionKind,
|
|
166
|
+
lineageResolved: previous?.lineageResolved ?? false,
|
|
150
167
|
systemStateSequence: previous?.systemStateSequence ?? 0,
|
|
151
168
|
seenSystemEntryIds: previous?.seenSystemEntryIds ?? new Set(),
|
|
152
169
|
seenUsageEntryIds: previous?.seenUsageEntryIds ?? new Set(),
|
package/src/types.ts
CHANGED
|
@@ -83,7 +83,7 @@ export interface LangfuseRuntime {
|
|
|
83
83
|
startObservation: (
|
|
84
84
|
name: string,
|
|
85
85
|
body?: ObservationUpdate,
|
|
86
|
-
options?: { asType?: "agent" | "event" | "generation" | "tool" | "span" },
|
|
86
|
+
options?: { asType?: "agent" | "event" | "generation" | "tool" | "span"; parentSpanContext?: import("@opentelemetry/api").SpanContext },
|
|
87
87
|
) => LangfuseObservation;
|
|
88
88
|
propagateAttributes: (
|
|
89
89
|
params: {
|
|
@@ -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;
|
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);
|
|
67
81
|
}
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
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);
|
|
71
90
|
}
|
|
72
|
-
|
|
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);
|
|
96
|
+
}
|
|
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>;
|
package/src/workflow.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { defaultTextMapGetter, ROOT_CONTEXT, trace, TraceFlags, type SpanContext } from "@opentelemetry/api";
|
|
2
|
+
import { W3CTraceContextPropagator } from "@opentelemetry/core";
|
|
3
|
+
import { redactString } from "./redaction.js";
|
|
4
|
+
import { getSessionRunState, state } from "./state.js";
|
|
5
|
+
import { truncate } from "./utils.js";
|
|
6
|
+
|
|
7
|
+
export interface WorkflowContext {
|
|
8
|
+
sessionId?: string;
|
|
9
|
+
traceparent?: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface LangfuseExtensionOptions {
|
|
13
|
+
getRunContext?(run: { piSessionId: string; messageType: "user" | "custom" | "unknown" }): WorkflowContext | undefined;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface WorkflowBinding {
|
|
17
|
+
sessionId?: string;
|
|
18
|
+
parent?: SpanContext;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const propagator = new W3CTraceContextPropagator();
|
|
22
|
+
|
|
23
|
+
export function warnWorkflow(reason: string) {
|
|
24
|
+
const session = getSessionRunState();
|
|
25
|
+
const warnings = session.workflowWarnings ??= new Set<string>();
|
|
26
|
+
if (warnings.has(reason)) return;
|
|
27
|
+
warnings.add(reason);
|
|
28
|
+
console.warn(`📊 Langfuse: ${reason}`);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function parseWorkflowContext(input: { sessionId?: unknown; traceparent?: unknown }): WorkflowBinding {
|
|
32
|
+
const binding: WorkflowBinding = {};
|
|
33
|
+
const { sessionId, traceparent } = input;
|
|
34
|
+
if (sessionId !== undefined) {
|
|
35
|
+
if (typeof sessionId === "string" && sessionId.length > 0 && sessionId.length <= 200
|
|
36
|
+
&& !/[^\x20-\x7e]/.test(sessionId) && sessionId.trim() === sessionId && redactString(sessionId) === sessionId) {
|
|
37
|
+
binding.sessionId = sessionId;
|
|
38
|
+
} else {
|
|
39
|
+
warnWorkflow("Ignoring invalid workflow session ID; using the default grouping for this trace.");
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (traceparent !== undefined) {
|
|
43
|
+
if (typeof traceparent === "string" && traceparent.length <= 512 && !/[^\x21-\x7e]/.test(traceparent)) {
|
|
44
|
+
const context = propagator.extract(ROOT_CONTEXT, { traceparent }, defaultTextMapGetter);
|
|
45
|
+
binding.parent = trace.getSpanContext(context);
|
|
46
|
+
}
|
|
47
|
+
if (!binding.parent) warnWorkflow("Ignoring invalid traceparent; creating an independent trace.");
|
|
48
|
+
}
|
|
49
|
+
return binding;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function resolveRunBinding(event: Record<string, unknown>, getRunContext?: LangfuseExtensionOptions["getRunContext"]): WorkflowBinding {
|
|
53
|
+
const session = getSessionRunState();
|
|
54
|
+
if (getRunContext && state.currentSessionId) {
|
|
55
|
+
try {
|
|
56
|
+
const messageType = event.messageType === "custom" ? "custom"
|
|
57
|
+
: typeof event.prompt === "string" || event.messageType === "user" ? "user" : "unknown";
|
|
58
|
+
const input = getRunContext({ piSessionId: state.currentSessionId, messageType });
|
|
59
|
+
if (input !== undefined) return parseWorkflowContext(input);
|
|
60
|
+
} catch {
|
|
61
|
+
warnWorkflow("Workflow context callback failed; using an independent trace.");
|
|
62
|
+
return {};
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return session.startupBinding ?? {};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function sessionGroupId() {
|
|
69
|
+
return getSessionRunState().startupBinding?.sessionId ?? localSessionGroupId();
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function localSessionGroupId() {
|
|
73
|
+
return state.currentSessionId ? truncate(state.currentSessionId, 200) : undefined;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function isUnsampled(binding?: WorkflowBinding) {
|
|
77
|
+
return !!binding?.parent && (binding.parent.traceFlags & TraceFlags.SAMPLED) === 0;
|
|
78
|
+
}
|