tool-agent-telemetry.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. import { describe, expect, it } from "vitest";
  2. import type {
  3. AgentExecutionTelemetryPort,
  4. ToolExecutionSpanWriter,
  5. ToolTraceStart,
  6. } from "@zcode/contracts";
  7. import {
  8. HookEventName,
  9. createRootTraceContext,
  10. createSessionId,
  11. createToolCallId,
  12. createTurnId,
  13. } from "@zcode/contracts";
  14. import { createInMemoryHookRunner } from "../src/hooks/index.js";
  15. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  16. import { createToolExecutor } from "../src/tool/executor.js";
  17. import { createToolRegistry } from "../src/tool/registry.js";
  18. describe("ToolExecutor Agent telemetry", () => {
  19. it("在统一 Executor 边界使用 canonical tool name 包裹完整执行", async () => {
  20. const lifecycle: string[] = [];
  21. let start: ToolTraceStart | undefined;
  22. const sessionId = createSessionId("tool-agent-telemetry");
  23. const turnId = createTurnId("turn-agent-telemetry");
  24. const toolCallId = createToolCallId("tool-call-agent-telemetry");
  25. const traceContext = createRootTraceContext({ sessionId, turnId });
  26. const registry = createToolRegistry();
  27. registry.register({
  28. aliases: ["TraceAlias"],
  29. inputSchema: {},
  30. metadata: {
  31. concurrentSafe: true,
  32. destructive: false,
  33. name: "TraceCanonical",
  34. needsApproval: false,
  35. readOnly: true,
  36. riskLevel: "low",
  37. sideEffectScope: "none",
  38. },
  39. handler: async () => {
  40. lifecycle.push("handler.execute");
  41. return "ok";
  42. },
  43. });
  44. const executor = createToolExecutor({
  45. agentTelemetry: recordingTelemetry(lifecycle, (input) => {
  46. start = input;
  47. }),
  48. agentTelemetryActorKind: "workflow_child",
  49. emitEvent: async () => {},
  50. permissionService: new PermissionService(defaultPermissionConfig),
  51. registry,
  52. sessionId,
  53. turnId,
  54. traceContext,
  55. });
  56. const result = await executor.execute(
  57. {
  58. id: toolCallId,
  59. input: {},
  60. name: "TraceAlias",
  61. },
  62. { traceContext },
  63. );
  64. expect(result.success).toBe(true);
  65. expect(start).toMatchObject({
  66. registeredToolName: "TraceCanonical",
  67. toolCallId,
  68. });
  69. expect(lifecycle).toEqual([
  70. "tool.start",
  71. "tool.run",
  72. "permission:not_required",
  73. "handler.execute",
  74. "tool.output_bytes",
  75. "tool.output_truncated:false",
  76. "tool.end:completed",
  77. ]);
  78. });
  79. it("在真实序列化边界写入输出大小并正常收口", async () => {
  80. const lifecycle: string[] = [];
  81. const sessionId = createSessionId("tool-agent-performance");
  82. const turnId = createTurnId("turn-agent-performance");
  83. const registry = createToolRegistry();
  84. registry.register({
  85. inputSchema: {},
  86. metadata: {
  87. concurrentSafe: true,
  88. destructive: false,
  89. name: "BashLike",
  90. needsApproval: false,
  91. readOnly: true,
  92. riskLevel: "low",
  93. sideEffectScope: "none",
  94. },
  95. handler: async () => ({
  96. stdout: "",
  97. perf: {
  98. detail: {
  99. kind: "command",
  100. command: {
  101. category: "git",
  102. count: 1,
  103. hash: "0123456789abcdef",
  104. name: "git",
  105. runMs: 12,
  106. status: "failed",
  107. exitCode: 2,
  108. },
  109. },
  110. },
  111. }),
  112. });
  113. const executor = createToolExecutor({
  114. agentTelemetry: recordingTelemetry(lifecycle, () => {}),
  115. emitEvent: async () => {},
  116. permissionService: new PermissionService(defaultPermissionConfig),
  117. registry,
  118. sessionId,
  119. turnId,
  120. });
  121. await executor.execute({
  122. id: createToolCallId("tool-call-agent-performance"),
  123. input: {},
  124. name: "BashLike",
  125. });
  126. expect(lifecycle).toEqual(
  127. expect.arrayContaining([
  128. "tool.output_bytes",
  129. "tool.output_truncated:false",
  130. "tool.end:completed",
  131. ]),
  132. );
  133. });
  134. it("未注册工具名在远端 Trace 中归入 unknown,业务错误仍保留原名", async () => {
  135. let start: ToolTraceStart | undefined;
  136. const sessionId = createSessionId("tool-agent-unknown");
  137. const turnId = createTurnId("turn-agent-unknown");
  138. const registry = createToolRegistry();
  139. const executor = createToolExecutor({
  140. agentTelemetry: recordingTelemetry([], (input) => {
  141. start = input;
  142. }),
  143. emitEvent: async () => {},
  144. permissionService: new PermissionService(defaultPermissionConfig),
  145. registry,
  146. sessionId,
  147. turnId,
  148. });
  149. const result = await executor.execute({
  150. id: createToolCallId("tool-call-agent-unknown"),
  151. input: {},
  152. name: "untrusted-user-derived-tool-name",
  153. });
  154. expect(start?.registeredToolName).toBe("unknown");
  155. expect(result.success).toBe(false);
  156. expect(result.toolName).toBe("untrusted-user-derived-tool-name");
  157. });
  158. it("工具专属语义校验失败按 validation 显式收口", async () => {
  159. const lifecycle: string[] = [];
  160. let handlerCalled = false;
  161. const registry = createToolRegistry();
  162. registry.register({
  163. inputSchema: {},
  164. metadata: {
  165. concurrentSafe: true,
  166. destructive: false,
  167. name: "SemanticValidationTool",
  168. needsApproval: false,
  169. readOnly: true,
  170. riskLevel: "low",
  171. sideEffectScope: "none",
  172. },
  173. validateInput: () => ({
  174. errorCode: 422,
  175. message: "semantic input rejected",
  176. result: false,
  177. }),
  178. handler: async () => {
  179. handlerCalled = true;
  180. return "unexpected";
  181. },
  182. });
  183. const executor = createToolExecutor({
  184. agentTelemetry: recordingTelemetry(lifecycle, () => {}),
  185. emitEvent: async () => {},
  186. permissionService: new PermissionService(defaultPermissionConfig),
  187. registry,
  188. sessionId: createSessionId("tool-agent-semantic-validation"),
  189. turnId: createTurnId("turn-agent-semantic-validation"),
  190. });
  191. const result = await executor.execute({
  192. id: createToolCallId("tool-call-agent-semantic-validation"),
  193. input: {},
  194. name: "SemanticValidationTool",
  195. });
  196. expect(result.success).toBe(false);
  197. expect(handlerCalled).toBe(false);
  198. expect(lifecycle).toEqual(["tool.start", "tool.run", "tool.fail:validation"]);
  199. });
  200. it("进入 handler 前已取消时按 abort_signal 显式收口", async () => {
  201. const lifecycle: string[] = [];
  202. const controller = new AbortController();
  203. controller.abort(new Error("cancel before execution"));
  204. const registry = createToolRegistry();
  205. registry.register({
  206. inputSchema: {},
  207. metadata: {
  208. concurrentSafe: true,
  209. destructive: false,
  210. name: "CancelledBeforeHandler",
  211. needsApproval: false,
  212. readOnly: true,
  213. riskLevel: "low",
  214. sideEffectScope: "none",
  215. },
  216. handler: async () => "unexpected",
  217. });
  218. const executor = createToolExecutor({
  219. agentTelemetry: recordingTelemetry(lifecycle, () => {}),
  220. emitEvent: async () => {},
  221. permissionService: new PermissionService(defaultPermissionConfig),
  222. registry,
  223. sessionId: createSessionId("tool-agent-cancelled-before-handler"),
  224. turnId: createTurnId("turn-agent-cancelled-before-handler"),
  225. });
  226. const result = await executor.execute(
  227. {
  228. id: createToolCallId("tool-call-agent-cancelled-before-handler"),
  229. input: {},
  230. name: "CancelledBeforeHandler",
  231. },
  232. { signal: controller.signal },
  233. );
  234. expect(result.success).toBe(false);
  235. expect(lifecycle).toEqual(["tool.start", "tool.run", "tool.cancel:abort_signal"]);
  236. });
  237. it("Hook 修改输入后校验失败按 validation 收口并保留诊断上下文", async () => {
  238. const lifecycle: string[] = [];
  239. const registry = createToolRegistry();
  240. registry.register({
  241. inputSchema: {
  242. additionalProperties: false,
  243. properties: { value: { type: "string" } },
  244. required: ["value"],
  245. type: "object",
  246. },
  247. metadata: {
  248. concurrentSafe: true,
  249. destructive: false,
  250. name: "HookValidationTool",
  251. needsApproval: false,
  252. readOnly: true,
  253. riskLevel: "low",
  254. sideEffectScope: "none",
  255. },
  256. handler: async () => "unexpected",
  257. });
  258. const hookRunner = createInMemoryHookRunner({
  259. hooks: [
  260. {
  261. callback: async (input) => ({
  262. hookSpecificOutput: {
  263. additionalContext: "hook validation context",
  264. hookEventName: input.hookEventName,
  265. updatedInput: {},
  266. },
  267. }),
  268. event: HookEventName.PreToolUse,
  269. matcher: "HookValidationTool",
  270. },
  271. ],
  272. });
  273. const executor = createToolExecutor({
  274. agentTelemetry: recordingTelemetry(lifecycle, () => {}),
  275. emitEvent: async () => {},
  276. hookRunner,
  277. permissionService: new PermissionService(defaultPermissionConfig),
  278. registry,
  279. sessionId: createSessionId("tool-agent-hook-validation"),
  280. turnId: createTurnId("turn-agent-hook-validation"),
  281. });
  282. const result = await executor.execute({
  283. id: createToolCallId("tool-call-agent-hook-validation"),
  284. input: { value: "valid-before-hook" },
  285. name: "HookValidationTool",
  286. });
  287. expect(result.success).toBe(false);
  288. expect(result.modelContent).toContain("hook validation context");
  289. expect(lifecycle).toEqual(["tool.start", "tool.run", "tool.fail:validation"]);
  290. });
  291. it("工具执行直接抛出异常时显式失败并原样重新抛出", async () => {
  292. const lifecycle: string[] = [];
  293. const failure = new Error("event sink failed");
  294. const executor = createToolExecutor({
  295. agentTelemetry: recordingTelemetry(lifecycle, () => {}),
  296. emitEvent: async () => {
  297. throw failure;
  298. },
  299. permissionService: new PermissionService(defaultPermissionConfig),
  300. registry: createToolRegistry(),
  301. sessionId: createSessionId("tool-agent-reject"),
  302. turnId: createTurnId("turn-agent-reject"),
  303. });
  304. await expect(
  305. executor.execute({
  306. id: createToolCallId("tool-call-agent-reject"),
  307. input: {},
  308. name: "missing-tool",
  309. }),
  310. ).rejects.toBe(failure);
  311. expect(lifecycle).toEqual(["tool.start", "tool.run", "tool.fail:unhandled"]);
  312. });
  313. it("已取消信号下工具执行直接抛出异常时按取消收口", async () => {
  314. const lifecycle: string[] = [];
  315. const controller = new AbortController();
  316. controller.abort(new Error("cancelled"));
  317. const executor = createToolExecutor({
  318. agentTelemetry: recordingTelemetry(lifecycle, () => {}),
  319. emitEvent: async () => {
  320. throw new Error("event sink failed after cancellation");
  321. },
  322. permissionService: new PermissionService(defaultPermissionConfig),
  323. registry: createToolRegistry(),
  324. sessionId: createSessionId("tool-agent-cancelled-reject"),
  325. turnId: createTurnId("turn-agent-cancelled-reject"),
  326. });
  327. await expect(
  328. executor.execute(
  329. {
  330. id: createToolCallId("tool-call-agent-cancelled-reject"),
  331. input: {},
  332. name: "missing-tool",
  333. },
  334. { signal: controller.signal },
  335. ),
  336. ).rejects.toThrow("event sink failed after cancellation");
  337. expect(lifecycle).toEqual(["tool.start", "tool.run", "tool.cancel:abort_signal"]);
  338. });
  339. });
  340. function recordingTelemetry(
  341. lifecycle: string[],
  342. onToolStart: (input: ToolTraceStart) => void,
  343. ): AgentExecutionTelemetryPort {
  344. return {
  345. abandonSession() {},
  346. captureCausation() {
  347. return undefined;
  348. },
  349. startCompaction() {
  350. return noopCompaction();
  351. },
  352. startDetachedOperation() {
  353. return noopDetached();
  354. },
  355. startStep() {
  356. return noopStep();
  357. },
  358. startTool(input) {
  359. onToolStart(input);
  360. lifecycle.push("tool.start");
  361. let ended = false;
  362. const writer: ToolExecutionSpanWriter = {
  363. captureCausation: () => undefined,
  364. finishCancelled(reason) {
  365. if (ended) return;
  366. ended = true;
  367. lifecycle.push(`tool.cancel:${reason}`);
  368. },
  369. finishCompleted() {
  370. if (ended) return;
  371. ended = true;
  372. lifecycle.push("tool.end:completed");
  373. },
  374. finishDenied(reason) {
  375. if (ended) return;
  376. ended = true;
  377. lifecycle.push(`tool.denied:${reason}`);
  378. },
  379. finishFailed(stage) {
  380. if (ended) return;
  381. ended = true;
  382. lifecycle.push(`tool.fail:${stage}`);
  383. },
  384. markPermissionRequested() {
  385. lifecycle.push("permission:requested");
  386. },
  387. run<T>(fn: () => T): T {
  388. lifecycle.push("tool.run");
  389. try {
  390. const value = fn();
  391. if (value && typeof value === "object" && "then" in value) {
  392. return Promise.resolve(value).catch((error) => {
  393. writer.finishFailed("unhandled", "unknown");
  394. throw error;
  395. }) as T;
  396. }
  397. return value;
  398. } catch (error) {
  399. writer.finishFailed("unhandled", "unknown");
  400. throw error;
  401. }
  402. },
  403. setOutputBytes() {
  404. lifecycle.push("tool.output_bytes");
  405. },
  406. setOutputTruncated(value) {
  407. lifecycle.push(`tool.output_truncated:${value}`);
  408. },
  409. setPermissionDecision(decision) {
  410. lifecycle.push(`permission:${decision}`);
  411. },
  412. startCommand: () => noopCommand(),
  413. };
  414. return writer;
  415. },
  416. startTurn() {
  417. return noopTurn();
  418. },
  419. };
  420. }
  421. function noopBase() {
  422. return {
  423. captureCausation: () => undefined,
  424. run<TResult>(fn: () => TResult): TResult {
  425. return fn();
  426. },
  427. };
  428. }
  429. function noopTurn() {
  430. return {
  431. ...noopBase(),
  432. finishCancelled() {},
  433. finishCompleted() {},
  434. finishFailed() {},
  435. };
  436. }
  437. function noopStep() {
  438. return {
  439. ...noopBase(),
  440. finishCancelled() {},
  441. finishCompleted() {},
  442. finishDiscarded() {},
  443. finishFailed() {},
  444. };
  445. }
  446. function noopCompaction() {
  447. return {
  448. ...noopBase(),
  449. finishCancelled() {},
  450. finishCompleted() {},
  451. finishDiscarded() {},
  452. finishFailed() {},
  453. markFallbackSelected() {},
  454. setInputTokens() {},
  455. setOutputTokens() {},
  456. };
  457. }
  458. function noopDetached() {
  459. return {
  460. ...noopBase(),
  461. finishCancelled() {},
  462. finishCompleted() {},
  463. finishFailed() {},
  464. setResultType() {},
  465. };
  466. }
  467. function noopCommand() {
  468. return {
  469. ...noopBase(),
  470. finishBackgrounded() {},
  471. finishCancelled() {},
  472. finishCompleted() {},
  473. finishFailed() {},
  474. markFirstOutput() {},
  475. markTerminationRequested() {},
  476. setExitCode() {},
  477. setOutputBytes() {},
  478. setSignal() {},
  479. setTimedOut() {},
  480. };
  481. }