# Tools (/docs/tools)



> **Tools are a thematic island.** Not one of the [six cluster
> triplets](/docs/concept-clusters#the-six-cluster-triplets) —
> tooling is one surface end to end (contract + dispatch +
> result-handling), not a three-concept cluster. See [What lives
> outside the cluster pattern](/docs/concept-clusters#what-lives-outside-the-cluster-pattern).

> **The standalone `@pleach/tools` package is deprecated — folded into `@pleach/core`.**
> The tool-definition surface described on this page (`defineTool` / `UnifiedToolDefinition`,
> the queryable `toolRegistry`, schema + hints helpers) ships inside `@pleach/core&#x60; and
> is reachable at &#x2A;*`@pleach/core/tools`** (and `@pleach/core/tools/unified`). The concept
> and API below are unchanged. `@pleach/tools` is now a re-export shim: its entry point
> is `export * from "@pleach/core/tools/unified"`, so `createUnifiedTool`, `toolRegistry`,
> `UnifiedToolRegistry`, `TOOL_CATEGORIES` and the schema helpers resolve identically from
> either path. It ships no catalog of its own and does not export `defineTool`. Import the
> tool contracts from `@pleach/core/tools`; new code should not depend on `@pleach/tools`.

Hand tools for the lattice — typed, scoped, batched, returned to
the shed at turn's end. A tool is a named function the LLM can call.
`@pleach/core` ships the contract (`defineTool`); the runtime handles
dispatch, streaming partial arguments, execution, and writing the
result back into the conversation. Input and output are Zod-validated; an invalid call
fails before dispatch with a structured error from the
[1xxx range](/docs/error-codes). See [Stream events](/docs/stream-events)
for the per-tool lifecycle on the wire.

```typescript
import { defineTool } from "@pleach/core";
import type { ToolDefinition, ToolContext } from "@pleach/core";
```

## `defineTool` [#definetool]

Identity at runtime; the type parameters give callers an inferred
`ToolDefinition<TInput, TOutput>` without ceremony.

```typescript
// lib/tools/searchCorpus.ts
import { z } from "zod";
import { defineTool } from "@pleach/core";

export const searchCorpus = defineTool({
  name: "search_corpus",
  description: "Free-text search over the host corpus.",
  inputSchema: z.object({
    query: z.string().min(1),
    limit: z.number().int().min(1).max(50).default(10),
  }),
  outputSchema: z.object({
    results: z.array(z.object({
      id:    z.string(),
      title: z.string(),
      year:  z.number().int(),
    })),
  }),
  async execute(input, ctx) {
    const res = await fetch(
      `${process.env.CORPUS_URL}/search?q=${encodeURIComponent(input.query)}`,
      { signal: ctx.signal },
    );
    const data = await res.json();
    return { results: data.results.slice(0, input.limit) };
  },
});
```

### Required fields [#required-fields]

| Field         | Type                               | Purpose                                                             |
| ------------- | ---------------------------------- | ------------------------------------------------------------------- |
| `name`        | `string`                           | Unique identifier; what the LLM emits in `tool_calls[].name`        |
| `description` | `string`                           | What the tool does — the LLM reads this to decide when to call it   |
| `inputSchema` | `ZodType<TInput>`                  | Validated before `execute` runs; invalid args throw before dispatch |
| `execute`     | `(input, ctx) => Promise<TOutput>` | The implementation                                                  |

### Optional fields [#optional-fields]

| Field          | Type               | Purpose                                                                  |
| -------------- | ------------------ | ------------------------------------------------------------------------ |
| `outputSchema` | `ZodType<TOutput>` | Validates the return; failures surface as `tool.failed` with code `1002` |

`safetyTier` is **not** a `defineTool` field — it lives on the
richer registry-level tool shape. See [`safetyTier`](#safetytier)
below.

## `safetyTier` [#safetytier]

A policy marker the runtime reads when a host-supplied detector flags
a tool argument as fabricated (an argument value with no provenance
in the turn's prior tool results). It is **not** part of the basic
`defineTool` contract — `ToolDefinition` carries only
`name`/`description`/`inputSchema`/`outputSchema`/`execute`, so
passing `safetyTier` to `defineTool({ … })` is a TypeScript
excess-property error. It is a field of the richer
`UnifiedToolDefinition` shape, set through `createUnifiedTool` (see
[Registering tools](#registering-tools-with-a-session) below).

Three values, three destinations:

| Value        | Destination                                                                                                                | User can override? |
| ------------ | -------------------------------------------------------------------------------------------------------------------------- | ------------------ |
| `"critical"` | A hard-halt pipeline stage short-circuits dispatch with `_recoverable: false`. The operator's pre-committed safety policy. | No                 |
| `"standard"` | The `InterruptApprovalCard` surfaces with a ground-truth panel; the user can accept, edit, or reject.                      | Yes                |
| `"advisory"` | Probe-only — the detector still fires for observability; no halt and no card.                                              | N/A                |

Absent on a tool that the host's detector doesn't guard, the field
is a no-op. Absent on a tool the host's detector *does* guard, the
runtime treats it as `"standard"`.

The field lives on the registry-level `UnifiedToolDefinition` shape
(reached through `@pleach/core/tools`), not on the basic
`ToolDefinition` returned by `defineTool`. Set it with
`createUnifiedTool` and register the result:

```typescript
// lib/tools/dangerousLookup.ts
import { createUnifiedTool, toolRegistry } from "@pleach/core/tools";

export const dangerousLookup = createUnifiedTool({
  id: "dangerous_lookup",
  name: "dangerous_lookup",
  displayName: "Dangerous Lookup",
  category: "analysis",
  schemaKey: "DangerousLookupInput",
  safetyTier: "critical",                         // hard-halt routing
  async execute(input, ctx) { /* ... */ },
});

toolRegistry.register(dangerousLookup);
```

Hosts contribute the detector that decides what "fabricated" means
for their domain — see
[Fabrication detection](/docs/fabrication-detection#host-supplied-tool-argument-fabrication-detectors)
for the detector contract and the routing rules. The runtime
enforces an invariant: every tool tagged `"critical"` must be
reachable by the host's detector. CI fails when coverage is missing,
so a `"critical"` tool can't silently bypass the hard-halt.

## `ToolContext` [#toolcontext]

Passed as the second arg to `execute`. Intentionally minimal — the
contract stays portable across hosts.

| Field        | Type           | Use                                                  |
| ------------ | -------------- | ---------------------------------------------------- |
| `toolCallId` | `string`       | Correlate audit + event log rows                     |
| `signal`     | `AbortSignal?` | Per-turn cancel — propagate into every fetch / spawn |

Tools that ignore `signal` keep burning resources after the user
hits stop. Always thread it through.

```typescript
async execute(input, ctx) {
  const child = spawn("expensive-cli", [input.q], { signal: ctx.signal });
  // ...
}
```

## Registering tools with a session [#registering-tools-with-a-session]

Pass tool names to `createSession`:

```typescript
const session = await runtime.createSession({
  tools: { enabled: ["search_corpus", "calculator"] },
});
```

The runtime looks the names up in the active tool registry. Wire
the registry at runtime construction either through a plugin
(`contributeTools` is the standard path) or via the legacy
`setOrchestratorRegistry` shim for hosts mid-migration:

```typescript
import { setOrchestratorRegistry } from "@pleach/core/tools";

const tools = [searchCorpus, calculator];
setOrchestratorRegistry({
  getToolDefinitions: () => tools,
  get: (name) => tools.find((t) => t.name === name),
  has: (name) => tools.some((t) => t.name === name),
  size: tools.length,
});
```

For the common cases (math, datetime, filesystem, HTTP, search), reach
for [`@pleach/core/base-tools`](/docs/base-tools); write `defineTool`
calls for your domain-specific tools.

## The `defineTool` → `ToolDefinitionLite` bridge [#the-definetool--tooldefinitionlite-bridge]

`defineTool` and the agent's `tools` arm speak different contracts.
`defineTool` returns a `ToolDefinition` (Zod schemas, typed
`execute(input, ctx)`); `createPleachAgent({ tools })` and the
plugin tool surface take `ToolDefinitionLite[]` (raw JSON-schema
`parameters`, `execute(args, ctx?)`). The bridge converts one into
the other:

```typescript
import { toToolDefinitionLite, isToolDefinition } from "@pleach/core/tools";
import type { AnyToolDefinition } from "@pleach/core/tools";

const lite = toToolDefinitionLite(searchCorpus);
```

All three exports are also on the root `@pleach/core` barrel.

`createPleachAgent` applies the bridge automatically — a
`defineTool` product passed straight into `tools: [...]` works
without ceremony. The exports exist for hand-wiring: a host that
builds its own registry or plugin tool list converts explicitly.
`isToolDefinition` is the structural guard (Zod `inputSchema` +
`execute`, no `parameters`); `AnyToolDefinition` is the alias for
"some `defineTool` product regardless of its generics" — a
concretely-typed `ToolDefinition<In, Out>` is not assignable to
`ToolDefinition<unknown, unknown>`, so accept the alias instead.

What the bridged `execute` guarantees:

* Input is parsed through the Zod `inputSchema` before the tool
  body runs — a malformed argument object rejects with the
  `ZodError` instead of reaching the tool.
* Output is validated through `outputSchema` when the definition
  declared one.
* The advertised `parameters` block is derived from the Zod schema
  via native JSON-schema conversion where the installed Zod
  supports it, degrading to a permissive `{ type: "object" }`
  otherwise. The degradation is advisory-only — the Zod parse
  inside the wrapped `execute` still guards every input.

### The optional execute context [#the-optional-execute-context]

`ToolDefinitionLite.execute` accepts an optional second parameter,
`ctx?: ToolLiteExecuteContext` — `{ toolCallId?, signal? }`. The
widening is additive: a one-parameter implementation stays
assignable. When the invoker supplies a context, `toolCallId` is
the canonical `ToolCall.id` and `signal` is the per-turn abort
signal — a set `ctx.signal` always means a real turn-abort signal
is behind it; the bridge never fabricates one.

## Validating arguments before dispatch [#validating-arguments-before-dispatch]

`useToolValidation(name)` validates input shape against the tool's
Zod schema on the client — useful for schema-driven forms that
build a tool call manually:

```tsx
import { useToolValidation } from "@pleach/core/react";

function SearchForm() {
  const [args, setArgs] = useState({ query: "", limit: 10 });
  const result = useToolValidation({
    id: "call_1",
    name: "search_corpus",
    arguments: args,
    status: "pending",
  });

  return (
    <form onSubmit={(e) => {
      e.preventDefault();
      if (result?.valid) submitToolCall("search_corpus", args);
    }}>
      <input value={args.query} onChange={(e) => setArgs({ ...args, query: (e.target as unknown as { value: string }).value })} />
      {result && !result.valid && <ErrorList errors={result.errors} />}
    </form>
  );
}
```

## Batching [#batching]

`ToolBatchExecutor` groups tool calls the runtime decides can fire
concurrently. The batching strategy per tool defaults to inferred
from the schema; override it explicitly when the inference is
wrong:

```typescript
// lib/tools/fetchDocument.ts
import { defineTool } from "@pleach/core";

export const fetchDocument = defineTool({
  name: "fetch_document",
  description: "Fetch full text for one document id.",
  inputSchema: z.object({ id: z.string() }),
  async execute(input, ctx) { /* ... */ },
});

// `batching` is NOT a `defineTool` field. Override the inferred strategy
// from a plugin via the `contributeBatchingHints` hook (routed through
// `_raw` on `definePleachPlugin`), keyed by tool name:
//   contributeBatchingHints: () => [
//     { toolName: "fetch_document", strategy: "parallel", maxConcurrency: 5 },
//   ]
```

Available strategies:

| Strategy   | Concurrency                                            | Use case                                        |
| ---------- | ------------------------------------------------------ | ----------------------------------------------- |
| `serial`   | 1                                                      | Writes, side-effecting tools, dependency chains |
| `parallel` | Up to `BatchingConfig.maxConcurrency`                  | Independent reads (database lookups, API calls) |
| `chunked`  | Grouped by key — parallel across groups, serial within | Per-resource serialization (per-user, per-file) |

`inferBatchingStrategy(toolDef)` reads strategy hints from the
definition; `getBatchingStrategyForTool(name)` resolves through
the active registry.

Use `Semaphore` from `@pleach/core` if you need a hand-rolled
concurrency limit inside `execute`:

```typescript
import { Semaphore } from "@pleach/core";

const limit = new Semaphore(4);
async execute(input, ctx) {
  return limit.run(async () => fetchOneThing(input, ctx));
}
```

## Weak-schema tool budget (deprecated) [#weak-schema-tool-budget-deprecated]

`weakToolSchemaBudgetPlugin` (`@pleach/core/prompts`) and
`createWeakToolSchemaPredicate` (`@pleach/core/modelfamily`) are
deprecated. The runtime now gives every model the same full-schema
promotion budget, repetition cap and synthesis request, and nothing in
it reads the weak-schema predicate.

Both still compile and still work if you install them yourself. The
plugin injects a batch-cap directive for the families it flags
(`google`, `deepseek` and `moonshot` by default), and the defaults stay
`maxBatch: 4` and `maxSameTool: 2`. New code shouldn't add them.

## Condensing a large tool set: `condenseTools` [#condensing-a-large-tool-set-condensetools]

> **Deprecated default.** The condenser behind `condenseTools`
> (`condenseSchemas`) is deprecated. To migrate, budget the offer
> yourself with the context-aware [`getTools(ctx)`
> hook](#budgeting-the-offer-yourself-gettoolsctx). `condenseTools`
> stays on by default until you migrate, so existing routes don't
> change.

`condenseTools` trims the `tools[]` array itself when the set is
large enough to threaten the context window. It's an option on the
packaged [`createPleachRoute`](/docs/runtime-construction) surface,
and on `createPleachRuntime` when you pass a `provider`.

```typescript
createPleachRoute({
  // …
  condenseTools: { threshold: 40 },   // condense once the set crosses 40 tools
});
```

Below the threshold the option is inert — every turn is
byte-identical to the uncondensed path. Above it, the generic default
keeps `maxSchemaTools` full schemas (default 1) and surfaces every
other tool as a one-line name in the condensed system-prompt text.
That's context-window-safe, but a dropped schema can't be pulled back
on its own — so the condensed set is only *usable* with a discovery
mechanism.

That mechanism is the **discovery meta-tool**. Supply a curated
policy and register it:

```typescript
condenseTools: {
  threshold: 40,
  config: {
    metaToolName: "discover_tools",   // the model calls this to pull a dropped schema back
    intentPriorityMap: {              // Record<string, readonly string[]>
      search: ["web_search", "vector_query"],  // keep full schemas when the turn's intent is "search"
      write:  ["fs_write", "patch_file"],
    },
  },
};
```

`intentPriorityMap` is `Record<string, readonly string[]>` — an intent
name mapped to the tool names that keep their full schema when that
intent is active. Tools not listed for the active intent are condensed
to a one-line name and recovered on demand through the meta-tool.

With the meta-tool registered, the model calls it by name to
re-request a full schema it needs mid-turn. Without it, a real 40+-
tool consumer should either supply the `config` or pass
`condenseTools: false` to keep every full schema. Pass a bare
`{ threshold }` to retune, or `false` to disable outright.

`createPleachRoute` wires the meta-tool for you. Hand-rolling a
server instead? Build it directly with `createDiscoverToolsTool`:

```typescript
import { createDiscoverToolsTool, DISCOVER_TOOLS_TOOL_NAME } from "@pleach/core";

// DISCOVER_TOOLS_TOOL_NAME === "discover_tools"
const discover = createDiscoverToolsTool(() => runtime.resolvedTools());
```

It takes a getter that returns the current resolved tool set, so the
model can pull a dropped schema back by exact name or free-text query
against a live snapshot rather than a stale copy.

### Budgeting the offer yourself: `getTools(ctx)` [#budgeting-the-offer-yourself-gettoolsctx]

This hook replaces the deprecated condenser. Pass `getTools` to
`createPleachRoute`, or to `createPleachRuntime` with a `provider`. It
runs once per tool resolution and returns the tools the model is
offered for that request:

```typescript
import { createPleachRoute } from "@pleach/core/quickstart";
import type { ToolOfferContext } from "@pleach/core";

const MAX_TOOLS = 40; // your own budget

createPleachRoute({
  // …
  getTools: (ctx: ToolOfferContext) => {
    const all = ctx.defaultTools ?? [];
    // Always keep what the plan still needs, the plugins' floor, and
    // anything the session already expanded.
    const keep = new Set([
      ...(ctx.openPlanStepToolNames ?? []),
      ...(ctx.keepToolNames ?? []),
      ...(ctx.sessionExpandedNames ?? []),
    ]);
    const kept = all.filter((t) => keep.has(t.name));
    const rest = all.filter((t) => !keep.has(t.name));
    return [...kept, ...rest.slice(0, Math.max(0, MAX_TOOLS - kept.length))];
  },
});
```

`ToolOfferContext` (and its tool shape, `ToolOfferEntry`) is exported
from `@pleach/core`, `@pleach/core/runtime` and `@pleach/core/quickstart`.

`ctx` carries:

| Field                      | What it holds                                                                                                   |
| -------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `modelId`                  | The model the request resolved                                                                                  |
| `allowedToolNames`         | The request allow-list, when one is set                                                                         |
| `deniedToolNames`          | The request deny set                                                                                            |
| `sessionExpandedNames`     | Names the session already expanded                                                                              |
| `searchActivatedNames`     | Names `tool_search` activated this turn                                                                         |
| `openPlanStepToolNames`    | The tool of every plan step still to run (at most 20; left out when there are none)                             |
| `keepToolNames`            | Tools the plugins ask to keep offered (`contributeFloorTools`): the floor plus every family's tools, as one set |
| `userMessage`, `messageId` | The request's message and its id                                                                                |
| `depth`, `isContinuation`  | The request's recursion depth, and whether it is an auto-continuation                                           |
| `defaultTools`             | What would be offered without the hook: the plugin tools, plus the host `toolCatalog` on the runtime            |

A field the request didn't carry is left out, not set to a default.

Return a selection of `ctx.defaultTools`. The runtime then applies the
request's tool policy to what you return: a denied tool is dropped,
and when an allow-list is set, anything outside it is dropped too. So
a denied tool is never offered, even if you return it. What's left is
the turn's whole dispatch catalog: if the model calls a tool you left
out, the call is refused.

The policy filter compares raw tool names, while dispatch checks the
policy after resolving aliases. Use canonical names in your policy and
in what `getTools` returns.

How `getTools` and `condenseTools` interact:

* **`getTools` only:** condensation turns off and your selection goes
  on the wire as is. No `discover_tools` is added.
* **Both set:** pass `condenseTools: true` (or `{ threshold, config }`)
  to also condense your selection.
* **`condenseTools: false`:** condensation is always off.

> ⚠ &#x2A;*The planner still sees every tool.** The plan generator, the
> plan parser and the runtime's registered tool names are built from
> the full plugin catalog, not from your return value. If a plan names
> a tool you withheld, the plan-coverage check holds the turn and
> retries, and each retry is a billed model call. Keeping
> `ctx.openPlanStepToolNames` in what you return reduces this, but
> doesn't close it: the list holds at most 20 names, it is empty for
> sub-agents, and a plan produced after a resolution (the async
> planner) is only seen on the next re-resolution.

Limits:

* Sub-agents don't call the hook. A child is offered its own tool set.
* `new SessionRuntime({ provider })` has neither `getTools` nor
  `condenseTools`. Use `createPleachRuntime` or `installStandardLoaders`.

`installStandardLoaders({ getTools })` receives the same `ctx`, except
`defaultTools`, and applies the same policy filter. At that layer
`condenseTools` is opt-in, as it always was. A zero-argument `getTools`
keeps working.

## Tool policy [#tool-policy]

A tool outside the runtime's policy is never offered and never
dispatched. A runtime that can't confirm the policy is enforced
refuses the adapter instead of running unrestricted.

The policy is a per-runtime allow / deny list over tool names,
set once on `SessionRuntimeConfig.toolPolicy`. Two runtimes in the
same process keep independent policies; nothing is module-level.

### Config shape [#config-shape]

```typescript
import { SessionRuntime } from "@pleach/core";

const runtime = new SessionRuntime({
  // …
  toolPolicy: {
    allow: new Set(["search_corpus", "calculator", "fs_read"]),
    deny: new Set(["fs_write"]),
    onWithheld: ({ name, reason }) => log.info("tool withheld", { name, reason }),
  },
});
```

| Field        | Type                  | Meaning                                                                                                                        |
| ------------ | --------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `allow`      | `ReadonlySet<string>` | When present, only these names are offered or run. An **empty** set means nothing runs.                                        |
| `deny`       | `ReadonlySet<string>` | Never offered, never run. Deny beats allow.                                                                                    |
| `onWithheld` | `(entry) => void`     | Called with `{ name, reason }` for each withheld tool; `reason` is `"excluded"` (denied) or `"not_allowed"` (outside `allow`). |

The policy only narrows. It intersects with any allow-list another
layer already applies and unions with any deny-list, so it can't
admit a tool a tier, guest rule, or access policy refuses. Names are
opaque to core: canonicalise aliases before you build the sets.
Omit `toolPolicy` and the runtime behaves exactly as before.

### The adapter contract [#the-adapter-contract]

Enforcement belongs to the embedder. Core composes the sets and hands
them to your `AgentAdapter` through one optional method:

```typescript
applyToolRestriction?(slice: ToolRestrictionSlice): boolean
```

The adapter must narrow, never widen, what it already enforces, and
return `true` only once the restriction holds for both offer and
execution. `mergeToolPolicyIntoConfig` computes the merged
`allowedToolNames` / `deniedToolNames` for you:

```typescript
import type { AgentAdapter } from "@pleach/core/adapters";
import { mergeToolPolicyIntoConfig, type ToolRestrictionSlice } from "@pleach/core/runtime";

class MyAdapter implements AgentAdapter {
  private config: { allowedToolNames?: Set<string>; deniedToolNames?: Set<string> } = {};

  applyToolRestriction(slice: ToolRestrictionSlice): boolean {
    this.config = { ...this.config, ...mergeToolPolicyIntoConfig(this.config, slice) };
    return true; // only once your offer + dispatch paths read this.config
  }

  getClient() {
    return { /* … */ getConfig: () => this.config };
  }
  // …the rest of AgentAdapter
}

runtime.adapter.set(new MyAdapter());
```

The runtime then reads the result back through
`getClient().getConfig()` and checks it with
`findToolPolicyViolation`. Every denied name must appear in
`deniedToolNames`; with an `allow` set, `allowedToolNames` must exist
and admit nothing outside it.

### Fail-closed: `ToolPolicyNotEnforcedError` [#fail-closed-toolpolicynotenforcederror]

With an active policy, the runtime throws `ToolPolicyNotEnforcedError`
and emits the `[ToolPolicy:unenforced]` probe when the adapter:

* has no `applyToolRestriction`,
* returns `false` or throws from it, or
* reads back a gap (`deny "x" not applied`, `allow-list not applied`,
  `allow-list admits "x"`).

The check runs **before** the adapter attaches, at construction or at
`runtime.adapter.set()`. A refused adapter is never attached, so no
turn runs on it. Core ships no adapter that implements the method —
it lives with your provider wiring.

### Sub-agents inherit a ceiling [#sub-agents-inherit-a-ceiling]

A spawned sub-agent's tools go through `narrowChildToolSets`. The
child's allow-list is the intersection with the parent's; its
deny-list is the union. A child spec of `"inherit"` takes the parent's
allow-list as is.

The root runtime's policy is the ceiling for every descendant. A child
can't re-add a tool its parent lacks — including the pull tools
(`skill_search`, `recall_facts`, `todo_read`) a child normally gets
with an explicit `tools` list.

### One denied set, every call site [#one-denied-set-every-call-site]

* **Planner and fabrication guard.** Both read `effectiveDeniedTools`:
  the guest-denied set (guest sessions only) unioned with the policy's
  `deny`. They can't disagree about what's unavailable.
* **Plan steps.** Generated plans drop any step whose `tool` is
  withheld, strip withheld names from `alternativeTools` /
  `expectedTools`, and prune `dependsOn` edges into dropped steps. The
  drop is recorded on `[PlanToolRestriction:steps-dropped]`.
* **Continuation and resumed plans.** A tool the session withholds is
  never counted as still owed: the continuation decision, the
  self-debug escalation and the anchor's tool-substitution notice all
  subtract withheld names first. A plan restored on resume is
  re-filtered against the current restriction before it is used, so a
  tool withheld after the plan was written doesn't come back.
* **Short-circuit tools.** Handlers that answer without the host
  pipeline check `refuseToolCallByRestriction` first: request deny,
  then the allow-list, then the session rule. A refusal is a soft row
  (`TOOL_EXCLUDED_BY_REQUEST`, `TOOL_NOT_ALLOWED_BY_REQUEST`,
  `TOOL_DENIED_FOR_SESSION`) the model can recover from in the same
  turn.
* **The offered set.** When a turn declares what it offered, a call to
  any other name is refused as `not_offered` before it runs, and that
  includes short-circuit tools that belong to a catalog (memory, plans,
  `session_lineage`). Only build-state short-circuit tools skip the
  check, because they answer from the build's own state and are in no
  offered catalog: `update_plan`, `get_data`, `recall_result`,
  `create_skill` and the async-task tools. A host adds its own with
  `registerBuildStateShortCircuitTool(name)`, which today ships only on
  the unstable `@pleach/core/internal/graph/shortCircuit` path (see
  [subpath exports](/docs/subpath-exports)); register only names no
  catalog offers. With no offered set declared, nothing changes.

### Per-session allow rule: `sessionToolAllowed` [#per-session-allow-rule-sessiontoolallowed]

`SessionRuntimeConfig.sessionToolAllowed` is a factory that returns a
`(name) => boolean` predicate — for example, a guest-mode allow rule.
It feeds `ToolCallRestriction.sessionAllowed`. A name the predicate
doesn't admit is refused as `session_denied`, so an undeclared tool
fails closed rather than slipping past a denylist.

The factory runs once per restriction read. A factory that throws or
returns a non-function, or a predicate that throws, still refuses every
name, but as `session_predicate_error`. That refusal isn't final and can
clear once the rule recovers.

Only a real deny is final. It reads `session_denied` and carries
`_access_refused: true` on the result, which tells plan reconciliation
to move the step to an alternative instead of retrying the same tool.

Your own tools can raise the same signal. Set `_access_refused: true` on
a result that refuses because of who is asking, such as a plan or role
check, not because of the arguments. Leave it off a refusal that a
corrected retry can clear.

```typescript
import { ACCESS_REFUSED_KEY, isAccessRefused } from "@pleach/core/graph/predicates/accessRefusal";

// In a tool: refuse for this caller, finally.
return { success: false, error: "Your plan doesn't include exports.", [ACCESS_REFUSED_KEY]: true };

// In a guard or report: read it at the top level or under `.data`.
isAccessRefused(result); // true
```

```typescript
const runtime = new SessionRuntime({
  // …
  sessionToolAllowed: () => {
    const allowed = buildGuestAllowSet(); // your rule
    return (name) => allowed.has(name);
  },
});
```

The helpers — `mergeToolPolicyIntoConfig`, `findToolPolicyViolation`,
`isToolPolicyActive`, `narrowChildToolSets`, `effectiveDeniedTools`,
`refuseToolCallByRestriction`, `ToolPolicyNotEnforcedError` — and the
`SessionToolPolicy` / `ToolRestrictionSlice` / `ToolCallRestriction`
types export from `@pleach/core/runtime`.

## Truncated tool-call arguments [#truncated-tool-call-arguments]

A tool call whose arguments arrive cut off is refused, not run. The model gets a failed result with `_error_code: "TRUNCATED_TOOL_ARGS"`. [Refused truncated tool calls](/docs/error-codes#refused-truncated-tool-calls) covers the rule and the `_args_truncated_by` values.

To keep a record, set `truncatedToolCallAudit` on `SessionRuntimeConfig`. Each refusal inside a turn then writes one `guard.decision` row with `reason: "TRUNCATED_TOOL_ARGS"`. The row holds:

* the call id and tool name, each cut to 128 characters;
* how the arguments ended, when the parser named it;
* the argument names the call had started, at most 32;
* the first 2 KB of the argument text, with its size and whether it was cut;
* `source`, which is `"core"` only when core's own argument parser provably built the refused arguments. `"unverified"` means the origin is unproven, not that the arguments were forged.

The setting is an object with one optional field, `onRefused`. It receives the chat id, the actor id when the host named one, the call id, the tool name, the argument names and the full, uncapped argument text. It runs after the row is written. It can't change the refusal, and an error it throws is ignored. Without the setting, nothing is recorded.

```typescript
import type { TruncatedToolCallAuditConfig } from "@pleach/core/tools";

const truncatedToolCallAudit: TruncatedToolCallAuditConfig = {
  onRefused: ({ toolName, argKeys }) => {
    metrics.increment("tool_call_truncated", { toolName, argKeys: argKeys.length });
  },
};
```

A turn writes at most 256 of these rows. The first refusal past the cap writes one more row that carries only the cap and `dropped_at_least: 1`. Later refusals are counted in memory, so that figure is a lower bound, and they don't reach `onRefused`.

The tool name, argument text and argument names are in the scrub allowlist for `guard.decision`. A scrubber chain redacts them and payload encryption seals them.

## Lifecycle in the stream [#lifecycle-in-the-stream]

A successful tool call produces three stream events:

```text
tool.delta     { toolCallId, delta }       // streaming argument assembly, before dispatch
tool.started   { toolCall: { id, name, args } }  // arguments complete, tool dispatched
tool.completed { toolCall, result }
```

A call that ran and failed usually still ends in `tool.completed`,
with `toolCall.status` set to `"failed"` (or `"error"`) and the error
on `toolCall.error` or `result.error`. A tool that throws or rejects
may end in `tool.failed` instead:

```text
tool.failed    { toolCall, error }
```

A call whose arguments streamed but that never starts gets
`tool.input.discarded { toolCallId, reason }` and no other event.

See [Stream events](/docs/stream-events) for the full payload
shapes.

## Where to go next [#where-to-go-next]

<Cards>
  <Card title="Base tools" href="/docs/base-tools" description="Ready-made tools in `@pleach/core/base-tools` — math, datetime, scratchpad, unit_convert, text_search, json_query, memory, plus capability-gated fs, code, web and todo tools." />

  <Card title="Providers" href="/docs/providers" description="How tools get serialized for the underlying LLM SDK." />

  <Card title="Stream events" href="/docs/stream-events" description="`tool.delta` / `tool.started` / `tool.completed` / `tool.failed`." />

  <Card title="Interrupts" href="/docs/interrupts" description="Pause for human approval before a tool fires." />

  <Card title="Error codes" href="/docs/error-codes" description="The 1xxx tool-error range." />
</Cards>
