Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(sdk): bound the turn's unread buffer, and emit events by tag
thinhlpg5f506a47c981
diff --git a/packages/agent-sdk/README.md b/packages/agent-sdk/README.mdindex c4f76424e..429bc3db9 100644--- a/packages/agent-sdk/README.md+++ b/packages/agent-sdk/README.md@@ -45,8 +45,10 @@ await runtime.close() // closes stdin, then the process`prompt()` returns as soon as the turn starts; the events stream while it runs,and `result()` resolves when the runtime closes the turn. Iterating is optional -a host that only awaits `result()` still gets the terminal record - but an-undrained turn keeps at most `maxBufferedEvents` (default 100000) and then drops-its oldest events, counting them on `turn.dropped`.+undrained turn keeps at most `maxBufferedEvents` (default 100000) *unread*+events and then drops its oldest, counting them on `turn.dropped`. The cap is+the buffer, not the turn: a reader that keeps up with a turn of any length loses+nothing.## Host toolsdiff --git a/packages/agent-sdk/src/index.d.ts b/packages/agent-sdk/src/index.d.tsindex a0a376d1c..aba687cfe 100644--- a/packages/agent-sdk/src/index.d.ts+++ b/packages/agent-sdk/src/index.d.ts@@ -206,6 +206,9 @@ export declare class JanSession {tools: string[]toolSpecs: Record<string, unknown>[]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'`, ...). */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>diff --git a/packages/agent-sdk/src/index.js b/packages/agent-sdk/src/index.jsindex 41f912eb2..b94fff1fc 100644--- a/packages/agent-sdk/src/index.js+++ b/packages/agent-sdk/src/index.js@@ -156,7 +156,6 @@ export class JanTurn {#settle;#reject;#terminal;- #buffered = 0;// The events of this turn, in the order the runtime emitted them.[Symbol.asyncIterator]() {@@ -180,11 +179,13 @@ export class JanTurn {// `maxBufferedEvents`, then loses its oldest events - a run that streams// tokens into an unread turn must not grow the client without limit._push(event) {- if (!this.#queue.push(event)) return- this.#buffered += 1- if (this.#buffered <= this.session.maxBufferedEvents) return- if (this.#queue.dropOldest()) {- this.#buffered -= 1+ this.#queue.push(event)+ // The cap is on what is still unread, not on the turn's own output: a+ // reader that keeps up takes events out, so the queue's depth is the+ // buffer. A running total would start dropping events a reader never+ // missed the moment the turn had emitted more than the cap in total.+ while (this.#queue.length > this.session.maxBufferedEvents) {+ if (!this.#queue.dropOldest()) returnthis.dropped += 1}}@@ -225,10 +226,13 @@ export class JanSession {#closed = false;// Every event the session reports, including the ones raised by a subagent,- // which arrive wrapped in a `subagent` event. `'*'` hears all of them.- ///- // `on('tool_request', fn)` observes host tool calls; the call is answered- // from the declaration's `handler` either way.+ // which arrive wrapped in a `subagent` event.+ //+ // `kind` is `'event'` for the stream as a whole, `'*'` for everything the+ // session reports, or an event tag such as `'token'`, `'tool_request'` or+ // `'permission_request'`: `on('tool_request', fn)` observes host tool calls,+ // which the declaration's `handler` answers either way. A tag is a second+ // name for an event already on the stream, so `'*'` hears each event once.on(kind, listener) {const list = this.#listeners.get(kind) ?? []list.push(listener)@@ -329,6 +333,9 @@ export class JanSession {// Called by the runtime on every frame addressed to this session._deliver(tag, { turnId, event }) {this.#emit('event', event)+ // By tag as well, so `on('tool_request')` and `on('permission_request')`+ // hear what they were told they would.+ this.#notify(tag, event)const turn = this.#turn(turnId, true)turn?._push(event)if (tag === 'tool_request') this.#answer(event)@@ -374,9 +381,17 @@ export class JanSession {return turn}+ // One emission, to the listeners of that kind and to `'*'`, which hears+ // everything once.#emit(kind, event) {+ this.#notify(kind, event)+ this.#notify('*', event)+ }++ // 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('*') ?? []) listener(event)}// A host tool was called. The handler runs without holding the reader: twodiff --git a/packages/agent-sdk/tests/sdk.test.mjs b/packages/agent-sdk/tests/sdk.test.mjsindex 551952014..737f3ab81 100644--- a/packages/agent-sdk/tests/sdk.test.mjs+++ b/packages/agent-sdk/tests/sdk.test.mjs@@ -90,6 +90,32 @@ const HOLDING = (text) =>choices: [{ index: 0, delta: { role: 'assistant', content: text }, finish_reason: null }],})}\n\n`+// One token per chunk, paced: a turn long enough that its total output passes+// the buffer cap while a reader keeps up with it. A cap on the running total+// would start dropping events this reader never missed.+const STREAM = (tokens, delayMs, burst = 1) => async (response) => {+ const chunk = (delta, finish = null, extra = '') =>+ `data: ${JSON.stringify({+ id: 'stub-4',+ object: 'chat.completion.chunk',+ created: 1,+ model: 'stub-model',+ choices: [{ index: 0, delta, finish_reason: finish }],+ ...extra,+ })}\n\n`+ for (const [index, text] of tokens.entries()) {+ response.write(chunk({ role: 'assistant', content: text }))+ // `burst` events back to back, then a pause: a reader falls a few events+ // behind inside a burst and catches up between them, which is what tells a+ // cap on the buffer apart from a count of everything ever buffered.+ if (delayMs && (index + 1) % burst === 0) await new Promise((resolve) => setTimeout(resolve, delayMs))+ }+ response.end(+ chunk({}, 'stop', { usage: { prompt_tokens: 9, completion_tokens: tokens.length, total_tokens: 9 + tokens.length } }) ++ 'data: [DONE]\n\n',+ )+}+// Serve `replies` in order, one per connection, repeating the last once they// run out. Bodies are kept so a test can assert what the model was actually// sent - which is where a host tool's answer has to land for a round trip to@@ -581,6 +607,75 @@ test('a turn nobody drains stays bounded, and still reports its outcome', { skip})+test('a turn a reader keeps up with keeps every event, however long it runs', { skip: missingRuntime }, async (t) => {+ // Twenty bursts of four against a cap of 8: a reader falls a few events+ // behind inside a burst and catches up between them, so nothing is ever+ // further behind than the cap -- yet some 60 of the 80 events were buffered+ // on the way. Counting the turn's output instead of its buffer would drop the+ // events past the eighth, to a reader that missed none of them.+ const tokens = Array.from({ length: 80 }, (_, index) => `token ${index} `)+ const { scratch, runtime } = await connect(t, {+ replies: [STREAM(tokens, 10, 4)],+ runtime: { maxBufferedEvents: 8 },+ })+ const session = await runtime.createSession({ cwd: scratch.projectPath, model: 'stub-model', ephemeral: true })++ const turn = await session.prompt('ramble')+ const seen = []+ for await (const event of turn) if (event.type === 'token') seen.push(event.text)+ await turn.result()++ assert.equal(turn.dropped, 0, 'a reader that keeps up must not lose events')+ assert.equal(seen.length, tokens.length)++})++test('a listener by tag hears that tag, not everything', { skip: missingRuntime }, async (t) => {+ const { scratch, runtime } = await connect(t, {+ replies: [TOOL_CALL('host__camera_observe', { mode: 'rgb' }), PROSE('a red cup')],+ })+ const session = await runtime.createSession({+ cwd: scratch.projectPath,+ model: 'stub-model',+ ephemeral: true,+ builtins: false,+ tools: [+ {+ name: 'camera_observe',+ description: 'Look through the camera.',+ capability: 'read',+ parameters: { type: 'object', properties: { mode: { type: 'string' } }, required: ['mode'] },+ handler: () => ({ text: 'a red cup' }),+ },+ ],+ })++ const calls = []+ const texts = []+ const prompts = []+ const every = []+ const streamed = []+ session.on('tool_request', (event) => calls.push(event.tool_name))+ session.on('token', (event) => texts.push(event.text))+ session.on('permission_request', (event) => prompts.push(event))+ session.on('*', (event) => every.push(event))+ session.on('event', (event) => streamed.push(event))++ const turn = await session.prompt('what is on the desk?')+ for await (const _event of turn);+ await turn.result()++ // The host is told the name it declared, not the `host__` name the model+ // calls, and a read never asks permission - so that listener stays silent.+ assert.deepEqual(calls, ['camera_observe'])+ assert.equal(texts.join(''), 'a red cup')+ assert.deepEqual(prompts, [], 'nothing was gated, so nothing may be reported')+ // A tag is a second name for an event already reported, not a second event:+ // `'*'` hears the stream once.+ assert.deepEqual(every, streamed)++})+test('a request with no runtime behind it is refused, not hung', { skip: missingRuntime }, async (t) => {const { runtime } = await connect(t, { replies: [PROSE('unused')] })await assert.rejects(diff --git a/sdk/python/README.md b/sdk/python/README.mdindex bfcbc8c1d..2c9d3e2b8 100644--- a/sdk/python/README.md+++ b/sdk/python/README.md@@ -41,8 +41,9 @@ with JanRuntime.start() as runtime:`prompt()` returns as soon as the turn starts; iterating the turn yields theevents while it runs, and `result()` blocks for the terminal record. Iteratingis 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`.+turn keeps at most `max_buffered_events` (default 100000) *unread* events and+then drops its oldest, counting them on `turn.dropped`. The cap is the buffer,+not the turn: a reader that keeps up with a turn of any length loses nothing.## Host toolsdiff --git a/sdk/python/jan_agent_sdk/_queue.py b/sdk/python/jan_agent_sdk/_queue.pyindex 8bd4e9f9b..8f5eceea5 100644--- a/sdk/python/jan_agent_sdk/_queue.py+++ b/sdk/python/jan_agent_sdk/_queue.py@@ -23,6 +23,11 @@ class EventQueue:self._ended = Falseself._failure: Optional[BaseException] = None+ def __len__(self) -> int:+ """How many events are buffered - pushed and not yet taken."""+ with self._condition:+ return len(self._items)+def push(self, item: Any) -> bool:"""Append ``item``; ``True`` when it had to be buffered.diff --git a/sdk/python/jan_agent_sdk/session.py b/sdk/python/jan_agent_sdk/session.pyindex c77e2546d..ba697cf50 100644--- a/sdk/python/jan_agent_sdk/session.py+++ b/sdk/python/jan_agent_sdk/session.py@@ -80,7 +80,6 @@ class JanTurn:#: A reader that iterates the turn never drops any.self.dropped = 0self._queue = EventQueue()- self._buffered = 0self._terminal = threading.Event()self._result: Optional[TurnResult] = Noneself._failure: Optional[BaseException] = None@@ -108,13 +107,14 @@ class JanTurn:# -- 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._queue.push(event)+ # The cap is on what is still unread, not on the turn's own output: a+ # reader that keeps up takes events out, so the queue's depth is the+ # buffer. A running total would start dropping events a reader never+ # missed the moment the turn had emitted more than the cap in total.+ while len(self._queue) > self.session.max_buffered_events:+ if not self._queue.drop_oldest():+ returnself.dropped += 1def _finish(self, result: TurnResult) -> None:@@ -150,12 +150,18 @@ class JanSession:# -- 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.+ """Observe every event of the session, one event tag, or ``'*'``.++ ``kind`` is ``"event"`` for the stream as a whole, ``"*"`` for+ everything the session reports, or an event tag such as+ ``"token"``, ``"tool_request"`` or ``"permission_request"``:+ ``on("tool_request", fn)`` observes host tool calls, which are+ answered from the declaration's handler either way.++ The listener runs on the SDK's own dispatch thread, in the order the+ runtime emitted the events, so it may call back into the runtime -+ answering a permission request from one is the case that matters -+ but it shares that thread and must not block for long."""self._listeners.setdefault(kind, []).append(listener)@@ -238,6 +244,9 @@ class JanSession:turn = self._turn(params.get("turnId"), create=True)if turn is not None:turn._push(event)+ # By tag as well, so ``on("tool_request")`` and+ # ``on("permission_request")`` hear what they were told they would.+ self._notify(tag, event)if tag == "tool_request":self._answer(event)elif tag == "tool_request_cancelled":@@ -286,10 +295,15 @@ class JanSession:return turndef _emit(self, kind: str, event: Dict[str, Any]) -> None:+ """One emission, to that kind and to ``"*"``, which hears everything once."""+ self._notify(kind, event)+ self._notify("*", event)++ def _notify(self, kind: str, event: Dict[str, Any]) -> None:+ """Without the ``"*"`` fan-out, for a second tag on an already-emitted+ event: a tag listener hears it, and ``"*"`` does not hear it twice."""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.diff --git a/sdk/python/tests/harness.py b/sdk/python/tests/harness.pyindex 6b340d1c5..2e51a0082 100644--- a/sdk/python/tests/harness.py+++ b/sdk/python/tests/harness.py@@ -12,6 +12,7 @@ import jsonimport osimport subprocessimport tempfile+import timeimport threadingfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom pathlib import Path@@ -173,6 +174,57 @@ def prose(text: str) -> str:)+def streamed(tokens: Sequence[str], delay: float = 0.010, burst: int = 1) -> Callable[[_Handler], None]:+ """One token per chunk, in bursts of ``burst`` with a pause between them.++ A turn long enough that its total output passes the buffer cap, bursty+ enough that a reader falls a few events behind inside a burst and catches up+ between them: what tells a cap on the *unread* buffer apart from a count of+ everything the turn ever buffered.+ """++ def write(handler: _Handler) -> None:+ for index, text in enumerate(tokens):+ handler.wfile.write(+ (+ "data: "+ + json.dumps(+ {+ "id": "stub-4",+ "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")+ )+ handler.wfile.flush()+ if delay and (index + 1) % burst == 0:+ time.sleep(delay)+ handler.wfile.write(+ (+ "data: "+ + json.dumps(+ {+ "id": "stub-4",+ "object": "chat.completion.chunk",+ "created": 1,+ "model": "stub-model",+ "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],+ "usage": {"prompt_tokens": 9, "completion_tokens": len(tokens), "total_tokens": 9 + len(tokens)},+ }+ )+ + "\n\n"+ + "data: [DONE]\n\n"+ ).encode("utf-8")+ )+ handler.wfile.flush()++ return write++def holding(text: str) -> Callable[[_Handler], None]:"""One token, then the socket stays open: a turn to interrupt mid-flight."""diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.pyindex 7e103c905..cc4d47135 100644--- a/sdk/python/tests/test_sdk.py+++ b/sdk/python/tests/test_sdk.py@@ -19,11 +19,12 @@ import sysimport timeimport unittestfrom pathlib import Path+from typing import Any, Dict, Listsys.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+from tests.harness import Provider, Scratch, holding, prose, streamed, tool_call # noqa: E402BIN = os.environ.get("JAN_BIN")@@ -210,6 +211,69 @@ class SdkTest(unittest.TestCase):# needs most.self.assertGreater(turn.dropped, 0)+ def test_a_drained_turn_keeps_every_event(self) -> None:+ """The cap bounds what is unread, not the turn's total output.++ Twenty bursts of four against a cap of 8: the reader falls a few events+ behind inside a burst and catches up between them, so nothing is ever+ further behind than the cap, while some 60 of the 80 events were+ buffered on the way. Counting the running total instead of the buffer+ would drop the events past the eighth, to a reader that missed none of+ them.+ """+ tokens = [f"token {index} " for index in range(80)]+ scratch = self.prepare([streamed(tokens, 0.010, 4)])+ with scratch.start(max_buffered_events=8) as runtime:+ session = runtime.create_session(cwd=scratch.project, model="stub-model", ephemeral=True)+ turn = session.prompt("ramble")+ seen = [event["text"] for event in turn if event.get("type") == "token"]+ self.assertEqual(turn.result().stop_reason, "completed")+ self.assertEqual(turn.dropped, 0, "a reader that keeps up must not lose events")+ self.assertEqual(len(seen), len(tokens))++ def test_a_listener_by_tag_hears_that_tag(self) -> None:+ scratch = self.prepare([tool_call("host__camera_observe", {"mode": "rgb"}), prose("a red cup")])+ 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 through the camera.",+ parameters={"type": "object", "properties": {"mode": {"type": "string"}}, "required": ["mode"]},+ capability="read",+ handler=lambda args, call: {"text": "a red cup"},+ )+ ],+ )+ calls: List[str] = []+ texts: List[str] = []+ prompts: List[Dict[str, Any]] = []+ every: List[Dict[str, Any]] = []+ stream: List[Dict[str, Any]] = []+ session.on("tool_request", lambda event: calls.append(event["tool_name"]))+ session.on("token", lambda event: texts.append(event["text"]))+ session.on("permission_request", lambda event: prompts.append(event))+ session.on("*", every.append)+ session.on("event", stream.append)++ turn = session.prompt("what is on the desk?")+ list(turn)+ self.assertEqual(turn.result().stop_reason, "completed")++ # The host is told the name it declared, not the `host__` name the+ # model calls, and a read never asks permission.+ self.assertEqual(calls, ["camera_observe"])+ self.assertEqual("".join(texts), "a red cup")+ self.assertEqual(prompts, [], "nothing was gated, so nothing may be reported")+ # A tag is a second name for an event already reported, not a+ # second event: `"*"` hears the stream once.+ self.assertEqual(every, stream)+# -- host tools -------------------------------------------------------def test_a_host_tool_round_trips(self) -> None: