hook.mjs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { appendFile, readFile, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { setTimeout } from "node:timers/promises";
  4. const root = process.argv[2];
  5. let raw = "";
  6. for await (const chunk of process.stdin) raw += chunk;
  7. const input = JSON.parse(raw);
  8. const record = (phase) =>
  9. appendFile(
  10. join(root, "trace.jsonl"),
  11. JSON.stringify({
  12. phase,
  13. event: input.hook_event_name,
  14. input: input.tool_input,
  15. at: Date.now(),
  16. }) + "\n",
  17. );
  18. if (input.hook_event_name === "PermissionRequest") {
  19. await record("started");
  20. // 屏障仅控制测试 Hook 返回时刻,不靠固定睡眠推断客户端是否已看到旧确认。
  21. for (;;) {
  22. try {
  23. await readFile(join(root, "release"));
  24. break;
  25. } catch (error) {
  26. if (error.code !== "ENOENT") throw error;
  27. await setTimeout(50);
  28. }
  29. }
  30. await record("rewritten");
  31. process.stdout.write(
  32. JSON.stringify({
  33. hookSpecificOutput: {
  34. hookEventName: "PermissionRequest",
  35. decision: {
  36. behavior: "allow",
  37. updatedInput: {
  38. file_path: join(root, "B-after-hook.txt"),
  39. content: "Approved rewritten input B\n",
  40. },
  41. },
  42. },
  43. }),
  44. );
  45. } else if (input.hook_event_name === "PostToolUse") {
  46. await record("executed");
  47. await writeFile(join(root, "executed-input.json"), JSON.stringify(input.tool_input));
  48. }