Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
docs(agent): Agent SDK preview pages and runnable examples
thinhlpgd22b443b7a0a
diff --git a/docs/src/pages/docs/agent/_meta.json b/docs/src/pages/docs/agent/_meta.jsonindex 0a2a27de2..cfd3e6c1c 100644--- a/docs/src/pages/docs/agent/_meta.json+++ b/docs/src/pages/docs/agent/_meta.json@@ -27,6 +27,10 @@"mcp": "MCP","embedding-separator": { "title": "Embedding", "type": "separator" },"sdk": "Agent SDK",+ "sdk-ts": "JavaScript Quickstart",+ "sdk-python": "Python Quickstart",+ "sdk-tools": "Host Tools",+ "sdk-runtime": "Process & Failures","protocol": "Protocol Records","reference-separator": { "title": "Reference", "type": "separator" },"cli": "CLI"diff --git a/docs/src/pages/docs/agent/sdk-python.mdx b/docs/src/pages/docs/agent/sdk-python.mdxnew file mode 100644index 000000000..79ea7b318--- /dev/null+++ b/docs/src/pages/docs/agent/sdk-python.mdx@@ -0,0 +1,105 @@+---+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]+---++import { Callout, Steps } from 'nextra/components'++# Python Quickstart (Preview)++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.++<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.+</Callout>++<Steps>++### Install Jan Agent and connect a provider++```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-...+```++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++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.++### Run it++```bash+python3 first_turn.py "Explain what a mutex is in one sentence."+```++You should see the session and model on stderr, the answer as it streams, then the stop reason:++```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)]+```++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.++</Steps>++## 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()+```++- **`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).++`--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.++## If it fails++| You see | Cause and fix |+| --- | --- |+| `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 |++## Next++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).diff --git a/docs/src/pages/docs/agent/sdk-runtime.mdx b/docs/src/pages/docs/agent/sdk-runtime.mdxnew file mode 100644index 000000000..d94f55c6a--- /dev/null+++ b/docs/src/pages/docs/agent/sdk-runtime.mdx@@ -0,0 +1,108 @@+---+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]+---++import { Callout, Tabs } from 'nextra/components'++# Process & Failures (Preview)++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.++<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>++## One task, one process++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.++- **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:++<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 })+```+ </Tabs.Tab>+ <Tabs.Tab>+```python filename="examples/agent-sdk/python/host_tool.py"+ run.stdin.close()+ run.wait()+```+ </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 permission prompts++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.++```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"}+```++- `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.++The [host tools example](/docs/agent/sdk-tools#3-decide-who-approves-the-call) approves its own+tool and refuses everything else.++## Stop a run++- **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.++## Exit codes++| 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 |++## Failures and retries++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.++| 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 |+| 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 |diff --git a/docs/src/pages/docs/agent/sdk-tools.mdx b/docs/src/pages/docs/agent/sdk-tools.mdxnew file mode 100644index 000000000..9d5b51401--- /dev/null+++ b/docs/src/pages/docs/agent/sdk-tools.mdx@@ -0,0 +1,284 @@+---+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]+---++import { Callout, Tabs } from 'nextra/components'++# Host Tools (Preview)++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`.++<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:++```text+[get_weather({"city":"Hanoi"}) -> {"city":"Hanoi","forecast":"sunny","celsius":21}]+It’s sunny in Hanoi and 21°C.+```++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", ...}+```++## 1. Declare the tools++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.++<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,+ },+ },+]+```+ </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,+ },+ }+]+```+ </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:++| 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 |++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`.++`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.++## 2. Check what the run advertised++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:++<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>++The set is fixed for the run: there is no message to add, remove or change a host tool once it has+started.++## 3. Decide who approves the call++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:++<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>++`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).++## 4. Answer the call++`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`:++<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>++- **Validate the arguments yourself.** `args` is what the model produced. Jan does not check it+ against your `parameters` schema before sending the request, so a handler that trusts it acts on+ whatever the model wrote. The examples' handlers check `city` before using it.+- **`content` is what the model sees**, as a string. There is no separate field for data only your+ UI shows: anything you put in `content` goes to the model.+- **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 |++## Not in the preview yet++- Images in a tool result: `content` is text.+- Host tools inside [subagents](/docs/agent/subagents): a subagent is given no host tools.+- Changing the declared set during a run.+- Schema validation of `args` by Jan.diff --git a/docs/src/pages/docs/agent/sdk-ts.mdx b/docs/src/pages/docs/agent/sdk-ts.mdxnew file mode 100644index 000000000..c860ea171--- /dev/null+++ b/docs/src/pages/docs/agent/sdk-ts.mdx@@ -0,0 +1,112 @@+---+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]+---++import { Callout, Steps } from 'nextra/components'++# JavaScript Quickstart (Preview)++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.++<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.+</Callout>++<Steps>++### Install Jan Agent and connect a provider++```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-...+```++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++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.++### Run it++```bash+node first-turn.mjs "Explain what a mutex is in one sentence."+```++You should see the session and model on stderr, the answer as it streams, then the stop reason:++```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)]+```++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.++</Steps>++## 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+ }+}+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).++`--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.++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)).++## If it fails++| You see | Cause and fix |+| --- | --- |+| `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 |++## Next++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).diff --git a/docs/src/pages/docs/agent/sdk.mdx b/docs/src/pages/docs/agent/sdk.mdxindex 8e384f754..a20256c5e 100644--- a/docs/src/pages/docs/agent/sdk.mdx+++ b/docs/src/pages/docs/agent/sdk.mdx@@ -1,53 +1,82 @@----title: Agent SDK-description: Choose a path for embedding Jan Agent and see which SDK guides are not yet available.-keywords: [Jan, Jan Agent, SDK, JavaScript, Python, embedding, stream-json, RPC]+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,+ ]---import { Callout } from 'nextra/components'-# Agent SDK+# Agent SDK (Preview)-Want to put Jan Agent inside your own application? Start with the transport you can use today.-The JavaScript and Python SDK packages are not released, so there is no SDK package to install or-SDK quickstart to run yet. [The Agent quickstart](/docs/agent/quickstart) is for using Jan from a-terminal, not for embedding an 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.++<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.+</Callout>## Choose your path-| You want to | State | Start here |-| --- | --- | --- |-| Use Jan interactively or run a one-shot CLI task | Available in the Jan CLI | [Agent quickstart](/docs/agent/quickstart) and [CLI reference](/docs/agent/cli) |-| Embed the current `stream-json` CLI transport | Shipped; your application owns the Jan process and stdin/stdout | [CLI `run` and `schema` reference](/docs/agent/cli#streaming-json-in-both-directions) and [generated record guide](/docs/agent/protocol) |-| Embed addressable sessions with RPC | Merged in [PR #9049](https://github.com/janhq/jan/pull/9049); not in a release yet | [CLI `rpc` reference](/docs/agent/cli#rpc) and [generated record guide](/docs/agent/protocol) |-| Let the model call tools your application runs | Available over `stream-json` (`--host-tools`) and RPC (`session/start` `tools`, `tool/respond`); not in a release yet | [RPC host tools](/docs/agent/protocol#rpc-host-tools) and [CLI `run` reference](/docs/agent/cli#streaming-json-in-both-directions) |-| Build a JavaScript or TypeScript app with the SDK | Planned; package not released ([#367](https://github.com/janhq/jan-internal/issues/367)) | Use `stream-json` now, or wait for the JS/TS SDK quickstart |-| Build a Python app with the SDK | Planned; package not released ([#367](https://github.com/janhq/jan-internal/issues/367)) | Use `stream-json` now, or wait for the Python SDK quickstart |+| You want to | Start here |+| --- | --- |+| 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) |+| Look up a record's fields, or validate against the generated schema | [CLI reference: streaming JSON](/docs/agent/cli#streaming-json-in-both-directions) |+| Use Jan interactively instead | [Quickstart](/docs/agent/quickstart) |-<Callout type="warning">-No JavaScript or Python Jan Agent SDK package is installable yet. RPC is merged but not in a-release, and it is a transport, not an SDK. Host tool callbacks work on both transports: declared,-correlated by request id, answered with text or content parts, and cancelled on interrupt.-</Callout>+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.++## How one run works++```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+```-## Guides and recipes on the way+One process runs one task. Follow-up messages on stdin join the same run, and `--resume` continues+a saved session in a new process.-These are planned pages, not links to runnable examples or released APIs:+## What your build supports-| Planned page | What it will cover | What it waits for |+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) || --- | --- | --- |-| JavaScript / TypeScript quickstart (`sdk-ts.mdx`) | First embedded turn, streamed outcome, one host tool, close | Released JS/TS SDK and host callbacks |-| Python quickstart (`sdk-python.mdx`) | Direct Python runtime, first turn, host tool, close without Node | Released Python SDK and host callbacks |-| Host tools (`sdk-tools.mdx`) | Callback validation, correlated results, permission and active tools as SDK calls | Released SDKs (the wire contract is in [RPC host tools](/docs/agent/protocol#rpc-host-tools)) |-| Images (`sdk-images.mdx`) | Prompt images, image-bearing results and sampled capture | Corresponding runtime and SDK support |-| Runtime and failures (`sdk-runtime.mdx`) | Process ownership, shutdown, permission and recovery | Released SDK runtime contract |-| Migration (`sdk-migration.mdx`) | Moving an existing `stream-json` harness to an SDK | Released SDKs and feature parity |-| Examples (`sdk-examples.mdx`) | Task-based index of checked-in, verified recipes | Runnable released-SDK examples |--For wire shapes you can inspect today, use the [generated protocol records](/docs/agent/protocol).-This page does not promise SDK install commands, versions or supported platforms before the-packages are released. Availability checked on 2026-09-24 against-[#367](https://github.com/janhq/jan-internal/issues/367),-[#368](https://github.com/janhq/jan-internal/issues/368),-[#386](https://github.com/janhq/jan-internal/issues/386) and-[PR #9049](https://github.com/janhq/jan/pull/9049); recheck at publication.+| 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 |+| Images in a `user` message | `init.input_content_parts` is not `null` | No. Builds from `main` accept and validate them but **do not forward them to the model yet**: only the text parts reach the provider |++Not in any build yet: images in a host tool result, host tools called from subagents, and the+JavaScript and Python SDK packages. Addressable sessions over JSON-RPC (`jan cli agent rpc`) are in+review in [janhq/jan#9049](https://github.com/janhq/jan/pull/9049), not released. Run `jan update`+to move to the newest nightly.diff --git a/examples/agent-sdk/js/first-turn.mjs b/examples/agent-sdk/js/first-turn.mjsnew file mode 100644index 000000000..7e4bc6bbd--- /dev/null+++ b/examples/agent-sdk/js/first-turn.mjs@@ -0,0 +1,52 @@+// Run one Jan Agent task from Node.js and stream the answer.+//+// Starts `jan cli agent run` with `--output-format stream-json`, prints the+// answer as it streams, and reads the terminal `result` record. No dependencies.+//+// node first-turn.mjs "Explain what a mutex is in one sentence."+//+// Set JAN_BIN to use a jan binary that is not on PATH, and JAN_MODEL to pick a model.++import { spawn } from 'node:child_process'+import { mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { createInterface } from 'node:readline'++const jan = process.env.JAN_BIN ?? 'jan'+const task = process.argv[2] ?? 'Reply with one short sentence: what is Jan Agent?'++// A fresh, empty project: the agent's own file and shell tools are confined to+// it, so an example cannot touch the directory you ran it from.+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+ }+}+const code = await exited+rmSync(project, { recursive: true, force: true })++console.log()+if (result === null) {+ console.error(`jan exited with ${code} before printing a result`)+ process.exit(1)+}+if (result.is_error) {+ console.error(`run failed: ${result.error.code}: ${result.error.message}`)+ process.exit(1)+}+console.error(`[${result.stop_reason} after ${result.num_turns} turn(s)]`)diff --git a/examples/agent-sdk/js/host-tool.mjs b/examples/agent-sdk/js/host-tool.mjsnew file mode 100644index 000000000..46ccd8a47--- /dev/null+++ b/examples/agent-sdk/js/host-tool.mjs@@ -0,0 +1,123 @@+// Give Jan Agent a tool that your Node.js code executes.+//+// Declares `get_weather` with `--host-tools`, checks the run advertised it,+// approves the permission prompt for it (the run is started with `--safe`, so+// your code decides every side effect), runs it when the model calls it, and+// sends the result back. Everything travels over the stream-json channel of+// `jan cli agent run`. No dependencies.+//+// node host-tool.mjs "What's the weather in Hanoi?"+//+// Set JAN_BIN to use a jan binary that is not on PATH, and JAN_MODEL to pick a model.++import { spawn } from 'node:child_process'+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { createInterface } from 'node:readline'++const jan = process.env.JAN_BIN ?? 'jan'+const task = process.argv[2] ?? "What's the weather in Hanoi? Use the get_weather tool."++// What the model sees, as `host__get_weather`. Jan validates the declaration+// before the run starts; the arguments are validated by your code, below.+const tools = [+ {+ name: 'get_weather',+ description: 'Current weather for a city.',+ parameters: {+ type: 'object',+ properties: { city: { type: 'string' } },+ required: ['city'],+ additionalProperties: false,+ },+ },+]++const handlers = {+ get_weather({ city }) {+ if (typeof city !== 'string') throw new Error("'city' must be a string")+ return { city, forecast: 'sunny', celsius: 21 }+ },+}++const scratch = mkdtempSync(join(tmpdir(), 'jan-host-tool-'))+const project = join(scratch, 'project')+mkdirSync(project)+const toolsFile = join(scratch, 'host-tools.json')+writeFileSync(toolsFile, JSON.stringify(tools))++const args = [+ 'cli', 'agent', 'run',+ '--project', project,+ '--safe',+ '--output-format', 'stream-json',+ '--input-format', 'stream-json',+ '--host-tools', toolsFile,+]+if (process.env.JAN_MODEL) args.push('--model', process.env.JAN_MODEL)+args.push(task)++const run = spawn(jan, args, { stdio: ['pipe', 'pipe', 'inherit'] })+const exited = new Promise((resolve) => run.on('close', resolve))+const send = (message) => run.stdin.write(JSON.stringify(message) + '\n')++let result = null+for await (const line of createInterface({ input: run.stdout })) {+ const record = JSON.parse(line)+ switch (record.type) {+ 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+ }+ 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+ 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+ }+ case 'token':+ process.stdout.write(record.text)+ break+ case 'result':+ result = record+ break+ }+}+run.stdin.end()+const code = await exited+rmSync(scratch, { recursive: true, force: true })++console.log()+if (result === null) {+ console.error(`jan exited with ${code} before printing a result`)+ process.exit(1)+}+if (result.is_error) {+ console.error(`run failed: ${result.error.code}: ${result.error.message}`)+ process.exit(1)+}diff --git a/examples/agent-sdk/python/first_turn.py b/examples/agent-sdk/python/first_turn.pynew file mode 100644index 000000000..09c495548--- /dev/null+++ b/examples/agent-sdk/python/first_turn.py@@ -0,0 +1,54 @@+"""Run one Jan Agent task from Python and stream the answer.++Starts `jan cli agent run` with `--output-format stream-json`, prints the answer+as it streams, and reads the terminal `result` record. Standard library only.++ python3 first_turn.py "Explain what a mutex is in one sentence."++Set JAN_BIN to use a jan binary that is not on PATH, and JAN_MODEL to pick a model.+"""++import json+import os+import subprocess+import sys+import tempfile++JAN = os.environ.get("JAN_BIN", "jan")+++def main() -> int:+ task = sys.argv[1] if len(sys.argv) > 1 else "Reply with one short sentence: what is Jan Agent?"+ # A fresh, empty project: the agent's own file and shell tools are confined+ # to it, so an example cannot touch the directory you ran it from.+ 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()++ print()+ if result is None:+ print(f"jan exited with {run.returncode} before printing a result", file=sys.stderr)+ return 1+ if result["is_error"]:+ print(f"run failed: {result['error']['code']}: {result['error']['message']}", file=sys.stderr)+ return 1+ print(f"[{result['stop_reason']} after {result['num_turns']} turn(s)]", file=sys.stderr)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/examples/agent-sdk/python/host_tool.py b/examples/agent-sdk/python/host_tool.pynew file mode 100644index 000000000..05b0bbaab--- /dev/null+++ b/examples/agent-sdk/python/host_tool.py@@ -0,0 +1,128 @@+"""Give Jan Agent a tool that your Python code executes.++Declares `get_weather` with `--host-tools`, checks the run advertised it,+approves the permission prompt for it (the run is started with `--safe`, so+your code decides every side effect), runs it when the model calls it, and+sends the result back. Everything travels over the stream-json channel of+`jan cli agent run`. Standard library only.++ python3 host_tool.py "What's the weather in Hanoi?"++Set JAN_BIN to use a jan binary that is not on PATH, and JAN_MODEL to pick a model.+"""++import json+import os+import subprocess+import sys+import tempfile++JAN = os.environ.get("JAN_BIN", "jan")++# What the model sees, as `host__get_weather`. Jan validates the declaration+# before the run starts; the arguments are validated by your code, below.+TOOLS = [+ {+ "name": "get_weather",+ "description": "Current weather for a city.",+ "parameters": {+ "type": "object",+ "properties": {"city": {"type": "string"}},+ "required": ["city"],+ "additionalProperties": False,+ },+ }+]+++def get_weather(args: dict) -> dict:+ if not isinstance(args.get("city"), str):+ raise ValueError("'city' must be a string")+ return {"city": args["city"], "forecast": "sunny", "celsius": 21}+++HANDLERS = {"get_weather": get_weather}+++def main() -> int:+ task = sys.argv[1] if len(sys.argv) > 1 else "What's the weather in Hanoi? Use the get_weather tool."+ with tempfile.TemporaryDirectory() as scratch:+ project = os.path.join(scratch, "project")+ os.mkdir(project)+ tools_file = os.path.join(scratch, "host-tools.json")+ with open(tools_file, "w") as f:+ json.dump(TOOLS, f)++ cmd = [+ JAN, "cli", "agent", "run",+ "--project", project,+ "--safe",+ "--output-format", "stream-json",+ "--input-format", "stream-json",+ "--host-tools", tools_file,+ ]+ if os.environ.get("JAN_MODEL"):+ cmd += ["--model", os.environ["JAN_MODEL"]]+ cmd.append(task)++ run = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)++ def send(message: dict) -> None:+ run.stdin.write(json.dumps(message) + "\n")+ run.stdin.flush()++ result = None+ for line in run.stdout:+ record = json.loads(line)+ kind = record["type"]+ 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)+ 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",+ })+ 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,+ })+ elif kind == "token":+ print(record["text"], end="", flush=True)+ elif kind == "result":+ result = record+ run.stdin.close()+ run.wait()++ print()+ if result is None:+ print(f"jan exited with {run.returncode} before printing a result", file=sys.stderr)+ return 1+ if result["is_error"]:+ print(f"run failed: {result['error']['code']}: {result['error']['message']}", file=sys.stderr)+ return 1+ return 0+++if __name__ == "__main__":+ sys.exit(main())