agent-trace-runtime.test.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  1. import { context, type Context } from "@opentelemetry/api";
  2. import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";
  3. import {
  4. BasicTracerProvider,
  5. InMemorySpanExporter,
  6. SimpleSpanProcessor,
  7. type ReadWriteSpan,
  8. type ReadableSpan,
  9. type SpanProcessor,
  10. } from "@opentelemetry/sdk-trace-base";
  11. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  12. import type { AgentTelemetryCausation } from "@zcode/contracts/telemetry";
  13. import { AgentExecutionTelemetryRuntime } from "../src/agent-trace-runtime.js";
  14. import type {
  15. AgentMetricSpanName,
  16. AgentTelemetryMetricRecorder,
  17. ModelTokenType,
  18. } from "../src/agent-metrics.js";
  19. interface Harness {
  20. activeSpans: Map<string, ReadWriteSpan>;
  21. exporter: InMemorySpanExporter;
  22. provider: BasicTracerProvider;
  23. runtime: AgentExecutionTelemetryRuntime;
  24. }
  25. let contextManager: AsyncLocalStorageContextManager;
  26. let harnesses: Harness[] = [];
  27. beforeEach(() => {
  28. context.disable();
  29. contextManager = new AsyncLocalStorageContextManager().enable();
  30. context.setGlobalContextManager(contextManager);
  31. });
  32. afterEach(async () => {
  33. for (const harness of harnesses) await harness.provider.shutdown();
  34. harnesses = [];
  35. context.disable();
  36. contextManager.disable();
  37. });
  38. describe("AgentExecutionTelemetryRuntime V5", () => {
  39. it("为 Auto Compact 记录触发时的上下文预算事实", () => {
  40. const harness = createHarness();
  41. const compaction = harness.runtime.startCompaction({
  42. maxAttempts: 3,
  43. modelMode: "streaming",
  44. phase: "pre_request",
  45. policyContextWindowTokens: 128_000,
  46. thresholdTokens: 94_000,
  47. tokenSource: "provider_usage",
  48. trigger: "auto",
  49. });
  50. compaction.setInputTokens(94_001);
  51. expect(harness.activeSpans.get("context_compaction")?.attributes).toMatchObject({
  52. "zcode.context_compaction.input_tokens": 94_001,
  53. "zcode.context_compaction.policy_context_window_tokens": 128_000,
  54. "zcode.context_compaction.threshold_tokens": 94_000,
  55. "zcode.context_compaction.token_source": "provider_usage",
  56. });
  57. compaction.finishCompleted();
  58. });
  59. it("创建稳定的 Turn -> Step -> Tool -> Command 拓扑,并由事实源写终态", async () => {
  60. const harness = createHarness();
  61. const turn = harness.runtime.startTurn({
  62. context: executionContext(),
  63. inputSource: "user",
  64. turnNumber: 3,
  65. });
  66. await turn.run(async () => {
  67. const step = harness.runtime.startStep({ stepId: "step-1", stepIndex: 0 });
  68. await step.run(async () => {
  69. const tool = harness.runtime.startTool({
  70. registeredToolName: "Bash",
  71. toolCallId: "tool-1",
  72. });
  73. await tool.run(async () => {
  74. tool.markPermissionRequested();
  75. tool.setPermissionDecision("granted");
  76. const command = tool.startCommand({
  77. category: "git",
  78. commandCount: 1,
  79. safeName: "git",
  80. sandboxed: true,
  81. shellKind: "bash",
  82. });
  83. await command.run(async () => {
  84. command.markFirstOutput();
  85. command.setExitCode(0);
  86. command.setOutputBytes(42);
  87. command.finishCompleted();
  88. });
  89. tool.setOutputBytes(42);
  90. tool.setOutputTruncated(false);
  91. tool.finishCompleted();
  92. });
  93. step.finishCompleted("tool_requested");
  94. });
  95. turn.finishCompleted("assistant_message");
  96. });
  97. const spans = harness.exporter.getFinishedSpans();
  98. expect(spans.map((span) => span.name)).toEqual([
  99. "command_execution",
  100. "tool_execution",
  101. "agent_step",
  102. "agent_turn",
  103. ]);
  104. expect(parentName(spans, "command_execution")).toBe("tool_execution");
  105. expect(parentName(spans, "tool_execution")).toBe("agent_step");
  106. expect(parentName(spans, "agent_step")).toBe("agent_turn");
  107. expect(span(spans, "command_execution").attributes).toMatchObject({
  108. "zcode.command_execution.safe_name": "git",
  109. "zcode.command_execution.exit_code": 0,
  110. "process.exit.code": 0,
  111. });
  112. expect(span(spans, "tool_execution").events.map((event) => event.name)).toEqual([
  113. "permission_requested",
  114. "permission_decided",
  115. ]);
  116. expect(
  117. Object.keys(span(spans, "agent_turn").attributes).some((key) => key.includes("span.type")),
  118. ).toBe(false);
  119. });
  120. it("run 对同步/异步异常只执行一次业务回调,并自动收口缺失 terminal", async () => {
  121. const harness = createHarness();
  122. let calls = 0;
  123. const thrown = harness.runtime.startDetachedOperation({
  124. context: executionContext(),
  125. executionKind: "foreground",
  126. operation: "workspace_generate_text",
  127. trigger: "user",
  128. });
  129. await expect(
  130. thrown.run(async () => {
  131. calls += 1;
  132. throw new Error("api_key=secret user@example.com /Users/alice/file.ts");
  133. }),
  134. ).rejects.toThrow();
  135. expect(calls).toBe(1);
  136. const missing = harness.runtime.startDetachedOperation({
  137. context: executionContext(),
  138. executionKind: "foreground",
  139. operation: "session_title_generation",
  140. trigger: "turn",
  141. });
  142. await missing.run(async () => "done");
  143. const spans = harness.exporter.getFinishedSpans();
  144. expect(spans[0]?.attributes).toMatchObject({
  145. "zcode.detached_operation.outcome": "failed",
  146. "zcode.detached_operation.failure_stage": "unhandled",
  147. });
  148. expect(String(spans[0]?.attributes["zcode.detached_operation.error_message"])).not.toContain(
  149. "secret",
  150. );
  151. expect(spans[1]?.attributes).toMatchObject({
  152. "zcode.detached_operation.outcome": "abandoned",
  153. "zcode.detached_operation.abandon_reason": "missing_terminal",
  154. });
  155. });
  156. it("Detached 使用独立 Root + Link,且身份只投影在 Turn Root", async () => {
  157. const harness = createHarness();
  158. harness.runtime.updateIdentity({
  159. identityState: "authenticated",
  160. userSubjectId: "subject-123",
  161. });
  162. const turn = harness.runtime.startTurn({
  163. context: executionContext(),
  164. turnNumber: 1,
  165. });
  166. let causation = turn.captureCausation();
  167. await turn.run(async () => {
  168. causation = harness.runtime.captureCausation();
  169. turn.finishCompleted();
  170. });
  171. causation = causation
  172. ? {
  173. ...causation,
  174. isRemote: true,
  175. traceState: "vendor=value",
  176. }
  177. : causation;
  178. const detached = harness.runtime.startDetachedOperation({
  179. causation,
  180. context: executionContext(),
  181. executionKind: "background",
  182. operation: "project_memory_extract",
  183. trigger: "turn",
  184. });
  185. detached.finishCompleted();
  186. const spans = harness.exporter.getFinishedSpans();
  187. const turnSpan = span(spans, "agent_turn");
  188. const detachedSpan = span(spans, "detached_operation");
  189. expect(detachedSpan.parentSpanContext).toBeUndefined();
  190. expect(detachedSpan.links[0]?.context.spanId).toBe(turnSpan.spanContext().spanId);
  191. expect(detachedSpan.links[0]?.context.traceId).toBe(turnSpan.spanContext().traceId);
  192. expect(detachedSpan.links[0]?.context.traceFlags).toBe(turnSpan.spanContext().traceFlags);
  193. expect(detachedSpan.links[0]?.context.traceState?.serialize()).toBe("vendor=value");
  194. expect(detachedSpan.links[0]?.context.isRemote).toBe(true);
  195. expect(detachedSpan.links[0]?.attributes).toEqual({
  196. "zcode.link.relation": "triggered_by",
  197. });
  198. expect(turnSpan.attributes).toMatchObject({
  199. "zcode.execution.identity_state": "authenticated",
  200. "zcode.execution.user_subject_id": "subject-123",
  201. });
  202. expect(detachedSpan.attributes["zcode.execution.user_subject_id"]).toBeUndefined();
  203. });
  204. it("被调用方等待的前台 Operation 使用真实 Parent,不伪造成跨 Trace Link", async () => {
  205. const harness = createHarness();
  206. const turn = harness.runtime.startTurn({
  207. context: executionContext(),
  208. turnNumber: 1,
  209. });
  210. await turn.run(async () => {
  211. const operation = harness.runtime.startDetachedOperation({
  212. causation: harness.runtime.captureCausation(),
  213. context: executionContext(),
  214. executionKind: "foreground",
  215. operation: "goal_completion_verification",
  216. targetKind: "goal",
  217. trigger: "turn",
  218. });
  219. operation.finishCompleted();
  220. turn.finishCompleted();
  221. });
  222. const spans = harness.exporter.getFinishedSpans();
  223. const turnSpan = span(spans, "agent_turn");
  224. const operationSpan = span(spans, "detached_operation");
  225. expect(operationSpan.parentSpanContext?.spanId).toBe(turnSpan.spanContext().spanId);
  226. expect(operationSpan.spanContext().traceId).toBe(turnSpan.spanContext().traceId);
  227. expect(operationSpan.links).toHaveLength(0);
  228. });
  229. it("显式 Causation 不会被执行时另一个 Active Context 覆盖", async () => {
  230. const harness = createHarness();
  231. const sourceTurn = harness.runtime.startTurn({
  232. context: { ...executionContext(), sessionId: "session-source" },
  233. turnNumber: 1,
  234. });
  235. const causation = sourceTurn.captureCausation();
  236. sourceTurn.finishCompleted();
  237. const unrelatedTurn = harness.runtime.startTurn({
  238. context: { ...executionContext(), sessionId: "session-unrelated" },
  239. turnNumber: 1,
  240. });
  241. await unrelatedTurn.run(async () => {
  242. const operation = harness.runtime.startDetachedOperation({
  243. causation,
  244. context: { ...executionContext(), sessionId: "session-child" },
  245. executionKind: "foreground",
  246. operation: "workspace_generate_text",
  247. trigger: "user",
  248. });
  249. operation.finishCompleted();
  250. unrelatedTurn.finishCompleted();
  251. });
  252. const spans = harness.exporter.getFinishedSpans();
  253. const sourceSpan = spans.find(
  254. (candidate) =>
  255. candidate.name === "agent_turn" &&
  256. candidate.attributes["zcode.execution.session_id"] === "session-source",
  257. );
  258. const unrelatedSpan = spans.find(
  259. (candidate) =>
  260. candidate.name === "agent_turn" &&
  261. candidate.attributes["zcode.execution.session_id"] === "session-unrelated",
  262. );
  263. const operationSpan = span(spans, "detached_operation");
  264. expect(operationSpan.parentSpanContext?.spanId).toBe(sourceSpan?.spanContext().spanId);
  265. expect(operationSpan.parentSpanContext?.spanId).not.toBe(unrelatedSpan?.spanContext().spanId);
  266. });
  267. it("前台 Subagent Turn 作为 Agent Tool 子树,后台 Subagent 使用独立 Trace + Link", async () => {
  268. const harness = createHarness();
  269. const parentTurn = harness.runtime.startTurn({
  270. context: executionContext(),
  271. turnNumber: 1,
  272. });
  273. let toolCausation: AgentTelemetryCausation | undefined;
  274. await parentTurn.run(async () => {
  275. const tool = harness.runtime.startTool({
  276. registeredToolName: "Agent",
  277. toolCallId: "tool-agent-1",
  278. });
  279. await tool.run(async () => {
  280. toolCausation = tool.captureCausation();
  281. const childTurn = harness.runtime.startTurn({
  282. causation: toolCausation,
  283. causationMode: "child",
  284. context: {
  285. actorKind: "subagent",
  286. agentName: "zcode-general-purpose",
  287. launchSurface: "desktop",
  288. parentSessionId: "session-1",
  289. sessionId: "session-child",
  290. turnId: "turn-child",
  291. },
  292. turnNumber: 0,
  293. });
  294. await childTurn.run(async () => {
  295. const childStep = harness.runtime.startStep({
  296. stepId: "step-child",
  297. stepIndex: 0,
  298. });
  299. await childStep.run(async () => {
  300. const call = harness.runtime.startCall({
  301. logicalCallId: "logical-child",
  302. operation: "agent_step",
  303. requested: {
  304. providerId: "provider-child",
  305. reasoning: {
  306. capability: "supported",
  307. effectiveControl: "fixed_level",
  308. effectiveState: "enabled",
  309. requestedControl: "fixed_level",
  310. requestedState: "enabled",
  311. },
  312. requestedModel: "model-child",
  313. },
  314. streaming: true,
  315. });
  316. await call.run(async () => {
  317. const attempt = call.startAttempt({
  318. apiOperation: "messages",
  319. attemptCause: "initial",
  320. attemptNumber: 1,
  321. requestId: "request-child",
  322. target: {
  323. providerId: "provider-child",
  324. providerKind: "anthropic",
  325. reasoning: {
  326. capability: "supported",
  327. effectiveControl: "fixed_level",
  328. effectiveState: "enabled",
  329. requestedControl: "fixed_level",
  330. requestedState: "enabled",
  331. },
  332. requestedModel: "model-child",
  333. },
  334. transport: "sse",
  335. });
  336. attempt.finishCompleted();
  337. call.finishCompleted();
  338. });
  339. const childTool = harness.runtime.startTool({
  340. registeredToolName: "Bash",
  341. toolCallId: "tool-child-bash",
  342. });
  343. await childTool.run(async () => {
  344. const command = childTool.startCommand({
  345. category: "git",
  346. commandCount: 1,
  347. safeName: "git",
  348. sandboxed: true,
  349. shellKind: "bash",
  350. });
  351. command.finishCompleted();
  352. childTool.finishCompleted();
  353. });
  354. childStep.finishCompleted("turn_completed");
  355. });
  356. childTurn.finishCompleted("assistant_message");
  357. });
  358. tool.finishCompleted();
  359. });
  360. parentTurn.finishCompleted("tool_request");
  361. });
  362. const backgroundTurn = harness.runtime.startTurn({
  363. causation: toolCausation,
  364. causationMode: "linked_root",
  365. context: {
  366. actorKind: "subagent",
  367. agentName: "zcode-general-purpose",
  368. launchSurface: "desktop",
  369. parentSessionId: "session-1",
  370. sessionId: "session-background",
  371. turnId: "turn-background",
  372. },
  373. turnNumber: 0,
  374. });
  375. backgroundTurn.finishCompleted("assistant_message");
  376. const spans = harness.exporter.getFinishedSpans();
  377. const toolSpan = spans.find(
  378. (candidate) =>
  379. candidate.name === "tool_execution" &&
  380. candidate.attributes["zcode.execution.tool_call_id"] === "tool-agent-1",
  381. );
  382. const foregroundTurn = spans.find(
  383. (candidate) =>
  384. candidate.name === "agent_turn" &&
  385. candidate.attributes["zcode.execution.session_id"] === "session-child",
  386. );
  387. const foregroundStep = spans.find(
  388. (candidate) =>
  389. candidate.name === "agent_step" &&
  390. candidate.attributes["zcode.execution.turn_id"] === "turn-child",
  391. );
  392. const foregroundCall = spans.find(
  393. (candidate) =>
  394. candidate.name === "model_call" &&
  395. candidate.attributes["zcode.execution.turn_id"] === "turn-child",
  396. );
  397. const foregroundAttempt = spans.find(
  398. (candidate) =>
  399. candidate.name === "model_attempt" &&
  400. candidate.attributes["zcode.execution.turn_id"] === "turn-child",
  401. );
  402. const foregroundTool = spans.find(
  403. (candidate) =>
  404. candidate.name === "tool_execution" &&
  405. candidate.attributes["zcode.execution.tool_call_id"] === "tool-child-bash",
  406. );
  407. const foregroundCommand = spans.find(
  408. (candidate) =>
  409. candidate.name === "command_execution" &&
  410. candidate.attributes["zcode.execution.tool_call_id"] === "tool-child-bash",
  411. );
  412. const linkedTurn = spans.find(
  413. (candidate) =>
  414. candidate.name === "agent_turn" &&
  415. candidate.attributes["zcode.execution.session_id"] === "session-background",
  416. );
  417. expect(foregroundTurn?.parentSpanContext?.spanId).toBe(toolSpan?.spanContext().spanId);
  418. expect(foregroundTurn?.spanContext().traceId).toBe(toolSpan?.spanContext().traceId);
  419. expect(foregroundStep?.parentSpanContext?.spanId).toBe(foregroundTurn?.spanContext().spanId);
  420. expect(foregroundCall?.parentSpanContext?.spanId).toBe(foregroundStep?.spanContext().spanId);
  421. expect(foregroundAttempt?.parentSpanContext?.spanId).toBe(foregroundCall?.spanContext().spanId);
  422. expect(foregroundTool?.parentSpanContext?.spanId).toBe(foregroundStep?.spanContext().spanId);
  423. expect(foregroundCommand?.parentSpanContext?.spanId).toBe(foregroundTool?.spanContext().spanId);
  424. for (const child of [
  425. foregroundTurn,
  426. foregroundStep,
  427. foregroundCall,
  428. foregroundAttempt,
  429. foregroundTool,
  430. foregroundCommand,
  431. ]) {
  432. expect(child?.spanContext().traceId).toBe(toolSpan?.spanContext().traceId);
  433. }
  434. expect(linkedTurn?.parentSpanContext).toBeUndefined();
  435. expect(linkedTurn?.links[0]?.context.spanId).toBe(toolSpan?.spanContext().spanId);
  436. expect(linkedTurn?.links[0]?.attributes).toEqual({
  437. "zcode.link.relation": "spawned_by",
  438. });
  439. });
  440. it("Tool 与 Command 不共享退出码语义,非命令 Tool 不产生 exit code", () => {
  441. const harness = createHarness();
  442. const tool = harness.runtime.startTool({
  443. registeredToolName: "Read",
  444. toolCallId: "tool-read",
  445. });
  446. tool.finishCompleted();
  447. const toolSpan = span(harness.exporter.getFinishedSpans(), "tool_execution");
  448. expect(toolSpan.attributes["zcode.tool_execution.exit_code"]).toBeUndefined();
  449. expect(toolSpan.attributes["process.exit.code"]).toBeUndefined();
  450. });
  451. it("显式失败接口保留清洗后的错误归因", () => {
  452. const harness = createHarness();
  453. const error = Object.assign(new Error("authorization: Bearer private-token user@example.com"), {
  454. code: "E_PROVIDER",
  455. });
  456. const turn = harness.runtime.startTurn({
  457. context: executionContext(),
  458. turnNumber: 1,
  459. });
  460. turn.finishFailed("agent_loop", "provider", error);
  461. expect(span(harness.exporter.getFinishedSpans(), "agent_turn").attributes).toMatchObject({
  462. "zcode.agent_turn.error_category": "provider",
  463. "zcode.agent_turn.error_code": "E_PROVIDER",
  464. "zcode.agent_turn.error_type": "Error",
  465. "zcode.agent_turn.outcome": "failed",
  466. });
  467. const message = String(
  468. span(harness.exporter.getFinishedSpans(), "agent_turn").attributes[
  469. "zcode.agent_turn.error_message"
  470. ],
  471. );
  472. expect(message).not.toContain("private-token");
  473. expect(message).not.toContain("user@example.com");
  474. expect(span(harness.exporter.getFinishedSpans(), "agent_turn").attributes).not.toHaveProperty(
  475. "error.cause.message",
  476. );
  477. });
  478. it("同一源异常只在最靠近来源的 Span 记录一次正文", () => {
  479. const harness = createHarness();
  480. const networkCause = Object.assign(
  481. new Error("socket reset authorization: Bearer secret-token"),
  482. { code: "ECONNRESET" },
  483. );
  484. const source = Object.assign(
  485. new Error("provider request req-raw-123 failed", { cause: networkCause }),
  486. {
  487. code: "E_PROVIDER",
  488. },
  489. );
  490. const call = harness.runtime.startCall({
  491. logicalCallId: "logical-error",
  492. operation: "agent_step",
  493. requested: {
  494. providerId: "provider-1",
  495. reasoning: {
  496. capability: "supported",
  497. effectiveControl: "fixed_level",
  498. effectiveState: "enabled",
  499. requestedControl: "fixed_level",
  500. requestedState: "enabled",
  501. },
  502. requestedModel: "claude-test",
  503. },
  504. streaming: true,
  505. });
  506. const attempt = call.startAttempt({
  507. apiOperation: "messages",
  508. attemptCause: "initial",
  509. attemptNumber: 1,
  510. requestId: "request-error",
  511. target: {
  512. providerId: "provider-1",
  513. providerKind: "anthropic",
  514. reasoning: {
  515. capability: "supported",
  516. effectiveControl: "fixed_level",
  517. effectiveState: "enabled",
  518. requestedControl: "fixed_level",
  519. requestedState: "enabled",
  520. },
  521. requestedModel: "claude-test",
  522. },
  523. transport: "sse",
  524. });
  525. attempt.finishFailed("response", "provider", source);
  526. call.finishFailed("attempts", "provider", new Error("classified wrapper", { cause: source }));
  527. const spans = harness.exporter.getFinishedSpans();
  528. expect(span(spans, "model_attempt").attributes).toMatchObject({
  529. "zcode.model_attempt.error_code": "E_PROVIDER",
  530. "zcode.model_attempt.error_message": "provider request req-raw-123 failed",
  531. "error.cause.code": "ECONNRESET",
  532. "error.cause.type": "Error",
  533. "error.cause.message": "socket reset authorization: {redacted}",
  534. });
  535. expect(span(spans, "model_call").attributes).toMatchObject({
  536. "zcode.model_call.failure_stage": "attempts",
  537. "zcode.model_call.outcome": "failed",
  538. });
  539. expect(span(spans, "model_call").attributes).not.toHaveProperty(
  540. "zcode.model_call.error_message",
  541. );
  542. expect(span(spans, "model_call").attributes).not.toHaveProperty("error.cause.message");
  543. });
  544. it("活动 Writer 达到容量时旁路新 Span,不阻塞业务", () => {
  545. const harness = createHarness({ maxActiveWriters: 1 });
  546. const first = harness.runtime.startTurn({
  547. context: executionContext(),
  548. turnNumber: 1,
  549. });
  550. const second = harness.runtime.startTurn({
  551. context: executionContext(),
  552. turnNumber: 2,
  553. });
  554. expect(second.run(() => "business-result")).toBe("business-result");
  555. harness.runtime.abandonSession("session-1");
  556. expect(harness.exporter.getFinishedSpans()).toHaveLength(1);
  557. expect(harness.exporter.getFinishedSpans()[0]?.attributes).toMatchObject({
  558. "zcode.agent_turn.abandon_reason": "session_shutdown",
  559. });
  560. first.finishCompleted();
  561. });
  562. it("原始 usage 只写 Attempt,父 Span 不复制无必要聚合", async () => {
  563. const harness = createHarness();
  564. const turn = harness.runtime.startTurn({
  565. context: executionContext(),
  566. turnNumber: 1,
  567. });
  568. await turn.run(async () => {
  569. const call = harness.runtime.startCall({
  570. logicalCallId: "logical-1",
  571. operation: "agent_step",
  572. requested: {
  573. providerId: "provider-1",
  574. reasoning: {
  575. capability: "supported",
  576. effectiveControl: "fixed_level",
  577. effectiveState: "enabled",
  578. requestedControl: "fixed_level",
  579. requestedState: "enabled",
  580. },
  581. requestedModel: "claude-test",
  582. },
  583. streaming: true,
  584. });
  585. const attempt = call.startAttempt({
  586. apiOperation: "messages",
  587. attemptCause: "initial",
  588. attemptNumber: 1,
  589. requestId: "request-1",
  590. target: {
  591. providerId: "provider-1",
  592. providerKind: "anthropic",
  593. reasoning: {
  594. capability: "supported",
  595. effectiveControl: "fixed_level",
  596. effectiveState: "enabled",
  597. requestedControl: "fixed_level",
  598. requestedState: "enabled",
  599. },
  600. requestedModel: "claude-test",
  601. },
  602. transport: "sse",
  603. });
  604. attempt.setInputTokens(12);
  605. attempt.setOutputTokens(4);
  606. expect(harness.activeSpans.get("model_attempt")?.attributes).toMatchObject({
  607. "zcode.model_attempt.input_tokens": 12,
  608. "zcode.model_attempt.output_tokens": 4,
  609. });
  610. expect(harness.activeSpans.get("model_call")?.attributes).not.toHaveProperty(
  611. "zcode.model_call.provider_input_tokens_total",
  612. );
  613. expect(harness.activeSpans.get("agent_turn")?.attributes).not.toHaveProperty(
  614. "zcode.agent_turn.provider_input_tokens_total",
  615. );
  616. attempt.finishCompleted();
  617. call.finishCompleted();
  618. turn.finishCompleted();
  619. });
  620. });
  621. it("missing terminal 和进程回收仍会输出终态明细 Metric", async () => {
  622. const metrics = new RecordingMetrics();
  623. const harness = createHarness({ metrics });
  624. const turn = harness.runtime.startTurn({
  625. context: executionContext(),
  626. turnNumber: 1,
  627. });
  628. await turn.run(async () => {
  629. const call = harness.runtime.startCall({
  630. logicalCallId: "logical-abandoned",
  631. operation: "agent_step",
  632. requested: {
  633. providerId: "provider-1",
  634. reasoning: {
  635. capability: "supported",
  636. effectiveControl: "fixed_level",
  637. effectiveState: "enabled",
  638. requestedControl: "fixed_level",
  639. requestedState: "enabled",
  640. },
  641. requestedModel: "claude-test",
  642. },
  643. streaming: true,
  644. });
  645. await call.run(async () => {
  646. const attempt = call.startAttempt({
  647. apiOperation: "messages",
  648. attemptCause: "initial",
  649. attemptNumber: 1,
  650. requestId: "request-abandoned",
  651. target: {
  652. providerId: "provider-1",
  653. providerKind: "anthropic",
  654. reasoning: {
  655. capability: "supported",
  656. effectiveControl: "fixed_level",
  657. effectiveState: "enabled",
  658. requestedControl: "fixed_level",
  659. requestedState: "enabled",
  660. },
  661. requestedModel: "claude-test",
  662. },
  663. transport: "sse",
  664. });
  665. await attempt.run(async () => {
  666. attempt.markFirstContent();
  667. });
  668. call.finishCompleted();
  669. });
  670. turn.finishCompleted();
  671. });
  672. expect(metrics.modelAttemptDetails).toHaveLength(1);
  673. expect(metrics.modelAttemptDetails[0]).toMatchObject({
  674. labels: { outcome: "abandoned" },
  675. });
  676. });
  677. });
  678. function createHarness(
  679. options: {
  680. maxActiveWriters?: number;
  681. metrics?: AgentTelemetryMetricRecorder;
  682. } = {},
  683. ): Harness {
  684. const exporter = new InMemorySpanExporter();
  685. const inspector = new InspectingSpanProcessor();
  686. const provider = new BasicTracerProvider({
  687. spanProcessors: [inspector, new SimpleSpanProcessor(exporter)],
  688. });
  689. const runtime = new AgentExecutionTelemetryRuntime({
  690. maxActiveWriters: options.maxActiveWriters,
  691. metrics: options.metrics,
  692. tracer: provider.getTracer("test"),
  693. });
  694. const harness = { activeSpans: inspector.activeSpans, exporter, provider, runtime };
  695. harnesses.push(harness);
  696. return harness;
  697. }
  698. class RecordingMetrics implements AgentTelemetryMetricRecorder {
  699. readonly modelAttemptDetails: Array<{
  700. detail: {
  701. firstContentMs?: number;
  702. firstProviderEventMs?: number;
  703. firstTextMs?: number;
  704. stallCount: number;
  705. streamMaxIdleMs: number;
  706. };
  707. labels: Record<string, unknown>;
  708. }> = [];
  709. recordCommandFirstOutput() {}
  710. recordCreationDrop() {}
  711. recordModelCallAttempts() {}
  712. recordModelTokenDelta(_tokenType: ModelTokenType) {}
  713. recordSpanTerminal(_spanName: AgentMetricSpanName) {}
  714. recordModelAttemptDetail(
  715. labels: Record<string, unknown>,
  716. detail: {
  717. firstContentMs?: number;
  718. firstProviderEventMs?: number;
  719. firstTextMs?: number;
  720. stallCount: number;
  721. streamMaxIdleMs: number;
  722. },
  723. ): void {
  724. this.modelAttemptDetails.push({ detail, labels });
  725. }
  726. }
  727. class InspectingSpanProcessor implements SpanProcessor {
  728. readonly activeSpans = new Map<string, ReadWriteSpan>();
  729. forceFlush(): Promise<void> {
  730. return Promise.resolve();
  731. }
  732. onEnd(span: ReadableSpan): void {
  733. this.activeSpans.delete(span.name);
  734. }
  735. onStart(span: ReadWriteSpan, _parentContext: Context): void {
  736. this.activeSpans.set(span.name, span);
  737. }
  738. shutdown(): Promise<void> {
  739. return Promise.resolve();
  740. }
  741. }
  742. function executionContext() {
  743. return {
  744. actorKind: "main" as const,
  745. launchSurface: "desktop" as const,
  746. queryId: "query-1",
  747. sessionId: "session-1",
  748. turnId: "turn-1",
  749. };
  750. }
  751. function span(spans: ReadableSpan[], name: string): ReadableSpan {
  752. const found = spans.find((candidate) => candidate.name === name);
  753. if (!found) throw new Error(`Missing ${name}`);
  754. return found;
  755. }
  756. function parentName(spans: ReadableSpan[], childName: string): string | undefined {
  757. const child = span(spans, childName);
  758. return spans.find(
  759. (candidate) => candidate.spanContext().spanId === child.parentSpanContext?.spanId,
  760. )?.name;
  761. }