# Tool Generation Flow

The end-to-end decision and build loop Agenvoy runs when a request requires a capability not covered by existing tools.

## Flow

```mermaid
graph TB
    Start[Request needs external data or missing capability] --> Guide[read_guides tool_generate]
    Guide --> SearchAPI[read_public_apis category on up to 3 categories]
    SearchAPI -->|Keyless public API fits| Docs[fetch_page API docs URL]
    Docs --> CallHTTP[http_request directly to answer<br/>no tool saved]
    SearchAPI -->|No public API fits / API needs key / Python logic| KeyCheck{Needs API key?}
    KeyCheck -->|Yes| Secret[store_secret BRAND_API_KEY<br/>read inside script via get_key]
    KeyCheck -->|No| WriteTool
    Secret --> WriteTool[write_tool mode=write tag=json + tag=script<br/>Automatic validation on every write/patch]
    WriteTool -->|Validation error| PatchVal[Fix via write_tool mode=patch]
    PatchVal --> WriteTool
    WriteTool -->|Valid| TestScript[test_script with sample stdin JSON<br/>Sandbox execution, 60s timeout]
    TestScript -->|Failed, up to 3 retries| PatchRun[Fix via write_tool mode=patch]
    PatchRun --> TestScript
    TestScript -->|Passed| Invoke[Call script_name to answer]
    SearchAPI -->|No API and no Python route| Fallback[Fallback: search_web / fetch_page<br/>Name the data source]
```

## Step-by-step sequence

1. **Load the build contract** — Call `read_guides(topics=["tool_generate"])` before acting.
2. **Prefer keyless public APIs** — Inspect up to 3 relevant categories via `read_public_apis(category)`. If a keyless HTTPS API fits, read its docs with `fetch_page` and call it directly with `http_request` without creating a persistent tool.
3. **Build a script tool only when needed** — Create a persistent tool under `~/.config/agenvoy/tools/script/<name>/` only when the capability is not covered by the public API list (e.g., a user-supplied API requiring a key via `store_secret`, or Python computation). Call `write_tool(mode=write)` for both `tag=json` (`tool.json`) and `tag=script` (`script.py`); each `write` and `patch` runs `toolAdapter.Validate` automatically.
4. **Test in sandbox** — Run `test_script` with sample JSON on `stdin` (60 s cap). Fix any error with `write_tool(mode=patch)` and re-test (up to 3 retries).
5. **Answer** — Invoke the newly registered `script_<name>` tool and return the answer (or fall back to `search_web` / `fetch_page` with source attribution if neither an API nor Python can provide the data).

## Version history

- v1.6.3: Added the dedicated tool generation flow page, reflecting automatic `toolAdapter.Validate` checks on `write_tool` `write`/`patch` and sandbox verification via `test_script`.
