tool-agent-telemetry.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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("未注册工具名在远端 Trace 中归入 unknown,业务错误仍保留原名", async () => {
  80. let start: ToolTraceStart | undefined;
  81. const sessionId = createSessionId("tool-agent-unknown");
  82. const turnId = createTurnId("turn-agent-unknown");
  83. const registry = createToolRegistry();
  84. const executor = createToolExecutor({
  85. agentTelemetry: recordingTelemetry([], (input) => {
  86. start = input;
  87. }),
  88. emitEvent: async () => {},
  89. permissionService: new PermissionService(defaultPermissionConfig),
  90. registry,
  91. sessionId,
  92. turnId,
  93. });
  94. const result = await executor.execute({
  95. id: createToolCallId("tool-call-agent-unknown"),
  96. input: {},
  97. name: "untrusted-user-derived-tool-name",
  98. });
  99. expect(start?.registeredToolName).toBe("unknown");
  100. expect(result.success).toBe(false);
  101. expect(result.toolName).toBe("untrusted-user-derived-tool-name");
  102. });
  103. it("工具专属语义校验失败按 validation 显式收口", async () => {
  104. const lifecycle: string[] = [];
  105. let handlerCalled = false;
  106. const registry = createToolRegistry();
  107. registry.register({
  108. inputSchema: {},
  109. metadata: {
  110. concurrentSafe: true,
  111. destructive: false,
  112. name: "SemanticValidationTool",
  113. needsApproval: false,
  114. readOnly: true,
  115. riskLevel: "low",
  116. sideEffectScope: "none",
  117. },
  118. validateInput: () => ({
  119. errorCode: 422,
  120. message: "semantic input rejected",
  121. result: false,
  122. }),
  123. handler: async () => {
  124. handlerCalled = true;
  125. return "unexpected";
  126. },
  127. });
  128. const executor = createToolExecutor({
  129. agentTelemetry: recordingTelemetry(lifecycle, () => {}),
  130. emitEvent: async () => {},
  131. permissionService: new PermissionService(defaultPermissionConfig),
  132. registry,
  133. sessionId: createSessionId("tool-agent-semantic-validation"),
  134. turnId: createTurnId("turn-agent-semantic-validation"),
  135. });
  136. const result = await executor.execute({
  137. id: createToolCallId("tool-call-agent-semantic-validation"),
  138. input: {},
  139. name: "SemanticValidationTool",
  140. });
  141. expect(result.success).toBe(false);
  142. expect(handlerCalled).toBe(false);
  143. expect(lifecycle).toEqual(["tool.start", "tool.run", "tool.fail:validation"]);
  144. });
  145. it("进入 handler 前已取消时按 abort_signal 显式收口", async () => {
  146. const lifecycle: string[] = [];
  147. const controller = new AbortController();
  148. controller.abort(new Error("cancel before execution"));
  149. const registry = createToolRegistry();
  150. registry.register({
  151. inputSchema: {},
  152. metadata: {
  153. concurrentSafe: true,
  154. destructive: false,
  155. name: "CancelledBeforeHandler",
  156. needsApproval: false,
  157. readOnly: true,
  158. riskLevel: "low",
  159. sideEffectScope: "none",
  160. },
  161. handler: async () => "unexpected",
  162. });
  163. const executor = createToolExecutor({
  164. agentTelemetry: recordingTelemetry(lifecycle, () => {}),
  165. emitEvent: async () => {},
  166. permissionService: new PermissionService(defaultPermissionConfig),
  167. registry,
  168. sessionId: createSessionId("tool-agent-cancelled-before-handler"),
  169. turnId: createTurnId("turn-agent-cancelled-before-handler"),
  170. });
  171. const result = await executor.execute(
  172. {
  173. id: createToolCallId("tool-call-agent-cancelled-before-handler"),
  174. input: {},
  175. name: "CancelledBeforeHandler",
  176. },
  177. { signal: controller.signal },
  178. );
  179. expect(result.success).toBe(false);
  180. expect(lifecycle).toEqual(["tool.start", "tool.run", "tool.cancel:abort_signal"]);
  181. });
  182. it("Hook 修改输入后校验失败按 validation 收口并保留诊断上下文", async () => {
  183. const lifecycle: string[] = [];
  184. const registry = createToolRegistry();
  185. registry.register({
  186. inputSchema: {
  187. additionalProperties: false,
  188. properties: { value: { type: "string" } },
  189. required: ["value"],
  190. type: "object",
  191. },
  192. metadata: {
  193. concurrentSafe: true,
  194. destructive: false,
  195. name: "HookValidationTool",
  196. needsApproval: false,
  197. readOnly: true,
  198. riskLevel: "low",
  199. sideEffectScope: "none",
  200. },
  201. handler: async () => "unexpected",
  202. });
  203. const hookRunner = createInMemoryHookRunner({
  204. hooks: [
  205. {
  206. callback: async (input) => ({
  207. hookSpecificOutput: {
  208. additionalContext: "hook validation context",
  209. hookEventName: input.hookEventName,
  210. updatedInput: {},
  211. },
  212. }),
  213. event: HookEventName.PreToolUse,
  214. matcher: "HookValidationTool",
  215. },
  216. ],
  217. });
  218. const executor = createToolExecutor({
  219. agentTelemetry: recordingTelemetry(lifecycle, () => {}),
  220. emitEvent: async () => {},
  221. hookRunner,
  222. permissionService: new PermissionService(defaultPermissionConfig),
  223. registry,
  224. sessionId: createSessionId("tool-agent-hook-validation"),
  225. turnId: createTurnId("turn-agent-hook-validation"),
  226. });
  227. const result = await executor.execute({
  228. id: createToolCallId("tool-call-agent-hook-validation"),
  229. input: { value: "valid-before-hook" },
  230. name: "HookValidationTool",
  231. });
  232. expect(result.success).toBe(false);
  233. expect(result.modelContent).toContain("hook validation context");
  234. expect(lifecycle).toEqual(["tool.start", "tool.run", "tool.fail:validation"]);
  235. });
  236. it("工具执行直接抛出异常时显式失败并原样重新抛出", async () => {
  237. const lifecycle: string[] = [];
  238. const failure = new Error("event sink failed");
  239. const executor = createToolExecutor({
  240. agentTelemetry: recordingTelemetry(lifecycle, () => {}),
  241. emitEvent: async () => {
  242. throw failure;
  243. },
  244. permissionService: new PermissionService(defaultPermissionConfig),
  245. registry: createToolRegistry(),
  246. sessionId: createSessionId("tool-agent-reject"),
  247. turnId: createTurnId("turn-agent-reject"),
  248. });
  249. await expect(
  250. executor.execute({
  251. id: createToolCallId("tool-call-agent-reject"),
  252. input: {},
  253. name: "missing-tool",
  254. }),
  255. ).rejects.toBe(failure);
  256. expect(lifecycle).toEqual(["tool.start", "tool.run", "tool.fail:unhandled"]);
  257. });
  258. it("已取消信号下工具执行直接抛出异常时按取消收口", async () => {
  259. const lifecycle: string[] = [];
  260. const controller = new AbortController();
  261. controller.abort(new Error("cancelled"));
  262. const executor = createToolExecutor({
  263. agentTelemetry: recordingTelemetry(lifecycle, () => {}),
  264. emitEvent: async () => {
  265. throw new Error("event sink failed after cancellation");
  266. },
  267. permissionService: new PermissionService(defaultPermissionConfig),
  268. registry: createToolRegistry(),
  269. sessionId: createSessionId("tool-agent-cancelled-reject"),
  270. turnId: createTurnId("turn-agent-cancelled-reject"),
  271. });
  272. await expect(
  273. executor.execute(
  274. {
  275. id: createToolCallId("tool-call-agent-cancelled-reject"),
  276. input: {},
  277. name: "missing-tool",
  278. },
  279. { signal: controller.signal },
  280. ),
  281. ).rejects.toThrow("event sink failed after cancellation");
  282. expect(lifecycle).toEqual(["tool.start", "tool.run", "tool.cancel:abort_signal"]);
  283. });
  284. });
  285. function recordingTelemetry(
  286. lifecycle: string[],
  287. onToolStart: (input: ToolTraceStart) => void,
  288. ): AgentExecutionTelemetryPort {
  289. return {
  290. abandonSession() {},
  291. captureCausation() {
  292. return undefined;
  293. },
  294. startCompaction() {
  295. return noopCompaction();
  296. },
  297. startDetachedOperation() {
  298. return noopDetached();
  299. },
  300. startStep() {
  301. return noopStep();
  302. },
  303. startTool(input) {
  304. onToolStart(input);
  305. lifecycle.push("tool.start");
  306. let ended = false;
  307. const writer: ToolExecutionSpanWriter = {
  308. captureCausation: () => undefined,
  309. finishCancelled(reason) {
  310. if (ended) return;
  311. ended = true;
  312. lifecycle.push(`tool.cancel:${reason}`);
  313. },
  314. finishCompleted() {
  315. if (ended) return;
  316. ended = true;
  317. lifecycle.push("tool.end:completed");
  318. },
  319. finishDenied(reason) {
  320. if (ended) return;
  321. ended = true;
  322. lifecycle.push(`tool.denied:${reason}`);
  323. },
  324. finishFailed(stage) {
  325. if (ended) return;
  326. ended = true;
  327. lifecycle.push(`tool.fail:${stage}`);
  328. },
  329. markPermissionRequested() {
  330. lifecycle.push("permission:requested");
  331. },
  332. run<T>(fn: () => T): T {
  333. lifecycle.push("tool.run");
  334. try {
  335. const value = fn();
  336. if (value && typeof value === "object" && "then" in value) {
  337. return Promise.resolve(value).catch((error) => {
  338. writer.finishFailed("unhandled", "unknown");
  339. throw error;
  340. }) as T;
  341. }
  342. return value;
  343. } catch (error) {
  344. writer.finishFailed("unhandled", "unknown");
  345. throw error;
  346. }
  347. },
  348. setOutputBytes() {
  349. lifecycle.push("tool.output_bytes");
  350. },
  351. setOutputTruncated(value) {
  352. lifecycle.push(`tool.output_truncated:${value}`);
  353. },
  354. setPermissionDecision(decision) {
  355. lifecycle.push(`permission:${decision}`);
  356. },
  357. startCommand: () => noopCommand(),
  358. };
  359. return writer;
  360. },
  361. startTurn() {
  362. return noopTurn();
  363. },
  364. };
  365. }
  366. function noopBase() {
  367. return {
  368. captureCausation: () => undefined,
  369. run<TResult>(fn: () => TResult): TResult {
  370. return fn();
  371. },
  372. };
  373. }
  374. function noopTurn() {
  375. return {
  376. ...noopBase(),
  377. finishCancelled() {},
  378. finishCompleted() {},
  379. finishFailed() {},
  380. };
  381. }
  382. function noopStep() {
  383. return {
  384. ...noopBase(),
  385. finishCancelled() {},
  386. finishCompleted() {},
  387. finishDiscarded() {},
  388. finishFailed() {},
  389. };
  390. }
  391. function noopCompaction() {
  392. return {
  393. ...noopBase(),
  394. finishCancelled() {},
  395. finishCompleted() {},
  396. finishDiscarded() {},
  397. finishFailed() {},
  398. markFallbackSelected() {},
  399. setInputTokens() {},
  400. setOutputTokens() {},
  401. };
  402. }
  403. function noopDetached() {
  404. return {
  405. ...noopBase(),
  406. finishCancelled() {},
  407. finishCompleted() {},
  408. finishFailed() {},
  409. setResultType() {},
  410. };
  411. }
  412. function noopCommand() {
  413. return {
  414. ...noopBase(),
  415. finishBackgrounded() {},
  416. finishCancelled() {},
  417. finishCompleted() {},
  418. finishFailed() {},
  419. markFirstOutput() {},
  420. markTerminationRequested() {},
  421. setExitCode() {},
  422. setOutputBytes() {},
  423. setSignal() {},
  424. setTimedOut() {},
  425. };
  426. }