@robota-sdk/agent-transport-http 3.0.0-beta.82 → 3.0.0-beta.84

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,198 @@
1
+ # @robota-sdk/agent-transport-http
2
+
3
+ ## 3.0.0-beta.84
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [e8d70ac]
8
+ - Updated dependencies [9c6a8db]
9
+ - @robota-sdk/agent-interface-session@3.0.0-beta.84
10
+ - @robota-sdk/agent-transport@3.0.0-beta.84
11
+ - @robota-sdk/agent-interface-transport@3.0.0-beta.84
12
+
13
+ ## 3.0.0-beta.83
14
+
15
+ ### Major Changes
16
+
17
+ - 6e6b06b: A wire client can now render the whole session the way the in-process terminal UI does: the full
18
+ history, the context window as it changes, when the history changes, and where each turn came from.
19
+
20
+ - `agent-interface-session` is **`major`**: `ISessionConversationRead` gains a required
21
+ `getFullHistory()`. Any implementation of it, or of `IInteractiveSession`, must add it.
22
+ - `agent-transport` is **`major`**:
23
+ - It adds `get-history { fromIndex? }` → `history { startIndex, total, entries }`. The history
24
+ crosses one bounded page at a time (at most 256 KiB of entries; a single larger entry is sent
25
+ alone), from `fromIndex` (default 0), so no reply grows with the session. The client asks for
26
+ the next page after the previous one arrived. Entries are `IWireHistoryEntry`: a history entry
27
+ with an ISO 8601 `timestamp`. An observer may send it.
28
+ - `complete` and `interrupted` carry the turn's result without the session's history
29
+ (`TWireExecutionResult`); a client reads the history with `get-history`.
30
+ - It adds `get-prompts`: the host sends the permission and ask prompts still open as the
31
+ `permission_request` / `ask_request` frames that asked them, for a client that attached later.
32
+ An observer may not send it.
33
+ - `pending` gains an optional `pendingCount`: a host sends it when it knows how many prompts are
34
+ queued, and a client that gets none counts the prompt it shows. The host sends `pending` in
35
+ reply to a `submit` once it has taken the prompt, so a prompt queued behind a running turn shows
36
+ as queued.
37
+ - `command` takes an optional `requestId`, which the host echoes on the command's
38
+ `command_result` or `protocol_error`.
39
+ - The session's `context_update` is pushed as the `context` frame that `get-context` answers with.
40
+ - `compact`, `skill_activation` and `memory_event` push the new `history_changed`; the client
41
+ reads the history again.
42
+ - `turn_source` is pushed as the new `turn_source` frame.
43
+ - An exhaustive map over `TClientMessage` or `TServerMessage` types must add the new variants,
44
+ and `IProtocolSession` now requires `getFullHistory()`.
45
+ - `agent-transport-http` is **`major`** only because `IHttpTransportSession` includes the conversation
46
+ read role, so a session handed to it must now provide `getFullHistory()`.
47
+ - `agent-framework`: `SessionSlot` forwards `getFullHistory()` to the current session.
48
+ - `agent-ui-web` receives the new frames and does not render them.
49
+
50
+ ### Patch Changes
51
+
52
+ - 57280bf: Every published package now declares `"engines": { "node": ">=22.12.0" }`. Before, 27 of the 38
53
+ packages declared no floor (`agent-core`, `agent-tools` and every provider among them),
54
+ `agent-session` and `agent-file-authority` declared `>=20.19.0`, and the other nine declared
55
+ `>=22.0.0`, so a consumer on Node 20 saw at most a warning from a transitive dependency.
56
+
57
+ Why 22.12: `agent-cli` and `agent-ui-terminal` need Node 22 through `ink` 7, and the CommonJS entries
58
+ of `agent-tools` and its dependents, `agent-transport`/`node` and its dependents, and
59
+ `agent-ui-terminal` `require()` ESM-only dependencies (`p-limit`, `jose`, `chalk`), which Node 22
60
+ supports unflagged only from 22.12. `engines` is advisory unless the consumer enables `engine-strict`.
61
+
62
+ No code changes: `tsdown` now reads `node22.12.0` as its build target from the field.
63
+
64
+ - 18c0d5c: Every published package now exports `./package.json`, so `require('<package>/package.json')` and
65
+ `import('<package>/package.json', { with: { type: 'json' } })` work instead of failing with
66
+ `ERR_PACKAGE_PATH_NOT_EXPORTED`, and each tarball now ships the package's `CHANGELOG.md`.
67
+ - Updated dependencies [724fabb]
68
+ - Updated dependencies [d877de2]
69
+ - Updated dependencies [d61e159]
70
+ - Updated dependencies [bfe8ed5]
71
+ - Updated dependencies [7b72344]
72
+ - Updated dependencies [6ae3f28]
73
+ - Updated dependencies [57f57f5]
74
+ - Updated dependencies [ba822c1]
75
+ - Updated dependencies [6e6b06b]
76
+ - Updated dependencies [57280bf]
77
+ - Updated dependencies [18c0d5c]
78
+ - @robota-sdk/agent-interface-transport@3.0.0-beta.83
79
+ - @robota-sdk/agent-transport@3.0.0-beta.83
80
+ - @robota-sdk/agent-interface-session@3.0.0-beta.83
81
+
82
+ ## 3.0.0-beta.82
83
+
84
+ ### Patch Changes
85
+
86
+ - Updated dependencies [c7f9203]
87
+ - @robota-sdk/agent-transport@3.0.0-beta.82
88
+ - @robota-sdk/agent-interface-session@3.0.0-beta.82
89
+ - @robota-sdk/agent-interface-transport@3.0.0-beta.82
90
+
91
+ ## 3.0.0-beta.81
92
+
93
+ ### Patch Changes
94
+
95
+ - Updated dependencies [3038eb7]
96
+ - @robota-sdk/agent-interface-session@3.0.0-beta.81
97
+ - @robota-sdk/agent-interface-transport@3.0.0-beta.81
98
+ - @robota-sdk/agent-transport@3.0.0-beta.81
99
+
100
+ ## 3.0.0-beta.80
101
+
102
+ ### Major Changes
103
+
104
+ - e82215f: **ARCH-011: replace the ambiguous transport lifecycle stub with executable conformance.**
105
+
106
+ `ITransportAdapter` now requires a frozen `service | runner` lifecycle descriptor. `start()` resolves
107
+ at the concrete transport's documented readiness boundary; start before attach and repeated active
108
+ start reject a stable lifecycle error, repeated stop is safe, and stopped adapters can reattach and
109
+ restart.
110
+
111
+ Runner adapters launch separately and expose a typed terminal outcome through
112
+ `waitForCompletion()`. The registry accepts base adapters, rejects duplicate names, keeps
113
+ configuration as an optional capability, returns complete ordered records whose pending slots become
114
+ registry-owned `abandoned` outcomes on stop/rollback, and exposes a real-runner-only first-failure
115
+ wait. It serializes startup/stop, rejects active restart before mutation, and reverses partial startup
116
+ from the currently failing adapter with typed safe rollback details. Runtime host and serve mode
117
+ propagate real nonzero runner results without treating normal shutdown abandonment as failure.
118
+
119
+ HTTP, MCP, both WebSocket adapters, WebRTC, and headless invoke one shared public conformance kit.
120
+ The former `TuiTransport` export is removed because it ignored the attached session; use `renderApp`
121
+ or `TuiInteractionChannel`, which honestly own their session lifecycle.
122
+
123
+ ### Minor Changes
124
+
125
+ - 9db63ee: Add named session capability roles and explicit capability-host queries while preserving the legacy
126
+ `IInteractiveSession` interface shape. HTTP, MCP, protocol, WS, WebRTC, and headless transports now
127
+ declare only the session roles they consume, and the direct aggregate-cast floor is zero.
128
+
129
+ ### Patch Changes
130
+
131
+ - 4f3c075: Assemble complete, verified package generations before switching build output; preserve the previous generation on build failure and pack only verified regular-file images. Include copied CLI web assets in affected-build ordering and artifact transfer. Preserve the CLI version in managed build paths. Public runtime contracts remain compatible (patch).
132
+ - Updated dependencies [37b4bd7]
133
+ - Updated dependencies [50d2c9f]
134
+ - Updated dependencies [a5961c9]
135
+ - Updated dependencies [4c5148e]
136
+ - Updated dependencies [0116a29]
137
+ - Updated dependencies [e82215f]
138
+ - Updated dependencies [52b7346]
139
+ - Updated dependencies [9db63ee]
140
+ - Updated dependencies [b078afa]
141
+ - Updated dependencies [2ebff01]
142
+ - Updated dependencies [9db63ee]
143
+ - Updated dependencies [2ebff01]
144
+ - Updated dependencies [4772067]
145
+ - Updated dependencies [0f98419]
146
+ - Updated dependencies [64ba748]
147
+ - Updated dependencies [d312755]
148
+ - Updated dependencies [3244fb8]
149
+ - Updated dependencies [1e3f91a]
150
+ - Updated dependencies [4f3c075]
151
+ - Updated dependencies [7669851]
152
+ - Updated dependencies [4b76cfa]
153
+ - Updated dependencies [07b627f]
154
+ - Updated dependencies [9665c6e]
155
+ - Updated dependencies [44393be]
156
+ - Updated dependencies [c7fa299]
157
+ - Updated dependencies [5134b3b]
158
+ - Updated dependencies [5c5ff23]
159
+ - Updated dependencies [9814afc]
160
+ - @robota-sdk/agent-interface-session@3.0.0-beta.80
161
+ - @robota-sdk/agent-interface-transport@3.0.0-beta.80
162
+ - @robota-sdk/agent-transport@3.0.0-beta.80
163
+
164
+ ## 3.0.0-beta.79
165
+
166
+ ### Patch Changes
167
+
168
+ - @robota-sdk/agent-interface-transport@3.0.0-beta.79
169
+
170
+ ## 3.0.0-beta.78
171
+
172
+ ### Patch Changes
173
+
174
+ - @robota-sdk/agent-interface-transport@3.0.0-beta.78
175
+
176
+ ## 3.0.0-beta.77
177
+
178
+ ### Patch Changes
179
+
180
+ - @robota-sdk/agent-interface-transport@3.0.0-beta.77
181
+
182
+ ## 3.0.0-beta.76
183
+
184
+ ### Minor Changes
185
+
186
+ - 9df3a88: Split the consolidated `@robota-sdk/agent-transport` package into per-concern transport packages (DQ-AUDIT-005) so unrelated heavy dependencies (React/Ink, ws, Hono, MCP SDK) no longer share one publishable unit and are not dragged into non-TUI consumers' graphs:
187
+
188
+ - `@robota-sdk/agent-transport` — lean core: headless adapter + `TransportRegistry` + scripted-provider testing fixtures (no external runtime deps).
189
+ - `@robota-sdk/agent-transport-tui` — React + Ink terminal UI.
190
+ - `@robota-sdk/agent-transport-ws` — WebSocket transport + protocol (`agent-web-ui` now depends only on this for WS types).
191
+ - `@robota-sdk/agent-transport-http` — Hono HTTP transport.
192
+ - `@robota-sdk/agent-transport-mcp` — MCP server transport.
193
+
194
+ The default transport-registry wiring (pre-registering `WsTransport`) moves to the CLI composition root, removing the core→ws edge.
195
+
196
+ ### Patch Changes
197
+
198
+ - @robota-sdk/agent-interface-transport@3.0.0-beta.76
package/README.md CHANGED
@@ -1,51 +1,107 @@
1
1
  # @robota-sdk/agent-transport-http
2
2
 
3
- HTTP transport (built on [Hono](https://hono.dev)) for the Robota SDK. It exposes a running
4
- `IInteractiveSession` over HTTP routes so a browser, another service, or any HTTP client can
5
- drive an agent session.
3
+ HTTP transport for the Robota SDK, built on [Hono](https://hono.dev). It exposes a running agent session
4
+ as a small set of HTTP routes, so a browser, another service, or any HTTP client can submit prompts,
5
+ stream the agent's response as Server-Sent Events, and read the session's state. The result is a Hono
6
+ app rather than a listening server: you mount it in your own Hono application or serve it yourself.
6
7
 
7
8
  ## Installation
8
9
 
9
10
  ```bash
10
11
  npm install @robota-sdk/agent-transport-http
11
- # or
12
- pnpm add @robota-sdk/agent-transport-http
13
12
  ```
14
13
 
14
+ Requires Node.js 22.12 or later. To serve or mount the routes yourself, also add `hono` to your
15
+ application. `@robota-sdk/agent-transport` is only needed if you import its admission helpers
16
+ directly (see below).
17
+
15
18
  ## Usage
16
19
 
17
- `createAgentRoutes` builds the agent route handlers from a `sessionFactory` that resolves an
18
- `IInteractiveSession` per request (e.g. by auth token or session id). `createHttpTransport`
19
- wraps them as a mountable transport with an optional `basePath`.
20
+ `createHttpTransport` wraps the routes as a transport with the standard `attach` / `start` / `stop`
21
+ lifecycle. After `start()`, `getApp()` returns the Hono app to serve.
22
+
23
+ ```typescript
24
+ import { createHttpTransport } from '@robota-sdk/agent-transport-http';
25
+ import type { IHttpTransportSession } from '@robota-sdk/agent-transport-http';
26
+
27
+ declare const session: IHttpTransportSession; // e.g. an InteractiveSession from @robota-sdk/agent-framework
28
+
29
+ const transport = createHttpTransport({ basePath: '/agent' });
30
+ transport.attach(session);
31
+ await transport.start();
32
+
33
+ const app = transport.getApp(); // a Hono app; serve it, or mount it in your own app
34
+ const token = transport.getAdmissionToken(); // hand this to your client
35
+ ```
36
+
37
+ Every request must carry `Authorization: Bearer <token>`; anything else is answered `401` before it
38
+ reaches a route. When you omit `admission`, a random per-launch token is minted and
39
+ `getAdmissionToken()` returns it. Pass `admission: { token }` to use a token you chose, or
40
+ `admission: { open: true, openReason: '…' }` to run without a credential when something in front of
41
+ the routes (a gateway, your own auth middleware) already decides who may reach them. `openReason` is
42
+ required, and a token together with `open: true` is rejected.
20
43
 
21
- The factory may return a fresh object per request. `/submit`'s concurrent-turn refusal is keyed by
22
- `getSession().getSessionId()`, not by object identity, so a per-request wrapper around one session
23
- is still recognised as that session.
44
+ ### Mounting the routes in your own app
24
45
 
25
- <!-- doc-example-skip: requires the host app's hono dependency -->
46
+ `createAgentRoutes` returns the same routes as a Hono router. It resolves the session per request
47
+ through `sessionFactory`, which receives the Hono request context, so one app can serve several
48
+ sessions (for example, looked up from a request header). Here `admission` is required. A token minted
49
+ inside `createAgentRoutes` could never be read back, so pass one you know: your own, or the result of
50
+ `resolveAdmission()` from `@robota-sdk/agent-transport/node`.
26
51
 
27
52
  ```typescript
28
53
  import { createAgentRoutes } from '@robota-sdk/agent-transport-http';
54
+ import type { IHttpTransportSession } from '@robota-sdk/agent-transport-http';
29
55
  import { Hono } from 'hono';
30
56
 
57
+ declare const session: IHttpTransportSession;
58
+ declare const agentToken: string; // shared with your clients out of band
59
+
31
60
  const app = new Hono();
32
61
  app.route(
33
62
  '/agent',
34
63
  createAgentRoutes({
35
- // Resolve (or create) the session for this request.
36
- sessionFactory: (c) => resolveSessionForRequest(c),
64
+ sessionFactory: () => session, // may also look the session up from the request context
65
+ admission: { token: agentToken },
37
66
  }),
38
67
  );
39
68
  ```
40
69
 
70
+ `sessionFactory` may return a new wrapper object on each call. `/submit` keys its one-turn-at-a-time
71
+ check on `getSession().getSessionId()`, not on object identity.
72
+
73
+ ## Routes
74
+
75
+ | Method | Path | Purpose |
76
+ | ------ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
77
+ | POST | `/submit` | Body `{ "prompt": string }`. Runs a turn and streams `text_delta`, `tool_start`, `tool_end`, `thinking`, then `complete`, `interrupted` or `error` as SSE. `409` while a turn is already running. |
78
+ | POST | `/command` | Body `{ "name": string, "args"?: string }`. Runs a session command on behalf of a remote caller. |
79
+ | POST | `/abort` | Aborts the running turn. |
80
+ | POST | `/cancel-queue` | Drops the queued prompt. |
81
+ | GET | `/messages` | The conversation history. |
82
+ | GET | `/context` | The context-window state. |
83
+ | GET | `/executing` | `{ "executing": boolean }`, using the same rule `/submit` uses to answer `409`. |
84
+ | GET | `/pending` | `{ "pending": … }`, the queued prompt, if any. |
85
+
86
+ Paths are relative to where the routes are mounted (`basePath`, or the prefix you pass to
87
+ `app.route`).
88
+
41
89
  ## Exports
42
90
 
43
- | Symbol | Kind | Description |
44
- | ----------------------- | --------- | --------------------------------------------------------- |
45
- | `createHttpTransport` | function | `(options?: IHttpTransportOptions)` — mountable transport |
46
- | `createAgentRoutes` | function | `(options: IAgentRoutesOptions)` — Hono agent routes |
47
- | `IHttpTransportOptions` | interface | `{ basePath?: string }` |
48
- | `IAgentRoutesOptions` | interface | `{ sessionFactory: TSessionFactory }` |
49
- | `TSessionFactory` | type | Resolves an `IInteractiveSession` per request |
91
+ | Symbol | Kind | Description |
92
+ | ------------------------ | --------- | ----------------------------------------------------------------------------------------------------- |
93
+ | `createHttpTransport` | function | `(options?: IHttpTransportOptions) => IHttpTransport` |
94
+ | `createAgentRoutes` | function | `(options: IAgentRoutesOptions) => Hono` |
95
+ | `IHttpTransportOptions` | interface | `{ basePath?, admission?, onStreamFailure? }` |
96
+ | `IHttpTransport` | interface | The transport; adds `getApp()` and `getAdmissionToken()` to the standard transport lifecycle |
97
+ | `IAgentRoutesOptions` | interface | `{ sessionFactory, admission, onStreamFailure? }` |
98
+ | `TSessionFactory` | type | `(c: Context) => IHttpTransportSession \| Promise<IHttpTransportSession>` |
99
+ | `IHttpTransportSession` | interface | The session capabilities the routes use; a full interactive session satisfies it |
100
+ | `TStreamFailureListener` | type | Receives the details of a stream that fails after headers were sent (the client sees a generic error) |
101
+
102
+ ## Related
50
103
 
51
- See [docs/SPEC.md](./docs/SPEC.md) for the full contract and route surface.
104
+ - [`@robota-sdk/agent-transport`](../agent-transport/README.md) — the admission helpers these routes use.
105
+ - [`@robota-sdk/agent-transport-ws`](../agent-transport-ws/README.md) — the WebSocket transport, which
106
+ carries the full session protocol (this HTTP surface covers a subset).
107
+ - [docs/SPEC.md](./docs/SPEC.md) — package contract and invariants.
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@robota-sdk/agent-transport/node"),t=require("hono"),n=require("hono/streaming");function r(e,t,n,r){let a=(t,r)=>{e.on(t,r),n.push(()=>e.off(t,r))},o=(e,n)=>t.writeSSE({event:e,data:JSON.stringify(n)}).catch(()=>{}),s,c=new Promise(e=>{s=e});return a(`text_delta`,e=>void o(`text_delta`,{delta:e})),a(`tool_start`,e=>void o(`tool_start`,e)),a(`tool_end`,e=>void o(`tool_end`,e)),a(`thinking`,e=>void o(`thinking`,{isThinking:e})),a(`complete`,async e=>{await o(`complete`,e),s()}),a(`interrupted`,async e=>{await o(`interrupted`,e),s()}),a(`error`,async e=>{await o(`error`,{message:e.message}),s()}),t.onAbort(()=>i(e,r,s)),c}function i(e,t,n){try{e.abort()}catch(e){try{t?.(e instanceof Error?e:Error(String(e)))}catch{}}finally{n()}}function a(e,t){for(let t of e)try{t()}catch{}t()}function o(e,t,n,i){return async o=>{try{let s=[];try{let n=r(e,o,s,i);await e.submit(t),await n}finally{a(s,n)}}catch(e){await s(e instanceof Error?e:Error(String(e)),o,i)}}}async function s(e,t,n){try{n?.(e)}catch{}await t.writeSSE({event:`error`,data:JSON.stringify({message:`the stream failed on the server after it opened — the turn may not have run`})}).catch(()=>{})}function c(e,t,n){let r=n.keyFor(t);return r===void 0?e.json({error:`concurrent-turn tracking is unavailable for this session, so this request cannot be served safely. Refusing rather than starting a turn that cannot be guaranteed to be yours.`},500):n.isHeld(r)||t.isExecuting()?e.json({error:`session busy — a turn is already in flight`},409):(n.hold(r),{claim:r})}function l(e,t,r){return async i=>{let a=await e(i),s=await i.req.json();if(!s.prompt||typeof s.prompt!=`string`)return i.json({error:`prompt is required`},400);let l=c(i,a,t);if(l instanceof Response)return l;let{claim:u}=l,d=!1,f=()=>{d||(d=!0,t.release(u))};try{return await(0,n.streamSSE)(i,o(a,s.prompt,f,r))}catch(e){throw f(),e}}}function u(){let e=new Set;return{keyFor(e){try{let t=e.getSession().getSessionId();return typeof t==`string`&&t!==``?t:void 0}catch{return}},isHeld:t=>e.has(t),hold:t=>void e.add(t),release:t=>void e.delete(t)}}function d(n){let{sessionFactory:r,onStreamFailure:i}=n,a=new t.Hono,o=u(),s=(0,e.resolveAdmission)(n.admission);return a.use(`*`,async(t,n)=>s.token===null||(0,e.credentialMatches)(s.token,(0,e.bearerCredential)(t.req.header(`authorization`)))?n():t.json({error:`unauthorized`},401)),a.post(`/submit`,l(r,o,i)),a.post(`/command`,async e=>{let t=await r(e),n=await e.req.json();if(!n.name||typeof n.name!=`string`)return e.json({error:`name is required`},400);let i=await t.executeCommand(n.name,n.args??``,`remote`);return i?e.json(i):e.json({error:`Unknown command: ${n.name}`},404)}),a.post(`/abort`,async e=>((await r(e)).abort(),e.json({ok:!0}))),a.post(`/cancel-queue`,async e=>((await r(e)).cancelQueue(),e.json({ok:!0}))),a.get(`/messages`,async e=>{let t=await r(e);return e.json(t.getMessages())}),a.get(`/context`,async e=>{let t=await r(e);return e.json(t.getContextState())}),a.get(`/executing`,async e=>{let t=await r(e),n=o.keyFor(t),i=n!==void 0&&o.isHeld(n);return e.json({executing:i||t.isExecuting()})}),a.get(`/pending`,async e=>{let t=await r(e);return e.json({pending:t.getPendingPrompt()})}),a}function f(n){let r=null,i=null,a=(0,e.resolveAdmission)(n?.admission),o=e=>Object.assign(Error(`HTTP transport ${e}.`),{name:`TransportLifecycleError`,code:e,transportName:`http`});return{name:`http`,lifecycle:Object.freeze({kind:`service`}),attach(e){r=e},async start(){if(!r)throw o(`not-attached`);if(i)throw o(`already-started`);let e=d({sessionFactory:()=>r,admission:a,onStreamFailure:n?.onStreamFailure});i=n?.basePath?new t.Hono().route(n.basePath,e):e},async stop(){i=null,r=null},getApp(){if(!i)throw Error(`Transport not started. Call start() first.`);return i},getAdmissionToken(){return a.token}}}exports.createAgentRoutes=d,exports.createHttpTransport=f;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@robota-sdk/agent-transport/node"),t=require("hono"),n=require("hono/streaming");function r(e,t,n,r){let a=(t,r)=>{e.on(t,r),n.push(()=>e.off(t,r))},o=(e,n)=>t.writeSSE({event:e,data:JSON.stringify(n)}).catch(()=>{}),s,c=new Promise(e=>{s=e});return a(`text_delta`,e=>void o(`text_delta`,{delta:e})),a(`tool_start`,e=>void o(`tool_start`,e)),a(`tool_end`,e=>void o(`tool_end`,e)),a(`thinking`,e=>void o(`thinking`,{isThinking:e})),a(`complete`,async e=>{await o(`complete`,e),s()}),a(`interrupted`,async e=>{await o(`interrupted`,e),s()}),a(`error`,async e=>{await o(`error`,{message:e.message}),s()}),t.onAbort(()=>i(e,r,s)),c}function i(e,t,n){try{e.abort()}catch(e){try{t?.(e instanceof Error?e:Error(String(e)))}catch{}}finally{n()}}function a(e,t){for(let t of e)try{t()}catch{}t()}function o(e,t,n,i){return async o=>{try{let s=[];try{let n=r(e,o,s,i);await e.submit(t),await n}finally{a(s,n)}}catch(e){await s(e instanceof Error?e:Error(String(e)),o,i)}}}async function s(e,t,n){try{n?.(e)}catch{}await t.writeSSE({event:`error`,data:JSON.stringify({message:`the stream failed on the server after it opened — the turn may not have run`})}).catch(()=>{})}function c(e,t,n){let r=n.keyFor(t);return r===void 0?e.json({error:`concurrent-turn tracking is unavailable for this session, so this request cannot be served safely. Refusing rather than starting a turn that cannot be guaranteed to be yours.`},500):n.isHeld(r)||t.isExecuting()?e.json({error:`session busy — a turn is already in flight`},409):(n.hold(r),{claim:r})}function l(e,t,r){return async i=>{let a=await e(i),s=await i.req.json();if(!s.prompt||typeof s.prompt!=`string`)return i.json({error:`prompt is required`},400);if(a.whenInitialized!==void 0)try{await a.whenInitialized()}catch{return i.json({error:`the session could not be started`},500)}let l=c(i,a,t);if(l instanceof Response)return l;let{claim:u}=l,d=!1,f=()=>{d||(d=!0,t.release(u))};try{return await(0,n.streamSSE)(i,o(a,s.prompt,f,r))}catch(e){throw f(),e}}}function u(){let e=new Set;return{keyFor(e){try{let t=e.getSession().getSessionId();return typeof t==`string`&&t!==``?t:void 0}catch{return}},isHeld:t=>e.has(t),hold:t=>void e.add(t),release:t=>void e.delete(t)}}function d(n){let{sessionFactory:r,onStreamFailure:i}=n,a=new t.Hono,o=u(),s=(0,e.resolveAdmission)(n.admission);return a.use(`*`,async(t,n)=>s.token===null||(0,e.credentialMatches)(s.token,(0,e.bearerCredential)(t.req.header(`authorization`)))?n():t.json({error:`unauthorized`},401)),a.post(`/submit`,l(r,o,i)),a.post(`/command`,async e=>{let t=await r(e),n=await e.req.json();if(!n.name||typeof n.name!=`string`)return e.json({error:`name is required`},400);let i=await t.executeCommand(n.name,n.args??``,`remote`);return i?e.json(i):e.json({error:`Unknown command: ${n.name}`},404)}),a.post(`/abort`,async e=>((await r(e)).abort(),e.json({ok:!0}))),a.post(`/cancel-queue`,async e=>((await r(e)).cancelQueue(),e.json({ok:!0}))),a.get(`/messages`,async e=>{let t=await r(e);return e.json(t.getMessages())}),a.get(`/context`,async e=>{let t=await r(e);return e.json(t.getContextState())}),a.get(`/executing`,async e=>{let t=await r(e),n=o.keyFor(t),i=n!==void 0&&o.isHeld(n);return e.json({executing:i||t.isExecuting()})}),a.get(`/pending`,async e=>{let t=await r(e);return e.json({pending:t.getPendingPrompt()})}),a}function f(n){let r=null,i=null,a=(0,e.resolveAdmission)(n?.admission),o=e=>Object.assign(Error(`HTTP transport ${e}.`),{name:`TransportLifecycleError`,code:e,transportName:`http`});return{name:`http`,lifecycle:Object.freeze({kind:`service`}),attach(e){r=e},async start(){if(!r)throw o(`not-attached`);if(i)throw o(`already-started`);let e=d({sessionFactory:()=>r,admission:a,onStreamFailure:n?.onStreamFailure});i=n?.basePath?new t.Hono().route(n.basePath,e):e},async stop(){i=null,r=null},getApp(){if(!i)throw Error(`Transport not started. Call start() first.`);return i},getAdmissionToken(){return a.token}}}exports.createAgentRoutes=d,exports.createHttpTransport=f;
@@ -4,7 +4,14 @@ import "hono/streaming";
4
4
  import { ITransportAdapter, ITransportAdmission, ITransportAdmissionConfig } from "@robota-sdk/agent-interface-transport";
5
5
  //#region src/http-session.d.ts
6
6
  /** The exact session capabilities consumed by the public HTTP transport. */
7
- interface IHttpTransportSession extends ISessionTurnSubmission, ISessionEvents, ISessionTurnControl, ISessionIdentity, ISessionCommands, ISessionConversationRead, ISessionExecutionState {}
7
+ interface IHttpTransportSession extends ISessionTurnSubmission, ISessionEvents, ISessionTurnControl, ISessionIdentity, ISessionCommands, ISessionConversationRead, ISessionExecutionState {
8
+ /**
9
+ * Resolves once the session can name itself, and rejects if it failed to start. A session that
10
+ * builds itself in the background (`InteractiveSession`) has no id before then, so `/submit` waits
11
+ * on this before claiming a turn. A session that is ready at construction can omit it.
12
+ */
13
+ whenInitialized?(): Promise<void>;
14
+ }
8
15
  //#endregion
9
16
  //#region src/submit-stream.d.ts
10
17
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/http-session.ts","../../src/submit-stream.ts","../../src/submit-route.ts","../../src/routes.ts","../../src/http-transport.ts"],"mappings":";;;;;;UAWiB,8BAEb,wBACA,gBACA,qBACA,kBACA,kBACA,0BACA;;;;;;;;;;;;;;;;KCMQ,0BAA0B,OAAO;;;;;;;;;;;;;;;;;;;;;;;KCYjC,mBACV,GAAG,YACA,wBAAwB,QAAQ;;;UCVpB;;EAEf,gBAAgB;;;;;;EAMhB,kBAAkB;;;;;;;;EAQlB,WAAW,4BAA4B;;;;;;;;;;;;iBAazB,kBAAkB,SAAS,sBAAsB;;;UCtChD;;EAEf;;;;;;;;EAQA,YAAY;;;;;;;EAOZ,kBAAkB;;UAGH,uBAAuB,kBAAkB;EACxD,UAAU;EACV;;iBAGc,oBAAoB,UAAU,wBAAwB"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/http-session.ts","../../src/submit-stream.ts","../../src/submit-route.ts","../../src/routes.ts","../../src/http-transport.ts"],"mappings":";;;;;;UAWiB,8BAEb,wBACA,gBACA,qBACA,kBACA,kBACA,0BACA;;;;;;EAMF,oBAAoB;;;;;;;;;;;;;;;;;KCAV,0BAA0B,OAAO;;;;;;;;;;;;;;;;;;;;;;;KCYjC,mBACV,GAAG,YACA,wBAAwB,QAAQ;;;UCVpB;;EAEf,gBAAgB;;;;;;EAMhB,kBAAkB;;;;;;;;EAQlB,WAAW,4BAA4B;;;;;;;;;;;;iBAazB,kBAAkB,SAAS,sBAAsB;;;UCtChD;;EAEf;;;;;;;;EAQA,YAAY;;;;;;;EAOZ,kBAAkB;;UAGH,uBAAuB,kBAAkB;EACxD,UAAU;EACV;;iBAGc,oBAAoB,UAAU,wBAAwB"}
@@ -4,7 +4,14 @@ import { ISessionCommands, ISessionConversationRead, ISessionEvents, ISessionExe
4
4
  import { ITransportAdapter, ITransportAdmission, ITransportAdmissionConfig } from "@robota-sdk/agent-interface-transport";
5
5
  //#region src/http-session.d.ts
6
6
  /** The exact session capabilities consumed by the public HTTP transport. */
7
- interface IHttpTransportSession extends ISessionTurnSubmission, ISessionEvents, ISessionTurnControl, ISessionIdentity, ISessionCommands, ISessionConversationRead, ISessionExecutionState {}
7
+ interface IHttpTransportSession extends ISessionTurnSubmission, ISessionEvents, ISessionTurnControl, ISessionIdentity, ISessionCommands, ISessionConversationRead, ISessionExecutionState {
8
+ /**
9
+ * Resolves once the session can name itself, and rejects if it failed to start. A session that
10
+ * builds itself in the background (`InteractiveSession`) has no id before then, so `/submit` waits
11
+ * on this before claiming a turn. A session that is ready at construction can omit it.
12
+ */
13
+ whenInitialized?(): Promise<void>;
14
+ }
8
15
  //#endregion
9
16
  //#region src/submit-stream.d.ts
10
17
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/http-session.ts","../../src/submit-stream.ts","../../src/submit-route.ts","../../src/routes.ts","../../src/http-transport.ts"],"mappings":";;;;;;UAWiB,8BAEb,wBACA,gBACA,qBACA,kBACA,kBACA,0BACA;;;;;;;;;;;;;;;;KCMQ,0BAA0B,OAAO;;;;;;;;;;;;;;;;;;;;;;;KCYjC,mBACV,GAAG,YACA,wBAAwB,QAAQ;;;UCVpB;;EAEf,gBAAgB;;;;;;EAMhB,kBAAkB;;;;;;;;EAQlB,WAAW,4BAA4B;;;;;;;;;;;;iBAazB,kBAAkB,SAAS,sBAAsB;;;UCtChD;;EAEf;;;;;;;;EAQA,YAAY;;;;;;;EAOZ,kBAAkB;;UAGH,uBAAuB,kBAAkB;EACxD,UAAU;EACV;;iBAGc,oBAAoB,UAAU,wBAAwB"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/http-session.ts","../../src/submit-stream.ts","../../src/submit-route.ts","../../src/routes.ts","../../src/http-transport.ts"],"mappings":";;;;;;UAWiB,8BAEb,wBACA,gBACA,qBACA,kBACA,kBACA,0BACA;;;;;;EAMF,oBAAoB;;;;;;;;;;;;;;;;;KCAV,0BAA0B,OAAO;;;;;;;;;;;;;;;;;;;;;;;KCYjC,mBACV,GAAG,YACA,wBAAwB,QAAQ;;;UCVpB;;EAEf,gBAAgB;;;;;;EAMhB,kBAAkB;;;;;;;;EAQlB,WAAW,4BAA4B;;;;;;;;;;;;iBAazB,kBAAkB,SAAS,sBAAsB;;;UCtChD;;EAEf;;;;;;;;EAQA,YAAY;;;;;;;EAOZ,kBAAkB;;UAGH,uBAAuB,kBAAkB;EACxD,UAAU;EACV;;iBAGc,oBAAoB,UAAU,wBAAwB"}
@@ -1,2 +1,2 @@
1
- import{bearerCredential as e,credentialMatches as t,resolveAdmission as n}from"@robota-sdk/agent-transport/node";import{Hono as r}from"hono";import{streamSSE as i}from"hono/streaming";function a(e,t,n,r){let i=(t,r)=>{e.on(t,r),n.push(()=>e.off(t,r))},a=(e,n)=>t.writeSSE({event:e,data:JSON.stringify(n)}).catch(()=>{}),s,c=new Promise(e=>{s=e});return i(`text_delta`,e=>void a(`text_delta`,{delta:e})),i(`tool_start`,e=>void a(`tool_start`,e)),i(`tool_end`,e=>void a(`tool_end`,e)),i(`thinking`,e=>void a(`thinking`,{isThinking:e})),i(`complete`,async e=>{await a(`complete`,e),s()}),i(`interrupted`,async e=>{await a(`interrupted`,e),s()}),i(`error`,async e=>{await a(`error`,{message:e.message}),s()}),t.onAbort(()=>o(e,r,s)),c}function o(e,t,n){try{e.abort()}catch(e){try{t?.(e instanceof Error?e:Error(String(e)))}catch{}}finally{n()}}function s(e,t){for(let t of e)try{t()}catch{}t()}function c(e,t,n,r){return async i=>{try{let o=[];try{let n=a(e,i,o,r);await e.submit(t),await n}finally{s(o,n)}}catch(e){await l(e instanceof Error?e:Error(String(e)),i,r)}}}async function l(e,t,n){try{n?.(e)}catch{}await t.writeSSE({event:`error`,data:JSON.stringify({message:`the stream failed on the server after it opened — the turn may not have run`})}).catch(()=>{})}function u(e,t,n){let r=n.keyFor(t);return r===void 0?e.json({error:`concurrent-turn tracking is unavailable for this session, so this request cannot be served safely. Refusing rather than starting a turn that cannot be guaranteed to be yours.`},500):n.isHeld(r)||t.isExecuting()?e.json({error:`session busy — a turn is already in flight`},409):(n.hold(r),{claim:r})}function d(e,t,n){return async r=>{let a=await e(r),o=await r.req.json();if(!o.prompt||typeof o.prompt!=`string`)return r.json({error:`prompt is required`},400);let s=u(r,a,t);if(s instanceof Response)return s;let{claim:l}=s,d=!1,f=()=>{d||(d=!0,t.release(l))};try{return await i(r,c(a,o.prompt,f,n))}catch(e){throw f(),e}}}function f(){let e=new Set;return{keyFor(e){try{let t=e.getSession().getSessionId();return typeof t==`string`&&t!==``?t:void 0}catch{return}},isHeld:t=>e.has(t),hold:t=>void e.add(t),release:t=>void e.delete(t)}}function p(i){let{sessionFactory:a,onStreamFailure:o}=i,s=new r,c=f(),l=n(i.admission);return s.use(`*`,async(n,r)=>l.token===null||t(l.token,e(n.req.header(`authorization`)))?r():n.json({error:`unauthorized`},401)),s.post(`/submit`,d(a,c,o)),s.post(`/command`,async e=>{let t=await a(e),n=await e.req.json();if(!n.name||typeof n.name!=`string`)return e.json({error:`name is required`},400);let r=await t.executeCommand(n.name,n.args??``,`remote`);return r?e.json(r):e.json({error:`Unknown command: ${n.name}`},404)}),s.post(`/abort`,async e=>((await a(e)).abort(),e.json({ok:!0}))),s.post(`/cancel-queue`,async e=>((await a(e)).cancelQueue(),e.json({ok:!0}))),s.get(`/messages`,async e=>{let t=await a(e);return e.json(t.getMessages())}),s.get(`/context`,async e=>{let t=await a(e);return e.json(t.getContextState())}),s.get(`/executing`,async e=>{let t=await a(e),n=c.keyFor(t),r=n!==void 0&&c.isHeld(n);return e.json({executing:r||t.isExecuting()})}),s.get(`/pending`,async e=>{let t=await a(e);return e.json({pending:t.getPendingPrompt()})}),s}function m(e){let t=null,i=null,a=n(e?.admission),o=e=>Object.assign(Error(`HTTP transport ${e}.`),{name:`TransportLifecycleError`,code:e,transportName:`http`});return{name:`http`,lifecycle:Object.freeze({kind:`service`}),attach(e){t=e},async start(){if(!t)throw o(`not-attached`);if(i)throw o(`already-started`);let n=p({sessionFactory:()=>t,admission:a,onStreamFailure:e?.onStreamFailure});i=e?.basePath?new r().route(e.basePath,n):n},async stop(){i=null,t=null},getApp(){if(!i)throw Error(`Transport not started. Call start() first.`);return i},getAdmissionToken(){return a.token}}}export{p as createAgentRoutes,m as createHttpTransport};
1
+ import{bearerCredential as e,credentialMatches as t,resolveAdmission as n}from"@robota-sdk/agent-transport/node";import{Hono as r}from"hono";import{streamSSE as i}from"hono/streaming";function a(e,t,n,r){let i=(t,r)=>{e.on(t,r),n.push(()=>e.off(t,r))},a=(e,n)=>t.writeSSE({event:e,data:JSON.stringify(n)}).catch(()=>{}),s,c=new Promise(e=>{s=e});return i(`text_delta`,e=>void a(`text_delta`,{delta:e})),i(`tool_start`,e=>void a(`tool_start`,e)),i(`tool_end`,e=>void a(`tool_end`,e)),i(`thinking`,e=>void a(`thinking`,{isThinking:e})),i(`complete`,async e=>{await a(`complete`,e),s()}),i(`interrupted`,async e=>{await a(`interrupted`,e),s()}),i(`error`,async e=>{await a(`error`,{message:e.message}),s()}),t.onAbort(()=>o(e,r,s)),c}function o(e,t,n){try{e.abort()}catch(e){try{t?.(e instanceof Error?e:Error(String(e)))}catch{}}finally{n()}}function s(e,t){for(let t of e)try{t()}catch{}t()}function c(e,t,n,r){return async i=>{try{let o=[];try{let n=a(e,i,o,r);await e.submit(t),await n}finally{s(o,n)}}catch(e){await l(e instanceof Error?e:Error(String(e)),i,r)}}}async function l(e,t,n){try{n?.(e)}catch{}await t.writeSSE({event:`error`,data:JSON.stringify({message:`the stream failed on the server after it opened — the turn may not have run`})}).catch(()=>{})}function u(e,t,n){let r=n.keyFor(t);return r===void 0?e.json({error:`concurrent-turn tracking is unavailable for this session, so this request cannot be served safely. Refusing rather than starting a turn that cannot be guaranteed to be yours.`},500):n.isHeld(r)||t.isExecuting()?e.json({error:`session busy — a turn is already in flight`},409):(n.hold(r),{claim:r})}function d(e,t,n){return async r=>{let a=await e(r),o=await r.req.json();if(!o.prompt||typeof o.prompt!=`string`)return r.json({error:`prompt is required`},400);if(a.whenInitialized!==void 0)try{await a.whenInitialized()}catch{return r.json({error:`the session could not be started`},500)}let s=u(r,a,t);if(s instanceof Response)return s;let{claim:l}=s,d=!1,f=()=>{d||(d=!0,t.release(l))};try{return await i(r,c(a,o.prompt,f,n))}catch(e){throw f(),e}}}function f(){let e=new Set;return{keyFor(e){try{let t=e.getSession().getSessionId();return typeof t==`string`&&t!==``?t:void 0}catch{return}},isHeld:t=>e.has(t),hold:t=>void e.add(t),release:t=>void e.delete(t)}}function p(i){let{sessionFactory:a,onStreamFailure:o}=i,s=new r,c=f(),l=n(i.admission);return s.use(`*`,async(n,r)=>l.token===null||t(l.token,e(n.req.header(`authorization`)))?r():n.json({error:`unauthorized`},401)),s.post(`/submit`,d(a,c,o)),s.post(`/command`,async e=>{let t=await a(e),n=await e.req.json();if(!n.name||typeof n.name!=`string`)return e.json({error:`name is required`},400);let r=await t.executeCommand(n.name,n.args??``,`remote`);return r?e.json(r):e.json({error:`Unknown command: ${n.name}`},404)}),s.post(`/abort`,async e=>((await a(e)).abort(),e.json({ok:!0}))),s.post(`/cancel-queue`,async e=>((await a(e)).cancelQueue(),e.json({ok:!0}))),s.get(`/messages`,async e=>{let t=await a(e);return e.json(t.getMessages())}),s.get(`/context`,async e=>{let t=await a(e);return e.json(t.getContextState())}),s.get(`/executing`,async e=>{let t=await a(e),n=c.keyFor(t),r=n!==void 0&&c.isHeld(n);return e.json({executing:r||t.isExecuting()})}),s.get(`/pending`,async e=>{let t=await a(e);return e.json({pending:t.getPendingPrompt()})}),s}function m(e){let t=null,i=null,a=n(e?.admission),o=e=>Object.assign(Error(`HTTP transport ${e}.`),{name:`TransportLifecycleError`,code:e,transportName:`http`});return{name:`http`,lifecycle:Object.freeze({kind:`service`}),attach(e){t=e},async start(){if(!t)throw o(`not-attached`);if(i)throw o(`already-started`);let n=p({sessionFactory:()=>t,admission:a,onStreamFailure:e?.onStreamFailure});i=e?.basePath?new r().route(e.basePath,n):n},async stop(){i=null,t=null},getApp(){if(!i)throw Error(`Transport not started. Call start() first.`);return i},getAdmissionToken(){return a.token}}}export{p as createAgentRoutes,m as createHttpTransport};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/submit-stream.ts","../../src/submit-route.ts","../../src/turn-claims.ts","../../src/routes.ts","../../src/http-transport.ts"],"sourcesContent":["/**\n * RUNTIME-14 / RUNTIME-38 — relaying ONE turn to an SSE client, and letting go of it afterwards.\n *\n * Split out of `routes.ts` under the file-size ceiling. The route's job is to decide whether this\n * request may start a turn; relaying the turn's events, tearing the subscriptions down, and telling\n * a client whose stream broke after the headers went out is a different job with its own failure\n * modes, and it was four fifths of the handler.\n */\n\nimport type { IHttpTransportSession } from './http-session.js';\nimport type { SSEStreamingApi } from 'hono/streaming';\n\n/**\n * Where the DETAIL of a post-headers stream failure goes — injected, never imported.\n *\n * The first version imported `createLogger` from `agent-core`, and review held it against two\n * authorities at once: `project-structure.md` declares this package contract-pure (transports\n * depend on the contracts and the protocol, nothing else), and its side-concern rule says a logging\n * destination \"must be injected, not imported directly\". The host that mounts this router decides\n * where diagnostics go; a module-level singleton decided it for every host, with no override.\n *\n * Absent, the detail is dropped — by the HOST's explicit default, which is a different thing from\n * this module deleting it: the client still learns the stream failed, and the host was offered the\n * detail at the boundary where it mounts the route.\n */\nexport type TStreamFailureListener = (error: Error) => void;\n\n/**\n * Wire every relay subscription and the abort path; answer with the promise that settles when the\n * turn is over (or refused one).\n *\n * The subscriptions are wired OUTSIDE the promise executor. Inside it, a throw from `session.on` —\n * a bad handler, an EventEmitter listener cap — is caught by the Promise constructor and becomes an\n * already-rejected `done` instead of propagating. Execution then reaches `await session.submit`, so\n * a REAL TURN is consumed with only some of its listeners attached and nothing to relay it, and the\n * rejection surfaces afterwards at `await done` — by which point the turn is gone.\n */\nfunction wireRelay(\n session: IHttpTransportSession,\n stream: SSEStreamingApi,\n cleanup: Array<() => void>,\n onFailure: TStreamFailureListener | undefined,\n): Promise<void> {\n const subscribe = <T>(event: string, handler: (data: T) => void): void => {\n session.on(event as 'text_delta', handler as () => void);\n cleanup.push(() => session.off(event as 'text_delta', handler as () => void));\n };\n\n // RUNTIME-14: await + catch every SSE write so a write to a client-closed stream is a blessed\n // no-op, not an unhandled rejection (post-headers errors bypass Hono's onError).\n const write = (event: string, data: unknown): Promise<void> =>\n stream.writeSSE({ event, data: JSON.stringify(data) }).catch(() => {\n // allow-fallback: client closed the stream mid-write — nothing to deliver; the finally teardown\n // (RUNTIME-14) removes the listeners, so this write has nothing left to do.\n });\n\n let settle!: () => void;\n const done = new Promise<void>((resolve) => {\n settle = resolve;\n });\n\n subscribe('text_delta', (delta: string) => void write('text_delta', { delta }));\n subscribe('tool_start', (state) => void write('tool_start', state));\n subscribe('tool_end', (state) => void write('tool_end', state));\n subscribe('thinking', (isThinking: boolean) => void write('thinking', { isThinking }));\n\n // Flush the terminal event before resolving, so the resolve → cleanup → stream-close\n // continuation cannot race ahead of the write.\n subscribe('complete', async (result) => {\n await write('complete', result);\n settle();\n });\n subscribe('interrupted', async (result) => {\n await write('interrupted', result);\n settle();\n });\n subscribe('error', async (error: Error) => {\n await write('error', { message: error.message });\n settle();\n });\n\n // RUNTIME-14: on client disconnect, CANCEL the underlying run (not merely stop writing) and\n // unblock `done` so the finally teardown runs — otherwise `done` would never resolve and the\n // listeners leak.\n stream.onAbort(() => onClientAbort(session, onFailure, settle));\n\n return done;\n}\n\n/**\n * The abort path, alone, because every clause of it is load-bearing and review shaped each one.\n *\n * `settle` in a `finally`: an `abort()` that throws used to cost a listener leak, and with the\n * claim registry it costs the SESSION — `done` never resolves, the teardown never runs, the claim\n * is held forever, and every future /submit is 409.\n *\n * The throw is REPORTED, not rethrown: this handler runs inside Hono's abort dispatch, OUTSIDE the\n * relay's try/catch, so a rethrow is an unhandled rejection rather than a reported failure. The\n * detail goes where every other stream failure's detail goes.\n */\nfunction onClientAbort(\n session: IHttpTransportSession,\n onFailure: TStreamFailureListener | undefined,\n settle: () => void,\n): void {\n try {\n session.abort();\n } catch (error) {\n // allow-fallback: an abort that throws is the HOST's news, not the runner's\n try {\n onFailure?.(error instanceof Error ? error : new Error(String(error)));\n } catch {\n // allow-fallback: a listener that throws must not replace the abort path's settle\n // Same rule as reportStreamFailure: the host's listener failing is the host's to see.\n }\n } finally {\n settle();\n }\n}\n\n/**\n * Teardown that cannot take the claim with it.\n *\n * Each entry individually, and review is why: these are `session.off` calls, and one that throws\n * inside a bare loop would end the caller's `finally` before `release()` ran — the same\n * claim-held-forever the abort path closes, reintroduced two lines down. A failed unsubscribe\n * forfeits one listener; taking the release with it forfeits the session.\n */\nfunction teardown(cleanup: Array<() => void>, release: () => void): void {\n for (const fn of cleanup) {\n try {\n fn();\n } catch {\n // allow-fallback: a failed unsubscribe must not take the claim release with it\n // The listener stays attached — the lesser loss, and the one the next turn can survive.\n }\n }\n // RUNTIME-38: released here for the same reason — a turn that throws must not wedge the session\n // it claimed.\n release();\n}\n\n/**\n * The `streamSSE` callback for one submitted prompt.\n *\n * `release` is called in the teardown, ALWAYS — on completion, on error, and on client disconnect.\n * It is passed in rather than taken here because the claim is made before the stream opens: a claim\n * whose release lives only inside the stream is a lock that outlives the request that took it.\n * (This block sat on `wireRelay` for one round after the split stranded it — the stale-doc shape\n * this file keeps writing about, caught doing it.)\n */\nexport function relayTurn(\n session: IHttpTransportSession,\n prompt: string,\n release: () => void,\n onFailure?: TStreamFailureListener,\n): (stream: SSEStreamingApi) => Promise<void> {\n return async (stream) => {\n // NOTHING may escape this callback, and the reason is measured rather than stylistic. Hono's\n // `streamSSE` runner calls its `onError` argument and then UNCONDITIONALLY writes\n // `event: error, data: e.message` to the stream — so an escaped exception reaches the client\n // verbatim no matter what the handler withheld. The probe that found it saw TWO error events:\n // this module's generic line, then Hono's raw one. The only place the trust boundary can be\n // held is here, before the throw reaches the runner at all.\n try {\n // The inner `try` opens BEFORE the wiring: a throw from `session.on` inside `wireRelay`\n // leaves the session claimed, and the `finally` is what releases it — opened later, every\n // later request gets 409 forever.\n const cleanup: Array<() => void> = [];\n try {\n const done = wireRelay(session, stream, cleanup, onFailure);\n await session.submit(prompt);\n await done;\n } finally {\n // RUNTIME-14: teardown ALWAYS runs — on completion, error, OR client disconnect — so the\n // session event listeners can never leak, and the claim always comes back.\n teardown(cleanup, release);\n }\n } catch (error) {\n await reportStreamFailure(\n error instanceof Error ? error : new Error(String(error)),\n stream,\n onFailure,\n );\n }\n };\n}\n\n/**\n * What to tell a client whose stream failed AFTER the response headers were sent.\n *\n * A throw at that point cannot become an error status — the client already has a 200 and an open\n * stream. Without this the throw is an UNHANDLED rejection: it left the process silently in a\n * browser and turned the `quality` job red under vitest, which is how it was found.\n *\n * By the time this runs, `relayTurn`'s teardown has removed the listeners and released the claim.\n * This handler owes only the telling.\n *\n * The CLIENT gets a generic line and the HOST gets the detail, and review moved this three times.\n * The first version sent `error.message` verbatim; the second sent it to a package logger imported\n * from `agent-core`, which the layering rule refuses (see `TStreamFailureListener`). What survives\n * both rounds is the boundary itself: an exception escaping the stream callback is not a message\n * anything composed for a client — it can carry provider internals, paths, or stack fragments,\n * exactly what the 500 branch in `routes.ts` withholds at the same boundary.\n *\n * The session's own `error` EVENT is different and stays verbatim in `relayTurn` above: that is the\n * session's client-facing error channel, worded by the session (`humanizeApiError`) and relayed\n * identically by the WS transport. One is a message meant for the client; this one never was.\n */\nexport async function reportStreamFailure(\n error: Error,\n stream: SSEStreamingApi,\n onFailure?: TStreamFailureListener,\n): Promise<void> {\n try {\n onFailure?.(error);\n } catch {\n // allow-fallback: a listener that throws must not take the client's only notification with it\n // The listener is the host's code; its failure is the host's to see, and the write below is the\n // one thing this function owes the client either way.\n }\n await stream\n .writeSSE({\n event: 'error',\n data: JSON.stringify({\n message: 'the stream failed on the server after it opened — the turn may not have run',\n }),\n })\n .catch(() => {\n // allow-fallback: the stream is already gone, which is the one case where there is nobody\n // left to tell. Rethrowing here would restore the unhandled rejection this exists to remove.\n });\n}\n","/**\n * `POST /submit` — the admission decision and the handler that hands an admitted turn to the relay.\n *\n * Split from `routes.ts` under the file-size ceiling, along the same seam the review rounds carved:\n * the route factory is a LIST of routes, and this one carries the concurrency-admission decision\n * plus the claim lifecycle, which is a different job from mounting endpoints.\n */\n\nimport { streamSSE } from 'hono/streaming';\n\nimport { relayTurn } from './submit-stream.js';\n\nimport type { IHttpTransportSession } from './http-session.js';\nimport type { TStreamFailureListener } from './submit-stream.js';\nimport type { ITurnClaims } from './turn-claims.js';\nimport type { Context } from 'hono';\n\n/**\n * Callback that resolves an HTTP session port from the request context.\n *\n * It need NOT return the same object twice for the same logical session. It briefly did: `/submit`\n * keyed its concurrent-turn claim on object identity, so a factory building a fresh wrapper per\n * call — a proxy, an adapter, a `{...session}` copy — defeated the guard in silence. The first\n * answer was to document that as a requirement callers had to keep, and a requirement neither the\n * type system nor a test can check is not a contract, it is a hope.\n *\n * What the session already promises is enough. `getSession(): { getSessionId(): string }` names the\n * session, the claim is keyed by that name, and the requirement is gone rather than written down.\n *\n * The session must therefore BE nameable. `/submit` refuses with 500 when `getSessionId()` returns\n * nothing, because without an id the concurrent-turn guarantee does not exist and serving anyway\n * would hand back the bug to whoever could least tell. The contract types that method as returning\n * a `string`, so a conformant session never meets it.\n *\n * (Review moved this block here: it sat on the RE-EXPORT in `routes.ts` after the split, where the\n * person editing the definition would never see it.)\n */\nexport type TSessionFactory = (\n c: Context,\n) => IHttpTransportSession | Promise<IHttpTransportSession>;\n\n/**\n * Admit this request to ONE turn on its session, or answer why not.\n *\n * Returns the claim key it HOLDS on success — the caller owes its release — or the refusal\n * Response. A named unit, and review is why: the admission decision (nameable? busy? claim) is what\n * this route decides, independently testable from the stream wiring it hands the turn to.\n */\nfunction admitTurn(\n c: Context,\n session: IHttpTransportSession,\n claims: ITurnClaims,\n): Response | { claim: string } {\n // RUNTIME-38: the session is single-threaded (one turn at a time) and shared across requests, so a\n // concurrent /submit would cross-subscribe to the same emitter and interleave two clients' events.\n //\n // The route CLAIMS the turn rather than asking whether one is running, and that difference is the\n // whole fix. `session.isExecuting()` is set inside `submit()` past an `await ensureInitialized()`\n // — an unconditional suspension point — so two requests both read `false`, both call `submit`, and\n // the loser coalesces into the pending queue while its HTTP response streams back the WINNER'S\n // events. One turn delivered to two clients as if each had asked for it, which is worse than the\n // race the earlier comment described and then wrongly declared absent.\n //\n // A synchronous flag on the route closes it because there is no suspension point between reading\n // and setting it. It is released in the stream's `finally`, so a turn that throws does not leave\n // the route wedged.\n //\n // BOTH are asked because neither subsumes the other. The claim is what this ROUTE knows;\n // `isExecuting()` is what the SESSION knows, including a turn started by another surface — the\n // TUI, a WS client, a previous process — which the claim cannot see.\n // A session that cannot name itself is REFUSED, not served racily. The busy check is a guarantee\n // only while the claim is keyed by a real id: with no id it falls back to `isExecuting()` alone,\n // which the comment above documents as the racy read this route exists to stop relying on.\n // Serving anyway would degrade the fix back into the bug for exactly the callers who could not\n // be told they were affected.\n //\n // `getSession(): { getSessionId(): string }` is required by the contract, so this is unreachable\n // for a conformant session. It is a 500 rather than a 503: the session is not temporarily\n // unavailable, it does not meet the contract this route is built on, which is a defect on the\n // server side of the boundary and not a condition that clears on retry.\n const claim = claims.keyFor(session);\n if (claim === undefined) {\n return c.json(\n {\n // No internal method signature: this route can be mounted outside a trust boundary, and\n // the caller cannot act on `getSession().getSessionId()` anyway — it names a contract\n // they do not implement. The HOST needs the detail and gets it from the comment above\n // this branch; the client needs to know its request was refused and why in its own terms.\n error:\n 'concurrent-turn tracking is unavailable for this session, so this request cannot be ' +\n 'served safely. Refusing rather than starting a turn that cannot be guaranteed to be ' +\n 'yours.',\n },\n 500,\n );\n }\n if (claims.isHeld(claim) || session.isExecuting()) {\n return c.json({ error: 'session busy — a turn is already in flight' }, 409);\n }\n claims.hold(claim);\n return { claim };\n}\n\nexport function submitHandler(\n sessionFactory: TSessionFactory,\n claims: ITurnClaims,\n onStreamFailure?: TStreamFailureListener,\n) {\n return async (c: Context) => {\n const session = await sessionFactory(c);\n const body = await c.req.json<{ prompt: string }>();\n\n if (!body.prompt || typeof body.prompt !== 'string') {\n return c.json({ error: 'prompt is required' }, 400);\n }\n\n const admitted = admitTurn(c, session, claims);\n if (admitted instanceof Response) {\n return admitted;\n }\n const { claim } = admitted;\n // SINGLE-SHOT, and review traced the double-release it prevents: the relay's teardown releases\n // this claim on the normal path, and if a future Hono ever rejected the outer promise AFTER the\n // callback completed, the catch below would release the SAME KEY a second time — by which point\n // another request may hold it, and the second release would free that request's claim, which is\n // the cross-talk this registry exists to prevent. A release that has happened is not a release\n // that can happen again.\n let released = false;\n const releaseOnce = (): void => {\n if (!released) {\n released = true;\n claims.release(claim);\n }\n };\n\n // The claim is taken OUTSIDE the callback, so its release cannot live only in the callback's\n // `finally` — a claim whose release is not in the same protected region is a lock, not a claim,\n // which this file states one level in. If `streamSSE` throws before it ever runs the callback,\n // this releases and rethrows; the callback's own `finally` covers everything after it starts.\n //\n // REPRODUCED at the module boundary: `routes-streamsse-throw.test.ts` mocks `hono/streaming`\n // to throw before the callback ever runs and asserts the second request is not 409 — a leaked\n // claim is what this catch exists to prevent. Two rounds shipped it as honestly-labelled\n // unverified code (a throw from `session.on` lands INSIDE the callback, where the inner\n // `finally` releases — measured, a case built that way is green with this catch removed), and\n // review supplied the third option: stub the boundary, not Hono's internals.\n try {\n // NO third argument, deliberately: Hono's runner follows any `onError` by writing the raw\n // `e.message` to the stream, so the only leak-proof shape is a callback nothing escapes —\n // `relayTurn` catches its own failures and reports them generically. An onError here would be\n // dead code that turns into a leak the day it stops being dead.\n // `await`, so the catch below covers a REJECTION as well as a synchronous throw. Today's\n // Hono returns the Response synchronously and only the sync path is real — but review is\n // right that a version returning a rejecting promise would sail past a bare `return`, and\n // the cost of closing that class is one keyword.\n return await streamSSE(c, relayTurn(session, body.prompt, releaseOnce, onStreamFailure));\n } catch (error) {\n releaseOnce();\n throw error;\n }\n };\n}\n","/**\n * RUNTIME-38 — who currently holds the one turn a session can run.\n *\n * Split out of `routes.ts`, which had grown past its size ceiling: routing is one job and deciding\n * whether a second turn may start on a session is another, and the second is the only part of that\n * file with state of its own.\n *\n * PER SESSION, not one flag for the router. `sessionFactory` resolves a session per request (the\n * documented multi-tenant shape), so a single flag made one tenant's turn refuse every other\n * tenant's — a busy neighbour is not a reason to refuse you, and that is a worse defect than the\n * race it closed.\n */\n\nimport type { IHttpTransportSession } from './http-session.js';\n\nexport interface ITurnClaims {\n /** The key this session is claimed under, or `undefined` when it will not name itself. */\n keyFor(session: IHttpTransportSession): string | undefined;\n isHeld(key: string): boolean;\n hold(key: string): void;\n release(key: string): void;\n}\n\n/**\n * A claim registry keyed by the session's declared ID, not by object identity.\n *\n * Keying on the OBJECT makes identity-stability a requirement of every caller that nothing can\n * check: a `sessionFactory` returning a fresh wrapper per call for the same logical session — a\n * proxy, an adapter, a spread copy — defeats the guard in silence, and every request looks\n * unclaimed. `getSession(): { getSessionId(): string }` already names the session, so asking for the\n * id turns an unenforceable requirement into no requirement at all.\n *\n * A claim is released in the caller's `finally`, so this does not grow with the number of sessions\n * the host has ever served — which is what weak keying would otherwise buy.\n */\nexport function createTurnClaims(): ITurnClaims {\n const held = new Set<string>();\n\n return {\n keyFor(session) {\n try {\n // No `?.`: `getSession(): { getSessionId(): string }` is non-nullable, and optional chaining\n // here would suggest the contract allows an absent session when it does not. A session that\n // breaks the contract anyway is caught below.\n const id = session.getSession().getSessionId();\n return typeof id === 'string' && id !== '' ? id : undefined;\n } catch {\n // allow-fallback: an unnameable session must not be guessed at\n // A session that throws while naming itself has not told us who it is, and guessing would\n // claim the wrong turn. The CALLER refuses on `undefined`, so nothing is swallowed here.\n //\n // `undefined` rather than a placeholder — a shared fallback key would collide every\n // unnameable session into one claim and refuse them all as each other's neighbours. There is\n // no `isExecuting()` fallback on the submit path, and an earlier comment said there was.\n return undefined;\n }\n },\n isHeld: (key) => held.has(key),\n hold: (key) => void held.add(key),\n release: (key) => void held.delete(key),\n };\n}\n","/**\n * HTTP transport adapter — exposes the declared session capabilities over REST API.\n *\n * Built on Hono for Cloudflare Workers + Node.js + AWS Lambda compatibility.\n * Exposes the core session methods (a subset; background-task, job-group, and\n * execution-workspace methods are WS-only).\n */\n\nimport {\n bearerCredential,\n credentialMatches,\n resolveAdmission,\n} from '@robota-sdk/agent-transport/node';\nimport { Hono } from 'hono';\n\nimport { submitHandler } from './submit-route.js';\nimport { createTurnClaims } from './turn-claims.js';\n\nimport type { TSessionFactory } from './submit-route.js';\nimport type { TStreamFailureListener } from './submit-stream.js';\nimport type {\n ITransportAdmission,\n ITransportAdmissionConfig,\n} from '@robota-sdk/agent-interface-transport';\n\n// Re-exported so existing importers keep their path; the definition and its rationale live with\n// the code that enforces them, in `submit-route.ts`.\nexport type { TSessionFactory } from './submit-route.js';\n\nexport interface IAgentRoutesOptions {\n /** Resolve an HTTP session port per request (e.g., by auth token, session ID). */\n sessionFactory: TSessionFactory;\n /**\n * Where the DETAIL of a post-headers stream failure goes (the client gets only a generic line —\n * see `submit-stream.ts`). Injected per the side-concern rule: the host decides the destination,\n * and absent means the host chose to drop it.\n */\n onStreamFailure?: TStreamFailureListener;\n /**\n * SEC-008: what a peer must present to reach the session. REQUIRED — there is no shape of this\n * option that means \"I did not think about it\", which is the state these routes shipped in.\n *\n * `{ open: true, openReason: '…' }` still runs with no credential, and that is a legitimate answer\n * for a host that has its own boundary in front. It just has to be written down.\n */\n admission: ITransportAdmissionConfig | ITransportAdmission;\n}\n\n/**\n * Create a Hono router with all agent HTTP endpoints.\n *\n * Usage:\n * ```typescript\n * const routes = createAgentRoutes({ sessionFactory });\n * app.route('/agent', routes); // mount on existing app\n * export default routes; // or use standalone (CF Workers)\n * ```\n */\nexport function createAgentRoutes(options: IAgentRoutesOptions): Hono {\n const { sessionFactory, onStreamFailure } = options;\n const app = new Hono();\n\n // RUNTIME-38: one turn at a time, per session — `turn-claims.ts` owns what that means and why it\n // is keyed by the session's declared ID rather than by object identity.\n const claims = createTurnClaims();\n\n // SEC-008: resolved ONCE, at construction, so a transport that cannot mint a credential fails to\n // build rather than serving without one. Resolving per request would also mint a new token per\n // request, which no peer could ever present.\n // Either shape goes in: `resolveAdmission` is idempotent, so an already-resolved admission comes\n // back unchanged and a config is resolved. `http-transport.ts` therefore does not have to take\n // its resolved admission apart and rebuild a config for this to resolve again — two resolutions\n // of one decision, and a mint on the second if the first had opened without a reason (review).\n //\n // This used to pick between the two with `'token' in options.admission`, and review showed that\n // cannot work: BOTH interfaces declare a `token`, so the shapes differ only by VALUE. A config of\n // `{ token: '' }` — documented as \"mint a fresh one\" — was read as pre-resolved and installed the\n // EMPTY STRING as the required credential, which a peer sending an empty bearer would match. The\n // discriminator is gone rather than repaired; there is nothing here left to get wrong.\n const admission = resolveAdmission(options.admission);\n\n /**\n * The trust boundary, installed BEFORE every route rather than checked inside each one.\n *\n * Before this, `POST /submit` reached `session.submit` and `POST /command` reached\n * `session.executeCommand` with nothing in between — remote arbitrary execution with no gate, and\n * an unauthenticated request looked exactly like an authorised one in both directions.\n *\n * A missing credential and a wrong one get the same answer, deliberately: telling them apart tells\n * a caller which half they got right.\n */\n app.use('*', async (c, next) => {\n if (admission.token === null) return next();\n if (credentialMatches(admission.token, bearerCredential(c.req.header('authorization')))) {\n return next();\n }\n return c.json({ error: 'unauthorized' }, 401);\n });\n\n // POST /submit — execute prompt, stream events via SSE\n app.post('/submit', submitHandler(sessionFactory, claims, onStreamFailure));\n\n // POST /command — execute system command\n app.post('/command', async (c) => {\n const session = await sessionFactory(c);\n const body = await c.req.json<{ name: string; args?: string }>();\n\n if (!body.name || typeof body.name !== 'string') {\n return c.json({ error: 'name is required' }, 400);\n }\n\n // SEC-008: 'remote', not the default 'user'. A peer over HTTP is not the person at the keyboard,\n // and defaulting to the local operator both mis-attributes the call and skips the 'remote' policy\n // seam that exists to treat the two differently. Admission decided WHO may reach the session; it\n // does not say who they are. (The MCP adapter had the same defect; this is its sibling.)\n const result = await session.executeCommand(body.name, body.args ?? '', 'remote');\n if (!result) {\n return c.json({ error: `Unknown command: ${body.name}` }, 404);\n }\n return c.json(result);\n });\n\n // POST /abort — abort current execution\n app.post('/abort', async (c) => {\n const session = await sessionFactory(c);\n session.abort();\n return c.json({ ok: true });\n });\n\n // POST /cancel-queue — cancel queued prompt\n app.post('/cancel-queue', async (c) => {\n const session = await sessionFactory(c);\n session.cancelQueue();\n return c.json({ ok: true });\n });\n\n // GET /messages — get message history\n app.get('/messages', async (c) => {\n const session = await sessionFactory(c);\n return c.json(session.getMessages());\n });\n\n // GET /context — get context window state\n app.get('/context', async (c) => {\n const session = await sessionFactory(c);\n return c.json(session.getContextState());\n });\n\n // GET /executing — check if currently executing\n //\n // Reports the SAME \"busy\" that `/submit` refuses on: the route's own claim OR the session's\n // `isExecuting()`. Asking only the session lets a client polling here see `executing: false` and\n // still get a 409 from `/submit`, and two endpoints disagreeing about one word is a worse answer\n // than either of them alone.\n app.get('/executing', async (c) => {\n const session = await sessionFactory(c);\n const claim = claims.keyFor(session);\n const claimed = claim !== undefined && claims.isHeld(claim);\n return c.json({ executing: claimed || session.isExecuting() });\n });\n\n // GET /pending — get pending queued prompt\n app.get('/pending', async (c) => {\n const session = await sessionFactory(c);\n return c.json({ pending: session.getPendingPrompt() });\n });\n\n return app;\n}\n","/**\n * ITransportAdapter implementation for HTTP transport.\n *\n * Wraps createAgentRoutes into the unified ITransportAdapter interface\n * while exposing the underlying Hono app via getApp().\n */\n\nimport { resolveAdmission } from '@robota-sdk/agent-transport/node';\nimport { Hono } from 'hono';\n\nimport { createAgentRoutes } from './routes.js';\n\nimport type { IHttpTransportSession } from './http-session.js';\nimport type { TStreamFailureListener } from './submit-stream.js';\nimport type {\n ITransportAdapter,\n ITransportAdmissionConfig,\n ITransportLifecycleError,\n} from '@robota-sdk/agent-interface-transport';\n\nexport interface IHttpTransportOptions {\n /** Optional: base path prefix for routes. */\n basePath?: string;\n /**\n * SEC-008: what a peer must present. Omitted means SECURE — a credential is minted and\n * `getAdmissionToken()` returns it for the host to hand to its client.\n *\n * This transport previously had no gate at all, so omitting the option used to mean \"anyone may\n * execute anything\". Omission now means the safe thing, and running open takes saying so.\n */\n admission?: ITransportAdmissionConfig;\n /**\n * Where the DETAIL of a post-headers stream failure goes — forwarded to `createAgentRoutes`.\n * Review found this seam missing: the option existed on the routes and not on the entry point\n * README and the examples actually use, so \"the host decides the destination\" was a decision no\n * host on this path could make. Same forwarding rule as `admission`, which sat beside it.\n */\n onStreamFailure?: TStreamFailureListener;\n}\n\nexport interface IHttpTransport extends ITransportAdapter<IHttpTransportSession> {\n getApp(): Hono;\n getAdmissionToken(): string | null;\n}\n\nexport function createHttpTransport(options?: IHttpTransportOptions): IHttpTransport {\n let session: IHttpTransportSession | null = null;\n let app: Hono | null = null;\n // Resolved at CONSTRUCTION, not at start: a host needs the credential to hand to its client, and\n // a transport that cannot mint one must fail before anything is served.\n const admission = resolveAdmission(options?.admission);\n const lifecycleError = (code: ITransportLifecycleError['code']): ITransportLifecycleError =>\n Object.assign(new Error(`HTTP transport ${code}.`), {\n name: 'TransportLifecycleError' as const,\n code,\n transportName: 'http',\n });\n\n return {\n name: 'http',\n lifecycle: Object.freeze({ kind: 'service' }),\n attach(s: IHttpTransportSession) {\n session = s;\n },\n async start() {\n if (!session) throw lifecycleError('not-attached');\n if (app) throw lifecycleError('already-started');\n const routes = createAgentRoutes({\n sessionFactory: () => session!,\n // The decision already made, passed through — not taken apart and rebuilt for the routes to\n // resolve a second time.\n admission,\n onStreamFailure: options?.onStreamFailure,\n });\n // TRANS-002 (issue #2480): `basePath` was declared and advertised but never read, so routes\n // always mounted at root. It is honored here — or absent, in which case the routes ARE the app.\n app = options?.basePath ? new Hono().route(options.basePath, routes) : routes;\n },\n async stop() {\n app = null;\n session = null;\n },\n getApp() {\n if (!app) throw new Error('Transport not started. Call start() first.');\n return app;\n },\n /** The credential this transport requires, or `null` when the host explicitly opened it. */\n getAdmissionToken() {\n return admission.token;\n },\n };\n}\n"],"mappings":"wLAqCA,SAAS,EACP,EACA,EACA,EACA,EACe,CACf,IAAM,GAAgB,EAAe,IAAqC,CACxE,EAAQ,GAAG,EAAuB,CAAqB,EACvD,EAAQ,SAAW,EAAQ,IAAI,EAAuB,CAAqB,CAAC,CAC9E,EAIM,GAAS,EAAe,IAC5B,EAAO,SAAS,CAAE,QAAO,KAAM,KAAK,UAAU,CAAI,CAAE,CAAC,CAAC,CAAC,UAAY,CAGnE,CAAC,EAEC,EACE,EAAO,IAAI,QAAe,GAAY,CAC1C,EAAS,CACX,CAAC,EA2BD,OAzBA,EAAU,aAAe,GAAkB,KAAK,EAAM,aAAc,CAAE,OAAM,CAAC,CAAC,EAC9E,EAAU,aAAe,GAAU,KAAK,EAAM,aAAc,CAAK,CAAC,EAClE,EAAU,WAAa,GAAU,KAAK,EAAM,WAAY,CAAK,CAAC,EAC9D,EAAU,WAAa,GAAwB,KAAK,EAAM,WAAY,CAAE,YAAW,CAAC,CAAC,EAIrF,EAAU,WAAY,KAAO,IAAW,CACtC,MAAM,EAAM,WAAY,CAAM,EAC9B,EAAO,CACT,CAAC,EACD,EAAU,cAAe,KAAO,IAAW,CACzC,MAAM,EAAM,cAAe,CAAM,EACjC,EAAO,CACT,CAAC,EACD,EAAU,QAAS,KAAO,IAAiB,CACzC,MAAM,EAAM,QAAS,CAAE,QAAS,EAAM,OAAQ,CAAC,EAC/C,EAAO,CACT,CAAC,EAKD,EAAO,YAAc,EAAc,EAA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MAAM,EAAe,CAAC,EACtC,OAAO,EAAE,KAAK,CAAE,QAAS,EAAQ,iBAAiB,CAAE,CAAC,CACvD,CAAC,EAEM,CACT,CC3HA,SAAgB,EAAoB,EAAiD,CACnF,IAAI,EAAwC,KACxC,EAAmB,KAGjB,EAAY,EAAiB,GAAS,SAAS,EAC/C,EAAkB,GACtB,OAAO,OAAW,MAAM,kBAAkB,EAAK,EAAE,EAAG,CAClD,KAAM,0BACN,OACA,cAAe,MACjB,CAAC,EAEH,MAAO,CACL,KAAM,OACN,UAAW,OAAO,OAAO,CAAE,KAAM,SAAU,CAAC,EAC5C,OAAO,EAA0B,CAC/B,EAAU,CACZ,EACA,MAAM,OAAQ,CACZ,GAAI,CAAC,EAAS,MAAM,EAAe,cAAc,EACjD,GAAI,EAAK,MAAM,EAAe,iBAAiB,EAC/C,IAAM,EAAS,EAAkB,CAC/B,mBAAsB,EAGtB,YACA,gBAAiB,GAAS,eAC5B,CAAC,EAGD,EAAM,GAAS,SAAW,IAAI,EAAK,CAAC,CAAC,MAAM,EAAQ,SAAU,CAAM,EAAI,CACzE,EACA,MAAM,MAAO,CACX,EAAM,KACN,EAAU,IACZ,EACA,QAAS,CACP,GAAI,CAAC,EAAK,MAAU,MAAM,4CAA4C,EACtE,OAAO,CACT,EAEA,mBAAoB,CAClB,OAAO,EAAU,KACnB,CACF,CACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/submit-stream.ts","../../src/submit-route.ts","../../src/turn-claims.ts","../../src/routes.ts","../../src/http-transport.ts"],"sourcesContent":["/**\n * RUNTIME-14 / RUNTIME-38 — relaying ONE turn to an SSE client, and letting go of it afterwards.\n *\n * Split out of `routes.ts` under the file-size ceiling. The route's job is to decide whether this\n * request may start a turn; relaying the turn's events, tearing the subscriptions down, and telling\n * a client whose stream broke after the headers went out is a different job with its own failure\n * modes, and it was four fifths of the handler.\n */\n\nimport type { IHttpTransportSession } from './http-session.js';\nimport type { SSEStreamingApi } from 'hono/streaming';\n\n/**\n * Where the DETAIL of a post-headers stream failure goes — injected, never imported.\n *\n * The first version imported `createLogger` from `agent-core`, and review held it against two\n * authorities at once: `project-structure.md` declares this package contract-pure (transports\n * depend on the contracts and the protocol, nothing else), and its side-concern rule says a logging\n * destination \"must be injected, not imported directly\". The host that mounts this router decides\n * where diagnostics go; a module-level singleton decided it for every host, with no override.\n *\n * Absent, the detail is dropped — by the HOST's explicit default, which is a different thing from\n * this module deleting it: the client still learns the stream failed, and the host was offered the\n * detail at the boundary where it mounts the route.\n */\nexport type TStreamFailureListener = (error: Error) => void;\n\n/**\n * Wire every relay subscription and the abort path; answer with the promise that settles when the\n * turn is over (or refused one).\n *\n * The subscriptions are wired OUTSIDE the promise executor. Inside it, a throw from `session.on` —\n * a bad handler, an EventEmitter listener cap — is caught by the Promise constructor and becomes an\n * already-rejected `done` instead of propagating. Execution then reaches `await session.submit`, so\n * a REAL TURN is consumed with only some of its listeners attached and nothing to relay it, and the\n * rejection surfaces afterwards at `await done` — by which point the turn is gone.\n */\nfunction wireRelay(\n session: IHttpTransportSession,\n stream: SSEStreamingApi,\n cleanup: Array<() => void>,\n onFailure: TStreamFailureListener | undefined,\n): Promise<void> {\n const subscribe = <T>(event: string, handler: (data: T) => void): void => {\n session.on(event as 'text_delta', handler as () => void);\n cleanup.push(() => session.off(event as 'text_delta', handler as () => void));\n };\n\n // RUNTIME-14: await + catch every SSE write so a write to a client-closed stream is a blessed\n // no-op, not an unhandled rejection (post-headers errors bypass Hono's onError).\n const write = (event: string, data: unknown): Promise<void> =>\n stream.writeSSE({ event, data: JSON.stringify(data) }).catch(() => {\n // allow-fallback: client closed the stream mid-write — nothing to deliver; the finally teardown\n // (RUNTIME-14) removes the listeners, so this write has nothing left to do.\n });\n\n let settle!: () => void;\n const done = new Promise<void>((resolve) => {\n settle = resolve;\n });\n\n subscribe('text_delta', (delta: string) => void write('text_delta', { delta }));\n subscribe('tool_start', (state) => void write('tool_start', state));\n subscribe('tool_end', (state) => void write('tool_end', state));\n subscribe('thinking', (isThinking: boolean) => void write('thinking', { isThinking }));\n\n // Flush the terminal event before resolving, so the resolve → cleanup → stream-close\n // continuation cannot race ahead of the write.\n subscribe('complete', async (result) => {\n await write('complete', result);\n settle();\n });\n subscribe('interrupted', async (result) => {\n await write('interrupted', result);\n settle();\n });\n subscribe('error', async (error: Error) => {\n await write('error', { message: error.message });\n settle();\n });\n\n // RUNTIME-14: on client disconnect, CANCEL the underlying run (not merely stop writing) and\n // unblock `done` so the finally teardown runs — otherwise `done` would never resolve and the\n // listeners leak.\n stream.onAbort(() => onClientAbort(session, onFailure, settle));\n\n return done;\n}\n\n/**\n * The abort path, alone, because every clause of it is load-bearing and review shaped each one.\n *\n * `settle` in a `finally`: an `abort()` that throws used to cost a listener leak, and with the\n * claim registry it costs the SESSION — `done` never resolves, the teardown never runs, the claim\n * is held forever, and every future /submit is 409.\n *\n * The throw is REPORTED, not rethrown: this handler runs inside Hono's abort dispatch, OUTSIDE the\n * relay's try/catch, so a rethrow is an unhandled rejection rather than a reported failure. The\n * detail goes where every other stream failure's detail goes.\n */\nfunction onClientAbort(\n session: IHttpTransportSession,\n onFailure: TStreamFailureListener | undefined,\n settle: () => void,\n): void {\n try {\n session.abort();\n } catch (error) {\n // allow-fallback: an abort that throws is the HOST's news, not the runner's\n try {\n onFailure?.(error instanceof Error ? error : new Error(String(error)));\n } catch {\n // allow-fallback: a listener that throws must not replace the abort path's settle\n // Same rule as reportStreamFailure: the host's listener failing is the host's to see.\n }\n } finally {\n settle();\n }\n}\n\n/**\n * Teardown that cannot take the claim with it.\n *\n * Each entry individually, and review is why: these are `session.off` calls, and one that throws\n * inside a bare loop would end the caller's `finally` before `release()` ran — the same\n * claim-held-forever the abort path closes, reintroduced two lines down. A failed unsubscribe\n * forfeits one listener; taking the release with it forfeits the session.\n */\nfunction teardown(cleanup: Array<() => void>, release: () => void): void {\n for (const fn of cleanup) {\n try {\n fn();\n } catch {\n // allow-fallback: a failed unsubscribe must not take the claim release with it\n // The listener stays attached — the lesser loss, and the one the next turn can survive.\n }\n }\n // RUNTIME-38: released here for the same reason — a turn that throws must not wedge the session\n // it claimed.\n release();\n}\n\n/**\n * The `streamSSE` callback for one submitted prompt.\n *\n * `release` is called in the teardown, ALWAYS — on completion, on error, and on client disconnect.\n * It is passed in rather than taken here because the claim is made before the stream opens: a claim\n * whose release lives only inside the stream is a lock that outlives the request that took it.\n * (This block sat on `wireRelay` for one round after the split stranded it — the stale-doc shape\n * this file keeps writing about, caught doing it.)\n */\nexport function relayTurn(\n session: IHttpTransportSession,\n prompt: string,\n release: () => void,\n onFailure?: TStreamFailureListener,\n): (stream: SSEStreamingApi) => Promise<void> {\n return async (stream) => {\n // NOTHING may escape this callback, and the reason is measured rather than stylistic. Hono's\n // `streamSSE` runner calls its `onError` argument and then UNCONDITIONALLY writes\n // `event: error, data: e.message` to the stream — so an escaped exception reaches the client\n // verbatim no matter what the handler withheld. The probe that found it saw TWO error events:\n // this module's generic line, then Hono's raw one. The only place the trust boundary can be\n // held is here, before the throw reaches the runner at all.\n try {\n // The inner `try` opens BEFORE the wiring: a throw from `session.on` inside `wireRelay`\n // leaves the session claimed, and the `finally` is what releases it — opened later, every\n // later request gets 409 forever.\n const cleanup: Array<() => void> = [];\n try {\n const done = wireRelay(session, stream, cleanup, onFailure);\n await session.submit(prompt);\n await done;\n } finally {\n // RUNTIME-14: teardown ALWAYS runs — on completion, error, OR client disconnect — so the\n // session event listeners can never leak, and the claim always comes back.\n teardown(cleanup, release);\n }\n } catch (error) {\n await reportStreamFailure(\n error instanceof Error ? error : new Error(String(error)),\n stream,\n onFailure,\n );\n }\n };\n}\n\n/**\n * What to tell a client whose stream failed AFTER the response headers were sent.\n *\n * A throw at that point cannot become an error status — the client already has a 200 and an open\n * stream. Without this the throw is an UNHANDLED rejection: it left the process silently in a\n * browser and turned the `quality` job red under vitest, which is how it was found.\n *\n * By the time this runs, `relayTurn`'s teardown has removed the listeners and released the claim.\n * This handler owes only the telling.\n *\n * The CLIENT gets a generic line and the HOST gets the detail, and review moved this three times.\n * The first version sent `error.message` verbatim; the second sent it to a package logger imported\n * from `agent-core`, which the layering rule refuses (see `TStreamFailureListener`). What survives\n * both rounds is the boundary itself: an exception escaping the stream callback is not a message\n * anything composed for a client — it can carry provider internals, paths, or stack fragments,\n * exactly what the 500 branch in `routes.ts` withholds at the same boundary.\n *\n * The session's own `error` EVENT is different and stays verbatim in `relayTurn` above: that is the\n * session's client-facing error channel, worded by the session (`humanizeApiError`) and relayed\n * identically by the WS transport. One is a message meant for the client; this one never was.\n */\nexport async function reportStreamFailure(\n error: Error,\n stream: SSEStreamingApi,\n onFailure?: TStreamFailureListener,\n): Promise<void> {\n try {\n onFailure?.(error);\n } catch {\n // allow-fallback: a listener that throws must not take the client's only notification with it\n // The listener is the host's code; its failure is the host's to see, and the write below is the\n // one thing this function owes the client either way.\n }\n await stream\n .writeSSE({\n event: 'error',\n data: JSON.stringify({\n message: 'the stream failed on the server after it opened — the turn may not have run',\n }),\n })\n .catch(() => {\n // allow-fallback: the stream is already gone, which is the one case where there is nobody\n // left to tell. Rethrowing here would restore the unhandled rejection this exists to remove.\n });\n}\n","/**\n * `POST /submit` — the admission decision and the handler that hands an admitted turn to the relay.\n *\n * Split from `routes.ts` under the file-size ceiling, along the same seam the review rounds carved:\n * the route factory is a LIST of routes, and this one carries the concurrency-admission decision\n * plus the claim lifecycle, which is a different job from mounting endpoints.\n */\n\nimport { streamSSE } from 'hono/streaming';\n\nimport { relayTurn } from './submit-stream.js';\n\nimport type { IHttpTransportSession } from './http-session.js';\nimport type { TStreamFailureListener } from './submit-stream.js';\nimport type { ITurnClaims } from './turn-claims.js';\nimport type { Context } from 'hono';\n\n/**\n * Callback that resolves an HTTP session port from the request context.\n *\n * It need NOT return the same object twice for the same logical session. It briefly did: `/submit`\n * keyed its concurrent-turn claim on object identity, so a factory building a fresh wrapper per\n * call — a proxy, an adapter, a `{...session}` copy — defeated the guard in silence. The first\n * answer was to document that as a requirement callers had to keep, and a requirement neither the\n * type system nor a test can check is not a contract, it is a hope.\n *\n * What the session already promises is enough. `getSession(): { getSessionId(): string }` names the\n * session, the claim is keyed by that name, and the requirement is gone rather than written down.\n *\n * The session must therefore BE nameable. `/submit` refuses with 500 when `getSessionId()` returns\n * nothing, because without an id the concurrent-turn guarantee does not exist and serving anyway\n * would hand back the bug to whoever could least tell. The contract types that method as returning\n * a `string`, so a conformant session never meets it.\n *\n * (Review moved this block here: it sat on the RE-EXPORT in `routes.ts` after the split, where the\n * person editing the definition would never see it.)\n */\nexport type TSessionFactory = (\n c: Context,\n) => IHttpTransportSession | Promise<IHttpTransportSession>;\n\n/**\n * Admit this request to ONE turn on its session, or answer why not.\n *\n * Returns the claim key it HOLDS on success — the caller owes its release — or the refusal\n * Response. A named unit, and review is why: the admission decision (nameable? busy? claim) is what\n * this route decides, independently testable from the stream wiring it hands the turn to.\n */\nfunction admitTurn(\n c: Context,\n session: IHttpTransportSession,\n claims: ITurnClaims,\n): Response | { claim: string } {\n // RUNTIME-38: the session is single-threaded (one turn at a time) and shared across requests, so a\n // concurrent /submit would cross-subscribe to the same emitter and interleave two clients' events.\n //\n // The route CLAIMS the turn rather than asking whether one is running, and that difference is the\n // whole fix. `session.isExecuting()` is set inside `submit()` past an `await ensureInitialized()`\n // — an unconditional suspension point — so two requests both read `false`, both call `submit`, and\n // the loser coalesces into the pending queue while its HTTP response streams back the WINNER'S\n // events. One turn delivered to two clients as if each had asked for it, which is worse than the\n // race the earlier comment described and then wrongly declared absent.\n //\n // A synchronous flag on the route closes it because there is no suspension point between reading\n // and setting it. It is released in the stream's `finally`, so a turn that throws does not leave\n // the route wedged.\n //\n // BOTH are asked because neither subsumes the other. The claim is what this ROUTE knows;\n // `isExecuting()` is what the SESSION knows, including a turn started by another surface — the\n // TUI, a WS client, a previous process — which the claim cannot see.\n // A session that cannot name itself is REFUSED, not served racily. The busy check is a guarantee\n // only while the claim is keyed by a real id: with no id it falls back to `isExecuting()` alone,\n // which the comment above documents as the racy read this route exists to stop relying on.\n // Serving anyway would degrade the fix back into the bug for exactly the callers who could not\n // be told they were affected.\n //\n // `getSession(): { getSessionId(): string }` is required by the contract, so this is unreachable\n // for a conformant session. It is a 500 rather than a 503: the session is not temporarily\n // unavailable, it does not meet the contract this route is built on, which is a defect on the\n // server side of the boundary and not a condition that clears on retry.\n const claim = claims.keyFor(session);\n if (claim === undefined) {\n return c.json(\n {\n // No internal method signature: this route can be mounted outside a trust boundary, and\n // the caller cannot act on `getSession().getSessionId()` anyway — it names a contract\n // they do not implement. The HOST needs the detail and gets it from the comment above\n // this branch; the client needs to know its request was refused and why in its own terms.\n error:\n 'concurrent-turn tracking is unavailable for this session, so this request cannot be ' +\n 'served safely. Refusing rather than starting a turn that cannot be guaranteed to be ' +\n 'yours.',\n },\n 500,\n );\n }\n if (claims.isHeld(claim) || session.isExecuting()) {\n return c.json({ error: 'session busy — a turn is already in flight' }, 409);\n }\n claims.hold(claim);\n return { claim };\n}\n\nexport function submitHandler(\n sessionFactory: TSessionFactory,\n claims: ITurnClaims,\n onStreamFailure?: TStreamFailureListener,\n) {\n return async (c: Context) => {\n const session = await sessionFactory(c);\n const body = await c.req.json<{ prompt: string }>();\n\n if (!body.prompt || typeof body.prompt !== 'string') {\n return c.json({ error: 'prompt is required' }, 400);\n }\n\n // A session still building itself cannot name itself yet, and the claim needs its name. The\n // claim itself is still taken synchronously after this, so two requests that both waited here\n // start one turn between them.\n if (session.whenInitialized !== undefined) {\n try {\n await session.whenInitialized();\n } catch {\n // The reason can name host paths or settings; the client only needs to know it failed.\n return c.json({ error: 'the session could not be started' }, 500);\n }\n }\n\n const admitted = admitTurn(c, session, claims);\n if (admitted instanceof Response) {\n return admitted;\n }\n const { claim } = admitted;\n // SINGLE-SHOT, and review traced the double-release it prevents: the relay's teardown releases\n // this claim on the normal path, and if a future Hono ever rejected the outer promise AFTER the\n // callback completed, the catch below would release the SAME KEY a second time — by which point\n // another request may hold it, and the second release would free that request's claim, which is\n // the cross-talk this registry exists to prevent. A release that has happened is not a release\n // that can happen again.\n let released = false;\n const releaseOnce = (): void => {\n if (!released) {\n released = true;\n claims.release(claim);\n }\n };\n\n // The claim is taken OUTSIDE the callback, so its release cannot live only in the callback's\n // `finally` — a claim whose release is not in the same protected region is a lock, not a claim,\n // which this file states one level in. If `streamSSE` throws before it ever runs the callback,\n // this releases and rethrows; the callback's own `finally` covers everything after it starts.\n //\n // REPRODUCED at the module boundary: `routes-streamsse-throw.test.ts` mocks `hono/streaming`\n // to throw before the callback ever runs and asserts the second request is not 409 — a leaked\n // claim is what this catch exists to prevent. Two rounds shipped it as honestly-labelled\n // unverified code (a throw from `session.on` lands INSIDE the callback, where the inner\n // `finally` releases — measured, a case built that way is green with this catch removed), and\n // review supplied the third option: stub the boundary, not Hono's internals.\n try {\n // NO third argument, deliberately: Hono's runner follows any `onError` by writing the raw\n // `e.message` to the stream, so the only leak-proof shape is a callback nothing escapes —\n // `relayTurn` catches its own failures and reports them generically. An onError here would be\n // dead code that turns into a leak the day it stops being dead.\n // `await`, so the catch below covers a REJECTION as well as a synchronous throw. Today's\n // Hono returns the Response synchronously and only the sync path is real — but review is\n // right that a version returning a rejecting promise would sail past a bare `return`, and\n // the cost of closing that class is one keyword.\n return await streamSSE(c, relayTurn(session, body.prompt, releaseOnce, onStreamFailure));\n } catch (error) {\n releaseOnce();\n throw error;\n }\n };\n}\n","/**\n * RUNTIME-38 — who currently holds the one turn a session can run.\n *\n * Split out of `routes.ts`, which had grown past its size ceiling: routing is one job and deciding\n * whether a second turn may start on a session is another, and the second is the only part of that\n * file with state of its own.\n *\n * PER SESSION, not one flag for the router. `sessionFactory` resolves a session per request (the\n * documented multi-tenant shape), so a single flag made one tenant's turn refuse every other\n * tenant's — a busy neighbour is not a reason to refuse you, and that is a worse defect than the\n * race it closed.\n */\n\nimport type { IHttpTransportSession } from './http-session.js';\n\nexport interface ITurnClaims {\n /** The key this session is claimed under, or `undefined` when it will not name itself. */\n keyFor(session: IHttpTransportSession): string | undefined;\n isHeld(key: string): boolean;\n hold(key: string): void;\n release(key: string): void;\n}\n\n/**\n * A claim registry keyed by the session's declared ID, not by object identity.\n *\n * Keying on the OBJECT makes identity-stability a requirement of every caller that nothing can\n * check: a `sessionFactory` returning a fresh wrapper per call for the same logical session — a\n * proxy, an adapter, a spread copy — defeats the guard in silence, and every request looks\n * unclaimed. `getSession(): { getSessionId(): string }` already names the session, so asking for the\n * id turns an unenforceable requirement into no requirement at all.\n *\n * A claim is released in the caller's `finally`, so this does not grow with the number of sessions\n * the host has ever served — which is what weak keying would otherwise buy.\n */\nexport function createTurnClaims(): ITurnClaims {\n const held = new Set<string>();\n\n return {\n keyFor(session) {\n try {\n // No `?.`: `getSession(): { getSessionId(): string }` is non-nullable, and optional chaining\n // here would suggest the contract allows an absent session when it does not. A session that\n // breaks the contract anyway is caught below.\n const id = session.getSession().getSessionId();\n return typeof id === 'string' && id !== '' ? id : undefined;\n } catch {\n // allow-fallback: an unnameable session must not be guessed at\n // A session that throws while naming itself has not told us who it is, and guessing would\n // claim the wrong turn. The CALLER refuses on `undefined`, so nothing is swallowed here.\n //\n // `undefined` rather than a placeholder — a shared fallback key would collide every\n // unnameable session into one claim and refuse them all as each other's neighbours. There is\n // no `isExecuting()` fallback on the submit path, and an earlier comment said there was.\n return undefined;\n }\n },\n isHeld: (key) => held.has(key),\n hold: (key) => void held.add(key),\n release: (key) => void held.delete(key),\n };\n}\n","/**\n * HTTP transport adapter — exposes the declared session capabilities over REST API.\n *\n * Built on Hono for Cloudflare Workers + Node.js + AWS Lambda compatibility.\n * Exposes the core session methods (a subset; background-task, job-group, and\n * execution-workspace methods are WS-only).\n */\n\nimport {\n bearerCredential,\n credentialMatches,\n resolveAdmission,\n} from '@robota-sdk/agent-transport/node';\nimport { Hono } from 'hono';\n\nimport { submitHandler } from './submit-route.js';\nimport { createTurnClaims } from './turn-claims.js';\n\nimport type { TSessionFactory } from './submit-route.js';\nimport type { TStreamFailureListener } from './submit-stream.js';\nimport type {\n ITransportAdmission,\n ITransportAdmissionConfig,\n} from '@robota-sdk/agent-interface-transport';\n\n// Re-exported so existing importers keep their path; the definition and its rationale live with\n// the code that enforces them, in `submit-route.ts`.\nexport type { TSessionFactory } from './submit-route.js';\n\nexport interface IAgentRoutesOptions {\n /** Resolve an HTTP session port per request (e.g., by auth token, session ID). */\n sessionFactory: TSessionFactory;\n /**\n * Where the DETAIL of a post-headers stream failure goes (the client gets only a generic line —\n * see `submit-stream.ts`). Injected per the side-concern rule: the host decides the destination,\n * and absent means the host chose to drop it.\n */\n onStreamFailure?: TStreamFailureListener;\n /**\n * SEC-008: what a peer must present to reach the session. REQUIRED — there is no shape of this\n * option that means \"I did not think about it\", which is the state these routes shipped in.\n *\n * `{ open: true, openReason: '…' }` still runs with no credential, and that is a legitimate answer\n * for a host that has its own boundary in front. It just has to be written down.\n */\n admission: ITransportAdmissionConfig | ITransportAdmission;\n}\n\n/**\n * Create a Hono router with all agent HTTP endpoints.\n *\n * Usage:\n * ```typescript\n * const routes = createAgentRoutes({ sessionFactory });\n * app.route('/agent', routes); // mount on existing app\n * export default routes; // or use standalone (CF Workers)\n * ```\n */\nexport function createAgentRoutes(options: IAgentRoutesOptions): Hono {\n const { sessionFactory, onStreamFailure } = options;\n const app = new Hono();\n\n // RUNTIME-38: one turn at a time, per session — `turn-claims.ts` owns what that means and why it\n // is keyed by the session's declared ID rather than by object identity.\n const claims = createTurnClaims();\n\n // SEC-008: resolved ONCE, at construction, so a transport that cannot mint a credential fails to\n // build rather than serving without one. Resolving per request would also mint a new token per\n // request, which no peer could ever present.\n // Either shape goes in: `resolveAdmission` is idempotent, so an already-resolved admission comes\n // back unchanged and a config is resolved. `http-transport.ts` therefore does not have to take\n // its resolved admission apart and rebuild a config for this to resolve again — two resolutions\n // of one decision, and a mint on the second if the first had opened without a reason (review).\n //\n // This used to pick between the two with `'token' in options.admission`, and review showed that\n // cannot work: BOTH interfaces declare a `token`, so the shapes differ only by VALUE. A config of\n // `{ token: '' }` — documented as \"mint a fresh one\" — was read as pre-resolved and installed the\n // EMPTY STRING as the required credential, which a peer sending an empty bearer would match. The\n // discriminator is gone rather than repaired; there is nothing here left to get wrong.\n const admission = resolveAdmission(options.admission);\n\n /**\n * The trust boundary, installed BEFORE every route rather than checked inside each one.\n *\n * Before this, `POST /submit` reached `session.submit` and `POST /command` reached\n * `session.executeCommand` with nothing in between — remote arbitrary execution with no gate, and\n * an unauthenticated request looked exactly like an authorised one in both directions.\n *\n * A missing credential and a wrong one get the same answer, deliberately: telling them apart tells\n * a caller which half they got right.\n */\n app.use('*', async (c, next) => {\n if (admission.token === null) return next();\n if (credentialMatches(admission.token, bearerCredential(c.req.header('authorization')))) {\n return next();\n }\n return c.json({ error: 'unauthorized' }, 401);\n });\n\n // POST /submit — execute prompt, stream events via SSE\n app.post('/submit', submitHandler(sessionFactory, claims, onStreamFailure));\n\n // POST /command — execute system command\n app.post('/command', async (c) => {\n const session = await sessionFactory(c);\n const body = await c.req.json<{ name: string; args?: string }>();\n\n if (!body.name || typeof body.name !== 'string') {\n return c.json({ error: 'name is required' }, 400);\n }\n\n // SEC-008: 'remote', not the default 'user'. A peer over HTTP is not the person at the keyboard,\n // and defaulting to the local operator both mis-attributes the call and skips the 'remote' policy\n // seam that exists to treat the two differently. Admission decided WHO may reach the session; it\n // does not say who they are. (The MCP adapter had the same defect; this is its sibling.)\n const result = await session.executeCommand(body.name, body.args ?? '', 'remote');\n if (!result) {\n return c.json({ error: `Unknown command: ${body.name}` }, 404);\n }\n return c.json(result);\n });\n\n // POST /abort — abort current execution\n app.post('/abort', async (c) => {\n const session = await sessionFactory(c);\n session.abort();\n return c.json({ ok: true });\n });\n\n // POST /cancel-queue — cancel queued prompt\n app.post('/cancel-queue', async (c) => {\n const session = await sessionFactory(c);\n session.cancelQueue();\n return c.json({ ok: true });\n });\n\n // GET /messages — get message history\n app.get('/messages', async (c) => {\n const session = await sessionFactory(c);\n return c.json(session.getMessages());\n });\n\n // GET /context — get context window state\n app.get('/context', async (c) => {\n const session = await sessionFactory(c);\n return c.json(session.getContextState());\n });\n\n // GET /executing — check if currently executing\n //\n // Reports the SAME \"busy\" that `/submit` refuses on: the route's own claim OR the session's\n // `isExecuting()`. Asking only the session lets a client polling here see `executing: false` and\n // still get a 409 from `/submit`, and two endpoints disagreeing about one word is a worse answer\n // than either of them alone.\n app.get('/executing', async (c) => {\n const session = await sessionFactory(c);\n const claim = claims.keyFor(session);\n const claimed = claim !== undefined && claims.isHeld(claim);\n return c.json({ executing: claimed || session.isExecuting() });\n });\n\n // GET /pending — get pending queued prompt\n app.get('/pending', async (c) => {\n const session = await sessionFactory(c);\n return c.json({ pending: session.getPendingPrompt() });\n });\n\n return app;\n}\n","/**\n * ITransportAdapter implementation for HTTP transport.\n *\n * Wraps createAgentRoutes into the unified ITransportAdapter interface\n * while exposing the underlying Hono app via getApp().\n */\n\nimport { resolveAdmission } from '@robota-sdk/agent-transport/node';\nimport { Hono } from 'hono';\n\nimport { createAgentRoutes } from './routes.js';\n\nimport type { IHttpTransportSession } from './http-session.js';\nimport type { TStreamFailureListener } from './submit-stream.js';\nimport type {\n ITransportAdapter,\n ITransportAdmissionConfig,\n ITransportLifecycleError,\n} from '@robota-sdk/agent-interface-transport';\n\nexport interface IHttpTransportOptions {\n /** Optional: base path prefix for routes. */\n basePath?: string;\n /**\n * SEC-008: what a peer must present. Omitted means SECURE — a credential is minted and\n * `getAdmissionToken()` returns it for the host to hand to its client.\n *\n * This transport previously had no gate at all, so omitting the option used to mean \"anyone may\n * execute anything\". Omission now means the safe thing, and running open takes saying so.\n */\n admission?: ITransportAdmissionConfig;\n /**\n * Where the DETAIL of a post-headers stream failure goes — forwarded to `createAgentRoutes`.\n * Review found this seam missing: the option existed on the routes and not on the entry point\n * README and the examples actually use, so \"the host decides the destination\" was a decision no\n * host on this path could make. Same forwarding rule as `admission`, which sat beside it.\n */\n onStreamFailure?: TStreamFailureListener;\n}\n\nexport interface IHttpTransport extends ITransportAdapter<IHttpTransportSession> {\n getApp(): Hono;\n getAdmissionToken(): string | null;\n}\n\nexport function createHttpTransport(options?: IHttpTransportOptions): IHttpTransport {\n let session: IHttpTransportSession | null = null;\n let app: Hono | null = null;\n // Resolved at CONSTRUCTION, not at start: a host needs the credential to hand to its client, and\n // a transport that cannot mint one must fail before anything is served.\n const admission = resolveAdmission(options?.admission);\n const lifecycleError = (code: ITransportLifecycleError['code']): ITransportLifecycleError =>\n Object.assign(new Error(`HTTP transport ${code}.`), {\n name: 'TransportLifecycleError' as const,\n code,\n transportName: 'http',\n });\n\n return {\n name: 'http',\n lifecycle: Object.freeze({ kind: 'service' }),\n attach(s: IHttpTransportSession) {\n session = s;\n },\n async start() {\n if (!session) throw lifecycleError('not-attached');\n if (app) throw lifecycleError('already-started');\n const routes = createAgentRoutes({\n sessionFactory: () => session!,\n // The decision already made, passed through — not taken apart and rebuilt for the routes to\n // resolve a second time.\n admission,\n onStreamFailure: options?.onStreamFailure,\n });\n // TRANS-002 (issue #2480): `basePath` was declared and advertised but never read, so routes\n // always mounted at root. It is honored here — or absent, in which case the routes ARE the app.\n app = options?.basePath ? new Hono().route(options.basePath, routes) : routes;\n },\n async stop() {\n app = null;\n session = null;\n },\n getApp() {\n if (!app) throw new Error('Transport not started. Call start() first.');\n return app;\n },\n /** The credential this transport requires, or `null` when the host explicitly opened it. */\n getAdmissionToken() {\n return admission.token;\n },\n };\n}\n"],"mappings":"wLAqCA,SAAS,EACP,EACA,EACA,EACA,EACe,CACf,IAAM,GAAgB,EAAe,IAAqC,CACxE,EAAQ,GAAG,EAAuB,CAAqB,EACvD,EAAQ,SAAW,EAAQ,IAAI,EAAuB,CAAqB,CAAC,CAC9E,EAIM,GAAS,EAAe,IAC5B,EAAO,SAAS,CAAE,QAAO,KAAM,KAAK,UAAU,CAAI,CAAE,CAAC,CAAC,CAAC,UAAY,CAGnE,CAAC,EAEC,EACE,EAAO,IAAI,QAAe,GAAY,CAC1C,EAAS,CACX,CAAC,EA2BD,OAzBA,EAA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/B,mBAAsB,EAGtB,YACA,gBAAiB,GAAS,eAC5B,CAAC,EAGD,EAAM,GAAS,SAAW,IAAI,EAAK,CAAC,CAAC,MAAM,EAAQ,SAAU,CAAM,EAAI,CACzE,EACA,MAAM,MAAO,CACX,EAAM,KACN,EAAU,IACZ,EACA,QAAS,CACP,GAAI,CAAC,EAAK,MAAU,MAAM,4CAA4C,EACtE,OAAO,CACT,EAEA,mBAAoB,CAClB,OAAO,EAAU,KACnB,CACF,CACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@robota-sdk/agent-transport-http",
3
- "version": "3.0.0-beta.82",
3
+ "version": "3.0.0-beta.84",
4
4
  "description": "HTTP (Hono) transport for the Robota SDK",
5
5
  "type": "module",
6
6
  "main": "dist/node/index.js",
@@ -28,28 +28,31 @@
28
28
  "default": "./dist/node/index.cjs"
29
29
  }
30
30
  }
31
- }
31
+ },
32
+ "./package.json": "./package.json"
32
33
  },
33
34
  "repository": {
34
35
  "type": "git",
35
- "url": "https://github.com/woojubb/robota.git"
36
+ "url": "https://github.com/woojubb/robota.git",
37
+ "directory": "packages/agent-transport-http"
36
38
  },
37
- "homepage": "https://robota.io/",
39
+ "homepage": "https://docs.robota.io/en/packages/agent-transport-http/",
38
40
  "bugs": {
39
41
  "url": "https://github.com/woojubb/robota/issues"
40
42
  },
41
43
  "engines": {
42
- "node": ">=22.0.0"
44
+ "node": ">=22.12.0"
43
45
  },
44
46
  "files": [
45
47
  "dist",
46
- "src"
48
+ "src",
49
+ "CHANGELOG.md"
47
50
  ],
48
51
  "dependencies": {
49
52
  "hono": "^4.12.32",
50
- "@robota-sdk/agent-interface-session": "3.0.0-beta.82",
51
- "@robota-sdk/agent-interface-transport": "3.0.0-beta.82",
52
- "@robota-sdk/agent-transport": "3.0.0-beta.82"
53
+ "@robota-sdk/agent-interface-session": "3.0.0-beta.84",
54
+ "@robota-sdk/agent-interface-transport": "3.0.0-beta.84",
55
+ "@robota-sdk/agent-transport": "3.0.0-beta.84"
53
56
  },
54
57
  "devDependencies": {
55
58
  "rimraf": "^5.0.10",
@@ -18,7 +18,11 @@ function createMockSession(): IHttpTransportSession {
18
18
  getSession,
19
19
  executeCommand,
20
20
  listCommands,
21
+ listSkills,
22
+ listModels,
21
23
  getMessages,
24
+ getFullHistory,
25
+ getMessagesDisplay,
22
26
  getContextState,
23
27
  isExecuting,
24
28
  getPendingPrompt,
@@ -33,7 +37,11 @@ function createMockSession(): IHttpTransportSession {
33
37
  getSession,
34
38
  executeCommand,
35
39
  listCommands,
40
+ listSkills,
41
+ listModels,
36
42
  getMessages,
43
+ getFullHistory,
44
+ getMessagesDisplay,
37
45
  getContextState,
38
46
  isExecuting,
39
47
  getPendingPrompt,
@@ -49,7 +57,9 @@ describe('createHttpTransport', () => {
49
57
  (session: IHttpTransportSession) => void
50
58
  >();
51
59
  expectTypeOf<IHttpTransportSession>().not.toHaveProperty('listRuntimeTools');
52
- expect(Object.keys(createMockSession())).toHaveLength(13);
60
+ // #3282 §2 added `listModels` to `ISessionCommands` (15 + 1); #3288 §2 added `getMessagesDisplay`
61
+ // to `ISessionConversationRead` (16 + 1).
62
+ expect(Object.keys(createMockSession())).toHaveLength(17);
53
63
  });
54
64
 
55
65
  it('returns an adapter with name "http"', () => {
@@ -120,14 +120,46 @@ describe('HTTP Transport Routes', () => {
120
120
  it('serves requests, a turn stream, and cancellation through only the declared port', async () => {
121
121
  const { session: full, startedTurns } = createHonestSession();
122
122
  const {
123
- submit, on, off, abort, cancelQueue, getSession, executeCommand, listCommands,
124
- getMessages, getContextState, isExecuting, getPendingPrompt, getPendingCount,
123
+ submit,
124
+ on,
125
+ off,
126
+ abort,
127
+ cancelQueue,
128
+ getSession,
129
+ executeCommand,
130
+ listCommands,
131
+ listSkills,
132
+ listModels,
133
+ getMessages,
134
+ getFullHistory,
135
+ getMessagesDisplay,
136
+ getContextState,
137
+ isExecuting,
138
+ getPendingPrompt,
139
+ getPendingCount,
125
140
  } = full;
126
141
  const port: IHttpTransportSession = {
127
- submit, on, off, abort, cancelQueue, getSession, executeCommand, listCommands,
128
- getMessages, getContextState, isExecuting, getPendingPrompt, getPendingCount,
142
+ submit,
143
+ on,
144
+ off,
145
+ abort,
146
+ cancelQueue,
147
+ getSession,
148
+ executeCommand,
149
+ listCommands,
150
+ listSkills,
151
+ listModels,
152
+ getMessages,
153
+ getFullHistory,
154
+ getMessagesDisplay,
155
+ getContextState,
156
+ isExecuting,
157
+ getPendingPrompt,
158
+ getPendingCount,
129
159
  };
130
- expect(Object.keys(port)).toHaveLength(13);
160
+ // #3282 §2 added `listModels` to `ISessionCommands` (15 + 1); #3288 §2 added
161
+ // `getMessagesDisplay` to `ISessionConversationRead` (16 + 1).
162
+ expect(Object.keys(port)).toHaveLength(17);
131
163
  const transport = createHttpTransport({
132
164
  admission: { open: true, openReason: 'least-authority HTTP port scenario' },
133
165
  });
@@ -946,3 +978,56 @@ describe('SEC-008: an unadmitted request never reaches the session', () => {
946
978
  expect(reached).toEqual([]);
947
979
  });
948
980
  });
981
+
982
+ describe('a session that builds itself in the background', () => {
983
+ /**
984
+ * `InteractiveSession` has no id until its background initialization finishes, so naming it
985
+ * throws until then. It says when it is ready through `whenInitialized()`.
986
+ */
987
+ function createStartingSession(initialization: Promise<void>): IHttpTransportSession {
988
+ const { session } = createHonestSession();
989
+ let ready = false;
990
+ void initialization.then(
991
+ () => (ready = true),
992
+ () => undefined,
993
+ );
994
+ session.getSession = (() => {
995
+ if (!ready) throw new Error('InteractiveSession not initialized.');
996
+ return { getSessionId: () => 'session_started' };
997
+ }) as IInteractiveSession['getSession'];
998
+ return Object.assign(session, { whenInitialized: () => initialization });
999
+ }
1000
+
1001
+ async function submit(session: IHttpTransportSession): Promise<Response> {
1002
+ const app = createAgentRoutes({
1003
+ sessionFactory: () => session,
1004
+ admission: { open: true, openReason: 'SEC-008: this case is about routing, not admission' },
1005
+ });
1006
+ return app.request('/submit', {
1007
+ method: 'POST',
1008
+ body: JSON.stringify({ prompt: 'hi' }),
1009
+ headers: { 'content-type': 'application/json' },
1010
+ });
1011
+ }
1012
+
1013
+ it('serves the first /submit once the session is ready, instead of refusing it', async () => {
1014
+ const session = createStartingSession(new Promise((resolve) => setTimeout(resolve, 10)));
1015
+
1016
+ const response = await submit(session);
1017
+
1018
+ expect(response.status).toBe(200);
1019
+ expect(await response.text()).toContain('event: complete');
1020
+ });
1021
+
1022
+ it('answers 500 without the reason when the session fails to start', async () => {
1023
+ const failed = Promise.reject(new Error('settings at /home/me/.robota are broken'));
1024
+ const session = createStartingSession(failed);
1025
+
1026
+ const response = await submit(session);
1027
+ const body = (await response.json()) as { error: string };
1028
+
1029
+ expect(response.status).toBe(500);
1030
+ expect(body.error).toMatch(/could not be started/);
1031
+ expect(body.error).not.toMatch(/home/);
1032
+ });
1033
+ });
@@ -17,4 +17,11 @@ export interface IHttpTransportSession
17
17
  ISessionIdentity,
18
18
  ISessionCommands,
19
19
  ISessionConversationRead,
20
- ISessionExecutionState {}
20
+ ISessionExecutionState {
21
+ /**
22
+ * Resolves once the session can name itself, and rejects if it failed to start. A session that
23
+ * builds itself in the background (`InteractiveSession`) has no id before then, so `/submit` waits
24
+ * on this before claiming a turn. A session that is ready at construction can omit it.
25
+ */
26
+ whenInitialized?(): Promise<void>;
27
+ }
@@ -114,6 +114,18 @@ export function submitHandler(
114
114
  return c.json({ error: 'prompt is required' }, 400);
115
115
  }
116
116
 
117
+ // A session still building itself cannot name itself yet, and the claim needs its name. The
118
+ // claim itself is still taken synchronously after this, so two requests that both waited here
119
+ // start one turn between them.
120
+ if (session.whenInitialized !== undefined) {
121
+ try {
122
+ await session.whenInitialized();
123
+ } catch {
124
+ // The reason can name host paths or settings; the client only needs to know it failed.
125
+ return c.json({ error: 'the session could not be started' }, 500);
126
+ }
127
+ }
128
+
117
129
  const admitted = admitTurn(c, session, claims);
118
130
  if (admitted instanceof Response) {
119
131
  return admitted;