Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(adk): keep host tools callable and contain listener failures (#9278)
Thinh Le395d181fea43
diff --git a/adk/python/README.md b/adk/python/README.mdindex 826713599..8c4f78780 100644--- a/adk/python/README.md+++ b/adk/python/README.md@@ -212,11 +212,22 @@ the cap by being rejected. `JanRpcError` is an answer (`code`, `retryable`), and`JanRuntimeError` is the channel (spawn failure, protocol mismatch, exit), withthe runtime's own stderr attached.+A session's host tools follow it. `fork()` answers for the source's tools with+the same handlers (`fork(tools=[...])` replaces them, `fork(tools=[])` drops+them), and `resume_session(id)` returns the session this client already holds,+with its turns, listeners and handlers, rather than a second object for the+same id. A host tool's name is stripped of surrounding whitespace, as the+runtime does.+Listeners registered with `session.on(...)` run on the ADK's own dispatchthread, in the order the runtime emitted the events, so a listener may call backinto the runtime - answering a permission request from one is the case thatmatters - but it must not block for long: the dispatch thread is shared.+A listener that raises fails the runtime rather than being skipped: every open+turn settles with a `JanRuntimeError` naming what it raised, so a listener that+was answering permission requests cannot leave a turn parked behind it.+## Types`jan_adk/_generated.py` is generated from `protocol/rpc-schema.json` -diff --git a/adk/python/jan_adk/errors.py b/adk/python/jan_adk/errors.pyindex 7732f51f9..f0609c8a8 100644--- a/adk/python/jan_adk/errors.py+++ b/adk/python/jan_adk/errors.py@@ -58,3 +58,12 @@ class JanRuntimeError(Exception):super().__init__(message)self.exit_code = exit_codeself.stderr = stderr+++def describe_error(error: BaseException) -> str:+ """What a handler or listener raised, as text, without trusting its+ ``__str__`` not to raise: that must not stop the failure being reported."""+ try:+ return str(error)+ except Exception: # noqa: BLE001+ return type(error).__name__diff --git a/adk/python/jan_adk/runtime.py b/adk/python/jan_adk/runtime.pyindex 3dadf4581..630ba44ea 100644--- a/adk/python/jan_adk/runtime.py+++ b/adk/python/jan_adk/runtime.py@@ -17,7 +17,7 @@ from collections import dequefrom typing import Any, Callable, Deque, Dict, List, Optional, Sequence, Unionfrom ._generated import PROTOCOL_VERSION-from .errors import JanRpcError, JanRuntimeError+from .errors import JanRpcError, JanRuntimeError, describe_errorfrom .session import HostTool, JanSessiontry: # The version is for the handshake's clientInfo; a source checkout has no metadata.@@ -252,27 +252,47 @@ class JanRuntime: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`.+ A session this client already holds is returned as it is, not rebuilt:+ it keeps its turns, listeners, host tool handlers and pending calls, so+ work in flight settles on the object the caller already has. The+ runtime only knows the sessions this process created, so an id this+ client has not seen is not expected; one that does arrive is attached+ without handlers."""- return self._session(self.request("session/resume", {"sessionId": session_id}))-- def fork_session(self, session_id: str, tools: Sequence[HostTool] = ()) -> JanSession:+ view = self.request("session/resume", {"sessionId": session_id})+ known = self._sessions.get(session_id)+ if known is not None:+ known.model = view.get("model") or known.model+ return known+ return self._session(view)++ def fork_session(self, session_id: str, tools: Optional[Sequence[HostTool]] = None) -> 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.+ Without ``tools`` it takes the source's host tools and handlers; with+ them, those replace the set."""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 work() -> JanSession:+ 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 is not None:+ session.set_tools(tools)+ elif source is not None:+ session._declare(source._declarations())+ return session++ # After the source's pending tool changes, and before later ones, so the+ # runtime clones the same tools whose handlers are copied here.+ if source is None:+ return work()+ with source._mutations:+ return work()def request(self, method: str, params: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None) -> Any:"""One JSON-RPC request, answered or refused.@@ -283,6 +303,10 @@ class JanRuntime:raise self._failureif self._closing:raise JanRuntimeError("the runtime is closing")+ # Encoded before anything is registered: a value that cannot be encoded (a+ # Path, a circular reference) is the caller's to hear about as it is, and+ # must neither leave a pending entry behind nor read as a failed write.+ params_json = json.dumps(params or {})with self._lock:request_id = self._next_idself._next_id += 1@@ -290,7 +314,9 @@ class JanRuntime:self._pending[request_id] = pendingtry: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.write(+ f'{{"jsonrpc": "2.0", "id": {request_id}, "method": {json.dumps(method)}, "params": {params_json}}}\n'+ )self._process.stdin.flush()except (BrokenPipeError, ValueError, OSError) as error:self._pending.pop(request_id, None)@@ -474,7 +500,7 @@ class JanRuntime: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))+ self._fail(JanRuntimeError(f"an event listener raised: {describe_error(error)}", stderr=self.stderr))returndef _fail(self, error: JanRuntimeError, *, notify_exit: bool = False) -> None:diff --git a/adk/python/jan_adk/session.py b/adk/python/jan_adk/session.pyindex ad5110f3e..eede8f3cb 100644--- a/adk/python/jan_adk/session.py+++ b/adk/python/jan_adk/session.py@@ -10,7 +10,7 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Union-from .errors import JanRuntimeError+from .errors import JanRpcError, JanRuntimeError, describe_errorfrom ._queue import EventQueue#: What a host tool is told about the call it is running.@@ -44,9 +44,18 @@ class HostTool:parameters: Optional[Dict[str, Any]] = Nonecapability: Optional[str] = None+ @property+ def declared_name(self) -> str:+ """The name the runtime holds: it trims what it is given, so the handler+ is found under the trimmed name or the tool would be advertised and+ never run."""+ return self.name.strip()+def declaration(self) -> Dict[str, Any]:"""The wire form: the handler never crosses the process boundary."""- declaration: Dict[str, Any] = {"name": self.name}+ if not self.declared_name:+ raise TypeError("a host tool needs a name")+ declaration: Dict[str, Any] = {"name": self.declared_name}if self.description is not None:declaration["description"] = self.descriptionif self.parameters is not None:@@ -146,6 +155,14 @@ class JanSession:self._calls: Dict[str, threading.Event] = {}self._late: "OrderedDict[str, TurnResult]" = OrderedDict()self._closed = False+ #: Why the runtime failed this session, once it has: a turn started as it+ #: failed would never hear a terminal record.+ self._failure: Optional[BaseException] = None+ #: One tool or fork change of this session at a time: the runtime clones+ #: the tools it holds when it reads ``session/fork``, so a replacement+ #: that lands between that read and the handlers being copied would+ #: leave the fork advertising a tool nothing here can run.+ self._mutations = threading.RLock()# -- the surface ------------------------------------------------------@@ -198,14 +215,15 @@ class JanSession: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+ with self._mutations:+ 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 viewdef set_model(self, model: str) -> str:"""Change the model between turns; refused while a turn is active."""@@ -213,11 +231,13 @@ class JanSession:self.model = currentreturn current- def fork(self, tools: Sequence[HostTool] = ()) -> "JanSession":+ def fork(self, tools: Optional[Sequence[HostTool]] = None) -> "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.+ It answers for the same host tools with the same handlers: the runtime+ copies the declarations, so the handlers have to come with them or the+ model would be offered tools that nothing here can run. ``tools``+ replaces them instead, and ``tools=[]`` drops them."""return self.runtime.fork_session(self.id, tools)@@ -236,7 +256,11 @@ class JanSession:# -- the runtime's own calls ------------------------------------------def _declare(self, tools: Sequence[HostTool]) -> None:- self._tools = {tool.name: tool for tool in tools}+ self._tools = {tool.declared_name: tool for tool in tools}++ def _declarations(self) -> List[HostTool]:+ """The declarations this session answers for, handlers included."""+ return list(self._tools.values())def _deliver(self, tag: str, params: Dict[str, Any]) -> None:event = params.get("event") or {}@@ -271,6 +295,7 @@ class JanSession:turn._finish(record)def _fail(self, error: BaseException) -> None:+ self._failure = errorfor turn in self._turns.values():turn._fail(error)self._turns.clear()@@ -287,11 +312,19 @@ class JanSession:if not create:return Noneturn = JanTurn(self, turn_id)+ # A terminal record the runtime already sent is the turn's outcome,+ # whatever happened to the runtime after it.late = self._late.pop(turn_id, None)- if late is None:- self._turns[turn_id] = turn- else:+ if late is not None:turn._finish(late)+ return turn+ # The runtime failed while ``prompt()`` was still waiting for its reply:+ # the turn it is about to return would never hear a terminal record, so+ # it fails now with the reason the runtime did.+ if self._failure is not None:+ turn._fail(self._failure)+ return turn+ self._turns[turn_id] = turnreturn turndef _emit(self, kind: str, event: Dict[str, Any]) -> None:@@ -333,11 +366,14 @@ class JanSession:)returntry:- result = tool.handler(event.get("args"), call)+ response = normalize_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))+ # A handler that raised and a result that could not be shaped -+ # an image file that is gone, a malformed part - are answered+ # alike: the model is told, and the turn goes on rather than+ # waiting on a call this client failed to answer.+ response = {"content": describe_error(error), "isError": True}+ self._respond(request_id, response)threading.Thread(target=run, name=f"jan-tool-{call.tool_name}", daemon=True).start()@@ -352,11 +388,36 @@ class JanSession: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+ except Exception as error: # noqa: BLE001 - classified below+ # The runtime is still waiting on this request unless it is gone, so a+ # failure to deliver the answer is itself answered, as a failed call.+ # That covers the runtime refusing what the result carried (an+ # unsupported part, an image over the caps) and the result failing to+ # encode here before anything was sent (a Path, a circular reference,+ # nesting past the recursion limit): which of them it was does not+ # change what the model needs.+ if not self._request_is_gone(error) and not flag.is_set():+ why = "the runtime refused this tool result" if isinstance(error, JanRpcError) else "the tool result could not be encoded"+ try:+ self.runtime.request(+ "tool/respond",+ {"requestId": request_id, "content": f"{why}: {describe_error(error)}", "isError": True},+ )+ except Exception: # noqa: BLE001 - nothing left to tell+ pass+ finally:+ self._calls.pop(request_id, None)++ @staticmethod+ def _request_is_gone(error: BaseException) -> bool:+ """Whether a failed ``tool/respond`` means the request is no longer waiting+ on the runtime: the channel is gone, or the runtime says nothing is+ pending. Any other failure leaves it waiting."""+ if isinstance(error, JanRuntimeError):+ return True+ return isinstance(error, JanRpcError) and isinstance(error.data, dict) and error.data.get("kind") == "not_pending"def _abort(self, error: BaseException) -> None:for flag in self._calls.values():@@ -365,17 +426,19 @@ class JanSession: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."""+ """``turn/start`` takes the text, or the content parts as a bare list. A+ ``{text}`` or ``{content}`` record is unwrapped to one of those; the+ stream-json ``{"type": "user", "content": ...}`` envelope is not what this+ verb parses, and the runtime refuses it."""if isinstance(content, str):return contentif isinstance(content, list):- return {"type": "user", "content": content}+ return contentif isinstance(content, dict):if isinstance(content.get("text"), str):return content["text"]if isinstance(content.get("content"), list):- return {"type": "user", "content": content["content"]}+ return content["content"]raise TypeError("prompt() takes a string, content parts, or a {text} / {content} record")diff --git a/adk/python/tests/test_adk.py b/adk/python/tests/test_adk.pyindex feda204bd..66c4a8c36 100644--- a/adk/python/tests/test_adk.py+++ b/adk/python/tests/test_adk.py@@ -463,6 +463,352 @@ class AdkTest(unittest.TestCase):with self.assertRaises(JanRuntimeError):turn.result(timeout=5)+ # -- host tools, inputs, forks and resumes --------------------------------++ def _echo(self, calls: list, label: str) -> HostTool:+ def handler(args: Any, call: Any) -> Dict[str, str]:+ calls.append(label)+ return {"text": f"echoed by {label}: {args['text']}"}++ return HostTool(name="echo", capability="read", handler=handler)++ def _last_user(self, body: str) -> Dict[str, Any]:+ return [message for message in json.loads(body)["messages"] if message["role"] == "user"][-1]++ def test_a_host_tool_declared_with_a_padded_name_is_still_called(self) -> None:+ scratch = self.prepare([tool_call("host__camera", {}), prose("seen")])+ calls: list[str] = []+ 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 ", capability="read", handler=lambda args, call: (calls.append("camera") or {"text": "CAMERA_RESULT"}))],+ )+ self.assertEqual(session.tools, ["host__camera"])++ turn = session.prompt("look")+ turn.result(timeout=4)+ # Advertised means callable: the handler ran, and the model got its+ # answer rather than "no host tool named".+ self.assertEqual(calls, ["camera"])+ self.assertIn("CAMERA_RESULT", self.provider.bodies[1])+ self.assertNotIn("no host tool named", self.provider.bodies[1])++ with self.assertRaises(TypeError):+ session.set_tools([HostTool(name=" ", handler=lambda args, call: "")])++ def test_a_host_result_that_cannot_be_shaped_is_answered_as_an_error_and_the_turn_goes_on(self) -> None:+ scratch = self.prepare([tool_call("host__camera_observe", {}), prose("no frame")])+ 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",+ capability="read",+ # The handler succeeds; formatting its result is what fails.+ handler=lambda args, call: {"text": "a frame", "images": [{"path": str(scratch.root / "missing-image.png")}]},+ )+ ],+ )+ turn = session.prompt("look")+ self.assertEqual(turn.result(timeout=4).stop_reason, "completed")+ self.assertEqual(len(self.provider.bodies), 2, "the model was told, so it was asked again")+ self.assertRegex(self.provider.bodies[1], r"(?i)no such file")++ # The session is still usable afterwards.+ again = session.prompt("and now?")+ self.assertEqual(again.result(timeout=4).stop_reason, "completed")++ def test_structured_prompt_inputs_reach_the_model_as_content_parts(self) -> None:+ scratch = self.prepare([prose("seen")])+ png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8AARAAB/wDcH1jPAAAAAElFTkSuQmCC"+ with scratch.start() as runtime:+ session = runtime.create_session(cwd=scratch.project, model="stub-model", ephemeral=True)++ session.prompt([{"type": "text", "text": "hello parts"}]).result(timeout=4)+ self.assertIn("hello parts", json.dumps(self._last_user(self.provider.bodies[0])["content"]))++ image = {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{png}"}}+ session.prompt([{"type": "text", "text": "what is this?"}, image]).result(timeout=4)+ mixed = self._last_user(self.provider.bodies[1])["content"]+ self.assertIsInstance(mixed, list)+ self.assertIn("what is this?", next(p for p in mixed if p["type"] == "text")["text"])+ self.assertEqual(next(p for p in mixed if p["type"] == "image_url")["image_url"]["url"], image["image_url"]["url"])++ # The documented record form is the same parts.+ session.prompt({"content": [{"type": "text", "text": "record form"}]}).result(timeout=4)+ self.assertIn("record form", json.dumps(self._last_user(self.provider.bodies[2])["content"]))++ # A refusal from the runtime stays an answer the caller can read.+ with self.assertRaises(JanRpcError):+ session.prompt([{"type": "audio", "data": "x"}])++ def test_a_fork_answers_for_its_sources_host_tools(self) -> None:+ scratch = self.prepare([tool_call("host__echo", {"text": "hi"}), prose("done")])+ calls: list[str] = []+ with scratch.start() as runtime:+ session = runtime.create_session(+ cwd=scratch.project,+ model="stub-model",+ ephemeral=True,+ builtins=False,+ permissions="host",+ tools=[self._echo(calls, "source")],+ )+ fork = session.fork()+ self.assertEqual(fork.tools, ["host__echo"])++ fork.prompt("echo hi").result(timeout=4)+ self.assertEqual(calls, ["source"])+ self.assertIn("echoed by source: hi", self.provider.bodies[1])+ self.assertNotIn("no host tool named", self.provider.bodies[1])++ def test_a_fork_given_its_own_tools_answers_with_those_and_one_given_none_has_none(self) -> None:+ scratch = self.prepare([tool_call("host__echo", {"text": "hi"}), prose("done")])+ calls: list[str] = []+ with scratch.start() as runtime:+ session = runtime.create_session(+ cwd=scratch.project,+ model="stub-model",+ ephemeral=True,+ builtins=False,+ permissions="host",+ tools=[self._echo(calls, "source")],+ )+ bare = session.fork(tools=[])+ self.assertEqual(bare.tools, [], "nothing is advertised that nothing can run")++ own = session.fork(tools=[self._echo(calls, "fork")])+ own.prompt("echo hi").result(timeout=4)+ self.assertEqual(calls, ["fork"], "the source's handler is not used by a fork that replaced it")+ self.assertIn("echoed by fork: hi", self.provider.bodies[1])++ def test_resuming_an_open_session_returns_it_and_its_turn_settles(self) -> None:+ scratch = self.prepare([holding("still here")])+ with scratch.start() as runtime:+ original = runtime.create_session(cwd=scratch.project, model="stub-model", ephemeral=True)+ turn = original.prompt("hold")+ for event in turn:+ if event["type"] == "token":+ break++ resumed = runtime.resume_session(original.id)+ self.assertIs(resumed, original, "the session this client already holds, not a second object for the id")++ resumed.interrupt()+ self.assertEqual(turn.result(timeout=4).stop_reason, "interrupted")++ def test_resuming_an_open_session_does_not_orphan_its_turn_when_the_runtime_closes(self) -> None:+ scratch = self.prepare([holding("still here")])+ runtime = scratch.start()+ original = runtime.create_session(cwd=scratch.project, model="stub-model", ephemeral=True)+ turn = original.prompt("hold")+ for event in turn:+ if event["type"] == "token":+ break+ runtime.resume_session(original.id)++ runtime.close()+ # The runtime's own failure, not `result()` giving up on a turn that was+ # never settled: that is also a JanRuntimeError, so the message tells+ # the two apart.+ with self.assertRaises(JanRuntimeError) as failed:+ turn.result(timeout=4)+ self.assertNotIn("did not finish", str(failed.exception))++ def test_a_resumed_session_keeps_the_handlers_of_its_host_tools(self) -> None:+ scratch = self.prepare([tool_call("host__echo", {"text": "hi"}), prose("done")])+ calls: list[str] = []+ with scratch.start() as runtime:+ session = runtime.create_session(+ cwd=scratch.project,+ model="stub-model",+ ephemeral=True,+ builtins=False,+ permissions="host",+ tools=[self._echo(calls, "source")],+ )+ resumed = runtime.resume_session(session.id)+ resumed.prompt("echo hi").result(timeout=4)+ self.assertEqual(calls, ["source"])+ self.assertIn("echoed by source: hi", self.provider.bodies[1])++ def test_a_tool_result_the_runtime_refuses_is_answered_as_an_error_and_the_turn_goes_on(self) -> None:+ scratch = self.prepare([tool_call("host__camera", {}), prose("no frame")])+ with scratch.start() as runtime:+ session = runtime.create_session(+ cwd=scratch.project,+ model="stub-model",+ ephemeral=True,+ builtins=False,+ permissions="host",+ # Shapes cleanly here, and the runtime refuses the part: the+ # request is still pending on its side, so a swallowed refusal+ # parks the turn.+ tools=[HostTool(name="camera", capability="read", handler=lambda args, call: {"parts": [{"type": "audio", "data": "x"}]})],+ )+ turn = session.prompt("look")+ self.assertEqual(turn.result(timeout=4).stop_reason, "completed")+ self.assertEqual(len(self.provider.bodies), 2, "the model was told, so it was asked again")+ self.assertIn("refused this tool result", self.provider.bodies[1])++ def _fork_with_a_tools_change(self, change_first: bool) -> None:+ import threading++ scratch = self.prepare([tool_call("host__echo", {"text": "hi"}), prose("done")])+ calls: list[str] = []+ with scratch.start() as runtime:+ session = runtime.create_session(+ cwd=scratch.project,+ model="stub-model",+ ephemeral=True,+ builtins=False,+ permissions="host",+ tools=[self._echo(calls, "a")],+ )+ made: list = []+ request = runtime.request++ # The first call holds on after the runtime has answered it, so the+ # second starts inside the window between the runtime's read and the+ # SDK's: the order is the test's, not the scheduler's.+ held = "session/tools/set" if change_first else "session/fork"++ def slow(method, params=None, timeout=None):+ answer = request(method, params, timeout)+ if method == held:+ time.sleep(0.4)+ return answer++ runtime.request = slow+ change = threading.Thread(target=lambda: session.set_tools([self._echo(calls, "b")]))+ fork = threading.Thread(target=lambda: made.append(session.fork()))+ first, second = (change, fork) if change_first else (fork, change)+ first.start()+ time.sleep(0.1)+ second.start()+ first.join(10)+ second.join(10)+ expected = "b" if change_first else "a"+ self.assertEqual(made[0].tools, ["host__echo"])+ made[0].prompt("echo hi").result(timeout=4)+ self.assertEqual(calls, [expected], "the fork ran the handler for the tools the runtime gave it")+ self.assertIn(f"echoed by {expected}: hi", self.provider.bodies[1])++ def test_a_fork_made_with_a_tools_change_keeps_matching_handlers_fork_first(self) -> None:+ self._fork_with_a_tools_change(change_first=False)++ def test_a_fork_made_with_a_tools_change_keeps_matching_handlers_change_first(self) -> None:+ self._fork_with_a_tools_change(change_first=True)++ def test_a_turn_started_as_the_runtime_fails_is_failed_not_left_pending(self) -> None:+ scratch = self.prepare([prose("hi")])+ with scratch.start() as runtime:+ session = runtime.create_session(cwd=scratch.project, model="stub-model", ephemeral=True)+ request = runtime.request++ # The runtime fails between the `turn/start` reply and `prompt()`+ # resuming with it.+ def request_then_fail(method, params=None, timeout=None):+ answer = request(method, params, timeout)+ if method == "turn/start":+ runtime._fail(JanRuntimeError("QA_FAILS_FIRST"))+ return answer++ runtime.request = request_then_fail+ turn = session.prompt("hi")+ with self.assertRaises(JanRuntimeError) as failed:+ turn.result(timeout=4)+ self.assertIn("QA_FAILS_FIRST", str(failed.exception))++ def test_a_terminal_record_already_received_wins_over_a_runtime_failure(self) -> None:+ scratch = self.prepare([prose("hi")])+ with scratch.start() as runtime:+ session = runtime.create_session(cwd=scratch.project, model="stub-model", ephemeral=True)+ request = runtime.request++ # The runtime sent the turn's terminal record, and then failed, before+ # `prompt()` resumed with the reply.+ def answered_then_closed(method, params=None, timeout=None):+ answer = request(method, params, timeout)+ if method == "turn/start":+ session._complete({"turnId": answer["turnId"], "stopReason": "interrupted"})+ runtime._fail(JanRuntimeError("QA_CLOSED_AFTER"))+ return answer++ runtime.request = answered_then_closed+ self.assertEqual(session.prompt("hi").result(timeout=4).stop_reason, "interrupted")++ def test_a_handler_that_raises_an_unprintable_error_is_still_answered(self) -> None:+ class Unprintable(Exception):+ def __str__(self) -> str:+ raise ValueError("no text for this")++ def handler(args: Any, call: Any) -> None:+ raise Unprintable()++ scratch = self.prepare([tool_call("host__camera", {}), prose("no frame")])+ 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", capability="read", handler=handler)],+ )+ self.assertEqual(session.prompt("look").result(timeout=4).stop_reason, "completed")+ self.assertIn("Unprintable", self.provider.bodies[1])++ def test_a_tool_result_that_cannot_be_encoded_is_answered_as_an_error_and_the_turn_goes_on(self) -> None:+ from pathlib import Path++ scratch = self.prepare([tool_call("host__camera", {}), prose("no frame")])+ with scratch.start() as runtime:+ session = runtime.create_session(+ cwd=scratch.project,+ model="stub-model",+ ephemeral=True,+ builtins=False,+ permissions="host",+ # Shapes cleanly, and cannot be written as JSON: nothing reaches+ # the runtime, which is still waiting on the request.+ tools=[HostTool(name="camera", capability="read", handler=lambda args, call: {"text": "ok", "details": {"path": Path("/tmp/frame.png")}})],+ )+ turn = session.prompt("look")+ self.assertEqual(turn.result(timeout=4).stop_reason, "completed")+ self.assertEqual(len(self.provider.bodies), 2, "the model was told, so it was asked again")+ self.assertIn("could not be encoded", self.provider.bodies[1])++ def test_a_tool_result_whose_encoding_raises_another_error_is_answered_as_an_error(self) -> None:+ class Unencodable(dict):+ def items(self): # the JSON encoder reads a dict subclass through this+ raise RuntimeError("no items for you")++ scratch = self.prepare([tool_call("host__camera", {}), prose("no frame")])+ with scratch.start() as runtime:+ session = runtime.create_session(+ cwd=scratch.project,+ model="stub-model",+ ephemeral=True,+ builtins=False,+ permissions="host",+ # Encoding this raises a RuntimeError, which is neither a TypeError+ # nor a ValueError, on every Python version: any failure to send the+ # answer is itself answered.+ tools=[HostTool(name="camera", capability="read", handler=lambda args, call: {"text": "ok", "details": {"value": Unencodable(a=1)}})],+ )+ self.assertEqual(session.prompt("look").result(timeout=4).stop_reason, "completed")+ self.assertIn("could not be encoded: no items for you", self.provider.bodies[1])+def _tmp(self) -> str:import tempfilediff --git a/packages/adk/README.md b/packages/adk/README.mdindex 907d72c81..5aa2a8c58 100644--- a/packages/adk/README.md+++ b/packages/adk/README.md@@ -208,6 +208,19 @@ the cap by being rejected. `JanRpcError` is an answer (`code`, `retryable`), and`JanRuntimeError` is the channel (spawn failure, protocol mismatch, exit), withthe runtime's own stderr attached.+A session's host tools follow it. `fork()` answers for the source's tools with+the same handlers (`fork({ tools })` replaces them, `fork({ tools: [] })` drops+them), and `resumeSession(id)` returns the session this client already holds,+with its turns, listeners and handlers, rather than a second object for the+same id. A host tool's name is trimmed, as the runtime trims it.++Listeners registered with `session.on(...)` and `runtime.on(...)` run on the+client's reader. One that throws, or returns a promise that rejects, does not+crash your application: it fails the runtime. Every open turn and call settles+with a `JanRuntimeError` (its `cause` is what the listener raised) and the+process is stopped, so a listener that was answering permission requests cannot+leave a turn parked behind it.+## Types`src/index.d.ts` is the public surface. `src/generated/rpc-types.d.ts` isdiff --git a/packages/adk/src/index.d.ts b/packages/adk/src/index.d.tsindex c416d4f7c..90de54d47 100644--- a/packages/adk/src/index.d.ts+++ b/packages/adk/src/index.d.ts@@ -83,6 +83,8 @@ export declare class JanRpcError extends Error {/** The runtime process failed: spawn, handshake, protocol version, or exit. */export declare class JanRuntimeError extends Error {+ /** What a listener raised, when this error is the runtime failing on it. */+ cause?: unknownexitCode?: number | nullsignal?: string | nullstderr?: string@@ -223,7 +225,9 @@ export declare class JanSession {readonly maxBufferedEvents: number/** Observe the session's events: `'event'` for the stream, `'*'` for* everything the session reports, or one event tag (`'token'`,- * `'tool_request'`, `'permission_request'`, ...). */+ * `'tool_request'`, `'permission_request'`, ...). A listener that throws, or+ * returns a promise that rejects, fails the runtime: open turns settle with a+ * `JanRuntimeError` whose `cause` is what it raised. */on(kind: EventTag | 'event' | '*', listener: (event: StreamEvent) => void): () => voidprompt(input: string | unknown[] | { text: string } | { content: unknown[] }): Promise<JanTurn>steer(input: string | { text: string }): Promise<null>@@ -232,6 +236,9 @@ export declare class JanSession {getTools(): Promise<ToolSetView>setTools(tools: HostTool[]): Promise<ToolSetView>setModel(model: string): Promise<string>+ /** A new session with this one's history. Without `tools` it answers for the+ * source's host tools with the same handlers; `tools` replaces them, and+ * `[]` drops them. */fork(options?: { tools?: HostTool[] }): Promise<JanSession>archive(): Promise<void>respondPermission(requestId: string, decision: PermissionDecision): Promise<null>@@ -252,7 +259,10 @@ export declare class JanRuntime {on(kind: 'exit' | 'event' | 'notification', listener: (payload: unknown) => void): () => voidcreateSession(options?: CreateSessionOptions): Promise<JanSession>listSessions(): Promise<SessionSummary[]>+ /** A session this client already holds is returned as it is, with its turns,+ * listeners and handlers; the runtime only knows this process's sessions. */resumeSession(sessionId: string): Promise<JanSession>+ /** As `JanSession.fork`. */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/adk/src/index.js b/packages/adk/src/index.jsindex 8341ba5a6..d8ce3651f 100644--- a/packages/adk/src/index.js+++ b/packages/adk/src/index.js@@ -75,8 +75,8 @@ export class JanRpcError extends Error {// 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)+ constructor(message, { exitCode, signal, stderr, cause } = {}) {+ super(message, cause === undefined ? undefined : { cause })this.name = 'JanRuntimeError'this.exitCode = exitCodethis.signal = signal@@ -238,6 +238,11 @@ export class JanSession {#calls = new Map();#late = new Map();#closed = false;+ // Why the runtime failed this session, once it has: nothing it was still+ // delivering may start a turn that no one will ever settle.+ #failure = null;+ // The tail of the session's tool and fork changes, which run one at a time.+ #mutations = Promise.resolve();// Every event the session reports, including the ones raised by a subagent,// which arrive wrapped in a `subagent` event.@@ -294,14 +299,31 @@ export class JanSession {// 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),+ // One at a time with a fork of this session: the runtime clones the tools it+ // holds when it reads `session/fork`, so a replacement that lands between+ // that read and the handlers being copied would leave the fork advertising a+ // tool nothing here can run.+ return this._exclusive(async () => {+ 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})- this._declare(tools)- this.tools = view.tools- this.toolSpecs = view.toolSpecs- return view+ }++ // Run `work` after every earlier tool or fork change of this session has+ // finished, whether it succeeded or not.+ _exclusive(work) {+ const run = this.#mutations.then(work, work)+ this.#mutations = run.then(+ () => {},+ () => {},+ )+ return run}// Change the model between turns. Refused while a turn is active.@@ -314,10 +336,12 @@ export class JanSession {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 = [] } = {}) {+ // A new session with this one's history, addressable on its own. It answers+ // for the same host tools with the same handlers - the runtime copies the+ // declarations, so the handlers have to come with them or the model would be+ // offered tools that nothing here can run. `fork({ tools })` replaces them+ // instead, and `fork({ tools: [] })` drops them.+ fork({ tools } = {}) {return this.runtime.forkSession(this.id, { tools })}@@ -339,17 +363,28 @@ export class JanSession {}// Attach the handlers a session's declarations carry. Called by the runtime- // when the session is created, and by `setTools` when they are replaced.+ // when the session is created, and by `setTools` when they are replaced. The+ // runtime trims a declared name, so it is keyed trimmed here: the host is+ // told the name the runtime holds._declare(tools) {- this.#decls = new Map(tools.map((tool) => [tool.name, tool]))+ this.#decls = new Map(tools.map((tool) => [tool.name.trim(), tool]))+ }++ // The declarations this session answers for, handlers included.+ _declarations() {+ return [...this.#decls.values()]}// Called by the runtime on every frame addressed to this session._deliver(tag, { turnId, event }) {this.#emit('event', event)+ if (this.#failure) return// By tag as well, so `on('tool_request')` and `on('permission_request')`// hear what they were told they would.this.#notify(tag, event)+ // A listener that raised has failed the runtime, and this session with it+ // (see `JanRuntime._callListener`): no turn is left to push to.+ if (this.#failure) returnconst turn = this.#turn(turnId, true)turn?._push(event)if (tag === 'tool_request') this.#answer(event)@@ -374,6 +409,7 @@ export class JanSession {// The runtime is gone: every open turn fails rather than hangs._fail(error) {+ this.#failure = errorfor (const turn of this.#turns.values()) turn._fail(error)this.#turns.clear()this.#abort(error)@@ -385,13 +421,22 @@ export class JanSession {if (existing) return existingif (!create) return nullconst turn = new JanTurn(this, turnId)- this.#turns.set(turnId, turn)+ // A terminal record the runtime already sent is the turn's outcome, whatever+ // happened to the runtime after it.const late = this.#late.get(turnId)if (late) {this.#late.delete(turnId)- this.#turns.delete(turnId)turn._finish(late)+ return turn+ }+ // The runtime failed while `prompt()` was still waiting for its reply: the+ // turn it is about to return would never hear a terminal record, so it fails+ // now with the reason the runtime did.+ if (this.#failure) {+ turn._fail(this.#failure)+ return turn}+ this.#turns.set(turnId, turn)return turn}@@ -405,7 +450,7 @@ export class JanSession {// Without the `'*'` fan-out, for a second tag on an event already emitted:// a tag listener hears it, and `'*'` does not hear it twice.#notify(kind, event) {- for (const listener of this.#listeners.get(kind) ?? []) listener(event)+ for (const listener of this.#listeners.get(kind) ?? []) this.runtime._callListener(listener, event)}// A host tool was called. The handler runs without holding the reader: two@@ -425,23 +470,27 @@ export class JanSession {})return}- let result+ let responsetry {- result = await declaration.handler(event.args, {+ const result = await declaration.handler(event.args, {requestId: event.request_id,toolName: event.tool_name,runId: event.run_id ?? null,session: this,signal: controller.signal,})+ response = await normalizeResult(result)} catch (error) {- await this.#respond(event.request_id, {- content: error instanceof Error ? error.message : String(error),+ // A handler that threw and a result that could not be shaped - an+ // image file that is gone, a malformed part - are answered alike: the+ // model is told, and the turn goes on rather than waiting on a call+ // this client failed to answer.+ response = {+ content: describeError(error),isError: true,- })- return+ }}- await this.#respond(event.request_id, await normalizeResult(result))+ await this.#respond(event.request_id, response)}answer().catch(() => {})}@@ -459,12 +508,24 @@ export class JanSession {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.+ } catch (error) {+ // The runtime is still waiting on this request unless it is gone, so a+ // failure to deliver the answer is itself answered, as a failed call. That+ // covers the runtime refusing what the result carried (an unsupported+ // part, an image over the caps) and the result failing to encode here+ // before anything was sent (a BigInt, a circular reference, a `toJSON`+ // that throws): which of them it was does not change what the model needs.+ if (!requestIsGone(error) && !controller.signal.aborted) {+ const why =+ error instanceof JanRpcError ? 'the runtime refused this tool result' : 'the tool result could not be encoded'+ await this.runtime+ .request('tool/respond', { requestId, content: `${why}: ${describeError(error)}`, isError: true })+ .catch(() => {})+ }+ } finally {+ this.#calls.delete(requestId)}}@@ -638,23 +699,40 @@ export class JanRuntime {return sessions}- // Reopen a session of this process from its id. Host tools are not- // inherited: re-declare them with `session.setTools`.+ // Reopen a session of this process from its id. A session this client already+ // holds is returned as it is, not rebuilt: it keeps its turns, listeners,+ // host tool handlers and pending calls, so work in flight settles on the+ // object the caller already has. The runtime only knows the sessions this+ // process created, so an id this client has not seen is not expected; one+ // that does arrive is attached without handlers.async resumeSession(sessionId) {- return this.#session(await this.request('session/resume', { sessionId }))+ const view = await this.request('session/resume', { sessionId })+ const known = this.#sessions.get(sessionId)+ if (known) {+ known.model = view.model ?? known.model+ return known+ }+ return this.#session(view)}- // A new session with another session's history.- async forkSession(sessionId, { tools = [] } = {}) {+ // A new session with another session's history. Without `tools` it takes the+ // source's host tools and handlers; with them, those replace the set. It runs+ // after the source's pending tool changes and before later ones, so the+ // runtime clones the same tools whose handlers are copied here.+ 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+ const work = async () => {+ 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 !== undefined) await session.setTools(tools)+ else if (source) session._declare(source._declarations())+ return session+ }+ return source ? source._exclusive(work) : work()}// One JSON-RPC request, answered or refused. The escape hatch for a verb@@ -759,6 +837,36 @@ export class JanRuntime {this.#sessions.delete(session.id)}+ // Run one listener. A listener that throws, or returns a promise that+ // rejects, fails the runtime: every open turn and call settles with a+ // `JanRuntimeError` naming the cause (`error.cause`), and the process is+ // stopped. The embedding application is not crashed by it, and it is not+ // left with a runtime that silently stopped delivering to a listener that+ // may have been the one answering a permission request.+ _callListener(listener, payload) {+ try {+ const returned = listener(payload)+ if (returned && typeof returned.then === 'function') {+ returned.then(undefined, (error) => this.#listenerFailed(error))+ }+ } catch (error) {+ this.#listenerFailed(error)+ }+ }++ #listenerFailed(error) {+ // Already failed or exited: the host has been told, and one more+ // listener's complaint changes nothing.+ if (this.#failure) return+ this.#fail(+ new JanRuntimeError(`an event listener raised: ${describeError(error)}`, {+ stderr: this.#stderr,+ cause: error,+ }),+ )+ this.close({ force: true }).catch(() => {})+ }+// The runtime's own frame, routed. Everything that is not an answer or a// session event ends up on the `notification` listener.#onLine(line) {@@ -816,7 +924,7 @@ export class JanRuntime {}#emit(kind, payload) {- for (const listener of this.#listeners.get(kind) ?? []) listener(payload)+ for (const listener of this.#listeners.get(kind) ?? []) this._callListener(listener, payload)}#fail(error) {@@ -832,29 +940,52 @@ export class JanRuntime {}}+// Whether a failed `tool/respond` means the request is no longer waiting on the+// runtime: the channel is gone, or the runtime says nothing is pending. Any+// other failure leaves it waiting.+function requestIsGone(error) {+ if (error instanceof JanRuntimeError) return true+ return error instanceof JanRpcError && error.data?.kind === 'not_pending'+}++// What a handler or listener threw, as text. Anything can be thrown, and reading+// or converting it can throw too (an object with no prototype, a throwing+// `toString`, an Error whose `message` getter throws or whose `message` is not+// text): none of that may stop the failure being reported.+function describeError(error) {+ try {+ return String(error instanceof Error ? error.message : error)+ } catch {+ return 'a thrown value that cannot be converted to text'+ }+}+// 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 name !== 'string' || !name.trim()) 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 }+ // Trimmed, as the runtime trims it: the handler is found by the name the+ // runtime reports, so an untrimmed key would advertise a tool nothing can run.+ const declaration = { name: name.trim() }if (description !== undefined) declaration.description = descriptionif (parameters !== undefined) declaration.parameters = parametersif (capability !== undefined) declaration.capability = capabilityreturn 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.+// `turn/start` takes the text, or the content parts as a bare array. A+// `{ text }` or `{ content }` record is unwrapped to one of those; the+// stream-json `{ type: 'user', content }` envelope is not what this verb+// parses, and the runtime refuses it.function normalizeInput(input) {if (typeof input === 'string') return input- if (Array.isArray(input)) return { type: 'user', content: input }+ if (Array.isArray(input)) return inputif (input && typeof input === 'object') {if (typeof input.text === 'string') return input.text- if (Array.isArray(input.content)) return { type: 'user', content: input.content }+ if (Array.isArray(input.content)) return input.content}throw new TypeError('prompt() takes a string, content parts, or a { text } / { content } record')}diff --git a/packages/adk/tests/adk.test.mjs b/packages/adk/tests/adk.test.mjsindex 000c69cac..301f49ed7 100644--- a/packages/adk/tests/adk.test.mjs+++ b/packages/adk/tests/adk.test.mjs@@ -698,3 +698,433 @@ test('a request with no runtime behind it is refused, not hung', { skip: missing(error) => error.name === 'JanRpcError',)})++// A test that waits on a turn must fail, not hang the runner, when the bug it+// pins is "the turn never settles".+const within = (promise, ms = 4000) =>+ Promise.race([+ promise,+ new Promise((_, reject) => setTimeout(() => reject(new Error(`still pending after ${ms}ms`)), ms).unref()),+ ])++// A 1x1 PNG, small enough to inline and a valid payload for the runtime.+const PNG = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8AARAAB/wDcH1jPAAAAAElFTkSuQmCC'++const lastUser = (body) => JSON.parse(body).messages.findLast((message) => message.role === 'user')++test('a host tool declared with a padded name is still called', { skip: missingRuntime }, async (t) => {+ const calls = []+ const { provider, scratch, runtime } = await connect(t, {+ replies: [TOOL_CALL('host__camera', {}), PROSE('seen')],+ })+ const session = await runtime.createSession({+ cwd: scratch.projectPath,+ model: 'stub-model',+ ephemeral: true,+ builtins: false,+ permissions: 'host',+ tools: [{ name: ' camera ', capability: 'read', handler: () => (calls.push('camera'), { text: 'CAMERA_RESULT' }) }],+ })+ assert.deepEqual(session.tools, ['host__camera'])++ const turn = await session.prompt('look')+ await within(turn.result())+ // Advertised means callable: the handler ran, and the model got its answer+ // rather than "no host tool named".+ assert.deepEqual(calls, ['camera'])+ assert.match(provider.bodies[1], /CAMERA_RESULT/)+ assert.doesNotMatch(provider.bodies[1], /no host tool named/)++ await assert.rejects(session.setTools([{ name: ' ', handler: () => '' }]), TypeError)+})++test('a host result that cannot be shaped is answered as an error, and the turn goes on', { skip: missingRuntime }, async (t) => {+ const { provider, scratch, runtime } = await connect(t, {+ replies: [TOOL_CALL('host__camera_observe', {}), PROSE('no frame')],+ })+ const session = await runtime.createSession({+ cwd: scratch.projectPath,+ model: 'stub-model',+ ephemeral: true,+ builtins: false,+ permissions: 'host',+ tools: [+ {+ name: 'camera_observe',+ capability: 'read',+ // The handler succeeds; formatting its result is what fails.+ handler: () => ({ text: 'a frame', images: [{ path: join(scratch.root, 'missing-image.png') }] }),+ },+ ],+ })++ const turn = await session.prompt('look')+ const result = await within(turn.result())+ assert.equal(result.stopReason, 'completed')+ assert.equal(provider.bodies.length, 2, 'the model was told, so it was asked again')+ assert.match(provider.bodies[1], /ENOENT|no such file/i)++ // The session is still usable afterwards.+ const again = await session.prompt('and now?')+ assert.equal((await within(again.result())).stopReason, 'completed')+})++test('structured prompt inputs reach the model as content parts', { skip: missingRuntime }, async (t) => {+ const { provider, scratch, runtime } = await connect(t, { replies: [PROSE('seen')] })+ const session = await runtime.createSession({ cwd: scratch.projectPath, model: 'stub-model', ephemeral: true })++ await within((await session.prompt([{ type: 'text', text: 'hello parts' }])).result())+ assert.match(JSON.stringify(lastUser(provider.bodies[0]).content), /hello parts/)++ const image = { type: 'image_url', image_url: { url: `data:image/png;base64,${PNG}` } }+ await within((await session.prompt([{ type: 'text', text: 'what is this?' }, image])).result())+ const mixed = lastUser(provider.bodies[1]).content+ assert.ok(Array.isArray(mixed))+ assert.match(mixed.find((part) => part.type === 'text').text, /what is this\?/)+ assert.equal(mixed.find((part) => part.type === 'image_url').image_url.url, image.image_url.url)++ // The documented record form is the same parts.+ await within((await session.prompt({ content: [{ type: 'text', text: 'record form' }] })).result())+ assert.match(JSON.stringify(lastUser(provider.bodies[2]).content), /record form/)++ // A refusal from the runtime stays an answer the caller can read.+ await assert.rejects(session.prompt([{ type: 'audio', data: 'x' }]), (error) => error.name === 'JanRpcError')+})++const echoTool = (calls, label) => ({+ name: 'echo',+ capability: 'read',+ handler: (args) => {+ calls.push(label)+ return { text: `echoed by ${label}: ${args.text}` }+ },+})++test('a fork answers for its source’s host tools', { skip: missingRuntime }, async (t) => {+ const calls = []+ const { provider, scratch, runtime } = await connect(t, {+ replies: [TOOL_CALL('host__echo', { text: 'hi' }), PROSE('done')],+ })+ const session = await runtime.createSession({+ cwd: scratch.projectPath,+ model: 'stub-model',+ ephemeral: true,+ builtins: false,+ permissions: 'host',+ tools: [echoTool(calls, 'source')],+ })+ const fork = await session.fork()+ assert.deepEqual(fork.tools, ['host__echo'])++ await within((await fork.prompt('echo hi')).result())+ assert.deepEqual(calls, ['source'])+ assert.match(provider.bodies[1], /echoed by source: hi/)+ assert.doesNotMatch(provider.bodies[1], /no host tool named/)+})++test('a fork given its own tools answers with those, and one given none has none', { skip: missingRuntime }, async (t) => {+ const calls = []+ const { provider, scratch, runtime } = await connect(t, {+ replies: [TOOL_CALL('host__echo', { text: 'hi' }), PROSE('done')],+ })+ const session = await runtime.createSession({+ cwd: scratch.projectPath,+ model: 'stub-model',+ ephemeral: true,+ builtins: false,+ permissions: 'host',+ tools: [echoTool(calls, 'source')],+ })++ const bare = await session.fork({ tools: [] })+ assert.deepEqual(bare.tools, [], 'nothing is advertised that nothing can run')++ const own = await session.fork({ tools: [echoTool(calls, 'fork')] })+ await within((await own.prompt('echo hi')).result())+ assert.deepEqual(calls, ['fork'], 'the source’s handler is not used by a fork that replaced it')+ assert.match(provider.bodies[1], /echoed by fork: hi/)+})++test('resuming an open session returns it, and its turn settles', { skip: missingRuntime }, async (t) => {+ const { scratch, runtime } = await connect(t, { replies: [(response) => response.write(HOLDING('still here'))] })+ const original = await runtime.createSession({ cwd: scratch.projectPath, model: 'stub-model', ephemeral: true })+ const turn = await original.prompt('hold')+ for await (const event of turn) if (event.type === 'token') break++ const resumed = await runtime.resumeSession(original.id)+ assert.equal(resumed, original, 'the session this client already holds, not a second object for the id')++ await resumed.interrupt()+ const result = await within(turn.result())+ assert.equal(result.stopReason, 'interrupted')+})++test('resuming an open session does not orphan its turn when the runtime closes', { skip: missingRuntime }, async (t) => {+ const { scratch, runtime } = await connect(t, { replies: [(response) => response.write(HOLDING('still here'))] })+ const original = await runtime.createSession({ cwd: scratch.projectPath, model: 'stub-model', ephemeral: true })+ const turn = await original.prompt('hold')+ for await (const event of turn) if (event.type === 'token') break+ await runtime.resumeSession(original.id)++ await runtime.close()+ await assert.rejects(within(turn.result()), (error) => error instanceof JanRuntimeError)+})++test('a resumed session keeps the handlers of its host tools', { skip: missingRuntime }, async (t) => {+ const calls = []+ const { provider, scratch, runtime } = await connect(t, {+ replies: [TOOL_CALL('host__echo', { text: 'hi' }), PROSE('done')],+ })+ const session = await runtime.createSession({+ cwd: scratch.projectPath,+ model: 'stub-model',+ ephemeral: true,+ builtins: false,+ permissions: 'host',+ tools: [echoTool(calls, 'source')],+ })+ const resumed = await runtime.resumeSession(session.id)+ await within((await resumed.prompt('echo hi')).result())+ assert.deepEqual(calls, ['source'])+ assert.match(provider.bodies[1], /echoed by source: hi/)+})++// The embedding application must survive a listener that raises, and must not+// be left waiting: the runtime fails, and every open turn settles with an error+// that names the listener's. This runs in its own Node process because the bug+// it pins is the process exiting.+const LISTENER_SCRIPT = `+import { JanRuntime, JanRuntimeError } from ${JSON.stringify(new URL('../src/index.js', import.meta.url).href)}+const mode = process.argv[1]+const runtime = await JanRuntime.start({ bin: process.env.JAN_BIN })+const session = await runtime.createSession({ cwd: process.env.PROJECT, model: 'stub-model', ephemeral: true })+// Anything can be thrown, and reading it can throw: \`-null\` modes throw an+// object with no prototype, \`-getter\` modes an Error whose \`message\` getter+// throws, \`-badmessage\` modes an Error whose \`message\` is such an object.+const thrown = () => {+ if (mode.endsWith('-null')) return Object.create(null)+ if (mode.endsWith('-getter')) {+ return Object.defineProperty(new Error('x'), 'message', { get() { throw new Error('no message for you') } })+ }+ if (mode.endsWith('-badmessage')) return Object.assign(new Error('x'), { message: Object.create(null) })+ return new Error('QA_THROWING_LISTENER')+}+session.on('event', async () => {+ if (mode.startsWith('async')) throw thrown()+})+if (mode.startsWith('sync')) session.on('event', () => { throw thrown() })+const turn = await session.prompt('hello')+const outcome = await turn.result().then(() => 'resolved', (error) => error)+await new Promise((resolve) => setTimeout(resolve, 300))+let alive = true+try { process.kill(runtime.pid, 0) } catch { alive = false }+console.log(JSON.stringify({+ runtimeError: outcome instanceof JanRuntimeError,+ message: outcome?.message,+ cause: (() => {+ const cause = outcome?.cause+ try {+ const text = cause?.message+ if (text && typeof text === 'object') return 'OBJECT_MESSAGE'+ return text ?? (cause && Object.getPrototypeOf(cause) === null ? 'NULL_PROTOTYPE' : undefined)+ } catch {+ return 'THROWING_GETTER'+ }+ })(),+ alive,+}))+`++for (const [mode, article, message, cause] of [+ ['sync', 'a', 'QA_THROWING_LISTENER', 'QA_THROWING_LISTENER'],+ ['async', 'an', 'QA_THROWING_LISTENER', 'QA_THROWING_LISTENER'],+ ['sync-null', 'a', 'a thrown value that cannot be converted to text', 'NULL_PROTOTYPE'],+ ['async-null', 'an', 'a thrown value that cannot be converted to text', 'NULL_PROTOTYPE'],+ ['sync-getter', 'a', 'a thrown value that cannot be converted to text', 'THROWING_GETTER'],+ ['async-getter', 'an', 'a thrown value that cannot be converted to text', 'THROWING_GETTER'],+ ['sync-badmessage', 'a', 'a thrown value that cannot be converted to text', 'OBJECT_MESSAGE'],+ ['async-badmessage', 'an', 'a thrown value that cannot be converted to text', 'OBJECT_MESSAGE'],+]) {+ test(`${article} ${mode} listener that throws fails the runtime, not the host`, { skip: missingRuntime }, async (t) => {+ const { scratch } = await connect(t, { replies: [PROSE('hello')] })+ const { stdout } = await run(process.execPath, ['--input-type=module', '-e', LISTENER_SCRIPT, mode], {+ env: { ...scratch.env, JAN_BIN: bin, PROJECT: scratch.projectPath },+ timeout: 20_000,+ })+ const report = JSON.parse(stdout.trim().split('\n').at(-1))+ assert.equal(report.runtimeError, true)+ assert.equal(report.message, `an event listener raised: ${message}`)+ assert.equal(report.cause, cause)+ assert.equal(report.alive, false, 'the runtime process was stopped')+ })+}++test('a tool result the runtime refuses is answered as an error, and the turn goes on', { skip: missingRuntime }, async (t) => {+ const { provider, scratch, runtime } = await connect(t, {+ replies: [TOOL_CALL('host__camera', {}), PROSE('no frame')],+ })+ const session = await runtime.createSession({+ cwd: scratch.projectPath,+ model: 'stub-model',+ ephemeral: true,+ builtins: false,+ permissions: 'host',+ // Shapes cleanly here, and the runtime refuses the part: the request is+ // still pending on its side, so a swallowed refusal parks the turn.+ tools: [{ name: 'camera', capability: 'read', handler: () => ({ parts: [{ type: 'audio', data: 'x' }] }) }],+ })++ const turn = await session.prompt('look')+ assert.equal((await within(turn.result())).stopReason, 'completed')+ assert.equal(provider.bodies.length, 2, 'the model was told, so it was asked again')+ assert.match(provider.bodies[1], /refused this tool result/)+})++// The two orders of one fork and one tools change made together. Whichever the+// runtime reads first is the tool set the fork holds, so it must be the handlers+// the fork answers with.+for (const [order, makeCalls] of [+ ['fork first', (session, next) => Promise.all([session.fork(), session.setTools([next])]).then(([fork]) => [fork, 'a'])],+ ['tools change first', (session, next) => Promise.all([session.setTools([next]), session.fork()]).then(([, fork]) => [fork, 'b'])],+]) {+ test(`a fork made with a tools change keeps matching handlers (${order})`, { skip: missingRuntime }, async (t) => {+ const calls = []+ const { provider, scratch, runtime } = await connect(t, {+ replies: [TOOL_CALL('host__echo', { text: 'hi' }), PROSE('done')],+ })+ const session = await runtime.createSession({+ cwd: scratch.projectPath,+ model: 'stub-model',+ ephemeral: true,+ builtins: false,+ permissions: 'host',+ tools: [echoTool(calls, 'a')],+ })+ const [fork, expected] = await makeCalls(session, echoTool(calls, 'b'))+ assert.deepEqual(fork.tools, ['host__echo'])++ await within((await fork.prompt('echo hi')).result())+ assert.deepEqual(calls, [expected], 'the fork ran the handler for the tools the runtime gave it')+ assert.match(provider.bodies[1], new RegExp(`echoed by ${expected}: hi`))+ })+}++test('a turn started as the runtime fails is failed, not left pending', { skip: missingRuntime }, async (t) => {+ const { scratch, runtime } = await connect(t, { replies: [PROSE('hi')] })+ const session = await runtime.createSession({ cwd: scratch.projectPath, model: 'stub-model', ephemeral: true })+ // The runtime fails between the `turn/start` reply and `prompt()` resuming+ // with it: what a listener that throws on the first event of a reply that+ // arrives in the same chunk does.+ const request = runtime.request.bind(runtime)+ runtime.request = async (...args) => {+ const answer = await request(...args)+ if (args[0] === 'turn/start') {+ runtime._callListener(() => {+ throw new Error('QA_FAILS_FIRST')+ })+ }+ return answer+ }++ const turn = await session.prompt('hi')+ await assert.rejects(within(turn.result()), (error) => error instanceof JanRuntimeError && /QA_FAILS_FIRST/.test(error.message))+})++test('a terminal record already received wins over a runtime failure', { skip: missingRuntime }, async (t) => {+ const { scratch, runtime } = await connect(t, { replies: [PROSE('hi')] })+ const session = await runtime.createSession({ cwd: scratch.projectPath, model: 'stub-model', ephemeral: true })+ // The runtime sent the turn's terminal record, and then failed, before+ // `prompt()` resumed with the reply.+ const request = runtime.request.bind(runtime)+ runtime.request = async (...args) => {+ const answer = await request(...args)+ if (args[0] === 'turn/start') {+ session._complete({ turnId: answer.turnId, stopReason: 'interrupted' })+ runtime._callListener(() => {+ throw new Error('QA_CLOSED_AFTER')+ })+ }+ return answer+ }++ const turn = await session.prompt('hi')+ assert.equal((await within(turn.result())).stopReason, 'interrupted')+})++test('a handler that throws a value with no text is still answered', { skip: missingRuntime }, async (t) => {+ const { provider, scratch, runtime } = await connect(t, {+ replies: [TOOL_CALL('host__camera', {}), PROSE('no frame')],+ })+ const session = await runtime.createSession({+ cwd: scratch.projectPath,+ model: 'stub-model',+ ephemeral: true,+ builtins: false,+ permissions: 'host',+ tools: [+ {+ name: 'camera',+ capability: 'read',+ handler: () => {+ // Converting this to a string throws.+ throw Object.create(null)+ },+ },+ ],+ })+ const turn = await session.prompt('look')+ assert.equal((await within(turn.result())).stopReason, 'completed')+ assert.match(provider.bodies[1], /cannot be converted to text/)+})++test('a tool result that cannot be encoded is answered as an error, and the turn goes on', { skip: missingRuntime }, async (t) => {+ const { provider, scratch, runtime } = await connect(t, {+ replies: [TOOL_CALL('host__camera', {}), PROSE('no frame')],+ })+ const session = await runtime.createSession({+ cwd: scratch.projectPath,+ model: 'stub-model',+ ephemeral: true,+ builtins: false,+ permissions: 'host',+ // Shapes cleanly, and cannot be written as JSON: nothing reaches the runtime,+ // which is still waiting on the request.+ tools: [{ name: 'camera', capability: 'read', handler: () => ({ text: 'ok', details: { count: 1n } }) }],+ })+ const turn = await session.prompt('look')+ assert.equal((await within(turn.result())).stopReason, 'completed')+ assert.equal(provider.bodies.length, 2, 'the model was told, so it was asked again')+ assert.match(provider.bodies[1], /could not be encoded/)+})++test('a tool result whose toJSON throws is answered as an error, and the turn goes on', { skip: missingRuntime }, async (t) => {+ const { provider, scratch, runtime } = await connect(t, {+ replies: [TOOL_CALL('host__camera', {}), PROSE('no frame')],+ })+ const session = await runtime.createSession({+ cwd: scratch.projectPath,+ model: 'stub-model',+ ephemeral: true,+ builtins: false,+ permissions: 'host',+ // JSON.stringify throws a plain Error here, not a TypeError: any failure to+ // send the answer is itself answered.+ tools: [+ {+ name: 'camera',+ capability: 'read',+ handler: () => ({+ text: 'ok',+ details: {+ toJSON() {+ throw new Error('cannot encode')+ },+ },+ }),+ },+ ],+ })+ const turn = await session.prompt('look')+ assert.equal((await within(turn.result())).stopReason, 'completed')+ assert.match(provider.bodies[1], /could not be encoded: cannot encode/)+})