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.

feat(sdk): the JavaScript client for the agent runtime

thinhlpg8b23187a4065
diff --git a/packages/agent-sdk/README.md b/packages/agent-sdk/README.md
new file mode 100644
index 000000000..c4f76424e
--- /dev/null
+++ b/packages/agent-sdk/README.md
@@ -0,0 +1,178 @@
+# @janhq/agent-sdk
+
+JavaScript and TypeScript client for the Jan agent runtime: sessions, streamed
+turns, and the host tools your own process runs. It speaks the JSON-RPC channel
+of `jan cli agent rpc`, so an embedding application gets one long-lived runtime
+process serving many addressable sessions.
+
+- No build step, no runtime dependencies, Node 20+.
+- The runtime is spawned and owned: a crash, an EOF or a `close()` settles every
+ parked turn and tool call, and the process is reaped.
+- Types are generated from `protocol/rpc-schema.json`, the same document the
+ Rust dispatcher publishes.
+
+## Install
+
+```bash
+npm install @janhq/agent-sdk
+```
+
+The runtime binary is separate: `jan` must be on `PATH`, or named by
+`process.env.JAN_BIN` (the `bin` option overrides both). A package that ships
+the runtime is the distribution half of the same protocol; until then, build it
+with `make agent` in the Jan repository.
+
+## Quickstart
+
+```js
+import { JanRuntime } from '@janhq/agent-sdk'
+
+const runtime = await JanRuntime.start()
+const session = await runtime.createSession({ model: 'gpt-4o-mini', ephemeral: true })
+
+const turn = await session.prompt('Summarise this table in one line.')
+
+for await (const event of turn) {
+ if (event.type === 'token') process.stdout.write(event.text)
+}
+
+const { stopReason } = await turn.result()
+console.log(`\n${stopReason}`)
+
+await runtime.close() // closes stdin, then the process
+```
+
+`prompt()` returns as soon as the turn starts; the events stream while it runs,
+and `result()` resolves when the runtime closes the turn. Iterating is optional -
+a host that only awaits `result()` still gets the terminal record - but an
+undrained turn keeps at most `maxBufferedEvents` (default 100000) and then drops
+its oldest events, counting them on `turn.dropped`.
+
+## Host tools
+
+A host tool is declared with the schema the model sees, what it does, and the
+handler that runs it here:
+
+```js
+const session = await runtime.createSession({
+ model: 'gpt-4o-mini',
+ builtins: false, // only the tools below, no shell/editor/subagent tools
+ permissions: 'host', // this process runs and gates these tools itself
+ tools: [
+ {
+ name: 'camera_observe',
+ description: 'Look at the robot bench and describe what is there.',
+ parameters: { type: 'object', properties: {}, additionalProperties: false },
+ capability: 'read', // never prompted, run concurrently, visible in Plan mode
+ handler: async () => ({ text: 'the bench holds a red bin', images: [framePath] }),
+ },
+ {
+ name: 'robot_arm_move',
+ description: 'Move the arm to a named position.',
+ parameters: {
+ type: 'object',
+ properties: { position: { type: 'string' } },
+ required: ['position'],
+ },
+ capability: 'actuator', // prompted, sequential, withheld in Plan mode
+ handler: async (args, call) => {
+ await arm.move(args.position, { signal: call.signal })
+ return { text: `moved to ${args.position}`, details: { joints: 3 } }
+ },
+ },
+ ],
+})
+```
+
+What a handler answers with:
+
+| Field | Meaning |
+| --- | --- |
+| `text` | Tool text, sent to the model. |
+| `images` | A path, a data URL, `{ data, mimeType }`, or `{ url }`. A tool message cannot carry an image, so `text` stays on the tool message and the runtime leads the next user turn with the image parts. |
+| `details` | Host-only data, echoed as `item/tool_details` and never sent to the model. |
+| `error` / `isError` | The call failed; the message is the tool result the model sees. |
+
+A thrown error is answered the same way, so a failed call never leaves the turn
+parked. The handler runs without holding the client's reader: two subagents may
+have calls in flight at once, and serializing them - one native call at a time,
+on a shared robot - is the host's decision through its own queue. `call.signal`
+is aborted when the runtime withdraws the request (an interrupt, or the client
+going away), and a late answer is not written.
+
+Requests from a delegated child arrive on the same session, carrying
+`run_id`; answer is by `request_id` alone, so one path serves both.
+
+`session.tools` and `session.toolSpecs` are what the runtime advertises, read
+back rather than assumed: the names there are the declared ones with their
+`host__` prefix, because that is what the model calls. The `tool_request` a
+handler runs for carries the bare name the host declared.
+
+### Permissions
+
+An `actuator` is gated: the runtime asks before the call reaches the handler,
+unless the session declares that the gate is the host's own.
+
+- `permissions: 'host'` - for a session whose host tools this process runs and
+ gates itself, which is the usual case for an embedding host. No prompt is
+ raised for those tools, so a turn never waits on an answer nobody will give.
+- `permissions: 'jan'` (the default) - the runtime owns the gate. A call to an
+ `actuator` raises `permission_request` on the turn's stream, naming the
+ advertised tool (`host__robot_arm_move`) and its `capability`. Answer it with
+ `session.respondPermission(requestId, 'allow_once' | 'allow_always' | 'deny')`,
+ from the code draining the turn:
+
+```js
+for await (const event of turn) {
+ if (event.type === 'permission_request') {
+ await session.respondPermission(event.request_id, 'allow_once')
+ }
+}
+```
+
+An unanswered request parks the turn: nothing moves until it is answered, the
+turn is interrupted, or the runtime is closed. A `read` tool is never prompted
+for, in either mode.
+
+## Process ownership
+
+```js
+await session.interrupt() // the turn settles with stopReason 'interrupted'
+await session.setModel('...') // between turns; refused mid-turn with -32001
+await session.fork() // a new session with this one's history and model
+await session.archive() // drop it from the runtime
+await runtime.close() // close stdin, then the process
+await runtime.close({ force: true }) // skip the grace period and kill
+```
+
+`runtime.limits` is what the handshake advertised - `max_images`,
+`max_image_bytes`, `max_message_image_bytes` and the accepted `mime_types` - so
+a client that sends an image can check it before sending rather than discover
+the cap by being rejected. `JanRpcError` is an answer (`code`, `retryable`), and
+`JanRuntimeError` is the channel (spawn failure, protocol mismatch, exit), with
+the runtime's own stderr attached.
+
+## Types
+
+`src/index.d.ts` is the public surface. `src/generated/rpc-types.d.ts` is
+generated from `protocol/rpc-schema.json` - request params, the event union, and
+the method and event-tag literals:
+
+```bash
+yarn workspace @janhq/agent-sdk generate # rewrite the generated files
+yarn workspace @janhq/agent-sdk check-types # regenerate, diff, type-check
+```
+
+The artifact covers request params and events, not responses; `RpcResponses` in
+`src/index.d.ts` declares those and the suite pins them against a real runtime.
+
+## Tests
+
+The suite drives a real runtime against a stub provider on loopback - no
+credentials, no network:
+
+```bash
+JAN_BIN=/path/to/jan yarn workspace @janhq/agent-sdk test
+```
+
+It is skipped, not failed, when `JAN_BIN` is unset.
diff --git a/packages/agent-sdk/package.json b/packages/agent-sdk/package.json
new file mode 100644
index 000000000..c11ae6b4a
--- /dev/null
+++ b/packages/agent-sdk/package.json
@@ -0,0 +1,40 @@
+{
+ "name": "@janhq/agent-sdk",
+ "version": "0.1.0",
+ "description": "JavaScript and TypeScript client for the Jan agent runtime: sessions, streamed turns, and host tools over `jan cli agent rpc`",
+ "keywords": [
+ "jan",
+ "agent",
+ "sdk",
+ "json-rpc"
+ ],
+ "homepage": "https://jan.ai",
+ "license": "AGPL-3.0",
+ "author": "Jan <[email protected]>",
+ "type": "module",
+ "main": "src/index.js",
+ "types": "src/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./src/index.d.ts",
+ "default": "./src/index.js"
+ },
+ "./package.json": "./package.json"
+ },
+ "files": [
+ "src",
+ "README.md"
+ ],
+ "engines": {
+ "node": ">=20"
+ },
+ "scripts": {
+ "generate": "node scripts/generate.mjs",
+ "check-types": "node scripts/generate.mjs --check && tsc -p tsconfig.json",
+ "test": "node --test tests/sdk.test.mjs"
+ },
+ "devDependencies": {
+ "@types/node": "^22.10.0",
+ "typescript": "^5.6.2"
+ }
+}
diff --git a/packages/agent-sdk/scripts/generate.mjs b/packages/agent-sdk/scripts/generate.mjs
new file mode 100755
index 000000000..22c838e92
--- /dev/null
+++ b/packages/agent-sdk/scripts/generate.mjs
@@ -0,0 +1,431 @@
+#!/usr/bin/env node
+//! Generate the SDK wire types from the committed RPC schema.
+//!
+//! `protocol/rpc-schema.json` is the artifact CI regenerates from the Rust
+//! dispatcher (`jan cli agent rpc-schema --out protocol/rpc-schema.json`), so a
+//! verb cannot change without the document moving with it. This script is the
+//! other half of that guarantee: the JavaScript and Python SDKs derive their
+//! request, event and enum types from the same document, and `--check` fails
+//! when the committed output no longer matches it.
+//!
+//! One generator for both languages on purpose - the two SDKs are the same
+//! client in different runtimes, and two generators would be two chances to
+//! drift. Nothing here is hand-maintained except the naming rules.
+//!
+//! Usage:
+//! node packages/agent-sdk/scripts/generate.mjs
+//! node packages/agent-sdk/scripts/generate.mjs --schema <path> --ts <path> --py <path>
+//! node packages/agent-sdk/scripts/generate.mjs --check
+
+import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'
+import { dirname, join, resolve } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const here = dirname(fileURLToPath(import.meta.url))
+const repo = resolve(here, '../../..')
+
+const argv = process.argv.slice(2)
+const flag = (name, fallback) => {
+ const i = argv.indexOf(`--${name}`)
+ return i === -1 ? fallback : argv[i + 1]
+}
+const check = argv.includes('--check')
+const schemaPath = resolve(flag('schema', join(repo, 'protocol/rpc-schema.json')))
+const tsPath = resolve(flag('ts', join(repo, 'packages/agent-sdk/src/generated/rpc-types.d.ts')))
+const jsPath = resolve(flag('js', join(repo, 'packages/agent-sdk/src/generated/rpc-types.js')))
+const pyPath = resolve(flag('py', join(repo, 'sdk/python/jan_agent_sdk/_generated.py')))
+
+const doc = JSON.parse(readFileSync(schemaPath, 'utf8'))
+
+/// `tool_call_args_delta` -> `ToolCallArgsDelta`.
+const pascal = (tag) =>
+ tag
+ .split(/[^A-Za-z0-9]+/)
+ .filter(Boolean)
+ .map((part) => part[0].toUpperCase() + part.slice(1))
+ .join('')
+
+/// Collect every `$defs` entry in the document, refusing two definitions that
+/// share a name but disagree: the generated names are the only identity the
+/// SDKs have, so a silent redefinition would mis-type a whole field.
+const defs = new Map()
+const gather = (node) => {
+ if (Array.isArray(node)) return node.forEach(gather)
+ if (!node || typeof node !== 'object') return
+ for (const [name, def] of Object.entries(node.$defs ?? {})) {
+ const previous = defs.get(name)
+ if (previous && JSON.stringify(previous) !== JSON.stringify(def)) {
+ throw new Error(`$defs.${name} is defined twice with different shapes`)
+ }
+ defs.set(name, def)
+ }
+ for (const value of Object.values(node)) gather(value)
+}
+gather(doc)
+
+/// A `$ref` to a named definition, or `null` when the node stands alone.
+const refName = (node) => {
+ const ref = node?.$ref
+ return typeof ref === 'string' && ref.startsWith('#/$defs/') ? ref.slice('#/$defs/'.length) : null
+}
+
+/// The schema's own prose, as a comment in the target language. Rust doc
+/// comments carry the contract - "reasoning never joins the assistant content"
+/// is not decoration - so it is carried across rather than dropped.
+const comments = (text, indent, prefix) => {
+ const words = String(text ?? '')
+ .split('\n')
+ .map((line) => line.trim())
+ .filter(Boolean)
+ .join(' ')
+ if (!words) return []
+ if (prefix === '#') return [`${indent}# ${words}`]
+ return [`${indent}/** ${words.replace(/\*\//g, '*\\/')} */`]
+}
+
+// ---------------------------------------------------------------------------
+// TypeScript
+// ---------------------------------------------------------------------------
+
+const tsType = (node, indent = '') => {
+ if (node === true || node === undefined) return 'unknown'
+ if (node === false) return 'never'
+ if (Array.isArray(node.enum)) return node.enum.map((v) => JSON.stringify(v)).join(' | ')
+ if (node.const !== undefined) return JSON.stringify(node.const)
+ const named = refName(node)
+ if (named) return named
+ const oneOf = node.oneOf ?? node.anyOf
+ if (Array.isArray(oneOf)) return tsUnion(oneOf.map((part) => tsType(part, indent)))
+ const types = Array.isArray(node.type) ? node.type : node.type ? [node.type] : []
+ const parts = types.map((t) => {
+ if (t === 'string') return 'string'
+ if (t === 'integer' || t === 'number') return 'number'
+ if (t === 'boolean') return 'boolean'
+ if (t === 'null') return 'null'
+ if (t === 'array') return `${tsType(node.items ?? true, indent)}[]`
+ if (t === 'object') return tsInterfaceBody(node, indent)
+ return 'unknown'
+ })
+ if (!parts.length) return node.properties ? tsInterfaceBody(node, indent) : 'unknown'
+ return tsUnion(parts)
+}
+
+/// A member that accepts anything absorbs the rest of the union: `"read" |
+/// unknown` is just `unknown`, and printing both would only mislead.
+const tsUnion = (parts) => {
+ const unique = [...new Set(parts)]
+ return unique.includes('unknown') ? 'unknown' : unique.join(' | ')
+}
+
+/// An object with no named properties is `Record<string, unknown>`; anything
+/// with properties keeps them, so a consumer sees the actual keys.
+const tsInterfaceBody = (node, indent) => {
+ const props = Object.entries(node.properties ?? {})
+ if (!props.length) return 'Record<string, unknown>'
+ const required = new Set(node.required ?? [])
+ const inner = `${indent} `
+ const lines = props.flatMap(([name, value]) => [
+ ...comments(value.description, inner, '//'),
+ `${inner}${JSON.stringify(name)}${required.has(name) ? '' : '?'}: ${tsType(value, inner)}`,
+ ])
+ return `{\n${lines.join('\n')}\n${indent}}`
+}
+
+/// A named definition is an interface when it has properties, and an alias
+/// otherwise: `HostCapability` is `"read" | "actuator"`, and printing it as an
+/// empty interface would lose the union a host has to choose from.
+const tsInterface = (name, node) => {
+ const props = Object.entries(node.properties ?? {})
+ if (!props.length) return [...comments(node.description, '', '//'), `export type ${name} = ${tsType(node)}`]
+ const required = new Set(node.required ?? [])
+ const lines = props.flatMap(([prop, value]) => [
+ ...comments(value.description, ' ', '//'),
+ ` ${JSON.stringify(prop)}${required.has(prop) ? '' : '?'}: ${tsType(value, ' ')}`,
+ ])
+ return [...comments(node.description, '', '//'), `export interface ${name} {`, ...lines, '}']
+}
+
+// ---------------------------------------------------------------------------
+// Python
+// ---------------------------------------------------------------------------
+
+const PY_SCALARS = { string: 'str', integer: 'int', number: 'float', boolean: 'bool', null: 'None' }
+
+const pyType = (node) => {
+ if (node === true || node === undefined) return 'Any'
+ if (Array.isArray(node.enum)) {
+ return `Literal[${node.enum.map((v) => (typeof v === 'string' ? JSON.stringify(v) : v)).join(', ')}]`
+ }
+ if (node.const !== undefined) {
+ return typeof node.const === 'string' ? `Literal[${JSON.stringify(node.const)}]` : `Literal[${node.const}]`
+ }
+ const named = refName(node)
+ if (named) return named
+ const oneOf = node.oneOf ?? node.anyOf
+ if (Array.isArray(oneOf)) return pyUnion(oneOf.map(pyType))
+ const types = Array.isArray(node.type) ? node.type : node.type ? [node.type] : []
+ const mapped = types.map((t) => {
+ if (t === 'array') return `list[${pyType(node.items ?? true)}]`
+ return PY_SCALARS[t] ?? (t === 'object' || node.properties ? 'dict[str, Any]' : 'Any')
+ })
+ if (!mapped.length) return node.properties ? 'dict[str, Any]' : 'Any'
+ return pyUnion(mapped)
+}
+
+/// As in TypeScript: a member that accepts anything absorbs the rest.
+const pyUnion = (members) => {
+ const unique = [...new Set(members)]
+ if (unique.includes('Any')) return 'Any'
+ return unique.length === 1 ? unique[0] : `Union[${unique.join(', ')}]`
+}
+
+/// An inline object has no name to reference, and inventing one per nesting
+/// site would make the two languages disagree about the same document. The wire
+/// is the same value; only the annotation is loose.
+///
+/// TypedDict's class syntax takes bare identifiers as keys, so a key that is
+/// not one - a dotted or dashed name a host may declare - falls back to the
+/// functional form, which takes string literals and keeps the same shape.
+const pyTypedDict = (name, node, docstring) => {
+ const props = Object.entries(node.properties ?? {})
+ const required = new Set(node.required ?? [])
+ const identifier = /^[A-Za-z_][A-Za-z0-9_]*$/
+ const bare = props.every(([prop]) => identifier.test(prop))
+ if (!props.length && !docstring) return [`${name} = ${pyType(node)}`]
+ const entry = ([prop, value], indent) => [
+ ...comments(value.description, indent, '#'),
+ `${indent}${bare ? prop : JSON.stringify(prop)}: ${required.has(prop) ? '' : 'NotRequired['}${pyType(value)}${required.has(prop) ? '' : ']'}`,
+ ]
+ if (!bare) {
+ const fields = props.flatMap((prop) => entry(prop, ' '))
+ return [
+ `${name} = TypedDict(${JSON.stringify(name)}, {`,
+ ...fields.map((line) => (line.trimStart().startsWith('#') ? line : ` ${line.trimStart()}`)),
+ '})',
+ ]
+ }
+ const lines = [`class ${name}(TypedDict):`]
+ if (docstring) lines.push(` """${docstring}"""`)
+ if (!props.length) {
+ lines.push(' pass')
+ return lines
+ }
+ if (docstring) lines.push('')
+ lines.push(...props.flatMap((prop) => entry(prop, ' ')))
+ return lines
+}
+
+// ---------------------------------------------------------------------------
+// The document
+// ---------------------------------------------------------------------------
+
+/// One request per method, but several methods share a params struct - every
+/// `{sessionId}` verb is the same Rust type, and the schema titles them all
+/// `SessionIdParams`. A generated name is emitted once, so the shape behind it
+/// is checked rather than the name trusted.
+const params = new Map()
+const requests = Object.entries(doc.requests ?? {}).map(([method, node]) => {
+ const name = node.title ?? `${pascal(method)}Params`
+ const previous = params.get(name)
+ if (previous && JSON.stringify(previous) !== JSON.stringify(node)) {
+ throw new Error(`two request shapes share the generated name ${name}`)
+ }
+ params.set(name, node)
+ return { method, name, node }
+})
+const paramTypes = [...params.entries()].map(([name, node]) => ({
+ name,
+ node,
+ methods: requests.filter((request) => request.name === name).map((request) => request.method),
+}))
+
+const events = (doc.events?.oneOf ?? []).map((node) => {
+ const tag = node.properties?.type?.const ?? ''
+ if (!tag) throw new Error('an event carries no `type` const, so it has no tag to route on')
+ return { tag, name: `${pascal(tag)}Event`, node }
+})
+const tags = events.map((event) => event.tag)
+if (new Set(tags).size !== tags.length) throw new Error('two events carry the same `type` const')
+if (new Set(events.map((event) => event.name)).size !== events.length) {
+ throw new Error('two events generate the same type name')
+}
+
+/// The banner both files open with. The instruction is the same sentence in
+/// both, and it names the committed schema rather than a machine-local path.
+const banner = [
+ 'Generated from protocol/rpc-schema.json by packages/agent-sdk/scripts/generate.mjs.',
+ 'Do not edit by hand: run `node packages/agent-sdk/scripts/generate.mjs` after',
+ 'changing the Rust dispatcher, and commit the regenerated output with it.',
+]
+
+const emitTs = () => {
+ const out = []
+ out.push(...banner.map((line) => `// ${line}`))
+ out.push('')
+ // The values live in the sibling `.js`; these declarations are what a
+ // TypeScript consumer sees, and the generator writes both from one list.
+ out.push(`export declare const PROTOCOL_VERSION: ${doc.protocol_version}`)
+ out.push('')
+ out.push('/** The JSON-RPC methods this protocol accepts, in schema order. */')
+ out.push('export type RpcMethod =')
+ out.push(requests.map((request) => ` | ${JSON.stringify(request.method)}`).join('\n'))
+ out.push('')
+ out.push('/** The `type` tag of an event, which is also its `item/<tag>` method name. */')
+ out.push('export type EventTag =')
+ out.push(tags.map((tag) => ` | ${JSON.stringify(tag)}`).join('\n'))
+ out.push('')
+ out.push('export declare const EVENT_TAGS: readonly EventTag[]')
+ out.push('')
+ out.push('// ---------------------------------------------------------------------------')
+ out.push('// Shared definitions')
+ out.push('// ---------------------------------------------------------------------------')
+ for (const [name, node] of [...defs.entries()].sort(([a], [b]) => a.localeCompare(b))) {
+ out.push('')
+ out.push(...tsInterface(name, node))
+ }
+ out.push('')
+ out.push('// ---------------------------------------------------------------------------')
+ out.push('// Request parameters, one type per Rust params struct')
+ out.push('// ---------------------------------------------------------------------------')
+ for (const { name, node, methods } of paramTypes) {
+ out.push('')
+ out.push(`/** ${methods.map((method) => `\`${method}\``).join(', ')} */`)
+ out.push(...tsInterface(name, node))
+ }
+ out.push('')
+ out.push('/** The params a given method accepts, refused at compile time when they mismatch. */')
+ out.push('export type RpcParams<M extends RpcMethod> =')
+ for (const { name, methods } of paramTypes) {
+ out.push(` | (M extends ${methods.map((method) => JSON.stringify(method)).join(' | ')} ? ${name} : never)`)
+ }
+ out.push('')
+ out.push('// ---------------------------------------------------------------------------')
+ out.push('// Events: the payload of an `item/<tag>` notification')
+ out.push('// ---------------------------------------------------------------------------')
+ for (const event of events) {
+ out.push('')
+ out.push(...tsInterface(event.name, event.node))
+ }
+ out.push('')
+ out.push('/** Every event a session may report, discriminated on `type`. */')
+ out.push('export type StreamEvent =')
+ out.push(events.map((event) => ` | ${event.name}`).join('\n'))
+ out.push('')
+ out.push('/** The event a given tag carries. */')
+ out.push('export interface EventByTag {')
+ out.push(events.map((event) => ` ${JSON.stringify(event.tag)}: ${event.name}`).join('\n'))
+ out.push('}')
+ out.push('')
+ return out.join('\n')
+}
+
+const emitPy = () => {
+ const out = []
+ out.push(...banner.map((line) => `# ${line}`))
+ out.push('')
+ out.push('from __future__ import annotations')
+ out.push('')
+ out.push('from typing import Any, Literal, NotRequired, TypedDict, Union')
+ out.push('')
+ out.push(`PROTOCOL_VERSION = ${doc.protocol_version}`)
+ out.push('')
+ out.push('#: The JSON-RPC methods this protocol accepts, in schema order.')
+ out.push('RPC_METHODS: tuple[str, ...] = (')
+ out.push(requests.map((request) => ` ${JSON.stringify(request.method)},`).join('\n'))
+ out.push(')')
+ out.push('')
+ out.push('#: The ``type`` tag of an event, which is also its ``item/<tag>`` method name.')
+ out.push('EVENT_TAGS: tuple[str, ...] = (')
+ out.push(tags.map((tag) => ` ${JSON.stringify(tag)},`).join('\n'))
+ out.push(')')
+ out.push('')
+ out.push('RpcMethod = Literal[')
+ out.push(requests.map((request) => ` ${JSON.stringify(request.method)},`).join('\n'))
+ out.push(']')
+ out.push('')
+ out.push('EventTag = Literal[')
+ out.push(tags.map((tag) => ` ${JSON.stringify(tag)},`).join('\n'))
+ out.push(']')
+ out.push('')
+ out.push('# ' + '-'.repeat(73))
+ out.push('# Shared definitions')
+ out.push('# ' + '-'.repeat(73))
+ for (const [name, node] of [...defs.entries()].sort(([a], [b]) => a.localeCompare(b))) {
+ out.push('')
+ out.push(...comments(node.description, '', '#'))
+ out.push(...pyTypedDict(name, node))
+ }
+ out.push('')
+ out.push('# ' + '-'.repeat(73))
+ out.push('# Request parameters, one type per Rust params struct')
+ out.push('# ' + '-'.repeat(73))
+ for (const { name, node, methods } of paramTypes) {
+ out.push('')
+ out.push(...pyTypedDict(name, node, methods.map((method) => `\`${method}\``).join(', ')))
+ }
+ out.push('')
+ out.push('# ' + '-'.repeat(73))
+ out.push('# Events: the payload of an ``item/<tag>`` notification')
+ out.push('# ' + '-'.repeat(73))
+ for (const event of events) {
+ out.push('')
+ out.push(...pyTypedDict(event.name, event.node, `\`item/${event.tag}\``))
+ }
+ out.push('')
+ out.push('#: Every event a session may report, discriminated on ``type``.')
+ out.push('StreamEvent = Union[')
+ out.push(events.map((event) => ` ${event.name},`).join('\n'))
+ out.push(']')
+ out.push('')
+ return out.join('\n')
+}
+
+/// The runtime half of the generated types: two frozen values, and nothing
+/// else, so the package has no build step. The declarations they satisfy are in
+/// the sibling `rpc-types.d.ts`, written from the same list in the same run.
+const emitJs = () => {
+ const out = []
+ out.push(...banner.map((line) => `// ${line}`))
+ out.push('')
+ out.push(`export const PROTOCOL_VERSION = ${doc.protocol_version}`)
+ out.push('')
+ out.push('/** The `type` tag of every event, which is also its `item/<tag>` method name. */')
+ out.push('export const EVENT_TAGS = Object.freeze([')
+ out.push(tags.map((tag) => ` ${JSON.stringify(tag)},`).join('\n'))
+ out.push('])')
+ out.push('')
+ return out.join('\n')
+}
+
+const outputs = [
+ [tsPath, emitTs()],
+ [jsPath, emitJs()],
+ [pyPath, emitPy()],
+]
+
+if (check) {
+ const stale = []
+ for (const [path, expected] of outputs) {
+ let actual = ''
+ try {
+ actual = readFileSync(path, 'utf8')
+ } catch {
+ stale.push(`${path} (missing)`)
+ continue
+ }
+ if (actual !== expected) stale.push(path)
+ }
+ if (stale.length) {
+ console.error('generated SDK types are out of date with protocol/rpc-schema.json:')
+ for (const path of stale) console.error(` ${path}`)
+ console.error('run: node packages/agent-sdk/scripts/generate.mjs')
+ process.exit(1)
+ }
+ console.log(`generated SDK types match ${schemaPath}`)
+} else {
+ for (const [path, text] of outputs) {
+ mkdirSync(dirname(path), { recursive: true })
+ writeFileSync(path, text)
+ console.log(`wrote ${path}`)
+ }
+}
diff --git a/packages/agent-sdk/src/generated/rpc-types.d.ts b/packages/agent-sdk/src/generated/rpc-types.d.ts
new file mode 100644
index 000000000..5246ac44e
--- /dev/null
+++ b/packages/agent-sdk/src/generated/rpc-types.d.ts
@@ -0,0 +1,490 @@
+// Generated from protocol/rpc-schema.json by packages/agent-sdk/scripts/generate.mjs.
+// Do not edit by hand: run `node packages/agent-sdk/scripts/generate.mjs` after
+// changing the Rust dispatcher, and commit the regenerated output with it.
+
+export declare const PROTOCOL_VERSION: 1
+
+/** The JSON-RPC methods this protocol accepts, in schema order. */
+export type RpcMethod =
+ | "initialize"
+ | "session/list"
+ | "session/start"
+ | "session/resume"
+ | "session/fork"
+ | "session/archive"
+ | "turn/start"
+ | "turn/steer"
+ | "turn/interrupt"
+ | "permission/respond"
+ | "tool/respond"
+ | "session/tools/get"
+ | "session/tools/set"
+ | "session/model/set"
+ | "session/reset"
+
+/** The `type` tag of an event, which is also its `item/<tag>` method name. */
+export type EventTag =
+ | "token"
+ | "reasoning"
+ | "step"
+ | "tool_call_started"
+ | "tool_call_args_delta"
+ | "tool_call"
+ | "tool_output_delta"
+ | "tool_result"
+ | "subagent_start"
+ | "subagent_queued"
+ | "subagent_end"
+ | "subagent_plan"
+ | "subagent"
+ | "notice"
+ | "monitors"
+ | "parked"
+ | "messages_updated"
+ | "ask_request"
+ | "ask_resolved"
+ | "todo_update"
+ | "turn_usage"
+ | "done"
+ | "error"
+ | "permission_request"
+ | "tool_request"
+ | "tool_request_cancelled"
+ | "tool_details"
+
+export declare const EVENT_TAGS: readonly EventTag[]
+
+// ---------------------------------------------------------------------------
+// Shared definitions
+// ---------------------------------------------------------------------------
+
+export interface AskRequest {
+ "questions": Question[]
+}
+
+export interface ClientInfo {
+ "name": string
+ "version": string
+}
+
+/** What a host says a tool does, which decides how the loop treats it. Absent means opaque: prompted unless `auto_approve`, sequential, withheld in Plan mode -- the plugin/MCP default. */
+export type HostCapability = "read" | "actuator"
+
+/** The declaration shape, for the document only: the dispatcher parses the real `HostToolDecl`, which lives outside this module and carries no schema. */
+export interface HostToolDeclSchema {
+ "name": string
+ "description"?: string
+ /** JSON Schema for the arguments, advertised to the model verbatim. */
+ "parameters"?: Record<string, unknown> | null
+ "capability"?: HostCapability | null
+}
+
+/** Display-only view of one active monitor, for a status panel. */
+export interface MonitorSnapshot {
+ "monitorId": string
+ "name": string
+ "script": string
+ "polls": number
+}
+
+export interface OptionItem {
+ "label": string
+ "description"?: string | null
+}
+
+/** A subagent in a not-yet-started phase of a phased dispatch: its name (unique across the plan, and its blackboard file) and 1-based phase number. Carried by [`StreamEvent::SubagentPlan`] so a consumer can show it waiting on the phase before it. */
+export interface PendingSubagent {
+ "name": string
+ "phase": number
+}
+
+/** Who gates host tool calls. `jan` prompts through `permission_request` the way any opaque tool is prompted; `host` means the host's own callback is the gate, so Jan never asks about a host tool. */
+export type PermissionOwner = "jan" | "host"
+
+export interface Question {
+ "id": string
+ "question": string
+ "options": OptionItem[]
+ "multi"?: boolean
+ "recommended"?: number | null
+}
+
+export interface TodoItem {
+ "content": string
+ "status": TodoStatus
+}
+
+export interface TodoList {
+ "phases": TodoPhase[]
+}
+
+export interface TodoPhase {
+ "name": string
+ "tasks": TodoItem[]
+}
+
+export type TodoStatus = "pending" | "in_progress" | "completed" | "abandoned"
+
+/** A host tool's answer: text, or OpenAI content parts (`text` / `image_url` with a base64 `data:` URL) under the same caps as a user message. */
+export type ToolResultContent = string | unknown[]
+
+export interface Usage {
+ "prompt_tokens"?: number | null
+ "completion_tokens"?: number | null
+ "total_tokens"?: number | null
+ /** Prompt tokens served from the provider's prompt cache (a read/hit). OpenAI reports it under `prompt_tokens_details.cached_tokens`; Anthropic under `cache_read_input_tokens`. A thrashing cache shows here as a low value against a high `prompt_tokens`. */
+ "cached_tokens"?: number | null
+ /** Prompt tokens written into the provider cache this request (a write). Only Anthropic bills this separately (`cache_creation_input_tokens`); absent for providers that do not distinguish reads from writes. */
+ "cache_write_tokens"?: number | null
+}
+
+// ---------------------------------------------------------------------------
+// Request parameters, one type per Rust params struct
+// ---------------------------------------------------------------------------
+
+/** `initialize` */
+export interface InitializeParams {
+ "protocolVersion": number
+ "clientInfo": ClientInfo
+ "capabilities"?: unknown
+}
+
+/** `session/list` */
+export type SessionListParams = Record<string, unknown>
+
+/** `session/start` */
+export interface SessionStartParams {
+ "cwd": string
+ "model"?: string | null
+ "ephemeral"?: boolean
+ /** Host tools this session may call. Kept as raw values until declaration so a malformed entry is reported as `invalid_tools` with the reason, rather than as a generic params error that names nothing. */
+ "tools"?: HostToolDeclSchema[]
+ /** `false` advertises only the host tools: no built-ins, MCP, plugin, `ask`, `todo`, subagent or monitor tools. */
+ "builtins"?: boolean
+ "permissions"?: PermissionOwner
+}
+
+/** `session/resume`, `session/fork`, `session/archive`, `turn/interrupt`, `session/tools/get`, `session/reset` */
+export interface SessionIdParams {
+ "sessionId": string
+}
+
+/** `turn/start` */
+export interface TurnStartParams {
+ "sessionId": string
+ "input": unknown
+}
+
+/** `turn/steer` */
+export interface TurnSteerParams {
+ "sessionId": string
+ "input": string
+}
+
+/** `permission/respond` */
+export interface PermissionResponseParams {
+ "requestId": string
+ "decision": string
+}
+
+/** `tool/respond` */
+export interface ToolRespondParams {
+ "requestId": string
+ "content": ToolResultContent
+ "isError"?: boolean
+ /** Host/UI-only data, echoed as `item/tool_details` and never sent to the model. */
+ "details"?: Record<string, unknown> | null
+}
+
+/** `session/tools/set` */
+export interface SessionToolsSetParams {
+ "sessionId": string
+ "tools": HostToolDeclSchema[]
+}
+
+/** `session/model/set` */
+export interface SessionModelSetParams {
+ "sessionId": string
+ "model": string
+}
+
+/** The params a given method accepts, refused at compile time when they mismatch. */
+export type RpcParams<M extends RpcMethod> =
+ | (M extends "initialize" ? InitializeParams : never)
+ | (M extends "session/list" ? SessionListParams : never)
+ | (M extends "session/start" ? SessionStartParams : never)
+ | (M extends "session/resume" | "session/fork" | "session/archive" | "turn/interrupt" | "session/tools/get" | "session/reset" ? SessionIdParams : never)
+ | (M extends "turn/start" ? TurnStartParams : never)
+ | (M extends "turn/steer" ? TurnSteerParams : never)
+ | (M extends "permission/respond" ? PermissionResponseParams : never)
+ | (M extends "tool/respond" ? ToolRespondParams : never)
+ | (M extends "session/tools/set" ? SessionToolsSetParams : never)
+ | (M extends "session/model/set" ? SessionModelSetParams : never)
+
+// ---------------------------------------------------------------------------
+// Events: the payload of an `item/<tag>` notification
+// ---------------------------------------------------------------------------
+
+/** A streamed content delta from the model. */
+export interface TokenEvent {
+ "text": string
+ "type": "token"
+}
+
+/** A streamed reasoning delta, carried natively when the upstream exposes it as a dedicated field (`reasoning_content`). Display-only: reasoning never joins the assistant `content` that is resent as history, and it must never leak into piped stdout. Providers that instead inline `<think>` tags in `content` stream those through [`Token`]; consumers fall back to stripping the tags manually. */
+export interface ReasoningEvent {
+ "text": string
+ "type": "reasoning"
+}
+
+/** A new orchestration turn began (`index` is 1-based; `max` is the turn cap, `0` when the run is unbounded, which is the normal case). */
+export interface StepEvent {
+ "index": number
+ "max": number
+ "type": "step"
+}
+
+/** A tool call started streaming: emitted mid-stream the instant the model's tool-call `id` and `name` are known, before its arguments finish streaming. Lets a consumer show an in-progress indicator during the (potentially long) argument-streaming window; the full [`ToolCall`] with parsed `args` follows once the completion is assembled. */
+export interface ToolCallStartedEvent {
+ "id": string
+ "name": string
+ "type": "tool_call_started"
+}
+
+/** A chunk of a tool call's raw JSON arguments, exactly as it arrived on the wire. Emitted between [`ToolCallStarted`] and [`ToolCall`] so a consumer can render the arguments as they land -- the difference between a featureless spinner and a live preview while a large `write` streams. Deltas, not the accumulated buffer: re-sending the whole prefix on every chunk is quadratic in a file-sized argument. Consumers concatenate. The result is *incomplete JSON* until [`ToolCall`] arrives; parse it leniently or not at all. */
+export interface ToolCallArgsDeltaEvent {
+ "id": string
+ "delta": string
+ "type": "tool_call_args_delta"
+}
+
+/** The model requested a tool call. `args` is the parsed argument object (null if the model emitted non-JSON arguments). */
+export interface ToolCallEvent {
+ "id": string
+ "name": string
+ "args": unknown
+ "type": "tool_call"
+}
+
+/** A chunk of a tool's output, as it is produced. Emitted between [`ToolCall`] and [`ToolResult`] so a consumer can show a command's output while it runs instead of only once it exits. Deltas, not the accumulated buffer, for the same reason as [`ToolCallArgsDelta`]: resending the prefix on every chunk is quadratic in the output size. Chunks are raw fragments and may split a line. Keeps arriving after a `bash` call has backgrounded itself, so a long-running job reports progress under the id of the call that started it. */
+export interface ToolOutputDeltaEvent {
+ "id": string
+ "delta": string
+ "type": "tool_output_delta"
+}
+
+/** A tool finished. `is_error` reflects the upstream "ERROR" encoding. `diff` is display-only focused-change text (line-prefixed `-`/`+`) for `write`/`edit`; `None` for other tools. */
+export interface ToolResultEvent {
+ "id": string
+ "content": string
+ "is_error": boolean
+ "diff"?: string | null
+ "type": "tool_result"
+}
+
+/** A backgrounded subagent run began. `run_id` identifies the run so a consumer can attribute concurrent children; brackets the child's wrapped events with `SubagentEnd`. */
+export interface SubagentStartEvent {
+ "run_id": string
+ "name": string
+ /** The task the child was dispatched with -- its sole user message. Carried on the event rather than left for consumers to correlate back to the `dispatch_subagent` call: two dispatches can share a `subagent_name`, so matching on name alone is ambiguous. */
+ "task"?: string | null
+ "type": "subagent_start"
+}
+
+/** A backgrounded subagent dispatch found the parent run's concurrency cap (`max_parallel_subagents`) exhausted and queued the child in FIFO order. `waiting` is the child's 1-based position in the queue (1 = next to start). The child's `SubagentStart` follows once a slot frees; a queued child aborted at parent teardown is closed by `SubagentEnd` like any other. */
+export interface SubagentQueuedEvent {
+ "run_id": string
+ "name": string
+ "task"?: string | null
+ "waiting": number
+ "type": "subagent_queued"
+}
+
+/** A backgrounded subagent run finished (success or error). Pairs with the `SubagentStart` of the same `run_id`. */
+export interface SubagentEndEvent {
+ "run_id": string
+ "name": string
+ /** Why the child failed, when it did: the same reason the parent's `<SYSTEM>` completion ping carries. Carried on the event because a background child's answer never reaches a consumer -- only the model reads it -- so without this a failed run is indistinguishable from a clean one on screen. `None` for a clean finish, and for a child cut off at parent teardown, which is not its own failure. */
+ "error"?: string | null
+ "type": "subagent_end"
+}
+
+/** The later phases of a phased dispatch, named up front so a consumer can show their subagents as WAITING on an earlier phase before they start. Each pending subagent is promoted by its own `SubagentStart` (or `SubagentQueued`), matched by `name`, which is unique across a plan. Display-only and never journaled; emitted only by the top-level run (children cannot dispatch), so it is never wrapped in `Subagent`. */
+export interface SubagentPlanEvent {
+ "pending": PendingSubagent[]
+ "type": "subagent_plan"
+}
+
+/** A backgrounded subagent's own internal event, tagged with its run so a consumer can attribute it to the right child even when several run concurrently. `event` is a non-terminal child event (Token/Step/ToolCall/ ToolResult/PermissionRequest); the child's terminal Done/Error is never wrapped (its result is delivered via `await_subagent`). Never a `ToolRequest`: a client answers a request by `request_id` on stdin, and it is told nothing about this wrapper, so a nested request would be unanswerable. A child's host tool call is routed to the root channel unwrapped instead, attributed by `ToolRequest.run_id`. */
+export interface SubagentEvent {
+ "run_id": string
+ "name": string
+ "event": unknown
+ "type": "subagent"
+}
+
+/** The user-facing headline of a background ping the loop just delivered to the model as a `<SYSTEM>` reminder (today: a `monitor` condition matching). Emitted at delivery, not when the ping is queued, so the transcript reads in the order the model saw things. Display-only and transient, like notes: it is never journaled. */
+export interface NoticeEvent {
+ "text": string
+ "type": "notice"
+}
+
+/** The run's active file monitors, as a whole replacing the previous set. Emitted whenever the set changes (a `monitor` start or stop, a condition matching, a monitor finishing), so a consumer keeps a live view without bookkeeping of its own. Display-only and never journaled. Not forwarded from a child: a child's monitors are its own. */
+export interface MonitorsEvent {
+ "monitors": MonitorSnapshot[]
+ "type": "monitors"
+}
+
+/** The model has finished its turn and the loop is parked on background work it started (a subagent still running, a monitor still watching). Nothing is being generated until a ping resumes the run, which the next `Step` marks. Lets a consumer say "watching" rather than "working". */
+export interface ParkedEvent {
+ "type": "parked"
+}
+
+/** The client should replace its session history with `messages` before subsequent turns. Includes accepted prompt guidance in its original position, but not a pending block from an unsuccessful request. Also carries compacted history when the loop retries a context overflow. */
+export interface MessagesUpdatedEvent {
+ "messages": unknown[]
+ "type": "messages_updated"
+}
+
+/** The `ask` tool is waiting for structured interactive input. Carries the `ask_timeout_secs` deadline (seconds until the loop auto-selects the recommended option) as `timeout_secs`, or `None` when no timeout is configured. It travels on the event so a client can render a countdown without re-reading config: the same value both arms the loop's timer and drives the display, keeping the two in agreement. */
+export interface AskRequestEvent {
+ "request_id": string
+ "request": AskRequest
+ "timeout_secs"?: number | null
+ "type": "ask_request"
+}
+
+/** An `ask` request the loop resolved without a user answer (it timed out and auto-selected). Tells a client showing the live prompt for `request_id` to dismiss it, since no `respond` from that client is coming. User-driven answers never emit this: the client clears its own prompt as it responds. */
+export interface AskResolvedEvent {
+ "request_id": string
+ "type": "ask_resolved"
+}
+
+/** The canonical todo list changed (tool mutation or user edit in the TUI). Carries the full resulting snapshot for reconstruction. */
+export interface TodoUpdateEvent {
+ "list": TodoList
+ "type": "todo_update"
+}
+
+/** Token usage for a single upstream request, emitted as soon as that request completes rather than waiting for the run to finish. `Done` carries only the *last* request's usage, which is too late and too little for a live display: a turn that calls tools makes many requests, and a subagent never emits `Done` into the parent stream at all. Consumers accumulate these to show context pressure, output volume, and throughput while the work is still happening -- for the parent run and, via the [`Subagent`] bracket, for each child. */
+export interface TurnUsageEvent {
+ "usage": Usage
+ /** The provider's id for the execution that produced this usage, when it reported one. This is the handle a per-request billing lookup is keyed by, so a consumer can ask what this one request actually cost rather than only what it estimates. A sibling of `usage` rather than a field inside it, because it is a billing handle and not a token count. Absent on the default upstream path, which cannot see the response headers (see [`crate::core::agent::correlation`]); that is a limitation to report, not a reason to synthesize one. */
+ "execution_id"?: string | null
+ "type": "turn_usage"
+}
+
+/** Terminal success: the model returned a final (tool-free) completion. */
+export interface DoneEvent {
+ "stop_reason": string
+ "usage"?: Usage | null
+ "type": "done"
+}
+
+/** Terminal failure (setup error, upstream/tool failure, or max_turns). */
+export interface ErrorEvent {
+ "code": string
+ "message": string
+ "type": "error"
+}
+
+/** The loop needs the user to approve a gated tool call. The client replies via the `agent_permission_respond` command referencing `request_id`. */
+export interface PermissionRequestEvent {
+ "request_id": string
+ "tool_name": string
+ "capability": string
+ "path"?: string | null
+ /** The shell command for exec prompts (drives the command-scoped "allow always" grant); `None` for non-exec tools. */
+ "command"?: string | null
+ /** Focused diff preview for `write`/`edit` prompts so the user sees the change before approving; `None` for other tools. */
+ "diff"?: string | null
+ "prompt_kind": string
+ "offers_always": boolean
+ "type": "permission_request"
+}
+
+/** A host-registered tool was called and the run is waiting for the host to execute it. The client replies with a `tool_result` line carrying this `request_id`; until it does, the turn is parked on this one call. `tool_name` is the name the *host* declared, not the `host__`-prefixed name the model calls: the host dispatches on the name it chose and never has to know this layer's prefixing rule. */
+export interface ToolRequestEvent {
+ "request_id": string
+ "tool_name": string
+ /** The arguments the model produced, already parsed from the call's JSON string. Validated against nothing here -- the host owns the schema it declared and is the only party that can enforce it. */
+ "args": unknown
+ /** Which run raised the request: `None` for the main run, the child's run id for a subagent. Attribution only -- the host answers by `request_id` alone, and a child's request is emitted unwrapped at the top level so the same answer path serves both. */
+ "run_id"?: string | null
+ "type": "tool_request"
+}
+
+/** A pending [`StreamEvent::ToolRequest`] was withdrawn: the host must not answer it any more, and a late answer is reported as not pending. `reason` is `aborted` | `interrupted` | `client_gone`. */
+export interface ToolRequestCancelledEvent {
+ "request_id": string
+ "reason": string
+ "type": "tool_request_cancelled"
+}
+
+/** Host/UI-only structured data a host tool returned alongside its result, emitted right after that call's [`StreamEvent::ToolResult`] (same `id`). Never sent to the model; a display may render it or ignore it. */
+export interface ToolDetailsEvent {
+ "id": string
+ "details": unknown
+ "type": "tool_details"
+}
+
+/** Every event a session may report, discriminated on `type`. */
+export type StreamEvent =
+ | TokenEvent
+ | ReasoningEvent
+ | StepEvent
+ | ToolCallStartedEvent
+ | ToolCallArgsDeltaEvent
+ | ToolCallEvent
+ | ToolOutputDeltaEvent
+ | ToolResultEvent
+ | SubagentStartEvent
+ | SubagentQueuedEvent
+ | SubagentEndEvent
+ | SubagentPlanEvent
+ | SubagentEvent
+ | NoticeEvent
+ | MonitorsEvent
+ | ParkedEvent
+ | MessagesUpdatedEvent
+ | AskRequestEvent
+ | AskResolvedEvent
+ | TodoUpdateEvent
+ | TurnUsageEvent
+ | DoneEvent
+ | ErrorEvent
+ | PermissionRequestEvent
+ | ToolRequestEvent
+ | ToolRequestCancelledEvent
+ | ToolDetailsEvent
+
+/** The event a given tag carries. */
+export interface EventByTag {
+ "token": TokenEvent
+ "reasoning": ReasoningEvent
+ "step": StepEvent
+ "tool_call_started": ToolCallStartedEvent
+ "tool_call_args_delta": ToolCallArgsDeltaEvent
+ "tool_call": ToolCallEvent
+ "tool_output_delta": ToolOutputDeltaEvent
+ "tool_result": ToolResultEvent
+ "subagent_start": SubagentStartEvent
+ "subagent_queued": SubagentQueuedEvent
+ "subagent_end": SubagentEndEvent
+ "subagent_plan": SubagentPlanEvent
+ "subagent": SubagentEvent
+ "notice": NoticeEvent
+ "monitors": MonitorsEvent
+ "parked": ParkedEvent
+ "messages_updated": MessagesUpdatedEvent
+ "ask_request": AskRequestEvent
+ "ask_resolved": AskResolvedEvent
+ "todo_update": TodoUpdateEvent
+ "turn_usage": TurnUsageEvent
+ "done": DoneEvent
+ "error": ErrorEvent
+ "permission_request": PermissionRequestEvent
+ "tool_request": ToolRequestEvent
+ "tool_request_cancelled": ToolRequestCancelledEvent
+ "tool_details": ToolDetailsEvent
+}
diff --git a/packages/agent-sdk/src/generated/rpc-types.js b/packages/agent-sdk/src/generated/rpc-types.js
new file mode 100644
index 000000000..8ca33b7a7
--- /dev/null
+++ b/packages/agent-sdk/src/generated/rpc-types.js
@@ -0,0 +1,36 @@
+// Generated from protocol/rpc-schema.json by packages/agent-sdk/scripts/generate.mjs.
+// Do not edit by hand: run `node packages/agent-sdk/scripts/generate.mjs` after
+// changing the Rust dispatcher, and commit the regenerated output with it.
+
+export const PROTOCOL_VERSION = 1
+
+/** The `type` tag of every event, which is also its `item/<tag>` method name. */
+export const EVENT_TAGS = Object.freeze([
+ "token",
+ "reasoning",
+ "step",
+ "tool_call_started",
+ "tool_call_args_delta",
+ "tool_call",
+ "tool_output_delta",
+ "tool_result",
+ "subagent_start",
+ "subagent_queued",
+ "subagent_end",
+ "subagent_plan",
+ "subagent",
+ "notice",
+ "monitors",
+ "parked",
+ "messages_updated",
+ "ask_request",
+ "ask_resolved",
+ "todo_update",
+ "turn_usage",
+ "done",
+ "error",
+ "permission_request",
+ "tool_request",
+ "tool_request_cancelled",
+ "tool_details",
+])
diff --git a/packages/agent-sdk/src/index.d.ts b/packages/agent-sdk/src/index.d.ts
new file mode 100644
index 000000000..a0a376d1c
--- /dev/null
+++ b/packages/agent-sdk/src/index.d.ts
@@ -0,0 +1,241 @@
+// The public surface of the JavaScript/TypeScript SDK, declared by hand over
+// the generated wire types.
+//
+// `generated/rpc-types.d.ts` is regenerated from `protocol/rpc-schema.json`;
+// everything here is the part the schema does not describe - the classes, the
+// handler contract, and the responses the runtime sends (the artifact covers
+// request params and events, so the responses are pinned by this package's
+// tests against a real runtime instead).
+//
+// The implementation is `src/index.js`, in plain JavaScript, so a consumer
+// needs no build step; `tsconfig.json` type-checks both against this file.
+
+import type { EventTag, HostCapability, RpcMethod, RpcParams, StreamEvent } from './generated/rpc-types.js'
+
+export type { EventTag, EventByTag, RpcMethod, RpcParams, StreamEvent } from './generated/rpc-types.js'
+export { EVENT_TAGS, PROTOCOL_VERSION } from './generated/rpc-types.js'
+
+/**
+ * What the runtime answers `permission/respond` with. The schema types the
+ * field as a string - the runtime matches on these three and refuses anything
+ * else - so the union is declared here rather than generated.
+ */
+export type PermissionDecision = 'allow_once' | 'allow_always' | 'deny'
+
+/** An image a host hands back: a file path, a data URL, or raw bytes. */
+export type HostImage =
+ | string
+ | { path: string; mimeType?: string }
+ | { url: string }
+ | { data: string | Uint8Array; mimeType?: string }
+
+/** What a host tool handler answers with. */
+export type ToolResult =
+ | string
+ | {
+ text?: string
+ /** OpenAI content parts, passed through unchanged. */
+ parts?: unknown[]
+ content?: string | unknown[]
+ images?: HostImage[]
+ /** Host-only data, echoed as `item/tool_details` and never sent to the model. */
+ details?: Record<string, unknown>
+ isError?: boolean
+ error?: string
+ }
+
+/** What a host tool handler is told about the call it is running. */
+export interface HostToolCall {
+ requestId: string
+ /** The name the host declared, not the `host__`-prefixed name the model calls. */
+ toolName: string
+ /** The child that called it, or `null` for the main run. */
+ runId: string | null
+ session: JanSession
+ /** Aborted when the runtime withdraws the request. */
+ signal: AbortSignal
+}
+
+/** A host tool: what the model sees, plus the handler that runs it here. */
+export interface HostTool {
+ name: string
+ description?: string
+ /** JSON Schema for the arguments, advertised to the model verbatim. */
+ parameters?: Record<string, unknown>
+ /**
+ * What the tool does, which decides how the loop treats it: `read` (a camera,
+ * a sensor) is never prompted, is advertised in Plan mode and runs
+ * concurrently; `actuator` is prompted even under `allow_always` unless the
+ * host owns the gate, runs sequentially, and is withheld in Plan mode.
+ */
+ capability?: HostCapability
+ handler: (args: unknown, call: HostToolCall) => ToolResult | Promise<ToolResult>
+}
+
+/** A method the runtime answered with a JSON-RPC error. */
+export declare class JanRpcError extends Error {
+ code?: number
+ data?: unknown
+ method?: string
+ /** `true` for "another turn is active": the same request could succeed later. */
+ get retryable(): boolean
+}
+
+/** The runtime process failed: spawn, handshake, protocol version, or exit. */
+export declare class JanRuntimeError extends Error {
+ exitCode?: number | null
+ signal?: string | null
+ stderr?: string
+}
+
+export interface JanRuntimeOptions {
+ /** The runtime binary. Defaults to `$JAN_BIN`, then `jan` on `PATH`. */
+ bin?: string
+ /** Arguments after the binary. Defaults to `['cli', 'agent', 'rpc']`. */
+ args?: string[]
+ /** Working directory for the process, and the default for a session's `cwd`. */
+ cwd?: string
+ env?: Record<string, string | undefined>
+ clientInfo?: { name: string; version: string }
+ /** How long the handshake may take before `start()` rejects. */
+ handshakeTimeoutMs?: number
+ /** How long `close()` waits for a clean exit before killing. */
+ shutdownGraceMs?: number
+ /** Most events one undrained turn keeps before dropping its oldest. */
+ maxBufferedEvents?: number
+ onStderr?: (chunk: string) => void
+}
+
+/** The caps a content-part array is held to, as the runtime advertises them. */
+export interface ContentPartLimits {
+ mime_types: string[]
+ max_image_bytes: number
+ max_message_image_bytes: number
+ max_images: number
+ max_line_bytes: number
+ max_echo_bytes: number
+}
+
+export interface CreateSessionOptions {
+ cwd?: string
+ model?: string
+ /** Keep nothing on disk: no thread, no media files. */
+ ephemeral?: boolean
+ /** `false` advertises only the host tools, no built-ins or MCP. */
+ builtins?: boolean
+ /**
+ * Who gates a host tool call. `'host'` when this process runs and gates its
+ * own tools, so the runtime never prompts for them. `'jan'` (the default)
+ * leaves the gate with the runtime: an `actuator` call raises
+ * `permission_request` and the turn waits until `respondPermission` answers
+ * it.
+ */
+ permissions?: 'jan' | 'host'
+ tools?: HostTool[]
+}
+
+/** A session as the runtime reports it in `session/list`. */
+export interface SessionSummary {
+ id: string
+ model: string
+ turns: number
+ hostTools: number
+}
+
+export interface ToolSetView {
+ tools: string[]
+ toolSpecs: Record<string, unknown>[]
+}
+
+/**
+ * What each method answers with.
+ *
+ * `protocol/rpc-schema.json` describes request params and events, not
+ * responses, so these are declared here and pinned by this package's tests
+ * against a real runtime - a shape that moves fails there rather than in a
+ * consumer's code.
+ *
+ * `null` is this file's way of saying the runtime answers `{}`: the verb has no
+ * value to read, and the field says so rather than making a caller destructure
+ * nothing.
+ */
+export interface RpcResponses {
+ initialize: {
+ protocolVersion: number
+ serverInfo: { name: string; version: string }
+ capabilities: Record<string, unknown>
+ /** Absent on a runtime older than the caps. */
+ input_content_parts?: ContentPartLimits
+ }
+ 'session/list': { sessions: SessionSummary[] }
+ 'session/start': ToolSetView & { sessionId: string; model: string }
+ 'session/resume': { sessionId: string; model: string; turns: number }
+ 'session/fork': { sessionId: string }
+ 'session/archive': null
+ 'turn/start': { turnId: string }
+ 'turn/steer': null
+ 'turn/interrupt': null
+ 'permission/respond': null
+ 'tool/respond': null
+ 'session/tools/get': ToolSetView
+ 'session/tools/set': ToolSetView
+ 'session/model/set': { model: string }
+ 'session/reset': null
+}
+
+/** One turn of a session: what `prompt()` returns. */
+export declare class JanTurn implements AsyncIterable<StreamEvent> {
+ readonly session: JanSession
+ readonly id: string
+ /** Events dropped because nobody drained this turn, oldest first. */
+ readonly dropped: number
+ [Symbol.asyncIterator](): AsyncIterator<StreamEvent>
+ /** `{ stopReason, usage, error }`, once the runtime closes the turn. */
+ result(): Promise<{ stopReason: string; usage?: unknown; error?: string | null }>
+ /** Stop this turn; it still settles, with `stopReason: "interrupted"`. */
+ interrupt(): Promise<null>
+}
+
+/** A session on a runtime. */
+export declare class JanSession {
+ readonly runtime: JanRuntime
+ readonly id: string
+ model: string | null
+ /** The names the runtime advertises, as it reports them: the declared ones
+ * with their `host__` prefix, which is what the model calls. */
+ tools: string[]
+ toolSpecs: Record<string, unknown>[]
+ readonly maxBufferedEvents: number
+ on(kind: EventTag | 'event' | '*', listener: (event: StreamEvent) => void): () => void
+ prompt(input: string | unknown[] | { text: string } | { content: unknown[] }): Promise<JanTurn>
+ steer(input: string | { text: string }): Promise<null>
+ interrupt(): Promise<null>
+ reset(): Promise<null>
+ getTools(): Promise<ToolSetView>
+ setTools(tools: HostTool[]): Promise<ToolSetView>
+ setModel(model: string): Promise<string>
+ fork(options?: { tools?: HostTool[] }): Promise<JanSession>
+ archive(): Promise<void>
+ respondPermission(requestId: string, decision: PermissionDecision): Promise<null>
+}
+
+/** A Jan runtime process, spawned and owned by this object. */
+export declare class JanRuntime {
+ static start(options?: JanRuntimeOptions): Promise<JanRuntime>
+ readonly cwd?: string
+ readonly maxBufferedEvents: number
+ readonly protocolVersion: number | null
+ readonly serverInfo: { name: string; version: string } | null
+ readonly capabilities: Record<string, unknown> | null
+ /** `null` when the runtime is too old to advertise the caps. */
+ readonly limits: ContentPartLimits | null
+ readonly pid?: number
+ readonly stderr: string
+ on(kind: 'exit' | 'event' | 'notification', listener: (payload: unknown) => void): () => void
+ createSession(options?: CreateSessionOptions): Promise<JanSession>
+ listSessions(): Promise<SessionSummary[]>
+ resumeSession(sessionId: string): Promise<JanSession>
+ forkSession(sessionId: string, options?: { tools?: HostTool[] }): Promise<JanSession>
+ request<M extends RpcMethod>(method: M, params?: RpcParams<M>, options?: { timeoutMs?: number }): Promise<RpcResponses[M]>
+ close(options?: { force?: boolean }): Promise<{ code: number | null; signal: string | null }>
+}
diff --git a/packages/agent-sdk/src/index.js b/packages/agent-sdk/src/index.js
new file mode 100644
index 000000000..41f912eb2
--- /dev/null
+++ b/packages/agent-sdk/src/index.js
@@ -0,0 +1,896 @@
+// JavaScript/TypeScript client for the Jan agent runtime.
+//
+// One long-lived `jan cli agent rpc` process serves many addressable sessions
+// over LF-delimited JSON-RPC; this module is the client half of that channel -
+// the handshake, the session and turn lifecycle, streamed events, and the host
+// tools the caller's own process runs.
+//
+// Types come from `protocol/rpc-schema.json` via `scripts/generate.mjs`, so a
+// verb cannot change without this package's types moving with it. The runtime
+// is spawned and owned: a crash, an EOF or a shutdown settles every parked
+// turn and tool call rather than hanging, and the process is reaped.
+//
+// See `README.md` for the quickstart and the host-tool contract.
+
+import { spawn } from 'node:child_process'
+import { readFile } from 'node:fs/promises'
+import { createRequire } from 'node:module'
+import { extname } from 'node:path'
+import { createInterface } from 'node:readline'
+
+import { EVENT_TAGS, PROTOCOL_VERSION } from './generated/rpc-types.js'
+
+const require = createRequire(import.meta.url)
+const { version: SDK_VERSION } = require('../package.json')
+
+const CLIENT_NAME = '@janhq/agent-sdk'
+
+// The types a host may hand back as an image without naming one. The runtime
+// enforces the same set (and the byte caps) on arrival; this is only what the
+// SDK can name from a file path.
+const IMAGE_MIME = {
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg',
+ '.jpeg': 'image/jpeg',
+ '.gif': 'image/gif',
+ '.webp': 'image/webp',
+}
+
+// A method the runtime answered with a JSON-RPC error. `code` is the
+// protocol's: `-32602` for malformed params, `-32001` while another turn is
+// active, `-32002` before the handshake, `-32601` for a method this runtime
+// does not have.
+export class JanRpcError extends Error {
+ constructor(message, { code, data, method } = {}) {
+ super(message)
+ this.name = 'JanRpcError'
+ this.code = code
+ this.data = data
+ this.method = method
+ }
+
+ // Whether retrying the same request could succeed: the runtime says so for
+ // "another turn is active", and this is where that answer is readable.
+ get retryable() {
+ return this.data?.retryable === true
+ }
+}
+
+// The runtime process failed: it could not be spawned, it did not complete the
+// handshake, it is not the protocol version this client speaks, or it exited.
+// Distinct from [`JanRpcError`] on purpose - one is an answer, this is the
+// channel.
+export class JanRuntimeError extends Error {
+ constructor(message, { exitCode, signal, stderr } = {}) {
+ super(message)
+ this.name = 'JanRuntimeError'
+ this.exitCode = exitCode
+ this.signal = signal
+ this.stderr = stderr
+ }
+}
+
+// An event queue one consumer reads. `push` reports whether the event was
+// taken immediately or buffered, which is what lets a turn nobody is draining
+// stay bounded.
+class EventQueue {
+ #items = [];
+ #waiters = [];
+ #ended = false;
+ #failure = null;
+
+ get length() {
+ return this.#items.length
+ }
+
+ // `true` when the event had to be buffered because no reader was waiting.
+ push(item) {
+ if (this.#ended) return false
+ const waiter = this.#waiters.shift()
+ if (waiter) {
+ waiter({ value: item, done: false })
+ return false
+ }
+ this.#items.push(item)
+ return true
+ }
+
+ // Drop the oldest buffered event, reporting whether there was one.
+ dropOldest() {
+ return this.#items.shift() !== undefined
+ }
+
+ end() {
+ if (this.#ended) return
+ this.#ended = true
+ for (const waiter of this.#waiters.splice(0)) waiter({ value: undefined, done: true })
+ }
+
+ fail(error) {
+ if (this.#ended) return
+ this.#failure = error
+ this.#ended = true
+ for (const waiter of this.#waiters.splice(0)) waiter({ value: undefined, done: true })
+ }
+
+ next() {
+ const waiter = this.#waiters.shift()
+ if (waiter) return waiter
+ if (this.#items.length) return Promise.resolve({ value: this.#items.shift(), done: false })
+ if (this.#failure) return Promise.reject(this.#failure)
+ if (this.#ended) return Promise.resolve({ value: undefined, done: true })
+ return new Promise((resolve) => this.#waiters.push(resolve))
+ }
+
+ [Symbol.asyncIterator]() {
+ return this
+ }
+}
+
+// One turn of a session: what `session.prompt()` returns.
+///
+// Iterate it for the events as they stream, and await `result()` for the
+// terminal record. Both are safe in any order and more than once; events are
+// buffered until read.
+export class JanTurn {
+ constructor(session, id) {
+ this.session = session
+ this.id = id
+ // Events dropped because nobody was draining this turn, oldest first. The
+ // assembled records and the terminal one are what a late reader needs, and
+ // those are the last to go.
+ this.dropped = 0
+ this.#queue = new EventQueue()
+ this.#terminal = new Promise((resolve, reject) => {
+ this.#settle = resolve
+ this.#reject = reject
+ })
+ // A turn can fail before its caller reaches `result()` - `close()` does
+ // exactly that - and an unhandled rejection in that gap is a crash in a
+ // caller's process rather than a value it can await. Marking it handled
+ // here does not consume it: `result()` still rejects.
+ this.#terminal.catch(() => {})
+ }
+
+ #queue;
+ #settle;
+ #reject;
+ #terminal;
+ #buffered = 0;
+
+ // The events of this turn, in the order the runtime emitted them.
+ [Symbol.asyncIterator]() {
+ return this.#queue[Symbol.asyncIterator]()
+ }
+
+ // `{ stopReason, usage, error }`. Resolves when the runtime closes the turn;
+ // rejects when the channel dies first, because a turn with no terminal
+ // record has no outcome to report.
+ result() {
+ return this.#terminal
+ }
+
+ // Ask the runtime to stop this turn. The turn still settles - with
+ // `stopReason: "interrupted"` - so `result()` is awaited exactly as usual.
+ interrupt() {
+ return this.session.interrupt()
+ }
+
+ // Called by the session. A turn nobody reads keeps at most the session's
+ // `maxBufferedEvents`, then loses its oldest events - a run that streams
+ // tokens into an unread turn must not grow the client without limit.
+ _push(event) {
+ if (!this.#queue.push(event)) return
+ this.#buffered += 1
+ if (this.#buffered <= this.session.maxBufferedEvents) return
+ if (this.#queue.dropOldest()) {
+ this.#buffered -= 1
+ this.dropped += 1
+ }
+ }
+
+ _finish(record) {
+ this.#queue.end()
+ this.#settle(record)
+ }
+
+ _fail(error) {
+ this.#queue.fail(error)
+ this.#reject(error)
+ }
+}
+
+// A session on a runtime: a conversation, its model, and its host tools.
+export class JanSession {
+ constructor(runtime, { id, model, tools, toolSpecs }) {
+ this.runtime = runtime
+ this.id = id
+ this.model = model
+ // The host tool names the runtime advertises, as it reports them.
+ this.tools = tools
+ // Their schemas, as the runtime advertises them.
+ this.toolSpecs = toolSpecs
+ // Most events one undrained turn keeps; set on the runtime.
+ this.maxBufferedEvents = runtime.maxBufferedEvents
+ this.#turns = new Map()
+ this.#decls = new Map()
+ this.#listeners = new Map()
+ }
+
+ #turns;
+ #decls;
+ #listeners;
+ #calls = new Map();
+ #late = new Map();
+ #closed = false;
+
+ // Every event the session reports, including the ones raised by a subagent,
+ // which arrive wrapped in a `subagent` event. `'*'` hears all of them.
+ ///
+ // `on('tool_request', fn)` observes host tool calls; the call is answered
+ // from the declaration's `handler` either way.
+ on(kind, listener) {
+ const list = this.#listeners.get(kind) ?? []
+ list.push(listener)
+ this.#listeners.set(kind, list)
+ return () => this.#listeners.set(kind, (this.#listeners.get(kind) ?? []).filter((entry) => entry !== listener))
+ }
+
+ // Start a turn and stream it. `input` is a string, or content parts, for the
+ // images a vision model needs: `[{ type: 'text', text }, { type: 'image_url',
+ // image_url: { url: 'data:image/png;base64,...' } }]`.
+ async prompt(input) {
+ const { turnId } = await this.runtime.request('turn/start', {
+ sessionId: this.id,
+ input: normalizeInput(input),
+ })
+ return this.#turn(turnId, true)
+ }
+
+ // Steer the active turn: the message joins the run it is already in, rather
+ // than queueing behind it.
+ steer(input) {
+ return this.runtime.request('turn/steer', {
+ sessionId: this.id,
+ input: extractText(input),
+ })
+ }
+
+ // Stop the active turn. It settles with `stopReason: "interrupted"`, and its
+ // outstanding host tool calls are withdrawn.
+ interrupt() {
+ return this.runtime.request('turn/interrupt', { sessionId: this.id })
+ }
+
+ // Clear the history, keeping the model and the tool set.
+ reset() {
+ return this.runtime.request('session/reset', { sessionId: this.id })
+ }
+
+ // The tool set the runtime currently advertises, read back from it rather
+ // than assumed: `{ tools, toolSpecs }`.
+ getTools() {
+ return this.runtime.request('session/tools/get', { sessionId: this.id })
+ }
+
+ // Replace the host tools of a session between turns. Refused while a turn is
+ // active (`JanRpcError.code === -32001`).
+ async setTools(tools) {
+ const view = await this.runtime.request('session/tools/set', {
+ sessionId: this.id,
+ tools: tools.map(toDeclaration),
+ })
+ this._declare(tools)
+ this.tools = view.tools
+ this.toolSpecs = view.toolSpecs
+ return view
+ }
+
+ // Change the model between turns. Refused while a turn is active.
+ async setModel(model) {
+ const { model: current } = await this.runtime.request('session/model/set', {
+ sessionId: this.id,
+ model,
+ })
+ this.model = current
+ return current
+ }
+
+ // A new session with this one's history, addressable on its own. Its host
+ // tools are not inherited - a declaration belongs to the session that made
+ // it - so `fork({ tools })` re-declares them.
+ fork({ tools = [] } = {}) {
+ return this.runtime.forkSession(this.id, { tools })
+ }
+
+ // Drop the session from the runtime. Turns already finished are unaffected;
+ // a turn still running is closed by the runtime first.
+ async archive() {
+ await this.runtime.request('session/archive', { sessionId: this.id })
+ this.runtime._release(this)
+ this.#closed = true
+ this.#abort(new JanRuntimeError('the session was archived'))
+ this.#listeners.clear()
+ }
+
+ // Answer a permission request. `decision` is `allow_once`, `allow_always` or
+ // `deny`. A session started with `permissions: 'host'` is not prompted for
+ // its host tools at all; this is for the built-ins the runtime still gates.
+ respondPermission(requestId, decision) {
+ return this.runtime.request('permission/respond', { requestId, decision })
+ }
+
+ // Attach the handlers a session's declarations carry. Called by the runtime
+ // when the session is created, and by `setTools` when they are replaced.
+ _declare(tools) {
+ this.#decls = new Map(tools.map((tool) => [tool.name, tool]))
+ }
+
+ // Called by the runtime on every frame addressed to this session.
+ _deliver(tag, { turnId, event }) {
+ this.#emit('event', event)
+ const turn = this.#turn(turnId, true)
+ turn?._push(event)
+ if (tag === 'tool_request') this.#answer(event)
+ else if (tag === 'tool_request_cancelled') this.#abandon(event)
+ }
+
+ _complete({ turnId, stopReason, error }) {
+ const record = { stopReason, error: error ?? null }
+ const turn = this.#turns.get(turnId)
+ // The runtime may close a turn it started before the client asked for it -
+ // a run that ends with no events, or an immediate refusal. The record is
+ // held so `prompt()` finds it on the turn it is about to return, rather
+ // than a turn that never finishes.
+ if (!turn) {
+ this.#late.set(turnId, record)
+ if (this.#late.size > 64) this.#late.delete(this.#late.keys().next().value)
+ return
+ }
+ this.#turns.delete(turnId)
+ turn._finish(record)
+ }
+
+ // The runtime is gone: every open turn fails rather than hangs.
+ _fail(error) {
+ for (const turn of this.#turns.values()) turn._fail(error)
+ this.#turns.clear()
+ this.#abort(error)
+ }
+
+ #turn(turnId, create = false) {
+ if (!turnId) return null
+ const existing = this.#turns.get(turnId)
+ if (existing) return existing
+ if (!create) return null
+ const turn = new JanTurn(this, turnId)
+ this.#turns.set(turnId, turn)
+ const late = this.#late.get(turnId)
+ if (late) {
+ this.#late.delete(turnId)
+ this.#turns.delete(turnId)
+ turn._finish(late)
+ }
+ return turn
+ }
+
+ #emit(kind, event) {
+ for (const listener of this.#listeners.get(kind) ?? []) listener(event)
+ for (const listener of this.#listeners.get('*') ?? []) listener(event)
+ }
+
+ // A host tool was called. The handler runs without holding the reader: two
+ // children may have calls in flight at once, and serializing them is the
+ // host's decision - its own queue, its own capability tokens - rather than
+ // this client's.
+ #answer(event) {
+ if (this.#closed) return
+ const declaration = this.#decls.get(event.tool_name)
+ const controller = new AbortController()
+ this.#calls.set(event.request_id, controller)
+ const answer = async () => {
+ if (!declaration) {
+ await this.#respond(event.request_id, {
+ content: `no host tool named '${event.tool_name}' is declared on this session`,
+ isError: true,
+ })
+ return
+ }
+ let result
+ try {
+ result = await declaration.handler(event.args, {
+ requestId: event.request_id,
+ toolName: event.tool_name,
+ runId: event.run_id ?? null,
+ session: this,
+ signal: controller.signal,
+ })
+ } catch (error) {
+ await this.#respond(event.request_id, {
+ content: error instanceof Error ? error.message : String(error),
+ isError: true,
+ })
+ return
+ }
+ await this.#respond(event.request_id, await normalizeResult(result))
+ }
+ answer().catch(() => {})
+ }
+
+ // The runtime withdrew a request: a late answer is refused as not pending,
+ // so the handler is aborted and nothing is written.
+ #abandon({ request_id }) {
+ this.#calls.get(request_id)?.abort()
+ this.#calls.delete(request_id)
+ }
+
+ async #respond(requestId, params) {
+ const controller = this.#calls.get(requestId)
+ if (!controller || controller.signal.aborted) {
+ this.#calls.delete(requestId)
+ return
+ }
+ this.#calls.delete(requestId)
+ try {
+ await this.runtime.request('tool/respond', { requestId, ...params })
+ } catch {
+ // The turn was interrupted or the channel closed: the request is already
+ // withdrawn, and there is no one left to tell.
+ }
+ }
+
+ #abort(error) {
+ for (const controller of this.#calls.values()) controller.abort(error)
+ this.#calls.clear()
+ }
+}
+
+// A Jan runtime process, spawned and owned by this object.
+///
+// `await JanRuntime.start()` resolves once the handshake is done, so a runtime
+// that cannot speak this protocol version fails before any work starts rather
+// than mid-turn.
+export class JanRuntime {
+ #child;
+ #stdin;
+ #reading;
+ #exited;
+ #bin;
+ #handshakeTimeoutMs;
+ #shutdownGraceMs;
+ #clientInfo;
+ #stderr = '';
+ #pending = new Map();
+ #nextId = 1;
+ #sessions = new Map();
+ #listeners = new Map();
+ #closing = false;
+ #failure = null;
+ #protocolVersion = null;
+ #serverInfo = null;
+ #capabilities = null;
+ #limits = null;
+
+ constructor(options = {}) {
+ const {
+ bin = process.env.JAN_BIN ?? 'jan',
+ args = ['cli', 'agent', 'rpc'],
+ cwd,
+ env,
+ clientInfo = { name: CLIENT_NAME, version: SDK_VERSION },
+ handshakeTimeoutMs = 20_000,
+ shutdownGraceMs = 5_000,
+ maxBufferedEvents = 100_000,
+ onStderr,
+ } = options
+
+ this.cwd = cwd
+ this.maxBufferedEvents = maxBufferedEvents
+ this.#bin = bin
+ this.#handshakeTimeoutMs = handshakeTimeoutMs
+ this.#shutdownGraceMs = shutdownGraceMs
+ this.#clientInfo = clientInfo
+
+ const child = spawn(bin, args, {
+ cwd,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ env: {
+ ...process.env,
+ // The SDK owns this process and its lifetime; an update check nobody
+ // asked for is a network call inside a caller's turn.
+ JAN_CLI_NO_UPDATE_CHECK: '1',
+ ...env,
+ },
+ })
+ this.#child = child
+ this.#stdin = child.stdin
+
+ child.stderr.setEncoding('utf8')
+ child.stderr.on('data', (chunk) => {
+ // Kept for the failure message and for a caller that wants the runtime's
+ // own logging; a runtime that dies mid-turn is otherwise unexplainable.
+ this.#stderr = (this.#stderr + chunk).slice(-8192)
+ if (onStderr) onStderr(chunk)
+ })
+
+ this.#reading = createInterface({ input: child.stdout, crlfDelay: Infinity })
+ this.#reading.on('line', (line) => this.#onLine(line))
+
+ this.#exited = new Promise((resolve) => {
+ child.once('error', (error) => {
+ this.#fail(new JanRuntimeError(`could not start '${bin}': ${error.message}`, { stderr: this.#stderr }))
+ resolve({ code: null, signal: null })
+ })
+ child.once('exit', (code, signal) => {
+ this.#fail(
+ new JanRuntimeError(
+ `the jan runtime exited with ${signal ? `signal ${signal}` : `code ${code}`}${this.#stderr ? `: ${this.#stderr.trim()}` : ''}`,
+ { exitCode: code, signal, stderr: this.#stderr },
+ ),
+ )
+ this.#emit('exit', { code, signal })
+ resolve({ code, signal })
+ })
+ })
+ }
+
+ // Spawn a runtime and complete the handshake: `initialize`, then the
+ // `initialized` notification every other method sits behind.
+ static async start(options = {}) {
+ const runtime = new JanRuntime(options)
+ await runtime.#handshake()
+ return runtime
+ }
+
+ // The version the runtime answered with. Equal to the version this client
+ // speaks, or `start()` would have thrown.
+ get protocolVersion() {
+ return this.#protocolVersion
+ }
+
+ // `{ name, version }` of the runtime binary.
+ get serverInfo() {
+ return this.#serverInfo
+ }
+
+ // What the runtime says it supports: `{ session, turn }`.
+ get capabilities() {
+ return this.#capabilities
+ }
+
+ // The caps a content-part array is held to - a `prompt()` with images and a
+ // host tool's answer alike: `{ mime_types, max_image_bytes,
+ // max_message_image_bytes, max_images, max_line_bytes, max_echo_bytes }`.
+ // `null` when the runtime is too old to advertise them.
+ get limits() {
+ return this.#limits
+ }
+
+ get pid() {
+ return this.#child.pid
+ }
+
+ // The runtime's own stderr so far.
+ get stderr() {
+ return this.#stderr
+ }
+
+ // Notifications this client does not route: `exit`, and any frame whose
+ // method it does not know, so a newer runtime's additions are observable
+ // rather than lost.
+ on(kind, listener) {
+ const list = this.#listeners.get(kind) ?? []
+ list.push(listener)
+ this.#listeners.set(kind, list)
+ return () => this.#listeners.set(kind, (this.#listeners.get(kind) ?? []).filter((entry) => entry !== listener))
+ }
+
+ // Start a session. `tools` are host tools this session may call: each
+ // declares what it does (`capability: 'read'` for a sensor, `'actuator'` for
+ // something that moves) and carries the `handler` that runs it here.
+ async createSession({ cwd, model, ephemeral, builtins, permissions = 'jan', tools = [] } = {}) {
+ const params = { cwd: cwd ?? this.cwd ?? process.cwd() }
+ if (model !== undefined) params.model = model
+ if (ephemeral !== undefined) params.ephemeral = ephemeral
+ if (builtins !== undefined) params.builtins = builtins
+ if (permissions !== 'jan') params.permissions = permissions
+ if (tools.length) params.tools = tools.map(toDeclaration)
+ const view = await this.request('session/start', params)
+ const session = this.#session(view)
+ if (tools.length) session._declare(tools)
+ return session
+ }
+
+ // Sessions this process is serving, as the runtime sees them.
+ async listSessions() {
+ const { sessions } = await this.request('session/list', {})
+ return sessions
+ }
+
+ // Reopen a session of this process from its id. Host tools are not
+ // inherited: re-declare them with `session.setTools`.
+ async resumeSession(sessionId) {
+ return this.#session(await this.request('session/resume', { sessionId }))
+ }
+
+ // A new session with another session's history.
+ async forkSession(sessionId, { tools = [] } = {}) {
+ const source = this.#sessions.get(sessionId)
+ const { sessionId: forked } = await this.request('session/fork', { sessionId })
+ const view = await this.request('session/tools/get', { sessionId: forked })
+ // The tools view carries the tools and nothing else: the id and the model
+ // have to come from the fork itself and from the session it was forked
+ // from, which the runtime rebuilt it from.
+ const session = this.#session({ ...view, sessionId: forked, model: source?.model ?? null })
+ if (tools.length) await session.setTools(tools)
+ return session
+ }
+
+ // One JSON-RPC request, answered or refused. The escape hatch for a verb
+ // this client has no wrapper for.
+ request(method, params = {}, { timeoutMs } = {}) {
+ if (this.#failure) return Promise.reject(this.#failure)
+ if (this.#closing) return Promise.reject(new JanRuntimeError('the runtime is closing'))
+ const id = this.#nextId++
+ return new Promise((resolve, reject) => {
+ const entry = { method, resolve, reject, timer: null }
+ if (timeoutMs) {
+ entry.timer = setTimeout(() => {
+ this.#pending.delete(id)
+ reject(new JanRuntimeError(`'${method}' was not answered within ${timeoutMs}ms`))
+ }, timeoutMs)
+ }
+ this.#pending.set(id, entry)
+ this.#write({ jsonrpc: '2.0', id, method, params }).catch((error) => {
+ const current = this.#pending.get(id)
+ this.#pending.delete(id)
+ clearTimeout(current?.timer)
+ current?.reject(error)
+ })
+ })
+ }
+
+ // Close the channel, then the process: closing stdin is the runtime's own
+ // shutdown signal, and a turn still running when it arrives is closed with
+ // `stopReason: "interrupted"` before the process exits. `force` skips the
+ // grace period and kills.
+ async close({ force = false } = {}) {
+ if (this.#closing) return this.#exited
+ this.#closing = true
+ const gone = new JanRuntimeError('the runtime was closed')
+ for (const session of this.#sessions.values()) session._fail(gone)
+ this.#sessions.clear()
+ if (!this.#stdin.destroyed) this.#stdin.end()
+ if (force) {
+ this.#child.kill('SIGKILL')
+ return this.#exited
+ }
+ const timer = setTimeout(() => this.#child.kill('SIGKILL'), this.#shutdownGraceMs)
+ try {
+ return await this.#exited
+ } finally {
+ clearTimeout(timer)
+ }
+ }
+
+ async #handshake() {
+ let result
+ try {
+ result = await this.request(
+ 'initialize',
+ { protocolVersion: PROTOCOL_VERSION, clientInfo: this.#clientInfo, capabilities: {} },
+ { timeoutMs: this.#handshakeTimeoutMs },
+ )
+ } catch (error) {
+ await this.#killQuietly()
+ if (error instanceof JanRpcError) {
+ throw new JanRuntimeError(
+ `'${this.#bin}' refused the handshake: ${error.message}${this.#stderr ? `: ${this.#stderr.trim()}` : ''}`,
+ { stderr: this.#stderr },
+ )
+ }
+ throw error
+ }
+ if (result?.protocolVersion !== PROTOCOL_VERSION) {
+ await this.#killQuietly()
+ throw new JanRuntimeError(
+ `the runtime speaks protocol version ${result?.protocolVersion}, this client speaks ${PROTOCOL_VERSION}`,
+ { stderr: this.#stderr },
+ )
+ }
+ this.#protocolVersion = result.protocolVersion
+ this.#serverInfo = result.serverInfo ?? null
+ this.#capabilities = result.capabilities ?? null
+ this.#limits = result.input_content_parts ?? null
+ this.#write({ jsonrpc: '2.0', method: 'initialized', params: {} }).catch(() => {})
+ }
+
+ async #killQuietly() {
+ this.#closing = true
+ if (!this.#stdin.destroyed) this.#stdin.end()
+ this.#child.kill('SIGKILL')
+ await this.#exited
+ }
+
+ #session(view) {
+ const session = new JanSession(this, {
+ id: view.sessionId,
+ model: view.model ?? null,
+ tools: view.tools ?? [],
+ toolSpecs: view.toolSpecs ?? [],
+ })
+ this.#sessions.set(session.id, session)
+ return session
+ }
+
+ // Called by a session that was archived: the runtime no longer knows it.
+ _release(session) {
+ this.#sessions.delete(session.id)
+ }
+
+ // The runtime's own frame, routed. Everything that is not an answer or a
+ // session event ends up on the `notification` listener.
+ #onLine(line) {
+ if (!line.trim()) return
+ let frame
+ try {
+ frame = JSON.parse(line)
+ } catch {
+ this.#fail(
+ new JanRuntimeError(`the runtime wrote a line that is not JSON: ${line.slice(0, 200)}`, {
+ stderr: this.#stderr,
+ }),
+ )
+ return
+ }
+ if (frame.method === undefined) {
+ this.#settle(frame.id, frame)
+ return
+ }
+ const method = frame.method
+ const params = frame.params ?? {}
+ if (method.startsWith('item/')) {
+ const session = this.#sessions.get(params.sessionId)
+ if (session) session._deliver(method.slice('item/'.length), params)
+ else this.#emit('event', { ...params, tag: method.slice('item/'.length) })
+ return
+ }
+ if (method === 'turn/completed') {
+ this.#sessions.get(params.sessionId)?._complete(params)
+ return
+ }
+ this.#emit('notification', frame)
+ }
+
+ #settle(id, frame) {
+ const entry = this.#pending.get(id)
+ if (!entry) return
+ this.#pending.delete(id)
+ clearTimeout(entry.timer)
+ if (frame.error) {
+ const { code, message, data } = frame.error
+ entry.reject(new JanRpcError(message ?? 'the runtime refused the request', { code, data, method: entry.method }))
+ return
+ }
+ entry.resolve(frame.result ?? null)
+ }
+
+ #write(frame) {
+ if (this.#stdin.destroyed || !this.#stdin.writable) {
+ return Promise.reject(new JanRuntimeError('the runtime channel is closed', { stderr: this.#stderr }))
+ }
+ return new Promise((resolve, reject) => {
+ this.#stdin.write(`${JSON.stringify(frame)}\n`, (error) => (error ? reject(error) : resolve()))
+ })
+ }
+
+ #emit(kind, payload) {
+ for (const listener of this.#listeners.get(kind) ?? []) listener(payload)
+ }
+
+ #fail(error) {
+ if (this.#failure) return
+ this.#failure = error
+ for (const entry of this.#pending.values()) {
+ clearTimeout(entry.timer)
+ entry.reject(error)
+ }
+ this.#pending.clear()
+ for (const session of this.#sessions.values()) session._fail(error)
+ this.#sessions.clear()
+ }
+}
+
+// A host tool declaration: what the model sees, minus the handler, which never
+// crosses the process boundary.
+function toDeclaration(tool) {
+ if (!tool || typeof tool !== 'object') throw new TypeError('a host tool must be an object')
+ const { name, description, parameters, capability, handler } = tool
+ if (typeof name !== 'string' || !name) throw new TypeError('a host tool needs a name')
+ if (typeof handler !== 'function') throw new TypeError(`host tool '${name}' needs a handler`)
+ const declaration = { name }
+ if (description !== undefined) declaration.description = description
+ if (parameters !== undefined) declaration.parameters = parameters
+ if (capability !== undefined) declaration.capability = capability
+ return declaration
+}
+
+// `turn/start` takes the text, the parts, or the record a client would write
+// to a stream-json `user` line. All three are accepted here, normalized to the
+// shape the parser already handles.
+function normalizeInput(input) {
+ if (typeof input === 'string') return input
+ if (Array.isArray(input)) return { type: 'user', content: input }
+ if (input && typeof input === 'object') {
+ if (typeof input.text === 'string') return input.text
+ if (Array.isArray(input.content)) return { type: 'user', content: input.content }
+ }
+ throw new TypeError('prompt() takes a string, content parts, or a { text } / { content } record')
+}
+
+function extractText(input) {
+ if (typeof input === 'string') return input
+ if (input && typeof input === 'object' && typeof input.text === 'string') return input.text
+ throw new TypeError('steer() takes a string or a { text } record')
+}
+
+// What a handler returned, as the `tool/respond` the runtime parses: text,
+// content parts, host-only details, and an image as a file path, a buffer or a
+// data URL. A result that cannot be shaped is still answered - the model is
+// never left parked on a call this client failed to format.
+async function normalizeResult(result) {
+ if (result === undefined || result === null) return { content: '' }
+ if (typeof result === 'string') return { content: result }
+ if (typeof result !== 'object') return { content: String(result) }
+ if (result.isError === true || typeof result.error === 'string') {
+ return {
+ content: typeof result.error === 'string' ? result.error : String(result.content ?? ''),
+ isError: true,
+ }
+ }
+ const parts = []
+ const text = result.text ?? (typeof result.content === 'string' ? result.content : undefined)
+ if (text) parts.push({ type: 'text', text: String(text) })
+ if (Array.isArray(result.parts)) parts.push(...result.parts)
+ else if (Array.isArray(result.content)) parts.push(...result.content)
+ for (const image of result.images ?? []) parts.push(await toImagePart(image))
+ const response = { content: parts.length ? parts : String(text ?? '') }
+ if (result.details !== undefined) {
+ // `details` is host-only data echoed back in `tool_details`; the runtime
+ // takes an object of values, so anything else is carried as one.
+ response.details = isPlainObject(result.details) ? result.details : { value: result.details }
+ }
+ return response
+}
+
+async function toImagePart(image) {
+ if (typeof image === 'string') {
+ return { type: 'image_url', image_url: { url: image.startsWith('data:') ? image : await dataUrlFromFile(image) } }
+ }
+ if (image && typeof image === 'object') {
+ if (typeof image.url === 'string') return { type: 'image_url', image_url: { url: image.url } }
+ if (typeof image.path === 'string') {
+ return { type: 'image_url', image_url: { url: await dataUrlFromFile(image.path, image.mimeType) } }
+ }
+ if (image.data !== undefined) {
+ const mimeType = image.mimeType ?? 'image/png'
+ const payload =
+ Buffer.isBuffer(image.data) || image.data instanceof Uint8Array
+ ? Buffer.from(image.data).toString('base64')
+ : String(image.data)
+ return { type: 'image_url', image_url: { url: `data:${mimeType};base64,${payload}` } }
+ }
+ }
+ throw new TypeError('an image is a path, a data URL, or { data, mimeType }')
+}
+
+async function dataUrlFromFile(path, mimeType = IMAGE_MIME[extname(path).toLowerCase()] ?? 'image/png') {
+ const bytes = await readFile(path)
+ return `data:${mimeType};base64,${bytes.toString('base64')}`
+}
+
+function isPlainObject(value) {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
+
+export { EVENT_TAGS, PROTOCOL_VERSION }
diff --git a/packages/agent-sdk/tests/sdk.test.mjs b/packages/agent-sdk/tests/sdk.test.mjs
new file mode 100644
index 000000000..63f4cdaac
--- /dev/null
+++ b/packages/agent-sdk/tests/sdk.test.mjs
@@ -0,0 +1,565 @@
+// The JavaScript SDK, driven end to end against a real runtime.
+//
+// The subject is the process boundary: every claim here is about what crosses
+// it - the handshake, a turn's events, a host tool's answer becoming the tool
+// message the model sees on the next request, an interrupt settling a parked
+// call exactly once. A unit test with a fake runtime would assert the client
+// agrees with itself; this asserts it agrees with `jan`.
+//
+// The provider is a stub on loopback, so the suite needs no credentials and no
+// network. Set `JAN_BIN` to the runtime binary to run it (the SDK's CI job
+// builds one; locally, `make agent` or a cargo build of `jan-cli`).
+
+import { execFile } from 'node:child_process'
+import { createServer } from 'node:http'
+import { mkdtemp, mkdir, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { promisify } from 'node:util'
+
+import { JanRuntime, JanRuntimeError, PROTOCOL_VERSION } from '../src/index.js'
+
+const run = promisify(execFile)
+const bin = process.env.JAN_BIN
+const missingRuntime = bin ? false : 'set JAN_BIN to the jan binary to run the SDK suite'
+
+// A chunk the model asks for the host tool with. `host__` is the advertised
+// name; the host is told the bare one.
+const TOOL_CALL = (name, args) =>
+ [
+ `data: ${JSON.stringify({
+ id: 'stub-1',
+ object: 'chat.completion.chunk',
+ created: 1,
+ model: 'stub-model',
+ choices: [
+ {
+ index: 0,
+ delta: {
+ role: 'assistant',
+ tool_calls: [
+ { index: 0, id: 'call-1', type: 'function', function: { name, arguments: JSON.stringify(args) } },
+ ],
+ },
+ finish_reason: null,
+ },
+ ],
+ })}\n\n`,
+ `data: ${JSON.stringify({
+ id: 'stub-1',
+ object: 'chat.completion.chunk',
+ created: 1,
+ model: 'stub-model',
+ choices: [{ index: 0, delta: {}, finish_reason: 'tool_calls' }],
+ usage: { prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 },
+ })}\n\n`,
+ 'data: [DONE]\n\n',
+ ].join('')
+
+// Plain prose, which ends the run.
+const PROSE = (text) =>
+ [
+ `data: ${JSON.stringify({
+ id: 'stub-2',
+ object: 'chat.completion.chunk',
+ created: 1,
+ model: 'stub-model',
+ choices: [{ index: 0, delta: { role: 'assistant', content: text }, finish_reason: null }],
+ })}\n\n`,
+ `data: ${JSON.stringify({
+ id: 'stub-2',
+ object: 'chat.completion.chunk',
+ created: 1,
+ model: 'stub-model',
+ choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
+ usage: { prompt_tokens: 9, completion_tokens: 4, total_tokens: 13 },
+ })}\n\n`,
+ 'data: [DONE]\n\n',
+ ].join('')
+
+// One token, then the socket stays open: a turn a test can interrupt in the
+// middle of, rather than after it finished.
+const HOLDING = (text) =>
+ `data: ${JSON.stringify({
+ id: 'stub-3',
+ object: 'chat.completion.chunk',
+ created: 1,
+ model: 'stub-model',
+ choices: [{ index: 0, delta: { role: 'assistant', content: text }, finish_reason: null }],
+ })}\n\n`
+
+// Serve `replies` in order, one per connection, repeating the last once they
+// run out. Bodies are kept so a test can assert what the model was actually
+// sent - which is where a host tool's answer has to land for a round trip to
+// mean anything.
+class Provider {
+ #server
+ #sockets = new Set()
+
+ constructor(replies) {
+ this.replies = replies
+ this.bodies = []
+ this.connections = 0
+ }
+
+ async start() {
+ this.#server = createServer((request, response) => {
+ const index = this.connections++
+ const reply = this.replies[Math.min(index, this.replies.length - 1)]
+ let body = ''
+ request.on('data', (chunk) => {
+ body += chunk
+ })
+ request.on('end', () => {
+ this.bodies.push(body)
+ response.writeHead(200, { 'content-type': 'text/event-stream', connection: 'close' })
+ if (typeof reply === 'function') {
+ this.#sockets.add(response)
+ reply(response, () => this.#sockets.delete(response))
+ return
+ }
+ response.end(reply)
+ })
+ })
+ await new Promise((resolve) => this.#server.listen(0, '127.0.0.1', resolve))
+ const { port } = this.#server.address()
+ return `http://127.0.0.1:${port}/v1`
+ }
+
+ async stop() {
+ for (const socket of this.#sockets) socket.destroy()
+ this.#sockets.clear()
+ if (this.#server) await new Promise((resolve) => this.#server.close(resolve))
+ }
+}
+
+// A private home and project, removed after the test.
+class Scratch {
+ static async create(name) {
+ const root = await mkdtemp(join(tmpdir(), `jan-sdk-${name}-`))
+ const scratch = new Scratch(root)
+ await mkdir(scratch.home, { recursive: true })
+ await mkdir(scratch.project, { recursive: true })
+ return scratch
+ }
+
+ constructor(root) {
+ this.root = root
+ this.home = join(root, 'home')
+ this.project = join(root, 'project')
+ }
+
+ // Point the runtime at the stub provider, so a session can resolve a model.
+ async configure(baseUrl) {
+ await run(
+ bin,
+ ['config', 'set', '--provider', 'stub', '--api-key', 'test-key', '--base-url', baseUrl, '--model', 'stub-model'],
+ { env: this.env },
+ )
+ }
+
+ get env() {
+ return { ...process.env, HOME: this.home, JAN_CLI_NO_UPDATE_CHECK: '1' }
+ }
+
+ get projectPath() {
+ return this.project
+ }
+
+ start(options = {}) {
+ return JanRuntime.start({ bin, env: this.env, ...options })
+ }
+
+ async cleanup() {
+ await rm(this.root, { recursive: true, force: true })
+ }
+}
+
+// One test's runtime, provider and scratch home, torn down whether the test
+// passed, failed or threw. A leaked stub server or child process keeps the
+// test runner waiting on the event loop, which is a hang rather than a
+// failure - so cleanup is registered before the first assertion.
+async function connect(t, { replies, runtime = {} } = {}) {
+ const provider = new Provider(replies)
+ const baseUrl = await provider.start()
+ const scratch = await Scratch.create('case')
+ await scratch.configure(baseUrl)
+ const jan = await scratch.start(runtime)
+ t.after(async () => {
+ await jan.close({ force: true }).catch(() => {})
+ await provider.stop()
+ await scratch.cleanup()
+ })
+ return { provider, scratch, runtime: jan }
+}
+
+// The events of a turn, collected while it runs.
+async function collect(turn) {
+ const events = []
+ for await (const event of turn) events.push(event)
+ return events
+}
+
+test('a runtime handshakes and reports its caps', { skip: missingRuntime }, async (t) => {
+ const { runtime } = await connect(t, { replies: [PROSE('unused')] })
+ assert.equal(runtime.protocolVersion, PROTOCOL_VERSION)
+ assert.equal(runtime.serverInfo.name, 'jan')
+ assert.equal(runtime.capabilities.session, true)
+ // The caps are the handshake's business: a client that sends an image learns
+ // the limits here rather than from a rejection.
+ assert.ok(runtime.limits, 'the handshake advertises the content-part caps')
+ assert.ok(runtime.limits.max_images >= 1)
+ assert.ok(runtime.limits.mime_types.includes('image/png'))
+ assert.ok(runtime.pid > 0)
+
+})
+
+test('a runtime that is not there fails before any work starts', { skip: missingRuntime }, async (t) => {
+ await assert.rejects(
+ JanRuntime.start({ bin: join(tmpdir(), 'jan-does-not-exist'), env: process.env }),
+ (error) => error instanceof JanRuntimeError,
+ )
+})
+
+test('a session runs a turn and reports its own state', { skip: missingRuntime }, async (t) => {
+ const { scratch, runtime } = await connect(t, { replies: [PROSE('the arm reached bin')] })
+ const session = await runtime.createSession({
+ cwd: scratch.projectPath,
+ model: 'stub-model',
+ ephemeral: true,
+ builtins: false,
+ })
+ assert.ok(session.id)
+ assert.equal(session.model, 'stub-model')
+
+ const seen = []
+ session.on('event', (event) => seen.push(event.type))
+ const turn = await session.prompt('move the arm')
+ const events = await collect(turn)
+ const result = await turn.result()
+
+ assert.equal(result.stopReason, 'completed')
+ const text = events.filter((event) => event.type === 'token').map((event) => event.text).join('')
+ assert.equal(text, 'the arm reached bin')
+ assert.ok(events.some((event) => event.type === 'step'))
+ // The session hears what the turn hears, so a host can observe a run it is
+ // not the one iterating.
+ assert.ok(seen.includes('token'))
+
+ // State that a host reads back rather than assumes.
+ const tools = await session.getTools()
+ assert.deepEqual(tools.tools, [])
+ const sessions = await runtime.listSessions()
+ assert.equal(sessions.find((entry) => entry.id === session.id).turns, 1)
+ assert.equal(await session.setModel('stub-model'), 'stub-model')
+ await session.reset()
+ await session.archive()
+
+})
+
+test('a host tool round-trips: the handler runs, the model gets the answer', { skip: missingRuntime }, async (t) => {
+ const calls = []
+ const { provider, scratch, runtime } = await connect(t, {
+ replies: [TOOL_CALL('host__robot_arm_move', { position: 'bin' }), PROSE('the arm reached bin')],
+ })
+ const session = await runtime.createSession({
+ cwd: scratch.projectPath,
+ model: 'stub-model',
+ ephemeral: true,
+ // Built-ins off, so the advertised set is exactly what this test declared,
+ // and the gate is the host's: an actuator this client runs itself must not
+ // be prompted for twice.
+ builtins: false,
+ permissions: 'host',
+ tools: [
+ {
+ name: 'robot_arm_move',
+ description: 'Move the arm.',
+ parameters: { type: 'object', properties: { position: { type: 'string' } }, required: ['position'] },
+ capability: 'actuator',
+ handler: (args, call) => {
+ calls.push({ args, call })
+ return { text: 'moved to bin', details: { joints: 3 } }
+ },
+ },
+ ],
+ })
+ // The runtime advertises the model-facing name, which is the declared one
+ // with its `host__` prefix; the host is told the name it chose (below).
+ assert.deepEqual(session.tools, ['host__robot_arm_move'])
+ assert.equal(session.toolSpecs[0].function.name, 'host__robot_arm_move')
+
+ const turn = await session.prompt('move the arm')
+ const events = await collect(turn)
+ const result = await turn.result()
+ assert.equal(result.stopReason, 'completed')
+
+ const request = events.find((event) => event.type === 'tool_request')
+ assert.ok(request, 'the host was asked')
+ // The host dispatches on the name it declared, not the `host__` name the
+ // model calls, and a main-run request carries no run id.
+ assert.equal(request.tool_name, 'robot_arm_move')
+ assert.deepEqual(request.args, { position: 'bin' })
+ assert.equal(request.run_id ?? null, null)
+ assert.deepEqual(request.args, calls[0].args)
+ assert.equal(calls[0].call.toolName, 'robot_arm_move')
+ assert.equal(calls[0].call.runId, null)
+ assert.equal(calls[0].call.session, session)
+
+ // The tool's answer became the tool message of the next provider request:
+ // that, not the handler call, is what makes the round trip real.
+ assert.equal(provider.bodies.length, 2, 'the model was asked twice')
+ assert.match(provider.bodies[1], /moved to bin/)
+ // `details` is host-only: it is echoed back on the channel and never sent.
+ assert.doesNotMatch(provider.bodies[1], /joints/)
+
+})
+
+test('an image-bearing host result reaches the model as an image part', { skip: missingRuntime }, async (t) => {
+ // A 1x1 PNG, which is a valid payload and small enough to inline here.
+ const png = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8AARAAB/wDcH1jPAAAAAElFTkSuQmCC'
+ const { provider, scratch, runtime } = await connect(t, {
+ replies: [TOOL_CALL('host__camera_observe', { frame: 1 }), PROSE('the bin is clear')],
+ })
+ const session = await runtime.createSession({
+ cwd: scratch.projectPath,
+ model: 'stub-model',
+ ephemeral: true,
+ builtins: false,
+ permissions: 'host',
+ tools: [
+ {
+ name: 'camera_observe',
+ description: 'Look at the bench.',
+ capability: 'read',
+ handler: () => ({ text: 'the bench', images: [{ data: png, mimeType: 'image/png' }] }),
+ },
+ ],
+ })
+
+ const turn = await session.prompt('look at the bench')
+ await collect(turn)
+ await turn.result()
+
+ const body = provider.bodies[1]
+ const messages = JSON.parse(body).messages
+ assert.equal(messages.at(-2).role, 'tool', 'the tool message reported the result')
+ assert.equal(messages.at(-2).content, 'the bench')
+ // A tool message cannot carry an image, so the runtime labels the user turn
+ // the result produces and leads it with the parts the host wrote; the label
+ // names the call, and the host's own text stayed on the tool message.
+ const parts = messages.at(-1)
+ assert.equal(parts.role, 'user')
+ assert.ok(Array.isArray(parts.content), 'the user message carries content parts')
+ assert.equal(parts.content[0].type, 'text')
+ assert.ok(parts.content[0].text.length > 0, 'the user turn is labelled')
+ assert.equal(parts.content[1].type, 'image_url')
+ assert.equal(parts.content[1].image_url.url, `data:image/png;base64,${png}`)
+
+})
+
+test('a handler that throws answers the call as an error, and the turn goes on', { skip: missingRuntime }, async (t) => {
+ const { provider, scratch, runtime } = await connect(t, {
+ replies: [TOOL_CALL('host__robot_arm_move', { position: 'bin' }), PROSE('the arm did not move')],
+ })
+ const session = await runtime.createSession({
+ cwd: scratch.projectPath,
+ model: 'stub-model',
+ ephemeral: true,
+ permissions: 'host',
+ tools: [
+ {
+ name: 'robot_arm_move',
+ capability: 'actuator',
+ handler: () => {
+ throw new Error('the emergency stop is engaged')
+ },
+ },
+ ],
+ })
+
+ const turn = await session.prompt('move the arm')
+ await collect(turn)
+ const result = await turn.result()
+
+ // An error is an answer, not a dropped turn: the model is told, and the run
+ // finishes with its own stop reason.
+ assert.equal(result.stopReason, 'completed')
+ assert.match(provider.bodies[1], /the emergency stop is engaged/)
+
+})
+
+test('interrupting a turn settles it once, and abandons its parked call', { skip: missingRuntime }, async (t) => {
+ let aborted = false
+ let answered = 0
+ const { scratch, runtime } = await connect(t, {
+ replies: [TOOL_CALL('host__robot_arm_move', { position: 'bin' }), (response) => response.write(HOLDING('working on it'))],
+ })
+ const session = await runtime.createSession({
+ cwd: scratch.projectPath,
+ model: 'stub-model',
+ ephemeral: true,
+ permissions: 'host',
+ tools: [
+ {
+ name: 'robot_arm_move',
+ capability: 'actuator',
+ handler: (_args, call) =>
+ new Promise((resolve) => {
+ call.signal.addEventListener('abort', () => {
+ aborted = true
+ answered += 1
+ resolve({ text: 'too late' })
+ })
+ }),
+ },
+ ],
+ })
+
+ const turn = await session.prompt('move the arm')
+ const events = []
+ const reading = (async () => {
+ for await (const event of turn) {
+ events.push(event)
+ if (event.type === 'tool_request') await session.interrupt()
+ }
+ })()
+ const result = await turn.result()
+ await reading
+
+ assert.equal(result.stopReason, 'interrupted')
+ // The parked call is withdrawn rather than answered: the runtime would refuse
+ // a late answer as not pending, so the SDK must not write one.
+ assert.ok(events.some((event) => event.type === 'tool_request_cancelled'))
+ assert.equal(aborted, true, 'the handler was told to stop')
+ assert.equal(answered, 1)
+ assert.equal(turn.dropped, 0)
+
+})
+
+test('a permission request the runtime owns is answered by the host', { skip: missingRuntime }, async (t) => {
+ const calls = []
+ const { scratch, runtime } = await connect(t, {
+ replies: [TOOL_CALL('host__robot_arm_move', { position: 'bin' }), PROSE('the arm reached bin')],
+ })
+ // No `permissions: 'host'`: the runtime owns the gate, so an actuator is
+ // prompted before the call reaches its handler.
+ const session = await runtime.createSession({
+ cwd: scratch.projectPath,
+ model: 'stub-model',
+ ephemeral: true,
+ builtins: false,
+ tools: [
+ {
+ name: 'robot_arm_move',
+ capability: 'actuator',
+ handler: (args) => {
+ calls.push(args)
+ return { text: 'moved to bin' }
+ },
+ },
+ ],
+ })
+
+ const turn = await session.prompt('move the arm')
+ const events = []
+ const reading = (async () => {
+ for await (const event of turn) {
+ events.push(event)
+ if (event.type === 'permission_request') {
+ // The prompt names the tool the model called - the advertised one.
+ assert.equal(event.tool_name, 'host__robot_arm_move')
+ assert.equal(typeof event.capability, 'string')
+ await session.respondPermission(event.request_id, 'allow_once')
+ }
+ }
+ })()
+ const result = await turn.result()
+ await reading
+
+ assert.equal(result.stopReason, 'completed')
+ assert.deepEqual(calls, [{ position: 'bin' }], 'the call ran once the host allowed it')
+ assert.ok(events.some((event) => event.type === 'tool_request'))
+})
+
+test('two sessions never see each other’s events', { skip: missingRuntime }, async (t) => {
+ const { scratch, runtime } = await connect(t, { replies: [PROSE('alpha'), PROSE('beta')] })
+ const first = await runtime.createSession({ cwd: scratch.projectPath, model: 'stub-model', ephemeral: true })
+ const second = await runtime.createSession({ cwd: scratch.projectPath, model: 'stub-model', ephemeral: true })
+
+ const noise = []
+ second.on('event', (event) => noise.push(event.type))
+
+ const turn = await first.prompt('say alpha')
+ const events = await collect(turn)
+ await turn.result()
+
+ assert.ok(events.some((event) => event.type === 'token' && event.text === 'alpha'))
+ assert.deepEqual(noise, [], 'the other session heard nothing')
+
+ // A fork is its own session, with its own id - and an address the runtime
+ // answers for, which is what makes it usable rather than merely named.
+ const fork = await first.fork()
+ assert.equal(typeof fork.id, 'string')
+ assert.ok(fork.id.length > 0)
+ assert.notEqual(fork.id, first.id)
+ assert.equal(fork.model, 'stub-model')
+ const forked = await fork.getTools()
+ assert.ok(forked.tools.includes('bash'))
+
+})
+
+test('a session is reopened by its id', { skip: missingRuntime }, async (t) => {
+ const { scratch, runtime } = await connect(t, { replies: [PROSE('one'), PROSE('two')] })
+ const first = await runtime.createSession({ cwd: scratch.projectPath, model: 'stub-model', ephemeral: true })
+ const turn = await first.prompt('say something')
+ await turn.result()
+
+ // The runtime rebuilt this session from its own state, so the id it answers
+ // for and the model it runs are the ones the first session had.
+ const again = await runtime.resumeSession(first.id)
+ assert.equal(again.id, first.id)
+ assert.equal(again.model, 'stub-model')
+ const resumed = await again.prompt('say something else')
+ const done = await resumed.result()
+ assert.equal(done.stopReason, 'completed')
+})
+
+test('closing the runtime settles an open turn instead of hanging', { skip: missingRuntime }, async (t) => {
+ const { scratch, runtime } = await connect(t, { replies: [(response) => response.write(HOLDING('still here'))] })
+ const session = await runtime.createSession({ cwd: scratch.projectPath, model: 'stub-model', ephemeral: true })
+ const turn = await session.prompt('say something')
+ const { code } = await runtime.close()
+
+ // Closing stdin is the runtime's own shutdown signal, and a turn that was
+ // running is closed on the channel before the process exits.
+ assert.equal(code, 0)
+ await assert.rejects(turn.result(), (error) => error instanceof JanRuntimeError)
+})
+
+test('a turn nobody drains stays bounded, and still reports its outcome', { skip: missingRuntime }, async (t) => {
+ const { scratch, runtime } = await connect(t, { replies: [PROSE('unread')], runtime: { maxBufferedEvents: 0 } })
+ const session = await runtime.createSession({ cwd: scratch.projectPath, model: 'stub-model', ephemeral: true })
+ const turn = await session.prompt('say something')
+ const result = await turn.result()
+
+ // The events were dropped rather than held: the terminal record still
+ // arrived, which is what a late reader needs most.
+ assert.equal(result.stopReason, 'completed')
+ assert.ok(turn.dropped > 0, 'the unread turn dropped events instead of growing')
+
+})
+
+test('a request with no runtime behind it is refused, not hung', { skip: missingRuntime }, async (t) => {
+ const { runtime } = await connect(t, { replies: [PROSE('unused')] })
+ await assert.rejects(
+ runtime.request('session/tools/get', { sessionId: 'not-a-session' }),
+ (error) => error.code === -32602 && /unknown session/i.test(error.message),
+ )
+ await assert.rejects(
+ runtime.request('turn/start', { sessionId: 'not-a-session', input: 'hi' }),
+ (error) => error.name === 'JanRpcError',
+ )
+})
diff --git a/packages/agent-sdk/tests/types.ts b/packages/agent-sdk/tests/types.ts
new file mode 100644
index 000000000..2b1c037b8
--- /dev/null
+++ b/packages/agent-sdk/tests/types.ts
@@ -0,0 +1,66 @@
+// Compile-time assertions over the generated types and the public surface.
+//
+// Nothing here is executed: `tsc -p tsconfig.json` includes this file, so a
+// shape that stops type-checking - a generated event union that loses a tag, a
+// handler contract that stops accepting what the README shows - fails the
+// package's own check rather than a consumer's build.
+//
+// The wire-shaped literals below are the same ones the runtime sends; the
+// behavioral suite in `sdk.test.mjs` is what proves they are real.
+
+import { EVENT_TAGS, PROTOCOL_VERSION, JanRuntime, type EventTag, type RpcResponses, type StreamEvent } from '../src/index.js'
+import type { RpcParams } from '../src/generated/rpc-types.js'
+
+declare function expectType<T>(value: T): T
+
+// The protocol version is a literal from the schema, not a number.
+expectType<1>(PROTOCOL_VERSION)
+expectType<readonly EventTag[]>(EVENT_TAGS)
+
+// The event union is discriminated on `type`, and each tag is assignable to its
+// own record - which is what a consumer's `switch (event.type)` relies on.
+const token: StreamEvent = { type: 'token', text: 'hello' }
+const toolRequest: StreamEvent = {
+ type: 'tool_request',
+ request_id: 'host-1',
+ tool_name: 'robot_arm_move',
+ args: { position: 'bin' },
+ run_id: 'child-9',
+}
+const done: StreamEvent = { type: 'done', stop_reason: 'stop', usage: {} }
+const permission: StreamEvent = {
+ type: 'permission_request',
+ request_id: 'perm-1',
+ tool_name: 'bash',
+ capability: 'actuator',
+ prompt_kind: 'exec',
+ offers_always: true,
+}
+expectType<string>(token.text)
+expectType<string | null | undefined>(toolRequest.run_id)
+expectType<string>(done.stop_reason)
+if (permission.type === 'permission_request') expectType<string>(permission.tool_name)
+if (toolRequest.type === 'tool_request') expectType<unknown>(toolRequest.args)
+
+// A tag the schema does not have is a compile error, which is the point of
+// generating the union instead of writing it out.
+// @ts-expect-error `tokn` is not an event tag
+const misspelled: StreamEvent = { type: 'tokn', text: 'x' }
+expectType<StreamEvent>(misspelled)
+
+// Request params are typed per method.
+expectType<RpcParams<'session/start'>>({ cwd: '/tmp' })
+expectType<RpcParams<'tool/respond'>>({ requestId: 'host-1', content: 'moved' })
+// @ts-expect-error `cwd` is required by session/start
+expectType<RpcParams<'session/start'>>({})
+// @ts-expect-error `content` is a string or parts, not a number
+expectType<RpcParams<'tool/respond'>>({ requestId: 'host-1', content: 7 })
+
+// Responses, which the schema does not describe: declared in `index.d.ts` and
+// pinned by the suite against a real runtime.
+declare const runtime: JanRuntime
+expectType<Promise<RpcResponses['turn/start']>>(runtime.request('turn/start', { sessionId: 's', input: 'hi' }))
+expectType<Promise<RpcResponses['session/tools/get']>>(runtime.request('session/tools/get', { sessionId: 's' }))
+
+// The public classes are constructible only the way the README shows.
+expectType<Promise<JanRuntime>>(JanRuntime.start({ bin: 'jan' }))
diff --git a/packages/agent-sdk/tsconfig.json b/packages/agent-sdk/tsconfig.json
new file mode 100644
index 000000000..9ea17d9a0
--- /dev/null
+++ b/packages/agent-sdk/tsconfig.json
@@ -0,0 +1,22 @@
+{
+ // The SDK's own config: what a consumer's `tsc` has to accept is what this
+ // compiles. `src/index.js` is plain JavaScript, so it is included as a module
+ // - the declarations it satisfies live in `src/index.d.ts`, and both come
+ // from the same generated wire types.
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "lib": ["ES2022"],
+ "types": ["node"],
+ "strict": true,
+ "noEmit": true,
+ "allowJs": true,
+ "checkJs": false,
+ "verbatimModuleSyntax": true,
+ "forceConsistentCasingInFileNames": true,
+ "noUncheckedIndexedAccess": false,
+ "skipLibCheck": true
+ },
+ "include": ["src/**/*.js", "src/**/*.d.ts", "tests/types.ts"]
+}