Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: CI

on:
push:
branches: [main]
pull_request:

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22.12.0'
cache: npm
Comment thread
Copilot marked this conversation as resolved.
Resolved
- run: npm ci
- run: npm run typecheck
- run: npm test
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
node_modules/
dist/
coverage/
.env
.env.*
!.env.example
*.log
.DS_Store
93 changes: 93 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# Agent dev guide — hadrontool-websearch

**hadrontool-websearch** is an independently-deployed, **stateless** web
**search** capability tool for the Hadron platform: it gives headless LLM runs a
governed way to query an external search provider and receive a ranked list of
result references. Core (hadron-server) keeps the contract, identity, provider
credentials, and ALL authorization; this tool executes searches and nothing
else.

**Design issue: hadron-server#647** (core-side spine merged in #648). It is the
reference implementation of the versioned, provider-agnostic **`web-search@1`**
contract — platform specs **`cor:web:020*`**. Sibling tool: `hadrontool-webfetch`
(the stateless template this repo copies); it is a *separate* capability, not a
mode of fetch.

## Commands

```bash
npm run dev # tsx watch (port 8080)
npm test # vitest — real HTTP via supertest over a FAKE fetch seam
npm run typecheck
npm run build # tsc -p tsconfig.build.json
```

No database, no Prisma, no migrations, no keys at rest — nothing to set up.

## Structure

- `src/providers.ts` — the fixed provider allowlist (spec cor:web:020:02). One
adapter per provider: hard-coded endpoint + generic-input→param mapping +
response→`RawResult` normalization. `brave` (default) and `bing`.
- `src/search.ts` — the guard-free egress engine: one GET to an allowlisted
endpoint under one timeout budget (covering the body read), then defensive
normalization into `{title,url,snippet,rank}`. Injectable `SearchDeps` fetch
seam. Status→typed-error classification.
- `src/auth.ts` — the inline credential channel (spec cor:web:020:02): the
three provider-agnostic shapes (bearer/basic/header) → one provider request
header. The zod schema + `buildAuthHeader`.
- `src/ops/index.ts` — the operation registry (`search`); one zod schema via
`defineOp`; contract-version check.
- `src/routes/` — `ops` (bearer-gated internal plane), `health` (open).
- `src/errors.ts` — the stable typed error catalog (the public code surface).
- Tests inject `SearchDeps` fakes — no network, no DNS in the suite.

## Key invariants

- **Stateless.** No database, no keys, no records. The provider credential
arrives inline per request (`auth`) — core sources it; the tool stores none.
A search is a GET-idempotent read, so retry is safe (unlike webfetch's non-GET
path), but the tool still holds nothing between calls.
- **All authorization happens in core.** Anonymous requests are allowed here by
design (behind the shared bearer); the policy chain (`tool.web_search`)
governs callers in core. Never add authorization logic to this tool.
- **Destinations are a fixed allowlist, never caller-supplied.** A request names
a provider *slug*; the tool resolves it to a hard-coded endpoint. This is why
there is NO SSRF guard and NO connection pinning here (spec cor:web:020:02) —
the caller-directed SSRF threat the fetch surface faces does not exist. The
query is a URL-encoded parameter to a fixed endpoint, never the destination.
**Never add a provider whose endpoint host is derived from request input.**
- **The normalized envelope is the contract.** Callers depend on
`{title,url,snippet,rank}` + `contractVersion` + `source:'external'` and NEVER
on which provider answered (spec cor:web:020:01). Adding a provider is
additive and must not change the envelope or leak provider identity into it.
- **Credentials never leak.** Not into logs (log codes/providers/statuses/counts
only — never the query), not into error bodies (zod messages don't echo
values), not into a URL (the `auth` header channel only). `authorization` and
`cookie` cannot be set through the `header` auth shape.
- **Provider output is untrusted** — malformed JSON or an unexpected shape
DEGRADES to an empty result list, never crashes; results are tagged
`source:'external'` so core's framing wraps them.
- **Agent-agnostic.** No agent names in `src/` (Constitution Invariant #14).

## The core contract (must stay in lockstep with hadron-server)

- Endpoint: `POST /ops/search`. Request `{version?, provider?, query, count?,
freshness?, locale?, providerOptions?, auth?}`; response `{ok, results,
contractVersion, source}`.
- Error body `{error:<code>, message, …}` with the catalog codes above — core's
`webSearchClient` passes `error` through as `extensions.webSearchErrorCode`.
- Contract version constant: `web-search@1` (`src/search.ts`). Bump additively;
a request naming an unsupported version is a `validation_error`.

## Use of Hadron

This tool has no memory of its own — work against the shared ones:

- `hrn:memory:hadronmemory.com::dev` — findings, conventions, the
capability-tool pattern (`capability-tool-pattern`), deploy runbook
- `hrn:memory:hadronmemory.com::specs` — product specs (`cor:web:020*` is the
web-search capability contract this tool implements)

Query Hadron before reading code/design (`hadron_find_nodes` → `hadron_get_node`),
and capture non-obvious findings as nodes the moment they emerge.
43 changes: 43 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# hadrontool-websearch — stateless web search capability tool.
#
# Built by Komodo from this repo's `main`, pushed to GHCR, deployed on the
# `komodo_default` network as an INTERNAL-ONLY service: no Traefik router, no
# public DNS. hadron-server reaches it by container name at
# http://hadrontool-websearch:8080. Secrets are injected at runtime by Doppler
# (`doppler run --`), matching the other services — Komodo sets only
# DOPPLER_TOKEN.

FROM node:22-slim

WORKDIR /app

# Doppler CLI for runtime secret injection (same pattern as the other services).
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates curl gnupg \
&& curl -sLf --retry 3 --tlsv1.2 --proto '=https' 'https://cli.doppler.com/install.sh' | sh \
&& apt-get purge -y curl gnupg && apt-get autoremove -y \
&& rm -rf /var/lib/apt/lists/*

ENV NODE_ENV=production \
PORT=8080

# Reproducible install from the committed lockfile, then compile and drop dev
# deps. --include=dev is required because NODE_ENV=production (set above)
# would otherwise make `npm ci` skip devDependencies (typescript/tsx) and the
# build would fail with `tsc: not found`.
#
# COPY every tsconfig the build references: `npm run build` runs
# `tsc -p tsconfig.build.json`, so that file must be in the image or the build
# fails with TS5058 (hadrontool-webfetch#3).
COPY package.json package-lock.json ./
RUN npm ci --include=dev
COPY tsconfig.json tsconfig.build.json ./
COPY src ./src
RUN npm run build && npm prune --omit=dev

RUN chown -R node:node /app
USER node

EXPOSE 8080
# Doppler injects WEBSEARCH_TOOL_TOKEN / NODE_ENV / PORT via DOPPLER_TOKEN.
CMD ["doppler", "run", "--", "node", "dist/index.js"]
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Hadron Memory

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
85 changes: 85 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# hadrontool-websearch

Stateless web **search** capability tool for the
[Hadron Memory](https://hadronmemory.com/) platform. It gives headless LLM runs
a governed way to query an external search provider and get back a ranked list
of result references (title, URL, snippet) — behind a fixed provider allowlist,
with the provider credential supplied inline per request.

Design and decisions: hadron-server#647 (core-side spine merged in
hadron-server#648). This is a *separate* capability from
[`hadrontool-webfetch`](https://github.com/hadron-memory/hadrontool-webfetch),
delivered by a *separate* stateless tool — not a mode of fetch. It is the
reference implementation of the versioned, provider-agnostic **`web-search@1`**
contract (platform specs `cor:web:020*`), so a conforming third-party tool can
be swapped in with no caller change. **All authorization happens in
hadron-server** before a request reaches this service.

## Operation

`POST /ops/search` (bearer-gated, JSON in/out).

**Request** — the normalized contract (`cor:web:020:01`):

```jsonc
{
"version": "web-search@1", // optional; rejected if not what this tool speaks
"provider": "brave", // optional; a slug from the allowlist (default: brave)
"query": "red pandas", // required
"count": 10, // optional; clamped to the tool/provider maximum
"freshness": "week", // optional: day | week | month | year
"locale": "en-US", // optional
"providerOptions": {}, // optional, opaque; unknown keys safely ignored
"auth": { "type": "header", "name": "X-Subscription-Token", "value": "…" }
}
```

**Response**:

```jsonc
{
"ok": true,
"results": [{ "title": "…", "url": "https://…", "snippet": "…", "rank": 1 }],
"contractVersion": "web-search@1",
"source": "external" // results are untrusted external input
}
```

Errors use a stable typed catalog (passed through by hadron-server's
`webSearchClient` as `extensions.webSearchErrorCode`): `validation_error`,
`provider_not_configured`, `provider_unauthorized`, `provider_rejected`,
`provider_rate_limited`, `upstream_unreachable`, `upstream_timeout`.

Also: `GET /healthz`, `GET /readyz` (open), `GET /info` (bearer).

## Providers

The allowlist lives in [`src/providers.ts`](src/providers.ts) — one adapter per
provider (endpoint + param mapping + response normalization). Ships with
`brave` (default) and `bing`. A request names a provider *slug*, never a URL:
the destination is always one of these fixed constants, which is why this
surface needs no SSRF guard or connection pinning (spec `cor:web:020:02`). The
provider API key is **not** stored here — hadron-server sources it and passes it
inline via `auth`.

## Commands

```bash
npm run dev # tsx watch (port 8080)
npm test # vitest — real HTTP via supertest over a FAKE fetch seam
npm run typecheck
npm run build # tsc -p tsconfig.build.json → dist/
```

No database, no keys at rest, nothing to set up.

## Configuration

| Var | Required | Purpose |
| --- | --- | --- |
| `WEBSEARCH_TOOL_TOKEN` | prod | Shared bearer for the internal `/ops` plane. Boot refuses to start without it when `NODE_ENV=production`. |
| `PORT` | no | Listen port (default 8080). |
| `NODE_ENV` | no | `production` enables the bearer requirement. |

Provider selection and the provider API key are **core-sourced** and travel in
the request body (`provider` + `auth`); they are not tool configuration.
Loading
Loading