failproofai 1.0.2-beta.8 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/build-manifest.json +3 -3
  3. package/.next/standalone/.next/prerender-manifest.json +4 -4
  4. package/.next/standalone/.next/required-server-files.json +1 -1
  5. package/.next/standalone/.next/server/app/_global-error/page/server-reference-manifest.json +1 -1
  6. package/.next/standalone/.next/server/app/_global-error/page.js.nft.json +1 -1
  7. package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  8. package/.next/standalone/.next/server/app/_global-error.html +1 -1
  9. package/.next/standalone/.next/server/app/_global-error.rsc +7 -7
  10. package/.next/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +6 -6
  11. package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +7 -7
  12. package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  13. package/.next/standalone/.next/server/app/_not-found/page/server-reference-manifest.json +1 -1
  14. package/.next/standalone/.next/server/app/_not-found/page.js.nft.json +1 -1
  15. package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  16. package/.next/standalone/.next/server/app/_not-found.html +1 -1
  17. package/.next/standalone/.next/server/app/_not-found.rsc +14 -14
  18. package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +14 -14
  19. package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +13 -13
  20. package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  21. package/.next/standalone/.next/server/app/api/audit/invite/route.js +3 -2
  22. package/.next/standalone/.next/server/app/api/audit/invite/route.js.nft.json +1 -1
  23. package/.next/standalone/.next/server/app/api/audit/run/route.js +4 -3
  24. package/.next/standalone/.next/server/app/api/audit/run/route.js.nft.json +1 -1
  25. package/.next/standalone/.next/server/app/api/audit/status/route.js.nft.json +1 -1
  26. package/.next/standalone/.next/server/app/api/auth/login-request/route.js +2 -2
  27. package/.next/standalone/.next/server/app/api/auth/login-request/route.js.nft.json +1 -1
  28. package/.next/standalone/.next/server/app/api/auth/login-verify/route.js +4 -3
  29. package/.next/standalone/.next/server/app/api/auth/login-verify/route.js.nft.json +1 -1
  30. package/.next/standalone/.next/server/app/api/auth/logout/route.js +4 -4
  31. package/.next/standalone/.next/server/app/api/auth/logout/route.js.nft.json +1 -1
  32. package/.next/standalone/.next/server/app/api/auth/status/route.js +4 -4
  33. package/.next/standalone/.next/server/app/api/auth/status/route.js.nft.json +1 -1
  34. package/.next/standalone/.next/server/app/api/download/[project]/[session]/route.js.nft.json +1 -1
  35. package/.next/standalone/.next/server/app/audit/page/server-reference-manifest.json +2 -2
  36. package/.next/standalone/.next/server/app/audit/page.js.nft.json +1 -1
  37. package/.next/standalone/.next/server/app/audit/page_client-reference-manifest.js +1 -1
  38. package/.next/standalone/.next/server/app/index.html +1 -1
  39. package/.next/standalone/.next/server/app/index.rsc +14 -14
  40. package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +13 -13
  41. package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +14 -14
  42. package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  43. package/.next/standalone/.next/server/app/page/server-reference-manifest.json +1 -1
  44. package/.next/standalone/.next/server/app/page.js.nft.json +1 -1
  45. package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  46. package/.next/standalone/.next/server/app/policies/page/server-reference-manifest.json +14 -14
  47. package/.next/standalone/.next/server/app/policies/page.js +4 -4
  48. package/.next/standalone/.next/server/app/policies/page.js.nft.json +1 -1
  49. package/.next/standalone/.next/server/app/policies/page_client-reference-manifest.js +1 -1
  50. package/.next/standalone/.next/server/app/project/[name]/page/server-reference-manifest.json +1 -1
  51. package/.next/standalone/.next/server/app/project/[name]/page.js.nft.json +1 -1
  52. package/.next/standalone/.next/server/app/project/[name]/page_client-reference-manifest.js +1 -1
  53. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/react-loadable-manifest.json +2 -2
  54. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/server-reference-manifest.json +2 -2
  55. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page.js.nft.json +1 -1
  56. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page_client-reference-manifest.js +1 -1
  57. package/.next/standalone/.next/server/app/projects/page/server-reference-manifest.json +1 -1
  58. package/.next/standalone/.next/server/app/projects/page.js.nft.json +1 -1
  59. package/.next/standalone/.next/server/app/projects/page_client-reference-manifest.js +1 -1
  60. package/.next/standalone/.next/server/app/settings/page/server-reference-manifest.json +4 -4
  61. package/.next/standalone/.next/server/app/settings/page.js.nft.json +1 -1
  62. package/.next/standalone/.next/server/app/settings/page_client-reference-manifest.js +1 -1
  63. package/.next/standalone/.next/server/chunks/[externals]__0-9ti7z._.js +3 -0
  64. package/.next/standalone/.next/server/chunks/{[externals]__1lt47k4._.js → [externals]__0sg9-3p._.js} +1 -1
  65. package/.next/standalone/.next/server/chunks/[externals]__0u3wrvq._.js +3 -0
  66. package/.next/standalone/.next/server/chunks/[root-of-the-server]__01eqny5._.js +3 -0
  67. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__1p8poxd._.js → [root-of-the-server]__0igxt32._.js} +2 -2
  68. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0o07qi9._.js +1 -1
  69. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0zlqo2t._.js +3 -0
  70. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1anxb5k._.js +3 -0
  71. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1le9jqc._.js +1 -1
  72. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1p-qi2t._.js +5 -0
  73. package/.next/standalone/.next/server/chunks/_09dz7xv._.js +27 -0
  74. package/.next/standalone/.next/server/chunks/_0bs-v8p._.js +3 -0
  75. package/.next/standalone/.next/server/chunks/_0tovk6q._.js +3 -0
  76. package/.next/standalone/.next/server/chunks/_0trp3yc._.js +3 -0
  77. package/.next/standalone/.next/server/chunks/{_19uwam-._.js → _1-akg6w._.js} +2 -2
  78. package/.next/standalone/.next/server/chunks/_185gyk9._.js +3 -0
  79. package/.next/standalone/.next/server/chunks/_1ek68ln._.js +5 -7
  80. package/.next/standalone/.next/server/chunks/{node_modules_posthog-node_dist_entrypoints_index_node_mjs_09d5c79._.js → node_modules_posthog-node_dist_entrypoints_index_node_mjs_04op_ou._.js} +1 -1
  81. package/.next/standalone/.next/server/chunks/{node_modules_posthog-node_dist_entrypoints_index_node_mjs_1d2g73o._.js → node_modules_posthog-node_dist_entrypoints_index_node_mjs_0dr20uz._.js} +1 -1
  82. package/.next/standalone/.next/server/chunks/package_json_[json]_cjs_1nxcc4v._.js +1 -1
  83. package/.next/standalone/.next/server/chunks/src_hooks_0iu54mz._.js +3 -0
  84. package/.next/standalone/.next/server/chunks/src_hooks_custom-hooks-loader_ts_0lnb3n3._.js +10 -0
  85. package/.next/standalone/.next/server/chunks/src_hooks_fp-home_ts_09kv0bn._.js +1 -1
  86. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__013jr2b._.js +2 -2
  87. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__01wy8d-._.js +2 -2
  88. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__02npjtd._.js +2 -2
  89. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0da85px._.js +2 -2
  90. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0ftmoxc._.js +2 -2
  91. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0n_lxhg._.js +5 -0
  92. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0oa1lav._.js +1 -1
  93. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0p-5p8u._.js +2 -2
  94. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0s740oi._.js +2 -2
  95. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1p2otjt._.js +2 -2
  96. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1yh7hlv._.js +3 -0
  97. package/.next/standalone/.next/server/chunks/ssr/_08x1r5t._.js +1 -1
  98. package/.next/standalone/.next/server/chunks/ssr/_0ehudfr._.js +23 -0
  99. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__1n2ywfz._.js → _1es2j7i._.js} +4 -4
  100. package/.next/standalone/.next/server/chunks/ssr/_1u8-lu2._.js +1 -1
  101. package/.next/standalone/.next/server/chunks/ssr/{_1h33neq._.js → _1un1pug._.js} +1 -1
  102. package/.next/standalone/.next/server/chunks/ssr/_1zopuov._.js +1 -1
  103. package/.next/standalone/.next/server/chunks/ssr/_next-internal_server_app_policies_page_actions_1sp2-yo.js +9 -9
  104. package/.next/standalone/.next/server/chunks/ssr/app_audit__components_audit-dashboard_tsx_0p9ud47._.js +1 -1
  105. package/.next/standalone/.next/server/chunks/ssr/app_global-error_tsx_1kp6l3x._.js +1 -1
  106. package/.next/standalone/.next/server/chunks/ssr/app_policies_hooks-client_tsx_19dqvpc._.js +2 -2
  107. package/.next/standalone/.next/server/chunks/ssr/app_settings_settings-client_tsx_20lq-mq._.js +1 -1
  108. package/.next/standalone/.next/server/chunks/ssr/src_hooks_1cv9_c4._.js +10 -0
  109. package/.next/standalone/.next/server/chunks/ssr/src_hooks_builtin-policies_ts_09j2ndl._.js +1 -1
  110. package/.next/standalone/.next/server/middleware-build-manifest.js +3 -3
  111. package/.next/standalone/.next/server/middleware.js +1 -1
  112. package/.next/standalone/.next/server/pages/404.html +1 -1
  113. package/.next/standalone/.next/server/pages/500.html +1 -1
  114. package/.next/standalone/.next/server/server-reference-manifest.js +1 -1
  115. package/.next/standalone/.next/server/server-reference-manifest.json +19 -19
  116. package/.next/standalone/.next/static/chunks/0nkpwjk01ei3t.js +1 -0
  117. package/.next/standalone/.next/static/chunks/{2iryw37qfqy5y.js → 0ofdelz65_517.js} +1 -1
  118. package/.next/standalone/.next/static/chunks/{34j7nmidlcuni.js → 12uhnpwgsmcev.js} +1 -1
  119. package/.next/standalone/.next/static/chunks/{0i3a6wf-f_yky.js → 1_1eb_149xyt9.js} +1 -1
  120. package/.next/standalone/.next/static/chunks/{3927pu4ss_l4k.js → 1tx9pnxyjrkoj.js} +1 -1
  121. package/.next/standalone/.next/static/chunks/{1n04wzsaes73g.js → 1x0jrl3a4_i2m.js} +1 -1
  122. package/.next/standalone/.next/static/chunks/{3r0udrtpn78-e.js → 1zpv6omeln7al.js} +1 -1
  123. package/.next/standalone/.next/static/chunks/{416zumre3fvfw.js → 20hbg-r3io_ip.js} +1 -1
  124. package/.next/standalone/.next/static/chunks/{11a_m8yksthtf.js → 32bhi32ym8yrz.js} +2 -2
  125. package/.next/standalone/.next/static/chunks/{0u2ojcw25c_np.js → 3fr78ugeb4tjc.js} +1 -1
  126. package/.next/standalone/app/actions/get-hooks-config.ts +8 -1
  127. package/.next/standalone/app/actions/pack-actions.ts +12 -1
  128. package/.next/standalone/app/policies/hooks-client.tsx +41 -4
  129. package/.next/standalone/fp-cloud-cli/tests/test_pagination.py +204 -0
  130. package/.next/standalone/package.json +9 -9
  131. package/.next/standalone/server.js +1 -1
  132. package/README.md +58 -13
  133. package/bin/failproofai.mjs +10 -1
  134. package/dist/cli.mjs +22429 -21292
  135. package/dist/worker.mjs +1247 -540
  136. package/package.json +9 -9
  137. package/src/audit/index.ts +24 -4
  138. package/src/hooks/builtin-policies.ts +933 -8
  139. package/src/hooks/custom-hooks-loader.ts +98 -8
  140. package/src/hooks/handler.ts +26 -14
  141. package/src/hooks/manager.ts +36 -2
  142. package/src/hooks/pack-cli.ts +415 -42
  143. package/src/hooks/pack-failclosed.ts +100 -4
  144. package/src/hooks/pack-manifest.ts +29 -0
  145. package/src/hooks/pack-param-key.ts +36 -0
  146. package/src/hooks/pack-store.ts +101 -9
  147. package/src/hooks/policy-catalog.ts +9 -1
  148. package/src/hooks/policy-evaluator.ts +77 -1
  149. package/.next/standalone/.next/server/chunks/[root-of-the-server]__06cuf1y._.js +0 -3
  150. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0_usx0j._.js +0 -3
  151. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0_zk340._.js +0 -3
  152. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0jnjf2t._.js +0 -3
  153. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0oy4kxb._.js +0 -3
  154. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0zf034w._.js +0 -3
  155. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1tg4pu6._.js +0 -3
  156. package/.next/standalone/.next/server/chunks/_0lxbzdq._.js +0 -3
  157. package/.next/standalone/.next/server/chunks/_1zuiiy3._.js +0 -3
  158. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0mgrjnx._.js +0 -10
  159. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1-wzs7f._.js +0 -3
  160. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1wlvpe5._.js +0 -5
  161. package/.next/standalone/.next/server/chunks/ssr/_0l7zv8b._.js +0 -23
  162. package/.next/standalone/.next/static/chunks/1ch5l9t2p16y4.js +0 -1
  163. /package/.next/standalone/.next/static/{NgD5HvuyPxwgrpeIiafJL → 5-xDMxcnrcXDFPQiy3yhg}/_buildManifest.js +0 -0
  164. /package/.next/standalone/.next/static/{NgD5HvuyPxwgrpeIiafJL → 5-xDMxcnrcXDFPQiy3yhg}/_clientMiddlewareManifest.js +0 -0
  165. /package/.next/standalone/.next/static/{NgD5HvuyPxwgrpeIiafJL → 5-xDMxcnrcXDFPQiy3yhg}/_ssgManifest.js +0 -0
@@ -1,6 +1,4 @@
1
- module.exports=[97610,e=>{"use strict";var t=e.i(89171),i=e.i(71809),n=e.i(50227),r=e.i(2157),o=e.i(12714),s=e.i(74533),a=e.i(60526);let l=[{name:"sanitize-jwt",description:"Stop Claude from reading JWTs in tool responses",displayTitle:"Redacted JWT tokens from tool output",impact:"Stops the agent from echoing auth tokens it saw in command output.",match:{events:["PostToolUse"]},defaultEnabled:!0,category:"Sanitize"},{name:"sanitize-api-keys",description:"Stop Claude from reading API keys (OpenAI, Anthropic, GitHub, AWS, Stripe, Google) in tool responses",displayTitle:"Redacted API keys from tool output",impact:"Catches OpenAI / Anthropic / GitHub / AWS / Stripe / Google keys before the model sees them.",match:{events:["PostToolUse"]},defaultEnabled:!0,category:"Sanitize",params:{additionalPatterns:{type:"pattern[]",description:"Additional API key patterns to scrub, each with { regex, label }",default:[]}}},{name:"sanitize-connection-strings",description:"Stop Claude from reading database connection strings with embedded credentials in tool responses",displayTitle:"Redacted database connection strings from tool output",impact:"Strips embedded DB credentials before they reach the model context.",match:{events:["PostToolUse"]},defaultEnabled:!0,category:"Sanitize"},{name:"sanitize-private-key-content",description:"Stop Claude from reading PEM private key content in tool responses",displayTitle:"Redacted PEM private keys from tool output",impact:"Prevents private key bodies from being echoed into chat context.",match:{events:["PostToolUse"]},defaultEnabled:!0,category:"Sanitize"},{name:"sanitize-bearer-tokens",displayTitle:"Redacted bearer tokens from tool output",impact:"Strips Authorization: Bearer values before they hit the model.",description:"Stop Claude from reading Authorization Bearer tokens in tool responses",match:{events:["PostToolUse"]},defaultEnabled:!0,category:"Sanitize"},{name:"protect-env-vars",displayTitle:"Tried to dump environment variables to chat",impact:"Env vars often contain secrets; blocking `env` / `printenv` keeps them out of the model context.",description:"Prevent commands that read environment variables",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!0,category:"Environment"},{name:"block-env-files",displayTitle:"Tried to read or write a .env file",impact:"`.env` files routinely contain API keys and DB credentials.",description:"Block reading/writing .env files",match:{events:["PreToolUse"]},defaultEnabled:!0,category:"Environment"},{name:"block-read-outside-cwd",displayTitle:"Tried to read files outside your project directory",impact:"Stops the agent from peeking at neighboring repos or your home directory.",description:"Block file reads outside the session working directory",match:{events:["PreToolUse"],toolNames:["Read","Glob","Grep","Bash"]},defaultEnabled:!1,category:"Environment",params:{allowPaths:{type:"string[]",description:"Absolute paths outside cwd that are allowed to be read",default:[]}}},{name:"block-sudo",displayTitle:"Tried to run a command with sudo",impact:"Sudo gives the agent root — blocked unless explicitly allow-listed.",description:"Block sudo commands",match:{events:["PreToolUse","PermissionRequest"],toolNames:["Bash"]},defaultEnabled:!0,category:"Dangerous Commands",params:{allowPatterns:{type:"string[]",description:"Sudo command patterns to allow, matched token-by-token (e.g. 'sudo systemctl status')",default:[]}}},{name:"block-curl-pipe-sh",displayTitle:"Tried to pipe a downloaded script straight to a shell",impact:"`curl ... | sh` runs unverified remote code on your machine.",description:"Block piping downloads to shell",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!0,category:"Dangerous Commands"},{name:"block-rm-rf",displayTitle:"Tried to recursively delete a system path",impact:"Catches catastrophic `rm -rf /` and Windows equivalents.",description:"Prevent catastrophic deletions",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Dangerous Commands",params:{allowPaths:{type:"string[]",description:"Paths that are allowed to be recursively deleted",default:[]}}},{name:"block-failproofai-commands",displayTitle:"Tried to disable, pause or modify failproofai itself",impact:"An agent that can pause or remove enforcement can switch off every other policy.",description:"Block failproofai CLI commands, self-pause and uninstallation",match:{events:["PreToolUse","PermissionRequest"],toolNames:["Bash"]},defaultEnabled:!0,alwaysOn:!0,category:"Dangerous Commands"},{name:"block-kubectl",displayTitle:"Tried to run a Kubernetes command",impact:"kubectl can change live cluster state — gated unless allow-listed.",description:"Block kubectl commands (Kubernetes cluster mutations)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"kubectl command patterns to allow, matched token-by-token (e.g. 'kubectl get *', 'kubectl describe *')",default:[]}}},{name:"block-terraform",displayTitle:"Tried to run a Terraform/OpenTofu command",impact:"Terraform mutates real infrastructure — gated unless allow-listed.",description:"Block terraform and tofu (OpenTofu) commands",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"terraform/tofu command patterns to allow (e.g. 'terraform plan', 'terraform validate')",default:[]}}},{name:"block-aws-cli",displayTitle:"Tried to run an AWS CLI command",impact:"AWS CLI can spend money or break prod — gated.",description:"Block aws CLI commands",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"aws CLI command patterns to allow (e.g. 'aws s3 ls *', 'aws sts get-caller-identity')",default:[]}}},{name:"block-gcloud",displayTitle:"Tried to run a Google Cloud command",impact:"gcloud can spend money or break prod — gated.",description:"Block gcloud (Google Cloud) CLI commands",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"gcloud command patterns to allow (e.g. 'gcloud auth list', 'gcloud config list')",default:[]}}},{name:"block-az-cli",displayTitle:"Tried to run an Azure CLI command",impact:"az can spend money or break prod — gated.",description:"Block az (Azure) CLI commands",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"az CLI command patterns to allow (e.g. 'az account show', 'az group list')",default:[]}}},{name:"block-helm",displayTitle:"Tried to run a Helm command",impact:"Helm releases mutate cluster state — gated.",description:"Block helm commands",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"helm command patterns to allow (e.g. 'helm list', 'helm status *')",default:[]}}},{name:"block-gh-pipeline",displayTitle:"Tried to run a privileged GitHub CLI pipeline command",impact:"Catches `gh workflow run`, `gh pr merge`, `gh secret set`, etc.",description:"Block gh CLI pipeline-trigger subcommands (workflow run, run rerun/cancel, pr merge, release create/delete, cache delete, secret set/delete)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"gh pipeline command patterns to allow (e.g. specific scripted invocations); read-only gh subcommands like 'gh pr view' and 'gh run list' are not matched by this policy",default:[]}}},{name:"block-secrets-write",displayTitle:"Tried to write a secret-key file",impact:"Stops the agent from creating `.pem`, `id_rsa`, `credentials.json`, etc.",description:"Block writing secret key files",match:{events:["PreToolUse"],toolNames:["Write"]},defaultEnabled:!1,category:"Dangerous Commands",params:{additionalPatterns:{type:"string[]",description:"Additional filename patterns (substrings) to block",default:[]}}},{name:"block-push-master",displayTitle:"Tried to push directly to main/master",impact:"Direct pushes to a protected branch bypass review.",description:"Block pushing to main/master",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!0,category:"Git",params:{protectedBranches:{type:"string[]",description:"Branch names to protect from direct pushes",default:["main","master"]}}},{name:"block-force-push",displayTitle:"Tried to force-push",impact:"Force-pushes rewrite history and can clobber teammates' work.",description:"Prevent force-pushing to any branch",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Git"},{name:"block-work-on-main",displayTitle:"Tried to commit or merge on main/master",impact:"Work should land via PR — direct commits skip review.",description:"Block git commits and merges on main/master branch",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Git",params:{protectedBranches:{type:"string[]",description:"Branch names where commits/merges are blocked",default:["main","master"]}}},{name:"warn-git-amend",displayTitle:"Used git commit --amend",impact:"Amending after a push rewrites history that others may have pulled.",description:"Warns before amending git commits, which rewrites history",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Git"},{name:"warn-git-stash-drop",displayTitle:"Tried to drop or clear git stash",impact:"Stash deletions are permanent and silent.",description:"Warns before permanently deleting stashed changes",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Git"},{name:"warn-all-files-staged",displayTitle:"Staged all files with git add -A / .",impact:"Wide stages routinely catch generated files or secrets you didn't intend to commit.",description:"Warns before staging all working tree files with git add -A / . / --all",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Git"},{name:"warn-destructive-sql",displayTitle:"Ran destructive SQL (DROP / TRUNCATE / DELETE without WHERE)",impact:"Easy way to wipe a table by accident.",description:"Warn before executing destructive SQL (DROP/TRUNCATE/DELETE without WHERE) via database clients",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Database"},{name:"warn-schema-alteration",displayTitle:"Altered a database schema column",impact:"ALTER TABLE operations can lock tables and break readers.",description:"Warns before SQL schema changes (ALTER TABLE with column or rename operations)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Database"},{name:"warn-package-publish",displayTitle:"Tried to publish a package",impact:"Publishes are irreversible — `npm publish` / `cargo publish` shouldn't happen without intent.",description:"Warn before publishing packages to public registries (npm, PyPI, crates.io, RubyGems, etc.)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Packages & System"},{name:"warn-global-package-install",displayTitle:"Installed a package globally",impact:"`npm i -g`, `cargo install`, `pip --user` pollute your machine outside the project.",description:"Warns before installing packages globally (npm -g, cargo install, etc.)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Packages & System"},{name:"prefer-package-manager",displayTitle:"Used a non-preferred package manager",impact:"Mixing package managers creates lockfile churn for your team.",description:"Blocks non-preferred package managers and tells Claude to use an allowed one (e.g., uv instead of pip)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Packages & System",params:{allowed:{type:"string[]",description:"Allowed package manager names (e.g. ['uv', 'bun']). Any detected manager not in this list is blocked.",default:[]},blocked:{type:"string[]",description:"Additional manager names to block beyond the built-in list (e.g. ['pdm', 'pipx']).",default:[]}}},{name:"warn-large-file-write",displayTitle:"Wrote a file larger than the configured threshold",impact:"Catches accidentally large file writes (logs, binaries, model dumps).",description:"Warn before writing files larger than 1MB (configurable via thresholdKb param)",match:{events:["PreToolUse"],toolNames:["Write"]},defaultEnabled:!1,category:"Packages & System",params:{thresholdKb:{type:"number",description:"File size threshold in KB above which a warning is issued",default:1024}}},{name:"warn-background-process",displayTitle:"Started a long-lived background process",impact:"Catches `nohup` / `&` / `screen` / `tmux` / `disown` patterns that the agent often forgets to clean up.",description:"Warns before starting detached or background processes",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Packages & System"},{name:"warn-repeated-tool-calls",displayTitle:"Called the same tool 3+ times with identical arguments",impact:"Usually a sign of a stuck loop burning tokens.",description:"Warn when the same tool is called 3+ times with identical parameters",match:{events:["PreToolUse"]},defaultEnabled:!1,category:"AI Behavior"},{name:"require-commit-before-stop",displayTitle:"Stopped with uncommitted changes",impact:"Work not in a commit is invisible to teammates and easy to lose.",description:"Require all changes to be committed before Claude stops",match:{events:["Stop"]},defaultEnabled:!1,category:"Workflow"},{name:"require-push-before-stop",displayTitle:"Stopped with unpushed commits",impact:"Local-only commits won't trigger CI or be reviewable.",description:"Require all commits to be pushed to remote before Claude stops",match:{events:["Stop"]},defaultEnabled:!1,category:"Workflow",params:{remote:{type:"string",description:"Remote name to push to (default: origin)",default:"origin"},baseBranch:{type:"string",description:"Base branch to compare against (default: main)",default:"main"}}},{name:"require-pr-before-stop",displayTitle:"Stopped without a PR for the branch",impact:"Branches without PRs don't get reviewed.",description:"Require a pull request to exist for the current branch before Claude stops",match:{events:["Stop"]},defaultEnabled:!1,category:"Workflow",params:{baseBranch:{type:"string",description:"Base branch to compare against (default: main)",default:"main"}}},{name:"require-no-conflicts-before-stop",displayTitle:"Stopped with a branch that conflicts with main",impact:"Conflicting branches can't merge — surface them early.",description:"Require the current branch to merge cleanly with the base branch before Claude stops",match:{events:["Stop"]},defaultEnabled:!1,category:"Workflow",params:{baseBranch:{type:"string",description:"Base branch to check for conflicts against (default: main)",default:"main"}}},{name:"require-ci-green-before-stop",displayTitle:"Stopped with failing CI",impact:"Failing CI blocks deploy.",description:"Require CI checks to pass on the current HEAD commit before Claude stops (ignores stale runs on prior commits)",match:{events:["Stop"]},defaultEnabled:!1,category:"Workflow"}];function c(e){return e?{decision:"allow",reason:e}:{decision:"allow"}}function d(e){return{decision:"deny",reason:e}}function p(e){return{decision:"instruct",reason:e}}let u="__FAILPROOFAI_POLICY_REGISTRY__",m="__FAILPROOFAI_POLICY_INDEX_CACHE__",f="failproofai";function h(e){return e.includes("/")?e:`${f}/${e}`}function g(e){globalThis[m]=e}function y(){let e=globalThis;return e[u]||(e[u]=[]),e[u]}var b=e.i(79857);let w={info:0,warn:1,error:2},k=(0,b.logsDir)(),v=!1,S="warn",N=!1,$=k;function T(e){return!function(){if(v)return;v=!0;let e=(process.env.FAILPROOFAI_LOG_LEVEL??"").toLowerCase();("info"===e||"warn"===e||"error"===e)&&(S=e);let t=(process.env.FAILPROOFAI_HOOK_LOG_FILE??"").trim();t&&(N=!0,"1"!==t&&"true"!==t&&($=t))}(),w[e]>=w[S]}function E(e,t){process.stderr.write(`[failproofai:hook] ${e} ${t}
2
- `)}function P(e,t){if(N)try{(0,r.existsSync)($)||(0,r.mkdirSync)($,{recursive:!0});let i=(0,n.join)($,"hooks.log");try{if((0,r.statSync)(i).size>=524288){let e=`hooks-${Date.now()}.log`;(0,r.renameSync)(i,(0,n.join)($,e))}}catch{}let o=new Date().toISOString(),s=`[${o}] ${e} ${t}
3
- `;(0,r.appendFileSync)(i,s,"utf-8")}catch{}}function C(e){T("info")&&(E("INFO",e),P("INFO",e))}function A(e){T("warn")&&(E("WARN",e),P("WARN",e))}let I=function(e){let t=e.replaceAll("\\","/");for(let e of[".claude",".codex",".copilot",".cursor",".opencode",".pi",".gemini"]){let i=(0,n.join)((0,a.homedir)(),e).replaceAll("\\","/");if(t===i||t.startsWith(i+"/"))return!0}for(let e of[(0,n.join)(".config","opencode"),(0,n.join)(".local","share","opencode")]){let i=(0,n.join)((0,a.homedir)(),e).replaceAll("\\","/");if(t===i||t.startsWith(i+"/"))return!0}return!1},O=function(e){return!!(/[\\/]\.claude[\\/]settings(?:\.[^/\\]+)?\.json$/.test(e)||/[\\/]\.codex[\\/]hooks\.json$/.test(e)||/[\\/]\.copilot[\\/]hooks[\\/][^/\\]+\.json$/.test(e)||/[\\/]\.github[\\/]hooks[\\/][^/\\]+\.json$/.test(e)||/[\\/]\.cursor[\\/]hooks\.json$/.test(e)||/[\\/]\.opencode[\\/]opencode\.jsonc?$/.test(e)||/[\\/]\.opencode[\\/]plugins[\\/][^/\\]+\.(?:mjs|js|ts)$/.test(e)||/[\\/]\.config[\\/]opencode[\\/]opencode\.jsonc?$/.test(e)||/[\\/]\.config[\\/]opencode[\\/]config\.json$/.test(e)||/[\\/]\.config[\\/]opencode[\\/]plugins[\\/][^/\\]+\.(?:mjs|js|ts)$/.test(e)||/[\\/]\.pi[\\/](?:agent[\\/])?settings\.json$/.test(e)||/[\\/]\.pi[\\/](?:agent[\\/])?extensions[\\/]/.test(e)||/[\\/]\.gemini[\\/]settings\.json$/.test(e)||/[\\/]\.gemini[\\/]config[\\/]hooks\.json$/.test(e))};function x(e){return e.toolInput?.command??""}function R(e){return e.toolInput?.file_path??""}function _(e){return e.trim().split(/\s+/).map(e=>e.replace(/^['"]|['"]$/g,""))}let B=new Set(["&&","||","|",";"]),j=/[;&<>`$()\\]/,D=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/,W=[[/sk-ant-[A-Za-z0-9\-_]{20,}/,"Anthropic API key"],[/sk-proj-[A-Za-z0-9\-_]{20,}/,"OpenAI project API key"],[/sk-[A-Za-z0-9]{20,}/,"OpenAI API key"],[/ghp_[A-Za-z0-9]{36}/,"GitHub personal access token"],[/github_pat_[A-Za-z0-9_]{82}/,"GitHub fine-grained token"],[/AKIA[A-Z0-9]{16}/,"AWS access key ID"],[/sk_live_[A-Za-z0-9]{24,}/,"Stripe live secret key"],[/sk_test_[A-Za-z0-9]{24,}/,"Stripe test secret key"],[/AIza[0-9A-Za-z\-_]{35}/,"Google API key"]],M=/(?:postgresql|postgres|mysql|mongodb(?:\+srv)?|redis|amqps?|smtps?):\/\/[^@\s]+@/,U=/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----/,z=/Authorization:\s*Bearer\s+[A-Za-z0-9\-._~+/]{20,}/i;[...W];let L=/\b(?:psql|mysql|sqlite3|pgcli|clickhouse-client)\b/,F=/\b(?:DROP\s+(?:TABLE|DATABASE|SCHEMA)|TRUNCATE\b)/i,H=/\bDELETE\s+FROM\b/i,q=/\bWHERE\b/i,J=/\bALTER\s+TABLE\b[\s\S]*\b(?:DROP\s+COLUMN|ADD\s+COLUMN|RENAME\s+(?:COLUMN|TO)|MODIFY\s+COLUMN)\b/i,G=/(?:npm\s+publish|bun\s+publish|pnpm\s+publish|yarn\s+npm\s+publish|twine\s+upload|poetry\s+publish|cargo\s+publish|gem\s+push)\b/,Y=/(?:^|\s|;|&&|\|\|)(?:env|printenv)(?:\s|$|;|&&|\|)/,Z=/echo\s+.*\$\{?[A-Za-z_]/,K=/(?:^|\s|;|&&|\|\|)export\s+\w+/,Q=/\$env:[A-Za-z_]/i,V=/(?:Get-ChildItem|dir|gci|ls)\s+Env:/i,X=/\[Environment\]::GetEnvironment/i,ee=/echo\s+%[A-Za-z_]/i,et=/(?:^|[\\/])\.env(?:\.|$)/,ei=/\.env(?:\b|\s|$|\.)/,en=/Start-Process\s+.*-Verb\s+RunAs/i,er=/(?:^|;|&&|\|\|)\s*runas\s/i,eo=/(?:curl|wget)\s.*\|\s*(?:sh|bash|zsh|dash|ksh|csh|tcsh|fish|ash)\b/,es=/[;&|\n\r(){}`]+/,ea=new Set(["npx","bunx","pnpx","npm","pnpm","yarn","dlx","exec","run","eval","node","bun","deno","env","command","builtin","nohup","setsid","time","timeout","nice","stdbuf","xargs","sudo","doas","sh","bash","zsh","dash","ksh","fish","ash"]),el=/(?:^|\/)failproofai[^/]*$/,ec=/failproofai\/(?:dist\/(?:cli|index)\.mjs|bin\/failproofai\.mjs)$/,ed=/^(?:config|configure|setup)$/,ep=/^--pause(?:=|$)/,eu=/^[A-Za-z_][A-Za-z0-9_]*=/,em=/^\d+[a-z]*$/i;function ef(e){let t=e.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,"$$$1"),i=null,n=new Set;for(let[,e,i]of t.matchAll(/(?:^|[\s;&|])([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|]+)/g)){let t=i.replace(/^["']|["']$/g,"");(el.test(t)||ec.test(t))&&n.add(e)}let r=e=>{let t=/^\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?$/.exec(e);return!!t&&n.has(t[1])};for(let e of t.split(es)){let t=e.split(/\s+/).filter(Boolean),n=0;for(;n<t.length;){let e=t[n];if(!(eu.test(e)||e.startsWith("-")||e.startsWith(">")||e.startsWith("<")||em.test(e)||ea.has(e.slice(e.lastIndexOf("/")+1))))break;n++}if(n>=t.length||!el.test(t[n])&&!ec.test(t[n])&&!r(t[n]))continue;let o=t.slice(n+1),s=o.findIndex(e=>ed.test(e));if(-1!==s&&o.slice(s+1).some(e=>ep.test(e)))return"pause";i="cli"}return i}let eh=/(?:Invoke-WebRequest|iwr|Invoke-RestMethod|irm)\s+.*\|\s*(?:Invoke-Expression|iex)/i,eg=/^-[a-zA-Z]*f[a-zA-Z]*$/,ey=["--force-with-lease","--force-if-includes"],eb=/\.(?:pem|key)$/,ew=/id_rsa/,ek=/credentials/,ev=/git\s+(commit|merge|rebase|cherry-pick)\b/,eS=/\b(?:rm|unlink|shred|mv|truncate)\b[^;&|]*\.failproofai(?:\/|\b)/,eN=/(?:npm\s+(?:uninstall|remove|un|r)\s.*failproofai|bun\s+remove\s.*failproofai|yarn\s+global\s+remove\s+failproofai|pnpm\s+(?:remove|uninstall|un)\s.*failproofai)/,e$=/\bgit\s+commit\b.*--amend\b/,eT=/\bgit\s+stash\s+(?:drop|clear)\b/,eE=/\bgit\s+add\s+(?:-A\b|--all\b|\.(?:\s|$|;|&&|\|\|))/,eP=/\bnpm\s+(?:install|i)\b(?=.*(?:\s-g\b|--global\b))/,eC=/\byarn\s+global\s+add\b/,eA=/\bpnpm\s+(?:add|install|i)\b(?=.*(?:\s-g\b|--global\b))/,eI=/\bbun\s+(?:install|add)\b(?=.*(?:\s-g\b|--global\b))/,eO=/\bcargo\s+install\b/,ex=/\bpip(?:3)?\s+install\b(?=.*(?:--user\b|--break-system-packages\b))/,eR={pip:[/\bpip\b/,/\bpip3\b/,/\bpython3?\s+-m\s+pip\b/],npm:[/\bnpm\b/,/\bnpx\b/],yarn:[/\byarn\b/],pnpm:[/\bpnpm\b/,/\bpnpx\b/],bun:[/\bbun\b/,/\bbunx\b/],uv:[/\buv\b/],poetry:[/\bpoetry\b/],pipenv:[/\bpipenv\b/],conda:[/\bconda\b/],cargo:[/\bcargo\b/]},e_=/\bnohup\s+\S/,eB=/\bscreen\s+-[A-Za-z]*d[A-Za-z]*\b/,ej=/\btmux\s+(?:new-session|new)\b[^|&;]*-d\b/,eD=/\bdisown\b/,eW=/(?<![&|])\s?&\s*(?:$|#|;)/,eM=/(?:^|[;\n]|&&|\|\|?|&)\s*kubectl(?:\s|$)/,eU=/(?:^|[;\n]|&&|\|\|?|&)\s*(?:terraform|tofu)(?:\s|$)/,ez=/(?:^|[;\n]|&&|\|\|?|&)\s*aws(?:\s|$)/,eL=/(?:^|[;\n]|&&|\|\|?|&)\s*gcloud(?:\s|$)/,eF=/(?:^|[;\n]|&&|\|\|?|&)\s*az(?:\s|$)/,eH=/(?:^|[;\n]|&&|\|\|?|&)\s*helm(?:\s|$)/,eq=/(?:^|[;\n]|&&|\|\|?|&)\s*gh\s+(?:workflow\s+(?:run|enable|disable)|run\s+(?:rerun|cancel)|pr\s+merge|release\s+(?:create|delete)|cache\s+delete|secret\s+(?:set|delete))\b/,eJ=new Map;function eG(e){try{let t=function(e){try{return(0,r.statSync)((0,n.join)(e,".git","HEAD")).mtimeMs}catch{return null}}(e),i=eJ.get(e);if(i&&null!==t&&i.headMtimeMs===t)return i.branch||null;let o=(0,s.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}).trim();return null!==t&&(eJ.size>=500&&eJ.clear(),eJ.set(e,{branch:o,headMtimeMs:t})),o||null}catch{return null}}function eY(e,t){let i=_(e),n=_(t);return!(i.length<n.length||i.some(e=>B.has(e))||i.some(e=>j.test(e)))&&n.every((e,t)=>"*"===e||e===i[t])}let eZ=/^-{1,2}c$/;function eK(e){return e.split(/&&|\|\||[|;\n]/).map(e=>e.trim()).filter(e=>/^git\s+push\s/.test(e)).map(e=>e.replace(/^git\s+push\s+/,""))}let eQ=/^(?:~[A-Za-z0-9_.-]*|\$HOME|\$\{HOME\})(?=$|\/)/,eV=/^(?:\/\S*\/)?rm$/,eX=/^(?:\/\S*\/)?find$/,e0=/^-(?:exec|execdir|ok|okdir)$/,e1=/^-(?:[HLP]|D|O\d*)$/,e6=/^(?:-|\\?[(!])/,e3=["/tmp","/var/tmp"];function e9(e){let t=e.match(/^(?:~|\$HOME|\$\{HOME\})(?=$|\/)/);return t?(0,a.homedir)()+e.slice(t[0].length):e}function e2(e){return e.replace(/\/\*$/,"").replace(/\/+$/,"")}function e8(e){let t=e.replace(/^['"]|['"]$/g,"");if(""===t)return!1;let i=t.match(eQ);if(!i&&/^[$`]/.test(t))return!0;let n=i?t.slice(i[0].length):t.startsWith("/")?t:null;if(null===n)return!1;let r=e2(n).split("/").filter(Boolean);return!(!i&&e3.some(e=>`/${r.join("/")}`.startsWith(`${e}/`)))&&r.length<=2}function e4(e){let t=_(e),i=t.findIndex(e=>eX.test(e));if(i>=0){let e=t.slice(i+1),n=e.findIndex(e=>e0.test(e));if(e.includes("-delete")||n>=0&&eV.test(e[n+1]??"")){let t=0;for(;t<e.length&&e1.test(e[t]);)t+="-D"===e[t]?2:1;let i=e.slice(t),n=i.findIndex(e=>e6.test(e));return n<0?i:i.slice(0,n)}}let n=t.findIndex(e=>eV.test(e));if(n>=0){let e=t.slice(n+1),i=e.filter(e=>/^-[^-]/.test(e)).join(""),r=e.filter(e=>/^--/.test(e)),o=/r/i.test(i)||r.some(e=>/^--recursive$/i.test(e)),s=/f/.test(i)||r.some(e=>/^--force$/i.test(e));if(o&&s)return e.filter(e=>!e.startsWith("-"))}return null}function e5(e){return e.split(/&&|\|\||[|;\n]/).map(e=>e.trim()).filter(e=>""!==e)}let e7=/(?:^|;|&&|\|\||\|)\s*(?:ls|find|cat|head|tail|less|more|wc|file|stat|tree|du)\s/;function te(e,t,i){if("Bash"!==e.toolName)return c();let n=x(e);return!t.test(n)||(e.params?.allowPatterns??[]).some(e=>eY(n,e))?c():d(i)}let tt=/\s*(?:&&|\|\||\||;)\s*/;function ti(e){return e.session?.permissionMode==="plan"}let tn={"sanitize-jwt":function(e){let t=JSON.stringify(e.payload);return D.test(t)?{decision:"deny",reason:"JWT token detected in tool output",message:"[REDACTED: JWT token removed by failproofai]"}:c()},"sanitize-api-keys":function(e){let t=JSON.stringify(e.payload);for(let[e,i]of W)if(e.test(t))return{decision:"deny",reason:`${i} detected in tool output`,message:`[REDACTED: ${i} removed by failproofai]`};for(let{regex:i,label:n}of e.params?.additionalPatterns??[])try{if(new RegExp(i).test(t))return{decision:"deny",reason:`${n} detected in tool output`,message:`[REDACTED: ${n} removed by failproofai]`}}catch{A(`additionalPatterns: invalid regex "${i}", skipping`)}return c()},"sanitize-connection-strings":function(e){let t=JSON.stringify(e.payload);return M.test(t)?{decision:"deny",reason:"Database connection string with credentials detected in tool output",message:"[REDACTED: connection string removed by failproofai]"}:c()},"sanitize-private-key-content":function(e){let t=JSON.stringify(e.payload);return U.test(t)?{decision:"deny",reason:"Private key content detected in tool output",message:"[REDACTED: private key content removed by failproofai]"}:c()},"sanitize-bearer-tokens":function(e){let t=JSON.stringify(e.payload);return z.test(t)?{decision:"deny",reason:"Bearer token detected in tool output",message:"[REDACTED: Bearer token removed by failproofai]"}:c()},"protect-env-vars":function(e){if("Bash"!==e.toolName)return c();let t=x(e);return Y.test(t)?d("Command reads environment variables"):Z.test(t)?d("Command echoes environment variable"):K.test(t)?d("Command exports environment variable"):Q.test(t)?d("Command reads environment variable via PowerShell"):V.test(t)?d("Command reads environment variables via PowerShell"):X.test(t)?d("Command reads environment variable via .NET"):ee.test(t)?d("Command echoes environment variable via cmd"):c()},"block-env-files":function(e){let t=x(e),i=R(e);return i&&et.test(i)?d("Access to .env file blocked"):"Bash"===e.toolName&&ei.test(t)?d("Command references .env file"):c()},"block-read-outside-cwd":function(e){let t=process.env.CLAUDE_PROJECT_DIR||e.session?.cwd;if(!t)return c();let i=e.params?.allowPaths??[];if("Bash"===e.toolName){let r=x(e);if(!e7.test(r))return c();let o=function(e){let t,i=[],r=/(?<![a-zA-Z0-9_.\-~\\*?:=])(?:~\/[^\s;|&"'()\[\]{}]*|~(?=\s|$|[;|&"'()\[\]{}])|\/[^\s;|&"'()\[\]{}]*)/g;function o(e){let t;for(r.lastIndex=0;null!==(t=r.exec(e));){let e=t[0];"~"===e?e=(0,a.homedir)():e.startsWith("~/")&&(e=(0,n.join)((0,a.homedir)(),e.slice(2))),i.push(e)}}let s=e.length,l=!1,c=!1;for(let t=0;t<e.length;t++){let i=e[t];if('"'!==i||c)if("'"!==i||l){if("|"===i&&!l&&!c){s=t;break}}else c=!c;else l=!l}let d=e.slice(0,s),p=/"([^"]*)"|'([^']*)'/g;for(;null!==(t=p.exec(d));){let e=t[1]??t[2]??"";/[*?\[\]^$+()\\]/.test(e)||o(e)}return o(e.replace(/"[^"]*"/g,e=>" ".repeat(e.length)).replace(/'[^']*'/g,e=>" ".repeat(e.length))),i}(r),s=t.endsWith("/")?t:t+"/";for(let e of o){let r=(0,n.resolve)(t,e);if(O(r))return d(`Reading agent settings file blocked: ${r}`);if(!I(r)&&"/dev/null"!==r&&r!==t&&!r.startsWith(s)){if(i.some(e=>r===e||r.startsWith(e.endsWith("/")?e:e+"/")))continue;return d(`Bash read outside project directory blocked: ${r}`)}}return c()}let r=R(e),o=e.toolInput?.path??"",s=r||o;if(!s)return c();let l=(0,n.resolve)(t,s);if(O(l))return d(`Reading agent settings file blocked: ${l}`);if(I(l)||"/dev/null"===l)return c();let p=t.endsWith("/")?t:t+"/";return l===t||l.startsWith(p)?c():i.some(e=>l===e||l.startsWith(e.endsWith("/")?e:e+"/"))?c():d(`Access outside project directory blocked: ${l}`)},"block-sudo":function(e){if("Bash"!==e.toolName)return c();let t=x(e).trimStart();return function e(t,i=0){for(let n of function(e){let t=[],i=[],n="",r=null,o=()=>{n&&i.push(n),n=""},s=()=>{o(),i.length&&t.push(i),i=[]};for(let t=0;t<e.length;t++){let i=e[t];if(r){if("\\"===i&&'"'===r&&t+1<e.length){n+=e[++t];continue}if(i===r){r=null;continue}n+=i;continue}if("\\"===i&&t+1<e.length){n+=e[++t];continue}if('"'===i||"'"===i){r=i;continue}if(/\s/.test(i)){o();continue}if(/[;&|\n\r(){}`]/.test(i)){s();continue}n+=i}return s(),t}(t)){let t=0;for(;t<n.length;){let r=n[t],o=r.slice(r.lastIndexOf("/")+1);if("sudo"===o||"doas"===o)return!0;if(!(eu.test(r)||r.startsWith("-")||r.startsWith(">")||r.startsWith("<")||em.test(r)||ea.has(o)))break;if(eZ.test(r)&&i<3&&t+1<n.length&&e(n[t+1],i+1))return!0;t++}}return!1}(t)?(e.params?.allowPatterns??[]).some(e=>eY(t,e))?c():d("sudo commands are blocked"):en.test(t)?d("Elevated process launch is blocked"):er.test(t)?d("runas elevation is blocked"):c()},"block-curl-pipe-sh":function(e){if("Bash"!==e.toolName)return c();let t=x(e);return eo.test(t)?d("Piping downloads to shell is blocked"):eh.test(t)?d("Piping downloads to Invoke-Expression is blocked"):c()},"block-rm-rf":function(e){if("Bash"!==e.toolName)return c();let t=x(e);return e5(t).some(e=>{let t=e4(e);return null!==t&&t.some(e8)})?!function(e,t){if(0===t.length)return!1;let i=t.map(e=>e2(e9(e))||"/"),n=!1;for(let r of e5(e)){let e=e4(r);if(null!==e)for(let o of(n=!0,e)){let e=e2(e9(o))||"/";if(!i.some(t=>e===t||e.startsWith(t+"/"))&&!t.some(e=>{let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return RegExp(`${t}(?:[/"'\\s/*]|$)`).test(r)}))return!1}}return n}(t,e.params?.allowPaths??[])?d("Catastrophic deletion blocked"):c():/Remove-Item\s+.*-Recurse.*-Force.*(?:[A-Z]:\\(?:\s|$)|\\\*)/i.test(t)||/(?:rd|rmdir)\s+\/s\s+\/q\s+[A-Z]:\\/i.test(t)?d("Catastrophic deletion blocked"):c()},"block-failproofai-commands":function(e){if("Bash"!==e.toolName)return c();let t=x(e),i=t.replace(/\\\r?\n/g,"").replace(/\$'((?:[^'\\]|\\.)*)'/g,(e,t)=>t.replace(/\\(x[0-9A-Fa-f]{1,2}|u[0-9A-Fa-f]{1,4}|U[0-9A-Fa-f]{1,8}|[0-7]{1,3}|.)/g,(e,t)=>{try{if("x"===t[0])return String.fromCharCode(parseInt(t.slice(1),16));if("u"===t[0]||"U"===t[0])return String.fromCodePoint(parseInt(t.slice(1),16));if(/^[0-7]+$/.test(t))return String.fromCharCode(parseInt(t,8))}catch{return t}return({a:"\x07",b:"\b",e:"\x1b",f:"\f",n:"\n",r:"\r",t:" ",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"})[t]??t})).replace(/\\(.)/g,"$1").replace(/['"]/g,""),n=ef(t)??ef(i);return"pause"===n?d("Pausing failproofai enforcement is a human action, not an agent one. If a policy is blocking legitimate work, say so and let the operator decide."):"cli"===n?d("Running failproofai CLI commands is blocked"):eN.test(t)||eN.test(i)?d("Uninstalling failproofai is blocked"):eS.test(t)||eS.test(i)?d("Deleting or moving failproofai's own state would switch enforcement off. If a policy is blocking legitimate work, say so and let the operator decide."):c()},"block-kubectl":function(e){return te(e,eM,"kubectl commands are blocked")},"block-terraform":function(e){return te(e,eU,"terraform/tofu commands are blocked")},"block-aws-cli":function(e){return te(e,ez,"aws CLI commands are blocked")},"block-gcloud":function(e){return te(e,eL,"gcloud commands are blocked")},"block-az-cli":function(e){return te(e,eF,"az (Azure) CLI commands are blocked")},"block-helm":function(e){return te(e,eH,"helm commands are blocked")},"block-gh-pipeline":function(e){return te(e,eq,"gh pipeline-trigger commands are blocked")},"block-secrets-write":function(e){if("Write"!==e.toolName)return c();let t=R(e);if(eb.test(t)||ew.test(t)||ek.test(t))return d("Writing secret key files is blocked");for(let i of e.params?.additionalPatterns??[])if(t.includes(i))return d(`Writing blocked file pattern: ${i}`);return c()},"block-push-master":function(e){if("Bash"!==e.toolName)return c();let t=e.params?.protectedBranches??["main","master"];if(0===t.length)return c();let i=eK(x(e)),n=RegExp(`\\b(?:${t.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")})\\b`);return i.some(e=>n.test(e))?d(`Pushing to ${t.join("/")} is blocked`):c()},"block-force-push":function(e){if("Bash"!==e.toolName)return c();for(let t of eK(x(e))){let e=!1;for(let i of t.split(/\s+/)){if("--"===i){e=!0;continue}if(!e&&function(e){return"--force"===e||!ey.some(t=>e.startsWith(t))&&(!!e.startsWith("--force")||eg.test(e))}(i))return d("Force-pushing is blocked")}}return c()},"block-work-on-main":function(e){if("Bash"!==e.toolName)return c();let t=x(e).match(ev);if(!t)return c();let i=e.session?.cwd;if(!i)return c();let n=eG(i);return n&&(e.params?.protectedBranches??["main","master"]).includes(n)?d(`Git ${t[1]} on ${n} is blocked. Create a feature branch first.`):c()},"warn-git-amend":function(e){if("Bash"!==e.toolName)return c();let t=x(e);return e$.test(t)?p("STOP: This command amends the last commit, which rewrites git history. If this commit has already been pushed to a shared branch, this will cause divergence for other contributors. Confirm with the user before executing."):c()},"warn-git-stash-drop":function(e){if("Bash"!==e.toolName)return c();let t=x(e);return eT.test(t)?p("STOP: This command permanently deletes stashed changes (git stash drop/clear). Stash entries cannot be recovered after deletion. Confirm with the user before executing."):c()},"warn-all-files-staged":function(e){if("Bash"!==e.toolName)return c();let t=x(e);return eE.test(t)?p("STOP: This command stages all files in the working tree (git add -A / --all / .). This may inadvertently include build artifacts, generated files, or sensitive files not covered by .gitignore. Confirm with the user before executing."):c()},"warn-destructive-sql":function(e){if("Bash"!==e.toolName)return c();let t=x(e);return L.test(t)&&(F.test(t)||H.test(t)&&!q.test(t))?p("STOP: This command contains destructive SQL (DROP/TRUNCATE/DELETE). Confirm with the user before executing."):c()},"warn-schema-alteration":function(e){if("Bash"!==e.toolName)return c();let t=x(e);return L.test(t)&&J.test(t)?p("STOP: This command contains a schema-altering SQL statement (ALTER TABLE with column or rename operation). Schema changes on production databases are irreversible or disruptive. Confirm with the user before executing."):c()},"warn-package-publish":function(e){if("Bash"!==e.toolName)return c();let t=x(e);return G.test(t)?p("STOP: This command publishes a package to a public registry. Confirm with the user that this is intentional."):c()},"warn-global-package-install":function(e){if("Bash"!==e.toolName)return c();let t=x(e);return eP.test(t)||eC.test(t)||eA.test(t)||eI.test(t)||eO.test(t)||ex.test(t)?p("STOP: This command installs a package globally, which modifies the system-wide environment outside the project. This can conflict with other projects or system tools. Confirm with the user before executing."):c()},"prefer-package-manager":function(e){if("Bash"!==e.toolName)return c();let t=x(e);if(!t)return c();let i=e.params?.allowed??[];if(0===i.length)return c();let n=new Set(i.map(e=>e.toLowerCase())),r=e.params?.blocked??[],o=i.join(", ");for(let e of t.split(tt)){let t=e.trim();if(!t)continue;let i=!1;for(let e of n){let n=eR[e];if(n){for(let e of n)if(e.test(t)){i=!0;break}if(i)break}}if(!i){for(let[e,i]of Object.entries(eR))if(!n.has(e)){for(let n of i)if(n.test(t))return d(`"${e}" is not an allowed package manager. Allowed package managers for this project: ${o}. Rewrite this command using an allowed package manager.`)}for(let e of r){let i=e.toLowerCase();if(!n.has(i)&&RegExp(`\\b${i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`).test(t))return d(`"${i}" is not an allowed package manager. Allowed package managers for this project: ${o}. Rewrite this command using an allowed package manager.`)}}}return c()},"warn-large-file-write":function(e){if("Write"!==e.toolName)return c();let t=e.toolInput?.content;if("string"!=typeof t)return c();let i=e.params?.thresholdKb??1024;return t.length>1024*i?p(`STOP: You are writing a file larger than ${i}KB (${Math.round(t.length/1024)}KB). This is unusually large. Confirm this is intentional before proceeding.`):c()},"warn-background-process":function(e){if("Bash"!==e.toolName)return c();let t=x(e);return e_.test(t)||eB.test(t)||ej.test(t)||eD.test(t)||eW.test(t)?p("STOP: This command starts a background or detached process (nohup, screen -d, tmux -d, or trailing &). Background processes persist after Claude's session and may be difficult to track or stop. Confirm with the user before executing."):c()},"warn-repeated-tool-calls":async function e(e){let t=e.session?.transcriptPath;if(!t||!e.toolName||!e.toolInput)return c();let i=`${t}.tool-calls.json`,n=JSON.stringify({tool:e.toolName,input:e.toolInput}),r={};try{let e=await (0,o.readFile)(i,"utf8");r=JSON.parse(e)}catch{}let s=r[n]??0;if(s>=3)return p(`STOP: You have already called ${e.toolName} ${s} times with identical parameters. This is wasteful and unproductive. Do NOT repeat this call — use a different approach or ask the user for clarification.`);r[n]=s+1;try{let e=JSON.stringify(r);e.length<=65536&&await (0,o.writeFile)(i,e,"utf8")}catch{}return c()},"require-commit-before-stop":function(e){if(ti(e))return c("Plan mode — no changes made, skipping commit check.");let t=e.session?.cwd;if(!t)return c("No working directory available, skipping commit check.");try{if((0,s.execSync)("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().length>0)return d("You have uncommitted changes in the working directory. Commit all changes now.");return c("All changes are committed.")}catch{return c("Not a git repository, skipping commit check.")}},"require-push-before-stop":function(e){if(ti(e))return c("Plan mode — no changes made, skipping push check.");let t=e.session?.cwd;if(!t)return c("No working directory available, skipping push check.");try{if(!(0,s.execSync)("git remote",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}).trim())return c("No git remote configured, skipping push check.");let i=e.params?.remote??"origin",n=eG(t);if(!n||"HEAD"===n)return c("Detached HEAD, skipping push check.");let r=e.params?.baseBranch??"main";if(n===r)return c(`On base branch "${r}", skipping push check.`);try{if(!(0,s.execFileSync)("git",["log",`${i}/${r}..HEAD`,"--oneline"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return c(`No commits ahead of ${i}/${r}, skipping push check.`);if(!(0,s.execFileSync)("git",["diff","--stat",`${i}/${r}`,"HEAD"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return c(`No file changes compared to ${i}/${r}, skipping push check.`)}catch{}let o=!1;try{(0,s.execFileSync)("git",["rev-parse","--verify",`${i}/${n}`],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}),o=!0}catch{}if(!o)return d(`Branch "${n}" has not been pushed to remote "${i}". Run now: git push -u ${i} ${n}`);let a=(0,s.execFileSync)("git",["log",`${i}/${n}..HEAD`,"--oneline"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim();if(a.length>0){let e=a.split("\n").length;return d(`You have ${e} unpushed commit${e>1?"s":""} on branch "${n}". Run now: git push`)}return c(`All commits pushed to "${i}".`)}catch{return c("Could not check push status, skipping.")}},"require-pr-before-stop":function(e){if(ti(e))return c("Plan mode — no changes made, skipping PR check.");let t=e.session?.cwd;if(!t)return c("No working directory available, skipping PR check.");try{let i;try{(0,s.execSync)("gh --version",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3})}catch{return c("GitHub CLI (gh) not installed, skipping PR check.")}let n=eG(t);if(!n||"HEAD"===n)return c("Detached HEAD, skipping PR check.");let r=e.params?.baseBranch??"main";if(n===r)return c(`On base branch "${r}", skipping PR check.`);try{if(!(0,s.execFileSync)("git",["log",`origin/${r}..HEAD`,"--oneline"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return c(`No commits ahead of origin/${r}, skipping PR check.`);if(!(0,s.execFileSync)("git",["diff","--stat",`origin/${r}`,"HEAD"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return c(`No file changes compared to origin/${r}, skipping PR check.`)}catch{}try{i=(0,s.execSync)("gh pr view --json number,url,state",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim()}catch{return d(`No pull request found for branch "${n}". Run now: gh pr create`)}let o=JSON.parse(i);if("OPEN"===o.state)return c(`PR #${o.number} exists: ${o.url}`);if("MERGED"===o.state)return c(`PR #${o.number} was merged: ${o.url}. Switch off this branch (e.g. 'git checkout ${r} && git pull') before stopping again.`);return d(`Pull request for branch "${n}" is ${o.state.toLowerCase()}. Run now: gh pr create`)}catch{return c("Could not check PR status, skipping.")}},"require-no-conflicts-before-stop":function(e){let t,i;if(ti(e))return c("Plan mode — no changes made, skipping conflict check.");let n=e.session?.cwd;if(!n)return c("No working directory available, skipping conflict check.");let r=eG(n);if(!r||"HEAD"===r)return c("Detached HEAD, skipping conflict check.");let o=e.params?.baseBranch??"main";if(r===o)return c(`On base branch "${o}", skipping conflict check.`);try{(0,s.execSync)("gh --version",{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3})}catch{return c("gh CLI not installed, skipping conflict check.")}try{t=(0,s.execSync)("gh pr view --json mergeable,number,url,state",{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim()}catch{return c("No pull request found for branch, skipping conflict check.")}try{i=JSON.parse(t)}catch{return c("Could not parse gh pr view output, skipping conflict check.")}if("OPEN"!==i.state)return c(`PR #${i.number} is ${i.state.toLowerCase()}; skipping conflict check.`);try{(0,s.execFileSync)("git",["rev-parse","--verify",`origin/${o}`],{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}),(0,s.execFileSync)("git",["log",`origin/${o}..HEAD`,"--oneline"],{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim()&&(0,s.execFileSync)("git",["merge-tree","--write-tree","--name-only",`origin/${o}`,"HEAD"],{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:1e4})}catch(e){if(1===e.status){let t=("string"==typeof e.stdout?e.stdout:e.stdout?.toString("utf8")??"").trim().split("\n"),i=[];for(let e=1;e<t.length;e++){let n=t[e];if(""===n)break;i.push(n)}let n=i.length?i.join(", "):"one or more files";return d(`Branch "${r}" has merge conflicts with ${o} in: ${n}. Rebase or merge origin/${o} now and resolve the conflicts.`)}}return"CONFLICTING"===i.mergeable?d(`PR #${i.number} has merge conflicts per GitHub (${i.url}). Rebase or merge origin/${o} now and resolve the conflicts.`):"UNKNOWN"===i.mergeable?d(`GitHub is still computing mergeability for PR #${i.number} (${i.url}). Wait ~10 seconds, then re-check with \`gh pr view --json mergeable\` before attempting to stop again.`):c(`PR #${i.number} merges cleanly per GitHub.`)},"require-ci-green-before-stop":function(e){if(ti(e))return c("Plan mode — no changes made, skipping CI check.");let t=e.session?.cwd;if(!t)return c("No working directory available, skipping CI check.");try{try{(0,s.execSync)("gh --version",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3})}catch{return c("GitHub CLI (gh) not installed, skipping CI check.")}let e=eG(t);if(!e||"HEAD"===e)return c("Detached HEAD, skipping CI check.");let i=function(e){try{return(0,s.execSync)("git rev-parse HEAD",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}).trim()||null}catch{return null}}(t),n=[];try{let r=(0,s.execFileSync)("gh",["run","list","--branch",e,"--limit","20","--json","status,conclusion,name,headSha"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim();if(r&&"[]"!==r){let e=JSON.parse(r),t=i?e.filter(e=>e.headSha===i):e,o=new Set;n=t.filter(e=>!o.has(e.name)&&(o.add(e.name),!0))}}catch{}let r=[],o=[];i&&(r=function(e,t){try{let i=(0,s.execFileSync)("gh",["api",`repos/{owner}/{repo}/commits/${t}/check-runs`,"--jq",'.check_runs | map(select(.app.slug != "github-actions")) | map({name: .name, status: .status, conclusion: (.conclusion // "")})'],{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim();if(!i||"[]"===i)return[];return JSON.parse(i)}catch{return[]}}(t,i),o=function(e,t){try{let i=(0,s.execFileSync)("gh",["api",`repos/{owner}/{repo}/commits/${t}/statuses`,"--jq","map({name: .context, state: .state}) | unique_by(.name)"],{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim();if(!i||"[]"===i)return[];return JSON.parse(i).map(e=>({name:e.name,status:"pending"===e.state?"in_progress":"completed",conclusion:"pending"===e.state?"":"success"===e.state?"success":"failure"}))}catch{return[]}}(t,i));let a=[...n,...r,...o];if(0===a.length)return c(`No CI runs found for branch "${e}".`);let l=a.filter(e=>"completed"===e.status&&"success"!==e.conclusion&&"skipped"!==e.conclusion&&"cancelled"!==e.conclusion&&"neutral"!==e.conclusion);if(l.length>0){let t=l.map(e=>`"${e.name}"`).join(", ");return d(`CI checks are failing on branch "${e}": ${t}. Fix the failing checks now.`)}let p=a.filter(e=>"in_progress"===e.status||"queued"===e.status||"waiting"===e.status);if(p.length>0){let t=p.map(e=>`"${e.name}"`).join(", ");return d(`CI checks are still running on branch "${e}": ${t}. Wait for all checks to complete, then verify they pass.`)}return c(`All CI checks passed on branch "${e}".`)}catch{return c("Could not check CI status, skipping.")}}},tr=new Set(Object.keys(tn)),to=l.filter(e=>!tr.has(e.name)).map(e=>e.name);if(to.length>0)throw Error(`failproofai: builtin policies missing an implementation: ${to.join(", ")}`);let ts=new Set(l.map(e=>e.name)),ta=[...tr].filter(e=>!ts.has(e));if(ta.length>0)throw Error(`failproofai: policy implementations with no catalog entry: ${ta.join(", ")}`);let tl=l.map(e=>({...e,fn:tn[e.name]}));function tc(e){if(!(0,r.existsSync)(e))return{};try{let t=(0,r.readFileSync)(e,"utf8");return JSON.parse(t)}catch(t){return A(`failed to parse config at ${e}: ${t instanceof Error?t.message:String(t)}`),{}}}var td=e.i(66680);let tp=[1],tu=/^[a-f0-9]{64}$/,tm=/^[A-Za-z0-9._-]{1,64}\/[A-Za-z0-9._-]{1,64}$/,tf=/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/,th=/^[0-9a-f]{7,40}$/,tg=/^[A-Za-z0-9._-]{1,128}$/;function ty(e){return e instanceof Error?e.message:String(e)}let tb=["claude","codex","copilot","cursor","opencode","pi","hermes","openclaw","factory","devin","antigravity","goose"],tw={apply_patch:"Edit",write_stdin:"Bash"},tk={terminal:"Bash",bash:"Bash",read_file:"Read",write_file:"Write",patch:"Edit",web_search:"WebSearch",web_extract:"WebFetch",search_files:"Grep",todo:"TodoWrite"},tv={Read:{path:"file_path"},Write:{path:"file_path"},Edit:{path:"file_path"}},tS={bash:"Bash",powershell:"Bash",list_bash:"Bash",read_bash:"Bash",stop_bash:"Bash",write_bash:"Bash",list_powershell:"Bash",read_powershell:"Bash",stop_powershell:"Bash",write_powershell:"Bash",read:"Read",view:"Read",show_file:"Read",write:"Write",create:"Write",edit:"Edit",apply_patch:"Edit",str_replace_editor:"Edit",glob:"Glob",grep:"Grep",rg:"Grep",ls:"LS",web_fetch:"WebFetch"},tN={Read:{path:"file_path"},Write:{path:"file_path",file_text:"content"},Edit:{path:"file_path",old_str:"old_string",new_str:"new_string"}},t$={Shell:"Bash"},tT={bash:"Bash",read:"Read",write:"Write",edit:"Edit",apply_patch:"Edit",glob:"Glob",grep:"Grep",list:"LS",webfetch:"WebFetch",websearch:"WebSearch",todowrite:"TodoWrite",todoread:"TodoRead"},tE={Read:{filePath:"file_path"},Write:{filePath:"file_path"},Edit:{filePath:"file_path",oldString:"old_string",newString:"new_string",replaceAll:"replace_all"}},tP={bash:"Bash",read:"Read",write:"Write",edit:"Edit",glob:"Glob",grep:"Grep"},tC={Read:{path:"file_path"},Write:{path:"file_path"},Edit:{path:"file_path"}},tA={exec:"Bash",read:"Read",write:"Write",edit:"Edit",grep:"Grep",glob:"Glob",web_search:"WebSearch",web_fetch:"WebFetch"},tI={Read:{path:"file_path"},Write:{path:"file_path"},Edit:{path:"file_path"}},tO={Execute:"Bash",Read:"Read",Edit:"Edit",Create:"Write",Grep:"Grep",Glob:"Glob",LS:"LS",FetchUrl:"WebFetch",WebSearch:"WebSearch",TodoWrite:"TodoWrite",Task:"Task"},tx={exec:"Bash"},tR={run_command:"Bash",write_to_file:"Write",read_file:"Read",view_file:"Read",edit_file:"Edit",replace_file_content:"Edit",list_dir:"LS",find_by_name:"Glob",grep_search:"Grep",read_url_content:"WebFetch",search_web:"WebSearch"},t_={Bash:{CommandLine:"command",Cwd:"cwd"},Write:{TargetFile:"file_path",CodeContent:"content"},Edit:{TargetFile:"file_path"},Read:{TargetFile:"file_path",AbsolutePath:"file_path",File:"file_path"}},tB={shell:"Bash",write:"Write",edit:"Edit",view:"Read",read_image:"Read",glob:"Glob",grep:"Grep",tree:"LS",delegate:"Task",todo__todo_write:"TodoWrite"},tj={Read:{path:"file_path",source:"file_path"},Write:{path:"file_path"},Edit:{path:"file_path"},LS:{path:"file_path"}};["SessionStart","SessionEnd","UserPromptSubmit","PreToolUse","PermissionRequest","PermissionDenied","PostToolUse","PostToolUseFailure","Notification","SubagentStart","SubagentStop","TaskCreated","TaskCompleted","Stop","StopFailure","TeammateIdle","InstructionsLoaded","ConfigChange","CwdChanged","FileChanged","WorktreeCreate","WorktreeRemove","PreCompact","PostCompact","Elicitation","ElicitationResult","UserPromptExpansion","PostToolBatch","Setup"].filter(e=>"WorktreeCreate"!==e);var tD=e.i(81580);let tW=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;var tM=e.i(54214);function tU(e,t){let i=[];for(let r of e)if("assistant"===r.type)for(let e of r.message.content){var n;let o;if("tool_use"!==e.type)continue;let s=e.name,a=(n=t.cli,(s?"copilot"===n?tS[s]??s:"cursor"===n?t$[s]??s:"codex"===n?tw[s]??s:"opencode"===n?tT[s]??s:"pi"===n?tP[s]??s:"hermes"===n?tk[s]??s:"openclaw"===n?tA[s]??s:"factory"===n?tO[s]??s:"devin"===n?tx[s]??s:"antigravity"===n?tR[s]??s:"goose"===n?tB[s]??s:s:s)??s),l=function(e,t,i){let n;if(!e||!t||"object"!=typeof t||Array.isArray(t)||("copilot"===i?n=tN[e]:"opencode"===i?n=tE[e]:"pi"===i?n=tC[e]:"hermes"===i?n=tv[e]:"openclaw"===i?n=tI[e]:"antigravity"===i?n=t_[e]:"goose"===i&&(n=tj[e]),!n))return t;let r={};for(let[e,i]of Object.entries(t))r[n[e]??e]=i;return r}(a,e.input,t.cli);e.result?.content&&(o=function(e){let t=Buffer.from(e,"utf-8");if(t.byteLength<=65536)return e;let i=65536;for(;i>0&&(192&t[i])==128;)i--;return t.subarray(0,i).toString("utf-8")}(e.result.content)),i.push({cli:t.cli,sessionId:t.sessionId,transcriptPath:t.transcriptPath,cwd:t.cwd,timestamp:r.timestamp,toolName:a,rawToolName:s,toolInput:l??{},toolResultText:o})}return i}async function tz(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,o=[];for(let e of function(){let e,t=(0,tD.getClaudeProjectsPath)();try{e=(0,r.readdirSync)(t,{withFileTypes:!0})}catch{return[]}return e.filter(e=>e.isDirectory()).map(e=>({name:e.name,cwd:(0,tD.decodeFolderName)(e.name),path:(0,n.join)(t,e.name)}))}()){let s;if(!t||t.has(e.cwd)){try{s=function(e){let t,i=[];try{t=(0,r.readdirSync)(e.path,{withFileTypes:!0})}catch{return i}for(let o of t)if(o.isFile()&&o.name.endsWith(".jsonl")){let t=o.name.slice(0,-6);if(!tW.test(t))continue;let s=(0,n.join)(e.path,o.name);try{let n=(0,r.statSync)(s);i.push({projectName:e.name,cwd:e.cwd,sessionId:t,transcriptPath:s,mtimeMs:n.mtimeMs,sizeBytes:n.size,isSubagent:!1})}catch{}}else if(o.isDirectory()&&tW.test(o.name)){let t,s=(0,n.join)(e.path,o.name,"subagents");if(!(0,r.existsSync)(s))continue;try{t=(0,r.readdirSync)(s,{withFileTypes:!0})}catch{continue}for(let o of t){if(!o.isFile()||!o.name.endsWith(".jsonl"))continue;let t=o.name.slice(0,-6),a=(0,n.join)(s,o.name);try{let n=(0,r.statSync)(a);i.push({projectName:e.name,cwd:e.cwd,sessionId:t,transcriptPath:a,mtimeMs:n.mtimeMs,sizeBytes:n.size,isSubagent:!0})}catch{}}}return i}(e)}catch{continue}for(let t of s)t.mtimeMs<i||o.push({cli:"claude",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.transcriptPath,mtimeMs:t.mtimeMs,sizeBytes:t.sizeBytes})}}return o}async function tL(e){let t,i;try{t=await (0,o.readFile)(e.transcriptPath,"utf-8")}catch{return[]}try{i=await (0,tM.parseLogContent)(t,"session")}catch{return[]}let n="";for(let e of t.split("\n",50))if(e.trim())try{let t=JSON.parse(e);if("string"==typeof t.cwd&&t.cwd.length>0){n=t.cwd;break}}catch{}return tU(i,{cli:"claude",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:n})}async function tF(e,t){let i,n;if(!Number.isFinite(t)||t<0)return null;let r=null;try{r=await (0,o.open)(e.transcriptPath,"r");let{size:n}=await r.stat();if(t>n)return null;if(t===n)return{events:[],bytesConsumed:t};let s=Buffer.alloc(n-t);await r.read(s,0,s.length,t),i=s.toString("utf-8")}catch{return null}finally{if(r)try{await r.close()}catch{}}let s=i.lastIndexOf("\n"),a=-1===s?"":i.slice(0,s+1),l=i.slice(s+1),c=l.trim().length>0&&(()=>{try{return JSON.parse(l),!0}catch{return!1}})()?a+l:a;if(0===c.length)return{events:[],bytesConsumed:t};let d=t+Buffer.byteLength(c,"utf-8");try{n=await (0,tM.parseLogContent)(c,"session")}catch{return null}let p="";for(let e of c.split("\n",50))if(e.trim())try{let t=JSON.parse(e);if("string"==typeof t.cwd&&t.cwd.length>0){p=t.cwd;break}}catch{}return{events:tU(n,{cli:"claude",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:p}),bytesConsumed:d,cwd:p||void 0}}var tH=e.i(36203),tq=e.i(57232);async function tJ(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tH.getCodexProjects)())){let{cwd:o,sessions:s}=await (0,tH.getCodexSessionsByEncodedName)(e.name),a=o??"";if(!t||t.has(a))for(let t of s){let o=t.lastModified.getTime();if(o<i)continue;let s=0;try{s=(0,r.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"codex",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:o,sizeBytes:s})}}return n}async function tG(e){let t=await (0,tq.getCodexSessionLog)(e.sessionId);return t?tU(t.entries,{cli:"codex",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tY=e.i(55851),tZ=e.i(78166);async function tK(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tY.getCopilotProjects)())){let{cwd:o,sessions:s}=await (0,tY.getCopilotSessionsByEncodedName)(e.name),a=o??"";if(!t||t.has(a))for(let t of s){let o=t.lastModified.getTime();if(o<i)continue;let s=0;try{s=(0,r.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"copilot",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:o,sizeBytes:s})}}return n}async function tQ(e){let t=await (0,tZ.getCopilotSessionLog)(e.sessionId);return t?tU(t.entries,{cli:"copilot",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tV=e.i(46413),tX=e.i(72094);async function t0(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tV.getCursorProjects)())){let{cwd:o,sessions:s}=await (0,tV.getCursorSessionsByEncodedName)(e.name),a=o??"";if(!t||t.has(a))for(let t of s){let o=t.lastModified.getTime();if(o<i)continue;let s=0;try{s=(0,r.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"cursor",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:o,sizeBytes:s})}}return n}async function t1(e){let t=await (0,tX.getCursorSessionLog)(e.sessionId);return t?tU(t.entries,{cli:"cursor",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var t6=e.i(35435),t3=e.i(99440);async function t9(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,t6.getOpenCodeProjects)())){let{cwd:r,sessions:o}=await (0,t6.getOpenCodeSessionsByEncodedName)(e.name),s=r??"";if(!t||t.has(s))for(let t of o){let r=t.lastModified.getTime();!(r<i)&&t.sessionId&&n.push({cli:"opencode",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:r,sizeBytes:0})}}return n}async function t2(e){let t=await (0,t3.getOpenCodeSessionLog)(e.sessionId);return t?tU(t.entries,{cli:"opencode",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var t8=e.i(19791),t4=e.i(85116);async function t5(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,t8.getPiProjects)())){let{cwd:o,sessions:s}=await (0,t8.getPiSessionsByEncodedName)(e.name),a=o??"";if(!t||t.has(a))for(let t of s){let o=t.lastModified.getTime();if(o<i)continue;let s=0;try{s=(0,r.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"pi",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:o,sizeBytes:s})}}return n}async function t7(e){let t=await (0,t4.getPiSessionLog)(e.sessionId);return t?tU(t.entries,{cli:"pi",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var ie=e.i(64828),it=e.i(28898),ii=e.i(3605);async function ir(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=await (0,ie.getHermesSessions)(),r=[];for(let e of n)!(e.mtimeMs<i)&&(!(e.messageCount<=0)||e.hasMessages)&&(!t||e.cwd&&t.has(e.cwd))&&r.push({cli:"hermes",projectName:e.cwd?(0,tD.encodeFolderName)(e.cwd):e.source?(0,it.hermesProjectPath)(e.profile,e.source):`hermes:${e.profile}`,sessionId:e.sessionId,transcriptPath:`hermes://${e.sessionId}`,mtimeMs:e.mtimeMs,sizeBytes:e.messageCount});return r}async function io(e){let t=await (0,ii.getHermesSessionLog)(e.sessionId);return t?tU(t.entries,{cli:"hermes",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var is=e.i(90624),ia=e.i(64199);async function il(e={}){if(e.projects&&e.projects.length>0)return[];let t=e.sinceMs??0,i=[];for(let e of(await (0,is.getOpenClawSessions)()))e.mtimeMs<t||i.push({cli:"openclaw",projectName:(0,is.openClawProjectPath)(e.agentId,e.channel),sessionId:e.sessionId,transcriptPath:e.transcriptPath,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes});return i}async function ic(e){let t=await (0,ia.getOpenClawSessionLog)(e.sessionId);return t?tU(t.entries,{cli:"openclaw",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var id=e.i(28246);async function ip(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(0,id.listFactoryTranscripts)())!(e.mtimeMs<i)&&(!t||t.has(e.cwd))&&n.push({cli:"factory",projectName:e.projectName,sessionId:e.sessionId,transcriptPath:e.transcriptPath,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes});return n}async function iu(e){let t;try{t=await (0,o.readFile)(e.transcriptPath,"utf-8")}catch{return[]}let i=(0,tM.parseRawLines)(t,"session"),n=(0,id.factoryLinesToLogEntries)(i,"session"),r="";for(let e of i)if(e&&"object"==typeof e&&"session_start"===e.type){let t=e.cwd;if("string"==typeof t&&t.length>0){r=t;break}}return tU(n,{cli:"factory",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:r})}var im=e.i(93114),ih=e.i(30441);async function ig(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[],r=await (0,ih.getAntigravityIndex)();for(let e of(0,im.listAntigravityTranscripts)()){if(e.mtimeMs<i)continue;let o=r.get(e.conversationId)?.cwd;(!t||o&&t.has(o))&&n.push({cli:"antigravity",projectName:o?(0,tD.encodeFolderName)(o):"antigravity",sessionId:e.conversationId,transcriptPath:e.transcriptPath,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes})}return n}async function iy(e){let t;try{t=await (0,o.readFile)(e.transcriptPath,"utf-8")}catch{return[]}let i=(0,tM.parseRawLines)(t,"session"),n=(0,im.antigravityLinesToLogEntries)(i,"session"),r="";for(let e of i){if(!e||"object"!=typeof e)continue;let t=e.tool_calls;if(Array.isArray(t)){for(let e of t){let t=e&&"object"==typeof e?e.args:void 0,i=t&&"object"==typeof t?t.Cwd:void 0;if("string"==typeof i&&i.length>0){r=i;break}}if(r)break}}return tU(n,{cli:"antigravity",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:r})}var ib=e.i(79364),iw=e.i(40375);async function ik(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=await (0,ib.getDevinSessions)(),r=[];for(let e of n)!(e.mtimeMs<i)&&(!t||e.cwd&&t.has(e.cwd))&&r.push({cli:"devin",projectName:e.projectName,sessionId:e.sessionId,transcriptPath:`devin-db://${e.sessionId}`,mtimeMs:e.mtimeMs,sizeBytes:0});return r}async function iv(e){let t=await (0,iw.getDevinSessionLog)(e.sessionId);return t?tU(t.entries,{cli:"devin",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var iS=e.i(69164),iN=e.i(36618);let i$={claude:{cli:"claude",listTranscripts:tz,streamEvents:tL,streamEventsFrom:tF},codex:{cli:"codex",listTranscripts:tJ,streamEvents:tG},copilot:{cli:"copilot",listTranscripts:tK,streamEvents:tQ},cursor:{cli:"cursor",listTranscripts:t0,streamEvents:t1},opencode:{cli:"opencode",listTranscripts:t9,streamEvents:t2},pi:{cli:"pi",listTranscripts:t5,streamEvents:t7},hermes:{cli:"hermes",listTranscripts:ir,streamEvents:io},openclaw:{cli:"openclaw",listTranscripts:il,streamEvents:ic},factory:{cli:"factory",listTranscripts:ip,streamEvents:iu},devin:{cli:"devin",listTranscripts:ik,streamEvents:iv},antigravity:{cli:"antigravity",listTranscripts:ig,streamEvents:iy},goose:{cli:"goose",listTranscripts:async function(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=await (0,iS.getGooseSessions)(),r=[];for(let e of n)!(e.mtimeMs<i)&&(!t||e.cwd&&t.has(e.cwd))&&r.push({cli:"goose",projectName:e.projectName,sessionId:e.sessionId,transcriptPath:`goose-db://${e.sessionId}`,mtimeMs:e.mtimeMs,sizeBytes:0});return r},streamEvents:async function(e){let t=await (0,iN.getGooseSessionLog)(e.sessionId);return t?tU(t.entries,{cli:"goose",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}}},iT=/\.(?:ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|swift|rb|php|c|h|cc|cpp|hpp|cs|scala|sh|bash|zsh|json|yaml|yml|toml|md|txt|sql|html|css|scss|sass)$/i,iE=["/","/home","/usr","/etc","/var","/opt","/Users"],iP="rereadAfterEdit",iC=[{name:"redundant-cd-cwd",description:"Bash commands prefixed with `cd <cwd> && …` even though commands already run in cwd.",category:"Wasteful",severity:"info",displayTitle:"Prepended cd <cwd> before commands",impact:"Pure waste — your agent's shell already runs in `cwd`.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;if("string"!=typeof t||!e.cwd)return null;let i=t.trimStart(),n=/^cd\s+(?:"([^"]+)"|'([^']+)'|(\S+))\s*&&\s*([\s\S]+)$/.exec(i);if(!n)return null;let r=(n[1]??n[2]??n[3]??"").replace(/\/+$/,"");if(r!==e.cwd.replace(/\/+$/,""))return null;let o=n[4].trim();return{example:`cd ${r} && ${o}`}}},{name:"prefer-edit-over-read-cat",description:"Bash `cat`/`head`/`tail`/`less`/`more` on a single source file — use Read.",category:"Wasteful",severity:"info",displayTitle:"Used `cat`/`head`/`tail` on a source file",impact:"Burns tokens; the Read tool returns content directly without going through Bash output.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;if("string"!=typeof t)return null;let i=t.trim();if(/[|<>;&`$()]/.test(i))return null;let n=/^(cat|head|tail|less|more)\s+(?:-\S+\s+)*(?:"([^"]+)"|'([^']+)'|(\S+))\s*$/.exec(i);if(!n)return null;let r=n[2]??n[3]??n[4]??"";return!r||/(?:^|\/)\.env(?:\..+)?$/.test(r)||!iT.test(r)?null:{example:i}}},{name:"prefer-edit-over-sed-awk",description:"Bash `sed -i`/`awk` in-place edits — use Edit.",category:"Wasteful",severity:"info",displayTitle:"Used sed -i or awk for an in-place edit",impact:"Edit tool is safer and produces a diff the agent can verify.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;if("string"!=typeof t)return null;let i=t.trim();return/(?:^|\s|;|&&|\|\|)sed\b[^|]*\s-i(?=\b|['"])/.test(i)||/(?:^|\s|;|&&|\|\|)awk\b[^|]*\s>\s*\S+/.test(i)&&!/\|/.test(i)?{example:i}:null}},{name:"prefer-write-over-heredoc",description:"Bash heredoc / `echo > file` writing multi-line content — use Write.",category:"Wasteful",severity:"info",displayTitle:"Used heredoc / `echo > file` to write a multi-line file",impact:"Write tool handles escaping and is verifiable.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;return"string"!=typeof t?null:/<<-?\s*['"]?[A-Za-z_][A-Za-z0-9_]*['"]?\s*>\s*\S/.test(t)||/(?:^|\s|;|&&|\|\|)(?:echo|printf)\s+["'][^"']*\n[^"']*["']\s*>\s*\S/.test(t)?{example:t.replace(/\s+/g," ").trim().slice(0,160)}:null}},{name:"sleep-polling-loop",description:"Bash long `sleep` or while-sleep polling loops.",category:"Wasteful",severity:"info",displayTitle:"Used a long sleep or while-sleep polling loop",impact:"Burns wall-clock; better to wait for an explicit signal.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;if("string"!=typeof t)return null;if(/\bwhile\b[\s\S]*?\bsleep\b[\s\S]*?\bdone\b/.test(t))return{example:t.replace(/\s+/g," ").trim().slice(0,160)};let i=/\bsleep\s+(\d+(?:\.\d+)?)(m|h|d)?\b/.exec(t);if(i){let e=parseFloat(i[1]),n=i[2]??"s";if(("m"===n?60*e:"h"===n?3600*e:"d"===n?86400*e:e)>=30)return{example:t.replace(/\s+/g," ").trim().slice(0,160)}}return null}},{name:"find-from-root",description:"Bash `find` against `/`, `/home`, `/usr`, etc. — scope to cwd instead.",category:"Risky",severity:"warn",displayTitle:"Ran find from /, /home, /usr, etc.",impact:"Filesystem-wide finds exhaust resources and rarely return useful results.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;if("string"!=typeof t)return null;let i=t.trim(),n=/(?:^|[\s;|&])find\s+(?:-\S+\s+)*("[^"]+"|'[^']+'|\S+)/.exec(i);if(!n)return null;let r=n[1].replace(/^["']|["']$/g,"").replace(/\/+$/,"")||"/";return iE.includes(r)?{example:i.slice(0,160)}:null}},{name:"git-commit-no-verify",description:"git commit invoked with --no-verify / -n, skipping hooks.",category:"Risky",severity:"warn",displayTitle:"Committed with --no-verify",impact:"Skips pre-commit hooks that exist to catch broken or unsafe code.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;return"string"!=typeof t?null:/\bgit\s+commit\b/.test(t)&&(/\s--no-verify\b/.test(t)||/\s-n\b/.test(t))?{example:t.replace(/\s+/g," ").trim().slice(0,160)}:null}},{name:"reread-after-edit",description:"Read of a file that was just Edit'd or Write'n in the same session.",category:"Wasteful",severity:"info",displayTitle:"Re-read a file it just edited",impact:"Edit/Write already returned the updated content; the second Read is wasted tokens.",detect(e,t){let i,n=((i=t[iP])||(i={countdown:new Map},t[iP]=i),i),r=e.toolInput.file_path,o="string"==typeof r?r:null;for(let[e,t]of n.countdown)t<=1?n.countdown.delete(e):n.countdown.set(e,t-1);return o?"Edit"===e.toolName||"Write"===e.toolName?(n.countdown.set(o,5),null):"Read"===e.toolName&&n.countdown.has(o)?(n.countdown.delete(o),{example:`Read ${o} immediately after Edit/Write`}):null:null}}],iA=["cowboy","explorer","ghost","optimist","hammer","architect"],iI={explorer:.38,architect:.33,hammer:.11,cowboy:.11,optimist:.07,ghost:.01,precision:0,goldfish:0},iO={optimist:0,cowboy:0,explorer:0,goldfish:0,architect:0,precision:0,hammer:0,ghost:0};for(let e of iA)iO[e]=Math.max(iI[e],.05);let ix=null,iR=null;function i_(){if(ix)return ix;let e=tl.map(e=>`${e.name}|${e.fn.toString()}`).sort().join("\n");return ix=(0,td.createHash)("sha1").update(e).digest("hex").slice(0,16)}function iB(){if(iR)return iR;let e=iC.map(e=>`${e.name}|${e.detect.toString()}`).sort().join("\n");return iR=(0,td.createHash)("sha1").update(e).digest("hex").slice(0,16)}function ij(e){let t=(0,b.auditCacheDir)(),i=(0,td.createHash)("sha1").update(e).digest("hex");return(0,n.join)(t,`${i}.json`)}function iD(e,t){if(t<=0)return null;let i=null;try{i=(0,r.openSync)(e,"r");let n=Buffer.alloc(Math.min(4096,t));(0,r.readSync)(i,n,0,n.length,0);let o=Math.min(4096,t),s=Buffer.alloc(o);return(0,r.readSync)(i,s,0,o,t-o),(0,td.createHash)("sha1").update(String(t)).update(n).update(s).digest("hex").slice(0,32)}catch{return null}finally{if(null!==i)try{(0,r.closeSync)(i)}catch{}}}var iW=e.i(24214),iM=e.i(28067),iU=e.i(17694);let iz=iM.POSTHOG_API_KEY,iL=new Set;async function iF(e,t,i){let n=JSON.stringify({api_key:process.env.FAILPROOFAI_POSTHOG_KEY??iz,event:t,distinct_id:e,properties:{...i,$lib:"failproofai-hooks",failproofai_version:iW.version,product:iM.POSTHOG_PRODUCT}});try{await fetch(process.env.FAILPROOFAI_POSTHOG_HOST?`${process.env.FAILPROOFAI_POSTHOG_HOST}/capture/`:"https://us.i.posthog.com/capture/",{method:"POST",headers:{"Content-Type":"application/json"},body:n,signal:AbortSignal.timeout(5e3)})}catch{}}async function iH(e,t,i){if(!(0,iU.isTelemetryEnabled)())return;let n=iF(e,t,i);iL.add(n),n.finally(()=>iL.delete(n)),await n}var iq=e.i(10659);function iJ(e,t){let i=e.trim(),n="string"==typeof t?t.trim():"";return n?i?`${i}. ${n}`:n:i}function iG(e,t){if(!e?.policyParams)return;let i=e.policyParams[t];if(i)return i;let n=`${f}/`;if(t.startsWith(n))return e.policyParams[t.slice(n.length)]}async function iY(e,t,i,n){let r=t.tool_name,o=t.tool_input,s=function(e,t){let i=globalThis[m];i||g(i=new Map);let n=`${e}:${t??""}`,r=i.get(n);if(r)return r;let o=y().filter(i=>(!i.match.events||!(i.match.events.length>0)||!!i.match.events.includes(e))&&(!i.match.toolNames||!(i.match.toolNames.length>0)||!!t&&!!i.match.toolNames.includes(t))).sort((e,t)=>t.priority-e.priority);return i.set(n,o),o}(e,r);if(C(`evaluating ${s.length} policies for ${e}`),0===s.length)return{exitCode:0,stdout:"",stderr:"",policyName:null,reason:null,decision:"allow"};let a={eventType:e,payload:t,toolName:r,toolInput:o,session:i,cli:i?.cli},l=[],c=[];for(let t of s){let r,o,s=t.params,d=iG(n,t.name)??{};if(s){let e={};for(let[t,i]of Object.entries(s))e[t]=t in d?d[t]:i.default;r={...a,params:e}}else r={...a,params:d};try{o=await t.fn(r)}catch(r){let n=r instanceof Error?r.message:String(r);A(`policy "${t.name}" threw: ${n}`),t.name.startsWith(`${f}/`)&&iH((0,iq.getInstanceId)(),"policy_evaluation_error",{policy_name:t.name,event_type:e,cli:i?.cli??null,error_type:r instanceof Error?r.name:"unknown"});continue}if("deny"===o.decision){let s,a=iJ(o.reason??`Blocked by policy: ${t.name}`,iG(n,t.name)?.hint);C(`deny by "${t.name}": ${a}`),s=r.toolName?r.toolName:"UserPromptSubmit"===e?"prompt":"SessionStart"===e?"session start":"SessionEnd"===e?"session end":"Stop"===e?"stop":"operation";let l=`Blocked ${s} by failproofai because: ${a}, as per the policy configured by the user`;if(i?.cli==="cursor"){if("Stop"===e||"SubagentStop"===e)return{exitCode:0,stdout:JSON.stringify({followup_message:`MANDATORY ACTION REQUIRED from failproofai (policy: ${t.name}): ${a}
1
+ module.exports=[97610,e=>{"use strict";var t=e.i(89171),i=e.i(71809),n=e.i(50227),s=e.i(2157),r=e.i(12714),o=e.i(74533),a=e.i(60526);let l=[{name:"sanitize-jwt",description:"Stop Claude from reading JWTs in tool responses",displayTitle:"Redacted JWT tokens from tool output",impact:"Stops the agent from echoing auth tokens it saw in command output.",match:{events:["PostToolUse"]},defaultEnabled:!0,category:"Sanitize"},{name:"sanitize-api-keys",description:"Stop Claude from reading API keys (OpenAI, Anthropic, GitHub, AWS, Stripe, Google) in tool responses",displayTitle:"Redacted API keys from tool output",impact:"Catches OpenAI / Anthropic / GitHub / AWS / Stripe / Google keys before the model sees them.",match:{events:["PostToolUse"]},defaultEnabled:!0,category:"Sanitize",params:{additionalPatterns:{type:"pattern[]",description:"Additional API key patterns to scrub, each with { regex, label }",default:[]}}},{name:"sanitize-connection-strings",description:"Stop Claude from reading database connection strings with embedded credentials in tool responses",displayTitle:"Redacted database connection strings from tool output",impact:"Strips embedded DB credentials before they reach the model context.",match:{events:["PostToolUse"]},defaultEnabled:!0,category:"Sanitize"},{name:"sanitize-private-key-content",description:"Stop Claude from reading PEM private key content in tool responses",displayTitle:"Redacted PEM private keys from tool output",impact:"Prevents private key bodies from being echoed into chat context.",match:{events:["PostToolUse"]},defaultEnabled:!0,category:"Sanitize"},{name:"sanitize-bearer-tokens",displayTitle:"Redacted bearer tokens from tool output",impact:"Strips Authorization: Bearer values before they hit the model.",description:"Stop Claude from reading Authorization Bearer tokens in tool responses",match:{events:["PostToolUse"]},defaultEnabled:!0,category:"Sanitize"},{name:"protect-env-vars",displayTitle:"Tried to dump environment variables to chat",impact:"Env vars often contain secrets; blocking `env` / `printenv` keeps them out of the model context.",description:"Prevent commands that read environment variables",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!0,category:"Environment"},{name:"block-env-files",displayTitle:"Tried to read or write a .env file",impact:"`.env` files routinely contain API keys and DB credentials.",description:"Block reading/writing .env files",match:{events:["PreToolUse"]},defaultEnabled:!0,category:"Environment"},{name:"block-read-outside-cwd",displayTitle:"Tried to read files outside your project directory",impact:"Stops the agent from peeking at neighboring repos or your home directory.",description:"Block file reads outside the session working directory",match:{events:["PreToolUse"],toolNames:["Read","Glob","Grep","Bash"]},defaultEnabled:!1,category:"Environment",params:{allowPaths:{type:"string[]",description:"Absolute paths outside cwd that are allowed to be read",default:[]}}},{name:"block-sudo",displayTitle:"Tried to run a command with sudo",impact:"Sudo gives the agent root — blocked unless explicitly allow-listed.",description:"Block sudo commands",match:{events:["PreToolUse","PermissionRequest"],toolNames:["Bash"]},defaultEnabled:!0,category:"Dangerous Commands",params:{allowPatterns:{type:"string[]",description:"Sudo command patterns to allow, matched token-by-token (e.g. 'sudo systemctl status')",default:[]}}},{name:"block-curl-pipe-sh",displayTitle:"Tried to pipe a downloaded script straight to a shell",impact:"`curl ... | sh` runs unverified remote code on your machine.",description:"Block piping downloads to shell",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!0,category:"Dangerous Commands"},{name:"block-rm-rf",displayTitle:"Tried to recursively delete a system path",impact:"Catches catastrophic `rm -rf /` and Windows equivalents.",description:"Prevent catastrophic deletions",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Dangerous Commands",params:{allowPaths:{type:"string[]",description:"Paths that are allowed to be recursively deleted",default:[]}}},{name:"block-failproofai-commands",displayTitle:"Tried to disable, pause or modify failproofai itself",impact:"An agent that can pause or remove enforcement can switch off every other policy.",description:"Block failproofai CLI commands, self-pause and uninstallation",match:{events:["PreToolUse","PermissionRequest"],toolNames:["Bash","Write","Edit","NotebookEdit"]},defaultEnabled:!0,alwaysOn:!0,category:"Dangerous Commands"},{name:"block-kubectl",displayTitle:"Tried to run a Kubernetes command",impact:"kubectl can change live cluster state — gated unless allow-listed.",description:"Block kubectl commands (Kubernetes cluster mutations)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"kubectl command patterns to allow, matched token-by-token (e.g. 'kubectl get *', 'kubectl describe *')",default:[]}}},{name:"block-terraform",displayTitle:"Tried to run a Terraform/OpenTofu command",impact:"Terraform mutates real infrastructure — gated unless allow-listed.",description:"Block terraform and tofu (OpenTofu) commands",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"terraform/tofu command patterns to allow (e.g. 'terraform plan', 'terraform validate')",default:[]}}},{name:"block-aws-cli",displayTitle:"Tried to run an AWS CLI command",impact:"AWS CLI can spend money or break prod — gated.",description:"Block aws CLI commands",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"aws CLI command patterns to allow (e.g. 'aws s3 ls *', 'aws sts get-caller-identity')",default:[]}}},{name:"block-gcloud",displayTitle:"Tried to run a Google Cloud command",impact:"gcloud can spend money or break prod — gated.",description:"Block gcloud (Google Cloud) CLI commands",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"gcloud command patterns to allow (e.g. 'gcloud auth list', 'gcloud config list')",default:[]}}},{name:"block-az-cli",displayTitle:"Tried to run an Azure CLI command",impact:"az can spend money or break prod — gated.",description:"Block az (Azure) CLI commands",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"az CLI command patterns to allow (e.g. 'az account show', 'az group list')",default:[]}}},{name:"block-helm",displayTitle:"Tried to run a Helm command",impact:"Helm releases mutate cluster state — gated.",description:"Block helm commands",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"helm command patterns to allow (e.g. 'helm list', 'helm status *')",default:[]}}},{name:"block-gh-pipeline",displayTitle:"Tried to run a privileged GitHub CLI pipeline command",impact:"Catches `gh workflow run`, `gh pr merge`, `gh secret set`, etc.",description:"Block gh CLI pipeline-trigger subcommands (workflow run, run rerun/cancel, pr merge, release create/delete, cache delete, secret set/delete)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"gh pipeline command patterns to allow (e.g. specific scripted invocations); read-only gh subcommands like 'gh pr view' and 'gh run list' are not matched by this policy",default:[]}}},{name:"block-secrets-write",displayTitle:"Tried to write a secret-key file",impact:"Stops the agent from creating `.pem`, `id_rsa`, `credentials.json`, etc.",description:"Block writing secret key files",match:{events:["PreToolUse"],toolNames:["Write"]},defaultEnabled:!1,category:"Dangerous Commands",params:{additionalPatterns:{type:"string[]",description:"Additional filename patterns (substrings) to block",default:[]}}},{name:"block-push-master",displayTitle:"Tried to push directly to main/master",impact:"Direct pushes to a protected branch bypass review.",description:"Block pushing to main/master",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!0,category:"Git",params:{protectedBranches:{type:"string[]",description:"Branch names to protect from direct pushes",default:["main","master"]}}},{name:"block-force-push",displayTitle:"Tried to force-push",impact:"Force-pushes rewrite history and can clobber teammates' work.",description:"Prevent force-pushing to any branch",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Git"},{name:"block-work-on-main",displayTitle:"Tried to commit or merge on main/master",impact:"Work should land via PR — direct commits skip review.",description:"Block git commits and merges on main/master branch",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Git",params:{protectedBranches:{type:"string[]",description:"Branch names where commits/merges are blocked",default:["main","master"]}}},{name:"warn-git-amend",displayTitle:"Used git commit --amend",impact:"Amending after a push rewrites history that others may have pulled.",description:"Warns before amending git commits, which rewrites history",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Git"},{name:"warn-git-stash-drop",displayTitle:"Tried to drop or clear git stash",impact:"Stash deletions are permanent and silent.",description:"Warns before permanently deleting stashed changes",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Git"},{name:"warn-all-files-staged",displayTitle:"Staged all files with git add -A / .",impact:"Wide stages routinely catch generated files or secrets you didn't intend to commit.",description:"Warns before staging all working tree files with git add -A / . / --all",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Git"},{name:"warn-destructive-sql",displayTitle:"Ran destructive SQL (DROP / TRUNCATE / DELETE without WHERE)",impact:"Easy way to wipe a table by accident.",description:"Warn before executing destructive SQL (DROP/TRUNCATE/DELETE without WHERE) via database clients",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Database"},{name:"warn-schema-alteration",displayTitle:"Altered a database schema column",impact:"ALTER TABLE operations can lock tables and break readers.",description:"Warns before SQL schema changes (ALTER TABLE with column or rename operations)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Database"},{name:"warn-package-publish",displayTitle:"Tried to publish a package",impact:"Publishes are irreversible — `npm publish` / `cargo publish` shouldn't happen without intent.",description:"Warn before publishing packages to public registries (npm, PyPI, crates.io, RubyGems, etc.)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Packages & System"},{name:"warn-global-package-install",displayTitle:"Installed a package globally",impact:"`npm i -g`, `cargo install`, `pip --user` pollute your machine outside the project.",description:"Warns before installing packages globally (npm -g, cargo install, etc.)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Packages & System"},{name:"prefer-package-manager",displayTitle:"Used a non-preferred package manager",impact:"Mixing package managers creates lockfile churn for your team.",description:"Blocks non-preferred package managers and tells Claude to use an allowed one (e.g., uv instead of pip)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Packages & System",params:{allowed:{type:"string[]",description:"Allowed package manager names (e.g. ['uv', 'bun']). Any detected manager not in this list is blocked.",default:[]},blocked:{type:"string[]",description:"Additional manager names to block beyond the built-in list (e.g. ['pdm', 'pipx']).",default:[]}}},{name:"warn-large-file-write",displayTitle:"Wrote a file larger than the configured threshold",impact:"Catches accidentally large file writes (logs, binaries, model dumps).",description:"Warn before writing files larger than 1MB (configurable via thresholdKb param)",match:{events:["PreToolUse"],toolNames:["Write"]},defaultEnabled:!1,category:"Packages & System",params:{thresholdKb:{type:"number",description:"File size threshold in KB above which a warning is issued",default:1024}}},{name:"warn-background-process",displayTitle:"Started a long-lived background process",impact:"Catches `nohup` / `&` / `screen` / `tmux` / `disown` patterns that the agent often forgets to clean up.",description:"Warns before starting detached or background processes",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Packages & System"},{name:"warn-repeated-tool-calls",displayTitle:"Called the same tool 3+ times with identical arguments",impact:"Usually a sign of a stuck loop burning tokens.",description:"Warn when the same tool is called 3+ times with identical parameters",match:{events:["PreToolUse"]},defaultEnabled:!1,category:"AI Behavior"},{name:"require-commit-before-stop",displayTitle:"Stopped with uncommitted changes",impact:"Work not in a commit is invisible to teammates and easy to lose.",description:"Require all changes to be committed before Claude stops",match:{events:["Stop"]},defaultEnabled:!1,category:"Workflow"},{name:"require-push-before-stop",displayTitle:"Stopped with unpushed commits",impact:"Local-only commits won't trigger CI or be reviewable.",description:"Require all commits to be pushed to remote before Claude stops",match:{events:["Stop"]},defaultEnabled:!1,category:"Workflow",params:{remote:{type:"string",description:"Remote name to push to (default: origin)",default:"origin"},baseBranch:{type:"string",description:"Base branch to compare against (default: main)",default:"main"}}},{name:"require-pr-before-stop",displayTitle:"Stopped without a PR for the branch",impact:"Branches without PRs don't get reviewed.",description:"Require a pull request to exist for the current branch before Claude stops",match:{events:["Stop"]},defaultEnabled:!1,category:"Workflow",params:{baseBranch:{type:"string",description:"Base branch to compare against (default: main)",default:"main"}}},{name:"require-no-conflicts-before-stop",displayTitle:"Stopped with a branch that conflicts with main",impact:"Conflicting branches can't merge — surface them early.",description:"Require the current branch to merge cleanly with the base branch before Claude stops",match:{events:["Stop"]},defaultEnabled:!1,category:"Workflow",params:{baseBranch:{type:"string",description:"Base branch to check for conflicts against (default: main)",default:"main"}}},{name:"require-ci-green-before-stop",displayTitle:"Stopped with failing CI",impact:"Failing CI blocks deploy.",description:"Require CI checks to pass on the current HEAD commit before Claude stops (ignores stale runs on prior commits)",match:{events:["Stop"]},defaultEnabled:!1,category:"Workflow"}];function c(e){return e?{decision:"allow",reason:e}:{decision:"allow"}}function d(e){return{decision:"deny",reason:e}}function u(e){return{decision:"instruct",reason:e}}let p="__FAILPROOFAI_POLICY_REGISTRY__",m="__FAILPROOFAI_POLICY_INDEX_CACHE__",f="failproofai";function h(e){return e.includes("/")?e:`${f}/${e}`}function g(e){globalThis[m]=e}function y(){let e=globalThis;return e[p]||(e[p]=[]),e[p]}var b=e.i(97348);let w=function(e){let t=e.replaceAll("\\","/");for(let e of[".claude",".codex",".copilot",".cursor",".opencode",".pi",".gemini"]){let i=(0,n.join)((0,a.homedir)(),e).replaceAll("\\","/");if(t===i||t.startsWith(i+"/"))return!0}for(let e of[(0,n.join)(".config","opencode"),(0,n.join)(".local","share","opencode")]){let i=(0,n.join)((0,a.homedir)(),e).replaceAll("\\","/");if(t===i||t.startsWith(i+"/"))return!0}return!1},k=function(e){return!!(/[\\/]\.claude[\\/]settings(?:\.[^/\\]+)?\.json$/.test(e)||/[\\/]\.codex[\\/]hooks\.json$/.test(e)||/[\\/]\.copilot[\\/]hooks[\\/][^/\\]+\.json$/.test(e)||/[\\/]\.github[\\/]hooks[\\/][^/\\]+\.json$/.test(e)||/[\\/]\.cursor[\\/]hooks\.json$/.test(e)||/[\\/]\.opencode[\\/]opencode\.jsonc?$/.test(e)||/[\\/]\.opencode[\\/]plugins[\\/][^/\\]+\.(?:mjs|js|ts)$/.test(e)||/[\\/]\.config[\\/]opencode[\\/]opencode\.jsonc?$/.test(e)||/[\\/]\.config[\\/]opencode[\\/]config\.json$/.test(e)||/[\\/]\.config[\\/]opencode[\\/]plugins[\\/][^/\\]+\.(?:mjs|js|ts)$/.test(e)||/[\\/]\.pi[\\/](?:agent[\\/])?settings\.json$/.test(e)||/[\\/]\.pi[\\/](?:agent[\\/])?extensions[\\/]/.test(e)||/[\\/]\.gemini[\\/]settings\.json$/.test(e)||/[\\/]\.gemini[\\/]config[\\/]hooks\.json$/.test(e))};function N(e){return e.toolInput?.command??""}function v(e){return e.toolInput?.file_path??""}function S(e){return e.trim().split(/\s+/).map(e=>e.replace(/^['"]|['"]$/g,""))}let T=new Set(["&&","||","|",";"]),$=/[;&<>`$()\\]/,E=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/,P=[[/sk-ant-[A-Za-z0-9\-_]{20,}/,"Anthropic API key"],[/sk-proj-[A-Za-z0-9\-_]{20,}/,"OpenAI project API key"],[/sk-[A-Za-z0-9]{20,}/,"OpenAI API key"],[/ghp_[A-Za-z0-9]{36}/,"GitHub personal access token"],[/github_pat_[A-Za-z0-9_]{82}/,"GitHub fine-grained token"],[/AKIA[A-Z0-9]{16}/,"AWS access key ID"],[/sk_live_[A-Za-z0-9]{24,}/,"Stripe live secret key"],[/sk_test_[A-Za-z0-9]{24,}/,"Stripe test secret key"],[/AIza[0-9A-Za-z\-_]{35}/,"Google API key"]],O=/(?:postgresql|postgres|mysql|mongodb(?:\+srv)?|redis|amqps?|smtps?):\/\/[^@\s]+@/,A=/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----/,I=/Authorization:\s*Bearer\s+[A-Za-z0-9\-._~+/]{20,}/i;[...P];let C=/\b(?:psql|mysql|sqlite3|pgcli|clickhouse-client)\b/,x=/\b(?:DROP\s+(?:TABLE|DATABASE|SCHEMA)|TRUNCATE\b)/i,R=/\bDELETE\s+FROM\b/i,j=/\bWHERE\b/i,B=/\bALTER\s+TABLE\b[\s\S]*\b(?:DROP\s+COLUMN|ADD\s+COLUMN|RENAME\s+(?:COLUMN|TO)|MODIFY\s+COLUMN)\b/i,_=/(?:npm\s+publish|bun\s+publish|pnpm\s+publish|yarn\s+npm\s+publish|twine\s+upload|poetry\s+publish|cargo\s+publish|gem\s+push)\b/,M=/(?:^|\s|;|&&|\|\|)(?:env|printenv)(?:\s|$|;|&&|\|)/,D=/echo\s+.*\$\{?[A-Za-z_]/,U=/(?:^|\s|;|&&|\|\|)export\s+\w+/,W=/\$env:[A-Za-z_]/i,z=/(?:Get-ChildItem|dir|gci|ls)\s+Env:/i,L=/\[Environment\]::GetEnvironment/i,q=/echo\s+%[A-Za-z_]/i,H=/(?:^|[\\/])\.env(?:\.|$)/,J=/\.env(?:\b|\s|$|\.)/,F=/Start-Process\s+.*-Verb\s+RunAs/i,G=/(?:^|;|&&|\|\|)\s*runas\s/i,Y=/(?:curl|wget)\s.*\|\s*(?:sh|bash|zsh|dash|ksh|csh|tcsh|fish|ash)\b/,Z=/[;&|\n\r(){}`]+/,Q=new Set(["npx","bunx","pnpx","npm","pnpm","yarn","dlx","exec","run","eval","node","bun","deno","env","command","builtin","nohup","setsid","time","timeout","nice","stdbuf","xargs","sudo","doas","sh","bash","zsh","dash","ksh","fish","ash"]),K=/(?:^|\/)failproofai[^/]*$/,V=/failproofai\/(?:dist\/(?:cli|index)\.mjs|bin\/failproofai\.mjs)$/,X=/^(?:config|configure|setup)$/,ee=/^--pause(?:=|$)/,et=/^[A-Za-z_][A-Za-z0-9_]*=/,ei=/^\d+[a-z]*$/i;function en(e){let t=e.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,"$$$1"),i=null,n=new Set;for(let[,e,i]of t.matchAll(/(?:^|[\s;&|])([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|]+)/g)){let t=i.replace(/^["']|["']$/g,"");(K.test(t)||V.test(t))&&n.add(e)}let s=e=>{let t=/^\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?$/.exec(e);return!!t&&n.has(t[1])};for(let e of t.split(Z)){let t=e.split(/\s+/).filter(Boolean),n=0;for(;n<t.length;){let e=t[n];if(!(et.test(e)||e.startsWith("-")||e.startsWith(">")||e.startsWith("<")||ei.test(e)||Q.has(e.slice(e.lastIndexOf("/")+1))))break;n++}if(n>=t.length||!K.test(t[n])&&!V.test(t[n])&&!s(t[n]))continue;let r=t.slice(n+1),o=r.findIndex(e=>X.test(e));if(-1!==o&&r.slice(o+1).some(e=>ee.test(e)))return"pause";i="cli"}return i}let es=/(?:Invoke-WebRequest|iwr|Invoke-RestMethod|irm)\s+.*\|\s*(?:Invoke-Expression|iex)/i,er=/^-[a-zA-Z]*f[a-zA-Z]*$/,eo=["--force-with-lease","--force-if-includes"],ea=/\.(?:pem|key)$/,el=/id_rsa/,ec=/credentials/,ed=/git\s+(commit|merge|rebase|cherry-pick)\b/,eu=/\.failproofai(?:\/|\b)/,ep=new Set(["cat","bat","less","more","head","tail","nl","strings","xxd","od","jq","yq","diff","cmp","wc","sort","uniq","column","awk","cut","ls","dir","tree","stat","file","du","df","readlink","realpath","basename","dirname","pwd","test","find","grep","egrep","fgrep","rg","ag","ack","md5sum","sha1sum","sha256sum","shasum","cksum","cd","pushd","popd","cp","rsync","install","tee","sed","true","false",":","echo","printf","[","[[","]","]]","test","read","for","select","case","done","fi","esac"]),em=new Set(["do","then","else","elif","if","while","until","!"]),ef=/(?:^|[\s(])(?:while|until|for|select)\s/,eh=new Set(["cp","rsync","install"]),eg=new Set(["tee"]),ey=new Set(["uniq","xxd"]),eb={sort:["-o","--output"],tree:["-o","--output"],curl:["-o","--output","--output-dir","-D","--dump-header","--trace","--trace-ascii"]},ew=new Set(["-fprint","-fprint0","-fprintf","-fls"]),ek=new Set(["cat","bat","head","tail","nl","strings","xxd","od","jq","yq","wc","ls","stat","file","du","readlink","realpath","basename","dirname","grep","egrep","fgrep","rg","md5sum","sha1sum","sha256sum","shasum","cksum","echo","printf","true",":"]),eN=new Set(["clean","rm","restore","checkout","reset","stash"]),ev=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path"]),eS=new Set(["git","gh","glab","echo","printf","curl","code","open"]),eT=new Set(["-exec","-execdir","-ok","-okdir"]),e$=/\|\||&&|[;\n\r&]+/,eE=/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g,eP=[".failproofai","~/.failproofai","$HOME/.failproofai","${HOME}/.failproofai","/root/.failproofai","/home/u/.failproofai","/Users/u/.failproofai"],eO=[".config",".cache",".local",".git",".npm",".ssh",".bashrc","node_modules","dist","build","target","coverage","tmp","src","~/.config","~/.cache","$HOME/.config","${HOME}/.cache","/home/u/.config","/Users/u/.config","/root/.cache","/tmp/build","a","foo.txt","test-failures"];function eA(e){if(!eC.test(e))return!1;for(let t of function(e){let t=[e];for(let i=0;i<24;i++){let i=[],n=!1;for(let e of t){let t=function(e){let t=e.indexOf("{");if(-1===t)return null;let i=0,n=[],s="";for(let r=t;r<e.length;r++){let o=e[r];if("{"===o){if(1==++i)continue}else if("}"===o){if(0==--i)return n.push(s),{start:t,end:r,alternatives:n}}else if(","===o&&1===i){n.push(s),s="";continue}s+=o}return null}(e);if(!t){i.push(e);continue}for(let s of(n=!0,t.alternatives))i.push(e.slice(0,t.start)+s+e.slice(t.end+1))}if(!n)return i;if(i.length>4096)return[eI(e)];t=i}return t.map(eI)}(e))if(function(e){if(eu.test(e))return!0;let t=e.split("/");for(let e=1;e<=t.length;e++)if(function(e){let t;if(!eC.test(e))return!1;let i="^"+function e(t){let i="";for(let n=0;n<t.length;n++){let s=function(t,i){let n=t[i];if(!"?*+@!".includes(n)||"("!==t[i+1])return null;let s=[],r="",o=0,a=i+1;for(;a<t.length;a++){let e=t[a];if("("===e){if(1==++o)continue}else if(")"===e){if(0==--o){s.push(r);break}}else if("|"===e&&1===o){s.push(r),r="";continue}r+=e}if(a>=t.length)return null;if("!"===n)return{source:"[^/]*",end:a};let l=s.map(t=>e(t)).join("|");return{source:`(?:${l})${"?"===n?"?":"*"===n?"*":"+"===n?"+":""}`,end:a}}(t,n);if(s){i+=s.source,n=s.end;continue}let r=t[n];if("*"===r)i+="[^/]*";else if("?"===r)i+="[^/]";else if("["===r){let e=function(e,t){let i=t+1,n=!1;("!"===e[i]||"^"===e[i])&&(n=!0,i++);let s="";for("]"===e[i]&&(s+="]",i++);i<e.length&&"]"!==e[i];){let t="["===e[i]?e[i+1]:void 0;if(":"===t||"."===t||"="===t){let n=e.indexOf(`${t}]`,i+2);if(-1!==n){s+=e.slice(i,n+2),i=n+2;continue}}s+=e[i],i++}if(i>=e.length)return null;if(/\[[.=:]/.test(s))return{source:"[^/]",end:i};let r=s.replace(/[\\\]]/g,"\\$&");return 0===r.length?{source:"[^/]",end:i}:{source:`[${n?"^":""}${r}]`,end:i}}(t,n);if(!e){i+="\\[";continue}i+=e.source,n=e.end}else i+=r.replace(/[.+^${}()|\\\]]/g,"\\$&")}return i}(e);try{t=RegExp(i+"$")}catch{return!1}return!!eP.some(e=>t.test(e))&&!eO.some(e=>t.test(e))}(t.slice(0,e).join("/")))return!0;return!1}(t))return!0;return!1}function eI(e){let t="",i=0;for(let n of e){if("{"===n){0===i&&(t+="*"),i++;continue}if("}"===n){i>0&&i--;continue}0===i&&(t+=n)}return t}let eC=/[*?[{]|[@+!]\(/;function ex(e){let t=[];for(let i=0;i<e.length;i++){if("`"===e[i]){let n=e.indexOf("`",i+1);if(-1===n)break;t.push(e.slice(i+1,n)),i=n;continue}if("$"!==e[i]||"("!==e[i+1])continue;let n=1,s=i+2;for(;s<e.length&&n>0;s++)"("===e[s]?n++:")"===e[s]&&n--;0===n&&t.push(e.slice(i+2,s-1)),i=s-1}return t}let eR=/\d*>{1,2}\|?\s*("[^"]*"|'[^']*'|[^\s;&|<>]+)/g;function ej(e){return e.replace(/^[(){}'"]+|[(){}'"]+$/g,"")}function eB(e){let t=ej(e);return t.slice(t.lastIndexOf("/")+1)}function e_(e,t=0){if(0===t){let t=ex(e);for(let e=0;e<t.length&&e<64;e++){if(e_(t[e],1))return!0;t.push(...ex(t[e]))}}let i=[...e.matchAll(/(?:^|[\s;&|(])(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|)]+)/g)].map(([,e,t])=>[e,t.replace(/^["']|["']$/g,"")]),n=new Set;for(let e=0;e<i.length+1;e++){let e=n.size;for(let[e,t]of i)(eu.test(t)||[...t.matchAll(eE)].some(([,e])=>n.has(e)))&&n.add(e);if(n.size===e)break}let s=e=>{if(eu.test(e))return!0;for(let[,t]of e.matchAll(eE))if(n.has(t))return!0;return e.split(/\s+/).some(e=>{var t;let i;return i=(t=e.replace(/^['"]+|['"]+$/g,"")).replace(/^[()]+|[()]+$/g,""),eA(t)||i!==t&&eA(i)})},r=!1,o=0,a=null,l=!1;for(let t of e.split(e$)){if(!t.trim())continue;let e=t.split("|"),i=s(t)||r||l;if(i&&ef.test(t)&&(l=!0),/(?:^|\s)done(?:\s|$)/.test(t)&&(l=!1),i){for(let[,e]of t.matchAll(eR))if(s(e.replace(/^["']|["']$/g,"")))return!0}for(let t of e){o+=(t.match(/\(/g)??[]).length;let e=function(e){let t=e.trim().split(/\s+/).map(ej).filter(Boolean),i=0;for(;i<t.length;){let e=t[i];if(/^\d*(?:>{1,2}\|?|<{1,3})/.test(e)){i+=/^\d*(?:>{1,2}\|?|<{1,3})$/.test(e)?2:1;continue}if(!(et.test(e)||e.startsWith("-")||ei.test(e)||em.has(e)||Q.has(eB(e))))break;i++}return t.slice(i)}(t),n=e.length>0?eB(e[0]):"";if("cd"===n||"pushd"===n){let t=e.slice(1).find(e=>!e.startsWith("-"));a=(r=void 0!==t&&s(t))?o:null}else if("popd"===n)r=!1,a=null;else if(i&&e.length>0&&function(e,t){if(0===e.length)return!1;let i=eB(e[0]),n=e.slice(1);if("find"===i)return!!(n.some(e=>"-delete"===e)||n.some(e=>ew.has(e)))||n.some((e,t)=>eT.has(e)&&!ek.has(eB(n[t+1]??"")));if("sed"===i)return!!n.some(e=>e.startsWith("-i")||e.startsWith("--in-place"))||n.some((e,i)=>/(?:^|[;}/\s])w$/.test(e)&&t(n[i+1]??""))||n.some(e=>/(?:^|[;}/\s])w\s*\S*\.failproofai/.test(e));if("awk"===i||"gawk"===i||"mawk"===i)return n.some(e=>/system\s*\(|\|\s*["']|\|&/.test(e));if(eh.has(i)){if(n.includes("--remove-source-files")&&n.some(e=>t(e)))return!0;let e=n.findIndex(e=>"-t"===e||"--target-directory"===e);if(-1!==e&&t(n[e+1]??"")||n.some(e=>e.startsWith("--target-directory=")&&t(e)))return!0;let i=n.filter(e=>!e.startsWith("-")),s=i[i.length-1];return void 0!==s&&t(s)}if(eg.has(i))return n.some(e=>!e.startsWith("-")&&t(e));if(ey.has(i)){let e=n.filter(e=>!e.startsWith("-"));return e.length>1&&t(e[e.length-1])}if("git"===i){let e=function(e){for(let t=0;t<e.length;t++){let i=e[t];if(ev.has(i)){t++;continue}if(!i.startsWith("-"))return i}}(n);return void 0!==e&&eN.has(e)}return!!function(e,t,i){let n=eb[e];if(!n)return!1;for(let e=0;e<t.length;e++){let s=t[e];if(n.find(e=>e.startsWith("--")&&s.startsWith(`${e}=`))&&i(s))return!0;let r=/^-[A-Za-z]*[oD]$/.test(s)&&n.includes(`-${s[s.length-1]}`);if((n.includes(s)||r)&&i(t[e+1]??""))return!0}return!1}(i,n,t)||!(ep.has(i)||eS.has(i))}(e,s))return!0;o-=(t.match(/\)/g)??[]).length,null!==a&&o<a&&(r=!1,a=null)}}return!1}let eM=/(?:npm\s+(?:uninstall|remove|un|r)\s.*failproofai|bun\s+remove\s.*failproofai|yarn\s+global\s+remove\s+failproofai|pnpm\s+(?:remove|uninstall|un)\s.*failproofai)/,eD=/\bgit\s+commit\b.*--amend\b/,eU=/\bgit\s+stash\s+(?:drop|clear)\b/,eW=/\bgit\s+add\s+(?:-A\b|--all\b|\.(?:\s|$|;|&&|\|\|))/,ez=/\bnpm\s+(?:install|i)\b(?=.*(?:\s-g\b|--global\b))/,eL=/\byarn\s+global\s+add\b/,eq=/\bpnpm\s+(?:add|install|i)\b(?=.*(?:\s-g\b|--global\b))/,eH=/\bbun\s+(?:install|add)\b(?=.*(?:\s-g\b|--global\b))/,eJ=/\bcargo\s+install\b/,eF=/\bpip(?:3)?\s+install\b(?=.*(?:--user\b|--break-system-packages\b))/,eG={pip:[/\bpip\b/,/\bpip3\b/,/\bpython3?\s+-m\s+pip\b/],npm:[/\bnpm\b/,/\bnpx\b/],yarn:[/\byarn\b/],pnpm:[/\bpnpm\b/,/\bpnpx\b/],bun:[/\bbun\b/,/\bbunx\b/],uv:[/\buv\b/],poetry:[/\bpoetry\b/],pipenv:[/\bpipenv\b/],conda:[/\bconda\b/],cargo:[/\bcargo\b/]},eY=/\bnohup\s+\S/,eZ=/\bscreen\s+-[A-Za-z]*d[A-Za-z]*\b/,eQ=/\btmux\s+(?:new-session|new)\b[^|&;]*-d\b/,eK=/\bdisown\b/,eV=/(?<![&|])\s?&\s*(?:$|#|;)/,eX=/(?:^|[;\n]|&&|\|\|?|&)\s*kubectl(?:\s|$)/,e0=/(?:^|[;\n]|&&|\|\|?|&)\s*(?:terraform|tofu)(?:\s|$)/,e1=/(?:^|[;\n]|&&|\|\|?|&)\s*aws(?:\s|$)/,e3=/(?:^|[;\n]|&&|\|\|?|&)\s*gcloud(?:\s|$)/,e9=/(?:^|[;\n]|&&|\|\|?|&)\s*az(?:\s|$)/,e2=/(?:^|[;\n]|&&|\|\|?|&)\s*helm(?:\s|$)/,e4=/(?:^|[;\n]|&&|\|\|?|&)\s*gh\s+(?:workflow\s+(?:run|enable|disable)|run\s+(?:rerun|cancel)|pr\s+merge|release\s+(?:create|delete)|cache\s+delete|secret\s+(?:set|delete))\b/,e6=new Map;function e8(e){try{let t=function(e){try{return(0,s.statSync)((0,n.join)(e,".git","HEAD")).mtimeMs}catch{return null}}(e),i=e6.get(e);if(i&&null!==t&&i.headMtimeMs===t)return i.branch||null;let r=(0,o.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}).trim();return null!==t&&(e6.size>=500&&e6.clear(),e6.set(e,{branch:r,headMtimeMs:t})),r||null}catch{return null}}function e5(e,t){let i=S(e),n=S(t);return!(i.length<n.length||i.some(e=>T.has(e))||i.some(e=>$.test(e)))&&n.every((e,t)=>"*"===e||e===i[t])}let e7=/^-{1,2}c$/;function te(e){return e.split(/&&|\|\||[|;\n]/).map(e=>e.trim()).filter(e=>/^git\s+push\s/.test(e)).map(e=>e.replace(/^git\s+push\s+/,""))}let tt=/^(?:~[A-Za-z0-9_.-]*|\$HOME|\$\{HOME\})(?=$|\/)/,ti=/^(?:\/\S*\/)?rm$/,tn=/^(?:\/\S*\/)?find$/,ts=/^-(?:exec|execdir|ok|okdir)$/,tr=/^-(?:[HLP]|D|O\d*)$/,to=/^(?:-|\\?[(!])/,ta=["/tmp","/var/tmp"];function tl(e){let t=e.match(/^(?:~|\$HOME|\$\{HOME\})(?=$|\/)/);return t?(0,a.homedir)()+e.slice(t[0].length):e}function tc(e){return e.replace(/\/\*$/,"").replace(/\/+$/,"")}function td(e){let t=e.replace(/^['"]|['"]$/g,"");if(""===t)return!1;let i=t.match(tt);if(!i&&/^[$`]/.test(t))return!0;let n=i?t.slice(i[0].length):t.startsWith("/")?t:null;if(null===n)return!1;let s=tc(n).split("/").filter(Boolean);return!(!i&&ta.some(e=>`/${s.join("/")}`.startsWith(`${e}/`)))&&s.length<=2}function tu(e){let t=S(e),i=t.findIndex(e=>tn.test(e));if(i>=0){let e=t.slice(i+1),n=e.findIndex(e=>ts.test(e));if(e.includes("-delete")||n>=0&&ti.test(e[n+1]??"")){let t=0;for(;t<e.length&&tr.test(e[t]);)t+="-D"===e[t]?2:1;let i=e.slice(t),n=i.findIndex(e=>to.test(e));return n<0?i:i.slice(0,n)}}let n=t.findIndex(e=>ti.test(e));if(n>=0){let e=t.slice(n+1),i=e.filter(e=>/^-[^-]/.test(e)).join(""),s=e.filter(e=>/^--/.test(e)),r=/r/i.test(i)||s.some(e=>/^--recursive$/i.test(e)),o=/f/.test(i)||s.some(e=>/^--force$/i.test(e));if(r&&o)return e.filter(e=>!e.startsWith("-"))}return null}function tp(e){return e.split(/&&|\|\||[|;\n]/).map(e=>e.trim()).filter(e=>""!==e)}let tm=/(?:^|;|&&|\|\||\|)\s*(?:ls|find|cat|head|tail|less|more|wc|file|stat|tree|du)\s/;function tf(e,t,i){if("Bash"!==e.toolName)return c();let n=N(e);return!t.test(n)||(e.params?.allowPatterns??[]).some(e=>e5(n,e))?c():d(i)}let th=/\s*(?:&&|\|\||\||;)\s*/;function tg(e){return e.session?.permissionMode==="plan"}let ty={"sanitize-jwt":function(e){let t=JSON.stringify(e.payload);return E.test(t)?{decision:"deny",reason:"JWT token detected in tool output",message:"[REDACTED: JWT token removed by failproofai]"}:c()},"sanitize-api-keys":function(e){let t=JSON.stringify(e.payload);for(let[e,i]of P)if(e.test(t))return{decision:"deny",reason:`${i} detected in tool output`,message:`[REDACTED: ${i} removed by failproofai]`};for(let{regex:i,label:n}of e.params?.additionalPatterns??[])try{if(new RegExp(i).test(t))return{decision:"deny",reason:`${n} detected in tool output`,message:`[REDACTED: ${n} removed by failproofai]`}}catch{(0,b.hookLogWarn)(`additionalPatterns: invalid regex "${i}", skipping`)}return c()},"sanitize-connection-strings":function(e){let t=JSON.stringify(e.payload);return O.test(t)?{decision:"deny",reason:"Database connection string with credentials detected in tool output",message:"[REDACTED: connection string removed by failproofai]"}:c()},"sanitize-private-key-content":function(e){let t=JSON.stringify(e.payload);return A.test(t)?{decision:"deny",reason:"Private key content detected in tool output",message:"[REDACTED: private key content removed by failproofai]"}:c()},"sanitize-bearer-tokens":function(e){let t=JSON.stringify(e.payload);return I.test(t)?{decision:"deny",reason:"Bearer token detected in tool output",message:"[REDACTED: Bearer token removed by failproofai]"}:c()},"protect-env-vars":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return M.test(t)?d("Command reads environment variables"):D.test(t)?d("Command echoes environment variable"):U.test(t)?d("Command exports environment variable"):W.test(t)?d("Command reads environment variable via PowerShell"):z.test(t)?d("Command reads environment variables via PowerShell"):L.test(t)?d("Command reads environment variable via .NET"):q.test(t)?d("Command echoes environment variable via cmd"):c()},"block-env-files":function(e){let t=N(e),i=v(e);return i&&H.test(i)?d("Access to .env file blocked"):"Bash"===e.toolName&&J.test(t)?d("Command references .env file"):c()},"block-read-outside-cwd":function(e){let t=process.env.CLAUDE_PROJECT_DIR||e.session?.cwd;if(!t)return c();let i=e.params?.allowPaths??[];if("Bash"===e.toolName){let s=N(e);if(!tm.test(s))return c();let r=function(e){let t,i=[],s=/(?<![a-zA-Z0-9_.\-~\\*?:=])(?:~\/[^\s;|&"'()\[\]{}]*|~(?=\s|$|[;|&"'()\[\]{}])|\/[^\s;|&"'()\[\]{}]*)/g;function r(e){let t;for(s.lastIndex=0;null!==(t=s.exec(e));){let e=t[0];"~"===e?e=(0,a.homedir)():e.startsWith("~/")&&(e=(0,n.join)((0,a.homedir)(),e.slice(2))),i.push(e)}}let o=e.length,l=!1,c=!1;for(let t=0;t<e.length;t++){let i=e[t];if('"'!==i||c)if("'"!==i||l){if("|"===i&&!l&&!c){o=t;break}}else c=!c;else l=!l}let d=e.slice(0,o),u=/"([^"]*)"|'([^']*)'/g;for(;null!==(t=u.exec(d));){let e=t[1]??t[2]??"";/[*?\[\]^$+()\\]/.test(e)||r(e)}return r(e.replace(/"[^"]*"/g,e=>" ".repeat(e.length)).replace(/'[^']*'/g,e=>" ".repeat(e.length))),i}(s),o=t.endsWith("/")?t:t+"/";for(let e of r){let s=(0,n.resolve)(t,e);if(k(s))return d(`Reading agent settings file blocked: ${s}`);if(!w(s)&&"/dev/null"!==s&&s!==t&&!s.startsWith(o)){if(i.some(e=>s===e||s.startsWith(e.endsWith("/")?e:e+"/")))continue;return d(`Bash read outside project directory blocked: ${s}`)}}return c()}let s=v(e),r=e.toolInput?.path??"",o=s||r;if(!o)return c();let l=(0,n.resolve)(t,o);if(k(l))return d(`Reading agent settings file blocked: ${l}`);if(w(l)||"/dev/null"===l)return c();let u=t.endsWith("/")?t:t+"/";return l===t||l.startsWith(u)?c():i.some(e=>l===e||l.startsWith(e.endsWith("/")?e:e+"/"))?c():d(`Access outside project directory blocked: ${l}`)},"block-sudo":function(e){if("Bash"!==e.toolName)return c();let t=N(e).trimStart();return function e(t,i=0){for(let n of function(e){let t=[],i=[],n="",s=null,r=()=>{n&&i.push(n),n=""},o=()=>{r(),i.length&&t.push(i),i=[]};for(let t=0;t<e.length;t++){let i=e[t];if(s){if("\\"===i&&'"'===s&&t+1<e.length){n+=e[++t];continue}if(i===s){s=null;continue}n+=i;continue}if("\\"===i&&t+1<e.length){n+=e[++t];continue}if('"'===i||"'"===i){s=i;continue}if(/\s/.test(i)){r();continue}if(/[;&|\n\r(){}`]/.test(i)){o();continue}n+=i}return o(),t}(t)){let t=0;for(;t<n.length;){let s=n[t],r=s.slice(s.lastIndexOf("/")+1);if("sudo"===r||"doas"===r)return!0;if(!(et.test(s)||s.startsWith("-")||s.startsWith(">")||s.startsWith("<")||ei.test(s)||Q.has(r)))break;if(e7.test(s)&&i<3&&t+1<n.length&&e(n[t+1],i+1))return!0;t++}}return!1}(t)?(e.params?.allowPatterns??[]).some(e=>e5(t,e))?c():d("sudo commands are blocked"):F.test(t)?d("Elevated process launch is blocked"):G.test(t)?d("runas elevation is blocked"):c()},"block-curl-pipe-sh":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return Y.test(t)?d("Piping downloads to shell is blocked"):es.test(t)?d("Piping downloads to Invoke-Expression is blocked"):c()},"block-rm-rf":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return tp(t).some(e=>{let t=tu(e);return null!==t&&t.some(td)})?!function(e,t){if(0===t.length)return!1;let i=t.map(e=>tc(tl(e))||"/"),n=!1;for(let s of tp(e)){let e=tu(s);if(null!==e)for(let r of(n=!0,e)){let e=tc(tl(r))||"/";if(!i.some(t=>e===t||e.startsWith(t+"/"))&&!t.some(e=>{let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return RegExp(`${t}(?:[/"'\\s/*]|$)`).test(s)}))return!1}}return n}(t,e.params?.allowPaths??[])?d("Catastrophic deletion blocked"):c():/Remove-Item\s+.*-Recurse.*-Force.*(?:[A-Z]:\\(?:\s|$)|\\\*)/i.test(t)||/(?:rd|rmdir)\s+\/s\s+\/q\s+[A-Z]:\\/i.test(t)?d("Catastrophic deletion blocked"):c()},"block-failproofai-commands":function(e){if("Write"===e.toolName||"Edit"===e.toolName||"NotebookEdit"===e.toolName){let t=v(e)||(e.toolInput?.notebook_path??"");return eu.test(t)?d("Writing to failproofai's own state would switch enforcement off. If a policy is blocking legitimate work, say so and let the operator decide."):c()}if("Bash"!==e.toolName)return c();let t=N(e),i=t.replace(/\\\r?\n/g,"").replace(/\$'((?:[^'\\]|\\.)*)'/g,(e,t)=>t.replace(/\\(x[0-9A-Fa-f]{1,2}|u[0-9A-Fa-f]{1,4}|U[0-9A-Fa-f]{1,8}|[0-7]{1,3}|.)/g,(e,t)=>{try{if("x"===t[0])return String.fromCharCode(parseInt(t.slice(1),16));if("u"===t[0]||"U"===t[0])return String.fromCodePoint(parseInt(t.slice(1),16));if(/^[0-7]+$/.test(t))return String.fromCharCode(parseInt(t,8))}catch{return t}return({a:"\x07",b:"\b",e:"\x1b",f:"\f",n:"\n",r:"\r",t:" ",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"})[t]??t})).replace(/\\(.)/g,"$1").replace(/['"]/g,""),n=en(t)??en(i);return"pause"===n?d("Pausing failproofai enforcement is a human action, not an agent one. If a policy is blocking legitimate work, say so and let the operator decide."):"cli"===n?d("Running failproofai CLI commands is blocked"):eM.test(t)||eM.test(i)?d("Uninstalling failproofai is blocked"):e_(t)||e_(i)?d("Deleting, moving or overwriting failproofai's own state would switch enforcement off. If a policy is blocking legitimate work, say so and let the operator decide."):c()},"block-kubectl":function(e){return tf(e,eX,"kubectl commands are blocked")},"block-terraform":function(e){return tf(e,e0,"terraform/tofu commands are blocked")},"block-aws-cli":function(e){return tf(e,e1,"aws CLI commands are blocked")},"block-gcloud":function(e){return tf(e,e3,"gcloud commands are blocked")},"block-az-cli":function(e){return tf(e,e9,"az (Azure) CLI commands are blocked")},"block-helm":function(e){return tf(e,e2,"helm commands are blocked")},"block-gh-pipeline":function(e){return tf(e,e4,"gh pipeline-trigger commands are blocked")},"block-secrets-write":function(e){if("Write"!==e.toolName)return c();let t=v(e);if(ea.test(t)||el.test(t)||ec.test(t))return d("Writing secret key files is blocked");for(let i of e.params?.additionalPatterns??[])if(t.includes(i))return d(`Writing blocked file pattern: ${i}`);return c()},"block-push-master":function(e){if("Bash"!==e.toolName)return c();let t=e.params?.protectedBranches??["main","master"];if(0===t.length)return c();let i=te(N(e)),n=RegExp(`\\b(?:${t.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")})\\b`);return i.some(e=>n.test(e))?d(`Pushing to ${t.join("/")} is blocked`):c()},"block-force-push":function(e){if("Bash"!==e.toolName)return c();for(let t of te(N(e))){let e=!1;for(let i of t.split(/\s+/)){if("--"===i){e=!0;continue}if(!e&&function(e){return"--force"===e||!eo.some(t=>e.startsWith(t))&&(!!e.startsWith("--force")||er.test(e))}(i))return d("Force-pushing is blocked")}}return c()},"block-work-on-main":function(e){if("Bash"!==e.toolName)return c();let t=N(e).match(ed);if(!t)return c();let i=e.session?.cwd;if(!i)return c();let n=e8(i);return n&&(e.params?.protectedBranches??["main","master"]).includes(n)?d(`Git ${t[1]} on ${n} is blocked. Create a feature branch first.`):c()},"warn-git-amend":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return eD.test(t)?u("STOP: This command amends the last commit, which rewrites git history. If this commit has already been pushed to a shared branch, this will cause divergence for other contributors. Confirm with the user before executing."):c()},"warn-git-stash-drop":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return eU.test(t)?u("STOP: This command permanently deletes stashed changes (git stash drop/clear). Stash entries cannot be recovered after deletion. Confirm with the user before executing."):c()},"warn-all-files-staged":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return eW.test(t)?u("STOP: This command stages all files in the working tree (git add -A / --all / .). This may inadvertently include build artifacts, generated files, or sensitive files not covered by .gitignore. Confirm with the user before executing."):c()},"warn-destructive-sql":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return C.test(t)&&(x.test(t)||R.test(t)&&!j.test(t))?u("STOP: This command contains destructive SQL (DROP/TRUNCATE/DELETE). Confirm with the user before executing."):c()},"warn-schema-alteration":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return C.test(t)&&B.test(t)?u("STOP: This command contains a schema-altering SQL statement (ALTER TABLE with column or rename operation). Schema changes on production databases are irreversible or disruptive. Confirm with the user before executing."):c()},"warn-package-publish":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return _.test(t)?u("STOP: This command publishes a package to a public registry. Confirm with the user that this is intentional."):c()},"warn-global-package-install":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return ez.test(t)||eL.test(t)||eq.test(t)||eH.test(t)||eJ.test(t)||eF.test(t)?u("STOP: This command installs a package globally, which modifies the system-wide environment outside the project. This can conflict with other projects or system tools. Confirm with the user before executing."):c()},"prefer-package-manager":function(e){if("Bash"!==e.toolName)return c();let t=N(e);if(!t)return c();let i=e.params?.allowed??[];if(0===i.length)return c();let n=new Set(i.map(e=>e.toLowerCase())),s=e.params?.blocked??[],r=i.join(", ");for(let e of t.split(th)){let t=e.trim();if(!t)continue;let i=!1;for(let e of n){let n=eG[e];if(n){for(let e of n)if(e.test(t)){i=!0;break}if(i)break}}if(!i){for(let[e,i]of Object.entries(eG))if(!n.has(e)){for(let n of i)if(n.test(t))return d(`"${e}" is not an allowed package manager. Allowed package managers for this project: ${r}. Rewrite this command using an allowed package manager.`)}for(let e of s){let i=e.toLowerCase();if(!n.has(i)&&RegExp(`\\b${i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`).test(t))return d(`"${i}" is not an allowed package manager. Allowed package managers for this project: ${r}. Rewrite this command using an allowed package manager.`)}}}return c()},"warn-large-file-write":function(e){if("Write"!==e.toolName)return c();let t=e.toolInput?.content;if("string"!=typeof t)return c();let i=e.params?.thresholdKb??1024;return t.length>1024*i?u(`STOP: You are writing a file larger than ${i}KB (${Math.round(t.length/1024)}KB). This is unusually large. Confirm this is intentional before proceeding.`):c()},"warn-background-process":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return eY.test(t)||eZ.test(t)||eQ.test(t)||eK.test(t)||eV.test(t)?u("STOP: This command starts a background or detached process (nohup, screen -d, tmux -d, or trailing &). Background processes persist after Claude's session and may be difficult to track or stop. Confirm with the user before executing."):c()},"warn-repeated-tool-calls":async function e(e){let t=e.session?.transcriptPath;if(!t||!e.toolName||!e.toolInput)return c();let i=`${t}.tool-calls.json`,n=JSON.stringify({tool:e.toolName,input:e.toolInput}),s={};try{let e=await (0,r.readFile)(i,"utf8");s=JSON.parse(e)}catch{}let o=s[n]??0;if(o>=3)return u(`STOP: You have already called ${e.toolName} ${o} times with identical parameters. This is wasteful and unproductive. Do NOT repeat this call — use a different approach or ask the user for clarification.`);s[n]=o+1;try{let e=JSON.stringify(s);e.length<=65536&&await (0,r.writeFile)(i,e,"utf8")}catch{}return c()},"require-commit-before-stop":function(e){if(tg(e))return c("Plan mode — no changes made, skipping commit check.");let t=e.session?.cwd;if(!t)return c("No working directory available, skipping commit check.");try{if((0,o.execSync)("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().length>0)return d("You have uncommitted changes in the working directory. Commit all changes now.");return c("All changes are committed.")}catch{return c("Not a git repository, skipping commit check.")}},"require-push-before-stop":function(e){if(tg(e))return c("Plan mode — no changes made, skipping push check.");let t=e.session?.cwd;if(!t)return c("No working directory available, skipping push check.");try{if(!(0,o.execSync)("git remote",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}).trim())return c("No git remote configured, skipping push check.");let i=e.params?.remote??"origin",n=e8(t);if(!n||"HEAD"===n)return c("Detached HEAD, skipping push check.");let s=e.params?.baseBranch??"main";if(n===s)return c(`On base branch "${s}", skipping push check.`);try{if(!(0,o.execFileSync)("git",["log",`${i}/${s}..HEAD`,"--oneline"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return c(`No commits ahead of ${i}/${s}, skipping push check.`);if(!(0,o.execFileSync)("git",["diff","--stat",`${i}/${s}`,"HEAD"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return c(`No file changes compared to ${i}/${s}, skipping push check.`)}catch{}let r=!1;try{(0,o.execFileSync)("git",["rev-parse","--verify",`${i}/${n}`],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}),r=!0}catch{}if(!r)return d(`Branch "${n}" has not been pushed to remote "${i}". Run now: git push -u ${i} ${n}`);let a=(0,o.execFileSync)("git",["log",`${i}/${n}..HEAD`,"--oneline"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim();if(a.length>0){let e=a.split("\n").length;return d(`You have ${e} unpushed commit${e>1?"s":""} on branch "${n}". Run now: git push`)}return c(`All commits pushed to "${i}".`)}catch{return c("Could not check push status, skipping.")}},"require-pr-before-stop":function(e){if(tg(e))return c("Plan mode — no changes made, skipping PR check.");let t=e.session?.cwd;if(!t)return c("No working directory available, skipping PR check.");try{let i;try{(0,o.execSync)("gh --version",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3})}catch{return c("GitHub CLI (gh) not installed, skipping PR check.")}let n=e8(t);if(!n||"HEAD"===n)return c("Detached HEAD, skipping PR check.");let s=e.params?.baseBranch??"main";if(n===s)return c(`On base branch "${s}", skipping PR check.`);try{if(!(0,o.execFileSync)("git",["log",`origin/${s}..HEAD`,"--oneline"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return c(`No commits ahead of origin/${s}, skipping PR check.`);if(!(0,o.execFileSync)("git",["diff","--stat",`origin/${s}`,"HEAD"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return c(`No file changes compared to origin/${s}, skipping PR check.`)}catch{}try{i=(0,o.execSync)("gh pr view --json number,url,state",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim()}catch{return d(`No pull request found for branch "${n}". Run now: gh pr create`)}let r=JSON.parse(i);if("OPEN"===r.state)return c(`PR #${r.number} exists: ${r.url}`);if("MERGED"===r.state)return c(`PR #${r.number} was merged: ${r.url}. Switch off this branch (e.g. 'git checkout ${s} && git pull') before stopping again.`);return d(`Pull request for branch "${n}" is ${r.state.toLowerCase()}. Run now: gh pr create`)}catch{return c("Could not check PR status, skipping.")}},"require-no-conflicts-before-stop":function(e){let t,i;if(tg(e))return c("Plan mode — no changes made, skipping conflict check.");let n=e.session?.cwd;if(!n)return c("No working directory available, skipping conflict check.");let s=e8(n);if(!s||"HEAD"===s)return c("Detached HEAD, skipping conflict check.");let r=e.params?.baseBranch??"main";if(s===r)return c(`On base branch "${r}", skipping conflict check.`);try{(0,o.execSync)("gh --version",{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3})}catch{return c("gh CLI not installed, skipping conflict check.")}try{t=(0,o.execSync)("gh pr view --json mergeable,number,url,state",{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim()}catch{return c("No pull request found for branch, skipping conflict check.")}try{i=JSON.parse(t)}catch{return c("Could not parse gh pr view output, skipping conflict check.")}if("OPEN"!==i.state)return c(`PR #${i.number} is ${i.state.toLowerCase()}; skipping conflict check.`);try{(0,o.execFileSync)("git",["rev-parse","--verify",`origin/${r}`],{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}),(0,o.execFileSync)("git",["log",`origin/${r}..HEAD`,"--oneline"],{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim()&&(0,o.execFileSync)("git",["merge-tree","--write-tree","--name-only",`origin/${r}`,"HEAD"],{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:1e4})}catch(e){if(1===e.status){let t=("string"==typeof e.stdout?e.stdout:e.stdout?.toString("utf8")??"").trim().split("\n"),i=[];for(let e=1;e<t.length;e++){let n=t[e];if(""===n)break;i.push(n)}let n=i.length?i.join(", "):"one or more files";return d(`Branch "${s}" has merge conflicts with ${r} in: ${n}. Rebase or merge origin/${r} now and resolve the conflicts.`)}}return"CONFLICTING"===i.mergeable?d(`PR #${i.number} has merge conflicts per GitHub (${i.url}). Rebase or merge origin/${r} now and resolve the conflicts.`):"UNKNOWN"===i.mergeable?d(`GitHub is still computing mergeability for PR #${i.number} (${i.url}). Wait ~10 seconds, then re-check with \`gh pr view --json mergeable\` before attempting to stop again.`):c(`PR #${i.number} merges cleanly per GitHub.`)},"require-ci-green-before-stop":function(e){if(tg(e))return c("Plan mode — no changes made, skipping CI check.");let t=e.session?.cwd;if(!t)return c("No working directory available, skipping CI check.");try{try{(0,o.execSync)("gh --version",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3})}catch{return c("GitHub CLI (gh) not installed, skipping CI check.")}let e=e8(t);if(!e||"HEAD"===e)return c("Detached HEAD, skipping CI check.");let i=function(e){try{return(0,o.execSync)("git rev-parse HEAD",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}).trim()||null}catch{return null}}(t),n=[];try{let s=(0,o.execFileSync)("gh",["run","list","--branch",e,"--limit","20","--json","status,conclusion,name,headSha"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim();if(s&&"[]"!==s){let e=JSON.parse(s),t=i?e.filter(e=>e.headSha===i):e,r=new Set;n=t.filter(e=>!r.has(e.name)&&(r.add(e.name),!0))}}catch{}let s=[],r=[];i&&(s=function(e,t){try{let i=(0,o.execFileSync)("gh",["api",`repos/{owner}/{repo}/commits/${t}/check-runs`,"--jq",'.check_runs | map(select(.app.slug != "github-actions")) | map({name: .name, status: .status, conclusion: (.conclusion // "")})'],{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim();if(!i||"[]"===i)return[];return JSON.parse(i)}catch{return[]}}(t,i),r=function(e,t){try{let i=(0,o.execFileSync)("gh",["api",`repos/{owner}/{repo}/commits/${t}/statuses`,"--jq","map({name: .context, state: .state}) | unique_by(.name)"],{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim();if(!i||"[]"===i)return[];return JSON.parse(i).map(e=>({name:e.name,status:"pending"===e.state?"in_progress":"completed",conclusion:"pending"===e.state?"":"success"===e.state?"success":"failure"}))}catch{return[]}}(t,i));let a=[...n,...s,...r];if(0===a.length)return c(`No CI runs found for branch "${e}".`);let l=a.filter(e=>"completed"===e.status&&"success"!==e.conclusion&&"skipped"!==e.conclusion&&"cancelled"!==e.conclusion&&"neutral"!==e.conclusion);if(l.length>0){let t=l.map(e=>`"${e.name}"`).join(", ");return d(`CI checks are failing on branch "${e}": ${t}. Fix the failing checks now.`)}let u=a.filter(e=>"in_progress"===e.status||"queued"===e.status||"waiting"===e.status);if(u.length>0){let t=u.map(e=>`"${e.name}"`).join(", ");return d(`CI checks are still running on branch "${e}": ${t}. Wait for all checks to complete, then verify they pass.`)}return c(`All CI checks passed on branch "${e}".`)}catch{return c("Could not check CI status, skipping.")}}},tb=new Set(Object.keys(ty)),tw=l.filter(e=>!tb.has(e.name)).map(e=>e.name);if(tw.length>0)throw Error(`failproofai: builtin policies missing an implementation: ${tw.join(", ")}`);let tk=new Set(l.map(e=>e.name)),tN=[...tb].filter(e=>!tk.has(e));if(tN.length>0)throw Error(`failproofai: policy implementations with no catalog entry: ${tN.join(", ")}`);let tv=l.map(e=>({...e,fn:ty[e.name]}));var tS=e.i(73136),tT=e.i(52306),t$=e.i(38441),tE=e.i(81580);let tP=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;var tO=e.i(54214);function tA(e,t){let i=[];for(let s of e)if("assistant"===s.type)for(let e of s.message.content){var n;let r;if("tool_use"!==e.type)continue;let o=e.name,a=(n=t.cli,(o?"copilot"===n?t$.COPILOT_TOOL_MAP[o]??o:"cursor"===n?t$.CURSOR_TOOL_MAP[o]??o:"codex"===n?t$.CODEX_TOOL_MAP[o]??o:"opencode"===n?t$.OPENCODE_TOOL_MAP[o]??o:"pi"===n?t$.PI_TOOL_MAP[o]??o:"hermes"===n?t$.HERMES_TOOL_MAP[o]??o:"openclaw"===n?t$.OPENCLAW_TOOL_MAP[o]??o:"factory"===n?t$.FACTORY_TOOL_MAP[o]??o:"devin"===n?t$.DEVIN_TOOL_MAP[o]??o:"antigravity"===n?t$.ANTIGRAVITY_TOOL_MAP[o]??o:"goose"===n?t$.GOOSE_TOOL_MAP[o]??o:o:o)??o),l=function(e,t,i){let n;if(!e||!t||"object"!=typeof t||Array.isArray(t)||("copilot"===i?n=t$.COPILOT_TOOL_INPUT_MAP[e]:"opencode"===i?n=t$.OPENCODE_TOOL_INPUT_MAP[e]:"pi"===i?n=t$.PI_TOOL_INPUT_MAP[e]:"hermes"===i?n=t$.HERMES_TOOL_INPUT_MAP[e]:"openclaw"===i?n=t$.OPENCLAW_TOOL_INPUT_MAP[e]:"antigravity"===i?n=t$.ANTIGRAVITY_TOOL_INPUT_MAP[e]:"goose"===i&&(n=t$.GOOSE_TOOL_INPUT_MAP[e]),!n))return t;let s={};for(let[e,i]of Object.entries(t))s[n[e]??e]=i;return s}(a,e.input,t.cli);e.result?.content&&(r=function(e){let t=Buffer.from(e,"utf-8");if(t.byteLength<=65536)return e;let i=65536;for(;i>0&&(192&t[i])==128;)i--;return t.subarray(0,i).toString("utf-8")}(e.result.content)),i.push({cli:t.cli,sessionId:t.sessionId,transcriptPath:t.transcriptPath,cwd:t.cwd,timestamp:s.timestamp,toolName:a,rawToolName:o,toolInput:l??{},toolResultText:r})}return i}async function tI(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,r=[];for(let e of function(){let e,t=(0,tE.getClaudeProjectsPath)();try{e=(0,s.readdirSync)(t,{withFileTypes:!0})}catch{return[]}return e.filter(e=>e.isDirectory()).map(e=>({name:e.name,cwd:(0,tE.decodeFolderName)(e.name),path:(0,n.join)(t,e.name)}))}()){let o;if(!t||t.has(e.cwd)){try{o=function(e){let t,i=[];try{t=(0,s.readdirSync)(e.path,{withFileTypes:!0})}catch{return i}for(let r of t)if(r.isFile()&&r.name.endsWith(".jsonl")){let t=r.name.slice(0,-6);if(!tP.test(t))continue;let o=(0,n.join)(e.path,r.name);try{let n=(0,s.statSync)(o);i.push({projectName:e.name,cwd:e.cwd,sessionId:t,transcriptPath:o,mtimeMs:n.mtimeMs,sizeBytes:n.size,isSubagent:!1})}catch{}}else if(r.isDirectory()&&tP.test(r.name)){let t,o=(0,n.join)(e.path,r.name,"subagents");if(!(0,s.existsSync)(o))continue;try{t=(0,s.readdirSync)(o,{withFileTypes:!0})}catch{continue}for(let r of t){if(!r.isFile()||!r.name.endsWith(".jsonl"))continue;let t=r.name.slice(0,-6),a=(0,n.join)(o,r.name);try{let n=(0,s.statSync)(a);i.push({projectName:e.name,cwd:e.cwd,sessionId:t,transcriptPath:a,mtimeMs:n.mtimeMs,sizeBytes:n.size,isSubagent:!0})}catch{}}}return i}(e)}catch{continue}for(let t of o)t.mtimeMs<i||r.push({cli:"claude",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.transcriptPath,mtimeMs:t.mtimeMs,sizeBytes:t.sizeBytes})}}return r}async function tC(e){let t,i;try{t=await (0,r.readFile)(e.transcriptPath,"utf-8")}catch{return[]}try{i=await (0,tO.parseLogContent)(t,"session")}catch{return[]}let n="";for(let e of t.split("\n",50))if(e.trim())try{let t=JSON.parse(e);if("string"==typeof t.cwd&&t.cwd.length>0){n=t.cwd;break}}catch{}return tA(i,{cli:"claude",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:n})}async function tx(e,t){let i,n;if(!Number.isFinite(t)||t<0)return null;let s=null;try{s=await (0,r.open)(e.transcriptPath,"r");let{size:n}=await s.stat();if(t>n)return null;if(t===n)return{events:[],bytesConsumed:t};let o=Buffer.alloc(n-t);await s.read(o,0,o.length,t),i=o.toString("utf-8")}catch{return null}finally{if(s)try{await s.close()}catch{}}let o=i.lastIndexOf("\n"),a=-1===o?"":i.slice(0,o+1),l=i.slice(o+1),c=l.trim().length>0&&(()=>{try{return JSON.parse(l),!0}catch{return!1}})()?a+l:a;if(0===c.length)return{events:[],bytesConsumed:t};let d=t+Buffer.byteLength(c,"utf-8");try{n=await (0,tO.parseLogContent)(c,"session")}catch{return null}let u="";for(let e of c.split("\n",50))if(e.trim())try{let t=JSON.parse(e);if("string"==typeof t.cwd&&t.cwd.length>0){u=t.cwd;break}}catch{}return{events:tA(n,{cli:"claude",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:u}),bytesConsumed:d,cwd:u||void 0}}var tR=e.i(36203),tj=e.i(57232);async function tB(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tR.getCodexProjects)())){let{cwd:r,sessions:o}=await (0,tR.getCodexSessionsByEncodedName)(e.name),a=r??"";if(!t||t.has(a))for(let t of o){let r=t.lastModified.getTime();if(r<i)continue;let o=0;try{o=(0,s.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"codex",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:r,sizeBytes:o})}}return n}async function t_(e){let t=await (0,tj.getCodexSessionLog)(e.sessionId);return t?tA(t.entries,{cli:"codex",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tM=e.i(55851),tD=e.i(78166);async function tU(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tM.getCopilotProjects)())){let{cwd:r,sessions:o}=await (0,tM.getCopilotSessionsByEncodedName)(e.name),a=r??"";if(!t||t.has(a))for(let t of o){let r=t.lastModified.getTime();if(r<i)continue;let o=0;try{o=(0,s.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"copilot",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:r,sizeBytes:o})}}return n}async function tW(e){let t=await (0,tD.getCopilotSessionLog)(e.sessionId);return t?tA(t.entries,{cli:"copilot",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tz=e.i(46413),tL=e.i(72094);async function tq(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tz.getCursorProjects)())){let{cwd:r,sessions:o}=await (0,tz.getCursorSessionsByEncodedName)(e.name),a=r??"";if(!t||t.has(a))for(let t of o){let r=t.lastModified.getTime();if(r<i)continue;let o=0;try{o=(0,s.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"cursor",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:r,sizeBytes:o})}}return n}async function tH(e){let t=await (0,tL.getCursorSessionLog)(e.sessionId);return t?tA(t.entries,{cli:"cursor",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tJ=e.i(35435),tF=e.i(99440);async function tG(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tJ.getOpenCodeProjects)())){let{cwd:s,sessions:r}=await (0,tJ.getOpenCodeSessionsByEncodedName)(e.name),o=s??"";if(!t||t.has(o))for(let t of r){let s=t.lastModified.getTime();!(s<i)&&t.sessionId&&n.push({cli:"opencode",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:s,sizeBytes:0})}}return n}async function tY(e){let t=await (0,tF.getOpenCodeSessionLog)(e.sessionId);return t?tA(t.entries,{cli:"opencode",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tZ=e.i(19791),tQ=e.i(85116);async function tK(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tZ.getPiProjects)())){let{cwd:r,sessions:o}=await (0,tZ.getPiSessionsByEncodedName)(e.name),a=r??"";if(!t||t.has(a))for(let t of o){let r=t.lastModified.getTime();if(r<i)continue;let o=0;try{o=(0,s.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"pi",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:r,sizeBytes:o})}}return n}async function tV(e){let t=await (0,tQ.getPiSessionLog)(e.sessionId);return t?tA(t.entries,{cli:"pi",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tX=e.i(64828),t0=e.i(28898),t1=e.i(3605);async function t3(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=await (0,tX.getHermesSessions)(),s=[];for(let e of n)!(e.mtimeMs<i)&&(!(e.messageCount<=0)||e.hasMessages)&&(!t||e.cwd&&t.has(e.cwd))&&s.push({cli:"hermes",projectName:e.cwd?(0,tE.encodeFolderName)(e.cwd):e.source?(0,t0.hermesProjectPath)(e.profile,e.source):`hermes:${e.profile}`,sessionId:e.sessionId,transcriptPath:`hermes://${e.sessionId}`,mtimeMs:e.mtimeMs,sizeBytes:e.messageCount});return s}async function t9(e){let t=await (0,t1.getHermesSessionLog)(e.sessionId);return t?tA(t.entries,{cli:"hermes",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var t2=e.i(90624),t4=e.i(64199);async function t6(e={}){if(e.projects&&e.projects.length>0)return[];let t=e.sinceMs??0,i=[];for(let e of(await (0,t2.getOpenClawSessions)()))e.mtimeMs<t||i.push({cli:"openclaw",projectName:(0,t2.openClawProjectPath)(e.agentId,e.channel),sessionId:e.sessionId,transcriptPath:e.transcriptPath,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes});return i}async function t8(e){let t=await (0,t4.getOpenClawSessionLog)(e.sessionId);return t?tA(t.entries,{cli:"openclaw",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var t5=e.i(28246);async function t7(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(0,t5.listFactoryTranscripts)())!(e.mtimeMs<i)&&(!t||t.has(e.cwd))&&n.push({cli:"factory",projectName:e.projectName,sessionId:e.sessionId,transcriptPath:e.transcriptPath,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes});return n}async function ie(e){let t;try{t=await (0,r.readFile)(e.transcriptPath,"utf-8")}catch{return[]}let i=(0,tO.parseRawLines)(t,"session"),n=(0,t5.factoryLinesToLogEntries)(i,"session"),s="";for(let e of i)if(e&&"object"==typeof e&&"session_start"===e.type){let t=e.cwd;if("string"==typeof t&&t.length>0){s=t;break}}return tA(n,{cli:"factory",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:s})}var it=e.i(93114),ii=e.i(30441);async function is(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[],s=await (0,ii.getAntigravityIndex)();for(let e of(0,it.listAntigravityTranscripts)()){if(e.mtimeMs<i)continue;let r=s.get(e.conversationId)?.cwd;(!t||r&&t.has(r))&&n.push({cli:"antigravity",projectName:r?(0,tE.encodeFolderName)(r):"antigravity",sessionId:e.conversationId,transcriptPath:e.transcriptPath,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes})}return n}async function ir(e){let t;try{t=await (0,r.readFile)(e.transcriptPath,"utf-8")}catch{return[]}let i=(0,tO.parseRawLines)(t,"session"),n=(0,it.antigravityLinesToLogEntries)(i,"session"),s="";for(let e of i){if(!e||"object"!=typeof e)continue;let t=e.tool_calls;if(Array.isArray(t)){for(let e of t){let t=e&&"object"==typeof e?e.args:void 0,i=t&&"object"==typeof t?t.Cwd:void 0;if("string"==typeof i&&i.length>0){s=i;break}}if(s)break}}return tA(n,{cli:"antigravity",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:s})}var io=e.i(79364),ia=e.i(40375);async function il(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=await (0,io.getDevinSessions)(),s=[];for(let e of n)!(e.mtimeMs<i)&&(!t||e.cwd&&t.has(e.cwd))&&s.push({cli:"devin",projectName:e.projectName,sessionId:e.sessionId,transcriptPath:`devin-db://${e.sessionId}`,mtimeMs:e.mtimeMs,sizeBytes:0});return s}async function ic(e){let t=await (0,ia.getDevinSessionLog)(e.sessionId);return t?tA(t.entries,{cli:"devin",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var id=e.i(69164),iu=e.i(36618);let ip={claude:{cli:"claude",listTranscripts:tI,streamEvents:tC,streamEventsFrom:tx},codex:{cli:"codex",listTranscripts:tB,streamEvents:t_},copilot:{cli:"copilot",listTranscripts:tU,streamEvents:tW},cursor:{cli:"cursor",listTranscripts:tq,streamEvents:tH},opencode:{cli:"opencode",listTranscripts:tG,streamEvents:tY},pi:{cli:"pi",listTranscripts:tK,streamEvents:tV},hermes:{cli:"hermes",listTranscripts:t3,streamEvents:t9},openclaw:{cli:"openclaw",listTranscripts:t6,streamEvents:t8},factory:{cli:"factory",listTranscripts:t7,streamEvents:ie},devin:{cli:"devin",listTranscripts:il,streamEvents:ic},antigravity:{cli:"antigravity",listTranscripts:is,streamEvents:ir},goose:{cli:"goose",listTranscripts:async function(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=await (0,id.getGooseSessions)(),s=[];for(let e of n)!(e.mtimeMs<i)&&(!t||e.cwd&&t.has(e.cwd))&&s.push({cli:"goose",projectName:e.projectName,sessionId:e.sessionId,transcriptPath:`goose-db://${e.sessionId}`,mtimeMs:e.mtimeMs,sizeBytes:0});return s},streamEvents:async function(e){let t=await (0,iu.getGooseSessionLog)(e.sessionId);return t?tA(t.entries,{cli:"goose",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}}},im=/\.(?:ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|swift|rb|php|c|h|cc|cpp|hpp|cs|scala|sh|bash|zsh|json|yaml|yml|toml|md|txt|sql|html|css|scss|sass)$/i,ih=["/","/home","/usr","/etc","/var","/opt","/Users"],ig="rereadAfterEdit",iy=[{name:"redundant-cd-cwd",description:"Bash commands prefixed with `cd <cwd> && …` even though commands already run in cwd.",category:"Wasteful",severity:"info",displayTitle:"Prepended cd <cwd> before commands",impact:"Pure waste — your agent's shell already runs in `cwd`.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;if("string"!=typeof t||!e.cwd)return null;let i=t.trimStart(),n=/^cd\s+(?:"([^"]+)"|'([^']+)'|(\S+))\s*&&\s*([\s\S]+)$/.exec(i);if(!n)return null;let s=(n[1]??n[2]??n[3]??"").replace(/\/+$/,"");if(s!==e.cwd.replace(/\/+$/,""))return null;let r=n[4].trim();return{example:`cd ${s} && ${r}`}}},{name:"prefer-edit-over-read-cat",description:"Bash `cat`/`head`/`tail`/`less`/`more` on a single source file — use Read.",category:"Wasteful",severity:"info",displayTitle:"Used `cat`/`head`/`tail` on a source file",impact:"Burns tokens; the Read tool returns content directly without going through Bash output.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;if("string"!=typeof t)return null;let i=t.trim();if(/[|<>;&`$()]/.test(i))return null;let n=/^(cat|head|tail|less|more)\s+(?:-\S+\s+)*(?:"([^"]+)"|'([^']+)'|(\S+))\s*$/.exec(i);if(!n)return null;let s=n[2]??n[3]??n[4]??"";return!s||/(?:^|\/)\.env(?:\..+)?$/.test(s)||!im.test(s)?null:{example:i}}},{name:"prefer-edit-over-sed-awk",description:"Bash `sed -i`/`awk` in-place edits — use Edit.",category:"Wasteful",severity:"info",displayTitle:"Used sed -i or awk for an in-place edit",impact:"Edit tool is safer and produces a diff the agent can verify.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;if("string"!=typeof t)return null;let i=t.trim();return/(?:^|\s|;|&&|\|\|)sed\b[^|]*\s-i(?=\b|['"])/.test(i)||/(?:^|\s|;|&&|\|\|)awk\b[^|]*\s>\s*\S+/.test(i)&&!/\|/.test(i)?{example:i}:null}},{name:"prefer-write-over-heredoc",description:"Bash heredoc / `echo > file` writing multi-line content — use Write.",category:"Wasteful",severity:"info",displayTitle:"Used heredoc / `echo > file` to write a multi-line file",impact:"Write tool handles escaping and is verifiable.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;return"string"!=typeof t?null:/<<-?\s*['"]?[A-Za-z_][A-Za-z0-9_]*['"]?\s*>\s*\S/.test(t)||/(?:^|\s|;|&&|\|\|)(?:echo|printf)\s+["'][^"']*\n[^"']*["']\s*>\s*\S/.test(t)?{example:t.replace(/\s+/g," ").trim().slice(0,160)}:null}},{name:"sleep-polling-loop",description:"Bash long `sleep` or while-sleep polling loops.",category:"Wasteful",severity:"info",displayTitle:"Used a long sleep or while-sleep polling loop",impact:"Burns wall-clock; better to wait for an explicit signal.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;if("string"!=typeof t)return null;if(/\bwhile\b[\s\S]*?\bsleep\b[\s\S]*?\bdone\b/.test(t))return{example:t.replace(/\s+/g," ").trim().slice(0,160)};let i=/\bsleep\s+(\d+(?:\.\d+)?)(m|h|d)?\b/.exec(t);if(i){let e=parseFloat(i[1]),n=i[2]??"s";if(("m"===n?60*e:"h"===n?3600*e:"d"===n?86400*e:e)>=30)return{example:t.replace(/\s+/g," ").trim().slice(0,160)}}return null}},{name:"find-from-root",description:"Bash `find` against `/`, `/home`, `/usr`, etc. — scope to cwd instead.",category:"Risky",severity:"warn",displayTitle:"Ran find from /, /home, /usr, etc.",impact:"Filesystem-wide finds exhaust resources and rarely return useful results.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;if("string"!=typeof t)return null;let i=t.trim(),n=/(?:^|[\s;|&])find\s+(?:-\S+\s+)*("[^"]+"|'[^']+'|\S+)/.exec(i);if(!n)return null;let s=n[1].replace(/^["']|["']$/g,"").replace(/\/+$/,"")||"/";return ih.includes(s)?{example:i.slice(0,160)}:null}},{name:"git-commit-no-verify",description:"git commit invoked with --no-verify / -n, skipping hooks.",category:"Risky",severity:"warn",displayTitle:"Committed with --no-verify",impact:"Skips pre-commit hooks that exist to catch broken or unsafe code.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;return"string"!=typeof t?null:/\bgit\s+commit\b/.test(t)&&(/\s--no-verify\b/.test(t)||/\s-n\b/.test(t))?{example:t.replace(/\s+/g," ").trim().slice(0,160)}:null}},{name:"reread-after-edit",description:"Read of a file that was just Edit'd or Write'n in the same session.",category:"Wasteful",severity:"info",displayTitle:"Re-read a file it just edited",impact:"Edit/Write already returned the updated content; the second Read is wasted tokens.",detect(e,t){let i,n=((i=t[ig])||(i={countdown:new Map},t[ig]=i),i),s=e.toolInput.file_path,r="string"==typeof s?s:null;for(let[e,t]of n.countdown)t<=1?n.countdown.delete(e):n.countdown.set(e,t-1);return r?"Edit"===e.toolName||"Write"===e.toolName?(n.countdown.set(r,5),null):"Read"===e.toolName&&n.countdown.has(r)?(n.countdown.delete(r),{example:`Read ${r} immediately after Edit/Write`}):null:null}}],ib=["cowboy","explorer","ghost","optimist","hammer","architect"],iw={explorer:.38,architect:.33,hammer:.11,cowboy:.11,optimist:.07,ghost:.01,precision:0,goldfish:0},ik={optimist:0,cowboy:0,explorer:0,goldfish:0,architect:0,precision:0,hammer:0,ghost:0};for(let e of ib)ik[e]=Math.max(iw[e],.05);var iN=e.i(66680),iv=e.i(79857);let iS=null,iT=null;function i$(){if(iS)return iS;let e=tv.map(e=>`${e.name}|${e.fn.toString()}`).sort().join("\n");return iS=(0,iN.createHash)("sha1").update(e).digest("hex").slice(0,16)}function iE(){if(iT)return iT;let e=iy.map(e=>`${e.name}|${e.detect.toString()}`).sort().join("\n");return iT=(0,iN.createHash)("sha1").update(e).digest("hex").slice(0,16)}function iP(e){let t=(0,iv.auditCacheDir)(),i=(0,iN.createHash)("sha1").update(e).digest("hex");return(0,n.join)(t,`${i}.json`)}function iO(e,t){if(t<=0)return null;let i=null;try{i=(0,s.openSync)(e,"r");let n=Buffer.alloc(Math.min(4096,t));(0,s.readSync)(i,n,0,n.length,0);let r=Math.min(4096,t),o=Buffer.alloc(r);return(0,s.readSync)(i,o,0,r,t-r),(0,iN.createHash)("sha1").update(String(t)).update(n).update(o).digest("hex").slice(0,32)}catch{return null}finally{if(null!==i)try{(0,s.closeSync)(i)}catch{}}}var iA=e.i(71194),iI=e.i(49335),iC=e.i(10659);function ix(e,t){let i=e.trim(),n="string"==typeof t?t.trim():"";return n?i?`${i}. ${n}`:n:i}function iR(e,t){if(!e?.policyParams)return;let i=e.policyParams[t];if(i)return i;let n=function(e){if(!e.startsWith("pack/"))return null;let t=e.slice(5),i=t.lastIndexOf("/");if(i<=0)return null;let n=t.slice(0,i),s=n.lastIndexOf("@");return{packId:s>0?n.slice(0,s):n,name:t.slice(i+1)}}(t);if(n)return function(e,t,i){if(!e)return;let n=e[`pack/${t}/${i}`];return n||(t.toLowerCase()===iA.CORE_SOURCE.toLowerCase()?e[i]:void 0)}(e.policyParams,n.packId,n.name);let s=`${f}/`;if(t.startsWith(s))return e.policyParams[t.slice(s.length)]}async function ij(e,t,i,n){let s=t.tool_name,r=t.tool_input,o=function(e,t){let i=globalThis[m];i||g(i=new Map);let n=`${e}:${t??""}`,s=i.get(n);if(s)return s;let r=y().filter(i=>(!i.match.events||!(i.match.events.length>0)||!!i.match.events.includes(e))&&(!i.match.toolNames||!(i.match.toolNames.length>0)||!!t&&!!i.match.toolNames.includes(t))).sort((e,t)=>t.priority-e.priority);return i.set(n,r),r}(e,s);if((0,b.hookLogInfo)(`evaluating ${o.length} policies for ${e}`),0===o.length)return{exitCode:0,stdout:"",stderr:"",policyName:null,reason:null,decision:"allow"};let a={eventType:e,payload:t,toolName:s,toolInput:r,session:i,cli:i?.cli},l=[],c=[];for(let t of o){let s,r,o=t.params,d=iR(n,t.name)??{};if(o){let e={};for(let[t,i]of Object.entries(o))e[t]=t in d?d[t]:i.default;s={...a,params:e}}else s={...a,params:d};try{r=await t.fn(s)}catch(s){let n=s instanceof Error?s.message:String(s);(0,b.hookLogWarn)(`policy "${t.name}" threw: ${n}`),t.name.startsWith(`${f}/`)&&(0,iI.trackHookEvent)((0,iC.getInstanceId)(),"policy_evaluation_error",{policy_name:t.name,event_type:e,cli:i?.cli??null,error_type:s instanceof Error?s.name:"unknown"});continue}if("deny"===r.decision){let o,a=ix(r.reason??`Blocked by policy: ${t.name}`,iR(n,t.name)?.hint);(0,b.hookLogInfo)(`deny by "${t.name}": ${a}`),o=s.toolName?s.toolName:"UserPromptSubmit"===e?"prompt":"SessionStart"===e?"session start":"SessionEnd"===e?"session end":"Stop"===e?"stop":"operation";let l=`Blocked ${o} by failproofai because: ${a}, as per the policy configured by the user`;if(i?.cli==="cursor"){if("Stop"===e||"SubagentStop"===e)return{exitCode:0,stdout:JSON.stringify({followup_message:`MANDATORY ACTION REQUIRED from failproofai (policy: ${t.name}): ${a}
4
2
 
5
3
  You MUST complete the above action NOW. Do NOT ask the user for confirmation — execute the required action, then attempt to finish your task again.`}),stderr:"",policyName:t.name,reason:a,decision:"deny"};if("UserPromptSubmit"===e)return{exitCode:0,stdout:JSON.stringify({continue:!1,user_message:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"};return{exitCode:0,stdout:JSON.stringify({permission:"deny",user_message:l,agent_message:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"}}if(i?.cli==="pi"){if("Stop"===e)return{exitCode:0,stdout:JSON.stringify({permission:"deny",reason:`MANDATORY ACTION REQUIRED from failproofai (policy: ${t.name}): ${a}
6
4
 
@@ -14,9 +12,9 @@ You MUST complete the above action NOW. Do NOT ask the user for confirmation —
14
12
 
15
13
  You MUST complete the above action NOW. Do NOT ask the user for confirmation — execute the required action, then attempt to finish your task again.`:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"};if(i?.cli==="antigravity"){if("Stop"===e)return{exitCode:0,stdout:JSON.stringify({decision:"continue",reason:`MANDATORY ACTION REQUIRED from failproofai (policy: ${t.name}): ${a}
16
14
 
17
- You MUST complete the above action NOW. Do NOT ask the user for confirmation — execute the required action, then attempt to finish your task again.`}),stderr:"",policyName:t.name,reason:a,decision:"deny"};return{exitCode:0,stdout:JSON.stringify({decision:"deny",reason:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"}}if(i?.cli==="goose")return{exitCode:0,stdout:JSON.stringify({decision:"block",reason:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"};if("PreToolUse"===e)return{exitCode:0,stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e,permissionDecision:"deny",permissionDecisionReason:l}}),stderr:"",policyName:t.name,reason:a,decision:"deny"};if(i?.cli==="copilot"){if("UserPromptSubmit"===e)return{exitCode:0,stdout:JSON.stringify({decision:"block",reason:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"};if("PermissionRequest"===e)return{exitCode:0,stdout:JSON.stringify({behavior:"deny",message:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"}}if("PermissionRequest"===e)return{exitCode:0,stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e,decision:{behavior:"deny",message:`Blocked ${s} by failproofai because: ${a}, as per the policy configured by the user`}}}),stderr:"",policyName:t.name,reason:a,decision:"deny"};if("PostToolUse"===e){if(i?.cli==="codex"||i?.cli==="copilot")return{exitCode:0,stdout:JSON.stringify({decision:"block",reason:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"};return{exitCode:0,stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e,additionalContext:`Blocked ${s} by failproofai because: ${a}, as per the policy configured by the user`}}),stderr:"",policyName:t.name,reason:a,decision:"deny"}}if("Stop"===e||"SubagentStop"===e){let e=`MANDATORY ACTION REQUIRED from failproofai (policy: ${t.name}): ${a}
15
+ You MUST complete the above action NOW. Do NOT ask the user for confirmation — execute the required action, then attempt to finish your task again.`}),stderr:"",policyName:t.name,reason:a,decision:"deny"};return{exitCode:0,stdout:JSON.stringify({decision:"deny",reason:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"}}if(i?.cli==="goose")return{exitCode:0,stdout:JSON.stringify({decision:"block",reason:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"};if("PreToolUse"===e)return{exitCode:0,stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e,permissionDecision:"deny",permissionDecisionReason:l}}),stderr:"",policyName:t.name,reason:a,decision:"deny"};if(i?.cli==="copilot"){if("UserPromptSubmit"===e)return{exitCode:0,stdout:JSON.stringify({decision:"block",reason:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"};if("PermissionRequest"===e)return{exitCode:0,stdout:JSON.stringify({behavior:"deny",message:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"}}if("PermissionRequest"===e)return{exitCode:0,stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e,decision:{behavior:"deny",message:`Blocked ${o} by failproofai because: ${a}, as per the policy configured by the user`}}}),stderr:"",policyName:t.name,reason:a,decision:"deny"};if("PostToolUse"===e){if(i?.cli==="codex"||i?.cli==="copilot")return{exitCode:0,stdout:JSON.stringify({decision:"block",reason:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"};return{exitCode:0,stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e,additionalContext:`Blocked ${o} by failproofai because: ${a}, as per the policy configured by the user`}}),stderr:"",policyName:t.name,reason:a,decision:"deny"}}if("Stop"===e||"SubagentStop"===e){let e=`MANDATORY ACTION REQUIRED from failproofai (policy: ${t.name}): ${a}
18
16
 
19
- You MUST complete the above action NOW. Do NOT ask the user for confirmation — execute the required action, then attempt to finish your task again.`;if(i?.cli==="copilot")return{exitCode:0,stdout:JSON.stringify({decision:"block",reason:e}),stderr:"",policyName:t.name,reason:a,decision:"deny"};return{exitCode:2,stdout:"",stderr:e,policyName:t.name,reason:a,decision:"deny"}}return{exitCode:2,stdout:"",stderr:a,policyName:t.name,reason:a,decision:"deny"}}if("instruct"===o.decision){let e=iJ(o.reason??`Instruction from policy: ${t.name}`,iG(n,t.name)?.hint);l.push({policyName:t.name,reason:e}),C(`instruct by "${t.name}": ${e}`)}"allow"===o.decision&&o.reason&&c.push({policyName:t.name,reason:o.reason})}if(l.length>0){let t=l.map(e=>e.reason).join("\n"),n=l.map(e=>e.policyName);if(i?.cli==="cursor")return"Stop"===e||"SubagentStop"===e?{exitCode:0,stdout:JSON.stringify({followup_message:`Instruction from failproofai: ${t}`}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}:{exitCode:0,stdout:JSON.stringify({permission:"allow",additional_context:`Instruction from failproofai: ${t}`}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"};if(i?.cli==="pi"){if("Stop"===e){let e=1===n.length?`policy: ${n[0]}`:`policies: ${n.join(", ")}`;return{exitCode:0,stdout:JSON.stringify({permission:"deny",reason:`MANDATORY ACTION REQUIRED from failproofai (${e}): ${t}
17
+ You MUST complete the above action NOW. Do NOT ask the user for confirmation — execute the required action, then attempt to finish your task again.`;if(i?.cli==="copilot")return{exitCode:0,stdout:JSON.stringify({decision:"block",reason:e}),stderr:"",policyName:t.name,reason:a,decision:"deny"};return{exitCode:2,stdout:"",stderr:e,policyName:t.name,reason:a,decision:"deny"}}return{exitCode:2,stdout:"",stderr:a,policyName:t.name,reason:a,decision:"deny"}}if("instruct"===r.decision){let e=ix(r.reason??`Instruction from policy: ${t.name}`,iR(n,t.name)?.hint);l.push({policyName:t.name,reason:e}),(0,b.hookLogInfo)(`instruct by "${t.name}": ${e}`)}"allow"===r.decision&&r.reason&&c.push({policyName:t.name,reason:r.reason})}if(l.length>0){let t=l.map(e=>e.reason).join("\n"),n=l.map(e=>e.policyName);if(i?.cli==="cursor")return"Stop"===e||"SubagentStop"===e?{exitCode:0,stdout:JSON.stringify({followup_message:`Instruction from failproofai: ${t}`}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}:{exitCode:0,stdout:JSON.stringify({permission:"allow",additional_context:`Instruction from failproofai: ${t}`}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"};if(i?.cli==="pi"){if("Stop"===e){let e=1===n.length?`policy: ${n[0]}`:`policies: ${n.join(", ")}`;return{exitCode:0,stdout:JSON.stringify({permission:"deny",reason:`MANDATORY ACTION REQUIRED from failproofai (${e}): ${t}
20
18
 
21
19
  You MUST complete the above action(s) NOW. Do NOT ask the user for confirmation — execute the required action(s), then attempt to finish your task again.`}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}}return{exitCode:0,stdout:JSON.stringify({permission:"allow",reason:`Instruction from failproofai: ${t}`}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}}if(i?.cli==="hermes"){let e=l.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n");return{exitCode:0,stdout:JSON.stringify({decision:"allow",reason:`Instruction from failproofai: ${t}`}),stderr:e+"\n",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}}if(i?.cli==="openclaw"){if("Stop"===e){let e=1===n.length?`policy: ${n[0]}`:`policies: ${n.join(", ")}`;return{exitCode:0,stdout:JSON.stringify({permission:"deny",reason:`MANDATORY ACTION REQUIRED from failproofai (${e}): ${t}
22
20
 
@@ -28,8 +26,8 @@ You MUST complete the above action(s) NOW. Do NOT ask the user for confirmation
28
26
 
29
27
  You MUST complete the above action(s) NOW. Do NOT ask the user for confirmation — execute the required action(s), then attempt to finish your task again.`}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}}if(i?.cli==="antigravity"){if("UserPromptSubmit"===e)return{exitCode:0,stdout:JSON.stringify({injectSteps:[{ephemeralMessage:`Instruction from failproofai: ${t}`}]}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"};if("Stop"===e){let e=1===n.length?`policy: ${n[0]}`:`policies: ${n.join(", ")}`;return{exitCode:0,stdout:JSON.stringify({decision:"continue",reason:`MANDATORY ACTION REQUIRED from failproofai (${e}): ${t}
30
28
 
31
- You MUST complete the above action(s) NOW. Do NOT ask the user for confirmation — execute the required action(s), then attempt to finish your task again.`}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}}return{exitCode:0,stdout:"",stderr:l.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n")+"\n",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}}if(i?.cli==="goose")return{exitCode:0,stdout:"",stderr:l.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n")+"\n",policyName:n[0],policyNames:n,reason:t,decision:"instruct"};if("Stop"===e||"SubagentStop"===e){let e=1===n.length?`policy: ${n[0]}`:`policies: ${n.join(", ")}`,r=`MANDATORY ACTION REQUIRED from failproofai (${e}): ${t}
29
+ You MUST complete the above action(s) NOW. Do NOT ask the user for confirmation — execute the required action(s), then attempt to finish your task again.`}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}}return{exitCode:0,stdout:"",stderr:l.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n")+"\n",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}}if(i?.cli==="goose")return{exitCode:0,stdout:"",stderr:l.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n")+"\n",policyName:n[0],policyNames:n,reason:t,decision:"instruct"};if("Stop"===e||"SubagentStop"===e){let e=1===n.length?`policy: ${n[0]}`:`policies: ${n.join(", ")}`,s=`MANDATORY ACTION REQUIRED from failproofai (${e}): ${t}
32
30
 
33
- You MUST complete the above action(s) NOW. Do NOT ask the user for confirmation — execute the required action(s), then attempt to finish your task again.`;return i?.cli==="copilot"?{exitCode:0,stdout:JSON.stringify({decision:"block",reason:r}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}:{exitCode:2,stdout:"",stderr:r,policyName:n[0],policyNames:n,reason:t,decision:"instruct"}}return{exitCode:0,stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e,additionalContext:`Instruction from failproofai: ${t}`}}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}}if(c.length>0){let t=c.map(e=>e.reason).join("\n"),n=c.map(e=>e.policyName);if(i?.cli==="cursor"){let e={permission:"allow",additional_context:`Note from failproofai: ${t}`},i=c.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n");return{exitCode:0,stdout:JSON.stringify(e),stderr:i+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}}if(i?.cli==="pi"){let e={permission:"allow",reason:`Note from failproofai: ${t}`},i=c.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n");return{exitCode:0,stdout:JSON.stringify(e),stderr:i+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}}if(i?.cli==="openclaw"){let e=c.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n");return{exitCode:0,stdout:JSON.stringify({permission:"allow",reason:`Note from failproofai: ${t}`}),stderr:e+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}}let r="PreToolUse"===e||"PostToolUse"===e||"UserPromptSubmit"===e||"PermissionRequest"===e,o=c.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n");return r?{exitCode:0,stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e,additionalContext:`Note from failproofai: ${t}`}}),stderr:o+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}:{exitCode:0,stdout:"",stderr:o+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}}return{exitCode:0,stdout:"",stderr:"",policyName:null,reason:null,decision:"allow"}}let iZ=new Set(["warn-repeated-tool-calls"].map(e=>h(e))),iK=!1,iQ=null;async function iV(){if(iK)return;iQ=[...y()],globalThis[u]=[],g(null);let e=new Set(tl.map(e=>e.name).filter(e=>!iZ.has(h(e))).map(h));for(let t of tl)(t.alwaysOn||e.has(h(t.name)))&&function(e,t,i,n,r=0,o){let s=h(e),a=y(),l=a.findIndex(e=>e.name===s),c={name:s,description:t,fn:i,match:n,priority:r,...o?{params:o}:{}};l>=0?a[l]=c:a.push(c),g(null)}(t.name,t.description,t.fn,t.match,0,t.params);iK=!0}async function iX(e){iK||await iV();let t={sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:e.cwd,cli:e.cli},i={tool_name:e.toolName,tool_input:e.toolInput,session_id:e.sessionId,cwd:e.cwd,transcript_path:e.transcriptPath},n=[];if(i0(await iY("PreToolUse",i,t),"PreToolUse",n),void 0!==e.toolResultText){let r={...i,tool_response:e.toolResultText};i0(await iY("PostToolUse",r,t),"PostToolUse",n)}return n}function i0(e,t,i){for(let n of e.policyNames&&e.policyNames.length>0?e.policyNames:e.policyName?[e.policyName]:[])i.push({policyName:n,decision:e.decision,reason:e.reason,eventType:t})}function i1(e){let t=e.indexOf("/");return t>=0?e.slice(t+1):e}function i6(e){return e.length<=80?e:e.slice(0,79)+"…"}async function i3(e,t){let i,n={transcriptPath:e.transcriptPath,cli:e.cli,projectName:e.projectName,sessionId:e.sessionId,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes,cwd:"",eventsScanned:0,hitsByName:{},examplesByName:{},rangeByName:{}},r=i$[e.cli],o=0,s=t?.detectorState??{};if(r.streamEventsFrom){let s=await r.streamEventsFrom(e,t?.fromByte??0);s?(i=s.events,o=s.bytesConsumed,n.cwd=s.cwd??""):(i=await r.streamEvents(e),o=0)}else i=await r.streamEvents(e),o=0;if(0===i.length)return{result:n,bytesScanned:o,detectorState:s};for(let e of(n.eventsScanned=i.length,n.cwd=n.cwd||i[0].cwd||"",i)){let t;for(let t of iC){let i=t.detect(e,s);i&&i9(n,t.name,e.timestamp,e.cwd,i6(i.example))}try{t=await iX(e)}catch{continue}for(let i of t){let t=function(e,t){if("Bash"===t.toolName){let e=t.toolInput.command;if("string"==typeof e)return e.replace(/\s+/g," ")}let i=t.toolInput.file_path;return"string"==typeof i?`${t.toolName} ${i}`:`${t.toolName}`}(i.policyName,e);i9(n,i.policyName,e.timestamp,e.cwd,i6(t))}}return{result:n,bytesScanned:o,detectorState:s}}function i9(e,t,i,n,r){e.hitsByName[t]=(e.hitsByName[t]??0)+1;let o=e.examplesByName[t]??[];o.length<3&&(o.push({timestamp:i,cwd:n,example:r}),e.examplesByName[t]=o);let s=e.rangeByName[t];s?(i<s.first&&(s.first=i),i>s.last&&(s.last=i)):e.rangeByName[t]={first:i,last:i}}async function i2(e={}){let t=Date.now();await iV();try{return await i8(e,t)}finally{if(iK){if(null!==iQ){var i;i=iQ,globalThis[u]=[...i],g(null),iQ=null}iK=!1}}}async function i8(e,t){let o=e.clis??Array.from(tb),s=function(e){if(!e)return;let t=/^(\d+)\s*([dhm])$/i.exec(e.trim());if(t){let e=parseInt(t[1],10),i=t[2].toLowerCase();return Date.now()-e*("d"===i?864e5:"h"===i?36e5:6e4)}let i=Date.parse(e);if(!Number.isNaN(i))return i;throw Error(`Invalid --since value: "${e}" (expected e.g. "7d", "30d", or "2026-04-01")`)}(e.since),l=new Set(((function(){let e=function(e){let t=(0,a.homedir)(),i=(0,n.resolve)(e);for(;i!==t;){let e=(0,n.resolve)(i,".failproofai");try{if((0,r.statSync)(e).isDirectory())return i}catch{}let t=(0,n.dirname)(i);if(t===i)break;i=t}return(0,n.resolve)(e)}((void 0)??process.cwd()),t=(0,n.resolve)(e,".failproofai","policies-config.json"),i=(0,n.resolve)(e,".failproofai","policies-config.local.json"),o=(0,b.globalPolicyConfigFile)(),s=tc(t),l=tc(i),c=tc(o),d=new Set([...s.enabledPolicies??[],...l.enabledPolicies??[],...c.enabledPolicies??[]]),p={};for(let e of[s,l,c])if(e.policyParams)for(let[t,i]of Object.entries(e.policyParams))t in p||(p[t]=i);let u=[s,l,c].map(e=>void 0!==e.customPoliciesPaths?e.customPoliciesPaths:void 0!==e.customPoliciesPath?[e.customPoliciesPath]:void 0).find(e=>void 0!==e),m=new Set([...s.disabledCustomPolicies??[],...l.disabledCustomPolicies??[],...c.disabledCustomPolicies??[]]),f=s.customPoliciesEnabled??l.customPoliciesEnabled??c.customPoliciesEnabled,h=s.llm??l.llm??c.llm;return{enabledPolicies:[...d],...Object.keys(p).length>0?{policyParams:p}:{},...void 0!==u?{customPoliciesPaths:u}:{},...m.size?{disabledCustomPolicies:[...m]}:{},...void 0!==f?{customPoliciesEnabled:f}:{},...void 0!==h?{llm:h}:{}}})().enabledPolicies??[]).map(e=>h(e)));try{for(let e of function(){let e,t=process.env.FAILPROOFAI_PACK_DIR?(0,n.resolve)(process.env.FAILPROOFAI_PACK_DIR,"installed.json"):(0,b.packsInstalledFile)();if(!(0,r.existsSync)(t))return{packs:[],errors:[]};try{e=JSON.parse((0,r.readFileSync)(t,"utf8"))}catch(e){return{packs:[],errors:[{id:null,reason:`unreadable pack manifest: ${ty(e)}`}]}}if(!e||"object"!=typeof e)return{packs:[],errors:[{id:null,reason:"pack manifest is not an object"}]};let i=e;if(!tp.includes(i.schemaVersion))return{packs:[],errors:[{id:null,reason:`unsupported pack manifest schema ${String(i.schemaVersion)} (supported: ${tp.join(", ")})`}]};if(!Array.isArray(i.packs))return{packs:[],errors:[{id:null,reason:"pack manifest packs is not an array"}]};let o=process.env.FAILPROOFAI_PACK_DIR??(0,b.packsDir)(),s=[],a=[],l=new Set;for(let e of i.packs){let t=e&&"object"==typeof e&&"string"==typeof e.id?e.id:null;try{let t=function(e,t){if(!t||"object"!=typeof t)throw Error("pack entry is not an object");let i=function(e){if("string"!=typeof e.id||!tm.test(e.id))throw Error(`unsafe pack id ${JSON.stringify(e.id)}`);if("string"!=typeof e.version||!tf.test(e.version))throw Error(`invalid version for pack ${e.id}`);if(void 0!==e.effect&&"enforce"!==e.effect&&"observe"!==e.effect)throw Error(`unknown effect ${JSON.stringify(e.effect)} for pack ${e.id}`);let t="string"==typeof e.commit&&th.test(e.commit.trim().toLowerCase())?e.commit.trim().toLowerCase():void 0;return{id:e.id,version:e.version,effect:e.effect??"enforce",...t?{commit:t}:{}}}(t);if("string"!=typeof t.source||0===t.source.length)throw Error(`pack ${t.id} has no source`);if("string"!=typeof t.sha256||!tu.test(t.sha256))throw Error(`invalid SHA-256 for pack ${t.id}`);let o=i.effect,s=function(e,t){if(!t||(0,n.isAbsolute)(t))throw Error(`unsafe managed policy path ${JSON.stringify(t)}`);let i=(0,n.resolve)(e,t),o=(0,n.relative)(e,i);if(o.startsWith("..")||(0,n.isAbsolute)(o))throw Error(`managed policy path escapes its root: ${JSON.stringify(t)}`);let s=(0,r.realpathSync)(e),a=(0,r.realpathSync)(i),l=(0,n.relative)(s,a);if(l.startsWith("..")||(0,n.isAbsolute)(l))throw Error(`managed policy symlink escapes its root: ${JSON.stringify(t)}`);return a}(e,t.entry),a=(0,td.createHash)("sha256").update((0,r.readFileSync)(s)).digest("hex");if(a!==t.sha256)throw Error(`pack ${t.id} failed integrity verification: expected ${t.sha256}, got ${a}`);if(!Array.isArray(t.policies))throw Error(`pack ${t.id} policies is not an array`);let l=t.policies.map((e,i)=>(function(e,t,i){let n=`${e} policy #${i}`;if(!t||"object"!=typeof t)throw Error(`${n} is not an object`);let r=t.name;if("string"!=typeof r||!tg.test(r))throw Error(`${n} has an unsafe name ${JSON.stringify(r)}`);if("alwaysOn"in t)throw Error(`${n} declares alwaysOn, which packs may not set`);if("string"!=typeof t.description||0===t.description.length)throw Error(`${n} is missing a description`);if("string"!=typeof t.category||0===t.category.length)throw Error(`${n} is missing a category`);if("boolean"!=typeof t.defaultEnabled)throw Error(`${n} is missing defaultEnabled`);if(!t.match||"object"!=typeof t.match)throw Error(`${n} is missing a match`);return t})(t.id,e,i)),c=new Set;for(let e of l){if(c.has(e.name))throw Error(`pack ${t.id} declares ${e.name} twice`);c.add(e.name)}let d=null;if(void 0!==t.enabled){if(!Array.isArray(t.enabled)||t.enabled.some(e=>"string"!=typeof e))throw Error(`pack ${t.id} enabled is not an array of names`);d=t.enabled.filter(e=>c.has(e))}let p=null;if(void 0!==t.clis){if(!Array.isArray(t.clis)||t.clis.some(e=>"string"!=typeof e))throw Error(`pack ${t.id} clis is not an array of agent names`);p=t.clis}return{clis:p,id:i.id,version:i.version,source:t.source,path:s,sha256:t.sha256,effect:o,policies:l,enabled:d}}(o,e);if(l.has(t.id))throw Error(`duplicate pack id ${t.id}`);l.add(t.id),s.push(t)}catch(n){let i=e&&("observe"===e.effect||"enforce"===e.effect)?e.effect:"enforce";a.push({id:t,reason:ty(n),effect:i,...Array.isArray(e?.policies)?{declared:function(e){let t=[];for(let i of e)i&&"object"==typeof i&&"string"==typeof i.name&&i.match&&"object"==typeof i.match&&t.push(i);return t}(e.policies)}:{}})}}return{packs:s,errors:a}}().packs)for(let t of e.enabled??e.policies.map(e=>e.name))l.add(h(t))}catch{}let c=[];for(let t of o){let i,n=i$[t];try{i=await n.listTranscripts({projects:e.projects,sinceMs:s})}catch{continue}c.push(...i)}let d=0,p=0,u=c.map(t=>async()=>{let i,n=null;if(!e.noCache){let e=function(e,t,i){if(0===i)return null;let n=ij(e);if(!(0,r.existsSync)(n))return null;try{let o=(0,r.readFileSync)(n,"utf-8"),s=JSON.parse(o);if(4!==s.schemaVersion||s.engineVersion!==i_()||s.detectorVersion!==iB()||!Number.isFinite(s.cachedAt)||Date.now()-s.cachedAt>2592e6||!s.result)return null;if(s.mtimeMs===t&&s.sizeBytes===i)return{kind:"hit",result:s.result};let a=s.bytesScanned;if(!Number.isFinite(a)||a<=0||a>i||!s.anchorHash||iD(e,a)!==s.anchorHash)return null;return{kind:"resume",result:s.result,fromByte:a,detectorState:function(e){if(!e)return{};try{return JSON.parse(e,(e,t)=>t&&"object"==typeof t&&Array.isArray(t.__map)?new Map(t.__map):t)}catch{return{}}}(s.detectorState)}}catch{return null}}(t.transcriptPath,t.mtimeMs,t.sizeBytes);if(e?.kind==="hit")return e.result;i=e?.kind==="resume"?{fromByte:e.fromByte,detectorState:e.detectorState}:void 0,n=e?.kind==="resume"?e.result:null}try{let o=await i3(t,i),s=n?function(e,t){let i={...e,mtimeMs:t.mtimeMs,sizeBytes:t.sizeBytes,cwd:e.cwd||t.cwd||"",eventsScanned:(e.eventsScanned??0)+(t.eventsScanned??0),hitsByName:{...e.hitsByName},examplesByName:{},rangeByName:{...e.rangeByName}};for(let[t,n]of Object.entries(e.examplesByName))i.examplesByName[t]=[...n];for(let[e,n]of Object.entries(t.hitsByName))i.hitsByName[e]=(i.hitsByName[e]??0)+n;for(let[e,n]of Object.entries(t.examplesByName)){let t=i.examplesByName[e]??[];for(let e of n){if(t.length>=3)break;t.push(e)}i.examplesByName[e]=t}for(let[e,n]of Object.entries(t.rangeByName)){let t=i.rangeByName[e];t?(n.first<t.first&&(t.first=n.first),n.last>t.last&&(t.last=n.last)):i.rangeByName[e]={...n}}return i}(n,o.result):o.result;return e.noCache||function(e,t,i,n,o){if(0===i)return;let s=ij(e);try{(0,r.mkdirSync)((0,b.auditCacheDir)(),{recursive:!0});let l={schemaVersion:4,cachedAt:Date.now(),mtimeMs:t,sizeBytes:i,engineVersion:i_(),detectorVersion:iB(),result:n};if(o&&o.bytesScanned>0){let t=iD(e,o.bytesScanned);if(t){var a;l.bytesScanned=o.bytesScanned,l.anchorHash=t,a=o.detectorState,l.detectorState=JSON.stringify(a,(e,t)=>t instanceof Map?{__map:[...t.entries()]}:t)}}(0,r.writeFileSync)(s,JSON.stringify(l),{encoding:"utf-8",mode:384});try{(0,r.chmodSync)(s,384)}catch{}}catch{}}(t.transcriptPath,t.mtimeMs,t.sizeBytes,s,o.bytesScanned>0?{bytesScanned:o.bytesScanned,detectorState:o.detectorState}:void 0),s}catch{return p++,{transcriptPath:t.transcriptPath,cli:t.cli,projectName:t.projectName,cwd:"",sessionId:t.sessionId,mtimeMs:t.mtimeMs,sizeBytes:t.sizeBytes,eventsScanned:0,hitsByName:{},examplesByName:{},rangeByName:{}}}}),m=await (0,i.batchAll)(u,8),f=[];for(let e of m)"fulfilled"===e.status?f.push(e.value):d++;let g=function(e,t){let i=new Map;for(let t of e)for(let[e,n]of Object.entries(t.hitsByName)){let r=i.get(e)??{hits:0,projects:new Set,examples:[]};for(let i of(r.hits+=n,r.projects.add(t.projectName),t.examplesByName[e]??[]))r.examples.length<3&&r.examples.push({...i,sessionId:t.sessionId});let o=t.rangeByName[e];o&&((!r.first||o.first<r.first)&&(r.first=o.first),(!r.last||o.last>r.last)&&(r.last=o.last)),i.set(e,r)}let n=new Map(iC.map(e=>[e.name,e])),r=[];for(let[e,o]of i){let i=n.get(e),s=!!i,a=s?null:function(e){let t=i1(e);for(let i of tl)if(i.name===e||i1(i.name)===t)return i;return null}(e),l=s?"audit-detector":"builtin",c=!s&&t.has(h(e)),d=i?.displayTitle??a?.displayTitle??i?.description??a?.description??i1(e),p=i?.impact??a?.impact??"";r.push({name:e,source:l,category:i?.category??a?.category??"Custom",severity:s?i?.severity??"info":function(e){let t,i=(t=e.indexOf("/"))>=0?e.slice(t+1):e;return i.startsWith("sanitize-")?"sanitize":i.startsWith("block-")?"deny":i.startsWith("warn-")||i.startsWith("protect-")||i.startsWith("prefer-")||i.startsWith("require-")?"warn":"deny"}(e),hits:o.hits,projects:o.projects.size,firstSeen:o.first,lastSeen:o.last,examples:o.examples,displayTitle:d,impact:p,enabledInConfig:c,installHint:"audit-detector"===l?"Audit-only — `failproofai audit` will keep tracking these.":c?"Already enforced — failproofai is blocking these in real time.":`Enable in one command: failproofai policies --install ${i1(e)}`})}return r.sort((e,t)=>t.hits-e.hits),r}(f,l);if(e.policies?.length){let t=new Set(e.policies.map(i1));g=g.filter(e=>t.has(i1(e.name)))}let y=g.reduce((e,t)=>e+t.hits,0),w=new Set,k=new Set,v=0;for(let e of f)Object.keys(e.hitsByName).length>0&&w.add(e.projectName),e.cwd&&k.add(e.cwd),v+=e.eventsScanned??0;return{version:2,scannedAt:new Date(t).toISOString(),scope:{cli:o,projects:e.projects??"all",since:e.since??null},transcripts:{scanned:c.length,skipped:d,errors:p,durationMs:Date.now()-t},results:g,totals:{hits:y,projectsWithHits:w.size},projectsScanned:[...k].sort(),eventsScanned:v,enabledBuiltinNames:[...l].map(e=>e.includes("/")?e.slice(e.indexOf("/")+1):e)}}var i4=e.i(47756),i5=e.i(48480),i7=e.i(29095),ne=e.i(46501);let nt=new Set(tb);async function ni(e){await (0,ne.initTelemetry)();let i={};try{let n=await e.text();if(n.trim().length>0){let e=JSON.parse(n);if(null===e||"object"!=typeof e||Array.isArray(e))return(0,ne.trackEvent)("audit_run_rejected",{source:"dashboard",reason:"non_object_body"}),t.NextResponse.json({error:"Request body must be a JSON object"},{status:400});i=e}}catch{return(0,ne.trackEvent)("audit_run_rejected",{source:"dashboard",reason:"invalid_json"}),t.NextResponse.json({error:"Invalid JSON body"},{status:400})}let n=function(e){let t={};if("string"==typeof e.since&&e.since.trim()&&(t.since=e.since.trim()),Array.isArray(e.cli)&&e.cli.length>0){let i=e.cli.filter(e=>"string"==typeof e&&nt.has(e));i.length>0&&(t.clis=i)}return Array.isArray(e.project)&&e.project.length>0&&(t.projects=e.project.filter(e=>"string"==typeof e)),Array.isArray(e.policy)&&e.policy.length>0&&(t.policies=e.policy.filter(e=>"string"==typeof e)),!0===e.noCache&&(t.noCache=!0),t}(i);if(!(0,i5.tryAcquireRun)())return(0,ne.trackEvent)("audit_run_rejected",{source:"dashboard",reason:"already_running"}),t.NextResponse.json({error:"Audit already running",status:"already-running"},{status:409});let r=(0,i7.acquireAuditLock)("dashboard");if(!r.ok)return(0,i5.finishRun)(null),(0,ne.trackEvent)("audit_run_rejected",{source:"dashboard",reason:"cross_process_lock"}),t.NextResponse.json({error:"Audit already running",status:"already-running"},{status:409});(0,ne.trackEvent)("audit_run_started",{source:"dashboard",since:n.since??null,no_cache:!0===n.noCache,cli_count:n.clis?.length??0,project_count:n.projects?.length??0});let o=Date.now();return(async()=>{try{let e=await i2(n),t=(0,i4.writeDashboardCache)(n,e);(0,ne.trackEvent)("audit_run_completed",{source:"dashboard",duration_ms:Date.now()-o,events_scanned:e.eventsScanned,sessions_scanned:e.transcripts.scanned,projects_scanned:e.projectsScanned.length,findings:e.results.length,total_hits:e.totals.hits,persisted:t}),(0,i5.finishRun)(t?null:"audit finished but its result could not be saved")}catch(e){(0,ne.trackEvent)("audit_run_failed",{source:"dashboard",duration_ms:Date.now()-o,error_type:e instanceof Error?e.name:"unknown",error_message:function(e){let t;try{t=e instanceof Error?e.message:String(e)}catch{return"unknown"}if(!t)return"";let i="";try{i=a.default.homedir()}catch{}return i&&i.length>1&&(t=t.split(i).join("~")),t.length>300&&(t=t.slice(0,300)+"…"),t}(e)}),(0,i5.finishRun)(e instanceof Error?e.message:String(e))}finally{r.lock.release()}})(),t.NextResponse.json({status:"started"},{status:202})}e.s(["POST",0,ni,"dynamic",0,"force-dynamic"],97610)},89498,e=>{"use strict";var t=e.i(47909),i=e.i(74017),n=e.i(96250),r=e.i(59756),o=e.i(61916),s=e.i(74677),a=e.i(69741),l=e.i(16795),c=e.i(87718),d=e.i(95169),p=e.i(47587),u=e.i(66012),m=e.i(70101),f=e.i(26937),h=e.i(10372),g=e.i(93695);e.i(52474);var y=e.i(220);let b=new t.AppRouteRouteModule({definition:{kind:i.RouteKind.APP_ROUTE,page:"/api/audit/run/route",pathname:"/api/audit/run",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/app/api/audit/run/route.ts",nextConfigOutput:"standalone",userland:()=>e.r(97610),...{}}),{workAsyncStorage:w,workUnitAsyncStorage:k,serverHooks:v}=b;async function S(e,t,n){n.requestMeta&&(0,r.setRequestMeta)(e,n.requestMeta),b.isDev&&(0,r.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let w="/api/audit/run/route";w=w.replace(/\/index$/,"")||"/";let k=await b.prepare(e,t,{srcPage:w,multiZoneDraftMode:!1});if(!k)return t.statusCode=400,t.end("Bad Request"),null==n.waitUntil||n.waitUntil.call(n,Promise.resolve()),null;let{buildId:v,deploymentId:S,params:N,nextConfig:$,parsedUrl:T,isDraftMode:E,prerenderManifest:P,routerServerContext:C,isOnDemandRevalidate:A,revalidateOnlyGenerated:I,resolvedPathname:O,clientReferenceManifest:x,serverActionsManifest:R}=k,_=(0,a.normalizeAppPath)(w),B=!!(P.dynamicRoutes[_]||P.routes[O]),j=async()=>((null==C?void 0:C.render404)?await C.render404(e,t,T,!1):t.end("This page could not be found"),null);if(B&&!E){let e=!!P.routes[O],t=P.dynamicRoutes[_];if(t&&!1===t.fallback&&!e){if($.adapterPath)return await j();throw new g.NoFallbackError}}let D=null;!B||b.isDev||E||(D="/index"===(D=O)?"/":D);let W=!0===b.isDev||!B,M=B&&!W;R&&x&&(0,s.setManifestsSingleton)({page:w,clientReferenceManifest:x,serverActionsManifest:R});let U=e.method||"GET",z=(0,o.getTracer)(),L=z.getActiveScopeSpan(),F=!!(null==C?void 0:C.isWrappedByNextServer),H=!!(0,r.getRequestMeta)(e,"minimalMode"),q=(0,r.getRequestMeta)(e,"incrementalCache")||await b.getIncrementalCache(e,$,P,H);null==q||q.resetRequestCache(),globalThis.__incrementalCache=q;let J={params:N,previewProps:P.preview,renderOpts:{experimental:{authInterrupts:!!$.experimental.authInterrupts,useCacheTimeout:$.experimental.useCacheTimeout},cacheComponents:!!$.cacheComponents,validationLevel:$.experimental.instantInsights.validationLevel,supportsDynamicResponse:W,incrementalCache:q,hmrRefreshHash:(0,r.getRequestMeta)(e,"hmrRefreshHash"),cacheLifeProfiles:$.cacheLife,staticPageGenerationTimeout:$.staticPageGenerationTimeout,waitUntil:n.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,i,n,r)=>b.onRequestError(e,t,n,r,C)},sharedContext:{buildId:v,deploymentId:S}},G=new l.NodeNextRequest(e),Y=new l.NodeNextResponse(t),Z=c.NextRequestAdapter.fromNodeNextRequest(G,(0,c.signalFromNodeResponse)(t)),K=async({previousCacheEntry:i})=>{try{if(!H&&A&&I&&!i)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let r=await b.handle(Z,J);e.fetchMetrics=J.renderOpts.fetchMetrics;let o=J.renderOpts.pendingWaitUntil;o&&n.waitUntil&&(n.waitUntil(o),o=void 0);let s=J.renderOpts.collectedTags;if(!B)return await (0,u.sendResponse)(G,Y,r,o),null;{let e=await r.blob(),t=(0,m.toNodeOutgoingHttpHeaders)(r.headers);s&&(t[h.NEXT_CACHE_TAGS_HEADER]=s),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let i=void 0!==J.renderOpts.collectedRevalidate&&!(J.renderOpts.collectedRevalidate>=h.INFINITE_CACHE)&&J.renderOpts.collectedRevalidate,n=void 0===J.renderOpts.collectedExpire||J.renderOpts.collectedExpire>=h.INFINITE_CACHE?!1!==i&&i>0?$.expireTime:void 0:J.renderOpts.collectedExpire;return{value:{kind:y.CachedRouteKind.APP_ROUTE,status:r.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:i,expire:n}}}}catch(t){throw(null==i?void 0:i.isStale)&&await b.onRequestError(e,t,{routerKind:"App Router",routePath:w,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:M,isOnDemandRevalidate:A})},!1,C),t}},Q=async(r,s)=>{try{var a,l;let r=await b.handleResponse({req:e,nextConfig:$,cacheKey:D,routeKind:i.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:P,isRoutePPREnabled:!1,isOnDemandRevalidate:A,revalidateOnlyGenerated:I,responseGenerator:K,waitUntil:n.waitUntil,isMinimalMode:H});if(!B)return;if((null==r||null==(a=r.value)?void 0:a.kind)!==y.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==r||null==(l=r.value)?void 0:l.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});H||t.setHeader("x-nextjs-cache",A?"REVALIDATED":r.isMiss?"MISS":r.isStale?"STALE":"HIT"),E&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let o=(0,m.fromNodeOutgoingHttpHeaders)(r.value.headers);H&&B||o.delete(h.NEXT_CACHE_TAGS_HEADER),!r.cacheControl||t.getHeader("Cache-Control")||o.get("Cache-Control")||o.set("Cache-Control",(0,f.getCacheControlHeader)(r.cacheControl)),await (0,u.sendResponse)(G,Y,new Response(r.value.body,{headers:o,status:r.value.status||200}));return}catch(t){if(t instanceof g.NoFallbackError||await b.onRequestError(e,t,{routerKind:"App Router",routePath:_,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:M,isOnDemandRevalidate:A})},!1,C),B)throw t;await (0,u.sendResponse)(G,Y,new Response(null,{status:500}));return}finally{(()=>{if(!r)return;let e=t.statusCode;r.setAttributes({"http.status_code":e,"next.rsc":!1}),e&&e>=500&&(r.setStatus({code:o.SpanStatusCode.ERROR}),r.setAttribute("error.type",e.toString()));let i=z.getRootSpanAttributes();if(!i)return;if(i.get("next.span_type")!==d.BaseServerSpan.handleRequest)return console.warn(`Unexpected root span type '${i.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let n=i.get("next.route")||_,a=`${U} ${n}`;r.setAttributes({"next.route":n,"http.route":n,"next.span_name":a}),r.updateName(a),s&&s!==r&&(s.setAttribute("http.route",n),s.updateName(a))})()}};if(F&&L)await Q(L,void 0);else{let t=z.getActiveScopeSpan();await z.withPropagatedContext(e.headers,()=>z.trace(d.BaseServerSpan.handleRequest,{spanName:`${U} ${w}`,kind:o.SpanKind.SERVER,attributes:{"http.method":U,"http.target":e.url}},e=>Q(e,t)),void 0,!F)}}e.s(["handler",0,S,"patchFetch",0,function(){return(0,n.patchFetch)({workAsyncStorage:w,workUnitAsyncStorage:k})},"routeModule",0,b,"serverHooks",0,v,"workAsyncStorage",0,w,"workUnitAsyncStorage",0,k])}];
31
+ You MUST complete the above action(s) NOW. Do NOT ask the user for confirmation — execute the required action(s), then attempt to finish your task again.`;return i?.cli==="copilot"?{exitCode:0,stdout:JSON.stringify({decision:"block",reason:s}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}:{exitCode:2,stdout:"",stderr:s,policyName:n[0],policyNames:n,reason:t,decision:"instruct"}}return{exitCode:0,stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e,additionalContext:`Instruction from failproofai: ${t}`}}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}}if(c.length>0){let t=c.map(e=>e.reason).join("\n"),n=c.map(e=>e.policyName);if(i?.cli==="cursor"){let e={permission:"allow",additional_context:`Note from failproofai: ${t}`},i=c.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n");return{exitCode:0,stdout:JSON.stringify(e),stderr:i+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}}if(i?.cli==="pi"){let e={permission:"allow",reason:`Note from failproofai: ${t}`},i=c.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n");return{exitCode:0,stdout:JSON.stringify(e),stderr:i+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}}if(i?.cli==="openclaw"){let e=c.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n");return{exitCode:0,stdout:JSON.stringify({permission:"allow",reason:`Note from failproofai: ${t}`}),stderr:e+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}}let s="PreToolUse"===e||"PostToolUse"===e||"UserPromptSubmit"===e||"PermissionRequest"===e,r=c.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n");return s?{exitCode:0,stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e,additionalContext:`Note from failproofai: ${t}`}}),stderr:r+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}:{exitCode:0,stdout:"",stderr:r+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}}return{exitCode:0,stdout:"",stderr:"",policyName:null,reason:null,decision:"allow"}}let iB=new Set(["warn-repeated-tool-calls"].map(e=>h(e))),i_=!1,iM=null;async function iD(){if(i_)return;iM=[...y()],globalThis[p]=[],g(null);let e=new Set(tv.map(e=>e.name).filter(e=>!iB.has(h(e))).map(h));for(let t of tv)(t.alwaysOn||e.has(h(t.name)))&&function(e,t,i,n,s=0,r){let o=h(e),a=y(),l=a.findIndex(e=>e.name===o),c={name:o,description:t,fn:i,match:n,priority:s,...r?{params:r}:{}};l>=0?a[l]=c:a.push(c),g(null)}(t.name,t.description,t.fn,t.match,0,t.params);i_=!0}async function iU(e){i_||await iD();let t={sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:e.cwd,cli:e.cli},i={tool_name:e.toolName,tool_input:e.toolInput,session_id:e.sessionId,cwd:e.cwd,transcript_path:e.transcriptPath},n=[];if(iW(await ij("PreToolUse",i,t),"PreToolUse",n),void 0!==e.toolResultText){let s={...i,tool_response:e.toolResultText};iW(await ij("PostToolUse",s,t),"PostToolUse",n)}return n}function iW(e,t,i){for(let n of e.policyNames&&e.policyNames.length>0?e.policyNames:e.policyName?[e.policyName]:[])i.push({policyName:n,decision:e.decision,reason:e.reason,eventType:t})}function iz(e){let t=e.indexOf("/");return t>=0?e.slice(t+1):e}function iL(e){return e.length<=80?e:e.slice(0,79)+"…"}async function iq(e,t){let i,n={transcriptPath:e.transcriptPath,cli:e.cli,projectName:e.projectName,sessionId:e.sessionId,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes,cwd:"",eventsScanned:0,hitsByName:{},examplesByName:{},rangeByName:{}},s=ip[e.cli],r=0,o=!1,a=t?.detectorState??{};if(s.streamEventsFrom){let a=await s.streamEventsFrom(e,t?.fromByte??0);a?(i=a.events,r=a.bytesConsumed,n.cwd=a.cwd??"",o=!0):(i=await s.streamEvents(e),r=0)}else i=await s.streamEvents(e),r=0;if(0===i.length)return{result:n,bytesScanned:r,detectorState:a,resumed:o};for(let e of(n.eventsScanned=i.length,n.cwd=n.cwd||i[0].cwd||"",i)){let t;for(let t of iy){let i=t.detect(e,a);i&&iH(n,t.name,e.timestamp,e.cwd,iL(i.example))}try{t=await iU(e)}catch{continue}for(let i of t){let t=function(e,t){if("Bash"===t.toolName){let e=t.toolInput.command;if("string"==typeof e)return e.replace(/\s+/g," ")}let i=t.toolInput.file_path;return"string"==typeof i?`${t.toolName} ${i}`:`${t.toolName}`}(i.policyName,e);iH(n,i.policyName,e.timestamp,e.cwd,iL(t))}}return{result:n,bytesScanned:r,detectorState:a,resumed:o}}function iH(e,t,i,n,s){e.hitsByName[t]=(e.hitsByName[t]??0)+1;let r=e.examplesByName[t]??[];r.length<3&&(r.push({timestamp:i,cwd:n,example:s}),e.examplesByName[t]=r);let o=e.rangeByName[t];o?(i<o.first&&(o.first=i),i>o.last&&(o.last=i)):e.rangeByName[t]={first:i,last:i}}async function iJ(e={}){let t=Date.now();await iD();try{return await iF(e,t)}finally{if(i_){if(null!==iM){var i;i=iM,globalThis[p]=[...i],g(null),iM=null}i_=!1}}}async function iF(e,t){let n=e.clis??Array.from(t$.INTEGRATION_TYPES),r=function(e){if(!e)return;let t=/^(\d+)\s*([dhm])$/i.exec(e.trim());if(t){let e=parseInt(t[1],10),i=t[2].toLowerCase();return Date.now()-e*("d"===i?864e5:"h"===i?36e5:6e4)}let i=Date.parse(e);if(!Number.isNaN(i))return i;throw Error(`Invalid --since value: "${e}" (expected e.g. "7d", "30d", or "2026-04-01")`)}(e.since),o=new Set(((0,tS.readMergedHooksConfig)().enabledPolicies??[]).map(e=>h(e)));try{for(let e of(0,tT.readInstalledPacks)().packs)for(let t of e.enabled??e.policies.map(e=>e.name))o.add(h(t))}catch{}let a=[];for(let t of n){let i,n=ip[t];try{i=await n.listTranscripts({projects:e.projects,sinceMs:r})}catch{continue}a.push(...i)}let l=0,c=0,d=a.map(t=>async()=>{let i,n=null;if(!e.noCache){let e=function(e,t,i){if(0===i)return null;let n=iP(e);if(!(0,s.existsSync)(n))return null;try{let r=(0,s.readFileSync)(n,"utf-8"),o=JSON.parse(r);if(4!==o.schemaVersion||o.engineVersion!==i$()||o.detectorVersion!==iE()||!Number.isFinite(o.cachedAt)||Date.now()-o.cachedAt>2592e6||!o.result)return null;if(o.mtimeMs===t&&o.sizeBytes===i)return{kind:"hit",result:o.result};let a=o.bytesScanned;if(!Number.isFinite(a)||a<=0||a>i||!o.anchorHash||iO(e,a)!==o.anchorHash)return null;return{kind:"resume",result:o.result,fromByte:a,detectorState:function(e){if(!e)return{};try{return JSON.parse(e,(e,t)=>t&&"object"==typeof t&&Array.isArray(t.__map)?new Map(t.__map):t)}catch{return{}}}(o.detectorState)}}catch{return null}}(t.transcriptPath,t.mtimeMs,t.sizeBytes);if(e?.kind==="hit")return e.result;i=e?.kind==="resume"?{fromByte:e.fromByte,detectorState:e.detectorState}:void 0,n=e?.kind==="resume"?e.result:null}try{let r=await iq(t,i),o=n&&r.resumed?function(e,t){let i={...e,mtimeMs:t.mtimeMs,sizeBytes:t.sizeBytes,cwd:e.cwd||t.cwd||"",eventsScanned:(e.eventsScanned??0)+(t.eventsScanned??0),hitsByName:{...e.hitsByName},examplesByName:{},rangeByName:{...e.rangeByName}};for(let[t,n]of Object.entries(e.examplesByName))i.examplesByName[t]=[...n];for(let[e,n]of Object.entries(t.hitsByName))i.hitsByName[e]=(i.hitsByName[e]??0)+n;for(let[e,n]of Object.entries(t.examplesByName)){let t=i.examplesByName[e]??[];for(let e of n){if(t.length>=3)break;t.push(e)}i.examplesByName[e]=t}for(let[e,n]of Object.entries(t.rangeByName)){let t=i.rangeByName[e];t?(n.first<t.first&&(t.first=n.first),n.last>t.last&&(t.last=n.last)):i.rangeByName[e]={...n}}return i}(n,r.result):r.result;return e.noCache||function(e,t,i,n,r){if(0===i)return;let o=iP(e);try{(0,s.mkdirSync)((0,iv.auditCacheDir)(),{recursive:!0});let l={schemaVersion:4,cachedAt:Date.now(),mtimeMs:t,sizeBytes:i,engineVersion:i$(),detectorVersion:iE(),result:n};if(r&&r.bytesScanned>0){let t=iO(e,r.bytesScanned);if(t){var a;l.bytesScanned=r.bytesScanned,l.anchorHash=t,a=r.detectorState,l.detectorState=JSON.stringify(a,(e,t)=>t instanceof Map?{__map:[...t.entries()]}:t)}}(0,s.writeFileSync)(o,JSON.stringify(l),{encoding:"utf-8",mode:384});try{(0,s.chmodSync)(o,384)}catch{}}catch{}}(t.transcriptPath,t.mtimeMs,t.sizeBytes,o,r.bytesScanned>0?{bytesScanned:r.bytesScanned,detectorState:r.detectorState}:void 0),o}catch{return c++,{transcriptPath:t.transcriptPath,cli:t.cli,projectName:t.projectName,cwd:"",sessionId:t.sessionId,mtimeMs:t.mtimeMs,sizeBytes:t.sizeBytes,eventsScanned:0,hitsByName:{},examplesByName:{},rangeByName:{}}}}),u=await (0,i.batchAll)(d,8),p=[];for(let e of u)"fulfilled"===e.status?p.push(e.value):l++;let m=function(e,t){let i=new Map;for(let t of e)for(let[e,n]of Object.entries(t.hitsByName)){let s=i.get(e)??{hits:0,projects:new Set,examples:[]};for(let i of(s.hits+=n,s.projects.add(t.projectName),t.examplesByName[e]??[]))s.examples.length<3&&s.examples.push({...i,sessionId:t.sessionId});let r=t.rangeByName[e];r&&((!s.first||r.first<s.first)&&(s.first=r.first),(!s.last||r.last>s.last)&&(s.last=r.last)),i.set(e,s)}let n=new Map(iy.map(e=>[e.name,e])),s=[];for(let[e,r]of i){let i=n.get(e),o=!!i,a=o?null:function(e){let t=iz(e);for(let i of tv)if(i.name===e||iz(i.name)===t)return i;return null}(e),l=o?"audit-detector":"builtin",c=!o&&t.has(h(e)),d=i?.displayTitle??a?.displayTitle??i?.description??a?.description??iz(e),u=i?.impact??a?.impact??"";s.push({name:e,source:l,category:i?.category??a?.category??"Custom",severity:o?i?.severity??"info":function(e){let t,i=(t=e.indexOf("/"))>=0?e.slice(t+1):e;return i.startsWith("sanitize-")?"sanitize":i.startsWith("block-")?"deny":i.startsWith("warn-")||i.startsWith("protect-")||i.startsWith("prefer-")||i.startsWith("require-")?"warn":"deny"}(e),hits:r.hits,projects:r.projects.size,firstSeen:r.first,lastSeen:r.last,examples:r.examples,displayTitle:d,impact:u,enabledInConfig:c,installHint:"audit-detector"===l?"Audit-only — `failproofai audit` will keep tracking these.":c?"Already enforced — failproofai is blocking these in real time.":`Enable in one command: failproofai policies --install ${iz(e)}`})}return s.sort((e,t)=>t.hits-e.hits),s}(p,o);if(e.policies?.length){let t=new Set(e.policies.map(iz));m=m.filter(e=>t.has(iz(e.name)))}let f=m.reduce((e,t)=>e+t.hits,0),g=new Set,y=new Set,b=0;for(let e of p)Object.keys(e.hitsByName).length>0&&g.add(e.projectName),e.cwd&&y.add(e.cwd),b+=e.eventsScanned??0;return{version:2,scannedAt:new Date(t).toISOString(),scope:{cli:n,projects:e.projects??"all",since:e.since??null},transcripts:{scanned:a.length,skipped:l,errors:c,durationMs:Date.now()-t},results:m,totals:{hits:f,projectsWithHits:g.size},projectsScanned:[...y].sort(),eventsScanned:b,enabledBuiltinNames:[...o].map(e=>e.includes("/")?e.slice(e.indexOf("/")+1):e)}}var iG=e.i(47756),iY=e.i(48480),iZ=e.i(29095),iQ=e.i(46501);let iK=new Set(t$.INTEGRATION_TYPES);async function iV(e){await (0,iQ.initTelemetry)();let i={};try{let n=await e.text();if(n.trim().length>0){let e=JSON.parse(n);if(null===e||"object"!=typeof e||Array.isArray(e))return(0,iQ.trackEvent)("audit_run_rejected",{source:"dashboard",reason:"non_object_body"}),t.NextResponse.json({error:"Request body must be a JSON object"},{status:400});i=e}}catch{return(0,iQ.trackEvent)("audit_run_rejected",{source:"dashboard",reason:"invalid_json"}),t.NextResponse.json({error:"Invalid JSON body"},{status:400})}let n=function(e){let t={};if("string"==typeof e.since&&e.since.trim()&&(t.since=e.since.trim()),Array.isArray(e.cli)&&e.cli.length>0){let i=e.cli.filter(e=>"string"==typeof e&&iK.has(e));i.length>0&&(t.clis=i)}return Array.isArray(e.project)&&e.project.length>0&&(t.projects=e.project.filter(e=>"string"==typeof e)),Array.isArray(e.policy)&&e.policy.length>0&&(t.policies=e.policy.filter(e=>"string"==typeof e)),!0===e.noCache&&(t.noCache=!0),t}(i);if(!(0,iY.tryAcquireRun)())return(0,iQ.trackEvent)("audit_run_rejected",{source:"dashboard",reason:"already_running"}),t.NextResponse.json({error:"Audit already running",status:"already-running"},{status:409});let s=(0,iZ.acquireAuditLock)("dashboard");if(!s.ok)return(0,iY.finishRun)(null),(0,iQ.trackEvent)("audit_run_rejected",{source:"dashboard",reason:"cross_process_lock"}),t.NextResponse.json({error:"Audit already running",status:"already-running"},{status:409});(0,iQ.trackEvent)("audit_run_started",{source:"dashboard",since:n.since??null,no_cache:!0===n.noCache,cli_count:n.clis?.length??0,project_count:n.projects?.length??0});let r=Date.now();return(async()=>{try{let e=await iJ(n),t=(0,iG.writeDashboardCache)(n,e);(0,iQ.trackEvent)("audit_run_completed",{source:"dashboard",duration_ms:Date.now()-r,events_scanned:e.eventsScanned,sessions_scanned:e.transcripts.scanned,projects_scanned:e.projectsScanned.length,findings:e.results.length,total_hits:e.totals.hits,persisted:t}),(0,iY.finishRun)(t?null:"audit finished but its result could not be saved")}catch(e){(0,iQ.trackEvent)("audit_run_failed",{source:"dashboard",duration_ms:Date.now()-r,error_type:e instanceof Error?e.name:"unknown",error_message:function(e){let t;try{t=e instanceof Error?e.message:String(e)}catch{return"unknown"}if(!t)return"";let i="";try{i=a.default.homedir()}catch{}return i&&i.length>1&&(t=t.split(i).join("~")),t.length>300&&(t=t.slice(0,300)+"…"),t}(e)}),(0,iY.finishRun)(e instanceof Error?e.message:String(e))}finally{s.lock.release()}})(),t.NextResponse.json({status:"started"},{status:202})}e.s(["POST",0,iV,"dynamic",0,"force-dynamic"],97610)},89498,e=>{"use strict";var t=e.i(47909),i=e.i(74017),n=e.i(96250),s=e.i(59756),r=e.i(61916),o=e.i(74677),a=e.i(69741),l=e.i(16795),c=e.i(87718),d=e.i(95169),u=e.i(47587),p=e.i(66012),m=e.i(70101),f=e.i(26937),h=e.i(10372),g=e.i(93695);e.i(52474);var y=e.i(220);let b=new t.AppRouteRouteModule({definition:{kind:i.RouteKind.APP_ROUTE,page:"/api/audit/run/route",pathname:"/api/audit/run",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/app/api/audit/run/route.ts",nextConfigOutput:"standalone",userland:()=>e.r(97610),...{}}),{workAsyncStorage:w,workUnitAsyncStorage:k,serverHooks:N}=b;async function v(e,t,n){n.requestMeta&&(0,s.setRequestMeta)(e,n.requestMeta),b.isDev&&(0,s.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let w="/api/audit/run/route";w=w.replace(/\/index$/,"")||"/";let k=await b.prepare(e,t,{srcPage:w,multiZoneDraftMode:!1});if(!k)return t.statusCode=400,t.end("Bad Request"),null==n.waitUntil||n.waitUntil.call(n,Promise.resolve()),null;let{buildId:N,deploymentId:v,params:S,nextConfig:T,parsedUrl:$,isDraftMode:E,prerenderManifest:P,routerServerContext:O,isOnDemandRevalidate:A,revalidateOnlyGenerated:I,resolvedPathname:C,clientReferenceManifest:x,serverActionsManifest:R}=k,j=(0,a.normalizeAppPath)(w),B=!!(P.dynamicRoutes[j]||P.routes[C]),_=async()=>((null==O?void 0:O.render404)?await O.render404(e,t,$,!1):t.end("This page could not be found"),null);if(B&&!E){let e=!!P.routes[C],t=P.dynamicRoutes[j];if(t&&!1===t.fallback&&!e){if(T.adapterPath)return await _();throw new g.NoFallbackError}}let M=null;!B||b.isDev||E||(M="/index"===(M=C)?"/":M);let D=!0===b.isDev||!B,U=B&&!D;R&&x&&(0,o.setManifestsSingleton)({page:w,clientReferenceManifest:x,serverActionsManifest:R});let W=e.method||"GET",z=(0,r.getTracer)(),L=z.getActiveScopeSpan(),q=!!(null==O?void 0:O.isWrappedByNextServer),H=!!(0,s.getRequestMeta)(e,"minimalMode"),J=(0,s.getRequestMeta)(e,"incrementalCache")||await b.getIncrementalCache(e,T,P,H);null==J||J.resetRequestCache(),globalThis.__incrementalCache=J;let F={params:S,previewProps:P.preview,renderOpts:{experimental:{authInterrupts:!!T.experimental.authInterrupts,useCacheTimeout:T.experimental.useCacheTimeout},cacheComponents:!!T.cacheComponents,validationLevel:T.experimental.instantInsights.validationLevel,supportsDynamicResponse:D,incrementalCache:J,hmrRefreshHash:(0,s.getRequestMeta)(e,"hmrRefreshHash"),cacheLifeProfiles:T.cacheLife,staticPageGenerationTimeout:T.staticPageGenerationTimeout,waitUntil:n.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,i,n,s)=>b.onRequestError(e,t,n,s,O)},sharedContext:{buildId:N,deploymentId:v}},G=new l.NodeNextRequest(e),Y=new l.NodeNextResponse(t),Z=c.NextRequestAdapter.fromNodeNextRequest(G,(0,c.signalFromNodeResponse)(t)),Q=async({previousCacheEntry:i})=>{try{if(!H&&A&&I&&!i)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let s=await b.handle(Z,F);e.fetchMetrics=F.renderOpts.fetchMetrics;let r=F.renderOpts.pendingWaitUntil;r&&n.waitUntil&&(n.waitUntil(r),r=void 0);let o=F.renderOpts.collectedTags;if(!B)return await (0,p.sendResponse)(G,Y,s,r),null;{let e=await s.blob(),t=(0,m.toNodeOutgoingHttpHeaders)(s.headers);o&&(t[h.NEXT_CACHE_TAGS_HEADER]=o),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let i=void 0!==F.renderOpts.collectedRevalidate&&!(F.renderOpts.collectedRevalidate>=h.INFINITE_CACHE)&&F.renderOpts.collectedRevalidate,n=void 0===F.renderOpts.collectedExpire||F.renderOpts.collectedExpire>=h.INFINITE_CACHE?!1!==i&&i>0?T.expireTime:void 0:F.renderOpts.collectedExpire;return{value:{kind:y.CachedRouteKind.APP_ROUTE,status:s.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:i,expire:n}}}}catch(t){throw(null==i?void 0:i.isStale)&&await b.onRequestError(e,t,{routerKind:"App Router",routePath:w,routeType:"route",revalidateReason:(0,u.getRevalidateReason)({isStaticGeneration:U,isOnDemandRevalidate:A})},!1,O),t}},K=async(s,o)=>{try{var a,l;let s=await b.handleResponse({req:e,nextConfig:T,cacheKey:M,routeKind:i.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:P,isRoutePPREnabled:!1,isOnDemandRevalidate:A,revalidateOnlyGenerated:I,responseGenerator:Q,waitUntil:n.waitUntil,isMinimalMode:H});if(!B)return;if((null==s||null==(a=s.value)?void 0:a.kind)!==y.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==s||null==(l=s.value)?void 0:l.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});H||t.setHeader("x-nextjs-cache",A?"REVALIDATED":s.isMiss?"MISS":s.isStale?"STALE":"HIT"),E&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let r=(0,m.fromNodeOutgoingHttpHeaders)(s.value.headers);H&&B||r.delete(h.NEXT_CACHE_TAGS_HEADER),!s.cacheControl||t.getHeader("Cache-Control")||r.get("Cache-Control")||r.set("Cache-Control",(0,f.getCacheControlHeader)(s.cacheControl)),await (0,p.sendResponse)(G,Y,new Response(s.value.body,{headers:r,status:s.value.status||200}));return}catch(t){if(t instanceof g.NoFallbackError||await b.onRequestError(e,t,{routerKind:"App Router",routePath:j,routeType:"route",revalidateReason:(0,u.getRevalidateReason)({isStaticGeneration:U,isOnDemandRevalidate:A})},!1,O),B)throw t;await (0,p.sendResponse)(G,Y,new Response(null,{status:500}));return}finally{(()=>{if(!s)return;let e=t.statusCode;s.setAttributes({"http.status_code":e,"next.rsc":!1}),e&&e>=500&&(s.setStatus({code:r.SpanStatusCode.ERROR}),s.setAttribute("error.type",e.toString()));let i=z.getRootSpanAttributes();if(!i)return;if(i.get("next.span_type")!==d.BaseServerSpan.handleRequest)return console.warn(`Unexpected root span type '${i.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let n=i.get("next.route")||j,a=`${W} ${n}`;s.setAttributes({"next.route":n,"http.route":n,"next.span_name":a}),s.updateName(a),o&&o!==s&&(o.setAttribute("http.route",n),o.updateName(a))})()}};if(q&&L)await K(L,void 0);else{let t=z.getActiveScopeSpan();await z.withPropagatedContext(e.headers,()=>z.trace(d.BaseServerSpan.handleRequest,{spanName:`${W} ${w}`,kind:r.SpanKind.SERVER,attributes:{"http.method":W,"http.target":e.url}},e=>K(e,t)),void 0,!q)}}e.s(["handler",0,v,"patchFetch",0,function(){return(0,n.patchFetch)({workAsyncStorage:w,workUnitAsyncStorage:k})},"routeModule",0,b,"serverHooks",0,N,"workAsyncStorage",0,w,"workUnitAsyncStorage",0,k])}];
34
32
 
35
33
  //# sourceMappingURL=_1ek68ln._.js.map
@@ -1,3 +1,3 @@
1
1
  module.exports=[78081,e=>{e.v(s=>Promise.all(["server/chunks/[externals]__0qxhecv._.js","server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_01r25oi._.js"].map(s=>e.l(s))).then(()=>s(39702)))}];
2
2
 
3
- //# sourceMappingURL=node_modules_posthog-node_dist_entrypoints_index_node_mjs_09d5c79._.js.map
3
+ //# sourceMappingURL=node_modules_posthog-node_dist_entrypoints_index_node_mjs_04op_ou._.js.map