pi-langfuse 1.7.0 → 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 +68 -2
- package/README_CN.md +43 -1
- package/index.ts +7 -1
- package/package.json +5 -2
- 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 +21 -43
- package/src/handlers/session.ts +71 -13
- package/src/handlers/tool.ts +6 -7
- 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 +1 -0
- package/src/utils.ts +95 -19
package/src/handlers/tool.ts
CHANGED
|
@@ -7,14 +7,13 @@ import {
|
|
|
7
7
|
getToolInput,
|
|
8
8
|
shapePayload,
|
|
9
9
|
extractTextContent,
|
|
10
|
-
|
|
10
|
+
toStatusMessage,
|
|
11
11
|
estimatePayloadBytes,
|
|
12
12
|
getCapturePolicy,
|
|
13
13
|
getLimits,
|
|
14
14
|
extractToolUsage,
|
|
15
15
|
} from "../utils.js";
|
|
16
|
-
import { applyCapturePolicy
|
|
17
|
-
import { redactString } from "../redaction.js";
|
|
16
|
+
import { applyCapturePolicy } from "../capture-policy.js";
|
|
18
17
|
|
|
19
18
|
export async function startToolObservation(event: Record<string, unknown>) {
|
|
20
19
|
if (state.isTracingDisabled || !state.agentState?.root) {
|
|
@@ -85,7 +84,7 @@ export async function finishToolObservation(event: Record<string, unknown>) {
|
|
|
85
84
|
|
|
86
85
|
const isError = Boolean(event.isError ?? event.error ?? event.status === "error");
|
|
87
86
|
const output =
|
|
88
|
-
extractTextContent(event.content
|
|
87
|
+
extractTextContent(event.content) ??
|
|
89
88
|
event.output ??
|
|
90
89
|
event.result ??
|
|
91
90
|
event.error ??
|
|
@@ -94,7 +93,7 @@ export async function finishToolObservation(event: Record<string, unknown>) {
|
|
|
94
93
|
|
|
95
94
|
try {
|
|
96
95
|
const policy = getCapturePolicy();
|
|
97
|
-
const shapedOutput = shapePayload(output, { maxString: getLimits().maxToolPayload });
|
|
96
|
+
const shapedOutput = shapePayload(output, { maxString: getLimits().maxToolPayload, parseJsonPrefix: isError });
|
|
98
97
|
const captured = applyCapturePolicy(
|
|
99
98
|
{
|
|
100
99
|
toolOutput: shapedOutput,
|
|
@@ -144,7 +143,7 @@ export async function finishToolObservation(event: Record<string, unknown>) {
|
|
|
144
143
|
output: captured.toolOutput,
|
|
145
144
|
level: isError ? "ERROR" : "DEFAULT",
|
|
146
145
|
statusMessage: isError
|
|
147
|
-
?
|
|
146
|
+
? toStatusMessage(event.error ?? output, 1_000)
|
|
148
147
|
: undefined,
|
|
149
148
|
metadata: {
|
|
150
149
|
...(captured.metadata ?? {}),
|
|
@@ -184,7 +183,7 @@ export function closeDanglingObservations(statusMessage: string) {
|
|
|
184
183
|
|
|
185
184
|
for (const generation of state.agentState.activeGenerations.values()) {
|
|
186
185
|
if (!generation.ended) {
|
|
187
|
-
generation.observation.update({ level: "WARNING", statusMessage, metadata: { ...generation.metadata, cancelled: true } }).end();
|
|
186
|
+
generation.observation.update({ level: "WARNING", statusMessage, ...generation.errorStatus, metadata: { ...generation.metadata, cancelled: true } }).end();
|
|
188
187
|
generation.ended = true;
|
|
189
188
|
}
|
|
190
189
|
}
|
package/src/langfuse.ts
CHANGED
|
@@ -54,7 +54,8 @@ interface RestFallbackObservation {
|
|
|
54
54
|
}
|
|
55
55
|
|
|
56
56
|
interface RestFallbackStore {
|
|
57
|
-
|
|
57
|
+
withTracerProvider?: <T>(fn: () => T) => T;
|
|
58
|
+
traces: Map<string, RestFallbackTrace>;
|
|
58
59
|
observations: RestFallbackObservation[];
|
|
59
60
|
observationById: Map<string, RestFallbackObservation>;
|
|
60
61
|
attempted: boolean;
|
|
@@ -274,7 +275,8 @@ function serializedBytes(value: unknown): number {
|
|
|
274
275
|
|
|
275
276
|
/**
|
|
276
277
|
* Split an ingestion event list into chunks whose serialized request bodies each
|
|
277
|
-
* stay under `maxBytes
|
|
278
|
+
* stay under `maxBytes`, skipping individually oversized events with a warning.
|
|
279
|
+
* Each chunk, when wrapped as `{ batch: chunk }`, matches
|
|
278
280
|
* the measurement exactly because entries are serialized individually and joined
|
|
279
281
|
* with single commas inside the `{"batch":[...]}` envelope.
|
|
280
282
|
*/
|
|
@@ -287,6 +289,12 @@ export function splitIngestionBatch(entries: unknown[], maxBytes: number): unkno
|
|
|
287
289
|
|
|
288
290
|
for (let index = 0; index < serialized.length; index++) {
|
|
289
291
|
const entryBytes = Buffer.byteLength(serialized[index], "utf8");
|
|
292
|
+
if (envelopeBytes + entryBytes > maxBytes) {
|
|
293
|
+
const message = `Skipping oversized REST fallback event (${envelopeBytes + entryBytes} bytes exceeds ${maxBytes}-byte request budget)`;
|
|
294
|
+
rememberRuntimeError("REST fallback ingestion", new Error(message));
|
|
295
|
+
console.warn(`📊 Langfuse: ${message}`);
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
290
298
|
const separators = chunk.length > 0 ? 1 : 0;
|
|
291
299
|
const projectedBytes = chunkBytes + entryBytes + separators;
|
|
292
300
|
if (chunk.length > 0 && projectedBytes > maxBytes) {
|
|
@@ -443,15 +451,16 @@ function applyObservationUpdate(record: RestFallbackObservation, body: Record<st
|
|
|
443
451
|
if (completionStartTime) record.completionStartTime = completionStartTime;
|
|
444
452
|
}
|
|
445
453
|
|
|
446
|
-
function applyTraceUpdate(store: RestFallbackStore, body: Record<string, unknown> | undefined) {
|
|
447
|
-
|
|
454
|
+
function applyTraceUpdate(store: RestFallbackStore, traceId: string, body: Record<string, unknown> | undefined) {
|
|
455
|
+
const trace = store.traces.get(traceId);
|
|
456
|
+
if (!trace || !body) {
|
|
448
457
|
return;
|
|
449
458
|
}
|
|
450
459
|
|
|
451
|
-
if ("input" in body)
|
|
452
|
-
if ("output" in body)
|
|
460
|
+
if ("input" in body) trace.input = body.input;
|
|
461
|
+
if ("output" in body) trace.output = body.output;
|
|
453
462
|
if ("metadata" in body && body.metadata && typeof body.metadata === "object") {
|
|
454
|
-
|
|
463
|
+
trace.metadata = mergeMetadata(trace.metadata, body.metadata as Record<string, unknown>);
|
|
455
464
|
}
|
|
456
465
|
}
|
|
457
466
|
|
|
@@ -542,7 +551,7 @@ function wrapObservation(
|
|
|
542
551
|
parentObservationId?: string,
|
|
543
552
|
): any {
|
|
544
553
|
const id = observation.id || randomUUID();
|
|
545
|
-
const traceId = observation.traceId ||
|
|
554
|
+
const traceId = observation.traceId || randomUUID();
|
|
546
555
|
const metadata = body?.metadata && typeof body.metadata === "object" ? body.metadata as Record<string, unknown> : undefined;
|
|
547
556
|
const record: RestFallbackObservation = {
|
|
548
557
|
id,
|
|
@@ -558,18 +567,18 @@ function wrapObservation(
|
|
|
558
567
|
store.observations.push(record);
|
|
559
568
|
store.observationById.set(id, record);
|
|
560
569
|
|
|
561
|
-
if (!parentObservationId && !store.
|
|
570
|
+
if (!parentObservationId && !store.traces.has(traceId)) {
|
|
562
571
|
const propagated = readPropagatedAttributes(observation);
|
|
563
|
-
store.
|
|
572
|
+
store.traces.set(traceId, {
|
|
564
573
|
id: traceId,
|
|
565
574
|
timestamp: record.startTime,
|
|
566
|
-
name,
|
|
575
|
+
name: propagated.traceName ?? name,
|
|
567
576
|
input: body?.input,
|
|
568
577
|
sessionId: propagated.sessionId
|
|
569
578
|
?? (typeof metadata?.sessionId === "string" ? metadata.sessionId : state.currentSessionId || undefined),
|
|
570
579
|
userId: propagated.userId ?? state.config?.userId,
|
|
571
|
-
metadata,
|
|
572
|
-
};
|
|
580
|
+
metadata: mergeMetadata(propagated.metadata, metadata),
|
|
581
|
+
});
|
|
573
582
|
}
|
|
574
583
|
|
|
575
584
|
return {
|
|
@@ -579,7 +588,7 @@ function wrapObservation(
|
|
|
579
588
|
update(updateBody?: Record<string, unknown>) {
|
|
580
589
|
applyObservationUpdate(record, updateBody);
|
|
581
590
|
if (!parentObservationId) {
|
|
582
|
-
applyTraceUpdate(store, updateBody);
|
|
591
|
+
applyTraceUpdate(store, traceId, updateBody);
|
|
583
592
|
}
|
|
584
593
|
const updated = observation.update(updateBody);
|
|
585
594
|
return updated === observation ? this : updated;
|
|
@@ -588,7 +597,7 @@ function wrapObservation(
|
|
|
588
597
|
if (endBody && typeof endBody === "object") {
|
|
589
598
|
applyObservationUpdate(record, endBody);
|
|
590
599
|
if (!parentObservationId) {
|
|
591
|
-
applyTraceUpdate(store, endBody);
|
|
600
|
+
applyTraceUpdate(store, traceId, endBody);
|
|
592
601
|
}
|
|
593
602
|
}
|
|
594
603
|
record.endTime = nowIso();
|
|
@@ -602,16 +611,17 @@ function wrapObservation(
|
|
|
602
611
|
}
|
|
603
612
|
const propagate = runtime?.propagateAttributes;
|
|
604
613
|
const createChild = () => observation.startObservation(childName, childBody, options);
|
|
614
|
+
const createOwnedChild = () => store.withTracerProvider ? store.withTracerProvider(createChild) : createChild();
|
|
605
615
|
const createInheritingChild = propagate && Object.keys(inherited).length > 0
|
|
606
|
-
? () => propagate(inherited,
|
|
607
|
-
:
|
|
616
|
+
? () => propagate(inherited, createOwnedChild)
|
|
617
|
+
: createOwnedChild;
|
|
608
618
|
const child = runtime?.withRootContext
|
|
609
619
|
? runtime.withRootContext(createInheritingChild)
|
|
610
620
|
: createInheritingChild();
|
|
611
621
|
return wrapObservation(child, store, childName, childBody, options?.asType, id);
|
|
612
622
|
},
|
|
613
623
|
setTraceIO(traceBody?: { input?: unknown; output?: unknown }) {
|
|
614
|
-
applyTraceUpdate(store, traceBody);
|
|
624
|
+
applyTraceUpdate(store, traceId, traceBody);
|
|
615
625
|
return observation.setTraceIO?.(traceBody);
|
|
616
626
|
},
|
|
617
627
|
};
|
|
@@ -694,22 +704,32 @@ async function getTraceVisibility(
|
|
|
694
704
|
async function waitForTraceVisibility(
|
|
695
705
|
rt: LangfuseRuntime,
|
|
696
706
|
store: RestFallbackStore,
|
|
697
|
-
traceId: string,
|
|
698
707
|
signal: AbortSignal,
|
|
699
|
-
|
|
700
|
-
|
|
708
|
+
shutdownDeadline: number,
|
|
709
|
+
): Promise<RestFallbackTrace[]> {
|
|
710
|
+
const now = Date.now();
|
|
711
|
+
// Leave a quarter of the remaining shutdown time for REST ingestion.
|
|
712
|
+
const deadline = now + Math.min(OTEL_VISIBILITY_TIMEOUT_MS, Math.max(0, shutdownDeadline - now) * 0.75);
|
|
713
|
+
const pending = new Map(store.traces);
|
|
714
|
+
const missing = new Set<string>();
|
|
701
715
|
|
|
702
716
|
while (true) {
|
|
703
|
-
const
|
|
704
|
-
|
|
705
|
-
|
|
717
|
+
const ids = [...pending.keys()];
|
|
718
|
+
// Bound read concurrency and stop polling in time to send the REST batch.
|
|
719
|
+
for (let index = 0; index < ids.length && Date.now() < deadline; index += 4) {
|
|
720
|
+
const readSignal = AbortSignal.any([signal, AbortSignal.timeout(Math.max(1, Math.floor(deadline - Date.now())))]);
|
|
721
|
+
await Promise.all(ids.slice(index, index + 4).map(async traceId => {
|
|
722
|
+
try {
|
|
723
|
+
const visibility = await getTraceVisibility(rt, store, traceId, readSignal);
|
|
724
|
+
if (visibility === "missing") missing.add(traceId);
|
|
725
|
+
else { pending.delete(traceId); missing.delete(traceId); }
|
|
726
|
+
} catch (error) {
|
|
727
|
+
if (signal.aborted || !readSignal.aborted) throw error;
|
|
728
|
+
}
|
|
729
|
+
}));
|
|
706
730
|
}
|
|
707
|
-
|
|
708
731
|
const remainingMs = deadline - Date.now();
|
|
709
|
-
if (remainingMs <= 0)
|
|
710
|
-
return "missing";
|
|
711
|
-
}
|
|
712
|
-
|
|
732
|
+
if (pending.size === 0 || remainingMs <= 0) return [...pending.values()].filter(trace => missing.has(trace.id));
|
|
713
733
|
await delay(Math.min(OTEL_VISIBILITY_POLL_INTERVAL_MS, remainingMs), signal);
|
|
714
734
|
}
|
|
715
735
|
}
|
|
@@ -718,42 +738,23 @@ function eventTimestamp(record: { endTime?: string; startTime?: string; timestam
|
|
|
718
738
|
return record.endTime ?? record.startTime ?? record.timestamp ?? nowIso();
|
|
719
739
|
}
|
|
720
740
|
|
|
721
|
-
async function fallbackToRestIngestion(rt: LangfuseRuntime, signal: AbortSignal) {
|
|
741
|
+
async function fallbackToRestIngestion(rt: LangfuseRuntime, signal: AbortSignal, shutdownDeadline: number) {
|
|
722
742
|
const store = rt.restFallback as RestFallbackStore | undefined;
|
|
723
|
-
if (!store?.
|
|
724
|
-
return;
|
|
725
|
-
}
|
|
743
|
+
if (!store?.traces.size || store.attempted) return;
|
|
726
744
|
store.attempted = true;
|
|
727
745
|
|
|
728
|
-
const
|
|
729
|
-
if (
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
const trace = store.trace;
|
|
738
|
-
const entries: any[] = [
|
|
739
|
-
{
|
|
740
|
-
type: "trace-create",
|
|
741
|
-
id: randomUUID(),
|
|
742
|
-
timestamp: eventTimestamp(trace),
|
|
743
|
-
body: {
|
|
744
|
-
id: trace.id,
|
|
745
|
-
timestamp: trace.timestamp,
|
|
746
|
-
name: trace.name,
|
|
747
|
-
input: trace.input,
|
|
748
|
-
output: trace.output,
|
|
749
|
-
sessionId: trace.sessionId,
|
|
750
|
-
userId: trace.userId,
|
|
751
|
-
metadata: trace.metadata,
|
|
752
|
-
},
|
|
753
|
-
},
|
|
754
|
-
];
|
|
746
|
+
const traces = await waitForTraceVisibility(rt, store, signal, shutdownDeadline);
|
|
747
|
+
if (traces.length === 0) return;
|
|
748
|
+
const missingIds = new Set(traces.map(trace => trace.id));
|
|
749
|
+
const entries: any[] = traces.map(trace => ({
|
|
750
|
+
type: "trace-create",
|
|
751
|
+
id: randomUUID(),
|
|
752
|
+
timestamp: eventTimestamp(trace),
|
|
753
|
+
body: { ...trace },
|
|
754
|
+
}));
|
|
755
755
|
|
|
756
756
|
for (const observation of store.observations) {
|
|
757
|
+
if (!missingIds.has(observation.traceId)) continue;
|
|
757
758
|
const body = {
|
|
758
759
|
id: observation.id,
|
|
759
760
|
traceId: observation.traceId,
|
|
@@ -815,7 +816,7 @@ async function fallbackToRestIngestion(rt: LangfuseRuntime, signal: AbortSignal)
|
|
|
815
816
|
console.warn("📊 Langfuse: REST fallback ingestion reported errors", errors);
|
|
816
817
|
} else {
|
|
817
818
|
debugLog(
|
|
818
|
-
`📊 Langfuse:
|
|
819
|
+
`📊 Langfuse: Processed ${traces.length} missing trace(s) via REST ingestion (${chunks.length} chunk(s))`,
|
|
819
820
|
);
|
|
820
821
|
}
|
|
821
822
|
}
|
|
@@ -852,7 +853,11 @@ export async function getRuntime(): Promise<LangfuseRuntime> {
|
|
|
852
853
|
import("@langfuse/client"),
|
|
853
854
|
]);
|
|
854
855
|
|
|
856
|
+
// Another caller may have initialized it while the shared imports loaded.
|
|
857
|
+
if (runtime) return runtime;
|
|
858
|
+
|
|
855
859
|
const restFallback: RestFallbackStore = {
|
|
860
|
+
traces: new Map(),
|
|
856
861
|
observations: [],
|
|
857
862
|
observationById: new Map(),
|
|
858
863
|
attempted: false,
|
|
@@ -874,11 +879,10 @@ export async function getRuntime(): Promise<LangfuseRuntime> {
|
|
|
874
879
|
resources.detectResources({ detectors: [resources.envDetector] }),
|
|
875
880
|
);
|
|
876
881
|
const tracerProvider = new BasicTracerProvider({ resource, spanProcessors: [spanProcessor] });
|
|
877
|
-
tracing.setLangfuseTracerProvider(tracerProvider);
|
|
878
882
|
|
|
879
883
|
runtime = {
|
|
880
884
|
startObservation: ((name: string, body?: Record<string, unknown>, options?: { asType?: string }) => {
|
|
881
|
-
const observation = (tracing as any).startObservation(name, body, options);
|
|
885
|
+
const observation = restFallback.withTracerProvider!(() => (tracing as any).startObservation(name, body, options));
|
|
882
886
|
return wrapObservation(observation, restFallback, name, body, options?.asType);
|
|
883
887
|
}) as unknown as LangfuseRuntime["startObservation"],
|
|
884
888
|
propagateAttributes: tracing.propagateAttributes as unknown as LangfuseRuntime["propagateAttributes"],
|
|
@@ -890,7 +894,6 @@ export async function getRuntime(): Promise<LangfuseRuntime> {
|
|
|
890
894
|
}) as LangfuseScoreClient,
|
|
891
895
|
spanProcessor,
|
|
892
896
|
tracerProvider,
|
|
893
|
-
clearTracerProvider: () => tracing.setLangfuseTracerProvider(null),
|
|
894
897
|
restFallback,
|
|
895
898
|
pendingScores: [],
|
|
896
899
|
scoreFlushAt,
|
|
@@ -903,6 +906,14 @@ export async function getRuntime(): Promise<LangfuseRuntime> {
|
|
|
903
906
|
host: state.config.host,
|
|
904
907
|
},
|
|
905
908
|
};
|
|
909
|
+
const ownedRuntime = runtime;
|
|
910
|
+
// Pi reloads extension modules per session, but the SDK provider is process-global.
|
|
911
|
+
restFallback.withTracerProvider = fn => {
|
|
912
|
+
const previous = tracing.getLangfuseTracerProvider();
|
|
913
|
+
tracing.setLangfuseTracerProvider(ownedRuntime.tracerProvider);
|
|
914
|
+
try { return fn(); }
|
|
915
|
+
finally { tracing.setLangfuseTracerProvider(previous); }
|
|
916
|
+
};
|
|
906
917
|
lastRuntimeError = null;
|
|
907
918
|
} catch (e) {
|
|
908
919
|
rememberRuntimeError("runtime init", e);
|
|
@@ -952,7 +963,7 @@ function doShutdownRuntime(): Promise<void> {
|
|
|
952
963
|
await runShutdownStep("OTel tracer shutdown", () => rt.tracerProvider?.shutdown?.(), deadline);
|
|
953
964
|
await runShutdownStep(
|
|
954
965
|
"REST fallback ingestion",
|
|
955
|
-
() => fallbackToRestIngestion(rt, controller.signal),
|
|
966
|
+
() => fallbackToRestIngestion(rt, controller.signal, deadline),
|
|
956
967
|
deadline,
|
|
957
968
|
controller.signal,
|
|
958
969
|
);
|
package/src/observation.ts
CHANGED
|
@@ -19,3 +19,30 @@ export async function startChildObservation({
|
|
|
19
19
|
|
|
20
20
|
return (await runtime()).startObservation(name, body, { asType });
|
|
21
21
|
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Starts a top-level observation for a session-scoped event that arrives when no
|
|
25
|
+
* agent run is active (e.g. recovery compaction after a failed generation).
|
|
26
|
+
*
|
|
27
|
+
* Attributes must be passed explicitly: `propagateAttributes` only seeds the OTel
|
|
28
|
+
* context for the duration of its callback, so a root observation created outside
|
|
29
|
+
* a run would be written without `session.id` or `langfuse.trace.name` and would
|
|
30
|
+
* drop out of every session filter in Langfuse v4.
|
|
31
|
+
*/
|
|
32
|
+
export async function startSessionObservation({
|
|
33
|
+
runtime,
|
|
34
|
+
name,
|
|
35
|
+
body,
|
|
36
|
+
asType,
|
|
37
|
+
attributes,
|
|
38
|
+
}: {
|
|
39
|
+
runtime: () => Promise<LangfuseRuntime>;
|
|
40
|
+
name: string;
|
|
41
|
+
body?: ObservationUpdate;
|
|
42
|
+
asType: "event" | "generation" | "tool" | "span";
|
|
43
|
+
attributes: Parameters<LangfuseRuntime["propagateAttributes"]>[0];
|
|
44
|
+
}): Promise<LangfuseObservation> {
|
|
45
|
+
const rt = await runtime();
|
|
46
|
+
const create = () => rt.propagateAttributes(attributes, () => rt.startObservation(name, body, { asType }));
|
|
47
|
+
return rt.withRootContext ? rt.withRootContext(create) : create();
|
|
48
|
+
}
|
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
|
+
}
|