# @pleach/base-tools (/docs/base-tools)



> **⚠️ Deprecated — folded into `@pleach/core`.** These tools now ship inside
> `@pleach/core&#x60; at the opt-in subpath &#x2A;*`@pleach/core/base-tools`** (with the same
> per-tool subpaths). Import from there — zero extra install for `@pleach/core`
> consumers, identical surface. The standalone `@pleach/base-tools` package is a thin
> re-export shim, retained only for back-compat, and is no longer maintained. New
> projects should not add it. The tools themselves are not going away — only the extra
> package is.

Starter implements for the gardener — shears, watering can,
scratchpad, fetcher. `@pleach/base-tools` is the batteries-included
bundle of domain-agnostic tools almost every agent ends up needing.
Zero-config: arithmetic, time, a per-session scratchpad, unit
conversion, in-text search, JSON extraction, and cross-session memory.
Opt-in and injected: web search, web-page reading, code execution,
human-in-the-loop, a sandboxed filesystem, and event-log recall. It
builds on the [tool contracts](/docs/tools) in `@pleach/core/tools`
(`defineTool`, `UnifiedToolDefinition`); this package ships ready-made
tools that drop straight into a `SessionRuntime`. The standalone
package is deprecated: the same code ships at `@pleach/core/base-tools`.

The tools split two ways. The zero-config set works the moment you
register the plugin — it needs no keys, no network, no host runtime. The
opt-in set follows one rule: &#x2A;*refuse by default, inject the
capability.** A tool that reaches the network, runs code, or opens the
filesystem stays off until the host hands it an allowlist, a sandbox
runner, or an adapter. The package ships the contract and the guard;
your trusted runtime supplies the teeth.

Hosts that hand-roll their toolbelt don't need this package. Hosts that
want a sane default surface — without writing seven small Zod schemas
to wrap `Date.now()` — install it.

**Package:** `@pleach/base-tools` ([not on npm yet](</docs/install#not-on-npm-yet>)) · **Source:** [github.com/pleachhq/base-tools](<https://www.getpleach.com/docs/base-tools>)

<Callout title="These tools now ship inside @pleach/core">
  The base tools have been hoisted into [`@pleach/core`](/docs/core&#x29; at
  the opt-in subpath &#x2A;*`@pleach/core/base-tools`**. If you already depend
  on `@pleach/core`, you can import them with zero extra install:

  ```typescript
  import { baseToolsPlugin } from "@pleach/core/base-tools";
  ```

  The subpath is opt-in (it is **not** part of the top-level `@pleach/core`
  barrel), so it stays tree-shakeable. The standalone `@pleach/base-tools`
  package below remains as a deprecated re-export shim over that
  subpath — same symbols, two import paths.
</Callout>

## Install [#install]

The tools ship with `@pleach/core` already (import from
`@pleach/core/base-tools`). Install the standalone shim only if you want
to depend on the SKU by name:

```bash
npm install @pleach/base-tools
```

```bash
pnpm add @pleach/base-tools
```

```bash
bun add @pleach/base-tools
```

```typescript
import {
  mathTool,
  datetimeTool,
  scratchpadTool,
  unitConvertTool,
  textSearchTool,
} from "@pleach/base-tools";
```

The import names above are illustrative. The authoritative export
shape lives in the package README (not on npm yet) — check it
when you wire the tools in, since the bundle's surface evolves
faster than this page.

## The tool surface [#the-tool-surface]

### `math` [#math]

Arithmetic with a `peek` mode (read the result without committing to
the conversation) and a reverse-polish-notation evaluator. Use it
when the model needs deterministic numeric work mid-turn instead of
guessing at sums in prose.

```json
{
  "name": "math",
  "args": { "mode": "rpn", "expr": "3 4 + 2 *" }
}
// → { "result": 14 }
```

```json
{
  "name": "math",
  "args": { "mode": "peek", "expr": "1.07 * 249.99" }
}
// → { "result": 267.4893, "committed": false }
```

### `datetime` [#datetime]

Clock and date arithmetic. Four operations — `now`, `parse`,
`format`, and `diff` — selected by the `operation` param. Every
output is a string or number, never a JS `Date`, so the wire stays
portable across the language-agnostic contract.

`now` returns the current UTC instant as an ISO-8601 string plus
epoch milliseconds:

```json
{
  "name": "datetime",
  "args": { "operation": "now" }
}
// → { "iso": "2026-06-06T16:14:22.117Z", "epochMs": 1781108062117, "timezone": "UTC" }
```

`format` renders an instant for a given IANA `timezone`. The
`formatted` field is a wall-clock string (`YYYY-MM-DDTHH:mm:ss`)
with **no** offset or `Z` suffix — it is local-to-the-zone, not a
round-trippable ISO-8601 instant. The `iso` field alongside it is
the original UTC instant if you need the portable form:

```json
{
  "name": "datetime",
  "args": { "operation": "format", "input": "2026-06-06T16:14:22Z", "timezone": "America/Los_Angeles" }
}
// → { "iso": "2026-06-06T16:14:22.000Z", "timezone": "America/Los_Angeles", "formatted": "2026-06-06T09:14:22" }
```

`diff` returns the signed difference between two instants in a
chosen `unit` (`milliseconds`, `seconds`, `minutes`, `hours`, or
`days`; default `milliseconds`):

```json
{
  "name": "datetime",
  "args": { "operation": "diff", "input": "2026-06-06T00:00:00Z", "other": "2026-06-20T00:00:00Z", "unit": "days" }
}
// → { "from": "2026-06-06T00:00:00.000Z", "to": "2026-06-20T00:00:00.000Z", "unit": "days", "value": 14 }
```

There is no `shift` operation — to add an interval, compute it
host-side (or with the `math` tool) and `parse` the result.

### `scratchpad` [#scratchpad]

A per-session key/value store the model can read and write across the
tool calls of a session. Keyed by `ToolContext.chatId`, so entries
persist across turns within the same session. Use it for
intermediate workings the model would otherwise have to thread through
prose between tool calls. The `operation` param selects the action
(`set` / `get` / `list` / `delete` / `clear`); values are strings.

```json
{ "name": "scratchpad", "args": { "operation": "set", "key": "note", "value": "remember this" } }
{ "name": "scratchpad", "args": { "operation": "get", "key": "note" } }
// → { "found": true, "value": "remember this" }
```

The store is per-session by design — it does not survive session
boundaries. A model that wants cross-session persistence should write
to a real tool that hits storage, not lean on scratchpad and be
surprised when state is gone in a new session.

### `unit_convert` [#unit_convert]

SI and imperial unit conversions. The tool rejects category mismatches
(length to mass, currency to temperature) with a typed error rather
than silently returning garbage.

```json
{ "name": "unit_convert", "args": { "value": 5, "from": "km", "to": "mi" } }
// → { "value": 3.1068559611866697, "unit": "mi" }
```

```json
{ "name": "unit_convert", "args": { "value": 5, "from": "km", "to": "kg" } }
// → error: { "code": "UNIT_CATEGORY_MISMATCH", "from": "length", "to": "mass" }
```

### `text_search` [#text_search]

Regex and substring search over a text body the caller supplies. No
external corpus and no network — the tool is for "find the line that
mentions X in this document I'm already holding."

```json
{
  "name": "text_search",
  "args": {
    "haystack": "...long document text...",
    "pattern": "section 4.2",
    "mode": "literal"
  }
}
// → { "matches": [{ "index": 5120, "endIndex": 5131, "match": "section 4.2", "groups": [] }, ...], "truncated": false, "mode": "literal" }
```

Regex fails closed. `mode` defaults to `"regex"`, but a pattern with a
regex metacharacter is refused: the tool runs on the host's thread and
a synchronous regex can't be interrupted. Literal mode and
metacharacter-free patterns always run.

To accept regexes, opt in with `createTextSearchTool({ allowInProcessRegex: true })`
or `textSearch: { allowInProcessRegex: true }` on `createBaseToolsPlugin`.
The opt-in screens each pattern with `checkGrepPatternSafety` and caps
the haystack at 4,096 characters.

### `json_query` [#json_query]

Extract a value from a JSON document by path. The natural partner to
`http_json` — fetch an API response, then pull the one field the model
needs instead of feeding the whole document back into the prompt. Pure
and network-free. Supports dotted keys, array indices (negative counts
from the end), quoted keys, and a `[*]` wildcard that collects a field
from every array element. It is not full JSONPath — no filters, no
recursive descent — so the evaluator is single-pass and cannot ReDoS.

```json
{ "name": "json_query", "args": { "json": { "data": { "items": [{ "id": 1 }, { "id": 2 }] } }, "path": "data.items[*].id" } }
// → { "value": [1, 2], "found": true, "path": "data.items[*].id" }
```

`found` reports `false` when a path segment is missing — that is a
result, not an error.

### `memory` [#memory]

Durable, cross-session key/value memory. Where `scratchpad` forgets
everything at the session boundary, `memory` persists — a value written
in one session is readable in the next. Use it for stable facts: a
user's preferences, a running profile, a decision made earlier. Values
are scoped by `namespace` (pass a user or tenant id) so one caller's
memory is never visible to another. Operations: `set` / `get` / `list`
/ `delete` / `search`.

```json
{ "name": "memory", "args": { "operation": "set", "namespace": "user-42", "key": "preferred_units", "value": "metric" } }
{ "name": "memory", "args": { "operation": "get", "namespace": "user-42", "key": "preferred_units" } }
// → { "found": true, "namespace": "user-42", "key": "preferred_units", "value": "metric" }
```

The backend is pluggable. The default is an in-process store — durable
across sessions, gone on restart. Inject a `MemoryStore` (a five-method
async interface) to back it with a real database and get restart-durable
memory:

```typescript
import { createMemoryTool } from "@pleach/base-tools";

const tool = createMemoryTool({ store: myDatabaseBackedStore });
```

**Writes can be approval-gated.** A model that can silently persist a
"learned" fact is a model you cannot audit. Set
`requireApprovalForWrites: true` and every `set` / `delete` routes
through an injected `approveWrite` gate before it commits; reads stay
ungated. `createGraduatingApproval` implements the common flow — prompt
the human for the first few writes, then let the agent write on its own
once trust is established:

```typescript
import { createMemoryTool, createGraduatingApproval } from "@pleach/base-tools";

const tool = createMemoryTool({
  store: myDatabaseBackedStore,
  requireApprovalForWrites: true,
  approveWrite: createGraduatingApproval({
    confirm: (req) => askTheHuman(req),  // your approval UI
    autonomousAfter: 3,                  // ask 3 times, then autonomous
  }),
});
```

A denied write does not count toward graduation, so the human stays in
control until they have approved enough writes to trust the agent.

### `url_fetch` (opt-in) [#url_fetch-opt-in]

A guarded HTTP GET. Off by default; the host opts in by registering
the policy plugin (see [Safety policies bundled](#safety-policies-bundled)
below). The fetcher enforces:

* No `localhost` or loopback targets.
* No private CIDR ranges (RFC 1918, link-local, etc.).
* A configurable allowlist for the domains the agent is permitted to
  reach.

Returns the body and response headers. Don't reach for it before the
host has decided which domains the agent is allowed to touch — the
defaults are restrictive precisely because "fetch any URL the model
emits" is rarely what production wants.

```json
{ "name": "url_fetch", "args": { "url": "https://example.com/article" } }
// → { "status": 200, "headers": { "content-type": "text/html" }, "body": "..." }
```

### `web_fetch` (opt-in) [#web_fetch-opt-in]

Read a web page as clean text. `url_fetch` returns the raw body; for an
HTML page that is a wall of markup the model cannot cheaply read.
`web_fetch` GETs an allowlisted URL through the same SSRF-safe fetch
core and reduces HTML to readable text — dropping scripts, styles, and
tags — returning the page title plus the body text. Non-HTML bodies pass
through untouched. Gated on the same allowlist as `url_fetch`.

```json
{ "name": "web_fetch", "args": { "url": "https://example.com/article" } }
// → { "httpStatus": 200, "url": "...", "title": "...", "text": "Readable body text...", "kind": "html", "truncated": false }
```

### `web_search` (opt-in) [#web_search-opt-in]

Search the web for a query and return a ranked list of
`{ title, url, snippet }`. The other half of the search-then-read loop:
`web_search` finds the sources, `web_fetch` reads the best hit. The
package ships no baked-in API key — you inject a `searchProvider`
(Tavily, Brave, SerpAPI, a self-hosted SearXNG). Without a provider the
tool refuses every call. A no-key `createDuckDuckGoProvider` is bundled
for the quickstart; production hosts inject a real API provider.

```typescript
import { createWebSearchTool } from "@pleach/base-tools";

const tool = createWebSearchTool({ searchProvider: myTavilyProvider });
```

```json
{ "name": "web_search", "args": { "query": "error budget SRE", "maxResults": 5 } }
// → { "query": "error budget SRE", "results": [{ "title": "...", "url": "...", "snippet": "..." }, ...] }
```

### `http_json` and `http_head` (opt-in) [#http_json-and-http_head-opt-in]

Two convenience network tools over the same allowlisted fetch core.
`http_json` GETs a URL and parses the body as JSON (returning the parsed
value, or the raw text plus a `parseError` when it is not JSON).
`http_head` issues a real HEAD request and returns metadata only —
status, content type, length, etag, last-modified — never the body.
Both share the `url_fetch` allowlist and refuse without one.

### `recall` (opt-in) [#recall-opt-in]

Query the session event log for what already happened — past tool
calls, their outcomes, interrupts. Use it before re-running an
expensive tool to check whether you already ran it and what it
returned. Provider-neutral by injection: you supply a `reader` over
whatever holds the log — a Supabase table on a server, a local JSONL or
SQLite file on a personal machine. Without a reader the tool refuses.

```json
{ "name": "recall", "args": { "toolName": "web_search", "limit": 5 } }
// → { "events": [{ "type": "tool.completed", "toolName": "web_search", "at": 1781108062117 }, ...] }
```

The package also ships `summarizeToolOutcomes`, a pure function that
folds recalled events into per-tool `{ started, completed, failed,
lastError }` counts. Feed the summary back as a prompt hint so the agent
stops repeating what already failed — turning the audit log into a
learning signal, not just a record.

## Personal-agent tools (store-backed, opt-in) [#personal-agent-tools-store-backed-opt-in]

These turn a stateless assistant into an agent that *grows with the user*
— it maintains an evolving identity, a model of the user, learned facts,
a searchable history, reminders, and a task plan across sessions. All are
opt-in, refuse-by-default, and user-scoped (namespaced by `(orgId,
userId)`) so one user's self is never another's. Each needs an injected
`BaseStore`; without one the writes refuse and the reads return empty.

You rarely wire these by hand: `createPleachAgent` from
`@pleach/core/quickstart` turns the whole family on automatically when
its `db` carries a durable `memory` store, keyed to the local user. What
the agent *writes* is re-injected into its own system prompt on the next
turn — a real self-modification loop, not just a log.

### Self-model — `self_view`, `revise_identity`, `set_user_profile`, `pin_preference` [#self-model--self_view-revise_identity-set_user_profile-pin_preference]

The "SOUL.md + USER.md" pattern, made durable. `self_view` reads the
composed self (identity + user-model + pinned preferences). The three
writers evolve it: `revise_identity` amends the agent's own persona,
`set_user_profile` records what it knows about the user, and
`pin_preference` pins a behaviour rule that is re-injected every turn.
Because identity rides the cacheable prompt prefix, revisions take effect
going forward — the agent you talk to tomorrow is shaped by what it
learned today.

```json
{ "name": "pin_preference", "args": { "preference": "Always include a runnable example." } }
{ "name": "set_user_profile", "args": { "content": "Prefers TypeScript, no semicolons.", "mode": "append" } }
```

A bundled safety policy (`self-model.guard-self-writes`) keeps the agent
from ever editing away its own safety, ethics, or honesty — those are not
part of the editable self.

The writers clean text before storing it. They remove invisible and
control characters and shorten runs of three or more angle brackets.
Text that is empty after cleaning is refused. The stored identity
renders as a `# Your identity` section: a one-line notice that it never
overrides a safety, system or operator instruction, then each line
quoted inside a fence, capped at 4,000 code points.
`composeIdentitySection` (`@pleach/core/quickstart`) builds that section,
so a custom persona source renders identically.

With `requireApprovalForWrites`, the gate's `SelfWriteRequest` carries
`proposed` (the exact text that will be stored), `previous`, `appended`
and `reason`, so the approver sees what it approves:

* Only an explicit `true` approves. Any other value refuses the write.
* A gate that throws gives the failed result "Refused: approval gate
  failed" and stores nothing.
* If the stored text changed while the gate decided, the write is refused
  and can be retried.
* An append to a document already at its cap is refused as full.
* An unpin of an id with nothing stored returns `removed: false`.

### Meta-learning — `recall_facts`, `correct_fact`, `forget_fact`, `prune_memory`, `detect_conflicts`, `reflect` [#meta-learning--recall_facts-correct_fact-forget_fact-prune_memory-detect_conflicts-reflect]

The typed, confidence-scored learning substrate, exposed to the agent
itself. `recall_facts` reads what it has learned about the user (with
categories + confidence); `correct_fact` pins a corrected belief
(confidence 1.0, user-verified, decay-exempt); `forget_fact` drops one;
`prune_memory` clears stale/low-confidence facts; `detect_conflicts`
surfaces contradictions to reconcile; `reflect` reads the agent's own
success/error rate and improving-or-degrading trend.

```json
{ "name": "recall_facts", "args": { "minConfidence": 0.7 } }
{ "name": "correct_fact", "args": { "fact_key": "fact_1x9k2a", "new_content": "Prefers Python, not TypeScript." } }
```

`correct_fact`, `forget_fact` and `prune_memory` check their arguments
before anything is stored. `fact_key` must be a key that `recall_facts`
returned, shaped `fact_<hash>` or `consolidated_<hash>`; any other key
fails with a tool error and changes nothing. A host whose own writers
store facts under other keys passes `isFactKey` in
`MetalearningToolsOptions`. `agent_name` is a short identifier (letters,
digits, `_ . : -`, at most 64 characters); omit it for the global scope.
`new_content` is normalised to one line, refused above 2,000 code points
(never truncated), and refused when it reads as an instruction to the
model. Correcting a key with no stored fact is reported as "No learned
fact has that `fact_key`".

### Knowledge & history — `skill_search`, `db_lookup`, `session_search` [#knowledge--history--skill_search-db_lookup-session_search]

`skill_search` discovers reusable skills by intent or free text (the
discovery half of `skill_view` / `create_skill`). `db_lookup` reads the
agent's own durable namespaces (facts, self, skills, memory), bounded to
its own data. `session_search` is full-text recall over past
conversation — "have we discussed this?" — relevance-ranked; back it with
a reader over a text index (the SQLite store's FTS5 `searchEvents`).

```json
{ "name": "session_search", "args": { "query": "docking results egfr", "limit": 5 } }
```

### Scheduling — `schedule`, `list_schedules`, `cancel_schedule` (opt-in) [#scheduling--schedule-list_schedules-cancel_schedule-opt-in]

Record a future task or proactive check-in for the agent itself
(`schedule`, with an optional `every` recurrence like `"1d"`), review
pending ones (`list_schedules`), or drop one (`cancel_schedule`). The
package owns the durable *intent*; a host supplies the clock — read due
tasks with `readScheduledTasks` and re-enter the agent with each task's
`prompt`.

```json
{ "name": "schedule", "args": { "when": "2026-08-05T09:00:00Z", "prompt": "Follow up on the EGFR run.", "every": "1d" } }
```

### Task tracker — `todo_write`, `todo_read` [#task-tracker--todo_write-todo_read]

A visible, status-tracked checklist for a multi-step job — the Claude
Code `TodoWrite` pattern. `todo_write` replaces the whole list (mark one
item `in_progress`, flip to `completed` as you go); `todo_read` resumes
it, even in a later session.

```json
{ "name": "todo_write", "args": { "todos": [
  { "content": "Read the config", "status": "completed" },
  { "content": "Add the field", "status": "in_progress" },
  { "content": "Write a test", "status": "pending" }
] } }
```

### Persistent plans — `create_plan`, `get_plans`, `advance_plan`, `revise_plan`, `plan_history` [#persistent-plans--create_plan-get_plans-advance_plan-revise_plan-plan_history]

`createPlanTools({ planManager, lineageTracker, getSessionId, getChatId, presenter })`
from `@pleach/core/base-tools` returns one handler per tool over a
[`PlanManager`](/docs/plans): a plan that outlives the chat it was made in.
They are opt-in: a `SessionRuntime` registers them for each graph build only
when `config.persistentPlanTools` is `true` and a `planManager` is set (and
`session_lineage` only when a `lineageTracker` is set). Without the opt-in every
tool answers `PLAN_STORE_NOT_WIRED`, even with a manager configured.
`advance_plan` stamps the step with the session and chat that ran it, records
`summary`, `canvas_cards` and `job_ids` as completion evidence, and, when a
`lineageTracker` is wired and the step runs in a later session than the plan,
writes a `planned_by` edge. `get_plans` with `include_completed` also lists
finished plans. Results are small JSON; arguments over a cap are refused, never
truncated. With no manager every tool answers `PLAN_STORE_NOT_WIRED`. The
optional `presenter` (`config.planToolTextPresenter` on the runtime) rewrites
each stored, model-written string before it reaches a result, and returning
`null` withholds the string. Its `notice` rides on every result.
`PLAN_TOOL_DEFINITIONS` exports each tool's name, description and JSON-schema
`input_schema`, so a host advertises the same arguments the handlers parse
instead of keeping its own copy.

```json
{ "name": "advance_plan", "args": { "plan_id": "plan_…", "step_id": "step_…", "status": "completed", "summary": "Docked 12 ligands", "job_ids": ["job_…"] } }
```

### Session lineage — `session_lineage` [#session-lineage--session_lineage]

`createSessionLineageTool({ tracker, getSessionId, presenter })` reads a
[`LineageTracker`](/docs/lineage): the sessions before (`ancestors`), after
(`descendants`) or around (`full`, with the edges) a session, which defaults to
the current one. `max_depth` defaults to 10 and is clamped to 1–25. Node and
edge lists are capped (200 nodes) and say `truncated`. With no tracker it answers
`LINEAGE_NOT_WIRED`. It registers under the same `persistentPlanTools` opt-in,
and its schema is exported as `SESSION_LINEAGE_TOOL_DEFINITION`.

```json
{ "name": "session_lineage", "args": { "direction": "ancestors", "max_depth": 5 } }
```

## Capability-gated tools (opt-in) [#capability-gated-tools-opt-in]

Three tools that touch code execution, the human, or the filesystem.
The package ships the tool contract and a permission gate, never a
bundled runtime — running untrusted code or opening the filesystem is
the host's trusted runtime's job. Each refuses by default until the host
injects the capability. That keeps `@pleach/core` free of a large attack
surface it should not carry.

### `code_exec` [#code_exec]

Execute code in a sandbox and return its stdout / stderr. You inject a
`runner` — your own sandbox (`@pleach/coding-agent`, Vercel Sandbox, a
Firecracker microVM). An optional language allowlist and a per-call
timeout bound what it runs. Without a runner the tool refuses.

```typescript
import { createCodeExecTool } from "@pleach/base-tools";

const tool = createCodeExecTool({ runner: mySandbox, allowedLanguages: ["python"] });
```

#### Choosing a backend per call — `resolveRunner` [#choosing-a-backend-per-call--resolverunner]

A single `runner` pins one backend for the tool's lifetime. When the
backend depends on the call — shell to an SSH host and Python to a
container, or a sandbox per tenant — supply `resolveRunner` instead.
It is consulted on **every invocation** and its return wins over
`runner`; returning `null` falls through to `runner`.

```typescript
const tool = createCodeExecTool({
  runner: defaultContainer,                 // fallback
  resolveRunner: ({ language, chatId }) =>
    language === "bash" ? sshHostFor(chatId) : null,
});
```

The resolver sees post-validation facts — `language` already lowercased
and allowlist-checked, `timeoutMs` already clamped, plus `codeChars` and
`chatId` — so it picks a backend for a call the tool has already agreed
to make, rather than re-implementing the tool's guards. It is never
consulted for a call that would be refused anyway.

A resolver has three answers, and the distinction matters:

| Return                     | Meaning                                         |
| -------------------------- | ----------------------------------------------- |
| a `CodeRunner`             | serve this call on that backend                 |
| `{ refuse: true, reason }` | **deny** — `runner` is *not* used as a fallback |
| `null` / `undefined`       | abstain — fall through to `runner`              |

Abstain and refuse are separate values on purpose. With only `throw` as
a denial channel, a deliberate policy decision is indistinguishable
from an infrastructure failure, and `null` silently means "allow on
default" for any deployment that also configured a static `runner`.

A **throwing** resolver still refuses the call and does not fall back —
if the resolver was the thing deciding which backend is authorised, a
fallback would run the code on a backend it may have been trying to
deny, so the failure direction is closed. Resolution must be
**synchronous**; a `Promise` smuggled through a cast is rejected, not
awaited. Refuse-by-default is unchanged: with neither `runner` nor
`resolveRunner`, the tool refuses every call, before validation,
exactly as before.

### `ask_user` [#ask_user]

Pause and ask the human a clarifying question. `@pleach/core` has a
richer interrupt system; this is the portable surface any host can wire,
including one not using the interrupt machinery — a CLI reading stdin, a
bot posting a question. You inject an `ask` handler that bridges to
whatever asks the human. Without it the tool refuses.

### Workspace file tools — `fs_read`, `fs_list`, `fs_glob`, `fs_grep`, `fs_write`, `fs_edit` [#workspace-file-tools--fs_read-fs_list-fs_glob-fs_grep-fs_write-fs_edit]

Six tools over one injected `FileSystemAdapter`. Every path is confined
under an `allowedRoots` entry, with `..` escapes and null bytes
rejected, before the adapter is called. The tools are pure JavaScript
over the adapter: no shell, no extra dependency.

| Tool       | Params                                                                                             | Mode       | `requiresApproval` |
| ---------- | -------------------------------------------------------------------------------------------------- | ---------- | ------------------ |
| `fs_read`  | `path`, `offset?`, `limit?`                                                                        | read-only  | no                 |
| `fs_list`  | `path`                                                                                             | read-only  | no                 |
| `fs_glob`  | `pattern`, `path?`, `max_results?`                                                                 | read-only  | no                 |
| `fs_grep`  | `pattern`, `path?`, `glob?`, `case_insensitive?`, `fixed_strings?`, `output_mode?`, `max_results?` | read-only  | no                 |
| `fs_write` | `path`, `content`                                                                                  | read-write | yes                |
| `fs_edit`  | `path`, `old_string`, `new_string`, `replace_all?`                                                 | read-write | yes                |

* **`fs_read`** takes an optional 1-based line window. With `offset` or
  `limit` it adds `startLine`, `endLine` and `totalLines`; with
  neither, the response is `{ path, content, bytes }` as before.
* **`fs_glob`** supports `**`, `*`, `?`, `{a,b}` and `[...]`. It returns
  sorted paths: 500 by default, 5,000 at most.
* **`fs_grep`** runs a JavaScript regex over files. `output_mode` is
  `content` (default), `files_with_matches` or `count`. It returns 100
  results by default, 2,000 at most.
* **`fs_edit`** is a literal `str_replace`. `old_string` must match
  exactly once unless `replace_all` is set; zero or several matches
  fail without writing. It returns `{ path, replacements, bytes }`.

The filesystem is read-only by default. `fs_write` and `fs_edit` refuse
until the host sets `mode: "read-write"`, the filesystem analogue of
`url_fetch`'s `allowHttp`. Both carry `requiresApproval` and the
`destructive` annotation. The flag is advisory: enforce it with
`interrupt.interruptBefore`, as with any approval-gated tool.

#### Symlink confinement [#symlink-confinement]

`FileSystemAdapter` has an optional `realpath(path)`. When it's
present, every fs tool re-confines each path after symlink resolution,
against the roots' own real paths, and calls the adapter with the real
path. A link that leaves a root is refused on read, write and edit, and
skipped by glob, grep and directory walks. A path that can't be
resolved is refused.

Without `realpath`, confinement is lexical only. Reads log a one-time
warning. `fs_write` and `fs_edit` refuse unless you set
`allowLexicalOnlyConfinement: true` — set it only for adapters with no
symlinks, such as in-memory or remote stores. An adapter over a real
disk should implement `realpath`.

#### Bounds and defaults [#bounds-and-defaults]

| Option             | Default                        | Bounds                                                                                                                    |
| ------------------ | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------- |
| `maxReadBytes`     | 5 MB                           | Per-file read cap; also the per-file cap for `fs_edit` and `fs_grep`                                                      |
| `maxWriteBytes`    | 5 MB                           | Write cap; also the size of the file `fs_edit` writes back                                                                |
| `maxWalkEntries`   | 20,000                         | Entries one `fs_glob` / `fs_grep` walk visits                                                                             |
| `maxGrepScanBytes` | 50 MB                          | Total bytes one `fs_grep` call reads                                                                                      |
| `ignoreDirs`       | `.git`, `node_modules`         | Directory names walks never enter                                                                                         |
| `denyPaths`        | A built-in sensitive-path list | Refused on read, write and list; skipped on walks. Covers `.ssh`, `.aws`, `.env*`, `*.pem` and more. Pass `[]` to opt out |
| `grepTimeoutMs`    | 2,000                          | Wall-clock budget for one `fs_grep` call                                                                                  |

`fs_grep` regexes fail closed too. On Node, each tool instance runs
regexes in a deadline-terminated worker by default. Where there's no
worker (browser, edge, or `grepWorker: false`) and no `grepMatcher`,
`fs_grep` is literal-only: `fixed_strings: true` and metacharacter-free
patterns still run. `allowInProcessRegex: true` runs regexes on the
main thread behind the `checkGrepPatternSafety` screen.

#### Enabling the tools [#enabling-the-tools]

Inject the adapter through `fileSystem` on `createBaseToolsPlugin` (or
`createPleachAgent`). With no explicit `include`, an adapter enables
`fs_list`, `fs_read`, `fs_glob` and `fs_grep`. `mode: "read-write"`
adds `fs_write` and `fs_edit`. An explicit `include` is honoured
exactly. Without an adapter, every fs tool refuses every call.

```typescript
import { createBaseToolsPlugin } from "@pleach/core/base-tools";

const plugin = createBaseToolsPlugin({
  fileSystem: {
    adapter: myFsAdapter,          // implements readFile, writeFile, list, realpath
    allowedRoots: ["/workspace"],
    mode: "read-write",            // adds fs_write + fs_edit
  },
});
```

To build the tools directly, `createFileSystemTools(config)` returns
`fsReadTool`, `fsWriteTool`, `fsListTool`, `fsEditTool`, `fsGlobTool`
and `fsGrepTool`. Each also has its own factory (`createFsEditTool`,
`createFsGlobTool`, `createFsGrepTool`, …).

#### Node-only grep worker: `@pleach/core/base-tools/node` [#node-only-grep-worker-pleachcorebase-toolsnode]

The worker matcher lives on a separate subpath, so `node:worker_threads`
never enters a browser or edge bundle. Reach for it when one process
runs several agents: build one semaphore and share it, since each tool
instance otherwise caps only its own workers (default 4).

```typescript
import { createGrepWorkerSemaphore } from "@pleach/core/base-tools/node";

const semaphore = createGrepWorkerSemaphore();
const fileSystem = { adapter, allowedRoots: ["/workspace"], grepWorker: { semaphore } };
```

The subpath also exports `createWorkerGrepMatcherFactory`,
`withDefaultGrepMatcher` and `isWorkerGrepMatcherAvailable`.

## Citation utility — `extractMarkdownLinks` [#citation-utility--extractmarkdownlinks]

Given a markdown body, returns the extracted-link envelope. Each link
carries the anchor text, the URL, the recognized shape (`inline` /
`reference` / `autolink` / `bare`), and the offset into the input
where the match started. Useful for "what did the model cite" auditing
on top of `url_fetch` output, or for inspecting markdown the model
itself produced.

```typescript
import { extractMarkdownLinks } from "@pleach/base-tools";
import type {
  MarkdownLink,
  MarkdownLinkExtractionResult,
} from "@pleach/base-tools";

const result: MarkdownLinkExtractionResult = extractMarkdownLinks(body);
// → {
//     links: [
//       { text: "the spec",   url: "https://example.com/spec",   kind: "inline", index: 42 },
//       { text: "issue #142", url: "https://github.com/.../142", kind: "inline", index: 118 },
//     ],
//     truncated: false,
//   }
```

`truncated` flips to `true` when the input exceeds the link cap
(default 1000) and the returned array was capped. Input larger than
the input cap (default 1 MB) throws — chunk the input first if
you're processing larger bodies.

This is a utility, not a tool — call it from host code that's
processing tool output, not from a tool the model invokes.

## Safety policies bundled [#safety-policies-bundled]

The package contributes safety policies via the standard
[`HarnessPlugin`](/docs/plugin-contract) contract. The headline policy
is the `url_fetch` private-network guard described above; the package
ships it as a `contributeSafetyPolicies` entry on its plugin export so
that registering the plugin opts the host into the guard.

```typescript
import { SessionRuntime } from "@pleach/core";
import { createBaseToolsPlugin } from "@pleach/base-tools";

const runtime = new SessionRuntime({
  storage: myStorage,
  plugins: [
    createBaseToolsPlugin({
      include: ["math", "url_fetch"],
      urlFetch: { allowedHostnames: ["example.com"] },
    }),
  ],
  userId: "user_123",
});
```

The host stays in control: don't register the plugin and `url_fetch`
isn't on the surface at all. Register it with a tight allowlist and
the model only reaches the domains the host approved. See
[Safety](/docs/safety) for the policy contract the bundled entries
implement against.

### The four named policies [#the-four-named-policies]

`contributeSafetyPolicies()` returns four `SafetyContribution`
constants, each also importable by name from `@pleach/base-tools` (and
`@pleach/core/base-tools`). Registration is not activation — each policy
is inert until the operator opts in via `enabledSafetyPolicies: [...]`
at `SessionRuntime` construction.

| Constant                        | Policy id                           | Kind                                                                                 |
| ------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------ |
| `NO_EVAL_POLICY`                | `base-tools.no-eval`                | refusal — reject arbitrary-code-execution requests; base-tools ships no eval surface |
| `NO_NETWORK_BY_DEFAULT_POLICY`  | `base-tools.no-network-by-default`  | advisory — declare that the base toolset performs no network I/O                     |
| `BOUNDED_RESOURCE_USAGE_POLICY` | `base-tools.bounded-resource-usage` | advisory — surface the explicit caps each tool enforces                              |
| `INPUT_VALIDATION_POLICY`       | `base-tools.input-validation`       | advisory — encourage shape validation before invocation                              |

The frozen `BASE_TOOLS_SAFETY_POLICIES` array holds all four in
registration order. A host that *does* provide eval or network
capability should not enable `base-tools.no-eval` /
`base-tools.no-network-by-default` — the prose would contradict its own
tool catalog.

{/* TODO: verified 2026-06-14 against the published `@pleach/base-tools` type declarations —
    none of toolExecutionLatencyObserver / toolFailureRateObserver /
    chunkSizeObserver are re-exported from @pleach/base-tools today.
    The package re-exports safety policies (BASE_TOOLS_SAFETY_POLICIES)
    and the citation extractor; stream observers must be imported from
    @pleach/core directly. Section preserved as TODO until either the
    re-exports land or the claim is replaced with an accurate inventory.

  ## Observer re-exports

  The package re-exports a handful of stream observers from
  `@pleach/core` so a host doesn't need to import from both places to
  wire common telemetry. The current re-export set:

  - `toolExecutionLatencyObserver` — emits a `metrics` channel envelope
  on every `tool.completed` with the wall-clock duration.
  - `toolFailureRateObserver` — emits a `metrics` envelope on
  `tool.failed`.
  - `chunkSizeObserver` — chunk-length histogram for streamed text
  content.

  The observer contracts themselves live in
  [Stream events](/docs/stream-events); the re-exports are convenience,
  not new behavior.
  */}

## Registration pattern [#registration-pattern]

The tools register through the plugin's `contributeTools` hook, the
same way any `HarnessPlugin` adds to the tool registry. Use
`createBaseToolsPlugin(...)` to configure the set; `baseToolsPlugin`
is the zero-config singleton for the quickstart.

### Which tools register by default [#which-tools-register-by-default]

Without `include`, `resolveBaseToolsProfile` picks the set from the
capabilities you inject. Injecting a capability enables its tool, so
nothing sits in the catalog refusing every call.

| Inputs                                                          | Resulting default set                                                                                                                     |
| --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| Nothing                                                         | `math`, `unit_convert`, `json_query`, `text_search`, `datetime`, `memory`, `scratchpad` (the seven in `DEFAULT_BASE_TOOLS`)               |
| `fileSystem.adapter`                                            | Pure pack + `datetime`, `memory`, plus `fs_list`, `fs_read`, `fs_glob`, `fs_grep`. `scratchpad` is dropped                                |
| `fileSystem.adapter` with `mode: "read-write"`                  | Adds `fs_write` and `fs_edit`                                                                                                             |
| `codeExec.runner` or `codeExec.resolveRunner`                   | Workspace profile: `code_exec` replaces the pure pack (`math`, `unit_convert`, `json_query`, `text_search`); `datetime` and `memory` stay |
| Runner + `todo.store`                                           | Adds `todo_write`, `todo_read`                                                                                                            |
| Runner + `webSearch.searchProvider`                             | Adds `web_search`                                                                                                                         |
| Runner + non-empty `urlFetch.allowedHostnames` or `allowedUrls` | Adds `web_fetch`                                                                                                                          |

The `todo`, `webSearch` and `urlFetch` rows apply only with a code
runner. Without one, list those tools in `include`. The network tools
`url_fetch`, `http_json` and `http_head` are never in the default
set: list them explicitly and supply an allowlist, or every call
refuses with `Refused: no allowlist configured`.

An explicit `include` is honoured exactly. No profile logic runs, so
`include` is how you turn any of the above off.

```typescript
import { SessionRuntime } from "@pleach/core";
import { createBaseToolsPlugin } from "@pleach/base-tools";

const runtime = new SessionRuntime({
  storage: myStorage,
  plugins: [
    createBaseToolsPlugin({
      // An explicit list is used as given; no profile logic runs:
      include: [
        "math", "datetime", "scratchpad", "unit_convert", "text_search",
        "json_query", "memory", "web_fetch", "web_search",
      ],
      // Network tools stay off until an allowlist is supplied:
      urlFetch: { allowedHostnames: ["docs.example.com"] },
      webSearch: { searchProvider: myTavilyProvider },
    }),
  ],
  userId: "user_123",
});

const session = await runtime.createSession({
  tools: { enabled: ["math", "datetime", "scratchpad"] },
});
```

The session's `tools.enabled` array selects which of the registered
tools that particular session can see — registration and exposure are
separate concerns, so the same runtime can serve a numeric agent and
a search agent without each one inheriting the other's surface.

## Position vs the tool contracts [#position-vs-the-tool-contracts]

| Import                    | What it ships                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | Reach for it when                                                         |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------- |
| `@pleach/core/tools`      | `defineTool`, `UnifiedToolDefinition`, `toolRegistry`, batching strategy hints                                                                                                                                                                                                                                                                                                                                                                                                                                     | You're writing your own tools                                             |
| `@pleach/core/base-tools` | Pre-built tools: zero-config (`math`, `datetime`, `scratchpad`, `unit_convert`, `text_search`, `json_query`, `memory`), opt-in network/agentic (`web_search`, `web_fetch`, `http_json`, `http_head`, `url_fetch`, `code_exec`, `ask_user`, `fs_read`/`fs_list`/`fs_glob`/`fs_grep`/`fs_write`/`fs_edit`, `recall`), and store-backed personal-agent tools (self-model, meta-learning, `skill_search`/`db_lookup`/`session_search`, scheduling, `todo_write`/`todo_read`), plus the safety policies that guard them | You want a sane default toolbelt without re-implementing the common cases |

Both compose. A typical host defines its domain tools with
`@pleach/core/tools` and adds `createBaseToolsPlugin` for the generic
surface; the two register side-by-side in the same tool registry.
`@pleach/tools` and `@pleach/base-tools` remain as deprecated
re-export shims.

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

<Cards>
  <Card title="Tools" href="/docs/tools" description="The `defineTool` primitive in `@pleach/core/tools` that base tools build on — Zod schemas, per-invocation context, batching." />

  <Card title="Recipes" href="/docs/recipes" description="End-to-end patterns that wire the bundled tools into common agent shapes." />

  <Card title="Reference apps" href="/docs/reference-apps" description="Runnable agents that import `@pleach/base-tools` alongside domain-specific tools." />

  <Card title="Plugin contract" href="/docs/plugin-contract" description="The `HarnessPlugin` surface this package ships its tools and safety policies through." />

  <Card title="Safety" href="/docs/safety" description="The safety-policy contract the bundled `url_fetch` guard implements against." />
</Cards>
