agent-trace-runtime.ts 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687
  1. import { recordRequestObservation } from "./request-security-edition/index.js";
  2. /* oxlint-disable eslint(max-lines) -- concrete Writer 在同一文件显式维护各自 canonical key,避免运行时 Schema/Registry 再造一层映射。 */
  3. import {
  4. context,
  5. ROOT_CONTEXT,
  6. SpanKind,
  7. trace,
  8. type Attributes,
  9. type Context,
  10. type Link,
  11. type Span,
  12. type Tracer,
  13. } from "@opentelemetry/api";
  14. import type {
  15. AgentExecutionTelemetryPort,
  16. AgentStepSpanWriter,
  17. AgentStepTraceStart,
  18. AgentTelemetryAbandonReason,
  19. AgentTelemetryCancellationReason,
  20. AgentTelemetryCausation,
  21. AgentTelemetryErrorCategory,
  22. AgentTelemetryExecutionContext,
  23. AgentTurnSpanWriter,
  24. AgentTurnTraceStart,
  25. CommandExecutionSpanWriter,
  26. CommandTraceStart,
  27. CompactionTraceStart,
  28. ContextCompactionSpanWriter,
  29. DetachedOperationSpanWriter,
  30. DetachedOperationTraceStart,
  31. ModelAttemptFailureStage,
  32. ModelAttemptSpanWriter,
  33. ModelAttemptTraceStart,
  34. ModelCallFailureStage,
  35. ModelCallSpanWriter,
  36. ModelCallTraceStart,
  37. ModelExecutionTelemetryPort,
  38. ModelFinishReason,
  39. ModelReasoningControlType,
  40. ModelReasoningState,
  41. ResponseModelTelemetryDescriptor,
  42. TelemetryIdentitySnapshot,
  43. ToolExecutionSpanWriter,
  44. ToolTraceStart,
  45. } from "@zcode/contracts/telemetry";
  46. import type { ModelRequestObservation } from "@zcode/contracts/model";
  47. import {
  48. activeWriterContext,
  49. BaseSpanWriter,
  50. compactAttributes,
  51. executionProjection,
  52. finiteNonNegative,
  53. integer,
  54. isAbortLike,
  55. safeEnum,
  56. safeId,
  57. safeIdentifier,
  58. safeString,
  59. contextFromCausation,
  60. spanContextFromCausation,
  61. type ActiveWriterContext,
  62. type WriterHealth,
  63. type WriterLifecycleKeys,
  64. type WriterTerminalObservation,
  65. } from "./agent-trace-support.js";
  66. import {
  67. NOOP_AGENT_TELEMETRY_METRICS,
  68. type AgentMetricSpanName,
  69. type AgentTelemetryMetricRecorder,
  70. type ModelTokenType,
  71. } from "./agent-metrics.js";
  72. import {
  73. commandCompatibilityAttributes,
  74. httpResponseCompatibilityAttributes,
  75. modelAttemptCompatibilityAttributes,
  76. modelResponseCompatibilityAttributes,
  77. toolCompatibilityAttributes,
  78. } from "./compatibility-adapters.js";
  79. import { sanitizeErrorMessage } from "./error-sanitizer.js";
  80. export interface AgentTraceRuntimeOptions extends WriterHealth {
  81. identity?: TelemetryIdentitySnapshot;
  82. maxActiveWriters?: number;
  83. metrics?: AgentTelemetryMetricRecorder;
  84. tracer: Tracer;
  85. }
  86. interface StartWriterOptions {
  87. attributes?: Attributes;
  88. context?: Context;
  89. correlation?: AgentTelemetryExecutionContext;
  90. kind?: SpanKind;
  91. links?: Link[];
  92. parent?: ActiveWriterContext;
  93. spanName: string;
  94. toolCallId?: string;
  95. }
  96. type TrackedWriter = BaseSpanWriter & {
  97. abandon(reason: AgentTelemetryAbandonReason): void;
  98. readonly state: ActiveWriterContext;
  99. };
  100. export class AgentExecutionTelemetryRuntime
  101. implements AgentExecutionTelemetryPort, ModelExecutionTelemetryPort
  102. {
  103. private readonly activeWriters = new Set<TrackedWriter>();
  104. private capacityWarningActive = false;
  105. private identity: TelemetryIdentitySnapshot;
  106. private readonly maxActiveWriters: number;
  107. private readonly tracer: Tracer;
  108. private readonly health: WriterHealth;
  109. private readonly metrics: AgentTelemetryMetricRecorder;
  110. constructor(options: AgentTraceRuntimeOptions) {
  111. this.tracer = options.tracer;
  112. this.maxActiveWriters = positiveLimit(options.maxActiveWriters, 5_000);
  113. this.health = { onWarning: options.onWarning };
  114. this.metrics = options.metrics ?? NOOP_AGENT_TELEMETRY_METRICS;
  115. this.identity = options.identity ?? { identityState: "unknown" };
  116. }
  117. updateIdentity(snapshot: TelemetryIdentitySnapshot): void {
  118. this.identity = {
  119. identityState: snapshot.identityState,
  120. ...(safeId(snapshot.userSubjectId) ? { userSubjectId: safeId(snapshot.userSubjectId) } : {}),
  121. };
  122. }
  123. captureCausation() {
  124. const active = activeWriterContext();
  125. if (!active) return undefined;
  126. const spanContext = active.span.spanContext();
  127. if (!trace.isSpanContextValid(spanContext)) return undefined;
  128. return {
  129. isRemote: spanContext.isRemote ?? false,
  130. spanId: spanContext.spanId,
  131. traceFlags: spanContext.traceFlags,
  132. traceId: spanContext.traceId,
  133. ...(spanContext.traceState ? { traceState: spanContext.traceState.serialize() } : {}),
  134. sessionId: active.correlation?.sessionId,
  135. turnId: active.correlation?.turnId,
  136. toolCallId: active.toolCallId,
  137. };
  138. }
  139. startTurn(input: AgentTurnTraceStart): AgentTurnSpanWriter {
  140. const correlation: AgentTelemetryExecutionContext = {
  141. ...input.context,
  142. identityState: this.identity.identityState,
  143. ...(this.identity.userSubjectId ? { userSubjectId: this.identity.userSubjectId } : {}),
  144. };
  145. const linkedRoot = input.causationMode !== "child";
  146. const links =
  147. input.causation && linkedRoot ? [causationLink(input.causation, "spawned_by")] : undefined;
  148. return this.safeCreate(
  149. "agent_turn",
  150. () => {
  151. const parentContext =
  152. input.causation && !linkedRoot ? contextFromCausation(input.causation) : ROOT_CONTEXT;
  153. const span = this.startSpan({
  154. attributes: compactAttributes({
  155. ...executionProjection(correlation, {
  156. includeActor: true,
  157. includeAgent: true,
  158. includeIdentity: true,
  159. includeQuery: true,
  160. includeSession: true,
  161. }),
  162. "zcode.agent_turn.turn_number": integer(input.turnNumber),
  163. "zcode.agent_turn.input_source": safeEnum(input.inputSource),
  164. }),
  165. context: parentContext,
  166. correlation,
  167. links,
  168. spanName: "agent_turn",
  169. });
  170. return this.track(
  171. new TurnWriter(
  172. span,
  173. parentContext,
  174. {
  175. correlation,
  176. spanName: "agent_turn",
  177. },
  178. this.health,
  179. this.metrics,
  180. turnMetricLabels(correlation, input.inputSource),
  181. (writer) => this.activeWriters.delete(writer),
  182. ),
  183. );
  184. },
  185. NOOP_TURN_WRITER,
  186. );
  187. }
  188. startStep(input: AgentStepTraceStart): AgentStepSpanWriter {
  189. const parent = activeWriterContext();
  190. return this.safeCreate(
  191. "agent_step",
  192. () => {
  193. const parentContext = parent?.activeContext ?? context.active();
  194. const span = this.startSpan({
  195. attributes: compactAttributes({
  196. ...executionProjection(parent?.correlation),
  197. "zcode.agent_step.step_id": safeId(input.stepId),
  198. "zcode.agent_step.step_index": integer(input.stepIndex),
  199. }),
  200. context: parentContext,
  201. correlation: parent?.correlation,
  202. parent,
  203. spanName: "agent_step",
  204. toolCallId: parent?.toolCallId,
  205. });
  206. return this.track(
  207. new StepWriter(
  208. span,
  209. parentContext,
  210. inheritedMetadata(parent, "agent_step"),
  211. this.health,
  212. this.metrics,
  213. stepMetricLabels(parent?.correlation),
  214. (writer) => this.activeWriters.delete(writer),
  215. ),
  216. );
  217. },
  218. NOOP_STEP_WRITER,
  219. );
  220. }
  221. startTool(input: ToolTraceStart): ToolExecutionSpanWriter {
  222. const parent = activeWriterContext();
  223. return this.safeCreate(
  224. "tool_execution",
  225. () => {
  226. const parentContext = parent?.activeContext ?? context.active();
  227. const toolName = safeString(input.registeredToolName, 128);
  228. const span = this.startSpan({
  229. attributes: compactAttributes({
  230. ...executionProjection(parent?.correlation, { includeActor: true }),
  231. "zcode.execution.tool_call_id": safeId(input.toolCallId),
  232. "zcode.tool_execution.tool_name": toolName,
  233. ...toolCompatibilityAttributes({
  234. toolCallId: input.toolCallId,
  235. toolName: input.registeredToolName,
  236. }),
  237. }),
  238. context: parentContext,
  239. correlation: parent?.correlation,
  240. parent,
  241. spanName: "tool_execution",
  242. toolCallId: safeId(input.toolCallId),
  243. });
  244. return this.track(
  245. new ToolWriter(
  246. span,
  247. parentContext,
  248. {
  249. ...inheritedMetadata(parent, "tool_execution"),
  250. toolCallId: safeId(input.toolCallId),
  251. },
  252. this.health,
  253. this.metrics,
  254. toolMetricLabels(input.registeredToolName),
  255. (writer) => this.activeWriters.delete(writer),
  256. (command) => this.startCommand(command),
  257. ),
  258. );
  259. },
  260. NOOP_TOOL_WRITER,
  261. );
  262. }
  263. startCompaction(input: CompactionTraceStart): ContextCompactionSpanWriter {
  264. const parent = activeWriterContext();
  265. return this.safeCreate(
  266. "context_compaction",
  267. () => {
  268. const parentContext = parent?.activeContext ?? context.active();
  269. const span = this.startSpan({
  270. attributes: compactAttributes({
  271. ...executionProjection(parent?.correlation),
  272. "zcode.context_compaction.trigger": safeEnum(input.trigger),
  273. "zcode.context_compaction.phase": safeEnum(input.phase),
  274. "zcode.context_compaction.model_mode": safeEnum(input.modelMode),
  275. "zcode.context_compaction.outer_attempt": integer(input.outerAttempt),
  276. "zcode.context_compaction.max_attempts": integer(input.maxAttempts),
  277. "zcode.context_compaction.triggering_step_index": integer(input.triggeringStepIndex),
  278. "zcode.context_compaction.policy_context_window_tokens": finiteNonNegative(
  279. input.policyContextWindowTokens,
  280. ),
  281. "zcode.context_compaction.threshold_tokens": finiteNonNegative(input.thresholdTokens),
  282. "zcode.context_compaction.token_source": safeEnum(input.tokenSource),
  283. "zcode.context_compaction.recovered_from_logical_call_id": safeId(
  284. input.recoveredFromLogicalCallId,
  285. ),
  286. }),
  287. context: parentContext,
  288. correlation: parent?.correlation,
  289. parent,
  290. spanName: "context_compaction",
  291. toolCallId: parent?.toolCallId,
  292. });
  293. return this.track(
  294. new CompactionWriter(
  295. span,
  296. parentContext,
  297. inheritedMetadata(parent, "context_compaction"),
  298. this.health,
  299. this.metrics,
  300. compactionMetricLabels(input),
  301. (writer) => this.activeWriters.delete(writer),
  302. ),
  303. );
  304. },
  305. NOOP_COMPACTION_WRITER,
  306. );
  307. }
  308. startDetachedOperation(input: DetachedOperationTraceStart): DetachedOperationSpanWriter {
  309. const linkedRoot = input.executionKind !== "foreground";
  310. const links =
  311. input.causation && linkedRoot
  312. ? [
  313. causationLink(
  314. input.causation,
  315. input.trigger === "recovery" ? "resumed_from" : "triggered_by",
  316. ),
  317. ]
  318. : undefined;
  319. return this.safeCreate(
  320. "detached_operation",
  321. () => {
  322. const parentContext =
  323. input.causation && !linkedRoot ? contextFromCausation(input.causation) : ROOT_CONTEXT;
  324. const span = this.startSpan({
  325. attributes: compactAttributes({
  326. ...executionProjection(input.context, {
  327. includeActor: true,
  328. includeQuery: true,
  329. includeSession: true,
  330. }),
  331. "zcode.detached_operation.operation": safeEnum(input.operation),
  332. "zcode.detached_operation.execution_kind": safeEnum(input.executionKind),
  333. "zcode.detached_operation.trigger": safeEnum(input.trigger),
  334. "zcode.detached_operation.target_kind": safeEnum(input.targetKind),
  335. "zcode.detached_operation.goal_iteration": integer(input.goalIteration),
  336. "zcode.detached_operation.chunk_index": integer(input.chunkIndex),
  337. "zcode.detached_operation.chunk_count": integer(input.chunkCount),
  338. }),
  339. context: parentContext,
  340. correlation: input.context,
  341. links,
  342. spanName: "detached_operation",
  343. });
  344. return this.track(
  345. new DetachedWriter(
  346. span,
  347. parentContext,
  348. {
  349. correlation: input.context,
  350. spanName: "detached_operation",
  351. },
  352. this.health,
  353. this.metrics,
  354. detachedMetricLabels(input),
  355. (writer) => this.activeWriters.delete(writer),
  356. ),
  357. );
  358. },
  359. NOOP_DETACHED_WRITER,
  360. );
  361. }
  362. startCall(input: ModelCallTraceStart): ModelCallSpanWriter {
  363. const parent = activeWriterContext();
  364. return this.safeCreate(
  365. "model_call",
  366. () => {
  367. const parentContext = parent?.activeContext ?? context.active();
  368. const span = this.startSpan({
  369. attributes: compactAttributes({
  370. ...executionProjection(parent?.correlation, {
  371. includeActor: true,
  372. includeQuery: true,
  373. includeSession: true,
  374. }),
  375. "zcode.execution.logical_call_id": safeId(input.logicalCallId),
  376. "zcode.model_call.operation": safeEnum(input.operation),
  377. "zcode.model_call.streaming": input.streaming,
  378. "zcode.model_call.model_role": safeEnum(input.modelRole),
  379. "zcode.model_call.requested_provider_id": safeString(input.requested.providerId, 128),
  380. "zcode.model_call.requested_model": safeString(input.requested.requestedModel, 128),
  381. "zcode.model_call.reasoning_capability": safeEnum(input.requested.reasoning.capability),
  382. "zcode.model_call.reasoning_requested_state": safeEnum(
  383. input.requested.reasoning.requestedState,
  384. ),
  385. "zcode.model_call.reasoning_requested_control": safeEnum(
  386. input.requested.reasoning.requestedControl,
  387. ),
  388. "zcode.model_call.reasoning_requested_level": safeString(
  389. input.requested.reasoning.requestedLevel,
  390. 128,
  391. ),
  392. "zcode.model_call.reasoning_requested_budget_tokens": integer(
  393. input.requested.reasoning.requestedBudgetTokens,
  394. ),
  395. "zcode.model_call.call_cause": safeEnum(input.callCause),
  396. "zcode.model_call.previous_logical_call_id": safeId(input.previousLogicalCallId),
  397. }),
  398. context: parentContext,
  399. correlation: parent?.correlation,
  400. parent,
  401. spanName: "model_call",
  402. toolCallId: parent?.toolCallId,
  403. });
  404. return this.track(
  405. new ModelCallWriter(
  406. span,
  407. parentContext,
  408. {
  409. ...inheritedMetadata(parent, "model_call"),
  410. },
  411. this.health,
  412. this.metrics,
  413. modelCallMetricLabels(input),
  414. (writer) => this.activeWriters.delete(writer),
  415. (writer, attempt) => this.startAttempt(writer, attempt),
  416. safeId(input.logicalCallId),
  417. safeEnum(input.operation),
  418. safeEnum(input.modelRole),
  419. ),
  420. );
  421. },
  422. NOOP_MODEL_CALL_WRITER,
  423. );
  424. }
  425. abandonSession(sessionId: string): void {
  426. for (const writer of this.activeWriters) {
  427. if (writer.state.correlation?.sessionId === sessionId) {
  428. writer.abandon("session_shutdown");
  429. }
  430. }
  431. }
  432. abandonProcess(): void {
  433. for (const writer of this.activeWriters) writer.abandon("process_shutdown");
  434. }
  435. private startCommand(
  436. input: CommandTraceStart & { parent: ToolWriter },
  437. ): CommandExecutionSpanWriter {
  438. const parent = input.parent.state;
  439. return this.safeCreate(
  440. "command_execution",
  441. () => {
  442. const span = this.startSpan({
  443. attributes: compactAttributes({
  444. ...executionProjection(parent.correlation),
  445. "zcode.execution.tool_call_id": safeId(parent.toolCallId),
  446. "zcode.command_execution.safe_name": safeString(input.safeName, 128),
  447. "zcode.command_execution.category": safeEnum(input.category),
  448. "zcode.command_execution.command_count": integer(input.commandCount),
  449. "zcode.command_execution.shell_kind": safeEnum(input.shellKind),
  450. "zcode.command_execution.sandboxed": input.sandboxed,
  451. }),
  452. context: parent.activeContext,
  453. correlation: parent.correlation,
  454. parent,
  455. spanName: "command_execution",
  456. toolCallId: parent.toolCallId,
  457. });
  458. return this.track(
  459. new CommandWriter(
  460. span,
  461. parent.activeContext,
  462. inheritedMetadata(parent, "command_execution"),
  463. this.health,
  464. this.metrics,
  465. commandMetricLabels(input),
  466. (writer) => this.activeWriters.delete(writer),
  467. ),
  468. );
  469. },
  470. NOOP_COMMAND_WRITER,
  471. );
  472. }
  473. private startAttempt(
  474. parentWriter: ModelCallWriter,
  475. input: ModelAttemptTraceStart,
  476. ): ModelAttemptSpanWriter {
  477. const parent = parentWriter.state;
  478. return this.safeCreate(
  479. "model_attempt",
  480. () => {
  481. const target = input.target;
  482. const span = this.startSpan({
  483. attributes: compactAttributes({
  484. ...executionProjection(parent.correlation, {
  485. includeActor: true,
  486. includeQuery: true,
  487. includeSession: true,
  488. }),
  489. "zcode.execution.tool_call_id": safeId(parent.toolCallId),
  490. "zcode.execution.logical_call_id": parentWriter.logicalCallId,
  491. "zcode.execution.model_operation": parentWriter.operation,
  492. "zcode.execution.model_role": parentWriter.modelRole,
  493. "zcode.model_attempt.request_id": safeId(input.requestId),
  494. "zcode.model_attempt.attempt_number": integer(input.attemptNumber),
  495. "zcode.model_attempt.max_attempts": integer(input.maxAttempts),
  496. "zcode.model_attempt.attempt_cause": safeEnum(input.attemptCause),
  497. "zcode.model_attempt.previous_request_id": safeId(input.previousRequestId),
  498. "zcode.model_attempt.retry_delay_ms": finiteNonNegative(input.retryDelayMs),
  499. "zcode.model_attempt.provider_id": safeString(target.providerId, 128),
  500. "zcode.model_attempt.provider_kind": safeEnum(target.providerKind),
  501. "zcode.model_attempt.provider_origin": safeString(target.providerOrigin),
  502. "zcode.model_attempt.provider_route": safeString(target.providerRoute),
  503. "zcode.model_attempt.requested_model": safeString(target.requestedModel, 128),
  504. "zcode.model_attempt.transport": safeEnum(input.transport),
  505. "zcode.model_attempt.api_operation": safeEnum(input.apiOperation),
  506. "zcode.model_attempt.reasoning_capability": safeEnum(target.reasoning.capability),
  507. "zcode.model_attempt.reasoning_requested_state": safeEnum(
  508. target.reasoning.requestedState,
  509. ),
  510. "zcode.model_attempt.reasoning_requested_control": safeEnum(
  511. target.reasoning.requestedControl,
  512. ),
  513. "zcode.model_attempt.reasoning_requested_level": safeString(
  514. target.reasoning.requestedLevel,
  515. 128,
  516. ),
  517. "zcode.model_attempt.reasoning_requested_budget_tokens": integer(
  518. target.reasoning.requestedBudgetTokens,
  519. ),
  520. ...modelAttemptCompatibilityAttributes(target),
  521. }),
  522. context: parent.activeContext,
  523. correlation: parent.correlation,
  524. kind: SpanKind.CLIENT,
  525. parent,
  526. spanName: "model_attempt",
  527. toolCallId: parent.toolCallId,
  528. });
  529. return this.track(
  530. new ModelAttemptWriter(
  531. span,
  532. parent.activeContext,
  533. inheritedMetadata(parent, "model_attempt"),
  534. this.health,
  535. this.metrics,
  536. modelAttemptMetricLabels(input, parentWriter),
  537. () => parentWriter.recordAttemptFailed(),
  538. (writer) => this.activeWriters.delete(writer),
  539. ),
  540. );
  541. },
  542. NOOP_MODEL_ATTEMPT_WRITER,
  543. );
  544. }
  545. private startSpan(options: StartWriterOptions): Span {
  546. return this.tracer.startSpan(
  547. options.spanName,
  548. {
  549. attributes: options.attributes,
  550. kind: options.kind ?? SpanKind.INTERNAL,
  551. links: options.links,
  552. },
  553. options.context ?? context.active(),
  554. );
  555. }
  556. private track<T extends TrackedWriter>(writer: T): T {
  557. this.activeWriters.add(writer);
  558. return writer;
  559. }
  560. private safeCreate<T>(spanName: string, create: () => T, fallback: T): T {
  561. if (this.activeWriters.size >= this.maxActiveWriters) {
  562. this.safeMetric(() =>
  563. this.metrics.recordCreationDrop(spanName as AgentMetricSpanName, "process_capacity"),
  564. );
  565. if (!this.capacityWarningActive) {
  566. this.capacityWarningActive = true;
  567. try {
  568. this.health.onWarning?.("Telemetry active writer capacity was reached", {
  569. activeWriterCount: this.activeWriters.size,
  570. maxActiveWriters: this.maxActiveWriters,
  571. spanName,
  572. });
  573. } catch {
  574. // 健康回调同样属于旁路。
  575. }
  576. }
  577. return fallback;
  578. }
  579. this.capacityWarningActive = false;
  580. try {
  581. return create();
  582. } catch (error) {
  583. this.safeMetric(() =>
  584. this.metrics.recordCreationDrop(spanName as AgentMetricSpanName, "unknown"),
  585. );
  586. try {
  587. this.health.onWarning?.("Telemetry writer creation failed", {
  588. errorType: error instanceof Error ? error.name : typeof error,
  589. spanName,
  590. });
  591. } catch {
  592. // 健康回调同样属于旁路。
  593. }
  594. return fallback;
  595. }
  596. }
  597. private safeMetric(record: () => void): void {
  598. try {
  599. record();
  600. } catch (error) {
  601. try {
  602. this.health.onWarning?.("Telemetry metric operation failed", {
  603. errorType: error instanceof Error ? error.name : typeof error,
  604. });
  605. } catch {
  606. // Metric 与健康回调都属于旁路。
  607. }
  608. }
  609. }
  610. }
  611. function positiveLimit(value: number | undefined, fallback: number): number {
  612. return value !== undefined && Number.isFinite(value) && value > 0 ? Math.trunc(value) : fallback;
  613. }
  614. function terminalMetricLabels(
  615. labels: Attributes,
  616. observation: WriterTerminalObservation,
  617. ): Attributes {
  618. return compactAttributes({
  619. ...labels,
  620. error_category: observation.errorCategory,
  621. });
  622. }
  623. function turnMetricLabels(
  624. correlation: AgentTelemetryExecutionContext,
  625. inputSource: AgentTurnTraceStart["inputSource"],
  626. ): Attributes {
  627. return compactAttributes({
  628. actor_kind: safeEnum(correlation.actorKind),
  629. input_source: safeEnum(inputSource),
  630. launch_surface: safeEnum(correlation.launchSurface),
  631. });
  632. }
  633. function stepMetricLabels(correlation: AgentTelemetryExecutionContext | undefined): Attributes {
  634. return compactAttributes({
  635. actor_kind: safeEnum(correlation?.actorKind),
  636. });
  637. }
  638. function toolMetricLabels(toolName: string): Attributes {
  639. return {
  640. tool_name: safeString(toolName, 128),
  641. };
  642. }
  643. function commandMetricLabels(input: CommandTraceStart): Attributes {
  644. return compactAttributes({
  645. command_category: safeEnum(input.category),
  646. command_safe_name: safeString(input.safeName, 128),
  647. });
  648. }
  649. function compactionMetricLabels(input: CompactionTraceStart): Attributes {
  650. return compactAttributes({
  651. model_mode: safeEnum(input.modelMode),
  652. trigger: safeEnum(input.trigger),
  653. });
  654. }
  655. function detachedMetricLabels(input: DetachedOperationTraceStart): Attributes {
  656. return compactAttributes({
  657. execution_kind: safeEnum(input.executionKind),
  658. operation: safeEnum(input.operation),
  659. });
  660. }
  661. function modelCallMetricLabels(input: ModelCallTraceStart): Attributes {
  662. return compactAttributes({
  663. call_cause: safeEnum(input.callCause ?? "initial"),
  664. model_operation: safeEnum(input.operation),
  665. model_role: safeEnum(input.modelRole),
  666. });
  667. }
  668. function modelAttemptMetricLabels(
  669. input: ModelAttemptTraceStart,
  670. parent: ModelCallWriter,
  671. ): Attributes {
  672. return compactAttributes({
  673. model: safeString(input.target.requestedModel, 128),
  674. model_operation: parent.operation,
  675. model_role: parent.modelRole,
  676. provider_kind: safeEnum(input.target.providerKind),
  677. transport: safeEnum(input.transport),
  678. });
  679. }
  680. abstract class TrackedBaseWriter extends BaseSpanWriter {
  681. protected readonly metricLabels: Attributes;
  682. constructor(
  683. span: Span,
  684. parentContext: Context,
  685. metadata: Omit<ActiveWriterContext, "activeContext" | "span">,
  686. lifecycle: WriterLifecycleKeys,
  687. health: WriterHealth,
  688. metrics: AgentTelemetryMetricRecorder,
  689. metricLabels: Attributes,
  690. onRemoved: (writer: TrackedWriter) => void,
  691. ) {
  692. const terminalTarget: { writer?: TrackedBaseWriter } = {};
  693. super(span, parentContext, metadata, lifecycle, health, (outcome, durationMs, observation) => {
  694. const writer = terminalTarget.writer;
  695. if (writer) {
  696. // 终态 Metric 从 Writer 已记录的实时事实投影,覆盖显式 finish、业务异常、
  697. // missing_terminal 和进程回收;不能只埋在各 finishXxx 分支里留下缺口。
  698. writer.safe(() => onRemoved(writer));
  699. writer.safe(() => writer.recordTerminalDetailMetrics(outcome, observation));
  700. writer.safe(() =>
  701. metrics.recordSpanTerminal(
  702. metadata.spanName as AgentMetricSpanName,
  703. outcome,
  704. durationMs,
  705. terminalMetricLabels(metricLabels, observation),
  706. observation.abandonReason,
  707. ),
  708. );
  709. }
  710. });
  711. terminalTarget.writer = this;
  712. this.metricLabels = metricLabels;
  713. }
  714. abandon(reason: AgentTelemetryAbandonReason): void {
  715. this.finishAbandonedIfOpen(reason);
  716. }
  717. protected recordTerminalDetailMetrics(
  718. _outcome: string,
  719. _observation: WriterTerminalObservation,
  720. ): void {}
  721. }
  722. function causationLink(
  723. causation: AgentTelemetryCausation,
  724. relation: "spawned_by" | "triggered_by" | "resumed_from",
  725. ): Link {
  726. return {
  727. attributes: {
  728. "zcode.link.relation": relation,
  729. },
  730. context: spanContextFromCausation(causation),
  731. };
  732. }
  733. class TurnWriter extends TrackedBaseWriter implements AgentTurnSpanWriter {
  734. constructor(
  735. span: Span,
  736. parentContext: Context,
  737. metadata: Omit<ActiveWriterContext, "activeContext" | "span">,
  738. health: WriterHealth,
  739. metrics: AgentTelemetryMetricRecorder,
  740. metricLabels: Attributes,
  741. onRemoved: (writer: TrackedWriter) => void,
  742. ) {
  743. super(
  744. span,
  745. parentContext,
  746. metadata,
  747. lifecycleKeys("agent_turn"),
  748. health,
  749. metrics,
  750. metricLabels,
  751. onRemoved,
  752. );
  753. }
  754. finishCompleted(
  755. resultType: "assistant_message" | "tool_request" | "no_output" | "other" = "other",
  756. ): void {
  757. this.finishCompletedIfOpen(() => this.setAttribute("zcode.agent_turn.result_type", resultType));
  758. }
  759. finishFailed(
  760. stage: "setup" | "agent_loop" | "finalize" | "unhandled",
  761. category: AgentTelemetryErrorCategory,
  762. error?: unknown,
  763. ): void {
  764. this.finishFailedIfOpen(stage, category, error);
  765. }
  766. finishCancelled(reason: AgentTelemetryCancellationReason): void {
  767. this.finishCancelledIfOpen(reason);
  768. }
  769. protected finishUnhandled(error: unknown): void {
  770. if (isAbortLike(error)) this.finishCancelledIfOpen("abort_signal");
  771. else this.finishFailedIfOpen("unhandled", classifyErrorCategory(error), error);
  772. }
  773. }
  774. class StepWriter extends TrackedBaseWriter implements AgentStepSpanWriter {
  775. constructor(
  776. span: Span,
  777. parentContext: Context,
  778. metadata: Omit<ActiveWriterContext, "activeContext" | "span">,
  779. health: WriterHealth,
  780. metrics: AgentTelemetryMetricRecorder,
  781. metricLabels: Attributes,
  782. onRemoved: (writer: TrackedWriter) => void,
  783. ) {
  784. super(
  785. span,
  786. parentContext,
  787. metadata,
  788. lifecycleKeys("agent_step"),
  789. health,
  790. metrics,
  791. metricLabels,
  792. onRemoved,
  793. );
  794. }
  795. finishCompleted(
  796. terminalReason:
  797. | "model_completed"
  798. | "tool_requested"
  799. | "turn_completed"
  800. | "compaction_requested",
  801. ): void {
  802. this.metricLabels.terminal_reason = terminalReason;
  803. this.finishCompletedIfOpen(() =>
  804. this.setAttribute("zcode.agent_step.terminal_reason", terminalReason),
  805. );
  806. }
  807. finishDiscarded(): void {
  808. this.finishDomainOutcomeIfOpen("discarded");
  809. }
  810. finishFailed(
  811. stage: "prepare" | "model" | "tool" | "commit" | "unhandled",
  812. category: AgentTelemetryErrorCategory,
  813. error?: unknown,
  814. ): void {
  815. this.finishFailedIfOpen(stage, category, error);
  816. }
  817. finishCancelled(reason: AgentTelemetryCancellationReason): void {
  818. this.finishCancelledIfOpen(reason);
  819. }
  820. protected finishUnhandled(error: unknown): void {
  821. if (isAbortLike(error)) this.finishCancelledIfOpen("abort_signal");
  822. else this.finishFailedIfOpen("unhandled", classifyErrorCategory(error), error);
  823. }
  824. }
  825. class ToolWriter extends TrackedBaseWriter implements ToolExecutionSpanWriter {
  826. private permissionRequested = false;
  827. constructor(
  828. span: Span,
  829. parentContext: Context,
  830. metadata: Omit<ActiveWriterContext, "activeContext" | "span">,
  831. health: WriterHealth,
  832. metrics: AgentTelemetryMetricRecorder,
  833. metricLabels: Attributes,
  834. onRemoved: (writer: TrackedWriter) => void,
  835. private readonly createCommand: (
  836. input: CommandTraceStart & { parent: ToolWriter },
  837. ) => CommandExecutionSpanWriter,
  838. ) {
  839. super(
  840. span,
  841. parentContext,
  842. metadata,
  843. lifecycleKeys("tool_execution"),
  844. health,
  845. metrics,
  846. metricLabels,
  847. onRemoved,
  848. );
  849. }
  850. markPermissionRequested(): void {
  851. if (this.permissionRequested) return;
  852. this.permissionRequested = true;
  853. this.addEvent("permission_requested");
  854. }
  855. setPermissionDecision(decision: "granted" | "denied" | "not_required"): void {
  856. this.setAttribute("zcode.tool_execution.permission_decision", decision);
  857. if (this.permissionRequested && decision !== "not_required") {
  858. this.addEvent("permission_decided", { decision });
  859. }
  860. }
  861. setOutputBytes(bytes: number): void {
  862. this.setAttribute("zcode.tool_execution.output_bytes", finiteNonNegative(bytes));
  863. }
  864. setOutputTruncated(truncated: boolean): void {
  865. this.setAttribute("zcode.tool_execution.output_truncated", truncated);
  866. }
  867. startCommand(input: CommandTraceStart): CommandExecutionSpanWriter {
  868. return this.createCommand({ ...input, parent: this });
  869. }
  870. finishCompleted(): void {
  871. this.finishCompletedIfOpen();
  872. }
  873. finishDenied(reason: "user_denied" | "policy_denied" | "unavailable" | "unknown"): void {
  874. this.finishDomainOutcomeIfOpen("denied", () =>
  875. this.setAttribute("zcode.tool_execution.permission_denial_reason", reason),
  876. );
  877. }
  878. finishFailed(
  879. stage:
  880. | "lookup"
  881. | "validation"
  882. | "permission"
  883. | "pre_hook"
  884. | "handler"
  885. | "post_hook"
  886. | "serialize"
  887. | "unhandled",
  888. category: AgentTelemetryErrorCategory,
  889. error?: unknown,
  890. ): void {
  891. this.finishFailedIfOpen(stage, category, error);
  892. }
  893. finishCancelled(reason: AgentTelemetryCancellationReason): void {
  894. this.finishCancelledIfOpen(reason);
  895. }
  896. protected finishUnhandled(error: unknown): void {
  897. if (isAbortLike(error)) this.finishCancelledIfOpen("abort_signal");
  898. else this.finishFailedIfOpen("unhandled", classifyErrorCategory(error), error);
  899. }
  900. }
  901. class CommandWriter extends TrackedBaseWriter implements CommandExecutionSpanWriter {
  902. private firstOutput = false;
  903. private firstOutputMs: number | undefined;
  904. constructor(
  905. span: Span,
  906. parentContext: Context,
  907. metadata: Omit<ActiveWriterContext, "activeContext" | "span">,
  908. health: WriterHealth,
  909. private readonly metrics: AgentTelemetryMetricRecorder,
  910. metricLabels: Attributes,
  911. onRemoved: (writer: TrackedWriter) => void,
  912. ) {
  913. super(
  914. span,
  915. parentContext,
  916. metadata,
  917. lifecycleKeys("command_execution"),
  918. health,
  919. metrics,
  920. metricLabels,
  921. onRemoved,
  922. );
  923. }
  924. markFirstOutput(): void {
  925. if (this.firstOutput) return;
  926. this.firstOutput = true;
  927. const elapsed = this.elapsedMs();
  928. this.firstOutputMs = elapsed;
  929. this.setAttribute("zcode.command_execution.first_output_ms", elapsed);
  930. this.addEvent("first_output");
  931. }
  932. markTerminationRequested(reason: "cancelled" | "timeout" | "shutdown"): void {
  933. this.addEvent("termination_requested", { reason });
  934. }
  935. setExitCode(exitCode: number): void {
  936. const normalized = integer(exitCode);
  937. this.setAttribute("zcode.command_execution.exit_code", normalized);
  938. this.setAttributes(commandCompatibilityAttributes({ exitCode: normalized }));
  939. }
  940. setSignal(signal: string): void {
  941. const normalized = safeIdentifier(signal);
  942. this.setAttribute("zcode.command_execution.signal", normalized);
  943. this.setAttributes(commandCompatibilityAttributes({ signal: normalized }));
  944. }
  945. setOutputBytes(bytes: number): void {
  946. this.setAttribute("zcode.command_execution.output_bytes", finiteNonNegative(bytes));
  947. }
  948. setTimedOut(timedOut: boolean): void {
  949. this.setAttribute("zcode.command_execution.timed_out", timedOut);
  950. }
  951. finishCompleted(): void {
  952. this.finishCompletedIfOpen();
  953. }
  954. finishFailed(
  955. stage: "prepare" | "spawn" | "execute" | "timeout" | "collect_output" | "unhandled",
  956. category: AgentTelemetryErrorCategory,
  957. error?: unknown,
  958. ): void {
  959. this.finishFailedIfOpen(stage, category, error);
  960. }
  961. finishCancelled(reason: AgentTelemetryCancellationReason): void {
  962. this.finishCancelledIfOpen(reason);
  963. }
  964. finishBackgrounded(): void {
  965. this.finishDomainOutcomeIfOpen("backgrounded");
  966. }
  967. protected finishUnhandled(error: unknown): void {
  968. if (isAbortLike(error)) {
  969. this.finishCancelledIfOpen("abort_signal");
  970. } else {
  971. const category = classifyErrorCategory(error);
  972. this.finishFailedIfOpen("unhandled", category, error);
  973. }
  974. }
  975. protected override recordTerminalDetailMetrics(
  976. outcome: string,
  977. observation: WriterTerminalObservation,
  978. ): void {
  979. if (this.firstOutputMs === undefined) return;
  980. this.metrics.recordCommandFirstOutput(
  981. this.firstOutputMs,
  982. compactAttributes({
  983. ...this.metricLabels,
  984. error_category: observation.errorCategory,
  985. outcome,
  986. }),
  987. );
  988. }
  989. }
  990. class CompactionWriter extends TrackedBaseWriter implements ContextCompactionSpanWriter {
  991. constructor(
  992. span: Span,
  993. parentContext: Context,
  994. metadata: Omit<ActiveWriterContext, "activeContext" | "span">,
  995. health: WriterHealth,
  996. metrics: AgentTelemetryMetricRecorder,
  997. metricLabels: Attributes,
  998. onRemoved: (writer: TrackedWriter) => void,
  999. ) {
  1000. super(
  1001. span,
  1002. parentContext,
  1003. metadata,
  1004. lifecycleKeys("context_compaction"),
  1005. health,
  1006. metrics,
  1007. metricLabels,
  1008. onRemoved,
  1009. );
  1010. }
  1011. setInputTokens(tokens: number): void {
  1012. this.setAttribute("zcode.context_compaction.input_tokens", finiteNonNegative(tokens));
  1013. }
  1014. setOutputTokens(tokens: number): void {
  1015. this.setAttribute("zcode.context_compaction.output_tokens", finiteNonNegative(tokens));
  1016. }
  1017. markFallbackSelected(reason: string): void {
  1018. this.addEvent("fallback_selected", { reason: safeEnum(reason) });
  1019. }
  1020. finishCompleted(): void {
  1021. this.finishCompletedIfOpen();
  1022. }
  1023. finishDiscarded(): void {
  1024. this.finishDomainOutcomeIfOpen("discarded");
  1025. }
  1026. finishFailed(
  1027. stage: "prepare" | "model" | "parse" | "commit" | "fallback" | "unhandled",
  1028. category: AgentTelemetryErrorCategory,
  1029. error?: unknown,
  1030. ): void {
  1031. this.finishFailedIfOpen(stage, category, error);
  1032. }
  1033. finishCancelled(reason: AgentTelemetryCancellationReason): void {
  1034. this.finishCancelledIfOpen(reason);
  1035. }
  1036. protected finishUnhandled(error: unknown): void {
  1037. if (isAbortLike(error)) this.finishCancelledIfOpen("abort_signal");
  1038. else this.finishFailedIfOpen("unhandled", classifyErrorCategory(error), error);
  1039. }
  1040. }
  1041. class DetachedWriter extends TrackedBaseWriter implements DetachedOperationSpanWriter {
  1042. constructor(
  1043. span: Span,
  1044. parentContext: Context,
  1045. metadata: Omit<ActiveWriterContext, "activeContext" | "span">,
  1046. health: WriterHealth,
  1047. metrics: AgentTelemetryMetricRecorder,
  1048. metricLabels: Attributes,
  1049. onRemoved: (writer: TrackedWriter) => void,
  1050. ) {
  1051. super(
  1052. span,
  1053. parentContext,
  1054. metadata,
  1055. lifecycleKeys("detached_operation"),
  1056. health,
  1057. metrics,
  1058. metricLabels,
  1059. onRemoved,
  1060. );
  1061. }
  1062. setResultType(resultType: "text" | "boolean" | "metadata" | "other"): void {
  1063. this.setAttribute("zcode.detached_operation.result_type", resultType);
  1064. }
  1065. finishCompleted(): void {
  1066. this.finishCompletedIfOpen();
  1067. }
  1068. finishFailed(
  1069. stage: "schedule" | "execute" | "commit" | "unhandled",
  1070. category: AgentTelemetryErrorCategory,
  1071. error?: unknown,
  1072. ): void {
  1073. this.finishFailedIfOpen(stage, category, error);
  1074. }
  1075. finishCancelled(reason: AgentTelemetryCancellationReason): void {
  1076. this.finishCancelledIfOpen(reason);
  1077. }
  1078. protected finishUnhandled(error: unknown): void {
  1079. if (isAbortLike(error)) this.finishCancelledIfOpen("abort_signal");
  1080. else this.finishFailedIfOpen("unhandled", classifyErrorCategory(error), error);
  1081. }
  1082. }
  1083. class ModelCallWriter extends TrackedBaseWriter implements ModelCallSpanWriter {
  1084. private attemptCount = 0;
  1085. private hadFailedAttempt = false;
  1086. readonly logicalCallId: string | undefined;
  1087. readonly modelRole: string | undefined;
  1088. readonly operation: string | undefined;
  1089. constructor(
  1090. span: Span,
  1091. parentContext: Context,
  1092. metadata: Omit<ActiveWriterContext, "activeContext" | "span">,
  1093. health: WriterHealth,
  1094. private readonly metrics: AgentTelemetryMetricRecorder,
  1095. metricLabels: Attributes,
  1096. onRemoved: (writer: TrackedWriter) => void,
  1097. private readonly createAttempt: (
  1098. writer: ModelCallWriter,
  1099. input: ModelAttemptTraceStart,
  1100. ) => ModelAttemptSpanWriter,
  1101. logicalCallId: string | undefined,
  1102. operation: string | undefined,
  1103. modelRole: string | undefined,
  1104. ) {
  1105. super(
  1106. span,
  1107. parentContext,
  1108. metadata,
  1109. lifecycleKeys("model_call"),
  1110. health,
  1111. metrics,
  1112. metricLabels,
  1113. onRemoved,
  1114. );
  1115. this.logicalCallId = logicalCallId;
  1116. this.operation = operation;
  1117. this.modelRole = modelRole;
  1118. }
  1119. startAttempt(input: ModelAttemptTraceStart): ModelAttemptSpanWriter {
  1120. this.attemptCount += 1;
  1121. return this.createAttempt(this, input);
  1122. }
  1123. markFallbackSelected(reason: string): void {
  1124. this.addEvent("fallback_selected", { reason: safeString(reason, 128) });
  1125. }
  1126. recordAttemptFailed(): void {
  1127. this.hadFailedAttempt = true;
  1128. }
  1129. finishCompleted(): void {
  1130. this.finishCompletedIfOpen();
  1131. }
  1132. finishFailed(
  1133. stage: ModelCallFailureStage,
  1134. category: AgentTelemetryErrorCategory,
  1135. error?: unknown,
  1136. ): void {
  1137. this.finishFailedIfOpen(stage, category, error);
  1138. }
  1139. finishAbandoned(reason: AgentTelemetryAbandonReason): void {
  1140. this.finishAbandonedIfOpen(reason);
  1141. }
  1142. finishCancelled(reason: AgentTelemetryCancellationReason): void {
  1143. this.finishCancelledIfOpen(reason);
  1144. }
  1145. protected finishUnhandled(error: unknown): void {
  1146. if (isAbortLike(error)) {
  1147. this.finishCancelledIfOpen("abort_signal");
  1148. } else {
  1149. const category = classifyErrorCategory(error);
  1150. this.finishFailedIfOpen("unhandled", category, error);
  1151. }
  1152. }
  1153. protected override recordTerminalDetailMetrics(
  1154. outcome: string,
  1155. observation: WriterTerminalObservation,
  1156. ): void {
  1157. const retryState =
  1158. this.attemptCount <= 1
  1159. ? "not_needed"
  1160. : outcome === "completed" && this.hadFailedAttempt
  1161. ? "recovered"
  1162. : "not_recovered";
  1163. this.metrics.recordModelCallAttempts(
  1164. this.attemptCount,
  1165. compactAttributes({
  1166. ...this.metricLabels,
  1167. error_category: observation.errorCategory,
  1168. outcome,
  1169. retry_state: retryState,
  1170. }),
  1171. );
  1172. }
  1173. }
  1174. class ModelAttemptWriter extends TrackedBaseWriter implements ModelAttemptSpanWriter {
  1175. private firstContent = false;
  1176. private firstContentMs: number | undefined;
  1177. private firstProviderEvent = false;
  1178. private firstProviderEventMs: number | undefined;
  1179. private firstText = false;
  1180. private firstTextMs: number | undefined;
  1181. private stallCount = 0;
  1182. private streamMaxIdleMs = 0;
  1183. private readonly usage = {
  1184. cacheReadTokens: 0,
  1185. cacheWriteTokens: 0,
  1186. inputTokens: 0,
  1187. outputTokens: 0,
  1188. reasoningTokens: 0,
  1189. };
  1190. constructor(
  1191. span: Span,
  1192. parentContext: Context,
  1193. metadata: Omit<ActiveWriterContext, "activeContext" | "span">,
  1194. health: WriterHealth,
  1195. private readonly metrics: AgentTelemetryMetricRecorder,
  1196. metricLabels: Attributes,
  1197. private readonly onAttemptFailed: () => void,
  1198. onRemoved: (writer: TrackedWriter) => void,
  1199. ) {
  1200. super(
  1201. span,
  1202. parentContext,
  1203. metadata,
  1204. lifecycleKeys("model_attempt"),
  1205. health,
  1206. metrics,
  1207. metricLabels,
  1208. onRemoved,
  1209. );
  1210. }
  1211. setProviderRequestId(requestId: string): void {
  1212. this.setAttribute("zcode.model_attempt.provider_request_id", safeString(requestId, 256));
  1213. }
  1214. setResponseModel(model: ResponseModelTelemetryDescriptor): void {
  1215. const value = safeString(model.model, 128);
  1216. this.setAttribute("zcode.model_attempt.response_model", value);
  1217. this.setAttributes(modelResponseCompatibilityAttributes({ responseModel: value }));
  1218. }
  1219. setEffectiveReasoningState(state: ModelReasoningState): void {
  1220. this.setAttribute("zcode.model_attempt.reasoning_effective_state", safeEnum(state));
  1221. }
  1222. setEffectiveReasoningControl(control: ModelReasoningControlType): void {
  1223. this.setAttribute("zcode.model_attempt.reasoning_effective_control", safeEnum(control));
  1224. }
  1225. setEffectiveReasoningLevel(level: string): void {
  1226. this.setAttribute("zcode.model_attempt.reasoning_effective_level", safeString(level, 128));
  1227. }
  1228. setEffectiveReasoningBudgetTokens(tokens: number): void {
  1229. this.setAttribute(
  1230. "zcode.model_attempt.reasoning_effective_budget_tokens",
  1231. finiteNonNegative(tokens),
  1232. );
  1233. }
  1234. setFinishReason(reason: ModelFinishReason): void {
  1235. const value = safeString(reason, 128);
  1236. this.setAttribute("zcode.model_attempt.finish_reason", value);
  1237. this.setAttributes(modelResponseCompatibilityAttributes({ finishReason: value }));
  1238. }
  1239. setInputTokens(tokens: number): void {
  1240. this.setUsage("inputTokens", "input", tokens, "zcode.model_attempt.input_tokens");
  1241. this.setAttributes(modelResponseCompatibilityAttributes({ inputTokens: tokens }));
  1242. }
  1243. setOutputTokens(tokens: number): void {
  1244. this.setUsage("outputTokens", "output", tokens, "zcode.model_attempt.output_tokens");
  1245. this.setAttributes(modelResponseCompatibilityAttributes({ outputTokens: tokens }));
  1246. }
  1247. setReasoningTokens(tokens: number): void {
  1248. this.setUsage("reasoningTokens", "reasoning", tokens, "zcode.model_attempt.reasoning_tokens");
  1249. }
  1250. setCacheReadTokens(tokens: number): void {
  1251. this.setUsage("cacheReadTokens", "cache_read", tokens, "zcode.model_attempt.cache_read_tokens");
  1252. }
  1253. setCacheWriteTokens(tokens: number): void {
  1254. this.setUsage(
  1255. "cacheWriteTokens",
  1256. "cache_write",
  1257. tokens,
  1258. "zcode.model_attempt.cache_write_tokens",
  1259. );
  1260. }
  1261. setStreamOutputCommitted(committed: boolean): void {
  1262. this.setAttribute("zcode.model_attempt.stream_output_committed", committed);
  1263. }
  1264. setHttpStatusCode(statusCode: number): void {
  1265. const normalized = integer(statusCode);
  1266. this.setAttribute("zcode.model_attempt.http_status_code", normalized);
  1267. this.setAttributes(httpResponseCompatibilityAttributes(statusCode));
  1268. }
  1269. setProviderErrorCode(code: string): void {
  1270. this.setAttribute("zcode.model_attempt.provider_error_code", safeString(code, 128));
  1271. }
  1272. setProviderErrorMessage(message: string): void {
  1273. this.setAttribute("zcode.model_attempt.provider_error_message", sanitizeErrorMessage(message));
  1274. }
  1275. setRetryAfterMs(delayMs: number): void {
  1276. this.setAttribute("zcode.model_attempt.retry_after_ms", finiteNonNegative(delayMs));
  1277. }
  1278. markFirstProviderEvent(): void {
  1279. if (this.firstProviderEvent) return;
  1280. this.firstProviderEvent = true;
  1281. const elapsed = this.elapsedMs();
  1282. this.firstProviderEventMs = elapsed;
  1283. this.setAttribute("zcode.model_attempt.time_to_first_provider_event_ms", elapsed);
  1284. this.addEvent("first_provider_event");
  1285. }
  1286. markFirstContent(): void {
  1287. if (this.firstContent) return;
  1288. this.firstContent = true;
  1289. const elapsed = this.elapsedMs();
  1290. this.firstContentMs = elapsed;
  1291. this.setAttribute("zcode.model_attempt.time_to_first_content_ms", elapsed);
  1292. this.addEvent("first_content");
  1293. }
  1294. markFirstText(): void {
  1295. if (this.firstText) return;
  1296. this.firstText = true;
  1297. const elapsed = this.elapsedMs();
  1298. this.firstTextMs = elapsed;
  1299. this.setAttribute("zcode.model_attempt.time_to_first_text_ms", elapsed);
  1300. this.addEvent("first_text");
  1301. }
  1302. markStreamStalled(idleMs: number): void {
  1303. const normalized = finiteNonNegative(idleMs);
  1304. if (normalized === undefined) return;
  1305. this.stallCount += 1;
  1306. this.streamMaxIdleMs = Math.max(this.streamMaxIdleMs, normalized);
  1307. this.addEvent("stream_stalled", { idle_ms: normalized });
  1308. }
  1309. recordRequestObservation(observation: ModelRequestObservation): void {
  1310. recordRequestObservation(
  1311. {
  1312. setAttribute: (name, value) => this.setAttribute(name, value),
  1313. addEvent: (name, attributes) => this.addEvent(name, attributes),
  1314. },
  1315. observation,
  1316. );
  1317. }
  1318. finishCompleted(): void {
  1319. this.finishCompletedIfOpen();
  1320. }
  1321. finishFailed(
  1322. stage: ModelAttemptFailureStage,
  1323. category: AgentTelemetryErrorCategory,
  1324. error?: unknown,
  1325. ): void {
  1326. this.onAttemptFailed();
  1327. this.finishFailedIfOpen(stage, category, error);
  1328. }
  1329. finishAbandoned(reason: AgentTelemetryAbandonReason): void {
  1330. this.finishAbandonedIfOpen(reason);
  1331. }
  1332. finishCancelled(reason: AgentTelemetryCancellationReason): void {
  1333. this.finishCancelledIfOpen(reason);
  1334. }
  1335. protected finishUnhandled(error: unknown): void {
  1336. if (isAbortLike(error)) {
  1337. this.finishCancelledIfOpen("abort_signal");
  1338. } else {
  1339. const category = classifyErrorCategory(error);
  1340. this.onAttemptFailed();
  1341. this.finishFailedIfOpen("unhandled", category, error);
  1342. }
  1343. }
  1344. private setUsage(
  1345. field: keyof ModelAttemptWriter["usage"],
  1346. tokenType: ModelTokenType,
  1347. value: number,
  1348. attribute: string,
  1349. ): void {
  1350. const normalized = finiteNonNegative(value);
  1351. if (normalized === undefined) return;
  1352. const delta = normalized - this.usage[field];
  1353. if (delta < 0) return;
  1354. this.usage[field] = normalized;
  1355. this.safe(() => this.metrics.recordModelTokenDelta(tokenType, delta, this.metricLabels));
  1356. this.setAttribute(attribute, normalized);
  1357. }
  1358. protected override recordTerminalDetailMetrics(
  1359. outcome: string,
  1360. observation: WriterTerminalObservation,
  1361. ): void {
  1362. this.metrics.recordModelAttemptDetail(
  1363. compactAttributes({
  1364. ...this.metricLabels,
  1365. error_category: observation.errorCategory,
  1366. outcome,
  1367. }),
  1368. {
  1369. firstContentMs: this.firstContentMs,
  1370. firstProviderEventMs: this.firstProviderEventMs,
  1371. firstTextMs: this.firstTextMs,
  1372. stallCount: this.stallCount,
  1373. streamMaxIdleMs: this.streamMaxIdleMs,
  1374. },
  1375. );
  1376. }
  1377. }
  1378. function inheritedMetadata(
  1379. parent: ActiveWriterContext | undefined,
  1380. spanName: string,
  1381. ): Omit<ActiveWriterContext, "activeContext" | "span"> {
  1382. return {
  1383. correlation: parent?.correlation,
  1384. parent,
  1385. spanName,
  1386. toolCallId: parent?.toolCallId,
  1387. };
  1388. }
  1389. function lifecycleKeys(spanName: string): WriterLifecycleKeys {
  1390. const prefix = `zcode.${spanName}`;
  1391. return {
  1392. abandonReason: `${prefix}.abandon_reason`,
  1393. cancelReason: `${prefix}.cancel_reason`,
  1394. errorCategory: `${prefix}.error_category`,
  1395. errorCode: `${prefix}.error_code`,
  1396. errorMessage: `${prefix}.error_message`,
  1397. errorType: `${prefix}.error_type`,
  1398. failureStage: `${prefix}.failure_stage`,
  1399. outcome: `${prefix}.outcome`,
  1400. };
  1401. }
  1402. function classifyErrorCategory(error: unknown): AgentTelemetryErrorCategory {
  1403. if (isAbortLike(error)) return "cancelled";
  1404. if (!error || typeof error !== "object") return "unknown";
  1405. const record = error as Record<string, unknown>;
  1406. const status = typeof record.status === "number" ? record.status : record.statusCode;
  1407. if (status === 401 || status === 403) return "authentication";
  1408. if (status === 408 || status === 504) return "timeout";
  1409. if (status === 429) return "rate_limit";
  1410. const code = String(record.code ?? "").toLowerCase();
  1411. if (code.includes("timeout")) return "timeout";
  1412. if (
  1413. code.includes("network") ||
  1414. code.includes("econn") ||
  1415. code.includes("enotfound") ||
  1416. code.includes("tls")
  1417. ) {
  1418. return "network";
  1419. }
  1420. return "unknown";
  1421. }
  1422. const NOOP_SCOPE = {
  1423. captureCausation: () => undefined,
  1424. run: <T>(execute: () => T): T => execute(),
  1425. };
  1426. const NOOP_COMMAND_WRITER: CommandExecutionSpanWriter = {
  1427. ...NOOP_SCOPE,
  1428. finishBackgrounded() {},
  1429. finishCancelled() {},
  1430. finishCompleted() {},
  1431. finishFailed() {},
  1432. markFirstOutput() {},
  1433. markTerminationRequested() {},
  1434. setExitCode() {},
  1435. setOutputBytes() {},
  1436. setSignal() {},
  1437. setTimedOut() {},
  1438. };
  1439. const NOOP_TOOL_WRITER: ToolExecutionSpanWriter = {
  1440. ...NOOP_SCOPE,
  1441. finishCancelled() {},
  1442. finishCompleted() {},
  1443. finishDenied() {},
  1444. finishFailed() {},
  1445. markPermissionRequested() {},
  1446. setOutputBytes() {},
  1447. setOutputTruncated() {},
  1448. setPermissionDecision() {},
  1449. startCommand: () => NOOP_COMMAND_WRITER,
  1450. };
  1451. const NOOP_STEP_WRITER: AgentStepSpanWriter = {
  1452. ...NOOP_SCOPE,
  1453. finishCancelled() {},
  1454. finishCompleted() {},
  1455. finishDiscarded() {},
  1456. finishFailed() {},
  1457. };
  1458. const NOOP_TURN_WRITER: AgentTurnSpanWriter = {
  1459. ...NOOP_SCOPE,
  1460. finishCancelled() {},
  1461. finishCompleted() {},
  1462. finishFailed() {},
  1463. };
  1464. const NOOP_COMPACTION_WRITER: ContextCompactionSpanWriter = {
  1465. ...NOOP_SCOPE,
  1466. finishCancelled() {},
  1467. finishCompleted() {},
  1468. finishDiscarded() {},
  1469. finishFailed() {},
  1470. markFallbackSelected() {},
  1471. setInputTokens() {},
  1472. setOutputTokens() {},
  1473. };
  1474. const NOOP_DETACHED_WRITER: DetachedOperationSpanWriter = {
  1475. ...NOOP_SCOPE,
  1476. finishCancelled() {},
  1477. finishCompleted() {},
  1478. finishFailed() {},
  1479. setResultType() {},
  1480. };
  1481. const NOOP_MODEL_ATTEMPT_WRITER: ModelAttemptSpanWriter = {
  1482. ...NOOP_SCOPE,
  1483. finishAbandoned() {},
  1484. finishCancelled() {},
  1485. finishCompleted() {},
  1486. finishFailed() {},
  1487. markFirstContent() {},
  1488. markFirstProviderEvent() {},
  1489. markFirstText() {},
  1490. markStreamStalled() {},
  1491. recordRequestObservation() {},
  1492. setCacheReadTokens() {},
  1493. setCacheWriteTokens() {},
  1494. setEffectiveReasoningBudgetTokens() {},
  1495. setEffectiveReasoningControl() {},
  1496. setEffectiveReasoningLevel() {},
  1497. setEffectiveReasoningState() {},
  1498. setFinishReason() {},
  1499. setHttpStatusCode() {},
  1500. setInputTokens() {},
  1501. setOutputTokens() {},
  1502. setProviderErrorCode() {},
  1503. setProviderErrorMessage() {},
  1504. setProviderRequestId() {},
  1505. setReasoningTokens() {},
  1506. setResponseModel() {},
  1507. setRetryAfterMs() {},
  1508. setStreamOutputCommitted() {},
  1509. };
  1510. const NOOP_MODEL_CALL_WRITER: ModelCallSpanWriter = {
  1511. ...NOOP_SCOPE,
  1512. finishAbandoned() {},
  1513. finishCancelled() {},
  1514. finishCompleted() {},
  1515. finishFailed() {},
  1516. markFallbackSelected() {},
  1517. startAttempt: () => NOOP_MODEL_ATTEMPT_WRITER,
  1518. };
  1519. export class NoopAgentExecutionTelemetry
  1520. implements AgentExecutionTelemetryPort, ModelExecutionTelemetryPort
  1521. {
  1522. abandonSession(): void {}
  1523. captureCausation() {
  1524. return undefined;
  1525. }
  1526. startCall(): ModelCallSpanWriter {
  1527. return NOOP_MODEL_CALL_WRITER;
  1528. }
  1529. startCompaction(): ContextCompactionSpanWriter {
  1530. return NOOP_COMPACTION_WRITER;
  1531. }
  1532. startDetachedOperation(): DetachedOperationSpanWriter {
  1533. return NOOP_DETACHED_WRITER;
  1534. }
  1535. startStep(): AgentStepSpanWriter {
  1536. return NOOP_STEP_WRITER;
  1537. }
  1538. startTool(): ToolExecutionSpanWriter {
  1539. return NOOP_TOOL_WRITER;
  1540. }
  1541. startTurn(): AgentTurnSpanWriter {
  1542. return NOOP_TURN_WRITER;
  1543. }
  1544. }