agent-trace-support.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. import {
  2. context,
  3. createContextKey,
  4. createTraceState,
  5. ROOT_CONTEXT,
  6. SpanStatusCode,
  7. trace,
  8. type Attributes,
  9. type Context,
  10. type Span,
  11. type SpanContext,
  12. } from "@opentelemetry/api";
  13. import type {
  14. AgentTelemetryAbandonReason,
  15. AgentTelemetryCausation,
  16. AgentTelemetryExecutionContext,
  17. AgentTelemetryScope,
  18. } from "@zcode/contracts/telemetry";
  19. import { claimSanitizedTelemetryError } from "./error-sanitizer.js";
  20. const ACTIVE_WRITER_CONTEXT_KEY = createContextKey("@zcode/telemetry/active-writer-v4");
  21. const SAFE_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/u;
  22. const SAFE_ENUM_PATTERN = /^[a-z0-9_./:-]{1,128}$/u;
  23. const SAFE_IDENTIFIER_PATTERN = /^[A-Za-z0-9._:/-]{1,128}$/u;
  24. export interface ActiveWriterContext {
  25. activeContext: Context;
  26. correlation?: AgentTelemetryExecutionContext;
  27. parent?: ActiveWriterContext;
  28. span: Span;
  29. spanName: string;
  30. toolCallId?: string;
  31. }
  32. export interface WriterHealth {
  33. onWarning?: (message: string, context: Record<string, unknown>) => void;
  34. }
  35. export interface WriterLifecycleKeys {
  36. abandonReason: string;
  37. cancelReason: string;
  38. errorCategory: string;
  39. errorCode: string;
  40. errorMessage: string;
  41. errorType: string;
  42. failureStage: string;
  43. outcome: string;
  44. }
  45. export interface WriterTerminalObservation {
  46. abandonReason?: string;
  47. errorCategory?: string;
  48. }
  49. export abstract class BaseSpanWriter implements AgentTelemetryScope {
  50. private ended = false;
  51. private readonly startedAtMs = monotonicNowMs();
  52. readonly state: ActiveWriterContext;
  53. protected constructor(
  54. span: Span,
  55. parentContext: Context,
  56. metadata: Omit<ActiveWriterContext, "activeContext" | "span">,
  57. private readonly lifecycle: WriterLifecycleKeys,
  58. private readonly health: WriterHealth,
  59. private readonly onTerminal?: (
  60. outcome: string,
  61. durationMs: number,
  62. observation: WriterTerminalObservation,
  63. ) => void,
  64. ) {
  65. this.state = {
  66. ...metadata,
  67. activeContext: parentContext,
  68. span,
  69. };
  70. this.state.activeContext = trace
  71. .setSpan(parentContext, span)
  72. .setValue(ACTIVE_WRITER_CONTEXT_KEY, this.state);
  73. }
  74. captureCausation(): AgentTelemetryCausation | undefined {
  75. return causationFromState(this.state);
  76. }
  77. run<T>(execute: () => T): T {
  78. let entered = false;
  79. let businessReturned = false;
  80. let businessValue: T | undefined;
  81. let businessError: unknown;
  82. const invokeBusinessOnce = (): T => {
  83. if (entered) {
  84. if (businessReturned) return businessValue as T;
  85. throw businessError;
  86. }
  87. entered = true;
  88. try {
  89. businessValue = execute();
  90. businessReturned = true;
  91. return businessValue;
  92. } catch (error) {
  93. businessError = error;
  94. throw error;
  95. }
  96. };
  97. let value: T;
  98. try {
  99. value = context.with(this.state.activeContext, invokeBusinessOnce);
  100. } catch (error) {
  101. if (!entered) {
  102. this.warn("Telemetry context activation failed", error);
  103. value = invokeBusinessOnce();
  104. } else if (businessReturned) {
  105. // Bug 根因:观测 Context Manager 理论上不应在业务返回后抛错;若第三方实现违反
  106. // 契约,不能因此重跑或覆盖已经成功执行一次的业务回调。
  107. this.warn("Telemetry context teardown failed", error);
  108. value = businessValue as T;
  109. } else {
  110. this.finishThrownIfOpen(error);
  111. throw error;
  112. }
  113. }
  114. if (!isPromiseLike(value)) {
  115. this.finishAbandonedIfOpen("missing_terminal");
  116. return value;
  117. }
  118. return Promise.resolve(value).then(
  119. (result) => {
  120. this.finishAbandonedIfOpen("missing_terminal");
  121. return result;
  122. },
  123. (error: unknown) => {
  124. this.finishThrownIfOpen(error);
  125. throw error;
  126. },
  127. ) as T;
  128. }
  129. protected abstract finishUnhandled(error: unknown): void;
  130. protected addEvent(name: string, attributes?: Attributes): void {
  131. this.safe(() => this.state.span.addEvent(name, compactAttributes(attributes ?? {})));
  132. }
  133. protected elapsedMs(): number {
  134. return Math.max(0, monotonicNowMs() - this.startedAtMs);
  135. }
  136. protected finishAbandonedIfOpen(reason: AgentTelemetryAbandonReason): void {
  137. if (!this.claimTerminal()) return;
  138. this.setAttribute(this.lifecycle.outcome, "abandoned");
  139. this.setAttribute(this.lifecycle.abandonReason, reason);
  140. this.endSpan("abandoned", { abandonReason: reason });
  141. }
  142. protected finishCancelledIfOpen(reason: string): void {
  143. if (!this.claimTerminal()) return;
  144. this.setAttribute(this.lifecycle.outcome, "cancelled");
  145. this.setAttribute(this.lifecycle.cancelReason, safeEnum(reason));
  146. this.endSpan("cancelled");
  147. }
  148. protected finishCompletedIfOpen(extra?: () => void): void {
  149. if (!this.claimTerminal()) return;
  150. this.safe(extra);
  151. this.setAttribute(this.lifecycle.outcome, "completed");
  152. this.safe(() => this.state.span.setStatus({ code: SpanStatusCode.OK }));
  153. this.endSpan("completed");
  154. }
  155. protected finishDomainOutcomeIfOpen(outcome: string, extra?: () => void): void {
  156. if (!this.claimTerminal()) return;
  157. this.safe(extra);
  158. this.setAttribute(this.lifecycle.outcome, safeEnum(outcome));
  159. this.endSpan(outcome);
  160. }
  161. protected finishFailedIfOpen(stage: string, category: string, error?: unknown): void {
  162. if (!this.claimTerminal()) return;
  163. this.setAttribute(this.lifecycle.outcome, "failed");
  164. this.setAttribute(this.lifecycle.failureStage, safeEnum(stage));
  165. this.setAttribute(this.lifecycle.errorCategory, safeEnum(category));
  166. if (error !== undefined) this.recordSanitizedError(error);
  167. this.safe(() =>
  168. this.state.span.setStatus({
  169. code: SpanStatusCode.ERROR,
  170. }),
  171. );
  172. this.endSpan("failed", { errorCategory: safeEnum(category) });
  173. }
  174. protected isOpen(): boolean {
  175. return !this.ended;
  176. }
  177. protected recordSanitizedError(error: unknown): void {
  178. const sanitized = claimSanitizedTelemetryError(error);
  179. if (!sanitized) return;
  180. this.setAttribute(this.lifecycle.errorType, sanitized.type);
  181. this.setAttribute(this.lifecycle.errorCode, sanitized.code);
  182. this.setAttribute(this.lifecycle.errorMessage, sanitized.message);
  183. this.setAttribute("error.type", sanitized.type);
  184. this.setAttribute("error.message", sanitized.message);
  185. if (sanitized.cause) {
  186. this.setAttribute("error.cause.type", sanitized.cause.type);
  187. this.setAttribute("error.cause.code", sanitized.cause.code);
  188. this.setAttribute("error.cause.message", sanitized.cause.message);
  189. }
  190. }
  191. protected setAttribute(key: string, value: unknown): void {
  192. const normalized = normalizeAttributeValue(value);
  193. if (normalized === undefined) return;
  194. this.safe(() => this.state.span.setAttribute(key, normalized));
  195. }
  196. protected setAttributes(attributes: Record<string, unknown>): void {
  197. for (const [key, value] of Object.entries(attributes)) this.setAttribute(key, value);
  198. }
  199. protected safe(run: (() => void) | undefined): void {
  200. if (!run) return;
  201. try {
  202. run();
  203. } catch (error) {
  204. this.warn("Telemetry writer operation failed", error);
  205. }
  206. }
  207. private claimTerminal(): boolean {
  208. if (this.ended) return false;
  209. // 先关闭内存闩锁,再触碰任何 SDK/Adapter;即使后续抛错也不会重复终结。
  210. this.ended = true;
  211. return true;
  212. }
  213. private endSpan(outcome: string, observation: WriterTerminalObservation = {}): void {
  214. const durationMs = this.elapsedMs();
  215. this.safe(() => this.onTerminal?.(outcome, durationMs, observation));
  216. this.safe(() => this.state.span.end());
  217. }
  218. private finishThrownIfOpen(error: unknown): void {
  219. if (!this.isOpen()) return;
  220. this.finishUnhandled(error);
  221. }
  222. private warn(message: string, error: unknown): void {
  223. try {
  224. this.health.onWarning?.(message, {
  225. errorType: error instanceof Error ? error.name : typeof error,
  226. spanName: this.state.spanName,
  227. });
  228. } catch {
  229. // Telemetry 的健康回调也属于旁路,绝不能覆盖业务返回或异常。
  230. }
  231. }
  232. }
  233. export function activeWriterContext(): ActiveWriterContext | undefined {
  234. return context.active().getValue(ACTIVE_WRITER_CONTEXT_KEY) as ActiveWriterContext | undefined;
  235. }
  236. export function causationFromState(
  237. state: ActiveWriterContext | undefined,
  238. ): AgentTelemetryCausation | undefined {
  239. if (!state) return undefined;
  240. const spanContext = state.span.spanContext();
  241. if (!trace.isSpanContextValid(spanContext)) return undefined;
  242. return {
  243. isRemote: spanContext.isRemote ?? false,
  244. spanId: spanContext.spanId,
  245. traceFlags: spanContext.traceFlags,
  246. traceId: spanContext.traceId,
  247. ...(spanContext.traceState ? { traceState: spanContext.traceState.serialize() } : {}),
  248. sessionId: state.correlation?.sessionId,
  249. turnId: state.correlation?.turnId,
  250. toolCallId: state.toolCallId,
  251. };
  252. }
  253. export function contextFromCausation(causation: AgentTelemetryCausation): Context {
  254. // 显式 Causation 只传播保存下来的 SpanContext。不能以执行时碰巧活跃的 Context
  255. // 为底,否则会把另一个异步任务的 Baggage 或 ZCode Writer 私有状态夹带进来。
  256. return trace.setSpanContext(ROOT_CONTEXT, spanContextFromCausation(causation));
  257. }
  258. export function spanContextFromCausation(causation: AgentTelemetryCausation): SpanContext {
  259. return {
  260. isRemote: causation.isRemote,
  261. spanId: causation.spanId,
  262. traceFlags: causation.traceFlags,
  263. traceId: causation.traceId,
  264. ...(causation.traceState ? { traceState: createTraceState(causation.traceState) } : {}),
  265. };
  266. }
  267. export function compactAttributes(attributes: Attributes): Attributes {
  268. const compacted: Attributes = {};
  269. for (const [key, value] of Object.entries(attributes)) {
  270. const normalized = normalizeAttributeValue(value);
  271. if (normalized !== undefined) compacted[key] = normalized;
  272. }
  273. return compacted;
  274. }
  275. export function executionProjection(
  276. correlation: AgentTelemetryExecutionContext | undefined,
  277. options: {
  278. includeActor?: boolean;
  279. includeAgent?: boolean;
  280. includeIdentity?: boolean;
  281. includeQuery?: boolean;
  282. includeSession?: boolean;
  283. } = {},
  284. ): Record<string, unknown> {
  285. if (!correlation) return {};
  286. return {
  287. "zcode.execution.session_id": options.includeSession
  288. ? safeId(correlation.sessionId)
  289. : undefined,
  290. "zcode.execution.parent_session_id": options.includeSession
  291. ? safeId(correlation.parentSessionId)
  292. : undefined,
  293. "zcode.execution.turn_id": safeId(correlation.turnId),
  294. "zcode.execution.parent_turn_id": options.includeSession
  295. ? safeId(correlation.parentTurnId)
  296. : undefined,
  297. "zcode.execution.query_id": options.includeQuery ? safeId(correlation.queryId) : undefined,
  298. "zcode.execution.actor_kind": options.includeActor
  299. ? safeEnum(correlation.actorKind)
  300. : undefined,
  301. "zcode.execution.agent_name": options.includeAgent
  302. ? safeIdentifier(correlation.agentName)
  303. : undefined,
  304. "zcode.execution.identity_state": options.includeIdentity
  305. ? safeEnum(correlation.identityState)
  306. : undefined,
  307. "zcode.execution.user_subject_id": options.includeIdentity
  308. ? safeId(correlation.userSubjectId)
  309. : undefined,
  310. "zcode.execution.launch_surface": safeEnum(correlation.launchSurface),
  311. };
  312. }
  313. export function safeEnum(value: string | undefined): string | undefined {
  314. if (!value) return undefined;
  315. const normalized = value.trim().toLowerCase();
  316. return SAFE_ENUM_PATTERN.test(normalized) ? normalized : undefined;
  317. }
  318. export function safeId(value: string | undefined): string | undefined {
  319. const normalized = value?.trim();
  320. return normalized && SAFE_ID_PATTERN.test(normalized) ? normalized : undefined;
  321. }
  322. export function safeIdentifier(value: string | undefined): string | undefined {
  323. if (!value) return undefined;
  324. const normalized = value.trim().slice(0, 128);
  325. return SAFE_IDENTIFIER_PATTERN.test(normalized) ? normalized : undefined;
  326. }
  327. export function safeString(value: string | undefined, maxLength = 256): string | undefined {
  328. if (!value) return undefined;
  329. const normalized = value
  330. .replace(/\p{Cc}+/gu, " ")
  331. .replace(/\s+/gu, " ")
  332. .trim()
  333. .slice(0, maxLength);
  334. return normalized || undefined;
  335. }
  336. export function finiteNonNegative(value: number | undefined): number | undefined {
  337. return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
  338. }
  339. export function integer(value: number | undefined): number | undefined {
  340. return typeof value === "number" && Number.isSafeInteger(value) ? value : undefined;
  341. }
  342. export function isAbortLike(error: unknown): boolean {
  343. if (!(error instanceof Error)) return false;
  344. return (
  345. error.name === "AbortError" ||
  346. ("code" in error && (error as Error & { code?: unknown }).code === "ABORT_ERR")
  347. );
  348. }
  349. function normalizeAttributeValue(
  350. value: unknown,
  351. ): string | number | boolean | string[] | number[] | boolean[] | undefined {
  352. if (typeof value === "string") return safeString(value, 1_024);
  353. if (typeof value === "number") return Number.isFinite(value) ? value : undefined;
  354. if (typeof value === "boolean") return value;
  355. if (Array.isArray(value)) {
  356. const strings = value.filter((item): item is string => typeof item === "string");
  357. if (strings.length === value.length) return strings;
  358. const numbers = value.filter(
  359. (item): item is number => typeof item === "number" && Number.isFinite(item),
  360. );
  361. if (numbers.length === value.length) return numbers;
  362. const booleans = value.filter((item): item is boolean => typeof item === "boolean");
  363. if (booleans.length === value.length) return booleans;
  364. return undefined;
  365. }
  366. return undefined;
  367. }
  368. function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
  369. return (
  370. (typeof value === "object" || typeof value === "function") &&
  371. value !== null &&
  372. typeof (value as PromiseLike<unknown>).then === "function"
  373. );
  374. }
  375. function monotonicNowMs(): number {
  376. return Number(process.hrtime.bigint()) / 1_000_000;
  377. }