{"slug": "stop-ai-agents-acting-on-bluffs-building-a-deterministic-tool-decider-gate", "title": "Stop AI Agents Acting on Bluffs: Building a Deterministic Tool-Decider Gate", "summary": "A developer published a tutorial on building a deterministic \"tool-decider gate\" that sits between an AI agent and every side-effecting tool, parsing structured tool calls with TypeScript and Zod and evaluating them against explicit policy rules to return an execution plan, a structured repair request, or a hard denial. The gate is designed to catch semantically wrong but structurally valid calls, such as a refund issued for 49 cents instead of $49.00, and to produce an auditable trail with machine-readable reason codes for each decision.", "body_md": "*Originally published on [tamiz.pro](https://tamiz.pro/insights/deterministic-tool-decider-gate-ai-agents).*\n\nAn AI agent can produce a perfectly plausible tool call that your runtime happily executes: a SQL statement against the wrong table, a shell command with an unexpected flag, a payment request for the wrong amount. The model was not \"lying\" in a moral sense; it was optimizing for a plausible next step, and plausibility is not correctness.\n\nThe fix is to move authorization and policy decisions out of the model's discretion and into a deterministic layer that sits between the agent and every side-effecting tool. This layer is often called a **tool-decider gate**. It parses structured tool calls, evaluates them against explicit, testable rules, and either returns an execution plan, a correction request, or a hard denial.\n\nThis tutorial builds that gate for a real agent workflow using TypeScript, Zod, and a small policy engine. The result is not merely a safer agent; it is an auditable one, where every decision has a machine-readable reason code and a replayable evidence trail.\n\nMost agent frameworks assume the model emits a tool call and the runtime executes it. That assumption is fine for read-only tools with no sensitive parameters. It breaks down when a tool can mutate state, spend money, delete data, or reach an internal network.\n\nConsider a customer-support agent asked to \"refund order A-1042 for $49.00.\" A model might emit:\n\n```\n{\n  \"tool\": \"issue_refund\",\n  \"args\": {\n    \"orderId\": \"A-1042\",\n    \"amount\": 4900,\n    \"currency\": \"USD\",\n    \"reason\": \"customer_request\"\n  }\n}\n```\n\nThat looks correct. Now consider the same agent under a slightly different prompt, where the model confuses cents and dollars:\n\n```\n{\n  \"tool\": \"issue_refund\",\n  \"args\": {\n    \"orderId\": \"A-1042\",\n    \"amount\": 49,\n    \"currency\": \"USD\",\n    \"reason\": \"customer_request\"\n  }\n}\n```\n\nThe second call is structurally valid, semantically wrong, and will happily refund $0.49 while reporting $49.00 to the customer. No schema validator catches this. No prompt makes it reliably safe.\n\nThe general failure mode is that **language models are probabilistic generators of text-shaped actions**, while production systems require **deterministic acceptance criteria over structured actions**. The gap between the two is where bluffs become incidents.\n\nA tool-decider gate narrows that gap by enforcing four properties:\n\nThe gate must be ordinary code. It must never ask a model whether it thinks the call is safe.\n\nThe gate is a chokepoint. Every tool call, whether generated by a model, a planner, a sub-agent, or a human-facing UI, passes through it.\n\n```\nUser Request\n     |\n     v\n[ Agent / Planner (LLM) ]\n     |\n     |  proposed tool call (structured)\n     v\n[ Tool-Decider Gate ]  <-- schemas, policy rules, context, allowlists\n     |          |  |  |\n     |          |  |  +--> DENY: hard block, no execution\n     |          |  +-----> REPAIR: return structured correction request\n     |          +--------> ALLOW: emit execution plan\n     v\n[ Executor / Sandbox ]\n     |\n     v\n[ Tool (DB, API, shell, browser, payments) ]\n     |\n     v\n[ Audit Log ]  <-- decision, rule IDs, evidence hashes, outcome\n```\n\nTwo design rules follow immediately.\n\n**The gate returns decisions, not just booleans.** A boolean `false` tells the agent nothing useful. A structured denial tells it exactly which field failed, what constraint applies, and what it must do next. That distinction is what turns a gate from a wall into a feedback loop.\n\n**The executor trusts only the gate's output.** The executor should never re-derive policy, and the model should never be able to construct an execution plan directly. If the agent can bypass the gate, the gate is decoration.\n\nA useful mental model: the LLM is a **proposal engine**, and the gate is the **compiler front end**. The model's output is untrusted source code. The gate performs type checking, semantic analysis, and admission control before anything runs.\n\nYou will need:\n\nYou do not need an LLM API key to build and test the gate. That is deliberate: policy logic that depends on a network call is not deterministic, and deterministic policy logic should be testable offline.\n\nCreate the project and install dependencies:\n\n```\nmkdir tool-decider-gate && cd tool-decider-gate\nnpm init -y\nnpm install zod\nnpm install -D typescript tsx @types/node vitest\nnpx tsc --init\n```\n\nConfigure `tsconfig.json`:\n\n```\n{\n  \"compilerOptions\": {\n    \"target\": \"ES2022\",\n    \"module\": \"NodeNext\",\n    \"moduleResolution\": \"NodeNext\",\n    \"strict\": true,\n    \"noUncheckedIndexedAccess\": true,\\n    \"exactOptionalPropertyTypes\": true,\\n    \"outDir\": \"dist\",\n    \"rootDir\": \"src\",\n    \"declaration\": true,\n    \"sourceMap\": true,\n    \"esModuleInterop\": true,\n    \"skipLibCheck\": true\n  },\n  \"include\": [\"src/**/*.ts\", \"tests/**/*.ts\"]\n}\n```\n\nSet the package to ESM and add scripts:\n\n```\nnpm pkg set type=module\nnpm pkg set scripts.build=\"tsc -p tsconfig.json\"\nnpm pkg set scripts.test=\"vitest run\"\nnpm pkg set scripts.dev=\"tsx src/demo.ts\"\n```\n\nCreate the source layout:\n\n```\nmkdir -p src/tools src/policy src/gate src/audit tests\n```\n\nTools are declared once, and that declaration drives three things: validation, the policy gate's type narrowing, and the agent-facing schema. One source of truth prevents the classic failure where the prompt describes a tool differently from the runtime.\n\nCreate `src/tools/registry.ts`:\n\n``` js\nimport { z } from \"zod\";\n\n/** Amounts are always integer minor units (cents). */\nexport const refundArgsSchema = z.object({\n  orderId: z.string().regex(/^[A-Z]{1,3}-\\d{4,10}$/, \"Invalid order ID format\"),\n  amount: z.number().int().positive().max(100_000),\n  currency: z.enum([\"USD\", \"EUR\", \"GBP\"]),\n  reason: z.enum([\"customer_request\", \"damaged_item\", \"duplicate_charge\"]),\n  idempotencyKey: z.string().min(8).max(128),\n});\n\nexport type RefundArgs = z.infer<typeof refundArgsSchema>;\n\nexport const searchOrdersArgsSchema = z.object({\n  customerEmail: z.string().email(),\n  limit: z.number().int().min(1).max(50).default(10),\n});\n\nexport type SearchOrdersArgs = z.infer<typeof searchOrdersArgsSchema>;\n\nexport const sendEmailArgsSchema = z.object({\n  to: z.string().email(),\n  subject: z.string().min(1).max(200),\n  body: z.string().min(1).max(10_000),\n});\n\nexport type SendEmailArgs = z.infer<typeof sendEmailArgsSchema>;\n\n/**\n * A tool definition carries its schema plus metadata used by the policy layer.\n * The policy layer reads metadata; it never re-parses raw model output.\n */\nexport interface ToolDefinition<\n  Args extends z.ZodTypeAny,\n  Result,\n> {\n  name: string;\n  description: string;\n  argsSchema: Args;\n  /** Side-effecting tools require an explicit authorization decision. */\n  effect: \"read\" | \"write\" | \"destructive\";\n  /** Tools that must never be reachable without a human confirmation token. */\n  requiresHumanApproval?: boolean;\n  execute: (args: z.infer<Args>, ctx: ExecutionContext) => Promise<Result>;\n}\n\nexport interface ExecutionContext {\n  requestId: string;\n  actorId: string;\n  agentRole: string;\n  /** Facts the gate can verify independently of the model. */\n  facts: Record<string, unknown>;\n  /** A short-lived token proving a human approved this specific action. */\n  approvalToken?: string;\n  now: Date;\n}\n\nexport const issueRefundTool: ToolDefinition<typeof refundArgsSchema, { refundId: string }> = {\n  name: \"issue_refund\",\n  description: \"Issue a refund to a customer for an existing order.\",\n  argsSchema: refundArgsSchema,\n  effect: \"write\",\n  requiresHumanApproval: true,\n  async execute(args, ctx) {\n    // Replace with a real payments API call.\n    return { refundId: `rf_${ctx.requestId}_${args.orderId}` };\n  },\n};\n\nexport const searchOrdersTool: ToolDefinition<typeof searchOrdersArgsSchema, { orderIds: string[] }> = {\n  name: \"search_orders\",\n  description: \"Look up a customer's recent orders.\",\n  argsSchema: searchOrdersArgsSchema,\n  effect: \"read\",\n  async execute(args) {\n    // Replace with a real database query.\n    return { orderIds: [\"A-1042\"] };\n  },\n};\n\nexport const sendEmailTool: ToolDefinition<typeof sendEmailArgsSchema, { messageId: string }> = {\n  name: \"send_email\",\n  description: \"Send an email to the customer.\",\n  argsSchema: sendEmailArgsSchema,\n  effect: \"write\",\n  async execute(args) {\n    // Replace with a real email provider call.\n    return { messageId: `msg_${args.to}` };\n  },\n};\n\nexport const toolRegistry = {\n  issue_refund: issueRefundTool,\n  search_orders: searchOrdersTool,\n  send_email: sendEmailTool,\n} as const;\n\nexport type ToolName = keyof typeof toolRegistry;\n```\n\nNote the schema details that do real work. `amount` is an integer in minor units, so decimal-cent ambiguity disappears at the type level. `orderId` has a format constraint, which rejects a hallucinated identifier before it reaches the database. `limit` is capped, which prevents a model from requesting an unbounded scan.\n\nThe `effect` field classifies risk. `requiresHumanApproval` marks tools where the gate must find a valid approval token. These are not prompts; they are control-flow branches.\n\nThe decider takes a proposed call plus context and returns a decision. It must be a pure function of its inputs, apart from explicitly injected lookups.\n\nCreate `src/gate/decider.ts`:\n\n``` js\nimport { z } from \"zod\";\nimport { toolRegistry, type ExecutionContext, type ToolName } from \"../tools/registry.js\";\nimport { evaluateRules, type RuleResult } from \"../policy/rules.js\";\n\nexport type Decision =\n  | {\n      status: \"allow\";\n      tool: ToolName;\n      args: Record<string, unknown>;\n      /** Rule IDs that explicitly permitted this action. */\n      satisfiedBy: string[];\n      /** Facts the executor may rely on. */\n      evidence: Record<string, unknown>;\n    }\n  | {\n      status: \"repair\";\n      tool: ToolName;\n      reasonCode: string;\n      message: string;\n      /** Machine-readable hints the agent can act on. */\n      violations: RuleResult[];\n    }\n  | {\n      status: \"deny\";\n      tool: ToolName | \"unknown\";\n      reasonCode: string;\n      message: string;\n      violations: RuleResult[];\n    };\n\nexport interface ProposedCall {\n  tool: string;\n  args: unknown;\n}\n\nexport interface DeciderDeps {\n  /** Resolves facts independently of the model. */\n  lookupFacts: (ctx: ExecutionContext) => Promise<Record<string, unknown>>;\n  /** Verifies an approval token. Inject a real verifier in production. */\n  verifyApproval: (token: string, ctx: ExecutionContext) => Promise<boolean>;\n}\n\nconst KNOWN_TOOLS = new Set<string>(Object.keys(toolRegistry));\n\nexport async function decide(\n  proposed: ProposedCall,\n  ctx: ExecutionContext,\n  deps: DeciderDeps,\n): Promise<Decision> {\n  // Step 1: is this even a tool we know about?\n  if (!KNOWN_TOOLS.has(proposed.tool)) {\n    return {\n      status: \"deny\",\n      tool: \"unknown\",\n      reasonCode: \"UNKNOWN_TOOL\",\n      message: `Tool \"${proposed.tool}\" is not registered. Available tools: ${[...KNOWN_TOOLS].join(\", \")}.`,\n      violations: [],\n    };\n  }\n\n  const toolName = proposed.tool as ToolName;\n  const tool = toolRegistry[toolName];\n\n  // Step 2: structural validation. Never trust shape from the model.\n  const parsed = tool.argsSchema.safeParse(proposed.args);\n  if (!parsed.success) {\n    const issues = parsed.error.issues.map((i) => ({\n      ruleId: \"SCHEMA_VALIDATION\",\n      field: i.path.join(\".\") || \"<root>\",\n      message: i.message,\n    }));\n\n    return {\n      status: \"repair\",\n      tool: toolName,\n      reasonCode: \"SCHEMA_VIOLATION\",\n      message: \"Tool arguments failed schema validation. Fix the fields listed and retry.\",\n      violations: issues,\n    };\n  }\n\n  const args = parsed.data as Record<string, unknown>;\n\n  // Step 3: gather independent facts. The model cannot supply these.\n  const facts = { ...ctx.facts, ...(await deps.lookupFacts(ctx)) };\n\n  // Step 4: deterministic policy evaluation.\n  const results = await evaluateRules(toolName, args, { ...ctx, facts });\n  const failures = results.filter((r) => r.status === \"fail\");\n\n  if (failures.length > 0) {\n    const hard = failures.filter((r) => r.severity === \"hard\");\n    const soft = failures.filter((r) => r.severity === \"soft\");\n\n    if (hard.length > 0) {\n      return {\n        status: \"deny\",\n        tool: toolName,\n        reasonCode: hard[0]!.ruleId,\n        message: hard.map((h) => h.message).join(\" \"),\n        violations: failures,\n      };\n    }\n\n    return {\n      status: \"repair\",\n      tool: toolName,\n      reasonCode: soft[0]!.ruleId,\n      message: soft.map((s) => s.message).join(\" \"),\n      violations: failures,\n    };\n  }\n\n  // Step 5: approval requirement for high-risk effects.\n  if (tool.requiresHumanApproval) {\n    const token = ctx.approvalToken;\\n    const approved = token ? await deps.verifyApproval(token, ctx) : false;\n    if (!approved) {\n      return {\n        status: \"deny\",\n        tool: toolName,\n        reasonCode: \"HUMAN_APPROVAL_REQUIRED\",\n        message:\n          \"This action requires human approval. Present the proposed action to an authorized approver and retry with a valid approval token.\",\n        violations: [\n          {\n            ruleId: \"HUMAN_APPROVAL_REQUIRED\",\n            status: \"fail\",\n            severity: \"hard\",\n            field: \"approvalToken\",\n            message: \"No valid approval token was supplied for this action.\",\n          },\n        ],\n      };\n    }\n  }\n\n  return {\n    status: \"allow\",\n    tool: toolName,\n    args,\n    satisfiedBy: results.filter((r) => r.status === \"pass\").map((r) => r.ruleId),\n    evidence: facts,\n  };\n}\n```\n\nThree properties of this design matter more than the code itself.\n\n**Ordering is fixed.** Unknown tool, then schema, then facts, then policy, then approval. Changing the order changes security semantics, so treat it as part of the contract.\n\n**Facts flow one way.** The gate collects facts from trusted systems. Model-provided claims can be *proposed* as facts, but they are never *promoted* to facts by the gate.\n\n**Repair and deny are distinct.** A schema error is repairable: the agent can retry with corrected fields. A policy violation like \"refund exceeds order total\" may also be repairable if the agent can look up the correct amount. But an unknown tool or a missing approval token is a deny. Conflating them causes agents to loop, retrying the same thing against a wall.\n\nRules are small, named, independently testable predicates. They receive the validated arguments, the execution context, and trusted facts.\n\nCreate `src/policy/rules.ts`:\n\n``` python\nimport type { ExecutionContext, ToolName } from \"../tools/registry.js\";\n\nexport type RuleSeverity = \"hard\" | \"soft\";\n\nexnexport interface RuleResult {\n  ruleId: string;\n  status: \"pass\" | \"fail\";\n  severity: RuleSeverity;\n  field?: string;\n  message: string;\n}\n\nexport interface RuleContext extends ExecutionContext {\n  facts: Record<string, unknown>;\n}\n\nexport type Rule = (\n  args: Record<string, unknown>,\n  ctx: RuleContext,\n) => RuleResult | Promise<RuleResult>;\n\nconst pass = (ruleId: string, message = \"Rule satisfied.\"): RuleResult => ({\n  ruleId,\n  status: \"pass\",\n  severity: \"hard\",\n  message,\n});\n\nconst fail = (\n  ruleId: string,\n  message: string,\n  severity: RuleSeverity = \"hard\",\n  field?: string,\n): RuleResult => ({ ruleId, status: \"fail\", severity, message, ...(field ? { field } : {}) });\n\nconst refundAmountWithinOrder: Rule = async (args, ctx) => {\n  const orderId = String(args.orderId ?? \"\");\n  const order = (ctx.facts.orders as Record<string, { total: number; currency: string }> | undefined)?.[orderId];\n\n  if (!order) {\n    return fail(\n      \"ORDER_MUST_EXIST\",\n      `Order ${orderId} was not found in the order system. Call search_orders first and use a verified order ID.`,\n      \"soft\",\n      \"orderId\",\n    );\n  }\n\n  const amount = Number(args.amount);\n  if (amount > order.total) {\n    return fail(\n      \"REFUND_EXCEEDS_ORDER_TOTAL\",\n      `Refund of ${amount} minor units exceeds the order total of ${order.total} for ${orderId}.`,\n      \"soft\",\n      \"amount\",\n    );\n  }\n\n  if (args.currency !== order.currency) {\n    return fail(\n      \"CURRENCY_MISMATCH\",\n      `Order ${orderId} is denominated in ${order.currency}, not ${String(args.currency)}.`,\n      \"soft\",\n      \"currency\",\n    );\n  }\n\n  return pass(\"REFUND_WITHIN_ORDER_TOTAL\");\n};\n\nconst refundNotAboveAgentLimit: Rule = (args, ctx) => {\n  const limit = Number(ctx.facts.agentRefundLimit ?? 0);\n  const amount = Number(args.amount ?? 0);\n\n  if (limit <= 0) {\n    return fail(\"NO_REFUND_AUTHORITY\", \"This agent role has no refund authority configured.\");\n  }\n\n  if (amount > limit) {\n    return fail(\n      \"REFUND_EXCEEDS_AGENT_LIMIT\",\n      `Refund of ${amount} exceeds this agent's limit of ${limit}. Escalate to a human operator.`,\n    );\n  }\n\n  return pass(\"REFUND_WITHIN_AGENT_LIMIT\");\n};\n\nconst emailOnlyToCustomer: Rule = async (args, ctx) => {\n  const customerEmail = ctx.facts.customerEmail;\n  const to = String(args.to ?? \"\").toLowerCase();\n\n  if (typeof customerEmail !== \"string\") {\n    return fail(\"CUSTOMER_CONTEXT_MISSING\", \"No customer context is bound to this session.\");\n  }\n\n  if (to !== customerEmail.toLowerCase()) {\n    return fail(\n      \"EMAIL_RECIPIENT_NOT_VERIFIED\",\n      `Recipient ${to} does not match the verified customer address for this session.`,\n      \"soft\",\n      \"to\",\n    );\n  }\n\n  return pass(\"EMAIL_RECIPIENT_VERIFIED\");\n};\n\nconst readOnlyToolIsSafe: Rule = (args, ctx) =>\n  pass(\"READ_TOOL_ALLOWED\", `Read tool permitted for agent role ${ctx.agentRole}.`);\n\nconst rulesByTool: Record<ToolName, Rule[]> = {\n  issue_refund: [refundAmountWithinOrder, refundNotAboveAgentLimit],\n  search_orders: [readOnlyToolIsSafe],\n  send_email: [emailOnlyToCustomer],\n};\n\nexport async function evaluateRules(\n  tool: ToolName,\n  args: Record<string, unknown>,\n  ctx: RuleContext,\n): Promise<RuleResult[]> {\n  const rules = rulesByTool[tool] ?? [];\n  const results: RuleResult[] = [];\n\n  for (const rule of rules) {\n    results.push(await rule(args, ctx));\n  }\n\n  return results;\n}\n```\n\nA rule has a stable `ruleId`. That ID is what appears in the audit log, the denial reason, and the dashboard. When a support engineer asks \"why was this refund blocked?\", the answer is a rule ID, not a stack trace or a paraphrase of a prompt.\n\nRules also have severity. A **soft** failure means the agent can plausibly correct itself by gathering more information. A **hard** failure means escalation is required. Getting this distinction wrong is a common source of agent loops: a hard failure returned as a repair prompt invites the model to retry indefinitely.\n\nNow wire the gate into an agent loop. The loop asks a planner for a proposed call, then hands that call to the gate. Only an `allow` decision reaches the executor.\n\nCreate `src/gate/executor.ts`:\n\n``` js\nimport { toolRegistry, type ExecutionContext, type ToolName } from \"../tools/registry.js\";\nimport type { Decision } from \"./decider.js\";\n\nexport interface ExecutionResult {\n  tool: ToolName;\n  output: unknown;\n  durationMs: number;\n}\n\n/**\n * The executor accepts ONLY gate-approved plans. There is no path from a\n * proposed call to execution that bypasses `decide`.\n */\nexport async function executeApproved(\n  decision: Decision,\n  ctx: ExecutionContext,\n): Promise<ExecutionResult> {\n  if (decision.status !== \"allow\") {\n    throw new Error(\n      `Refusing to execute a ${decision.status} decision. Only \"allow\" decisions may execute.`,\n    );\n  }\n\n  const tool = toolRegistry[decision.tool];\n  const started = Date.now();\n  const output = await tool.execute(decision.args as never, ctx);\n\n  return {\n    tool: decision.tool,\n    output,\n    durationMs: Date.now() - started,\n  };\n}\n```\n\nNow the agent loop. Create `src/agent-loop.ts`:\n\n``` js\nimport { decide, type Decision, type DeciderDeps, type ProposedCall } from \"./gate/decider.js\";\nimport { executeApproved } from \"./gate/executor.js\";\nimport { writeAuditRecord } from \"./audit/log.js\";\nimport type { ExecutionContext } from \"./tools/registry.js\";\n\nexport interface Planner {\n  /** Produces the next proposed tool call, or null when the task is complete. */\n  nextProposal: (history: Turn[]) => Promise<ProposedCall | null>;\n}\n\nexport interface Turn {\n  role: \"proposal\" | \"decision\" | \"result\";\n  content: string;\n}\n\nexport interface LoopResult {\n  turns: Turn[];\n  finalOutput?: string;\n  stoppedBecause: \"completed\" | \"max_steps\" | \"denied\";\n}\n\nconst MAX_STEPS = 8;\n\nexport async function runAgent(\n  planner: Planner,\n  ctx: ExecutionContext,\n  deps: DeciderDeps,\n): Promise<LoopResult> {\n  const history: Turn[] = [];\n\n  for (let step = 0; step < MAX_STEPS; step++) {\n    const proposal = await planner.nextProposal(history);\n\n    if (proposal === null) {\n      const finalOutput = history.findLast((t) => t.role === \"result\")?.content ?? \"\";\n      return { turns: history, finalOutput, stoppedBecause: \"completed\" };\n    }\n\n    history.push({\n      role: \"proposal\",\n      content: JSON.stringify(proposal),\n    });\n\n    const decision = await decide(proposal, ctx, deps);\n    history.push({\n      role: \"decision\",\n      content: JSON.stringify(decision),\n    });\n\n    await writeAuditRecord({\n      requestId: ctx.requestId,\n      tool: decision.tool,\n      decision,\n      proposedArgs: proposal.args,\n    });\n\n    if (decision.status === \"deny\") {\n      return { turns: history, stoppedBecause: \"denied\" };\n    }\n\n    if (decision.status === \"repair\") {\n      // The agent sees the structured violation and may try again.\n      continue;\n    }\n\n    const result = await executeApproved(decision, ctx);\n    history.push({\n      role: \"result\",\n      content: JSON.stringify(result.output),\n    });\n  }\n\n  return { turns: history, stoppedBecause: \"max_steps\" };\n}\n```\n\nNote that the loop never interprets a denial as success. A denied action ends the run and surfaces an escalation, which is exactly what you want when an agent tries to issue a refund beyond its authority.\n\nThe difference between a good denial and a bad denial is the information content. A bad denial says \"blocked.\" A good denial says what failed, why, and what to do next.\n\nCreate `src/gate/repair-prompt.ts`:\n\n``` python\nimport type { Decision } from \"./decider.js\";\n\n/**\n * Convert a repair decision into a compact, structured instruction for the planner.\n * The planner sees facts and constraints, not prose negotiation.\n */\nexport function buildRepairInstruction(decision: Decision): string {\n  if (decision.status !== \"repair\") {\n    throw new Error(\"buildRepairInstruction expects a repair decision.\");\n  }\n\n  const lines = [\n    `The proposed call to \\`${decision.tool}\\` was rejected by policy.`,\n    `Reason code: ${decision.reasonCode}`,\n    \"\",\n    \"Violations:\",\n  ];\n\n  for (const v of decision.violations) {\n    const field = v.field ? ` [field: ${v.field}]` : \"\";\n    lines.push(`- ${v.ruleId}${field}: ${v.message}`);\n  }\n\n  lines.push(\n    \"\",\n    \"Do not repeat the same call. Either gather the missing information with an allowed read tool, correct the flagged field, or escalate to a human operator.\",\n  );\n\n  return lines.join(\"\\n\");\n}\n```\n\nTwo safeguards belong here.\n\n**Cap repairs per rule.** Track how many times each `ruleId` has produced a repair in a session. After two or three attempts, escalate. Without this, a model can oscillate between two near-identical calls indefinitely.\n\n**Never let repair widen authority.** A repair instruction must not grant the agent new capabilities. It may only request a different value, a read to obtain a verified value, or escalation.\n\nA denial should also be a first-class outcome in your API, not an exception. Something like:\n\n```\n{\n  \"status\": \"denied\",\n  \"reasonCode\": \"REFUND_EXCEEDS_AGENT_LIMIT\",\n  \"message\": \"Refund of 50000 exceeds this agent's limit of 20000. Escalate to a human operator.\",\n  \"escalationTicket\": \"esc_9f2a\"\n}\n```\n\nReturning a structured denial lets the surrounding application route the case, notify the right team, and keep the customer informed without pretending the task succeeded.\n\nAuditability requires more than logging that something happened. It requires reconstructing *why* a decision was made, with the exact inputs, the exact rule outcomes, and a tamper-evident record.\n\nCreate `src/audit/log.ts`:\n\n``` python\nimport { createHash } from \"node:crypto\";\nimport type { Decision } from \"../gate/decider.js\";\n\nexport interface AuditRecord {\n  requestId: string;\n  tool: string;\n  decision: Decision;\n  proposedArgs: unknown;\n  timestamp: string;\n  /** Hash of the previous record, forming a tamper-evident chain. */\n  prevHash: string;\n  /** Hash of this record's canonical contents. */\n  hash: string;\n}\n\nconst records: AuditRecord[] = [];\n\nfunction canonicalize(value: unknown): string {\n  if (value === null || typeof value !== \"object\") {\n    return JSON.stringify(value) ?? \"null\";\n  }\n  if (Array.isArray(value)) {\n    return `[${value.map(canonicalize).join(\",\")}]`;\n  }\n  const entries = Object.entries(value as Record<string, unknown>)\n    .filter(([, v]) => v !== undefined)\n    .sort(([a], [b]) => a.localeCompare(b));\n  return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalize(v)}`).join(\",\")}}`;\n}\n\nexport async function writeAuditRecord(input: {\n  requestId: string;\n  tool: string;\n  decision: Decision;\n  proposedArgs: unknown;\n}): Promise<AuditRecord> {\n  const prevHash = records.at(-1)?.hash ?? \"GENESIS\";\n  const timestamp = new Date().toISOString();\n\n  const body = {\n    requestId: input.requestId,\n    tool: input.tool,\n    decision: input.decision,\n    proposedArgs: input.proposedArgs,\n    timestamp,\n    prevHash,\n  };\n\n  const hash = createHash(\"sha256\").update(canonicalize(body)).digest(\"hex\");\n  const record: AuditRecord = { ...body, hash };\n\n  records.push(record);\n\n  // In production: append to an append-only store (Postgres, S3 Object Lock,\n  // or a dedicated ledger service) and ship to your SIEM.\n  console.log(`[audit] ${record.requestId} ${record.tool} ${input.decision.status} ${hash.slice(0, 12)}`);\n\n  return record;\n}\n\nexport function getAuditRecords(): readonly AuditRecord[] {\n  return records;\n}\n```\n\nThe hash chain gives you a property that plain logs do not: you can detect modification or deletion of historical records. Recompute the chain over the stored records and compare. If a hash does not match, the log has been altered.\n\nFor production, ship audit records to append-only storage and keep the decision record separate from the full tool arguments if arguments contain PII. Store a redacted or hashed representation of sensitive fields, plus a pointer to the encrypted original under your retention policy.\n\nA useful audit query surface:\n\n| Field | Purpose | \n|---|---|\n| `requestId` | Trace one end-to-end agent run | \n| `tool` | Identify which tool was targeted | \n| `decision.status` | allow / repair / deny | \n| `decision.reasonCode` | Which rule fired | \n| `violations[].ruleId` | Every rule that failed, not just the first | \n| `satisfiedBy` | Which rules explicitly permitted the action | \n| `prevHash` /`hash` | Tamper-evidence chain | \n\nA policy engine without tests is a liability. Because the gate is deterministic, tests are fast and exhaustive. You do not need to mock a model to test whether a refund of $500 is blocked.\n\nCreate `tests/decider.test.ts`:\n\n``` js\nimport { describe, expect, it } from \"vitest\";\nimport { decide, type DeciderDeps } from \"../src/gate/decider.js\";\nimport type { ExecutionContext } from \"../src/tools/registry.js\";\n\nconst deps: DeciderDeps = {\n  async lookupFacts() {\n    return {\n      orders: {\n        \"A-1042\": { total: 4900, currency: \"USD\" },\n        \"B-2001\": { total: 12000, currency: \"EUR\" },\n      },\n    };\n  },\n  async verifyApproval() {\n    return true;\n  },\n};\n\nfunction ctx(overrides: Partial<ExecutionContext> = {}): ExecutionContext {\n  return {\n    requestId: \"req_001\",\n    actorId: \"user_77\",\n    agentRole: \"support_l1\",\n    facts: {\n      customerEmail: \"buyer@example.com\",\n      agentRefundLimit: 20000,\n    },\n    now: new Date(\"2025-01-01T00:00:00Z\"),\n    ...overrides,\n  };\n}\n\ndescribe(\"tool-decider gate\", () => {\n  it(\"denies an unknown tool\", async () => {\n    const decision = await decide({ tool: \"drop_database\", args: {} }, ctx(), deps);\n    expect(decision.status).toBe(\"deny\");\n    expect(decision.reasonCode).toBe(\"UNKNOWN_TOOL\");\n  });\n\n  it(\"repairs a schema violation with a non-integer amount\", async () => {\n    const decision = await decide(\n      {\n        tool: \"issue_refund\",\n        args: {\n          orderId: \"A-1042\",\n          amount: 49.5,\n          currency: \"USD\",\n          reason: \"customer_request\",\n          idempotencyKey: \"idem-key-1234\",\n        },\n      },\n      ctx({ approvalToken: \"tok_abc\" }),\n      deps,\n    );\n    expect(decision.status).toBe(\"repair\");\n    expect(decision.reasonCode).toBe(\"SCHEMA_VIOLATION\");\n  });\n\n  it(\"blocks a refund above the order total\", async () => {\n    const decision = await decide(\n      {\n        tool: \"issue_refund\",\n        args: {\n          orderId: \"A-1042\",\n          amount: 9900,\n          currency: \"USD\",\n          reason: \"customer_request\",\n          idempotencyKey: \"idem-key-1234\",\n        },\n      },\n      ctx({ approvalToken: \"tok_abc\" }),\n      deps,\n    );\n    expect(decision.status).toBe(\"repair\");\n    expect(decision.reasonCode).toBe(\"REFUND_EXCEEDS_ORDER_TOTAL\");\n  });\n\n  it(\"blocks a refund above the agent's authority limit\", async () => {\n    const decision = await decide(\n      {\n        tool: \"issue_refund\",\n        args: {\n          orderId: \"B-2001\",\n          amount: 12000,\n          currency: \"EUR\",\n          reason: \"customer_request\",\n          idempotencyKey: \"idem-key-1234\",\n        },\n      },\n      ctx({ agentRole: \"support_l1\", approvalToken: \"tok_abc\" }),\n      deps,\n    );\n    expect(decision.status).toBe(\"deny\");\n    expect(decision.reasonCode).toBe(\"REFUND_EXCEEDS_AGENT_LIMIT\");\n  });\n\n  it(\"denies a write tool with no approval token\", async () => {\n    const decision = await decide(\n      {\n        tool: \"issue_refund\",\n        args: {\n          orderId: \"A-1042\",\n          amount: 4900,\n          currency: \"USD\",\n          reason: \"customer_request\",\n          idempotencyKey: \"idem-key-1234\",\n        },\n      },\n      ctx(),\n      deps,\n    );\n    expect(decision.status).toBe(\"deny\");\n    expect(decision.reasonCode).toBe(\"HUMAN_APPROVAL_REQUIRED\");\n  });\n\n  it(\"allows a valid, approved refund\", async () => {\n    const decision = await decide(\n      {\n        tool: \"issue_refund\",\n        args: {\n          orderId: \"A-1042\",\n          amount: 4900,\n          currency: \"USD\",\n          reason: \"customer_request\",\n          idempotencyKey: \"idem-key-1234\",\n        },\n      },\n      ctx({ approvalToken: \"tok_abc\" }),\n      deps,\n    );\n    expect(decision.status).toBe(\"allow\");\n    if (decision.status === \"allow\") {\n      expect(decision.args.amount).toBe(4900);\n    }\n  });\n\n  it(\"blocks emailing an unverified recipient\", async () => {\n    const decision = await decide(\n      {\n        tool: \"send_email\",\n        args: {\n          to: \"attacker@evil.test\",\n          subject: \"Your refund\",\n          body: \"Click here\",\n        },\n      },\n      ctx(),\n      deps,\n    );\n    expect(decision.status).toBe(\"repair\");\n    expect(decision.reasonCode).toBe(\"EMAIL_RECIPIENT_NOT_VERIFIED\");\n  });\n});\n```\n\nRun the suite:\n\n```\nnpm test\n```\n\nNow add a test that proves the gate is immune to a class of prompt-injection bluffs. The critical property is that the *model's own claims* cannot become facts. Create `tests/injection.test.ts`:\n\n``` js\nimport { describe, expect, it } from \"vitest\";\nimport { decide, type DeciderDeps } from \"../src/gate/decider.js\";\nimport type { ExecutionContext } from \"../src/tools/registry.js\";\n\nconst deps: DeciderDeps = {\n  // The trusted system knows nothing about this order.\n  async lookupFacts() {\n    return { orders: {} };\n  },\n  async verifyApproval() {\n    return true;\n  },\n};\n\ndescribe(\"model claims cannot become facts\", () => {\n  it(\"ignores a model-supplied orderTotal claim\", async () => {\n    const ctx: ExecutionContext = {\n      requestId: \"req_inj\",\n      actorId: \"user_1\",\n      agentRole: \"support_l1\",\n      facts: { agentRefundLimit: 100_000 },\n      now: new Date(),\n    };\n\n    const decision = await decide(\n      {\n        tool: \"issue_refund\",\n        args: {\n          orderId: \"A-1042\",\n          amount: 999_99,\n          currency: \"USD\",\n          reason: \"customer_request\",\n          idempotencyKey: \"idem-key-1234\",\n          // The model claims the order total is huge. The gate ignores it.\n          orderTotal: 999_999_99,\n          verified: true,\n        },\n      },\n      ctx,\n      deps,\n    );\n\n    expect(decision.status).toBe(\"repair\");\n    expect(decision.reasonCode).toBe(\"ORDER_MUST_EXIST\");\n  });\n});\n```\n\nThis test is the heart of the technique. The model can assert anything in its arguments, but the gate only consults facts it gathered itself. Extra fields are also stripped by Zod's default object parsing, so unverified claims never reach the executor.\n\nThe gate works in the tutorial. Production requires more.\n\nWrap tool invocation in a single exported function that requires a valid `allow` decision. Do not export raw tool executors to agent code. If you use an MCP server or a plugin system, enforce the same gate server-side, because a client-side gate protects only against honest clients.\n\nAn approval token must be scoped to a hash of the tool, arguments, actor, and expiry. Approving \"issue a refund for order A-1042\" must not authorize a different amount. Verify the token signature, expiry, and subject on every use, and burn it after use so it cannot be replayed.\n\nThe schema requires an `idempotencyKey`. Enforce it at the executor and at the downstream API: a duplicate key with different arguments is a conflict and must fail loudly, not silently reuse the first result.\n\nAs rule count grows, move rules into a declarative format (Rego, Cedar, OPA, or a JSON/YAML rule file) and keep the gate's evaluation order fixed. The gate stays deterministic; only the rule definitions become configurable.\n\nRecord the policy version and tool schema version in each audit entry. Without them, you cannot explain why a call allowed in March was denied in June after a rule change.\n\nMaintain a corpus of real agent failures. Each becomes a test asserting the gate blocks it. This turns production incidents into permanent regression protection, and it is the single highest-leverage practice in this whole architecture.\n\nThe gate adds latency to every tool call. Keep it fast: cache facts with short TTLs, avoid network calls inside individual rules, and batch lookups before rule evaluation. If a fact lookup is slow, the model will route around the gate by trying more calls, which is worse than the latency you were trying to avoid.\n\nRules that an LLM generates at runtime are not deterministic and not auditable in the sense you need. If you want model-assisted policy authoring, generate a *proposal* that a human reviews and promotes into a versioned rule file.\n\nA tool-decider gate is one component of a broader control plane. For more on structuring agent systems and the tooling around them, see [Tamiz's Insights](https://tamiz.pro/insights). For practical API integration patterns, [tamiz.pro](https://tamiz.pro) is a useful reference.\n\n**Should the tool-decider gate be a model or a rules engine?**\n\nA rules engine. The entire point is that the decision does not depend on a stochastic model. If you use an LLM to evaluate policy, you have moved the bluff rather than removed it. Models may *assist* in authoring rules, but the runtime path must be deterministic.\n\n**How do I handle tools with many valid argument shapes?**\n\nUse discriminated unions in the schema and branch the rules on the discriminator. Keep each branch's rules small and independently testable. If a tool has more than a handful of materially different modes, split it into multiple tools; smaller tools produce smaller policy surfaces.\n\n**Does this replace prompt engineering and output-format constraints?**\n\nNo. Structured output and clear tool descriptions still matter, because they reduce the number of invalid proposals the model generates. But they are *efficiency* measures. The gate is the *correctness* boundary. Even a perfectly formatted call can be semantically wrong, and only the gate catches that.\n\n**How do I avoid the agent getting stuck in repair loops?**\n\nTrack repair attempts per `ruleId` within a session, cap them at two or three, and escalate to a human on exhaustion. Also make repair messages actionable: name the field, state the constraint, and suggest the next allowed action. A repair that only says \"invalid\" gives the model nothing to converge on.\n\n**What is the minimum viable version of this pattern?**\n\nThree pieces: a strict schema per tool, one rule that checks arguments against trusted facts, and an executor that refuses anything without an `allow` decision. That alone eliminates the most common class of agent bluffs. Add approval tokens and audit chaining next, then expand the rule set as you observe real failures.", "url": "https://wpnews.pro/news/stop-ai-agents-acting-on-bluffs-building-a-deterministic-tool-decider-gate", "canonical_source": "https://dev.to/tamizuddin/stop-ai-agents-acting-on-bluffs-building-a-deterministic-tool-decider-gate-2i8i", "published_at": "2026-11-26 18:05:18+00:00", "updated_at": "2026-11-26 18:15:38.190052+00:00", "lang": "en", "topics": ["ai-agents", "ai-safety", "ai-tools", "developer-tools"], "entities": ["tamiz.pro", "TypeScript", "Zod"], "also_reported_by": [], "takeaway": "Route every side-effecting tool call through a deterministic gate that returns structured ALLOW, REPAIR or DENY decisions with reason codes, so the executor never re-derives policy and the model cannot construct an execution plan directly.", "recommendation": {"advice": "Put a deterministic, code-based gate between the agent and every side-effecting tool that validates structured calls against explicit rules and returns structured denials, and let the executor trust only the gate's output.", "playbook": "agent-security", "playbook_url": "https://wpnews.pro/playbooks/agent-security"}, "alternates": {"html": "https://wpnews.pro/news/stop-ai-agents-acting-on-bluffs-building-a-deterministic-tool-decider-gate", "markdown": "https://wpnews.pro/news/stop-ai-agents-acting-on-bluffs-building-a-deterministic-tool-decider-gate.md", "text": "https://wpnews.pro/news/stop-ai-agents-acting-on-bluffs-building-a-deterministic-tool-decider-gate.txt", "jsonld": "https://wpnews.pro/news/stop-ai-agents-acting-on-bluffs-building-a-deterministic-tool-decider-gate.jsonld"}}