remote-tool-execution-evidence.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import type { SSHConnectionConfig } from "./ssh-remote-p0.js";
  2. interface ToolExecutionQuery {
  3. toolCallId?: string;
  4. sessionId?: string;
  5. toolName: string;
  6. }
  7. export interface RemoteToolExecutionEvent {
  8. event: "tool.call.started" | "tool.call.completed";
  9. toolCallId: string;
  10. toolName: string;
  11. sessionId?: string;
  12. }
  13. /** 保留每个真实事件,包括同 ID 的重复执行;不以文件内容或去重后的 ID 代替执行次数。 */
  14. export function parseRemoteToolExecutionEvents(
  15. text: string,
  16. query: ToolExecutionQuery,
  17. ): RemoteToolExecutionEvent[] {
  18. if (!query.toolCallId && !query.sessionId) throw new Error("工具执行取证必须限定任务或调用身份");
  19. const events: RemoteToolExecutionEvent[] = [];
  20. for (const line of text.split("\n").filter((line) => line.trim())) {
  21. const record = JSON.parse(line) as Record<string, unknown>;
  22. if (!record || typeof record !== "object" || Array.isArray(record)) {
  23. throw new Error("远端工具日志不是合法对象");
  24. }
  25. const context =
  26. record.context && typeof record.context === "object"
  27. ? (record.context as Record<string, unknown>)
  28. : {};
  29. const toolCallId = record.toolCallId ?? context.toolCallId;
  30. const sessionId = record.sessionId ?? context.sessionId;
  31. if (
  32. (record.event === "tool.call.started" || record.event === "tool.call.completed") &&
  33. typeof toolCallId === "string" &&
  34. (!query.toolCallId || toolCallId === query.toolCallId) &&
  35. (!query.sessionId || sessionId === query.sessionId) &&
  36. (record.toolName ?? context.toolName) === query.toolName
  37. ) {
  38. events.push({
  39. event: record.event,
  40. toolCallId,
  41. toolName: query.toolName,
  42. ...(typeof sessionId === "string" ? { sessionId } : {}),
  43. });
  44. }
  45. }
  46. return events;
  47. }
  48. export async function readRemoteToolExecutionEvents(
  49. config: SSHConnectionConfig,
  50. query: ToolExecutionQuery,
  51. ): Promise<RemoteToolExecutionEvent[]> {
  52. const { runSSHCommand } = await import("./ssh-remote-p0.js");
  53. const result = await runSSHCommand(
  54. config,
  55. `grep -h -E '"event"[[:space:]]*:[[:space:]]*"tool[.]call[.](started|completed)"' "$HOME/.zcode/cli/log/"*.jsonl`,
  56. );
  57. // grep 1 表示没有执行事件;日志不可读等真实错误不能伪装为零次执行。
  58. if (result.code !== 0 && result.code !== 1) {
  59. throw new Error(`无法读取远端工具执行日志(exit=${result.code})`);
  60. }
  61. return parseRemoteToolExecutionEvents(result.stdout, query);
  62. }