@narumitw/pi-otel 0.54.3 → 0.55.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.
@@ -3,6 +3,7 @@
3
3
 
4
4
  // src/otlp-settings.ts
5
5
  import { validateHeaderName, validateHeaderValue } from "node:http";
6
+ import { isIP } from "node:net";
6
7
  var RESERVED_HEADERS = /* @__PURE__ */ new Set([
7
8
  "__proto__",
8
9
  "connection",
@@ -14,22 +15,27 @@ var RESERVED_HEADERS = /* @__PURE__ */ new Set([
14
15
  "user-agent"
15
16
  ]);
16
17
  function normalizeOtlpConnection(input) {
17
- const endpoint = normalizeHttpUrl(input.endpoint);
18
- if (!endpoint) {
18
+ const url = parseHttpUrl(input.endpoint);
19
+ if (!url) {
19
20
  throw new Error("OTLP endpoint must be a full HTTP or HTTPS URL without credentials, a query, or a fragment.");
20
21
  }
21
22
  const serviceName = input.serviceName === void 0 ? "pi" : input.serviceName;
22
23
  if (typeof serviceName !== "string" || !serviceName.trim()) {
23
24
  throw new Error("OTLP serviceName must be a non-empty string.");
24
25
  }
25
- return { endpoint, headers: normalizeHeaders(input.headers), serviceName: serviceName.trim() };
26
+ const headers = normalizeHeaders(input.headers);
27
+ const loopback = url.hostname.startsWith("127.") && isIP(url.hostname) === 4 || url.hostname === "[::1]";
28
+ if (Object.keys(headers).length > 0 && url.protocol === "http:" && !loopback) {
29
+ throw new Error("OTLP headers require HTTPS unless the endpoint uses a loopback IP (127.0.0.0/8 or [::1]).");
30
+ }
31
+ return { endpoint: url.href, headers, serviceName: serviceName.trim() };
26
32
  }
27
- function normalizeHttpUrl(value) {
33
+ function parseHttpUrl(value) {
28
34
  if (typeof value !== "string" || !/^https?:\/\//iu.test(value.trim()) || /[?#]/u.test(value)) return void 0;
29
35
  try {
30
36
  const url = new URL(value.trim());
31
37
  if (url.username || url.password) return void 0;
32
- return url.href;
38
+ return url;
33
39
  } catch {
34
40
  return void 0;
35
41
  }
@@ -69,4 +75,4 @@ export {
69
75
  otlpSecrets,
70
76
  DEFAULT_BASE_URL
71
77
  };
72
- //# sourceMappingURL=chunk-7JGM5RS3.js.map
78
+ //# sourceMappingURL=chunk-ROM6FIM7.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/otlp-settings.ts", "../../src/runtime-defaults.ts"],
4
+ "sourcesContent": ["import { validateHeaderName, validateHeaderValue } from \"node:http\";\nimport { isIP } from \"node:net\";\n\nexport interface OtlpRuntimeConfig {\n endpoint: string;\n /** Requires HTTPS unless the endpoint uses a loopback IP. */\n headers?: Readonly<Record<string, string>>;\n serviceName?: string;\n}\n\nexport type OtlpConnection = Required<OtlpRuntimeConfig>;\n\nconst RESERVED_HEADERS = new Set([\n \"__proto__\",\n \"connection\",\n \"content-encoding\",\n \"content-length\",\n \"content-type\",\n \"host\",\n \"transfer-encoding\",\n \"user-agent\",\n]);\n\nexport function normalizeOtlpConnection(input: Readonly<Record<string, unknown>>): OtlpConnection {\n const url = parseHttpUrl(input.endpoint);\n if (!url) {\n throw new Error(\"OTLP endpoint must be a full HTTP or HTTPS URL without credentials, a query, or a fragment.\");\n }\n const serviceName = input.serviceName === undefined ? \"pi\" : input.serviceName;\n if (typeof serviceName !== \"string\" || !serviceName.trim()) {\n throw new Error(\"OTLP serviceName must be a non-empty string.\");\n }\n const headers = normalizeHeaders(input.headers);\n // URL canonicalizes numeric IPs. Do not trust DNS or hosts-file aliases with cleartext credentials.\n const loopback = (url.hostname.startsWith(\"127.\") && isIP(url.hostname) === 4) || url.hostname === \"[::1]\";\n if (Object.keys(headers).length > 0 && url.protocol === \"http:\" && !loopback) {\n throw new Error(\"OTLP headers require HTTPS unless the endpoint uses a loopback IP (127.0.0.0/8 or [::1]).\");\n }\n return { endpoint: url.href, headers, serviceName: serviceName.trim() };\n}\n\nfunction parseHttpUrl(value: unknown): URL | undefined {\n if (typeof value !== \"string\" || !/^https?:\\/\\//iu.test(value.trim()) || /[?#]/u.test(value)) return undefined;\n try {\n const url = new URL(value.trim());\n if (url.username || url.password) return undefined;\n return url;\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeHeaders(input: unknown): Record<string, string> {\n if (input === undefined) return {};\n if (input === null || typeof input !== \"object\" || Array.isArray(input)) {\n throw new Error(\"OTLP headers must be an object of literal HTTP header names and values.\");\n }\n const entries = new Map<string, string>();\n for (const [name, value] of Object.entries(input)) {\n const key = name.toLowerCase();\n try {\n validateHeaderName(name);\n if (typeof value !== \"string\" || !value.trim() || RESERVED_HEADERS.has(key) || entries.has(key)) {\n throw new Error(\"Invalid header\");\n }\n validateHeaderValue(name, value);\n entries.set(key, value.trim());\n } catch {\n // Neither the header name nor its value is safe to include in a diagnostic.\n throw new Error(\"OTLP headers contain an invalid, reserved, empty, or duplicate HTTP header.\");\n }\n }\n return Object.fromEntries([...entries].sort(([left], [right]) => left.localeCompare(right)));\n}\n\nexport function otlpSecrets(headers: Readonly<Record<string, string>>): string[] {\n const auth = headers.authorization;\n const token = auth?.match(/^\\S+\\s+(.+)$/u)?.[1];\n return [...new Set([...Object.values(headers), ...(token ? [token] : [])])].sort((a, b) => b.length - a.length);\n}\n", "export const DEFAULT_BASE_URL = \"https://us.cloud.langfuse.com\";\n"],
5
+ "mappings": ";;;;AAAA,SAAS,oBAAoB,2BAA2B;AACxD,SAAS,YAAY;AAWrB,IAAM,mBAAmB,oBAAI,IAAI;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAEM,SAAS,wBAAwB,OAA0D;AAChG,QAAM,MAAM,aAAa,MAAM,QAAQ;AACvC,MAAI,CAAC,KAAK;AACR,UAAM,IAAI,MAAM,6FAA6F;AAAA,EAC/G;AACA,QAAM,cAAc,MAAM,gBAAgB,SAAY,OAAO,MAAM;AACnE,MAAI,OAAO,gBAAgB,YAAY,CAAC,YAAY,KAAK,GAAG;AAC1D,UAAM,IAAI,MAAM,8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,6EAA6E;AAAA,IAC/F;AAAA,EACF;AACA,SAAO,OAAO,YAAY,CAAC,GAAG,OAAO,EAAE,KAAK,CAAC,CAAC,IAAI,GAAG,CAAC,KAAK,MAAM,KAAK,cAAc,KAAK,CAAC,CAAC;AAC7F;AAEO,SAAS,YAAY,SAAqD;AAC/E,QAAM,OAAO,QAAQ;AACrB,QAAM,QAAQ,MAAM,MAAM,eAAe,IAAI,CAAC;AAC9C,SAAO,CAAC,GAAG,oBAAI,IAAI,CAAC,GAAG,OAAO,OAAO,OAAO,GAAG,GAAI,QAAQ,CAAC,KAAK,IAAI,CAAC,CAAE,CAAC,CAAC,EAAE,KAAK,CAAC,GAAG,MAAM,EAAE,SAAS,EAAE,MAAM;AAChH;;;AC/EO,IAAM,mBAAmB;",
6
+ "names": []
7
+ }
@@ -3,11 +3,11 @@
3
3
 
4
4
  // src/runtime-api.ts
5
5
  async function createLangfuseRuntime(options = {}) {
6
- const runtime = await import("./runtime-554E6FVF.js");
6
+ const runtime = await import("./runtime-7TSAKORH.js");
7
7
  return runtime.createLangfuseRuntime(options);
8
8
  }
9
9
  async function createOtelRuntime(config) {
10
- const runtime = await import("./runtime-554E6FVF.js");
10
+ const runtime = await import("./runtime-7TSAKORH.js");
11
11
  return runtime.createOtelRuntime(config);
12
12
  }
13
13
 
@@ -155,4 +155,4 @@ export {
155
155
  createLangfuseRuntime,
156
156
  createOtelRuntime
157
157
  };
158
- //# sourceMappingURL=chunk-7DN64UHE.js.map
158
+ //# sourceMappingURL=chunk-ZCEZBO2T.js.map
@@ -4,7 +4,7 @@ import {
4
4
  DEFAULT_BASE_URL,
5
5
  normalizeOtlpConnection,
6
6
  otlpSecrets
7
- } from "./chunk-7JGM5RS3.js";
7
+ } from "./chunk-ROM6FIM7.js";
8
8
  import {
9
9
  createLangfuseRuntimeFromBackend,
10
10
  getLangfuseRuntimeInternal
@@ -403,4 +403,4 @@ export {
403
403
  maskSecrets,
404
404
  resolveLangfuseRuntimeConfig
405
405
  };
406
- //# sourceMappingURL=runtime-554E6FVF.js.map
406
+ //# sourceMappingURL=runtime-7TSAKORH.js.map
@@ -1,5 +1,6 @@
1
1
  export interface OtlpRuntimeConfig {
2
2
  endpoint: string;
3
+ /** Requires HTTPS unless the endpoint uses a loopback IP. */
3
4
  headers?: Readonly<Record<string, string>>;
4
5
  serviceName?: string;
5
6
  }
package/dist/tracing.d.ts CHANGED
@@ -194,5 +194,6 @@ export declare class TraceRecorder {
194
194
  private closeTools;
195
195
  private closeGeneration;
196
196
  private closeCompaction;
197
+ private captureErrorMessage;
197
198
  private capture;
198
199
  }
package/docs/durable.md CHANGED
@@ -14,7 +14,7 @@ Import `createPiLangfuseDurableConversation` from `@narumitw/pi-otel/durable` to
14
14
  The coding-agent, durable and Chord peers are optional because each entry only needs its own runtime. Install durable and Chord explicitly for `/durable`. They are host peers rather than adapter-owned execution dependencies so the host's experimental Harness and Context APIs stay aligned. The adapter uses the host Harness's public `observeConversation()` and `observeCommits()` methods. Keep host dependencies within the declared peer contract, and check `active`/`onError` when attaching. Run the durable and packed-consumer checks on the host's supported Node versions before deployment.
15
15
  The Langfuse SDK independently requires Node >=22, but that is not sufficient for these Pi runtimes; see the [installation requirements](../README.md#-install). The tested host dependencies are the versions resolved from the package's devDependencies and repository lockfile. Pi AI's nominal transcript types must resolve consistently with the host's durable dependency resolution; do not pass a Models collection from an incompatible Pi AI release.
16
16
 
17
- For an upstream upgrade, inspect the changelog, README, public root exports/types and installed implementation. Review synchronous observation ordering, deferred persistence, submission and task publications, request checkpoint identities, the read-only attachment barrier, source end reasons and `Harness.closed`, `Submission.status()`, committed message projections and cancellation semantics. Review the durable peer range and update the test dependency together. Run the focused durable and coding-agent suites, `npm run check`, `npm test`, `npm run package:pack -- langfuse`, packed consumer tests on supported Node versions, and the package-directory Pi loading smoke. Never replace removed public APIs with private imports or coding-agent event casts.
17
+ For an upstream upgrade, inspect the changelog, README, public root exports/types and installed implementation. Review synchronous observation ordering, deferred persistence, submission and task publications, request checkpoint identities, the read-only attachment barrier, source end reasons and `Harness.closed`, `Submission.status()`, committed message projections and cancellation semantics. Review the durable peer range and update the test dependency together. Run the focused durable and coding-agent suites, `npm run check`, `npm test`, `npm run package:pack -- otel`, packed consumer tests on supported Node versions, and the package-directory Pi loading smoke. Never replace removed public APIs with private imports or coding-agent event casts.
18
18
 
19
19
  ## Minimal host example
20
20
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-otel",
3
- "version": "0.54.3",
3
+ "version": "0.55.1",
4
4
  "description": "Pi extension that exports agent, model, and tool traces to OpenTelemetry collectors or Langfuse.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -64,9 +64,9 @@
64
64
  }
65
65
  },
66
66
  "devDependencies": {
67
- "@earendil-works/pi-coding-agent": "1.5.0",
68
- "@earendil-works/pi-durable": "1.5.0",
69
- "@earendil-works/chord": "1.5.0",
67
+ "@earendil-works/pi-coding-agent": "1.6.0",
68
+ "@earendil-works/pi-durable": "1.6.0",
69
+ "@earendil-works/chord": "1.6.0",
70
70
  "@types/node": "26.6.6",
71
71
  "protobufjs": "7.6.5",
72
72
  "typescript": "7.0.2",
@@ -17,7 +17,7 @@ import {
17
17
 
18
18
  export interface DurableLive {
19
19
  run?: { taskId: TaskId; inputs: readonly SubmissionId[]; afterRun: boolean };
20
- tools: readonly { taskId?: TaskId; callId: string; name: string; status: "pending" | "running" | "done" }[];
20
+ tools: readonly { taskId?: TaskId; callId: string; name: string }[];
21
21
  }
22
22
  export interface DurableSnapshot {
23
23
  entries: readonly EntryRecord[];
@@ -49,11 +49,10 @@ function liveProjection(live: LiveState = {}): DurableLive {
49
49
  ...(live.run
50
50
  ? { run: { taskId: live.run.taskId, inputs: live.run.inputs, afterRun: live.run.afterRun !== undefined } }
51
51
  : {}),
52
- tools: [...(live.tools ?? []), ...(live.nestedTools ?? [])].map(({ taskId, callId, name, status }) => ({
52
+ tools: [...(live.tools ?? []), ...(live.nestedTools ?? [])].map(({ taskId, callId, name }) => ({
53
53
  taskId,
54
54
  callId,
55
55
  name,
56
- status,
57
56
  })),
58
57
  };
59
58
  }
package/src/durable.ts CHANGED
@@ -1,5 +1,4 @@
1
- import type { Context } from "@earendil-works/chord";
2
- import { awaitWithContext, withCancel } from "@earendil-works/chord/context";
1
+ import { awaitWithContext, type Context, withCancel } from "@earendil-works/chord/context";
3
2
  import type {
4
3
  CommitObservation,
5
4
  ConversationId,
@@ -1,7 +1,9 @@
1
1
  import { validateHeaderName, validateHeaderValue } from "node:http";
2
+ import { isIP } from "node:net";
2
3
 
3
4
  export interface OtlpRuntimeConfig {
4
5
  endpoint: string;
6
+ /** Requires HTTPS unless the endpoint uses a loopback IP. */
5
7
  headers?: Readonly<Record<string, string>>;
6
8
  serviceName?: string;
7
9
  }
@@ -20,23 +22,29 @@ const RESERVED_HEADERS = new Set([
20
22
  ]);
21
23
 
22
24
  export function normalizeOtlpConnection(input: Readonly<Record<string, unknown>>): OtlpConnection {
23
- const endpoint = normalizeHttpUrl(input.endpoint);
24
- if (!endpoint) {
25
+ const url = parseHttpUrl(input.endpoint);
26
+ if (!url) {
25
27
  throw new Error("OTLP endpoint must be a full HTTP or HTTPS URL without credentials, a query, or a fragment.");
26
28
  }
27
29
  const serviceName = input.serviceName === undefined ? "pi" : input.serviceName;
28
30
  if (typeof serviceName !== "string" || !serviceName.trim()) {
29
31
  throw new Error("OTLP serviceName must be a non-empty string.");
30
32
  }
31
- return { endpoint, headers: normalizeHeaders(input.headers), serviceName: serviceName.trim() };
33
+ const headers = normalizeHeaders(input.headers);
34
+ // URL canonicalizes numeric IPs. Do not trust DNS or hosts-file aliases with cleartext credentials.
35
+ const loopback = (url.hostname.startsWith("127.") && isIP(url.hostname) === 4) || url.hostname === "[::1]";
36
+ if (Object.keys(headers).length > 0 && url.protocol === "http:" && !loopback) {
37
+ throw new Error("OTLP headers require HTTPS unless the endpoint uses a loopback IP (127.0.0.0/8 or [::1]).");
38
+ }
39
+ return { endpoint: url.href, headers, serviceName: serviceName.trim() };
32
40
  }
33
41
 
34
- function normalizeHttpUrl(value: unknown): string | undefined {
42
+ function parseHttpUrl(value: unknown): URL | undefined {
35
43
  if (typeof value !== "string" || !/^https?:\/\//iu.test(value.trim()) || /[?#]/u.test(value)) return undefined;
36
44
  try {
37
45
  const url = new URL(value.trim());
38
46
  if (url.username || url.password) return undefined;
39
- return url.href;
47
+ return url;
40
48
  } catch {
41
49
  return undefined;
42
50
  }
package/src/tracing.ts CHANGED
@@ -372,7 +372,7 @@ export class TraceRecorder {
372
372
  level: "WARNING" as const,
373
373
  statusMessage: `Turn ${turnIndex} ended while turn ${this.turnIndex} was active.`,
374
374
  }
375
- : severityForOutcome(outcome, result.message.errorMessage)),
375
+ : severityForOutcome(outcome, this.captureErrorMessage(result.message.errorMessage))),
376
376
  });
377
377
  this.turn.end();
378
378
  this.turn = undefined;
@@ -482,7 +482,7 @@ export class TraceRecorder {
482
482
  ? { "pi.usage.cache_write_1h_tokens": message.usage.cacheWrite1h }
483
483
  : {}),
484
484
  },
485
- ...severityForOutcome(outcome, message.errorMessage),
485
+ ...severityForOutcome(outcome, this.captureErrorMessage(message.errorMessage)),
486
486
  });
487
487
  state.observation.end(state.endTime);
488
488
  this.generation = undefined;
@@ -656,7 +656,7 @@ export class TraceRecorder {
656
656
  const finalAttributes: ObservationAttributes = {
657
657
  ...(this.lastOutput !== undefined ? { output: this.lastOutput } : {}),
658
658
  metadata: finalMetadata,
659
- ...severityForOutcome(baseOutcome, statusMessage ?? this.lastAssistant?.errorMessage),
659
+ ...severityForOutcome(baseOutcome, statusMessage ?? this.captureErrorMessage(this.lastAssistant?.errorMessage)),
660
660
  };
661
661
  this.root.update(finalAttributes);
662
662
  this.root.updateTrace?.({
@@ -687,7 +687,7 @@ export class TraceRecorder {
687
687
  "pi.attempt.outcome": outcome,
688
688
  ...(message?.stopReason ? { "pi.attempt.stop_reason": message.stopReason } : {}),
689
689
  },
690
- ...severityForOutcome(outcome, statusMessage ?? message?.errorMessage),
690
+ ...severityForOutcome(outcome, statusMessage ?? this.captureErrorMessage(message?.errorMessage)),
691
691
  });
692
692
  this.attempt.end();
693
693
  this.attempt = undefined;
@@ -757,6 +757,12 @@ export class TraceRecorder {
757
757
  this.compaction = undefined;
758
758
  }
759
759
 
760
+ private captureErrorMessage(message: string | undefined): string | undefined {
761
+ // Provider error text can include request or response content. Keep the outcome, not the text, when capture is off.
762
+ if (!this.context.captureContent || typeof message !== "string") return undefined;
763
+ return String(sanitizeTraceValue(message));
764
+ }
765
+
760
766
  private capture(value: unknown): unknown {
761
767
  return this.context.captureContent ? sanitizeTraceValue(value) : CONTENT_DISABLED;
762
768
  }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/otlp-settings.ts", "../../src/runtime-defaults.ts", "../../src/runtime-core.ts"],
4
- "sourcesContent": ["import { validateHeaderName, validateHeaderValue } from \"node:http\";\n\nexport interface OtlpRuntimeConfig {\n endpoint: string;\n headers?: Readonly<Record<string, string>>;\n serviceName?: string;\n}\n\nexport type OtlpConnection = Required<OtlpRuntimeConfig>;\n\nconst RESERVED_HEADERS = new Set([\n \"__proto__\",\n \"connection\",\n \"content-encoding\",\n \"content-length\",\n \"content-type\",\n \"host\",\n \"transfer-encoding\",\n \"user-agent\",\n]);\n\nexport function normalizeOtlpConnection(input: Readonly<Record<string, unknown>>): OtlpConnection {\n const endpoint = normalizeHttpUrl(input.endpoint);\n if (!endpoint) {\n throw new Error(\"OTLP endpoint must be a full HTTP or HTTPS URL without credentials, a query, or a fragment.\");\n }\n const serviceName = input.serviceName === undefined ? \"pi\" : input.serviceName;\n if (typeof serviceName !== \"string\" || !serviceName.trim()) {\n throw new Error(\"OTLP serviceName must be a non-empty string.\");\n }\n return { endpoint, headers: normalizeHeaders(input.headers), serviceName: serviceName.trim() };\n}\n\nfunction normalizeHttpUrl(value: unknown): string | undefined {\n if (typeof value !== \"string\" || !/^https?:\\/\\//iu.test(value.trim()) || /[?#]/u.test(value)) return undefined;\n try {\n const url = new URL(value.trim());\n if (url.username || url.password) return undefined;\n return url.href;\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeHeaders(input: unknown): Record<string, string> {\n if (input === undefined) return {};\n if (input === null || typeof input !== \"object\" || Array.isArray(input)) {\n throw new Error(\"OTLP headers must be an object of literal HTTP header names and values.\");\n }\n const entries = new Map<string, string>();\n for (const [name, value] of Object.entries(input)) {\n const key = name.toLowerCase();\n try {\n validateHeaderName(name);\n if (typeof value !== \"string\" || !value.trim() || RESERVED_HEADERS.has(key) || entries.has(key)) {\n throw new Error(\"Invalid header\");\n }\n validateHeaderValue(name, value);\n entries.set(key, value.trim());\n } catch {\n // Neither the header name nor its value is safe to include in a diagnostic.\n throw new Error(\"OTLP headers contain an invalid, reserved, empty, or duplicate HTTP header.\");\n }\n }\n return Object.fromEntries([...entries].sort(([left], [right]) => left.localeCompare(right)));\n}\n\nexport function otlpSecrets(headers: Readonly<Record<string, string>>): string[] {\n const auth = headers.authorization;\n const token = auth?.match(/^\\S+\\s+(.+)$/u)?.[1];\n return [...new Set([...Object.values(headers), ...(token ? [token] : [])])].sort((a, b) => b.length - a.length);\n}\n", "export const DEFAULT_BASE_URL = \"https://us.cloud.langfuse.com\";\n", "import type { TraceBackend } from \"./tracing.js\";\n\nexport interface LangfuseRuntimeConfig {\n publicKey?: string;\n secretKey?: string;\n baseUrl?: string;\n environment?: string;\n release?: string;\n}\n\nexport interface CreateLangfuseRuntimeOptions {\n config?: LangfuseRuntimeConfig;\n env?: NodeJS.ProcessEnv | false;\n}\n\nexport interface LangfuseRuntime {\n readonly closed: boolean;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\ntype RuntimeSessionDisposer = (statusMessage: string) => void | Promise<void>;\n\nexport interface LangfuseRuntimeInternal extends LangfuseRuntime {\n readonly backend: TraceBackend;\n registerSession(disposer: RuntimeSessionDisposer): () => void;\n}\n\nconst RUNTIME_INTERNAL_KEY = Symbol.for(\"@narumitw/pi-langfuse/runtime-internal/v2\");\n\nclass ManagedLangfuseRuntime implements LangfuseRuntimeInternal {\n private state: \"open\" | \"closing\" | \"closed\" = \"open\";\n private readonly sessionDisposers = new Set<RuntimeSessionDisposer>();\n private flushQueue = Promise.resolve();\n private shutdownPromise: Promise<void> | undefined;\n\n constructor(readonly backend: TraceBackend) {}\n\n get closed(): boolean {\n return this.state !== \"open\";\n }\n\n registerSession(disposer: RuntimeSessionDisposer): () => void {\n if (this.state !== \"open\") throw new Error(\"Langfuse runtime is shutting down or already closed.\");\n this.sessionDisposers.add(disposer);\n return () => this.sessionDisposers.delete(disposer);\n }\n\n flush(): Promise<void> {\n if (this.state !== \"open\") {\n return Promise.reject(new Error(\"Langfuse runtime is shutting down or already closed.\"));\n }\n const operation = this.flushQueue.then(() => this.backend.forceFlush());\n this.flushQueue = operation.then(\n () => undefined,\n () => undefined,\n );\n return operation;\n }\n\n shutdown(): Promise<void> {\n if (this.shutdownPromise) return this.shutdownPromise;\n this.state = \"closing\";\n // Publish the promise before invoking controller callbacks, which can reenter shutdown().\n this.shutdownPromise = Promise.resolve().then(() => this.shutdownNow());\n return this.shutdownPromise;\n }\n\n private async shutdownNow(): Promise<void> {\n const errors: unknown[] = [];\n for (const dispose of [...this.sessionDisposers]) {\n try {\n await dispose(\"Langfuse runtime shut down before the Pi session was disposed.\");\n } catch (error) {\n errors.push(error);\n }\n }\n this.sessionDisposers.clear();\n\n await this.flushQueue;\n try {\n await this.backend.forceFlush();\n } catch (error) {\n errors.push(error);\n }\n try {\n await this.backend.shutdown();\n } catch (error) {\n errors.push(error);\n } finally {\n this.state = \"closed\";\n }\n\n if (errors.length === 1) throw errors[0];\n if (errors.length > 1) throw new AggregateError(errors, \"Langfuse runtime shutdown failed.\");\n }\n}\n\nexport function getLangfuseRuntimeInternal(runtime: LangfuseRuntime): LangfuseRuntimeInternal {\n const internal = (runtime as LangfuseRuntime & { [key: symbol]: LangfuseRuntimeInternal | undefined })[\n RUNTIME_INTERNAL_KEY\n ];\n if (!internal) throw new Error(\"The tracing runtime was not created by this package.\");\n return internal;\n}\n\nexport function createLangfuseRuntimeFromBackend(backend: TraceBackend): LangfuseRuntime {\n return registerLangfuseRuntime(new ManagedLangfuseRuntime(backend));\n}\n\nexport function registerLangfuseRuntime(runtime: LangfuseRuntimeInternal): LangfuseRuntimeInternal {\n Object.defineProperty(runtime, RUNTIME_INTERNAL_KEY, { value: runtime });\n return runtime;\n}\n"],
5
- "mappings": ";;;;AAAA,SAAS,oBAAoB,2BAA2B;AAUxD,IAAM,mBAAmB,oBAAI,IAAI;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAEM,SAAS,wBAAwB,OAA0D;AAChG,QAAM,WAAW,iBAAiB,MAAM,QAAQ;AAChD,MAAI,CAAC,UAAU;AACb,UAAM,IAAI,MAAM,6FAA6F;AAAA,EAC/G;AACA,QAAM,cAAc,MAAM,gBAAgB,SAAY,OAAO,MAAM;AACnE,MAAI,OAAO,gBAAgB,YAAY,CAAC,YAAY,KAAK,GAAG;AAC1D,UAAM,IAAI,MAAM,8CAA8C;AAAA,EAChE;AACA,SAAO,EAAE,UAAU,SAAS,iBAAiB,MAAM,OAAO,GAAG,aAAa,YAAY,KAAK,EAAE;AAC/F;AAEA,SAAS,iBAAiB,OAAoC;AAC5D,MAAI,OAAO,UAAU,YAAY,CAAC,iBAAiB,KAAK,MAAM,KAAK,CAAC,KAAK,QAAQ,KAAK,KAAK,EAAG,QAAO;AACrG,MAAI;AACF,UAAM,MAAM,IAAI,IAAI,MAAM,KAAK,CAAC;AAChC,QAAI,IAAI,YAAY,IAAI,SAAU,QAAO;AACzC,WAAO,IAAI;AAAA,EACb,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,iBAAiB,OAAwC;AAChE,MAAI,UAAU,OAAW,QAAO,CAAC;AACjC,MAAI,UAAU,QAAQ,OAAO,UAAU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AAS,EAAG,OAAM,IAAI,eAAe,QAAQ,mCAAmC;AAAA,EAC7F;AACF;AAEO,SAAS,2BAA2B,SAAmD;AAC5F,QAAM,WAAY,QAChB,oBACF;AACA,MAAI,CAAC,SAAU,OAAM,IAAI,MAAM,sDAAsD;AACrF,SAAO;AACT;AAEO,SAAS,iCAAiC,SAAwC;AACvF,SAAO,wBAAwB,IAAI,uBAAuB,OAAO,CAAC;AACpE;AAEO,SAAS,wBAAwB,SAA2D;AACjG,SAAO,eAAe,SAAS,sBAAsB,EAAE,OAAO,QAAQ,CAAC;AACvE,SAAO;AACT;",
6
- "names": []
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/otlp-settings.ts", "../../src/runtime-defaults.ts"],
4
- "sourcesContent": ["import { validateHeaderName, validateHeaderValue } from \"node:http\";\n\nexport interface OtlpRuntimeConfig {\n endpoint: string;\n headers?: Readonly<Record<string, string>>;\n serviceName?: string;\n}\n\nexport type OtlpConnection = Required<OtlpRuntimeConfig>;\n\nconst RESERVED_HEADERS = new Set([\n \"__proto__\",\n \"connection\",\n \"content-encoding\",\n \"content-length\",\n \"content-type\",\n \"host\",\n \"transfer-encoding\",\n \"user-agent\",\n]);\n\nexport function normalizeOtlpConnection(input: Readonly<Record<string, unknown>>): OtlpConnection {\n const endpoint = normalizeHttpUrl(input.endpoint);\n if (!endpoint) {\n throw new Error(\"OTLP endpoint must be a full HTTP or HTTPS URL without credentials, a query, or a fragment.\");\n }\n const serviceName = input.serviceName === undefined ? \"pi\" : input.serviceName;\n if (typeof serviceName !== \"string\" || !serviceName.trim()) {\n throw new Error(\"OTLP serviceName must be a non-empty string.\");\n }\n return { endpoint, headers: normalizeHeaders(input.headers), serviceName: serviceName.trim() };\n}\n\nfunction normalizeHttpUrl(value: unknown): string | undefined {\n if (typeof value !== \"string\" || !/^https?:\\/\\//iu.test(value.trim()) || /[?#]/u.test(value)) return undefined;\n try {\n const url = new URL(value.trim());\n if (url.username || url.password) return undefined;\n return url.href;\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeHeaders(input: unknown): Record<string, string> {\n if (input === undefined) return {};\n if (input === null || typeof input !== \"object\" || Array.isArray(input)) {\n throw new Error(\"OTLP headers must be an object of literal HTTP header names and values.\");\n }\n const entries = new Map<string, string>();\n for (const [name, value] of Object.entries(input)) {\n const key = name.toLowerCase();\n try {\n validateHeaderName(name);\n if (typeof value !== \"string\" || !value.trim() || RESERVED_HEADERS.has(key) || entries.has(key)) {\n throw new Error(\"Invalid header\");\n }\n validateHeaderValue(name, value);\n entries.set(key, value.trim());\n } catch {\n // Neither the header name nor its value is safe to include in a diagnostic.\n throw new Error(\"OTLP headers contain an invalid, reserved, empty, or duplicate HTTP header.\");\n }\n }\n return Object.fromEntries([...entries].sort(([left], [right]) => left.localeCompare(right)));\n}\n\nexport function otlpSecrets(headers: Readonly<Record<string, string>>): string[] {\n const auth = headers.authorization;\n const token = auth?.match(/^\\S+\\s+(.+)$/u)?.[1];\n return [...new Set([...Object.values(headers), ...(token ? [token] : [])])].sort((a, b) => b.length - a.length);\n}\n", "export const DEFAULT_BASE_URL = \"https://us.cloud.langfuse.com\";\n"],
5
- "mappings": ";;;;AAAA,SAAS,oBAAoB,2BAA2B;AAUxD,IAAM,mBAAmB,oBAAI,IAAI;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAEM,SAAS,wBAAwB,OAA0D;AAChG,QAAM,WAAW,iBAAiB,MAAM,QAAQ;AAChD,MAAI,CAAC,UAAU;AACb,UAAM,IAAI,MAAM,6FAA6F;AAAA,EAC/G;AACA,QAAM,cAAc,MAAM,gBAAgB,SAAY,OAAO,MAAM;AACnE,MAAI,OAAO,gBAAgB,YAAY,CAAC,YAAY,KAAK,GAAG;AAC1D,UAAM,IAAI,MAAM,8CAA8C;AAAA,EAChE;AACA,SAAO,EAAE,UAAU,SAAS,iBAAiB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