runtime-agent-telemetry.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. import { describe, expect, it, vi } from "vitest";
  2. import type { AgentExecutionTelemetryPort } from "@zcode/contracts";
  3. import { createSessionId } from "@zcode/contracts";
  4. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  5. import { createTestSessionEventStore } from "./test-event-store.js";
  6. import { createTestModelFactory } from "./test-runtime-model.js";
  7. describe("AgentRuntime telemetry integration", () => {
  8. it("Auto Compact 复用策略决策值上报当前占用、窗口和阈值", async () => {
  9. const lifecycle: string[] = [];
  10. const compactionStarts: Array<Parameters<AgentExecutionTelemetryPort["startCompaction"]>[0]> =
  11. [];
  12. const compactionInputTokens: number[] = [];
  13. const telemetry = createRecordingTelemetry(lifecycle);
  14. const startCompaction = telemetry.startCompaction.bind(telemetry);
  15. telemetry.startCompaction = (input) => {
  16. compactionStarts.push(input);
  17. const writer = startCompaction(input);
  18. return {
  19. ...writer,
  20. setInputTokens(tokens) {
  21. compactionInputTokens.push(tokens);
  22. writer.setInputTokens(tokens);
  23. },
  24. };
  25. };
  26. const info = vi.fn();
  27. const logger = {
  28. child: () => logger,
  29. debug: vi.fn(),
  30. error: vi.fn(),
  31. info,
  32. warn: vi.fn(),
  33. };
  34. let mainRequestCount = 0;
  35. const runtime = createTestAgentRuntime(
  36. createSessionId("runtime-auto-compact-telemetry"),
  37. {
  38. maxOutputTokens: 64_000,
  39. modelContextBudgetStrategy: "preflight-v1",
  40. modelStreaming: "off",
  41. },
  42. {
  43. agentTelemetry: telemetry,
  44. eventStore: createTestSessionEventStore(),
  45. logger,
  46. modelFactory: createTestModelFactory({
  47. properties: { contextWindow: 128_000 },
  48. async generateText(_request, observation) {
  49. if (observation.invocationContext?.modelCall?.operation === "context_compaction") {
  50. return {
  51. finishReason: "stop",
  52. providerMetadata: undefined,
  53. text: "<summary>Telemetry compact summary.</summary>",
  54. toolCalls: [],
  55. usage: { inputTokens: 100, outputTokens: 10, totalTokens: 110 },
  56. };
  57. }
  58. mainRequestCount += 1;
  59. return {
  60. finishReason: "stop",
  61. providerMetadata: undefined,
  62. text: `response-${mainRequestCount}`,
  63. toolCalls: [],
  64. usage:
  65. mainRequestCount === 1
  66. ? { inputTokens: 94_001, outputTokens: 1, totalTokens: 94_002 }
  67. : { inputTokens: 2, outputTokens: 1, totalTokens: 3 },
  68. };
  69. },
  70. } as never),
  71. },
  72. );
  73. await runtime.executeTurn("seed provider usage");
  74. await runtime.executeTurn("trigger auto compact");
  75. const decisionLog = info.mock.calls
  76. .map((call) => call[1])
  77. .find((context) => context?.event === "compact.auto.started");
  78. expect(decisionLog).toMatchObject({
  79. contextWindow: 128_000,
  80. threshold: 94_000,
  81. tokenSource: "provider_usage",
  82. });
  83. expect(compactionStarts).toHaveLength(1);
  84. expect(compactionStarts[0]).toMatchObject({
  85. phase: "pre_request",
  86. policyContextWindowTokens: 128_000,
  87. thresholdTokens: 94_000,
  88. tokenSource: "provider_usage",
  89. trigger: "auto",
  90. });
  91. expect(compactionInputTokens).toEqual([decisionLog.tokenCount]);
  92. });
  93. it("只在 Turn/Step 权威边界调用端口,并由 Scope 包裹真实模型执行", async () => {
  94. const lifecycle: string[] = [];
  95. const telemetry = createRecordingTelemetry(lifecycle);
  96. const runtime = createTestAgentRuntime(
  97. createSessionId("runtime-agent-telemetry"),
  98. {
  99. modelStreaming: "off",
  100. workingDirectory: "/tmp/runtime-agent-telemetry",
  101. },
  102. {
  103. agentTelemetry: telemetry,
  104. eventStore: createTestSessionEventStore(),
  105. modelFactory: createTestModelFactory({
  106. async generateText() {
  107. lifecycle.push("model.execute");
  108. return {
  109. finishReason: "stop",
  110. providerMetadata: undefined,
  111. text: "done",
  112. toolCalls: [],
  113. usage: { inputTokens: 2, outputTokens: 1, totalTokens: 3 },
  114. };
  115. },
  116. } as never),
  117. },
  118. );
  119. const result = await runtime.executeTurn("hello");
  120. expect(result.response).toBe("done");
  121. expect(lifecycle).toEqual([
  122. "turn.start",
  123. "turn.run",
  124. "step.start",
  125. "step.run",
  126. "model.execute",
  127. "step.end:completed",
  128. "turn.end:completed",
  129. ]);
  130. });
  131. it.each([
  132. ["child", "child"],
  133. ["linked_root", "linked_root"],
  134. ] as const)(
  135. "Subagent Runtime 继续产生完整 Turn/Step,并保留 %s 因果模式",
  136. async (_label, causationMode) => {
  137. const lifecycle: string[] = [];
  138. const parentSessionId = createSessionId("runtime-subagent-parent");
  139. const turnStarts: Parameters<AgentExecutionTelemetryPort["startTurn"]>[0][] = [];
  140. const stepStarts: Parameters<AgentExecutionTelemetryPort["startStep"]>[0][] = [];
  141. const modelCalls: unknown[] = [];
  142. const telemetry = createRecordingTelemetry(lifecycle);
  143. const startTurn = telemetry.startTurn.bind(telemetry);
  144. const startStep = telemetry.startStep.bind(telemetry);
  145. telemetry.startTurn = (input) => {
  146. turnStarts.push(input);
  147. return startTurn(input);
  148. };
  149. telemetry.startStep = (input) => {
  150. stepStarts.push(input);
  151. return startStep(input);
  152. };
  153. const runtime = createTestAgentRuntime(
  154. createSessionId(`runtime-subagent-telemetry-${causationMode}`),
  155. {
  156. agentName: "zcode-general-purpose",
  157. modelStreaming: "off",
  158. parentSessionId,
  159. taskType: "subagent_child",
  160. workingDirectory: "/tmp/runtime-subagent-telemetry",
  161. },
  162. {
  163. agentTelemetry: telemetry,
  164. agentTelemetryCausation: {
  165. isRemote: false,
  166. sessionId: String(parentSessionId),
  167. spanId: "1234567890abcdef",
  168. traceFlags: 1,
  169. traceId: "1234567890abcdef1234567890abcdef",
  170. turnId: "turn-parent",
  171. },
  172. agentTelemetryCausationMode: causationMode,
  173. eventStore: createTestSessionEventStore(),
  174. modelFactory: createTestModelFactory({
  175. async generateText(_request, observation) {
  176. modelCalls.push(observation.invocationContext?.modelCall);
  177. return {
  178. finishReason: "stop",
  179. providerMetadata: undefined,
  180. text: "child done",
  181. toolCalls: [],
  182. usage: { inputTokens: 2, outputTokens: 1, totalTokens: 3 },
  183. };
  184. },
  185. } as never),
  186. },
  187. );
  188. await runtime.executeTurn("child prompt", undefined, {
  189. inputSource: "subagent",
  190. });
  191. expect(turnStarts).toHaveLength(1);
  192. expect(turnStarts[0]).toMatchObject({
  193. causationMode,
  194. context: {
  195. actorKind: "subagent",
  196. agentName: "zcode-general-purpose",
  197. parentSessionId,
  198. parentTurnId: "turn-parent",
  199. },
  200. inputSource: "subagent",
  201. });
  202. expect(stepStarts).toHaveLength(1);
  203. expect(stepStarts[0]).toMatchObject({ stepIndex: 0 });
  204. expect(modelCalls).toEqual([
  205. expect.objectContaining({
  206. actorKind: "subagent",
  207. operation: "agent_step",
  208. }),
  209. ]);
  210. },
  211. );
  212. });
  213. function createRecordingTelemetry(lifecycle: string[]): AgentExecutionTelemetryPort {
  214. return {
  215. abandonSession() {},
  216. captureCausation() {
  217. return undefined;
  218. },
  219. startCompaction() {
  220. lifecycle.push("compaction.start");
  221. return {
  222. ...recordingBase("compaction", lifecycle),
  223. finishCancelled: (reason: string) => lifecycle.push(`compaction.cancel:${reason}`),
  224. finishCompleted: () => lifecycle.push("compaction.end:completed"),
  225. finishDiscarded: () => lifecycle.push("compaction.end:discarded"),
  226. finishFailed: (stage: string) => lifecycle.push(`compaction.fail:${stage}`),
  227. markFallbackSelected() {},
  228. setInputTokens() {},
  229. setOutputTokens() {},
  230. };
  231. },
  232. startDetachedOperation(input) {
  233. lifecycle.push(`detached.start:${input.operation}`);
  234. return {
  235. ...recordingBase("detached", lifecycle),
  236. finishCancelled: (reason: string) => lifecycle.push(`detached.cancel:${reason}`),
  237. finishCompleted: () => lifecycle.push("detached.end:completed"),
  238. finishFailed: (stage: string) => lifecycle.push(`detached.fail:${stage}`),
  239. setResultType() {},
  240. };
  241. },
  242. startStep() {
  243. lifecycle.push("step.start");
  244. return {
  245. ...recordingBase("step", lifecycle),
  246. finishCancelled: (reason: string) => lifecycle.push(`step.cancel:${reason}`),
  247. finishCompleted: () => lifecycle.push("step.end:completed"),
  248. finishDiscarded: () => lifecycle.push("step.end:discarded"),
  249. finishFailed: (stage: string) => lifecycle.push(`step.fail:${stage}`),
  250. };
  251. },
  252. startTool() {
  253. lifecycle.push("tool.start");
  254. return {
  255. ...recordingBase("tool", lifecycle),
  256. finishCancelled: (reason: string) => lifecycle.push(`tool.cancel:${reason}`),
  257. finishCompleted: () => lifecycle.push("tool.end:completed"),
  258. finishDenied: (reason: string) => lifecycle.push(`tool.denied:${reason}`),
  259. finishFailed: (stage: string) => lifecycle.push(`tool.fail:${stage}`),
  260. markPermissionRequested() {},
  261. setOutputBytes() {},
  262. setOutputTruncated() {},
  263. setPermissionDecision() {},
  264. startCommand() {
  265. throw new Error("command writer is not used by this test");
  266. },
  267. };
  268. },
  269. startTurn() {
  270. lifecycle.push("turn.start");
  271. return {
  272. ...recordingBase("turn", lifecycle),
  273. finishCancelled: (reason: string) => lifecycle.push(`turn.cancel:${reason}`),
  274. finishCompleted: () => lifecycle.push("turn.end:completed"),
  275. finishFailed: (stage: string) => lifecycle.push(`turn.fail:${stage}`),
  276. };
  277. },
  278. };
  279. }
  280. function recordingBase(name: string, lifecycle: string[]) {
  281. return {
  282. captureCausation: () => undefined,
  283. run<R>(fn: () => R): R {
  284. lifecycle.push(`${name}.run`);
  285. return fn();
  286. },
  287. };
  288. }