tool-agent-telemetry.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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.hookAdditionalContexts).toEqual([
  234. "PreToolUse:HookValidationTool hook additional context: hook validation context",
  235. ]);
  236. expect(lifecycle).toEqual(["tool.start", "tool.run", "tool.fail:validation"]);
  237. });
  238. it("工具执行直接抛出异常时显式失败并原样重新抛出", async () => {
  239. const lifecycle: string[] = [];
  240. const failure = new Error("event sink failed");
  241. const executor = createToolExecutor({
  242. agentTelemetry: recordingTelemetry(lifecycle, () => {}),
  243. emitEvent: async () => {
  244. throw failure;
  245. },
  246. permissionService: new PermissionService(defaultPermissionConfig),
  247. registry: createToolRegistry(),
  248. sessionId: createSessionId("tool-agent-reject"),
  249. turnId: createTurnId("turn-agent-reject"),
  250. });
  251. await expect(
  252. executor.execute({
  253. id: createToolCallId("tool-call-agent-reject"),
  254. input: {},
  255. name: "missing-tool",
  256. }),
  257. ).rejects.toBe(failure);
  258. expect(lifecycle).toEqual(["tool.start", "tool.run", "tool.fail:unhandled"]);
  259. });
  260. it("已取消信号下工具执行直接抛出异常时按取消收口", async () => {
  261. const lifecycle: string[] = [];
  262. const controller = new AbortController();
  263. controller.abort(new Error("cancelled"));
  264. const executor = createToolExecutor({
  265. agentTelemetry: recordingTelemetry(lifecycle, () => {}),
  266. emitEvent: async () => {
  267. throw new Error("event sink failed after cancellation");
  268. },
  269. permissionService: new PermissionService(defaultPermissionConfig),
  270. registry: createToolRegistry(),
  271. sessionId: createSessionId("tool-agent-cancelled-reject"),
  272. turnId: createTurnId("turn-agent-cancelled-reject"),
  273. });
  274. await expect(
  275. executor.execute(
  276. {
  277. id: createToolCallId("tool-call-agent-cancelled-reject"),
  278. input: {},
  279. name: "missing-tool",
  280. },
  281. { signal: controller.signal },
  282. ),
  283. ).rejects.toThrow("event sink failed after cancellation");
  284. expect(lifecycle).toEqual(["tool.start", "tool.run", "tool.cancel:abort_signal"]);
  285. });
  286. });
  287. function recordingTelemetry(
  288. lifecycle: string[],
  289. onToolStart: (input: ToolTraceStart) => void,
  290. ): AgentExecutionTelemetryPort {
  291. return {
  292. abandonSession() {},
  293. captureCausation() {
  294. return undefined;
  295. },
  296. startCompaction() {
  297. return noopCompaction();
  298. },
  299. startDetachedOperation() {
  300. return noopDetached();
  301. },
  302. startStep() {
  303. return noopStep();
  304. },
  305. startTool(input) {
  306. onToolStart(input);
  307. lifecycle.push("tool.start");
  308. let ended = false;
  309. const writer: ToolExecutionSpanWriter = {
  310. captureCausation: () => undefined,
  311. finishCancelled(reason) {
  312. if (ended) return;
  313. ended = true;
  314. lifecycle.push(`tool.cancel:${reason}`);
  315. },
  316. finishCompleted() {
  317. if (ended) return;
  318. ended = true;
  319. lifecycle.push("tool.end:completed");
  320. },
  321. finishDenied(reason) {
  322. if (ended) return;
  323. ended = true;
  324. lifecycle.push(`tool.denied:${reason}`);
  325. },
  326. finishFailed(stage) {
  327. if (ended) return;
  328. ended = true;
  329. lifecycle.push(`tool.fail:${stage}`);
  330. },
  331. markPermissionRequested() {
  332. lifecycle.push("permission:requested");
  333. },
  334. run<T>(fn: () => T): T {
  335. lifecycle.push("tool.run");
  336. try {
  337. const value = fn();
  338. if (value && typeof value === "object" && "then" in value) {
  339. return Promise.resolve(value).catch((error) => {
  340. writer.finishFailed("unhandled", "unknown");
  341. throw error;
  342. }) as T;
  343. }
  344. return value;
  345. } catch (error) {
  346. writer.finishFailed("unhandled", "unknown");
  347. throw error;
  348. }
  349. },
  350. setOutputBytes() {
  351. lifecycle.push("tool.output_bytes");
  352. },
  353. setOutputTruncated(value) {
  354. lifecycle.push(`tool.output_truncated:${value}`);
  355. },
  356. setPermissionDecision(decision) {
  357. lifecycle.push(`permission:${decision}`);
  358. },
  359. startCommand: () => noopCommand(),
  360. };
  361. return writer;
  362. },
  363. startTurn() {
  364. return noopTurn();
  365. },
  366. };
  367. }
  368. function noopBase() {
  369. return {
  370. captureCausation: () => undefined,
  371. run<TResult>(fn: () => TResult): TResult {
  372. return fn();
  373. },
  374. };
  375. }
  376. function noopTurn() {
  377. return {
  378. ...noopBase(),
  379. finishCancelled() {},
  380. finishCompleted() {},
  381. finishFailed() {},
  382. };
  383. }
  384. function noopStep() {
  385. return {
  386. ...noopBase(),
  387. finishCancelled() {},
  388. finishCompleted() {},
  389. finishDiscarded() {},
  390. finishFailed() {},
  391. };
  392. }
  393. function noopCompaction() {
  394. return {
  395. ...noopBase(),
  396. finishCancelled() {},
  397. finishCompleted() {},
  398. finishDiscarded() {},
  399. finishFailed() {},
  400. markFallbackSelected() {},
  401. setInputTokens() {},
  402. setOutputTokens() {},
  403. };
  404. }
  405. function noopDetached() {
  406. return {
  407. ...noopBase(),
  408. finishCancelled() {},
  409. finishCompleted() {},
  410. finishFailed() {},
  411. setResultType() {},
  412. };
  413. }
  414. function noopCommand() {
  415. return {
  416. ...noopBase(),
  417. finishBackgrounded() {},
  418. finishCancelled() {},
  419. finishCompleted() {},
  420. finishFailed() {},
  421. markFirstOutput() {},
  422. markTerminationRequested() {},
  423. setExitCode() {},
  424. setOutputBytes() {},
  425. setSignal() {},
  426. setTimedOut() {},
  427. };
  428. }