| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454 |
- import { describe, expect, it } from "vitest";
- import type {
- AgentExecutionTelemetryPort,
- ToolExecutionSpanWriter,
- ToolTraceStart,
- } from "@zcode/contracts";
- import {
- HookEventName,
- createRootTraceContext,
- createSessionId,
- createToolCallId,
- createTurnId,
- } from "@zcode/contracts";
- import { createInMemoryHookRunner } from "../src/hooks/index.js";
- import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
- import { createToolExecutor } from "../src/tool/executor.js";
- import { createToolRegistry } from "../src/tool/registry.js";
- describe("ToolExecutor Agent telemetry", () => {
- it("在统一 Executor 边界使用 canonical tool name 包裹完整执行", async () => {
- const lifecycle: string[] = [];
- let start: ToolTraceStart | undefined;
- const sessionId = createSessionId("tool-agent-telemetry");
- const turnId = createTurnId("turn-agent-telemetry");
- const toolCallId = createToolCallId("tool-call-agent-telemetry");
- const traceContext = createRootTraceContext({ sessionId, turnId });
- const registry = createToolRegistry();
- registry.register({
- aliases: ["TraceAlias"],
- inputSchema: {},
- metadata: {
- concurrentSafe: true,
- destructive: false,
- name: "TraceCanonical",
- needsApproval: false,
- readOnly: true,
- riskLevel: "low",
- sideEffectScope: "none",
- },
- handler: async () => {
- lifecycle.push("handler.execute");
- return "ok";
- },
- });
- const executor = createToolExecutor({
- agentTelemetry: recordingTelemetry(lifecycle, (input) => {
- start = input;
- }),
- agentTelemetryActorKind: "workflow_child",
- emitEvent: async () => {},
- permissionService: new PermissionService(defaultPermissionConfig),
- registry,
- sessionId,
- turnId,
- traceContext,
- });
- const result = await executor.execute(
- {
- id: toolCallId,
- input: {},
- name: "TraceAlias",
- },
- { traceContext },
- );
- expect(result.success).toBe(true);
- expect(start).toMatchObject({
- registeredToolName: "TraceCanonical",
- toolCallId,
- });
- expect(lifecycle).toEqual([
- "tool.start",
- "tool.run",
- "permission:not_required",
- "handler.execute",
- "tool.output_bytes",
- "tool.output_truncated:false",
- "tool.end:completed",
- ]);
- });
- it("未注册工具名在远端 Trace 中归入 unknown,业务错误仍保留原名", async () => {
- let start: ToolTraceStart | undefined;
- const sessionId = createSessionId("tool-agent-unknown");
- const turnId = createTurnId("turn-agent-unknown");
- const registry = createToolRegistry();
- const executor = createToolExecutor({
- agentTelemetry: recordingTelemetry([], (input) => {
- start = input;
- }),
- emitEvent: async () => {},
- permissionService: new PermissionService(defaultPermissionConfig),
- registry,
- sessionId,
- turnId,
- });
- const result = await executor.execute({
- id: createToolCallId("tool-call-agent-unknown"),
- input: {},
- name: "untrusted-user-derived-tool-name",
- });
- expect(start?.registeredToolName).toBe("unknown");
- expect(result.success).toBe(false);
- expect(result.toolName).toBe("untrusted-user-derived-tool-name");
- });
- it("工具专属语义校验失败按 validation 显式收口", async () => {
- const lifecycle: string[] = [];
- let handlerCalled = false;
- const registry = createToolRegistry();
- registry.register({
- inputSchema: {},
- metadata: {
- concurrentSafe: true,
- destructive: false,
- name: "SemanticValidationTool",
- needsApproval: false,
- readOnly: true,
- riskLevel: "low",
- sideEffectScope: "none",
- },
- validateInput: () => ({
- errorCode: 422,
- message: "semantic input rejected",
- result: false,
- }),
- handler: async () => {
- handlerCalled = true;
- return "unexpected";
- },
- });
- const executor = createToolExecutor({
- agentTelemetry: recordingTelemetry(lifecycle, () => {}),
- emitEvent: async () => {},
- permissionService: new PermissionService(defaultPermissionConfig),
- registry,
- sessionId: createSessionId("tool-agent-semantic-validation"),
- turnId: createTurnId("turn-agent-semantic-validation"),
- });
- const result = await executor.execute({
- id: createToolCallId("tool-call-agent-semantic-validation"),
- input: {},
- name: "SemanticValidationTool",
- });
- expect(result.success).toBe(false);
- expect(handlerCalled).toBe(false);
- expect(lifecycle).toEqual(["tool.start", "tool.run", "tool.fail:validation"]);
- });
- it("进入 handler 前已取消时按 abort_signal 显式收口", async () => {
- const lifecycle: string[] = [];
- const controller = new AbortController();
- controller.abort(new Error("cancel before execution"));
- const registry = createToolRegistry();
- registry.register({
- inputSchema: {},
- metadata: {
- concurrentSafe: true,
- destructive: false,
- name: "CancelledBeforeHandler",
- needsApproval: false,
- readOnly: true,
- riskLevel: "low",
- sideEffectScope: "none",
- },
- handler: async () => "unexpected",
- });
- const executor = createToolExecutor({
- agentTelemetry: recordingTelemetry(lifecycle, () => {}),
- emitEvent: async () => {},
- permissionService: new PermissionService(defaultPermissionConfig),
- registry,
- sessionId: createSessionId("tool-agent-cancelled-before-handler"),
- turnId: createTurnId("turn-agent-cancelled-before-handler"),
- });
- const result = await executor.execute(
- {
- id: createToolCallId("tool-call-agent-cancelled-before-handler"),
- input: {},
- name: "CancelledBeforeHandler",
- },
- { signal: controller.signal },
- );
- expect(result.success).toBe(false);
- expect(lifecycle).toEqual(["tool.start", "tool.run", "tool.cancel:abort_signal"]);
- });
- it("Hook 修改输入后校验失败按 validation 收口并保留诊断上下文", async () => {
- const lifecycle: string[] = [];
- const registry = createToolRegistry();
- registry.register({
- inputSchema: {
- additionalProperties: false,
- properties: { value: { type: "string" } },
- required: ["value"],
- type: "object",
- },
- metadata: {
- concurrentSafe: true,
- destructive: false,
- name: "HookValidationTool",
- needsApproval: false,
- readOnly: true,
- riskLevel: "low",
- sideEffectScope: "none",
- },
- handler: async () => "unexpected",
- });
- const hookRunner = createInMemoryHookRunner({
- hooks: [
- {
- callback: async (input) => ({
- hookSpecificOutput: {
- additionalContext: "hook validation context",
- hookEventName: input.hookEventName,
- updatedInput: {},
- },
- }),
- event: HookEventName.PreToolUse,
- matcher: "HookValidationTool",
- },
- ],
- });
- const executor = createToolExecutor({
- agentTelemetry: recordingTelemetry(lifecycle, () => {}),
- emitEvent: async () => {},
- hookRunner,
- permissionService: new PermissionService(defaultPermissionConfig),
- registry,
- sessionId: createSessionId("tool-agent-hook-validation"),
- turnId: createTurnId("turn-agent-hook-validation"),
- });
- const result = await executor.execute({
- id: createToolCallId("tool-call-agent-hook-validation"),
- input: { value: "valid-before-hook" },
- name: "HookValidationTool",
- });
- expect(result.success).toBe(false);
- expect(result.modelContent).toContain("hook validation context");
- expect(lifecycle).toEqual(["tool.start", "tool.run", "tool.fail:validation"]);
- });
- it("工具执行直接抛出异常时显式失败并原样重新抛出", async () => {
- const lifecycle: string[] = [];
- const failure = new Error("event sink failed");
- const executor = createToolExecutor({
- agentTelemetry: recordingTelemetry(lifecycle, () => {}),
- emitEvent: async () => {
- throw failure;
- },
- permissionService: new PermissionService(defaultPermissionConfig),
- registry: createToolRegistry(),
- sessionId: createSessionId("tool-agent-reject"),
- turnId: createTurnId("turn-agent-reject"),
- });
- await expect(
- executor.execute({
- id: createToolCallId("tool-call-agent-reject"),
- input: {},
- name: "missing-tool",
- }),
- ).rejects.toBe(failure);
- expect(lifecycle).toEqual(["tool.start", "tool.run", "tool.fail:unhandled"]);
- });
- it("已取消信号下工具执行直接抛出异常时按取消收口", async () => {
- const lifecycle: string[] = [];
- const controller = new AbortController();
- controller.abort(new Error("cancelled"));
- const executor = createToolExecutor({
- agentTelemetry: recordingTelemetry(lifecycle, () => {}),
- emitEvent: async () => {
- throw new Error("event sink failed after cancellation");
- },
- permissionService: new PermissionService(defaultPermissionConfig),
- registry: createToolRegistry(),
- sessionId: createSessionId("tool-agent-cancelled-reject"),
- turnId: createTurnId("turn-agent-cancelled-reject"),
- });
- await expect(
- executor.execute(
- {
- id: createToolCallId("tool-call-agent-cancelled-reject"),
- input: {},
- name: "missing-tool",
- },
- { signal: controller.signal },
- ),
- ).rejects.toThrow("event sink failed after cancellation");
- expect(lifecycle).toEqual(["tool.start", "tool.run", "tool.cancel:abort_signal"]);
- });
- });
- function recordingTelemetry(
- lifecycle: string[],
- onToolStart: (input: ToolTraceStart) => void,
- ): AgentExecutionTelemetryPort {
- return {
- abandonSession() {},
- captureCausation() {
- return undefined;
- },
- startCompaction() {
- return noopCompaction();
- },
- startDetachedOperation() {
- return noopDetached();
- },
- startStep() {
- return noopStep();
- },
- startTool(input) {
- onToolStart(input);
- lifecycle.push("tool.start");
- let ended = false;
- const writer: ToolExecutionSpanWriter = {
- captureCausation: () => undefined,
- finishCancelled(reason) {
- if (ended) return;
- ended = true;
- lifecycle.push(`tool.cancel:${reason}`);
- },
- finishCompleted() {
- if (ended) return;
- ended = true;
- lifecycle.push("tool.end:completed");
- },
- finishDenied(reason) {
- if (ended) return;
- ended = true;
- lifecycle.push(`tool.denied:${reason}`);
- },
- finishFailed(stage) {
- if (ended) return;
- ended = true;
- lifecycle.push(`tool.fail:${stage}`);
- },
- markPermissionRequested() {
- lifecycle.push("permission:requested");
- },
- run<T>(fn: () => T): T {
- lifecycle.push("tool.run");
- try {
- const value = fn();
- if (value && typeof value === "object" && "then" in value) {
- return Promise.resolve(value).catch((error) => {
- writer.finishFailed("unhandled", "unknown");
- throw error;
- }) as T;
- }
- return value;
- } catch (error) {
- writer.finishFailed("unhandled", "unknown");
- throw error;
- }
- },
- setOutputBytes() {
- lifecycle.push("tool.output_bytes");
- },
- setOutputTruncated(value) {
- lifecycle.push(`tool.output_truncated:${value}`);
- },
- setPermissionDecision(decision) {
- lifecycle.push(`permission:${decision}`);
- },
- startCommand: () => noopCommand(),
- };
- return writer;
- },
- startTurn() {
- return noopTurn();
- },
- };
- }
- function noopBase() {
- return {
- captureCausation: () => undefined,
- run<TResult>(fn: () => TResult): TResult {
- return fn();
- },
- };
- }
- function noopTurn() {
- return {
- ...noopBase(),
- finishCancelled() {},
- finishCompleted() {},
- finishFailed() {},
- };
- }
- function noopStep() {
- return {
- ...noopBase(),
- finishCancelled() {},
- finishCompleted() {},
- finishDiscarded() {},
- finishFailed() {},
- };
- }
- function noopCompaction() {
- return {
- ...noopBase(),
- finishCancelled() {},
- finishCompleted() {},
- finishDiscarded() {},
- finishFailed() {},
- markFallbackSelected() {},
- setInputTokens() {},
- setOutputTokens() {},
- };
- }
- function noopDetached() {
- return {
- ...noopBase(),
- finishCancelled() {},
- finishCompleted() {},
- finishFailed() {},
- setResultType() {},
- };
- }
- function noopCommand() {
- return {
- ...noopBase(),
- finishBackgrounded() {},
- finishCancelled() {},
- finishCompleted() {},
- finishFailed() {},
- markFirstOutput() {},
- markTerminationRequested() {},
- setExitCode() {},
- setOutputBytes() {},
- setSignal() {},
- setTimedOut() {},
- };
- }
|