failproofai 1.0.1 → 1.0.2-beta.0
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.
- package/.next/standalone/.next/BUILD_ID +1 -1
- package/.next/standalone/.next/build-manifest.json +3 -3
- package/.next/standalone/.next/prerender-manifest.json +6 -6
- package/.next/standalone/.next/required-server-files.json +1 -1
- package/.next/standalone/.next/server/app/_global-error/page/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/server/app/_global-error/page.js +2 -2
- package/.next/standalone/.next/server/app/_global-error/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/_global-error.html +1 -1
- package/.next/standalone/.next/server/app/_global-error.rsc +7 -7
- package/.next/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +6 -6
- package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +7 -7
- package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found/page/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/server/app/_not-found/page.js +2 -2
- package/.next/standalone/.next/server/app/_not-found/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/_not-found.html +1 -1
- package/.next/standalone/.next/server/app/_not-found.rsc +15 -15
- package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +15 -15
- package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +14 -14
- package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/api/audit/invite/route.js +3 -2
- package/.next/standalone/.next/server/app/api/audit/invite/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/audit/run/route.js +5 -4
- package/.next/standalone/.next/server/app/api/audit/run/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/audit/status/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/auth/login-request/route.js +2 -2
- package/.next/standalone/.next/server/app/api/auth/login-request/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/auth/login-verify/route.js +4 -3
- package/.next/standalone/.next/server/app/api/auth/login-verify/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/auth/logout/route.js +4 -4
- package/.next/standalone/.next/server/app/api/auth/logout/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/auth/status/route.js +4 -4
- package/.next/standalone/.next/server/app/api/auth/status/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/download/[project]/[session]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/audit/page/server-reference-manifest.json +2 -2
- package/.next/standalone/.next/server/app/audit/page.js +2 -2
- package/.next/standalone/.next/server/app/audit/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/audit/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/index.html +1 -1
- package/.next/standalone/.next/server/app/index.rsc +15 -15
- package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +14 -14
- package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +15 -15
- package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/page/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/server/app/page.js +2 -2
- package/.next/standalone/.next/server/app/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/policies/page/server-reference-manifest.json +66 -22
- package/.next/standalone/.next/server/app/policies/page.js +5 -4
- package/.next/standalone/.next/server/app/policies/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/policies/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/project/[name]/page/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/server/app/project/[name]/page.js +2 -2
- package/.next/standalone/.next/server/app/project/[name]/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/project/[name]/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/react-loadable-manifest.json +2 -2
- package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/server-reference-manifest.json +2 -2
- package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page.js +2 -2
- package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/projects/page/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/server/app/projects/page.js +2 -2
- package/.next/standalone/.next/server/app/projects/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/projects/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/settings/page/server-reference-manifest.json +4 -4
- package/.next/standalone/.next/server/app/settings/page.js +1 -1
- package/.next/standalone/.next/server/app/settings/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/settings/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/chunks/{[externals]__1qzqcio._.js → [externals]__0e32-7c._.js} +1 -1
- package/.next/standalone/.next/server/chunks/[externals]__1s462yl._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__01eqny5._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0_0xu5z._.js +1 -1
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__1p8poxd._.js → [root-of-the-server]__0igxt32._.js} +2 -2
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0neqlu-._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0o07qi9._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0t9oqnn._.js +3 -0
- package/.next/standalone/.next/server/chunks/_0bs-v8p._.js +3 -0
- package/.next/standalone/.next/server/chunks/_0tovk6q._.js +3 -0
- package/.next/standalone/.next/server/chunks/_0trp3yc._.js +3 -0
- package/.next/standalone/.next/server/chunks/_185gyk9._.js +3 -0
- package/.next/standalone/.next/server/chunks/_1ek68ln._.js +5 -6
- package/.next/standalone/.next/server/chunks/lib_telemetry-id_ts_1k8gj9o._.js +3 -0
- 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
- 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
- package/.next/standalone/.next/server/chunks/package_json_[json]_cjs_1nxcc4v._.js +1 -1
- package/.next/standalone/.next/server/chunks/src_hooks_0xbw3bu._.js +12 -0
- package/.next/standalone/.next/server/chunks/src_hooks_fp-home_ts_09kv0bn._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__013jr2b._.js +4 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__01wy8d-._.js +4 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__02npjtd._.js +4 -0
- package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0spkm68._.js → [root-of-the-server]__07gm3zl._.js} +21 -20
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0da85px._.js +4 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0ftmoxc._.js +4 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0oa1lav._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0p-5p8u._.js +4 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0s740oi._.js +6 -0
- package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__07tbbf3._.js → [root-of-the-server]__0zig5sv._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__192nhvh._.js +5 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1p2otjt._.js +4 -0
- package/.next/standalone/.next/server/chunks/ssr/{_0lvyuv4._.js → _00e9tnf._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/_08x1r5t._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{_0u5zauv._.js → _12l4a_k._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_1u8-lu2._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_1zopuov._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/app_audit__components_audit-dashboard_tsx_0p9ud47._.js +13 -13
- package/.next/standalone/.next/server/chunks/ssr/app_global-error_tsx_1kp6l3x._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/app_policies_hooks-client_tsx_19dqvpc._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/app_settings_settings-client_tsx_20lq-mq._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/src_hooks_08o7bqo._.js +10 -0
- package/.next/standalone/.next/server/chunks/ssr/src_hooks_builtin-policies_ts_09j2ndl._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/src_hooks_fp-home_ts_0je3xkv._.js +1 -1
- package/.next/standalone/.next/server/middleware-build-manifest.js +3 -3
- package/.next/standalone/.next/server/middleware.js +1 -1
- package/.next/standalone/.next/server/pages/404.html +1 -1
- package/.next/standalone/.next/server/pages/500.html +1 -1
- package/.next/standalone/.next/server/server-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/server-reference-manifest.json +71 -27
- package/.next/standalone/.next/static/chunks/{37fcpc36x9gpe.js → 0eqky-7n7dgdm.js} +1 -1
- package/.next/standalone/.next/static/chunks/{1ide1wl2f7zi1.js → 0sa9v5mhc8861.js} +13 -13
- package/.next/standalone/.next/static/chunks/1mfzsja6ftim5.css +2 -0
- package/.next/standalone/.next/static/chunks/{3k7mxbp9hiom0.js → 1nuqytbta44af.js} +1 -1
- package/.next/standalone/.next/static/chunks/1sl2xmn9inx3y.js +6 -0
- package/.next/standalone/.next/static/chunks/{2_2lhuojq2xop.js → 2aawsjld9ied_.js} +1 -1
- package/.next/standalone/.next/static/chunks/2gn7ut4svofm2.js +1 -0
- package/.next/standalone/.next/static/chunks/{31s1smp-g7gks.js → 2hs7ycvsav7v2.js} +1 -1
- package/.next/standalone/.next/static/chunks/{0k5050ezjvv49.js → 2i2yt3hzjredm.js} +1 -1
- package/.next/standalone/.next/static/chunks/{3c808qrfcq0im.js → 35xg6retpe6rp.js} +1 -1
- package/.next/standalone/.next/static/chunks/{2zpp1we2jv6tb.js → 3y54nw0i7dsjl.js} +1 -1
- package/.next/standalone/SECURITY.md +5 -4
- package/.next/standalone/app/actions/get-hooks-config.ts +108 -17
- package/.next/standalone/app/actions/pack-actions.ts +153 -0
- package/.next/standalone/app/audit/_components/run-progress.tsx +1 -1
- package/.next/standalone/app/audit/_components/share-templates.ts +13 -13
- package/.next/standalone/app/policies/hooks-client.tsx +320 -14
- package/.next/standalone/components/navbar.tsx +2 -28
- package/.next/standalone/components/reach-developers.tsx +8 -1
- package/.next/standalone/docs-old/agenteye/python-sdk-skill.mdx +1 -1
- package/.next/standalone/docs-old/agenteye/python-sdk.mdx +59 -35
- package/.next/standalone/docs-old/i18n/README.ar.md +1 -0
- package/.next/standalone/docs-old/i18n/README.de.md +1 -0
- package/.next/standalone/docs-old/i18n/README.es.md +1 -0
- package/.next/standalone/docs-old/i18n/README.fr.md +1 -0
- package/.next/standalone/docs-old/i18n/README.he.md +1 -0
- package/.next/standalone/docs-old/i18n/README.hi.md +1 -0
- package/.next/standalone/docs-old/i18n/README.it.md +1 -0
- package/.next/standalone/docs-old/i18n/README.ja.md +1 -0
- package/.next/standalone/docs-old/i18n/README.ko.md +1 -0
- package/.next/standalone/docs-old/i18n/README.pt-br.md +1 -0
- package/.next/standalone/docs-old/i18n/README.ru.md +1 -0
- package/.next/standalone/docs-old/i18n/README.tr.md +1 -0
- package/.next/standalone/docs-old/i18n/README.vi.md +1 -0
- package/.next/standalone/docs-old/i18n/README.zh.md +1 -0
- package/.next/standalone/fp-cloud-cli/CHANGELOG.md +431 -0
- package/.next/standalone/fp-cloud-cli/LICENSE +42 -0
- package/.next/standalone/fp-cloud-cli/MANIFEST.in +10 -0
- package/.next/standalone/fp-cloud-cli/README.md +259 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/__init__.py +10 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/__main__.py +4 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/_click_compat.py +64 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/_context.py +332 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/_version.py +1 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/analytics.py +432 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/analytics_config.py +77 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/analytics_registry.py +83 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/app.py +492 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/auth.py +160 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/client.py +1694 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/__init__.py +0 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/_write.py +214 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/agent_cmds.py +407 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/alerts_cmds.py +445 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/audits_cmds.py +1054 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/auth_cmds.py +512 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/errors_cmds.py +190 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/evals_cmds.py +161 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/events_cmds.py +159 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/fleet_cmds.py +416 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/guardrails_cmds.py +148 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/incidents_cmds.py +472 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/keys_cmds.py +407 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/list_cmds.py +63 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/orgs_cmds.py +319 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/policies_cmds.py +499 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/queries_cmds.py +378 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/sessions_cmds.py +151 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/settings_cmds.py +150 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/usage_cmds.py +35 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/users_cmds.py +404 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/config.py +330 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/dates.py +78 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/enforcement.py +345 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/errors.py +98 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/models.py +891 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/orgs.py +30 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/output.py +6593 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/permissions.py +208 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/policy_check.py +290 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/py.typed +0 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/select.py +322 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/theme.py +53 -0
- package/.next/standalone/fp-cloud-cli/pyproject.toml +106 -0
- package/.next/standalone/fp-cloud-cli/skill/SKILL.md +302 -0
- package/.next/standalone/fp-cloud-cli/skill/agents/openai.yaml +8 -0
- package/.next/standalone/fp-cloud-cli/skill/references/commands.md +254 -0
- package/.next/standalone/fp-cloud-cli/tests/__init__.py +0 -0
- package/.next/standalone/fp-cloud-cli/tests/conftest.py +92 -0
- package/.next/standalone/fp-cloud-cli/tests/test_alerting.py +644 -0
- package/.next/standalone/fp-cloud-cli/tests/test_analytics.py +385 -0
- package/.next/standalone/fp-cloud-cli/tests/test_audits.py +950 -0
- package/.next/standalone/fp-cloud-cli/tests/test_auth.py +98 -0
- package/.next/standalone/fp-cloud-cli/tests/test_auth_mode.py +272 -0
- package/.next/standalone/fp-cloud-cli/tests/test_click_compat.py +118 -0
- package/.next/standalone/fp-cloud-cli/tests/test_client.py +299 -0
- package/.next/standalone/fp-cloud-cli/tests/test_commands.py +814 -0
- package/.next/standalone/fp-cloud-cli/tests/test_config.py +99 -0
- package/.next/standalone/fp-cloud-cli/tests/test_dashboards_agent.py +340 -0
- package/.next/standalone/fp-cloud-cli/tests/test_dates.py +76 -0
- package/.next/standalone/fp-cloud-cli/tests/test_enforcement_logic.py +481 -0
- package/.next/standalone/fp-cloud-cli/tests/test_facets.py +170 -0
- package/.next/standalone/fp-cloud-cli/tests/test_failproofai_home.py +722 -0
- package/.next/standalone/fp-cloud-cli/tests/test_fp_home_contract.py +198 -0
- package/.next/standalone/fp-cloud-cli/tests/test_hardening.py +186 -0
- package/.next/standalone/fp-cloud-cli/tests/test_help_table_coverage.py +127 -0
- package/.next/standalone/fp-cloud-cli/tests/test_keys_queries.py +496 -0
- package/.next/standalone/fp-cloud-cli/tests/test_list.py +59 -0
- package/.next/standalone/fp-cloud-cli/tests/test_multivalue.py +183 -0
- package/.next/standalone/fp-cloud-cli/tests/test_no_customer_identifiers.py +168 -0
- package/.next/standalone/fp-cloud-cli/tests/test_operator.py +492 -0
- package/.next/standalone/fp-cloud-cli/tests/test_orgs.py +692 -0
- package/.next/standalone/fp-cloud-cli/tests/test_output.py +1732 -0
- package/.next/standalone/fp-cloud-cli/tests/test_policy_check.py +191 -0
- package/.next/standalone/fp-cloud-cli/tests/test_readme_matches_reality.py +125 -0
- package/.next/standalone/fp-cloud-cli/tests/test_review_fixes.py +161 -0
- package/.next/standalone/fp-cloud-cli/tests/test_telemetry_completeness.py +90 -0
- package/.next/standalone/fp-cloud-cli/tests/test_usage.py +115 -0
- package/.next/standalone/fp-cloud-cli/tests/test_v1_origin_diagnostic.py +70 -0
- package/.next/standalone/fp-cloud-cli/tests/test_v1_routing.py +214 -0
- package/.next/standalone/fp-cloud-cli/tests/test_whoami.py +104 -0
- package/.next/standalone/fp-cloud-cli/uv.lock +552 -0
- package/.next/standalone/package.json +29 -22
- package/.next/standalone/sdk/python/CHANGELOG.md +70 -0
- package/.next/standalone/sdk/python/LICENSE +42 -0
- package/.next/standalone/sdk/python/MANIFEST.in +21 -0
- package/.next/standalone/sdk/python/README.md +466 -0
- package/.next/standalone/sdk/python/docs/README.md +249 -0
- package/.next/standalone/sdk/python/docs/_shared/README.md +43 -0
- package/.next/standalone/sdk/python/docs/_shared/__init__.py +195 -0
- package/.next/standalone/sdk/python/docs/crewai/README.md +328 -0
- package/.next/standalone/sdk/python/docs/crewai/examples/quickstart.py +61 -0
- package/.next/standalone/sdk/python/docs/crewai/examples/research_crew.py +92 -0
- package/.next/standalone/sdk/python/docs/langgraph/README.md +481 -0
- package/.next/standalone/sdk/python/docs/langgraph/examples/quickstart.py +51 -0
- package/.next/standalone/sdk/python/docs/langgraph/examples/research_agent.py +86 -0
- package/.next/standalone/sdk/python/docs/langgraph/examples/supervisor_handoff.py +83 -0
- package/.next/standalone/sdk/python/docs/llama_index/README.md +332 -0
- package/.next/standalone/sdk/python/docs/llama_index/examples/quickstart.py +62 -0
- package/.next/standalone/sdk/python/docs/llama_index/examples/research_agent.py +93 -0
- package/.next/standalone/sdk/python/docs/manual/README.md +491 -0
- package/.next/standalone/sdk/python/docs/manual/examples/quickstart.py +57 -0
- package/.next/standalone/sdk/python/docs/manual/examples/research_agent.py +133 -0
- package/.next/standalone/sdk/python/docs/pydantic_ai/README.md +323 -0
- package/.next/standalone/sdk/python/docs/pydantic_ai/examples/quickstart.py +48 -0
- package/.next/standalone/sdk/python/docs/pydantic_ai/examples/research_agent.py +94 -0
- package/.next/standalone/sdk/python/failproofai_sdk/__init__.py +131 -0
- package/.next/standalone/sdk/python/failproofai_sdk/_context.py +218 -0
- package/.next/standalone/sdk/python/failproofai_sdk/_environment.py +78 -0
- package/.next/standalone/sdk/python/failproofai_sdk/_events.py +752 -0
- package/.next/standalone/sdk/python/failproofai_sdk/_resolver.py +118 -0
- package/.next/standalone/sdk/python/failproofai_sdk/_runtime.py +21 -0
- package/.next/standalone/sdk/python/failproofai_sdk/_schema.py +317 -0
- package/.next/standalone/sdk/python/failproofai_sdk/_scopes.py +422 -0
- package/.next/standalone/sdk/python/failproofai_sdk/_version.py +1 -0
- package/.next/standalone/sdk/python/failproofai_sdk/_writer.py +750 -0
- package/.next/standalone/sdk/python/failproofai_sdk/integrations/__init__.py +274 -0
- package/.next/standalone/sdk/python/failproofai_sdk/integrations/_compat.py +247 -0
- package/.next/standalone/sdk/python/failproofai_sdk/integrations/_core.py +1076 -0
- package/.next/standalone/sdk/python/failproofai_sdk/integrations/crewai.py +1669 -0
- package/.next/standalone/sdk/python/failproofai_sdk/integrations/langchain.py +2151 -0
- package/.next/standalone/sdk/python/failproofai_sdk/integrations/llama_index.py +1588 -0
- package/.next/standalone/sdk/python/failproofai_sdk/integrations/pydantic_ai.py +977 -0
- package/.next/standalone/sdk/python/failproofai_sdk/py.typed +0 -0
- package/.next/standalone/sdk/python/pyproject.toml +92 -0
- package/.next/standalone/sdk/python/skill/SKILL.md +399 -0
- package/.next/standalone/sdk/python/skill/agents/openai.yaml +8 -0
- package/.next/standalone/sdk/python/skill/references/events.md +234 -0
- package/.next/standalone/sdk/python/skill/references/frameworks.md +314 -0
- package/.next/standalone/sdk/python/skill/references/install.md +100 -0
- package/.next/standalone/sdk/python/skill/references/integration.md +352 -0
- package/.next/standalone/sdk/python/tests/__init__.py +0 -0
- package/.next/standalone/sdk/python/tests/conftest.py +169 -0
- package/.next/standalone/sdk/python/tests/integrations/__init__.py +6 -0
- package/.next/standalone/sdk/python/tests/integrations/test_crewai.py +1299 -0
- package/.next/standalone/sdk/python/tests/integrations/test_langchain.py +2338 -0
- package/.next/standalone/sdk/python/tests/integrations/test_llama_index.py +1576 -0
- package/.next/standalone/sdk/python/tests/integrations/test_pydantic_ai.py +1102 -0
- package/.next/standalone/sdk/python/tests/test_context.py +410 -0
- package/.next/standalone/sdk/python/tests/test_docs.py +411 -0
- package/.next/standalone/sdk/python/tests/test_durability.py +1352 -0
- package/.next/standalone/sdk/python/tests/test_encoding.py +571 -0
- package/.next/standalone/sdk/python/tests/test_integrations.py +1127 -0
- package/.next/standalone/sdk/python/tests/test_no_customer_identifiers.py +214 -0
- package/.next/standalone/sdk/python/tests/test_packaging.py +185 -0
- package/.next/standalone/sdk/python/tests/test_resolver_umbrella.py +178 -0
- package/.next/standalone/sdk/python/tests/test_scopes.py +487 -0
- package/.next/standalone/sdk/python/tests/test_sdk.py +923 -0
- package/.next/standalone/sdk/python/tests/test_server_contract.py +650 -0
- package/.next/standalone/sdk/python/tests/test_site_docs.py +371 -0
- package/.next/standalone/sdk/python/tests/test_skill_snippets.py +165 -0
- package/.next/standalone/sdk/python/tests/test_spool_contract.py +287 -0
- package/.next/standalone/sdk/python/tests/test_spool_creation.py +360 -0
- package/.next/standalone/sdk/python/tests/test_wire_format.py +279 -0
- package/.next/standalone/sdk/python/tests/test_zero_dependencies.py +378 -0
- package/.next/standalone/sdk/python/uv.lock +6005 -0
- package/.next/standalone/server.js +1 -1
- package/README.md +77 -21
- package/bin/failproofai.mjs +145 -11
- package/dist/cli.mjs +4482 -2205
- package/dist/index.js +5 -5
- package/dist/worker.mjs +2399 -1978
- package/package.json +29 -22
- package/policy-pack/SHA256SUMS +2 -0
- package/policy-pack/failproofai-pack.json +732 -0
- package/policy-pack/failproofai-pack.mjs +2017 -0
- package/scripts/build-policy-pack.mjs +121 -0
- package/scripts/changelog-section.py +77 -0
- package/scripts/prune-standalone.mjs +3 -0
- package/scripts/python-version.py +232 -0
- package/scripts/translate-docs/cli.ts +21 -0
- package/scripts/translate-docs/mintlify-nav.ts +85 -13
- package/scripts/translate-docs/translator.ts +66 -11
- package/src/audit/cache.ts +40 -3
- package/src/audit/cli.ts +1 -1
- package/src/audit/index.ts +1 -1
- package/src/audit/replay.ts +89 -3
- package/src/audit/report.ts +5 -5
- package/src/audit/schedule-cli.ts +49 -53
- package/src/hooks/builtin-policies.ts +217 -579
- package/src/hooks/cloud-enrollment-cli.ts +66 -27
- package/src/hooks/cloud-managed-policies.ts +6 -1
- package/src/hooks/configure-wizard.ts +1 -1
- package/src/hooks/custom-hooks-loader.ts +89 -6
- package/src/hooks/fp-home.ts +92 -4
- package/src/hooks/fp-reset.ts +26 -2
- package/src/hooks/handler.ts +181 -11
- package/src/hooks/harness-cli.ts +79 -25
- package/src/hooks/hook-activity-store.ts +13 -3
- package/src/hooks/install-prompt.ts +25 -3
- package/src/hooks/manager.ts +418 -172
- package/src/hooks/migrations.ts +2 -2
- package/src/hooks/pack-cli.ts +505 -0
- package/src/hooks/pack-failclosed.ts +189 -0
- package/src/hooks/pack-manifest.ts +344 -0
- package/src/hooks/pack-store.ts +930 -0
- package/src/hooks/policy-catalog.ts +535 -0
- package/src/hooks/policy-evaluator.ts +24 -16
- package/src/hooks/policy-presets.ts +4 -2
- package/src/hooks/policy-registry.ts +8 -2
- package/src/hooks/policy-types.ts +26 -0
- package/src/hooks/session-pause-cli.ts +33 -9
- package/src/hooks/tui.ts +570 -0
- package/src/hooks/types.ts +15 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0_usx0j._.js +0 -3
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0_zk340._.js +0 -3
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0agdw2a._.js +0 -3
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0d1u_na._.js +0 -3
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0oy4kxb._.js +0 -3
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0zf034w._.js +0 -3
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1tvn4wf._.js +0 -3
- package/.next/standalone/.next/server/chunks/_0lxbzdq._.js +0 -3
- package/.next/standalone/.next/server/chunks/_1ger0a2._.js +0 -3
- package/.next/standalone/.next/server/chunks/_1zuiiy3._.js +0 -3
- package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_1iiwm5e._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0kc8_v5._.js +0 -4
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0kgy9da._.js +0 -4
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0mhqk5a._.js +0 -4
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0pltpn8._.js +0 -4
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0qkcyf-._.js +0 -4
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0w0x_ok._.js +0 -4
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1_dfocn._.js +0 -4
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1bfex62._.js +0 -5
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1kzapg5._.js +0 -6
- package/.next/standalone/.next/static/chunks/36fw6yk1s6x_f.js +0 -1
- package/.next/standalone/.next/static/chunks/3tzq0260n17ae.js +0 -6
- package/.next/standalone/.next/static/chunks/3wq9x0c-7ld5d.css +0 -2
- /package/.next/standalone/.next/static/{ZklXxyA5ygsWSQz2u_zii → nwbyWT06Ud0XdXOrVJyvS}/_buildManifest.js +0 -0
- /package/.next/standalone/.next/static/{ZklXxyA5ygsWSQz2u_zii → nwbyWT06Ud0XdXOrVJyvS}/_clientMiddlewareManifest.js +0 -0
- /package/.next/standalone/.next/static/{ZklXxyA5ygsWSQz2u_zii → nwbyWT06Ud0XdXOrVJyvS}/_ssgManifest.js +0 -0
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
module.exports=[97610,e=>{"use strict";var t=e.i(89171),i=e.i(71809),n=e.i(50227),o=e.i(2157),s=e.i(12714),r=e.i(74533),a=e.i(60526);function l(e){return e?{decision:"allow",reason:e}:{decision:"allow"}}function c(e){return{decision:"deny",reason:e}}function d(e){return{decision:"instruct",reason:e}}let p="__FAILPROOFAI_POLICY_REGISTRY__",u="__FAILPROOFAI_POLICY_INDEX_CACHE__",m="failproofai";function f(e){return e.includes("/")?e:`${m}/${e}`}function h(e){globalThis[u]=e}function g(){let e=globalThis;return e[p]||(e[p]=[]),e[p]}var y=e.i(79857);let b={info:0,warn:1,error:2},w=(0,y.logsDir)(),k=!1,v="warn",N=!1,S=w;function T(e){return!function(){if(k)return;k=!0;let e=(process.env.FAILPROOFAI_LOG_LEVEL??"").toLowerCase();("info"===e||"warn"===e||"error"===e)&&(v=e);let t=(process.env.FAILPROOFAI_HOOK_LOG_FILE??"").trim();t&&(N=!0,"1"!==t&&"true"!==t&&(S=t))}(),b[e]>=b[v]}function P(e,t){process.stderr.write(`[failproofai:hook] ${e} ${t}
|
|
2
|
-
|
|
3
|
-
`;(0,o.appendFileSync)(i,r,"utf-8")}catch{}}function $(e){T("info")&&(P("INFO",e),E("INFO",e))}function C(e){T("warn")&&(P("WARN",e),E("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},x=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 A(e){return e.toolInput?.command??""}function R(e){return e.toolInput?.file_path??""}function O(e){return e.trim().split(/\s+/).map(e=>e.replace(/^['"]|['"]$/g,""))}let _=new Set(["&&","||","|",";"]),B=/[;&<>`$()\\]/,j=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/,D=[[/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"]],W=/(?:postgresql|postgres|mysql|mongodb(?:\+srv)?|redis|amqps?|smtps?):\/\/[^@\s]+@/,M=/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----/,U=/Authorization:\s*Bearer\s+[A-Za-z0-9\-._~+/]{20,}/i;[...D];let L=/\b(?:psql|mysql|sqlite3|pgcli|clickhouse-client)\b/,z=/\b(?:DROP\s+(?:TABLE|DATABASE|SCHEMA)|TRUNCATE\b)/i,F=/\bDELETE\s+FROM\b/i,H=/\bWHERE\b/i,q=/\bALTER\s+TABLE\b[\s\S]*\b(?:DROP\s+COLUMN|ADD\s+COLUMN|RENAME\s+(?:COLUMN|TO)|MODIFY\s+COLUMN)\b/i,J=/(?: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/,G=/(?:^|\s|;|&&|\|\|)(?:env|printenv)(?:\s|$|;|&&|\|)/,Y=/echo\s+.*\$\{?[A-Za-z_]/,Z=/(?:^|\s|;|&&|\|\|)export\s+\w+/,K=/\$env:[A-Za-z_]/i,Q=/(?:Get-ChildItem|dir|gci|ls)\s+Env:/i,V=/\[Environment\]::GetEnvironment/i,X=/echo\s+%[A-Za-z_]/i,ee=/(?:^|[\\/])\.env(?:\.|$)/,et=/\.env(?:\b|\s|$|\.)/,ei=/Start-Process\s+.*-Verb\s+RunAs/i,en=/(?:^|;|&&|\|\|)\s*runas\s/i,eo=/(?:curl|wget)\s.*\|\s*(?:sh|bash|zsh|dash|ksh|csh|tcsh|fish|ash)\b/,es=/[;&|\n\r(){}`]+/,er=new Set(["npx","bunx","pnpx","npm","pnpm","yarn","dlx","exec","run","node","bun","deno","env","command","builtin","nohup","setsid","time","timeout","nice","stdbuf","xargs","sudo","doas","sh","bash","zsh","dash","ksh","fish","ash"]),ea=/(?:^|\/)failproofai[^/]*$/,el=/^(?:config|configure|setup)$/,ec=/^--pause(?:=|$)/,ed=/^[A-Za-z_][A-Za-z0-9_]*=/,ep=/^\d+[a-z]*$/i;function eu(e){for(let t of e.split(es)){let e=t.split(/\s+/).filter(Boolean),i=0;for(;i<e.length;){let t=e[i];if(!(ed.test(t)||t.startsWith("-")||t.startsWith(">")||t.startsWith("<")||ep.test(t)||er.has(t.slice(t.lastIndexOf("/")+1))))break;i++}if(i>=e.length||!ea.test(e[i]))continue;let n=e.slice(i+1),o=n.findIndex(e=>el.test(e));if(-1!==o&&n.slice(o+1).some(e=>ec.test(e)))return!0}return!1}let em=/(?:Invoke-WebRequest|iwr|Invoke-RestMethod|irm)\s+.*\|\s*(?:Invoke-Expression|iex)/i,ef=/^-[a-zA-Z]*f[a-zA-Z]*$/,eh=["--force-with-lease","--force-if-includes"],eg=/\.(?:pem|key)$/,ey=/id_rsa/,eb=/credentials/,ew=/git\s+(commit|merge|rebase|cherry-pick)\b/,ek=/(?:^|;|&&|\|\||\|)\s*failproofai(?:\s|$)/,ev=/(?: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)/,eN=/\bgit\s+commit\b.*--amend\b/,eS=/\bgit\s+stash\s+(?:drop|clear)\b/,eT=/\bgit\s+add\s+(?:-A\b|--all\b|\.(?:\s|$|;|&&|\|\|))/,eP=/\bnpm\s+(?:install|i)\b(?=.*(?:\s-g\b|--global\b))/,eE=/\byarn\s+global\s+add\b/,e$=/\bpnpm\s+(?:add|install|i)\b(?=.*(?:\s-g\b|--global\b))/,eC=/\bbun\s+(?:install|add)\b(?=.*(?:\s-g\b|--global\b))/,eI=/\bcargo\s+install\b/,ex=/\bpip(?:3)?\s+install\b(?=.*(?:--user\b|--break-system-packages\b))/,eA={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/]},eR=/\bnohup\s+\S/,eO=/\bscreen\s+-[A-Za-z]*d[A-Za-z]*\b/,e_=/\btmux\s+(?:new-session|new)\b[^|&;]*-d\b/,eB=/\bdisown\b/,ej=/(?<![&|])\s?&\s*(?:$|#|;)/,eD=/(?:^|[;\n]|&&|\|\|?|&)\s*kubectl(?:\s|$)/,eW=/(?:^|[;\n]|&&|\|\|?|&)\s*(?:terraform|tofu)(?:\s|$)/,eM=/(?:^|[;\n]|&&|\|\|?|&)\s*aws(?:\s|$)/,eU=/(?:^|[;\n]|&&|\|\|?|&)\s*gcloud(?:\s|$)/,eL=/(?:^|[;\n]|&&|\|\|?|&)\s*az(?:\s|$)/,ez=/(?:^|[;\n]|&&|\|\|?|&)\s*helm(?:\s|$)/,eF=/(?:^|[;\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/,eH=new Map;function eq(e){try{let t=function(e){try{return(0,o.statSync)((0,n.join)(e,".git","HEAD")).mtimeMs}catch{return null}}(e),i=eH.get(e);if(i&&null!==t&&i.headMtimeMs===t)return i.branch||null;let s=(0,r.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}).trim();return null!==t&&(eH.size>=500&&eH.clear(),eH.set(e,{branch:s,headMtimeMs:t})),s||null}catch{return null}}function eJ(e,t){let i=O(e),n=O(t);return!(i.length<n.length||i.some(e=>_.has(e))||i.some(e=>B.test(e)))&&n.every((e,t)=>"*"===e||e===i[t])}let eG=/^-{1,2}c$/;function eY(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 eZ=/^(?:~[A-Za-z0-9_.-]*|\$HOME|\$\{HOME\})(?=$|\/)/,eK=/^(?:\/\S*\/)?rm$/,eQ=/^(?:\/\S*\/)?find$/,eV=/^-(?:exec|execdir|ok|okdir)$/,eX=/^-(?:[HLP]|D|O\d*)$/,e0=/^(?:-|\\?[(!])/,e1=["/tmp","/var/tmp"];function e3(e){let t=e.match(/^(?:~|\$HOME|\$\{HOME\})(?=$|\/)/);return t?(0,a.homedir)()+e.slice(t[0].length):e}function e8(e){return e.replace(/\/\*$/,"").replace(/\/+$/,"")}function e6(e){let t=e.replace(/^['"]|['"]$/g,"");if(""===t)return!1;let i=t.match(eZ);if(!i&&/^[$`]/.test(t))return!0;let n=i?t.slice(i[0].length):t.startsWith("/")?t:null;if(null===n)return!1;let o=e8(n).split("/").filter(Boolean);return!(!i&&e1.some(e=>`/${o.join("/")}`.startsWith(`${e}/`)))&&o.length<=2}function e2(e){let t=O(e),i=t.findIndex(e=>eQ.test(e));if(i>=0){let e=t.slice(i+1),n=e.findIndex(e=>eV.test(e));if(e.includes("-delete")||n>=0&&eK.test(e[n+1]??"")){let t=0;for(;t<e.length&&eX.test(e[t]);)t+="-D"===e[t]?2:1;let i=e.slice(t),n=i.findIndex(e=>e0.test(e));return n<0?i:i.slice(0,n)}}let n=t.findIndex(e=>eK.test(e));if(n>=0){let e=t.slice(n+1),i=e.filter(e=>/^-[^-]/.test(e)).join(""),o=e.filter(e=>/^--/.test(e)),s=/r/i.test(i)||o.some(e=>/^--recursive$/i.test(e)),r=/f/.test(i)||o.some(e=>/^--force$/i.test(e));if(s&&r)return e.filter(e=>!e.startsWith("-"))}return null}function e4(e){return e.split(/&&|\|\||[|;\n]/).map(e=>e.trim()).filter(e=>""!==e)}let e9=/(?:^|;|&&|\|\||\|)\s*(?:ls|find|cat|head|tail|less|more|wc|file|stat|tree|du)\s/;function e5(e,t,i){if("Bash"!==e.toolName)return l();let n=A(e);return!t.test(n)||(e.params?.allowPatterns??[]).some(e=>eJ(n,e))?l():c(i)}let e7=/\s*(?:&&|\|\||\||;)\s*/;function te(e){return e.session?.permissionMode==="plan"}let tt=[{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.",fn:function(e){let t=JSON.stringify(e.payload);return j.test(t)?{decision:"deny",reason:"JWT token detected in tool output",message:"[REDACTED: JWT token removed by failproofai]"}:l()},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.",fn:function(e){let t=JSON.stringify(e.payload);for(let[e,i]of D)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{C(`additionalPatterns: invalid regex "${i}", skipping`)}return l()},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.",fn:function(e){let t=JSON.stringify(e.payload);return W.test(t)?{decision:"deny",reason:"Database connection string with credentials detected in tool output",message:"[REDACTED: connection string removed by failproofai]"}:l()},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.",fn:function(e){let t=JSON.stringify(e.payload);return M.test(t)?{decision:"deny",reason:"Private key content detected in tool output",message:"[REDACTED: private key content removed by failproofai]"}:l()},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",fn:function(e){let t=JSON.stringify(e.payload);return U.test(t)?{decision:"deny",reason:"Bearer token detected in tool output",message:"[REDACTED: Bearer token removed by failproofai]"}:l()},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",fn:function(e){if("Bash"!==e.toolName)return l();let t=A(e);return G.test(t)?c("Command reads environment variables"):Y.test(t)?c("Command echoes environment variable"):Z.test(t)?c("Command exports environment variable"):K.test(t)?c("Command reads environment variable via PowerShell"):Q.test(t)?c("Command reads environment variables via PowerShell"):V.test(t)?c("Command reads environment variable via .NET"):X.test(t)?c("Command echoes environment variable via cmd"):l()},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",fn:function(e){let t=A(e),i=R(e);return i&&ee.test(i)?c("Access to .env file blocked"):"Bash"===e.toolName&&et.test(t)?c("Command references .env file"):l()},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",fn:function(e){let t=process.env.CLAUDE_PROJECT_DIR||e.session?.cwd;if(!t)return l();let i=e.params?.allowPaths??[];if("Bash"===e.toolName){let o=A(e);if(!e9.test(o))return l();let s=function(e){let t,i=[],o=/(?<![a-zA-Z0-9_.\-~\\*?:=])(?:~\/[^\s;|&"'()\[\]{}]*|~(?=\s|$|[;|&"'()\[\]{}])|\/[^\s;|&"'()\[\]{}]*)/g;function s(e){let t;for(o.lastIndex=0;null!==(t=o.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 r=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){r=t;break}}else c=!c;else l=!l}let d=e.slice(0,r),p=/"([^"]*)"|'([^']*)'/g;for(;null!==(t=p.exec(d));){let e=t[1]??t[2]??"";/[*?\[\]^$+()\\]/.test(e)||s(e)}return s(e.replace(/"[^"]*"/g,e=>" ".repeat(e.length)).replace(/'[^']*'/g,e=>" ".repeat(e.length))),i}(o),r=t.endsWith("/")?t:t+"/";for(let e of s){let o=(0,n.resolve)(t,e);if(x(o))return c(`Reading agent settings file blocked: ${o}`);if(!I(o)&&"/dev/null"!==o&&o!==t&&!o.startsWith(r)){if(i.some(e=>o===e||o.startsWith(e.endsWith("/")?e:e+"/")))continue;return c(`Bash read outside project directory blocked: ${o}`)}}return l()}let o=R(e),s=e.toolInput?.path??"",r=o||s;if(!r)return l();let d=(0,n.resolve)(t,r);if(x(d))return c(`Reading agent settings file blocked: ${d}`);if(I(d)||"/dev/null"===d)return l();let p=t.endsWith("/")?t:t+"/";return d===t||d.startsWith(p)?l():i.some(e=>d===e||d.startsWith(e.endsWith("/")?e:e+"/"))?l():c(`Access outside project directory blocked: ${d}`)},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-self-pause",displayTitle:"Tried to pause failproofai enforcement",impact:"An agent that can pause enforcement can switch off every other policy.",description:"Block agents from pausing failproofai enforcement",fn:function(e){if("Bash"!==e.toolName)return l();let t=A(e);return eu(t)||eu(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,""))?c("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."):l()},match:{events:["PreToolUse","PermissionRequest"],toolNames:["Bash"]},defaultEnabled:!0,category:"Dangerous Commands"},{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",fn:function(e){if("Bash"!==e.toolName)return l();let t=A(e).trimStart();return function e(t,i=0){for(let n of function(e){let t=[],i=[],n="",o=null,s=()=>{n&&i.push(n),n=""},r=()=>{s(),i.length&&t.push(i),i=[]};for(let t=0;t<e.length;t++){let i=e[t];if(o){if("\\"===i&&'"'===o&&t+1<e.length){n+=e[++t];continue}if(i===o){o=null;continue}n+=i;continue}if("\\"===i&&t+1<e.length){n+=e[++t];continue}if('"'===i||"'"===i){o=i;continue}if(/\s/.test(i)){s();continue}if(/[;&|\n\r(){}`]/.test(i)){r();continue}n+=i}return r(),t}(t)){let t=0;for(;t<n.length;){let o=n[t],s=o.slice(o.lastIndexOf("/")+1);if("sudo"===s||"doas"===s)return!0;if(!(ed.test(o)||o.startsWith("-")||o.startsWith(">")||o.startsWith("<")||ep.test(o)||er.has(s)))break;if(eG.test(o)&&i<3&&t+1<n.length&&e(n[t+1],i+1))return!0;t++}}return!1}(t)?(e.params?.allowPatterns??[]).some(e=>eJ(t,e))?l():c("sudo commands are blocked"):ei.test(t)?c("Elevated process launch is blocked"):en.test(t)?c("runas elevation is blocked"):l()},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",fn:function(e){if("Bash"!==e.toolName)return l();let t=A(e);return eo.test(t)?c("Piping downloads to shell is blocked"):em.test(t)?c("Piping downloads to Invoke-Expression is blocked"):l()},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",fn:function(e){if("Bash"!==e.toolName)return l();let t=A(e);return e4(t).some(e=>{let t=e2(e);return null!==t&&t.some(e6)})?!function(e,t){if(0===t.length)return!1;let i=t.map(e=>e8(e3(e))||"/"),n=!1;for(let o of e4(e)){let e=e2(o);if(null!==e)for(let s of(n=!0,e)){let e=e8(e3(s))||"/";if(!i.some(t=>e===t||e.startsWith(t+"/"))&&!t.some(e=>{let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return RegExp(`${t}(?:[/"'\\s/*]|$)`).test(o)}))return!1}}return n}(t,e.params?.allowPaths??[])?c("Catastrophic deletion blocked"):l():/Remove-Item\s+.*-Recurse.*-Force.*(?:[A-Z]:\\(?:\s|$)|\\\*)/i.test(t)||/(?:rd|rmdir)\s+\/s\s+\/q\s+[A-Z]:\\/i.test(t)?c("Catastrophic deletion blocked"):l()},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 or modify failproofai itself",impact:"Prevents the agent from turning off the policies that protect you.",description:"Block failproofai CLI commands and uninstallation",fn:function(e){if("Bash"!==e.toolName)return l();let t=A(e);return ek.test(t)?c("Running failproofai CLI commands is blocked"):ev.test(t)?c("Uninstalling failproofai is blocked"):l()},match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!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)",fn:function(e){return e5(e,eD,"kubectl commands are blocked")},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",fn:function(e){return e5(e,eW,"terraform/tofu commands are blocked")},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",fn:function(e){return e5(e,eM,"aws CLI commands are blocked")},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",fn:function(e){return e5(e,eU,"gcloud commands are blocked")},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",fn:function(e){return e5(e,eL,"az (Azure) CLI commands are blocked")},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",fn:function(e){return e5(e,ez,"helm commands are blocked")},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)",fn:function(e){return e5(e,eF,"gh pipeline-trigger commands are blocked")},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",fn:function(e){if("Write"!==e.toolName)return l();let t=R(e);if(eg.test(t)||ey.test(t)||eb.test(t))return c("Writing secret key files is blocked");for(let i of e.params?.additionalPatterns??[])if(t.includes(i))return c(`Writing blocked file pattern: ${i}`);return l()},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",fn:function(e){if("Bash"!==e.toolName)return l();let t=e.params?.protectedBranches??["main","master"];if(0===t.length)return l();let i=eY(A(e)),n=RegExp(`\\b(?:${t.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")})\\b`);return i.some(e=>n.test(e))?c(`Pushing to ${t.join("/")} is blocked`):l()},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",fn:function(e){if("Bash"!==e.toolName)return l();for(let t of eY(A(e))){let e=!1;for(let i of t.split(/\s+/)){if("--"===i){e=!0;continue}if(!e&&function(e){return"--force"===e||!eh.some(t=>e.startsWith(t))&&(!!e.startsWith("--force")||ef.test(e))}(i))return c("Force-pushing is blocked")}}return l()},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",fn:function(e){if("Bash"!==e.toolName)return l();let t=A(e).match(ew);if(!t)return l();let i=e.session?.cwd;if(!i)return l();let n=eq(i);return n&&(e.params?.protectedBranches??["main","master"]).includes(n)?c(`Git ${t[1]} on ${n} is blocked. Create a feature branch first.`):l()},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",fn:function(e){if("Bash"!==e.toolName)return l();let t=A(e);return eN.test(t)?d("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."):l()},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",fn:function(e){if("Bash"!==e.toolName)return l();let t=A(e);return eS.test(t)?d("STOP: This command permanently deletes stashed changes (git stash drop/clear). Stash entries cannot be recovered after deletion. Confirm with the user before executing."):l()},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",fn:function(e){if("Bash"!==e.toolName)return l();let t=A(e);return eT.test(t)?d("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."):l()},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",fn:function(e){if("Bash"!==e.toolName)return l();let t=A(e);return L.test(t)&&(z.test(t)||F.test(t)&&!H.test(t))?d("STOP: This command contains destructive SQL (DROP/TRUNCATE/DELETE). Confirm with the user before executing."):l()},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)",fn:function(e){if("Bash"!==e.toolName)return l();let t=A(e);return L.test(t)&&q.test(t)?d("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."):l()},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.)",fn:function(e){if("Bash"!==e.toolName)return l();let t=A(e);return J.test(t)?d("STOP: This command publishes a package to a public registry. Confirm with the user that this is intentional."):l()},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.)",fn:function(e){if("Bash"!==e.toolName)return l();let t=A(e);return eP.test(t)||eE.test(t)||e$.test(t)||eC.test(t)||eI.test(t)||ex.test(t)?d("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."):l()},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)",fn:function(e){if("Bash"!==e.toolName)return l();let t=A(e);if(!t)return l();let i=e.params?.allowed??[];if(0===i.length)return l();let n=new Set(i.map(e=>e.toLowerCase())),o=e.params?.blocked??[],s=i.join(", ");for(let e of t.split(e7)){let t=e.trim();if(!t)continue;let i=!1;for(let e of n){let n=eA[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(eA))if(!n.has(e)){for(let n of i)if(n.test(t))return c(`"${e}" is not an allowed package manager. Allowed package managers for this project: ${s}. Rewrite this command using an allowed package manager.`)}for(let e of o){let i=e.toLowerCase();if(!n.has(i)&&RegExp(`\\b${i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`).test(t))return c(`"${i}" is not an allowed package manager. Allowed package managers for this project: ${s}. Rewrite this command using an allowed package manager.`)}}}return l()},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)",fn:function(e){if("Write"!==e.toolName)return l();let t=e.toolInput?.content;if("string"!=typeof t)return l();let i=e.params?.thresholdKb??1024;return t.length>1024*i?d(`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.`):l()},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",fn:function(e){if("Bash"!==e.toolName)return l();let t=A(e);return eR.test(t)||eO.test(t)||e_.test(t)||eB.test(t)||ej.test(t)?d("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."):l()},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",fn:async function e(e){let t=e.session?.transcriptPath;if(!t||!e.toolName||!e.toolInput)return l();let i=`${t}.tool-calls.json`,n=JSON.stringify({tool:e.toolName,input:e.toolInput}),o={};try{let e=await (0,s.readFile)(i,"utf8");o=JSON.parse(e)}catch{}let r=o[n]??0;if(r>=3)return d(`STOP: You have already called ${e.toolName} ${r} times with identical parameters. This is wasteful and unproductive. Do NOT repeat this call — use a different approach or ask the user for clarification.`);o[n]=r+1;try{let e=JSON.stringify(o);e.length<=65536&&await (0,s.writeFile)(i,e,"utf8")}catch{}return l()},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",fn:function(e){if(te(e))return l("Plan mode — no changes made, skipping commit check.");let t=e.session?.cwd;if(!t)return l("No working directory available, skipping commit check.");try{if((0,r.execSync)("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().length>0)return c("You have uncommitted changes in the working directory. Commit all changes now.");return l("All changes are committed.")}catch{return l("Not a git repository, skipping commit check.")}},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",fn:function(e){if(te(e))return l("Plan mode — no changes made, skipping push check.");let t=e.session?.cwd;if(!t)return l("No working directory available, skipping push check.");try{if(!(0,r.execSync)("git remote",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}).trim())return l("No git remote configured, skipping push check.");let i=e.params?.remote??"origin",n=eq(t);if(!n||"HEAD"===n)return l("Detached HEAD, skipping push check.");let o=e.params?.baseBranch??"main";if(n===o)return l(`On base branch "${o}", skipping push check.`);try{if(!(0,r.execFileSync)("git",["log",`${i}/${o}..HEAD`,"--oneline"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return l(`No commits ahead of ${i}/${o}, skipping push check.`);if(!(0,r.execFileSync)("git",["diff","--stat",`${i}/${o}`,"HEAD"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return l(`No file changes compared to ${i}/${o}, skipping push check.`)}catch{}let s=!1;try{(0,r.execFileSync)("git",["rev-parse","--verify",`${i}/${n}`],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}),s=!0}catch{}if(!s)return c(`Branch "${n}" has not been pushed to remote "${i}". Run now: git push -u ${i} ${n}`);let a=(0,r.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 c(`You have ${e} unpushed commit${e>1?"s":""} on branch "${n}". Run now: git push`)}return l(`All commits pushed to "${i}".`)}catch{return l("Could not check push status, skipping.")}},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",fn:function(e){if(te(e))return l("Plan mode — no changes made, skipping PR check.");let t=e.session?.cwd;if(!t)return l("No working directory available, skipping PR check.");try{let i;try{(0,r.execSync)("gh --version",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3})}catch{return l("GitHub CLI (gh) not installed, skipping PR check.")}let n=eq(t);if(!n||"HEAD"===n)return l("Detached HEAD, skipping PR check.");let o=e.params?.baseBranch??"main";if(n===o)return l(`On base branch "${o}", skipping PR check.`);try{if(!(0,r.execFileSync)("git",["log",`origin/${o}..HEAD`,"--oneline"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return l(`No commits ahead of origin/${o}, skipping PR check.`);if(!(0,r.execFileSync)("git",["diff","--stat",`origin/${o}`,"HEAD"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return l(`No file changes compared to origin/${o}, skipping PR check.`)}catch{}try{i=(0,r.execSync)("gh pr view --json number,url,state",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim()}catch{return c(`No pull request found for branch "${n}". Run now: gh pr create`)}let s=JSON.parse(i);if("OPEN"===s.state)return l(`PR #${s.number} exists: ${s.url}`);if("MERGED"===s.state)return l(`PR #${s.number} was merged: ${s.url}. Switch off this branch (e.g. 'git checkout ${o} && git pull') before stopping again.`);return c(`Pull request for branch "${n}" is ${s.state.toLowerCase()}. Run now: gh pr create`)}catch{return l("Could not check PR status, skipping.")}},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",fn:function(e){let t,i;if(te(e))return l("Plan mode — no changes made, skipping conflict check.");let n=e.session?.cwd;if(!n)return l("No working directory available, skipping conflict check.");let o=eq(n);if(!o||"HEAD"===o)return l("Detached HEAD, skipping conflict check.");let s=e.params?.baseBranch??"main";if(o===s)return l(`On base branch "${s}", skipping conflict check.`);try{(0,r.execSync)("gh --version",{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3})}catch{return l("gh CLI not installed, skipping conflict check.")}try{t=(0,r.execSync)("gh pr view --json mergeable,number,url,state",{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim()}catch{return l("No pull request found for branch, skipping conflict check.")}try{i=JSON.parse(t)}catch{return l("Could not parse gh pr view output, skipping conflict check.")}if("OPEN"!==i.state)return l(`PR #${i.number} is ${i.state.toLowerCase()}; skipping conflict check.`);try{(0,r.execFileSync)("git",["rev-parse","--verify",`origin/${s}`],{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}),(0,r.execFileSync)("git",["log",`origin/${s}..HEAD`,"--oneline"],{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim()&&(0,r.execFileSync)("git",["merge-tree","--write-tree","--name-only",`origin/${s}`,"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 c(`Branch "${o}" has merge conflicts with ${s} in: ${n}. Rebase or merge origin/${s} now and resolve the conflicts.`)}}return"CONFLICTING"===i.mergeable?c(`PR #${i.number} has merge conflicts per GitHub (${i.url}). Rebase or merge origin/${s} now and resolve the conflicts.`):"UNKNOWN"===i.mergeable?c(`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.`):l(`PR #${i.number} merges cleanly per GitHub.`)},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)",fn:function(e){if(te(e))return l("Plan mode — no changes made, skipping CI check.");let t=e.session?.cwd;if(!t)return l("No working directory available, skipping CI check.");try{try{(0,r.execSync)("gh --version",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3})}catch{return l("GitHub CLI (gh) not installed, skipping CI check.")}let e=eq(t);if(!e||"HEAD"===e)return l("Detached HEAD, skipping CI check.");let i=function(e){try{return(0,r.execSync)("git rev-parse HEAD",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}).trim()||null}catch{return null}}(t),n=[];try{let o=(0,r.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(o&&"[]"!==o){let e=JSON.parse(o),t=i?e.filter(e=>e.headSha===i):e,s=new Set;n=t.filter(e=>!s.has(e.name)&&(s.add(e.name),!0))}}catch{}let o=[],s=[];i&&(o=function(e,t){try{let i=(0,r.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),s=function(e,t){try{let i=(0,r.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,...o,...s];if(0===a.length)return l(`No CI runs found for branch "${e}".`);let d=a.filter(e=>"completed"===e.status&&"success"!==e.conclusion&&"skipped"!==e.conclusion&&"cancelled"!==e.conclusion&&"neutral"!==e.conclusion);if(d.length>0){let t=d.map(e=>`"${e.name}"`).join(", ");return c(`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 c(`CI checks are still running on branch "${e}": ${t}. Wait for all checks to complete, then verify they pass.`)}return l(`All CI checks passed on branch "${e}".`)}catch{return l("Could not check CI status, skipping.")}},match:{events:["Stop"]},defaultEnabled:!1,category:"Workflow"}];function ti(e){if(!(0,o.existsSync)(e))return{};try{let t=(0,o.readFileSync)(e,"utf8");return JSON.parse(t)}catch(t){return C(`failed to parse config at ${e}: ${t instanceof Error?t.message:String(t)}`),{}}}let tn=["claude","codex","copilot","cursor","opencode","pi","hermes","openclaw","factory","devin","antigravity","goose"],to={apply_patch:"Edit",write_stdin:"Bash"},ts={terminal:"Bash",bash:"Bash",read_file:"Read",write_file:"Write",patch:"Edit",web_search:"WebSearch",web_extract:"WebFetch",search_files:"Grep",todo:"TodoWrite"},tr={Read:{path:"file_path"},Write:{path:"file_path"},Edit:{path:"file_path"}},ta={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"},tl={Read:{path:"file_path"},Write:{path:"file_path",file_text:"content"},Edit:{path:"file_path",old_str:"old_string",new_str:"new_string"}},tc={Shell:"Bash"},td={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"},tp={Read:{filePath:"file_path"},Write:{filePath:"file_path"},Edit:{filePath:"file_path",oldString:"old_string",newString:"new_string",replaceAll:"replace_all"}},tu={bash:"Bash",read:"Read",write:"Write",edit:"Edit",glob:"Glob",grep:"Grep"},tm={Read:{path:"file_path"},Write:{path:"file_path"},Edit:{path:"file_path"}},tf={exec:"Bash",read:"Read",write:"Write",edit:"Edit",grep:"Grep",glob:"Glob",web_search:"WebSearch",web_fetch:"WebFetch"},th={Read:{path:"file_path"},Write:{path:"file_path"},Edit:{path:"file_path"}},tg={Execute:"Bash",Read:"Read",Edit:"Edit",Create:"Write",Grep:"Grep",Glob:"Glob",LS:"LS",FetchUrl:"WebFetch",WebSearch:"WebSearch",TodoWrite:"TodoWrite",Task:"Task"},ty={exec:"Bash"},tb={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"},tw={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"}},tk={shell:"Bash",write:"Write",edit:"Edit",view:"Read",read_image:"Read",glob:"Glob",grep:"Grep",tree:"LS",delegate:"Task",todo__todo_write:"TodoWrite"},tv={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 tN=e.i(81580);let tS=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;var tT=e.i(54214);function tP(e,t){let i=[];for(let o of e)if("assistant"===o.type)for(let e of o.message.content){var n;let s;if("tool_use"!==e.type)continue;let r=e.name,a=(n=t.cli,(r?"copilot"===n?ta[r]??r:"cursor"===n?tc[r]??r:"codex"===n?to[r]??r:"opencode"===n?td[r]??r:"pi"===n?tu[r]??r:"hermes"===n?ts[r]??r:"openclaw"===n?tf[r]??r:"factory"===n?tg[r]??r:"devin"===n?ty[r]??r:"antigravity"===n?tb[r]??r:"goose"===n?tk[r]??r:r:r)??r),l=function(e,t,i){let n;if(!e||!t||"object"!=typeof t||Array.isArray(t)||("copilot"===i?n=tl[e]:"opencode"===i?n=tp[e]:"pi"===i?n=tm[e]:"hermes"===i?n=tr[e]:"openclaw"===i?n=th[e]:"antigravity"===i?n=tw[e]:"goose"===i&&(n=tv[e]),!n))return t;let o={};for(let[e,i]of Object.entries(t))o[n[e]??e]=i;return o}(a,e.input,t.cli);e.result?.content&&(s=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:o.timestamp,toolName:a,rawToolName:r,toolInput:l??{},toolResultText:s})}return i}async function tE(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,s=[];for(let e of function(){let e,t=(0,tN.getClaudeProjectsPath)();try{e=(0,o.readdirSync)(t,{withFileTypes:!0})}catch{return[]}return e.filter(e=>e.isDirectory()).map(e=>({name:e.name,cwd:(0,tN.decodeFolderName)(e.name),path:(0,n.join)(t,e.name)}))}()){let r;if(!t||t.has(e.cwd)){try{r=function(e){let t,i=[];try{t=(0,o.readdirSync)(e.path,{withFileTypes:!0})}catch{return i}for(let s of t)if(s.isFile()&&s.name.endsWith(".jsonl")){let t=s.name.slice(0,-6);if(!tS.test(t))continue;let r=(0,n.join)(e.path,s.name);try{let n=(0,o.statSync)(r);i.push({projectName:e.name,cwd:e.cwd,sessionId:t,transcriptPath:r,mtimeMs:n.mtimeMs,sizeBytes:n.size,isSubagent:!1})}catch{}}else if(s.isDirectory()&&tS.test(s.name)){let t,r=(0,n.join)(e.path,s.name,"subagents");if(!(0,o.existsSync)(r))continue;try{t=(0,o.readdirSync)(r,{withFileTypes:!0})}catch{continue}for(let s of t){if(!s.isFile()||!s.name.endsWith(".jsonl"))continue;let t=s.name.slice(0,-6),a=(0,n.join)(r,s.name);try{let n=(0,o.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 r)t.mtimeMs<i||s.push({cli:"claude",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.transcriptPath,mtimeMs:t.mtimeMs,sizeBytes:t.sizeBytes})}}return s}async function t$(e){let t,i;try{t=await (0,s.readFile)(e.transcriptPath,"utf-8")}catch{return[]}try{i=await (0,tT.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 tP(i,{cli:"claude",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:n})}var tC=e.i(36203),tI=e.i(57232);async function tx(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tC.getCodexProjects)())){let{cwd:s,sessions:r}=await (0,tC.getCodexSessionsByEncodedName)(e.name),a=s??"";if(!t||t.has(a))for(let t of r){let s=t.lastModified.getTime();if(s<i)continue;let r=0;try{r=(0,o.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"codex",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:s,sizeBytes:r})}}return n}async function tA(e){let t=await (0,tI.getCodexSessionLog)(e.sessionId);return t?tP(t.entries,{cli:"codex",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tR=e.i(55851),tO=e.i(78166);async function t_(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tR.getCopilotProjects)())){let{cwd:s,sessions:r}=await (0,tR.getCopilotSessionsByEncodedName)(e.name),a=s??"";if(!t||t.has(a))for(let t of r){let s=t.lastModified.getTime();if(s<i)continue;let r=0;try{r=(0,o.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"copilot",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:s,sizeBytes:r})}}return n}async function tB(e){let t=await (0,tO.getCopilotSessionLog)(e.sessionId);return t?tP(t.entries,{cli:"copilot",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tj=e.i(46413),tD=e.i(72094);async function tW(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tj.getCursorProjects)())){let{cwd:s,sessions:r}=await (0,tj.getCursorSessionsByEncodedName)(e.name),a=s??"";if(!t||t.has(a))for(let t of r){let s=t.lastModified.getTime();if(s<i)continue;let r=0;try{r=(0,o.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"cursor",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:s,sizeBytes:r})}}return n}async function tM(e){let t=await (0,tD.getCursorSessionLog)(e.sessionId);return t?tP(t.entries,{cli:"cursor",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tU=e.i(35435),tL=e.i(99440);async function tz(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tU.getOpenCodeProjects)())){let{cwd:o,sessions:s}=await (0,tU.getOpenCodeSessionsByEncodedName)(e.name),r=o??"";if(!t||t.has(r))for(let t of s){let o=t.lastModified.getTime();!(o<i)&&t.sessionId&&n.push({cli:"opencode",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:o,sizeBytes:0})}}return n}async function tF(e){let t=await (0,tL.getOpenCodeSessionLog)(e.sessionId);return t?tP(t.entries,{cli:"opencode",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tH=e.i(19791),tq=e.i(85116);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.getPiProjects)())){let{cwd:s,sessions:r}=await (0,tH.getPiSessionsByEncodedName)(e.name),a=s??"";if(!t||t.has(a))for(let t of r){let s=t.lastModified.getTime();if(s<i)continue;let r=0;try{r=(0,o.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"pi",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:s,sizeBytes:r})}}return n}async function tG(e){let t=await (0,tq.getPiSessionLog)(e.sessionId);return t?tP(t.entries,{cli:"pi",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tY=e.i(64828),tZ=e.i(28898),tK=e.i(3605);async function tQ(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=await (0,tY.getHermesSessions)(),o=[];for(let e of n)!(e.mtimeMs<i)&&(!(e.messageCount<=0)||e.hasMessages)&&(!t||e.cwd&&t.has(e.cwd))&&o.push({cli:"hermes",projectName:e.cwd?(0,tN.encodeFolderName)(e.cwd):e.source?(0,tZ.hermesProjectPath)(e.profile,e.source):`hermes:${e.profile}`,sessionId:e.sessionId,transcriptPath:`hermes://${e.sessionId}`,mtimeMs:e.mtimeMs,sizeBytes:e.messageCount});return o}async function tV(e){let t=await (0,tK.getHermesSessionLog)(e.sessionId);return t?tP(t.entries,{cli:"hermes",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tX=e.i(90624),t0=e.i(64199);async function t1(e={}){if(e.projects&&e.projects.length>0)return[];let t=e.sinceMs??0,i=[];for(let e of(await (0,tX.getOpenClawSessions)()))e.mtimeMs<t||i.push({cli:"openclaw",projectName:(0,tX.openClawProjectPath)(e.agentId,e.channel),sessionId:e.sessionId,transcriptPath:e.transcriptPath,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes});return i}async function t3(e){let t=await (0,t0.getOpenClawSessionLog)(e.sessionId);return t?tP(t.entries,{cli:"openclaw",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var t8=e.i(28246);async function t6(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(0,t8.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 t2(e){let t;try{t=await (0,s.readFile)(e.transcriptPath,"utf-8")}catch{return[]}let i=(0,tT.parseRawLines)(t,"session"),n=(0,t8.factoryLinesToLogEntries)(i,"session"),o="";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){o=t;break}}return tP(n,{cli:"factory",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:o})}var t4=e.i(93114),t9=e.i(30441);async function t5(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[],o=await (0,t9.getAntigravityIndex)();for(let e of(0,t4.listAntigravityTranscripts)()){if(e.mtimeMs<i)continue;let s=o.get(e.conversationId)?.cwd;(!t||s&&t.has(s))&&n.push({cli:"antigravity",projectName:s?(0,tN.encodeFolderName)(s):"antigravity",sessionId:e.conversationId,transcriptPath:e.transcriptPath,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes})}return n}async function t7(e){let t;try{t=await (0,s.readFile)(e.transcriptPath,"utf-8")}catch{return[]}let i=(0,tT.parseRawLines)(t,"session"),n=(0,t4.antigravityLinesToLogEntries)(i,"session"),o="";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){o=i;break}}if(o)break}}return tP(n,{cli:"antigravity",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:o})}var ie=e.i(79364),it=e.i(40375);async function ii(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=await (0,ie.getDevinSessions)(),o=[];for(let e of n)!(e.mtimeMs<i)&&(!t||e.cwd&&t.has(e.cwd))&&o.push({cli:"devin",projectName:e.projectName,sessionId:e.sessionId,transcriptPath:`devin-db://${e.sessionId}`,mtimeMs:e.mtimeMs,sizeBytes:0});return o}async function io(e){let t=await (0,it.getDevinSessionLog)(e.sessionId);return t?tP(t.entries,{cli:"devin",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var is=e.i(69164),ir=e.i(36618);let ia={claude:{cli:"claude",listTranscripts:tE,streamEvents:t$},codex:{cli:"codex",listTranscripts:tx,streamEvents:tA},copilot:{cli:"copilot",listTranscripts:t_,streamEvents:tB},cursor:{cli:"cursor",listTranscripts:tW,streamEvents:tM},opencode:{cli:"opencode",listTranscripts:tz,streamEvents:tF},pi:{cli:"pi",listTranscripts:tJ,streamEvents:tG},hermes:{cli:"hermes",listTranscripts:tQ,streamEvents:tV},openclaw:{cli:"openclaw",listTranscripts:t1,streamEvents:t3},factory:{cli:"factory",listTranscripts:t6,streamEvents:t2},devin:{cli:"devin",listTranscripts:ii,streamEvents:io},antigravity:{cli:"antigravity",listTranscripts:t5,streamEvents:t7},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)(),o=[];for(let e of n)!(e.mtimeMs<i)&&(!t||e.cwd&&t.has(e.cwd))&&o.push({cli:"goose",projectName:e.projectName,sessionId:e.sessionId,transcriptPath:`goose-db://${e.sessionId}`,mtimeMs:e.mtimeMs,sizeBytes:0});return o},streamEvents:async function(e){let t=await (0,ir.getGooseSessionLog)(e.sessionId);return t?tP(t.entries,{cli:"goose",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}}},il=/\.(?: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,ic=["/","/home","/usr","/etc","/var","/opt","/Users"],id="rereadAfterEdit",ip=[{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 o=(n[1]??n[2]??n[3]??"").replace(/\/+$/,"");if(o!==e.cwd.replace(/\/+$/,""))return null;let s=n[4].trim();return{example:`cd ${o} && ${s}`}}},{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 o=n[2]??n[3]??n[4]??"";return!o||/(?:^|\/)\.env(?:\..+)?$/.test(o)||!il.test(o)?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 o=n[1].replace(/^["']|["']$/g,"").replace(/\/+$/,"")||"/";return ic.includes(o)?{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[id])||(i={countdown:new Map},t[id]=i),i),o=e.toolInput.file_path,s="string"==typeof o?o:null;for(let[e,t]of n.countdown)t<=1?n.countdown.delete(e):n.countdown.set(e,t-1);return s?"Edit"===e.toolName||"Write"===e.toolName?(n.countdown.set(s,5),null):"Read"===e.toolName&&n.countdown.has(s)?(n.countdown.delete(s),{example:`Read ${s} immediately after Edit/Write`}):null:null}}],iu=["cowboy","explorer","ghost","optimist","hammer","architect"],im={explorer:.38,architect:.33,hammer:.11,cowboy:.11,optimist:.07,ghost:.01,precision:0,goldfish:0},ih={optimist:0,cowboy:0,explorer:0,goldfish:0,architect:0,precision:0,hammer:0,ghost:0};for(let e of iu)ih[e]=Math.max(im[e],.05);var ig=e.i(66680);let iy=null,ib=null;function iw(){if(iy)return iy;let e=tt.map(e=>`${e.name}|${e.fn.toString()}`).sort().join("\n");return iy=(0,ig.createHash)("sha1").update(e).digest("hex").slice(0,16)}function ik(){if(ib)return ib;let e=ip.map(e=>`${e.name}|${e.detect.toString()}`).sort().join("\n");return ib=(0,ig.createHash)("sha1").update(e).digest("hex").slice(0,16)}function iv(e){let t=(0,y.auditCacheDir)(),i=(0,ig.createHash)("sha1").update(e).digest("hex");return(0,n.join)(t,`${i}.json`)}var iN=e.i(24214),iS=e.i(28067),iT=e.i(17694);let iP=iS.POSTHOG_API_KEY,iE=new Set;async function i$(e,t,i){let n=JSON.stringify({api_key:process.env.FAILPROOFAI_POSTHOG_KEY??iP,event:t,distinct_id:e,properties:{...i,$lib:"failproofai-hooks",failproofai_version:iN.version,product:iS.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 iC(e,t,i){if(!(0,iT.isTelemetryEnabled)())return;let n=i$(e,t,i);iE.add(n),n.finally(()=>iE.delete(n)),await n}var iI=e.i(10659);function ix(e,t){let i=e.trim(),n="string"==typeof t?t.trim():"";return n?i?`${i}. ${n}`:n:i}let iA=new Map(tt.filter(e=>e.params).map(e=>[f(e.name),e.params]));function iR(e,t){if(!e?.policyParams)return;let i=e.policyParams[t];if(i)return i;let n=`${m}/`;if(t.startsWith(n))return e.policyParams[t.slice(n.length)]}async function iO(e,t,i,n){let o=t.tool_name,s=t.tool_input,r=function(e,t){let i=globalThis[u];i||h(i=new Map);let n=`${e}:${t??""}`,o=i.get(n);if(o)return o;let s=g().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,s),s}(e,o);if($(`evaluating ${r.length} policies for ${e}`),0===r.length)return{exitCode:0,stdout:"",stderr:"",policyName:null,reason:null,decision:"allow"};let a={eventType:e,payload:t,toolName:o,toolInput:s,session:i,cli:i?.cli},l=[],c=[];for(let t of r){let o,s,r=iA.get(t.name);if(r){let e=iR(n,t.name)??{},i={};for(let[t,n]of Object.entries(r))i[t]=t in e?e[t]:n.default;o={...a,params:i}}else o={...a,params:{}};try{s=await t.fn(o)}catch(o){let n=o instanceof Error?o.message:String(o);C(`policy "${t.name}" threw: ${n}`),t.name.startsWith("custom/")||t.name.startsWith(".failproofai-")||iC((0,iI.getInstanceId)(),"policy_evaluation_error",{policy_name:t.name,event_type:e,cli:i?.cli??null,error_type:o instanceof Error?o.name:"unknown"});continue}if("deny"===s.decision){let r,a=ix(s.reason??`Blocked by policy: ${t.name}`,iR(n,t.name)?.hint);$(`deny by "${t.name}": ${a}`),r=o.toolName?o.toolName:"UserPromptSubmit"===e?"prompt":"SessionStart"===e?"session start":"SessionEnd"===e?"session end":"Stop"===e?"stop":"operation";let l=`Blocked ${r} 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),o=e.i(2157),r=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]}function b(e,t,i,n,o=0,r){let s=h(e),a=y(),l=a.findIndex(e=>e.name===s),c={name:s,description:t,fn:i,match:n,priority:o,...r?{params:r}:{}};l>=0?a[l]=c:a.push(c),g(null)}var w=e.i(97348);let k=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},v=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 S(e){return e.toolInput?.file_path??""}function $(e){return e.trim().split(/\s+/).map(e=>e.replace(/^['"]|['"]$/g,""))}let T=new Set(["&&","||","|",";"]),E=/[;&<>`$()\\]/,C=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/,A=[[/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"]],P=/(?:postgresql|postgres|mysql|mongodb(?:\+srv)?|redis|amqps?|smtps?):\/\/[^@\s]+@/,I=/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----/,x=/Authorization:\s*Bearer\s+[A-Za-z0-9\-._~+/]{20,}/i;[...A];let R=/\b(?:psql|mysql|sqlite3|pgcli|clickhouse-client)\b/,O=/\b(?:DROP\s+(?:TABLE|DATABASE|SCHEMA)|TRUNCATE\b)/i,_=/\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,D=/(?: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/,W=/(?:^|\s|;|&&|\|\|)(?:env|printenv)(?:\s|$|;|&&|\|)/,M=/echo\s+.*\$\{?[A-Za-z_]/,U=/(?:^|\s|;|&&|\|\|)export\s+\w+/,z=/\$env:[A-Za-z_]/i,L=/(?:Get-ChildItem|dir|gci|ls)\s+Env:/i,F=/\[Environment\]::GetEnvironment/i,q=/echo\s+%[A-Za-z_]/i,H=/(?:^|[\\/])\.env(?:\.|$)/,J=/\.env(?:\b|\s|$|\.)/,G=/Start-Process\s+.*-Verb\s+RunAs/i,Z=/(?:^|;|&&|\|\|)\s*runas\s/i,Y=/(?:curl|wget)\s.*\|\s*(?:sh|bash|zsh|dash|ksh|csh|tcsh|fish|ash)\b/,K=/[;&|\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"]),V=/(?:^|\/)failproofai[^/]*$/,X=/failproofai\/(?:dist\/(?:cli|index)\.mjs|bin\/failproofai\.mjs)$/,ee=/^(?:config|configure|setup)$/,et=/^--pause(?:=|$)/,ei=/^[A-Za-z_][A-Za-z0-9_]*=/,en=/^\d+[a-z]*$/i;function eo(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,"");(V.test(t)||X.test(t))&&n.add(e)}let o=e=>{let t=/^\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?$/.exec(e);return!!t&&n.has(t[1])};for(let e of t.split(K)){let t=e.split(/\s+/).filter(Boolean),n=0;for(;n<t.length;){let e=t[n];if(!(ei.test(e)||e.startsWith("-")||e.startsWith(">")||e.startsWith("<")||en.test(e)||Q.has(e.slice(e.lastIndexOf("/")+1))))break;n++}if(n>=t.length||!V.test(t[n])&&!X.test(t[n])&&!o(t[n]))continue;let r=t.slice(n+1),s=r.findIndex(e=>ee.test(e));if(-1!==s&&r.slice(s+1).some(e=>et.test(e)))return"pause";i="cli"}return i}let er=/(?:Invoke-WebRequest|iwr|Invoke-RestMethod|irm)\s+.*\|\s*(?:Invoke-Expression|iex)/i,es=/^-[a-zA-Z]*f[a-zA-Z]*$/,ea=["--force-with-lease","--force-if-includes"],el=/\.(?:pem|key)$/,ec=/id_rsa/,ed=/credentials/,ep=/git\s+(commit|merge|rebase|cherry-pick)\b/,eu=/\b(?:rm|unlink|shred|mv|truncate)\b[^;&|]*\.failproofai(?:\/|\b)/,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)/,ef=/\bgit\s+commit\b.*--amend\b/,eh=/\bgit\s+stash\s+(?:drop|clear)\b/,eg=/\bgit\s+add\s+(?:-A\b|--all\b|\.(?:\s|$|;|&&|\|\|))/,ey=/\bnpm\s+(?:install|i)\b(?=.*(?:\s-g\b|--global\b))/,eb=/\byarn\s+global\s+add\b/,ew=/\bpnpm\s+(?:add|install|i)\b(?=.*(?:\s-g\b|--global\b))/,ek=/\bbun\s+(?:install|add)\b(?=.*(?:\s-g\b|--global\b))/,ev=/\bcargo\s+install\b/,eN=/\bpip(?:3)?\s+install\b(?=.*(?:--user\b|--break-system-packages\b))/,eS={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/,eT=/\bscreen\s+-[A-Za-z]*d[A-Za-z]*\b/,eE=/\btmux\s+(?:new-session|new)\b[^|&;]*-d\b/,eC=/\bdisown\b/,eA=/(?<![&|])\s?&\s*(?:$|#|;)/,eP=/(?:^|[;\n]|&&|\|\|?|&)\s*kubectl(?:\s|$)/,eI=/(?:^|[;\n]|&&|\|\|?|&)\s*(?:terraform|tofu)(?:\s|$)/,ex=/(?:^|[;\n]|&&|\|\|?|&)\s*aws(?:\s|$)/,eR=/(?:^|[;\n]|&&|\|\|?|&)\s*gcloud(?:\s|$)/,eO=/(?:^|[;\n]|&&|\|\|?|&)\s*az(?:\s|$)/,e_=/(?:^|[;\n]|&&|\|\|?|&)\s*helm(?:\s|$)/,ej=/(?:^|[;\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/,eB=new Map;function eD(e){try{let t=function(e){try{return(0,o.statSync)((0,n.join)(e,".git","HEAD")).mtimeMs}catch{return null}}(e),i=eB.get(e);if(i&&null!==t&&i.headMtimeMs===t)return i.branch||null;let r=(0,s.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}).trim();return null!==t&&(eB.size>=500&&eB.clear(),eB.set(e,{branch:r,headMtimeMs:t})),r||null}catch{return null}}function eW(e,t){let i=$(e),n=$(t);return!(i.length<n.length||i.some(e=>T.has(e))||i.some(e=>E.test(e)))&&n.every((e,t)=>"*"===e||e===i[t])}let eM=/^-{1,2}c$/;function eU(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 ez=/^(?:~[A-Za-z0-9_.-]*|\$HOME|\$\{HOME\})(?=$|\/)/,eL=/^(?:\/\S*\/)?rm$/,eF=/^(?:\/\S*\/)?find$/,eq=/^-(?:exec|execdir|ok|okdir)$/,eH=/^-(?:[HLP]|D|O\d*)$/,eJ=/^(?:-|\\?[(!])/,eG=["/tmp","/var/tmp"];function eZ(e){let t=e.match(/^(?:~|\$HOME|\$\{HOME\})(?=$|\/)/);return t?(0,a.homedir)()+e.slice(t[0].length):e}function eY(e){return e.replace(/\/\*$/,"").replace(/\/+$/,"")}function eK(e){let t=e.replace(/^['"]|['"]$/g,"");if(""===t)return!1;let i=t.match(ez);if(!i&&/^[$`]/.test(t))return!0;let n=i?t.slice(i[0].length):t.startsWith("/")?t:null;if(null===n)return!1;let o=eY(n).split("/").filter(Boolean);return!(!i&&eG.some(e=>`/${o.join("/")}`.startsWith(`${e}/`)))&&o.length<=2}function eQ(e){let t=$(e),i=t.findIndex(e=>eF.test(e));if(i>=0){let e=t.slice(i+1),n=e.findIndex(e=>eq.test(e));if(e.includes("-delete")||n>=0&&eL.test(e[n+1]??"")){let t=0;for(;t<e.length&&eH.test(e[t]);)t+="-D"===e[t]?2:1;let i=e.slice(t),n=i.findIndex(e=>eJ.test(e));return n<0?i:i.slice(0,n)}}let n=t.findIndex(e=>eL.test(e));if(n>=0){let e=t.slice(n+1),i=e.filter(e=>/^-[^-]/.test(e)).join(""),o=e.filter(e=>/^--/.test(e)),r=/r/i.test(i)||o.some(e=>/^--recursive$/i.test(e)),s=/f/.test(i)||o.some(e=>/^--force$/i.test(e));if(r&&s)return e.filter(e=>!e.startsWith("-"))}return null}function eV(e){return e.split(/&&|\|\||[|;\n]/).map(e=>e.trim()).filter(e=>""!==e)}let eX=/(?:^|;|&&|\|\||\|)\s*(?:ls|find|cat|head|tail|less|more|wc|file|stat|tree|du)\s/;function e0(e,t,i){if("Bash"!==e.toolName)return c();let n=N(e);return!t.test(n)||(e.params?.allowPatterns??[]).some(e=>eW(n,e))?c():d(i)}let e1=/\s*(?:&&|\|\||\||;)\s*/;function e3(e){return e.session?.permissionMode==="plan"}let e6={"sanitize-jwt":function(e){let t=JSON.stringify(e.payload);return C.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 A)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,w.hookLogWarn)(`additionalPatterns: invalid regex "${i}", skipping`)}return c()},"sanitize-connection-strings":function(e){let t=JSON.stringify(e.payload);return P.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 I.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 x.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 W.test(t)?d("Command reads environment variables"):M.test(t)?d("Command echoes environment variable"):U.test(t)?d("Command exports environment variable"):z.test(t)?d("Command reads environment variable via PowerShell"):L.test(t)?d("Command reads environment variables via PowerShell"):F.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=S(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 o=N(e);if(!eX.test(o))return c();let r=function(e){let t,i=[],o=/(?<![a-zA-Z0-9_.\-~\\*?:=])(?:~\/[^\s;|&"'()\[\]{}]*|~(?=\s|$|[;|&"'()\[\]{}])|\/[^\s;|&"'()\[\]{}]*)/g;function r(e){let t;for(o.lastIndex=0;null!==(t=o.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)||r(e)}return r(e.replace(/"[^"]*"/g,e=>" ".repeat(e.length)).replace(/'[^']*'/g,e=>" ".repeat(e.length))),i}(o),s=t.endsWith("/")?t:t+"/";for(let e of r){let o=(0,n.resolve)(t,e);if(v(o))return d(`Reading agent settings file blocked: ${o}`);if(!k(o)&&"/dev/null"!==o&&o!==t&&!o.startsWith(s)){if(i.some(e=>o===e||o.startsWith(e.endsWith("/")?e:e+"/")))continue;return d(`Bash read outside project directory blocked: ${o}`)}}return c()}let o=S(e),r=e.toolInput?.path??"",s=o||r;if(!s)return c();let l=(0,n.resolve)(t,s);if(v(l))return d(`Reading agent settings file blocked: ${l}`);if(k(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=N(e).trimStart();return function e(t,i=0){for(let n of function(e){let t=[],i=[],n="",o=null,r=()=>{n&&i.push(n),n=""},s=()=>{r(),i.length&&t.push(i),i=[]};for(let t=0;t<e.length;t++){let i=e[t];if(o){if("\\"===i&&'"'===o&&t+1<e.length){n+=e[++t];continue}if(i===o){o=null;continue}n+=i;continue}if("\\"===i&&t+1<e.length){n+=e[++t];continue}if('"'===i||"'"===i){o=i;continue}if(/\s/.test(i)){r();continue}if(/[;&|\n\r(){}`]/.test(i)){s();continue}n+=i}return s(),t}(t)){let t=0;for(;t<n.length;){let o=n[t],r=o.slice(o.lastIndexOf("/")+1);if("sudo"===r||"doas"===r)return!0;if(!(ei.test(o)||o.startsWith("-")||o.startsWith(">")||o.startsWith("<")||en.test(o)||Q.has(r)))break;if(eM.test(o)&&i<3&&t+1<n.length&&e(n[t+1],i+1))return!0;t++}}return!1}(t)?(e.params?.allowPatterns??[]).some(e=>eW(t,e))?c():d("sudo commands are blocked"):G.test(t)?d("Elevated process launch is blocked"):Z.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"):er.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 eV(t).some(e=>{let t=eQ(e);return null!==t&&t.some(eK)})?!function(e,t){if(0===t.length)return!1;let i=t.map(e=>eY(eZ(e))||"/"),n=!1;for(let o of eV(e)){let e=eQ(o);if(null!==e)for(let r of(n=!0,e)){let e=eY(eZ(r))||"/";if(!i.some(t=>e===t||e.startsWith(t+"/"))&&!t.some(e=>{let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return RegExp(`${t}(?:[/"'\\s/*]|$)`).test(o)}))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=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=eo(t)??eo(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"):eu.test(t)||eu.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 e0(e,eP,"kubectl commands are blocked")},"block-terraform":function(e){return e0(e,eI,"terraform/tofu commands are blocked")},"block-aws-cli":function(e){return e0(e,ex,"aws CLI commands are blocked")},"block-gcloud":function(e){return e0(e,eR,"gcloud commands are blocked")},"block-az-cli":function(e){return e0(e,eO,"az (Azure) CLI commands are blocked")},"block-helm":function(e){return e0(e,e_,"helm commands are blocked")},"block-gh-pipeline":function(e){return e0(e,ej,"gh pipeline-trigger commands are blocked")},"block-secrets-write":function(e){if("Write"!==e.toolName)return c();let t=S(e);if(el.test(t)||ec.test(t)||ed.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=eU(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 eU(N(e))){let e=!1;for(let i of t.split(/\s+/)){if("--"===i){e=!0;continue}if(!e&&function(e){return"--force"===e||!ea.some(t=>e.startsWith(t))&&(!!e.startsWith("--force")||es.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(ep);if(!t)return c();let i=e.session?.cwd;if(!i)return c();let n=eD(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 ef.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=N(e);return eh.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=N(e);return eg.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=N(e);return R.test(t)&&(O.test(t)||_.test(t)&&!j.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=N(e);return R.test(t)&&B.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=N(e);return D.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=N(e);return ey.test(t)||eb.test(t)||ew.test(t)||ek.test(t)||ev.test(t)||eN.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=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())),o=e.params?.blocked??[],r=i.join(", ");for(let e of t.split(e1)){let t=e.trim();if(!t)continue;let i=!1;for(let e of n){let n=eS[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(eS))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 o){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?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=N(e);return e$.test(t)||eT.test(t)||eE.test(t)||eC.test(t)||eA.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}),o={};try{let e=await (0,r.readFile)(i,"utf8");o=JSON.parse(e)}catch{}let s=o[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.`);o[n]=s+1;try{let e=JSON.stringify(o);e.length<=65536&&await (0,r.writeFile)(i,e,"utf8")}catch{}return c()},"require-commit-before-stop":function(e){if(e3(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(e3(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=eD(t);if(!n||"HEAD"===n)return c("Detached HEAD, skipping push check.");let o=e.params?.baseBranch??"main";if(n===o)return c(`On base branch "${o}", skipping push check.`);try{if(!(0,s.execFileSync)("git",["log",`${i}/${o}..HEAD`,"--oneline"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return c(`No commits ahead of ${i}/${o}, skipping push check.`);if(!(0,s.execFileSync)("git",["diff","--stat",`${i}/${o}`,"HEAD"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return c(`No file changes compared to ${i}/${o}, skipping push check.`)}catch{}let r=!1;try{(0,s.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,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(e3(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=eD(t);if(!n||"HEAD"===n)return c("Detached HEAD, skipping PR check.");let o=e.params?.baseBranch??"main";if(n===o)return c(`On base branch "${o}", skipping PR check.`);try{if(!(0,s.execFileSync)("git",["log",`origin/${o}..HEAD`,"--oneline"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return c(`No commits ahead of origin/${o}, skipping PR check.`);if(!(0,s.execFileSync)("git",["diff","--stat",`origin/${o}`,"HEAD"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return c(`No file changes compared to origin/${o}, 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 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 ${o} && 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(e3(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 o=eD(n);if(!o||"HEAD"===o)return c("Detached HEAD, skipping conflict check.");let r=e.params?.baseBranch??"main";if(o===r)return c(`On base branch "${r}", 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/${r}`],{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}),(0,s.execFileSync)("git",["log",`origin/${r}..HEAD`,"--oneline"],{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim()&&(0,s.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 "${o}" 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(e3(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=eD(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 o=(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(o&&"[]"!==o){let e=JSON.parse(o),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 o=[],r=[];i&&(o=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),r=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,...o,...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 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.")}}},e9=new Set(Object.keys(e6)),e2=l.filter(e=>!e9.has(e.name)).map(e=>e.name);if(e2.length>0)throw Error(`failproofai: builtin policies missing an implementation: ${e2.join(", ")}`);let e8=new Set(l.map(e=>e.name)),e4=[...e9].filter(e=>!e8.has(e));if(e4.length>0)throw Error(`failproofai: policy implementations with no catalog entry: ${e4.join(", ")}`);let e5=l.map(e=>({...e,fn:e6[e.name]}));var e7=e.i(73136);let te=["claude","codex","copilot","cursor","opencode","pi","hermes","openclaw","factory","devin","antigravity","goose"],tt={apply_patch:"Edit",write_stdin:"Bash"},ti={terminal:"Bash",bash:"Bash",read_file:"Read",write_file:"Write",patch:"Edit",web_search:"WebSearch",web_extract:"WebFetch",search_files:"Grep",todo:"TodoWrite"},tn={Read:{path:"file_path"},Write:{path:"file_path"},Edit:{path:"file_path"}},to={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"},tr={Read:{path:"file_path"},Write:{path:"file_path",file_text:"content"},Edit:{path:"file_path",old_str:"old_string",new_str:"new_string"}},ts={Shell:"Bash"},ta={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"},tl={Read:{filePath:"file_path"},Write:{filePath:"file_path"},Edit:{filePath:"file_path",oldString:"old_string",newString:"new_string",replaceAll:"replace_all"}},tc={bash:"Bash",read:"Read",write:"Write",edit:"Edit",glob:"Glob",grep:"Grep"},td={Read:{path:"file_path"},Write:{path:"file_path"},Edit:{path:"file_path"}},tp={exec:"Bash",read:"Read",write:"Write",edit:"Edit",grep:"Grep",glob:"Glob",web_search:"WebSearch",web_fetch:"WebFetch"},tu={Read:{path:"file_path"},Write:{path:"file_path"},Edit:{path:"file_path"}},tm={Execute:"Bash",Read:"Read",Edit:"Edit",Create:"Write",Grep:"Grep",Glob:"Glob",LS:"LS",FetchUrl:"WebFetch",WebSearch:"WebSearch",TodoWrite:"TodoWrite",Task:"Task"},tf={exec:"Bash"},th={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"},tg={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"}},ty={shell:"Bash",write:"Write",edit:"Edit",view:"Read",read_image:"Read",glob:"Glob",grep:"Grep",tree:"LS",delegate:"Task",todo__todo_write:"TodoWrite"},tb={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 tw=e.i(81580);let tk=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;var tv=e.i(54214);function tN(e,t){let i=[];for(let o of e)if("assistant"===o.type)for(let e of o.message.content){var n;let r;if("tool_use"!==e.type)continue;let s=e.name,a=(n=t.cli,(s?"copilot"===n?to[s]??s:"cursor"===n?ts[s]??s:"codex"===n?tt[s]??s:"opencode"===n?ta[s]??s:"pi"===n?tc[s]??s:"hermes"===n?ti[s]??s:"openclaw"===n?tp[s]??s:"factory"===n?tm[s]??s:"devin"===n?tf[s]??s:"antigravity"===n?th[s]??s:"goose"===n?ty[s]??s:s:s)??s),l=function(e,t,i){let n;if(!e||!t||"object"!=typeof t||Array.isArray(t)||("copilot"===i?n=tr[e]:"opencode"===i?n=tl[e]:"pi"===i?n=td[e]:"hermes"===i?n=tn[e]:"openclaw"===i?n=tu[e]:"antigravity"===i?n=tg[e]:"goose"===i&&(n=tb[e]),!n))return t;let o={};for(let[e,i]of Object.entries(t))o[n[e]??e]=i;return o}(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:o.timestamp,toolName:a,rawToolName:s,toolInput:l??{},toolResultText:r})}return i}async function tS(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,r=[];for(let e of function(){let e,t=(0,tw.getClaudeProjectsPath)();try{e=(0,o.readdirSync)(t,{withFileTypes:!0})}catch{return[]}return e.filter(e=>e.isDirectory()).map(e=>({name:e.name,cwd:(0,tw.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,o.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(!tk.test(t))continue;let s=(0,n.join)(e.path,r.name);try{let n=(0,o.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(r.isDirectory()&&tk.test(r.name)){let t,s=(0,n.join)(e.path,r.name,"subagents");if(!(0,o.existsSync)(s))continue;try{t=(0,o.readdirSync)(s,{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)(s,r.name);try{let n=(0,o.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||r.push({cli:"claude",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.transcriptPath,mtimeMs:t.mtimeMs,sizeBytes:t.sizeBytes})}}return r}async function t$(e){let t,i;try{t=await (0,r.readFile)(e.transcriptPath,"utf-8")}catch{return[]}try{i=await (0,tv.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 tN(i,{cli:"claude",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:n})}var tT=e.i(36203),tE=e.i(57232);async function tC(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tT.getCodexProjects)())){let{cwd:r,sessions:s}=await (0,tT.getCodexSessionsByEncodedName)(e.name),a=r??"";if(!t||t.has(a))for(let t of s){let r=t.lastModified.getTime();if(r<i)continue;let s=0;try{s=(0,o.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"codex",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:r,sizeBytes:s})}}return n}async function tA(e){let t=await (0,tE.getCodexSessionLog)(e.sessionId);return t?tN(t.entries,{cli:"codex",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tP=e.i(55851),tI=e.i(78166);async function tx(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tP.getCopilotProjects)())){let{cwd:r,sessions:s}=await (0,tP.getCopilotSessionsByEncodedName)(e.name),a=r??"";if(!t||t.has(a))for(let t of s){let r=t.lastModified.getTime();if(r<i)continue;let s=0;try{s=(0,o.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"copilot",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:r,sizeBytes:s})}}return n}async function tR(e){let t=await (0,tI.getCopilotSessionLog)(e.sessionId);return t?tN(t.entries,{cli:"copilot",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tO=e.i(46413),t_=e.i(72094);async function tj(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tO.getCursorProjects)())){let{cwd:r,sessions:s}=await (0,tO.getCursorSessionsByEncodedName)(e.name),a=r??"";if(!t||t.has(a))for(let t of s){let r=t.lastModified.getTime();if(r<i)continue;let s=0;try{s=(0,o.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"cursor",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:r,sizeBytes:s})}}return n}async function tB(e){let t=await (0,t_.getCursorSessionLog)(e.sessionId);return t?tN(t.entries,{cli:"cursor",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tD=e.i(35435),tW=e.i(99440);async function tM(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tD.getOpenCodeProjects)())){let{cwd:o,sessions:r}=await (0,tD.getOpenCodeSessionsByEncodedName)(e.name),s=o??"";if(!t||t.has(s))for(let t of r){let o=t.lastModified.getTime();!(o<i)&&t.sessionId&&n.push({cli:"opencode",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:o,sizeBytes:0})}}return n}async function tU(e){let t=await (0,tW.getOpenCodeSessionLog)(e.sessionId);return t?tN(t.entries,{cli:"opencode",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tz=e.i(19791),tL=e.i(85116);async function tF(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:s}=await (0,tz.getPiSessionsByEncodedName)(e.name),a=r??"";if(!t||t.has(a))for(let t of s){let r=t.lastModified.getTime();if(r<i)continue;let s=0;try{s=(0,o.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"pi",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:r,sizeBytes:s})}}return n}async function tq(e){let t=await (0,tL.getPiSessionLog)(e.sessionId);return t?tN(t.entries,{cli:"pi",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tH=e.i(64828),tJ=e.i(28898),tG=e.i(3605);async function tZ(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=await (0,tH.getHermesSessions)(),o=[];for(let e of n)!(e.mtimeMs<i)&&(!(e.messageCount<=0)||e.hasMessages)&&(!t||e.cwd&&t.has(e.cwd))&&o.push({cli:"hermes",projectName:e.cwd?(0,tw.encodeFolderName)(e.cwd):e.source?(0,tJ.hermesProjectPath)(e.profile,e.source):`hermes:${e.profile}`,sessionId:e.sessionId,transcriptPath:`hermes://${e.sessionId}`,mtimeMs:e.mtimeMs,sizeBytes:e.messageCount});return o}async function tY(e){let t=await (0,tG.getHermesSessionLog)(e.sessionId);return t?tN(t.entries,{cli:"hermes",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tK=e.i(90624),tQ=e.i(64199);async function tV(e={}){if(e.projects&&e.projects.length>0)return[];let t=e.sinceMs??0,i=[];for(let e of(await (0,tK.getOpenClawSessions)()))e.mtimeMs<t||i.push({cli:"openclaw",projectName:(0,tK.openClawProjectPath)(e.agentId,e.channel),sessionId:e.sessionId,transcriptPath:e.transcriptPath,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes});return i}async function tX(e){let t=await (0,tQ.getOpenClawSessionLog)(e.sessionId);return t?tN(t.entries,{cli:"openclaw",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var t0=e.i(28246);async function t1(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(0,t0.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 t3(e){let t;try{t=await (0,r.readFile)(e.transcriptPath,"utf-8")}catch{return[]}let i=(0,tv.parseRawLines)(t,"session"),n=(0,t0.factoryLinesToLogEntries)(i,"session"),o="";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){o=t;break}}return tN(n,{cli:"factory",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:o})}var t6=e.i(93114),t9=e.i(30441);async function t2(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[],o=await (0,t9.getAntigravityIndex)();for(let e of(0,t6.listAntigravityTranscripts)()){if(e.mtimeMs<i)continue;let r=o.get(e.conversationId)?.cwd;(!t||r&&t.has(r))&&n.push({cli:"antigravity",projectName:r?(0,tw.encodeFolderName)(r):"antigravity",sessionId:e.conversationId,transcriptPath:e.transcriptPath,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes})}return n}async function t8(e){let t;try{t=await (0,r.readFile)(e.transcriptPath,"utf-8")}catch{return[]}let i=(0,tv.parseRawLines)(t,"session"),n=(0,t6.antigravityLinesToLogEntries)(i,"session"),o="";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){o=i;break}}if(o)break}}return tN(n,{cli:"antigravity",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:o})}var t4=e.i(79364),t5=e.i(40375);async function t7(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=await (0,t4.getDevinSessions)(),o=[];for(let e of n)!(e.mtimeMs<i)&&(!t||e.cwd&&t.has(e.cwd))&&o.push({cli:"devin",projectName:e.projectName,sessionId:e.sessionId,transcriptPath:`devin-db://${e.sessionId}`,mtimeMs:e.mtimeMs,sizeBytes:0});return o}async function ie(e){let t=await (0,t5.getDevinSessionLog)(e.sessionId);return t?tN(t.entries,{cli:"devin",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var it=e.i(69164),ii=e.i(36618);let io={claude:{cli:"claude",listTranscripts:tS,streamEvents:t$},codex:{cli:"codex",listTranscripts:tC,streamEvents:tA},copilot:{cli:"copilot",listTranscripts:tx,streamEvents:tR},cursor:{cli:"cursor",listTranscripts:tj,streamEvents:tB},opencode:{cli:"opencode",listTranscripts:tM,streamEvents:tU},pi:{cli:"pi",listTranscripts:tF,streamEvents:tq},hermes:{cli:"hermes",listTranscripts:tZ,streamEvents:tY},openclaw:{cli:"openclaw",listTranscripts:tV,streamEvents:tX},factory:{cli:"factory",listTranscripts:t1,streamEvents:t3},devin:{cli:"devin",listTranscripts:t7,streamEvents:ie},antigravity:{cli:"antigravity",listTranscripts:t2,streamEvents:t8},goose:{cli:"goose",listTranscripts:async function(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=await (0,it.getGooseSessions)(),o=[];for(let e of n)!(e.mtimeMs<i)&&(!t||e.cwd&&t.has(e.cwd))&&o.push({cli:"goose",projectName:e.projectName,sessionId:e.sessionId,transcriptPath:`goose-db://${e.sessionId}`,mtimeMs:e.mtimeMs,sizeBytes:0});return o},streamEvents:async function(e){let t=await (0,ii.getGooseSessionLog)(e.sessionId);return t?tN(t.entries,{cli:"goose",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}}},ir=/\.(?: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,is=["/","/home","/usr","/etc","/var","/opt","/Users"],ia="rereadAfterEdit",il=[{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 o=(n[1]??n[2]??n[3]??"").replace(/\/+$/,"");if(o!==e.cwd.replace(/\/+$/,""))return null;let r=n[4].trim();return{example:`cd ${o} && ${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 o=n[2]??n[3]??n[4]??"";return!o||/(?:^|\/)\.env(?:\..+)?$/.test(o)||!ir.test(o)?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 o=n[1].replace(/^["']|["']$/g,"").replace(/\/+$/,"")||"/";return is.includes(o)?{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[ia])||(i={countdown:new Map},t[ia]=i),i),o=e.toolInput.file_path,r="string"==typeof o?o: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}}],ic=["cowboy","explorer","ghost","optimist","hammer","architect"],id={explorer:.38,architect:.33,hammer:.11,cowboy:.11,optimist:.07,ghost:.01,precision:0,goldfish:0},ip={optimist:0,cowboy:0,explorer:0,goldfish:0,architect:0,precision:0,hammer:0,ghost:0};for(let e of ic)ip[e]=Math.max(id[e],.05);var iu=e.i(66680),im=e.i(79857);let ih=[1],ig=/^[a-f0-9]{64}$/,iy=/^[A-Za-z0-9._-]{1,64}\/[A-Za-z0-9._-]{1,64}$/,ib=/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/,iw=/^[A-Za-z0-9._-]{1,128}$/;function ik(e){return e instanceof Error?e.message:String(e)}let iv=null,iN=null;function iS(){if(iv)return iv;let e=e5.map(e=>`${e.name}|${e.fn.toString()}`).sort().join("\n"),t="";try{t=(function(){let e,t=process.env.FAILPROOFAI_PACK_DIR?(0,n.resolve)(process.env.FAILPROOFAI_PACK_DIR,"installed.json"):(0,im.packsInstalledFile)();if(!(0,o.existsSync)(t))return{packs:[],errors:[]};try{e=JSON.parse((0,o.readFileSync)(t,"utf8"))}catch(e){return{packs:[],errors:[{id:null,reason:`unreadable pack manifest: ${ik(e)}`}]}}if(!e||"object"!=typeof e)return{packs:[],errors:[{id:null,reason:"pack manifest is not an object"}]};let i=e;if(!ih.includes(i.schemaVersion))return{packs:[],errors:[{id:null,reason:`unsupported pack manifest schema ${String(i.schemaVersion)} (supported: ${ih.join(", ")})`}]};if(!Array.isArray(i.packs))return{packs:[],errors:[{id:null,reason:"pack manifest packs is not an array"}]};let r=process.env.FAILPROOFAI_PACK_DIR??(0,im.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||!iy.test(e.id))throw Error(`unsafe pack id ${JSON.stringify(e.id)}`);if("string"!=typeof e.version||!ib.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}`);return{id:e.id,version:e.version,effect:e.effect??"enforce"}}(t);if("string"!=typeof t.source||0===t.source.length)throw Error(`pack ${t.id} has no source`);if("string"!=typeof t.sha256||!ig.test(t.sha256))throw Error(`invalid SHA-256 for pack ${t.id}`);let r=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),r=(0,n.relative)(e,i);if(r.startsWith("..")||(0,n.isAbsolute)(r))throw Error(`managed policy path escapes its root: ${JSON.stringify(t)}`);let s=(0,o.realpathSync)(e),a=(0,o.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,iu.createHash)("sha256").update((0,o.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 o=t.name;if("string"!=typeof o||!iw.test(o))throw Error(`${n} has an unsafe name ${JSON.stringify(o)}`);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))}return{id:i.id,version:i.version,source:t.source,path:s,sha256:t.sha256,effect:r,policies:l,enabled:d}}(r,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:ik(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.map(e=>`${e.id}|${e.version}|${e.sha256}`).sort().join("\n")}catch{t=""}let i=t?`${e}
|
|
2
|
+
${t}`:e;return iv=(0,iu.createHash)("sha1").update(i).digest("hex").slice(0,16)}function i$(){if(iN)return iN;let e=il.map(e=>`${e.name}|${e.detect.toString()}`).sort().join("\n");return iN=(0,iu.createHash)("sha1").update(e).digest("hex").slice(0,16)}function iT(e){let t=(0,im.auditCacheDir)(),i=(0,iu.createHash)("sha1").update(e).digest("hex");return(0,n.join)(t,`${i}.json`)}var iE=e.i(49335),iC=e.i(10659);function iA(e,t){let i=e.trim(),n="string"==typeof t?t.trim():"";return n?i?`${i}. ${n}`:n:i}function iP(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 iI(e,t,i,n){let o=t.tool_name,r=t.tool_input,s=function(e,t){let i=globalThis[m];i||g(i=new Map);let n=`${e}:${t??""}`,o=i.get(n);if(o)return o;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,o);if((0,w.hookLogInfo)(`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:o,toolInput:r,session:i,cli:i?.cli},l=[],c=[];for(let t of s){let o,r,s=t.params,d=iP(n,t.name)??{};if(s){let e={};for(let[t,i]of Object.entries(s))e[t]=t in d?d[t]:i.default;o={...a,params:e}}else o={...a,params:d};try{r=await t.fn(o)}catch(o){let n=o instanceof Error?o.message:String(o);(0,w.hookLogWarn)(`policy "${t.name}" threw: ${n}`),t.name.startsWith(`${f}/`)&&(0,iE.trackHookEvent)((0,iC.getInstanceId)(),"policy_evaluation_error",{policy_name:t.name,event_type:e,cli:i?.cli??null,error_type:o instanceof Error?o.name:"unknown"});continue}if("deny"===r.decision){let s,a=iA(r.reason??`Blocked by policy: ${t.name}`,iP(n,t.name)?.hint);(0,w.hookLogInfo)(`deny by "${t.name}": ${a}`),s=o.toolName?o.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}
|
|
4
3
|
|
|
5
4
|
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
5
|
|
|
@@ -14,9 +13,9 @@ You MUST complete the above action NOW. Do NOT ask the user for confirmation —
|
|
|
14
13
|
|
|
15
14
|
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
15
|
|
|
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 ${
|
|
16
|
+
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}
|
|
18
17
|
|
|
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"===
|
|
18
|
+
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=iA(r.reason??`Instruction from policy: ${t.name}`,iP(n,t.name)?.hint);l.push({policyName:t.name,reason:e}),(0,w.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
19
|
|
|
21
20
|
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
21
|
|
|
@@ -30,6 +29,6 @@ You MUST complete the above action(s) NOW. Do NOT ask the user for confirmation
|
|
|
30
29
|
|
|
31
30
|
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(", ")}`,o=`MANDATORY ACTION REQUIRED from failproofai (${e}): ${t}
|
|
32
31
|
|
|
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:o}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}:{exitCode:2,stdout:"",stderr:o,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 o="PreToolUse"===e||"PostToolUse"===e||"UserPromptSubmit"===e||"PermissionRequest"===e,s=c.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n");return o?{exitCode:0,stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e,additionalContext:`Note from failproofai: ${t}`}}),stderr:s+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}:{exitCode:0,stdout:"",stderr:s+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}}return{exitCode:0,stdout:"",stderr:"",policyName:null,reason:null,decision:"allow"}}let i_=new Set(["warn-repeated-tool-calls"].map(e=>f(e))),iB=!1,ij=null;function iD(){if(iB)return;ij=[...g()],globalThis[p]=[],h(null);let e=new Set(tt.map(e=>e.name).filter(e=>!i_.has(f(e))).map(f));for(let t of tt)e.has(f(t.name))&&function(e,t,i,n,o=0){let s=f(e),r=g(),a=r.findIndex(e=>e.name===s),l={name:s,description:t,fn:i,match:n,priority:o};a>=0?r[a]=l:r.push(l),h(null)}(t.name,t.description,t.fn,t.match);iB=!0}async function iW(e){iB||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(iM(await iO("PreToolUse",i,t),"PreToolUse",n),void 0!==e.toolResultText){let o={...i,tool_response:e.toolResultText};iM(await iO("PostToolUse",o,t),"PostToolUse",n)}return n}function iM(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 iU(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 iz(e){let t={transcriptPath:e.transcriptPath,cli:e.cli,projectName:e.projectName,sessionId:e.sessionId,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes,cwd:"",eventsScanned:0,hitsByName:{},examplesByName:{},rangeByName:{}},i=await ia[e.cli].streamEvents(e);if(0===i.length)return t;t.eventsScanned=i.length,t.cwd=i[0].cwd||"";let n={};for(let e of i){let i;for(let i of ip){let o=i.detect(e,n);o&&iF(t,i.name,e.timestamp,e.cwd,iL(o.example))}try{i=await iW(e)}catch{continue}for(let n of i){let i=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}`}(n.policyName,e);iF(t,n.policyName,e.timestamp,e.cwd,iL(i))}}return t}function iF(e,t,i,n,o){e.hitsByName[t]=(e.hitsByName[t]??0)+1;let s=e.examplesByName[t]??[];s.length<3&&(s.push({timestamp:i,cwd:n,example:o}),e.examplesByName[t]=s);let r=e.rangeByName[t];r?(i<r.first&&(r.first=i),i>r.last&&(r.last=i)):e.rangeByName[t]={first:i,last:i}}async function iH(e={}){let t=Date.now();iD();try{return await iq(e,t)}finally{if(iB){if(null!==ij){var i;i=ij,globalThis[p]=[...i],h(null),ij=null}iB=!1}}}async function iq(e,t){let s=e.clis??Array.from(tn),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),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,o.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"),s=(0,y.globalPolicyConfigFile)(),r=ti(t),l=ti(i),c=ti(s),d=new Set([...r.enabledPolicies??[],...l.enabledPolicies??[],...c.enabledPolicies??[]]),p={};for(let e of[r,l,c])if(e.policyParams)for(let[t,i]of Object.entries(e.policyParams))t in p||(p[t]=i);let u=[r,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([...r.disabledCustomPolicies??[],...l.disabledCustomPolicies??[],...c.disabledCustomPolicies??[]]),f=r.customPoliciesEnabled??l.customPoliciesEnabled??c.customPoliciesEnabled,h=r.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=>f(e))),c=[];for(let t of s){let i,n=ia[t];try{i=await n.listTranscripts({projects:e.projects,sinceMs:r})}catch{continue}c.push(...i)}let d=0,p=0,u=c.map(t=>async()=>{if(!e.noCache){let e=function(e,t,i){if(0===i)return null;let n=iv(e);if(!(0,o.existsSync)(n))return null;try{let e=(0,o.readFileSync)(n,"utf-8"),s=JSON.parse(e);if(3!==s.schemaVersion||s.mtimeMs!==t||s.sizeBytes!==i||s.engineVersion!==iw()||s.detectorVersion!==ik()||!Number.isFinite(s.cachedAt)||Date.now()-s.cachedAt>2592e6)return null;return s.result??null}catch{return null}}(t.transcriptPath,t.mtimeMs,t.sizeBytes);if(e)return e}try{let i=await iz(t);return e.noCache||function(e,t,i,n){if(0===i)return;let s=iv(e);try{(0,o.mkdirSync)((0,y.auditCacheDir)(),{recursive:!0});let e={schemaVersion:3,cachedAt:Date.now(),mtimeMs:t,sizeBytes:i,engineVersion:iw(),detectorVersion:ik(),result:n};(0,o.writeFileSync)(s,JSON.stringify(e),{encoding:"utf-8",mode:384});try{(0,o.chmodSync)(s,384)}catch{}}catch{}}(t.transcriptPath,t.mtimeMs,t.sizeBytes,i),i}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),h=[];for(let e of m)"fulfilled"===e.status?h.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 o=i.get(e)??{hits:0,projects:new Set,examples:[]};for(let i of(o.hits+=n,o.projects.add(t.projectName),t.examplesByName[e]??[]))o.examples.length<3&&o.examples.push({...i,sessionId:t.sessionId});let s=t.rangeByName[e];s&&((!o.first||s.first<o.first)&&(o.first=s.first),(!o.last||s.last>o.last)&&(o.last=s.last)),i.set(e,o)}let n=new Map(ip.map(e=>[e.name,e])),o=[];for(let[e,s]of i){let i=n.get(e),r=!!i,a=r?null:function(e){let t=iU(e);for(let i of tt)if(i.name===e||iU(i.name)===t)return i;return null}(e),l=r?"audit-detector":"builtin",c=!r&&t.has(f(e)),d=i?.displayTitle??a?.displayTitle??i?.description??a?.description??iU(e),p=i?.impact??a?.impact??"";o.push({name:e,source:l,category:i?.category??a?.category??"Custom",severity:r?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:s.hits,projects:s.projects.size,firstSeen:s.first,lastSeen:s.last,examples:s.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 ${iU(e)}`})}return o.sort((e,t)=>t.hits-e.hits),o}(h,l);if(e.policies?.length){let t=new Set(e.policies.map(iU));g=g.filter(e=>t.has(iU(e.name)))}let b=g.reduce((e,t)=>e+t.hits,0),w=new Set,k=new Set,v=0;for(let e of h)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:s,projects:e.projects??"all",since:e.since??null},transcripts:{scanned:c.length,skipped:d,errors:p,durationMs:Date.now()-t},results:g,totals:{hits:b,projectsWithHits:w.size},projectsScanned:[...k].sort(),eventsScanned:v,enabledBuiltinNames:[...l].map(e=>e.includes("/")?e.slice(e.indexOf("/")+1):e)}}var iJ=e.i(47756),iG=e.i(48480),iY=e.i(29095),iZ=e.i(46501);let iK=new Set(tn);async function iQ(e){await (0,iZ.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,iZ.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,iZ.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,iG.tryAcquireRun)())return(0,iZ.trackEvent)("audit_run_rejected",{source:"dashboard",reason:"already_running"}),t.NextResponse.json({error:"Audit already running",status:"already-running"},{status:409});let o=(0,iY.acquireAuditLock)("dashboard");if(!o.ok)return(0,iG.finishRun)(null),(0,iZ.trackEvent)("audit_run_rejected",{source:"dashboard",reason:"cross_process_lock"}),t.NextResponse.json({error:"Audit already running",status:"already-running"},{status:409});(0,iZ.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 s=Date.now();return(async()=>{try{let e=await iH(n),t=(0,iJ.writeDashboardCache)(n,e);(0,iZ.trackEvent)("audit_run_completed",{source:"dashboard",duration_ms:Date.now()-s,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,iG.finishRun)(t?null:"audit finished but its result could not be saved")}catch(e){(0,iZ.trackEvent)("audit_run_failed",{source:"dashboard",duration_ms:Date.now()-s,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,iG.finishRun)(e instanceof Error?e.message:String(e))}finally{o.lock.release()}})(),t.NextResponse.json({status:"started"},{status:202})}e.s(["POST",0,iQ,"dynamic",0,"force-dynamic"],97610)},89498,e=>{"use strict";var t=e.i(47909),i=e.i(74017),n=e.i(96250),o=e.i(59756),s=e.i(61916),r=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 N(e,t,n){n.requestMeta&&(0,o.setRequestMeta)(e,n.requestMeta),b.isDev&&(0,o.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:N,params:S,nextConfig:T,parsedUrl:P,isDraftMode:E,prerenderManifest:$,routerServerContext:C,isOnDemandRevalidate:I,revalidateOnlyGenerated:x,resolvedPathname:A,clientReferenceManifest:R,serverActionsManifest:O}=k,_=(0,a.normalizeAppPath)(w),B=!!($.dynamicRoutes[_]||$.routes[A]),j=async()=>((null==C?void 0:C.render404)?await C.render404(e,t,P,!1):t.end("This page could not be found"),null);if(B&&!E){let e=!!$.routes[A],t=$.dynamicRoutes[_];if(t&&!1===t.fallback&&!e){if(T.adapterPath)return await j();throw new g.NoFallbackError}}let D=null;!B||b.isDev||E||(D="/index"===(D=A)?"/":D);let W=!0===b.isDev||!B,M=B&&!W;O&&R&&(0,r.setManifestsSingleton)({page:w,clientReferenceManifest:R,serverActionsManifest:O});let U=e.method||"GET",L=(0,s.getTracer)(),z=L.getActiveScopeSpan(),F=!!(null==C?void 0:C.isWrappedByNextServer),H=!!(0,o.getRequestMeta)(e,"minimalMode"),q=(0,o.getRequestMeta)(e,"incrementalCache")||await b.getIncrementalCache(e,T,$,H);null==q||q.resetRequestCache(),globalThis.__incrementalCache=q;let J={params:S,previewProps:$.preview,renderOpts:{experimental:{authInterrupts:!!T.experimental.authInterrupts,useCacheTimeout:T.experimental.useCacheTimeout},cacheComponents:!!T.cacheComponents,validationLevel:T.experimental.instantInsights.validationLevel,supportsDynamicResponse:W,incrementalCache:q,hmrRefreshHash:(0,o.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,o)=>b.onRequestError(e,t,n,o,C)},sharedContext:{buildId:v,deploymentId:N}},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&&I&&x&&!i)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let o=await b.handle(Z,J);e.fetchMetrics=J.renderOpts.fetchMetrics;let s=J.renderOpts.pendingWaitUntil;s&&n.waitUntil&&(n.waitUntil(s),s=void 0);let r=J.renderOpts.collectedTags;if(!B)return await (0,u.sendResponse)(G,Y,o,s),null;{let e=await o.blob(),t=(0,m.toNodeOutgoingHttpHeaders)(o.headers);r&&(t[h.NEXT_CACHE_TAGS_HEADER]=r),!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?T.expireTime:void 0:J.renderOpts.collectedExpire;return{value:{kind:y.CachedRouteKind.APP_ROUTE,status:o.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:I})},!1,C),t}},Q=async(o,r)=>{try{var a,l;let o=await b.handleResponse({req:e,nextConfig:T,cacheKey:D,routeKind:i.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:$,isRoutePPREnabled:!1,isOnDemandRevalidate:I,revalidateOnlyGenerated:x,responseGenerator:K,waitUntil:n.waitUntil,isMinimalMode:H});if(!B)return;if((null==o||null==(a=o.value)?void 0:a.kind)!==y.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==o||null==(l=o.value)?void 0:l.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});H||t.setHeader("x-nextjs-cache",I?"REVALIDATED":o.isMiss?"MISS":o.isStale?"STALE":"HIT"),E&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let s=(0,m.fromNodeOutgoingHttpHeaders)(o.value.headers);H&&B||s.delete(h.NEXT_CACHE_TAGS_HEADER),!o.cacheControl||t.getHeader("Cache-Control")||s.get("Cache-Control")||s.set("Cache-Control",(0,f.getCacheControlHeader)(o.cacheControl)),await (0,u.sendResponse)(G,Y,new Response(o.value.body,{headers:s,status:o.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:I})},!1,C),B)throw t;await (0,u.sendResponse)(G,Y,new Response(null,{status:500}));return}finally{(()=>{if(!o)return;let e=t.statusCode;o.setAttributes({"http.status_code":e,"next.rsc":!1}),e&&e>=500&&(o.setStatus({code:s.SpanStatusCode.ERROR}),o.setAttribute("error.type",e.toString()));let i=L.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}`;o.setAttributes({"next.route":n,"http.route":n,"next.span_name":a}),o.updateName(a),r&&r!==o&&(r.setAttribute("http.route",n),r.updateName(a))})()}};if(F&&z)await Q(z,void 0);else{let t=L.getActiveScopeSpan();await L.withPropagatedContext(e.headers,()=>L.trace(d.BaseServerSpan.handleRequest,{spanName:`${U} ${w}`,kind:s.SpanKind.SERVER,attributes:{"http.method":U,"http.target":e.url}},e=>Q(e,t)),void 0,!F)}}e.s(["handler",0,N,"patchFetch",0,function(){return(0,n.patchFetch)({workAsyncStorage:w,workUnitAsyncStorage:k})},"routeModule",0,b,"serverHooks",0,v,"workAsyncStorage",0,w,"workUnitAsyncStorage",0,k])}];
|
|
32
|
+
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:o}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}:{exitCode:2,stdout:"",stderr:o,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 o="PreToolUse"===e||"PostToolUse"===e||"UserPromptSubmit"===e||"PermissionRequest"===e,r=c.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n");return o?{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"}}var ix=e.i(90521),iR=e.i(93119);let iO=new Set(["warn-repeated-tool-calls"].map(e=>h(e))),i_=!1,ij=null;async function iB(){if(i_)return;ij=[...y()],globalThis[u]=[],g(null);let e=e5.map(e=>e.name).filter(e=>!iO.has(h(e)));await iD(e)||function(e){let t=new Set(e.map(h));for(let e of e5)(e.alwaysOn||t.has(h(e.name)))&&b(e.name,e.description,e.fn,e.match,0,e.params)}(e),i_=!0}async function iD(e){let t,i=function(){let e=process.env.FAILPROOFAI_PACKAGE_ROOT;if(!e)return null;let t=(0,n.resolve)(e,"policy-pack");return(0,o.existsSync)((0,n.resolve)(t,"failproofai-pack.json"))?t:null}();if(!i)return!1;let r=(0,n.resolve)(i,"failproofai-pack.mjs");if(!(0,o.existsSync)(r))return!1;let s=new Set(e);try{(0,iR.clearCustomHooks)(),t=await (0,ix.loadCustomHooks)(r,{strict:!0})}catch{return!1}finally{(0,iR.clearCustomHooks)()}if(0===t.length)return!1;let a=new Map(t.map(e=>[e.name,e])),l=0;for(let e of e5){if(!s.has(e.name))continue;let t=a.get(e.name);if(e.alwaysOn||!t){b(e.name,e.description,e.fn,e.match,0,e.params);continue}b(t.name,t.description??e.description,t.fn,t.match??e.match,0,e.params),l+=1}return l>0}async function iW(e){i_||await iB();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(iM(await iI("PreToolUse",i,t),"PreToolUse",n),void 0!==e.toolResultText){let o={...i,tool_response:e.toolResultText};iM(await iI("PostToolUse",o,t),"PostToolUse",n)}return n}function iM(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 iU(e){let t=e.indexOf("/");return t>=0?e.slice(t+1):e}function iz(e){return e.length<=80?e:e.slice(0,79)+"…"}async function iL(e){let t={transcriptPath:e.transcriptPath,cli:e.cli,projectName:e.projectName,sessionId:e.sessionId,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes,cwd:"",eventsScanned:0,hitsByName:{},examplesByName:{},rangeByName:{}},i=await io[e.cli].streamEvents(e);if(0===i.length)return t;t.eventsScanned=i.length,t.cwd=i[0].cwd||"";let n={};for(let e of i){let i;for(let i of il){let o=i.detect(e,n);o&&iF(t,i.name,e.timestamp,e.cwd,iz(o.example))}try{i=await iW(e)}catch{continue}for(let n of i){let i=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}`}(n.policyName,e);iF(t,n.policyName,e.timestamp,e.cwd,iz(i))}}return t}function iF(e,t,i,n,o){e.hitsByName[t]=(e.hitsByName[t]??0)+1;let r=e.examplesByName[t]??[];r.length<3&&(r.push({timestamp:i,cwd:n,example:o}),e.examplesByName[t]=r);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 iq(e={}){let t=Date.now();await iB();try{return await iH(e,t)}finally{if(i_){if(null!==ij){var i;i=ij,globalThis[u]=[...i],g(null),ij=null}i_=!1}}}async function iH(e,t){let n=e.clis??Array.from(te),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),s=new Set(((0,e7.readMergedHooksConfig)().enabledPolicies??[]).map(e=>h(e))),a=[];for(let t of n){let i,n=io[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()=>{if(!e.noCache){let e=function(e,t,i){if(0===i)return null;let n=iT(e);if(!(0,o.existsSync)(n))return null;try{let e=(0,o.readFileSync)(n,"utf-8"),r=JSON.parse(e);if(3!==r.schemaVersion||r.mtimeMs!==t||r.sizeBytes!==i||r.engineVersion!==iS()||r.detectorVersion!==i$()||!Number.isFinite(r.cachedAt)||Date.now()-r.cachedAt>2592e6)return null;return r.result??null}catch{return null}}(t.transcriptPath,t.mtimeMs,t.sizeBytes);if(e)return e}try{let i=await iL(t);return e.noCache||function(e,t,i,n){if(0===i)return;let r=iT(e);try{(0,o.mkdirSync)((0,im.auditCacheDir)(),{recursive:!0});let e={schemaVersion:3,cachedAt:Date.now(),mtimeMs:t,sizeBytes:i,engineVersion:iS(),detectorVersion:i$(),result:n};(0,o.writeFileSync)(r,JSON.stringify(e),{encoding:"utf-8",mode:384});try{(0,o.chmodSync)(r,384)}catch{}}catch{}}(t.transcriptPath,t.mtimeMs,t.sizeBytes,i),i}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:{}}}}),p=await (0,i.batchAll)(d,8),u=[];for(let e of p)"fulfilled"===e.status?u.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 o=i.get(e)??{hits:0,projects:new Set,examples:[]};for(let i of(o.hits+=n,o.projects.add(t.projectName),t.examplesByName[e]??[]))o.examples.length<3&&o.examples.push({...i,sessionId:t.sessionId});let r=t.rangeByName[e];r&&((!o.first||r.first<o.first)&&(o.first=r.first),(!o.last||r.last>o.last)&&(o.last=r.last)),i.set(e,o)}let n=new Map(il.map(e=>[e.name,e])),o=[];for(let[e,r]of i){let i=n.get(e),s=!!i,a=s?null:function(e){let t=iU(e);for(let i of e5)if(i.name===e||iU(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??iU(e),p=i?.impact??a?.impact??"";o.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:r.hits,projects:r.projects.size,firstSeen:r.first,lastSeen:r.last,examples:r.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 ${iU(e)}`})}return o.sort((e,t)=>t.hits-e.hits),o}(u,s);if(e.policies?.length){let t=new Set(e.policies.map(iU));m=m.filter(e=>t.has(iU(e.name)))}let f=m.reduce((e,t)=>e+t.hits,0),g=new Set,y=new Set,b=0;for(let e of u)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:[...s].map(e=>e.includes("/")?e.slice(e.indexOf("/")+1):e)}}var iJ=e.i(47756),iG=e.i(48480),iZ=e.i(29095),iY=e.i(46501);let iK=new Set(te);async function iQ(e){await (0,iY.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,iY.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,iY.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,iG.tryAcquireRun)())return(0,iY.trackEvent)("audit_run_rejected",{source:"dashboard",reason:"already_running"}),t.NextResponse.json({error:"Audit already running",status:"already-running"},{status:409});let o=(0,iZ.acquireAuditLock)("dashboard");if(!o.ok)return(0,iG.finishRun)(null),(0,iY.trackEvent)("audit_run_rejected",{source:"dashboard",reason:"cross_process_lock"}),t.NextResponse.json({error:"Audit already running",status:"already-running"},{status:409});(0,iY.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 iq(n),t=(0,iJ.writeDashboardCache)(n,e);(0,iY.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,iG.finishRun)(t?null:"audit finished but its result could not be saved")}catch(e){(0,iY.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,iG.finishRun)(e instanceof Error?e.message:String(e))}finally{o.lock.release()}})(),t.NextResponse.json({status:"started"},{status:202})}e.s(["POST",0,iQ,"dynamic",0,"force-dynamic"],97610)},89498,e=>{"use strict";var t=e.i(47909),i=e.i(74017),n=e.i(96250),o=e.i(59756),r=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 N(e,t,n){n.requestMeta&&(0,o.setRequestMeta)(e,n.requestMeta),b.isDev&&(0,o.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:N,params:S,nextConfig:$,parsedUrl:T,isDraftMode:E,prerenderManifest:C,routerServerContext:A,isOnDemandRevalidate:P,revalidateOnlyGenerated:I,resolvedPathname:x,clientReferenceManifest:R,serverActionsManifest:O}=k,_=(0,a.normalizeAppPath)(w),j=!!(C.dynamicRoutes[_]||C.routes[x]),B=async()=>((null==A?void 0:A.render404)?await A.render404(e,t,T,!1):t.end("This page could not be found"),null);if(j&&!E){let e=!!C.routes[x],t=C.dynamicRoutes[_];if(t&&!1===t.fallback&&!e){if($.adapterPath)return await B();throw new g.NoFallbackError}}let D=null;!j||b.isDev||E||(D="/index"===(D=x)?"/":D);let W=!0===b.isDev||!j,M=j&&!W;O&&R&&(0,s.setManifestsSingleton)({page:w,clientReferenceManifest:R,serverActionsManifest:O});let U=e.method||"GET",z=(0,r.getTracer)(),L=z.getActiveScopeSpan(),F=!!(null==A?void 0:A.isWrappedByNextServer),q=!!(0,o.getRequestMeta)(e,"minimalMode"),H=(0,o.getRequestMeta)(e,"incrementalCache")||await b.getIncrementalCache(e,$,C,q);null==H||H.resetRequestCache(),globalThis.__incrementalCache=H;let J={params:S,previewProps:C.preview,renderOpts:{experimental:{authInterrupts:!!$.experimental.authInterrupts,useCacheTimeout:$.experimental.useCacheTimeout},cacheComponents:!!$.cacheComponents,validationLevel:$.experimental.instantInsights.validationLevel,supportsDynamicResponse:W,incrementalCache:H,hmrRefreshHash:(0,o.getRequestMeta)(e,"hmrRefreshHash"),cacheLifeProfiles:$.cacheLife,staticPageGenerationTimeout:$.staticPageGenerationTimeout,waitUntil:n.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,i,n,o)=>b.onRequestError(e,t,n,o,A)},sharedContext:{buildId:v,deploymentId:N}},G=new l.NodeNextRequest(e),Z=new l.NodeNextResponse(t),Y=c.NextRequestAdapter.fromNodeNextRequest(G,(0,c.signalFromNodeResponse)(t)),K=async({previousCacheEntry:i})=>{try{if(!q&&P&&I&&!i)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let o=await b.handle(Y,J);e.fetchMetrics=J.renderOpts.fetchMetrics;let r=J.renderOpts.pendingWaitUntil;r&&n.waitUntil&&(n.waitUntil(r),r=void 0);let s=J.renderOpts.collectedTags;if(!j)return await (0,u.sendResponse)(G,Z,o,r),null;{let e=await o.blob(),t=(0,m.toNodeOutgoingHttpHeaders)(o.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:o.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:P})},!1,A),t}},Q=async(o,s)=>{try{var a,l;let o=await b.handleResponse({req:e,nextConfig:$,cacheKey:D,routeKind:i.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:C,isRoutePPREnabled:!1,isOnDemandRevalidate:P,revalidateOnlyGenerated:I,responseGenerator:K,waitUntil:n.waitUntil,isMinimalMode:q});if(!j)return;if((null==o||null==(a=o.value)?void 0:a.kind)!==y.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==o||null==(l=o.value)?void 0:l.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});q||t.setHeader("x-nextjs-cache",P?"REVALIDATED":o.isMiss?"MISS":o.isStale?"STALE":"HIT"),E&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let r=(0,m.fromNodeOutgoingHttpHeaders)(o.value.headers);q&&j||r.delete(h.NEXT_CACHE_TAGS_HEADER),!o.cacheControl||t.getHeader("Cache-Control")||r.get("Cache-Control")||r.set("Cache-Control",(0,f.getCacheControlHeader)(o.cacheControl)),await (0,u.sendResponse)(G,Z,new Response(o.value.body,{headers:r,status:o.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:P})},!1,A),j)throw t;await (0,u.sendResponse)(G,Z,new Response(null,{status:500}));return}finally{(()=>{if(!o)return;let e=t.statusCode;o.setAttributes({"http.status_code":e,"next.rsc":!1}),e&&e>=500&&(o.setStatus({code:r.SpanStatusCode.ERROR}),o.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}`;o.setAttributes({"next.route":n,"http.route":n,"next.span_name":a}),o.updateName(a),s&&s!==o&&(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:r.SpanKind.SERVER,attributes:{"http.method":U,"http.target":e.url}},e=>Q(e,t)),void 0,!F)}}e.s(["handler",0,N,"patchFetch",0,function(){return(0,n.patchFetch)({workAsyncStorage:w,workUnitAsyncStorage:k})},"routeModule",0,b,"serverHooks",0,v,"workAsyncStorage",0,w,"workUnitAsyncStorage",0,k])}];
|
|
34
33
|
|
|
35
34
|
//# sourceMappingURL=_1ek68ln._.js.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
module.exports=[15855,43477,e=>{"use strict";let t;var r=e.i(2157),i=e.i(50227),a=e.i(60526),l=e.i(66680);function f(e){return e?(0,i.resolve)(e,".failproofai"):process.env.FAILPROOFAI_HOME||(0,i.resolve)((0,a.homedir)(),".failproofai")}e.i(74533);let n=(e,...t)=>e?(0,i.resolve)(f(e),...t):((...e)=>(0,i.resolve)(f(),...e))(...t),u=e=>(0,i.resolve)(n(e,"state"),"telemetry-id");e.s(["configFile",0,e=>n(e,"config.json"),"telemetryIdFile",0,u],43477);let c=i.default.join(a.default.homedir(),".failproofai"),d=i.default.join(c,"instance-id");function o(e){return l.default.createHmac("sha256","failproofai-telemetry-v1").update(e).digest("hex")}function s(e){let t;try{if(t=u(),r.default.readFileSync(t,"utf-8").trim()===e)return}catch{try{t=u()}catch{return}}try{r.default.mkdirSync(i.default.dirname(t),{recursive:!0});let a=`${t}.${process.pid}.tmp`;r.default.writeFileSync(a,e,{encoding:"utf-8",mode:384}),r.default.renameSync(a,t)}catch{}}e.s(["getInstanceId",0,function(){if(t)return t;let e=function(){try{for(let e of(a.default.platform(),["/etc/machine-id","/var/lib/dbus/machine-id"]))try{let t=r.default.readFileSync(e,"utf-8").trim();if(t)return t}catch{}}catch{}}();if(e)return s(t=o(e)),t;let i=[a.default.hostname(),a.default.homedir(),a.default.platform(),a.default.arch(),a.default.cpus()[0]?.model??""].join(":");return i?s(t=o(i)):s(t=function(){try{let e=r.default.readFileSync(d,"utf-8").trim();if(e)return e}catch{}let e=l.default.randomUUID();try{r.default.mkdirSync(c,{recursive:!0}),r.default.writeFileSync(d,e,"utf-8")}catch{}return e}()),t},"hashToId",0,o],15855)}];
|
|
2
|
+
|
|
3
|
+
//# sourceMappingURL=lib_telemetry-id_ts_1k8gj9o._.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-
|
|
3
|
+
//# sourceMappingURL=node_modules_posthog-node_dist_entrypoints_index_node_mjs_04op_ou._.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-
|
|
3
|
+
//# sourceMappingURL=node_modules_posthog-node_dist_entrypoints_index_node_mjs_0dr20uz._.js.map
|