@agimon-ai/po-core 0.0.0-alpha.46 → 0.0.0-alpha.48
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/dist/src/services/poTelemetry/index.cjs +49 -1
- package/dist/src/services/poTelemetry/index.cjs.map +1 -1
- package/dist/src/services/poTelemetry/index.d.mts.map +1 -1
- package/dist/src/services/poTelemetry/index.mjs +49 -1
- package/dist/src/services/poTelemetry/index.mjs.map +1 -1
- package/dist/src/services/telemetry/index.cjs +18 -2
- package/dist/src/services/telemetry/index.cjs.map +1 -1
- package/dist/src/services/telemetry/index.mjs +18 -2
- package/dist/src/services/telemetry/index.mjs.map +1 -1
- package/package.json +4 -4
|
@@ -1,11 +1,59 @@
|
|
|
1
1
|
const require_index = require("../telemetry/index.cjs");
|
|
2
2
|
//#region src/services/poTelemetry/index.ts
|
|
3
3
|
let nodeTelemetryModule;
|
|
4
|
+
const SESSION_HEADERS = /* @__PURE__ */ new Set(["x-agent-session-id", "x-agent-parent-session-id"]);
|
|
5
|
+
const PIPELINE_ENV = /^(?:OTEL_|LOG_SINK_)|^npm_package_version$/u;
|
|
6
|
+
const pipelines = /* @__PURE__ */ new Map();
|
|
7
|
+
/** One exporter pipeline per service and endpoint for the whole process; the last shutdown frees it. */
|
|
8
|
+
function shareNodeTelemetry(create) {
|
|
9
|
+
return async (options) => {
|
|
10
|
+
const shared = {
|
|
11
|
+
...options,
|
|
12
|
+
cwd: options.resolvedEndpoints ? void 0 : options.cwd,
|
|
13
|
+
env: options.env && Object.fromEntries(Object.entries(options.env).filter(([key]) => PIPELINE_ENV.test(key))),
|
|
14
|
+
headers: options.headers && Object.fromEntries(Object.entries(options.headers).filter(([key]) => !SESSION_HEADERS.has(key)))
|
|
15
|
+
};
|
|
16
|
+
const key = JSON.stringify(shared);
|
|
17
|
+
let entry = pipelines.get(key);
|
|
18
|
+
if (!entry) {
|
|
19
|
+
const created = {
|
|
20
|
+
handle: create(shared),
|
|
21
|
+
leases: 0
|
|
22
|
+
};
|
|
23
|
+
created.handle.catch(() => {
|
|
24
|
+
if (pipelines.get(key) === created) pipelines.delete(key);
|
|
25
|
+
});
|
|
26
|
+
pipelines.set(key, created);
|
|
27
|
+
entry = created;
|
|
28
|
+
}
|
|
29
|
+
const lease = entry;
|
|
30
|
+
lease.leases += 1;
|
|
31
|
+
let handle;
|
|
32
|
+
try {
|
|
33
|
+
handle = await lease.handle;
|
|
34
|
+
} catch (error) {
|
|
35
|
+
lease.leases -= 1;
|
|
36
|
+
throw error;
|
|
37
|
+
}
|
|
38
|
+
let released = false;
|
|
39
|
+
return {
|
|
40
|
+
...handle,
|
|
41
|
+
async shutdown() {
|
|
42
|
+
if (released) return;
|
|
43
|
+
released = true;
|
|
44
|
+
lease.leases -= 1;
|
|
45
|
+
if (lease.leases > 0) return;
|
|
46
|
+
if (pipelines.get(key) === lease) pipelines.delete(key);
|
|
47
|
+
await handle.shutdown();
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
}
|
|
4
52
|
async function loadNodeTelemetryRuntime() {
|
|
5
53
|
nodeTelemetryModule ??= import("@agimon-ai/po-logsink/telemetry/node");
|
|
6
54
|
const module = await nodeTelemetryModule;
|
|
7
55
|
return {
|
|
8
|
-
createNodeTelemetry: module.createNodeTelemetry,
|
|
56
|
+
createNodeTelemetry: shareNodeTelemetry(module.createNodeTelemetry),
|
|
9
57
|
resolveNodeTelemetryEndpoints: module.resolveNodeTelemetryEndpoints
|
|
10
58
|
};
|
|
11
59
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["createPoTelemetryService"],"sources":["../../../../src/services/poTelemetry/index.ts"],"sourcesContent":["import type { PoTelemetry, PoTelemetryOptions, PoTelemetryRuntime } from '../../types/telemetry';\nimport {\n createPoTelemetryService,\n createTelemetryHeaders,\n sanitizeTelemetryAttributes,\n subscribeTelemetryRecords,\n} from '../telemetry';\n\nexport type {\n PoTelemetry,\n PoTelemetryAttributes,\n PoTelemetryErrorOptions,\n PoTelemetryEventLevel,\n PoTelemetryOptions,\n PoTelemetryRecord,\n PoTelemetryStatus,\n PoTraceContext,\n} from '../../types/telemetry';\n\nlet nodeTelemetryModule: Promise<typeof import('@agimon-ai/po-logsink/telemetry/node')> | undefined;\n\nasync function loadNodeTelemetryRuntime(): Promise<PoTelemetryRuntime> {\n nodeTelemetryModule ??= import('@agimon-ai/po-logsink/telemetry/node');\n const module = await nodeTelemetryModule;\n return {\n createNodeTelemetry: module.createNodeTelemetry,\n resolveNodeTelemetryEndpoints: module.resolveNodeTelemetryEndpoints,\n };\n}\n\nexport function createPoTelemetry(options: PoTelemetryOptions): PoTelemetry {\n return createPoTelemetryService(options, loadNodeTelemetryRuntime);\n}\n\nexport { createTelemetryHeaders, sanitizeTelemetryAttributes, subscribeTelemetryRecords };\n"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["createPoTelemetryService"],"sources":["../../../../src/services/poTelemetry/index.ts"],"sourcesContent":["import type { NodeTelemetryHandle } from '@agimon-ai/po-logsink/telemetry/node';\n\nimport type { PoTelemetry, PoTelemetryOptions, PoTelemetryRuntime, TelemetryFactory } from '../../types/telemetry';\nimport {\n createPoTelemetryService,\n createTelemetryHeaders,\n sanitizeTelemetryAttributes,\n subscribeTelemetryRecords,\n} from '../telemetry';\n\nexport type {\n PoTelemetry,\n PoTelemetryAttributes,\n PoTelemetryErrorOptions,\n PoTelemetryEventLevel,\n PoTelemetryOptions,\n PoTelemetryRecord,\n PoTelemetryStatus,\n PoTraceContext,\n} from '../../types/telemetry';\n\nlet nodeTelemetryModule: Promise<typeof import('@agimon-ai/po-logsink/telemetry/node')> | undefined;\n\n// Records carry the session (`agent.session.id`), so the exporter only depends on these.\nconst SESSION_HEADERS = new Set(['x-agent-session-id', 'x-agent-parent-session-id']);\nconst PIPELINE_ENV = /^(?:OTEL_|LOG_SINK_)|^npm_package_version$/u;\nconst pipelines = new Map<string, { handle: Promise<NodeTelemetryHandle>; leases: number }>();\n\n/** One exporter pipeline per service and endpoint for the whole process; the last shutdown frees it. */\nfunction shareNodeTelemetry(create: TelemetryFactory): TelemetryFactory {\n return async (options) => {\n const shared = {\n ...options,\n cwd: options.resolvedEndpoints ? undefined : options.cwd,\n env: options.env && Object.fromEntries(Object.entries(options.env).filter(([key]) => PIPELINE_ENV.test(key))),\n headers:\n options.headers &&\n Object.fromEntries(Object.entries(options.headers).filter(([key]) => !SESSION_HEADERS.has(key))),\n };\n const key = JSON.stringify(shared);\n let entry = pipelines.get(key);\n if (!entry) {\n const created = { handle: create(shared), leases: 0 };\n created.handle.catch(() => {\n if (pipelines.get(key) === created) pipelines.delete(key);\n });\n pipelines.set(key, created);\n entry = created;\n }\n const lease = entry;\n lease.leases += 1;\n let handle: NodeTelemetryHandle;\n try {\n handle = await lease.handle;\n } catch (error) {\n lease.leases -= 1;\n throw error;\n }\n let released = false;\n return {\n ...handle,\n async shutdown() {\n if (released) return;\n released = true;\n lease.leases -= 1;\n if (lease.leases > 0) return;\n if (pipelines.get(key) === lease) pipelines.delete(key);\n await handle.shutdown();\n },\n };\n };\n}\n\nasync function loadNodeTelemetryRuntime(): Promise<PoTelemetryRuntime> {\n nodeTelemetryModule ??= import('@agimon-ai/po-logsink/telemetry/node');\n const module = await nodeTelemetryModule;\n return {\n createNodeTelemetry: shareNodeTelemetry(module.createNodeTelemetry),\n resolveNodeTelemetryEndpoints: module.resolveNodeTelemetryEndpoints,\n };\n}\n\nexport function createPoTelemetry(options: PoTelemetryOptions): PoTelemetry {\n return createPoTelemetryService(options, loadNodeTelemetryRuntime);\n}\n\nexport { createTelemetryHeaders, sanitizeTelemetryAttributes, subscribeTelemetryRecords };\n"],"mappings":";;AAqBA,IAAI;AAGJ,MAAM,kCAAkB,IAAI,IAAI,CAAC,sBAAsB,2BAA2B,CAAC;AACnF,MAAM,eAAe;AACrB,MAAM,4BAAY,IAAI,IAAsE;;AAG5F,SAAS,mBAAmB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,cAAAA,yBAAyB,SAAS,wBAAwB;AACnE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../../src/services/poTelemetry/index.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../../src/services/poTelemetry/index.ts"],"mappings":";;;wBAkFgB,kBAAkB,SAAS,qBAAqB"}
|
|
@@ -1,11 +1,59 @@
|
|
|
1
1
|
import { createPoTelemetryService, createTelemetryHeaders, sanitizeTelemetryAttributes, subscribeTelemetryRecords } from "../telemetry/index.mjs";
|
|
2
2
|
//#region src/services/poTelemetry/index.ts
|
|
3
3
|
let nodeTelemetryModule;
|
|
4
|
+
const SESSION_HEADERS = /* @__PURE__ */ new Set(["x-agent-session-id", "x-agent-parent-session-id"]);
|
|
5
|
+
const PIPELINE_ENV = /^(?:OTEL_|LOG_SINK_)|^npm_package_version$/u;
|
|
6
|
+
const pipelines = /* @__PURE__ */ new Map();
|
|
7
|
+
/** One exporter pipeline per service and endpoint for the whole process; the last shutdown frees it. */
|
|
8
|
+
function shareNodeTelemetry(create) {
|
|
9
|
+
return async (options) => {
|
|
10
|
+
const shared = {
|
|
11
|
+
...options,
|
|
12
|
+
cwd: options.resolvedEndpoints ? void 0 : options.cwd,
|
|
13
|
+
env: options.env && Object.fromEntries(Object.entries(options.env).filter(([key]) => PIPELINE_ENV.test(key))),
|
|
14
|
+
headers: options.headers && Object.fromEntries(Object.entries(options.headers).filter(([key]) => !SESSION_HEADERS.has(key)))
|
|
15
|
+
};
|
|
16
|
+
const key = JSON.stringify(shared);
|
|
17
|
+
let entry = pipelines.get(key);
|
|
18
|
+
if (!entry) {
|
|
19
|
+
const created = {
|
|
20
|
+
handle: create(shared),
|
|
21
|
+
leases: 0
|
|
22
|
+
};
|
|
23
|
+
created.handle.catch(() => {
|
|
24
|
+
if (pipelines.get(key) === created) pipelines.delete(key);
|
|
25
|
+
});
|
|
26
|
+
pipelines.set(key, created);
|
|
27
|
+
entry = created;
|
|
28
|
+
}
|
|
29
|
+
const lease = entry;
|
|
30
|
+
lease.leases += 1;
|
|
31
|
+
let handle;
|
|
32
|
+
try {
|
|
33
|
+
handle = await lease.handle;
|
|
34
|
+
} catch (error) {
|
|
35
|
+
lease.leases -= 1;
|
|
36
|
+
throw error;
|
|
37
|
+
}
|
|
38
|
+
let released = false;
|
|
39
|
+
return {
|
|
40
|
+
...handle,
|
|
41
|
+
async shutdown() {
|
|
42
|
+
if (released) return;
|
|
43
|
+
released = true;
|
|
44
|
+
lease.leases -= 1;
|
|
45
|
+
if (lease.leases > 0) return;
|
|
46
|
+
if (pipelines.get(key) === lease) pipelines.delete(key);
|
|
47
|
+
await handle.shutdown();
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
}
|
|
4
52
|
async function loadNodeTelemetryRuntime() {
|
|
5
53
|
nodeTelemetryModule ??= import("@agimon-ai/po-logsink/telemetry/node");
|
|
6
54
|
const module = await nodeTelemetryModule;
|
|
7
55
|
return {
|
|
8
|
-
createNodeTelemetry: module.createNodeTelemetry,
|
|
56
|
+
createNodeTelemetry: shareNodeTelemetry(module.createNodeTelemetry),
|
|
9
57
|
resolveNodeTelemetryEndpoints: module.resolveNodeTelemetryEndpoints
|
|
10
58
|
};
|
|
11
59
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../src/services/poTelemetry/index.ts"],"sourcesContent":["import type { PoTelemetry, PoTelemetryOptions, PoTelemetryRuntime } from '../../types/telemetry';\nimport {\n createPoTelemetryService,\n createTelemetryHeaders,\n sanitizeTelemetryAttributes,\n subscribeTelemetryRecords,\n} from '../telemetry';\n\nexport type {\n PoTelemetry,\n PoTelemetryAttributes,\n PoTelemetryErrorOptions,\n PoTelemetryEventLevel,\n PoTelemetryOptions,\n PoTelemetryRecord,\n PoTelemetryStatus,\n PoTraceContext,\n} from '../../types/telemetry';\n\nlet nodeTelemetryModule: Promise<typeof import('@agimon-ai/po-logsink/telemetry/node')> | undefined;\n\nasync function loadNodeTelemetryRuntime(): Promise<PoTelemetryRuntime> {\n nodeTelemetryModule ??= import('@agimon-ai/po-logsink/telemetry/node');\n const module = await nodeTelemetryModule;\n return {\n createNodeTelemetry: module.createNodeTelemetry,\n resolveNodeTelemetryEndpoints: module.resolveNodeTelemetryEndpoints,\n };\n}\n\nexport function createPoTelemetry(options: PoTelemetryOptions): PoTelemetry {\n return createPoTelemetryService(options, loadNodeTelemetryRuntime);\n}\n\nexport { createTelemetryHeaders, sanitizeTelemetryAttributes, subscribeTelemetryRecords };\n"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../src/services/poTelemetry/index.ts"],"sourcesContent":["import type { NodeTelemetryHandle } from '@agimon-ai/po-logsink/telemetry/node';\n\nimport type { PoTelemetry, PoTelemetryOptions, PoTelemetryRuntime, TelemetryFactory } from '../../types/telemetry';\nimport {\n createPoTelemetryService,\n createTelemetryHeaders,\n sanitizeTelemetryAttributes,\n subscribeTelemetryRecords,\n} from '../telemetry';\n\nexport type {\n PoTelemetry,\n PoTelemetryAttributes,\n PoTelemetryErrorOptions,\n PoTelemetryEventLevel,\n PoTelemetryOptions,\n PoTelemetryRecord,\n PoTelemetryStatus,\n PoTraceContext,\n} from '../../types/telemetry';\n\nlet nodeTelemetryModule: Promise<typeof import('@agimon-ai/po-logsink/telemetry/node')> | undefined;\n\n// Records carry the session (`agent.session.id`), so the exporter only depends on these.\nconst SESSION_HEADERS = new Set(['x-agent-session-id', 'x-agent-parent-session-id']);\nconst PIPELINE_ENV = /^(?:OTEL_|LOG_SINK_)|^npm_package_version$/u;\nconst pipelines = new Map<string, { handle: Promise<NodeTelemetryHandle>; leases: number }>();\n\n/** One exporter pipeline per service and endpoint for the whole process; the last shutdown frees it. */\nfunction shareNodeTelemetry(create: TelemetryFactory): TelemetryFactory {\n return async (options) => {\n const shared = {\n ...options,\n cwd: options.resolvedEndpoints ? undefined : options.cwd,\n env: options.env && Object.fromEntries(Object.entries(options.env).filter(([key]) => PIPELINE_ENV.test(key))),\n headers:\n options.headers &&\n Object.fromEntries(Object.entries(options.headers).filter(([key]) => !SESSION_HEADERS.has(key))),\n };\n const key = JSON.stringify(shared);\n let entry = pipelines.get(key);\n if (!entry) {\n const created = { handle: create(shared), leases: 0 };\n created.handle.catch(() => {\n if (pipelines.get(key) === created) pipelines.delete(key);\n });\n pipelines.set(key, created);\n entry = created;\n }\n const lease = entry;\n lease.leases += 1;\n let handle: NodeTelemetryHandle;\n try {\n handle = await lease.handle;\n } catch (error) {\n lease.leases -= 1;\n throw error;\n }\n let released = false;\n return {\n ...handle,\n async shutdown() {\n if (released) return;\n released = true;\n lease.leases -= 1;\n if (lease.leases > 0) return;\n if (pipelines.get(key) === lease) pipelines.delete(key);\n await handle.shutdown();\n },\n };\n };\n}\n\nasync function loadNodeTelemetryRuntime(): Promise<PoTelemetryRuntime> {\n nodeTelemetryModule ??= import('@agimon-ai/po-logsink/telemetry/node');\n const module = await nodeTelemetryModule;\n return {\n createNodeTelemetry: shareNodeTelemetry(module.createNodeTelemetry),\n resolveNodeTelemetryEndpoints: module.resolveNodeTelemetryEndpoints,\n };\n}\n\nexport function createPoTelemetry(options: PoTelemetryOptions): PoTelemetry {\n return createPoTelemetryService(options, loadNodeTelemetryRuntime);\n}\n\nexport { createTelemetryHeaders, sanitizeTelemetryAttributes, subscribeTelemetryRecords };\n"],"mappings":";;AAqBA,IAAI;AAGJ,MAAM,kCAAkB,IAAI,IAAI,CAAC,sBAAsB,2BAA2B,CAAC;AACnF,MAAM,eAAe;AACrB,MAAM,4BAAY,IAAI,IAAsE;;AAG5F,SAAS,mBAAmB,QAA4C;CACtE,OAAO,OAAO,YAAY;EACxB,MAAM,SAAS;GACb,GAAG;GACH,KAAK,QAAQ,oBAAoB,KAAA,IAAY,QAAQ;GACrD,KAAK,QAAQ,OAAO,OAAO,YAAY,OAAO,QAAQ,QAAQ,GAAG,CAAC,CAAC,QAAQ,CAAC,SAAS,aAAa,KAAK,GAAG,CAAC,CAAC;GAC5G,SACE,QAAQ,WACR,OAAO,YAAY,OAAO,QAAQ,QAAQ,OAAO,CAAC,CAAC,QAAQ,CAAC,SAAS,CAAC,gBAAgB,IAAI,GAAG,CAAC,CAAC;EACnG;EACA,MAAM,MAAM,KAAK,UAAU,MAAM;EACjC,IAAI,QAAQ,UAAU,IAAI,GAAG;EAC7B,IAAI,CAAC,OAAO;GACV,MAAM,UAAU;IAAE,QAAQ,OAAO,MAAM;IAAG,QAAQ;GAAE;GACpD,QAAQ,OAAO,YAAY;IACzB,IAAI,UAAU,IAAI,GAAG,MAAM,SAAS,UAAU,OAAO,GAAG;GAC1D,CAAC;GACD,UAAU,IAAI,KAAK,OAAO;GAC1B,QAAQ;EACV;EACA,MAAM,QAAQ;EACd,MAAM,UAAU;EAChB,IAAI;EACJ,IAAI;GACF,SAAS,MAAM,MAAM;EACvB,SAAS,OAAO;GACd,MAAM,UAAU;GAChB,MAAM;EACR;EACA,IAAI,WAAW;EACf,OAAO;GACL,GAAG;GACH,MAAM,WAAW;IACf,IAAI,UAAU;IACd,WAAW;IACX,MAAM,UAAU;IAChB,IAAI,MAAM,SAAS,GAAG;IACtB,IAAI,UAAU,IAAI,GAAG,MAAM,OAAO,UAAU,OAAO,GAAG;IACtD,MAAM,OAAO,SAAS;GACxB;EACF;CACF;AACF;AAEA,eAAe,2BAAwD;CACrE,wBAAwB,OAAO;CAC/B,MAAM,SAAS,MAAM;CACrB,OAAO;EACL,qBAAqB,mBAAmB,OAAO,mBAAmB;EAClE,+BAA+B,OAAO;CACxC;AACF;AAEA,SAAgB,kBAAkB,SAA0C;CAC1E,OAAO,yBAAyB,SAAS,wBAAwB;AACnE"}
|
|
@@ -269,6 +269,15 @@ function createTelemetryHeaders(serviceName, env) {
|
|
|
269
269
|
if (parentSessionId) headers["x-agent-parent-session-id"] = hashIdentifier(parentSessionId);
|
|
270
270
|
return headers;
|
|
271
271
|
}
|
|
272
|
+
/** The session on every exported record lets the Node runtime share one exporter per service. */
|
|
273
|
+
function sessionAttributes(env) {
|
|
274
|
+
const attributes = {};
|
|
275
|
+
const sessionId = firstEnvironmentValue(env, SESSION_ID_HEADERS);
|
|
276
|
+
const parentSessionId = firstEnvironmentValue(env, PARENT_SESSION_ID_HEADERS);
|
|
277
|
+
if (sessionId) attributes["agent.session.id"] = hashIdentifier(sessionId);
|
|
278
|
+
if (parentSessionId) attributes["agent.parent_session.id"] = hashIdentifier(parentSessionId);
|
|
279
|
+
return attributes;
|
|
280
|
+
}
|
|
272
281
|
function createTransportEnvironment(env) {
|
|
273
282
|
const transportEnv = { ...env };
|
|
274
283
|
const sessionId = firstEnvironmentValue(env, SESSION_ID_HEADERS);
|
|
@@ -322,6 +331,7 @@ function createPoTelemetryService(options, runtimeLoader) {
|
|
|
322
331
|
const telemetryFactory = options.telemetryFactory;
|
|
323
332
|
const endpointResolver = options.endpointResolver;
|
|
324
333
|
const transportEnv = createTransportEnvironment(env);
|
|
334
|
+
const session = sessionAttributes(env);
|
|
325
335
|
const warn = options.warn ?? ((message) => console.warn(message));
|
|
326
336
|
const reportWarning = (message) => {
|
|
327
337
|
try {
|
|
@@ -463,7 +473,10 @@ function createPoTelemetryService(options, runtimeLoader) {
|
|
|
463
473
|
});
|
|
464
474
|
try {
|
|
465
475
|
(await getHandle())?.logger[level](safeEvent, {
|
|
466
|
-
attributes:
|
|
476
|
+
attributes: {
|
|
477
|
+
...session,
|
|
478
|
+
...safeAttributes
|
|
479
|
+
},
|
|
467
480
|
...errorOptions?.includeException === true && error !== void 0 ? { exception: error } : {}
|
|
468
481
|
});
|
|
469
482
|
} catch (failure) {
|
|
@@ -505,7 +518,10 @@ function createPoTelemetryService(options, runtimeLoader) {
|
|
|
505
518
|
try {
|
|
506
519
|
const nextParentContext = parentContext(parent);
|
|
507
520
|
const result = await nextHandle.runInSpan(normalizeToken(name, "po.telemetry.span"), {
|
|
508
|
-
attributes:
|
|
521
|
+
attributes: {
|
|
522
|
+
...session,
|
|
523
|
+
...sanitizeTelemetryAttributes(attributes)
|
|
524
|
+
},
|
|
509
525
|
...nextParentContext ? { context: nextParentContext } : {}
|
|
510
526
|
}, async (span) => {
|
|
511
527
|
const child = childTraceContext(span);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["isSpanContextValid","trace","context"],"sources":["../../../../src/services/telemetry/index.ts"],"sourcesContent":["import { context, isSpanContextValid, trace, type Context, type Span } from '@opentelemetry/api';\n\nimport type {\n PoTelemetry,\n PoTelemetryAttributes,\n PoTelemetryErrorOptions,\n PoTelemetryEventLevel,\n PoTelemetryHandle,\n PoTelemetryOptions,\n PoTelemetryRecord,\n PoTelemetryRuntimeLoader,\n PoTelemetryStatus,\n PoTraceContext,\n} from '../../types/telemetry';\n\n/** Only the operation owning an aborted signal may classify its rejection as cancellation. */\nexport class OperationCancelledError extends Error {\n constructor(options?: ErrorOptions) {\n super('The operation was cancelled', options);\n this.name = 'OperationCancelledError';\n }\n}\n\nconst DEFAULT_RETRY_DELAY_MS = 1_000;\n// A wedged collector `/health` must not hold every span and event behind it.\nconst ENDPOINT_DISCOVERY_TIMEOUT_MS = 2_000;\nconst MAX_WARNING_DETAIL_LENGTH = 512;\nconst MAX_WARNING_DETAIL_DEPTH = 3;\nconst MAX_ATTRIBUTE_STRING_LENGTH = 128;\nconst MAX_REPORTED_FAILURES = 500;\nconst MAX_EVENT_NAME_LENGTH = 128;\nconst SESSION_ID_HEADERS = ['AGENT_SESSION_ID', 'PI_SESSION_ID'] as const;\nconst PARENT_SESSION_ID_HEADERS = ['AGENT_PARENT_SESSION_ID', 'PARENT_AGENT_SESSION_ID'] as const;\nconst TRANSPORT_SESSION_HEADERS = ['PI_SESSION_ID', 'AGENT_PARENT_SESSION_ID'] as const;\nconst TRUE_VALUES = new Set(['1', 'true', 'yes']);\nconst SPAN_STATUS_ERROR = 2;\nconst TRACEPARENT_PATTERN = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/u;\nconst SENSITIVE_ATTRIBUTE_PARTS = [\n 'prompt',\n 'message',\n 'content',\n 'payload',\n 'command',\n 'cwd',\n 'path',\n 'file',\n 'stack',\n 'traceback',\n 'transcript',\n 'diff',\n 'secret',\n 'authorization',\n 'header',\n 'environment',\n 'env',\n 'details',\n 'args',\n] as const;\nconst SAFE_RESULT_KEYS = new Set([\n 'tool.result.error',\n 'tool.result.count',\n 'tool.result.bytes',\n 'tool.result.duration_ms',\n]);\nconst SAFE_METADATA_KEY_PARTS = new Set([\n 'count',\n 'length',\n 'bytes',\n 'duration',\n 'duration_ms',\n 'size',\n 'index',\n 'number',\n 'active',\n 'enabled',\n 'previous',\n 'empty',\n 'silent',\n 'fallback',\n 'bypass',\n 'success',\n 'is_error',\n 'has_ui',\n 'requires_confirmation',\n 'exit_code',\n 'status_code',\n 'interval_seconds',\n 'concurrency',\n 'budget',\n]);\nconst SAFE_INPUT_KEYS = new Set([\n 'gen_ai.usage.input_tokens',\n 'gen_ai.usage.output_tokens',\n 'gen_ai.usage.total_tokens',\n 'gen_ai.usage.cache_read_tokens',\n 'gen_ai.usage.cache_write_tokens',\n 'gen_ai.usage.reasoning_tokens',\n]);\nconst SAFE_IDENTIFIER_KEY_PARTS = [\n 'id',\n 'correlation',\n 'session',\n 'trace',\n 'span',\n 'call',\n 'run',\n 'job',\n 'step',\n] as const;\nconst SAFE_STRING_KEY_PARTS = [\n 'name',\n 'operation',\n 'outcome',\n 'reason',\n 'status',\n 'mode',\n 'source',\n 'phase',\n 'engine',\n 'provider',\n 'model',\n 'level',\n 'type',\n 'code',\n 'signal',\n 'finish_reasons',\n 'trigger',\n 'action',\n 'kind',\n 'version',\n 'scope',\n 'layer',\n 'profile',\n 'domain',\n 'theme',\n 'leader',\n 'pass',\n 'role',\n 'stage',\n 'state',\n 'language',\n 'transport',\n 'adapter',\n 'runtime',\n 'backend',\n 'launcher',\n 'event',\n 'component',\n 'package',\n 'command_name',\n 'tool_name',\n 'token_attribution',\n] as const;\n\nconst recordObservers = new Set<(record: PoTelemetryRecord) => void>();\n\nexport function subscribeTelemetryRecords(observer: (record: PoTelemetryRecord) => void): () => void {\n recordObservers.add(observer);\n return () => recordObservers.delete(observer);\n}\n\nfunction isTruthy(value: string | undefined): boolean {\n return value !== undefined && TRUE_VALUES.has(value.toLowerCase());\n}\n\nfunction normalizeToken(value: string, fallback: string): string {\n const normalized = value.replace(/[^a-zA-Z0-9._:-]/g, '_').slice(0, MAX_ATTRIBUTE_STRING_LENGTH);\n return normalized || fallback;\n}\n\nfunction hashIdentifier(value: string): string {\n let hash = 2166136261;\n for (let index = 0; index < value.length; index += 1) {\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, 16777619);\n }\n return `id_${(hash >>> 0).toString(16).padStart(8, '0')}`;\n}\n\nfunction isSafeMetadataKey(key: string): boolean {\n const normalized = key.toLowerCase();\n return [...SAFE_METADATA_KEY_PARTS].some(\n (part) => normalized === part || normalized.endsWith(`.${part}`) || normalized.endsWith(`_${part}`),\n );\n}\n\nfunction isSensitiveKey(key: string): boolean {\n const normalized = key.toLowerCase();\n if (SAFE_RESULT_KEYS.has(normalized) || SAFE_INPUT_KEYS.has(normalized) || isSafeMetadataKey(normalized))\n return false;\n return SENSITIVE_ATTRIBUTE_PARTS.some((part) => normalized.split(/[._-]/u).includes(part));\n}\n\nfunction hasSafeStringMeaning(key: string): boolean {\n const normalized = key.toLowerCase();\n return SAFE_STRING_KEY_PARTS.some(\n (part) => normalized === part || normalized.endsWith(`.${part}`) || normalized.endsWith(`_${part}`),\n );\n}\n\nfunction hasSafeIdentifierMeaning(key: string): boolean {\n const normalized = key.toLowerCase();\n return SAFE_IDENTIFIER_KEY_PARTS.some(\n (part) => normalized === part || normalized.endsWith(`.${part}`) || normalized.endsWith(`_${part}`),\n );\n}\n\nfunction isScalar(value: unknown): value is string | number | boolean {\n return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean';\n}\n\nfunction sanitizeValue(key: string, value: string | number | boolean): string | number | boolean | undefined {\n if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;\n if (typeof value === 'boolean') return value;\n if (value.length === 0 || value.length > MAX_ATTRIBUTE_STRING_LENGTH) return undefined;\n if (hasSafeIdentifierMeaning(key)) return hashIdentifier(value);\n if (!hasSafeStringMeaning(key)) return undefined;\n if (key === 'telemetry.package' || key.endsWith('.package')) {\n if (value.startsWith('/') || value.includes('\\\\')) return undefined;\n return value.replace(/[^a-zA-Z0-9@/._:-]/g, '_');\n }\n return normalizeToken(value, 'unknown');\n}\n\nexport function sanitizeTelemetryAttributes(attributes: Record<string, unknown> = {}): PoTelemetryAttributes {\n const sanitized: PoTelemetryAttributes = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (isSensitiveKey(key) || !isScalar(value)) continue;\n const safeValue = sanitizeValue(key, value);\n if (safeValue !== undefined) sanitized[key] = safeValue;\n }\n return sanitized;\n}\n\nfunction safeErrorToken(value: string, fallback: string): string {\n if (!/^[a-zA-Z][a-zA-Z0-9._:-]{0,63}$/u.test(value)) return fallback;\n return normalizeToken(value, fallback);\n}\n\nfunction errorType(error: unknown): string {\n // A subclass that keeps the default name still exports its class, never its message.\n if (error instanceof Error)\n return safeErrorToken(error.name === 'Error' ? error.constructor.name : error.name, 'Error');\n if (typeof error === 'string') return 'StringError';\n if (error && typeof error === 'object') return 'ObjectError';\n return 'UnknownError';\n}\n\n/**\n * Format an error for a local diagnostic warning.\n *\n * Deliberately separate from errorType: that produces a redacted token for the\n * exported `error.type` attribute and must stay metadata-only, whereas warnings\n * go to the local operator and are useless without the actual cause. Arrays are\n * unwrapped because OpenTelemetry's forceFlush rejects with one.\n */\nfunction describeError(error: unknown, depth = 0): string {\n if (depth > MAX_WARNING_DETAIL_DEPTH) return '...';\n if (Array.isArray(error)) return error.map((entry) => describeError(entry, depth + 1)).join('; ');\n if (error instanceof Error) {\n const rawCode = 'code' in error ? (error as { code?: unknown }).code : undefined;\n const code = typeof rawCode === 'string' || typeof rawCode === 'number' ? ` (code ${rawCode})` : '';\n const aggregate = error instanceof AggregateError ? `: ${describeError(error.errors, depth + 1)}` : '';\n const cause = error.cause === undefined ? '' : ` <- caused by ${describeError(error.cause, depth + 1)}`;\n return `${error.name}: ${error.message}${code}${aggregate}${cause}`;\n }\n if (typeof error === 'string') return error;\n if (error && typeof error === 'object') {\n try {\n return JSON.stringify(error);\n } catch {\n return 'ObjectError';\n }\n }\n return String(error);\n}\n\nfunction warningDetail(error: unknown): string {\n return describeError(error).slice(0, MAX_WARNING_DETAIL_LENGTH);\n}\n\nfunction errorCode(error: unknown): string | undefined {\n if (!error || typeof error !== 'object' || !('code' in error)) return undefined;\n const code = (error as { code?: unknown }).code;\n if (typeof code !== 'string' && typeof code !== 'number') return undefined;\n const normalized = String(code);\n return /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,63}$/u.test(normalized) ? normalizeToken(normalized, 'unknown') : undefined;\n}\n\nfunction errorAttributes(error: unknown): PoTelemetryAttributes {\n const attributes: PoTelemetryAttributes = {\n 'error.type': errorType(error),\n outcome: 'error',\n };\n const code = errorCode(error);\n if (code) attributes['error.code'] = code;\n return attributes;\n}\n\nfunction firstEnvironmentValue(env: NodeJS.ProcessEnv, keys: readonly string[]): string | undefined {\n for (const key of keys) {\n const value = env[key]?.trim();\n if (value) return value;\n }\n return undefined;\n}\n\nexport function createTelemetryHeaders(serviceName: string, env: NodeJS.ProcessEnv): Record<string, string> {\n const headers: Record<string, string> = { 'x-agent': normalizeToken(serviceName, 'po') };\n const sessionId = firstEnvironmentValue(env, SESSION_ID_HEADERS);\n const parentSessionId = firstEnvironmentValue(env, PARENT_SESSION_ID_HEADERS);\n if (sessionId) headers['x-agent-session-id'] = hashIdentifier(sessionId);\n if (parentSessionId) headers['x-agent-parent-session-id'] = hashIdentifier(parentSessionId);\n return headers;\n}\n\nfunction createTransportEnvironment(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const transportEnv = { ...env };\n const sessionId = firstEnvironmentValue(env, SESSION_ID_HEADERS);\n const parentSessionId = firstEnvironmentValue(env, PARENT_SESSION_ID_HEADERS);\n if (sessionId) transportEnv.AGENT_SESSION_ID = hashIdentifier(sessionId);\n else delete transportEnv.AGENT_SESSION_ID;\n if (parentSessionId) transportEnv.PARENT_AGENT_SESSION_ID = hashIdentifier(parentSessionId);\n else delete transportEnv.PARENT_AGENT_SESSION_ID;\n for (const key of TRANSPORT_SESSION_HEADERS) delete transportEnv[key];\n for (const key of Object.keys(transportEnv)) {\n if (key.startsWith('WORKFLOW_')) delete transportEnv[key];\n }\n return transportEnv;\n}\n\nfunction defaultStatus(options: PoTelemetryOptions): PoTelemetryStatus {\n return {\n serviceName: options.serviceName,\n packageName: options.packageName,\n backend: 'disabled',\n enabled: false,\n endpointSource: 'none',\n traces: false,\n fileFallback: false,\n };\n}\n\nfunction createSafeCallbackError(error: unknown): Error {\n const code = errorCode(error);\n return new Error(`Po telemetry callback failed: ${errorType(error)}${code ? ` (${code})` : ''}`);\n}\n\nfunction parentContext(parent: PoTraceContext | undefined): Context | undefined {\n if (!parent) return undefined;\n const match = TRACEPARENT_PATTERN.exec(parent.traceparent);\n if (!match) return undefined;\n const [, traceId, spanId, traceFlags] = match;\n if (!traceId || !spanId || !traceFlags) return undefined;\n const spanContext = { traceId, spanId, traceFlags: Number.parseInt(traceFlags, 16), isRemote: true };\n return isSpanContextValid(spanContext) ? trace.setSpanContext(context.active(), spanContext) : undefined;\n}\n\nfunction childTraceContext(span: Span | undefined): PoTraceContext | undefined {\n if (!span) return undefined;\n const spanContext = span.spanContext();\n if (!isSpanContextValid(spanContext)) return undefined;\n const traceFlags = spanContext.traceFlags.toString(16).padStart(2, '0');\n return { traceparent: `00-${spanContext.traceId}-${spanContext.spanId}-${traceFlags}` };\n}\nexport function createPoTelemetryService(\n options: PoTelemetryOptions,\n runtimeLoader?: PoTelemetryRuntimeLoader,\n): PoTelemetry {\n const env = { ...options.env };\n const telemetryFactory = options.telemetryFactory;\n const endpointResolver = options.endpointResolver;\n const transportEnv = createTransportEnvironment(env);\n const warn = options.warn ?? ((message: string) => console.warn(message));\n const reportWarning = (message: string): void => {\n try {\n warn(message);\n } catch (error) {\n console.warn(`Po telemetry warning callback failed: ${warningDetail(error)}`);\n }\n };\n const retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;\n const allowFileFallback = options.allowFileFallback ?? isTruthy(env.LOG_SINK_PI_FILE_FALLBACK);\n const defaultTelemetryStatus = defaultStatus(options);\n let currentStatus = defaultTelemetryStatus;\n let handle: PoTelemetryHandle | undefined;\n let initialization: Promise<PoTelemetryHandle | undefined> | undefined;\n let retryAfter = 0;\n let discoveryFailureReported = false;\n const reportDiscoveryFailure = (message: string): void => {\n if (!discoveryFailureReported) reportWarning(message);\n discoveryFailureReported = true;\n };\n let shutdownPromise: Promise<void> | undefined;\n let shutdownRequested = false;\n const reportedFailures = new Set<string>();\n\n const disabledByEnvironment = (): boolean =>\n isTruthy(env.AGENT_TELEMETRY_DISABLED) || isTruthy(env.OTEL_SDK_DISABLED);\n\n const publish = (record: PoTelemetryRecord): void => {\n for (const observer of [...recordObservers, ...(options.onRecord ? [options.onRecord] : [])]) {\n try {\n observer(record);\n } catch (error) {\n reportWarning(`Po telemetry observer failed: ${warningDetail(error)}`);\n }\n }\n };\n\n const initialize = async (): Promise<PoTelemetryHandle | undefined> => {\n if (disabledByEnvironment() || shutdownRequested) return undefined;\n const defaults = telemetryFactory ? undefined : await runtimeLoader?.();\n const resolveEndpoints = endpointResolver ?? defaults?.resolveNodeTelemetryEndpoints;\n const createTelemetry = telemetryFactory ?? defaults?.createNodeTelemetry;\n if ((!resolveEndpoints && !telemetryFactory) || !createTelemetry)\n throw new Error('Node telemetry runtime is unavailable.');\n let discoveryTimer: ReturnType<typeof setTimeout> | undefined;\n const discoveryTimedOut = Symbol('discoveryTimedOut');\n const resolvedEndpoints =\n resolveEndpoints === undefined\n ? undefined\n : await Promise.race([\n resolveEndpoints({\n cwd: options.cwd,\n env,\n packageName: options.packageName,\n serviceName: options.serviceName,\n workspaceRoot: options.workspaceRoot,\n discoverEndpoint: true,\n healthCheck: true,\n }),\n new Promise<typeof discoveryTimedOut>((resolve) => {\n discoveryTimer = setTimeout(() => resolve(discoveryTimedOut), ENDPOINT_DISCOVERY_TIMEOUT_MS);\n }),\n ]).finally(() => clearTimeout(discoveryTimer));\n if (resolvedEndpoints === discoveryTimedOut) {\n reportDiscoveryFailure(\n `Po telemetry endpoint discovery timed out after ${ENDPOINT_DISCOVERY_TIMEOUT_MS} ms; retrying`,\n );\n retryAfter = Date.now() + retryDelayMs;\n currentStatus = { ...defaultTelemetryStatus };\n return undefined;\n }\n const endpoints = resolvedEndpoints ?? { endpointSource: 'env' as const, endpoint: 'injected' };\n if (!endpoints.endpoint && !endpoints.tracesEndpoint && !endpoints.logsEndpoint && !allowFileFallback) {\n retryAfter = Date.now() + retryDelayMs;\n currentStatus = { ...defaultTelemetryStatus };\n return undefined;\n }\n const nextHandle = await createTelemetry({\n serviceName: options.serviceName,\n packageName: options.packageName,\n cwd: options.cwd,\n workspaceRoot: options.workspaceRoot,\n env: transportEnv,\n discoverEndpoint: resolvedEndpoints === undefined,\n resolvedEndpoints,\n enableLogs: options.enableLogs ?? true,\n enableTraces: options.enableTraces ?? true,\n headers: createTelemetryHeaders(options.serviceName, env),\n });\n if (shutdownRequested) {\n await nextHandle.shutdown().catch((error: unknown) => {\n reportWarning(`Po telemetry late initialization shutdown failed: ${warningDetail(error)}`);\n });\n return undefined;\n }\n if (nextHandle.backend === 'file' && !allowFileFallback) {\n await nextHandle\n .shutdown()\n .catch((error: unknown) => reportWarning(`Po telemetry fallback shutdown failed: ${warningDetail(error)}`));\n retryAfter = Date.now() + retryDelayMs;\n currentStatus = { ...defaultTelemetryStatus };\n return undefined;\n }\n if (discoveryFailureReported) reportWarning('Po telemetry endpoint discovery recovered');\n discoveryFailureReported = false;\n handle = nextHandle;\n currentStatus = {\n serviceName: options.serviceName,\n packageName: options.packageName,\n backend: nextHandle.backend,\n enabled: nextHandle.enabled,\n endpoint: nextHandle.endpoint,\n endpointSource: nextHandle.endpointSource,\n traces: Boolean(options.enableTraces ?? true),\n fileFallback: nextHandle.backend === 'file',\n };\n try {\n options.onStatus?.({ ...currentStatus });\n } catch (error) {\n reportWarning(`Po telemetry status observer failed: ${warningDetail(error)}`);\n }\n return nextHandle;\n };\n\n const getHandle = async (): Promise<PoTelemetryHandle | undefined> => {\n if (disabledByEnvironment() || shutdownRequested) return undefined;\n if (handle) return handle;\n if (Date.now() < retryAfter) return undefined;\n initialization ??= initialize()\n .catch((error: unknown) => {\n retryAfter = Date.now() + retryDelayMs;\n reportDiscoveryFailure(`Po telemetry initialization failed: ${warningDetail(error)}`);\n return undefined;\n })\n .finally(() => {\n initialization = undefined;\n });\n return initialization;\n };\n\n const emit = async (\n level: PoTelemetryEventLevel,\n event: string,\n error: unknown,\n attributes: Record<string, unknown> | undefined,\n errorOptions?: PoTelemetryErrorOptions,\n ): Promise<void> => {\n const safeEvent = normalizeToken(event, 'po.telemetry.event').slice(0, MAX_EVENT_NAME_LENGTH);\n const safeAttributes = sanitizeTelemetryAttributes({\n 'telemetry.package': options.packageName,\n ...attributes,\n ...(error === undefined ? {} : errorAttributes(error)),\n });\n if (error !== undefined) {\n const failureKey = `${safeEvent}:${level}:${JSON.stringify(safeAttributes)}`;\n if (reportedFailures.has(failureKey)) return;\n if (reportedFailures.size >= MAX_REPORTED_FAILURES) reportedFailures.clear();\n reportedFailures.add(failureKey);\n }\n const record: PoTelemetryRecord = { event: safeEvent, level, attributes: safeAttributes };\n publish(record);\n try {\n const nextHandle = await getHandle();\n nextHandle?.logger[level](safeEvent, {\n attributes: safeAttributes,\n ...(errorOptions?.includeException === true && error !== undefined ? { exception: error } : {}),\n });\n } catch (failure) {\n reportWarning(`Po telemetry record failed: ${warningDetail(failure)}`);\n }\n };\n\n const flush = async (): Promise<void> => {\n try {\n const pendingInitialization = initialization;\n if (pendingInitialization) await pendingInitialization;\n await handle?.flush();\n } catch (error) {\n reportWarning(`Po telemetry flush failed: ${warningDetail(error)}`);\n }\n };\n\n return {\n recordDebug(event, attributes) {\n return emit('debug', event, undefined, attributes);\n },\n recordEvent(event, attributes) {\n return emit('info', event, undefined, attributes);\n },\n recordWarning(event, error, attributes) {\n return emit('warn', event, error, attributes);\n },\n recordError(event, error, attributes, errorOptions) {\n return emit('error', event, error, attributes, errorOptions);\n },\n async runInSpan<T>(\n name: string,\n attributes: Record<string, unknown>,\n callback: (context?: PoTraceContext) => Promise<T> | T,\n parent?: PoTraceContext,\n ) {\n let callbackPromise: Promise<T> | undefined;\n let callbackFailure: { value: unknown } | undefined;\n const invokeCallback = (child?: PoTraceContext): Promise<T> => {\n callbackPromise ??= Promise.resolve().then(() => callback(child));\n return callbackPromise;\n };\n const nextHandle = await getHandle();\n if (!nextHandle) return invokeCallback();\n const startedAt = Date.now();\n try {\n const nextParentContext = parentContext(parent);\n const result = await nextHandle.runInSpan(\n normalizeToken(name, 'po.telemetry.span'),\n {\n attributes: sanitizeTelemetryAttributes(attributes),\n ...(nextParentContext ? { context: nextParentContext } : {}),\n },\n async (span) => {\n const child = childTraceContext(span);\n try {\n const result = await invokeCallback(child);\n span?.setAttribute('duration_ms', Date.now() - startedAt);\n span?.setAttribute('outcome', 'success');\n return result;\n } catch (error) {\n callbackFailure = { value: error };\n if (error instanceof OperationCancelledError) {\n span?.setAttribute('outcome', 'cancelled');\n span?.setAttribute('duration_ms', Date.now() - startedAt);\n // Do not throw through the exporter, which would create an error span.\n return undefined as T;\n }\n const safeError = errorAttributes(error);\n // The real cause stays in the local log; the exported span carries only its class and code.\n const detail = `Po telemetry span ${name} failed: ${warningDetail(error)}`;\n if (!reportedFailures.has(detail)) {\n if (reportedFailures.size >= MAX_REPORTED_FAILURES) reportedFailures.clear();\n reportedFailures.add(detail);\n reportWarning(detail);\n }\n for (const [key, value] of Object.entries(safeError)) span?.setAttribute(key, value);\n span?.setAttribute('duration_ms', Date.now() - startedAt);\n span?.setStatus({ code: SPAN_STATUS_ERROR });\n throw createSafeCallbackError(error);\n }\n },\n );\n if (callbackFailure) throw callbackFailure.value;\n return result;\n } catch (error) {\n if (callbackFailure) return Promise.reject(callbackFailure.value);\n if (callbackPromise) return callbackPromise;\n reportWarning(`Po telemetry span failed: ${warningDetail(error)}`);\n return invokeCallback();\n }\n },\n flush,\n async shutdown() {\n if (shutdownPromise) return shutdownPromise;\n shutdownRequested = true;\n shutdownPromise = (async () => {\n await flush();\n const currentHandle = handle;\n handle = undefined;\n if (!currentHandle) return;\n try {\n await currentHandle.shutdown();\n } catch (error) {\n reportWarning(`Po telemetry shutdown failed: ${warningDetail(error)}`);\n }\n })();\n return shutdownPromise;\n },\n status() {\n return { ...currentStatus };\n },\n };\n}\n"],"mappings":";;;AAgBA,IAAa,0BAAb,cAA6C,MAAM;CACjD,YAAY,SAAwB;EAClC,MAAM,+BAA+B,OAAO;EAC5C,KAAK,OAAO;CACd;AACF;AAEA,MAAM,yBAAyB;AAE/B,MAAM,gCAAgC;AACtC,MAAM,4BAA4B;AAClC,MAAM,2BAA2B;AACjC,MAAM,8BAA8B;AACpC,MAAM,wBAAwB;AAC9B,MAAM,wBAAwB;AAC9B,MAAM,qBAAqB,CAAC,oBAAoB,eAAe;AAC/D,MAAM,4BAA4B,CAAC,2BAA2B,yBAAyB;AACvF,MAAM,4BAA4B,CAAC,iBAAiB,yBAAyB;AAC7E,MAAM,8BAAc,IAAI,IAAI;CAAC;CAAK;CAAQ;AAAK,CAAC;AAChD,MAAM,oBAAoB;AAC1B,MAAM,sBAAsB;AAC5B,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,mCAAmB,IAAI,IAAI;CAC/B;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,0CAA0B,IAAI,IAAI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S,OAAO;IACd,IAAI,iBAAiB,OAAO,QAAQ,OAAO,gBAAgB,KAAK;IAChE,IAAI,iBAAiB,OAAO;IAC5B,cAAc,6BAA6B,cAAc,KAAK,GAAG;IACjE,OAAO,eAAe;GACxB;EACF;EACA;EACA,MAAM,WAAW;GACf,IAAI,iBAAiB,OAAO;GAC5B,oBAAoB;GACpB,mBAAmB,YAAY;IAC7B,MAAM,MAAM;IACZ,MAAM,gBAAgB;IACtB,SAAS,KAAA;IACT,IAAI,CAAC,eAAe;IACpB,IAAI;KACF,MAAM,cAAc,SAAS;IAC/B,SAAS,OAAO;KACd,cAAc,iCAAiC,cAAc,KAAK,GAAG;IACvE;GACF,EAAA,CAAG;GACH,OAAO;EACT;EACA,SAAS;GACP,OAAO,EAAE,GAAG,cAAc;EAC5B;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["isSpanContextValid","trace","context"],"sources":["../../../../src/services/telemetry/index.ts"],"sourcesContent":["import { context, isSpanContextValid, trace, type Context, type Span } from '@opentelemetry/api';\n\nimport type {\n PoTelemetry,\n PoTelemetryAttributes,\n PoTelemetryErrorOptions,\n PoTelemetryEventLevel,\n PoTelemetryHandle,\n PoTelemetryOptions,\n PoTelemetryRecord,\n PoTelemetryRuntimeLoader,\n PoTelemetryStatus,\n PoTraceContext,\n} from '../../types/telemetry';\n\n/** Only the operation owning an aborted signal may classify its rejection as cancellation. */\nexport class OperationCancelledError extends Error {\n constructor(options?: ErrorOptions) {\n super('The operation was cancelled', options);\n this.name = 'OperationCancelledError';\n }\n}\n\nconst DEFAULT_RETRY_DELAY_MS = 1_000;\n// A wedged collector `/health` must not hold every span and event behind it.\nconst ENDPOINT_DISCOVERY_TIMEOUT_MS = 2_000;\nconst MAX_WARNING_DETAIL_LENGTH = 512;\nconst MAX_WARNING_DETAIL_DEPTH = 3;\nconst MAX_ATTRIBUTE_STRING_LENGTH = 128;\nconst MAX_REPORTED_FAILURES = 500;\nconst MAX_EVENT_NAME_LENGTH = 128;\nconst SESSION_ID_HEADERS = ['AGENT_SESSION_ID', 'PI_SESSION_ID'] as const;\nconst PARENT_SESSION_ID_HEADERS = ['AGENT_PARENT_SESSION_ID', 'PARENT_AGENT_SESSION_ID'] as const;\nconst TRANSPORT_SESSION_HEADERS = ['PI_SESSION_ID', 'AGENT_PARENT_SESSION_ID'] as const;\nconst TRUE_VALUES = new Set(['1', 'true', 'yes']);\nconst SPAN_STATUS_ERROR = 2;\nconst TRACEPARENT_PATTERN = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/u;\nconst SENSITIVE_ATTRIBUTE_PARTS = [\n 'prompt',\n 'message',\n 'content',\n 'payload',\n 'command',\n 'cwd',\n 'path',\n 'file',\n 'stack',\n 'traceback',\n 'transcript',\n 'diff',\n 'secret',\n 'authorization',\n 'header',\n 'environment',\n 'env',\n 'details',\n 'args',\n] as const;\nconst SAFE_RESULT_KEYS = new Set([\n 'tool.result.error',\n 'tool.result.count',\n 'tool.result.bytes',\n 'tool.result.duration_ms',\n]);\nconst SAFE_METADATA_KEY_PARTS = new Set([\n 'count',\n 'length',\n 'bytes',\n 'duration',\n 'duration_ms',\n 'size',\n 'index',\n 'number',\n 'active',\n 'enabled',\n 'previous',\n 'empty',\n 'silent',\n 'fallback',\n 'bypass',\n 'success',\n 'is_error',\n 'has_ui',\n 'requires_confirmation',\n 'exit_code',\n 'status_code',\n 'interval_seconds',\n 'concurrency',\n 'budget',\n]);\nconst SAFE_INPUT_KEYS = new Set([\n 'gen_ai.usage.input_tokens',\n 'gen_ai.usage.output_tokens',\n 'gen_ai.usage.total_tokens',\n 'gen_ai.usage.cache_read_tokens',\n 'gen_ai.usage.cache_write_tokens',\n 'gen_ai.usage.reasoning_tokens',\n]);\nconst SAFE_IDENTIFIER_KEY_PARTS = [\n 'id',\n 'correlation',\n 'session',\n 'trace',\n 'span',\n 'call',\n 'run',\n 'job',\n 'step',\n] as const;\nconst SAFE_STRING_KEY_PARTS = [\n 'name',\n 'operation',\n 'outcome',\n 'reason',\n 'status',\n 'mode',\n 'source',\n 'phase',\n 'engine',\n 'provider',\n 'model',\n 'level',\n 'type',\n 'code',\n 'signal',\n 'finish_reasons',\n 'trigger',\n 'action',\n 'kind',\n 'version',\n 'scope',\n 'layer',\n 'profile',\n 'domain',\n 'theme',\n 'leader',\n 'pass',\n 'role',\n 'stage',\n 'state',\n 'language',\n 'transport',\n 'adapter',\n 'runtime',\n 'backend',\n 'launcher',\n 'event',\n 'component',\n 'package',\n 'command_name',\n 'tool_name',\n 'token_attribution',\n] as const;\n\nconst recordObservers = new Set<(record: PoTelemetryRecord) => void>();\n\nexport function subscribeTelemetryRecords(observer: (record: PoTelemetryRecord) => void): () => void {\n recordObservers.add(observer);\n return () => recordObservers.delete(observer);\n}\n\nfunction isTruthy(value: string | undefined): boolean {\n return value !== undefined && TRUE_VALUES.has(value.toLowerCase());\n}\n\nfunction normalizeToken(value: string, fallback: string): string {\n const normalized = value.replace(/[^a-zA-Z0-9._:-]/g, '_').slice(0, MAX_ATTRIBUTE_STRING_LENGTH);\n return normalized || fallback;\n}\n\nfunction hashIdentifier(value: string): string {\n let hash = 2166136261;\n for (let index = 0; index < value.length; index += 1) {\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, 16777619);\n }\n return `id_${(hash >>> 0).toString(16).padStart(8, '0')}`;\n}\n\nfunction isSafeMetadataKey(key: string): boolean {\n const normalized = key.toLowerCase();\n return [...SAFE_METADATA_KEY_PARTS].some(\n (part) => normalized === part || normalized.endsWith(`.${part}`) || normalized.endsWith(`_${part}`),\n );\n}\n\nfunction isSensitiveKey(key: string): boolean {\n const normalized = key.toLowerCase();\n if (SAFE_RESULT_KEYS.has(normalized) || SAFE_INPUT_KEYS.has(normalized) || isSafeMetadataKey(normalized))\n return false;\n return SENSITIVE_ATTRIBUTE_PARTS.some((part) => normalized.split(/[._-]/u).includes(part));\n}\n\nfunction hasSafeStringMeaning(key: string): boolean {\n const normalized = key.toLowerCase();\n return SAFE_STRING_KEY_PARTS.some(\n (part) => normalized === part || normalized.endsWith(`.${part}`) || normalized.endsWith(`_${part}`),\n );\n}\n\nfunction hasSafeIdentifierMeaning(key: string): boolean {\n const normalized = key.toLowerCase();\n return SAFE_IDENTIFIER_KEY_PARTS.some(\n (part) => normalized === part || normalized.endsWith(`.${part}`) || normalized.endsWith(`_${part}`),\n );\n}\n\nfunction isScalar(value: unknown): value is string | number | boolean {\n return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean';\n}\n\nfunction sanitizeValue(key: string, value: string | number | boolean): string | number | boolean | undefined {\n if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;\n if (typeof value === 'boolean') return value;\n if (value.length === 0 || value.length > MAX_ATTRIBUTE_STRING_LENGTH) return undefined;\n if (hasSafeIdentifierMeaning(key)) return hashIdentifier(value);\n if (!hasSafeStringMeaning(key)) return undefined;\n if (key === 'telemetry.package' || key.endsWith('.package')) {\n if (value.startsWith('/') || value.includes('\\\\')) return undefined;\n return value.replace(/[^a-zA-Z0-9@/._:-]/g, '_');\n }\n return normalizeToken(value, 'unknown');\n}\n\nexport function sanitizeTelemetryAttributes(attributes: Record<string, unknown> = {}): PoTelemetryAttributes {\n const sanitized: PoTelemetryAttributes = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (isSensitiveKey(key) || !isScalar(value)) continue;\n const safeValue = sanitizeValue(key, value);\n if (safeValue !== undefined) sanitized[key] = safeValue;\n }\n return sanitized;\n}\n\nfunction safeErrorToken(value: string, fallback: string): string {\n if (!/^[a-zA-Z][a-zA-Z0-9._:-]{0,63}$/u.test(value)) return fallback;\n return normalizeToken(value, fallback);\n}\n\nfunction errorType(error: unknown): string {\n // A subclass that keeps the default name still exports its class, never its message.\n if (error instanceof Error)\n return safeErrorToken(error.name === 'Error' ? error.constructor.name : error.name, 'Error');\n if (typeof error === 'string') return 'StringError';\n if (error && typeof error === 'object') return 'ObjectError';\n return 'UnknownError';\n}\n\n/**\n * Format an error for a local diagnostic warning.\n *\n * Deliberately separate from errorType: that produces a redacted token for the\n * exported `error.type` attribute and must stay metadata-only, whereas warnings\n * go to the local operator and are useless without the actual cause. Arrays are\n * unwrapped because OpenTelemetry's forceFlush rejects with one.\n */\nfunction describeError(error: unknown, depth = 0): string {\n if (depth > MAX_WARNING_DETAIL_DEPTH) return '...';\n if (Array.isArray(error)) return error.map((entry) => describeError(entry, depth + 1)).join('; ');\n if (error instanceof Error) {\n const rawCode = 'code' in error ? (error as { code?: unknown }).code : undefined;\n const code = typeof rawCode === 'string' || typeof rawCode === 'number' ? ` (code ${rawCode})` : '';\n const aggregate = error instanceof AggregateError ? `: ${describeError(error.errors, depth + 1)}` : '';\n const cause = error.cause === undefined ? '' : ` <- caused by ${describeError(error.cause, depth + 1)}`;\n return `${error.name}: ${error.message}${code}${aggregate}${cause}`;\n }\n if (typeof error === 'string') return error;\n if (error && typeof error === 'object') {\n try {\n return JSON.stringify(error);\n } catch {\n return 'ObjectError';\n }\n }\n return String(error);\n}\n\nfunction warningDetail(error: unknown): string {\n return describeError(error).slice(0, MAX_WARNING_DETAIL_LENGTH);\n}\n\nfunction errorCode(error: unknown): string | undefined {\n if (!error || typeof error !== 'object' || !('code' in error)) return undefined;\n const code = (error as { code?: unknown }).code;\n if (typeof code !== 'string' && typeof code !== 'number') return undefined;\n const normalized = String(code);\n return /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,63}$/u.test(normalized) ? normalizeToken(normalized, 'unknown') : undefined;\n}\n\nfunction errorAttributes(error: unknown): PoTelemetryAttributes {\n const attributes: PoTelemetryAttributes = {\n 'error.type': errorType(error),\n outcome: 'error',\n };\n const code = errorCode(error);\n if (code) attributes['error.code'] = code;\n return attributes;\n}\n\nfunction firstEnvironmentValue(env: NodeJS.ProcessEnv, keys: readonly string[]): string | undefined {\n for (const key of keys) {\n const value = env[key]?.trim();\n if (value) return value;\n }\n return undefined;\n}\n\nexport function createTelemetryHeaders(serviceName: string, env: NodeJS.ProcessEnv): Record<string, string> {\n const headers: Record<string, string> = { 'x-agent': normalizeToken(serviceName, 'po') };\n const sessionId = firstEnvironmentValue(env, SESSION_ID_HEADERS);\n const parentSessionId = firstEnvironmentValue(env, PARENT_SESSION_ID_HEADERS);\n if (sessionId) headers['x-agent-session-id'] = hashIdentifier(sessionId);\n if (parentSessionId) headers['x-agent-parent-session-id'] = hashIdentifier(parentSessionId);\n return headers;\n}\n\n/** The session on every exported record lets the Node runtime share one exporter per service. */\nfunction sessionAttributes(env: NodeJS.ProcessEnv): PoTelemetryAttributes {\n const attributes: PoTelemetryAttributes = {};\n const sessionId = firstEnvironmentValue(env, SESSION_ID_HEADERS);\n const parentSessionId = firstEnvironmentValue(env, PARENT_SESSION_ID_HEADERS);\n if (sessionId) attributes['agent.session.id'] = hashIdentifier(sessionId);\n if (parentSessionId) attributes['agent.parent_session.id'] = hashIdentifier(parentSessionId);\n return attributes;\n}\n\nfunction createTransportEnvironment(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const transportEnv = { ...env };\n const sessionId = firstEnvironmentValue(env, SESSION_ID_HEADERS);\n const parentSessionId = firstEnvironmentValue(env, PARENT_SESSION_ID_HEADERS);\n if (sessionId) transportEnv.AGENT_SESSION_ID = hashIdentifier(sessionId);\n else delete transportEnv.AGENT_SESSION_ID;\n if (parentSessionId) transportEnv.PARENT_AGENT_SESSION_ID = hashIdentifier(parentSessionId);\n else delete transportEnv.PARENT_AGENT_SESSION_ID;\n for (const key of TRANSPORT_SESSION_HEADERS) delete transportEnv[key];\n for (const key of Object.keys(transportEnv)) {\n if (key.startsWith('WORKFLOW_')) delete transportEnv[key];\n }\n return transportEnv;\n}\n\nfunction defaultStatus(options: PoTelemetryOptions): PoTelemetryStatus {\n return {\n serviceName: options.serviceName,\n packageName: options.packageName,\n backend: 'disabled',\n enabled: false,\n endpointSource: 'none',\n traces: false,\n fileFallback: false,\n };\n}\n\nfunction createSafeCallbackError(error: unknown): Error {\n const code = errorCode(error);\n return new Error(`Po telemetry callback failed: ${errorType(error)}${code ? ` (${code})` : ''}`);\n}\n\nfunction parentContext(parent: PoTraceContext | undefined): Context | undefined {\n if (!parent) return undefined;\n const match = TRACEPARENT_PATTERN.exec(parent.traceparent);\n if (!match) return undefined;\n const [, traceId, spanId, traceFlags] = match;\n if (!traceId || !spanId || !traceFlags) return undefined;\n const spanContext = { traceId, spanId, traceFlags: Number.parseInt(traceFlags, 16), isRemote: true };\n return isSpanContextValid(spanContext) ? trace.setSpanContext(context.active(), spanContext) : undefined;\n}\n\nfunction childTraceContext(span: Span | undefined): PoTraceContext | undefined {\n if (!span) return undefined;\n const spanContext = span.spanContext();\n if (!isSpanContextValid(spanContext)) return undefined;\n const traceFlags = spanContext.traceFlags.toString(16).padStart(2, '0');\n return { traceparent: `00-${spanContext.traceId}-${spanContext.spanId}-${traceFlags}` };\n}\nexport function createPoTelemetryService(\n options: PoTelemetryOptions,\n runtimeLoader?: PoTelemetryRuntimeLoader,\n): PoTelemetry {\n const env = { ...options.env };\n const telemetryFactory = options.telemetryFactory;\n const endpointResolver = options.endpointResolver;\n const transportEnv = createTransportEnvironment(env);\n const session = sessionAttributes(env);\n const warn = options.warn ?? ((message: string) => console.warn(message));\n const reportWarning = (message: string): void => {\n try {\n warn(message);\n } catch (error) {\n console.warn(`Po telemetry warning callback failed: ${warningDetail(error)}`);\n }\n };\n const retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;\n const allowFileFallback = options.allowFileFallback ?? isTruthy(env.LOG_SINK_PI_FILE_FALLBACK);\n const defaultTelemetryStatus = defaultStatus(options);\n let currentStatus = defaultTelemetryStatus;\n let handle: PoTelemetryHandle | undefined;\n let initialization: Promise<PoTelemetryHandle | undefined> | undefined;\n let retryAfter = 0;\n let discoveryFailureReported = false;\n const reportDiscoveryFailure = (message: string): void => {\n if (!discoveryFailureReported) reportWarning(message);\n discoveryFailureReported = true;\n };\n let shutdownPromise: Promise<void> | undefined;\n let shutdownRequested = false;\n const reportedFailures = new Set<string>();\n\n const disabledByEnvironment = (): boolean =>\n isTruthy(env.AGENT_TELEMETRY_DISABLED) || isTruthy(env.OTEL_SDK_DISABLED);\n\n const publish = (record: PoTelemetryRecord): void => {\n for (const observer of [...recordObservers, ...(options.onRecord ? [options.onRecord] : [])]) {\n try {\n observer(record);\n } catch (error) {\n reportWarning(`Po telemetry observer failed: ${warningDetail(error)}`);\n }\n }\n };\n\n const initialize = async (): Promise<PoTelemetryHandle | undefined> => {\n if (disabledByEnvironment() || shutdownRequested) return undefined;\n const defaults = telemetryFactory ? undefined : await runtimeLoader?.();\n const resolveEndpoints = endpointResolver ?? defaults?.resolveNodeTelemetryEndpoints;\n const createTelemetry = telemetryFactory ?? defaults?.createNodeTelemetry;\n if ((!resolveEndpoints && !telemetryFactory) || !createTelemetry)\n throw new Error('Node telemetry runtime is unavailable.');\n let discoveryTimer: ReturnType<typeof setTimeout> | undefined;\n const discoveryTimedOut = Symbol('discoveryTimedOut');\n const resolvedEndpoints =\n resolveEndpoints === undefined\n ? undefined\n : await Promise.race([\n resolveEndpoints({\n cwd: options.cwd,\n env,\n packageName: options.packageName,\n serviceName: options.serviceName,\n workspaceRoot: options.workspaceRoot,\n discoverEndpoint: true,\n healthCheck: true,\n }),\n new Promise<typeof discoveryTimedOut>((resolve) => {\n discoveryTimer = setTimeout(() => resolve(discoveryTimedOut), ENDPOINT_DISCOVERY_TIMEOUT_MS);\n }),\n ]).finally(() => clearTimeout(discoveryTimer));\n if (resolvedEndpoints === discoveryTimedOut) {\n reportDiscoveryFailure(\n `Po telemetry endpoint discovery timed out after ${ENDPOINT_DISCOVERY_TIMEOUT_MS} ms; retrying`,\n );\n retryAfter = Date.now() + retryDelayMs;\n currentStatus = { ...defaultTelemetryStatus };\n return undefined;\n }\n const endpoints = resolvedEndpoints ?? { endpointSource: 'env' as const, endpoint: 'injected' };\n if (!endpoints.endpoint && !endpoints.tracesEndpoint && !endpoints.logsEndpoint && !allowFileFallback) {\n retryAfter = Date.now() + retryDelayMs;\n currentStatus = { ...defaultTelemetryStatus };\n return undefined;\n }\n const nextHandle = await createTelemetry({\n serviceName: options.serviceName,\n packageName: options.packageName,\n cwd: options.cwd,\n workspaceRoot: options.workspaceRoot,\n env: transportEnv,\n discoverEndpoint: resolvedEndpoints === undefined,\n resolvedEndpoints,\n enableLogs: options.enableLogs ?? true,\n enableTraces: options.enableTraces ?? true,\n headers: createTelemetryHeaders(options.serviceName, env),\n });\n if (shutdownRequested) {\n await nextHandle.shutdown().catch((error: unknown) => {\n reportWarning(`Po telemetry late initialization shutdown failed: ${warningDetail(error)}`);\n });\n return undefined;\n }\n if (nextHandle.backend === 'file' && !allowFileFallback) {\n await nextHandle\n .shutdown()\n .catch((error: unknown) => reportWarning(`Po telemetry fallback shutdown failed: ${warningDetail(error)}`));\n retryAfter = Date.now() + retryDelayMs;\n currentStatus = { ...defaultTelemetryStatus };\n return undefined;\n }\n if (discoveryFailureReported) reportWarning('Po telemetry endpoint discovery recovered');\n discoveryFailureReported = false;\n handle = nextHandle;\n currentStatus = {\n serviceName: options.serviceName,\n packageName: options.packageName,\n backend: nextHandle.backend,\n enabled: nextHandle.enabled,\n endpoint: nextHandle.endpoint,\n endpointSource: nextHandle.endpointSource,\n traces: Boolean(options.enableTraces ?? true),\n fileFallback: nextHandle.backend === 'file',\n };\n try {\n options.onStatus?.({ ...currentStatus });\n } catch (error) {\n reportWarning(`Po telemetry status observer failed: ${warningDetail(error)}`);\n }\n return nextHandle;\n };\n\n const getHandle = async (): Promise<PoTelemetryHandle | undefined> => {\n if (disabledByEnvironment() || shutdownRequested) return undefined;\n if (handle) return handle;\n if (Date.now() < retryAfter) return undefined;\n initialization ??= initialize()\n .catch((error: unknown) => {\n retryAfter = Date.now() + retryDelayMs;\n reportDiscoveryFailure(`Po telemetry initialization failed: ${warningDetail(error)}`);\n return undefined;\n })\n .finally(() => {\n initialization = undefined;\n });\n return initialization;\n };\n\n const emit = async (\n level: PoTelemetryEventLevel,\n event: string,\n error: unknown,\n attributes: Record<string, unknown> | undefined,\n errorOptions?: PoTelemetryErrorOptions,\n ): Promise<void> => {\n const safeEvent = normalizeToken(event, 'po.telemetry.event').slice(0, MAX_EVENT_NAME_LENGTH);\n const safeAttributes = sanitizeTelemetryAttributes({\n 'telemetry.package': options.packageName,\n ...attributes,\n ...(error === undefined ? {} : errorAttributes(error)),\n });\n if (error !== undefined) {\n const failureKey = `${safeEvent}:${level}:${JSON.stringify(safeAttributes)}`;\n if (reportedFailures.has(failureKey)) return;\n if (reportedFailures.size >= MAX_REPORTED_FAILURES) reportedFailures.clear();\n reportedFailures.add(failureKey);\n }\n const record: PoTelemetryRecord = { event: safeEvent, level, attributes: safeAttributes };\n publish(record);\n try {\n const nextHandle = await getHandle();\n nextHandle?.logger[level](safeEvent, {\n attributes: { ...session, ...safeAttributes },\n ...(errorOptions?.includeException === true && error !== undefined ? { exception: error } : {}),\n });\n } catch (failure) {\n reportWarning(`Po telemetry record failed: ${warningDetail(failure)}`);\n }\n };\n\n const flush = async (): Promise<void> => {\n try {\n const pendingInitialization = initialization;\n if (pendingInitialization) await pendingInitialization;\n await handle?.flush();\n } catch (error) {\n reportWarning(`Po telemetry flush failed: ${warningDetail(error)}`);\n }\n };\n\n return {\n recordDebug(event, attributes) {\n return emit('debug', event, undefined, attributes);\n },\n recordEvent(event, attributes) {\n return emit('info', event, undefined, attributes);\n },\n recordWarning(event, error, attributes) {\n return emit('warn', event, error, attributes);\n },\n recordError(event, error, attributes, errorOptions) {\n return emit('error', event, error, attributes, errorOptions);\n },\n async runInSpan<T>(\n name: string,\n attributes: Record<string, unknown>,\n callback: (context?: PoTraceContext) => Promise<T> | T,\n parent?: PoTraceContext,\n ) {\n let callbackPromise: Promise<T> | undefined;\n let callbackFailure: { value: unknown } | undefined;\n const invokeCallback = (child?: PoTraceContext): Promise<T> => {\n callbackPromise ??= Promise.resolve().then(() => callback(child));\n return callbackPromise;\n };\n const nextHandle = await getHandle();\n if (!nextHandle) return invokeCallback();\n const startedAt = Date.now();\n try {\n const nextParentContext = parentContext(parent);\n const result = await nextHandle.runInSpan(\n normalizeToken(name, 'po.telemetry.span'),\n {\n attributes: { ...session, ...sanitizeTelemetryAttributes(attributes) },\n ...(nextParentContext ? { context: nextParentContext } : {}),\n },\n async (span) => {\n const child = childTraceContext(span);\n try {\n const result = await invokeCallback(child);\n span?.setAttribute('duration_ms', Date.now() - startedAt);\n span?.setAttribute('outcome', 'success');\n return result;\n } catch (error) {\n callbackFailure = { value: error };\n if (error instanceof OperationCancelledError) {\n span?.setAttribute('outcome', 'cancelled');\n span?.setAttribute('duration_ms', Date.now() - startedAt);\n // Do not throw through the exporter, which would create an error span.\n return undefined as T;\n }\n const safeError = errorAttributes(error);\n // The real cause stays in the local log; the exported span carries only its class and code.\n const detail = `Po telemetry span ${name} failed: ${warningDetail(error)}`;\n if (!reportedFailures.has(detail)) {\n if (reportedFailures.size >= MAX_REPORTED_FAILURES) reportedFailures.clear();\n reportedFailures.add(detail);\n reportWarning(detail);\n }\n for (const [key, value] of Object.entries(safeError)) span?.setAttribute(key, value);\n span?.setAttribute('duration_ms', Date.now() - startedAt);\n span?.setStatus({ code: SPAN_STATUS_ERROR });\n throw createSafeCallbackError(error);\n }\n },\n );\n if (callbackFailure) throw callbackFailure.value;\n return result;\n } catch (error) {\n if (callbackFailure) return Promise.reject(callbackFailure.value);\n if (callbackPromise) return callbackPromise;\n reportWarning(`Po telemetry span failed: ${warningDetail(error)}`);\n return invokeCallback();\n }\n },\n flush,\n async shutdown() {\n if (shutdownPromise) return shutdownPromise;\n shutdownRequested = true;\n shutdownPromise = (async () => {\n await flush();\n const currentHandle = handle;\n handle = undefined;\n if (!currentHandle) return;\n try {\n await currentHandle.shutdown();\n } catch (error) {\n reportWarning(`Po telemetry shutdown failed: ${warningDetail(error)}`);\n }\n })();\n return shutdownPromise;\n },\n status() {\n return { ...currentStatus };\n },\n };\n}\n"],"mappings":";;;AAgBA,IAAa,0BAAb,cAA6C,MAAM;CACjD,YAAY,SAAwB;EAClC,MAAM,+BAA+B,OAAO;EAC5C,KAAK,OAAO;CACd;AACF;AAEA,MAAM,yBAAyB;AAE/B,MAAM,gCAAgC;AACtC,MAAM,4BAA4B;AAClC,MAAM,2BAA2B;AACjC,MAAM,8BAA8B;AACpC,MAAM,wBAAwB;AAC9B,MAAM,wBAAwB;AAC9B,MAAM,qBAAqB,CAAC,oBAAoB,eAAe;AAC/D,MAAM,4BAA4B,CAAC,2BAA2B,yBAAyB;AACvF,MAAM,4BAA4B,CAAC,iBAAiB,yBAAyB;AAC7E,MAAM,8BAAc,IAAI,IAAI;CAAC;CAAK;CAAQ;AAAK,CAAC;AAChD,MAAM,oBAAoB;AAC1B,MAAM,sBAAsB;AAC5B,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,mCAAmB,IAAI,IAAI;CAC/B;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,0CAA0B,IAAI,IAAI;CACtC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,kCAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,wBAAwB;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,kCAAkB,IAAI,IAAyC;AAErE,SAAgB,0BAA0B,UAA2D;CACnG,gBAAgB,IAAI,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Y;IAC7B,MAAM,MAAM;IACZ,MAAM,gBAAgB;IACtB,SAAS,KAAA;IACT,IAAI,CAAC,eAAe;IACpB,IAAI;KACF,MAAM,cAAc,SAAS;IAC/B,SAAS,OAAO;KACd,cAAc,iCAAiC,cAAc,KAAK,GAAG;IACvE;GACF,EAAA,CAAG;GACH,OAAO;EACT;EACA,SAAS;GACP,OAAO,EAAE,GAAG,cAAc;EAC5B;CACF;AACF"}
|
|
@@ -269,6 +269,15 @@ function createTelemetryHeaders(serviceName, env) {
|
|
|
269
269
|
if (parentSessionId) headers["x-agent-parent-session-id"] = hashIdentifier(parentSessionId);
|
|
270
270
|
return headers;
|
|
271
271
|
}
|
|
272
|
+
/** The session on every exported record lets the Node runtime share one exporter per service. */
|
|
273
|
+
function sessionAttributes(env) {
|
|
274
|
+
const attributes = {};
|
|
275
|
+
const sessionId = firstEnvironmentValue(env, SESSION_ID_HEADERS);
|
|
276
|
+
const parentSessionId = firstEnvironmentValue(env, PARENT_SESSION_ID_HEADERS);
|
|
277
|
+
if (sessionId) attributes["agent.session.id"] = hashIdentifier(sessionId);
|
|
278
|
+
if (parentSessionId) attributes["agent.parent_session.id"] = hashIdentifier(parentSessionId);
|
|
279
|
+
return attributes;
|
|
280
|
+
}
|
|
272
281
|
function createTransportEnvironment(env) {
|
|
273
282
|
const transportEnv = { ...env };
|
|
274
283
|
const sessionId = firstEnvironmentValue(env, SESSION_ID_HEADERS);
|
|
@@ -322,6 +331,7 @@ function createPoTelemetryService(options, runtimeLoader) {
|
|
|
322
331
|
const telemetryFactory = options.telemetryFactory;
|
|
323
332
|
const endpointResolver = options.endpointResolver;
|
|
324
333
|
const transportEnv = createTransportEnvironment(env);
|
|
334
|
+
const session = sessionAttributes(env);
|
|
325
335
|
const warn = options.warn ?? ((message) => console.warn(message));
|
|
326
336
|
const reportWarning = (message) => {
|
|
327
337
|
try {
|
|
@@ -463,7 +473,10 @@ function createPoTelemetryService(options, runtimeLoader) {
|
|
|
463
473
|
});
|
|
464
474
|
try {
|
|
465
475
|
(await getHandle())?.logger[level](safeEvent, {
|
|
466
|
-
attributes:
|
|
476
|
+
attributes: {
|
|
477
|
+
...session,
|
|
478
|
+
...safeAttributes
|
|
479
|
+
},
|
|
467
480
|
...errorOptions?.includeException === true && error !== void 0 ? { exception: error } : {}
|
|
468
481
|
});
|
|
469
482
|
} catch (failure) {
|
|
@@ -505,7 +518,10 @@ function createPoTelemetryService(options, runtimeLoader) {
|
|
|
505
518
|
try {
|
|
506
519
|
const nextParentContext = parentContext(parent);
|
|
507
520
|
const result = await nextHandle.runInSpan(normalizeToken(name, "po.telemetry.span"), {
|
|
508
|
-
attributes:
|
|
521
|
+
attributes: {
|
|
522
|
+
...session,
|
|
523
|
+
...sanitizeTelemetryAttributes(attributes)
|
|
524
|
+
},
|
|
509
525
|
...nextParentContext ? { context: nextParentContext } : {}
|
|
510
526
|
}, async (span) => {
|
|
511
527
|
const child = childTraceContext(span);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../src/services/telemetry/index.ts"],"sourcesContent":["import { context, isSpanContextValid, trace, type Context, type Span } from '@opentelemetry/api';\n\nimport type {\n PoTelemetry,\n PoTelemetryAttributes,\n PoTelemetryErrorOptions,\n PoTelemetryEventLevel,\n PoTelemetryHandle,\n PoTelemetryOptions,\n PoTelemetryRecord,\n PoTelemetryRuntimeLoader,\n PoTelemetryStatus,\n PoTraceContext,\n} from '../../types/telemetry';\n\n/** Only the operation owning an aborted signal may classify its rejection as cancellation. */\nexport class OperationCancelledError extends Error {\n constructor(options?: ErrorOptions) {\n super('The operation was cancelled', options);\n this.name = 'OperationCancelledError';\n }\n}\n\nconst DEFAULT_RETRY_DELAY_MS = 1_000;\n// A wedged collector `/health` must not hold every span and event behind it.\nconst ENDPOINT_DISCOVERY_TIMEOUT_MS = 2_000;\nconst MAX_WARNING_DETAIL_LENGTH = 512;\nconst MAX_WARNING_DETAIL_DEPTH = 3;\nconst MAX_ATTRIBUTE_STRING_LENGTH = 128;\nconst MAX_REPORTED_FAILURES = 500;\nconst MAX_EVENT_NAME_LENGTH = 128;\nconst SESSION_ID_HEADERS = ['AGENT_SESSION_ID', 'PI_SESSION_ID'] as const;\nconst PARENT_SESSION_ID_HEADERS = ['AGENT_PARENT_SESSION_ID', 'PARENT_AGENT_SESSION_ID'] as const;\nconst TRANSPORT_SESSION_HEADERS = ['PI_SESSION_ID', 'AGENT_PARENT_SESSION_ID'] as const;\nconst TRUE_VALUES = new Set(['1', 'true', 'yes']);\nconst SPAN_STATUS_ERROR = 2;\nconst TRACEPARENT_PATTERN = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/u;\nconst SENSITIVE_ATTRIBUTE_PARTS = [\n 'prompt',\n 'message',\n 'content',\n 'payload',\n 'command',\n 'cwd',\n 'path',\n 'file',\n 'stack',\n 'traceback',\n 'transcript',\n 'diff',\n 'secret',\n 'authorization',\n 'header',\n 'environment',\n 'env',\n 'details',\n 'args',\n] as const;\nconst SAFE_RESULT_KEYS = new Set([\n 'tool.result.error',\n 'tool.result.count',\n 'tool.result.bytes',\n 'tool.result.duration_ms',\n]);\nconst SAFE_METADATA_KEY_PARTS = new Set([\n 'count',\n 'length',\n 'bytes',\n 'duration',\n 'duration_ms',\n 'size',\n 'index',\n 'number',\n 'active',\n 'enabled',\n 'previous',\n 'empty',\n 'silent',\n 'fallback',\n 'bypass',\n 'success',\n 'is_error',\n 'has_ui',\n 'requires_confirmation',\n 'exit_code',\n 'status_code',\n 'interval_seconds',\n 'concurrency',\n 'budget',\n]);\nconst SAFE_INPUT_KEYS = new Set([\n 'gen_ai.usage.input_tokens',\n 'gen_ai.usage.output_tokens',\n 'gen_ai.usage.total_tokens',\n 'gen_ai.usage.cache_read_tokens',\n 'gen_ai.usage.cache_write_tokens',\n 'gen_ai.usage.reasoning_tokens',\n]);\nconst SAFE_IDENTIFIER_KEY_PARTS = [\n 'id',\n 'correlation',\n 'session',\n 'trace',\n 'span',\n 'call',\n 'run',\n 'job',\n 'step',\n] as const;\nconst SAFE_STRING_KEY_PARTS = [\n 'name',\n 'operation',\n 'outcome',\n 'reason',\n 'status',\n 'mode',\n 'source',\n 'phase',\n 'engine',\n 'provider',\n 'model',\n 'level',\n 'type',\n 'code',\n 'signal',\n 'finish_reasons',\n 'trigger',\n 'action',\n 'kind',\n 'version',\n 'scope',\n 'layer',\n 'profile',\n 'domain',\n 'theme',\n 'leader',\n 'pass',\n 'role',\n 'stage',\n 'state',\n 'language',\n 'transport',\n 'adapter',\n 'runtime',\n 'backend',\n 'launcher',\n 'event',\n 'component',\n 'package',\n 'command_name',\n 'tool_name',\n 'token_attribution',\n] as const;\n\nconst recordObservers = new Set<(record: PoTelemetryRecord) => void>();\n\nexport function subscribeTelemetryRecords(observer: (record: PoTelemetryRecord) => void): () => void {\n recordObservers.add(observer);\n return () => recordObservers.delete(observer);\n}\n\nfunction isTruthy(value: string | undefined): boolean {\n return value !== undefined && TRUE_VALUES.has(value.toLowerCase());\n}\n\nfunction normalizeToken(value: string, fallback: string): string {\n const normalized = value.replace(/[^a-zA-Z0-9._:-]/g, '_').slice(0, MAX_ATTRIBUTE_STRING_LENGTH);\n return normalized || fallback;\n}\n\nfunction hashIdentifier(value: string): string {\n let hash = 2166136261;\n for (let index = 0; index < value.length; index += 1) {\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, 16777619);\n }\n return `id_${(hash >>> 0).toString(16).padStart(8, '0')}`;\n}\n\nfunction isSafeMetadataKey(key: string): boolean {\n const normalized = key.toLowerCase();\n return [...SAFE_METADATA_KEY_PARTS].some(\n (part) => normalized === part || normalized.endsWith(`.${part}`) || normalized.endsWith(`_${part}`),\n );\n}\n\nfunction isSensitiveKey(key: string): boolean {\n const normalized = key.toLowerCase();\n if (SAFE_RESULT_KEYS.has(normalized) || SAFE_INPUT_KEYS.has(normalized) || isSafeMetadataKey(normalized))\n return false;\n return SENSITIVE_ATTRIBUTE_PARTS.some((part) => normalized.split(/[._-]/u).includes(part));\n}\n\nfunction hasSafeStringMeaning(key: string): boolean {\n const normalized = key.toLowerCase();\n return SAFE_STRING_KEY_PARTS.some(\n (part) => normalized === part || normalized.endsWith(`.${part}`) || normalized.endsWith(`_${part}`),\n );\n}\n\nfunction hasSafeIdentifierMeaning(key: string): boolean {\n const normalized = key.toLowerCase();\n return SAFE_IDENTIFIER_KEY_PARTS.some(\n (part) => normalized === part || normalized.endsWith(`.${part}`) || normalized.endsWith(`_${part}`),\n );\n}\n\nfunction isScalar(value: unknown): value is string | number | boolean {\n return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean';\n}\n\nfunction sanitizeValue(key: string, value: string | number | boolean): string | number | boolean | undefined {\n if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;\n if (typeof value === 'boolean') return value;\n if (value.length === 0 || value.length > MAX_ATTRIBUTE_STRING_LENGTH) return undefined;\n if (hasSafeIdentifierMeaning(key)) return hashIdentifier(value);\n if (!hasSafeStringMeaning(key)) return undefined;\n if (key === 'telemetry.package' || key.endsWith('.package')) {\n if (value.startsWith('/') || value.includes('\\\\')) return undefined;\n return value.replace(/[^a-zA-Z0-9@/._:-]/g, '_');\n }\n return normalizeToken(value, 'unknown');\n}\n\nexport function sanitizeTelemetryAttributes(attributes: Record<string, unknown> = {}): PoTelemetryAttributes {\n const sanitized: PoTelemetryAttributes = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (isSensitiveKey(key) || !isScalar(value)) continue;\n const safeValue = sanitizeValue(key, value);\n if (safeValue !== undefined) sanitized[key] = safeValue;\n }\n return sanitized;\n}\n\nfunction safeErrorToken(value: string, fallback: string): string {\n if (!/^[a-zA-Z][a-zA-Z0-9._:-]{0,63}$/u.test(value)) return fallback;\n return normalizeToken(value, fallback);\n}\n\nfunction errorType(error: unknown): string {\n // A subclass that keeps the default name still exports its class, never its message.\n if (error instanceof Error)\n return safeErrorToken(error.name === 'Error' ? error.constructor.name : error.name, 'Error');\n if (typeof error === 'string') return 'StringError';\n if (error && typeof error === 'object') return 'ObjectError';\n return 'UnknownError';\n}\n\n/**\n * Format an error for a local diagnostic warning.\n *\n * Deliberately separate from errorType: that produces a redacted token for the\n * exported `error.type` attribute and must stay metadata-only, whereas warnings\n * go to the local operator and are useless without the actual cause. Arrays are\n * unwrapped because OpenTelemetry's forceFlush rejects with one.\n */\nfunction describeError(error: unknown, depth = 0): string {\n if (depth > MAX_WARNING_DETAIL_DEPTH) return '...';\n if (Array.isArray(error)) return error.map((entry) => describeError(entry, depth + 1)).join('; ');\n if (error instanceof Error) {\n const rawCode = 'code' in error ? (error as { code?: unknown }).code : undefined;\n const code = typeof rawCode === 'string' || typeof rawCode === 'number' ? ` (code ${rawCode})` : '';\n const aggregate = error instanceof AggregateError ? `: ${describeError(error.errors, depth + 1)}` : '';\n const cause = error.cause === undefined ? '' : ` <- caused by ${describeError(error.cause, depth + 1)}`;\n return `${error.name}: ${error.message}${code}${aggregate}${cause}`;\n }\n if (typeof error === 'string') return error;\n if (error && typeof error === 'object') {\n try {\n return JSON.stringify(error);\n } catch {\n return 'ObjectError';\n }\n }\n return String(error);\n}\n\nfunction warningDetail(error: unknown): string {\n return describeError(error).slice(0, MAX_WARNING_DETAIL_LENGTH);\n}\n\nfunction errorCode(error: unknown): string | undefined {\n if (!error || typeof error !== 'object' || !('code' in error)) return undefined;\n const code = (error as { code?: unknown }).code;\n if (typeof code !== 'string' && typeof code !== 'number') return undefined;\n const normalized = String(code);\n return /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,63}$/u.test(normalized) ? normalizeToken(normalized, 'unknown') : undefined;\n}\n\nfunction errorAttributes(error: unknown): PoTelemetryAttributes {\n const attributes: PoTelemetryAttributes = {\n 'error.type': errorType(error),\n outcome: 'error',\n };\n const code = errorCode(error);\n if (code) attributes['error.code'] = code;\n return attributes;\n}\n\nfunction firstEnvironmentValue(env: NodeJS.ProcessEnv, keys: readonly string[]): string | undefined {\n for (const key of keys) {\n const value = env[key]?.trim();\n if (value) return value;\n }\n return undefined;\n}\n\nexport function createTelemetryHeaders(serviceName: string, env: NodeJS.ProcessEnv): Record<string, string> {\n const headers: Record<string, string> = { 'x-agent': normalizeToken(serviceName, 'po') };\n const sessionId = firstEnvironmentValue(env, SESSION_ID_HEADERS);\n const parentSessionId = firstEnvironmentValue(env, PARENT_SESSION_ID_HEADERS);\n if (sessionId) headers['x-agent-session-id'] = hashIdentifier(sessionId);\n if (parentSessionId) headers['x-agent-parent-session-id'] = hashIdentifier(parentSessionId);\n return headers;\n}\n\nfunction createTransportEnvironment(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const transportEnv = { ...env };\n const sessionId = firstEnvironmentValue(env, SESSION_ID_HEADERS);\n const parentSessionId = firstEnvironmentValue(env, PARENT_SESSION_ID_HEADERS);\n if (sessionId) transportEnv.AGENT_SESSION_ID = hashIdentifier(sessionId);\n else delete transportEnv.AGENT_SESSION_ID;\n if (parentSessionId) transportEnv.PARENT_AGENT_SESSION_ID = hashIdentifier(parentSessionId);\n else delete transportEnv.PARENT_AGENT_SESSION_ID;\n for (const key of TRANSPORT_SESSION_HEADERS) delete transportEnv[key];\n for (const key of Object.keys(transportEnv)) {\n if (key.startsWith('WORKFLOW_')) delete transportEnv[key];\n }\n return transportEnv;\n}\n\nfunction defaultStatus(options: PoTelemetryOptions): PoTelemetryStatus {\n return {\n serviceName: options.serviceName,\n packageName: options.packageName,\n backend: 'disabled',\n enabled: false,\n endpointSource: 'none',\n traces: false,\n fileFallback: false,\n };\n}\n\nfunction createSafeCallbackError(error: unknown): Error {\n const code = errorCode(error);\n return new Error(`Po telemetry callback failed: ${errorType(error)}${code ? ` (${code})` : ''}`);\n}\n\nfunction parentContext(parent: PoTraceContext | undefined): Context | undefined {\n if (!parent) return undefined;\n const match = TRACEPARENT_PATTERN.exec(parent.traceparent);\n if (!match) return undefined;\n const [, traceId, spanId, traceFlags] = match;\n if (!traceId || !spanId || !traceFlags) return undefined;\n const spanContext = { traceId, spanId, traceFlags: Number.parseInt(traceFlags, 16), isRemote: true };\n return isSpanContextValid(spanContext) ? trace.setSpanContext(context.active(), spanContext) : undefined;\n}\n\nfunction childTraceContext(span: Span | undefined): PoTraceContext | undefined {\n if (!span) return undefined;\n const spanContext = span.spanContext();\n if (!isSpanContextValid(spanContext)) return undefined;\n const traceFlags = spanContext.traceFlags.toString(16).padStart(2, '0');\n return { traceparent: `00-${spanContext.traceId}-${spanContext.spanId}-${traceFlags}` };\n}\nexport function createPoTelemetryService(\n options: PoTelemetryOptions,\n runtimeLoader?: PoTelemetryRuntimeLoader,\n): PoTelemetry {\n const env = { ...options.env };\n const telemetryFactory = options.telemetryFactory;\n const endpointResolver = options.endpointResolver;\n const transportEnv = createTransportEnvironment(env);\n const warn = options.warn ?? ((message: string) => console.warn(message));\n const reportWarning = (message: string): void => {\n try {\n warn(message);\n } catch (error) {\n console.warn(`Po telemetry warning callback failed: ${warningDetail(error)}`);\n }\n };\n const retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;\n const allowFileFallback = options.allowFileFallback ?? isTruthy(env.LOG_SINK_PI_FILE_FALLBACK);\n const defaultTelemetryStatus = defaultStatus(options);\n let currentStatus = defaultTelemetryStatus;\n let handle: PoTelemetryHandle | undefined;\n let initialization: Promise<PoTelemetryHandle | undefined> | undefined;\n let retryAfter = 0;\n let discoveryFailureReported = false;\n const reportDiscoveryFailure = (message: string): void => {\n if (!discoveryFailureReported) reportWarning(message);\n discoveryFailureReported = true;\n };\n let shutdownPromise: Promise<void> | undefined;\n let shutdownRequested = false;\n const reportedFailures = new Set<string>();\n\n const disabledByEnvironment = (): boolean =>\n isTruthy(env.AGENT_TELEMETRY_DISABLED) || isTruthy(env.OTEL_SDK_DISABLED);\n\n const publish = (record: PoTelemetryRecord): void => {\n for (const observer of [...recordObservers, ...(options.onRecord ? [options.onRecord] : [])]) {\n try {\n observer(record);\n } catch (error) {\n reportWarning(`Po telemetry observer failed: ${warningDetail(error)}`);\n }\n }\n };\n\n const initialize = async (): Promise<PoTelemetryHandle | undefined> => {\n if (disabledByEnvironment() || shutdownRequested) return undefined;\n const defaults = telemetryFactory ? undefined : await runtimeLoader?.();\n const resolveEndpoints = endpointResolver ?? defaults?.resolveNodeTelemetryEndpoints;\n const createTelemetry = telemetryFactory ?? defaults?.createNodeTelemetry;\n if ((!resolveEndpoints && !telemetryFactory) || !createTelemetry)\n throw new Error('Node telemetry runtime is unavailable.');\n let discoveryTimer: ReturnType<typeof setTimeout> | undefined;\n const discoveryTimedOut = Symbol('discoveryTimedOut');\n const resolvedEndpoints =\n resolveEndpoints === undefined\n ? undefined\n : await Promise.race([\n resolveEndpoints({\n cwd: options.cwd,\n env,\n packageName: options.packageName,\n serviceName: options.serviceName,\n workspaceRoot: options.workspaceRoot,\n discoverEndpoint: true,\n healthCheck: true,\n }),\n new Promise<typeof discoveryTimedOut>((resolve) => {\n discoveryTimer = setTimeout(() => resolve(discoveryTimedOut), ENDPOINT_DISCOVERY_TIMEOUT_MS);\n }),\n ]).finally(() => clearTimeout(discoveryTimer));\n if (resolvedEndpoints === discoveryTimedOut) {\n reportDiscoveryFailure(\n `Po telemetry endpoint discovery timed out after ${ENDPOINT_DISCOVERY_TIMEOUT_MS} ms; retrying`,\n );\n retryAfter = Date.now() + retryDelayMs;\n currentStatus = { ...defaultTelemetryStatus };\n return undefined;\n }\n const endpoints = resolvedEndpoints ?? { endpointSource: 'env' as const, endpoint: 'injected' };\n if (!endpoints.endpoint && !endpoints.tracesEndpoint && !endpoints.logsEndpoint && !allowFileFallback) {\n retryAfter = Date.now() + retryDelayMs;\n currentStatus = { ...defaultTelemetryStatus };\n return undefined;\n }\n const nextHandle = await createTelemetry({\n serviceName: options.serviceName,\n packageName: options.packageName,\n cwd: options.cwd,\n workspaceRoot: options.workspaceRoot,\n env: transportEnv,\n discoverEndpoint: resolvedEndpoints === undefined,\n resolvedEndpoints,\n enableLogs: options.enableLogs ?? true,\n enableTraces: options.enableTraces ?? true,\n headers: createTelemetryHeaders(options.serviceName, env),\n });\n if (shutdownRequested) {\n await nextHandle.shutdown().catch((error: unknown) => {\n reportWarning(`Po telemetry late initialization shutdown failed: ${warningDetail(error)}`);\n });\n return undefined;\n }\n if (nextHandle.backend === 'file' && !allowFileFallback) {\n await nextHandle\n .shutdown()\n .catch((error: unknown) => reportWarning(`Po telemetry fallback shutdown failed: ${warningDetail(error)}`));\n retryAfter = Date.now() + retryDelayMs;\n currentStatus = { ...defaultTelemetryStatus };\n return undefined;\n }\n if (discoveryFailureReported) reportWarning('Po telemetry endpoint discovery recovered');\n discoveryFailureReported = false;\n handle = nextHandle;\n currentStatus = {\n serviceName: options.serviceName,\n packageName: options.packageName,\n backend: nextHandle.backend,\n enabled: nextHandle.enabled,\n endpoint: nextHandle.endpoint,\n endpointSource: nextHandle.endpointSource,\n traces: Boolean(options.enableTraces ?? true),\n fileFallback: nextHandle.backend === 'file',\n };\n try {\n options.onStatus?.({ ...currentStatus });\n } catch (error) {\n reportWarning(`Po telemetry status observer failed: ${warningDetail(error)}`);\n }\n return nextHandle;\n };\n\n const getHandle = async (): Promise<PoTelemetryHandle | undefined> => {\n if (disabledByEnvironment() || shutdownRequested) return undefined;\n if (handle) return handle;\n if (Date.now() < retryAfter) return undefined;\n initialization ??= initialize()\n .catch((error: unknown) => {\n retryAfter = Date.now() + retryDelayMs;\n reportDiscoveryFailure(`Po telemetry initialization failed: ${warningDetail(error)}`);\n return undefined;\n })\n .finally(() => {\n initialization = undefined;\n });\n return initialization;\n };\n\n const emit = async (\n level: PoTelemetryEventLevel,\n event: string,\n error: unknown,\n attributes: Record<string, unknown> | undefined,\n errorOptions?: PoTelemetryErrorOptions,\n ): Promise<void> => {\n const safeEvent = normalizeToken(event, 'po.telemetry.event').slice(0, MAX_EVENT_NAME_LENGTH);\n const safeAttributes = sanitizeTelemetryAttributes({\n 'telemetry.package': options.packageName,\n ...attributes,\n ...(error === undefined ? {} : errorAttributes(error)),\n });\n if (error !== undefined) {\n const failureKey = `${safeEvent}:${level}:${JSON.stringify(safeAttributes)}`;\n if (reportedFailures.has(failureKey)) return;\n if (reportedFailures.size >= MAX_REPORTED_FAILURES) reportedFailures.clear();\n reportedFailures.add(failureKey);\n }\n const record: PoTelemetryRecord = { event: safeEvent, level, attributes: safeAttributes };\n publish(record);\n try {\n const nextHandle = await getHandle();\n nextHandle?.logger[level](safeEvent, {\n attributes: safeAttributes,\n ...(errorOptions?.includeException === true && error !== undefined ? { exception: error } : {}),\n });\n } catch (failure) {\n reportWarning(`Po telemetry record failed: ${warningDetail(failure)}`);\n }\n };\n\n const flush = async (): Promise<void> => {\n try {\n const pendingInitialization = initialization;\n if (pendingInitialization) await pendingInitialization;\n await handle?.flush();\n } catch (error) {\n reportWarning(`Po telemetry flush failed: ${warningDetail(error)}`);\n }\n };\n\n return {\n recordDebug(event, attributes) {\n return emit('debug', event, undefined, attributes);\n },\n recordEvent(event, attributes) {\n return emit('info', event, undefined, attributes);\n },\n recordWarning(event, error, attributes) {\n return emit('warn', event, error, attributes);\n },\n recordError(event, error, attributes, errorOptions) {\n return emit('error', event, error, attributes, errorOptions);\n },\n async runInSpan<T>(\n name: string,\n attributes: Record<string, unknown>,\n callback: (context?: PoTraceContext) => Promise<T> | T,\n parent?: PoTraceContext,\n ) {\n let callbackPromise: Promise<T> | undefined;\n let callbackFailure: { value: unknown } | undefined;\n const invokeCallback = (child?: PoTraceContext): Promise<T> => {\n callbackPromise ??= Promise.resolve().then(() => callback(child));\n return callbackPromise;\n };\n const nextHandle = await getHandle();\n if (!nextHandle) return invokeCallback();\n const startedAt = Date.now();\n try {\n const nextParentContext = parentContext(parent);\n const result = await nextHandle.runInSpan(\n normalizeToken(name, 'po.telemetry.span'),\n {\n attributes: sanitizeTelemetryAttributes(attributes),\n ...(nextParentContext ? { context: nextParentContext } : {}),\n },\n async (span) => {\n const child = childTraceContext(span);\n try {\n const result = await invokeCallback(child);\n span?.setAttribute('duration_ms', Date.now() - startedAt);\n span?.setAttribute('outcome', 'success');\n return result;\n } catch (error) {\n callbackFailure = { value: error };\n if (error instanceof OperationCancelledError) {\n span?.setAttribute('outcome', 'cancelled');\n span?.setAttribute('duration_ms', Date.now() - startedAt);\n // Do not throw through the exporter, which would create an error span.\n return undefined as T;\n }\n const safeError = errorAttributes(error);\n // The real cause stays in the local log; the exported span carries only its class and code.\n const detail = `Po telemetry span ${name} failed: ${warningDetail(error)}`;\n if (!reportedFailures.has(detail)) {\n if (reportedFailures.size >= MAX_REPORTED_FAILURES) reportedFailures.clear();\n reportedFailures.add(detail);\n reportWarning(detail);\n }\n for (const [key, value] of Object.entries(safeError)) span?.setAttribute(key, value);\n span?.setAttribute('duration_ms', Date.now() - startedAt);\n span?.setStatus({ code: SPAN_STATUS_ERROR });\n throw createSafeCallbackError(error);\n }\n },\n );\n if (callbackFailure) throw callbackFailure.value;\n return result;\n } catch (error) {\n if (callbackFailure) return Promise.reject(callbackFailure.value);\n if (callbackPromise) return callbackPromise;\n reportWarning(`Po telemetry span failed: ${warningDetail(error)}`);\n return invokeCallback();\n }\n },\n flush,\n async shutdown() {\n if (shutdownPromise) return shutdownPromise;\n shutdownRequested = true;\n shutdownPromise = (async () => {\n await flush();\n const currentHandle = handle;\n handle = undefined;\n if (!currentHandle) return;\n try {\n await currentHandle.shutdown();\n } catch (error) {\n reportWarning(`Po telemetry shutdown failed: ${warningDetail(error)}`);\n }\n })();\n return shutdownPromise;\n },\n status() {\n return { ...currentStatus };\n },\n };\n}\n"],"mappings":";;;AAgBA,IAAa,0BAAb,cAA6C,MAAM;CACjD,YAAY,SAAwB;EAClC,MAAM,+BAA+B,OAAO;EAC5C,KAAK,OAAO;CACd;AACF;AAEA,MAAM,yBAAyB;AAE/B,MAAM,gCAAgC;AACtC,MAAM,4BAA4B;AAClC,MAAM,2BAA2B;AACjC,MAAM,8BAA8B;AACpC,MAAM,wBAAwB;AAC9B,MAAM,wBAAwB;AAC9B,MAAM,qBAAqB,CAAC,oBAAoB,eAAe;AAC/D,MAAM,4BAA4B,CAAC,2BAA2B,yBAAyB;AACvF,MAAM,4BAA4B,CAAC,iBAAiB,yBAAyB;AAC7E,MAAM,8BAAc,IAAI,IAAI;CAAC;CAAK;CAAQ;AAAK,CAAC;AAChD,MAAM,oBAAoB;AAC1B,MAAM,sBAAsB;AAC5B,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,mCAAmB,IAAI,IAAI;CAC/B;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,0CAA0B,IAAI,IAAI;CACtC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,kCAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,wBAAwB;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,kCAAkB,IAAI,IAAyC;AAErE,SAAgB,0BAA0B,UAA2D;CACnG,gBAAgB,IAAI,QAAQ;CAC5B,aAAa,gBAAgB,OAAO,QAAQ;AAC9C;AAEA,SAAS,SAAS,OAAoC;CACpD,OAAO,UAAU,KAAA,KAAa,YAAY,IAAI,MAAM,YAAY,CAAC;AACnE;AAEA,SAAS,eAAe,OAAe,UAA0B;CAE/D,OADmB,MAAM,QAAQ,qBAAqB,GAAG,CAAC,CAAC,MAAM,GAAG,2BACpD,KAAK;AACvB;AAEA,S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,iBAAiB,IAAI,MAAM;OAC3B,cAAc,MAAM;MACtB;MACA,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,SAAS,GAAG,MAAM,aAAa,KAAK,KAAK;MACnF,MAAM,aAAa,eAAe,KAAK,IAAI,IAAI,SAAS;MACxD,MAAM,UAAU,EAAE,MAAM,kBAAkB,CAAC;MAC3C,MAAM,wBAAwB,KAAK;KACrC;IACF,CACF;IACA,IAAI,iBAAiB,MAAM,gBAAgB;IAC3C,OAAO;GACT,SAAS,OAAO;IACd,IAAI,iBAAiB,OAAO,QAAQ,OAAO,gBAAgB,KAAK;IAChE,IAAI,iBAAiB,OAAO;IAC5B,cAAc,6BAA6B,cAAc,KAAK,GAAG;IACjE,OAAO,eAAe;GACxB;EACF;EACA;EACA,MAAM,WAAW;GACf,IAAI,iBAAiB,OAAO;GAC5B,oBAAoB;GACpB,mBAAmB,YAAY;IAC7B,MAAM,MAAM;IACZ,MAAM,gBAAgB;IACtB,SAAS,KAAA;IACT,IAAI,CAAC,eAAe;IACpB,IAAI;KACF,MAAM,cAAc,SAAS;IAC/B,SAAS,OAAO;KACd,cAAc,iCAAiC,cAAc,KAAK,GAAG;IACvE;GACF,EAAA,CAAG;GACH,OAAO;EACT;EACA,SAAS;GACP,OAAO,EAAE,GAAG,cAAc;EAC5B;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../src/services/telemetry/index.ts"],"sourcesContent":["import { context, isSpanContextValid, trace, type Context, type Span } from '@opentelemetry/api';\n\nimport type {\n PoTelemetry,\n PoTelemetryAttributes,\n PoTelemetryErrorOptions,\n PoTelemetryEventLevel,\n PoTelemetryHandle,\n PoTelemetryOptions,\n PoTelemetryRecord,\n PoTelemetryRuntimeLoader,\n PoTelemetryStatus,\n PoTraceContext,\n} from '../../types/telemetry';\n\n/** Only the operation owning an aborted signal may classify its rejection as cancellation. */\nexport class OperationCancelledError extends Error {\n constructor(options?: ErrorOptions) {\n super('The operation was cancelled', options);\n this.name = 'OperationCancelledError';\n }\n}\n\nconst DEFAULT_RETRY_DELAY_MS = 1_000;\n// A wedged collector `/health` must not hold every span and event behind it.\nconst ENDPOINT_DISCOVERY_TIMEOUT_MS = 2_000;\nconst MAX_WARNING_DETAIL_LENGTH = 512;\nconst MAX_WARNING_DETAIL_DEPTH = 3;\nconst MAX_ATTRIBUTE_STRING_LENGTH = 128;\nconst MAX_REPORTED_FAILURES = 500;\nconst MAX_EVENT_NAME_LENGTH = 128;\nconst SESSION_ID_HEADERS = ['AGENT_SESSION_ID', 'PI_SESSION_ID'] as const;\nconst PARENT_SESSION_ID_HEADERS = ['AGENT_PARENT_SESSION_ID', 'PARENT_AGENT_SESSION_ID'] as const;\nconst TRANSPORT_SESSION_HEADERS = ['PI_SESSION_ID', 'AGENT_PARENT_SESSION_ID'] as const;\nconst TRUE_VALUES = new Set(['1', 'true', 'yes']);\nconst SPAN_STATUS_ERROR = 2;\nconst TRACEPARENT_PATTERN = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/u;\nconst SENSITIVE_ATTRIBUTE_PARTS = [\n 'prompt',\n 'message',\n 'content',\n 'payload',\n 'command',\n 'cwd',\n 'path',\n 'file',\n 'stack',\n 'traceback',\n 'transcript',\n 'diff',\n 'secret',\n 'authorization',\n 'header',\n 'environment',\n 'env',\n 'details',\n 'args',\n] as const;\nconst SAFE_RESULT_KEYS = new Set([\n 'tool.result.error',\n 'tool.result.count',\n 'tool.result.bytes',\n 'tool.result.duration_ms',\n]);\nconst SAFE_METADATA_KEY_PARTS = new Set([\n 'count',\n 'length',\n 'bytes',\n 'duration',\n 'duration_ms',\n 'size',\n 'index',\n 'number',\n 'active',\n 'enabled',\n 'previous',\n 'empty',\n 'silent',\n 'fallback',\n 'bypass',\n 'success',\n 'is_error',\n 'has_ui',\n 'requires_confirmation',\n 'exit_code',\n 'status_code',\n 'interval_seconds',\n 'concurrency',\n 'budget',\n]);\nconst SAFE_INPUT_KEYS = new Set([\n 'gen_ai.usage.input_tokens',\n 'gen_ai.usage.output_tokens',\n 'gen_ai.usage.total_tokens',\n 'gen_ai.usage.cache_read_tokens',\n 'gen_ai.usage.cache_write_tokens',\n 'gen_ai.usage.reasoning_tokens',\n]);\nconst SAFE_IDENTIFIER_KEY_PARTS = [\n 'id',\n 'correlation',\n 'session',\n 'trace',\n 'span',\n 'call',\n 'run',\n 'job',\n 'step',\n] as const;\nconst SAFE_STRING_KEY_PARTS = [\n 'name',\n 'operation',\n 'outcome',\n 'reason',\n 'status',\n 'mode',\n 'source',\n 'phase',\n 'engine',\n 'provider',\n 'model',\n 'level',\n 'type',\n 'code',\n 'signal',\n 'finish_reasons',\n 'trigger',\n 'action',\n 'kind',\n 'version',\n 'scope',\n 'layer',\n 'profile',\n 'domain',\n 'theme',\n 'leader',\n 'pass',\n 'role',\n 'stage',\n 'state',\n 'language',\n 'transport',\n 'adapter',\n 'runtime',\n 'backend',\n 'launcher',\n 'event',\n 'component',\n 'package',\n 'command_name',\n 'tool_name',\n 'token_attribution',\n] as const;\n\nconst recordObservers = new Set<(record: PoTelemetryRecord) => void>();\n\nexport function subscribeTelemetryRecords(observer: (record: PoTelemetryRecord) => void): () => void {\n recordObservers.add(observer);\n return () => recordObservers.delete(observer);\n}\n\nfunction isTruthy(value: string | undefined): boolean {\n return value !== undefined && TRUE_VALUES.has(value.toLowerCase());\n}\n\nfunction normalizeToken(value: string, fallback: string): string {\n const normalized = value.replace(/[^a-zA-Z0-9._:-]/g, '_').slice(0, MAX_ATTRIBUTE_STRING_LENGTH);\n return normalized || fallback;\n}\n\nfunction hashIdentifier(value: string): string {\n let hash = 2166136261;\n for (let index = 0; index < value.length; index += 1) {\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, 16777619);\n }\n return `id_${(hash >>> 0).toString(16).padStart(8, '0')}`;\n}\n\nfunction isSafeMetadataKey(key: string): boolean {\n const normalized = key.toLowerCase();\n return [...SAFE_METADATA_KEY_PARTS].some(\n (part) => normalized === part || normalized.endsWith(`.${part}`) || normalized.endsWith(`_${part}`),\n );\n}\n\nfunction isSensitiveKey(key: string): boolean {\n const normalized = key.toLowerCase();\n if (SAFE_RESULT_KEYS.has(normalized) || SAFE_INPUT_KEYS.has(normalized) || isSafeMetadataKey(normalized))\n return false;\n return SENSITIVE_ATTRIBUTE_PARTS.some((part) => normalized.split(/[._-]/u).includes(part));\n}\n\nfunction hasSafeStringMeaning(key: string): boolean {\n const normalized = key.toLowerCase();\n return SAFE_STRING_KEY_PARTS.some(\n (part) => normalized === part || normalized.endsWith(`.${part}`) || normalized.endsWith(`_${part}`),\n );\n}\n\nfunction hasSafeIdentifierMeaning(key: string): boolean {\n const normalized = key.toLowerCase();\n return SAFE_IDENTIFIER_KEY_PARTS.some(\n (part) => normalized === part || normalized.endsWith(`.${part}`) || normalized.endsWith(`_${part}`),\n );\n}\n\nfunction isScalar(value: unknown): value is string | number | boolean {\n return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean';\n}\n\nfunction sanitizeValue(key: string, value: string | number | boolean): string | number | boolean | undefined {\n if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;\n if (typeof value === 'boolean') return value;\n if (value.length === 0 || value.length > MAX_ATTRIBUTE_STRING_LENGTH) return undefined;\n if (hasSafeIdentifierMeaning(key)) return hashIdentifier(value);\n if (!hasSafeStringMeaning(key)) return undefined;\n if (key === 'telemetry.package' || key.endsWith('.package')) {\n if (value.startsWith('/') || value.includes('\\\\')) return undefined;\n return value.replace(/[^a-zA-Z0-9@/._:-]/g, '_');\n }\n return normalizeToken(value, 'unknown');\n}\n\nexport function sanitizeTelemetryAttributes(attributes: Record<string, unknown> = {}): PoTelemetryAttributes {\n const sanitized: PoTelemetryAttributes = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (isSensitiveKey(key) || !isScalar(value)) continue;\n const safeValue = sanitizeValue(key, value);\n if (safeValue !== undefined) sanitized[key] = safeValue;\n }\n return sanitized;\n}\n\nfunction safeErrorToken(value: string, fallback: string): string {\n if (!/^[a-zA-Z][a-zA-Z0-9._:-]{0,63}$/u.test(value)) return fallback;\n return normalizeToken(value, fallback);\n}\n\nfunction errorType(error: unknown): string {\n // A subclass that keeps the default name still exports its class, never its message.\n if (error instanceof Error)\n return safeErrorToken(error.name === 'Error' ? error.constructor.name : error.name, 'Error');\n if (typeof error === 'string') return 'StringError';\n if (error && typeof error === 'object') return 'ObjectError';\n return 'UnknownError';\n}\n\n/**\n * Format an error for a local diagnostic warning.\n *\n * Deliberately separate from errorType: that produces a redacted token for the\n * exported `error.type` attribute and must stay metadata-only, whereas warnings\n * go to the local operator and are useless without the actual cause. Arrays are\n * unwrapped because OpenTelemetry's forceFlush rejects with one.\n */\nfunction describeError(error: unknown, depth = 0): string {\n if (depth > MAX_WARNING_DETAIL_DEPTH) return '...';\n if (Array.isArray(error)) return error.map((entry) => describeError(entry, depth + 1)).join('; ');\n if (error instanceof Error) {\n const rawCode = 'code' in error ? (error as { code?: unknown }).code : undefined;\n const code = typeof rawCode === 'string' || typeof rawCode === 'number' ? ` (code ${rawCode})` : '';\n const aggregate = error instanceof AggregateError ? `: ${describeError(error.errors, depth + 1)}` : '';\n const cause = error.cause === undefined ? '' : ` <- caused by ${describeError(error.cause, depth + 1)}`;\n return `${error.name}: ${error.message}${code}${aggregate}${cause}`;\n }\n if (typeof error === 'string') return error;\n if (error && typeof error === 'object') {\n try {\n return JSON.stringify(error);\n } catch {\n return 'ObjectError';\n }\n }\n return String(error);\n}\n\nfunction warningDetail(error: unknown): string {\n return describeError(error).slice(0, MAX_WARNING_DETAIL_LENGTH);\n}\n\nfunction errorCode(error: unknown): string | undefined {\n if (!error || typeof error !== 'object' || !('code' in error)) return undefined;\n const code = (error as { code?: unknown }).code;\n if (typeof code !== 'string' && typeof code !== 'number') return undefined;\n const normalized = String(code);\n return /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,63}$/u.test(normalized) ? normalizeToken(normalized, 'unknown') : undefined;\n}\n\nfunction errorAttributes(error: unknown): PoTelemetryAttributes {\n const attributes: PoTelemetryAttributes = {\n 'error.type': errorType(error),\n outcome: 'error',\n };\n const code = errorCode(error);\n if (code) attributes['error.code'] = code;\n return attributes;\n}\n\nfunction firstEnvironmentValue(env: NodeJS.ProcessEnv, keys: readonly string[]): string | undefined {\n for (const key of keys) {\n const value = env[key]?.trim();\n if (value) return value;\n }\n return undefined;\n}\n\nexport function createTelemetryHeaders(serviceName: string, env: NodeJS.ProcessEnv): Record<string, string> {\n const headers: Record<string, string> = { 'x-agent': normalizeToken(serviceName, 'po') };\n const sessionId = firstEnvironmentValue(env, SESSION_ID_HEADERS);\n const parentSessionId = firstEnvironmentValue(env, PARENT_SESSION_ID_HEADERS);\n if (sessionId) headers['x-agent-session-id'] = hashIdentifier(sessionId);\n if (parentSessionId) headers['x-agent-parent-session-id'] = hashIdentifier(parentSessionId);\n return headers;\n}\n\n/** The session on every exported record lets the Node runtime share one exporter per service. */\nfunction sessionAttributes(env: NodeJS.ProcessEnv): PoTelemetryAttributes {\n const attributes: PoTelemetryAttributes = {};\n const sessionId = firstEnvironmentValue(env, SESSION_ID_HEADERS);\n const parentSessionId = firstEnvironmentValue(env, PARENT_SESSION_ID_HEADERS);\n if (sessionId) attributes['agent.session.id'] = hashIdentifier(sessionId);\n if (parentSessionId) attributes['agent.parent_session.id'] = hashIdentifier(parentSessionId);\n return attributes;\n}\n\nfunction createTransportEnvironment(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const transportEnv = { ...env };\n const sessionId = firstEnvironmentValue(env, SESSION_ID_HEADERS);\n const parentSessionId = firstEnvironmentValue(env, PARENT_SESSION_ID_HEADERS);\n if (sessionId) transportEnv.AGENT_SESSION_ID = hashIdentifier(sessionId);\n else delete transportEnv.AGENT_SESSION_ID;\n if (parentSessionId) transportEnv.PARENT_AGENT_SESSION_ID = hashIdentifier(parentSessionId);\n else delete transportEnv.PARENT_AGENT_SESSION_ID;\n for (const key of TRANSPORT_SESSION_HEADERS) delete transportEnv[key];\n for (const key of Object.keys(transportEnv)) {\n if (key.startsWith('WORKFLOW_')) delete transportEnv[key];\n }\n return transportEnv;\n}\n\nfunction defaultStatus(options: PoTelemetryOptions): PoTelemetryStatus {\n return {\n serviceName: options.serviceName,\n packageName: options.packageName,\n backend: 'disabled',\n enabled: false,\n endpointSource: 'none',\n traces: false,\n fileFallback: false,\n };\n}\n\nfunction createSafeCallbackError(error: unknown): Error {\n const code = errorCode(error);\n return new Error(`Po telemetry callback failed: ${errorType(error)}${code ? ` (${code})` : ''}`);\n}\n\nfunction parentContext(parent: PoTraceContext | undefined): Context | undefined {\n if (!parent) return undefined;\n const match = TRACEPARENT_PATTERN.exec(parent.traceparent);\n if (!match) return undefined;\n const [, traceId, spanId, traceFlags] = match;\n if (!traceId || !spanId || !traceFlags) return undefined;\n const spanContext = { traceId, spanId, traceFlags: Number.parseInt(traceFlags, 16), isRemote: true };\n return isSpanContextValid(spanContext) ? trace.setSpanContext(context.active(), spanContext) : undefined;\n}\n\nfunction childTraceContext(span: Span | undefined): PoTraceContext | undefined {\n if (!span) return undefined;\n const spanContext = span.spanContext();\n if (!isSpanContextValid(spanContext)) return undefined;\n const traceFlags = spanContext.traceFlags.toString(16).padStart(2, '0');\n return { traceparent: `00-${spanContext.traceId}-${spanContext.spanId}-${traceFlags}` };\n}\nexport function createPoTelemetryService(\n options: PoTelemetryOptions,\n runtimeLoader?: PoTelemetryRuntimeLoader,\n): PoTelemetry {\n const env = { ...options.env };\n const telemetryFactory = options.telemetryFactory;\n const endpointResolver = options.endpointResolver;\n const transportEnv = createTransportEnvironment(env);\n const session = sessionAttributes(env);\n const warn = options.warn ?? ((message: string) => console.warn(message));\n const reportWarning = (message: string): void => {\n try {\n warn(message);\n } catch (error) {\n console.warn(`Po telemetry warning callback failed: ${warningDetail(error)}`);\n }\n };\n const retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;\n const allowFileFallback = options.allowFileFallback ?? isTruthy(env.LOG_SINK_PI_FILE_FALLBACK);\n const defaultTelemetryStatus = defaultStatus(options);\n let currentStatus = defaultTelemetryStatus;\n let handle: PoTelemetryHandle | undefined;\n let initialization: Promise<PoTelemetryHandle | undefined> | undefined;\n let retryAfter = 0;\n let discoveryFailureReported = false;\n const reportDiscoveryFailure = (message: string): void => {\n if (!discoveryFailureReported) reportWarning(message);\n discoveryFailureReported = true;\n };\n let shutdownPromise: Promise<void> | undefined;\n let shutdownRequested = false;\n const reportedFailures = new Set<string>();\n\n const disabledByEnvironment = (): boolean =>\n isTruthy(env.AGENT_TELEMETRY_DISABLED) || isTruthy(env.OTEL_SDK_DISABLED);\n\n const publish = (record: PoTelemetryRecord): void => {\n for (const observer of [...recordObservers, ...(options.onRecord ? [options.onRecord] : [])]) {\n try {\n observer(record);\n } catch (error) {\n reportWarning(`Po telemetry observer failed: ${warningDetail(error)}`);\n }\n }\n };\n\n const initialize = async (): Promise<PoTelemetryHandle | undefined> => {\n if (disabledByEnvironment() || shutdownRequested) return undefined;\n const defaults = telemetryFactory ? undefined : await runtimeLoader?.();\n const resolveEndpoints = endpointResolver ?? defaults?.resolveNodeTelemetryEndpoints;\n const createTelemetry = telemetryFactory ?? defaults?.createNodeTelemetry;\n if ((!resolveEndpoints && !telemetryFactory) || !createTelemetry)\n throw new Error('Node telemetry runtime is unavailable.');\n let discoveryTimer: ReturnType<typeof setTimeout> | undefined;\n const discoveryTimedOut = Symbol('discoveryTimedOut');\n const resolvedEndpoints =\n resolveEndpoints === undefined\n ? undefined\n : await Promise.race([\n resolveEndpoints({\n cwd: options.cwd,\n env,\n packageName: options.packageName,\n serviceName: options.serviceName,\n workspaceRoot: options.workspaceRoot,\n discoverEndpoint: true,\n healthCheck: true,\n }),\n new Promise<typeof discoveryTimedOut>((resolve) => {\n discoveryTimer = setTimeout(() => resolve(discoveryTimedOut), ENDPOINT_DISCOVERY_TIMEOUT_MS);\n }),\n ]).finally(() => clearTimeout(discoveryTimer));\n if (resolvedEndpoints === discoveryTimedOut) {\n reportDiscoveryFailure(\n `Po telemetry endpoint discovery timed out after ${ENDPOINT_DISCOVERY_TIMEOUT_MS} ms; retrying`,\n );\n retryAfter = Date.now() + retryDelayMs;\n currentStatus = { ...defaultTelemetryStatus };\n return undefined;\n }\n const endpoints = resolvedEndpoints ?? { endpointSource: 'env' as const, endpoint: 'injected' };\n if (!endpoints.endpoint && !endpoints.tracesEndpoint && !endpoints.logsEndpoint && !allowFileFallback) {\n retryAfter = Date.now() + retryDelayMs;\n currentStatus = { ...defaultTelemetryStatus };\n return undefined;\n }\n const nextHandle = await createTelemetry({\n serviceName: options.serviceName,\n packageName: options.packageName,\n cwd: options.cwd,\n workspaceRoot: options.workspaceRoot,\n env: transportEnv,\n discoverEndpoint: resolvedEndpoints === undefined,\n resolvedEndpoints,\n enableLogs: options.enableLogs ?? true,\n enableTraces: options.enableTraces ?? true,\n headers: createTelemetryHeaders(options.serviceName, env),\n });\n if (shutdownRequested) {\n await nextHandle.shutdown().catch((error: unknown) => {\n reportWarning(`Po telemetry late initialization shutdown failed: ${warningDetail(error)}`);\n });\n return undefined;\n }\n if (nextHandle.backend === 'file' && !allowFileFallback) {\n await nextHandle\n .shutdown()\n .catch((error: unknown) => reportWarning(`Po telemetry fallback shutdown failed: ${warningDetail(error)}`));\n retryAfter = Date.now() + retryDelayMs;\n currentStatus = { ...defaultTelemetryStatus };\n return undefined;\n }\n if (discoveryFailureReported) reportWarning('Po telemetry endpoint discovery recovered');\n discoveryFailureReported = false;\n handle = nextHandle;\n currentStatus = {\n serviceName: options.serviceName,\n packageName: options.packageName,\n backend: nextHandle.backend,\n enabled: nextHandle.enabled,\n endpoint: nextHandle.endpoint,\n endpointSource: nextHandle.endpointSource,\n traces: Boolean(options.enableTraces ?? true),\n fileFallback: nextHandle.backend === 'file',\n };\n try {\n options.onStatus?.({ ...currentStatus });\n } catch (error) {\n reportWarning(`Po telemetry status observer failed: ${warningDetail(error)}`);\n }\n return nextHandle;\n };\n\n const getHandle = async (): Promise<PoTelemetryHandle | undefined> => {\n if (disabledByEnvironment() || shutdownRequested) return undefined;\n if (handle) return handle;\n if (Date.now() < retryAfter) return undefined;\n initialization ??= initialize()\n .catch((error: unknown) => {\n retryAfter = Date.now() + retryDelayMs;\n reportDiscoveryFailure(`Po telemetry initialization failed: ${warningDetail(error)}`);\n return undefined;\n })\n .finally(() => {\n initialization = undefined;\n });\n return initialization;\n };\n\n const emit = async (\n level: PoTelemetryEventLevel,\n event: string,\n error: unknown,\n attributes: Record<string, unknown> | undefined,\n errorOptions?: PoTelemetryErrorOptions,\n ): Promise<void> => {\n const safeEvent = normalizeToken(event, 'po.telemetry.event').slice(0, MAX_EVENT_NAME_LENGTH);\n const safeAttributes = sanitizeTelemetryAttributes({\n 'telemetry.package': options.packageName,\n ...attributes,\n ...(error === undefined ? {} : errorAttributes(error)),\n });\n if (error !== undefined) {\n const failureKey = `${safeEvent}:${level}:${JSON.stringify(safeAttributes)}`;\n if (reportedFailures.has(failureKey)) return;\n if (reportedFailures.size >= MAX_REPORTED_FAILURES) reportedFailures.clear();\n reportedFailures.add(failureKey);\n }\n const record: PoTelemetryRecord = { event: safeEvent, level, attributes: safeAttributes };\n publish(record);\n try {\n const nextHandle = await getHandle();\n nextHandle?.logger[level](safeEvent, {\n attributes: { ...session, ...safeAttributes },\n ...(errorOptions?.includeException === true && error !== undefined ? { exception: error } : {}),\n });\n } catch (failure) {\n reportWarning(`Po telemetry record failed: ${warningDetail(failure)}`);\n }\n };\n\n const flush = async (): Promise<void> => {\n try {\n const pendingInitialization = initialization;\n if (pendingInitialization) await pendingInitialization;\n await handle?.flush();\n } catch (error) {\n reportWarning(`Po telemetry flush failed: ${warningDetail(error)}`);\n }\n };\n\n return {\n recordDebug(event, attributes) {\n return emit('debug', event, undefined, attributes);\n },\n recordEvent(event, attributes) {\n return emit('info', event, undefined, attributes);\n },\n recordWarning(event, error, attributes) {\n return emit('warn', event, error, attributes);\n },\n recordError(event, error, attributes, errorOptions) {\n return emit('error', event, error, attributes, errorOptions);\n },\n async runInSpan<T>(\n name: string,\n attributes: Record<string, unknown>,\n callback: (context?: PoTraceContext) => Promise<T> | T,\n parent?: PoTraceContext,\n ) {\n let callbackPromise: Promise<T> | undefined;\n let callbackFailure: { value: unknown } | undefined;\n const invokeCallback = (child?: PoTraceContext): Promise<T> => {\n callbackPromise ??= Promise.resolve().then(() => callback(child));\n return callbackPromise;\n };\n const nextHandle = await getHandle();\n if (!nextHandle) return invokeCallback();\n const startedAt = Date.now();\n try {\n const nextParentContext = parentContext(parent);\n const result = await nextHandle.runInSpan(\n normalizeToken(name, 'po.telemetry.span'),\n {\n attributes: { ...session, ...sanitizeTelemetryAttributes(attributes) },\n ...(nextParentContext ? { context: nextParentContext } : {}),\n },\n async (span) => {\n const child = childTraceContext(span);\n try {\n const result = await invokeCallback(child);\n span?.setAttribute('duration_ms', Date.now() - startedAt);\n span?.setAttribute('outcome', 'success');\n return result;\n } catch (error) {\n callbackFailure = { value: error };\n if (error instanceof OperationCancelledError) {\n span?.setAttribute('outcome', 'cancelled');\n span?.setAttribute('duration_ms', Date.now() - startedAt);\n // Do not throw through the exporter, which would create an error span.\n return undefined as T;\n }\n const safeError = errorAttributes(error);\n // The real cause stays in the local log; the exported span carries only its class and code.\n const detail = `Po telemetry span ${name} failed: ${warningDetail(error)}`;\n if (!reportedFailures.has(detail)) {\n if (reportedFailures.size >= MAX_REPORTED_FAILURES) reportedFailures.clear();\n reportedFailures.add(detail);\n reportWarning(detail);\n }\n for (const [key, value] of Object.entries(safeError)) span?.setAttribute(key, value);\n span?.setAttribute('duration_ms', Date.now() - startedAt);\n span?.setStatus({ code: SPAN_STATUS_ERROR });\n throw createSafeCallbackError(error);\n }\n },\n );\n if (callbackFailure) throw callbackFailure.value;\n return result;\n } catch (error) {\n if (callbackFailure) return Promise.reject(callbackFailure.value);\n if (callbackPromise) return callbackPromise;\n reportWarning(`Po telemetry span failed: ${warningDetail(error)}`);\n return invokeCallback();\n }\n },\n flush,\n async shutdown() {\n if (shutdownPromise) return shutdownPromise;\n shutdownRequested = true;\n shutdownPromise = (async () => {\n await flush();\n const currentHandle = handle;\n handle = undefined;\n if (!currentHandle) return;\n try {\n await currentHandle.shutdown();\n } catch (error) {\n reportWarning(`Po telemetry shutdown failed: ${warningDetail(error)}`);\n }\n })();\n return shutdownPromise;\n },\n status() {\n return { ...currentStatus };\n },\n };\n}\n"],"mappings":";;;AAgBA,IAAa,0BAAb,cAA6C,MAAM;CACjD,YAAY,SAAwB;EAClC,MAAM,+BAA+B,OAAO;EAC5C,KAAK,OAAO;CACd;AACF;AAEA,MAAM,yBAAyB;AAE/B,MAAM,gCAAgC;AACtC,MAAM,4BAA4B;AAClC,MAAM,2BAA2B;AACjC,MAAM,8BAA8B;AACpC,MAAM,wBAAwB;AAC9B,MAAM,wBAAwB;AAC9B,MAAM,qBAAqB,CAAC,oBAAoB,eAAe;AAC/D,MAAM,4BAA4B,CAAC,2BAA2B,yBAAyB;AACvF,MAAM,4BAA4B,CAAC,iBAAiB,yBAAyB;AAC7E,MAAM,8BAAc,IAAI,IAAI;CAAC;CAAK;CAAQ;AAAK,CAAC;AAChD,MAAM,oBAAoB;AAC1B,MAAM,sBAAsB;AAC5B,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,mCAAmB,IAAI,IAAI;CAC/B;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,0CAA0B,IAAI,IAAI;CACtC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,kCAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,M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,SAAS,OAAO;IACd,IAAI,iBAAiB,OAAO,QAAQ,OAAO,gBAAgB,KAAK;IAChE,IAAI,iBAAiB,OAAO;IAC5B,cAAc,6BAA6B,cAAc,KAAK,GAAG;IACjE,OAAO,eAAe;GACxB;EACF;EACA;EACA,MAAM,WAAW;GACf,IAAI,iBAAiB,OAAO;GAC5B,oBAAoB;GACpB,mBAAmB,YAAY;IAC7B,MAAM,MAAM;IACZ,MAAM,gBAAgB;IACtB,SAAS,KAAA;IACT,IAAI,CAAC,eAAe;IACpB,IAAI;KACF,MAAM,cAAc,SAAS;IAC/B,SAAS,OAAO;KACd,cAAc,iCAAiC,cAAc,KAAK,GAAG;IACvE;GACF,EAAA,CAAG;GACH,OAAO;EACT;EACA,SAAS;GACP,OAAO,EAAE,GAAG,cAAc;EAC5B;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agimon-ai/po-core",
|
|
3
|
-
"version": "0.0.0-alpha.
|
|
3
|
+
"version": "0.0.0-alpha.48",
|
|
4
4
|
"description": "Po runtime systems and reusable core services.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -559,8 +559,8 @@
|
|
|
559
559
|
"registry": "https://registry.npmjs.org/"
|
|
560
560
|
},
|
|
561
561
|
"dependencies": {
|
|
562
|
-
"@agimon-ai/po-logsink": "0.0.1-alpha.
|
|
563
|
-
"@agimon-ai/po-web-security": "0.0.0-alpha.
|
|
562
|
+
"@agimon-ai/po-logsink": "0.0.1-alpha.30",
|
|
563
|
+
"@agimon-ai/po-web-security": "0.0.0-alpha.48",
|
|
564
564
|
"@deepseek-ai/cordis": "4.0.5",
|
|
565
565
|
"@earendil-works/chord": "1.4.0",
|
|
566
566
|
"@earendil-works/pi-agent-core": "1.4.0",
|
|
@@ -584,7 +584,7 @@
|
|
|
584
584
|
"yaml": "2.9.1"
|
|
585
585
|
},
|
|
586
586
|
"devDependencies": {
|
|
587
|
-
"@agimon-ai/vibe-lint-plugin-po-core": "0.0.0-alpha.
|
|
587
|
+
"@agimon-ai/vibe-lint-plugin-po-core": "0.0.0-alpha.48",
|
|
588
588
|
"@apidevtools/swagger-parser": "^13.1.0",
|
|
589
589
|
"@asyncapi/parser": "^3.6.4",
|
|
590
590
|
"@earendil-works/pi-ai": "1.4.0",
|