Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

docs(agent): teach SDK concepts before protocol details

thinhlpgc116c29b8407
diff --git a/docs/src/pages/docs/agent/protocol.mdx b/docs/src/pages/docs/agent/protocol.mdx
index 6e7c197a9..cf307d583 100644
--- a/docs/src/pages/docs/agent/protocol.mdx
+++ b/docs/src/pages/docs/agent/protocol.mdx
@@ -1,77 +1,69 @@
---
-title: Agent Protocol Records
-description: Read the generated stream-json and RPC records and check each surface's availability.
-keywords: [Jan, Jan Agent, protocol, stream-json, RPC, ACP, JSON Schema, reference]
+title: Protocol Records
+description: The wire reference for custom Jan clients. Choose RPC or stream-json, then use the generated schemas for record shapes.
+keywords: [Jan, Jan Agent, protocol, stream-json, RPC, JSON Schema, reference]
---
import { Callout } from 'nextra/components'
-# Agent Protocol Records
+# Protocol Records
-Building a client against Jan's wire protocol? Use the generated artifacts for record shapes,
-then check the surface's release state before treating a method or event as available. For a first
-CLI run, start with the [Agent quickstart](/docs/agent/quickstart); for an embedding path, see
-[Agent SDK](/docs/agent/sdk).
+**You do not need this page for the SDK quickstarts.** The SDK handles the messages for you.
+Use this reference when building your own client, debugging the channel, or generating types.
+
+## Choose the transport first
+
+| | RPC | stream-json |
+| --- | --- | --- |
+| Start command | `jan cli agent rpc` | `jan cli agent run --output-format stream-json --input-format stream-json` |
+| Process lifetime | One process, multiple sessions, one active turn at a time | One process per run |
+| First exchange | `initialize` request, then `initialized` notification | The runtime emits `init` when setup succeeds |
+| During work | JSON-RPC requests and notifications such as `item/token` | Records with a `type`, such as `token` |
+| End of work | `turn/completed`; the process stays available | `result`, then process exit |
+| Best for | SDKs and long-lived applications | Direct CLI automation |
+
+These are different envelopes. Do not send a stream-json `abort` record to RPC, or parse an RPC
+notification as a bare stream-json event. For normal application code, use the
+[JavaScript](/docs/agent/sdk-ts) or [Python](/docs/agent/sdk-python) SDK.
## Read the generated records
-- **`stream-json`:** [`protocol/schema.json`](https://github.com/janhq/jan/blob/08f88a4aca8ac77ec444c454635b5bbd633f0f15/protocol/schema.json) is generated from the Rust types for the input and
- output records of `jan cli agent run --output-format stream-json`. Read its root `input` and
- `output` schemas and follow references into `$defs` for individual record definitions. The
- `x-protocol-version` keyword identifies the contract version. Print the same generated document
- with `jan cli agent schema`, or write it with `jan cli agent schema --out protocol/schema.json`.
- The [CLI `schema` section](/docs/agent/cli#schema) explains the transport.
-- **RPC:** [`protocol/rpc-schema.json`](https://github.com/janhq/jan/blob/bbe3f3e3649cb67ee94dfbd9a689594c62837e84/protocol/rpc-schema.json) is generated from the RPC envelope and typed request and event
- definitions. Read its `protocol_version`, `envelope`, `requests`, `notifications` and `events`
- sections to navigate the artifact rather than copying field declarations from this page. Print
- it with `jan cli agent rpc-schema`, or write it with
- `jan cli agent rpc-schema --out protocol/rpc-schema.json`. The implementation and artifact were
- merged in [PR #9049](https://github.com/janhq/jan/pull/9049) and are on `main`, not yet in a
- nightly or release. See the [CLI `rpc` section](/docs/agent/cli#rpc) for the transport and
- [RPC host tools](#rpc-host-tools) below for host callbacks.
-
-Both artifacts are generated and checked for drift against their Rust source by the `protocol
-schema` job in `.github/workflows/rust-check.yml`, which regenerates both and fails the job on a
-diff of either. `protocol/schema.json` describes **only `stream-json`**; it
-is not an RPC or ACP schema. `protocol/rpc-schema.json` describes RPC records, not an ACP adapter
-or a published SDK. Neither artifact is a per-surface capability inventory, and there is no
-checked-in generated availability inventory. Do not infer release or runtime support from a
-record appearing in a schema.
-
-## Surface availability
-
-Checked on **2026-09-24**. This table records the known availability of each surface, not the
-negotiated capabilities of a particular session. Recheck release and feature availability before
-publishing or deploying a client.
-
-| | `stream-json` | RPC | ACP |
-| --- | --- | --- | --- |
-| **Release state** | **Shipped** in `main` | **On `main`**, not yet in a nightly or release | **Planned**, no implementation |
-| **Record reference** | Generated `protocol/schema.json` | Generated `protocol/rpc-schema.json` | No ACP record artifact or implemented surface |
-| **Evidence** | `src-tauri/src/core/cli/protocol_schema.rs:73-84,103-124`; the `protocol schema` job in `.github/workflows/rust-check.yml`; [PR #9023](https://github.com/janhq/jan/pull/9023) merged | `src-tauri/src/core/cli/rpc.rs:258-297`; `src-tauri/src/core/cli/rpc_schema.rs:87-106`; [PR #9049](https://github.com/janhq/jan/pull/9049) merged, [#360](https://github.com/janhq/jan-internal/issues/360) open | [#347](https://github.com/janhq/jan-internal/issues/347) open; no ACP subcommand in `src-tauri/jan-cli/src/main.rs:443-521` |
-
-A schema says which records a transport accepts or emits. A surface inventory would say what
-that surface *can* do, but the table above is an evidence-backed release snapshot, not a generated
-inventory and not a list of supported verbs. The `init` record for `stream-json` reports what
-**this run** accepts (see `src-tauri/src/core/cli/mod.rs:2106-2121` and
-[CLI protocol version](/docs/agent/cli#the-protocol-version)). RPC's `initialize` response reports
-what **this RPC session** negotiated (`src-tauri/src/core/cli/rpc.rs:286-297`). Do not copy
-`stream-json`'s `init` fields into RPC or treat a negotiated response as universal availability.
-
-<Callout type="warning">
-RPC is on `main` but not yet in a nightly or release. ACP remains planned. JavaScript and Python
-SDK packages are not released ([#367](https://github.com/janhq/jan-internal/issues/367)). Host tools
-exist on both `stream-json` (`--host-tools`) and RPC (below). See
-[what your build supports](/docs/agent/sdk#what-your-build-supports).
+Generate the schema from the **same binary your client will run**:
+
+```bash
+jan cli agent rpc-schema --out rpc-schema.json
+jan cli agent schema --out stream-schema.json
+```
+
+| Artifact | What to read |
+| --- | --- |
+| [`protocol/rpc-schema.json`](https://github.com/janhq/jan/blob/main/protocol/rpc-schema.json) | `protocol_version`, `envelope`, `requests`, `notifications` and `events` |
+| [`protocol/schema.json`](https://github.com/janhq/jan/blob/main/protocol/schema.json) | Root `input` and `output` schemas, `$defs`, and `x-protocol-version` |
+
+Both are generated from Rust types and checked for drift in CI. The repository links describe
+`main`; your installed binary can be older. RPC's schema covers requests and events, not every
+response shape. The method tables below document the host-tool responses.
+
+## Check runtime support
+
+Use RPC's `initialize` response for its negotiated protocol and capabilities. For stream-json,
+use that run's `init` record. These are not interchangeable capability inventories.
+
+<Callout type="info">
+The current SDKs use RPC. If your binary has no `rpc` command, update the nightly runtime.
+ACP is a separate, planned integration, not another name for either protocol.
</Callout>
+See the [RPC command reference](/docs/agent/cli#rpc) for startup and session methods, and
+[CLI protocol version](/docs/agent/cli#the-protocol-version) for the stream-json contract.
+
## RPC stream events
A turn's events reach the client as notifications named `item/<tag>`, where `<tag>` is the event's
own `type` on the `stream-json` surface: one naming rule for both, and no second list to keep in
sync. `protocol/rpc-schema.json` publishes the resulting notification names in its `events`
-section, generated from the same Rust enum that produces them (`src-tauri/src/core/cli/rpc.rs:736`),
-so a record can be looked up there rather than inferred from this page.
+section, generated from the same Rust enum that produces them. Look up the record there rather
+than maintaining a second event list in your client.
A `request_provenance` event therefore arrives as `item/request_provenance`, carrying the identity
of each outbound provider request (run, session, provider, model, wire API, body and tool-array
@@ -162,3 +154,90 @@ model id that no provider lists is refused as above.
Every mutating method is answered. A client that gets no answer, for example because the process
died, should treat the session as gone and close it. This fail-closed handling belongs to the SDK
or client, not the wire protocol.
+
+## Direct stream-json examples
+
+Prefer the SDK unless you need to own the pipes yourself. The runnable examples in
+[`examples/agent-sdk`](https://github.com/janhq/jan/tree/main/examples/agent-sdk) show that
+lower-level alternative. CI runs all four against a real runtime and checks these excerpts
+against their source. They are not the RPC SDK examples above.
+
+<details>
+<summary>Read a streamed answer without the SDK</summary>
+
+The complete scripts handle startup and cleanup. Their reading loops distinguish answer text
+from the terminal result:
+
+```js filename="examples/agent-sdk/js/first-turn.mjs"
+for await (const line of createInterface({ input: run.stdout })) {
+ const record = JSON.parse(line)
+ if (record.type === 'init') {
+ console.error(`[session ${record.session_id} on ${record.model}]`)
+ } else if (record.type === 'token') {
+ process.stdout.write(record.text)
+ } else if (record.type === 'result') {
+ result = record
+ }
+}
+```
+
+```python filename="examples/agent-sdk/python/first_turn.py"
+ for line in run.stdout:
+ record = json.loads(line)
+ if record["type"] == "init":
+ print(f"[session {record['session_id']} on {record['model']}]", file=sys.stderr)
+ elif record["type"] == "token":
+ print(record["text"], end="", flush=True)
+ elif record["type"] == "result":
+ result = record
+```
+
+</details>
+
+<details>
+<summary>Answer a host tool call without the SDK</summary>
+
+The complete scripts declare a weather fixture and handle permissions. These dispatch blocks
+show the extra work a direct client owns: looking up a handler, reporting errors and matching
+the request id. The SDK performs that dispatch for you.
+
+```js filename="examples/agent-sdk/js/host-tool.mjs"
+ case 'tool_request': {
+ // `tool_name` is the name declared above, without `host__`.
+ let content
+ let isError = false
+ try {
+ const handler = handlers[record.tool_name]
+ if (!handler) throw new Error(`no handler for ${record.tool_name}`)
+ content = JSON.stringify(handler(record.args))
+ } catch (error) {
+ // The model sees this as the tool's error.
+ content = `${error.name}: ${error.message}`
+ isError = true
+ }
+ console.error(`\n[${record.tool_name}(${JSON.stringify(record.args)}) -> ${content}]`)
+ send({ type: 'tool_result', request_id: record.request_id, content, is_error: isError })
+ break
+ }
+```
+
+```python filename="examples/agent-sdk/python/host_tool.py"
+ elif kind == "tool_request":
+ # `tool_name` is the name declared above, without `host__`.
+ handler = HANDLERS.get(record["tool_name"])
+ try:
+ if handler is None:
+ raise KeyError(f"no handler for {record['tool_name']}")
+ content, is_error = json.dumps(handler(record["args"])), False
+ except Exception as error: # the model sees this as the tool's error
+ content, is_error = f"{type(error).__name__}: {error}", True
+ print(f"\n[{record['tool_name']}({json.dumps(record['args'])}) -> {content}]", file=sys.stderr)
+ send({
+ "type": "tool_result",
+ "request_id": record["request_id"],
+ "content": content,
+ "is_error": is_error,
+ })
+```
+
+</details>
diff --git a/docs/src/pages/docs/agent/sdk-python.mdx b/docs/src/pages/docs/agent/sdk-python.mdx
index 79ea7b318..62d309b03 100644
--- a/docs/src/pages/docs/agent/sdk-python.mdx
+++ b/docs/src/pages/docs/agent/sdk-python.mdx
@@ -1,105 +1,147 @@
---
-title: Python Quickstart (Preview)
-description: Run your first embedded Jan Agent task from Python, using only the standard library.
-keywords: [Jan, Jan Agent, SDK, Python, subprocess, stream-json, quickstart, embedding]
+title: Python Quickstart
+description: Install the preview SDK, connect a model, and stream your first Jan Agent response from Python.
+keywords: [Jan, Jan Agent, SDK, Python, quickstart, embedding]
---
-import { Callout, Steps } from 'nextra/components'
+import { Callout, Steps, Tabs } from 'nextra/components'
-# Python Quickstart (Preview)
+# Python Quickstart
-Start Jan Agent from a Python script, stream its answer, and read the result. You need Python 3.9
-or newer and no packages - only the standard library.
+**Run a script that asks Jan a question and prints its answer as it arrives.**
+
+You need **Python 3.11+**, **Git**, and access to a model provider. No Node.js, Jan Desktop or Rust
+toolchain is needed. Python talks directly to the Jan runtime.
<Callout type="warning">
-Preview, `agent-nightly` channel only. There is no Python SDK package yet: this page drives the
-`jan` binary directly. See [Agent SDK](/docs/agent/sdk) for what the preview supports.
+The SDK is a preview and is not published to PyPI yet. Install the source package below, not
+`pip install jan-agent-sdk`. The runtime is a separate, prebuilt download.
</Callout>
<Steps>
-### Install Jan Agent and connect a provider
+### Install the SDK and runtime
+
+Create a demo directory and an isolated Python environment:
```bash
-curl -fsSL https://delta.jan.ai/jan-cli/install-jan-agent.sh | bash
-jan login # or: jan config set --provider anthropic --api-key sk-ant-...
+mkdir jan-python-demo
+cd jan-python-demo
```
-The [Agent quickstart](/docs/agent/quickstart) covers Windows and other providers. Check that a
-task runs from the terminal before you embed it: `jan cli agent run "say hi"`.
+<Tabs items={['macOS / Linux', 'Windows PowerShell']}>
+ <Tabs.Tab>
+```bash
+python3 -m venv .venv
+source .venv/bin/activate
+```
+ </Tabs.Tab>
+ <Tabs.Tab>
+```powershell
+py -3 -m venv .venv
+.venv\Scripts\Activate.ps1
+```
+ </Tabs.Tab>
+</Tabs>
+
+```bash
+git clone --depth 1 https://github.com/janhq/jan.git jan-source
+python -m pip install ./jan-source/sdk/python
+```
-### Get the example
+Only the SDK package is installed. You do not need to install or build the rest of the repository.
-Download
-[`first_turn.py`](https://github.com/janhq/jan/blob/main/examples/agent-sdk/python/first_turn.py),
-or run it from a checkout of the repository.
+Install the `jan` runtime:
-### Run it
+<Tabs items={['macOS / Linux', 'Windows PowerShell']}>
+ <Tabs.Tab>
+```bash
+bash jan-source/scripts/install-jan-agent.sh
+export PATH="$HOME/.local/bin:$PATH"
+```
+ </Tabs.Tab>
+ <Tabs.Tab>
+```powershell
+irm https://delta.jan.ai/jan-cli/install-jan-agent.ps1 | iex
+```
+Follow the installer's PATH instructions before continuing.
+ </Tabs.Tab>
+</Tabs>
```bash
-python3 first_turn.py "Explain what a mutex is in one sentence."
+jan cli agent rpc --help
```
-You should see the session and model on stderr, the answer as it streams, then the stop reason:
+If you already have a current Jan runtime, skip its installation.
-```text
-[session 46ae2e36-3ac4-425b-92a3-2eb1cb280787 on openai/gpt-6-sol]
-A mutex is a lock that ensures only one thread or process at a time can access a shared resource.
-[stop after 1 turn(s)]
+### Connect a model
+
+Sign in to Tokamak:
+
+```bash
+jan login
```
-The answer and the model depend on your provider.
+Or [configure your own provider](/docs/agent/quickstart#connect-a-provider). Both the CLI and SDK
+use Jan's provider configuration. If you have already configured Jan, skip this step.
-Set `JAN_BIN` if `jan` is not on your `PATH`, and `JAN_MODEL` to pick a model.
+### Save and run the script
-</Steps>
+Save this complete example as `hello.py` in `jan-python-demo`:
+
+```python filename="hello.py"
+from jan_agent_sdk import JanRuntime
+
+with JanRuntime.start() as runtime:
+ session = runtime.create_session(ephemeral=True, builtins=False)
+ turn = session.prompt("Explain what a mutex is in one sentence.")
+
+ for event in turn:
+ if event["type"] == "token":
+ print(event["text"], end="", flush=True)
-## What the code does
-
-It starts one run with `--output-format stream-json` and reads stdout line by line. Every line is
-one JSON record with a `type`:
-
-```python filename="examples/agent-sdk/python/first_turn.py"
-with tempfile.TemporaryDirectory() as project:
- cmd = [JAN, "cli", "agent", "run", "--project", project, "--output-format", "stream-json"]
- if os.environ.get("JAN_MODEL"):
- cmd += ["--model", os.environ["JAN_MODEL"]]
- cmd.append(task)
-
- run = subprocess.Popen(cmd, stdout=subprocess.PIPE, text=True)
- result = None
- for line in run.stdout:
- record = json.loads(line)
- if record["type"] == "init":
- print(f"[session {record['session_id']} on {record['model']}]", file=sys.stderr)
- elif record["type"] == "token":
- print(record["text"], end="", flush=True)
- elif record["type"] == "result":
- result = record
- run.wait()
+ result = turn.result()
+ if result.stop_reason == "error":
+ raise RuntimeError(result.error)
+ print(f"\nFinished: {result.stop_reason}")
```
-- **`init`** is the first line of a run that starts: the session id, the model, the tools this run
- advertises, and what it accepts on stdin. See
- [the protocol version](/docs/agent/cli#the-protocol-version).
-- **`token`** carries answer text as it streams. Other records - tool calls, tool results,
- reasoning, usage - arrive in between; a client ignores the types it does not handle.
-- **`result`** is always the last line: the final answer, `stop_reason`, `num_turns`, `usage`,
- and `is_error` with an `error` object on failure. See [JSON output](/docs/agent/cli#json-output).
+```bash
+python hello.py
+```
-`--project` points the run at a fresh temporary directory. The agent's built-in file and shell
-tools are confined to the project, so an example cannot change the directory you ran it from. Point
-it at a real project when you want the agent to work on one.
+The answer depends on your model. A successful run prints answer text followed by
+`Finished: completed`.
+
+</Steps>
+
+## What just happened?
+
+- `start()` launched the Jan runtime and checked its protocol version.
+- `create_session()` created a conversation. `ephemeral=True` avoids saving it; `builtins=False`
+ disables built-in and external tool sources, so this first example only answers a question.
+- `prompt()` started a turn. Each `token` event contains another piece of the answer.
+- `result()` returned the final status. Leaving the `with` block closed the runtime, including
+ when an exception occurred.
+
+Send another prompt on the same `session` to continue the conversation. To select a specific
+configured model, add `model="provider/model-id"` to `create_session()`.
+
+The Python API is synchronous: iterating a turn waits for events. In an async application, run
+blocking SDK work in a worker thread rather than on your event loop.
## If it fails
-| You see | Cause and fix |
+| Problem | What to do |
| --- | --- |
-| `FileNotFoundError: ... 'jan'` | `jan` is not on `PATH`. Set `JAN_BIN=/path/to/jan` |
-| `run failed: setup_error: no model specified ...` | No provider or model is configured. Run `jan login` or `jan config set`, or set `JAN_MODEL`. A setup failure prints the `result` alone, with no `init` line |
-| `run failed: upstream_error: ...` | The provider refused the request - often a wrong key or a model name the provider does not serve |
+| `ModuleNotFoundError: jan_agent_sdk` | Activate the demo's virtual environment and run the local `pip install` above with that Python. |
+| Cannot start `jan` | Add it to PATH, or pass its absolute path as `JanRuntime.start(bin="/path/to/jan")`. |
+| Unknown `rpc` command or protocol mismatch | Run `jan update`, then retry startup. |
+| No model, authentication error, or provider error | Run `jan login` or fix the provider configuration. A model override must name a model that provider serves. |
+
+See [Process & failures](/docs/agent/sdk-runtime) for error handling in an application.
-## Next
+## Next: give the agent a function
-Give the model a function to call in your code: [Host tools](/docs/agent/sdk-tools). To answer
-permission prompts, stop a run or handle exit codes, see [Process & failures](/docs/agent/sdk-runtime).
+The first script cannot act on your app. Add a [host tool](/docs/agent/sdk-tools) when you want it
+to read application data or perform an action.
diff --git a/docs/src/pages/docs/agent/sdk-runtime.mdx b/docs/src/pages/docs/agent/sdk-runtime.mdx
index d136bfe1b..707bb0edc 100644
--- a/docs/src/pages/docs/agent/sdk-runtime.mdx
+++ b/docs/src/pages/docs/agent/sdk-runtime.mdx
@@ -1,110 +1,148 @@
---
-title: Process & Failures (Preview)
-description: Own the jan process from an embedding app - lifecycle, permission prompts, stopping a run, exit codes, and which failures are safe to retry.
-keywords: [Jan, Jan Agent, SDK, stream-json, process, permissions, abort, exit codes, errors, retry]
+title: Process & Failures
+description: "Keep control of an embedded Jan runtime: close it, interrupt work, answer permissions, and handle failures without repeating side effects."
+keywords: [Jan, Jan Agent, SDK, process, permissions, errors, cancellation]
---
-import { Callout, Tabs } from 'nextra/components'
+import { Tabs } from 'nextra/components'
-# Process & Failures (Preview)
+# Process & Failures
-Your code owns the `jan` process: it starts it, answers it, and must see it end. This page covers
-the lifecycle of one run, the prompts your code answers, how to stop a run, and what each failure
-looks like - including which ones are safe to retry.
+**Your app owns the Jan process. Close it when you are done, and check how each turn ended.**
-<Callout type="warning">
-Preview, `agent-nightly` channel only; see [Agent SDK](/docs/agent/sdk) for what your build
-supports. The shapes named here are defined in the [CLI reference](/docs/agent/cli#streaming-json-in-both-directions).
-</Callout>
+The quickstarts already do both. This page explains what to change when your app needs multiple
+conversations, a Stop button, tool approval, or recovery from a failure.
-## One task, one process
+## Keep the runtime, reuse the session
-Start one `jan cli agent run` per task. It prints `init`, does the work, prints `result`, and
-exits. Everything your code parses is on **stdout**; stderr carries human-readable logs and
-warnings, so pass it through or log it, but don't parse it.
+- Start one runtime for your app's work, rather than one process per message.
+- Reuse a session to keep conversation history. Create another session for a separate conversation.
+- Wait for a turn to finish before starting another. One runtime runs one active turn at a time.
+- Use `ephemeral: true` / `ephemeral=True` when the conversation should not be saved.
-- **A run belongs to the process that started it.** Separate clients start separate processes;
- nothing attaches to a run from outside, and a session id does not either.
-- **Follow-ups join the running task.** A `user` message on stdin joins at the next turn boundary.
- Once the `result` is out, the run is over.
-- **Continue later in a new process** with `--resume=<id>`, using the `session_id` from `init`.
-- **Close and reap.** Close stdin once the `result` has arrived, then wait for the process to exit,
- so it never outlives your code. Both examples end this way:
+Always arrange cleanup, including on errors. In JavaScript, put `await runtime.close()` in a
+`finally` block. In Python, use `with JanRuntime.start() as runtime:`. The
+[JavaScript](/docs/agent/sdk-ts) and [Python](/docs/agent/sdk-python) quickstarts show both patterns.
+
+The SDK closes the channel and reaps its child process, escalating when the process does not exit.
+It does not attach to an existing process just because you know a session id.
+
+## Stop a turn, not the whole app
+
+Call `await session.interrupt()` in JavaScript or `session.interrupt()` in Python, for example
+from your application's Stop action. Keep consuming the turn and read its result:
+
+| Final status | Meaning |
+| --- | --- |
+| `completed` | The agent finished normally. |
+| `interrupted` | Work was stopped. Earlier tool side effects remain. |
+| `error` | The turn failed. Read the result's `error` message. |
+
+These are **RPC SDK** statuses: JavaScript uses `result.stopReason`; Python uses
+`result.stop_reason`. They are not the `stream-json` CLI's exit codes or `stop_reason` values.
+
+Closing the runtime ends all work owned by that process. Use forced close only when necessary:
+`await runtime.close({ force: true })` or `runtime.close(force=True)`.
+A handler that has already changed an external system cannot be rolled back by killing Jan.
+
+## Answer permission prompts
+
+If you leave `permissions` at its default, `jan`, a host actuator waits for your app's approval.
+Handle that event while consuming the turn. The example below **denies** requests until you add
+your own approval UI or policy:
<Tabs items={['JavaScript', 'Python']}>
<Tabs.Tab>
-```js filename="examples/agent-sdk/js/host-tool.mjs"
-run.stdin.end()
-const code = await exited
-rmSync(scratch, { recursive: true, force: true })
+```js
+for await (const event of turn) {
+ if (event.type === 'permission_request') {
+ await session.respondPermission(event.request_id, 'deny')
+ } else if (event.type === 'token') {
+ process.stdout.write(event.text)
+ }
+}
```
</Tabs.Tab>
<Tabs.Tab>
-```python filename="examples/agent-sdk/python/host_tool.py"
- run.stdin.close()
- run.wait()
+```python
+for event in turn:
+ if event["type"] == "permission_request":
+ session.respond_permission(event["request_id"], "deny")
+ elif event["type"] == "token":
+ print(event["text"], end="", flush=True)
```
</Tabs.Tab>
</Tabs>
-`--project` confines the agent's built-in file and shell tools to one directory; the examples use a
-fresh temporary directory, so a recipe cannot touch the directory you run it from.
+Answer with `allow_once`, `allow_always` where offered, or `deny`. Denying a tool call lets the
+model continue without that action. A `read` tool is not prompted.
-## Answer permission prompts
+If your application already gates every host action, set `permissions` to `host` instead. That
+removes Jan's approval step for host tools; it does not provide a replacement safety policy.
-A default headless run auto-approves every tool call, which is what an unattended script wants.
-Start it with `--safe` and your code decides instead: writes, shell commands, MCP tools and
-[host tools](/docs/agent/sdk-tools) each arrive as a `permission_request` first.
+## Handle the right kind of failure
-```text
-stdout {"type":"permission_request","request_id":"perm-1","tool_name":"host__get_weather","capability":"run","path":null,"prompt_kind":"mcp","offers_always":true}
-stdin {"type":"permission","request_id":"perm-1","decision":"allow_once"}
-stdout {"type":"permission_decision","request_id":"perm-1","decision":"allow_once"}
-```
+| Failure | How it appears | What your app should do |
+| --- | --- | --- |
+| Runtime cannot be installed | `JanInstallError` | Check the manifest, platform and checksum error. Do not bypass verification. |
+| Runtime cannot start, crashes, or speaks another protocol | `JanRuntimeError` | Close it, fix the binary/configuration issue, and start a new runtime. |
+| An RPC operation is refused | `JanRpcError` | Read its code and message. A busy-session error is retryable after the active turn ends. |
+| Provider authentication, model or request failure | Turn result with `error` status | Show the message. Fix the provider or model configuration before trying again. |
+| Your tool handler fails | Failed tool result sent to the model | Let the agent handle that result; do not assume the whole turn failed. |
-- `decision` is `allow_once`, `allow_always` (when `offers_always` is `true`) or `deny`.
-- A denied call reaches the model as a failed tool call, and the run goes on.
-- Each `request_id` is answered once.
-- The run waits for your answer. Closing stdin denies every prompt still pending and every prompt
- after it, and the run then finishes on its own.
+A completed stream is not proof of success: inspect the terminal result, as the quickstarts do.
+Do not discard `JanRuntimeError` diagnostics; stderr can explain why startup or the process failed.
-The [host tools example](/docs/agent/sdk-tools#3-decide-who-approves-the-call) approves its own
-tool and refuses everything else.
+### Retry only after checking side effects
-## Stop a run
+A retry can run your tools again. After any failure or disconnect, first reconcile writes,
+payments, device movements or other external actions that might already have happened. A missing
+answer does not prove an action never ran.
-- **Ask it to stop:** write `{"type":"abort"}`. The run ends with `stop_reason: "aborted"`,
- `is_error: false`, and exit code `0`. Tool calls that already ran are not undone.
-- **Bound it up front:** `--max-turns`, `--max-session-tokens` and `--max-budget-usd` - see
- [`run`](/docs/agent/cli#run).
-- **Kill the process** only as a last resort: there is no `result`, so the outcome of the task is
- unknown.
+## Download a runtime from code
-## Exit codes
+For deployments that do not put `jan` on PATH, the SDK can install the nightly runtime itself:
-| Code | Meaning |
-| --- | --- |
-| `0` | The run finished: a normal stop, `aborted`, or `budget_exceeded` |
-| `1` | The run failed. The `result` has `is_error: true` and an `error` object |
-| `2` | The command line was rejected - an unknown flag, for example. Nothing is printed on stdout |
-| `53` | `--max-turns` ran out while the model was still calling tools. The `result` has `is_error: true`; there is no final answer |
+<Tabs items={['JavaScript', 'Python']}>
+ <Tabs.Tab>
+```js
+import { installRuntime, JanRuntime } from '@janhq/agent-sdk'
+
+const installed = await installRuntime()
+const runtime = await JanRuntime.start({ bin: installed.bin })
+try {
+ console.log(runtime.serverInfo)
+} finally {
+ await runtime.close()
+}
+```
+ </Tabs.Tab>
+ <Tabs.Tab>
+```python
+from jan_agent_sdk import install_runtime, JanRuntime
-## Failures and retries
+installed = install_runtime()
+with JanRuntime.start(bin=installed.bin) as runtime:
+ print(runtime.server_info)
+```
+ </Tabs.Tab>
+</Tabs>
-A retry starts the task again in a new process. It is safe only if nothing with a side effect ran:
-every tool call the stream showed before the failure - a `tool_request` your code answered, a write
-or a shell command the run made - really happened, and runs again on a retry. Check the stream
-before retrying; never re-run a host side effect blindly.
+Installation downloads a prebuilt executable, verifies its published SHA-256, and caches it.
+It does not configure a model provider. Use the binary's `login` or `config set` command for that.
+`JAN_AGENT_HOME` selects the cache root. Previously returned binary paths remain valid across
+concurrent installs; remove old cache generations only when no runtime is using them.
-| Condition | What you see | Retry |
-| --- | --- | --- |
-| `jan` not found | `Error: spawn jan ENOENT` (Node.js), `FileNotFoundError` (Python) | Safe once fixed - nothing ran |
-| Flag unknown to this build | `error: unexpected argument ...` on stderr, exit `2` | Safe after `jan update` - nothing ran |
-| No model configured, or a bad `--host-tools` file | `result` alone, no `init`, `error.code: "setup_error"`, exit `1` | Safe once fixed - nothing ran |
-| Provider refused or failed | An `error` record, then `result` with `error.code: "upstream_error"`, exit `1` | Only if the stream showed no tool calls |
-| Conversation too long for the model | `error.code: "context_overflow"`, exit `1` | Only if the stream showed no tool calls; shorten the task or start a new session |
-| Turn cap reached | `error.message: "reached the N-turn limit while the model was still calling tools"`, exit `53` | Not as is: the tool calls it made already ran. Raise `--max-turns` or narrow the task |
-| Any other failure | `error.code` is the raw code, exit `1` | Check the stream first |
-| Your tool failed | Your `tool_result` with `is_error: true` - the model sees it and goes on | Not needed |
-| A line on stdin was invalid | An `input_error` record; the line is skipped and the run goes on | Fix the client |
-| The process crashed or was killed | stdout ends without a `result` | Outcome unknown: reconcile your own side effects first |
+For reproducible deployments, pass both `version` and `sha256` from the
+[nightly manifest](https://delta.jan.ai/agent-nightly/manifest.json) to the installer. They must
+match that manifest when a download is needed; an arbitrary historical version is not a download
+service. A matching pinned cache entry can be reused without network access.
+
+## Working directly with the CLI?
+
+The SDK uses a long-lived `jan cli agent rpc` process. A direct
+`jan cli agent run --output-format stream-json` integration is different: one run ends with a
+`result` record and a process exit. Do not mix its messages or status names with RPC.
+
+Use [Protocol records](/docs/agent/protocol) and the [CLI reference](/docs/agent/cli#run)
+for that lower-level path.
diff --git a/docs/src/pages/docs/agent/sdk-tools.mdx b/docs/src/pages/docs/agent/sdk-tools.mdx
index cf2ba9d53..005615f99 100644
--- a/docs/src/pages/docs/agent/sdk-tools.mdx
+++ b/docs/src/pages/docs/agent/sdk-tools.mdx
@@ -1,293 +1,156 @@
---
-title: Host Tools (Preview)
-description: Let Jan Agent call functions your own code executes - declare them, approve them, answer them, and handle the failures.
-keywords: [Jan, Jan Agent, SDK, host tools, tool calling, function calling, stream-json, embedding]
+title: Host Tools
+description: Give the agent a function in your app. Declare what it does, run the callback, and return a result.
+keywords: [Jan, Jan Agent, SDK, host tools, function calling, JavaScript, Python]
---
-import { Callout, Tabs } from 'nextra/components'
+import { Tabs } from 'nextra/components'
-# Host Tools (Preview)
+# Host Tools
-A host tool is a function the model calls and **your code** runs: a device only your process can
-reach, your application's own state, an API behind your credentials. You declare the tools when you
-start the run; each call arrives on stdout as a `tool_request`, and you answer it on stdin with a
-`tool_result`.
+**A host tool is a function in your app that the agent can ask to run.**
-<Callout type="warning">
-Host tools need a build whose `jan cli agent run --help` lists `--host-tools`. The `agent-nightly`
-build published on 2026-09-22 (`jan --version` prints `0.8.4-49`) predates them; run `jan update`
-once a newer nightly is out. On an older build the run fails with
-`error: unexpected argument '--host-tools' found` and exit code `2`.
-</Callout>
-
-## Run the example
-
-Each example declares one tool, `get_weather`, starts the run with `--safe` so that your code
-approves every side effect, and answers the call when the model makes it.
-
-<Tabs items={['JavaScript', 'Python']}>
- <Tabs.Tab>
-```bash
-node host-tool.mjs "What's the weather in Hanoi?"
-```
-
-Source: [`examples/agent-sdk/js/host-tool.mjs`](https://github.com/janhq/jan/blob/main/examples/agent-sdk/js/host-tool.mjs)
- </Tabs.Tab>
- <Tabs.Tab>
-```bash
-python3 host_tool.py "What's the weather in Hanoi?"
-```
-
-Source: [`examples/agent-sdk/python/host_tool.py`](https://github.com/janhq/jan/blob/main/examples/agent-sdk/python/host_tool.py)
- </Tabs.Tab>
-</Tabs>
-
-The call and its result are printed to stderr, then the answer that used them:
+The model chooses a tool and supplies arguments. The SDK calls your handler. Your handler's result
+goes back to the model, which can use it to answer or choose another action.
```text
-[get_weather({"city":"Hanoi"}) -> {"city":"Hanoi","forecast":"sunny","celsius":21}]
-It’s sunny in Hanoi and 21°C.
+Model asks for get_time -> your handler reads the clock -> model receives the time
```
-On the wire, one call is this sequence (other records omitted):
-
-```text
-stdout {"type":"init", ..., "tool_specs":[{"type":"function","function":{"name":"host__get_weather", ...}}]}
-stdout {"type":"permission_request","request_id":"perm-1","tool_name":"host__get_weather","prompt_kind":"mcp", ...}
-stdin {"type":"permission","request_id":"perm-1","decision":"allow_once"}
-stdout {"type":"permission_decision","request_id":"perm-1","decision":"allow_once"}
-stdout {"type":"tool_request","request_id":"host-1","tool_name":"get_weather","args":{"city":"Hanoi"}}
-stdin {"type":"tool_result","request_id":"host-1","content":"{\"city\":\"Hanoi\",...}","is_error":false}
-stdout {"type":"result","is_error":false,"stop_reason":"stop", ...}
-```
+First complete the [JavaScript](/docs/agent/sdk-ts) or [Python](/docs/agent/sdk-python) quickstart.
+These examples use the same installed SDK and provider configuration.
-## 1. Declare the tools
+## Add one real function
-Write the declarations to a JSON file and pass it with `--host-tools`, together with
-`--output-format stream-json --input-format stream-json` - only your code can answer a call, so it
-must be reading the stream and writing to stdin.
+This tool reads your machine's clock. It needs no API key of its own and changes no application state.
+Save the example in your quickstart directory and run it with `node clock.mjs` or `python clock.py`.
<Tabs items={['JavaScript', 'Python']}>
<Tabs.Tab>
-```js filename="examples/agent-sdk/js/host-tool.mjs"
-const tools = [
- {
- name: 'get_weather',
- description: 'Current weather for a city.',
- parameters: {
- type: 'object',
- properties: { city: { type: 'string' } },
- required: ['city'],
- additionalProperties: false,
- },
- },
-]
+```js filename="clock.mjs"
+import { JanRuntime } from '@janhq/agent-sdk'
+
+const runtime = await JanRuntime.start()
+try {
+ const session = await runtime.createSession({
+ ephemeral: true,
+ builtins: false,
+ tools: [{
+ name: 'get_time',
+ description: 'Read the current UTC time from this machine.',
+ parameters: { type: 'object', properties: {}, additionalProperties: false },
+ capability: 'read',
+ handler: () => new Date().toISOString(),
+ }],
+ })
+
+ const turn = await session.prompt('Use get_time and tell me the current UTC time.')
+ for await (const event of turn) {
+ if (event.type === 'token') process.stdout.write(event.text)
+ }
+ const result = await turn.result()
+ if (result.stopReason === 'error') throw new Error(result.error)
+ console.log(`\nFinished: ${result.stopReason}`)
+} finally {
+ await runtime.close()
+}
```
</Tabs.Tab>
<Tabs.Tab>
-```python filename="examples/agent-sdk/python/host_tool.py"
-TOOLS = [
- {
- "name": "get_weather",
- "description": "Current weather for a city.",
- "parameters": {
- "type": "object",
- "properties": {"city": {"type": "string"}},
- "required": ["city"],
- "additionalProperties": False,
- },
- }
-]
+```python filename="clock.py"
+from datetime import datetime, timezone
+from jan_agent_sdk import HostTool, JanRuntime
+
+
+def get_time(args, call):
+ return datetime.now(timezone.utc).isoformat()
+
+
+with JanRuntime.start() as runtime:
+ session = runtime.create_session(
+ ephemeral=True,
+ builtins=False,
+ tools=[HostTool(
+ name="get_time",
+ description="Read the current UTC time from this machine.",
+ parameters={"type": "object", "properties": {}, "additionalProperties": False},
+ capability="read",
+ handler=get_time,
+ )],
+ )
+
+ turn = session.prompt("Use get_time and tell me the current UTC time.")
+ for event in turn:
+ if event["type"] == "token":
+ print(event["text"], end="", flush=True)
+ result = turn.result()
+ if result.stop_reason == "error":
+ raise RuntimeError(result.error)
+ print(f"\nFinished: {result.stop_reason}")
```
</Tabs.Tab>
</Tabs>
-The model sees each tool as `host__<name>`, so it can never shadow one of Jan's own tools. The
-whole file is checked before the run starts, and one bad entry fails the run:
+The model receives the tool description and argument schema, **not your handler's source code**.
+It asks to call the tool; the SDK runs the handler in your process. No manual JSON messages are needed.
-| Rule | Refused with |
-| --- | --- |
-| Names are ASCII letters, digits, `_` and `-`, without `__` | `host tool name 'has space' must be ASCII letters, digits, '_' or '-' and cannot contain '__'` |
-| `host__<name>` is at most 64 characters; at most 128 tools per run | `... is too long` / `... more than the 128 a run accepts` |
-| A name is not one of Jan's own tools (`bash`, `read`, `ask`, `todo`, ...) | `host tool name 'bash' is reserved by a built-in tool` |
-| Each name is declared once | `host tool name 'a' is declared twice` |
-| Only `name`, `description` and `parameters`; `parameters` is a JSON object | The unknown key, or the tool whose `parameters` is not an object |
+## What a tool needs
-A refused file ends the run before it starts: stdout carries only the `result`, with
-`error.code: "setup_error"` and the reason in `error.message`, and `jan` exits with `1`.
+| Field | Purpose |
+| --- | --- |
+| `name` | A short identifier, such as `get_time`. Jan advertises it as `host__get_time` to avoid collisions. |
+| `description` | Tell the model when to use the tool and what it returns. |
+| `parameters` | A JSON Schema for the arguments. Jan validates supported constraints before calling you. |
+| `capability` | Use `read` for observation, or `actuator` for actions with side effects. |
+| `handler` | Your function, receiving the arguments and call context. |
-`parameters` is passed to the provider **verbatim**. Jan checks that it is an object, not that it
-is a schema the provider accepts: OpenAI, for one, refuses a tool whose schema is not
-`"type": "object"`, and that surfaces as an `upstream_error` on the first request. Leave
-`parameters` out for a tool that takes no arguments.
+Use simple names containing letters, digits, `_` or `-`; avoid `__`, reserved built-in names and
+duplicates. Keep names at most 58 characters so the `host__` prefix fits the wire limit.
-## 2. Check what the run advertised
+A schema checks shape, not authorization or physical safety. Your handler must still check
+whether the requested action is allowed. For hardware or shared state, serialize operations in
+your own application when necessary; callbacks can overlap, including calls from delegated children.
-The `init` record lists the schemas the run actually advertises in `tool_specs`. A tool you
-declared that is missing there was withheld by policy - read-only plan mode, or the deny list in
-your [tool permissions](/docs/agent/permissions) - and will never be called:
+## Return only what the model should see
-<Tabs items={['JavaScript', 'Python']}>
- <Tabs.Tab>
-```js filename="examples/agent-sdk/js/host-tool.mjs"
- case 'init': {
- // A declared tool missing here was withheld by policy (deny list, plan
- // mode) and will never be called.
- const advertised = new Set((record.tool_specs ?? []).map((spec) => spec.function.name))
- const missing = tools.map((t) => `host__${t.name}`).filter((name) => !advertised.has(name))
- if (missing.length) console.error(`withheld by policy: ${missing.join(', ')}`)
- break
- }
-```
- </Tabs.Tab>
- <Tabs.Tab>
-```python filename="examples/agent-sdk/python/host_tool.py"
- if kind == "init":
- # A declared tool missing here was withheld by policy (deny
- # list, plan mode) and will never be called.
- advertised = {spec["function"]["name"] for spec in record.get("tool_specs", [])}
- missing = {f"host__{t['name']}" for t in TOOLS} - advertised
- if missing:
- print(f"withheld by policy: {sorted(missing)}", file=sys.stderr)
-```
- </Tabs.Tab>
-</Tabs>
+A handler can return a string, as above, or an object:
-The set is fixed for the run: there is no message to add, remove or change a host tool once it has
-started.
+| Field | Goes to the model? | Example use |
+| --- | --- | --- |
+| `text` | Yes | A database query result or sensor reading |
+| `images` | Yes | An array of file paths, data URLs or image objects |
+| `details` | No | Host-only metadata for your UI |
+| `error` or `isError` | Yes, as a failed tool result | Explain why the action failed |
-## 3. Decide who approves the call
+Throwing an exception also produces a failed tool result. The agent can respond to that failure;
+it does not automatically mean the whole turn failed.
-A host tool is gated like an [MCP tool](/docs/agent/mcp). In a default headless run every tool call
-is auto-approved, host tools included. Start the run with `--safe` and the run asks first: a
-`permission_request` whose `prompt_kind` is `"mcp"` and whose `tool_name` is the `host__` name.
-Under `--safe` the same prompt comes for writes and shell commands, so the examples approve their
-own tool and refuse everything else:
+For image tools, use a vision-capable model and check `runtime.limits`. See
+[tool result images](/docs/agent/cli#tool-result-images) for provider-specific placement.
-<Tabs items={['JavaScript', 'Python']}>
- <Tabs.Tab>
-```js filename="examples/agent-sdk/js/host-tool.mjs"
- case 'permission_request':
- // Under `--safe` a host tool is prompted like an MCP tool, and so are
- // writes and shell commands. Approve ours; refuse the rest.
- send({
- type: 'permission',
- request_id: record.request_id,
- decision: record.tool_name.startsWith('host__') ? 'allow_once' : 'deny',
- })
- break
-```
- </Tabs.Tab>
- <Tabs.Tab>
-```python filename="examples/agent-sdk/python/host_tool.py"
- elif kind == "permission_request":
- # Under `--safe` a host tool is prompted like an MCP tool, and
- # so are writes and shell commands. Approve ours; refuse the rest.
- ours = record["tool_name"].startswith("host__")
- send({
- "type": "permission",
- "request_id": record["request_id"],
- "decision": "allow_once" if ours else "deny",
- })
-```
- </Tabs.Tab>
-</Tabs>
+## Decide who approves actions
-`allow_always` stops the run asking about that tool for the rest of the run. A denied call reaches
-the model as a failed tool call (`ERROR: tool 'host__get_weather' denied by user`), and the model
-carries on without it. More on answering prompts in
-[Process & failures](/docs/agent/sdk-runtime#answer-permission-prompts).
+A `read` tool such as the clock is not prompted. For an `actuator`:
-## 4. Answer the call
+- **Jan owns approval by default.** Your app must handle `permission_request` events and answer
+ them. Otherwise the turn waits. See [permission prompts](/docs/agent/sdk-runtime#answer-permission-prompts).
+- **Your app can own approval** with `permissions: 'host'` in JavaScript or `permissions="host"`
+ in Python. Jan will not ask for approval of host tools; your handler must enforce the policy.
-`tool_request.tool_name` is the name **you declared**, without `host__`, so you dispatch on your
-own names. Answer with a `tool_result` carrying the same `request_id`:
+`builtins: false` / `builtins=False` keeps this example limited to your declared tools. It is not
+an operating-system sandbox for your callback: that function still has your process's access.
-<Tabs items={['JavaScript', 'Python']}>
- <Tabs.Tab>
-```js filename="examples/agent-sdk/js/host-tool.mjs"
- case 'tool_request': {
- // `tool_name` is the name declared above, without `host__`.
- let content
- let isError = false
- try {
- const handler = handlers[record.tool_name]
- if (!handler) throw new Error(`no handler for ${record.tool_name}`)
- content = JSON.stringify(handler(record.args))
- } catch (error) {
- // The model sees this as the tool's error.
- content = `${error.name}: ${error.message}`
- isError = true
- }
- console.error(`\n[${record.tool_name}(${JSON.stringify(record.args)}) -> ${content}]`)
- send({ type: 'tool_result', request_id: record.request_id, content, is_error: isError })
- break
- }
-```
- </Tabs.Tab>
- <Tabs.Tab>
-```python filename="examples/agent-sdk/python/host_tool.py"
- elif kind == "tool_request":
- # `tool_name` is the name declared above, without `host__`.
- handler = HANDLERS.get(record["tool_name"])
- try:
- if handler is None:
- raise KeyError(f"no handler for {record['tool_name']}")
- content, is_error = json.dumps(handler(record["args"])), False
- except Exception as error: # the model sees this as the tool's error
- content, is_error = f"{type(error).__name__}: {error}", True
- print(f"\n[{record['tool_name']}({json.dumps(record['args'])}) -> {content}]", file=sys.stderr)
- send({
- "type": "tool_result",
- "request_id": record["request_id"],
- "content": content,
- "is_error": is_error,
- })
-```
- </Tabs.Tab>
-</Tabs>
+## Change tools or stop a callback
-- **Ask for the shape you want, then check anyway.** Before the request is emitted, Jan validates
- `args` against the `parameters` you declared, and a call that breaks the schema never reaches you:
- the model is told the mismatch and can try again. The check covers `type`, `properties`,
- `required`, `additionalProperties`, `items`, `minItems`, `maxItems`, `enum`, `const`, `minLength`,
- `maxLength`, `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum` and `pattern`; any other
- keyword is ignored, never failed. A schema is a shape, not a safety property - a handler that
- moves hardware still checks what it acts on.
-- **`content` is what the model sees.** It is either a string or a content-part array of `text` and
- `image_url` parts, held to the same caps as a `user` message. The parts' text becomes the run's
- tool message, and an image follows it as the next user turn - a provider's tool response carries
- text, so that is where an image can ride. There is no separate field for data only your UI shows:
- anything you put in `content` goes to the model.
-- **`details` stays yours.** The optional `details` object on a `tool_result` never leaves the
- client side: it is not in the tool message the model sees.
-- **Report a failure, don't drop the call.** `is_error: true` with the reason in `content` reaches
- the model as the tool's error, and the turn goes on. An unanswered call holds the run.
-- **Each `request_id` is answered once.** A second answer, or an answer to an id that is not
- pending, is reported as an `input_error` record (`no host tool request 'host-99' is pending`) and
- ignored; the run continues.
-- **Calls come one at a time**, in the order the model made them: the run waits for your
- `tool_result` before it sends the next `tool_request`, so a stateful device never sees two calls
- overlap.
-
-Closing stdin while a call is pending fails that call - the model receives
-`ERROR: host tool 'get_weather' was not answered: the client is gone` - and fails every host tool
-call after it. Keep stdin open until the `result` arrives.
-
-## If it fails
-
-| You see | Cause and fix |
-| --- | --- |
-| `error: unexpected argument '--host-tools' found`, exit `2` | The build predates host tools. `jan update` |
-| `setup_error` naming the `--host-tools` file | The declaration file broke a rule above, or could not be read |
-| `upstream_error` on the first request, naming `host__<name>` | The provider refused the tool's `parameters` schema |
-| `withheld by policy: ...` | Plan mode or the deny list removed the tool from this run |
-| The model never calls the tool | Name and describe it for the task, or ask for it in the prompt |
-| `input_error` after a `tool_result` | The `request_id` was already answered, or never issued |
+Between turns, use `session.setTools(...)` / `session.set_tools(...)` to replace the host tool set.
+The session's `tools` and `toolSpecs` / `tool_specs` report what Jan actually advertises.
-## Not in the preview yet
+When a request is cancelled, JavaScript receives an aborted `call.signal`; Python receives a set
+`call.aborted` threading event. Make long-running handlers cooperate with cancellation. An action
+that has already happened is not undone.
-- Changing the declared set during a run.
+## Next
-A subagent's host tool call reaches you exactly as the main run's does, attributed by the child's
-`run_id` (a main-run request carries none); children cannot dispatch children.
+[Process & failures](/docs/agent/sdk-runtime) covers stopping turns, permissions, shutdown and
+retries. [Protocol records](/docs/agent/protocol#rpc-host-tools) is the lower-level reference if
+you are implementing your own client.
diff --git a/docs/src/pages/docs/agent/sdk-ts.mdx b/docs/src/pages/docs/agent/sdk-ts.mdx
index c860ea171..35f4c516f 100644
--- a/docs/src/pages/docs/agent/sdk-ts.mdx
+++ b/docs/src/pages/docs/agent/sdk-ts.mdx
@@ -1,112 +1,131 @@
---
-title: JavaScript Quickstart (Preview)
-description: Run your first embedded Jan Agent task from Node.js, with no dependencies.
-keywords: [Jan, Jan Agent, SDK, JavaScript, TypeScript, Node.js, stream-json, quickstart, embedding]
+title: JavaScript Quickstart
+description: Install the preview SDK, connect a model, and stream your first Jan Agent response from Node.js.
+keywords: [Jan, Jan Agent, SDK, JavaScript, TypeScript, Node.js, quickstart]
---
-import { Callout, Steps } from 'nextra/components'
+import { Callout, Steps, Tabs } from 'nextra/components'
-# JavaScript Quickstart (Preview)
+# JavaScript Quickstart
-Start Jan Agent from a Node.js script, stream its answer, and read the result. You need Node.js 20
-or newer and no packages - only Node's built-in modules.
+**Run a script that asks Jan a question and prints its answer as it arrives.**
+
+You need **Node.js 20+**, **Git**, and access to a model provider. No Jan Desktop, Rust toolchain,
+or TypeScript build step is needed.
<Callout type="warning">
-Preview, `agent-nightly` channel only. There is no JavaScript or TypeScript SDK package yet: this
-page drives the `jan` binary directly. See [Agent SDK](/docs/agent/sdk) for what the preview
-supports.
+The SDK is a preview and is not published to npm yet. Install the source package below, not
+`npm install @janhq/agent-sdk`. The runtime is a separate, prebuilt download.
</Callout>
<Steps>
-### Install Jan Agent and connect a provider
+### Install the SDK and runtime
+
+In a new directory:
```bash
-curl -fsSL https://delta.jan.ai/jan-cli/install-jan-agent.sh | bash
-jan login # or: jan config set --provider anthropic --api-key sk-ant-...
+mkdir jan-js-demo
+cd jan-js-demo
+npm init -y
+git clone --depth 1 https://github.com/janhq/jan.git jan-source
+npm install ./jan-source/packages/agent-sdk
```
-The [Agent quickstart](/docs/agent/quickstart) covers Windows and other providers. Check that a
-task runs from the terminal before you embed it: `jan cli agent run "say hi"`.
-
-### Get the example
+Only the SDK package is installed. You do not need to install or build the rest of the repository.
-Download
-[`first-turn.mjs`](https://github.com/janhq/jan/blob/main/examples/agent-sdk/js/first-turn.mjs),
-or run it from a checkout of the repository.
+Install the `jan` runtime:
-### Run it
+<Tabs items={['macOS / Linux', 'Windows PowerShell']}>
+ <Tabs.Tab>
+```bash
+bash jan-source/scripts/install-jan-agent.sh
+export PATH="$HOME/.local/bin:$PATH"
+```
+ </Tabs.Tab>
+ <Tabs.Tab>
+```powershell
+irm https://delta.jan.ai/jan-cli/install-jan-agent.ps1 | iex
+```
+Follow the installer's PATH instructions before continuing.
+ </Tabs.Tab>
+</Tabs>
```bash
-node first-turn.mjs "Explain what a mutex is in one sentence."
+jan cli agent rpc --help
```
-You should see the session and model on stderr, the answer as it streams, then the stop reason:
+If you already have a current Jan runtime, skip its installation.
-```text
-[session 964f0e01-a6e3-4185-993c-dae73dbd4c39 on openai/gpt-6-sol]
-A mutex is a lock that lets only one thread or process access a shared resource at a time.
-[stop after 1 turn(s)]
+### Connect a model
+
+Sign in to Tokamak:
+
+```bash
+jan login
```
-The answer and the model depend on your provider. Set `JAN_BIN` if `jan` is not on your `PATH`,
-and `JAN_MODEL` to pick a model.
+Or [configure your own provider](/docs/agent/quickstart#connect-a-provider). Both the CLI and SDK
+use Jan's provider configuration. If you have already configured Jan, skip this step.
-</Steps>
+### Save and run the script
+
+Save this complete example as `hello.mjs` in `jan-js-demo`:
-## What the code does
-
-It starts one run with `--output-format stream-json` and reads stdout line by line. Every line is
-one JSON record with a `type`:
-
-```js filename="examples/agent-sdk/js/first-turn.mjs"
-const project = mkdtempSync(join(tmpdir(), 'jan-first-turn-'))
-const args = ['cli', 'agent', 'run', '--project', project, '--output-format', 'stream-json']
-if (process.env.JAN_MODEL) args.push('--model', process.env.JAN_MODEL)
-args.push(task)
-
-const run = spawn(jan, args, { stdio: ['ignore', 'pipe', 'inherit'] })
-const exited = new Promise((resolve) => run.on('close', resolve))
-
-let result = null
-for await (const line of createInterface({ input: run.stdout })) {
- const record = JSON.parse(line)
- if (record.type === 'init') {
- console.error(`[session ${record.session_id} on ${record.model}]`)
- } else if (record.type === 'token') {
- process.stdout.write(record.text)
- } else if (record.type === 'result') {
- result = record
+```js filename="hello.mjs"
+import { JanRuntime } from '@janhq/agent-sdk'
+
+const runtime = await JanRuntime.start()
+try {
+ const session = await runtime.createSession({ ephemeral: true, builtins: false })
+ const turn = await session.prompt('Explain what a mutex is in one sentence.')
+
+ for await (const event of turn) {
+ if (event.type === 'token') process.stdout.write(event.text)
}
+
+ const result = await turn.result()
+ if (result.stopReason === 'error') throw new Error(result.error)
+ console.log(`\nFinished: ${result.stopReason}`)
+} finally {
+ await runtime.close()
}
-const code = await exited
```
-- **`init`** is the first line of a run that starts: the session id, the model, the tools this run
- advertises, and what it accepts on stdin. See
- [the protocol version](/docs/agent/cli#the-protocol-version).
-- **`token`** carries answer text as it streams. Other records - tool calls, tool results,
- reasoning, usage - arrive in between; a client ignores the types it does not handle.
-- **`result`** is always the last line: the final answer, `stop_reason`, `num_turns`, `usage`,
- and `is_error` with an `error` object on failure. See [JSON output](/docs/agent/cli#json-output).
+```bash
+node hello.mjs
+```
-`--project` points the run at a fresh temporary directory. The agent's built-in file and shell
-tools are confined to the project, so an example cannot change the directory you ran it from. Point
-it at a real project when you want the agent to work on one.
+The answer depends on your model. A successful run prints answer text followed by
+`Finished: completed`.
-TypeScript works the same way. To type the records, generate types from the JSON Schema that
-[`jan cli agent schema`](/docs/agent/cli#schema) prints, on a build that has it (see
-[what your build supports](/docs/agent/sdk#what-your-build-supports)).
+</Steps>
+
+## What just happened?
+
+- `start()` launched the Jan runtime and checked its protocol version.
+- `createSession()` created a conversation. `ephemeral: true` avoids saving it; `builtins: false`
+ disables built-in and external tool sources, so this first example only answers a question.
+- `prompt()` started a turn. Each `token` event contains another piece of the answer.
+- `result()` returned the final status. `close()` ended the process, even if the script failed.
+
+Send another prompt on the same `session` to continue the conversation. To select a specific
+configured model, add `model: 'provider/model-id'` to `createSession()`.
+
+TypeScript uses the same API; the installed package includes type declarations.
## If it fails
-| You see | Cause and fix |
+| Problem | What to do |
| --- | --- |
-| `Error: spawn jan ENOENT` | `jan` is not on `PATH`. Set `JAN_BIN=/path/to/jan` |
-| `run failed: setup_error: no model specified ...` | No provider or model is configured. Run `jan login` or `jan config set`, or set `JAN_MODEL`. A setup failure prints the `result` alone, with no `init` line |
-| `run failed: upstream_error: ...` | The provider refused the request - often a wrong key or a model name the provider does not serve |
+| Cannot find `@janhq/agent-sdk` | Run the local `npm install` above and keep `hello.mjs` in the demo directory. |
+| Cannot start `jan` | Add it to PATH, or pass its absolute path as `JanRuntime.start({ bin: '/path/to/jan' })`. |
+| Unknown `rpc` command or protocol mismatch | Run `jan update`, then retry startup. |
+| No model, authentication error, or provider error | Run `jan login` or fix the provider configuration. A model override must name a model that provider serves. |
+
+See [Process & failures](/docs/agent/sdk-runtime) for error handling in an application.
-## Next
+## Next: give the agent a function
-Give the model a function to call in your code: [Host tools](/docs/agent/sdk-tools). To answer
-permission prompts, stop a run or handle exit codes, see [Process & failures](/docs/agent/sdk-runtime).
+The first script cannot act on your app. Add a [host tool](/docs/agent/sdk-tools) when you want it
+to read application data or perform an action.
diff --git a/docs/src/pages/docs/agent/sdk.mdx b/docs/src/pages/docs/agent/sdk.mdx
index 4f24d1454..f40e5404f 100644
--- a/docs/src/pages/docs/agent/sdk.mdx
+++ b/docs/src/pages/docs/agent/sdk.mdx
@@ -1,88 +1,81 @@
---
-title: Agent SDK (Preview)
-description: Embed Jan Agent in your own JavaScript or Python application - choose a path, and see what the nightly channel supports today.
-keywords:
- [
- Jan,
- Jan Agent,
- SDK,
- embedding,
- JavaScript,
- Python,
- stream-json,
- host tools,
- headless,
- ]
+title: Agent SDK
+description: Add an AI agent to your app. Start with a prompt, then give the agent functions your code can run.
+keywords: [Jan, Jan Agent, SDK, JavaScript, Python, embedding, host tools]
---
import { Callout } from 'nextra/components'
-# Agent SDK (Preview)
+# Agent SDK
-Want Jan Agent inside your own application - a script, a service, a robot controller - instead of
-in a terminal? You start `jan cli agent run` as a child process and talk to it over **`stream-json`**:
-one JSON record per line on stdout, one message per line on stdin. Your code sees every token, tool
-call and permission prompt, and can hand the agent **host tools**: tools your code executes.
+**Send a task from your app. Get a streamed answer. Let the agent call your functions when it needs to act.**
+
+Jan handles the conversation with the model and the loop of choosing a tool, reading its result,
+and deciding what to do next. Your app supplies the task, controls access to its tools, and displays the result.
+
+## Start with one response
+
+Choose the language your app already uses:
+
+- **[JavaScript quickstart](/docs/agent/sdk-ts)** - Node.js 20+, also usable from TypeScript.
+- **[Python quickstart](/docs/agent/sdk-python)** - Python 3.11+, no Node.js required.
+
+Both guides end with a complete script that prints an answer. You do not need to understand the
+wire protocol, manage subprocess pipes, or install Jan Desktop.
<Callout type="warning">
-The Agent SDK is a preview. It ships with Jan Agent in the `agent-nightly` channel, not in stable
-releases - expect nightly-quality builds. There is no SDK package to install yet: the recipes here
-drive the `jan` binary with nothing but Node.js or Python and their standard libraries.
+Preview: the SDK source is available, but the packages are not yet published to npm or PyPI.
+The quickstarts install the client from the Jan repository and use a prebuilt nightly runtime.
+No Rust build is required.
</Callout>
-## Choose your path
+## Three pieces, one app
-| You want to | Start here |
+```text
+Your app + SDK <-> Jan runtime <-> Model provider
+ |
+ +-- Your functions: read a sensor, query a database, call an API
+```
+
+| Piece | Its job |
| --- | --- |
-| Run a first embedded task from Node.js | [JavaScript quickstart](/docs/agent/sdk-ts) |
-| Run a first embedded task from Python | [Python quickstart](/docs/agent/sdk-python) |
-| Let the model call a function in your code | [Host tools](/docs/agent/sdk-tools) |
-| Own the process: permissions, stopping, failures, exit codes | [Process & failures](/docs/agent/sdk-runtime) |
-| Run several sessions in one long-lived process | [CLI reference: `rpc`](/docs/agent/cli#rpc) |
-| Look up a record's fields, or validate against the generated schemas | [Protocol records](/docs/agent/protocol) |
-| Use Jan interactively instead | [Quickstart](/docs/agent/quickstart) |
+| **SDK** | The JavaScript or Python library you import. It starts Jan, streams events and calls your tool handlers. |
+| **Runtime** | The separate `jan` executable. It manages conversations and the agent loop. |
+| **Model provider** | The service Jan sends model requests to. Configure a provider or sign in with `jan login`. |
-Every code block these pages attribute to a file is an excerpt of a runnable example in
-[`examples/agent-sdk/`](https://github.com/janhq/jan/tree/main/examples/agent-sdk). CI runs each
-example against `jan` built from the same commit, and fails when a page's excerpt no longer
-matches its source.
+The runtime runs locally, but that does **not** mean inference runs locally. Your configured
+provider receives the prompt and the tool results you return to the model.
-## How one run works
+## The three objects you use
-```text
- your app jan cli agent run
- | spawn --output-format stream-json |
- | --input-format stream-json |
- | <------------------------------ init --- | session, model, tools, caps
- | <------------- token, tool_call, ... --- | the run, as it happens
- | <---------------------- tool_request --- | the model called your host tool
- | ---- tool_result ----------------------> |
- | <---------------- permission_request --- | only when the run asks (--safe)
- | ---- permission -----------------------> |
- | <---------------------------- result --- | answer, stop reason, usage; the process exits
-```
+1. **Runtime** - the Jan process your app owns. Start it once; close it when your app is done.
+2. **Session** - one conversation, with its own history, model and tools.
+3. **Turn** - one prompt and the work it triggers. Stream its events, then read its final status.
+
+A runtime can hold multiple sessions, but runs one active turn at a time. Reuse a session for
+follow-up questions; create a new one for a separate conversation.
-One process runs one task. Follow-up messages on stdin join the same run, and `--resume` continues
-a saved session in a new process.
+## After your first response
+
+| Next goal | Guide |
+| --- | --- |
+| Let the agent call a function in your app | [Host tools](/docs/agent/sdk-tools) |
+| Stop work, close the process, or handle an error | [Process & failures](/docs/agent/sdk-runtime) |
+| Build your own client or inspect the JSON messages | [Protocol records](/docs/agent/protocol) |
+| Use Jan from a terminal instead of code | [Agent quickstart](/docs/agent/quickstart) |
## What your build supports
-Check the build you run rather than trusting a page: the `init` record says what this run accepts.
-
-| Capability | How to tell | Nightly `0.8.4-49` (published 2026-09-22) |
-| --- | --- | --- |
-| Streamed events and a terminal `result` | `init.protocol_version` is `1` | Yes |
-| Follow-ups, permission answers, `abort` | `init.input_kinds` lists `user`, `permission` and `abort` | Yes |
-| [Host tools](/docs/agent/sdk-tools) | `jan cli agent run --help` lists `--host-tools`; `init.input_kinds` lists `tool_result` | No - on `main`, arriving with the next nightly |
-| The generated JSON Schema | `jan cli agent schema` exists | No - on `main`, arriving with the next nightly |
-| Several sessions in one process over JSON-RPC | `jan cli agent --help` lists `rpc` | No - on `main`, arriving with the next nightly. `main` also serves host tools over RPC (`session/start` `tools`, `tool/respond`) |
-| Images in a `user` message | `init.input_content_parts` is not `null` | No - on `main`, arriving with the next nightly. `main` forwards the parts to the provider as written, images included |
-
-Not in any build yet: the JavaScript and Python SDK packages. On `main`, two more behaviours arrive
-with the next nightly: an image in a host tool result (it follows the tool message as a user turn,
-since a provider's tool response carries text), and a subagent's host tool call, which reaches you
-like the main run's, attributed by the child's `run_id`. Run `jan update` to move to the newest
-nightly.
-
-Capabilities here were checked on 2026-09-24 against `main` (`cc4927cff`) and the nightly named
-above; a build's own `init` record is the authority.
+The SDK uses `jan cli agent rpc`. Check that your runtime has it:
+
+```bash
+jan cli agent rpc --help
+```
+
+If the command is missing, update your nightly with `jan update`. The SDK checks protocol
+compatibility when it starts the runtime. A binary built from source must be rebuilt instead.
+
+For download locations and checksums, use the
+[nightly manifest](https://delta.jan.ai/agent-nightly/manifest.json). For negotiated capabilities
+and image limits, read `runtime.capabilities` and `runtime.limits` after SDK startup rather than
+assuming every nightly has the same features.