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.
Files changed (66) hide show
  1. package/README.md +87 -5
  2. package/README_CN.md +63 -5
  3. package/dist/index.d.ts +14 -0
  4. package/dist/index.js +216 -0
  5. package/dist/src/capture-policy.d.ts +43 -0
  6. package/dist/src/capture-policy.js +125 -0
  7. package/dist/src/commands.d.ts +25 -0
  8. package/dist/src/commands.js +374 -0
  9. package/dist/src/config.d.ts +13 -0
  10. package/dist/src/config.js +157 -0
  11. package/dist/src/constants.d.ts +9 -0
  12. package/dist/src/constants.js +11 -0
  13. package/dist/src/handlers/agent.d.ts +18 -0
  14. package/dist/src/handlers/agent.js +310 -0
  15. package/dist/src/handlers/cache.d.ts +5 -0
  16. package/dist/src/handlers/cache.js +134 -0
  17. package/dist/src/handlers/generation.d.ts +9 -0
  18. package/dist/src/handlers/generation.js +249 -0
  19. package/dist/src/handlers/session.d.ts +4 -0
  20. package/dist/src/handlers/session.js +121 -0
  21. package/dist/src/handlers/system-state.d.ts +3 -0
  22. package/dist/src/handlers/system-state.js +185 -0
  23. package/dist/src/handlers/tool.d.ts +3 -0
  24. package/dist/src/handlers/tool.js +168 -0
  25. package/dist/src/handlers/turn.d.ts +2 -0
  26. package/dist/src/handlers/turn.js +48 -0
  27. package/dist/src/langfuse.d.ts +42 -0
  28. package/dist/src/langfuse.js +837 -0
  29. package/dist/src/limits.d.ts +43 -0
  30. package/dist/src/limits.js +63 -0
  31. package/dist/src/observation.d.ts +24 -0
  32. package/dist/src/observation.js +24 -0
  33. package/dist/src/redaction.d.ts +14 -0
  34. package/dist/src/redaction.js +254 -0
  35. package/dist/src/session-lineage.d.ts +15 -0
  36. package/dist/src/session-lineage.js +87 -0
  37. package/dist/src/source-metadata.d.ts +2 -0
  38. package/dist/src/source-metadata.js +55 -0
  39. package/dist/src/state.d.ts +52 -0
  40. package/dist/src/state.js +144 -0
  41. package/dist/src/types.d.ts +157 -0
  42. package/dist/src/types.js +1 -0
  43. package/dist/src/usage-options.d.ts +27 -0
  44. package/dist/src/usage-options.js +21 -0
  45. package/dist/src/utils.d.ts +61 -0
  46. package/dist/src/utils.js +600 -0
  47. package/dist/src/workflow.d.ts +24 -0
  48. package/dist/src/workflow.js +62 -0
  49. package/examples/workflow-sdk.mjs +56 -0
  50. package/index.ts +47 -13
  51. package/package.json +16 -2
  52. package/src/commands.ts +48 -5
  53. package/src/config.ts +1 -1
  54. package/src/handlers/agent.ts +63 -33
  55. package/src/handlers/cache.ts +14 -10
  56. package/src/handlers/generation.ts +21 -43
  57. package/src/handlers/session.ts +71 -13
  58. package/src/handlers/tool.ts +12 -8
  59. package/src/langfuse.ts +110 -80
  60. package/src/observation.ts +31 -0
  61. package/src/redaction.ts +145 -10
  62. package/src/session-lineage.ts +98 -0
  63. package/src/state.ts +19 -2
  64. package/src/types.ts +2 -1
  65. package/src/utils.ts +95 -19
  66. package/src/workflow.ts +78 -0
@@ -0,0 +1,43 @@
1
+ import type { EnvLike } from "./capture-policy.js";
2
+ /**
3
+ * Payload-shaping limits. Every field is a positive integer, or
4
+ * `Number.POSITIVE_INFINITY` to disable that limit entirely (capture everything).
5
+ * Resolved once from the environment and stored on the loaded config; consumers
6
+ * read the resolved values via `getLimits()` rather than the raw constants.
7
+ */
8
+ export interface PayloadLimits {
9
+ /** Max characters kept per captured string (generation/agent inputs, outputs, system prompt). */
10
+ readonly maxString: number;
11
+ /** Max characters kept for tool inputs/outputs (their payloads run larger than chat strings). */
12
+ readonly maxToolPayload: number;
13
+ /** Max nesting depth walked when shaping a structured payload. */
14
+ readonly maxDepth: number;
15
+ /** Max array elements kept per array. */
16
+ readonly maxArrayItems: number;
17
+ /** Max own-keys kept per object. */
18
+ readonly maxObjectKeys: number;
19
+ /** Max total nodes visited across a whole payload before bailing with `[payload too large]`. */
20
+ readonly maxNodes: number;
21
+ }
22
+ export declare const DEFAULT_LIMITS: PayloadLimits;
23
+ /**
24
+ * Parse one limit env value.
25
+ * - unset / blank / unparseable -> `fallback` (the built-in default)
26
+ * - "off"/"none"/"unlimited"/... or a value <= 0 -> `Infinity` (limit removed)
27
+ * - a positive number -> that integer
28
+ */
29
+ export declare function parseLimit(raw: string | undefined, fallback: number): number;
30
+ /**
31
+ * Resolve payload limits from the environment. Each `PI_LANGFUSE_MAX_*` var overrides
32
+ * the corresponding default; set any to `0`/`off`/`unlimited` to remove that limit.
33
+ * Namespaced `PI_LANGFUSE_*` (not `LANGFUSE_*`) to avoid clashing with Langfuse
34
+ * server env vars such as `LANGFUSE_MAX_EVENT_SIZE_BYTES`.
35
+ */
36
+ export declare function createPayloadLimits(env?: EnvLike): PayloadLimits;
37
+ /**
38
+ * Resolved limits for the current session: the config-loaded values when a
39
+ * config is active, otherwise a fresh resolve from the environment. Every
40
+ * capture/redaction path reads limits through this so a single env change
41
+ * (or config) governs truncation everywhere.
42
+ */
43
+ export declare function getLimits(): PayloadLimits;
@@ -0,0 +1,63 @@
1
+ import { MAX_ARRAY_ITEMS, MAX_DEPTH, MAX_OBJECT_KEYS, MAX_PAYLOAD_NODES, MAX_STRING_LENGTH, MAX_TOOL_PAYLOAD_LENGTH, } from "./constants.js";
2
+ import { state } from "./state.js";
3
+ export const DEFAULT_LIMITS = {
4
+ maxString: MAX_STRING_LENGTH,
5
+ maxToolPayload: MAX_TOOL_PAYLOAD_LENGTH,
6
+ maxDepth: MAX_DEPTH,
7
+ maxArrayItems: MAX_ARRAY_ITEMS,
8
+ maxObjectKeys: MAX_OBJECT_KEYS,
9
+ maxNodes: MAX_PAYLOAD_NODES,
10
+ };
11
+ /** Words that mean "no limit" when supplied as an env value. */
12
+ const UNLIMITED_WORDS = new Set(["off", "none", "false", "no", "unlimited", "inf", "infinity"]);
13
+ /**
14
+ * Parse one limit env value.
15
+ * - unset / blank / unparseable -> `fallback` (the built-in default)
16
+ * - "off"/"none"/"unlimited"/... or a value <= 0 -> `Infinity` (limit removed)
17
+ * - a positive number -> that integer
18
+ */
19
+ export function parseLimit(raw, fallback) {
20
+ if (raw === undefined) {
21
+ return fallback;
22
+ }
23
+ const trimmed = raw.trim().toLowerCase();
24
+ if (trimmed === "") {
25
+ return fallback;
26
+ }
27
+ if (UNLIMITED_WORDS.has(trimmed)) {
28
+ return Number.POSITIVE_INFINITY;
29
+ }
30
+ const parsed = Number(trimmed);
31
+ if (!Number.isFinite(parsed)) {
32
+ return fallback;
33
+ }
34
+ if (parsed <= 0) {
35
+ return Number.POSITIVE_INFINITY;
36
+ }
37
+ return Math.floor(parsed);
38
+ }
39
+ /**
40
+ * Resolve payload limits from the environment. Each `PI_LANGFUSE_MAX_*` var overrides
41
+ * the corresponding default; set any to `0`/`off`/`unlimited` to remove that limit.
42
+ * Namespaced `PI_LANGFUSE_*` (not `LANGFUSE_*`) to avoid clashing with Langfuse
43
+ * server env vars such as `LANGFUSE_MAX_EVENT_SIZE_BYTES`.
44
+ */
45
+ export function createPayloadLimits(env = process.env) {
46
+ return {
47
+ maxString: parseLimit(env.PI_LANGFUSE_MAX_STRING_LENGTH, DEFAULT_LIMITS.maxString),
48
+ maxToolPayload: parseLimit(env.PI_LANGFUSE_MAX_TOOL_PAYLOAD_LENGTH, DEFAULT_LIMITS.maxToolPayload),
49
+ maxDepth: parseLimit(env.PI_LANGFUSE_MAX_DEPTH, DEFAULT_LIMITS.maxDepth),
50
+ maxArrayItems: parseLimit(env.PI_LANGFUSE_MAX_ARRAY_ITEMS, DEFAULT_LIMITS.maxArrayItems),
51
+ maxObjectKeys: parseLimit(env.PI_LANGFUSE_MAX_OBJECT_KEYS, DEFAULT_LIMITS.maxObjectKeys),
52
+ maxNodes: parseLimit(env.PI_LANGFUSE_MAX_PAYLOAD_NODES, DEFAULT_LIMITS.maxNodes),
53
+ };
54
+ }
55
+ /**
56
+ * Resolved limits for the current session: the config-loaded values when a
57
+ * config is active, otherwise a fresh resolve from the environment. Every
58
+ * capture/redaction path reads limits through this so a single env change
59
+ * (or config) governs truncation everywhere.
60
+ */
61
+ export function getLimits() {
62
+ return state.config?.limits ?? createPayloadLimits();
63
+ }
@@ -0,0 +1,24 @@
1
+ import type { LangfuseObservation, LangfuseRuntime, ObservationUpdate } from "./types.js";
2
+ export declare function startChildObservation({ parent, runtime, name, body, asType, }: {
3
+ parent: LangfuseObservation;
4
+ runtime: () => Promise<LangfuseRuntime>;
5
+ name: string;
6
+ body?: ObservationUpdate;
7
+ asType: "event" | "generation" | "tool" | "span";
8
+ }): Promise<LangfuseObservation>;
9
+ /**
10
+ * Starts a top-level observation for a session-scoped event that arrives when no
11
+ * agent run is active (e.g. recovery compaction after a failed generation).
12
+ *
13
+ * Attributes must be passed explicitly: `propagateAttributes` only seeds the OTel
14
+ * context for the duration of its callback, so a root observation created outside
15
+ * a run would be written without `session.id` or `langfuse.trace.name` and would
16
+ * drop out of every session filter in Langfuse v4.
17
+ */
18
+ export declare function startSessionObservation({ runtime, name, body, asType, attributes, }: {
19
+ runtime: () => Promise<LangfuseRuntime>;
20
+ name: string;
21
+ body?: ObservationUpdate;
22
+ asType: "event" | "generation" | "tool" | "span";
23
+ attributes: Parameters<LangfuseRuntime["propagateAttributes"]>[0];
24
+ }): Promise<LangfuseObservation>;
@@ -0,0 +1,24 @@
1
+ import { getSessionRunState } from "./state.js";
2
+ export async function startChildObservation({ parent, runtime, name, body, asType, }) {
3
+ if (parent.startObservation) {
4
+ return parent.startObservation(name, body, { asType });
5
+ }
6
+ if (getSessionRunState().runBinding?.parent) {
7
+ throw new Error("Cannot attach child observation to its workflow parent");
8
+ }
9
+ return (await runtime()).startObservation(name, body, { asType });
10
+ }
11
+ /**
12
+ * Starts a top-level observation for a session-scoped event that arrives when no
13
+ * agent run is active (e.g. recovery compaction after a failed generation).
14
+ *
15
+ * Attributes must be passed explicitly: `propagateAttributes` only seeds the OTel
16
+ * context for the duration of its callback, so a root observation created outside
17
+ * a run would be written without `session.id` or `langfuse.trace.name` and would
18
+ * drop out of every session filter in Langfuse v4.
19
+ */
20
+ export async function startSessionObservation({ runtime, name, body, asType, attributes, }) {
21
+ const rt = await runtime();
22
+ const create = () => rt.propagateAttributes(attributes, () => rt.startObservation(name, body, { asType }));
23
+ return rt.withRootContext ? rt.withRootContext(create) : create();
24
+ }
@@ -0,0 +1,14 @@
1
+ export declare const REDACTED = "[REDACTED_SECRET]";
2
+ export interface RedactOptions {
3
+ maxDepth: number;
4
+ maxArrayItems: number;
5
+ maxObjectKeys: number;
6
+ maxStringLength: number;
7
+ /** When false, absolute filesystem paths are emitted verbatim instead of `[PATH_HASH:...]`. */
8
+ redactPaths: boolean;
9
+ }
10
+ /** Recognize unmasked fields even when surrounding prose prevents parsing the JSON. */
11
+ export declare function hasUnredactedSensitiveJsonField(value: string): boolean;
12
+ export declare function hashPath(path: string): string;
13
+ export declare function redactString(value: string, options?: Partial<RedactOptions>): string;
14
+ export declare function redactValue(value: unknown, options?: Partial<RedactOptions>): unknown;
@@ -0,0 +1,254 @@
1
+ import { createHash } from "node:crypto";
2
+ import { getLimits } from "./limits.js";
3
+ import { state } from "./state.js";
4
+ export const REDACTED = "[REDACTED_SECRET]";
5
+ /**
6
+ * Fallback for callers that do not pass the resolved capture policy. Mirrors
7
+ * `getLimits()` by reading the session config, and defaults to redacting so a
8
+ * missing policy can never widen disclosure. Callers that hold a policy should
9
+ * pass `redactOptionsFor(policy)` instead of relying on this.
10
+ */
11
+ function defaultOptions() {
12
+ const limits = getLimits();
13
+ return {
14
+ maxDepth: limits.maxDepth,
15
+ maxArrayItems: limits.maxArrayItems,
16
+ maxObjectKeys: limits.maxObjectKeys,
17
+ maxStringLength: limits.maxString,
18
+ redactPaths: !(state.config?.capturePolicy?.capturePaths ?? false),
19
+ };
20
+ }
21
+ const SENSITIVE_ASSIGNMENT_KEY_RE = /SECRET|TOKEN|PASSWORD|PASS|API[_-]?KEY|PRIVATE[_-]?KEY|AUTH|COOKIE/i;
22
+ const PRIVATE_KEY_RE = /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g;
23
+ const BEARER_RE = /\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi;
24
+ const KNOWN_TOKEN_RE = /\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;
25
+ const ABSOLUTE_PATH_RE = /(?:\/Users\/[^/\s]+|\/home\/[^/\s]+|\/private\/tmp|\/tmp|[A-Za-z]:\\Users\\[^\\\s]+)(?:[^\s"'`]*)/g;
26
+ const SENSITIVE_FIELDS = new Set([
27
+ "authorization", "cookie", "setcookie", "xapikey", "apikey", "token", "accesstoken",
28
+ "refreshtoken", "secret", "secretkey", "password", "passwd", "privatekey",
29
+ ]);
30
+ const MAX_SENSITIVE_FIELD_LENGTH = Math.max(...[...SENSITIVE_FIELDS].map(key => key.length));
31
+ function isSensitiveField(key) {
32
+ return SENSITIVE_FIELDS.has(key.replace(/[^a-zA-Z0-9]/g, "").toLowerCase());
33
+ }
34
+ function inspectJsonFields(text, exceededBudget) {
35
+ let inKey = false;
36
+ let validKey = true;
37
+ let normalizedKey = "";
38
+ const maskedValue = /\s*"\[REDACTED_SECRET\]"(?=\s*[,}\]]|\s*$)/y;
39
+ function appendKeyCharacter(char) {
40
+ // Keep one extra character to distinguish long, non-sensitive names.
41
+ if (normalizedKey.length <= MAX_SENSITIVE_FIELD_LENGTH && /[a-zA-Z0-9]/.test(char)) {
42
+ normalizedKey += char.toLowerCase();
43
+ }
44
+ }
45
+ // Scan each candidate once. Interior escaped quotes share its closing quote;
46
+ // retrying from them after a failed match would rescan the same suffix.
47
+ // Reuse a closing quote as the next opener when it is not followed by a colon,
48
+ // so an unmatched prose quote cannot hide a later JSON field.
49
+ for (let index = 0; index < text.length; index++) {
50
+ const char = text[index];
51
+ if (!inKey) {
52
+ if (char !== '"')
53
+ continue;
54
+ inKey = true;
55
+ validKey = true;
56
+ normalizedKey = "";
57
+ continue;
58
+ }
59
+ if (char === '"') {
60
+ let colon = index + 1;
61
+ while (colon < text.length && /\s/.test(text[colon]))
62
+ colon++;
63
+ if (text[colon] === ":") {
64
+ if (exceededBudget())
65
+ return true;
66
+ if (validKey && SENSITIVE_FIELDS.has(normalizedKey)) {
67
+ maskedValue.lastIndex = colon + 1;
68
+ if (!maskedValue.test(text))
69
+ return true;
70
+ }
71
+ inKey = false;
72
+ index = colon;
73
+ }
74
+ validKey = true;
75
+ normalizedKey = "";
76
+ }
77
+ else if (char === "\\") {
78
+ const escaped = text[++index];
79
+ if (escaped === undefined || /[\n\r\u2028\u2029]/.test(escaped)) {
80
+ inKey = false;
81
+ }
82
+ else if (escaped === "u") {
83
+ const hex = text.slice(index + 1, index + 5);
84
+ if (/^[0-9a-f]{4}$/i.test(hex)) {
85
+ appendKeyCharacter(String.fromCharCode(parseInt(hex, 16)));
86
+ index += 4;
87
+ }
88
+ else {
89
+ validKey = false;
90
+ }
91
+ }
92
+ else if (!'"\\/bfnrt'.includes(escaped)) {
93
+ validKey = false;
94
+ }
95
+ }
96
+ else if (char.charCodeAt(0) < 0x20) {
97
+ validKey = false;
98
+ }
99
+ else {
100
+ appendKeyCharacter(char);
101
+ }
102
+ }
103
+ return false;
104
+ }
105
+ /** Recognize unmasked fields even when surrounding prose prevents parsing the JSON. */
106
+ export function hasUnredactedSensitiveJsonField(value) {
107
+ const { maxDepth, maxNodes } = getLimits();
108
+ let nodes = 0;
109
+ function inspect(text, depth) {
110
+ if (inspectJsonFields(text, () => ++nodes > maxNodes))
111
+ return true;
112
+ for (const match of text.matchAll(/"((?:\\[\s\S]?|[^"\\])*)("|$)/g)) {
113
+ if (++nodes > maxNodes)
114
+ return true;
115
+ try {
116
+ const decoded = JSON.parse(match[0]);
117
+ if (decoded.includes('"') && (depth >= maxDepth || inspect(decoded, depth + 1)))
118
+ return true;
119
+ }
120
+ catch {
121
+ // Truncated or invalid escaping must not hide an embedded JSON credential.
122
+ if (match[1].includes("\\"))
123
+ return true;
124
+ }
125
+ }
126
+ return false;
127
+ }
128
+ return inspect(value, 0);
129
+ }
130
+ export function hashPath(path) {
131
+ return `[PATH_HASH:${createHash("sha256").update(path).digest("hex").slice(0, 12)}]`;
132
+ }
133
+ function truncate(value, maxStringLength) {
134
+ return value.length > maxStringLength ? `${value.slice(0, maxStringLength)}... [truncated]` : value;
135
+ }
136
+ function assignmentValueEnd(value, start) {
137
+ let quote;
138
+ let quoteSlashes = 0;
139
+ let end = start;
140
+ while (end < value.length) {
141
+ const slashStart = end;
142
+ while (value[end] === "\\")
143
+ end++;
144
+ const slashes = end - slashStart;
145
+ const char = value[end];
146
+ if (char === undefined)
147
+ break;
148
+ if (quote) {
149
+ // JSON escapes double quotes, revealing their depth; single quotes stay ambiguous.
150
+ const closesQuote = quote === "'" ? slashes === quoteSlashes
151
+ : slashes % (2 * (quoteSlashes + 1)) === quoteSlashes;
152
+ if (char === quote && closesQuote)
153
+ quote = undefined;
154
+ }
155
+ else if (char === '"' || char === "'") {
156
+ quote = char;
157
+ quoteSlashes = slashes;
158
+ }
159
+ else if (slashes === 0 && /\s|`/.test(char)) {
160
+ break;
161
+ }
162
+ end++;
163
+ }
164
+ // A missing closing quote keeps the remaining value secret.
165
+ return end;
166
+ }
167
+ function redactAssignments(value) {
168
+ // Tokenize each key once; retrying sensitive fragments inside long keys is quadratic.
169
+ const keys = /(?<![\w-])([\w-]+)\s*=\s*/g;
170
+ const parts = [];
171
+ let cursor = 0;
172
+ let match;
173
+ while ((match = keys.exec(value))) {
174
+ if (!SENSITIVE_ASSIGNMENT_KEY_RE.test(match[1]))
175
+ continue;
176
+ const end = assignmentValueEnd(value, keys.lastIndex);
177
+ if (end === keys.lastIndex)
178
+ continue;
179
+ parts.push(value.slice(cursor, match.index), `${match[1]}=${REDACTED}`);
180
+ cursor = keys.lastIndex = end;
181
+ }
182
+ parts.push(value.slice(cursor));
183
+ return parts.join("");
184
+ }
185
+ export function redactString(value, options = {}) {
186
+ const merged = { ...defaultOptions(), ...options };
187
+ // Truncating first can make a known token too short for its recognizer.
188
+ const secretsRedacted = truncate(redactAssignments(value
189
+ .replace(PRIVATE_KEY_RE, REDACTED)
190
+ .replace(BEARER_RE, REDACTED)
191
+ .replace(KNOWN_TOKEN_RE, REDACTED)), merged.maxStringLength);
192
+ if (hasUnredactedSensitiveJsonField(secretsRedacted))
193
+ return REDACTED;
194
+ if (!merged.redactPaths) {
195
+ return secretsRedacted;
196
+ }
197
+ return secretsRedacted.replace(ABSOLUTE_PATH_RE, (path) => {
198
+ const envSuffix = path.match(/([/\\]\.env(?:\.[A-Za-z0-9_-]+)?)$/)?.[1];
199
+ return `${hashPath(envSuffix ? path.slice(0, -envSuffix.length) : path)}${envSuffix ?? ""}`;
200
+ });
201
+ }
202
+ function visit(value, options, depth, seen) {
203
+ if (value === null || value === undefined || typeof value === "number" || typeof value === "boolean") {
204
+ return value;
205
+ }
206
+ if (typeof value === "bigint") {
207
+ return value.toString();
208
+ }
209
+ if (typeof value === "string") {
210
+ return redactString(value, options);
211
+ }
212
+ if (typeof value === "function" || typeof value === "symbol") {
213
+ return `[${typeof value}]`;
214
+ }
215
+ if (depth <= 0) {
216
+ return `[max depth ${options.maxDepth} reached]`;
217
+ }
218
+ if (value instanceof Error) {
219
+ return {
220
+ name: redactString(value.name, options),
221
+ message: redactString(value.message, options),
222
+ stack: value.stack ? redactString(value.stack, options) : undefined,
223
+ };
224
+ }
225
+ if (typeof value !== "object") {
226
+ return redactString(String(value), options);
227
+ }
228
+ if (seen.has(value)) {
229
+ return "[circular]";
230
+ }
231
+ seen.add(value);
232
+ if (Array.isArray(value)) {
233
+ const output = value
234
+ .slice(0, options.maxArrayItems)
235
+ .map((item) => visit(item, options, depth - 1, seen));
236
+ if (value.length > options.maxArrayItems) {
237
+ output.push(`[${value.length - options.maxArrayItems} truncated items]`);
238
+ }
239
+ return output;
240
+ }
241
+ const entries = Object.entries(value);
242
+ const output = {};
243
+ for (const [key, item] of entries.slice(0, options.maxObjectKeys)) {
244
+ output[key] = isSensitiveField(key) ? REDACTED : visit(item, options, depth - 1, seen);
245
+ }
246
+ if (entries.length > options.maxObjectKeys) {
247
+ output.__truncatedKeys = entries.length - options.maxObjectKeys;
248
+ }
249
+ return output;
250
+ }
251
+ export function redactValue(value, options = {}) {
252
+ const merged = { ...defaultOptions(), ...options };
253
+ return visit(value, merged, merged.maxDepth, new WeakSet());
254
+ }
@@ -0,0 +1,15 @@
1
+ export interface SessionLineage {
2
+ parentSessionId?: string;
3
+ sessionKind?: "subagent" | "fork";
4
+ }
5
+ /**
6
+ * Session lineage from Pi's public session header (`SessionHeader.parentSession`).
7
+ * `sessionKind` is a best-effort guess: pi-subagents marks child processes with
8
+ * PI_SUBAGENT_CHILD, and that flag is not a contract this package owns, so a
9
+ * missing flag only degrades the label to "fork".
10
+ */
11
+ export declare function resolveSessionLineage(sessionManager: unknown, env?: Record<string, string | undefined>): SessionLineage;
12
+ /** Resolves once per session and caches the result, including "no parent". */
13
+ export declare function bindSessionLineage(sessionManager?: unknown): void;
14
+ /** Metadata for the active session; empty for a root session with no parent. */
15
+ export declare function sessionLineageMetadata(sessionManager?: unknown): Record<string, string>;
@@ -0,0 +1,87 @@
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
+ // Pi names session files either "<timestamp>_<uuid>.jsonl" or "session.jsonl"
6
+ // (165 of 368 local files use the latter), so the id cannot be read from the
7
+ // name alone. The header line is short; reading a bounded prefix keeps a large
8
+ // transcript from being pulled into memory for one id.
9
+ const HEADER_READ_BYTES = 4096;
10
+ 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;
11
+ function readSessionFileId(filePath) {
12
+ let fd;
13
+ try {
14
+ fd = openSync(filePath, "r");
15
+ const buffer = Buffer.alloc(HEADER_READ_BYTES);
16
+ const bytesRead = readSync(fd, buffer, 0, HEADER_READ_BYTES, 0);
17
+ const firstLine = buffer.subarray(0, bytesRead).toString("utf8").split("\n", 1)[0];
18
+ const header = JSON.parse(firstLine);
19
+ const id = header.id;
20
+ return typeof id === "string" && id ? id : undefined;
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ finally {
26
+ if (fd !== undefined) {
27
+ try {
28
+ closeSync(fd);
29
+ }
30
+ catch {
31
+ // Already-rotated file: the id stays unresolved, which only loses lineage.
32
+ }
33
+ }
34
+ }
35
+ }
36
+ /**
37
+ * Session lineage from Pi's public session header (`SessionHeader.parentSession`).
38
+ * `sessionKind` is a best-effort guess: pi-subagents marks child processes with
39
+ * PI_SUBAGENT_CHILD, and that flag is not a contract this package owns, so a
40
+ * missing flag only degrades the label to "fork".
41
+ */
42
+ export function resolveSessionLineage(sessionManager, env = process.env) {
43
+ const lineage = {};
44
+ const parentSession = sessionManager
45
+ ?.getHeader?.()?.parentSession;
46
+ if (typeof parentSession === "string" && parentSession) {
47
+ const parentSessionId = readSessionFileId(parentSession)
48
+ ?? basename(parentSession).replace(/\.jsonl$/i, "").match(SESSION_ID_PATTERN)?.[0];
49
+ if (parentSessionId) {
50
+ lineage.parentSessionId = parentSessionId;
51
+ }
52
+ lineage.sessionKind = env.PI_SUBAGENT_CHILD === "1" ? "subagent" : "fork";
53
+ }
54
+ else if (env.PI_SUBAGENT_CHILD === "1") {
55
+ lineage.sessionKind = "subagent";
56
+ }
57
+ return lineage;
58
+ }
59
+ /** Resolves once per session and caches the result, including "no parent". */
60
+ export function bindSessionLineage(sessionManager) {
61
+ const sessionState = getSessionRunState();
62
+ if (sessionState.lineageResolved) {
63
+ return;
64
+ }
65
+ // Without a header source the answer is unknown, not "root": leave the cache
66
+ // open so a later call that holds a real session manager can resolve it.
67
+ if (typeof sessionManager?.getHeader !== "function") {
68
+ return;
69
+ }
70
+ const lineage = resolveSessionLineage(sessionManager);
71
+ sessionState.parentSessionId = lineage.parentSessionId;
72
+ sessionState.sessionKind = lineage.sessionKind;
73
+ sessionState.lineageResolved = true;
74
+ }
75
+ /** Metadata for the active session; empty for a root session with no parent. */
76
+ export function sessionLineageMetadata(sessionManager) {
77
+ bindSessionLineage(sessionManager);
78
+ const sessionState = getSessionRunState();
79
+ const metadata = {};
80
+ if (sessionState.parentSessionId) {
81
+ metadata.parentSessionId = redactString(sessionState.parentSessionId);
82
+ }
83
+ if (sessionState.sessionKind) {
84
+ metadata.sessionKind = sessionState.sessionKind;
85
+ }
86
+ return metadata;
87
+ }
@@ -0,0 +1,2 @@
1
+ export type SourceMetadata = Record<string, string>;
2
+ export declare function collectSourceMetadata(cwd: string, enabled: boolean, env?: NodeJS.ProcessEnv): SourceMetadata;
@@ -0,0 +1,55 @@
1
+ import { execFileSync } from "node:child_process";
2
+ function sourceStatus(status) {
3
+ return {
4
+ source_type: status,
5
+ metadata_source: status,
6
+ };
7
+ }
8
+ function runGit(cwd, args, env) {
9
+ try {
10
+ return {
11
+ status: "ok",
12
+ value: execFileSync("git", args, {
13
+ cwd,
14
+ encoding: "utf8",
15
+ env,
16
+ stdio: ["ignore", "pipe", "ignore"],
17
+ timeout: 2000,
18
+ }).trim(),
19
+ };
20
+ }
21
+ catch (error) {
22
+ const failure = error;
23
+ return typeof failure.status === "number"
24
+ ? { status: "failed" }
25
+ : { status: "unavailable" };
26
+ }
27
+ }
28
+ export function collectSourceMetadata(cwd, enabled, env = process.env) {
29
+ if (!enabled) {
30
+ return sourceStatus("disabled");
31
+ }
32
+ const inside = runGit(cwd, ["rev-parse", "--is-inside-work-tree"], env);
33
+ if (inside.status === "unavailable") {
34
+ return sourceStatus("unavailable");
35
+ }
36
+ if (inside.status !== "ok" || inside.value !== "true") {
37
+ return sourceStatus("non-git");
38
+ }
39
+ const revision = runGit(cwd, ["rev-parse", "--verify", "HEAD"], env);
40
+ const ref = runGit(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"], env);
41
+ const workingTree = runGit(cwd, ["status", "--porcelain=v1", "--untracked-files=normal"], env);
42
+ if (revision.status !== "ok" ||
43
+ !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(revision.value) ||
44
+ workingTree.status !== "ok" ||
45
+ ref.status === "unavailable") {
46
+ return sourceStatus("unavailable");
47
+ }
48
+ return {
49
+ source_type: "git-repo",
50
+ "vcs.ref.head.revision": revision.value,
51
+ git_detached: String(ref.status !== "ok"),
52
+ git_dirty: String(Boolean(workingTree.value)),
53
+ metadata_source: "git-detection",
54
+ };
55
+ }
@@ -0,0 +1,52 @@
1
+ import type { Config, AgentState } from "./types.js";
2
+ import type { WorkflowBinding } from "./workflow.js";
3
+ export interface SessionRunState {
4
+ instance: symbol;
5
+ startupBinding?: WorkflowBinding;
6
+ runBinding?: WorkflowBinding;
7
+ startingRun?: Promise<void>;
8
+ finishingRun?: boolean;
9
+ workflowWarnings?: Set<string>;
10
+ currentModel: string;
11
+ currentProvider: string;
12
+ agentState: AgentState | null;
13
+ toolCallCount: number;
14
+ errorCount: number;
15
+ turnCount: number;
16
+ tracingDisabled: boolean;
17
+ setupAttemptedThisSession: boolean;
18
+ lastPromptStateHash?: string;
19
+ lastToolStateHash?: string;
20
+ lastActiveTools: string[];
21
+ parentSessionId?: string;
22
+ sessionKind?: "subagent" | "fork";
23
+ lineageResolved: boolean;
24
+ systemStateSequence: number;
25
+ seenSystemEntryIds: Set<string>;
26
+ seenUsageEntryIds: Set<string>;
27
+ }
28
+ export declare function getSessionRunState(sessionId?: string): SessionRunState;
29
+ export declare function setCurrentSession(sessionId?: string): void;
30
+ export declare function runWithSession<T>(sessionId: string | undefined, fn: () => T): T;
31
+ export declare const state: {
32
+ config: Config | null;
33
+ sessionStates: Map<string, SessionRunState>;
34
+ currentSessionId: string;
35
+ currentModel: string;
36
+ currentProvider: string;
37
+ agentState: AgentState | null;
38
+ toolCallCount: number;
39
+ errorCount: number;
40
+ turnCount: number;
41
+ isTracingDisabled: boolean;
42
+ setupAttemptedThisSession: boolean;
43
+ };
44
+ export declare function resetRunState(sessionId?: string): void;
45
+ export declare function clearAllSessionStates(): void;
46
+ export declare function computeEvaluationScores(sessionId?: string): {
47
+ tool_call_count: number;
48
+ turn_count: number;
49
+ total_tool_errors: number;
50
+ tool_success_rate: number;
51
+ session_had_errors: number;
52
+ };