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 Python client for the agent runtime

thinhlpg9115e4272748
diff --git a/.gitignore b/.gitignore
index bd787bfb0..a87cd7bc4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -38,7 +38,10 @@ archive/
# auto qa
autoqa/trajectories
autoqa/recordings
-autoqa/__pycache__
+
+# python bytecode
+__pycache__/
+*.py[cod]
# Astro / Starlight specific
website/dist/
diff --git a/sdk/python/README.md b/sdk/python/README.md
new file mode 100644
index 000000000..bfcbc8c1d
--- /dev/null
+++ b/sdk/python/README.md
@@ -0,0 +1,184 @@
+# jan-agent-sdk
+
+Python 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.
+
+- Python 3.11+, standard library only - no Node, no third-party packages.
+- The runtime is spawned and owned: a crash, an EOF or `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
+pip install jan-agent-sdk
+```
+
+The runtime binary is separate: `jan` must be on `PATH`, or named by
+`$JAN_BIN` (the `bin` argument 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
+
+```python
+from jan_agent_sdk import JanRuntime
+
+with JanRuntime.start() as runtime:
+ session = runtime.create_session(model="gpt-4o-mini", ephemeral=True)
+ turn = session.prompt("Summarise this table in one line.")
+
+ for event in turn: # blocks until the turn ends
+ if event["type"] == "token":
+ print(event["text"], end="", flush=True)
+
+ print(turn.result().stop_reason)
+```
+
+`prompt()` returns as soon as the turn starts; iterating the turn yields the
+events while it runs, and `result()` blocks for the terminal record. Iterating
+is optional - a host that only calls `result()` still gets it - but an undrained
+turn keeps at most `max_buffered_events` (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:
+
+```python
+from jan_agent_sdk import HostTool, JanRuntime
+
+def observe(args, call):
+ return {"text": "the bench holds a red bin", "images": [frame_path]}
+
+def move(args, call):
+ arm.move(args["position"], abort=call.aborted) # a threading.Event
+ return {"text": f"moved to {args['position']}", "details": {"joints": 3}}
+
+with JanRuntime.start() as runtime:
+ session = runtime.create_session(
+ model="gpt-4o-mini",
+ builtins=False, # only the tools below
+ permissions="host", # this process gates them itself
+ tools=[
+ HostTool(
+ name="camera_observe",
+ description="Look at the robot bench and describe what is there.",
+ parameters={"type": "object", "properties": {}, "additionalProperties": False},
+ capability="read", # never prompted, concurrent
+ handler=observe,
+ ),
+ HostTool(
+ 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
+ handler=move,
+ ),
+ ],
+ )
+```
+
+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 raised exception is answered the same way, so a failed call never leaves the
+turn parked. Each handler runs on its own thread, so the client's reader is
+never held and two subagents may have calls in flight at once: serializing them
+- one native call at a time, on a shared robot - is the host's decision through
+its own queue. `call.aborted` is set 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`;
+the answer is by `request_id` alone, so one path serves both.
+
+`session.tools` and `session.tool_specs` 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.respond_permission(request_id, "allow_once" | "allow_always" | "deny")`,
+ from the code draining the turn:
+
+```python
+for event in turn:
+ if event["type"] == "permission_request":
+ session.respond_permission(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
+
+```python
+session.interrupt() # the turn settles with stop_reason "interrupted"
+session.set_model("...") # between turns; refused mid-turn with -32001
+session.fork() # a new session with this one's history and model
+session.archive() # drop it from the runtime
+runtime.close() # close stdin, then the process
+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.
+
+Listeners registered with `session.on(...)` run on the SDK's own dispatch
+thread, in the order the runtime emitted the events, so a listener may call back
+into the runtime - answering a permission request from one is the case that
+matters - but it must not block for long: the dispatch thread is shared.
+
+## Types
+
+`jan_agent_sdk/_generated.py` is generated from `protocol/rpc-schema.json` -
+request params, the event union, and the method and event-tag literals - by the
+same generator the JavaScript SDK uses:
+
+```bash
+node packages/agent-sdk/scripts/generate.mjs # rewrite both SDKs' types
+node packages/agent-sdk/scripts/generate.mjs --check # fail on drift
+```
+
+The artifact covers request params and events, not responses; the suite pins the
+responses it uses against a real runtime.
+
+## Tests
+
+The suite drives a real runtime against a stub provider on loopback - no
+credentials, no network, no Node:
+
+```bash
+JAN_BIN=/path/to/jan python3 -m unittest discover -s sdk/python/tests -t sdk/python
+```
+
+It is skipped, not failed, when `JAN_BIN` is unset.
diff --git a/sdk/python/jan_agent_sdk/__init__.py b/sdk/python/jan_agent_sdk/__init__.py
new file mode 100644
index 000000000..8261e7e8a
--- /dev/null
+++ b/sdk/python/jan_agent_sdk/__init__.py
@@ -0,0 +1,40 @@
+"""The Jan agent SDK for Python.
+
+One long-lived ``jan cli agent rpc`` runtime, many addressable sessions, and the
+host tools your own process runs - with no Node and no third-party packages.
+
+ from jan_agent_sdk import JanRuntime
+
+ with JanRuntime.start() as runtime:
+ session = runtime.create_session(model="gpt-4o-mini", ephemeral=True)
+ turn = session.prompt("Summarise this table in one line.")
+ for event in turn:
+ if event["type"] == "token":
+ print(event["text"], end="", flush=True)
+ print(turn.result().stop_reason)
+
+See ``README.md`` for host tools, images and process ownership.
+"""
+
+from ._generated import EVENT_TAGS, PROTOCOL_VERSION
+from .errors import JanRpcError, JanRuntimeError
+from .runtime import CLIENT_NAME, CLIENT_VERSION, JanRuntime
+from .session import HostTool, HostToolCall, JanSession, JanTurn, TurnResult
+
+__version__ = CLIENT_VERSION
+
+__all__ = [
+ "CLIENT_NAME",
+ "CLIENT_VERSION",
+ "EVENT_TAGS",
+ "PROTOCOL_VERSION",
+ "HostTool",
+ "HostToolCall",
+ "JanRpcError",
+ "JanRuntime",
+ "JanRuntimeError",
+ "JanSession",
+ "JanTurn",
+ "TurnResult",
+ "__version__",
+]
diff --git a/sdk/python/jan_agent_sdk/_generated.py b/sdk/python/jan_agent_sdk/_generated.py
new file mode 100644
index 000000000..148153794
--- /dev/null
+++ b/sdk/python/jan_agent_sdk/_generated.py
@@ -0,0 +1,489 @@
+# 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.
+
+from __future__ import annotations
+
+from typing import Any, Literal, NotRequired, TypedDict, Union
+
+PROTOCOL_VERSION = 1
+
+#: The JSON-RPC methods this protocol accepts, in schema order.
+RPC_METHODS: tuple[str, ...] = (
+ "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.
+EVENT_TAGS: tuple[str, ...] = (
+ "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",
+)
+
+RpcMethod = Literal[
+ "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",
+]
+
+EventTag = Literal[
+ "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",
+]
+
+# -------------------------------------------------------------------------
+# Shared definitions
+# -------------------------------------------------------------------------
+
+class AskRequest(TypedDict):
+ questions: list[Question]
+
+class ClientInfo(TypedDict):
+ name: str
+ version: str
+
+# 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.
+HostCapability = Union[Literal["read"], Literal["actuator"]]
+
+# The declaration shape, for the document only: the dispatcher parses the real `HostToolDecl`, which lives outside this module and carries no schema.
+class HostToolDeclSchema(TypedDict):
+ name: str
+ description: NotRequired[str]
+ # JSON Schema for the arguments, advertised to the model verbatim.
+ parameters: NotRequired[Union[dict[str, Any], None]]
+ capability: NotRequired[Union[HostCapability, None]]
+
+# Display-only view of one active monitor, for a status panel.
+class MonitorSnapshot(TypedDict):
+ monitorId: str
+ name: str
+ script: str
+ polls: int
+
+class OptionItem(TypedDict):
+ label: str
+ description: NotRequired[Union[str, None]]
+
+# 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.
+class PendingSubagent(TypedDict):
+ name: str
+ phase: int
+
+# 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.
+PermissionOwner = Literal["jan", "host"]
+
+class Question(TypedDict):
+ id: str
+ question: str
+ options: list[OptionItem]
+ multi: NotRequired[bool]
+ recommended: NotRequired[Union[int, None]]
+
+class TodoItem(TypedDict):
+ content: str
+ status: TodoStatus
+
+class TodoList(TypedDict):
+ phases: list[TodoPhase]
+
+class TodoPhase(TypedDict):
+ name: str
+ tasks: list[TodoItem]
+
+TodoStatus = Literal["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.
+ToolResultContent = Union[str, list[Any]]
+
+class Usage(TypedDict):
+ prompt_tokens: NotRequired[Union[int, None]]
+ completion_tokens: NotRequired[Union[int, None]]
+ total_tokens: NotRequired[Union[int, None]]
+ # 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: NotRequired[Union[int, None]]
+ # 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: NotRequired[Union[int, None]]
+
+# -------------------------------------------------------------------------
+# Request parameters, one type per Rust params struct
+# -------------------------------------------------------------------------
+
+class InitializeParams(TypedDict):
+ """`initialize`"""
+
+ protocolVersion: int
+ clientInfo: ClientInfo
+ capabilities: NotRequired[Any]
+
+class SessionListParams(TypedDict):
+ """`session/list`"""
+ pass
+
+class SessionStartParams(TypedDict):
+ """`session/start`"""
+
+ cwd: str
+ model: NotRequired[Union[str, None]]
+ ephemeral: NotRequired[bool]
+ # 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: NotRequired[list[HostToolDeclSchema]]
+ # `false` advertises only the host tools: no built-ins, MCP, plugin, `ask`, `todo`, subagent or monitor tools.
+ builtins: NotRequired[bool]
+ permissions: NotRequired[PermissionOwner]
+
+class SessionIdParams(TypedDict):
+ """`session/resume`, `session/fork`, `session/archive`, `turn/interrupt`, `session/tools/get`, `session/reset`"""
+
+ sessionId: str
+
+class TurnStartParams(TypedDict):
+ """`turn/start`"""
+
+ sessionId: str
+ input: Any
+
+class TurnSteerParams(TypedDict):
+ """`turn/steer`"""
+
+ sessionId: str
+ input: str
+
+class PermissionResponseParams(TypedDict):
+ """`permission/respond`"""
+
+ requestId: str
+ decision: str
+
+class ToolRespondParams(TypedDict):
+ """`tool/respond`"""
+
+ requestId: str
+ content: ToolResultContent
+ isError: NotRequired[bool]
+ # Host/UI-only data, echoed as `item/tool_details` and never sent to the model.
+ details: NotRequired[Union[dict[str, Any], None]]
+
+class SessionToolsSetParams(TypedDict):
+ """`session/tools/set`"""
+
+ sessionId: str
+ tools: list[HostToolDeclSchema]
+
+class SessionModelSetParams(TypedDict):
+ """`session/model/set`"""
+
+ sessionId: str
+ model: str
+
+# -------------------------------------------------------------------------
+# Events: the payload of an ``item/<tag>`` notification
+# -------------------------------------------------------------------------
+
+class TokenEvent(TypedDict):
+ """`item/token`"""
+
+ text: str
+ type: Literal["token"]
+
+class ReasoningEvent(TypedDict):
+ """`item/reasoning`"""
+
+ text: str
+ type: Literal["reasoning"]
+
+class StepEvent(TypedDict):
+ """`item/step`"""
+
+ index: int
+ max: int
+ type: Literal["step"]
+
+class ToolCallStartedEvent(TypedDict):
+ """`item/tool_call_started`"""
+
+ id: str
+ name: str
+ type: Literal["tool_call_started"]
+
+class ToolCallArgsDeltaEvent(TypedDict):
+ """`item/tool_call_args_delta`"""
+
+ id: str
+ delta: str
+ type: Literal["tool_call_args_delta"]
+
+class ToolCallEvent(TypedDict):
+ """`item/tool_call`"""
+
+ id: str
+ name: str
+ args: Any
+ type: Literal["tool_call"]
+
+class ToolOutputDeltaEvent(TypedDict):
+ """`item/tool_output_delta`"""
+
+ id: str
+ delta: str
+ type: Literal["tool_output_delta"]
+
+class ToolResultEvent(TypedDict):
+ """`item/tool_result`"""
+
+ id: str
+ content: str
+ is_error: bool
+ diff: NotRequired[Union[str, None]]
+ type: Literal["tool_result"]
+
+class SubagentStartEvent(TypedDict):
+ """`item/subagent_start`"""
+
+ run_id: str
+ name: str
+ # 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: NotRequired[Union[str, None]]
+ type: Literal["subagent_start"]
+
+class SubagentQueuedEvent(TypedDict):
+ """`item/subagent_queued`"""
+
+ run_id: str
+ name: str
+ task: NotRequired[Union[str, None]]
+ waiting: int
+ type: Literal["subagent_queued"]
+
+class SubagentEndEvent(TypedDict):
+ """`item/subagent_end`"""
+
+ run_id: str
+ name: str
+ # 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: NotRequired[Union[str, None]]
+ type: Literal["subagent_end"]
+
+class SubagentPlanEvent(TypedDict):
+ """`item/subagent_plan`"""
+
+ pending: list[PendingSubagent]
+ type: Literal["subagent_plan"]
+
+class SubagentEvent(TypedDict):
+ """`item/subagent`"""
+
+ run_id: str
+ name: str
+ event: Any
+ type: Literal["subagent"]
+
+class NoticeEvent(TypedDict):
+ """`item/notice`"""
+
+ text: str
+ type: Literal["notice"]
+
+class MonitorsEvent(TypedDict):
+ """`item/monitors`"""
+
+ monitors: list[MonitorSnapshot]
+ type: Literal["monitors"]
+
+class ParkedEvent(TypedDict):
+ """`item/parked`"""
+
+ type: Literal["parked"]
+
+class MessagesUpdatedEvent(TypedDict):
+ """`item/messages_updated`"""
+
+ messages: list[Any]
+ type: Literal["messages_updated"]
+
+class AskRequestEvent(TypedDict):
+ """`item/ask_request`"""
+
+ request_id: str
+ request: AskRequest
+ timeout_secs: NotRequired[Union[int, None]]
+ type: Literal["ask_request"]
+
+class AskResolvedEvent(TypedDict):
+ """`item/ask_resolved`"""
+
+ request_id: str
+ type: Literal["ask_resolved"]
+
+class TodoUpdateEvent(TypedDict):
+ """`item/todo_update`"""
+
+ list: TodoList
+ type: Literal["todo_update"]
+
+class TurnUsageEvent(TypedDict):
+ """`item/turn_usage`"""
+
+ 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: NotRequired[Union[str, None]]
+ type: Literal["turn_usage"]
+
+class DoneEvent(TypedDict):
+ """`item/done`"""
+
+ stop_reason: str
+ usage: NotRequired[Union[Usage, None]]
+ type: Literal["done"]
+
+class ErrorEvent(TypedDict):
+ """`item/error`"""
+
+ code: str
+ message: str
+ type: Literal["error"]
+
+class PermissionRequestEvent(TypedDict):
+ """`item/permission_request`"""
+
+ request_id: str
+ tool_name: str
+ capability: str
+ path: NotRequired[Union[str, None]]
+ # The shell command for exec prompts (drives the command-scoped "allow always" grant); `None` for non-exec tools.
+ command: NotRequired[Union[str, None]]
+ # Focused diff preview for `write`/`edit` prompts so the user sees the change before approving; `None` for other tools.
+ diff: NotRequired[Union[str, None]]
+ prompt_kind: str
+ offers_always: bool
+ type: Literal["permission_request"]
+
+class ToolRequestEvent(TypedDict):
+ """`item/tool_request`"""
+
+ request_id: str
+ tool_name: str
+ # 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: Any
+ # 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: NotRequired[Union[str, None]]
+ type: Literal["tool_request"]
+
+class ToolRequestCancelledEvent(TypedDict):
+ """`item/tool_request_cancelled`"""
+
+ request_id: str
+ reason: str
+ type: Literal["tool_request_cancelled"]
+
+class ToolDetailsEvent(TypedDict):
+ """`item/tool_details`"""
+
+ id: str
+ details: Any
+ type: Literal["tool_details"]
+
+#: Every event a session may report, discriminated on ``type``.
+StreamEvent = Union[
+ 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,
+]
diff --git a/sdk/python/jan_agent_sdk/_queue.py b/sdk/python/jan_agent_sdk/_queue.py
new file mode 100644
index 000000000..9eb6eab7a
--- /dev/null
+++ b/sdk/python/jan_agent_sdk/_queue.py
@@ -0,0 +1,83 @@
+"""One event queue, read by one consumer.
+
+A turn's events, in the order the runtime emitted them. ``push`` reports whether
+the event had to be buffered, which is what lets a turn nobody is draining stay
+bounded.
+"""
+
+from __future__ import annotations
+
+import threading
+from collections import deque
+from typing import Any, Deque, Iterator, Optional
+
+
+# The end of the stream, distinct from every event an ``item/*`` record carries.
+_END: Any = object()
+
+
+class EventQueue:
+ def __init__(self) -> None:
+ self._items: Deque[Any] = deque()
+ self._condition = threading.Condition()
+ self._ended = False
+ self._failure: Optional[BaseException] = None
+
+ def __len__(self) -> int:
+ with self._condition:
+ return len(self._items)
+
+ def push(self, item: Any) -> bool:
+ """Append ``item``; ``True`` when it had to be buffered.
+
+ A waiting reader takes it directly and the answer is ``False``, which is
+ the signal that nobody is behind.
+ """
+ with self._condition:
+ if self._ended:
+ return False
+ if self._items:
+ self._items.append(item)
+ return True
+ self._items.append(item)
+ self._condition.notify()
+ return False
+
+ def drop_oldest(self) -> bool:
+ with self._condition:
+ if not self._items:
+ return False
+ self._items.popleft()
+ return True
+
+ def end(self) -> None:
+ with self._condition:
+ self._ended = True
+ self._condition.notify_all()
+
+ def fail(self, error: BaseException) -> None:
+ with self._condition:
+ self._failure = error
+ self._ended = True
+ self._condition.notify_all()
+
+ def __iter__(self) -> Iterator[Any]:
+ while True:
+ item = self._take()
+ if item is _END:
+ return
+ # Handed over with the lock released: a consumer is allowed to call
+ # back into the runtime from the loop body - interrupting the turn
+ # it is iterating is the case that matters - and that call needs the
+ # reader to keep reading, which needs this lock.
+ yield item
+
+ def _take(self) -> Any:
+ with self._condition:
+ while not self._items and not self._ended:
+ self._condition.wait()
+ if self._items:
+ return self._items.popleft()
+ if self._failure is not None:
+ raise self._failure
+ return _END
diff --git a/sdk/python/jan_agent_sdk/errors.py b/sdk/python/jan_agent_sdk/errors.py
new file mode 100644
index 000000000..d92692807
--- /dev/null
+++ b/sdk/python/jan_agent_sdk/errors.py
@@ -0,0 +1,60 @@
+"""Errors the SDK raises.
+
+Two kinds, and the difference matters to a caller: an answer from the runtime,
+and the channel itself.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Optional
+
+
+class JanRpcError(Exception):
+ """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.
+ """
+
+ def __init__(
+ self,
+ message: str,
+ *,
+ code: Optional[int] = None,
+ data: Any = None,
+ method: Optional[str] = None,
+ ) -> None:
+ super().__init__(message)
+ self.code = code
+ self.data = data
+ self.method = method
+
+ @property
+ def retryable(self) -> bool:
+ """Whether retrying the same request could succeed.
+
+ The runtime says so for "another turn is active", which is the one
+ refusal a host is expected to wait out rather than treat as a bug.
+ """
+ return isinstance(self.data, dict) and self.data.get("retryable") is True
+
+
+class JanRuntimeError(Exception):
+ """The runtime process failed.
+
+ It could not be spawned, it did not complete the handshake, it speaks a
+ protocol version this client does not, or it exited - a channel failure,
+ where :class:`JanRpcError` is an answer.
+ """
+
+ def __init__(
+ self,
+ message: str,
+ *,
+ exit_code: Optional[int] = None,
+ stderr: str = "",
+ ) -> None:
+ super().__init__(message)
+ self.exit_code = exit_code
+ self.stderr = stderr
diff --git a/sdk/python/jan_agent_sdk/py.typed b/sdk/python/jan_agent_sdk/py.typed
new file mode 100644
index 000000000..e69de29bb
diff --git a/sdk/python/jan_agent_sdk/runtime.py b/sdk/python/jan_agent_sdk/runtime.py
new file mode 100644
index 000000000..3897a4eff
--- /dev/null
+++ b/sdk/python/jan_agent_sdk/runtime.py
@@ -0,0 +1,480 @@
+"""The runtime process: one long-lived ``jan cli agent rpc``, spawned and owned.
+
+Everything a client does goes through the JSON-RPC channel this object holds:
+the handshake, one request at a time with an answer, and the notifications a
+turn streams back. One reader thread owns the channel, so a turn's events never
+wait on a request's answer, and a request never waits on a turn.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import queue
+import subprocess
+import threading
+from collections import deque
+from typing import Any, Callable, Deque, Dict, List, Optional, Sequence, Union
+
+from ._generated import PROTOCOL_VERSION
+from .errors import JanRpcError, JanRuntimeError
+from .session import HostTool, JanSession
+
+try: # The version is for the handshake's clientInfo; a source checkout has no metadata.
+ from importlib.metadata import PackageNotFoundError, version as _package_version
+
+ try:
+ CLIENT_VERSION = _package_version("jan-agent-sdk")
+ except PackageNotFoundError: # pragma: no cover - source checkout
+ CLIENT_VERSION = "0.0.0+source"
+except ImportError: # pragma: no cover - Python < 3.8 has no importlib.metadata
+ CLIENT_VERSION = "0.0.0+source"
+
+CLIENT_NAME = "jan-agent-sdk"
+
+
+class _Pending:
+ """One request's slot: the reader thread fills it, the caller waits."""
+
+ __slots__ = ("method", "done", "result", "error")
+
+ def __init__(self, method: str) -> None:
+ self.method = method
+ self.done = threading.Event()
+ self.result: Any = None
+ self.error: Optional[BaseException] = None
+
+ def resolve(self, result: Any) -> None:
+ self.result = result
+ self.done.set()
+
+ def reject(self, error: BaseException) -> None:
+ self.error = error
+ self.done.set()
+
+ def wait(self, timeout: Optional[float]) -> Any:
+ if not self.done.wait(timeout):
+ raise JanRuntimeError(f"{self.method!r} was not answered in time")
+ if self.error is not None:
+ raise self.error
+ return self.result
+
+
+class JanRuntime:
+ """A Jan runtime process.
+
+ :meth:`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.
+ """
+
+ def __init__(
+ self,
+ *,
+ bin: Optional[str] = None,
+ args: Sequence[str] = ("cli", "agent", "rpc"),
+ cwd: Optional[Union[str, os.PathLike]] = None,
+ env: Optional[Dict[str, str]] = None,
+ client_info: Optional[Dict[str, str]] = None,
+ handshake_timeout: float = 20.0,
+ shutdown_grace: float = 5.0,
+ max_buffered_events: int = 100_000,
+ on_stderr: Optional[Callable[[str], None]] = None,
+ ) -> None:
+ self.binary = bin or os.environ.get("JAN_BIN") or "jan"
+ self.cwd = str(cwd) if cwd is not None else None
+ self.max_buffered_events = max_buffered_events
+ self._client_info = client_info or {"name": CLIENT_NAME, "version": CLIENT_VERSION}
+ self._handshake_timeout = handshake_timeout
+ self._shutdown_grace = shutdown_grace
+ self._on_stderr = on_stderr
+ self._stderr_tail: Deque[str] = deque(maxlen=256)
+ self._lock = threading.Lock()
+ # `queue` here is the standard library's, not `._queue` - the SDK's own
+ # event queue - which is why no module of this package shadows it.
+ self._dispatch_queue: "queue.Queue[Optional[Any]]" = queue.Queue()
+ self._dispatch_thread = threading.Thread(target=self._run_dispatch, name="jan-sdk-events", daemon=True)
+ self._pending: Dict[int, _Pending] = {}
+ self._next_id = 1
+ self._sessions: Dict[str, JanSession] = {}
+ self._listeners: Dict[str, List[Callable[[Any], None]]] = {}
+ self._failure: Optional[JanRuntimeError] = None
+ self._closing = False
+ self._protocol_version: Optional[int] = None
+ self._server_info: Optional[Dict[str, str]] = None
+ self._capabilities: Optional[Dict[str, Any]] = None
+ self._limits: Optional[Dict[str, Any]] = None
+
+ environment = {
+ **os.environ,
+ # 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 or {}),
+ }
+ try:
+ self._process = subprocess.Popen(
+ [self.binary, *args],
+ cwd=self.cwd,
+ env=environment,
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ bufsize=1,
+ )
+ except OSError as error:
+ # A binary that is not there is the channel failing to exist, which
+ # is what `JanRuntimeError` is for - not a stray `FileNotFoundError`
+ # from the spawn. No thread has been started yet, so nothing leaks.
+ raise JanRuntimeError(f"could not start '{self.binary}': {error.strerror or error}") from None
+ # Threads start only once the process exists: a failed spawn leaves
+ # nothing behind to join, and the dispatcher never runs without events.
+ self._dispatch_thread.start()
+ self._reader = threading.Thread(target=self._read_stdout, name="jan-rpc-reader", daemon=True)
+ self._reader.start()
+ self._stderr_reader = threading.Thread(target=self._read_stderr, name="jan-rpc-stderr", daemon=True)
+ self._stderr_reader.start()
+
+ # -- construction ------------------------------------------------------
+
+ @classmethod
+ def start(cls, **options: Any) -> "JanRuntime":
+ """Spawn a runtime and complete the handshake."""
+ runtime = cls(**options)
+ try:
+ runtime._handshake()
+ except BaseException:
+ runtime._kill()
+ raise
+ return runtime
+
+ def __enter__(self) -> "JanRuntime":
+ return self
+
+ def __exit__(self, *_: Any) -> None:
+ self.close()
+
+ # -- what the handshake said ------------------------------------------
+
+ @property
+ def protocol_version(self) -> Optional[int]:
+ """The version the runtime answered with, or the handshake threw."""
+ return self._protocol_version
+
+ @property
+ def server_info(self) -> Optional[Dict[str, str]]:
+ return self._server_info
+
+ @property
+ def capabilities(self) -> Optional[Dict[str, Any]]:
+ return self._capabilities
+
+ @property
+ def limits(self) -> Optional[Dict[str, Any]]:
+ """The caps a content-part array is held to - a prompt's images and a
+ host tool's answer alike. ``None`` when the runtime is too old to
+ advertise them."""
+ return self._limits
+
+ @property
+ def pid(self) -> Optional[int]:
+ return self._process.pid
+
+ @property
+ def stderr(self) -> str:
+ """The runtime's own stderr so far."""
+ return "".join(self._stderr_tail)
+
+ def on(self, kind: str, listener: Callable[[Any], None]) -> Callable[[], None]:
+ """Observe ``'exit'``, a frame's ``'notification'``, or an ``'event'``
+ for a session this runtime does not know."""
+ self._listeners.setdefault(kind, []).append(listener)
+
+ def off() -> None:
+ self._listeners[kind] = [entry for entry in self._listeners.get(kind, []) if entry is not listener]
+
+ return off
+
+ # -- the surface -------------------------------------------------------
+
+ def create_session(
+ self,
+ *,
+ cwd: Optional[Union[str, os.PathLike]] = None,
+ model: Optional[str] = None,
+ ephemeral: Optional[bool] = None,
+ builtins: Optional[bool] = None,
+ permissions: Optional[str] = None,
+ tools: Sequence[HostTool] = (),
+ ) -> JanSession:
+ """Start a session. ``tools`` are host tools this session may call.
+
+ ``permissions`` says who gates a host tool call: ``"host"`` when this
+ process runs and gates its own tools, so the runtime never prompts for
+ them, and ``"jan"`` (the default) to leave the gate with the runtime -
+ an actuator call then raises ``permission_request`` and the turn waits
+ until ``session.respond_permission`` answers it.
+ """
+ params: Dict[str, Any] = {"cwd": str(cwd) if cwd is not None else self.cwd or os.getcwd()}
+ if model is not None:
+ params["model"] = model
+ if ephemeral is not None:
+ params["ephemeral"] = ephemeral
+ if builtins is not None:
+ params["builtins"] = builtins
+ if permissions is not None and permissions != "jan":
+ params["permissions"] = permissions
+ if tools:
+ params["tools"] = [tool.declaration() for tool in tools]
+ session = self._session(self.request("session/start", params))
+ if tools:
+ session._declare(tools)
+ return session
+
+ def list_sessions(self) -> List[Dict[str, Any]]:
+ """Sessions this process is serving, as the runtime sees them."""
+ return self.request("session/list", {})["sessions"]
+
+ def resume_session(self, session_id: str) -> JanSession:
+ """Reopen a session of this process from its id.
+
+ Host tools are not inherited: declare them again with
+ :meth:`JanSession.set_tools`.
+ """
+ return self._session(self.request("session/resume", {"sessionId": session_id}))
+
+ def fork_session(self, session_id: str, tools: Sequence[HostTool] = ()) -> JanSession:
+ """A new session with another session's history.
+
+ Host tools are not inherited - a declaration belongs to the session that
+ made it - so they are re-declared here when given.
+ """
+ source = self._sessions.get(session_id)
+ forked = self.request("session/fork", {"sessionId": session_id})["sessionId"]
+ view = self.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.
+ session = self._session({**view, "sessionId": forked, "model": source.model if source is not None else None})
+ if tools:
+ session.set_tools(tools)
+ return session
+
+ def request(self, method: str, params: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None) -> Any:
+ """One JSON-RPC request, answered or refused.
+
+ The escape hatch for a verb this client has no wrapper for.
+ """
+ if self._failure is not None:
+ raise self._failure
+ if self._closing:
+ raise JanRuntimeError("the runtime is closing")
+ with self._lock:
+ request_id = self._next_id
+ self._next_id += 1
+ pending = _Pending(method)
+ self._pending[request_id] = pending
+ try:
+ assert self._process.stdin is not None
+ self._process.stdin.write(json.dumps({"jsonrpc": "2.0", "id": request_id, "method": method, "params": params or {}}) + "\n")
+ self._process.stdin.flush()
+ except (BrokenPipeError, ValueError, OSError) as error:
+ self._pending.pop(request_id, None)
+ raise JanRuntimeError(f"could not write to the runtime: {error}", stderr=self.stderr) from None
+ try:
+ return pending.wait(timeout)
+ finally:
+ self._pending.pop(request_id, None)
+
+ def close(self, *, force: bool = False) -> Optional[int]:
+ """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.
+ """
+ if self._closing:
+ return self._wait_or_kill()
+ self._closing = True
+ gone = JanRuntimeError("the runtime was closed")
+ for session in list(self._sessions.values()):
+ session._fail(gone)
+ self._sessions.clear()
+ if self._process.stdin is not None and not self._process.stdin.closed:
+ try:
+ self._process.stdin.close()
+ except OSError:
+ pass
+ if force:
+ self._kill()
+ self._dispatch_queue.put(None)
+ return self._process.wait()
+ code = self._wait_or_kill()
+ self._dispatch_queue.put(None)
+ return code
+
+ # -- internals ---------------------------------------------------------
+
+ def _handshake(self) -> None:
+ try:
+ result = self.request(
+ "initialize",
+ {
+ "protocolVersion": PROTOCOL_VERSION,
+ "clientInfo": self._client_info,
+ "capabilities": {},
+ },
+ timeout=self._handshake_timeout,
+ )
+ except JanRpcError as error:
+ raise JanRuntimeError(
+ f"{self.binary!r} refused the handshake: {error}" + (f": {self.stderr.strip()}" if self.stderr else ""),
+ stderr=self.stderr,
+ ) from error
+ if result.get("protocolVersion") != PROTOCOL_VERSION:
+ raise JanRuntimeError(
+ f"the runtime speaks protocol version {result.get('protocolVersion')}, "
+ f"this client speaks {PROTOCOL_VERSION}",
+ stderr=self.stderr,
+ )
+ self._protocol_version = result["protocolVersion"]
+ self._server_info = result.get("serverInfo")
+ self._capabilities = result.get("capabilities")
+ self._limits = result.get("input_content_parts")
+ with self._lock:
+ assert self._process.stdin is not None
+ self._process.stdin.write(json.dumps({"jsonrpc": "2.0", "method": "initialized", "params": {}}) + "\n")
+ self._process.stdin.flush()
+
+ def _wait_or_kill(self) -> int:
+ try:
+ return self._process.wait(timeout=self._shutdown_grace)
+ except subprocess.TimeoutExpired:
+ self._kill()
+ return self._process.wait()
+
+ def _kill(self) -> None:
+ self._closing = True
+ try:
+ self._process.kill()
+ except (ProcessLookupError, OSError):
+ pass
+
+ def _session(self, view: Dict[str, Any]) -> JanSession:
+ session = JanSession(self, view)
+ self._sessions[session.id] = session
+ return session
+
+ def _release(self, session: JanSession) -> None:
+ self._sessions.pop(session.id, None)
+
+ def _read_stdout(self) -> None:
+ assert self._process.stdout is not None
+ for line in self._process.stdout:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ frame = json.loads(line)
+ except ValueError:
+ self._fail(JanRuntimeError(f"the runtime wrote a line that is not JSON: {line[:200]}", stderr=self.stderr))
+ return
+ try:
+ self._dispatch(frame)
+ except Exception as error: # noqa: BLE001 - one bad frame must not stop the reader
+ self._fail(JanRuntimeError(f"the SDK could not route a frame: {error}", stderr=self.stderr))
+ return
+ # EOF: the process is gone or going. Anything still parked has no answer
+ # coming, which is exactly what the failure below says.
+ code = self._process.wait()
+ self._fail(
+ JanRuntimeError(
+ f"the jan runtime exited with code {code}" + (f": {self.stderr.strip()}" if self.stderr else ""),
+ exit_code=code,
+ stderr=self.stderr,
+ ),
+ notify_exit=True,
+ )
+
+ def _read_stderr(self) -> None:
+ assert self._process.stderr is not None
+ for line in self._process.stderr:
+ self._stderr_tail.append(line)
+ if self._on_stderr is not None:
+ self._on_stderr(line)
+
+ def _dispatch(self, frame: Dict[str, Any]) -> None:
+ if "method" not in frame:
+ pending = self._pending.get(frame.get("id"))
+ if pending is None:
+ return
+ error = frame.get("error")
+ if error:
+ pending.reject(
+ JanRpcError(
+ error.get("message") or "the runtime refused the request",
+ code=error.get("code"),
+ data=error.get("data"),
+ method=pending.method,
+ )
+ )
+ return
+ pending.resolve(frame.get("result"))
+ return
+ method = frame["method"]
+ params = frame.get("params") or {}
+ if method.startswith("item/"):
+ session = self._sessions.get(params.get("sessionId"))
+ if session is not None:
+ session._deliver(method[len("item/") :], params)
+ else:
+ self._emit("event", {**params, "tag": method[len("item/") :]})
+ return
+ if method == "turn/completed":
+ session = self._sessions.get(params.get("sessionId"))
+ if session is not None:
+ session._complete(params)
+ return
+ self._emit("notification", frame)
+
+ def _emit(self, kind: str, payload: Any) -> None:
+ for listener in list(self._listeners.get(kind, [])):
+ self._notify(listener, payload)
+
+ def _notify(self, listener: Callable[[Any], None], payload: Any) -> None:
+ """Hand a listener its event on the dispatch thread.
+
+ A listener is allowed to call back into the runtime - answering a
+ permission request is the case that matters - so listeners never run on
+ the reader, where the answer they are waiting for could not arrive.
+ Order is kept: one thread drains the queue in the order events are read.
+ """
+ self._dispatch_queue.put((listener, payload))
+
+ def _run_dispatch(self) -> None:
+ while True:
+ job = self._dispatch_queue.get()
+ if job is None:
+ return
+ listener, payload = job
+ try:
+ listener(payload)
+ except Exception as error: # noqa: BLE001 - a listener chose to raise
+ self._fail(JanRuntimeError(f"an event listener raised: {error}", stderr=self.stderr))
+ return
+
+ def _fail(self, error: JanRuntimeError, *, notify_exit: bool = False) -> None:
+ if self._failure is not None:
+ if notify_exit:
+ self._emit("exit", {"code": error.exit_code})
+ return
+ self._failure = error
+ for pending in self._pending.values():
+ pending.reject(error)
+ self._pending.clear()
+ for session in list(self._sessions.values()):
+ session._fail(error)
+ self._sessions.clear()
+ if notify_exit:
+ self._emit("exit", {"code": error.exit_code})
diff --git a/sdk/python/jan_agent_sdk/session.py b/sdk/python/jan_agent_sdk/session.py
new file mode 100644
index 000000000..ec984ad46
--- /dev/null
+++ b/sdk/python/jan_agent_sdk/session.py
@@ -0,0 +1,447 @@
+"""Sessions, turns and the host tools they call."""
+
+from __future__ import annotations
+
+import base64
+import mimetypes
+import threading
+from collections import OrderedDict
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Union
+
+from .errors import JanRuntimeError
+from ._queue import EventQueue
+
+#: What a host tool is told about the call it is running.
+@dataclass
+class HostToolCall:
+ request_id: str
+ """The id the answer is written against."""
+ tool_name: str
+ """The name the host declared, not the ``host__``-prefixed name the model calls."""
+ run_id: Optional[str]
+ """The child that called it, or ``None`` for the main run."""
+ session: "JanSession"
+ aborted: threading.Event
+ """Set when the runtime withdraws the request; a late answer is refused."""
+
+ @property
+ def cancelled(self) -> bool:
+ return self.aborted.is_set()
+
+
+@dataclass
+class HostTool:
+ """A host tool: what the model sees, plus the handler that runs it here.
+
+ ``capability`` is 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 ``auto_approve``
+ unless the host owns the gate, runs sequentially, and is withheld in Plan
+ mode.
+ """
+
+ name: str
+ handler: Callable[[Any, HostToolCall], Any]
+ description: Optional[str] = None
+ parameters: Optional[Dict[str, Any]] = None
+ capability: Optional[str] = None
+
+ def declaration(self) -> Dict[str, Any]:
+ """The wire form: the handler never crosses the process boundary."""
+ declaration: Dict[str, Any] = {"name": self.name}
+ if self.description is not None:
+ declaration["description"] = self.description
+ if self.parameters is not None:
+ declaration["parameters"] = self.parameters
+ if self.capability is not None:
+ declaration["capability"] = self.capability
+ return declaration
+
+
+@dataclass
+class TurnResult:
+ """The terminal record of a turn."""
+
+ stop_reason: str
+ usage: Any = None
+ error: Optional[str] = None
+
+
+class JanTurn:
+ """One turn of a session: what ``session.prompt()`` returns.
+
+ Iterate it for the events as they stream, and call :meth:`result` for the
+ terminal record. Both are safe in any order and more than once; events are
+ buffered until read.
+ """
+
+ def __init__(self, session: "JanSession", turn_id: str) -> None:
+ self.session = session
+ self.id = turn_id
+ #: Events dropped because nobody was draining this turn, oldest first.
+ #: A reader that iterates the turn never drops any.
+ self.dropped = 0
+ self._queue = EventQueue()
+ self._buffered = 0
+ self._terminal = threading.Event()
+ self._result: Optional[TurnResult] = None
+ self._failure: Optional[BaseException] = None
+
+ def __iter__(self) -> Iterator[Dict[str, Any]]:
+ return iter(self._queue)
+
+ def result(self, timeout: Optional[float] = None) -> TurnResult:
+ """Block for ``{stop_reason, usage, error}``.
+
+ Raises :class:`JanRuntimeError` when the channel dies first: a turn with
+ no terminal record has no outcome to report.
+ """
+ if not self._terminal.wait(timeout):
+ raise JanRuntimeError(f"the turn {self.id} did not finish within {timeout}s")
+ if self._failure is not None:
+ raise self._failure
+ assert self._result is not None
+ return self._result
+
+ def interrupt(self) -> None:
+ """Stop this turn; it still settles, with ``stopReason: interrupted``."""
+ self.session.interrupt()
+
+ # -- the session's own calls ------------------------------------------
+
+ def _push(self, event: Dict[str, Any]) -> None:
+ if not self._queue.push(event):
+ return
+ self._buffered += 1
+ if self._buffered <= self.session.max_buffered_events:
+ return
+ if self._queue.drop_oldest():
+ self._buffered -= 1
+ self.dropped += 1
+
+ def _finish(self, result: TurnResult) -> None:
+ self._result = result
+ self._queue.end()
+ self._terminal.set()
+
+ def _fail(self, error: BaseException) -> None:
+ self._failure = error
+ self._queue.fail(error)
+ self._terminal.set()
+
+
+class JanSession:
+ """A session on a runtime: a conversation, its model, and its host tools."""
+
+ def __init__(self, runtime: Any, view: Dict[str, Any]) -> None:
+ self.runtime = runtime
+ self.id: str = view["sessionId"]
+ self.model: Optional[str] = view.get("model")
+ #: The names the runtime advertises, as it reports them: the declared
+ #: ones with their ``host__`` prefix, which is what the model calls.
+ self.tools: List[str] = list(view.get("tools") or [])
+ self.tool_specs: List[Dict[str, Any]] = list(view.get("toolSpecs") or [])
+ self.max_buffered_events = runtime.max_buffered_events
+ self._turns: Dict[str, JanTurn] = {}
+ self._tools: Dict[str, HostTool] = {}
+ self._listeners: Dict[str, List[Callable[[Dict[str, Any]], None]]] = {}
+ self._calls: Dict[str, threading.Event] = {}
+ self._late: "OrderedDict[str, TurnResult]" = OrderedDict()
+ self._closed = False
+
+ # -- the surface ------------------------------------------------------
+
+ def on(self, kind: str, listener: Callable[[Dict[str, Any]], None]) -> Callable[[], None]:
+ """Observe every event of the session, or one kind, or ``'*'``.
+
+ The listener runs on the reader thread that owns the channel: it must
+ not block, or it holds the client's reader. Tool handlers do not run
+ there - each has its own thread - and a turn being iterated does not
+ either.
+ """
+ self._listeners.setdefault(kind, []).append(listener)
+
+ def off() -> None:
+ self._listeners[kind] = [entry for entry in self._listeners.get(kind, []) if entry is not listener]
+
+ return off
+
+ def prompt(self, content: Union[str, List[Dict[str, Any]], Dict[str, Any]]) -> JanTurn:
+ """Start a turn and return it for iteration.
+
+ ``content`` 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,..."}}]``.
+ """
+ turn_id = self.runtime.request("turn/start", {"sessionId": self.id, "input": normalize_input(content)})["turnId"]
+ return self._turn(turn_id, create=True)
+
+ def steer(self, content: Union[str, Dict[str, Any]]) -> None:
+ """Steer the active turn: the message joins the run already in flight."""
+ self.runtime.request("turn/steer", {"sessionId": self.id, "input": extract_text(content)})
+
+ def interrupt(self) -> None:
+ """Stop the active turn and withdraw its outstanding host tool calls."""
+ self.runtime.request("turn/interrupt", {"sessionId": self.id})
+
+ def reset(self) -> None:
+ """Clear the history, keeping the model and the tool set."""
+ self.runtime.request("session/reset", {"sessionId": self.id})
+
+ def get_tools(self) -> Dict[str, Any]:
+ """The tool set the runtime currently advertises, read back from it."""
+ return self.runtime.request("session/tools/get", {"sessionId": self.id})
+
+ def set_tools(self, tools: Sequence[HostTool]) -> Dict[str, Any]:
+ """Replace the host tools between turns; refused while a turn is active."""
+ view = self.runtime.request(
+ "session/tools/set",
+ {"sessionId": self.id, "tools": [tool.declaration() for tool in tools]},
+ )
+ self._declare(tools)
+ self.tools = list(view["tools"])
+ self.tool_specs = list(view["toolSpecs"])
+ return view
+
+ def set_model(self, model: str) -> str:
+ """Change the model between turns; refused while a turn is active."""
+ current = self.runtime.request("session/model/set", {"sessionId": self.id, "model": model})["model"]
+ self.model = current
+ return current
+
+ def fork(self, tools: Sequence[HostTool] = ()) -> "JanSession":
+ """A new session with this one's history.
+
+ Host tools are not inherited - a declaration belongs to the session that
+ made it - so they are re-declared here when given.
+ """
+ return self.runtime.fork_session(self.id, tools)
+
+ def archive(self) -> None:
+ """Drop the session from the runtime."""
+ self.runtime.request("session/archive", {"sessionId": self.id})
+ self.runtime._release(self)
+ self._closed = True
+ self._abort(JanRuntimeError("the session was archived"))
+ self._listeners.clear()
+
+ def respond_permission(self, request_id: str, decision: str) -> None:
+ """Answer a permission request: ``allow_once``, ``allow_always`` or ``deny``."""
+ self.runtime.request("permission/respond", {"requestId": request_id, "decision": decision})
+
+ # -- the runtime's own calls ------------------------------------------
+
+ def _declare(self, tools: Sequence[HostTool]) -> None:
+ self._tools = {tool.name: tool for tool in tools}
+
+ def _deliver(self, tag: str, params: Dict[str, Any]) -> None:
+ event = params.get("event") or {}
+ self._emit("event", event)
+ turn = self._turn(params.get("turnId"), create=True)
+ if turn is not None:
+ turn._push(event)
+ if tag == "tool_request":
+ self._answer(event)
+ elif tag == "tool_request_cancelled":
+ self._abandon(event)
+
+ def _complete(self, params: Dict[str, Any]) -> None:
+ record = TurnResult(
+ stop_reason=params.get("stopReason") or "completed",
+ usage=params.get("usage"),
+ error=params.get("error"),
+ )
+ turn = self._turns.pop(params.get("turnId"), None)
+ if turn is None:
+ # The runtime may close a turn 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.
+ self._late[params.get("turnId") or ""] = record
+ while len(self._late) > 64:
+ self._late.popitem(last=False)
+ return
+ turn._finish(record)
+
+ def _fail(self, error: BaseException) -> None:
+ for turn in self._turns.values():
+ turn._fail(error)
+ self._turns.clear()
+ self._abort(error)
+
+ # -- internals ---------------------------------------------------------
+
+ def _turn(self, turn_id: Optional[str], *, create: bool = False) -> Optional[JanTurn]:
+ if not turn_id:
+ return None
+ existing = self._turns.get(turn_id)
+ if existing is not None:
+ return existing
+ if not create:
+ return None
+ turn = JanTurn(self, turn_id)
+ late = self._late.pop(turn_id, None)
+ if late is None:
+ self._turns[turn_id] = turn
+ else:
+ turn._finish(late)
+ return turn
+
+ def _emit(self, kind: str, event: Dict[str, Any]) -> None:
+ for listener in list(self._listeners.get(kind, [])):
+ self.runtime._notify(listener, event)
+ for listener in list(self._listeners.get("*", [])):
+ self.runtime._notify(listener, event)
+
+ def _answer(self, event: Dict[str, Any]) -> None:
+ """Run a host tool's handler, on its own thread.
+
+ Serializing calls is the host's decision through its own queue, so the
+ reader is never held and two children may be in flight at once.
+ """
+ if self._closed:
+ return
+ request_id = event.get("request_id") or ""
+ tool = self._tools.get(event.get("tool_name") or "")
+ aborted = threading.Event()
+ self._calls[request_id] = aborted
+ call = HostToolCall(
+ request_id=request_id,
+ tool_name=event.get("tool_name") or "",
+ run_id=event.get("run_id"),
+ session=self,
+ aborted=aborted,
+ )
+
+ def run() -> None:
+ if tool is None:
+ self._respond(
+ request_id,
+ {"content": f"no host tool named '{call.tool_name}' is declared on this session", "isError": True},
+ )
+ return
+ try:
+ result = tool.handler(event.get("args"), call)
+ except BaseException as error: # noqa: BLE001 - the answer is the report
+ self._respond(request_id, {"content": str(error), "isError": True})
+ return
+ self._respond(request_id, normalize_result(result))
+
+ threading.Thread(target=run, name=f"jan-tool-{call.tool_name}", daemon=True).start()
+
+ def _abandon(self, event: Dict[str, Any]) -> None:
+ request_id = event.get("request_id") or ""
+ flag = self._calls.pop(request_id, None)
+ if flag is not None:
+ flag.set()
+
+ def _respond(self, request_id: str, params: Dict[str, Any]) -> None:
+ flag = self._calls.get(request_id)
+ if flag is None or flag.is_set():
+ self._calls.pop(request_id, None)
+ return
+ self._calls.pop(request_id, None)
+ try:
+ self.runtime.request("tool/respond", {"requestId": request_id, **params})
+ except Exception: # noqa: BLE001 - the turn was interrupted or the channel closed
+ pass
+
+ def _abort(self, error: BaseException) -> None:
+ for flag in self._calls.values():
+ flag.set()
+ self._calls.clear()
+
+
+def normalize_input(content: Union[str, List[Dict[str, Any]], Dict[str, Any]]) -> Any:
+ """``turn/start`` takes the text, the parts, or the record a stream-json
+ client would write to a ``user`` line."""
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ return {"type": "user", "content": content}
+ if isinstance(content, dict):
+ if isinstance(content.get("text"), str):
+ return content["text"]
+ if isinstance(content.get("content"), list):
+ return {"type": "user", "content": content["content"]}
+ raise TypeError("prompt() takes a string, content parts, or a {text} / {content} record")
+
+
+def extract_text(content: Union[str, Dict[str, Any]]) -> str:
+ if isinstance(content, str):
+ return content
+ if isinstance(content, dict) and isinstance(content.get("text"), str):
+ return content["text"]
+ raise TypeError("steer() takes a string or a {text} record")
+
+
+def normalize_result(result: Any) -> Dict[str, Any]:
+ """What a handler returned, as the ``tool/respond`` the runtime parses.
+
+ A result that cannot be shaped is still answered: the model is never left
+ parked on a call this client failed to format.
+ """
+ if result is None:
+ return {"content": ""}
+ if isinstance(result, str):
+ return {"content": result}
+ if not isinstance(result, dict):
+ return {"content": str(result)}
+ if result.get("isError") is True or isinstance(result.get("error"), str):
+ return {"content": result.get("error") or str(result.get("content") or ""), "isError": True}
+ parts: List[Dict[str, Any]] = []
+ text = result.get("text")
+ if text is None and isinstance(result.get("content"), str):
+ text = result["content"]
+ if text:
+ parts.append({"type": "text", "text": str(text)})
+ for key in ("parts", "content"):
+ value = result.get(key)
+ if isinstance(value, list):
+ parts.extend(value)
+ break
+ for image in result.get("images") or []:
+ parts.append(to_image_part(image))
+ response: Dict[str, Any] = {"content": parts if parts else str(text or "")}
+ if result.get("details") is not None:
+ details = result["details"]
+ # `details` is host-only data echoed back in `tool_details`, and the
+ # runtime takes an object of values, so anything else is carried as one.
+ response["details"] = details if isinstance(details, dict) else {"value": details}
+ return response
+
+
+def to_image_part(image: Any) -> Dict[str, Any]:
+ """An image as the wire wants it: a path, a data URL, or bytes."""
+ if isinstance(image, str):
+ url = image if image.startswith("data:") else data_url_from_file(image)
+ return {"type": "image_url", "image_url": {"url": url}}
+ if isinstance(image, Path):
+ return {"type": "image_url", "image_url": {"url": data_url_from_file(image)}}
+ if isinstance(image, dict):
+ if isinstance(image.get("url"), str):
+ return {"type": "image_url", "image_url": {"url": image["url"]}}
+ if isinstance(image.get("path"), str):
+ return {
+ "type": "image_url",
+ "image_url": {"url": data_url_from_file(image["path"], image.get("mimeType"))},
+ }
+ if image.get("data") is not None:
+ payload = image["data"]
+ if isinstance(payload, (bytes, bytearray, memoryview)):
+ encoded = base64.b64encode(bytes(payload)).decode("ascii")
+ else:
+ encoded = str(payload)
+ return {
+ "type": "image_url",
+ "image_url": {"url": f"data:{image.get('mimeType') or 'image/png'};base64,{encoded}"},
+ }
+ raise TypeError("an image is a path, a data URL, or {data, mimeType}")
+
+
+def data_url_from_file(path: Union[str, Path], mime_type: Optional[str] = None) -> str:
+ resolved = Path(path)
+ mime = mime_type or mimetypes.guess_type(resolved.name)[0] or "image/png"
+ return f"data:{mime};base64,{base64.b64encode(resolved.read_bytes()).decode('ascii')}"
diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml
new file mode 100644
index 000000000..7b58f24a2
--- /dev/null
+++ b/sdk/python/pyproject.toml
@@ -0,0 +1,32 @@
+[build-system]
+requires = ["setuptools>=68"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "jan-agent-sdk"
+version = "0.1.0"
+description = "Python client for the Jan agent runtime: sessions, streamed turns, and host tools over `jan cli agent rpc`"
+readme = "README.md"
+requires-python = ">=3.11"
+license = { text = "AGPL-3.0" }
+authors = [{ name = "Jan", email = "[email protected]" }]
+keywords = ["jan", "agent", "sdk", "json-rpc"]
+classifiers = [
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.11",
+ "Programming Language :: Python :: 3.12",
+ "License :: OSI Approved :: GNU Affero General Public License v3",
+]
+# No dependencies on purpose: the runtime is a process, the channel is JSON, and
+# a host that has to install a tree to embed an agent will not.
+dependencies = []
+
+[project.urls]
+Homepage = "https://jan.ai"
+Repository = "https://github.com/janhq/jan"
+
+[tool.setuptools]
+packages = ["jan_agent_sdk"]
+
+[tool.setuptools.package-data]
+jan_agent_sdk = ["py.typed"]
diff --git a/sdk/python/tests/__init__.py b/sdk/python/tests/__init__.py
new file mode 100644
index 000000000..cef2bec8f
--- /dev/null
+++ b/sdk/python/tests/__init__.py
@@ -0,0 +1 @@
+"""The SDK suite: a stub provider, a scratch home, and a real runtime."""
diff --git a/sdk/python/tests/harness.py b/sdk/python/tests/harness.py
new file mode 100644
index 000000000..6b340d1c5
--- /dev/null
+++ b/sdk/python/tests/harness.py
@@ -0,0 +1,243 @@
+"""The harness the SDK suite drives: a stub provider on loopback and a scratch
+home, so the tests need no credentials, no network and no Jan Desktop.
+
+The provider is the same shape the Rust CLI tests use: the first request is
+answered with a tool call, the second with prose, and the bodies are kept so a
+test can assert what the model was actually sent.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import tempfile
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from typing import Any, Callable, Dict, List, Optional, Sequence, Union
+
+Reply = Union[str, Callable[["_Handler"], None]]
+
+
+class _Handler(BaseHTTPRequestHandler):
+ """The handler http.server builds per request, with the provider attached.
+
+ Not a dataclass: http.server instantiates it as
+ ``(request, client_address, server)``, so it must keep the base's
+ ``__init__``.
+ """
+
+ provider: "Provider"
+
+ def do_POST(self) -> None: # noqa: N802 - the name http.server calls
+ length = int(self.headers.get("content-length") or 0)
+ body = self.rfile.read(length).decode("utf-8")
+ reply = self.provider._next_reply(body)
+ self.send_response(200)
+ self.send_header("content-type", "text/event-stream")
+ self.send_header("connection", "close")
+ self.end_headers()
+ if callable(reply):
+ # A reply the test drives: the socket stays open until it says so,
+ # which is what an interrupt test needs to interrupt a live turn.
+ reply(self)
+ self.wfile.flush()
+ self.provider._hold.wait(self.provider._hold_timeout)
+ return
+ self.wfile.write(reply.encode("utf-8"))
+ self.wfile.flush()
+
+ def log_message(self, *_: Any) -> None:
+ """Silence: the suite's output is the tests', not the server's."""
+
+
+class Provider:
+ """Serve ``replies`` in order, one per request, repeating the last."""
+
+ def __init__(self, replies: Sequence[Reply], hold_timeout: float = 10.0) -> None:
+ self.replies = list(replies)
+ self.bodies: List[str] = []
+ self.connections = 0
+ self._lock = threading.Lock()
+ self._hold = threading.Event()
+ self._hold_timeout = hold_timeout
+ self._server: Optional[ThreadingHTTPServer] = None
+
+ def start(self) -> str:
+ handler = type("Handler", (_Handler,), {"provider": self})
+ self._server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
+ self._server.daemon_threads = True
+ threading.Thread(target=self._server.serve_forever, name="stub-provider", daemon=True).start()
+ host, port = self._server.server_address
+ return f"http://{host}:{port}/v1"
+
+ def _next_reply(self, body: str) -> Reply:
+ with self._lock:
+ body, index = body, self.connections
+ self.bodies.append(body)
+ self.connections += 1
+ return self.replies[min(index, len(self.replies) - 1)]
+
+ def release(self) -> None:
+ """Let a held reply finish."""
+ self._hold.set()
+
+ def stop(self) -> None:
+ self._hold.set()
+ if self._server is not None:
+ self._server.shutdown()
+ self._server.server_close()
+
+
+def tool_call(name: str, args: Dict[str, Any]) -> str:
+ """A chunk the model asks for a tool with.
+
+ ``host__`` is the advertised name; the host is told the bare one.
+ """
+ return "".join(
+ [
+ "data: "
+ + json.dumps(
+ {
+ "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": name, "arguments": json.dumps(args)},
+ }
+ ],
+ },
+ "finish_reason": None,
+ }
+ ],
+ }
+ )
+ + "\n\n",
+ "data: "
+ + json.dumps(
+ {
+ "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",
+ ]
+ )
+
+
+def prose(text: str) -> str:
+ """Plain prose, which ends the run."""
+ return "".join(
+ [
+ "data: "
+ + json.dumps(
+ {
+ "id": "stub-2",
+ "object": "chat.completion.chunk",
+ "created": 1,
+ "model": "stub-model",
+ "choices": [{"index": 0, "delta": {"role": "assistant", "content": text}, "finish_reason": None}],
+ }
+ )
+ + "\n\n",
+ "data: "
+ + json.dumps(
+ {
+ "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",
+ ]
+ )
+
+
+def holding(text: str) -> Callable[[_Handler], None]:
+ """One token, then the socket stays open: a turn to interrupt mid-flight."""
+
+ def write(handler: _Handler) -> None:
+ handler.wfile.write(
+ (
+ "data: "
+ + json.dumps(
+ {
+ "id": "stub-3",
+ "object": "chat.completion.chunk",
+ "created": 1,
+ "model": "stub-model",
+ "choices": [{"index": 0, "delta": {"role": "assistant", "content": text}, "finish_reason": None}],
+ }
+ )
+ + "\n\n"
+ ).encode("utf-8")
+ )
+
+ return write
+
+
+class Scratch:
+ """A private home and project, removed by :meth:`cleanup`."""
+
+ def __init__(self, bin: str) -> None:
+ self.bin = bin
+ self.root = Path(tempfile.mkdtemp(prefix="jan-sdk-py-"))
+ self.home = self.root / "home"
+ self.project = self.root / "project"
+ self.home.mkdir(parents=True, exist_ok=True)
+ self.project.mkdir(parents=True, exist_ok=True)
+
+ @property
+ def env(self) -> Dict[str, str]:
+ return {**os.environ, "HOME": str(self.home), "JAN_CLI_NO_UPDATE_CHECK": "1"}
+
+ def configure(self, base_url: str) -> None:
+ """Point the runtime at the stub provider, so a session resolves a model."""
+ subprocess.run(
+ [
+ self.bin,
+ "config",
+ "set",
+ "--provider",
+ "stub",
+ "--api-key",
+ "test-key",
+ "--base-url",
+ base_url,
+ "--model",
+ "stub-model",
+ ],
+ env=self.env,
+ check=True,
+ capture_output=True,
+ )
+
+ def start(self, **options: Any):
+ from jan_agent_sdk import JanRuntime
+
+ return JanRuntime.start(bin=self.bin, env=self.env, **options)
+
+ def cleanup(self) -> None:
+ import shutil
+
+ shutil.rmtree(self.root, ignore_errors=True)
diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.py
new file mode 100644
index 000000000..b4840aabe
--- /dev/null
+++ b/sdk/python/tests/test_sdk.py
@@ -0,0 +1,373 @@
+"""The Python SDK, driven end to end against a real runtime.
+
+The same conformance cases the JavaScript suite runs, because they are the same
+client in a different runtime: the handshake and its caps, a session and its
+turn, a host tool's answer becoming the tool message the model sees, an
+image-bearing result, a handler that fails, an interrupt that settles once, two
+sessions that never hear each other, and a channel that closes under a turn
+instead of hanging.
+
+Set ``JAN_BIN`` to the runtime binary; without it the suite skips rather than
+fails. Nothing here needs Node.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import unittest
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from jan_agent_sdk import PROTOCOL_VERSION, HostTool, JanRpcError, JanRuntime, JanRuntimeError # noqa: E402
+from tests.harness import Provider, Scratch, holding, prose, tool_call # noqa: E402
+
+BIN = os.environ.get("JAN_BIN")
+
+
[email protected](BIN, "set JAN_BIN to the jan binary to run the SDK suite")
+class SdkTest(unittest.TestCase):
+ def setUp(self) -> None:
+ self.provider: Provider | None = None
+ self.scratch: Scratch | None = None
+
+ def tearDown(self) -> None:
+ if self.provider is not None:
+ self.provider.stop()
+ if self.scratch is not None:
+ self.scratch.cleanup()
+
+ def prepare(self, replies) -> Scratch:
+ provider = Provider(replies)
+ url = provider.start()
+ scratch = Scratch(BIN)
+ scratch.configure(url)
+ self.provider = provider
+ self.scratch = scratch
+ return scratch
+
+ # -- the channel ------------------------------------------------------
+
+ def test_a_runtime_handshakes_and_reports_its_caps(self) -> None:
+ scratch = self.prepare([prose("unused")])
+ with scratch.start() as runtime:
+ self.assertEqual(runtime.protocol_version, PROTOCOL_VERSION)
+ self.assertEqual(runtime.server_info["name"], "jan")
+ self.assertTrue(runtime.capabilities["session"])
+ # The caps are the handshake's business: a client that sends an
+ # image learns the limits here rather than from a rejection.
+ self.assertIsNotNone(runtime.limits, "the handshake advertises the content-part caps")
+ self.assertGreaterEqual(runtime.limits["max_images"], 1)
+ self.assertIn("image/png", runtime.limits["mime_types"])
+ self.assertGreater(runtime.pid or 0, 0)
+
+ def test_a_runtime_that_is_not_there_fails_before_any_work_starts(self) -> None:
+ with self.assertRaises(JanRuntimeError):
+ JanRuntime.start(bin=os.path.join(self._tmp(), "jan-does-not-exist"), env=os.environ)
+
+ def test_a_request_with_no_runtime_behind_it_is_refused_not_hung(self) -> None:
+ scratch = self.prepare([prose("unused")])
+ with scratch.start() as runtime:
+ with self.assertRaises(JanRpcError) as refusal:
+ runtime.request("session/tools/get", {"sessionId": "not-a-session"})
+ self.assertEqual(refusal.exception.code, -32602)
+ self.assertIn("unknown session", str(refusal.exception))
+ self.assertFalse(refusal.exception.retryable)
+
+ # -- sessions and turns -----------------------------------------------
+
+ def test_a_session_runs_a_turn_and_reports_its_own_state(self) -> None:
+ scratch = self.prepare([prose("the arm reached bin")])
+ with scratch.start() as runtime:
+ session = runtime.create_session(
+ cwd=scratch.project, model="stub-model", ephemeral=True, builtins=False
+ )
+ self.assertTrue(session.id)
+ self.assertEqual(session.model, "stub-model")
+
+ seen: list[str] = []
+ session.on("event", lambda event: seen.append(event["type"]))
+
+ turn = session.prompt("move the arm")
+ events = list(turn)
+ result = turn.result()
+
+ self.assertEqual(result.stop_reason, "completed")
+ self.assertEqual("".join(e["text"] for e in events if e["type"] == "token"), "the arm reached bin")
+ self.assertTrue(any(e["type"] == "step" for e in events))
+ # The session hears what the turn hears, so a host can observe a run
+ # it is not the one iterating.
+ self.assertIn("token", seen)
+
+ self.assertEqual(session.get_tools()["tools"], [])
+ sessions = {entry["id"]: entry for entry in runtime.list_sessions()}
+ self.assertEqual(sessions[session.id]["turns"], 1)
+ self.assertEqual(session.set_model("stub-model"), "stub-model")
+ session.reset()
+ session.archive()
+
+ def test_a_permission_request_the_runtime_owns_is_answered_by_the_host(self) -> None:
+ calls: list[dict] = []
+ scratch = self.prepare([tool_call("host__robot_arm_move", {"position": "bin"}), prose("the arm reached bin")])
+ with scratch.start() as runtime:
+ # No `permissions="host"`: the runtime owns the gate, so an actuator
+ # is prompted before the call reaches its handler.
+ session = runtime.create_session(
+ cwd=scratch.project,
+ model="stub-model",
+ ephemeral=True,
+ builtins=False,
+ tools=[
+ HostTool(
+ name="robot_arm_move",
+ description="Move the arm.",
+ capability="actuator",
+ handler=lambda args, _call: calls.append(args) or {"text": "moved to bin"},
+ )
+ ],
+ )
+ seen: list[str] = []
+
+ def on_event(event: dict) -> None:
+ seen.append(event["type"])
+ if event["type"] == "permission_request":
+ self.assertEqual(event["tool_name"], "host__robot_arm_move")
+ self.assertIsInstance(event["capability"], str)
+ session.respond_permission(event["request_id"], "allow_once")
+
+ session.on("event", on_event)
+ turn = session.prompt("move the arm")
+ list(turn)
+ result = turn.result()
+
+ self.assertEqual(result.stop_reason, "completed")
+ self.assertEqual(calls, [{"position": "bin"}], "the call ran once the host allowed it")
+ self.assertIn("tool_request", seen)
+
+
+ def test_two_sessions_never_see_each_others_events(self) -> None:
+ scratch = self.prepare([prose("alpha"), prose("beta")])
+ with scratch.start() as runtime:
+ first = runtime.create_session(cwd=scratch.project, model="stub-model", ephemeral=True)
+ second = runtime.create_session(cwd=scratch.project, model="stub-model", ephemeral=True)
+
+ noise: list[str] = []
+ second.on("event", lambda event: noise.append(event["type"]))
+
+ turn = first.prompt("say alpha")
+ events = list(turn)
+ turn.result()
+
+ self.assertTrue(any(e["type"] == "token" and e["text"] == "alpha" for e in events))
+ self.assertEqual(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.
+ fork = first.fork()
+ self.assertIsInstance(fork.id, str)
+ self.assertTrue(fork.id)
+ self.assertNotEqual(fork.id, first.id)
+ self.assertEqual(fork.model, "stub-model")
+ self.assertIn("bash", fork.get_tools()["tools"])
+
+ def test_a_turn_is_bounded_when_nobody_drains_it(self) -> None:
+ scratch = self.prepare([prose("unread")])
+ with scratch.start(max_buffered_events=0) as runtime:
+ session = runtime.create_session(cwd=scratch.project, model="stub-model", ephemeral=True)
+ turn = session.prompt("say something")
+ result = turn.result()
+ self.assertEqual(result.stop_reason, "completed")
+ # Nothing was reading, so the events were dropped rather than held:
+ # the terminal record still arrived, which is what a late reader
+ # needs most.
+ self.assertGreater(turn.dropped, 0)
+
+ # -- host tools -------------------------------------------------------
+
+ def test_a_host_tool_round_trips(self) -> None:
+ scratch = self.prepare([tool_call("host__robot_arm_move", {"position": "bin"}), prose("the arm reached bin")])
+ calls: list[tuple] = []
+ with scratch.start() as runtime:
+ session = runtime.create_session(
+ cwd=scratch.project,
+ model="stub-model",
+ ephemeral=True,
+ # Built-ins off, so the advertised set is exactly what this test
+ # declared; the gate is the host's, so an actuator this client
+ # runs itself is not prompted for twice.
+ builtins=False,
+ permissions="host",
+ tools=[
+ HostTool(
+ name="robot_arm_move",
+ description="Move the arm.",
+ parameters={
+ "type": "object",
+ "properties": {"position": {"type": "string"}},
+ "required": ["position"],
+ },
+ capability="actuator",
+ handler=lambda args, call: (calls.append((args, call)) or {"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 (asserted below, on the request it receives).
+ self.assertEqual(session.tools, ["host__robot_arm_move"])
+ self.assertEqual(session.tool_specs[0]["function"]["name"], "host__robot_arm_move")
+
+ turn = session.prompt("move the arm")
+ events = list(turn)
+ self.assertEqual(turn.result().stop_reason, "completed")
+
+ request = next(e for e in events if e["type"] == "tool_request")
+ # The host dispatches on the name it declared, not the `host__` name
+ # the model calls, and a main-run request carries no run id.
+ self.assertEqual(request["tool_name"], "robot_arm_move")
+ self.assertEqual(request["args"], {"position": "bin"})
+ self.assertIsNone(request.get("run_id"))
+ self.assertEqual(calls[0][0], {"position": "bin"})
+ self.assertEqual(calls[0][1].tool_name, "robot_arm_move")
+ self.assertIsNone(calls[0][1].run_id)
+ self.assertIs(calls[0][1].session, session)
+
+ # The tool's answer became the tool message of the next provider
+ # request: that, not the handler call, is what makes it a round trip.
+ self.assertEqual(len(self.provider.bodies), 2, "the model was asked twice")
+ self.assertIn("moved to bin", self.provider.bodies[1])
+ # `details` is host-only: echoed on the channel, never sent.
+ self.assertNotIn("joints", self.provider.bodies[1])
+
+ def test_an_image_bearing_host_result_reaches_the_model_as_an_image_part(self) -> None:
+ scratch = self.prepare([tool_call("host__camera_observe", {"frame": 1}), prose("the bin is clear")])
+ # A 1x1 PNG: a valid payload, small enough to inline.
+ png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8AARAAB/wDcH1jPAAAAAElFTkSuQmCC"
+ with scratch.start() as runtime:
+ session = runtime.create_session(
+ cwd=scratch.project,
+ model="stub-model",
+ ephemeral=True,
+ builtins=False,
+ permissions="host",
+ tools=[
+ HostTool(
+ name="camera_observe",
+ description="Look at the bench.",
+ capability="read",
+ handler=lambda _args, _call: {"text": "the bench", "images": [{"data": png, "mimeType": "image/png"}]},
+ )
+ ],
+ )
+ turn = session.prompt("look at the bench")
+ list(turn)
+ turn.result()
+
+ messages = json.loads(self.provider.bodies[1])["messages"]
+ self.assertEqual(messages[-2]["role"], "tool", "the tool message reported the result")
+ self.assertEqual(messages[-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.
+ message = messages[-1]
+ self.assertEqual(message["role"], "user")
+ self.assertIsInstance(message["content"], list, "the user message carries content parts")
+ self.assertEqual(message["content"][0]["type"], "text")
+ self.assertGreater(len(message["content"][0]["text"]), 0, "the user turn is labelled")
+ self.assertEqual(message["content"][1]["type"], "image_url")
+ self.assertEqual(message["content"][1]["image_url"]["url"], f"data:image/png;base64,{png}")
+
+ def test_a_handler_that_raises_answers_the_call_and_the_turn_goes_on(self) -> None:
+ scratch = self.prepare([tool_call("host__robot_arm_move", {"position": "bin"}), prose("the arm did not move")])
+
+ def explode(_args, _call):
+ raise RuntimeError("the emergency stop is engaged")
+
+ with scratch.start() as runtime:
+ session = runtime.create_session(
+ cwd=scratch.project,
+ model="stub-model",
+ ephemeral=True,
+ permissions="host",
+ tools=[HostTool(name="robot_arm_move", capability="actuator", handler=explode)],
+ )
+ turn = session.prompt("move the arm")
+ list(turn)
+ self.assertEqual(turn.result().stop_reason, "completed")
+ self.assertIn("the emergency stop is engaged", self.provider.bodies[1])
+
+ def test_interrupting_a_turn_settles_it_once_and_abandons_its_parked_call(self) -> None:
+ scratch = self.prepare([tool_call("host__robot_arm_move", {"position": "bin"}), holding("working on it")])
+ aborted: list[bool] = []
+ answered: list[bool] = []
+
+ def wait_for_abort(_args, call):
+ if call.aborted.wait(10):
+ aborted.append(True)
+ answered.append(True)
+ return {"text": "too late"}
+
+ with scratch.start() as runtime:
+ session = runtime.create_session(
+ cwd=scratch.project,
+ model="stub-model",
+ ephemeral=True,
+ permissions="host",
+ tools=[HostTool(name="robot_arm_move", capability="actuator", handler=wait_for_abort)],
+ )
+ turn = session.prompt("move the arm")
+ events = []
+ for event in turn:
+ events.append(event)
+ if event["type"] == "tool_request":
+ session.interrupt()
+
+ self.assertEqual(turn.result().stop_reason, "interrupted")
+ # The parked call is withdrawn rather than answered: the runtime
+ # would refuse a late answer as not pending.
+ self.assertTrue(any(e["type"] == "tool_request_cancelled" for e in events))
+ self.assertEqual(aborted, [True], "the handler was told to stop")
+ self.assertEqual(turn.dropped, 0)
+
+ # -- the channel under a turn -----------------------------------------
+
+ def test_a_session_is_reopened_by_its_id(self) -> None:
+ scratch = self.prepare([prose("one"), prose("two")])
+ with scratch.start() as runtime:
+ first = runtime.create_session(cwd=scratch.project, model="stub-model", ephemeral=True)
+ list(first.prompt("say something"))
+
+ # The runtime rebuilt this session from its own state, so the id it
+ # answers for and the model it runs are the ones it had.
+ again = runtime.resume_session(first.id)
+ self.assertEqual(again.id, first.id)
+ self.assertEqual(again.model, "stub-model")
+ resumed = again.prompt("say something else")
+ list(resumed)
+ self.assertEqual(resumed.result().stop_reason, "completed")
+
+
+ def test_closing_the_runtime_settles_an_open_turn(self) -> None:
+ scratch = self.prepare([holding("still here")])
+ runtime = scratch.start()
+ session = runtime.create_session(cwd=scratch.project, model="stub-model", ephemeral=True)
+ turn = session.prompt("say something")
+ code = 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.
+ self.assertEqual(code, 0)
+ with self.assertRaises(JanRuntimeError):
+ turn.result(timeout=5)
+
+ def _tmp(self) -> str:
+ import tempfile
+
+ return tempfile.mkdtemp(prefix="jan-sdk-missing-")
+
+
+if __name__ == "__main__":
+ unittest.main()