fullcourtdefense 2.0.0 → 2.2.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.
Files changed (437) hide show
  1. package/README.md +233 -53
  2. package/dist/adapters.d.ts +11 -0
  3. package/dist/adapters.js +16 -0
  4. package/dist/anthropic.d.ts +32 -0
  5. package/dist/anthropic.js +67 -0
  6. package/dist/argsBounds.d.ts +38 -0
  7. package/dist/argsBounds.js +84 -0
  8. package/dist/autoInstrument.d.ts +24 -7
  9. package/dist/autoInstrument.js +148 -23
  10. package/dist/circuitBreaker.d.ts +17 -0
  11. package/dist/circuitBreaker.js +39 -0
  12. package/dist/cliMoved.d.ts +4 -0
  13. package/dist/cliMoved.js +20 -0
  14. package/dist/client.d.ts +185 -1
  15. package/dist/client.js +1094 -87
  16. package/dist/errors.d.ts +73 -0
  17. package/dist/errors.js +110 -0
  18. package/dist/failMode.d.ts +96 -0
  19. package/dist/failMode.js +180 -0
  20. package/dist/identity.d.ts +32 -0
  21. package/dist/identity.js +120 -0
  22. package/dist/index.d.ts +5 -2
  23. package/dist/index.js +9 -1
  24. package/dist/lambda.d.ts +101 -0
  25. package/dist/lambda.js +357 -0
  26. package/dist/localDecision.d.ts +100 -0
  27. package/dist/localDecision.js +246 -0
  28. package/dist/localGate.d.ts +44 -0
  29. package/dist/localGate.js +114 -0
  30. package/dist/localSafety.d.ts +48 -0
  31. package/dist/localSafety.js +220 -0
  32. package/dist/policy/acorn.js +6365 -0
  33. package/dist/policy/actionPolicyEngine.d.ts +427 -0
  34. package/dist/policy/actionPolicyEngine.js +6481 -0
  35. package/dist/policy/detectionData.d.ts +21 -0
  36. package/dist/policy/detectionData.js +71 -0
  37. package/dist/policy/detectorRuntime.d.ts +27 -0
  38. package/dist/policy/detectorRuntime.js +58 -0
  39. package/dist/policy/deterministicGuard.d.ts +406 -0
  40. package/dist/policy/deterministicGuard.js +6651 -0
  41. package/dist/protect.d.ts +48 -0
  42. package/dist/protect.js +223 -1
  43. package/dist/recordQueue.d.ts +53 -0
  44. package/dist/recordQueue.js +132 -0
  45. package/dist/recordSpool.d.ts +17 -0
  46. package/dist/recordSpool.js +137 -0
  47. package/dist/types.d.ts +167 -2
  48. package/lambda.js +6 -0
  49. package/package.json +31 -27
  50. package/dist/cli/actionPolicyEngine.d.ts +0 -146
  51. package/dist/cli/actionPolicyEngine.js +0 -754
  52. package/dist/cli/api.d.ts +0 -116
  53. package/dist/cli/api.js +0 -65
  54. package/dist/cli/appDetection.d.ts +0 -8
  55. package/dist/cli/appDetection.js +0 -107
  56. package/dist/cli/attack-corpus/context_escape/context-escape-newline.yaml +0 -23
  57. package/dist/cli/attack-corpus/context_escape/context-escape-unicode.yaml +0 -14
  58. package/dist/cli/attack-corpus/context_escape/delimiter-json.yaml +0 -14
  59. package/dist/cli/attack-corpus/context_escape/delimiter-markdown.yaml +0 -22
  60. package/dist/cli/attack-corpus/context_escape/delimiter-xml.yaml +0 -19
  61. package/dist/cli/attack-corpus/context_escape/html-injection.yaml +0 -14
  62. package/dist/cli/attack-corpus/context_escape/javascript-injection.yaml +0 -13
  63. package/dist/cli/attack-corpus/data_extraction/adv26-adversarial-function-hallucination.yaml +0 -20
  64. package/dist/cli/attack-corpus/data_extraction/adv26-cot-hijack-debug-trace.yaml +0 -20
  65. package/dist/cli/attack-corpus/data_extraction/adv26-cot-hijack-verification.yaml +0 -18
  66. package/dist/cli/attack-corpus/data_extraction/adv26-crossmodal-diff.yaml +0 -22
  67. package/dist/cli/attack-corpus/data_extraction/adv26-crossmodal-graphql.yaml +0 -34
  68. package/dist/cli/attack-corpus/data_extraction/adv26-crossmodal-regex.yaml +0 -19
  69. package/dist/cli/attack-corpus/data_extraction/adv26-crossmodal-sql-prose.yaml +0 -18
  70. package/dist/cli/attack-corpus/data_extraction/adv26-meta-confidence-calibration.yaml +0 -21
  71. package/dist/cli/attack-corpus/data_extraction/adv26-meta-instruction-count.yaml +0 -18
  72. package/dist/cli/attack-corpus/data_extraction/adv26-meta-output-format.yaml +0 -16
  73. package/dist/cli/attack-corpus/data_extraction/adv26-meta-summarize-yourself.yaml +0 -19
  74. package/dist/cli/attack-corpus/data_extraction/adv26-semantic-decomp-definition.yaml +0 -15
  75. package/dist/cli/attack-corpus/data_extraction/adv26-semantic-decomp-fill-blank.yaml +0 -19
  76. package/dist/cli/attack-corpus/data_extraction/adv26-semantic-decomp-negation.yaml +0 -14
  77. package/dist/cli/attack-corpus/data_extraction/cloud-provider-discovery.yaml +0 -11
  78. package/dist/cli/attack-corpus/data_extraction/config-file-request.yaml +0 -11
  79. package/dist/cli/attack-corpus/data_extraction/cve-2025-echoleak.yaml +0 -17
  80. package/dist/cli/attack-corpus/data_extraction/data-api-key.yaml +0 -11
  81. package/dist/cli/attack-corpus/data_extraction/data-architecture.yaml +0 -11
  82. package/dist/cli/attack-corpus/data_extraction/data-conversation-history.yaml +0 -10
  83. package/dist/cli/attack-corpus/data_extraction/data-credit-card.yaml +0 -15
  84. package/dist/cli/attack-corpus/data_extraction/data-customer-list.yaml +0 -11
  85. package/dist/cli/attack-corpus/data_extraction/data-database.yaml +0 -11
  86. package/dist/cli/attack-corpus/data_extraction/data-employees.yaml +0 -11
  87. package/dist/cli/attack-corpus/data_extraction/data-export.yaml +0 -11
  88. package/dist/cli/attack-corpus/data_extraction/data-inference-v1.yaml +0 -10
  89. package/dist/cli/attack-corpus/data_extraction/data-inference-v2.yaml +0 -10
  90. package/dist/cli/attack-corpus/data_extraction/data-logs.yaml +0 -10
  91. package/dist/cli/attack-corpus/data_extraction/data-model-info.yaml +0 -10
  92. package/dist/cli/attack-corpus/data_extraction/data-password.yaml +0 -11
  93. package/dist/cli/attack-corpus/data_extraction/data-ssn.yaml +0 -11
  94. package/dist/cli/attack-corpus/data_extraction/data-training.yaml +0 -10
  95. package/dist/cli/attack-corpus/data_extraction/dependency-enum.yaml +0 -11
  96. package/dist/cli/attack-corpus/data_extraction/dialogflow-fulfillment-leak.yaml +0 -11
  97. package/dist/cli/attack-corpus/data_extraction/dialogflow-intent-leak.yaml +0 -11
  98. package/dist/cli/attack-corpus/data_extraction/error-induced-leak.yaml +0 -17
  99. package/dist/cli/attack-corpus/data_extraction/error-message-leak.yaml +0 -12
  100. package/dist/cli/attack-corpus/data_extraction/infra-fingerprint.yaml +0 -16
  101. package/dist/cli/attack-corpus/data_extraction/make-scenario-leak.yaml +0 -11
  102. package/dist/cli/attack-corpus/data_extraction/n8n-execution-data.yaml +0 -11
  103. package/dist/cli/attack-corpus/data_extraction/n8n-node-enumeration.yaml +0 -11
  104. package/dist/cli/attack-corpus/data_extraction/n8n-workflow-disclosure.yaml +0 -15
  105. package/dist/cli/attack-corpus/data_extraction/prompt-extraction-v1.yaml +0 -10
  106. package/dist/cli/attack-corpus/data_extraction/prompt-extraction-v2.yaml +0 -11
  107. package/dist/cli/attack-corpus/data_extraction/prompt-extraction-v3.yaml +0 -10
  108. package/dist/cli/attack-corpus/data_extraction/prompt-leak-completion.yaml +0 -10
  109. package/dist/cli/attack-corpus/data_extraction/prompt-leak-indirect.yaml +0 -10
  110. package/dist/cli/attack-corpus/data_extraction/rasa-domain-leak.yaml +0 -11
  111. package/dist/cli/attack-corpus/data_extraction/system-prompt-section.yaml +0 -14
  112. package/dist/cli/attack-corpus/data_extraction/tech-architecture.yaml +0 -16
  113. package/dist/cli/attack-corpus/data_extraction/tool-api-key-exfil.yaml +0 -15
  114. package/dist/cli/attack-corpus/data_extraction/tool-email-exfil.yaml +0 -14
  115. package/dist/cli/attack-corpus/data_extraction/tool-env-extraction.yaml +0 -14
  116. package/dist/cli/attack-corpus/data_extraction/tool-file-read.yaml +0 -16
  117. package/dist/cli/attack-corpus/data_extraction/tool-nosql-injection.yaml +0 -11
  118. package/dist/cli/attack-corpus/data_extraction/tool-payment-manipulation.yaml +0 -11
  119. package/dist/cli/attack-corpus/data_extraction/tool-price-manipulation.yaml +0 -11
  120. package/dist/cli/attack-corpus/data_extraction/tool-session-hijack.yaml +0 -11
  121. package/dist/cli/attack-corpus/data_extraction/tool-sql-injection.yaml +0 -13
  122. package/dist/cli/attack-corpus/data_extraction/tool-webhook-hijack.yaml +0 -13
  123. package/dist/cli/attack-corpus/data_extraction/version-fingerprint.yaml +0 -16
  124. package/dist/cli/attack-corpus/data_extraction/webhook-secret-extraction.yaml +0 -11
  125. package/dist/cli/attack-corpus/data_extraction/webhook-url-enum.yaml +0 -11
  126. package/dist/cli/attack-corpus/data_extraction/workflow-instance-id.yaml +0 -11
  127. package/dist/cli/attack-corpus/data_extraction/workflow-state-leak.yaml +0 -16
  128. package/dist/cli/attack-corpus/data_extraction/zapier-zap-leak.yaml +0 -11
  129. package/dist/cli/attack-corpus/encoding_attack/adv26-adversarial-token-confusion.yaml +0 -13
  130. package/dist/cli/attack-corpus/encoding_attack/base64-decode-request.yaml +0 -14
  131. package/dist/cli/attack-corpus/encoding_attack/base64-injection-v1.yaml +0 -14
  132. package/dist/cli/attack-corpus/encoding_attack/flip-attack-v1.yaml +0 -14
  133. package/dist/cli/attack-corpus/encoding_attack/flip-attack-v2.yaml +0 -14
  134. package/dist/cli/attack-corpus/encoding_attack/token-smuggling.yaml +0 -10
  135. package/dist/cli/attack-corpus/encoding_attack/unicode-homoglyph.yaml +0 -15
  136. package/dist/cli/attack-corpus/encoding_attack/unicode-invisible.yaml +0 -15
  137. package/dist/cli/attack-corpus/encoding_attack/unicode-rtl.yaml +0 -11
  138. package/dist/cli/attack-corpus/encoding_bypass/adv26-compound-encoding-chain.yaml +0 -19
  139. package/dist/cli/attack-corpus/encoding_bypass/adv26-smuggle-acrostic.yaml +0 -26
  140. package/dist/cli/attack-corpus/encoding_bypass/adv26-smuggle-ascii-art.yaml +0 -25
  141. package/dist/cli/attack-corpus/encoding_bypass/adv26-smuggle-emoji-cipher.yaml +0 -22
  142. package/dist/cli/attack-corpus/encoding_bypass/adv26-smuggle-first-word.yaml +0 -15
  143. package/dist/cli/attack-corpus/encoding_bypass/adv26-smuggle-pig-latin.yaml +0 -15
  144. package/dist/cli/attack-corpus/encoding_bypass/encoding-base64-v1.yaml +0 -11
  145. package/dist/cli/attack-corpus/encoding_bypass/encoding-base64-v2.yaml +0 -15
  146. package/dist/cli/attack-corpus/encoding_bypass/encoding-hex-v1.yaml +0 -11
  147. package/dist/cli/attack-corpus/encoding_bypass/encoding-leetspeak-v1.yaml +0 -10
  148. package/dist/cli/attack-corpus/encoding_bypass/encoding-morse-v1.yaml +0 -11
  149. package/dist/cli/attack-corpus/encoding_bypass/encoding-reverse-v1.yaml +0 -11
  150. package/dist/cli/attack-corpus/encoding_bypass/encoding-rot13-v1.yaml +0 -11
  151. package/dist/cli/attack-corpus/encoding_bypass/unicode-tag-injection.yaml +0 -10
  152. package/dist/cli/attack-corpus/encoding_bypass/zero-width-injection.yaml +0 -10
  153. package/dist/cli/attack-corpus/exploitation/exploit-command-injection.yaml +0 -12
  154. package/dist/cli/attack-corpus/exploitation/exploit-path-traversal.yaml +0 -12
  155. package/dist/cli/attack-corpus/exploitation/exploit-sql-injection.yaml +0 -12
  156. package/dist/cli/attack-corpus/exploitation/exploit-sql-union.yaml +0 -12
  157. package/dist/cli/attack-corpus/exploitation/exploit-template-injection.yaml +0 -12
  158. package/dist/cli/attack-corpus/glitch_token/glitch-davidjl.yaml +0 -10
  159. package/dist/cli/attack-corpus/glitch_token/glitch-solidgoldmagikarp.yaml +0 -10
  160. package/dist/cli/attack-corpus/harmful_content/dna-deepfake-guidance.yaml +0 -14
  161. package/dist/cli/attack-corpus/harmful_content/dna-discrimination.yaml +0 -14
  162. package/dist/cli/attack-corpus/harmful_content/dna-information-hazard.yaml +0 -14
  163. package/dist/cli/attack-corpus/harmful_content/dna-malicious-use-phishing.yaml +0 -14
  164. package/dist/cli/attack-corpus/harmful_content/dna-malware-assistance.yaml +0 -16
  165. package/dist/cli/attack-corpus/harmful_content/dna-misinformation-health.yaml +0 -17
  166. package/dist/cli/attack-corpus/jailbreak/adv26-adversarial-few-shot-poison.yaml +0 -27
  167. package/dist/cli/attack-corpus/jailbreak/adv26-adversarial-prompt-refraction.yaml +0 -19
  168. package/dist/cli/attack-corpus/jailbreak/adv26-adversarial-response-prefill.yaml +0 -25
  169. package/dist/cli/attack-corpus/jailbreak/adv26-compound-authority-technical.yaml +0 -24
  170. package/dist/cli/attack-corpus/jailbreak/adv26-context-error-recovery.yaml +0 -19
  171. package/dist/cli/attack-corpus/jailbreak/adv26-context-token-budget.yaml +0 -19
  172. package/dist/cli/attack-corpus/jailbreak/adv26-cot-hijack-proof.yaml +0 -20
  173. package/dist/cli/attack-corpus/jailbreak/adv26-cot-hijack-reasoning.yaml +0 -19
  174. package/dist/cli/attack-corpus/jailbreak/adv26-meta-alignment-test.yaml +0 -22
  175. package/dist/cli/attack-corpus/jailbreak/adv26-persona-memory.yaml +0 -17
  176. package/dist/cli/attack-corpus/jailbreak/adv26-persona-mirror.yaml +0 -16
  177. package/dist/cli/attack-corpus/jailbreak/adv26-persona-split.yaml +0 -17
  178. package/dist/cli/attack-corpus/jailbreak/adv26-persona-timetravel.yaml +0 -15
  179. package/dist/cli/attack-corpus/jailbreak/dan-anti.yaml +0 -16
  180. package/dist/cli/attack-corpus/jailbreak/dan-dude.yaml +0 -16
  181. package/dist/cli/attack-corpus/jailbreak/dan-jailbreak-v1.yaml +0 -21
  182. package/dist/cli/attack-corpus/jailbreak/dan-jailbreak-v2.yaml +0 -19
  183. package/dist/cli/attack-corpus/jailbreak/dan-stan.yaml +0 -16
  184. package/dist/cli/attack-corpus/jailbreak/debug-mode-activation.yaml +0 -20
  185. package/dist/cli/attack-corpus/jailbreak/iris-self-jailbreak.yaml +0 -23
  186. package/dist/cli/attack-corpus/jailbreak/logic-trap-moral.yaml +0 -20
  187. package/dist/cli/attack-corpus/jailbreak/logic-trap-paradox.yaml +0 -17
  188. package/dist/cli/attack-corpus/jailbreak/policy-puppetry-json.yaml +0 -25
  189. package/dist/cli/attack-corpus/jailbreak/policy-puppetry-xml.yaml +0 -20
  190. package/dist/cli/attack-corpus/jailbreak/simulation-mode.yaml +0 -19
  191. package/dist/cli/attack-corpus/latent_injection/adv26-compound-trojan-doc.yaml +0 -26
  192. package/dist/cli/attack-corpus/latent_injection/latent-code-comment-injection.yaml +0 -18
  193. package/dist/cli/attack-corpus/latent_injection/latent-email-injection.yaml +0 -23
  194. package/dist/cli/attack-corpus/latent_injection/latent-report-injection.yaml +0 -21
  195. package/dist/cli/attack-corpus/latent_injection/latent-resume-injection.yaml +0 -23
  196. package/dist/cli/attack-corpus/latent_injection/latent-whois-snippet.yaml +0 -19
  197. package/dist/cli/attack-corpus/multi-turn/multiturn-context-confusion.yaml +0 -20
  198. package/dist/cli/attack-corpus/multi-turn/multiturn-emergency.yaml +0 -20
  199. package/dist/cli/attack-corpus/multi-turn/multiturn-employee-impersonation.yaml +0 -20
  200. package/dist/cli/attack-corpus/multi-turn/multiturn-example-injection.yaml +0 -20
  201. package/dist/cli/attack-corpus/multi-turn/multiturn-jailbreak-buildup.yaml +0 -20
  202. package/dist/cli/attack-corpus/multi-turn/multiturn-memory-manipulation.yaml +0 -20
  203. package/dist/cli/attack-corpus/multi-turn/multiturn-privilege-escalation.yaml +0 -23
  204. package/dist/cli/attack-corpus/multi-turn/multiturn-split-request.yaml +0 -20
  205. package/dist/cli/attack-corpus/multi-turn/multiturn-trust-building.yaml +0 -19
  206. package/dist/cli/attack-corpus/multilingual/multilingual-mixed.yaml +0 -10
  207. package/dist/cli/attack-corpus/multilingual/multilingual-spanish.yaml +0 -10
  208. package/dist/cli/attack-corpus/prompt_injection/adv26-context-fake-history.yaml +0 -16
  209. package/dist/cli/attack-corpus/prompt_injection/adv26-context-sandwich.yaml +0 -18
  210. package/dist/cli/attack-corpus/prompt_injection/adv26-context-system-message.yaml +0 -19
  211. package/dist/cli/attack-corpus/prompt_injection/adv26-crossmodal-yaml.yaml +0 -30
  212. package/dist/cli/attack-corpus/prompt_injection/adv26-semantic-decomp-stepwise.yaml +0 -16
  213. package/dist/cli/attack-corpus/prompt_injection/context-json-injection.yaml +0 -15
  214. package/dist/cli/attack-corpus/prompt_injection/context-markdown-injection.yaml +0 -26
  215. package/dist/cli/attack-corpus/prompt_injection/context-xml-injection.yaml +0 -19
  216. package/dist/cli/attack-corpus/prompt_injection/continuation-code.yaml +0 -16
  217. package/dist/cli/attack-corpus/prompt_injection/continuation-story.yaml +0 -10
  218. package/dist/cli/attack-corpus/prompt_injection/cve-2025-copilot.yaml +0 -17
  219. package/dist/cli/attack-corpus/prompt_injection/ignore-instructions-v1.yaml +0 -14
  220. package/dist/cli/attack-corpus/prompt_injection/ignore-instructions-v2.yaml +0 -16
  221. package/dist/cli/attack-corpus/prompt_injection/ignore-instructions-v3.yaml +0 -18
  222. package/dist/cli/attack-corpus/prompt_injection/indirect-file.yaml +0 -10
  223. package/dist/cli/attack-corpus/prompt_injection/indirect-url.yaml +0 -10
  224. package/dist/cli/attack-corpus/prompt_injection/instruction-hierarchy.yaml +0 -20
  225. package/dist/cli/attack-corpus/prompt_injection/multilang-chain.yaml +0 -16
  226. package/dist/cli/attack-corpus/prompt_injection/multilang-chinese.yaml +0 -10
  227. package/dist/cli/attack-corpus/prompt_injection/multilang-japanese.yaml +0 -11
  228. package/dist/cli/attack-corpus/prompt_injection/multilang-mixed.yaml +0 -10
  229. package/dist/cli/attack-corpus/prompt_injection/multilang-polish.yaml +0 -11
  230. package/dist/cli/attack-corpus/prompt_injection/multilang-spanish.yaml +0 -14
  231. package/dist/cli/attack-corpus/prompt_injection/nested-instruction.yaml +0 -22
  232. package/dist/cli/attack-corpus/prompt_injection/template-injection-v1.yaml +0 -14
  233. package/dist/cli/attack-corpus/prompt_injection/template-injection-v2.yaml +0 -10
  234. package/dist/cli/attack-corpus/prompt_injection/tool-file-write.yaml +0 -13
  235. package/dist/cli/attack-corpus/prompt_injection/tool-function-override.yaml +0 -13
  236. package/dist/cli/attack-corpus/prompt_injection/tool-log-injection.yaml +0 -13
  237. package/dist/cli/attack-corpus/prompt_injection/tool-orchestration-abuse.yaml +0 -14
  238. package/dist/cli/attack-corpus/prompt_injection/tool-session-fixation.yaml +0 -12
  239. package/dist/cli/attack-corpus/role_manipulation/role-reversal-v1.yaml +0 -20
  240. package/dist/cli/attack-corpus/role_manipulation/role-reversal-v2.yaml +0 -16
  241. package/dist/cli/attack-corpus/social_engineering/adv26-compound-compliance-trap.yaml +0 -23
  242. package/dist/cli/attack-corpus/social_engineering/adv26-compound-emotional-technical.yaml +0 -18
  243. package/dist/cli/attack-corpus/social_engineering/adv26-cot-hijack-socratic.yaml +0 -19
  244. package/dist/cli/attack-corpus/social_engineering/adv26-persona-dying.yaml +0 -15
  245. package/dist/cli/attack-corpus/social_engineering/adv26-reward-consensus.yaml +0 -17
  246. package/dist/cli/attack-corpus/social_engineering/adv26-reward-gradient.yaml +0 -21
  247. package/dist/cli/attack-corpus/social_engineering/adv26-reward-helpful-framing.yaml +0 -17
  248. package/dist/cli/attack-corpus/social_engineering/adv26-reward-praise-prime.yaml +0 -13
  249. package/dist/cli/attack-corpus/social_engineering/adv26-reward-punishment.yaml +0 -13
  250. package/dist/cli/attack-corpus/social_engineering/adv26-semantic-decomp-analogy.yaml +0 -16
  251. package/dist/cli/attack-corpus/social_engineering/emotional-authority.yaml +0 -14
  252. package/dist/cli/attack-corpus/social_engineering/emotional-urgency.yaml +0 -14
  253. package/dist/cli/attack-corpus/social_engineering/grandma-bedtime-v1.yaml +0 -21
  254. package/dist/cli/attack-corpus/social_engineering/grandma-bedtime-v2.yaml +0 -17
  255. package/dist/cli/attack-corpus/social_engineering/grandma-colorful-words.yaml +0 -14
  256. package/dist/cli/attack-corpus/social_engineering/hypothetical-fiction.yaml +0 -10
  257. package/dist/cli/attack-corpus/social_engineering/hypothetical-research.yaml +0 -10
  258. package/dist/cli/attack-corpus/social_engineering/hypothetical-training.yaml +0 -13
  259. package/dist/cli/attack-corpus/social_engineering/hypothetical-v1.yaml +0 -17
  260. package/dist/cli/attack-corpus/social_engineering/hypothetical-v2.yaml +0 -14
  261. package/dist/cli/attack-corpus/social_engineering/hypothetical-v3.yaml +0 -14
  262. package/dist/cli/attack-corpus/social_engineering/meta-explanation.yaml +0 -14
  263. package/dist/cli/attack-corpus/social_engineering/phrasing-comparative.yaml +0 -10
  264. package/dist/cli/attack-corpus/social_engineering/phrasing-educational.yaml +0 -14
  265. package/dist/cli/attack-corpus/social_engineering/phrasing-future-tense.yaml +0 -10
  266. package/dist/cli/attack-corpus/social_engineering/phrasing-past-tense.yaml +0 -10
  267. package/dist/cli/attack-corpus/social_engineering/phrasing-third-person.yaml +0 -10
  268. package/dist/cli/attack-corpus/social_engineering/privilege-escalation-v1.yaml +0 -14
  269. package/dist/cli/attack-corpus/social_engineering/privilege-escalation-v2.yaml +0 -14
  270. package/dist/cli/attack-corpus/social_engineering/recursive-explanation.yaml +0 -15
  271. package/dist/cli/attack-corpus/social_engineering/smuggle-academic-paper.yaml +0 -10
  272. package/dist/cli/attack-corpus/social_engineering/smuggle-function-masking.yaml +0 -19
  273. package/dist/cli/attack-corpus/social_engineering/smuggle-hypothetical-response.yaml +0 -10
  274. package/dist/cli/attack-corpus/social_engineering/smuggle-roleplay-interviewer.yaml +0 -12
  275. package/dist/cli/attack-corpus/social_engineering/smuggle-translation-mask.yaml +0 -12
  276. package/dist/cli/attack-corpus/social_engineering/tool-admin-impersonation.yaml +0 -16
  277. package/dist/cli/attack-corpus/social_engineering/tool-sudo-mode.yaml +0 -17
  278. package/dist/cli/attack-corpus/stress_test/context-window-overflow.yaml +0 -17
  279. package/dist/cli/attack-corpus/stress_test/extreme-payload-50k.yaml +0 -13
  280. package/dist/cli/attack-corpus/stress_test/large-payload-10k.yaml +0 -12
  281. package/dist/cli/attack-corpus/stress_test/large-payload-5k.yaml +0 -12
  282. package/dist/cli/attack-corpus/stress_test/long-prompt-exhaustion.yaml +0 -19
  283. package/dist/cli/attack-corpus/stress_test/stress-large-payload.yaml +0 -16
  284. package/dist/cli/attack-corpus/stress_test/stress-repetition.yaml +0 -14
  285. package/dist/cli/backupManifest.d.ts +0 -7
  286. package/dist/cli/backupManifest.js +0 -108
  287. package/dist/cli/commands/agentCi.d.ts +0 -15
  288. package/dist/cli/commands/agentCi.js +0 -418
  289. package/dist/cli/commands/approve.d.ts +0 -17
  290. package/dist/cli/commands/approve.js +0 -40
  291. package/dist/cli/commands/autoProtect.d.ts +0 -10
  292. package/dist/cli/commands/autoProtect.js +0 -154
  293. package/dist/cli/commands/ciProtect.d.ts +0 -44
  294. package/dist/cli/commands/ciProtect.js +0 -123
  295. package/dist/cli/commands/clipboardScan.d.ts +0 -2
  296. package/dist/cli/commands/clipboardScan.js +0 -51
  297. package/dist/cli/commands/cmdGuard.d.ts +0 -41
  298. package/dist/cli/commands/cmdGuard.js +0 -411
  299. package/dist/cli/commands/configure.d.ts +0 -10
  300. package/dist/cli/commands/configure.js +0 -131
  301. package/dist/cli/commands/credits.d.ts +0 -6
  302. package/dist/cli/commands/credits.js +0 -21
  303. package/dist/cli/commands/daemon.d.ts +0 -120
  304. package/dist/cli/commands/daemon.js +0 -2449
  305. package/dist/cli/commands/demoActions.d.ts +0 -117
  306. package/dist/cli/commands/demoActions.js +0 -450
  307. package/dist/cli/commands/desktopChatGuard.d.ts +0 -54
  308. package/dist/cli/commands/desktopChatGuard.js +0 -629
  309. package/dist/cli/commands/deterministicGuard.d.ts +0 -102
  310. package/dist/cli/commands/deterministicGuard.js +0 -1281
  311. package/dist/cli/commands/discover.d.ts +0 -92
  312. package/dist/cli/commands/discover.js +0 -1125
  313. package/dist/cli/commands/discoverAgentFiles.d.ts +0 -36
  314. package/dist/cli/commands/discoverAgentFiles.js +0 -345
  315. package/dist/cli/commands/discoverBlastRadius.d.ts +0 -36
  316. package/dist/cli/commands/discoverBlastRadius.js +0 -201
  317. package/dist/cli/commands/discoverPaths.d.ts +0 -83
  318. package/dist/cli/commands/discoverPaths.js +0 -537
  319. package/dist/cli/commands/discoverProxy.d.ts +0 -46
  320. package/dist/cli/commands/discoverProxy.js +0 -302
  321. package/dist/cli/commands/discoverSchedule.d.ts +0 -12
  322. package/dist/cli/commands/discoverSchedule.js +0 -209
  323. package/dist/cli/commands/discoverSecrets.d.ts +0 -41
  324. package/dist/cli/commands/discoverSecrets.js +0 -608
  325. package/dist/cli/commands/doctor.d.ts +0 -11
  326. package/dist/cli/commands/doctor.js +0 -297
  327. package/dist/cli/commands/ephemeralStack.d.ts +0 -82
  328. package/dist/cli/commands/ephemeralStack.js +0 -185
  329. package/dist/cli/commands/flushSpool.d.ts +0 -13
  330. package/dist/cli/commands/flushSpool.js +0 -28
  331. package/dist/cli/commands/hook.d.ts +0 -141
  332. package/dist/cli/commands/hook.js +0 -1679
  333. package/dist/cli/commands/init.d.ts +0 -1
  334. package/dist/cli/commands/init.js +0 -95
  335. package/dist/cli/commands/installAll.d.ts +0 -22
  336. package/dist/cli/commands/installAll.js +0 -186
  337. package/dist/cli/commands/installClaudeHook.d.ts +0 -39
  338. package/dist/cli/commands/installClaudeHook.js +0 -336
  339. package/dist/cli/commands/installCursorHook.d.ts +0 -33
  340. package/dist/cli/commands/installCursorHook.js +0 -380
  341. package/dist/cli/commands/knownMcpServers.d.ts +0 -8
  342. package/dist/cli/commands/knownMcpServers.js +0 -113
  343. package/dist/cli/commands/local-scan.d.ts +0 -44
  344. package/dist/cli/commands/local-scan.js +0 -3003
  345. package/dist/cli/commands/login.d.ts +0 -17
  346. package/dist/cli/commands/login.js +0 -75
  347. package/dist/cli/commands/mcpGateway.d.ts +0 -119
  348. package/dist/cli/commands/mcpGateway.js +0 -2987
  349. package/dist/cli/commands/onboard.d.ts +0 -41
  350. package/dist/cli/commands/onboard.js +0 -713
  351. package/dist/cli/commands/onboardingJournal.d.ts +0 -20
  352. package/dist/cli/commands/onboardingJournal.js +0 -104
  353. package/dist/cli/commands/posixShellGuard.d.ts +0 -26
  354. package/dist/cli/commands/posixShellGuard.js +0 -410
  355. package/dist/cli/commands/protectionRepair.d.ts +0 -14
  356. package/dist/cli/commands/protectionRepair.js +0 -24
  357. package/dist/cli/commands/restartNotice.d.ts +0 -2
  358. package/dist/cli/commands/restartNotice.js +0 -14
  359. package/dist/cli/commands/scan.d.ts +0 -48
  360. package/dist/cli/commands/scan.js +0 -134
  361. package/dist/cli/commands/shellGuard.d.ts +0 -96
  362. package/dist/cli/commands/shellGuard.js +0 -880
  363. package/dist/cli/commands/taintLedger.d.ts +0 -108
  364. package/dist/cli/commands/taintLedger.js +0 -587
  365. package/dist/cli/commands/uninstallAll.d.ts +0 -67
  366. package/dist/cli/commands/uninstallAll.js +0 -454
  367. package/dist/cli/commands/verifyRemoved.d.ts +0 -24
  368. package/dist/cli/commands/verifyRemoved.js +0 -294
  369. package/dist/cli/commands/watchdog.d.ts +0 -28
  370. package/dist/cli/commands/watchdog.js +0 -158
  371. package/dist/cli/commands/windowsAudit.d.ts +0 -92
  372. package/dist/cli/commands/windowsAudit.js +0 -479
  373. package/dist/cli/commands/workloadProtect.d.ts +0 -61
  374. package/dist/cli/commands/workloadProtect.js +0 -173
  375. package/dist/cli/config.d.ts +0 -130
  376. package/dist/cli/config.js +0 -583
  377. package/dist/cli/credentialStore.d.ts +0 -19
  378. package/dist/cli/credentialStore.js +0 -136
  379. package/dist/cli/daemonForensics.d.ts +0 -178
  380. package/dist/cli/daemonForensics.js +0 -318
  381. package/dist/cli/describeError.d.ts +0 -17
  382. package/dist/cli/describeError.js +0 -74
  383. package/dist/cli/devConfirm.d.ts +0 -78
  384. package/dist/cli/devConfirm.js +0 -241
  385. package/dist/cli/discoveryMarker.d.ts +0 -9
  386. package/dist/cli/discoveryMarker.js +0 -81
  387. package/dist/cli/distress.d.ts +0 -124
  388. package/dist/cli/distress.js +0 -245
  389. package/dist/cli/envDiagnostics.d.ts +0 -53
  390. package/dist/cli/envDiagnostics.js +0 -114
  391. package/dist/cli/honeypot.d.ts +0 -45
  392. package/dist/cli/honeypot.js +0 -190
  393. package/dist/cli/hookIo.d.ts +0 -43
  394. package/dist/cli/hookIo.js +0 -189
  395. package/dist/cli/hookSlim.d.ts +0 -32
  396. package/dist/cli/hookSlim.js +0 -142
  397. package/dist/cli/index.d.ts +0 -2
  398. package/dist/cli/index.js +0 -1141
  399. package/dist/cli/integrity.d.ts +0 -23
  400. package/dist/cli/integrity.js +0 -159
  401. package/dist/cli/localSafetySnapshot.d.ts +0 -49
  402. package/dist/cli/localSafetySnapshot.js +0 -254
  403. package/dist/cli/machineActionVerify.d.ts +0 -58
  404. package/dist/cli/machineActionVerify.js +0 -160
  405. package/dist/cli/machineIdentity.d.ts +0 -23
  406. package/dist/cli/machineIdentity.js +0 -235
  407. package/dist/cli/machineKeyFile.d.ts +0 -25
  408. package/dist/cli/machineKeyFile.js +0 -226
  409. package/dist/cli/notify.d.ts +0 -30
  410. package/dist/cli/notify.js +0 -139
  411. package/dist/cli/output.d.ts +0 -11
  412. package/dist/cli/output.js +0 -292
  413. package/dist/cli/perfSnapshot.d.ts +0 -113
  414. package/dist/cli/perfSnapshot.js +0 -274
  415. package/dist/cli/policyGateHealth.d.ts +0 -45
  416. package/dist/cli/policyGateHealth.js +0 -135
  417. package/dist/cli/pollLoop.d.ts +0 -78
  418. package/dist/cli/pollLoop.js +0 -160
  419. package/dist/cli/runtimeConfig.d.ts +0 -183
  420. package/dist/cli/runtimeConfig.js +0 -474
  421. package/dist/cli/securityAgents.d.ts +0 -26
  422. package/dist/cli/securityAgents.js +0 -65
  423. package/dist/cli/selfTest.d.ts +0 -48
  424. package/dist/cli/selfTest.js +0 -212
  425. package/dist/cli/selfUpdate.d.ts +0 -101
  426. package/dist/cli/selfUpdate.js +0 -515
  427. package/dist/cli/sessionLimits.d.ts +0 -76
  428. package/dist/cli/sessionLimits.js +0 -330
  429. package/dist/cli/telemetry.d.ts +0 -134
  430. package/dist/cli/telemetry.js +0 -433
  431. package/dist/cli/verdictIpc.d.ts +0 -30
  432. package/dist/cli/verdictIpc.js +0 -244
  433. package/dist/cli/verdictIpcClient.d.ts +0 -103
  434. package/dist/cli/verdictIpcClient.js +0 -251
  435. package/dist/cli/version.json +0 -3
  436. package/dist/cli/windowsTaskState.d.ts +0 -40
  437. package/dist/cli/windowsTaskState.js +0 -43
package/dist/client.js CHANGED
@@ -5,15 +5,30 @@ exports._clearShieldModeCache = _clearShieldModeCache;
5
5
  const circuitBreaker_1 = require("./circuitBreaker");
6
6
  Object.defineProperty(exports, "_clearCircuitBreakers", { enumerable: true, get: function () { return circuitBreaker_1._clearCircuitBreakers; } });
7
7
  const protect_1 = require("./protect");
8
+ const anthropic_1 = require("./anthropic");
9
+ const failMode_1 = require("./failMode");
10
+ const identity_1 = require("./identity");
11
+ const errors_1 = require("./errors");
12
+ const recordSpool_1 = require("./recordSpool");
13
+ const argsBounds_1 = require("./argsBounds");
14
+ const localDecision_1 = require("./localDecision");
15
+ const recordQueue_1 = require("./recordQueue");
8
16
  const DEFAULT_API_URL = 'https://api.fullcourtdefense.ai';
9
17
  const SHIELD_ID_ENV_VARS = ['FCD_SHIELD_ID', 'FULLCOURTDEFENSE_SHIELD_ID', 'AGENTGUARD_SHIELD_ID'];
10
18
  const SHIELD_KEY_ENV_VARS = ['FCD_SHIELD_KEY', 'FULLCOURTDEFENSE_SHIELD_KEY', 'AGENTGUARD_SHIELD_KEY'];
11
19
  const API_URL_ENV_VARS = ['FCD_API_URL', 'FULLCOURTDEFENSE_API_URL'];
12
20
  const API_KEY_ENV_VARS = ['FCD_API_KEY', 'FULLCOURTDEFENSE_API_KEY', 'BOTGUARD_API_KEY'];
13
- const AGENT_ID_ENV_VARS = ['FCD_AGENT_ID', 'FULLCOURTDEFENSE_AGENT_ID'];
14
21
  const AGENT_INSTANCE_ID_ENV_VARS = ['FCD_AGENT_INSTANCE_ID', 'FULLCOURTDEFENSE_AGENT_INSTANCE_ID'];
15
22
  const ENVIRONMENT_ENV_VARS = ['FCD_ENVIRONMENT', 'FULLCOURTDEFENSE_ENVIRONMENT', 'NODE_ENV'];
16
23
  const TEXT_SCAN_ENV_VARS = ['FCD_TEXT_SCAN', 'FULLCOURTDEFENSE_TEXT_SCAN'];
24
+ const DECISION_MODE_ENV_VARS = ['FCD_DECISION_MODE', 'FULLCOURTDEFENSE_DECISION_MODE'];
25
+ const COLD_START_WAIT_ENV_VARS = ['FCD_COLD_START_WAIT_MS', 'FULLCOURTDEFENSE_COLD_START_WAIT_MS'];
26
+ /** Local decisions: the longest a call waits for the first bundle, measured from the client's construction. */
27
+ const DEFAULT_COLD_START_WAIT_MS = 1500;
28
+ function parseDecisionMode(raw) {
29
+ const value = (raw || '').trim().toLowerCase();
30
+ return value === 'local' || value === 'server' ? value : undefined;
31
+ }
17
32
  function readEnv(names) {
18
33
  const env = globalThis.process?.env;
19
34
  if (!env)
@@ -87,7 +102,13 @@ function extractShield(data) {
87
102
  }
88
103
  function validateShieldId(shieldId) {
89
104
  if (!shieldId || typeof shieldId !== 'string' || !shieldId.trim()) {
105
+ // A common mix-up: FCD_API_KEY is the LLM provider key for the chat gateway only; tool
106
+ // gating needs the shield id (and its key when the shield is locked).
107
+ const apiKeyHint = readEnv(API_KEY_ENV_VARS)
108
+ ? 'FCD_API_KEY is set, but it is not a shield: tool gating needs FCD_SHIELD_ID (sh_...) and, for a locked shield, FCD_SHIELD_KEY.\n'
109
+ : '';
90
110
  throw new Error('FullCourtDefense: shieldId is required.\n' +
111
+ apiKeyHint +
91
112
  'Pass it as: new FullCourtDefense({ shieldId: "sh_your_shield_id" })\n' +
92
113
  'Or set one of these env vars: FCD_SHIELD_ID, FULLCOURTDEFENSE_SHIELD_ID, AGENTGUARD_SHIELD_ID\n' +
93
114
  'Get a free Shield ID at: https://fullcourtdefense.ai → Sign up → Shield → Create Shield');
@@ -124,17 +145,31 @@ function sleep(ms) {
124
145
  // shield for MODE_CACHE_TTL_MS so the hot path never waits on a mode lookup:
125
146
  // a console flip (monitor <-> block) takes effect within one TTL window.
126
147
  // Lookup failures fall back to the last-known mode (stale-while-error); with
127
- // no cache at all we assume 'block' so the sync path (with its own fail-open
128
- // guard) still attempts a real verdict.
148
+ // no live answer yet in this process we use the shield's mode recorded on the
149
+ // agent (FCD_MODE_AT_PROTECT, kept in step with the shield by FullCourtDefense)
150
+ // and otherwise assume 'block' so the sync path (with its own fail-open guard)
151
+ // still attempts a real verdict. A mode no live answer confirmed is never
152
+ // silent: a Monitor call on it is reported once the API answers (failMode.ts,
153
+ // `unconfirmed_monitor`). The same lookup brings the agent's never-allowed
154
+ // rules (`agentRules=1`), kept through an outage for the FCD_FAIL_MODE decision.
129
155
  const MODE_CACHE_TTL_MS = 60000;
130
156
  const MODE_FETCH_TIMEOUT_MS = 1500;
131
157
  // After a failed mode lookup, don't retry for this window — avoids adding the
132
158
  // lookup timeout to every call while the backend is down.
133
159
  const MODE_FAILURE_RETRY_MS = 5000;
160
+ /** How often local decisions refresh the bundle in the background (never on a tool call's path). */
161
+ const BUNDLE_REFRESH_MS = 60000;
162
+ /** A background bundle fetch may take longer than a hot-path lookup: nothing waits for it. */
163
+ const BUNDLE_FETCH_TIMEOUT_MS = 5000;
164
+ const bundleRefreshTimers = new Map();
134
165
  const modeCache = new Map();
135
166
  /** Test hook — clears the module-level shield mode cache. */
136
167
  function _clearShieldModeCache() {
137
168
  modeCache.clear();
169
+ replayedShields.clear();
170
+ for (const timer of bundleRefreshTimers.values())
171
+ clearInterval(timer);
172
+ bundleRefreshTimers.clear();
138
173
  }
139
174
  // Built-in high-risk operations/tools that fail CLOSED when the backend is
140
175
  // unreachable in block mode. Irreversible/high-impact actions must never
@@ -148,8 +183,123 @@ const DEFAULT_FAIL_CLOSED_OPERATIONS = [
148
183
  function errorMessage(error) {
149
184
  return error instanceof Error ? error.message : String(error);
150
185
  }
186
+ /** The error's type name (`TypeError`, `AbortError`) for records: never its message. */
187
+ function errorTypeName(error) {
188
+ const name = error instanceof Error
189
+ ? (error.name || error.constructor?.name || 'Error')
190
+ : typeof error;
191
+ return /^[A-Za-z_$][A-Za-z0-9_.$:-]{0,79}$/.test(name) ? name : 'Error';
192
+ }
193
+ /** Longest a monitor-mode `awaitRecord` call waits for its record after the tool finished. */
194
+ const RECORD_FLUSH_MAX_MS = 1500;
195
+ /** Wait for `work`, at most `ms`; never throws. */
196
+ async function settleWithin(work, ms) {
197
+ let cap;
198
+ await Promise.race([work.catch(() => undefined), new Promise((resolve) => { cap = setTimeout(resolve, ms); })]);
199
+ if (cap !== undefined)
200
+ clearTimeout(cap);
201
+ }
202
+ const EXIT_FLUSH_MAX_MS = 1500;
203
+ const FAILED_RECORDS_MAX = 200;
204
+ const pendingRecords = new Set();
205
+ const failedRecords = [];
206
+ /** Clients holding calls in memory (spooled while the API was down, or waiting for the first mode lookup). */
207
+ const liveClients = new Set();
208
+ const replayedShields = new Set();
209
+ let exitHooksInstalled = false;
210
+ let exitFlushRunning = false;
211
+ function toSpooled(entry) {
212
+ try {
213
+ return { path: entry.path, body: JSON.parse(entry.json), shieldId: entry.shieldId, at: entry.at };
214
+ }
215
+ catch {
216
+ return undefined;
217
+ }
218
+ }
219
+ /** Write everything still unsent to the local spool (synchronous: it runs at `exit`). */
220
+ function persistLeftovers() {
221
+ const records = [];
222
+ const keep = (entry) => {
223
+ const record = toSpooled(entry);
224
+ if (record)
225
+ records.push(record);
226
+ };
227
+ for (const entry of pendingRecords)
228
+ keep(entry);
229
+ pendingRecords.clear();
230
+ for (const entry of failedRecords)
231
+ keep(entry);
232
+ failedRecords.length = 0;
233
+ for (const client of liveClients)
234
+ records.push(...client._takeUnsentForSpool());
235
+ liveClients.clear();
236
+ (0, recordSpool_1.writeSpool)(records);
237
+ }
238
+ async function flushAtExit() {
239
+ if (exitFlushRunning)
240
+ return;
241
+ exitFlushRunning = true;
242
+ try {
243
+ const work = [];
244
+ for (const entry of pendingRecords)
245
+ if (entry.done)
246
+ work.push(entry.done);
247
+ for (const client of liveClients)
248
+ work.push(client._flushForExit());
249
+ if (work.length > 0)
250
+ await settleWithin(Promise.all(work), EXIT_FLUSH_MAX_MS);
251
+ }
252
+ finally {
253
+ persistLeftovers();
254
+ exitFlushRunning = false;
255
+ }
256
+ }
257
+ function installExitHooks() {
258
+ if (exitHooksInstalled)
259
+ return;
260
+ const proc = globalThis.process;
261
+ if (!proc || typeof proc.on !== 'function')
262
+ return;
263
+ exitHooksInstalled = true;
264
+ try {
265
+ proc.on('beforeExit', () => { void flushAtExit(); });
266
+ proc.on('exit', () => { persistLeftovers(); });
267
+ for (const signal of ['SIGINT', 'SIGTERM']) {
268
+ const handler = () => {
269
+ // Another handler of the host shuts down its own way (and `exit` still runs); when ours is the only
270
+ // one, the signal would have ended the process: keep the records, then end it the same way.
271
+ if (proc.listenerCount(signal) > 1)
272
+ return;
273
+ persistLeftovers();
274
+ proc.removeListener(signal, handler);
275
+ proc.kill(proc.pid, signal);
276
+ };
277
+ proc.on(signal, handler);
278
+ }
279
+ }
280
+ catch {
281
+ // no process events here (a worker, an unusual host): the in-process tracking still applies
282
+ }
283
+ }
284
+ function keepFailed(entry) {
285
+ if (failedRecords.length >= FAILED_RECORDS_MAX)
286
+ failedRecords.shift();
287
+ failedRecords.push(entry);
288
+ }
151
289
  class FullCourtDefense {
152
290
  constructor(config = {}) {
291
+ /** Calls decided without a check while the API was unreachable; sent (the alert) once it is back. */
292
+ this.skippedChecks = new failMode_1.SkippedCheckSpool();
293
+ /** Calls that ran before the first mode lookup answered; their record follows the answer (and survives an early exit). */
294
+ this.awaitingMode = new Set();
295
+ /** HTTP statuses (401 / 403 / 404 / 400) already reported on stderr by this client. */
296
+ this.reportedConfigErrors = new Set();
297
+ /** O4: a Monitor call ran with a refused key or shield and stderr said so (once, without onDegrade). */
298
+ this.warnedMonitorConfigError = false;
299
+ /** One warning when a Block-mode call ran before any policy bundle was available. */
300
+ this.warnedNoBundle = false;
301
+ /** guardToolCall's calls: the local decision's record is handed back here and written after the tool ran. */
302
+ this.deferredLocalRecords = new WeakMap();
153
303
  const shieldId = config.shieldId ?? readEnv(SHIELD_ID_ENV_VARS);
154
304
  validateShieldId(shieldId);
155
305
  this.config = {
@@ -161,9 +311,10 @@ class FullCourtDefense {
161
311
  monitorMode: config.monitorMode ?? 'auto',
162
312
  failOpen: config.failOpen !== false,
163
313
  scanTimeoutMs: config.scanTimeoutMs || 3000,
314
+ toolCheckTimeoutMs: config.toolCheckTimeoutMs || config.scanTimeoutMs || 1500,
164
315
  };
165
316
  this._identity = {
166
- agentId: config.agentId ?? readEnv(AGENT_ID_ENV_VARS),
317
+ ...(0, identity_1.resolveAgentId)(config.agentId),
167
318
  agentInstanceId: config.agentInstanceId ?? readEnv(AGENT_INSTANCE_ID_ENV_VARS) ?? randomInstanceId(),
168
319
  environment: config.environment ?? readEnv(ENVIRONMENT_ENV_VARS),
169
320
  };
@@ -172,11 +323,154 @@ class FullCourtDefense {
172
323
  };
173
324
  this.failClosedOperations = (config.failClosedOperations ?? DEFAULT_FAIL_CLOSED_OPERATIONS)
174
325
  .map((s) => s.toLowerCase());
326
+ // Owner decision 2026-10-27 (replaces closed): unset = tiered. Enforce with FullCourtDefense unreachable stops the never-allowed rules and the high-risk names, and runs the rest (reported once the API is back).
327
+ this.failMode = config.failMode ?? (0, failMode_1.parseFailMode)(readEnv(failMode_1.FAIL_MODE_ENV_VARS)) ?? 'tiered';
328
+ this.modeAtProtect = config.modeAtProtect ?? (0, failMode_1.parseModeAtProtect)(readEnv(failMode_1.MODE_AT_PROTECT_ENV_VARS));
175
329
  this.onDegrade = config.onDegrade;
330
+ this.decisionMode = config.decisionMode ?? parseDecisionMode(readEnv(DECISION_MODE_ENV_VARS)) ?? 'local';
331
+ const coldStartRaw = config.coldStartWaitMs ?? Number(readEnv(COLD_START_WAIT_ENV_VARS) ?? DEFAULT_COLD_START_WAIT_MS);
332
+ const coldStartWaitMs = Number.isFinite(coldStartRaw) ? Math.max(0, Math.min(coldStartRaw, 10000)) : DEFAULT_COLD_START_WAIT_MS;
333
+ this.coldStartDeadline = Date.now() + coldStartWaitMs;
334
+ this.records = new recordQueue_1.RecordQueue((body) => this._sendQueuedRecord(body));
176
335
  this.breaker = config.circuitBreaker === false
177
336
  ? null
178
337
  : (0, circuitBreaker_1.getCircuitBreaker)(`${this.config.apiUrl}|${this.config.shieldId}`, config.circuitBreaker || undefined);
179
338
  this.chat = new ChatNamespace(this);
339
+ // Warm the shield mode right after construction (as soon as the current code yields, so a caller that sets up its own fetch just after
340
+ // building the client still gets it used), so the first tool call usually finds it (B8). A call made before then
341
+ // starts the same lookup itself. Never awaited, never throws.
342
+ if (this.config.monitorMode !== 'off') {
343
+ const key = this._modeCacheKey();
344
+ queueMicrotask(() => {
345
+ try {
346
+ if (typeof fetch === 'function' && !modeCache.has(key))
347
+ void this._firstLookup(key);
348
+ }
349
+ catch {
350
+ // never reaches the agent
351
+ }
352
+ });
353
+ }
354
+ if (this.decisionMode === 'local')
355
+ this._startBundleRefresh();
356
+ this._replaySpooledRecords();
357
+ }
358
+ /**
359
+ * Local decisions: refresh the bundle every BUNDLE_REFRESH_MS in the background (stale-while-revalidate), one
360
+ * timer per shield, never keeping the process alive. A call never waits for it; a failed refresh keeps the
361
+ * last bundle (the policies a live answer gave) and the next tick tries again.
362
+ */
363
+ _startBundleRefresh() {
364
+ const key = this._modeCacheKey();
365
+ if (bundleRefreshTimers.has(key) || typeof setInterval !== 'function')
366
+ return;
367
+ const timer = setInterval(() => {
368
+ try {
369
+ const cached = modeCache.get(key);
370
+ if (cached?.inflight || typeof fetch !== 'function')
371
+ return;
372
+ const refresh = this._fetchShieldMode();
373
+ if (cached)
374
+ cached.inflight = refresh;
375
+ void refresh.then((fetched) => { this._applyFetchedMode(key, modeCache.get(key), fetched); }, () => { this._applyFetchedMode(key, modeCache.get(key), null); });
376
+ }
377
+ catch {
378
+ // never reaches the agent
379
+ }
380
+ }, BUNDLE_REFRESH_MS);
381
+ timer.unref?.();
382
+ bundleRefreshTimers.set(key, timer);
383
+ }
384
+ /**
385
+ * Wait (at most `timeoutMs`, default 3 s) for the shield's mode and policies, at START-UP, outside any tool call.
386
+ * Local decisions never wait inside a call: a call made before the first bundle arrives runs and is reported. An
387
+ * agent that must have its first call checked awaits this once after building the client (a Lambda handler during
388
+ * its init). Resolves true when the policies are here, false when FullCourtDefense did not answer in time. Never throws.
389
+ */
390
+ async ready(timeoutMs = 3000) {
391
+ try {
392
+ if (this.config.monitorMode === 'off' && this.decisionMode !== 'local')
393
+ return true;
394
+ const key = this._modeCacheKey();
395
+ const cached = modeCache.get(key);
396
+ if (cached && cached.fetchedAt > 0 && cached.confirmed)
397
+ return true;
398
+ if (typeof fetch !== 'function')
399
+ return false;
400
+ await settleWithin(this._firstLookup(key), timeoutMs);
401
+ return Boolean(modeCache.get(key)?.confirmed);
402
+ }
403
+ catch {
404
+ return false;
405
+ }
406
+ }
407
+ /** The bundle for a local decision, or undefined (none yet, or the backend serves no policies to decide from). */
408
+ _localBundle() {
409
+ return modeCache.get(this._modeCacheKey())?.bundle;
410
+ }
411
+ /** One queued record to the record endpoint (RecordQueue's sender). */
412
+ async _sendQueuedRecord(body) {
413
+ const result = await this._postAgentSecurity('/api/agent-security/runtime/tool-call', body, 'inflight');
414
+ if (result.success)
415
+ return 'sent';
416
+ if (result.localEncodingError)
417
+ return 'refused';
418
+ const status = typeof result.status === 'number' ? result.status : undefined;
419
+ if (status === undefined || status >= 500 || status === 408 || status === 429)
420
+ return 'outage';
421
+ return 'refused';
422
+ }
423
+ /** Queue a record for the background batches; kept across the end of the process (exit flush, local spool). */
424
+ _enqueueRecord(body) {
425
+ this.records.push(body);
426
+ liveClients.add(this);
427
+ installExitHooks();
428
+ }
429
+ /** Send the records an earlier process left in the local spool (once per shield per process, off the first tick). */
430
+ _replaySpooledRecords() {
431
+ const shieldId = this.config.shieldId;
432
+ if (replayedShields.has(shieldId) || !(0, recordSpool_1.spoolDir)())
433
+ return;
434
+ replayedShields.add(shieldId);
435
+ setTimeout(() => {
436
+ try {
437
+ for (const record of (0, recordSpool_1.claimSpooled)(shieldId))
438
+ void this._postAgentSecurity(record.path, record.body, 'full');
439
+ }
440
+ catch {
441
+ // never reaches the agent
442
+ }
443
+ }, 0);
444
+ }
445
+ /** @internal Calls held in memory, as request bodies for the local spool (called at exit). */
446
+ _takeUnsentForSpool() {
447
+ for (const item of this.awaitingMode) {
448
+ this.skippedChecks.add({ kind: 'allow', agentName: item.agentName, toolName: item.toolName, outcome: 'unconfirmed_monitor', at: new Date().toISOString() });
449
+ }
450
+ this.awaitingMode.clear();
451
+ const { entries, dropped } = this.skippedChecks.drain();
452
+ if (dropped > 0 && entries.length > 0) {
453
+ const last = entries[entries.length - 1];
454
+ entries[entries.length - 1] = { ...last, count: last.count + dropped };
455
+ }
456
+ const out = [];
457
+ for (const entry of entries) {
458
+ out.push({
459
+ path: '/api/agent-security/runtime/tool-call',
460
+ body: { ...this.withIdentity(this._skippedCheckBody(entry)), shieldId: this.config.shieldId },
461
+ shieldId: this.config.shieldId,
462
+ at: entry.lastAt,
463
+ });
464
+ }
465
+ // Records of locally decided calls not sent yet: the next process with this shield sends them.
466
+ for (const item of this.records.drain()) {
467
+ out.push({ path: '/api/agent-security/runtime/tool-call', body: { ...item.body, shieldId: this.config.shieldId }, shieldId: this.config.shieldId, at: item.at });
468
+ }
469
+ return out;
470
+ }
471
+ /** @internal Send the calls spooled while the API was down and the queued records (called at `beforeExit`; the caller bounds the wait). */
472
+ _flushForExit() {
473
+ return Promise.all([this._flushSkippedChecks(), this.records.flush()]).then(() => undefined);
180
474
  }
181
475
  /** Identity recorded on every runtime action (agentId / agentInstanceId / environment). */
182
476
  get identity() {
@@ -193,15 +487,29 @@ class FullCourtDefense {
193
487
  /**
194
488
  * Merge client-level identity into a tool-call input. Call-level values win;
195
489
  * `agentName` falls back to `agentId` so callers never have to repeat it.
490
+ * `agentIdSource` says whether the id was configured, declared in the
491
+ * environment, or derived from the service / process name. A name passed in
492
+ * code (`agentName` or `agentId` on the call, or `protect(tool, { agentName })`)
493
+ * is declared: `config`, even when the client's own id was derived. Otherwise a
494
+ * shield with "Require agent identity" would refuse an agent named the
495
+ * documented way (review of #2730 / #2729).
196
496
  */
197
497
  withIdentity(input) {
198
- const agentId = input.agentId ?? this._identity.agentId;
498
+ const callAgentId = typeof input.agentId === 'string' && input.agentId.trim() ? input.agentId : undefined;
499
+ const callAgentName = typeof input.agentName === 'string' && input.agentName.trim() ? input.agentName : undefined;
500
+ const agentId = callAgentId ?? this._identity.agentId;
199
501
  return {
200
502
  ...input,
201
- agentName: input.agentName ?? agentId ?? 'unknown-agent',
503
+ agentName: callAgentName ?? agentId,
202
504
  agentId,
505
+ // Kept when already set (guardToolCall -> checkToolCall merges twice).
506
+ agentIdSource: input.agentIdSource ?? (callAgentId || callAgentName ? 'config' : this._identity.agentIdSource),
203
507
  agentInstanceId: input.agentInstanceId ?? this._identity.agentInstanceId,
204
508
  environment: input.environment ?? this._identity.environment,
509
+ ...(input.toolCallId && !input.attemptId ? { attemptId: input.toolCallId } : {}),
510
+ // Mixed SDK + local AI gateway: one action = one record by (agent, toolCallId), so a call with the provider's
511
+ // tool-call id says who sent it. `source` stays runtime_sdk (the backend reads an SDK agent from it).
512
+ ...(input.toolCallId ? { decisionSource: 'sdk' } : {}),
205
513
  };
206
514
  }
207
515
  // ── protect(): actions-first, one call ──
@@ -215,6 +523,14 @@ class FullCourtDefense {
215
523
  protect(target, options = {}) {
216
524
  return (0, protect_1.protectTarget)(this, target, options);
217
525
  }
526
+ /**
527
+ * Anthropic SDK tool use: run the `tool_use` blocks of one assistant message through the action gate and get the
528
+ * `tool_result` blocks to send back. A stopped call never runs; its block is an error block carrying the reason.
529
+ * const results = await fcd.anthropicToolResults(response.content, { read_customer, send_email });
530
+ */
531
+ anthropicToolResults(content, handlers, options) {
532
+ return (0, anthropic_1.anthropicToolResults)(this, content, handlers, options);
533
+ }
218
534
  // ── Resilience helpers (block-mode sync path) ──
219
535
  /**
220
536
  * Decide whether a degraded call should fail CLOSED (block) instead of the
@@ -232,6 +548,34 @@ class FullCourtDefense {
232
548
  breakerState() {
233
549
  return this.breaker ? this.breaker.currentState() : 'closed';
234
550
  }
551
+ /**
552
+ * The tool-call check may go to the network only while the breaker is CLOSED. Otherwise it answers from the fail mode at
553
+ * once, and (at most every `probeIntervalMs`) a background probe of the API runs; nothing waits for it.
554
+ */
555
+ _toolCheckAllowed() {
556
+ const breaker = this.breaker;
557
+ if (!breaker || breaker.isClosed())
558
+ return true;
559
+ if (breaker.probeDue())
560
+ void this._probeApi();
561
+ return false;
562
+ }
563
+ /** The background probe: a mode lookup. Any HTTP answer means the API is back (a refused key is answered by the next check). */
564
+ async _probeApi() {
565
+ let ok = false;
566
+ try {
567
+ const fetched = await this._fetchShieldMode();
568
+ if (fetched) {
569
+ ok = true;
570
+ const key = this._modeCacheKey();
571
+ this._applyFetchedMode(key, modeCache.get(key), fetched);
572
+ }
573
+ }
574
+ catch {
575
+ // a failed probe waits for the next interval
576
+ }
577
+ this.breaker?.probeFinished(ok);
578
+ }
235
579
  /** True when the breaker permits a real backend fetch (or there is no breaker). */
236
580
  breakerAllows() {
237
581
  return this.breaker ? this.breaker.allowRequest() : true;
@@ -256,57 +600,262 @@ class FullCourtDefense {
256
600
  * `'enforce'` — synchronous verdict path (block mode / unknown mode).
257
601
  */
258
602
  async _getEffectiveMode() {
603
+ return (await this._resolveMode()).effective;
604
+ }
605
+ /**
606
+ * The mode a TOOL CALL runs under. Same as `_resolveMode`, except that a mode nobody could read (the API was down since
607
+ * this process started, no live answer, no FCD_MODE_AT_PROTECT) is Monitor, not Block: a Monitor agent never blocks, so a
608
+ * call that cannot know the mode runs, and is reported as unconfirmed once the API answers (owner decision 2026-10-27).
609
+ * A refused key or shield (HTTP 401 / 403 / 404) is not "unknown": it keeps its own rule.
610
+ */
611
+ async _resolveToolMode() {
612
+ // Local decisions never wait for the network once the first bundle is here (owner order 2026-11-01). Without
613
+ // one, a call runs and its record follows the answer (allow + record + one warning, never stall), except for the
614
+ // bounded cold-start wait below.
615
+ let mode = await this._resolveMode(this._mayRunBeforeModeKnown() || this.decisionMode === 'local');
616
+ // Cold start (local decisions): while the first bundle is on its way, a call on a shield not recorded as Monitor
617
+ // waits for it, at most until the deadline set when the client was built. Never after: one bounded wait per
618
+ // process at most, and a hanging FullCourtDefense costs only the calls made in that first window.
619
+ if (mode.pending && this.decisionMode === 'local' && !this._mayRunBeforeModeKnown()) {
620
+ const left = this.coldStartDeadline - Date.now();
621
+ if (left > 0) {
622
+ let timer;
623
+ const settled = await Promise.race([
624
+ mode.pending.then((value) => value, () => undefined),
625
+ new Promise((resolve) => { timer = setTimeout(() => resolve(undefined), left); }),
626
+ ]);
627
+ if (timer !== undefined)
628
+ clearTimeout(timer);
629
+ if (settled)
630
+ mode = { effective: settled.effective, confirmed: settled.confirmed, ...(settled.configError ? { configError: settled.configError } : {}) };
631
+ }
632
+ }
633
+ if (mode.pending)
634
+ return { ...mode, pending: mode.pending.then((settled) => this._adjustToolMode(settled)) };
635
+ return this._adjustToolMode(mode);
636
+ }
637
+ _adjustToolMode(mode) {
638
+ if (mode.effective === 'enforce' && !mode.confirmed && !mode.configError && !this.modeAtProtect) {
639
+ return { effective: 'monitor', confirmed: false };
640
+ }
641
+ return mode;
642
+ }
643
+ /**
644
+ * May the FIRST call of this process run before the shield mode is known (B8)? Only when the mode recorded on the agent
645
+ * (FCD_MODE_AT_PROTECT, written by Protect) says Monitor: a Monitor agent never waits for FullCourtDefense. With a recorded
646
+ * Block, or no recorded mode, the first call waits for the lookup and the verdict (bounded by MODE_FETCH_TIMEOUT_MS): running
647
+ * the first call of a shield whose mode nobody has read could run it unchecked on a Block shield. The lookup starts when the
648
+ * client is built, so it is usually warm by the first call.
649
+ */
650
+ _mayRunBeforeModeKnown() {
651
+ return this.config.monitorMode !== 'off' && this.modeAtProtect === 'monitor';
652
+ }
653
+ /**
654
+ * `_getEffectiveMode`, plus whether a live answer confirmed the mode (false = recorded on the agent, or assumed).
655
+ * `noWaitWhenUnknown`: a first lookup still running is not waited for; the result says Monitor (unconfirmed) with
656
+ * `pending` resolving to what the lookup settles on.
657
+ */
658
+ async _resolveMode(noWaitWhenUnknown = false) {
259
659
  if (this.config.monitorMode === 'off')
260
- return 'enforce';
660
+ return { effective: 'enforce', confirmed: true };
661
+ const resolved = (mode, confirmed, configError) => ({
662
+ effective: mode === 'monitor' ? 'monitor' : 'enforce',
663
+ confirmed,
664
+ ...(configError ? { configError } : {}),
665
+ });
261
666
  const key = this._modeCacheKey();
262
667
  const now = Date.now();
263
668
  const cached = modeCache.get(key);
264
669
  if (cached && now - cached.fetchedAt < cached.ttlMs) {
265
- return cached.mode === 'monitor' ? 'monitor' : 'enforce';
266
- }
267
- // Single in-flight refresh per shield; concurrent callers share it.
268
- let inflight = cached?.inflight;
269
- if (!inflight) {
270
- inflight = this._fetchShieldMode();
271
- if (cached)
272
- cached.inflight = inflight;
273
- else
274
- modeCache.set(key, { mode: 'block', fetchedAt: 0, ttlMs: 0, inflight });
275
- }
276
- const fetched = await inflight;
277
- const entry = modeCache.get(key);
278
- if (entry)
279
- entry.inflight = undefined;
280
- if (fetched) {
281
- modeCache.set(key, { mode: fetched, fetchedAt: Date.now(), ttlMs: MODE_CACHE_TTL_MS });
282
- return fetched === 'monitor' ? 'monitor' : 'enforce';
283
- }
284
- // Fetch failed: stale-while-error — keep the last-known mode for a short
285
- // retry window so a down backend doesn't add a lookup timeout to every call.
286
- const lastKnown = cached && cached.fetchedAt > 0 ? cached.mode : 'block';
287
- modeCache.set(key, { mode: lastKnown, fetchedAt: Date.now(), ttlMs: MODE_FAILURE_RETRY_MS });
288
- return lastKnown === 'monitor' ? 'monitor' : 'enforce';
670
+ return resolved(cached.mode, cached.confirmed, cached.configError);
671
+ }
672
+ // A mode is already known (a live answer, the one recorded on the agent, or an assumed Block) and only its time is
673
+ // up: answer from it NOW and refresh in the background. The lookup can take its whole timeout (MODE_FETCH_TIMEOUT_MS)
674
+ // when the API is slow or down, and a Monitor agent's tool must never wait for FullCourtDefense (v19 invariant I2:
675
+ // on Monitor no FullCourtDefense failure delays or denies a call). Only the very first lookup of a process waits.
676
+ if (cached && cached.fetchedAt > 0) {
677
+ if (!cached.inflight) {
678
+ const refresh = this._fetchShieldMode();
679
+ cached.inflight = refresh;
680
+ void refresh.then((fetched) => { this._applyFetchedMode(key, cached, fetched); }, () => { this._applyFetchedMode(key, cached, null); });
681
+ }
682
+ return resolved(cached.mode, cached.confirmed, cached.configError);
683
+ }
684
+ // First lookup of this process: single in-flight refresh per shield; concurrent callers share it.
685
+ const resolving = this._firstLookup(key);
686
+ if (noWaitWhenUnknown)
687
+ return { effective: 'monitor', confirmed: false, pending: resolving };
688
+ return resolving;
689
+ }
690
+ /** Start (or join) the first mode lookup of this process; the answer is applied to the cache exactly once. */
691
+ _firstLookup(key) {
692
+ const cached = modeCache.get(key);
693
+ if (cached?.resolving)
694
+ return cached.resolving;
695
+ const fetching = this._fetchShieldMode();
696
+ const resolving = fetching.then((fetched) => this._applyFetchedMode(key, cached, fetched), () => this._applyFetchedMode(key, cached, null));
697
+ if (cached) {
698
+ cached.inflight = fetching;
699
+ cached.resolving = resolving;
700
+ }
701
+ else
702
+ modeCache.set(key, { mode: 'block', fetchedAt: 0, ttlMs: 0, confirmed: false, inflight: fetching, resolving });
703
+ return resolving;
704
+ }
705
+ /** What a finished mode lookup means: store it in the cache and say which mode the call that asked runs under. */
706
+ _applyFetchedMode(key, cached, fetched) {
707
+ const resolved = (mode, confirmed, configError) => ({
708
+ effective: mode === 'monitor' ? 'monitor' : 'enforce',
709
+ confirmed,
710
+ ...(configError ? { configError } : {}),
711
+ });
712
+ if (cached)
713
+ cached.inflight = undefined;
714
+ if (fetched && 'mode' in fetched) {
715
+ modeCache.set(key, {
716
+ mode: fetched.mode, rules: fetched.rules, fetchedAt: Date.now(), ttlMs: MODE_CACHE_TTL_MS, confirmed: true,
717
+ ...(fetched.bundle ? { bundle: fetched.bundle } : {}),
718
+ });
719
+ // The API answers again: send what was decided without a check meanwhile (the alert), and the queued records.
720
+ if (this.skippedChecks.size > 0)
721
+ void this._flushSkippedChecks();
722
+ this.records.resume();
723
+ return resolved(fetched.mode, true);
724
+ }
725
+ if (fetched && 'configError' in fetched) {
726
+ // Owner decision O4 (2026-10-22): a wrong or expired key or an unknown shield. The API answered, so
727
+ // it is not an outage; the mode is what the agent knows: the last live answer in this process, else
728
+ // FCD_MODE_AT_PROTECT, else Block. Monitor: the tool runs and its report raises the server's key
729
+ // alert. Block: the check is refused with the same error and the tool stops. Retried after a short
730
+ // window (a fixed key is picked up on the next lookup).
731
+ const knownMode = cached && cached.confirmed && cached.fetchedAt > 0 ? cached.mode : undefined;
732
+ const mode = knownMode ?? this.modeAtProtect ?? 'block';
733
+ modeCache.set(key, {
734
+ mode, rules: knownMode ? cached?.rules : undefined, fetchedAt: Date.now(), ttlMs: MODE_FAILURE_RETRY_MS,
735
+ confirmed: Boolean(knownMode), configError: fetched.configError,
736
+ // A refused key decides nothing locally: Block calls go to the server, which answers the same refusal.
737
+ });
738
+ return resolved(mode, Boolean(knownMode), fetched.configError);
739
+ }
740
+ // Fetch failed: stale-while-error — keep the last mode a live answer gave (and its
741
+ // rules) for a short retry window so a down backend doesn't add a lookup timeout to
742
+ // every call. No live answer yet in this process (a cold start with the API down):
743
+ // the shield's mode recorded on the agent (FCD_MODE_AT_PROTECT, which FullCourtDefense
744
+ // rewrites whenever the shield's mode changes), so a Monitor agent never blocks; with
745
+ // none recorded, Block (the tiered rule with FCD_FAIL_MODE). Unconfirmed either way:
746
+ // a Monitor call is reported once the API answers, a Block call is spooled as before.
747
+ const known = Boolean(cached && cached.confirmed && cached.fetchedAt > 0);
748
+ const lastKnown = known && cached ? cached.mode : (this.modeAtProtect ?? 'block');
749
+ // Local decisions keep deciding from the last bundle a live answer gave (stale-while-error).
750
+ modeCache.set(key, {
751
+ mode: lastKnown, rules: known ? cached?.rules : undefined, fetchedAt: Date.now(), ttlMs: MODE_FAILURE_RETRY_MS, confirmed: known,
752
+ ...(known && cached?.bundle ? { bundle: cached.bundle } : {}),
753
+ });
754
+ return resolved(lastKnown, known);
289
755
  }
290
756
  async _fetchShieldMode() {
291
757
  try {
292
- const url = `${this.config.apiUrl}/api/cli/bundle?shieldId=${encodeURIComponent(this.config.shieldId)}`;
758
+ const url = `${this.config.apiUrl}/api/cli/bundle?shieldId=${encodeURIComponent(this.config.shieldId)}&agentRules=1`;
293
759
  const resp = await fetch(url, {
294
760
  method: 'GET',
295
761
  headers: this.config.shieldKey ? { 'x-shield-key': this.config.shieldKey } : {},
296
- signal: AbortSignal.timeout(MODE_FETCH_TIMEOUT_MS),
762
+ // Local decisions never wait for this request, so it may take longer than a lookup a call waits for.
763
+ signal: AbortSignal.timeout(this.decisionMode === 'local' ? BUNDLE_FETCH_TIMEOUT_MS : MODE_FETCH_TIMEOUT_MS),
297
764
  });
298
- if (!resp.ok)
765
+ if (!resp.ok) {
766
+ // A wrong key or an unknown shield is not an outage: say so once, loudly (O4: a Monitor agent's
767
+ // tools run and are reported, a Blocking agent's tools stop with the same explanation).
768
+ if (resp.status === 401 || resp.status === 403 || resp.status === 404) {
769
+ this._reportConfigurationError(resp.status, 'read the shield mode', undefined, 'Tool calls of this agent are not checked until this is fixed: on a Monitor shield they run and are reported, on a Blocking shield they stop.');
770
+ return { configError: resp.status };
771
+ }
299
772
  return null;
773
+ }
300
774
  const data = await resp.json().catch(() => null);
301
775
  const mode = data?.data?.mode;
302
- if (mode === 'monitor' || mode === 'block' || mode === 'shadow')
303
- return mode;
776
+ if (mode === 'monitor' || mode === 'block' || mode === 'shadow') {
777
+ // A bundle without `actionPolicies` (a backend that serves none to an SDK) cannot decide locally: the server does.
778
+ const bundle = this.decisionMode === 'local' && Array.isArray(data?.data?.actionPolicies) ? (0, localDecision_1.prepareLocalBundle)(data?.data) : undefined;
779
+ return { mode, rules: (0, failMode_1.sanitizeFailsafeRules)(data?.data?.agentFailsafeRules), ...(bundle ? { bundle } : {}) };
780
+ }
304
781
  return null;
305
782
  }
306
783
  catch {
307
784
  return null;
308
785
  }
309
786
  }
787
+ /**
788
+ * Say once per status, on stderr, that the API refused this client's configuration
789
+ * (wrong key, unknown shield, refused request). Returns the error the caller throws.
790
+ */
791
+ _reportConfigurationError(status, call, serverError, outcome, serverCode) {
792
+ const error = new errors_1.FullCourtDefenseApiError({ status, shieldId: this.config.shieldId, apiUrl: this.config.apiUrl, serverError, serverCode, call, outcome });
793
+ if (!this.reportedConfigErrors.has(status)) {
794
+ this.reportedConfigErrors.add(status);
795
+ console.error(`[FullCourtDefense] ${error.message}`);
796
+ }
797
+ return error;
798
+ }
799
+ /** The never-allowed rules from the last successful lookup (empty before the first one). */
800
+ _failsafeRules() {
801
+ return modeCache.get(this._modeCacheKey())?.rules ?? [];
802
+ }
803
+ /** The tool-call record that reports a call decided without a check (the alert). */
804
+ _skippedCheckBody(entry) {
805
+ return {
806
+ agentName: entry.agentName,
807
+ toolName: entry.toolName,
808
+ decision: entry.kind === 'deny' ? 'block' : 'allow',
809
+ reason: entry.kind === 'deny'
810
+ ? `failsafe_deny: FullCourtDefense could not be reached; stopped ${entry.count} time(s) (${entry.outcome}${entry.ruleId ? ` ${entry.ruleId}` : ''}).`
811
+ : entry.outcome === 'unconfirmed_monitor'
812
+ ? `failsafe_allow: FullCourtDefense could not be reached when this agent started; it ran ${entry.count} time(s) as Monitor, the mode recorded on the agent (unconfirmed_monitor).`
813
+ : entry.outcome === 'would_need_manager'
814
+ ? `failsafe_allow: FullCourtDefense could not be reached; ran ${entry.count} time(s) unattended although ${entry.ruleName ? `"${entry.ruleName}"` : 'a rule'} needs a manager's approval (would_need_manager).`
815
+ : `failsafe_allow: FullCourtDefense could not be reached; ran unchecked ${entry.count} time(s).`,
816
+ failsafe: entry.kind,
817
+ failsafeOutcome: entry.outcome,
818
+ failsafeCount: entry.count,
819
+ ...(entry.ruleId ? { failsafeRuleId: entry.ruleId } : {}),
820
+ ...(entry.ruleName ? { failsafeRuleName: entry.ruleName } : {}),
821
+ // The call RAN while FullCourtDefense could not be reached (the backend alerts on these).
822
+ ...(entry.kind === 'allow' ? { ranDuringOutage: true } : {}),
823
+ // ... and a rule needed a manager for it: the unattended agent could not wait for one.
824
+ ...(entry.outcome === 'would_need_manager' ? { wouldHaveNeeded: 'manager' } : {}),
825
+ failsafeFirstAt: entry.firstAt,
826
+ failsafeLastAt: entry.lastAt,
827
+ };
828
+ }
829
+ /** Hold a call decided without a check until the API answers; kept across an early exit (local spool). */
830
+ _spoolCheck(entry) {
831
+ this.skippedChecks.add(entry);
832
+ liveClients.add(this);
833
+ installExitHooks();
834
+ }
835
+ /**
836
+ * Send the calls decided without a check (FCD_FAIL_MODE) as tool-call records the server turns into
837
+ * a security alert. One in flight at a time; an entry that could not be sent goes back to the spool.
838
+ */
839
+ _flushSkippedChecks() {
840
+ if (this.skippedFlush)
841
+ return this.skippedFlush;
842
+ if (this.skippedChecks.size === 0)
843
+ return Promise.resolve();
844
+ const { entries, dropped } = this.skippedChecks.drain();
845
+ if (dropped > 0 && entries.length > 0) {
846
+ const last = entries[entries.length - 1];
847
+ entries[entries.length - 1] = { ...last, count: last.count + dropped };
848
+ }
849
+ const send = async (entry) => {
850
+ const result = await this._postAgentSecurity('/api/agent-security/runtime/tool-call', this.withIdentity(this._skippedCheckBody(entry)), 'inflight');
851
+ if (!result.success) {
852
+ this._spoolCheck({ kind: entry.kind, agentName: entry.agentName, toolName: entry.toolName, outcome: entry.outcome, ruleId: entry.ruleId, ruleName: entry.ruleName, at: entry.lastAt, firstAt: entry.firstAt, count: entry.count });
853
+ }
854
+ };
855
+ const flush = Promise.all(entries.map(send)).then(() => undefined, () => undefined);
856
+ this.skippedFlush = flush.finally(() => { this.skippedFlush = undefined; });
857
+ return this.skippedFlush;
858
+ }
310
859
  /**
311
860
  * Fire-and-forget event report (monitor mode). Never awaited on the caller's
312
861
  * hot path; every failure is swallowed — reporting must never affect the agent.
@@ -711,19 +1260,16 @@ class FullCourtDefense {
711
1260
  return this._postAgentSecurity('/api/agent-security/runtime/register-agent', input);
712
1261
  }
713
1262
  async recordToolCall(rawInput) {
714
- return this._postAgentSecurity('/api/agent-security/runtime/tool-call', this.withIdentity(rawInput));
1263
+ return this._postAgentSecurity('/api/agent-security/runtime/tool-call', this.withIdentity(rawInput), 'full');
715
1264
  }
716
1265
  async checkToolCall(rawInput) {
717
1266
  const input = this.withIdentity(rawInput);
718
1267
  // Monitor mode: allow instantly; record the tool call fire-and-forget so
719
- // the console inventory/audit trail still sees it.
720
- if (await this._getEffectiveMode() === 'monitor') {
721
- void this.recordToolCall({
722
- ...input,
723
- decision: input.decision || 'allow',
724
- reason: input.reason || 'monitor_mode_async',
725
- argsSummary: input.argsSummary || input.toolArgs,
726
- }).catch(() => { });
1268
+ // the console inventory/audit trail still sees it. On a mode no live answer
1269
+ // confirmed (cold start, API down), the call is spooled and reported instead.
1270
+ const mode = await this._resolveToolMode();
1271
+ if (mode.effective === 'monitor') {
1272
+ void this._recordMonitorCall(input, mode);
727
1273
  return {
728
1274
  success: true,
729
1275
  data: {
@@ -731,10 +1277,31 @@ class FullCourtDefense {
731
1277
  decision: 'allow',
732
1278
  operation: input.operation || 'unknown',
733
1279
  analysis: 'async',
1280
+ ...((mode.confirmed && !mode.configError) || mode.pending ? {} : { degraded: true }),
734
1281
  },
735
1282
  };
736
1283
  }
1284
+ // Arguments the API could not check (too deep, too many values, not encodable): a definite answer
1285
+ // here, before any request. Never an outage (no fail mode, no breaker failure, nothing spooled).
1286
+ const argsProblem = (0, argsBounds_1.toolCallArgsProblem)(input);
1287
+ if (argsProblem)
1288
+ return this._argsProblemVerdict(input, argsProblem);
1289
+ // Local decisions (owner order 2026-11-01): from the bundle, in this process, no request. A manager approval
1290
+ // and a call the bundle cannot decide continue to the server check below.
1291
+ const local = this._decideLocal(input, mode);
1292
+ if (local) {
1293
+ if (local.record) {
1294
+ // guardToolCall writes ONE record after the tool ran (decision + how it ended); a direct check writes it now.
1295
+ if (this.deferredLocalRecords.has(rawInput))
1296
+ this.deferredLocalRecords.set(rawInput, local.record);
1297
+ else
1298
+ this._enqueueRecord(local.record);
1299
+ }
1300
+ return local.result;
1301
+ }
737
1302
  const degrade = (reason) => {
1303
+ if (this.failMode)
1304
+ return this._degradeByFailMode(input, reason, this.failMode);
738
1305
  const failedClosed = this.shouldFailClosed({ operation: input.operation, toolName: input.toolName, failClosed: input.failClosed });
739
1306
  const breakerState = this.breakerState();
740
1307
  this.emitDegrade({ call: 'checkToolCall', reason, breakerState, failedClosed });
@@ -761,23 +1328,281 @@ class FullCourtDefense {
761
1328
  },
762
1329
  };
763
1330
  };
764
- // Circuit breaker open: skip the doomed fetch and degrade immediately.
765
- if (!this.breakerAllows()) {
1331
+ // Circuit breaker not closed: skip the doomed fetch and answer from the fail mode at once. A background probe (not this
1332
+ // call) finds out when the API is back.
1333
+ if (!this._toolCheckAllowed()) {
766
1334
  return degrade('circuit breaker open');
767
1335
  }
768
1336
  const startedAt = Date.now();
769
- const result = await this._postAgentSecurity('/api/agent-security/runtime/check-tool-call', input);
1337
+ const result = await this._postAgentSecurity('/api/agent-security/runtime/check-tool-call', input, undefined, this.config.toolCheckTimeoutMs);
770
1338
  if (result.success) {
771
1339
  this.breaker?.recordSuccess(Date.now() - startedAt);
1340
+ if (this.skippedChecks.size > 0)
1341
+ void this._flushSkippedChecks();
772
1342
  return result;
773
1343
  }
774
- this.breaker?.recordFailure(Date.now() - startedAt);
775
- // Backend unreachable: risk-tiered degrade (fail-closed for high-risk ops).
776
- if (this.config.failOpen || this.shouldFailClosed({ operation: input.operation, toolName: input.toolName, failClosed: input.failClosed })) {
1344
+ // The body could not be encoded (a value with a throwing toJSON): the call's own input, definite.
1345
+ if (result.localEncodingError)
1346
+ return this._argsProblemVerdict(input, { kind: 'unencodable', errorType: result.localEncodingError });
1347
+ // Any 4xx except 408 / 429 (400 / 401 / 403 / 404 / 413 ...): the API answered and refused the call.
1348
+ // Not an outage: no fail-open, no fail mode, no breaker failure, nothing spooled as "ran without a
1349
+ // check", so crafted arguments can neither run the call unchecked nor trip the breaker. The caller
1350
+ // gets an explicit error (guardToolCall throws it; the tool does not run). An API that classifies
1351
+ // its errors (G-04) may still call a 400 retryable (a server failure answered the way machines
1352
+ // expect): that one is an outage.
1353
+ if ((0, errors_1.isDefiniteStatus)(result.status) && result.retryable !== true && result.category !== 'server') {
1354
+ const error = this._reportConfigurationError(result.status, `check tool call "${input.toolName}"`, result.serverError, undefined, result.serverCode);
1355
+ return {
1356
+ success: false, error: error.message, status: error.status, code: error.code,
1357
+ serverError: result.serverError, serverCode: result.serverCode, category: result.category, retryable: false,
1358
+ };
1359
+ }
1360
+ // An outage: no answer, a timeout, 408, 429 or 5xx. A hang or a network failure (no HTTP answer at all) opens the
1361
+ // breaker at once, so the calls after this one never wait; an HTTP answer counts toward the usual ratio.
1362
+ if (typeof result.error === 'string' && result.error.startsWith('fcd_unavailable'))
1363
+ this.breaker?.tripNow();
1364
+ else
1365
+ this.breaker?.recordFailure(Date.now() - startedAt);
1366
+ // Backend unreachable: FCD_FAIL_MODE decides when set; otherwise the SDK 2.0
1367
+ // risk-tiered degrade (fail-closed for high-risk ops).
1368
+ if (this.failMode || this.config.failOpen || this.shouldFailClosed({ operation: input.operation, toolName: input.toolName, failClosed: input.failClosed })) {
777
1369
  return degrade(result.error || 'request failed');
778
1370
  }
779
1371
  return result;
780
1372
  }
1373
+ /**
1374
+ * A Block-mode call decided in this process from the bundle, or undefined when the server decides it (server
1375
+ * decision mode, a manager approval, a call the bundle cannot decide, a backend that serves no policies, a
1376
+ * refused key). With no bundle at all (FullCourtDefense never reached since this agent started), the call is
1377
+ * answered by the fail mode at once: it runs (only a never-allowed rule stops one), it is recorded, and one
1378
+ * warning says so. Never a request, never a wait.
1379
+ */
1380
+ _decideLocal(input, mode) {
1381
+ if (this.decisionMode !== 'local' || mode.configError)
1382
+ return undefined;
1383
+ const bundle = this._localBundle();
1384
+ if (!bundle) {
1385
+ // A live answer came without policies (an older backend): the server decides, as before.
1386
+ if (modeCache.get(this._modeCacheKey())?.confirmed)
1387
+ return undefined;
1388
+ if (!this.warnedNoBundle) {
1389
+ this.warnedNoBundle = true;
1390
+ console.warn('[FullCourtDefense] No policy bundle yet (FullCourtDefense not reached since this agent started): tool calls run under the fail mode and are recorded; local decisions start with the first bundle.');
1391
+ }
1392
+ return { result: this._degradeByFailMode(input, 'no policy bundle yet', this.failMode ?? 'tiered') };
1393
+ }
1394
+ const decided = (0, localDecision_1.decideLocally)(bundle, input);
1395
+ if (decided.route === 'server' || decided.decision === 'approval')
1396
+ return undefined;
1397
+ const data = {
1398
+ allowed: decided.allowed,
1399
+ decision: decided.decision,
1400
+ operation: decided.operation,
1401
+ actionPolicy: decided.actionPolicy,
1402
+ analysis: 'sync',
1403
+ decidedBy: 'local',
1404
+ outcome: decided.outcome,
1405
+ };
1406
+ return { result: { success: true, data }, record: this._localRecordBody(input, data) };
1407
+ }
1408
+ /**
1409
+ * The record of a locally decided call, for the existing record endpoint (`POST /runtime/tool-call`): what was
1410
+ * decided and by which rule, the arguments as their summary (the server minimizes them as for every SDK record),
1411
+ * the provider's tool-call id (one action = one record when a local AI gateway also saw it), and how the tool
1412
+ * ended when it ran.
1413
+ */
1414
+ _localRecordBody(input, data, ended) {
1415
+ const { toolArgs, failClosed: _failClosed, ...rest } = input;
1416
+ void _failClosed;
1417
+ const policy = data.actionPolicy || {};
1418
+ const why = policy.reason || (data.decision === 'block' ? 'Blocked by policy' : 'No policy stops this call');
1419
+ const ran = ended ? (ended.outcome === 'failed' ? ` The tool ran and raised ${ended.errorType ?? 'an error'}.` : ' The tool ran.') : '';
1420
+ return {
1421
+ ...rest,
1422
+ argsSummary: input.argsSummary || toolArgs,
1423
+ operation: data.operation,
1424
+ decision: data.decision === 'block' ? 'block' : 'allow',
1425
+ reason: `${data.outcome === 'warn' ? 'Warn only: ' : ''}${why} (decided in the agent's process from the shield's policies).${ran}`.slice(0, 1000),
1426
+ ...(policy.policyId ? { policyId: policy.policyId } : {}),
1427
+ ...(policy.policyName ? { policyName: policy.policyName } : {}),
1428
+ ...(policy.matchedRule ? { matchedRule: policy.matchedRule } : {}),
1429
+ ...(policy.monitorMatches?.length ? { monitorMatches: policy.monitorMatches } : {}),
1430
+ decisionSource: 'sdk',
1431
+ decidedBy: 'sdk_local',
1432
+ ...(data.outcome ? { localOutcome: data.outcome } : {}),
1433
+ ...(input.toolCallId ? { toolCallId: input.toolCallId } : {}),
1434
+ ...(ended ? { toolOutcome: ended.outcome, ...(ended.errorType ? { errorType: ended.errorType } : {}) } : {}),
1435
+ occurredAt: new Date().toISOString(),
1436
+ };
1437
+ }
1438
+ /**
1439
+ * The record of a call that runs in Monitor (it never waits for it):
1440
+ * - the API refused the key or shield (O4): the call runs; its report goes to the API anyway, where
1441
+ * the refusal raises the shield's key alert (`tamper.agent_key_rejected`), and `onDegrade` says so;
1442
+ * - a mode no live answer confirmed (cold start, API down): spooled, reported once the API answers;
1443
+ * - otherwise the Monitor record, with a fact in place of arguments the API could not check.
1444
+ * Resolves when the record was sent (or immediately when it was spooled); never rejects.
1445
+ */
1446
+ _recordMonitorCall(input, mode) {
1447
+ if (mode.pending) {
1448
+ // The call ran before the first mode lookup answered (B8). Its record follows the answer: a Monitor shield gets
1449
+ // the normal record; a shield found in Block, or no answer, is spooled as `unconfirmed_monitor` (the server alerts
1450
+ // on a Block shield). Until then it is held, so an exit before the answer still keeps it (local spool).
1451
+ const waiting = { agentName: input.agentName, toolName: input.toolName };
1452
+ this.awaitingMode.add(waiting);
1453
+ liveClients.add(this);
1454
+ installExitHooks();
1455
+ return mode.pending.then((settled) => {
1456
+ if (!this.awaitingMode.delete(waiting))
1457
+ return undefined; // already handed to the spool at exit
1458
+ if (settled.effective === 'monitor' && (settled.confirmed || settled.configError))
1459
+ return this._recordMonitorCall(input, settled);
1460
+ this._spoolUnconfirmedMonitor(input, settled.confirmed ? 'the shield is in Block; this call ran before its mode was read' : undefined);
1461
+ if (settled.confirmed)
1462
+ return this._flushSkippedChecks();
1463
+ return undefined;
1464
+ }).catch(() => undefined);
1465
+ }
1466
+ if (mode.configError) {
1467
+ // onDegrade hears about every such call; without one, stderr says it once (not on every call).
1468
+ if (!this.onDegrade && this.warnedMonitorConfigError)
1469
+ return this._sendMonitorRecord(input);
1470
+ this.warnedMonitorConfigError = true;
1471
+ this.emitDegrade({
1472
+ call: 'checkToolCall',
1473
+ reason: `FullCourtDefense refused this agent's shield key or shield (HTTP ${mode.configError}): ran as Monitor, the mode the agent knows; reported so FullCourtDefense raises an alert`,
1474
+ breakerState: this.breakerState(),
1475
+ failedClosed: false,
1476
+ outcome: 'monitor_config_error',
1477
+ });
1478
+ }
1479
+ else if (!mode.confirmed) {
1480
+ this._spoolUnconfirmedMonitor(input);
1481
+ return Promise.resolve();
1482
+ }
1483
+ return this._sendMonitorRecord(input);
1484
+ }
1485
+ /** The Monitor record (`monitor_mode_async`), with a fact in place of arguments the API could not check. */
1486
+ _sendMonitorRecord(input) {
1487
+ const problem = (0, argsBounds_1.toolCallArgsProblem)(input);
1488
+ const { toolArgs, ...rest } = input;
1489
+ if (this.decisionMode === 'local') {
1490
+ // Local decisions: the Monitor record joins the background batches (the server still evaluates its would-have).
1491
+ this._enqueueRecord({
1492
+ ...rest,
1493
+ decision: input.decision || 'allow',
1494
+ reason: input.reason || 'monitor_mode_async',
1495
+ argsSummary: problem ? (0, argsBounds_1.toolArgsProblemSummary)(problem) : (input.argsSummary || toolArgs),
1496
+ decisionSource: 'sdk',
1497
+ ...(input.toolCallId ? { toolCallId: input.toolCallId } : {}),
1498
+ });
1499
+ return Promise.resolve();
1500
+ }
1501
+ return this.recordToolCall({
1502
+ ...rest,
1503
+ decision: input.decision || 'allow',
1504
+ reason: input.reason || 'monitor_mode_async',
1505
+ argsSummary: problem ? (0, argsBounds_1.toolArgsProblemSummary)(problem) : (input.argsSummary || toolArgs),
1506
+ }).catch(() => undefined);
1507
+ }
1508
+ /**
1509
+ * The SDK's own definite answer for a call whose arguments the API could not check (nested deeper than
1510
+ * 32 levels, more than 20,000 values, or not encodable as JSON): stopped, as the API answers the same
1511
+ * call on a Block shield. Not an outage: no fail mode, no breaker failure, nothing spooled. A record
1512
+ * with a fact instead of the arguments goes to the API in the background.
1513
+ */
1514
+ _argsProblemVerdict(input, problem) {
1515
+ const words = (0, argsBounds_1.toolArgsProblemWords)(problem);
1516
+ const reason = `Stopped: the tool call's arguments are ${words}, so FullCourtDefense cannot check them safely.`;
1517
+ const { toolArgs: _toolArgs, ...rest } = input;
1518
+ void _toolArgs;
1519
+ void this.recordToolCall({ ...rest, decision: 'block', reason, argsSummary: (0, argsBounds_1.toolArgsProblemSummary)(problem) }).catch(() => undefined);
1520
+ return {
1521
+ success: true,
1522
+ data: {
1523
+ allowed: false,
1524
+ decision: 'block',
1525
+ operation: input.operation || 'unknown',
1526
+ argsProblem: words,
1527
+ actionPolicy: { allowed: false, verdict: 'block', reason, policyName: 'Too large to check safely', matchedRule: argsBounds_1.TOOL_ARGS_BOUNDS_RULE_ID },
1528
+ },
1529
+ };
1530
+ }
1531
+ /**
1532
+ * A Monitor call made on a mode no live answer confirmed: the mode recorded on the agent
1533
+ * (FCD_MODE_AT_PROTECT) during a cold start with the API down. It runs (Monitor never blocks),
1534
+ * but it is never silent: spooled as `unconfirmed_monitor` and reported once the API answers,
1535
+ * when the server alerts if the shield is in Block by then (the recorded mode was out of date).
1536
+ * No record now: the API did not answer the mode lookup moments ago, so it would only wait.
1537
+ */
1538
+ _spoolUnconfirmedMonitor(input, why) {
1539
+ this.emitDegrade({
1540
+ call: 'checkToolCall',
1541
+ reason: why ?? 'mode not confirmed (FullCourtDefense unreachable): ran as Monitor, the mode recorded on the agent; reported once the API answers',
1542
+ breakerState: this.breakerState(),
1543
+ failedClosed: false,
1544
+ ...(this.failMode ? { failMode: this.failMode } : {}),
1545
+ outcome: 'unconfirmed_monitor',
1546
+ });
1547
+ this._spoolCheck({
1548
+ kind: 'allow',
1549
+ agentName: input.agentName,
1550
+ toolName: input.toolName,
1551
+ outcome: 'unconfirmed_monitor',
1552
+ at: new Date().toISOString(),
1553
+ });
1554
+ }
1555
+ /**
1556
+ * FCD_FAIL_MODE (owner decision 2026-10-19): decide a Block-mode tool call the API could not
1557
+ * check — never-allowed rules and the high-risk names stop it (tiered), or everything does
1558
+ * (closed); the rest runs. Either way the call is spooled and alerted once the API is back.
1559
+ */
1560
+ _degradeByFailMode(input, reason, failMode) {
1561
+ const decision = (0, failMode_1.decideDuringOutage)({
1562
+ failMode,
1563
+ rules: this._failsafeRules(),
1564
+ toolName: input.toolName,
1565
+ agentName: input.agentName,
1566
+ operation: input.operation,
1567
+ failClosed: input.failClosed,
1568
+ });
1569
+ const breakerState = this.breakerState();
1570
+ this.emitDegrade({
1571
+ call: 'checkToolCall', reason, breakerState, failedClosed: decision.block, failMode, outcome: decision.outcome,
1572
+ ...(decision.rule ? { ruleId: decision.rule.id } : {}),
1573
+ });
1574
+ this._spoolCheck({
1575
+ kind: decision.block ? 'deny' : 'allow',
1576
+ agentName: input.agentName,
1577
+ toolName: input.toolName,
1578
+ outcome: decision.outcome,
1579
+ ruleId: decision.rule?.id,
1580
+ ruleName: decision.rule ? (decision.rule.policyName || decision.rule.policyId) : undefined,
1581
+ at: new Date().toISOString(),
1582
+ });
1583
+ if (decision.block) {
1584
+ return {
1585
+ success: true,
1586
+ data: {
1587
+ allowed: false,
1588
+ decision: 'block',
1589
+ operation: input.operation || 'unknown',
1590
+ degraded: true,
1591
+ failsafe: 'deny',
1592
+ actionPolicy: {
1593
+ allowed: false,
1594
+ verdict: 'block',
1595
+ reason: `degraded_fail_closed: ${decision.reason}`,
1596
+ ...(decision.rule ? { policyId: decision.rule.policyId, policyName: decision.rule.policyName } : {}),
1597
+ },
1598
+ },
1599
+ };
1600
+ }
1601
+ return {
1602
+ success: true,
1603
+ data: { allowed: true, decision: 'allow', operation: input.operation || 'unknown', degraded: true, failsafe: 'allow' },
1604
+ };
1605
+ }
781
1606
  async checkContext(input) {
782
1607
  this.requireTextScan('checkContext');
783
1608
  // Monitor mode: allow instantly; report the content for async analysis.
@@ -830,56 +1655,113 @@ class FullCourtDefense {
830
1655
  const input = this.withIdentity(rawInput);
831
1656
  // Monitor mode: run the action immediately — no preflight wait, no approval
832
1657
  // gate. The tool call is recorded fire-and-forget for console visibility.
833
- if (await this._getEffectiveMode() === 'monitor') {
834
- void this.recordToolCall({
835
- ...input,
836
- decision: 'allow',
837
- reason: input.reason || 'monitor_mode_async',
838
- argsSummary: input.argsSummary || input.toolArgs,
839
- }).catch(() => { });
840
- return action();
1658
+ const mode = await this._resolveToolMode();
1659
+ if (mode.effective === 'monitor') {
1660
+ // Monitor on the mode recorded on the agent, no live answer yet (cold start, API down):
1661
+ // it still never blocks, but it is not silent — spooled and reported once the API answers.
1662
+ // A refused key or shield on a Monitor shield (O4): it runs, and its report raises the alert.
1663
+ if (!mode.confirmed && !mode.configError && !mode.pending) {
1664
+ this._spoolUnconfirmedMonitor(input);
1665
+ return action();
1666
+ }
1667
+ const recording = this._recordMonitorCall({ ...input, decision: 'allow' }, mode);
1668
+ if (!options.awaitRecord)
1669
+ return action();
1670
+ try {
1671
+ return await action();
1672
+ }
1673
+ finally {
1674
+ // Short-lived hosts (Lambda) freeze when the handler returns: the record, and a report of
1675
+ // calls spooled while the API was down (started when the mode lookup answered), finish first.
1676
+ await settleWithin(Promise.all([recording, this.skippedFlush, this.records.flush()]), RECORD_FLUSH_MAX_MS);
1677
+ }
1678
+ }
1679
+ // A local decision's record is written once, after the tool ran (decision + how it ended).
1680
+ this.deferredLocalRecords.set(input, null);
1681
+ let preflight;
1682
+ try {
1683
+ preflight = await this.checkToolCall(input);
1684
+ }
1685
+ catch (error) {
1686
+ this.deferredLocalRecords.delete(input);
1687
+ throw error;
1688
+ }
1689
+ const localRecord = this.deferredLocalRecords.get(input) ?? undefined;
1690
+ this.deferredLocalRecords.delete(input);
1691
+ if (localRecord && preflight.data?.decidedBy === 'local') {
1692
+ return this._runLocallyDecided(input, preflight.data, action, options);
841
1693
  }
842
- const preflight = await this.checkToolCall(input);
843
1694
  if (!preflight.success) {
1695
+ // `code` is set only when checkToolCall classified the answer as definite (a 4xx, not an outage).
1696
+ if (preflight.code && (0, errors_1.isDefiniteStatus)(preflight.status)) {
1697
+ throw new errors_1.FullCourtDefenseApiError({
1698
+ status: preflight.status,
1699
+ shieldId: this.config.shieldId,
1700
+ apiUrl: this.config.apiUrl,
1701
+ serverError: preflight.serverError,
1702
+ serverCode: preflight.serverCode,
1703
+ call: `check tool call "${input.toolName}"`,
1704
+ });
1705
+ }
844
1706
  throw new Error(`FullCourtDefense Agent Security error: ${preflight.error || 'tool-call preflight failed'}`);
845
1707
  }
846
1708
  if (preflight.data && !preflight.data.allowed) {
847
- const blockedError = options.onBlocked ?? ((message) => new Error(message));
848
- if (preflight.data.decision === 'approval' && options.approvalMode === 'wait') {
849
- const approvalActionId = preflight.data.approvalActionId;
1709
+ const data = preflight.data;
1710
+ const policy = data.actionPolicy;
1711
+ const rule = policy && (policy.matchedRule || policy.policyId || policy.policyName)
1712
+ ? { ...(policy.matchedRule || policy.policyId ? { id: String(policy.matchedRule || policy.policyId) } : {}), ...(policy.policyName ? { name: String(policy.policyName) } : {}) }
1713
+ : undefined;
1714
+ const outcome = data.argsProblem ? 'args_problem' : (data.degraded ? 'fail_closed' : (data.decision === 'approval' ? 'approval' : 'block'));
1715
+ const code = outcome === 'args_problem' ? 'FCD_ARGS_TOO_LARGE' : outcome === 'fail_closed' ? 'FCD_FAIL_CLOSED' : outcome === 'approval' ? 'FCD_APPROVAL_REQUIRED' : 'FCD_BLOCKED';
1716
+ // The error the agent code receives: typed (`ToolCallBlocked`, same shape as Python's) unless the caller supplies its own.
1717
+ const blockedError = (message, reason) => (options.onBlocked
1718
+ ? options.onBlocked(message)
1719
+ : new errors_1.ToolCallBlocked(message, {
1720
+ toolName: input.toolName, decision: data.decision, reason: reason ?? policy?.reason ?? message, outcome, code,
1721
+ rule, approvalActionId: data.approvalActionId, degraded: data.degraded === true,
1722
+ }));
1723
+ if (data.decision === 'approval' && options.approvalMode === 'wait') {
1724
+ const approvalActionId = data.approvalActionId;
850
1725
  if (!approvalActionId) {
851
1726
  throw blockedError(`FullCourtDefense blocked tool call "${input.toolName}": approval required, but no approval request id was returned.`);
852
1727
  }
853
1728
  await this._waitForApproval(approvalActionId, options);
854
1729
  }
855
1730
  else {
856
- const policy = preflight.data.actionPolicy;
857
- const reason = policy?.reason || `Tool call ${preflight.data.decision}`;
858
- throw blockedError(`FullCourtDefense blocked tool call "${input.toolName}": ${reason}`);
1731
+ const reason = policy?.reason || `Tool call ${data.decision}`;
1732
+ // Approval in block mode (a hosted agent cannot wait): the same call made again after
1733
+ // an admin approves runs once on that approval (the server reuses one request per action).
1734
+ const approvalHint = data.decision === 'approval' && data.approvalActionId
1735
+ ? `${/[.!?]$/.test(reason) ? ' ' : '. '}An admin must approve request ${data.approvalActionId} in FullCourtDefense; after that, the same call made again runs once.`
1736
+ : '';
1737
+ throw blockedError(`FullCourtDefense blocked tool call "${input.toolName}": ${reason}${approvalHint}`, reason);
859
1738
  }
860
1739
  }
1740
+ // Allowed without a check (FCD_FAIL_MODE): the spool already holds this call and reports it
1741
+ // once the API is back; a record now would only wait out the request timeout.
1742
+ const unchecked = Boolean(this.failMode && preflight.data?.degraded);
861
1743
  let result;
862
1744
  try {
863
1745
  result = await action();
864
1746
  }
865
1747
  catch (error) {
1748
+ if (unchecked)
1749
+ throw error;
1750
+ // Minimal facts: the error's type name, never its message (it can carry business data).
1751
+ const errorType = errorTypeName(error);
866
1752
  if (preflight.data?.approvalActionId) {
867
1753
  await this._markApprovalExecuted(preflight.data.approvalActionId, {
868
1754
  success: false,
869
- error: error instanceof Error ? error.message : 'Tool call failed',
1755
+ error: `The tool raised ${errorType}.`,
870
1756
  }).catch(() => undefined);
871
1757
  }
872
1758
  else {
873
- await this.recordToolCall({
874
- ...input,
875
- operation: input.operation || preflight.data?.operation,
876
- decision: 'block',
877
- reason: error instanceof Error ? error.message : 'Tool call failed',
878
- argsSummary: input.argsSummary || input.toolArgs,
879
- }).catch(() => undefined);
1759
+ await this._reportOutcome(input, preflight.data, { outcome: 'failed', errorType }, options);
880
1760
  }
881
1761
  throw error;
882
1762
  }
1763
+ if (unchecked)
1764
+ return result;
883
1765
  if (preflight.data?.approvalActionId) {
884
1766
  await this._markApprovalExecuted(preflight.data.approvalActionId, {
885
1767
  success: true,
@@ -887,22 +1769,94 @@ class FullCourtDefense {
887
1769
  });
888
1770
  }
889
1771
  else {
890
- await this.recordToolCall({
1772
+ await this._reportOutcome(input, preflight.data, { outcome: 'executed' }, options);
1773
+ }
1774
+ // Short-lived hosts (Lambda) freeze when the handler returns: finish sending the calls
1775
+ // decided without a check while the API was down, capped like the monitor record.
1776
+ if (options.awaitRecord && this.skippedFlush)
1777
+ await settleWithin(this.skippedFlush, RECORD_FLUSH_MAX_MS);
1778
+ return result;
1779
+ }
1780
+ /**
1781
+ * Run (or stop) a call decided locally, and write its ONE record afterwards in the background: a stopped call
1782
+ * at once, an allowed call with how it ended (`executed`, or `failed` with the error's type name only).
1783
+ */
1784
+ async _runLocallyDecided(input, data, action, options) {
1785
+ const finish = async (record) => {
1786
+ this._enqueueRecord(record);
1787
+ // Short-lived hosts (Lambda) freeze when the handler returns: the record goes first, capped.
1788
+ if (options.awaitRecord)
1789
+ await settleWithin(this.records.flush(), RECORD_FLUSH_MAX_MS);
1790
+ };
1791
+ if (!data.allowed) {
1792
+ await finish(this._localRecordBody(input, data));
1793
+ const policy = data.actionPolicy;
1794
+ const reason = policy?.reason || `Tool call ${data.decision}`;
1795
+ const message = `FullCourtDefense blocked tool call "${input.toolName}": ${reason}`;
1796
+ const rule = policy && (policy.matchedRule || policy.policyId || policy.policyName)
1797
+ ? { ...(policy.matchedRule || policy.policyId ? { id: String(policy.matchedRule || policy.policyId) } : {}), ...(policy.policyName ? { name: String(policy.policyName) } : {}) }
1798
+ : undefined;
1799
+ throw options.onBlocked
1800
+ ? options.onBlocked(message)
1801
+ : new errors_1.ToolCallBlocked(message, { toolName: input.toolName, decision: data.decision, reason, outcome: 'block', code: 'FCD_BLOCKED', rule, degraded: false });
1802
+ }
1803
+ let result;
1804
+ try {
1805
+ result = await action();
1806
+ }
1807
+ catch (error) {
1808
+ await finish(this._localRecordBody(input, data, { outcome: 'failed', errorType: errorTypeName(error) }));
1809
+ throw error;
1810
+ }
1811
+ await finish(this._localRecordBody(input, data, { outcome: 'executed' }));
1812
+ return result;
1813
+ }
1814
+ /**
1815
+ * How an allowed call ended. When the check returned the gate record's `actionId` (backends with
1816
+ * the G-11 outcome report), the outcome goes ON that record: no second record, and a failure
1817
+ * carries its error type only. With an older backend, the 2.0 post-run record, except that a tool
1818
+ * that failed is an allowed call that failed (decision `allow`, error type only), never a `block`
1819
+ * carrying the tool's error text. Sent in the background; `awaitRecord` (Lambda) waits for it,
1820
+ * capped like the monitor record.
1821
+ */
1822
+ async _reportOutcome(input, check, report, options) {
1823
+ const actionId = typeof check?.actionId === 'string' && check.actionId ? check.actionId : undefined;
1824
+ const sending = actionId
1825
+ ? this._postAgentSecurity('/api/agent-security/runtime/tool-call', {
1826
+ actionId,
1827
+ outcome: report.outcome,
1828
+ ...(report.errorType ? { errorType: report.errorType } : {}),
1829
+ }, 'full')
1830
+ : this.recordToolCall({
891
1831
  ...input,
892
- operation: input.operation || preflight.data?.operation,
1832
+ operation: input.operation || check?.operation,
893
1833
  decision: 'allow',
1834
+ ...(report.outcome === 'failed' ? { reason: `Allowed by policy; the tool raised ${report.errorType ?? 'an error'}.` } : {}),
894
1835
  argsSummary: input.argsSummary || input.toolArgs,
895
1836
  });
896
- }
897
- return result;
1837
+ const settled = sending.catch(() => undefined);
1838
+ if (options.awaitRecord)
1839
+ await settleWithin(settled, RECORD_FLUSH_MAX_MS);
898
1840
  }
899
1841
  async _waitForApproval(actionId, options) {
900
1842
  const timeoutMs = options.timeoutMs ?? 900000;
901
1843
  const pollIntervalMs = Math.max(1000, options.pollIntervalMs ?? 3000);
902
1844
  const deadline = Date.now() + timeoutMs;
1845
+ // This wait's own id: two identical calls of a hosted agent share one request (the server
1846
+ // reuses it per action), and only the waiter that receives the approval is told "approved";
1847
+ // any other waiter on the same request is told it expired, so one approval runs once.
1848
+ const waiter = randomInstanceId();
903
1849
  while (Date.now() <= deadline) {
904
- const status = await this._getApprovalStatus(actionId);
1850
+ const status = await this._getApprovalStatus(actionId, waiter);
905
1851
  if (!status.success) {
1852
+ // A refused key / shield ends the wait with the explicit error. A 400 here is about the
1853
+ // request id (not found, already spent), so it keeps the approval wording below.
1854
+ if (status.status === 401 || status.status === 403 || status.status === 404) {
1855
+ throw new errors_1.FullCourtDefenseApiError({
1856
+ status: status.status, shieldId: this.config.shieldId, apiUrl: this.config.apiUrl,
1857
+ serverError: status.serverError, call: `read approval ${actionId}`,
1858
+ });
1859
+ }
906
1860
  throw new Error(`FullCourtDefense approval error: ${status.error || 'approval status failed'}`);
907
1861
  }
908
1862
  const approval = status.data?.approval;
@@ -922,8 +1876,8 @@ class FullCourtDefense {
922
1876
  }
923
1877
  throw new Error(`FullCourtDefense approval timed out for tool call. Request ${actionId} is still waiting for human approval.`);
924
1878
  }
925
- async _getApprovalStatus(actionId) {
926
- const url = `${this.config.apiUrl}/api/agent-security/runtime/approvals/${encodeURIComponent(actionId)}?shieldId=${encodeURIComponent(this.config.shieldId)}`;
1879
+ async _getApprovalStatus(actionId, waiter) {
1880
+ const url = `${this.config.apiUrl}/api/agent-security/runtime/approvals/${encodeURIComponent(actionId)}?shieldId=${encodeURIComponent(this.config.shieldId)}${waiter ? `&waiter=${encodeURIComponent(waiter)}` : ''}`;
927
1881
  const resp = await fetch(url, {
928
1882
  method: 'GET',
929
1883
  headers: buildScanHeaders(this.config.shieldKey),
@@ -931,24 +1885,77 @@ class FullCourtDefense {
931
1885
  });
932
1886
  const data = await resp.json().catch(() => ({}));
933
1887
  if (!resp.ok) {
934
- return { success: false, error: data.error || `Approval status request failed (${resp.status})` };
1888
+ if (resp.status === 401 || resp.status === 403 || resp.status === 404) {
1889
+ return {
1890
+ success: false,
1891
+ status: resp.status,
1892
+ serverError: data.error,
1893
+ error: (0, errors_1.describeApiError)({ status: resp.status, shieldId: this.config.shieldId, apiUrl: this.config.apiUrl, serverError: data.error, call: `read approval ${actionId}` }),
1894
+ };
1895
+ }
1896
+ return { success: false, status: resp.status, error: data.error || `Approval status request failed (${resp.status})` };
935
1897
  }
936
1898
  return data;
937
1899
  }
938
1900
  async _markApprovalExecuted(actionId, input) {
939
1901
  return this._postAgentSecurity(`/api/agent-security/runtime/approvals/${encodeURIComponent(actionId)}/executed`, input);
940
1902
  }
941
- async _postAgentSecurity(path, input) {
1903
+ async _postAgentSecurity(path, input, durable, timeoutMs) {
1904
+ // Encoded first, on its own: a body that cannot be encoded is the call's own input (a throwing
1905
+ // toJSON, a value too deep for JSON.stringify), never a network failure and never an outage.
1906
+ const encoded = (0, argsBounds_1.encodeBody)({ ...input, shieldId: this.config.shieldId });
1907
+ if (!encoded.ok) {
1908
+ return {
1909
+ success: false,
1910
+ error: `FullCourtDefense could not encode this call as JSON (${encoded.errorType}); it was not sent.`,
1911
+ localEncodingError: encoded.errorType,
1912
+ category: 'request',
1913
+ retryable: false,
1914
+ };
1915
+ }
1916
+ if (!durable)
1917
+ return this._postEncoded(path, encoded.json, timeoutMs);
1918
+ // A record: tracked while on the wire so the end of the process can wait for it briefly or spool it.
1919
+ const entry = { path, json: encoded.json, shieldId: this.config.shieldId, at: new Date().toISOString() };
1920
+ const sending = this._postEncoded(path, encoded.json);
1921
+ entry.done = sending;
1922
+ pendingRecords.add(entry);
1923
+ installExitHooks();
1924
+ const result = await sending;
1925
+ if (pendingRecords.delete(entry) && durable === 'full' && !result.success) {
1926
+ const noAnswer = typeof result.error === 'string' && result.error.startsWith('fcd_unavailable');
1927
+ const status = typeof result.status === 'number' ? result.status : undefined;
1928
+ if (noAnswer || (status !== undefined && (status >= 500 || status === 408 || status === 429)))
1929
+ keepFailed(entry);
1930
+ }
1931
+ return result;
1932
+ }
1933
+ async _postEncoded(path, json, timeoutMs) {
942
1934
  try {
1935
+ const headers = buildScanHeaders(this.config.shieldKey);
1936
+ // The outage setting this agent runs with: the console says what happens to a Blocking agent
1937
+ // when FullCourtDefense cannot be reached only once the agent itself reports it.
1938
+ if (this.failMode && this.failMode !== 'open')
1939
+ headers[failMode_1.FAIL_MODE_HEADER] = this.failMode;
943
1940
  const resp = await fetch(`${this.config.apiUrl}${path}`, {
944
1941
  method: 'POST',
945
- headers: buildScanHeaders(this.config.shieldKey),
946
- body: JSON.stringify({ ...input, shieldId: this.config.shieldId }),
947
- signal: AbortSignal.timeout(this.config.scanTimeoutMs),
1942
+ headers,
1943
+ body: json,
1944
+ signal: AbortSignal.timeout(timeoutMs ?? this.config.scanTimeoutMs),
948
1945
  });
949
1946
  const data = await resp.json().catch(() => ({}));
950
1947
  if (!resp.ok) {
951
- return { success: false, error: data.error || `Agent Security request failed (${resp.status})` };
1948
+ // The runtime API's error body: { error, message?, code, category, retryable } (G-04).
1949
+ const said = typeof data.message === 'string' && data.message ? data.message : data.error;
1950
+ return {
1951
+ success: false,
1952
+ status: resp.status,
1953
+ ...(typeof said === 'string' && said ? { serverError: said } : {}),
1954
+ ...(typeof data.code === 'string' && data.code ? { serverCode: data.code } : {}),
1955
+ ...(typeof data.category === 'string' ? { category: data.category } : {}),
1956
+ ...(typeof data.retryable === 'boolean' ? { retryable: data.retryable } : {}),
1957
+ error: data.error || `Agent Security request failed (${resp.status})`,
1958
+ };
952
1959
  }
953
1960
  return data;
954
1961
  }