The open-source agent harness - the runtime layer that turns an LLM into a working agent.
Cleaned up repo and added documentation (#99)
Abhishek Choudharyec3c0c8a1a2b
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlnew file mode 100644index 000000000..183f03353--- /dev/null+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -0,0 +1,58 @@+name: Bug report+description: Something isn't working as expected+labels: ['bug']+body:+ - type: markdown+ attributes:+ value: |+ Thanks for taking the time to report a bug! Please do not report security vulnerabilities here — see [SECURITY.md](../../SECURITY.md).+ - type: textarea+ id: what-happened+ attributes:+ label: What happened?+ description: A clear description of the bug, including what you expected to happen instead.+ validations:+ required: true+ - type: textarea+ id: reproduce+ attributes:+ label: Steps to reproduce+ placeholder: |+ 1. Run `npx @truefoundry/trueforge`+ 2. Open Settings → ...+ 3. ...+ validations:+ required: true+ - type: dropdown+ id: deployment+ attributes:+ label: How are you running TrueForge?+ options:+ - npx (standalone / SQLite)+ - Docker Compose+ - Kubernetes (Helm)+ - From source+ - As a library (@truefoundry/trueforge-core)+ validations:+ required: true+ - type: input+ id: version+ attributes:+ label: Version+ placeholder: e.g. 0.2.0, or a commit SHA if running from source+ validations:+ required: true+ - type: textarea+ id: logs+ attributes:+ label: Relevant logs or screenshots+ description: Server logs, browser console output, or screenshots. Redact secrets.+ render: shell+ - type: textarea+ id: environment+ attributes:+ label: Environment+ placeholder: |+ OS:+ Node.js version:+ Browser (if UI-related):diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.ymlnew file mode 100644index 000000000..ed69bb01d--- /dev/null+++ b/.github/ISSUE_TEMPLATE/config.yml@@ -0,0 +1,9 @@+blank_issues_enabled: true+contact_links:+ # TODO: replace placeholder URLs+ - name: Documentation+ url: https://example.com/docs+ about: Guides, configuration reference, and API docs.+ - name: Security vulnerability+ url: https://example.com/security+ about: Please report security issues privately — see SECURITY.md.diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.ymlnew file mode 100644index 000000000..b1ecfe31b--- /dev/null+++ b/.github/ISSUE_TEMPLATE/feature_request.yml@@ -0,0 +1,28 @@+name: Feature request+description: Suggest an idea or improvement+labels: ['enhancement']+body:+ - type: textarea+ id: problem+ attributes:+ label: What problem are you trying to solve?+ description: Describe the use case or pain point, not only the solution you have in mind.+ validations:+ required: true+ - type: textarea+ id: solution+ attributes:+ label: Proposed solution+ description: What would you like to happen?+ validations:+ required: true+ - type: textarea+ id: alternatives+ attributes:+ label: Alternatives considered+ description: Any workarounds or alternative designs you've thought about.+ - type: textarea+ id: context+ attributes:+ label: Additional context+ description: Anything else that helps — links, sketches, related issues.diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.mdnew file mode 100644index 000000000..7dd04a06e--- /dev/null+++ b/.github/PULL_REQUEST_TEMPLATE.md@@ -0,0 +1,20 @@+## Summary++<!-- What does this PR change, and why? Link the related issue if there is one. -->++Closes #++## Changes++-++## How was this tested?++<!-- e.g. unit tests added, `pnpm test`, `pnpm smoke`, manual steps in the UI -->++## Checklist++- [ ] `pnpm build`, `pnpm test`, `pnpm typecheck`, `pnpm lint:ci`, and `pnpm format:check` pass locally+- [ ] Tests added/updated where it makes sense+- [ ] No hand-edits to generated code (`packages/sdk`, `fern/openapi/openapi.json`)+- [ ] Docs / `.env.example` updated if configuration or behavior changeddiff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.mdnew file mode 100644index 000000000..d9fb871ac--- /dev/null+++ b/CODE_OF_CONDUCT.md@@ -0,0 +1,77 @@+# Contributor Covenant Code of Conduct++## Our Pledge++We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.++We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.++## Our Standards++Examples of behavior that contributes to a positive environment for our community include:++- Demonstrating empathy and kindness toward other people+- Being respectful of differing opinions, viewpoints, and experiences+- Giving and gracefully accepting constructive feedback+- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience+- Focusing on what is best not just for us as individuals, but for the overall community++Examples of unacceptable behavior include:++- The use of sexualized language or imagery, and sexual attention or advances of any kind+- Trolling, insulting or derogatory comments, and personal or political attacks+- Public or private harassment+- Publishing others' private information, such as a physical or email address, without their explicit permission+- Other conduct which could reasonably be considered inappropriate in a professional setting++## Enforcement Responsibilities++Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.++Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.++## Scope++This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event.++## Enforcement++Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at <!-- TODO: confirm contact --> **[email protected]**. All complaints will be reviewed and investigated promptly and fairly.++All community leaders are obligated to respect the privacy and security of the reporter of any incident.++## Enforcement Guidelines++Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:++### 1. Correction++**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.++**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.++### 2. Warning++**Community Impact**: A violation through a single incident or series of actions.++**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.++### 3. Temporary Ban++**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.++**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.++### 4. Permanent Ban++**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.++**Consequence**: A permanent ban from any sort of public interaction within the community.++## Attribution++This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html](https://www.contributor-covenant.org/version/2/1/code_of_conduct.html).++Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).++For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq](https://www.contributor-covenant.org/faq). Translations are available at [https://www.contributor-covenant.org/translations](https://www.contributor-covenant.org/translations).diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 000000000..630b090cf--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,214 @@+# Contributing to TrueForge++Thanks for your interest in contributing! This document covers how to set up a development environment, run the test suites, and get a pull request merged.++By participating you agree to follow our [Code of Conduct](CODE_OF_CONDUCT.md). By contributing you agree that your contributions are licensed under the [MIT License](LICENSE).++## Ways to contribute++- **Report bugs** — open an issue with steps to reproduce, expected vs actual behavior, and your environment.+- **Suggest features** — open an issue describing the problem you're trying to solve, not only the solution.+- **Improve docs** — typo fixes and clarifications are always welcome.+- **Fix bugs / build features** — for anything non-trivial, please open an issue first so we can discuss the approach before you invest time.++For security vulnerabilities, do **not** open a public issue — see [SECURITY.md](SECURITY.md).++## Prerequisites++- **Node.js 22.13+** (see [`.nvmrc`](.nvmrc))+- **pnpm** (version pinned via `packageManager` in [`package.json`](package.json); `corepack enable` handles it)+- **Docker** — only needed for Postgres/Redis dev infra, the smoke test, and SDK generation++## Repository layout++This is a pnpm workspace:++| Workspace package | Published as | Path | What it is |+| --------------------------- | ----------------------------- | -------------------------------------------------------- | -------------------------------------------- |+| `@truefoundry/utils` | `@truefoundry/trueforge` | [`packages/server`](packages/server) | Agent server + bundled UI |+| `@truefoundry/utils-core` | `@truefoundry/trueforge-core` | [`packages/harness`](packages/harness) | Library: agent core, sessions, and streaming |+| `@truefoundry/trueforge-ui` | `@truefoundry/trueforge-ui` | [`packages/trueforge-ui-sdk`](packages/trueforge-ui-sdk) | Embeddable agent chat UI SDK |+| `trueforge` | `@truefoundry/trueforge-sdk` | [`packages/sdk`](packages/sdk) | Generated TypeScript API client |+| `frontend` | — | [`packages/frontend`](packages/frontend) | Chat UI app (bundled into the server) |++> Note: some workspace package and folder names (`utils`, `harness`) predate the public release names and will be renamed.++## Setup++```bash+pnpm install+cp packages/server/.env.example packages/server/.env+```++## Running from source++There are two dev topologies. Both serve the UI on [http://localhost:3000](http://localhost:3000) (Vite, with live reload, proxying `/api/*`) and the API on [http://localhost:8790](http://localhost:8790).++### Standalone (zero infra)++SQLite only — good for most day-to-day development:++```bash+pnpm standalone:dev+```++### Multi-replica (Postgres + Redis)++Use this when working on anything involving Postgres storage or Redis peering (cross-replica turn cancels and stream handoff).++Terminal 1 — start Postgres (`:5432`) and Redis (`:6379`):++```bash+pnpm dev:infra+```++Terminal 2:++```bash+pnpm dev+```++| | Standalone | Multi-replica |+| --------- | -------------------------------------- | ----------------------------------------------- |+| Process | One server | One or more replicas with Redis peering |+| Database | SQLite | Postgres |+| Infra | None | Postgres + Redis (`pnpm dev:infra` or your own) |+| Dev | `pnpm standalone:dev` | `pnpm dev` (after infra) |+| Prod-like | `pnpm build` → `pnpm standalone:start` | `pnpm build` → `pnpm start` |++Local server scripts resolve `@truefoundry/utils-core` from source, so you do not need a utils-core `dist/` build for `pnpm dev` / `standalone:dev`. Frontend scripts build `@truefoundry/trueforge-ui` `dist/` before Vite starts (workspace package exports point at `dist/`).++### How the UI is served++Dev and production-like runs use different process topologies. Standalone vs multi-replica only changes storage/peering (`STANDALONE`); it does not change how the UI is served.++**Development** — `pnpm standalone:dev` / `pnpm dev` run two processes in parallel: Vite (UI, with live reload) and the Hono API. The browser talks to Vite; Vite proxies `/api/*` to Hono.++```+ browser Vite (:3000) Hono (:8790)+ │ │ │+ │ GET / (UI) │ │+ │────────────────────────────>│ │+ │ │ │+ │ /api/* │ proxy │+ │────────────────────────────>│─────────────────────────────>│+```++**Production-like** — after `pnpm build`, `pnpm standalone:start` / `pnpm start` run a single Hono process. It serves the built frontend bundle for non-API routes and handles `/api/*` itself. The Docker container works the same way: one process, one origin.++```+ browser Hono (:8790)+ │ │+ │ GET / (static UI from dist/_frontend) │+ │───────────────────────────────────────────>│+ │ │+ │ /api/* │+ │───────────────────────────────────────────>│+```++On one origin (start / Docker): `/api/*` (including OpenAPI) and `/healthz` are the API; everything else is the UI. The server prefers a packaged `dist/_frontend`, then `packages/frontend/dist`. With no UI build present it serves the API only (normal for Vite-backed `pnpm dev`).++### Configuration++See [`packages/server/.env.example`](packages/server/.env.example) for every env var. Useful dev overrides:++- `PORT` — API port (default `8790`)+- `FRONTEND_PORT` — Vite UI port in dev (default `3000`); see [`packages/frontend/README.md`](packages/frontend/README.md)+- `VITE_SERVER_URL` — point the Vite proxy at a different API+- `FRONTEND_DIR` — directory of a built UI for the server to serve+- `SQLITE_PATH` — SQLite file location in standalone mode+- `REDIS_URL` / `POSTGRES_*` — used when `STANDALONE=false`++### Migrations++Migrations run on server startup. To run Postgres migrations without starting HTTP:++```bash+pnpm --filter @truefoundry/utils migrate+```++That script sets `STANDALONE=false` and uses `POSTGRES_*` from `packages/server/.env`. It will not run in standalone mode (SQLite migrations happen on boot instead).++## Workspace scripts++Workspace tasks go through `package.json` scripts — if a repeatable workflow is missing, add a script rather than documenting an ad hoc command.++| Script | Purpose |+| ---------------------------------------------------- | ----------------------------------------------------- |+| `pnpm standalone:dev` / `pnpm dev` | Local UI + API (see modes above) |+| `pnpm standalone:dev:no-watch` / `pnpm dev:no-watch` | Same, but the server does not restart on file changes |+| `pnpm dev:server:ui` | Packed UI + watched API (no Vite) |+| `pnpm build` | Build all packages |+| `pnpm test` / `pnpm typecheck` | Workspace checks |+| `pnpm lint` / `pnpm format` | ESLint (with fixes) / Prettier |+| `pnpm smoke` / `pnpm smoke:down` | Full Docker Compose stack + health check |+| `pnpm chart:lint` / `pnpm chart:template` | Validate the Helm chart |+| `pnpm clean` / `pnpm clean:all` | Remove build outputs (+ `node_modules` for `:all`) |++## Testing++```bash+pnpm test # unit tests across all packages+pnpm typecheck # TypeScript across all packages+pnpm lint # ESLint+pnpm format:check # Prettier+```++### Store contract tests++Storage-layer changes should pass both store suites (CI runs them when store paths change):++```bash+pnpm --dir packages/server test:store:sqlite+pnpm test:store:local # Postgres suite against local infra+```++### Smoke test (Docker)++Full stack in containers — the built server image serves API + UI, in multi-replica mode (`STANDALONE=false`):++```bash+pnpm smoke # build, wait for healthy services, check /healthz and UI+pnpm smoke:down+```++Open [http://localhost:8791](http://localhost:8791). Credentials come from `packages/server/.env`. Host ports are offset from local dev so they do not collide: Postgres `:5433`, Redis `:6380`, app `:8791`.++## Generated code — do not edit by hand++- [`packages/sdk`](packages/sdk) and [`fern/openapi/openapi.json`](fern/openapi/openapi.json) are generated by [Fern](https://buildwithfern.com) and committed. Edit route handlers under `packages/server/src/routes/` instead; CI regenerates the outputs. To regenerate locally (Docker required): `pnpm sdk:generate`.+- Catalog YAML files under `packages/server/src/catalog/` are inlined at build time by `build:gen` scripts.++## Server entry points++| File | Used by | Role |+| -------------- | --------------------------------------------- | ------------------------------------------- |+| `dist/main.js` | Docker, `pnpm start`, `pnpm standalone:start` | Env-only server boot |+| `dist/cli.js` | `npx @truefoundry/trueforge` | CLI (`--help`, `--port`), then loads `main` |++## Coding conventions++The repository-wide rules live in [`AGENTS.md`](AGENTS.md) (some packages have their own nested `AGENTS.md`). Highlights:++- No type-assertion escapes (`as T`, non-null `!`) to silence errors — fix the types.+- Wrap-and-rethrow must preserve the original error via `{ cause }`.+- Zod-backed types are derived with `z.infer<typeof Schema>`; don't duplicate schemas as interfaces.+- Static `import` / `import type` only — no `require()`.+- Tests live under a top-level `test`/`tests` directory mirroring `src`, never inline.+- Wire shapes (HTTP/OpenAPI) and database identifiers use `snake_case`.+- Server env reads go through `packages/server/src/config.ts`, never `process.env` directly.+- Remove dead code in the same change that makes it dead.++Prettier and ESLint run as pre-commit hooks via husky + lint-staged.++## Pull requests++1. Fork (or branch) and create a topic branch: `git checkout -b my-fix`.+2. Make your change, with tests where it makes sense.+3. Make sure `pnpm build`, `pnpm test`, `pnpm typecheck`, `pnpm lint:ci`, and `pnpm format:check` pass — CI runs exactly these.+4. Keep PRs focused and reasonably small; describe **what** changed and **why** in the description.+5. Open the PR. A maintainer will review it; squash-merge is the norm.++## Releases++Maintainers: see [RELEASING.md](RELEASING.md) for the npm, container image, and Helm chart release flows.diff --git a/LICENSE b/LICENSEnew file mode 100644index 000000000..d1e5f37a5--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2024-2026 TrueFoundry++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.diff --git a/README.md b/README.mdindex f59277c58..8812bbda5 100644--- a/README.md+++ b/README.md@@ -1,189 +1,173 @@# TrueForge-TrueForge is an open-source agent harness: the runtime layer that turns an LLM into a working agent. It runs the execution loop — model calls, tool use, context, and session state — and exposes the result as a chat UI, an HTTP API, and a TypeScript library.+**The open-source agent harness — the runtime layer that turns an LLM into a working agent.**-Out of the box you get multi-turn sessions with streaming, MCP tool servers (including OAuth), skills, sandboxed code execution, human-in-the-loop approvals, and subagents. Configure providers in the UI or via the settings APIs; run as a single process on SQLite, or scale out with Postgres and Redis.+TrueForge runs the agent execution loop for you — model calls, tool use, context management, and session state — and exposes the result three ways: a chat UI, an HTTP API, and a TypeScript library.-## Quick Start+[](LICENSE)+[](https://nodejs.org)-### Prerequisites+<!-- TODO: replace placeholder links below with real URLs -->-- Node.js 22.13+-- pnpm-- Docker (optional)+[Documentation](#) · [Quickstart Guide](#) · [API Reference](#) · [Community](#)-### Run the server+<!-- TODO: hero screenshot of the chat UI -->-```bash-cp packages/server/.env.example packages/server/.env-pnpm standalone:dev-```+-## Packages+## Why TrueForge?-> Note: Package and folder names will be renamed soon to match the release names below. They have been intentionally named "utils" to not leak before announcement.+Building an agent is easy. Running one in production is not — you need streaming, session persistence, tool servers, sandboxing, approvals, and a UI. TrueForge gives you all of that out of the box:-| Package | Release Name | Path | What it is |-| --------------------------- | ----------------------------- | -------------------------------------------------------- | ---------------------------------------------------- |-| `@truefoundry/utils` | `@truefoundry/trueforge` | [`packages/server`](packages/server) | Agent server + bundled UI |-| `@truefoundry/utils-core` | `@truefoundry/trueforge-core` | [`packages/harness`](packages/harness) | Library: agent core, sessions, and streaming |-| `@truefoundry/trueforge-ui` | — | [`packages/trueforge-ui-sdk`](packages/trueforge-ui-sdk) | Published agent chat UI SDK |-| `trueforge` | `@truefoundry/trueforge-sdk` | [`packages/sdk`](packages/sdk) | Generated TypeScript SDK |-| `frontend` | — | [`packages/frontend`](packages/frontend) | Chat UI (bundled into the server; uses trueforge-ui) |+- **Multi-turn sessions with streaming** — resumable turn streams that survive reconnects and server restarts.+- **MCP tool servers** — connect any [Model Context Protocol](https://modelcontextprotocol.io) server, including ones that require OAuth.+- **Any model provider** — OpenAI, Anthropic, Google, and OpenAI-compatible endpoints, configured from the UI or the API.+- **Skills** — reusable instruction packs the agent loads on demand.+- **Sandboxed code execution** — run agent-generated code in isolated sandboxes.+- **Human-in-the-loop approvals** — pause the agent and wait for a person before sensitive tool calls.+- **Subagents** — agents that delegate work to other agents.+- **Chat UI, HTTP API, and TypeScript library** — use whichever surface fits your product.-Requires **Node.js 22.13+** and **pnpm**.+It scales down and up: run it as a single process backed by SQLite, or run multiple replicas backed by Postgres and Redis.-## Run from source--```bash-pnpm install-cp packages/server/.env.example packages/server/.env-```+## Quick start-### Standalone (local, zero infra)+### Option 1: npx (fastest)-SQLite only — good for trying the product or single-process use.+Requires [Node.js](https://nodejs.org) 22.13 or newer. One command, no other infrastructure — data is stored in a local SQLite file:```bash-pnpm standalone:dev+npx @truefoundry/trueforge```-- UI (Vite): [http://localhost:3000](http://localhost:3000) — proxies `/api/*` to the API-- API: [http://localhost:8790](http://localhost:8790)+Then open [http://localhost:8790](http://localhost:8790), add a model provider under **Settings**, and start chatting.-### Multi-replica (Postgres + Redis)+| Configuration | Default | Description |+| ----------------- | -------------------------- | --------------------------------------------------------------- |+| `--port` / `PORT` | `8790` | HTTP port the server (UI + API) listens on. |+| `SQLITE_PATH` | OS data dir | Location of the SQLite database file. |+| `PUBLIC_BASE_URL` | `http://localhost:${PORT}` | Public origin, used for MCP OAuth callbacks. |+| `STANDALONE` | `true` | Keep `true` for single-process SQLite mode (the `npx` default). |-Use this when you need more than one server process (cancels and turn streams peer over Redis).+### Option 2: Docker Compose-Terminal 1 — start Postgres (`:5432`) and Redis (`:6379`):+Runs the full production topology on your machine: the server (UI + API), Postgres, and Redis.```bash-pnpm dev:infra+git clone <REPO_URL> trueforge && cd trueforge # TODO: repo URL+cp packages/server/.env.example packages/server/.env+docker compose up --build```-Terminal 2:+Then open [http://localhost:8791](http://localhost:8791).-```bash-pnpm dev-```+| Configuration | Default | Description |+| ----------------------------------------------------------- | ----------------------- | --------------------------------------------------------------------- |+| `POSTGRES_USER` / `POSTGRES_PASSWORD` / `POSTGRES_DB` | `harness` (from `.env`) | Postgres credentials, read from `packages/server/.env`. |+| `PUBLIC_BASE_URL` | `http://localhost:8791` | Public origin, used for MCP OAuth callbacks. |+| Host ports | `8791`, `5433`, `6380` | App, Postgres, and Redis — offset so they don't clash with local dev. |+| `OIDC_ISSUER_URL` / `OIDC_CLIENT_ID` / `OIDC_CLIENT_SECRET` | unset | Optional: connect an identity provider. Unset = local admin identity. |-- UI (Vite): [http://localhost:3000](http://localhost:3000) — proxies `/api/*` to the API-- API: [http://localhost:8790](http://localhost:8790)+Every environment variable is documented in [`packages/server/.env.example`](packages/server/.env.example).-| | Standalone | Multi-replica |-| --------- | -------------------------------------- | ----------------------------------------------- |-| Process | One server | One or more replicas with Redis peering |-| Database | SQLite | Postgres |-| Infra | None | Postgres + Redis (`pnpm dev:infra` or your own) |-| Dev | `pnpm standalone:dev` | `pnpm dev` (after infra) |-| Prod-like | `pnpm build` → `pnpm standalone:start` | `pnpm build` → `pnpm start` |+### Option 3: Kubernetes (Helm)-Migrations run on server startup. To run Postgres migrations without starting HTTP:+The [`charts/trueforge`](charts/trueforge) Helm chart deploys the server with bundled Postgres and Redis (or point it at your own):```bash-pnpm --filter @truefoundry/utils migrate+# TODO: replace <HELM_REPO> with the published Helm repo URL+helm install trueforge oci://<HELM_REPO>/trueforge \+ --version <x.y.z> \+ --set server.publicBaseUrl=https://trueforge.example.com```-That script sets `STANDALONE=false` and uses `POSTGRES_*` from `packages/server/.env`. It will not run in standalone mode (SQLite migrations happen on boot instead).--### Serving the UI from the server--Dev and production-like runs use different process topologies. Standalone vs multi-replica only changes storage/peering (`STANDALONE`); it does not change how the UI is served.+| Configuration | Default | Description |+| ---------------------- | ------------ | ----------------------------------------------------------------------------- |+| `server.publicBaseUrl` | — (required) | Public origin for MCP OAuth callbacks. |+| `replicaCount` | `1` | Number of server replicas (turn cancel/streaming peers over Redis). |+| `postgresql.enabled` | `true` | Bundle Postgres; set `false` and fill `externalPostgres.*` to bring your own. |+| `redis.enabled` | `true` | Bundle Redis; set `false` and set `externalRedis.url` to bring your own. |+| `autoscaling.enabled` | `false` | Enable a HorizontalPodAutoscaler. |-**Development** — `pnpm standalone:dev` / `pnpm dev` run two processes in parallel: Vite (UI, with live reload) and the Hono API. The browser talks to Vite; Vite proxies `/api/`* to Hono.+See the [chart README](charts/trueforge/README.md) for external databases, ingress via `extraObjects`, and the full values reference.-```- browser Vite (:3000) Hono (:8790)- │ │ │- │ GET / (UI) │ │- │────────────────────────────>│ │- │ │ │- │ /api/* │ proxy │- │────────────────────────────>│─────────────────────────────>│-```--**Production-like** — after `pnpm build`, `pnpm standalone:start` / `pnpm start` run a single Hono process. It serves the built frontend bundle for non-API routes and handles `/api/`* itself. The Docker container works the same way: one process, one origin.+## Getting started walkthrough-```- browser Hono (:8790)- │ │- │ GET / (static UI from dist/_frontend) │- │───────────────────────────────────────────>│- │ │- │ /api/* │- │───────────────────────────────────────────>│-```+<!-- TODO: replace with real screenshots -->-Open the UI on `:3000` in dev, or on the API port (`:8790`) when the server is serving the bundle.+1. **Add a model provider** — open **Settings → Model Providers**, pick a provider from the catalog, and paste your API key.-## Configuration+ -Model providers, MCP servers, skills, and sandboxes are configured in the UI under **Settings**, or via the settings APIs. Discovery presets come from the `*/catalog` endpoints. Interactive API docs are at `/api/v1/docs`.+2. **(Optional) Connect tools** — add MCP servers, skills, and a sandbox provider under **Settings**.-See `[packages/server/.env.example](packages/server/.env.example)` for every env var.+ -Useful overrides:+3. **Start a session** — create a chat and talk to your agent. Streaming, tool calls, and approvals all show up live in the UI.-- `PORT` — API port (default `8790`)-- `FRONTEND_PORT` — Vite UI port in dev (default `3000`); see `[packages/frontend/README.md](packages/frontend/README.md)`-- `VITE_SERVER_URL` — point the Vite proxy at a different API-- `FRONTEND_DIR` — directory of a built UI for the server to serve-- `SQLITE_PATH` — SQLite file location in standalone mode-- `REDIS_URL` / `POSTGRES_*` — used when `STANDALONE=false`+ -On one origin (start / Docker): `/api/*` (including OpenAPI) and `/healthz` are the API; everything else is the UI. The server prefers a packaged `dist/_frontend`, then `packages/frontend/dist`. With no UI build present it serves the API only (normal for Vite-backed `pnpm dev`). See [Serving the UI from the server](#serving-the-ui-from-the-server).+Interactive API docs are served by your running instance at `/api/v1/docs`. For everything else, see the [documentation](#). <!-- TODO: docs link -->-## Use as a library+## Components-```ts-import { AgentThread } from '@truefoundry/utils-core/core';-import { Sessions } from '@truefoundry/utils-core/agent-session';-```+TrueForge is a single container image (or `npx` process) plus a database — and Redis when you run more than one replica.-Or namespaced:+```mermaid+flowchart LR+ browser([Browser])+ subgraph server [TrueForge server]+ ui[Chat UI]+ api[HTTP API]+ end+ db[(Postgres or SQLite)]+ redis[(Redis)]+ llm[Model providers]+ mcp[MCP servers]+ sandbox[Sandboxes]-```ts-import { core, agentSession } from '@truefoundry/utils-core';+ browser --> ui+ browser --> api+ api --> db+ api <--> redis+ api --> llm+ api --> mcp+ api --> sandbox```-The published package supports both CommonJS and ESM. Server-only dependencies (Hono, SQLite, Postgres, Redis, etc.) stay in `@truefoundry/utils` and are not pulled in by library consumers.+| Component | What it does |+| --------------------- | --------------------------------------------------------------------------------------------------- |+| **UI** | React chat interface, bundled into the server image and served on the same port as the API. |+| **Backend** | Node.js (Hono) server: the agent execution loop, sessions, streaming, settings, and OpenAPI docs. |+| **Postgres / SQLite** | Session and settings storage. SQLite in standalone mode; Postgres for multi-replica deployments. |+| **Redis** | Cross-replica peering (turn cancellation and stream handoff). Only needed when running > 1 replica. |-## Development+### Deployment modes-| Script | Purpose |-| ---------------------------------------------------- | ----------------------------------------------------- |-| `pnpm standalone:dev` / `pnpm dev` | Local UI + API (see modes above) |-| `pnpm standalone:dev:no-watch` / `pnpm dev:no-watch` | Same, but the server does not restart on file changes |-| `pnpm dev:server:ui` | Packed UI + watched API (no Vite) |-| `pnpm build` | Build all packages |-| `pnpm test` / `pnpm typecheck` | Workspace checks |-| `pnpm smoke` / `pnpm smoke:down` | Full Docker Compose stack |-| `pnpm clean` / `pnpm clean:all` | Remove build outputs (+ `node_modules` for `:all`) |+| | Standalone | Multi-replica |+| ----------- | -------------------------------- | ------------------------------------ |+| Best for | Trying it out, single-user, edge | Production, teams, high availability |+| Processes | One | One or more, peered over Redis |+| Database | SQLite | Postgres |+| Extra infra | None | Postgres + Redis |+| How to run | `npx @truefoundry/trueforge` | Docker Compose or the Helm chart |-Local server scripts resolve `@truefoundry/utils-core` from source, so you do not need a utils-core `dist/` build for `pnpm dev` / `standalone:dev`. Frontend scripts build `@truefoundry/trueforge-ui` `dist/` before Vite starts (workspace package exports point at `dist/`).+## Documentation-### Smoke test (Docker)+<!-- TODO: replace placeholder links with real URLs -->-Full stack in containers — built server image serves API + UI. Forces multi-replica mode (`STANDALONE=false`):+- [Introduction](#)+- [Quickstart](#)+- [Configuration reference](#)+- [API reference](#)+- [Deploying to Kubernetes](#)-```bash-pnpm smoke # build, wait for healthy services, check /healthz and UI-pnpm smoke:down-```--Open [http://localhost:8791](http://localhost:8791). Credentials come from `packages/server/.env`. Host ports differ from local dev so they do not collide: Postgres `:5433`, Redis `:6380`, app `:8791`.+## Contributing-### Entry points+We love contributions! Whether it's a bug report, a new feature, or a docs fix — see [CONTRIBUTING.md](CONTRIBUTING.md) for how to set up a development environment and open a pull request. Please also read our [Code of Conduct](CODE_OF_CONDUCT.md).-| File | Used by | Role |-| -------------- | --------------------------------------------- | ------------------------------------------- |-| `dist/main.js` | Docker, `pnpm start`, `pnpm standalone:start` | Env-only server boot |-| `dist/cli.js` | `npx @truefoundry/trueforge` | CLI (`--help`, `--port`), then loads `main` |+To report a security vulnerability, please follow [SECURITY.md](SECURITY.md) instead of opening a public issue.-### Generated SDK and OpenAPI+## License-`packages/sdk` and `fern/openapi/openapi.json` are generated by [Fern](https://buildwithfern.com) and committed. Edit route handlers under `packages/server/src/routes/`, not the generated output. CI regenerates them; to run locally (Docker required):--```bash-pnpm sdk:generate-```+TrueForge is released under the [MIT License](LICENSE).diff --git a/RELEASING.md b/RELEASING.mdindex c77313bc4..cd5f2ea19 100644--- a/RELEASING.md+++ b/RELEASING.md@@ -136,16 +136,18 @@ Publish a real version when CI or teammates need it.## Deferred to the real OSS release — grep for `TODO(oss)`+Done: root LICENSE + MIT license fields, CONTRIBUTING, SECURITY,+CODE_OF_CONDUCT, issue/PR templates.+| Item | Where || ------------------------------------------------------------------------------- | ------------------------------------------------------- |-| License: UNLICENSED → Apache-2.0 + LICENSE file | both package.jsons, repo root || Ship README (guard lives in make-dist-package-json.mjs) | packages/harness/scripts || Add repository/homepage/bugs/keywords metadata | packages/harness/package.json || Add `--provenance` to publish | .github/workflows/release.yml || Replace `internal.devtest.truefoundry.tech` URLs | packages/server/src/config || Private-repo links in shipped sandbox scripts | packages/harness/src/core/sandbox/scripts/mcp_client.py || Sourcemaps/declarationMap decision | packages/harness/tsup.config.ts, tsconfig.build.json |-| CONTRIBUTING / SECURITY / CODE_OF_CONDUCT / CODEOWNERS / CI for external PRs | .github/ |+| CODEOWNERS / CI for external (fork) PRs | .github/ || Secret-scan history, enable secret scanning + push protection, flip repo public | GitHub settings |---diff --git a/SECURITY.md b/SECURITY.mdnew file mode 100644index 000000000..98601dbf0--- /dev/null+++ b/SECURITY.md@@ -0,0 +1,29 @@+# Security Policy++## Reporting a vulnerability++Please do **not** report security vulnerabilities through public GitHub issues, discussions, or pull requests.++Instead, report them privately through one of these channels:++<!-- TODO: confirm the security contact email and enable GitHub private vulnerability reporting -->++- Email: **[email protected]**+- GitHub: use [private vulnerability reporting](#) on this repository++Please include as much of the following as you can:++- A description of the vulnerability and its impact+- Steps to reproduce, or a proof of concept+- Affected versions or deployment modes (standalone / multi-replica / Helm)+- Any suggested mitigations++## What to expect++- We will acknowledge your report within **3 business days**.+- We will keep you informed as we investigate and work on a fix.+- We will credit you in the release notes when the fix ships, unless you prefer to remain anonymous.++## Supported versions++Security fixes are applied to the latest release. We recommend always running the most recent version.diff --git a/docs/api/agent-spec.mdx b/docs/api/agent-spec.mdxnew file mode 100644index 000000000..a4bbd1351--- /dev/null+++ b/docs/api/agent-spec.mdx@@ -0,0 +1,122 @@+---+title: 'Agent Spec Reference'+sidebarTitle: 'Agent Spec'+description: 'Every field on the AgentSpec — model, instructions, MCP servers, skills, and runtime config.'+---++An `AgentSpec` is the complete definition of an agent. It is used inline when creating a session (`agent.type: "value"`) or saved as a named agent (`POST /api/v1/agents`) and referenced by id (`agent.type: "ref"`). All fields are `snake_case`.++```json A complete example+{+ "model": {+ "name": "anthropic/claude-sonnet-4-6",+ "params": { "max_tokens": 4096, "temperature": 0.2 }+ },+ "instructions": "You help customers with orders. Always confirm before processing refunds.",+ "mcp_servers": [+ {+ "name": "orders-api",+ "enable_tools": ["@all"],+ "require_approval_for_tools": ["process_refund"],+ "preload": false+ }+ ],+ "skills": [{ "name": "customer-support" }],+ "config": {+ "iteration_limit": 50,+ "sandbox": { "enabled": true },+ "dynamic_sub_agents": { "enabled": true },+ "ask_user_questions": { "enabled": true },+ "generative_ui": { "enabled": true },+ "context_management": {+ "compaction": { "enabled": true },+ "large_tool_response": { "enabled": true }+ }+ }+}+```++## `model`++The only required field.++| Field | Type | Required | Description |+| -------- | ------ | -------- | -------------------------------------------------------------------------- |+| `name` | string | Yes | Model FQN: `provider/model`, e.g. `openai/gpt-5.2`. See [Models](/models). |+| `params` | object | No | Model call parameters, passed through to the provider. |++`model.params` recognizes `max_tokens`, `temperature`, `top_p`, `top_k`, `parallel_tool_calls` (boolean), and `reasoning_effort` (string). Extra keys are allowed and forwarded to the provider as-is.++## `instructions`++Optional string. The agent's system prompt — its role, behavior, and constraints. The harness appends its own guidance for enabled capabilities (sandbox, subagents, etc.), so keep this focused on _your_ agent. See [context engineering best practices](/context-engineering/overview#best-practices).++## `messages`++Optional array of seed messages injected at the start of every session:++```json+{ "messages": [{ "type": "user.message", "content": "Introduce yourself briefly." }] }+```++## `mcp_servers`++Optional array. Each entry attaches a [configured MCP server](/mcp-servers) by name:++| Field | Default | Description |+| ---------------------------- | ---------------------------- | -------------------------------------------------------------------------------------------------------------- |+| `name` | — (required) | Name of a server registered under **Settings → MCP Servers**. |+| `enable_tools` | `["@all"]` | Tools exposed to the agent: `@all`, `@read-only`, or literal tool names. |+| `disable_tools` | `[]` | Tools subtracted from the enabled set. |+| `preload_tools` | `[]` | Tools loaded eagerly into context while the rest stay deferred. |+| `require_approval_for_tools` | `["@write", "@destructive"]` | Tools that pause for [human approval](/human-in-the-loop): `@all`, `@write`, `@destructive`, or literal names. |+| `preload` | `false` | Load all tool schemas upfront instead of [on demand](/context-engineering/deferred-tool-loading). |++The `@read-only`, `@write`, and `@destructive` selectors are resolved from the tool annotations published by the MCP server.++## `response_format`++Optional. Constrains the agent's final output: `{ "type": "text" }` (default), `{ "type": "json_object" }`, or `{ "type": "json_schema", "json_schema": { ... } }`.++## `skills`++Optional array of name-only references to [configured skills](/skills):++```json+{ "skills": [{ "name": "customer-support" }] }+```++Skill names may contain letters, numbers, `.`, `_`, and `-` (max 64 characters). Attaching skills requires `config.sandbox.enabled: true`.++## `config`++Runtime behavior. Every field has a default, so `config` can be omitted entirely.++| Field | Default | Description |+| -------------------- | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |+| `iteration_limit` | `100` | Max agent-loop iterations per turn (1–1024). A safety stop for runaway loops. |+| `sandbox` | `{ "enabled": false }` | [Sandbox](/sandbox) for code execution, files, and skills. |+| `dynamic_sub_agents` | `{ "enabled": true }` | [Subagents](/context-engineering/subagents). |+| `context_management` | all enabled | [Compaction](/context-engineering/overview#context-compaction) and [large tool response offloading](/context-engineering/large-tool-responses). |+| `generative_ui` | `{ "enabled": true }` | [Generative UI](/generative-ui) (OpenUI blocks). |+| `ask_user_questions` | `{ "enabled": true }` | The [`ask_user_question`](/ask-user-questions) tool. |++### `config.sandbox`++| Field | Default | Description |+| ---------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `enabled` | `false` | Give the agent a sandbox. Required for skills and Code Mode. |+| `file_downloads` | `true` | Allow downloading agent-produced files via the turn download endpoint. |+| `network_policy.auth_inject` | — | Up to one rule injecting git basic-auth credentials for exact hosts: `{ "type": "git", "match": { "hosts": ["github.com"] }, "auth_data": { "type": "basic", "username": "...", "password": "..." } }`. |++### `config.context_management`++| Field | Default | Description |+| ---------------------------------------- | ------- | ----------------------------------------------------- |+| `compaction.enabled` | `true` | Summarize older history when context grows too large. |+| `compaction.compaction_threshold_tokens` | `50000` | Context size (tokens) that triggers compaction. |+| `large_tool_response.enabled` | `true` | Offload oversized tool responses to a sandbox file. |++## `variables`++Optional map of string key–value pairs stored on the spec, reserved for parameterizing agent definitions.diff --git a/docs/api/overview.mdx b/docs/api/overview.mdxnew file mode 100644index 000000000..d21e11ab0--- /dev/null+++ b/docs/api/overview.mdx@@ -0,0 +1,190 @@+---+title: 'Using the API'+sidebarTitle: 'Overview'+description: 'Create sessions, run turns, and stream events — the concepts and the full REST lifecycle with examples.'+---++Everything the chat UI does goes through the HTTP API, so anything you can do in the UI you can automate. The API is served under `/api/v1`, documented interactively at `/api/v1/docs` (OpenAPI 3.1 at `/api/v1/openapi.json`). A generated TypeScript client, `@truefoundry/trueforge-sdk`, wraps the same API.++## Core concepts++Interaction with an agent follows a strict hierarchy: **one Agent → many Sessions → many Turns → many Events → some Deltas.**++### Agent++An **agent** is a definition — model, instructions, MCP servers, skills, and runtime config — described by an [AgentSpec](/api/agent-spec). You can save agents by name (`POST /api/v1/agents`) and reference them across sessions, or pass an inline spec when creating a session.++### Session++A **session** is one conversation. All turns in a session chain together, so the agent remembers what happened earlier. Each independent conversation — a different user, a different issue — gets its own session. Only one turn runs in a session at a time.++### Turn++A **turn** is one request boundary: a user message, an approval decision, or an answer to an agent's question. Turns chain automatically — a new turn sees everything from the previous turns in the session.++### Event++While a turn runs, the server streams **events** over Server-Sent Events (SSE): model output, tool responses, subagent lifecycle, approval requests. Every stream opens with `turn.created` and closes with `turn.done`. See the [turn events reference](/api/turn-events).++### Delta++Model output streams token by token: a base `model.message` event arrives first (empty), then `model.message.delta` fragments that share its `id`. Merge deltas into the base event to render text as it is generated. When you list events after the fact, you get one pre-merged `model.message` — no deltas on replay.++## The lifecycle, end to end++### 1. Create a session++Pass an inline agent spec (`type: "value"`), or reference a saved agent by id (`type: "ref"`):++```bash+curl -X POST http://localhost:8790/api/v1/sessions \+ -H 'Content-Type: application/json' \+ -d '{+ "agent": {+ "type": "value",+ "agent_spec": {+ "model": { "name": "anthropic/claude-sonnet-4-6" },+ "instructions": "You help customers with orders. Always confirm before processing refunds.",+ "mcp_servers": [+ { "name": "orders-api", "require_approval_for_tools": ["process_refund"] }+ ]+ }+ }+ }'+```++```json Response+{+ "data": {+ "id": "sess-7f2a9c1b",+ "agent": { "type": "value", "agent_spec": { ... } },+ "title": null,+ "created_by": "trueforge-default",+ "created_at": "2026-06-24T10:00:00Z",+ "updated_at": "2026-06-24T10:00:00Z"+ }+}+```++Persist the session `id` — the user can return tomorrow and pick up where they left off.++### 2. Run a turn and stream events++```bash+curl -N -X POST http://localhost:8790/api/v1/sessions/sess-7f2a9c1b/turns \+ -H 'Content-Type: application/json' \+ -d '{+ "input": [+ { "type": "user.message", "content": "What is the status of order ORD-2031?" }+ ]+ }'+```++The response is an SSE stream:++| # | Event | What your app learns |+| --- | ------------------------ | ------------------------------------------------------- |+| 1 | `turn.created` | Turn started — carries `turn_id` and `previous_turn_id` |+| 2 | `mcp.initialize` | Agent connected to `orders-api` |+| 3 | `model.message` + deltas | Agent decided to call `get_order` |+| 4 | `tool.response` | Order data: shipped, $1,240.00 |+| 5 | `model.message` + deltas | Reply streaming in, token by token |+| 6 | `turn.done` | Turn finished — final reply in `state.output` |++The `input` field accepts three item types:++| `type` | Purpose |+| -------------------- | ------------------------------------------------------------------------------------------- |+| `user.message` | A message. `content` is a string or an array of `text` / `file` parts (files as data URIs). |+| `user.tool_approval` | An [approval decision](/human-in-the-loop) for a paused tool call. |+| `user.tool_response` | An [answer](/ask-user-questions) for a paused client-side tool call. |++A single turn cannot mix `user.message` items with approval or tool-response items.++### 3. Chain the next turn++`previous_turn_id` defaults to `"auto"`, which chains to the session's last turn — you never resend history:++```bash+curl -N -X POST http://localhost:8790/api/v1/sessions/sess-7f2a9c1b/turns \+ -H 'Content-Type: application/json' \+ -d '{+ "input": [{ "type": "user.message", "content": "Please issue a full refund for that order." }]+ }'+```++Use `"previous_turn_id": "none"` to start a fresh root turn in the same session, or pass an explicit turn id to branch from a specific point.++### 4. Handle a pause (approvals and questions)++`process_refund` requires approval, so this turn ends paused: the stream carries `tool.approval_required`, and `turn.done` arrives with `state.output: null` and the pending action in `state.required_actions`:++```json turn.done (paused)+{+ "type": "turn.done",+ "state": {+ "status": "done",+ "output": null,+ "required_actions": [+ {+ "type": "tool.approval_required",+ "thread_id": "main",+ "tool_calls": [{ "id": "call-refund-01", "source_event_id": "msg-b2" }]+ }+ ]+ }+}+```++Resume with a new turn carrying the decision:++```bash+curl -N -X POST http://localhost:8790/api/v1/sessions/sess-7f2a9c1b/turns \+ -H 'Content-Type: application/json' \+ -d '{+ "input": [{+ "type": "user.tool_approval",+ "thread_id": "main",+ "tool_call_id": "call-refund-01",+ "approval": { "status": "allow" }+ }]+ }'+```++The same pattern applies to [`tool.response_required`](/ask-user-questions) (resume with `user.tool_response`) and [`mcp.auth_required`](/mcp-servers#in-chat-authentication) (resume after the user completes OAuth).++## Non-streaming, reconnects, and cancellation++**Fire and poll.** Pass `"stream": false` to `POST .../turns` to get the running turn back immediately, then poll `GET .../turns/{turn_id}` until `state.status` is terminal.++**Reconnect to a live turn.** If your SSE connection drops, resume from where you left off:++```text+GET /api/v1/sessions/{session_id}/turns/{turn_id}/subscribe?after_sequence_number=N+```++**Cancel.** `POST /api/v1/sessions/{session_id}/cancel` cancels the session's running turn. The stream ends with `turn.done` and `state.status: "cancelled"`.++**Replay history.** `GET .../sessions/{session_id}/events` lists the persisted event timeline (deltas pre-merged), which is how the chat UI restores a conversation.++## Endpoint summary++| Method | Path | Purpose |+| -------------- | ------------------------------------------------- | -------------------------------------------------------------------------------- |+| `POST` | `/api/v1/sessions` | Create a session |+| `GET` | `/api/v1/sessions` | List sessions |+| `GET` | `/api/v1/sessions/{id}` | Get a session |+| `DELETE` | `/api/v1/sessions/{id}` | Delete a session and its turns/events |+| `POST` | `/api/v1/sessions/{id}/cancel` | Cancel the running turn |+| `GET` | `/api/v1/sessions/{id}/events` | List the session's event timeline |+| `POST` | `/api/v1/sessions/{id}/turns` | Create and execute a turn (SSE by default) |+| `GET` | `/api/v1/sessions/{id}/turns/{turn_id}` | Get a turn and its state |+| `GET` | `/api/v1/sessions/{id}/turns/{turn_id}/events` | List a turn's events |+| `GET` | `/api/v1/sessions/{id}/turns/{turn_id}/subscribe` | Reconnect to a live turn's stream |+| `GET` | `/api/v1/sessions/{id}/turns/{turn_id}/download` | Download a sandbox file |+| `POST` / `GET` | `/api/v1/agents` | Save / list named agents |+| `GET` / `PUT` | `/api/v1/settings/...` | Model providers, MCP servers, skills, sandbox providers (each with a `/catalog`) |+| `GET` | `/api/v1/models` | All models across configured providers |+| `GET` | `/api/v1/capabilities` | Which optional capabilities are configured |++The complete request/response schemas are in the interactive docs at `/api/v1/docs` on your running instance.diff --git a/docs/api/turn-events.mdx b/docs/api/turn-events.mdxnew file mode 100644index 000000000..dd5415640--- /dev/null+++ b/docs/api/turn-events.mdx@@ -0,0 +1,152 @@+---+title: 'Turn Events Reference'+sidebarTitle: 'Turn Events'+description: 'Every event type streamed while a turn runs — lifecycle, model output, tool activity, subagent threads, and pause events.'+---++While a turn runs, the server streams events as Server-Sent Events (SSE). Each SSE message's `data` is one JSON event; the SSE `id` field carries the per-stream **sequence number**, which you can pass back (as a `Last-Event-Id` header or the `after_sequence_number` query parameter) to the [subscribe endpoint](/api/overview#non-streaming-reconnects-and-cancellation) to resume after a disconnect.++Every event carries:++| Field | Description |+| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `type` | The event type — one of the types below. |+| `id` | Unique event id (monotonic ULID — sortable by creation order). |+| `created_at` | ISO 8601 timestamp. |+| `thread_id` | Which execution thread emitted it: `"main"` for the root agent, a generated id for [subagents](/context-engineering/subagents), or `null` for run-level events (`turn.*`, `sandbox.created`, `mcp.auth_required`). |++A stream always opens with `turn.created` and closes with `turn.done`. When you list persisted events afterwards (`GET .../events`), you get the same events with deltas pre-merged into their `model.message`.++## Lifecycle events++### `turn.created`++First event on every stream.++| Field | Description |+| ------------------ | --------------------------------------------------------- |+| `turn_id` | Id of this turn. |+| `previous_turn_id` | The turn this one chains from, or `null` for a root turn. |+| `input` | The turn's input items, echoed back. |+| `state` | `{ "status": "running" }` |++### `turn.done`++Last event on every stream. `state.status` is one of:++- **`done`** — carries `output` (the final `model.message`, or `null` when the turn ended paused), `required_actions` (pending `tool.approval_required` / `tool.response_required` / `mcp.auth_required` events, empty when none), `completed_at`, and optional `metrics`.+- **`cancelled`** — carries a `reason`: `client-cancelled`, `server-execution-timeout`, `cancelled-for-next-turn`, or `abandoned`.+- **`error`** — carries a `message`.++`metrics`, when present, aggregates the whole turn: `total_input_tokens`, `total_output_tokens`, `total_tokens`, `total_cache_read_tokens`, `total_cache_write_tokens`, `total_reasoning_tokens`, and `total_cost_in_usd`.++```json turn.done — paused for approval+{+ "type": "turn.done",+ "id": "01jc...",+ "thread_id": null,+ "created_at": "2026-06-24T10:01:12Z",+ "state": {+ "status": "done",+ "output": null,+ "required_actions": [+ {+ "type": "tool.approval_required",+ "thread_id": "main",+ "tool_calls": [{ "id": "call-refund-01", "source_event_id": "msg-b2" }]+ }+ ],+ "completed_at": "2026-06-24T10:01:12Z",+ "metrics": { "total_tokens": 2451, "total_cost_in_usd": 0.011 }+ }+}+```++## Model output++### `model.message`++An assistant message — text content and/or tool calls. On a live stream the base event arrives first and fills in via deltas; the merged event carries:++| Field | Description |+| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `content` | Assistant text (may be empty when the message is only tool calls). |+| `tool_calls` | Tool invocations, each with an `id` and `function` (`name`, `arguments`). |+| `finish_reason` | Why generation stopped (`stop`, `tool_calls`, ...), `null` mid-stream. |+| `usage` | Token usage for this model call: `input_tokens`, `output_tokens`, optional cache counters, and `input_tokens_breakdown` (`harness`, `skills`, `instructions`, `tool_definitions`, `messages`). |++### `model.message.delta`++An incremental fragment of a `model.message` — text and/or tool-call chunks. All deltas share the base event's `id`; append `content` chunks and merge tool-call fragments by index. The most frequent event on a live stream. Not present when listing persisted events.++## Tool activity++### `tool.response`++The result of a tool the harness executed, linked to its call by `tool_call_id`:++```json+{+ "type": "tool.response",+ "id": "01jc...",+ "thread_id": "main",+ "tool_call_id": "call-get-order-01",+ "content": "{\"order_id\":\"ORD-2031\",\"status\":\"shipped\",\"total\":1240.0}",+ "created_at": "2026-06-24T10:00:04Z"+}+```++### `tool.approval_required`++A tool call needs [human approval](/human-in-the-loop) before it can run. The turn ends after this event; resume with a `user.tool_approval` input.++| Field | Description |+| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------- |+| `tool_calls` | Pending calls: each `{ id, source_event_id }`, where `source_event_id` points at the `model.message` that contains the call's name and arguments. |++### `tool.response_required`++A client-side tool (e.g. [`ask_user_question`](/ask-user-questions)) needs a result from your app. Same shape as `tool.approval_required`; resume with a `user.tool_response` input.++## Subagent threads++### `thread.created`++A [subagent](/context-engineering/subagents) started. Subsequent events with this `thread_id` belong to it.++| Field | Description |+| ------------ | -------------------------------------------------------------------------------------- |+| `thread_id` | The new thread's id. |+| `title` | Human-readable subagent name. |+| `parent` | `{ thread_id, tool_call_id }` — the spawning thread and tool call. |+| `agent_info` | `{ type: "dynamic", name, input }` — the generated instructions the subagent received. |++### `thread.done`++The subagent finished. `state` is `{ status: "done", output: <model.message> }` or `{ status: "error", error, output? }`. Does not close the turn stream — the root agent continues.++## Environment events++### `mcp.initialize`++MCP server connections were initialized for a thread. `mcp_servers` lists each server: `{ id, name, session_id?, transport_type? }` (`streamable-http` or `sse`).++### `mcp.auth_required`++One or more MCP servers need [OAuth authorization](/mcp-servers#in-chat-authentication) before the agent can proceed. `mcp_servers` lists `{ id, name, auth_url }` — send the user to `auth_url`, then start the next turn. The turn ends after this event.++### `sandbox.created`++A [sandbox](/sandbox) was provisioned, carrying its `sandbox_id`. Emitted once per session — subsequent turns reuse the same sandbox and emit no new event.++## User input events++These are not streamed — they are the input items **you send** when creating a turn, listed here for completeness:++| Type | Fields | Purpose |+| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ |+| `user.message` | `content` — string, or array of `{ type: "text", text }` / `{ type: "file", name, data }` parts (files as `data:<mime>;base64,...` URIs) | A user message. |+| `user.tool_approval` | `thread_id`, `tool_call_id`, `approval` — `{ status: "allow" }` or `{ status: "deny", reason? }` | Decision for a paused tool call. |+| `user.tool_response` | `thread_id`, `tool_call_id`, `content` | Answer for a paused client-side tool call. |++A turn's `input` cannot mix `user.message` items with approval or tool-response items.diff --git a/docs/ask-user-questions.mdx b/docs/ask-user-questions.mdxnew file mode 100644index 000000000..ea9a6aebf--- /dev/null+++ b/docs/ask-user-questions.mdx@@ -0,0 +1,102 @@+---+title: 'Ask User Questions'+sidebarTitle: 'Ask User Questions'+description: 'Let the agent ask structured multiple-choice questions and pause until the user answers.'+---++Agents often hit decision points where they cannot make a safe assumption — which environment to deploy to, which of three matching resources the user meant, what an ambiguous required field should be set to. Without a way to ask, the agent either guesses (and gets it wrong) or stalls with a free-form question the UI cannot render as a first-class action.++Ask User Questions lets the harness pause the agent, surface a structured multiple-choice prompt to the user, and resume the run with the chosen answer. It is **enabled by default**.++## How it works++TrueForge registers `ask_user_question` as a **client-side tool** — the server never executes it. When the agent calls it, the harness emits `tool.response_required`, finishes the turn (with the pending question in `state.required_actions`), and waits for your application to collect the user's choice and resume with a new turn containing a `user.tool_response` input.++```mermaid+sequenceDiagram+ participant User+ participant Client+ participant Harness as TrueForge+ participant Model++ User->>Client: Send message+ Client->>Harness: POST /turns+ Harness->>Model: LLM call+ rect rgba(255, 237, 153, 0.45)+ Model->>Harness: Tool call: ask_user_question+ Harness-->>Client: tool.response_required (turn ends)+ end+ Client->>User: Show question + options+ User->>Client: Pick an option+ rect rgba(255, 237, 153, 0.45)+ Client->>Harness: POST /turns (user.tool_response)+ Harness->>Model: Tool response+ end+```++The user selects one of the listed options or types a free-form answer. The agent receives the response as a regular tool result and continues from where it paused. The bundled chat UI renders questions and options natively.++<Note>+ Only the root agent can call `ask_user_question`. [Subagents](/context-engineering/subagents) must resolve ambiguity+ from the context the root agent provides them.+</Note>++## Example++A user asks the agent to _"create a new environment called `testing-1`"_, but the underlying tool requires fields the user never specified. Instead of inventing values, the agent asks:++```json ask_user_question — tool call+{+ "question": "Should this environment be a production environment?",+ "options": ["Yes — mark it as Production", "No — keep it as Non-production"]+}+```++Once the user answers, the agent asks the next required field or proceeds to the actual tool call — turning an ambiguous request into a deterministic, auditable sequence of decisions.++## Handling questions from the API++The `tool.response_required` event references the pending tool call:++```json+{+ "type": "tool.response_required",+ "thread_id": "main",+ "tool_calls": [{ "id": "call-q-01", "source_event_id": "msg-a4" }]+}+```++The question and options are in the tool call's arguments on the referenced `model.message` event (`source_event_id`). Resume with the answer:++```json+{+ "input": [+ {+ "type": "user.tool_response",+ "thread_id": "main",+ "tool_call_id": "call-q-01",+ "content": "No — keep it as Non-production"+ }+ ]+}+```++Turns in the same session chain automatically (`previous_turn_id` defaults to `"auto"`), so the agent picks up exactly where it paused.++## When to use it++Use `ask_user_question` when the agent genuinely cannot proceed without a user decision and the answer comes from a small, enumerable set:++- Choosing a target environment, cluster, account, or workspace+- Disambiguating between multiple matches ("I found 3 services named `api`, which one?")+- Resolving required tool-call fields the user did not specify (booleans, enums, modes)+- Picking between alternative strategies before a destructive or expensive operation++<Note>+ Skip it for decisions the agent can confidently infer from context, conversation history, or sensible defaults. Asking+ too often turns the agent into a form and breaks autonomy.+</Note>++## Disabling++Set `config.ask_user_questions.enabled: false` on the agent. See [`config.ask_user_questions`](/api/agent-spec#config) in the agent spec reference.diff --git a/docs/assets/.gitkeep b/docs/assets/.gitkeepnew file mode 100644index 000000000..e69de29bbdiff --git a/docs/context-engineering/code-mode.mdx b/docs/context-engineering/code-mode.mdxnew file mode 100644index 000000000..dcb79c5ed--- /dev/null+++ b/docs/context-engineering/code-mode.mdx@@ -0,0 +1,106 @@+---+title: 'Code Mode'+sidebarTitle: 'Code Mode'+description: 'Run a single script in the sandbox to aggregate tool output or chain MCP tool calls — also known as Programmatic Tool Calling (PTC).'+---++## Why Code Mode?++When an agent uses tools the standard way, every tool call is a separate round-trip with the model: the agent calls one MCP tool, the full JSON response enters the conversation, the model reasons over that JSON, then it calls the next tool — copying IDs and computing counts in prose along the way. For tasks that involve aggregating tool output, or chaining several calls together, this approach is slow, fills the context window with intermediate JSON the user doesn't care about, and is prone to small errors like miscounts and typoed IDs.++Take a common task: _"How many open PRs does each contributor have on this repo?"_ The user only cares about a small summary table, but the underlying GitHub tool returns a full record per PR — title, labels, reviewers, timestamps, and more. Without Code Mode, every one of those records lands in context and the model has to count from prose. With Code Mode, the agent calls the same tool inside a script, counts the author logins in code, and prints only the table.++## What is Code Mode?++Code Mode collapses tool round-trips into a single script. Using the [sandbox](/sandbox), the agent writes Python that calls MCP tools through an in-sandbox MCP client (`mcp_client`), processes the responses in code, and prints only what the user actually needs:++```python+import asyncio+from collections import Counter+from mcp_client import call_tool++async def main():+ result = await call_tool(+ "github",+ "list_pull_requests",+ body={"owner": "your-org", "repo": "your-repo", "state": "open"},+ )+ prs = result.get("pull_requests", [])+ counts = Counter(pr["user"]["login"] for pr in prs)++ print(f"Open PRs: {len(prs)}\n")+ for login, count in counts.most_common():+ print(f"{login:<24} {count:>4}")++asyncio.run(main())+```++The script runs in the sandbox, but the MCP tool calls are **bridged back to the harness**, which applies the stored server credentials — the sandbox never holds tokens:++```mermaid+sequenceDiagram+ participant Agent+ participant Sandbox+ participant Harness as TrueForge+ participant MCP as MCP server++ Agent->>Sandbox: Write and run script+ Sandbox->>Harness: call_tool("github", "list_pull_requests", ...)+ Harness->>MCP: Authenticated tool call+ MCP-->>Harness: Open PRs JSON+ Harness-->>Sandbox: Result (stays in the sandbox)+ Sandbox-->>Agent: Printed summary only+```++Code Mode is available whenever the agent's [sandbox](/sandbox) is enabled. The agent decides at runtime whether a task is worth running in code or whether a single direct tool call is enough. Before writing a script, it can call [`get_tool_output_schema`](/context-engineering/deferred-tool-loading#how-it-works) so it knows the exact shape of a tool's response instead of guessing keys from raw JSON.++<Note>+ [Approval policies](/human-in-the-loop) still apply in Code Mode — a script that calls a tool matching+ `require_approval_for_tools` pauses for user approval just like a direct tool call.+</Note>++## When the agent uses Code Mode++Code Mode wins whenever running the work in code is materially better than reasoning over raw JSON in chat:++### Aggregate or format tool output++Counts, group-bys, sums, filters, or formatted tables over a tool response.++| | With Code Mode | Without Code Mode |+| --------------- | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |+| **Approach** | Call the tool inside a script, group in code, print only the summary table. | Full tool response enters the conversation; the model counts from prose. |+| **Cost** | Only the summary reaches the model — minimal tokens. | Dozens of records sit in context even though the user only asked for counts. |+| **Reliability** | Counts are computed by code, so they are exact. | Group-by and count tasks are hallucination-prone when done from prose. |++### Chain tool calls++One tool's output feeds another tool's input — for example, resolving an entity's ID before fetching its details.++| | With Code Mode | Without Code Mode |+| --------------- | --------------------------------------------------- | -------------------------------------------------------------------------- |+| **Approach** | Both calls in one script; IDs flow inside the code. | Call the first tool, wait for a model turn, copy IDs into the second call. |+| **Cost** | The intermediate response stays in the sandbox. | The full intermediate response sits in the conversation. |+| **Latency** | One model turn covers both tool calls. | Each hop needs another model call in between. |+| **Reliability** | No copy-paste — no typoed IDs. | The model can typo an ID or pick the wrong record from a long list. |++```python+import asyncio+from mcp_client import call_tool++async def main():+ apps = await call_tool("platform", "list_applications",+ body={"name": "my-app"})+ app = apps["data"][0]++ charts = await call_tool("platform", "list_app_metric_charts",+ body={"application_id": app["id"]})++ print(f"{app['name']}: {len(charts['graphs'])} metric charts")+ for g in charts["graphs"]:+ print(f"- {g['name']} ({g['chartType']})")++asyncio.run(main())+```++Only the printed lines enter the agent's context — the two full JSON payloads never do.diff --git a/docs/context-engineering/deferred-tool-loading.mdx b/docs/context-engineering/deferred-tool-loading.mdxnew file mode 100644index 000000000..0c15e2ee7--- /dev/null+++ b/docs/context-engineering/deferred-tool-loading.mdx@@ -0,0 +1,86 @@+---+title: 'Deferred Tool Loading'+sidebarTitle: 'Deferred Tool Loading'+description: 'Control whether MCP tool definitions are preloaded into agent context or discovered on demand.'+---++When an agent is connected to many MCP servers, each with dozens of tools, the full set of tool definitions can consume a large portion of the context window before the user even sends a message. The `preload` setting on each MCP server entry controls whether those definitions are loaded upfront or discovered on demand.++By default, **`preload` is `false`** — the agent only sees each MCP server's name and description at startup and loads individual tool schemas as needed. This keeps the context window lean while still giving the agent access to the full breadth of tools.++## The problem++- Each tool definition — name, description, input schema, output schema — consumes tokens from the available context window.+- With many MCP servers and tools, the context window can fill up before any user interaction happens.+- Most interactions only need a small subset of the available tools.++<Frame caption="Deferring tool loading keeps the agent's context window lean">+ <img+ src="/images/preload-tools.png"+ alt="Comparison showing context window usage with tool preloading off versus on across many MCP servers"+ />+</Frame>++## How it works++| `preload` | Behavior | Best for |+| ----------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------ |+| `false` (default) | Only the server's name and description are in context. Tool schemas are discovered on demand via meta tools. | Large tool catalogs, servers used only occasionally |+| `true` | Full tool definitions are loaded into context at startup. | Small, frequently-used servers where every turn calls a tool |++When `preload` is off, the harness exposes four **meta tools** instead of the individual tool definitions:++| Meta tool | Purpose |+| ------------------------ | ---------------------------------------------------------------------------------------------- |+| `list_tools` | List the tool names available on an MCP server |+| `get_tool_info` | Fetch a tool's description and input/output schema |+| `get_tool_output_schema` | Fetch just the output schema — used before [Code Mode](/context-engineering/code-mode) scripts |+| `call_tool` | Invoke a tool on a server by name |++```mermaid+sequenceDiagram+ participant Model+ participant Harness as TrueForge++ Note over Model,Harness: Model only has the MCP server's name + description in context++ Model->>Harness: list_tools("github")+ Harness-->>Model: Tool names++ Model->>Harness: get_tool_info("github", "list_pull_requests")+ Harness-->>Model: Description, input schema, output schema++ Model->>Harness: call_tool("github", "list_pull_requests", input)+ Harness-->>Model: Tool result+```++The extra discovery round-trips only happen the first time a tool is needed — and they are far cheaper than carrying every schema in context on every model call.++## Selective preloading++You don't have to choose all-or-nothing. `preload_tools` eagerly loads specific tools while the rest of the server stays deferred:++```json+{+ "mcp_servers": [+ {+ "name": "github",+ "preload": false,+ "preload_tools": ["search_pull_requests"]+ }+ ]+}+```++This is useful when one or two tools are used on almost every run but the server exposes dozens more.++## Example++An agent has `internal-platform-mcp` (100+ tools, `preload: false`) and `web_search` (2 tools, `preload: true`) attached. The user asks a question that needs a platform lookup:++1. The agent calls `list_tools("internal-platform-mcp")` and gets back the tool names.+2. It calls `get_tool_info("internal-platform-mcp", "list_applications")` for the schema of the one tool it needs.+3. It calls `call_tool("internal-platform-mcp", "list_applications", {...})` and gets the result.+4. The `web_search` tools were preloaded, so it can call them directly with no discovery step.++Only the schemas the agent actually needed ever entered context.diff --git a/docs/context-engineering/large-tool-responses.mdx b/docs/context-engineering/large-tool-responses.mdxnew file mode 100644index 000000000..750c9f016--- /dev/null+++ b/docs/context-engineering/large-tool-responses.mdx@@ -0,0 +1,70 @@+---+title: 'Handling Large Tool Responses'+sidebarTitle: 'Large Tool Responses'+description: "Automatically offload large MCP tool responses to the sandbox instead of flooding the agent's context window."+---++## Why++- An MCP tool call may return a large amount of data, which can quickly fill the available context window.+- The agent may not be able to control how much data a server returns by adjusting tool arguments alone. Fetching a single pull request can still return a very large `description` field.++Large tool response handling is **enabled by default** and requires the agent's [sandbox](/sandbox) to be enabled (the offloaded data is written to a sandbox file).++## How it works++```mermaid+flowchart LR+ Tool[Tool executes] --> Check{Size > threshold?}+ Check -->|No| Full[Full result in context] --> Continue[Agent continues]+ Check -->|Yes| Save[Save to sandbox file] --> Preview[Preview + file path in context] --> Continue+```++Two complementary thresholds govern when tool responses are written to the sandbox instead of staying in context:++**A single tool response that's too large.** If an individual tool response exceeds the per-call threshold (default **6,000 tokens**), the full result is written to a file in the sandbox and replaced in context with a short preview (default the first and last **100 characters**) plus the file path.++**Parallel tool calls returning together.** When the agent fires several tool calls in parallel, no single response may be over the per-call threshold but their _combined_ size can still flood the context window. If the combined tool-call content exceeds the total threshold (default **10,000 tokens**), the harness offloads responses one at a time — **starting with the largest** — until the total drops below the limit. The smallest responses stay inline and the largest end up on disk.++In every case the offloaded content remains accessible — the agent can read, `grep`, or parse the saved file from the sandbox whenever it needs the original data, typically using [Code Mode](/context-engineering/code-mode) to extract just the fields it needs.++## Example++1. The user asks: _"List the MCP servers I have access to."_+2. The agent calls `list_mcp_servers`. The response is a 180-item JSON array — far over the threshold. The harness writes it to a sandbox file and returns only a preview:++ ```text+ Tool response too large — full result saved to /tmp/tool-id-xyz-output+ Use the sandbox to read parts of the file or extract data.++ Preview (first and last 100 chars):+ {"data":[{"id":"v3sgnimki67gd1do5vkcv9wz","name":"test-realtime-global", ... "total":180}+ ```++3. The agent inspects the file's structure, then writes a small script to extract just the names:++ ```python+ import json+ with open('/tmp/tool-id-xyz-output') as f:+ data = json.load(f)+ for item in data['data']:+ print(item['name'])+ ```++4. It answers with the list of names. The 180 full records never entered the model's context.++## Configuration++Turn offloading on or off per agent:++```json+{+ "config": {+ "context_management": {+ "large_tool_response": { "enabled": true }+ }+ }+}+```++The thresholds themselves default to **6,000 tokens** per response, **10,000 tokens** combined, and a **100-character** preview. See [`config.context_management`](/api/agent-spec#config) in the agent spec reference.diff --git a/docs/context-engineering/overview.mdx b/docs/context-engineering/overview.mdxnew file mode 100644index 000000000..5cdadcfc4--- /dev/null+++ b/docs/context-engineering/overview.mdx@@ -0,0 +1,151 @@+---+title: 'Context Engineering'+sidebarTitle: 'Overview'+description: 'How TrueForge manages, optimizes, and constrains agent context within model limits.'+---++## What is context engineering?++Context engineering is the practice of providing the **right information in the right format** so an agent can reliably accomplish tasks. In TrueForge, _context_ is everything the model sees on each step — from system instructions and skills to tool definitions, conversation history, and tool results.++Getting context right has a direct impact on agent quality:++- **Too little context** — the agent lacks the information it needs and produces wrong or incomplete answers.+- **Too much context** — the model overflows its context window or the signal gets buried in noise, degrading reasoning quality and increasing cost and latency.++TrueForge automates the balance through a layered set of strategies. To understand them, it helps to think of context in two phases:++<CardGroup cols={2}>+ <Card title="Input context" icon="upload" href="#input-context">+ Information loaded into the model's context at the **start** of every run. You configure this when you build the+ agent: the instructions, skills, and which MCP servers are available.+ </Card>+ <Card title="Runtime context" icon="bolt" href="#runtime-context">+ Information that accumulates **during the run** as the agent works: user messages, tool calls, tool results,+ subagent outputs. This grows turn by turn and is what the harness actively manages.+ </Card>+</CardGroup>++<Frame caption="Input context is set at startup; runtime context grows turn by turn as the agent loop runs">+ <img+ src="/images/agent-harness-context-window.png"+ alt="Diagram of an agent's context window split into input context (system prompt, skills, MCP tool definitions) feeding the agent loop, and runtime context (user messages, tool calls and results, subagent results) flowing back into the loop"+ />+</Frame>++## Input context++Input context is everything the model receives at the **start** of a run. It is mostly static across runs of the same agent — you configure it once and the harness loads it every time. The smaller and more focused your input context, the more room the model has to reason.++<AccordionGroup>+ <Accordion title="Instructions" icon="message">+ Your `instructions` are the system prompt — plus built-in harness guidance for using the sandbox, subagents, and other enabled capabilities. It is the single biggest lever you control:++ - **Stick to this agent's role** — what it does, who it's for, how it should behave.+ - **Don't duplicate MCP tool docs or skill content** — the harness already injects those.+ - **Move long procedures into skills** — anything that reads like a workflow or playbook belongs in a [skill](/skills), not the instructions.++ </Accordion>++<Accordion title="Skills" icon="book">+ Each attached skill contributes only its `name` and `description` to the input context. The full `SKILL.md` body is+ read from the sandbox on demand when the agent decides the skill is relevant — this is called **progressive+ disclosure**. See [Skills](/skills).+</Accordion>++ <Accordion title="MCP tool definitions" icon="plug">+ Each tool definition — name, description, input schema, output schema — consumes tokens. With many MCP servers each exposing dozens of tools, the schemas alone can fill a large portion of the context window before the user types anything.++ By default (`preload: false`), each attached MCP server contributes only its `name` and `description`; individual tool schemas are discovered on demand. Turn `preload` on only for small, frequently-used servers. See [Deferred tool loading](/context-engineering/deferred-tool-loading).++ </Accordion>+</AccordionGroup>++## Runtime context++Runtime context is everything added to the model's context **as the run progresses**:++| Source | What it is |+| ---------------------- | --------------------------------------------------------------------------------- |+| **User messages** | Whatever the user sends, including follow-ups in a multi-turn conversation |+| **Assistant messages** | The model's reasoning and replies on each step |+| **Tool calls** | Each tool invocation made by the agent, with its arguments |+| **Tool results** | Whatever the tool returns — JSON payloads, file contents, search results, errors |+| **Subagent outputs** | Final results returned from delegated [subagents](/context-engineering/subagents) |++Runtime context is where most of the **context bloat problem** happens. A single tool call returning a 50,000-token JSON payload, or a long conversation with dozens of intermediate steps, can quickly approach the model's limit. This is the part the harness actively manages.++## Managing runtime context++<CardGroup cols={2}>+ <Card title="Subagents" icon="diagram-project" href="/context-engineering/subagents">+ Delegate focused subtasks to parallel subagents, each with its own clean context. Only the final result flows back —+ the intermediate tool calls never touch the main context.+ </Card>+ <Card title="Large Result Offloading" icon="file-export" href="/context-engineering/large-tool-responses">+ When a tool returns more data than fits comfortably in context, the harness writes the full output to a sandbox file+ and replaces it with a short preview and the file path.+ </Card>+ <Card title="Code Mode" icon="code" href="/context-engineering/code-mode">+ The agent calls MCP tools from a Python script in the sandbox, processing results in code. Only the printed summary+ enters context.+ </Card>+ <Card title="Context Compaction" icon="compress" href="#context-compaction">+ When context grows past a threshold, the harness replaces older history with a structured in-context summary so the+ agent can keep working.+ </Card>+</CardGroup>++### Context compaction++When the conversation grows longer than offloading alone can manage, the harness triggers **compaction**. Compaction is enabled by default and kicks in when the active context crosses a token threshold (default **50,000 tokens**, configurable per agent).++An LLM generates a structured summary of the conversation so far — the original intent, key decisions, files and artifacts, errors and fixes, and next steps — and that summary replaces the older message history in the agent's working context, freeing tokens for continued reasoning.++```mermaid+flowchart TD+ Trigger[Active context exceeds<br/>compaction_threshold_tokens] --> Compact[Compaction]+ Compact --> Summary[Structured summary:<br/>intent, decisions, artifacts, next steps]+ Summary --> Working[Working context = summary<br/>+ continuation instruction]+ Working --> Next[Agent continues the task]+```++<Note>+ Compaction is **lossy in the working context** — fine-grained details from earlier messages are condensed into the+ summary. The full event history of the session remains persisted and queryable via the [session events+ API](/api/overview), but the agent works from the summary after compaction.+</Note>++Configuration:++```json+{+ "config": {+ "context_management": {+ "compaction": {+ "enabled": true,+ "compaction_threshold_tokens": 50000+ }+ }+ }+}+```++## How the strategies compose++In practice, these strategies stack. A single agent run might:++1. Start with **preload off**, so only a handful of tool schemas are in input context.+2. **Delegate** a research subtask to a subagent that makes dozens of tool calls in isolation.+3. **Offload** a large tool result inside the subagent to a sandbox file.+4. Use **Code Mode** to aggregate the offloaded data into a small summary.+5. Return the summary to the root agent — keeping the root's runtime context clean.+6. **Compact** the root agent's history later if a long conversation crosses the threshold.++## Best practices++1. **Start with input context discipline.** Keep instructions focused on the agent's role; move procedures into skills; leave preload off for large MCP servers.+2. **Let progressive disclosure do the work.** Default to deferred loading for both skills and MCP servers. Override only when a server is truly needed on every run.+3. **Delegate heavy work to subagents.** Multi-step research or tasks with large intermediate outputs belong in subagents.+4. **Use Code Mode for aggregation.** When the model needs to count, group, filter, or join tool output, Code Mode keeps raw data out of context entirely and avoids arithmetic hallucinations.+5. **Watch token usage.** Every `model.message` event carries `usage` with an `input_tokens_breakdown` (harness, skills, instructions, tool definitions, messages), so you can see exactly where context is going.diff --git a/docs/context-engineering/subagents.mdx b/docs/context-engineering/subagents.mdxnew file mode 100644index 000000000..fba4eaf6f--- /dev/null+++ b/docs/context-engineering/subagents.mdx@@ -0,0 +1,99 @@+---+title: 'Subagents'+sidebarTitle: 'Subagents'+description: "The harness delegates focused subtasks to parallel subagents, keeping the root agent's context clean."+---++When a task involves gathering or processing information from multiple sources, a single agent can quickly fill its context window with intermediate tool calls and results. TrueForge solves this with **subagents** — lightweight, isolated agent runs that handle focused subtasks in parallel and return only their final results to the root agent. Dynamic subagents are **enabled by default**.++The root agent stays focused on high-level coordination. Subagents do the heavy lifting.++## Why subagents?++Subagents solve the **context bloat problem**. When an agent uses tools with large outputs — API responses, search results, file contents — the context window fills up with intermediate data that is only needed temporarily. As the context grows, the agent becomes slower, more expensive, and more prone to errors.++Consider a task: _"Summarize the recent pull requests for every member of my team."_++<Tabs>+ <Tab title="Without subagents">+ 1. The agent looks up members of the team. 2. It works on each member **one by one**, fetching pull requests and+ summarizing each. 3. All intermediate tool calls and results stay in the context window. 4. The agent has to reason+ over a large, cluttered context to produce the final answer. 5. The bloat carries over to future turns in the+ session.+ </Tab>+ <Tab title="With subagents">+ 1. The agent looks up members of the team. 2. It creates a subagent **per team member** — they run in parallel. 3.+ Each subagent fetches pull requests and produces a summary independently. 4. Subagents return only their summaries+ to the root agent. 5. The root agent combines the summaries — the raw data never enters its context.+ </Tab>+</Tabs>++**When subagents help most:**++- Multi-step research across several entities (users, repos, services) that can run in parallel+- Tasks where intermediate tool output is large but the final answer is a summary+- Work that benefits from isolation — each subtask gets a clean context to reason in++## How it works++The root agent decides at runtime whether to delegate. When it does, it calls the built-in `create_sub_agent` tool with focused, generated instructions for each subtask, spawns the subagents, and waits for their results.++```mermaid+flowchart LR+ User[User message] --> Root[Root agent]++ Root --> Decide{Delegate?}+ Decide -->|No| Direct[Answer directly]++ Decide -->|Yes| Fan[Generate instructions<br/>per subtask]++ Fan --> S1[Subagent 1]+ Fan --> S2[Subagent 2]+ Fan --> SN[Subagent N]++ S1 --> Merge[Collect results]+ S2 --> Merge+ SN --> Merge++ Merge --> Root+ Root --> Answer[Final answer]+```++<Note>+ - **Shared tools and sandbox** — subagents have access to the same MCP tools and sandbox environment as the root+ agent. - **No user interaction** — subagents cannot ask the user questions. Only the root agent talks to the user.+ Subagent tool calls that require [approval](/human-in-the-loop) still pause for the user, though. - **No nesting** —+ subagents cannot create other subagents. Delegation is one level deep. - **Parallel execution** — multiple subagents+ run concurrently. The root agent waits for all of them before continuing.+</Note>++## Following subagents in the event stream++Every execution — root and subagent — runs in its own **thread**, identified by a `thread_id` on each event. The root agent is always `"main"`. Subagent lifecycle is marked by two events:++```json thread.created+{+ "type": "thread.created",+ "thread_id": "th-9f31",+ "title": "bob-prs",+ "parent": { "thread_id": "main", "tool_call_id": "call-sub-01" },+ "agent_info": { "type": "dynamic", "name": "bob-prs", "input": "Search for pull requests merged by..." }+}+```++```json thread.done+{+ "type": "thread.done",+ "thread_id": "th-9f31",+ "title": "bob-prs",+ "state": { "status": "done", "output": { "type": "model.message", "content": "Bob merged 2 PRs..." } }+}+```++Between the two, the subagent's own `model.message`, `tool.response`, and other events stream with its `thread_id` — so a client can render each subagent as its own collapsible trace while the root agent's events keep flowing on `"main"`. The bundled chat UI does exactly this.++See [Turn events](/api/turn-events#thread-created) for the full schemas.++## Disabling++Set `config.dynamic_sub_agents.enabled: false` on the agent. See [`config.dynamic_sub_agents`](/api/agent-spec#config) in the agent spec reference.diff --git a/docs/docs.json b/docs/docs.jsonindex 7b43ff5f5..29006549c 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -21,6 +21,32 @@{"group": "Getting Started","pages": ["introduction", "quickstart"]+ },+ {+ "group": "Capabilities",+ "pages": [+ "models",+ "mcp-servers",+ "skills",+ "sandbox",+ "human-in-the-loop",+ "ask-user-questions",+ "generative-ui"+ ]+ },+ {+ "group": "Context Engineering",+ "pages": [+ "context-engineering/overview",+ "context-engineering/subagents",+ "context-engineering/deferred-tool-loading",+ "context-engineering/code-mode",+ "context-engineering/large-tool-responses"+ ]+ },+ {+ "group": "API",+ "pages": ["api/overview", "api/agent-spec", "api/turn-events"]}]}diff --git a/docs/generative-ui.mdx b/docs/generative-ui.mdxnew file mode 100644index 000000000..5c87f00af--- /dev/null+++ b/docs/generative-ui.mdx@@ -0,0 +1,104 @@+---+title: 'Generative UI'+sidebarTitle: 'Generative UI'+description: 'Let the agent respond with rich, interactive components — charts, tables, cards, forms — instead of plain text.'+---++Plain text and markdown work for short answers, but they fall flat the moment an agent needs to show a dashboard, compare metrics, render a sortable table, or guide a user through a form. Users end up squinting at walls of numbers when a single chart would have told the story in seconds.++**Generative UI** lets your agent respond with real, interactive components — charts, tables, cards, forms, layouts — that the client renders as actual React UI. The agent decides _what_ to show; the harness ships it in a standard format your renderer turns into pixels. It is **enabled by default**, and the bundled chat UI renders it out of the box.++## How it works++Generative UI is **not** a separate tool call. The agent writes a small, streaming-friendly snippet inside its normal assistant message, and the client renders it on the fly as tokens arrive.++Under the hood, this uses [OpenUI](https://www.openui.com/) — an open standard for agent-generated UI:++- **OpenUI Lang** — a compact, streaming-first language for describing UI, far more token-efficient than equivalent JSON.+- **Component library** — built-in charts, tables, forms, cards, and layouts, extensible with your own design system.+- **Streaming renderer** — parses and renders UI progressively in React as the response streams in.+- **Safe by default** — no arbitrary code execution. The agent can only emit components the renderer has registered.++When `config.generative_ui.enabled` is true, the harness exposes the OpenUI authoring instructions to the agent (loaded on demand via a `get_openui_instructions` tool, so they cost no context until the agent decides to render UI). The stream uses normal [`model.message`](/api/turn-events#model-message) events and deltas — the only difference is that some message content contains an ` ```openui ` fenced block that the client extracts and renders as React components.++```mermaid+sequenceDiagram+ participant User+ participant Client+ participant Harness as TrueForge+ participant Model++ User->>Client: "Show me request volume by model"+ Client->>Harness: POST /turns+ Harness->>Model: LLM call (OpenUI instructions available on demand)+ Model->>Harness: Streams assistant message with an openui block+ Harness-->>Client: model.message + deltas+ Client->>Client: Detect openui fence, render with OpenUI renderer+ Client->>User: Interactive chart + table+```++## Example++<Steps>+<Step title="User" noAnchor>+ Show me a dashboard comparing request volume and error rate across my three production models.+</Step>++<Step title="Assistant" noAnchor>+ I will summarize the model traffic visually.++```openui+root = Stack([title, cards, chart, table])+title = TextContent("Production Model Health", "large-heavy")+cards = Stack([totalCard, errorCard], "row", "m", "stretch")+totalCard = Card([TextContent("Total requests", "small"), TextContent("2,630", "large-heavy")])+errorCard = Card([TextContent("Average error rate", "small"), TextContent("1.8%", "large-heavy")])+chart = BarChart(models, [requests], "grouped", "Model", "Requests")+table = Table([Col("Model", models), Col("Requests", requestValues, "number"), Col("Error rate", errorRates)])+models = ["gpt-4.1", "claude-sonnet", "llama-3.1"]+requestValues = [1240, 980, 410]+errorRates = ["1.2%", "2.1%", "2.5%"]+requests = Series("Requests", requestValues)+```++The highest traffic is on `gpt-4.1`, while `llama-3.1` has the highest error rate despite lower volume.++</Step>+</Steps>++The renderer turns the snippet above into a full dashboard — summary cards on top, a grouped bar chart in the middle, and a sortable data table at the bottom — all real React components, not markdown.++## Available components++The OpenUI built-in library covers the patterns most agents need:++| Category | Components |+| ---------- | --------------------------------------------- |+| **Layout** | `Stack`, `Card`, `Tabs`, `Accordion` |+| **Text** | `TextContent`, `Markdown` |+| **Data** | `Table`, `Col` |+| **Charts** | `BarChart`, `LineChart`, `PieChart`, `Series` |+| **Input** | `TextInput`, `Select`, `Button`, `Form` |+| **Media** | `Image`, `Link` |++Building your own client? Register custom components with `defineComponent` and `createLibrary` from `@openuidev/react-lang`. The agent will only ever emit components that are registered — it cannot generate arbitrary HTML or code.++## When to use it++| Use case | What the agent renders |+| ------------------- | --------------------------------------------------------------- |+| **Dashboards** | KPI cards, charts, and tables for metrics and comparisons |+| **Tables** | Sortable structured data — logs, resources, results to scan |+| **Charts** | Bar, line, and pie charts that show patterns faster than prose |+| **Cards & layouts** | Summary panels, multi-section reports, side-by-side comparisons |+| **Forms** | Inputs, dropdowns, and selections that guide the next action |++<Note>+ Skip Generative UI for simple answers where markdown is enough — a short explanation, a bullet list, a code block.+ Generative UI is also not a replacement for server-side actions: if a UI button needs to trigger a follow-up, the+ client sends that back as a normal user message in the next turn.+</Note>++## Disabling++Set `config.generative_ui.enabled: false` on the agent. See [`config.generative_ui`](/api/agent-spec#config) in the agent spec reference.diff --git a/docs/human-in-the-loop.mdx b/docs/human-in-the-loop.mdxnew file mode 100644index 000000000..3acbb8790--- /dev/null+++ b/docs/human-in-the-loop.mdx@@ -0,0 +1,100 @@+---+title: 'Human in the Loop'+sidebarTitle: 'Human in the Loop'+description: 'Pause an agent before sensitive tool calls so the user can approve or deny execution.'+---++Some agent actions — deploying to production, restarting a service, deleting data — should not happen without explicit user consent. Human in the Loop lets the harness pause the agent before a sensitive tool call, surface the tool name and arguments to the user, and resume only after an approval decision.++This keeps the agent autonomous for safe operations while giving users a checkpoint before anything destructive or irreversible runs.++## Which tools require approval++Approval policy is set per MCP server on the agent spec via [`require_approval_for_tools`](/api/agent-spec#mcp_servers). The default is `["@write", "@destructive"]` — any tool that the MCP server does not mark as read-only, or marks as destructive, pauses for approval out of the box. You can also list literal tool names, or use `@all` to gate every tool.++```json+{+ "mcp_servers": [+ {+ "name": "orders-api",+ "require_approval_for_tools": ["process_refund"]+ }+ ]+}+```++## How it works++When the agent requests a tool call that requires approval, the harness does not execute the tool. Instead, it emits `tool.approval_required`, finishes the current turn (with the pending approval in `state.required_actions`), and waits. Resume by starting a new turn in the same session with a `user.tool_approval` input for each pending tool call.++```mermaid+sequenceDiagram+ participant Client+ participant Harness as TrueForge+ participant Tool++ Client->>Harness: POST /turns (user message)+ Harness->>Harness: Agent calls sensitive tool+ rect rgba(255, 237, 153, 0.45)+ Harness-->>Client: tool.approval_required (turn ends)+ Client->>Harness: POST /turns (user.tool_approval)+ end+ alt Allow+ Harness->>Tool: Execute+ Tool-->>Harness: Tool result+ else Deny+ Harness->>Harness: Denial becomes the tool result+ end+ Harness-->>Client: Agent continues+```++<Info>+ Subagents can also request approval. When a subagent's tool call requires approval, the harness finishes the current+ turn and emits `tool.approval_required` with that subagent's `thread_id`. Sending a `user.tool_approval` in the next+ turn resumes the subagent from where it paused.+</Info>++## Approving or denying from the API++The `tool.approval_required` event references the pending tool calls:++```json+{+ "type": "tool.approval_required",+ "thread_id": "main",+ "tool_calls": [{ "id": "call-refund-01", "source_event_id": "msg-b2" }]+}+```++Resume with a new turn whose input carries the decision:++```json+{+ "input": [+ {+ "type": "user.tool_approval",+ "thread_id": "main",+ "tool_call_id": "call-refund-01",+ "approval": { "status": "allow" }+ }+ ]+}+```++To deny, send `{ "status": "deny", "reason": "..." }` — the agent receives the denial (and your reason) as the tool result and can adjust its plan instead of failing.++The bundled chat UI handles all of this automatically: it pauses the run, shows the tool name and request payload with **Approve / Deny** buttons, and resumes on your decision.++## When to use approvals++Use approvals for tool calls that change state, are irreversible, or affect production — mutating data, modifying infrastructure, sending external communications, or triggering expensive operations. The `@write` / `@destructive` defaults cover this when the MCP server annotates its tools correctly.++<Note>+ Skip approvals for safe read-only tools — listing resources, fetching metrics, searching docs — where confirmation+ adds friction without reducing risk. Those are excluded by default.+</Note>++<Info>+ Approvals do not replace authorization. The user still needs whatever access the underlying tool requires; approval+ only controls whether the pending tool call should proceed.+</Info>diff --git a/docs/images/agent-harness-context-window.png b/docs/images/agent-harness-context-window.pngnew file mode 100644index 000000000..fa9c2c28eBinary files /dev/null and b/docs/images/agent-harness-context-window.png differdiff --git a/docs/images/agent-harness-definition.png b/docs/images/agent-harness-definition.pngnew file mode 100644index 000000000..7e517500cBinary files /dev/null and b/docs/images/agent-harness-definition.png differdiff --git a/docs/images/preload-tools.png b/docs/images/preload-tools.pngnew file mode 100644index 000000000..3c0c6422eBinary files /dev/null and b/docs/images/preload-tools.png differdiff --git a/docs/introduction.mdx b/docs/introduction.mdxnew file mode 100644index 000000000..fe0ee1a03--- /dev/null+++ b/docs/introduction.mdx@@ -0,0 +1,127 @@+---+title: 'TrueForge'+sidebarTitle: 'Introduction'+description: 'TrueForge is an open-source agent harness — the runtime layer that turns an LLM into a working agent, with MCP tools, skills, sandboxing, approvals, and subagents built in.'+---++## What is an agent harness?++An agent harness is the runtime layer around an LLM that turns it into a reliable, long-running agent.++Instead of only generating text, the harness manages the full execution loop: planning, tool calling, context management, approvals, state, and streaming.++Most production harnesses include:++- An orchestration loop (`plan -> act -> observe -> continue/stop`)+- Tool routing and execution (for APIs, MCP tools, and code)+- Memory and context controls for long-running tasks+- Security boundaries (sandboxing, credentials, permissions)+- Human-in-the-loop gates for sensitive actions+- Session state that survives reconnects and restarts++<Frame caption="The harness orchestrates the agent run, connecting the model, tools, sandbox, and approvals to deliver a safe, reliable result">+ <img+ src="/images/agent-harness-definition.png"+ alt="Diagram of the agent harness sitting between a user goal and the final response: the harness orchestrates the run, routes between model, tools and MCP servers, sandbox, and approval gates, and records every step"+ />+</Frame>++## What is TrueForge?++TrueForge is an **open-source agent harness**. It runs the agent execution loop — model calls, tool use, context, and session state — and exposes the result three ways:++- A **chat UI**, bundled into the server and served on the same port+- An **HTTP API** (REST + Server-Sent Events) with an OpenAPI spec+- A **TypeScript library** (`@truefoundry/trueforge-core`) for embedding the agent core in your own application++You choose a model, connect MCP servers, add skills, and write instructions. TrueForge handles orchestration, tool execution, sandbox lifecycle, approvals, and streaming.++It scales down and up: run a single process backed by SQLite with `npx @truefoundry/trueforge`, or run multiple replicas backed by Postgres and Redis behind a load balancer.++## Capabilities++<CardGroup cols={2}>+ <Card title="Models" icon="brain" href="/models">+ OpenAI, Anthropic, Google Gemini, and any OpenAI-compatible provider. Configure once, switch per agent.+ </Card>+ <Card title="MCP Servers" icon="plug" href="/mcp-servers">+ Connect remote MCP servers with header auth or OAuth (dynamic client registration), including in-chat authorization.+ </Card>+ <Card title="Skills" icon="book" href="/skills">+ Git-backed `SKILL.md` instruction packs, mounted into the sandbox and loaded on demand.+ </Card>+ <Card title="Sandbox" icon="cube" href="/sandbox">+ An isolated execution environment for code, files, and shell commands — provisioned only when the agent needs one.+ </Card>+ <Card title="Context Engineering" icon="layer-group" href="/context-engineering/overview">+ Subagents, deferred tool loading, code mode, large-result offloading, and compaction — keep context lean+ automatically.+ </Card>+ <Card title="Human in the Loop" icon="shield-check" href="/human-in-the-loop">+ Pause sensitive tool calls and require explicit user approval before execution.+ </Card>+ <Card title="Ask User Questions" icon="message-question" href="/ask-user-questions">+ Let the agent request clarification or pick between options during a run.+ </Card>+ <Card title="Generative UI" icon="sparkles" href="/generative-ui">+ Stream structured UI blocks the client can render as cards, tables, and charts.+ </Card>+</CardGroup>++## Architecture++TrueForge is a single server process (or several peered replicas) plus a database — and Redis when you run more than one replica.++```mermaid+flowchart LR+ browser([Browser / your app])+ subgraph server [TrueForge server]+ ui[Chat UI]+ api[HTTP API + agent loop]+ end+ db[(Postgres or SQLite)]+ redis[(Redis)]+ llm[Model providers]+ mcp[MCP servers]+ sandbox[Sandbox provider]++ browser --> ui+ browser --> api+ api --> db+ api <--> redis+ api --> llm+ api --> mcp+ api --> sandbox+```++| Component | Role |+| --------------------- | --------------------------------------------------------------------------------------------------- |+| **Chat UI** | React chat interface, bundled into the server image and served on the same port as the API. |+| **Server** | Node.js server: the agent execution loop, sessions, turns, streaming, settings, and OpenAPI docs. |+| **Postgres / SQLite** | Session, turn, and settings storage. SQLite in standalone mode; Postgres for multi-replica. |+| **Redis** | Cross-replica peering (turn cancellation and stream handoff). Only needed when running > 1 replica. |+| **Sandbox provider** | Remote isolated compute for code execution and skills. Optional — enable it per agent. |++## Core concepts++Interaction with an agent follows a strict hierarchy: **one Agent → many Sessions → many Turns → many Events**.++| Concept | What it is |+| ----------- | --------------------------------------------------------------------------------------------------------------------- |+| **Agent** | A saved definition — model, instructions, MCP servers, skills, and runtime config. See [Agent spec](/api/agent-spec). |+| **Session** | One conversation with an agent. Turns in a session chain together, so the agent remembers earlier context. |+| **Turn** | One request/response boundary — a user message, an approval decision, or an answer to an agent question. |+| **Event** | A JSON object streamed while a turn runs: model output, tool responses, approval requests, subagent lifecycle. |++See the [API overview](/api/overview) for the full lifecycle with examples.++## Start building++<CardGroup cols={2}>+ <Card title="Quickstart" icon="rocket" href="/quickstart">+ Run TrueForge with one command, configure a model provider, and start chatting.+ </Card>+ <Card title="Use the API" icon="code" href="/api/overview">+ Create sessions, stream turn events, and integrate TrueForge into your application.+ </Card>+</CardGroup>diff --git a/docs/mcp-servers.mdx b/docs/mcp-servers.mdxnew file mode 100644index 000000000..851cd732a--- /dev/null+++ b/docs/mcp-servers.mdx@@ -0,0 +1,104 @@+---+title: 'MCP Servers'+sidebarTitle: 'MCP Servers'+description: 'Connect remote MCP servers to give your agent tools — with header auth or OAuth, per-tool enablement, and approval policies.'+---++MCP servers are how your agent reaches real systems: SaaS apps, internal APIs, data platforms, ticketing tools, and infrastructure controls.++In TrueForge, MCP servers are registered once — in the UI under **Settings → MCP Servers** or via the settings API — and agents reference them by name. Credentials live in the server configuration, never in agent definitions.++## Registering an MCP server++An MCP server is configured with a small manifest:++```json+{+ "type": "remote",+ "name": "github",+ "url": "https://api.githubcopilot.com/mcp/",+ "auth": { "type": "dcr" }+}+```++| Field | Description |+| ------ | -------------------------------------------------------------------------------------------------------------------------------------------------- |+| `type` | `remote` — a server reachable over HTTP. TrueForge connects via Streamable HTTP, falling back to SSE. |+| `name` | How agents reference the server. |+| `url` | The MCP endpoint URL. |+| `auth` | Optional. `{ "type": "header", "headers": { ... } }` for static credentials, or `{ "type": "dcr" }` for OAuth. Omit for servers that need no auth. |++Register it with `PUT /api/v1/settings/mcp-servers` (or through the UI). A catalog of popular servers is available at `GET /api/v1/settings/mcp-servers/catalog`, and you can verify connectivity with `GET /api/v1/settings/mcp-servers/{name}/tools`, which lists the server's live tools.++### Authentication options++- **No auth** — public or network-trusted servers.+- **Header auth** (`type: "header"`) — static HTTP headers (API keys, bearer tokens) sent on every request to the server.+- **OAuth with Dynamic Client Registration** (`type: "dcr"`) — TrueForge registers itself as an OAuth client with the server's authorization server, runs the authorization-code flow, and stores and refreshes tokens. Users never handle tokens.++## In-chat authentication++If a server uses OAuth and the user has not yet authorized it, the agent does not fail — the turn pauses with an `mcp.auth_required` event that carries an `auth_url` for each server that needs authorization. The chat UI renders this as a **Connect** button: the user completes the OAuth flow in a popup and continues the conversation.++```mermaid+sequenceDiagram+ participant User+ participant Client+ participant TrueForge+ participant MCP as MCP server++ Client->>TrueForge: Start turn+ TrueForge->>MCP: Connect+ MCP-->>TrueForge: 401 — OAuth required+ TrueForge-->>Client: mcp.auth_required (auth_url)+ User->>TrueForge: Completes OAuth flow+ Client->>TrueForge: Next turn+ TrueForge->>MCP: Authenticated tool calls+```++Set `PUBLIC_BASE_URL` on the server so OAuth callbacks resolve to the right origin.++## Attaching servers to an agent++Each agent lists the servers it uses, with fine-grained control over which tools are exposed and which require approval:++```json+{+ "mcp_servers": [+ {+ "name": "github",+ "enable_tools": ["@all"],+ "disable_tools": ["delete_repository"],+ "require_approval_for_tools": ["@write", "@destructive"],+ "preload": false+ }+ ]+}+```++| Field | Default | Description |+| ---------------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |+| `enable_tools` | `["@all"]` | Tools exposed to the agent. `@all`, `@read-only`, or literal names. |+| `disable_tools` | `[]` | Tools removed from the enabled set. |+| `require_approval_for_tools` | `["@write", "@destructive"]` | Tools that pause for [human approval](/human-in-the-loop). `@all`, `@write`, `@destructive`, or literal names. |+| `preload` | `false` | Whether tool schemas are loaded into context upfront. See [Deferred tool loading](/context-engineering/deferred-tool-loading). |+| `preload_tools` | `[]` | Specific tools to load eagerly while the rest stay deferred. |++The `@read-only`, `@write`, and `@destructive` selectors are derived from the tool annotations the MCP server publishes (`readOnlyHint`, `destructiveHint`), so approval policy follows the server's own metadata.++<Tip>+ Attach only the servers an agent needs, and disable tools it should never call. A smaller tool surface reduces risk+ and improves tool-call quality by minimizing irrelevant choices.+</Tip>++## Safety controls++- Tools matching `require_approval_for_tools` pause the turn for explicit user confirmation — see [Human in the Loop](/human-in-the-loop).+- The defaults (`@write`, `@destructive`) mean state-changing tools require approval out of the box; read-only tools run freely.+- Approval enforcement also applies when tools are called from [Code Mode](/context-engineering/code-mode) scripts inside the sandbox.++## Keeping context lean++Tool definitions consume context. With many servers each exposing dozens of tools, the schemas alone can fill a large share of the context window before the user types anything. By default (`preload: false`), TrueForge only puts each server's name and description in context and lets the agent discover tool schemas on demand.++See [Deferred tool loading](/context-engineering/deferred-tool-loading) for the full flow.diff --git a/docs/models.mdx b/docs/models.mdxnew file mode 100644index 000000000..475403c6b--- /dev/null+++ b/docs/models.mdx@@ -0,0 +1,87 @@+---+title: 'Models'+sidebarTitle: 'Models'+description: 'Configure model providers once, then reference models by name in any agent — switching models is a config change, not a code change.'+---++TrueForge works with the major model providers and any OpenAI-compatible endpoint. Provider credentials are configured once — in the UI under **Settings → Model Providers** or via the settings API — and agents reference models by name. Agent definitions never contain API keys.++## Supported providers++| Provider type | Notes |+| --------------- | ---------------------------------------------------------------------- |+| `openai` | OpenAI |+| `anthropic` | Anthropic |+| `google-gemini` | Google Gemini |+| `fireworks` | Fireworks AI |+| `together` | Together AI |+| `moonshot` | Moonshot AI (Kimi) |+| `zai` | Z.ai (GLM) |+| `alibaba` | Alibaba (Qwen) |+| `custom` | Any OpenAI-compatible endpoint — self-hosted models, gateways, proxies |++The shipped catalog (`GET /api/v1/settings/model-providers/catalog`) contains ready-to-fill templates for each provider. Use the `custom` type to connect vLLM, Ollama, a corporate gateway, or any other OpenAI-compatible API.++## Configuring a provider++<Tabs>+ <Tab title="UI">+ Open **Settings → Model Providers**, pick a provider from the catalog, and paste your API key. Models from that provider become available immediately in the model selector.+ </Tab>+ <Tab title="API">+ Fetch a template from the catalog, fill in the credentials, and upsert it:++ ```bash+ curl http://localhost:8790/api/v1/settings/model-providers/catalog+ curl -X PUT http://localhost:8790/api/v1/settings/model-providers \+ -H 'Content-Type: application/json' \+ -d '<provider manifest from the catalog, with your API key>'+ ```++ List every available model across configured providers with `GET /api/v1/models`.++ </Tab>+</Tabs>++## Referencing a model in an agent++Models are addressed as `provider/model` in the agent spec:++```json+{+ "model": {+ "name": "anthropic/claude-sonnet-4-6",+ "params": {+ "max_tokens": 4096,+ "temperature": 0.2+ }+ }+}+```++`model.params` supports `max_tokens`, `temperature`, `top_p`, `top_k`, `parallel_tool_calls`, and `reasoning_effort` — plus any extra provider-specific parameters, which are passed through as-is. See the [agent spec reference](/api/agent-spec#model).++Switching models is a one-line change to the agent spec (or one click in the UI). No code edits, no new credentials.++## Why model choice matters for agents++Agent workloads are different from single-turn chat. They involve multiple tool calls, retries, long context, and structured outputs. Model selection directly affects:++- Reliability of tool calling and structured output+- Latency across multi-step tasks+- Total run cost over many turns+- Accuracy on planning and complex reasoning++| Category | Best for |+| -------------------------- | --------------------------------------------------------------- |+| Balanced general-purpose | Most production assistants and tool-driven workflows |+| Cost-optimized high-volume | High request volume, triage, lightweight actions |+| High reasoning depth | Complex planning, multi-step analysis, long tool chains |+| Open / self-hosted | Data residency, cost control, private deployment (via `custom`) |++<Tip>+ Start with a balanced model and a tight [agent spec](/api/agent-spec), then measure. Token usage per model call is+ reported on every `model.message` event (`usage.input_tokens`, `usage.output_tokens`, and a breakdown of where input+ tokens went), and per-turn totals appear in `turn.done` metrics — so you can see exactly what a model choice costs+ before switching.+</Tip>diff --git a/docs/quickstart.mdx b/docs/quickstart.mdxnew file mode 100644index 000000000..7c5d0cb56--- /dev/null+++ b/docs/quickstart.mdx@@ -0,0 +1,139 @@+---+title: 'Quickstart'+sidebarTitle: 'Quickstart'+description: 'Run TrueForge with one command, configure a model provider, and have your first agent conversation in minutes.'+---++## Run TrueForge++<Tabs>+ <Tab title="npx">+ Requires [Node.js](https://nodejs.org) 22.13 or newer. One command, no other infrastructure — data is stored in a local SQLite file:++ ```bash+ npx @truefoundry/trueforge+ ```++ Then open [http://localhost:8790](http://localhost:8790).++ | Configuration | Default | Description |+ | ----------------- | -------------------------- | ----------------------------------------------- |+ | `--port` / `PORT` | `8790` | HTTP port the server (UI + API) listens on. |+ | `SQLITE_PATH` | OS data dir | Location of the SQLite database file. |+ | `PUBLIC_BASE_URL` | `http://localhost:${PORT}` | Public origin, used for MCP OAuth callbacks. |++ </Tab>+ <Tab title="Docker Compose">+ Runs the full production topology on your machine: the server (UI + API), Postgres, and Redis.++ ```bash+ git clone <REPO_URL> trueforge && cd trueforge # TODO: repo URL+ cp packages/server/.env.example packages/server/.env+ docker compose up --build+ ```++ Then open [http://localhost:8791](http://localhost:8791).++ | Configuration | Default | Description |+ | ----------------------------------------------------- | ----------------------- | -------------------------------------------------------- |+ | `POSTGRES_USER` / `POSTGRES_PASSWORD` / `POSTGRES_DB` | from `.env` | Postgres credentials, read from `packages/server/.env`. |+ | `PUBLIC_BASE_URL` | `http://localhost:8791` | Public origin, used for MCP OAuth callbacks. |+ | Host ports | `8791`, `5433`, `6380` | App, Postgres, and Redis. |++ </Tab>+ <Tab title="Kubernetes (Helm)">+ The Helm chart deploys the server with bundled Postgres and Redis (or point it at your own):++ ```bash+ # TODO: replace <HELM_REPO> with the published Helm repo URL+ helm install trueforge oci://<HELM_REPO>/trueforge \+ --version <x.y.z> \+ --set server.publicBaseUrl=https://trueforge.example.com+ ```++ | Value | Default | Description |+ | ---------------------- | ------------ | ------------------------------------------------------------------------ |+ | `server.publicBaseUrl` | — (required) | Public origin for MCP OAuth callbacks. |+ | `replicaCount` | `1` | Number of server replicas (peered over Redis). |+ | `postgresql.enabled` | `true` | Bundle Postgres; set `false` + `externalPostgres.*` to bring your own. |+ | `redis.enabled` | `true` | Bundle Redis; set `false` + `externalRedis.url` to bring your own. |++ </Tab>+</Tabs>++<Note>+ Standalone (`npx`) uses SQLite and needs no other services. Docker Compose and Kubernetes run the multi-replica+ topology: Postgres for storage and Redis for cross-replica peering. The agent features are identical in both.+</Note>++## Configure a model provider++TrueForge ships with a catalog of model providers. Configure one before your first chat:++<Steps>+ <Step title="Open Settings">In the UI, open **Settings → Model Providers**.</Step>+ <Step title="Pick a provider">+ Choose a provider from the catalog — OpenAI, Anthropic, Google Gemini, or an OpenAI-compatible endpoint — and paste+ your API key.+ </Step>+ <Step title="Select a model">+ Back in the chat, pick a model. Models are addressed as `provider/model`, for example `anthropic/claude-sonnet-4-6`.+ </Step>+</Steps>++Everything you can do in Settings is also available through the API — see `GET /api/v1/settings/model-providers/catalog` and `PUT /api/v1/settings/model-providers` in the interactive API docs at `/api/v1/docs`.++## Start chatting++Send your first message. Out of the box the agent supports multi-turn conversations with streaming. To give it more capabilities:++- **Connect tools** — add [MCP servers](/mcp-servers) under **Settings → MCP Servers**.+- **Enable the sandbox** — configure a [sandbox provider](/sandbox) so the agent can run code and use [skills](/skills).+- **Add skills** — register [git-backed skills](/skills) under **Settings → Skills**.++## Call the API++Every conversation in the UI is a session in the API. Create one yourself:++```bash+curl -X POST http://localhost:8790/api/v1/sessions \+ -H 'Content-Type: application/json' \+ -d '{+ "agent": {+ "type": "value",+ "agent_spec": {+ "model": { "name": "anthropic/claude-sonnet-4-6" },+ "instructions": "You are a helpful assistant."+ }+ }+ }'+```++Then start a turn and stream events over SSE:++```bash+curl -N -X POST http://localhost:8790/api/v1/sessions/{session_id}/turns \+ -H 'Content-Type: application/json' \+ -d '{+ "input": [{ "type": "user.message", "content": "Hello!" }]+ }'+```++See the [API overview](/api/overview) for the full lifecycle — turn chaining, approvals, and event handling.++## Next steps++<CardGroup cols={2}>+ <Card title="Connect MCP servers" icon="plug" href="/mcp-servers">+ Give your agent tools — with per-tool enablement and approval policies.+ </Card>+ <Card title="Enable the sandbox" icon="cube" href="/sandbox">+ Let the agent run code, work with files, and use skills.+ </Card>+ <Card title="Context engineering" icon="layer-group" href="/context-engineering/overview">+ How TrueForge keeps agent context lean on long tasks.+ </Card>+ <Card title="API reference" icon="code" href="/api/overview">+ Sessions, turns, events, and the agent spec.+ </Card>+</CardGroup>diff --git a/docs/sandbox.mdx b/docs/sandbox.mdxnew file mode 100644index 000000000..130a7e615--- /dev/null+++ b/docs/sandbox.mdx@@ -0,0 +1,142 @@+---+title: 'Sandbox'+sidebarTitle: 'Sandbox'+description: 'An isolated execution environment for code, files, and shell commands — provisioned only when the agent needs one.'+---++The sandbox gives your agent a secure, isolated environment to run code, manipulate files, and execute shell commands — completely separate from the TrueForge server and your infrastructure.++## Sandbox as a tool++There are two architecture patterns for combining agents with sandboxes. TrueForge uses the **sandbox as tool** pattern: the agent and all orchestration logic run in the harness, and the sandbox is only used for code execution, file operations, and shell commands.++```mermaid+flowchart LR+ subgraph Harness["TrueForge server"]+ Agent[Agent loop + LLM client]+ end+ Agent <-->|"exec tool calls"| SB+ subgraph SB["Sandbox"]+ FS[Filesystem]+ Shell[Shell]+ end+```++This design has several consequences:++- **Secrets stay out of the sandbox** — model API keys and MCP credentials live in the harness. Even a sandbox compromised through prompt injection has no secrets to exfiltrate.+- **Agent state survives sandbox failures** — conversation history, context, and tool definitions live in the harness. A sandbox crash doesn't lose the agent's progress.+- **On-demand provisioning** — a sandbox is created only when the agent actually needs one. Simple Q&A and MCP tool calls incur no sandbox cost.++## Configuring a sandbox provider++TrueForge delegates sandbox compute to a provider. Configure it once — in the UI under **Settings → Sandbox** or via `PUT /api/v1/settings/sandbox-providers`. Today the supported provider is [Daytona](https://www.daytona.io):++```json+{+ "type": "daytona",+ "snapshot_name": "your-snapshot",+ "auth": { "api_key": "..." },+ "exec_timeout_ms": 120000,+ "auto_stop_interval_in_minutes": 15,+ "auto_archive_interval_in_minutes": 10080,+ "auto_delete_interval_in_minutes": 43200+}+```++| Field | Description |+| ---------------------------------- | ---------------------------------------------------------------- |+| `snapshot_name` | Daytona snapshot (base image) used when creating sandboxes. |+| `auth.api_key` | Daytona API key. |+| `exec_timeout_ms` | Default timeout for a single command execution. |+| `auto_stop_interval_in_minutes` | Idle time before a running sandbox is stopped (files preserved). |+| `auto_archive_interval_in_minutes` | Time before a stopped sandbox is archived. |+| `auto_delete_interval_in_minutes` | Time before an archived sandbox is deleted. |++A template with defaults is available at `GET /api/v1/settings/sandbox-providers/catalog`. Whether a provider is configured is reported by `GET /api/v1/capabilities`.++## Enabling the sandbox on an agent++The sandbox is **off by default** per agent. Enable it in the agent spec:++```json+{+ "config": {+ "sandbox": {+ "enabled": true,+ "file_downloads": true+ }+ }+}+```++| Field | Default | Description |+| ---------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |+| `enabled` | `false` | Give this agent a sandbox. Required for [skills](/skills) and [Code Mode](/context-engineering/code-mode). |+| `file_downloads` | `true` | Allow users to download files the agent produces (via the turn download endpoint). |+| `network_policy.auth_inject` | — | Optional: inject git basic-auth credentials for specific hosts, so the agent can clone private repositories without ever seeing the credentials. |++```json+{+ "config": {+ "sandbox": {+ "enabled": true,+ "network_policy": {+ "auth_inject": [+ {+ "type": "git",+ "match": { "hosts": ["github.com"] },+ "auth_data": { "type": "basic", "username": "x-access-token", "password": "<token>" }+ }+ ]+ }+ }+ }+}+```++## On-demand provisioning++Most agent tasks — answering questions, calling MCP tools, reasoning — do not require code execution. TrueForge provisions a sandbox only when the agent decides it needs one:++```mermaid+flowchart LR+ User[User message] --> Harness[Agent loop]+ Harness --> Check{Needs code execution<br/>or filesystem?}+ Check -->|No| Respond[Respond directly<br/>No sandbox cost]+ Check -->|Yes| Provision[Provision sandbox]+ Provision --> Execute[Run command in sandbox]+ Execute --> Respond2[Return result]+```++The sandbox is used when the agent needs to:++- Run Python, shell, or other code+- Write, read, or process files+- Use [skills](/skills) (skill repositories are cloned into the sandbox)+- Run [Code Mode](/context-engineering/code-mode) scripts that chain MCP tool calls programmatically+- Generate downloadable artifacts (CSVs, reports, images)++When a sandbox is created, the turn stream emits a [`sandbox.created`](/api/turn-events#sandbox-created) event with the `sandbox_id`.++## Persistence across turns++Once provisioned, the sandbox is reused across turns in the same session — files written in one turn are available in the next, and no new `sandbox.created` event is emitted. Idle sandboxes are stopped after `auto_stop_interval_in_minutes` (state preserved and restartable), then archived and eventually deleted per the provider configuration.++## File downloads++When the agent produces a file, clients can fetch it through the server:++```text+GET /api/v1/sessions/{session_id}/turns/{turn_id}/download?path=...+```++The bundled chat UI renders download links automatically. Set `config.sandbox.file_downloads: false` to disable this per agent. The maximum download size is controlled by the `SANDBOX_FILE_MAX_BYTES_FOR_DOWNLOAD` server environment variable (default 20 MB).++## Credential safety++Because TrueForge uses the sandbox-as-tool pattern:++- Model and MCP credentials are used by the harness, outside the sandbox.+- When the agent calls MCP tools from inside a [Code Mode](/context-engineering/code-mode) script, the calls are **bridged back to the harness**, which applies the stored credentials — the sandbox never holds tokens.+- The only credentials that can enter the sandbox are ones you explicitly inject via `network_policy.auth_inject` (for cloning private git repositories).diff --git a/docs/skills.mdx b/docs/skills.mdxnew file mode 100644index 000000000..171f5e0c6--- /dev/null+++ b/docs/skills.mdx@@ -0,0 +1,106 @@+---+title: 'Skills'+sidebarTitle: 'Skills'+description: 'Teach agents specialized procedures with git-backed SKILL.md instruction packs, loaded on demand at runtime.'+---++Skills are reusable capability bundles that teach an agent how to perform specialized tasks — querying a database, triaging an alert, following an escalation playbook, or drafting release notes.++In TrueForge, a skill is a **directory in a git repository** rooted at a `SKILL.md` file. You register skills once — in the UI under **Settings → Skills** or via the settings API — and attach them to agents by name.++## What a skill contains++A skill is a directory with a `SKILL.md` file (YAML frontmatter with `name` and `description`, plus a markdown body of instructions) and any supporting files:++```text+customer-support-skill/+├── SKILL.md+├── references/+│ └── escalation-policy.md+└── scripts/+ └── classify_ticket.py+```++The `description` is what the agent sees upfront to decide whether the skill is relevant. The full body — and the supporting files — are only read when the agent picks the skill. This **progressive disclosure** keeps context lean while giving the agent access to detailed procedures on demand.++## Registering a skill++A skill manifest points at a GitHub or GitLab repository:++```json+{+ "type": "git",+ "name": "customer-support",+ "url": "https://github.com/your-org/agent-skills",+ "path": "skills/customer-support",+ "ref": "main",+ "description": "Triage and respond to customer support tickets following the escalation policy."+}+```++| Field | Description |+| ------------- | ------------------------------------------------------------------------------- |+| `type` | `git` — the skill lives in a git repository. |+| `name` | How agents reference the skill. Also the directory name inside the sandbox. |+| `url` | HTTPS URL of a GitHub or GitLab repository. |+| `path` | Optional path to the skill directory within the repo. Omit for the repo root. |+| `ref` | Branch name, tag, or commit SHA. **Pin a tag or SHA for production stability.** |+| `description` | Concise guidance for when the agent should use the skill. |++Register it with `PUT /api/v1/settings/skills` (or through the UI). Starter skills are available in the catalog at `GET /api/v1/settings/skills/catalog`.++<Tip>+ Because `ref` can be a branch, tag, or commit SHA, you get versioning through git itself: pin production agents to a+ tag or SHA, test changes on a branch, and roll back by changing the ref.+</Tip>++## Attaching skills to an agent++Agents reference skills by name only:++```json+{+ "skills": [{ "name": "customer-support" }],+ "config": {+ "sandbox": { "enabled": true }+ }+}+```++<Note>+ Skills require the agent's **[sandbox](/sandbox)** to be enabled — the skill repository is cloned into the sandbox, and the agent reads `SKILL.md` and runs any bundled scripts there. Session creation rejects agents that attach skills without a sandbox (check `GET /api/v1/capabilities` to see whether a sandbox provider is configured).++Two skills cannot share the same `name` within a single agent.++</Note>++## How skills are used at runtime++1. At startup, the harness exposes each attached skill's `name` and `description` to the model.+2. When the model decides a skill is relevant, the skill's repository is materialized in the sandbox under `/opt/tfy/skills/{name}`.+3. The agent reads `SKILL.md`, follows its instructions, and accesses supporting files or runs bundled scripts as needed.++```mermaid+flowchart LR+ Start[Turn starts] --> Meta[Skill name + description in context]+ Meta --> Decide{Skill relevant?}+ Decide -->|No| Skip[Skill body never enters context]+ Decide -->|Yes| Mount[Clone into sandbox at /opt/tfy/skills/name]+ Mount --> Read[Agent reads SKILL.md and follows it]+```++## Skills + MCP tools++Skills and MCP tools are complementary:++- **Skills** define _how_ to handle a task — the procedure, decision logic, and formatting rules.+- **MCP tools** provide the _actions and data_ needed to execute it.++Example: a "CRM follow-up" skill instructs the agent on decision logic and message tone, while MCP tools handle record lookup, ticket update, and Slack notification.++## Authoring guidelines++- Keep the `description` sharp — it is the only thing the model sees before deciding to load the skill.+- Write `SKILL.md` like instructions to a competent new teammate: the workflow, the edge cases, the output format.+- Move heavy reference material into supporting files the skill links to, so the agent reads them only when needed.+- Prefer several focused skills over one sprawling skill — the agent composes them per task.diff --git a/packages/frontend/package.json b/packages/frontend/package.jsonindex 35889b35e..02f91bca8 100644--- a/packages/frontend/package.json+++ b/packages/frontend/package.json@@ -3,7 +3,7 @@"version": "0.0.0","description": "TrueFoundry agent chat frontend (draft-only). Private app — not published to npm.","author": "Truefoundry",- "license": "UNLICENSED",+ "license": "MIT","private": true,"type": "module","scripts": {diff --git a/packages/harness/package.json b/packages/harness/package.jsonindex 440f2f118..3ed006496 100644--- a/packages/harness/package.json+++ b/packages/harness/package.json@@ -3,7 +3,7 @@"version": "0.1.9-rc.2","description": "TrueFoundry agent core and session library","author": "Truefoundry",- "license": "UNLICENSED",+ "license": "MIT","private": false,"type": "module","main": "./dist/index.js",diff --git a/packages/server/package.json b/packages/server/package.jsonindex 6fe995e25..bc766c5df 100644--- a/packages/server/package.json+++ b/packages/server/package.json@@ -3,7 +3,7 @@"version": "0.2.0-rc.2","description": "TrueFoundry agent server + UI (npx @truefoundry/utils)","author": "Truefoundry",- "license": "UNLICENSED",+ "license": "MIT","private": false,"type": "module","bin": "./dist/cli.js",diff --git a/packages/trueforge-ui-sdk/LICENSE b/packages/trueforge-ui-sdk/LICENSEindex d64569567..d1e5f37a5 100644--- a/packages/trueforge-ui-sdk/LICENSE+++ b/packages/trueforge-ui-sdk/LICENSE@@ -1,202 +1,21 @@-- Apache License- Version 2.0, January 2004- http://www.apache.org/licenses/-- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION-- 1. Definitions.-- "License" shall mean the terms and conditions for use, reproduction,- and distribution as defined by Sections 1 through 9 of this document.-- "Licensor" shall mean the copyright owner or entity authorized by- the copyright owner that is granting the License.-- "Legal Entity" shall mean the union of the acting entity and all- other entities that control, are controlled by, or are under common- control with that entity. For the purposes of this definition,- "control" means (i) the power, direct or indirect, to cause the- direction or management of such entity, whether by contract or- otherwise, or (ii) ownership of fifty percent (50%) or more of the- outstanding shares, or (iii) beneficial ownership of such entity.-- "You" (or "Your") shall mean an individual or Legal Entity- exercising permissions granted by this License.-- "Source" form shall mean the preferred form for making modifications,- including but not limited to software source code, documentation- source, and configuration files.-- "Object" form shall mean any form resulting from mechanical- transformation or translation of a Source form, including but- not limited to compiled object code, generated documentation,- and conversions to other media types.-- "Work" shall mean the work of authorship, whether in Source or- Object form, made available under the License, as indicated by a- copyright notice that is included in or attached to the work- (an example is provided in the Appendix below).-- "Derivative Works" shall mean any work, whether in Source or Object- form, that is based on (or derived from) the Work and for which the- editorial revisions, annotations, elaborations, or other modifications- represent, as a whole, an original work of authorship. For the purposes- of this License, Derivative Works shall not include works that remain- separable from, or merely link (or bind by name) to the interfaces of,- the Work and Derivative Works thereof.-- "Contribution" shall mean any work of authorship, including- the original version of the Work and any modifications or additions- to that Work or Derivative Works thereof, that is intentionally- submitted to Licensor for inclusion in the Work by the copyright owner- or by an individual or Legal Entity authorized to submit on behalf of- the copyright owner. For the purposes of this definition, "submitted"- means any form of electronic, verbal, or written communication sent- to the Licensor or its representatives, including but not limited to- communication on electronic mailing lists, source code control systems,- and issue tracking systems that are managed by, or on behalf of, the- Licensor for the purpose of discussing and improving the Work, but- excluding communication that is conspicuously marked or otherwise- designated in writing by the copyright owner as "Not a Contribution."-- "Contributor" shall mean Licensor and any individual or Legal Entity- on behalf of whom a Contribution has been received by Licensor and- subsequently incorporated within the Work.-- 2. Grant of Copyright License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- copyright license to reproduce, prepare Derivative Works of,- publicly display, publicly perform, sublicense, and distribute the- Work and such Derivative Works in Source or Object form.-- 3. Grant of Patent License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- (except as stated in this section) patent license to make, have made,- use, offer to sell, sell, import, and otherwise transfer the Work,- where such license applies only to those patent claims licensable- by such Contributor that are necessarily infringed by their- Contribution(s) alone or by combination of their Contribution(s)- with the Work to which such Contribution(s) was submitted. If You- institute patent litigation against any entity (including a- cross-claim or counterclaim in a lawsuit) alleging that the Work- or a Contribution incorporated within the Work constitutes direct- or contributory patent infringement, then any patent licenses- granted to You under this License for that Work shall terminate- as of the date such litigation is filed.-- 4. Redistribution. You may reproduce and distribute copies of the- Work or Derivative Works thereof in any medium, with or without- modifications, and in Source or Object form, provided that You- meet the following conditions:-- (a) You must give any other recipients of the Work or- Derivative Works a copy of this License; and-- (b) You must cause any modified files to carry prominent notices- stating that You changed the files; and-- (c) You must retain, in the Source form of any Derivative Works- that You distribute, all copyright, patent, trademark, and- attribution notices from the Source form of the Work,- excluding those notices that do not pertain to any part of- the Derivative Works; and-- (d) If the Work includes a "NOTICE" text file as part of its- distribution, then any Derivative Works that You distribute must- include a readable copy of the attribution notices contained- within such NOTICE file, excluding those notices that do not- pertain to any part of the Derivative Works, in at least one- of the following places: within a NOTICE text file distributed- as part of the Derivative Works; within the Source form or- documentation, if provided along with the Derivative Works; or,- within a display generated by the Derivative Works, if and- wherever such third-party notices normally appear. The contents- of the NOTICE file are for informational purposes only and- do not modify the License. You may add Your own attribution- notices within Derivative Works that You distribute, alongside- or as an addendum to the NOTICE text from the Work, provided- that such additional attribution notices cannot be construed- as modifying the License.-- You may add Your own copyright statement to Your modifications and- may provide additional or different license terms and conditions- for use, reproduction, or distribution of Your modifications, or- for any such Derivative Works as a whole, provided Your use,- reproduction, and distribution of the Work otherwise complies with- the conditions stated in this License.-- 5. Submission of Contributions. Unless You explicitly state otherwise,- any Contribution intentionally submitted for inclusion in the Work- by You to the Licensor shall be under the terms and conditions of- this License, without any additional terms or conditions.- Notwithstanding the above, nothing herein shall supersede or modify- the terms of any separate license agreement you may have executed- with Licensor regarding such Contributions.-- 6. Trademarks. This License does not grant permission to use the trade- names, trademarks, service marks, or product names of the Licensor,- except as required for reasonable and customary use in describing the- origin of the Work and reproducing the content of the NOTICE file.-- 7. Disclaimer of Warranty. Unless required by applicable law or- agreed to in writing, Licensor provides the Work (and each- Contributor provides its Contributions) on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or- implied, including, without limitation, any warranties or conditions- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A- PARTICULAR PURPOSE. You are solely responsible for determining the- appropriateness of using or redistributing the Work and assume any- risks associated with Your exercise of permissions under this License.-- 8. Limitation of Liability. In no event and under no legal theory,- whether in tort (including negligence), contract, or otherwise,- unless required by applicable law (such as deliberate and grossly- negligent acts) or agreed to in writing, shall any Contributor be- liable to You for damages, including any direct, indirect, special,- incidental, or consequential damages of any character arising as a- result of this License or out of the use or inability to use the- Work (including but not limited to damages for loss of goodwill,- work stoppage, computer failure or malfunction, or any and all- other commercial damages or losses), even if such Contributor- has been advised of the possibility of such damages.-- 9. Accepting Warranty or Additional Liability. While redistributing- the Work or Derivative Works thereof, You may choose to offer,- and charge a fee for, acceptance of support, warranty, indemnity,- or other liability obligations and/or rights consistent with this- License. However, in accepting such obligations, You may act only- on Your own behalf and on Your sole responsibility, not on behalf- of any other Contributor, and only if You agree to indemnify,- defend, and hold each Contributor harmless for any liability- incurred by, or claims asserted against, such Contributor by reason- of your accepting any such warranty or additional liability.-- END OF TERMS AND CONDITIONS-- APPENDIX: How to apply the Apache License to your work.-- To apply the Apache License to your work, attach the following- boilerplate notice, with the fields enclosed by brackets "[]"- replaced with your own identifying information. (Don't include- the brackets!) The text should be enclosed in the appropriate- comment syntax for the file format. We also recommend that a- file or class name and description of purpose be included on the- same "printed page" as the copyright notice for easier- identification within third-party archives.-- Copyright [yyyy] [name of copyright owner]-- Licensed under the Apache License, Version 2.0 (the "License");- you may not use this file except in compliance with the License.- You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing, software- distributed under the License is distributed on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- See the License for the specific language governing permissions and- limitations under the License.+MIT License++Copyright (c) 2024-2026 TrueFoundry++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.diff --git a/packages/trueforge-ui-sdk/README.md b/packages/trueforge-ui-sdk/README.mdindex 0ba094027..1aa58d1f3 100644--- a/packages/trueforge-ui-sdk/README.md+++ b/packages/trueforge-ui-sdk/README.md@@ -500,6 +500,6 @@ Local demo: see [example/](./example/). Publishing: see [RELEASING.md](../../REL## License-Apache-2.0. See [LICENSE](./LICENSE) and [NOTICE](./NOTICE).+MIT. See [LICENSE](./LICENSE) and [NOTICE](./NOTICE).Security: [SECURITY.md](./SECURITY.md) · Conduct: [CODE_OF_CONDUCT.md](./CODE_OF_CONDUCT.md) · Changes: [CHANGELOG.md](./CHANGELOG.md)diff --git a/packages/trueforge-ui-sdk/package.json b/packages/trueforge-ui-sdk/package.jsonindex 6ca3adb87..bd68c72c9 100644--- a/packages/trueforge-ui-sdk/package.json+++ b/packages/trueforge-ui-sdk/package.json@@ -2,7 +2,7 @@"name": "@truefoundry/trueforge-ui","version": "0.1.4","description": "TrueFoundry agent chat UI (atoms + containers) built on assistant-ui, with owned theming, presets, and swappable slots.",- "license": "Apache-2.0",+ "license": "MIT","repository": {"type": "git","url": "git+https://github.com/truefoundry/harness.git",