@robota-sdk/agent-transport-http 3.0.0-beta.99 → 3.0.1
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 +205 -0
- package/dist/node/index.cjs +1 -1
- package/dist/node/index.d.cts +2 -0
- package/dist/node/index.d.cts.map +1 -1
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +1 -1
- package/dist/node/index.js.map +1 -1
- package/package.json +4 -4
- package/src/__tests__/routes.test.ts +73 -0
- package/src/routes.ts +16 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,210 @@
|
|
|
1
1
|
# @robota-sdk/agent-transport-http
|
|
2
2
|
|
|
3
|
+
## 3.0.1
|
|
4
|
+
### Patch Changes
|
|
5
|
+
|
|
6
|
+
- @robota-sdk/agent-interface-session@3.0.1
|
|
7
|
+
- @robota-sdk/agent-interface-transport@3.0.1
|
|
8
|
+
- @robota-sdk/agent-transport@3.0.1
|
|
9
|
+
|
|
10
|
+
## 3.0.0
|
|
11
|
+
### Major Changes
|
|
12
|
+
|
|
13
|
+
- 6e6b06b: A wire client can now render the whole session the way the in-process terminal UI does: the full
|
|
14
|
+
history, the context window as it changes, when the history changes, and where each turn came from.
|
|
15
|
+
|
|
16
|
+
- `agent-interface-session` is **`major`**: `ISessionConversationRead` gains a required
|
|
17
|
+
`getFullHistory()`. Any implementation of it, or of `IInteractiveSession`, must add it.
|
|
18
|
+
- `agent-transport` is **`major`**:
|
|
19
|
+
- It adds `get-history { fromIndex? }` → `history { startIndex, total, entries }`. The history
|
|
20
|
+
crosses one bounded page at a time (at most 256 KiB of entries; a single larger entry is sent
|
|
21
|
+
alone), from `fromIndex` (default 0), so no reply grows with the session. The client asks for
|
|
22
|
+
the next page after the previous one arrived. Entries are `IWireHistoryEntry`: a history entry
|
|
23
|
+
with an ISO 8601 `timestamp`. An observer may send it.
|
|
24
|
+
- `complete` and `interrupted` carry the turn's result without the session's history
|
|
25
|
+
(`TWireExecutionResult`); a client reads the history with `get-history`.
|
|
26
|
+
- It adds `get-prompts`: the host sends the permission and ask prompts still open as the
|
|
27
|
+
`permission_request` / `ask_request` frames that asked them, for a client that attached later.
|
|
28
|
+
An observer may not send it.
|
|
29
|
+
- `pending` gains an optional `pendingCount`: a host sends it when it knows how many prompts are
|
|
30
|
+
queued, and a client that gets none counts the prompt it shows. The host sends `pending` in
|
|
31
|
+
reply to a `submit` once it has taken the prompt, so a prompt queued behind a running turn shows
|
|
32
|
+
as queued.
|
|
33
|
+
- `command` takes an optional `requestId`, which the host echoes on the command's
|
|
34
|
+
`command_result` or `protocol_error`.
|
|
35
|
+
- The session's `context_update` is pushed as the `context` frame that `get-context` answers with.
|
|
36
|
+
- `compact`, `skill_activation` and `memory_event` push the new `history_changed`; the client
|
|
37
|
+
reads the history again.
|
|
38
|
+
- `turn_source` is pushed as the new `turn_source` frame.
|
|
39
|
+
- An exhaustive map over `TClientMessage` or `TServerMessage` types must add the new variants,
|
|
40
|
+
and `IProtocolSession` now requires `getFullHistory()`.
|
|
41
|
+
- `agent-transport-http` is **`major`** only because `IHttpTransportSession` includes the conversation
|
|
42
|
+
read role, so a session handed to it must now provide `getFullHistory()`.
|
|
43
|
+
- `agent-framework`: `SessionSlot` forwards `getFullHistory()` to the current session.
|
|
44
|
+
- `agent-ui-web` receives the new frames and does not render them.
|
|
45
|
+
- e82215f: **ARCH-011: replace the ambiguous transport lifecycle stub with executable conformance.**
|
|
46
|
+
|
|
47
|
+
`ITransportAdapter` now requires a frozen `service | runner` lifecycle descriptor. `start()` resolves
|
|
48
|
+
at the concrete transport's documented readiness boundary; start before attach and repeated active
|
|
49
|
+
start reject a stable lifecycle error, repeated stop is safe, and stopped adapters can reattach and
|
|
50
|
+
restart.
|
|
51
|
+
|
|
52
|
+
Runner adapters launch separately and expose a typed terminal outcome through
|
|
53
|
+
`waitForCompletion()`. The registry accepts base adapters, rejects duplicate names, keeps
|
|
54
|
+
configuration as an optional capability, returns complete ordered records whose pending slots become
|
|
55
|
+
registry-owned `abandoned` outcomes on stop/rollback, and exposes a real-runner-only first-failure
|
|
56
|
+
wait. It serializes startup/stop, rejects active restart before mutation, and reverses partial startup
|
|
57
|
+
from the currently failing adapter with typed safe rollback details. Runtime host and serve mode
|
|
58
|
+
propagate real nonzero runner results without treating normal shutdown abandonment as failure.
|
|
59
|
+
|
|
60
|
+
HTTP, MCP, both WebSocket adapters, WebRTC, and headless invoke one shared public conformance kit.
|
|
61
|
+
The former `TuiTransport` export is removed because it ignored the attached session; use `renderApp`
|
|
62
|
+
or `TuiInteractionChannel`, which honestly own their session lifecycle.
|
|
63
|
+
|
|
64
|
+
### Minor Changes
|
|
65
|
+
|
|
66
|
+
- ca44ac6: HTTP clients can now receive and answer permission and ask prompts. `POST /submit` with `receivePrompts: true` streams `permission_request`, `ask_request` and `prompt_resolved`. `GET /prompts` lists the prompts still open, so a client that attaches later can see them, and `POST /prompts/:id` answers one; an id that is not open returns 404, and an answer the session did not take returns 409. Clients that omit `receivePrompts` see no change. `IHttpTransportSession` now also requires `resolvePermission` and `resolveAsk`, which `InteractiveSession` already implements. The `--serve --http-port` API gains these routes as well.
|
|
67
|
+
- 9db63ee: Add named session capability roles and explicit capability-host queries while preserving the legacy
|
|
68
|
+
`IInteractiveSession` interface shape. HTTP, MCP, protocol, WS, WebRTC, and headless transports now
|
|
69
|
+
declare only the session roles they consume, and the direct aggregate-cast floor is zero.
|
|
70
|
+
|
|
71
|
+
### Patch Changes
|
|
72
|
+
|
|
73
|
+
- 57280bf: Every published package now declares `"engines": { "node": ">=22.12.0" }`. Before, 27 of the 38
|
|
74
|
+
packages declared no floor (`agent-core`, `agent-tools` and every provider among them),
|
|
75
|
+
`agent-session` and `agent-file-authority` declared `>=20.19.0`, and the other nine declared
|
|
76
|
+
`>=22.0.0`, so a consumer on Node 20 saw at most a warning from a transitive dependency.
|
|
77
|
+
|
|
78
|
+
Why 22.12: `agent-cli` and `agent-ui-terminal` need Node 22 through `ink` 7, and the CommonJS entries
|
|
79
|
+
of `agent-tools` and its dependents, `agent-transport`/`node` and its dependents, and
|
|
80
|
+
`agent-ui-terminal` `require()` ESM-only dependencies (`p-limit`, `jose`, `chalk`), which Node 22
|
|
81
|
+
supports unflagged only from 22.12. `engines` is advisory unless the consumer enables `engine-strict`.
|
|
82
|
+
|
|
83
|
+
No code changes: `tsdown` now reads `node22.12.0` as its build target from the field.
|
|
84
|
+
- 18c0d5c: Every published package now exports `./package.json`, so `require('<package>/package.json')` and
|
|
85
|
+
`import('<package>/package.json', { with: { type: 'json' } })` work instead of failing with
|
|
86
|
+
`ERR_PACKAGE_PATH_NOT_EXPORTED`, and each tarball now ships the package's `CHANGELOG.md`.
|
|
87
|
+
- 54e2848: `POST /submit` on a session that is still starting (a fresh `InteractiveSession`) now waits for it to start and runs the turn. It used to answer 500 ("concurrent-turn tracking is unavailable") until background initialization finished. A session that fails to start is answered 500 without the reason. `IHttpTransportSession` gains an optional `whenInitialized()` for this.
|
|
88
|
+
- 2c612ba: Release the migrated Robota product with its public SDK namespace, robota command, compatible SDK exports, internal product configuration, and verified CLI startup and delivery corrections.
|
|
89
|
+
- 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).
|
|
90
|
+
- 5783499: Harden file, HTTP, relay, hosted-runtime, editor, and native path boundaries against resource exhaustion, short writes, path races, and integer narrowing.
|
|
91
|
+
|
|
92
|
+
Editor integrations now carry `Read`, `Write`, and `Edit` only when their `IEditorFileAccess` adapter declares `pathAuthority: 'stable-root'`; pathname-only adapters continue to receive disk-search notices, while file operations use the tools' stable disk authority. Existing adapters that can prove stable rooted access should add the marker to retain editor-buffer reads and writes.
|
|
93
|
+
|
|
94
|
+
`HttpDagRuntimeProvider` accepts a `token` option and applies it to every orchestration and event-stream request so it interoperates with the authenticated native DAG runtime server.
|
|
95
|
+
- Updated dependencies [37b4bd7]
|
|
96
|
+
- Updated dependencies [50d2c9f]
|
|
97
|
+
- Updated dependencies [724fabb]
|
|
98
|
+
- Updated dependencies [d877de2]
|
|
99
|
+
- Updated dependencies [d61e159]
|
|
100
|
+
- Updated dependencies [bfe8ed5]
|
|
101
|
+
- Updated dependencies [a5961c9]
|
|
102
|
+
- Updated dependencies [3038eb7]
|
|
103
|
+
- Updated dependencies [c7f9203]
|
|
104
|
+
- Updated dependencies [7b72344]
|
|
105
|
+
- Updated dependencies [6ae3f28]
|
|
106
|
+
- Updated dependencies [57f57f5]
|
|
107
|
+
- Updated dependencies [ba822c1]
|
|
108
|
+
- Updated dependencies [6e6b06b]
|
|
109
|
+
- Updated dependencies [57280bf]
|
|
110
|
+
- Updated dependencies [18c0d5c]
|
|
111
|
+
- Updated dependencies [9a01e78]
|
|
112
|
+
- Updated dependencies [e8d70ac]
|
|
113
|
+
- Updated dependencies [2c612ba]
|
|
114
|
+
- Updated dependencies [3427887]
|
|
115
|
+
- Updated dependencies [c967c57]
|
|
116
|
+
- Updated dependencies [60f3965]
|
|
117
|
+
- Updated dependencies [115e104]
|
|
118
|
+
- Updated dependencies [04719a9]
|
|
119
|
+
- Updated dependencies [04a6de4]
|
|
120
|
+
- Updated dependencies [0ba247b]
|
|
121
|
+
- Updated dependencies [4c5148e]
|
|
122
|
+
- Updated dependencies [0116a29]
|
|
123
|
+
- Updated dependencies [e82215f]
|
|
124
|
+
- Updated dependencies [52b7346]
|
|
125
|
+
- Updated dependencies [9db63ee]
|
|
126
|
+
- Updated dependencies [b078afa]
|
|
127
|
+
- Updated dependencies [2ebff01]
|
|
128
|
+
- Updated dependencies [9db63ee]
|
|
129
|
+
- Updated dependencies [2ebff01]
|
|
130
|
+
- Updated dependencies [4772067]
|
|
131
|
+
- Updated dependencies [0f98419]
|
|
132
|
+
- Updated dependencies [64ba748]
|
|
133
|
+
- Updated dependencies [d312755]
|
|
134
|
+
- Updated dependencies [c207a31]
|
|
135
|
+
- Updated dependencies [3244fb8]
|
|
136
|
+
- Updated dependencies [1e3f91a]
|
|
137
|
+
- Updated dependencies [4f3c075]
|
|
138
|
+
- Updated dependencies [7669851]
|
|
139
|
+
- Updated dependencies [4b76cfa]
|
|
140
|
+
- Updated dependencies [07b627f]
|
|
141
|
+
- Updated dependencies [9665c6e]
|
|
142
|
+
- Updated dependencies [44393be]
|
|
143
|
+
- Updated dependencies [c7fa299]
|
|
144
|
+
- Updated dependencies [5134b3b]
|
|
145
|
+
- Updated dependencies [7911a7d]
|
|
146
|
+
- Updated dependencies [7d9cc66]
|
|
147
|
+
- Updated dependencies [5c5ff23]
|
|
148
|
+
- Updated dependencies [9814afc]
|
|
149
|
+
- Updated dependencies [9c6a8db]
|
|
150
|
+
- @robota-sdk/agent-interface-session@3.0.0
|
|
151
|
+
- @robota-sdk/agent-interface-transport@3.0.0
|
|
152
|
+
- @robota-sdk/agent-transport@3.0.0
|
|
153
|
+
|
|
154
|
+
## 3.0.0-beta.106
|
|
155
|
+
### Patch Changes
|
|
156
|
+
|
|
157
|
+
- @robota-sdk/agent-interface-session@3.0.0-beta.106
|
|
158
|
+
- @robota-sdk/agent-interface-transport@3.0.0-beta.106
|
|
159
|
+
- @robota-sdk/agent-transport@3.0.0-beta.106
|
|
160
|
+
|
|
161
|
+
## 3.0.0-beta.105
|
|
162
|
+
### Patch Changes
|
|
163
|
+
|
|
164
|
+
- @robota-sdk/agent-interface-session@3.0.0-beta.105
|
|
165
|
+
- @robota-sdk/agent-interface-transport@3.0.0-beta.105
|
|
166
|
+
- @robota-sdk/agent-transport@3.0.0-beta.105
|
|
167
|
+
|
|
168
|
+
## 3.0.0-beta.104
|
|
169
|
+
### Patch Changes
|
|
170
|
+
|
|
171
|
+
- @robota-sdk/agent-interface-session@3.0.0-beta.104
|
|
172
|
+
- @robota-sdk/agent-interface-transport@3.0.0-beta.104
|
|
173
|
+
- @robota-sdk/agent-transport@3.0.0-beta.104
|
|
174
|
+
|
|
175
|
+
## 3.0.0-beta.103
|
|
176
|
+
### Patch Changes
|
|
177
|
+
|
|
178
|
+
- @robota-sdk/agent-interface-session@3.0.0-beta.103
|
|
179
|
+
- @robota-sdk/agent-interface-transport@3.0.0-beta.103
|
|
180
|
+
- @robota-sdk/agent-transport@3.0.0-beta.103
|
|
181
|
+
|
|
182
|
+
## 3.0.0-beta.102
|
|
183
|
+
### Patch Changes
|
|
184
|
+
|
|
185
|
+
- @robota-sdk/agent-interface-session@3.0.0-beta.102
|
|
186
|
+
- @robota-sdk/agent-interface-transport@3.0.0-beta.102
|
|
187
|
+
- @robota-sdk/agent-transport@3.0.0-beta.102
|
|
188
|
+
|
|
189
|
+
## 3.0.0-beta.101
|
|
190
|
+
### Patch Changes
|
|
191
|
+
|
|
192
|
+
- 5783499: Harden file, HTTP, relay, hosted-runtime, editor, and native path boundaries against resource exhaustion, short writes, path races, and integer narrowing.
|
|
193
|
+
|
|
194
|
+
Editor integrations now carry `Read`, `Write`, and `Edit` only when their `IEditorFileAccess` adapter declares `pathAuthority: 'stable-root'`; pathname-only adapters continue to receive disk-search notices, while file operations use the tools' stable disk authority. Existing adapters that can prove stable rooted access should add the marker to retain editor-buffer reads and writes.
|
|
195
|
+
|
|
196
|
+
`HttpDagRuntimeProvider` accepts a `token` option and applies it to every orchestration and event-stream request so it interoperates with the authenticated native DAG runtime server.
|
|
197
|
+
- @robota-sdk/agent-interface-session@3.0.0-beta.101
|
|
198
|
+
- @robota-sdk/agent-interface-transport@3.0.0-beta.101
|
|
199
|
+
- @robota-sdk/agent-transport@3.0.0-beta.101
|
|
200
|
+
|
|
201
|
+
## 3.0.0-beta.100
|
|
202
|
+
### Patch Changes
|
|
203
|
+
|
|
204
|
+
- @robota-sdk/agent-interface-session@3.0.0-beta.100
|
|
205
|
+
- @robota-sdk/agent-interface-transport@3.0.0-beta.100
|
|
206
|
+
- @robota-sdk/agent-transport@3.0.0-beta.100
|
|
207
|
+
|
|
3
208
|
## 3.0.0-beta.99
|
|
4
209
|
### Patch Changes
|
|
5
210
|
|
package/dist/node/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@robota-sdk/agent-transport/node"),t=require("hono"),n=require("@robota-sdk/agent-transport"),
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@robota-sdk/agent-transport/node"),t=require("hono"),n=require("hono/body-limit"),r=require("@robota-sdk/agent-transport"),i=require("hono/streaming");function a(){let e=new Map;return{record(t,n){let r=e.get(t);r===void 0&&(r=new Map,e.set(t,r)),r.set(n.event.id,n)},forget(t,n){e.get(t)?.delete(n)},list:t=>[...e.get(t)?.values()??[]],find:(t,n)=>e.get(t)?.get(n),clear(t){e.delete(t)}}}function o(e){return async t=>{let n=await e.sessionFactory(t),r=e.claims.keyFor(n);return t.json({prompts:r===void 0?[]:e.openPrompts.list(r)})}}function s(e){let{sessionFactory:t,claims:n,openPrompts:i,attribution:a}=e;return async e=>{let o=await t(e),s=e.req.param(`id`)??``,c;try{c=await e.req.json()}catch{return e.json({error:`the body must be a JSON object`},400)}let l=n.keyFor(o),u=l===void 0?void 0:i.find(l,s);if(l===void 0||u===void 0)return e.json({error:`no open prompt with this id`},404);if(u.type===`permission_request`){let t=(0,r.decodeClientMessage)({type:`permission-response`,id:s,result:c?.result});if(!t.ok||t.message.type!==`permission-response`)return e.json({error:`result must be true, false, "allow-session" or "allow-project"`},400);o.resolvePermission(s,t.message.result,a?.driverId)}else{let t=(0,r.decodeClientMessage)({type:`ask-response`,id:s,response:c?.response});if(!t.ok||t.message.type!==`ask-response`)return e.json({error:`response must be { "type": "answer", "values": string[], "text"?: string } or { "type": "cancelled" }`},400);o.resolveAsk(s,t.message.response,a?.driverId)}return i.find(l,s)===void 0?e.json({ok:!0}):e.json({error:`the session did not accept this answer`},409)}}function c(e,t,n,r,i){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})),i!==void 0&&l(a,o,i),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(()=>u(e,r,s)),c}function l(e,t,n){e(`permission_request`,e=>{n.record({type:`permission_request`,event:e}),t(`permission_request`,e)}),e(`ask_request`,e=>{n.record({type:`ask_request`,event:e}),t(`ask_request`,e)}),e(`prompt_resolved`,e=>{n.forget(e.id),t(`prompt_resolved`,e)})}function u(e,t,n){try{e.abort()}catch(e){try{t?.(e instanceof Error?e:Error(String(e)))}catch{}}finally{n()}}function d(e,t){for(let t of e)try{t()}catch{}t()}function f(e,t,n,r,i,a){return async o=>{try{let s=[];try{let n=c(e,o,s,r,a);await(i===void 0?e.submit(t):e.submit(t,void 0,void 0,{...i})),await n}finally{d(s,n)}}catch(e){await p(e instanceof Error?e:Error(String(e)),o,r)}}}async function p(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 m(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 h(e){let{sessionFactory:t,claims:n,openPrompts:r,onStreamFailure:a,attribution:o}=e;return async e=>{let s=await t(e),c=await e.req.json();if(!c.prompt||typeof c.prompt!=`string`)return e.json({error:`prompt is required`},400);if(c.receivePrompts!==void 0&&typeof c.receivePrompts!=`boolean`)return e.json({error:`receivePrompts must be a boolean`},400);if(s.whenInitialized!==void 0)try{await s.whenInitialized()}catch{return e.json({error:`the session could not be started`},500)}let l=m(e,s,n);if(l instanceof Response)return l;let{claim:u}=l,d=!1,p=()=>{d||(d=!0,r.clear(u),n.release(u))},h=c.receivePrompts===!0?{record:e=>r.record(u,e),forget:e=>r.forget(u,e)}:void 0;try{return await(0,i.streamSSE)(e,f(s,c.prompt,p,a,o,h))}catch(e){throw p(),e}}}function g(){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 _(r){let{sessionFactory:i,onStreamFailure:c,attribution:l}=r,u=new t.Hono,d=g(),f=a(),p=r.maxJsonBodyBytes??65536;if(!Number.isSafeInteger(p)||p<1)throw Error(`maxJsonBodyBytes must be a positive integer`);let m=(0,n.bodyLimit)({maxSize:p,onError:e=>e.json({error:`request body too large`},413)}),_=(0,e.resolveAdmission)(r.admission);return u.use(`*`,async(t,n)=>_.token===null||(0,e.credentialMatches)(_.token,(0,e.bearerCredential)(t.req.header(`authorization`)))?n():t.json({error:`unauthorized`},401)),u.post(`/submit`,m,h({sessionFactory:i,claims:d,openPrompts:f,onStreamFailure:c,attribution:l})),u.get(`/prompts`,o({sessionFactory:i,claims:d,openPrompts:f,attribution:l})),u.post(`/prompts/:id`,m,s({sessionFactory:i,claims:d,openPrompts:f,attribution:l})),u.post(`/command`,m,async e=>{let t=await i(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)}),u.post(`/abort`,async e=>((await i(e)).abort(),e.json({ok:!0}))),u.post(`/cancel-queue`,async e=>((await i(e)).cancelQueue(),e.json({ok:!0}))),u.get(`/messages`,async e=>{let t=await i(e);return e.json(t.getMessages())}),u.get(`/context`,async e=>{let t=await i(e);return e.json(t.getContextState())}),u.get(`/executing`,async e=>{let t=await i(e),n=d.keyFor(t),r=n!==void 0&&d.isHeld(n);return e.json({executing:r||t.isExecuting()})}),u.get(`/pending`,async e=>{let t=await i(e);return e.json({pending:t.getPendingPrompt()})}),u}function v(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=_({sessionFactory:()=>r,admission:a,onStreamFailure:n?.onStreamFailure,attribution:n?.attribution});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=_,exports.createHttpTransport=v;
|
package/dist/node/index.d.cts
CHANGED
|
@@ -82,6 +82,8 @@ interface IAgentRoutesOptions {
|
|
|
82
82
|
* body. Absent leaves the session's own default.
|
|
83
83
|
*/
|
|
84
84
|
attribution?: TTurnAttribution;
|
|
85
|
+
/** Maximum bytes accepted by a JSON request route. Default 64 KiB. */
|
|
86
|
+
maxJsonBodyBytes?: number;
|
|
85
87
|
}
|
|
86
88
|
/**
|
|
87
89
|
* Create a Hono router with all agent HTTP endpoints.
|
|
@@ -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":";;;;;;UAYiB,8BAEb,wBACA,gBACA,qBACA,kBACA,0BACA,kBACA,0BACA;;;;;;EAMF,oBAAoB;;;;;;;;;;;;;;;;;KCKV,0BAA0B,OAAO;;;;;;KAOjC,mBAAmB,KAAK;;;;;;;;;;;;;;;;;;;;;;;KCDxB,mBACV,GAAG,YACA,wBAAwB,QAAQ;;;
|
|
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":";;;;;;UAYiB,8BAEb,wBACA,gBACA,qBACA,kBACA,0BACA,kBACA,0BACA;;;;;;EAMF,oBAAoB;;;;;;;;;;;;;;;;;KCKV,0BAA0B,OAAO;;;;;;KAOjC,mBAAmB,KAAK;;;;;;;;;;;;;;;;;;;;;;;KCDxB,mBACV,GAAG,YACA,wBAAwB,QAAQ;;;UCRpB;;EAEf,gBAAgB;;;;;;EAMhB,kBAAkB;;;;;;;;EAQlB,WAAW,4BAA4B;;;;;;EAMvC,cAAc;;EAEd;;;;;;;;;;;;iBAec,kBAAkB,SAAS,sBAAsB;;;UCnDhD;;EAEf;;;;;;;;EAQA,YAAY;;;;;;;EAOZ,kBAAkB;;EAElB,cAAc;;UAGC,uBAAuB,kBAAkB;EACxD,UAAU;EACV;;iBAGc,oBAAoB,UAAU,wBAAwB"}
|
package/dist/node/index.d.ts
CHANGED
|
@@ -82,6 +82,8 @@ interface IAgentRoutesOptions {
|
|
|
82
82
|
* body. Absent leaves the session's own default.
|
|
83
83
|
*/
|
|
84
84
|
attribution?: TTurnAttribution;
|
|
85
|
+
/** Maximum bytes accepted by a JSON request route. Default 64 KiB. */
|
|
86
|
+
maxJsonBodyBytes?: number;
|
|
85
87
|
}
|
|
86
88
|
/**
|
|
87
89
|
* Create a Hono router with all agent HTTP endpoints.
|
package/dist/node/index.d.ts.map
CHANGED
|
@@ -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":";;;;;;UAYiB,8BAEb,wBACA,gBACA,qBACA,kBACA,0BACA,kBACA,0BACA;;;;;;EAMF,oBAAoB;;;;;;;;;;;;;;;;;KCKV,0BAA0B,OAAO;;;;;;KAOjC,mBAAmB,KAAK;;;;;;;;;;;;;;;;;;;;;;;KCDxB,mBACV,GAAG,YACA,wBAAwB,QAAQ;;;
|
|
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":";;;;;;UAYiB,8BAEb,wBACA,gBACA,qBACA,kBACA,0BACA,kBACA,0BACA;;;;;;EAMF,oBAAoB;;;;;;;;;;;;;;;;;KCKV,0BAA0B,OAAO;;;;;;KAOjC,mBAAmB,KAAK;;;;;;;;;;;;;;;;;;;;;;;KCDxB,mBACV,GAAG,YACA,wBAAwB,QAAQ;;;UCRpB;;EAEf,gBAAgB;;;;;;EAMhB,kBAAkB;;;;;;;;EAQlB,WAAW,4BAA4B;;;;;;EAMvC,cAAc;;EAEd;;;;;;;;;;;;iBAec,kBAAkB,SAAS,sBAAsB;;;UCnDhD;;EAEf;;;;;;;;EAQA,YAAY;;;;;;;EAOZ,kBAAkB;;EAElB,cAAc;;UAGC,uBAAuB,kBAAkB;EACxD,UAAU;EACV;;iBAGc,oBAAoB,UAAU,wBAAwB"}
|
package/dist/node/index.js
CHANGED
|
@@ -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{
|
|
1
|
+
import{bearerCredential as e,credentialMatches as t,resolveAdmission as n}from"@robota-sdk/agent-transport/node";import{Hono as r}from"hono";import{bodyLimit as i}from"hono/body-limit";import{decodeClientMessage as a}from"@robota-sdk/agent-transport";import{streamSSE as o}from"hono/streaming";function s(){let e=new Map;return{record(t,n){let r=e.get(t);r===void 0&&(r=new Map,e.set(t,r)),r.set(n.event.id,n)},forget(t,n){e.get(t)?.delete(n)},list:t=>[...e.get(t)?.values()??[]],find:(t,n)=>e.get(t)?.get(n),clear(t){e.delete(t)}}}function c(e){return async t=>{let n=await e.sessionFactory(t),r=e.claims.keyFor(n);return t.json({prompts:r===void 0?[]:e.openPrompts.list(r)})}}function l(e){let{sessionFactory:t,claims:n,openPrompts:r,attribution:i}=e;return async e=>{let o=await t(e),s=e.req.param(`id`)??``,c;try{c=await e.req.json()}catch{return e.json({error:`the body must be a JSON object`},400)}let l=n.keyFor(o),u=l===void 0?void 0:r.find(l,s);if(l===void 0||u===void 0)return e.json({error:`no open prompt with this id`},404);if(u.type===`permission_request`){let t=a({type:`permission-response`,id:s,result:c?.result});if(!t.ok||t.message.type!==`permission-response`)return e.json({error:`result must be true, false, "allow-session" or "allow-project"`},400);o.resolvePermission(s,t.message.result,i?.driverId)}else{let t=a({type:`ask-response`,id:s,response:c?.response});if(!t.ok||t.message.type!==`ask-response`)return e.json({error:`response must be { "type": "answer", "values": string[], "text"?: string } or { "type": "cancelled" }`},400);o.resolveAsk(s,t.message.response,i?.driverId)}return r.find(l,s)===void 0?e.json({ok:!0}):e.json({error:`the session did not accept this answer`},409)}}function u(e,t,n,r,i){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})),i!==void 0&&d(a,o,i),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(()=>f(e,r,s)),c}function d(e,t,n){e(`permission_request`,e=>{n.record({type:`permission_request`,event:e}),t(`permission_request`,e)}),e(`ask_request`,e=>{n.record({type:`ask_request`,event:e}),t(`ask_request`,e)}),e(`prompt_resolved`,e=>{n.forget(e.id),t(`prompt_resolved`,e)})}function f(e,t,n){try{e.abort()}catch(e){try{t?.(e instanceof Error?e:Error(String(e)))}catch{}}finally{n()}}function p(e,t){for(let t of e)try{t()}catch{}t()}function m(e,t,n,r,i,a){return async o=>{try{let s=[];try{let n=u(e,o,s,r,a);await(i===void 0?e.submit(t):e.submit(t,void 0,void 0,{...i})),await n}finally{p(s,n)}}catch(e){await h(e instanceof Error?e:Error(String(e)),o,r)}}}async function h(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 g(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 _(e){let{sessionFactory:t,claims:n,openPrompts:r,onStreamFailure:i,attribution:a}=e;return async e=>{let s=await t(e),c=await e.req.json();if(!c.prompt||typeof c.prompt!=`string`)return e.json({error:`prompt is required`},400);if(c.receivePrompts!==void 0&&typeof c.receivePrompts!=`boolean`)return e.json({error:`receivePrompts must be a boolean`},400);if(s.whenInitialized!==void 0)try{await s.whenInitialized()}catch{return e.json({error:`the session could not be started`},500)}let l=g(e,s,n);if(l instanceof Response)return l;let{claim:u}=l,d=!1,f=()=>{d||(d=!0,r.clear(u),n.release(u))},p=c.receivePrompts===!0?{record:e=>r.record(u,e),forget:e=>r.forget(u,e)}:void 0;try{return await o(e,m(s,c.prompt,f,i,a,p))}catch(e){throw f(),e}}}function v(){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 y(a){let{sessionFactory:o,onStreamFailure:u,attribution:d}=a,f=new r,p=v(),m=s(),h=a.maxJsonBodyBytes??65536;if(!Number.isSafeInteger(h)||h<1)throw Error(`maxJsonBodyBytes must be a positive integer`);let g=i({maxSize:h,onError:e=>e.json({error:`request body too large`},413)}),y=n(a.admission);return f.use(`*`,async(n,r)=>y.token===null||t(y.token,e(n.req.header(`authorization`)))?r():n.json({error:`unauthorized`},401)),f.post(`/submit`,g,_({sessionFactory:o,claims:p,openPrompts:m,onStreamFailure:u,attribution:d})),f.get(`/prompts`,c({sessionFactory:o,claims:p,openPrompts:m,attribution:d})),f.post(`/prompts/:id`,g,l({sessionFactory:o,claims:p,openPrompts:m,attribution:d})),f.post(`/command`,g,async e=>{let t=await o(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)}),f.post(`/abort`,async e=>((await o(e)).abort(),e.json({ok:!0}))),f.post(`/cancel-queue`,async e=>((await o(e)).cancelQueue(),e.json({ok:!0}))),f.get(`/messages`,async e=>{let t=await o(e);return e.json(t.getMessages())}),f.get(`/context`,async e=>{let t=await o(e);return e.json(t.getContextState())}),f.get(`/executing`,async e=>{let t=await o(e),n=p.keyFor(t),r=n!==void 0&&p.isHeld(n);return e.json({executing:r||t.isExecuting()})}),f.get(`/pending`,async e=>{let t=await o(e);return e.json({pending:t.getPendingPrompt()})}),f}function b(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=y({sessionFactory:()=>t,admission:a,onStreamFailure:e?.onStreamFailure,attribution:e?.attribution});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{y as createAgentRoutes,b as createHttpTransport};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/node/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/open-prompts.ts","../../src/prompt-routes.ts","../../src/submit-stream.ts","../../src/submit-route.ts","../../src/turn-claims.ts","../../src/routes.ts","../../src/http-transport.ts"],"sourcesContent":["/**\n * The permission and ask prompts a `/submit` stream forwarded and that are still open, per session.\n *\n * The session emits a prompt once, when it is asked, so a client that comes later would never see\n * it; `GET /prompts` answers from here, and `POST /prompts/:id` refuses an id that is not here.\n *\n * Keyed by the session's id, the same key as the turn claim, and not by object identity: the session\n * factory may return a fresh wrapper per request, so the `agent-transport` registry (a WeakMap on the\n * session object) would never find the prompt a different request recorded.\n *\n * It learns only through the prompt-receiving stream's own subscriptions and never listens to the\n * session itself. A listener of its own would keep an unattended turn's prompt parked instead of\n * letting the session fail it closed. A session's entries go when that stream's claim is released.\n */\n\nimport type {\n IAskRequestEvent,\n IPermissionRequestEvent,\n} from '@robota-sdk/agent-interface-session';\n\nexport type THttpPromptFrame =\n | { readonly type: 'permission_request'; readonly event: IPermissionRequestEvent }\n | { readonly type: 'ask_request'; readonly event: IAskRequestEvent };\n\nexport interface IHttpOpenPrompts {\n record(sessionKey: string, frame: THttpPromptFrame): void;\n forget(sessionKey: string, id: string): void;\n /** The session's open prompts, oldest first. */\n list(sessionKey: string): readonly THttpPromptFrame[];\n find(sessionKey: string, id: string): THttpPromptFrame | undefined;\n /** The stream that received the session's prompts has ended. */\n clear(sessionKey: string): void;\n}\n\nexport function createHttpOpenPrompts(): IHttpOpenPrompts {\n const bySession = new Map<string, Map<string, THttpPromptFrame>>();\n\n return {\n record(sessionKey, frame) {\n let open = bySession.get(sessionKey);\n if (open === undefined) {\n open = new Map();\n bySession.set(sessionKey, open);\n }\n open.set(frame.event.id, frame);\n },\n forget(sessionKey, id) {\n bySession.get(sessionKey)?.delete(id);\n },\n list: (sessionKey) => [...(bySession.get(sessionKey)?.values() ?? [])],\n find: (sessionKey, id) => bySession.get(sessionKey)?.get(id),\n clear(sessionKey) {\n bySession.delete(sessionKey);\n },\n };\n}\n","/**\n * `GET /prompts` and `POST /prompts/:id` — reading and answering the permission and ask prompts a\n * prompt-receiving `/submit` stream forwarded.\n *\n * Split from `routes.ts` for the same reason `/submit` is: these routes carry a decision of their own\n * (is this id open here, and is this answer the right kind for it), not just a mount.\n */\n\nimport { decodeClientMessage } from '@robota-sdk/agent-transport';\n\nimport type { IHttpOpenPrompts } from './open-prompts.js';\nimport type { TSessionFactory } from './submit-route.js';\nimport type { TTurnAttribution } from './submit-stream.js';\nimport type { ITurnClaims } from './turn-claims.js';\nimport type { Context } from 'hono';\n\nexport interface IPromptRouteDeps {\n readonly sessionFactory: TSessionFactory;\n readonly claims: ITurnClaims;\n readonly openPrompts: IHttpOpenPrompts;\n readonly attribution?: TTurnAttribution;\n}\n\n/** The open prompts of the request's session, oldest first: what a client that came later reads. */\nexport function listPromptsHandler(deps: IPromptRouteDeps) {\n return async (c: Context) => {\n const session = await deps.sessionFactory(c);\n const key = deps.claims.keyFor(session);\n return c.json({ prompts: key === undefined ? [] : deps.openPrompts.list(key) });\n };\n}\n\n/**\n * Answer one open prompt by id.\n *\n * The id must be one this session's prompt-receiving stream forwarded and that is still open. An id\n * that never was and one already settled get the same 404: the client cannot act differently on the\n * two, and the registry forgets a prompt once it settles.\n *\n * The answerer is the HOST's `attribution.driverId`, never the request, for the same reason `/submit`\n * attribution is: a client must not record its answer as another surface's.\n *\n * Nothing awaits between the lookup and the resolve. The session settles synchronously and emits\n * `prompt_resolved`, which the stream forwards and the registry forgets, so a second answer for the\n * same id finds nothing open and is refused rather than reported as accepted.\n *\n * `200` means the prompt settled, not merely that the answer was handed over: the session ignores an\n * answer it does not take (one in an outside party's name, say), and a prompt still open after the\n * resolve is answered `409` so the client does not believe it decided something it did not.\n */\nexport function answerPromptHandler(deps: IPromptRouteDeps) {\n const { sessionFactory, claims, openPrompts, attribution } = deps;\n return async (c: Context) => {\n const session = await sessionFactory(c);\n const id = c.req.param('id') ?? '';\n let body: { result?: unknown; response?: unknown };\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'the body must be a JSON object' }, 400);\n }\n\n const key = claims.keyFor(session);\n const frame = key === undefined ? undefined : openPrompts.find(key, id);\n if (key === undefined || frame === undefined) {\n return c.json({ error: 'no open prompt with this id' }, 404);\n }\n\n if (frame.type === 'permission_request') {\n const decoded = decodeClientMessage({\n type: 'permission-response',\n id,\n result: body?.result,\n });\n if (!decoded.ok || decoded.message.type !== 'permission-response') {\n return c.json(\n { error: 'result must be true, false, \"allow-session\" or \"allow-project\"' },\n 400,\n );\n }\n session.resolvePermission(id, decoded.message.result, attribution?.driverId);\n } else {\n const decoded = decodeClientMessage({ type: 'ask-response', id, response: body?.response });\n if (!decoded.ok || decoded.message.type !== 'ask-response') {\n return c.json(\n {\n error:\n 'response must be { \"type\": \"answer\", \"values\": string[], \"text\"?: string } or ' +\n '{ \"type\": \"cancelled\" }',\n },\n 400,\n );\n }\n session.resolveAsk(id, decoded.message.response, attribution?.driverId);\n }\n if (openPrompts.find(key, id) !== undefined) {\n return c.json({ error: 'the session did not accept this answer' }, 409);\n }\n return c.json({ ok: true });\n };\n}\n","/**\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 { THttpPromptFrame } from './open-prompts.js';\nimport type { SSEStreamingApi } from 'hono/streaming';\nimport type {\n IAskRequestEvent,\n IPermissionRequestEvent,\n IPromptResolvedEvent,\n ISubmitOptions,\n} from '@robota-sdk/agent-interface-session';\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 * Who a submitted turn is attributed to, assigned by the HOST that composed the routes — never read\n * from the request, because a client could otherwise claim to be the local operator or another\n * surface in the usage record. Absent means the session's own default.\n */\nexport type TTurnAttribution = Pick<ISubmitOptions, 'driverId' | 'surface'>;\n\n/**\n * Where a prompt-receiving stream reports the prompts it forwarded, so a later request can list or\n * answer them. Present only when the client asked to receive prompts.\n */\nexport interface IRelayPrompts {\n record(frame: THttpPromptFrame): void;\n forget(id: string): void;\n}\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 prompts: IRelayPrompts | 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 if (prompts !== undefined) subscribePrompts(subscribe, write, prompts);\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 * Forward the turn's permission and ask prompts, and their settlement, to a client that said it can\n * answer them.\n *\n * Only such a client subscribes: the session parks a prompt only while someone listens for it, so a\n * client that cannot answer must not listen, or the turn would wait on a prompt nobody settles\n * instead of failing it closed at once.\n */\nfunction subscribePrompts(\n subscribe: <T>(event: string, handler: (data: T) => void) => void,\n write: (event: string, data: unknown) => Promise<void>,\n prompts: IRelayPrompts,\n): void {\n subscribe('permission_request', (event: IPermissionRequestEvent) => {\n prompts.record({ type: 'permission_request', event });\n void write('permission_request', event);\n });\n subscribe('ask_request', (event: IAskRequestEvent) => {\n prompts.record({ type: 'ask_request', event });\n void write('ask_request', event);\n });\n subscribe('prompt_resolved', (event: IPromptResolvedEvent) => {\n prompts.forget(event.id);\n void write('prompt_resolved', event);\n });\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 attribution?: TTurnAttribution,\n prompts?: IRelayPrompts,\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, prompts);\n await (attribution === undefined\n ? session.submit(prompt)\n : session.submit(prompt, undefined, undefined, { ...attribution }));\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 { IHttpOpenPrompts } from './open-prompts.js';\nimport type { IRelayPrompts, TStreamFailureListener, TTurnAttribution } 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 interface ISubmitRouteDeps {\n readonly sessionFactory: TSessionFactory;\n readonly claims: ITurnClaims;\n readonly openPrompts: IHttpOpenPrompts;\n readonly onStreamFailure?: TStreamFailureListener;\n readonly attribution?: TTurnAttribution;\n}\n\nexport function submitHandler(deps: ISubmitRouteDeps) {\n const { sessionFactory, claims, openPrompts, onStreamFailure, attribution } = deps;\n return async (c: Context) => {\n const session = await sessionFactory(c);\n const body = await c.req.json<{ prompt: string; receivePrompts?: unknown }>();\n\n if (!body.prompt || typeof body.prompt !== 'string') {\n return c.json({ error: 'prompt is required' }, 400);\n }\n if (body.receivePrompts !== undefined && typeof body.receivePrompts !== 'boolean') {\n return c.json({ error: 'receivePrompts must be a boolean' }, 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 // The stream that held this session's prompts is gone; what is still open is the session's\n // to settle, and no longer this route's to list or answer.\n openPrompts.clear(claim);\n claims.release(claim);\n }\n };\n const prompts: IRelayPrompts | undefined =\n body.receivePrompts === true\n ? {\n record: (frame) => openPrompts.record(claim, frame),\n forget: (id) => openPrompts.forget(claim, id),\n }\n : undefined;\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(\n c,\n relayTurn(session, body.prompt, releaseOnce, onStreamFailure, attribution, prompts),\n );\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 { createHttpOpenPrompts } from './open-prompts.js';\nimport { answerPromptHandler, listPromptsHandler } from './prompt-routes.js';\nimport { submitHandler } from './submit-route.js';\nimport { createTurnClaims } from './turn-claims.js';\n\nimport type { TSessionFactory } from './submit-route.js';\nimport type { TStreamFailureListener, TTurnAttribution } 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 * Who `/submit` turns and prompt answers are attributed to — the driver and product surface the\n * HOST assigns, as the WebSocket transport's `driverId`/`surface` do. Never taken from the request\n * body. Absent leaves the session's own default.\n */\n attribution?: TTurnAttribution;\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, attribution } = 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 const openPrompts = createHttpOpenPrompts();\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(\n '/submit',\n submitHandler({ sessionFactory, claims, openPrompts, onStreamFailure, attribution }),\n );\n\n // GET /prompts — the open permission/ask prompts a prompt-receiving /submit stream forwarded\n app.get('/prompts', listPromptsHandler({ sessionFactory, claims, openPrompts, attribution }));\n\n // POST /prompts/:id — answer one of them\n app.post(\n '/prompts/:id',\n answerPromptHandler({ sessionFactory, claims, openPrompts, attribution }),\n );\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, TTurnAttribution } 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 /** Who `/submit` turns are attributed to — forwarded to `createAgentRoutes`, like `admission`. */\n attribution?: TTurnAttribution;\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 attribution: options?.attribution,\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":"0PAkCA,SAAgB,GAA0C,CACxD,IAAM,EAAY,IAAI,IAEtB,MAAO,CACL,OAAO,EAAY,EAAO,CACxB,IAAI,EAAO,EAAU,IAAI,CAAU,EAC/B,IAAS,IAAA,KACX,EAAO,IAAI,IACX,EAAU,IAAI,EAAY,CAAI,GAEhC,EAAK,IAAI,EAAM,MAAM,GAAI,CAAK,CAChC,EACA,OAAO,EAAY,EAAI,CACrB,EAAU,IAAI,CAAU,CAAC,EAAE,OAAO,CAAE,CACtC,EACA,KAAO,GAAe,CAAC,GAAI,EAAU,IAAI,CAAU,CAAC,EAAE,OAAO,GAAK,CAAC,CAAE,EACrE,MAAO,EAAY,IAAO,EAAU,IAAI,CAAU,CAAC,EAAE,IAAI,CAAE,EAC3D,MAAM,EAAY,CAChB,EAAU,OAAO,CAAU,CAC7B,CACF,CACF,CC/BA,SAAgB,EAAmB,EAAwB,CACzD,OAAO,KAAO,IAAe,CAC3B,IAAM,EAAU,MAAM,EAAK,eAAe,CAAC,EACrC,EAAM,EAAK,OAAO,OAAO,CAAO,EACtC,OAAO,EAAE,KAAK,CAAE,QAAS,IAAQ,IAAA,GAAY,CAAC,EAAI,EAAK,YAAY,KAAK,CAAG,CAAE,CAAC,CAChF,CACF,CAoBA,SAAgB,EAAoB,EAAwB,CAC1D,GAAM,CAAE,iBAAgB,SAAQ,cAAa,eAAgB,EAC7D,OAAO,KAAO,IAAe,CAC3B,IAAM,EAAU,MAAM,EAAe,CAAC,EAChC,EAAK,EAAE,IAAI,MAAM,IAAI,GAAK,GAC5B,EACJ,GAAI,CAC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AC1B,YAAa,GAAS,WACxB,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/open-prompts.ts","../../src/prompt-routes.ts","../../src/submit-stream.ts","../../src/submit-route.ts","../../src/turn-claims.ts","../../src/routes.ts","../../src/http-transport.ts"],"sourcesContent":["/**\n * The permission and ask prompts a `/submit` stream forwarded and that are still open, per session.\n *\n * The session emits a prompt once, when it is asked, so a client that comes later would never see\n * it; `GET /prompts` answers from here, and `POST /prompts/:id` refuses an id that is not here.\n *\n * Keyed by the session's id, the same key as the turn claim, and not by object identity: the session\n * factory may return a fresh wrapper per request, so the `agent-transport` registry (a WeakMap on the\n * session object) would never find the prompt a different request recorded.\n *\n * It learns only through the prompt-receiving stream's own subscriptions and never listens to the\n * session itself. A listener of its own would keep an unattended turn's prompt parked instead of\n * letting the session fail it closed. A session's entries go when that stream's claim is released.\n */\n\nimport type {\n IAskRequestEvent,\n IPermissionRequestEvent,\n} from '@robota-sdk/agent-interface-session';\n\nexport type THttpPromptFrame =\n | { readonly type: 'permission_request'; readonly event: IPermissionRequestEvent }\n | { readonly type: 'ask_request'; readonly event: IAskRequestEvent };\n\nexport interface IHttpOpenPrompts {\n record(sessionKey: string, frame: THttpPromptFrame): void;\n forget(sessionKey: string, id: string): void;\n /** The session's open prompts, oldest first. */\n list(sessionKey: string): readonly THttpPromptFrame[];\n find(sessionKey: string, id: string): THttpPromptFrame | undefined;\n /** The stream that received the session's prompts has ended. */\n clear(sessionKey: string): void;\n}\n\nexport function createHttpOpenPrompts(): IHttpOpenPrompts {\n const bySession = new Map<string, Map<string, THttpPromptFrame>>();\n\n return {\n record(sessionKey, frame) {\n let open = bySession.get(sessionKey);\n if (open === undefined) {\n open = new Map();\n bySession.set(sessionKey, open);\n }\n open.set(frame.event.id, frame);\n },\n forget(sessionKey, id) {\n bySession.get(sessionKey)?.delete(id);\n },\n list: (sessionKey) => [...(bySession.get(sessionKey)?.values() ?? [])],\n find: (sessionKey, id) => bySession.get(sessionKey)?.get(id),\n clear(sessionKey) {\n bySession.delete(sessionKey);\n },\n };\n}\n","/**\n * `GET /prompts` and `POST /prompts/:id` — reading and answering the permission and ask prompts a\n * prompt-receiving `/submit` stream forwarded.\n *\n * Split from `routes.ts` for the same reason `/submit` is: these routes carry a decision of their own\n * (is this id open here, and is this answer the right kind for it), not just a mount.\n */\n\nimport { decodeClientMessage } from '@robota-sdk/agent-transport';\n\nimport type { IHttpOpenPrompts } from './open-prompts.js';\nimport type { TSessionFactory } from './submit-route.js';\nimport type { TTurnAttribution } from './submit-stream.js';\nimport type { ITurnClaims } from './turn-claims.js';\nimport type { Context } from 'hono';\n\nexport interface IPromptRouteDeps {\n readonly sessionFactory: TSessionFactory;\n readonly claims: ITurnClaims;\n readonly openPrompts: IHttpOpenPrompts;\n readonly attribution?: TTurnAttribution;\n}\n\n/** The open prompts of the request's session, oldest first: what a client that came later reads. */\nexport function listPromptsHandler(deps: IPromptRouteDeps) {\n return async (c: Context) => {\n const session = await deps.sessionFactory(c);\n const key = deps.claims.keyFor(session);\n return c.json({ prompts: key === undefined ? [] : deps.openPrompts.list(key) });\n };\n}\n\n/**\n * Answer one open prompt by id.\n *\n * The id must be one this session's prompt-receiving stream forwarded and that is still open. An id\n * that never was and one already settled get the same 404: the client cannot act differently on the\n * two, and the registry forgets a prompt once it settles.\n *\n * The answerer is the HOST's `attribution.driverId`, never the request, for the same reason `/submit`\n * attribution is: a client must not record its answer as another surface's.\n *\n * Nothing awaits between the lookup and the resolve. The session settles synchronously and emits\n * `prompt_resolved`, which the stream forwards and the registry forgets, so a second answer for the\n * same id finds nothing open and is refused rather than reported as accepted.\n *\n * `200` means the prompt settled, not merely that the answer was handed over: the session ignores an\n * answer it does not take (one in an outside party's name, say), and a prompt still open after the\n * resolve is answered `409` so the client does not believe it decided something it did not.\n */\nexport function answerPromptHandler(deps: IPromptRouteDeps) {\n const { sessionFactory, claims, openPrompts, attribution } = deps;\n return async (c: Context) => {\n const session = await sessionFactory(c);\n const id = c.req.param('id') ?? '';\n let body: { result?: unknown; response?: unknown };\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'the body must be a JSON object' }, 400);\n }\n\n const key = claims.keyFor(session);\n const frame = key === undefined ? undefined : openPrompts.find(key, id);\n if (key === undefined || frame === undefined) {\n return c.json({ error: 'no open prompt with this id' }, 404);\n }\n\n if (frame.type === 'permission_request') {\n const decoded = decodeClientMessage({\n type: 'permission-response',\n id,\n result: body?.result,\n });\n if (!decoded.ok || decoded.message.type !== 'permission-response') {\n return c.json(\n { error: 'result must be true, false, \"allow-session\" or \"allow-project\"' },\n 400,\n );\n }\n session.resolvePermission(id, decoded.message.result, attribution?.driverId);\n } else {\n const decoded = decodeClientMessage({ type: 'ask-response', id, response: body?.response });\n if (!decoded.ok || decoded.message.type !== 'ask-response') {\n return c.json(\n {\n error:\n 'response must be { \"type\": \"answer\", \"values\": string[], \"text\"?: string } or ' +\n '{ \"type\": \"cancelled\" }',\n },\n 400,\n );\n }\n session.resolveAsk(id, decoded.message.response, attribution?.driverId);\n }\n if (openPrompts.find(key, id) !== undefined) {\n return c.json({ error: 'the session did not accept this answer' }, 409);\n }\n return c.json({ ok: true });\n };\n}\n","/**\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 { THttpPromptFrame } from './open-prompts.js';\nimport type { SSEStreamingApi } from 'hono/streaming';\nimport type {\n IAskRequestEvent,\n IPermissionRequestEvent,\n IPromptResolvedEvent,\n ISubmitOptions,\n} from '@robota-sdk/agent-interface-session';\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 * Who a submitted turn is attributed to, assigned by the HOST that composed the routes — never read\n * from the request, because a client could otherwise claim to be the local operator or another\n * surface in the usage record. Absent means the session's own default.\n */\nexport type TTurnAttribution = Pick<ISubmitOptions, 'driverId' | 'surface'>;\n\n/**\n * Where a prompt-receiving stream reports the prompts it forwarded, so a later request can list or\n * answer them. Present only when the client asked to receive prompts.\n */\nexport interface IRelayPrompts {\n record(frame: THttpPromptFrame): void;\n forget(id: string): void;\n}\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 prompts: IRelayPrompts | 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 if (prompts !== undefined) subscribePrompts(subscribe, write, prompts);\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 * Forward the turn's permission and ask prompts, and their settlement, to a client that said it can\n * answer them.\n *\n * Only such a client subscribes: the session parks a prompt only while someone listens for it, so a\n * client that cannot answer must not listen, or the turn would wait on a prompt nobody settles\n * instead of failing it closed at once.\n */\nfunction subscribePrompts(\n subscribe: <T>(event: string, handler: (data: T) => void) => void,\n write: (event: string, data: unknown) => Promise<void>,\n prompts: IRelayPrompts,\n): void {\n subscribe('permission_request', (event: IPermissionRequestEvent) => {\n prompts.record({ type: 'permission_request', event });\n void write('permission_request', event);\n });\n subscribe('ask_request', (event: IAskRequestEvent) => {\n prompts.record({ type: 'ask_request', event });\n void write('ask_request', event);\n });\n subscribe('prompt_resolved', (event: IPromptResolvedEvent) => {\n prompts.forget(event.id);\n void write('prompt_resolved', event);\n });\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 attribution?: TTurnAttribution,\n prompts?: IRelayPrompts,\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, prompts);\n await (attribution === undefined\n ? session.submit(prompt)\n : session.submit(prompt, undefined, undefined, { ...attribution }));\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 { IHttpOpenPrompts } from './open-prompts.js';\nimport type { IRelayPrompts, TStreamFailureListener, TTurnAttribution } 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 interface ISubmitRouteDeps {\n readonly sessionFactory: TSessionFactory;\n readonly claims: ITurnClaims;\n readonly openPrompts: IHttpOpenPrompts;\n readonly onStreamFailure?: TStreamFailureListener;\n readonly attribution?: TTurnAttribution;\n}\n\nexport function submitHandler(deps: ISubmitRouteDeps) {\n const { sessionFactory, claims, openPrompts, onStreamFailure, attribution } = deps;\n return async (c: Context) => {\n const session = await sessionFactory(c);\n const body = await c.req.json<{ prompt: string; receivePrompts?: unknown }>();\n\n if (!body.prompt || typeof body.prompt !== 'string') {\n return c.json({ error: 'prompt is required' }, 400);\n }\n if (body.receivePrompts !== undefined && typeof body.receivePrompts !== 'boolean') {\n return c.json({ error: 'receivePrompts must be a boolean' }, 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 // The stream that held this session's prompts is gone; what is still open is the session's\n // to settle, and no longer this route's to list or answer.\n openPrompts.clear(claim);\n claims.release(claim);\n }\n };\n const prompts: IRelayPrompts | undefined =\n body.receivePrompts === true\n ? {\n record: (frame) => openPrompts.record(claim, frame),\n forget: (id) => openPrompts.forget(claim, id),\n }\n : undefined;\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(\n c,\n relayTurn(session, body.prompt, releaseOnce, onStreamFailure, attribution, prompts),\n );\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';\nimport { bodyLimit } from 'hono/body-limit';\n\nimport { createHttpOpenPrompts } from './open-prompts.js';\nimport { answerPromptHandler, listPromptsHandler } from './prompt-routes.js';\nimport { submitHandler } from './submit-route.js';\nimport { createTurnClaims } from './turn-claims.js';\n\nimport type { TSessionFactory } from './submit-route.js';\nimport type { TStreamFailureListener, TTurnAttribution } 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 * Who `/submit` turns and prompt answers are attributed to — the driver and product surface the\n * HOST assigns, as the WebSocket transport's `driverId`/`surface` do. Never taken from the request\n * body. Absent leaves the session's own default.\n */\n attribution?: TTurnAttribution;\n /** Maximum bytes accepted by a JSON request route. Default 64 KiB. */\n maxJsonBodyBytes?: number;\n}\n\nconst DEFAULT_MAX_JSON_BODY_BYTES = 64 * 1024;\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, attribution } = 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 const openPrompts = createHttpOpenPrompts();\n const maxJsonBodyBytes = options.maxJsonBodyBytes ?? DEFAULT_MAX_JSON_BODY_BYTES;\n if (!Number.isSafeInteger(maxJsonBodyBytes) || maxJsonBodyBytes < 1) {\n throw new Error('maxJsonBodyBytes must be a positive integer');\n }\n const limitJsonBody = bodyLimit({\n maxSize: maxJsonBodyBytes,\n onError: (c) => c.json({ error: 'request body too large' }, 413),\n });\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(\n '/submit',\n limitJsonBody,\n submitHandler({ sessionFactory, claims, openPrompts, onStreamFailure, attribution }),\n );\n\n // GET /prompts — the open permission/ask prompts a prompt-receiving /submit stream forwarded\n app.get('/prompts', listPromptsHandler({ sessionFactory, claims, openPrompts, attribution }));\n\n // POST /prompts/:id — answer one of them\n app.post(\n '/prompts/:id',\n limitJsonBody,\n answerPromptHandler({ sessionFactory, claims, openPrompts, attribution }),\n );\n\n // POST /command — execute system command\n app.post('/command', limitJsonBody, 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, TTurnAttribution } 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 /** Who `/submit` turns are attributed to — forwarded to `createAgentRoutes`, like `admission`. */\n attribution?: TTurnAttribution;\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 attribution: options?.attribution,\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":"sSAkCA,SAAgB,GAA0C,CACxD,IAAM,EAAY,IAAI,IAEtB,MAAO,CACL,OAAO,EAAY,EAAO,CACxB,IAAI,EAAO,EAAU,IAAI,CAAU,EAC/B,IAAS,IAAA,KACX,EAAO,IAAI,IACX,EAAU,IAAI,EAAY,CAAI,GAEhC,EAAK,IAAI,EAAM,MAAM,GAAI,CAAK,CAChC,EACA,OAAO,EAAY,EAAI,CACrB,EAAU,IAAI,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@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@robota-sdk/agent-transport-http",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.1",
|
|
4
4
|
"description": "HTTP (Hono) transport for the Robota SDK",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/node/index.js",
|
|
@@ -41,9 +41,9 @@
|
|
|
41
41
|
],
|
|
42
42
|
"dependencies": {
|
|
43
43
|
"hono": "^4.12.32",
|
|
44
|
-
"@robota-sdk/agent-interface-session": "3.0.
|
|
45
|
-
"@robota-sdk/agent-interface-transport": "3.0.
|
|
46
|
-
"@robota-sdk/agent-transport": "3.0.
|
|
44
|
+
"@robota-sdk/agent-interface-session": "3.0.1",
|
|
45
|
+
"@robota-sdk/agent-interface-transport": "3.0.1",
|
|
46
|
+
"@robota-sdk/agent-transport": "3.0.1"
|
|
47
47
|
},
|
|
48
48
|
"devDependencies": {
|
|
49
49
|
"rimraf": "^5.0.10",
|
|
@@ -199,6 +199,79 @@ describe('HTTP Transport Routes', () => {
|
|
|
199
199
|
return { app, mockSession };
|
|
200
200
|
}
|
|
201
201
|
|
|
202
|
+
it.each(['/submit', '/command', '/prompts/prompt-1'])(
|
|
203
|
+
'refuses an oversized JSON body on %s before resolving a session',
|
|
204
|
+
async (pathname) => {
|
|
205
|
+
const sessionFactory = vi.fn(() => createMockSession());
|
|
206
|
+
const app = createAgentRoutes({
|
|
207
|
+
sessionFactory,
|
|
208
|
+
admission: { token: 'expected-token' },
|
|
209
|
+
maxJsonBodyBytes: 16,
|
|
210
|
+
});
|
|
211
|
+
const response = await app.request(pathname, {
|
|
212
|
+
method: 'POST',
|
|
213
|
+
headers: {
|
|
214
|
+
authorization: 'Bearer expected-token',
|
|
215
|
+
'content-type': 'application/json',
|
|
216
|
+
'content-length': '128',
|
|
217
|
+
},
|
|
218
|
+
body: JSON.stringify({ value: 'x'.repeat(100) }),
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
expect(response.status).toBe(413);
|
|
222
|
+
expect(sessionFactory).not.toHaveBeenCalled();
|
|
223
|
+
},
|
|
224
|
+
);
|
|
225
|
+
|
|
226
|
+
it('refuses an oversized streamed JSON body without Content-Length', async () => {
|
|
227
|
+
const sessionFactory = vi.fn(() => createMockSession());
|
|
228
|
+
const app = createAgentRoutes({
|
|
229
|
+
sessionFactory,
|
|
230
|
+
admission: { token: 'expected-token' },
|
|
231
|
+
maxJsonBodyBytes: 16,
|
|
232
|
+
});
|
|
233
|
+
const body = new ReadableStream<Uint8Array>({
|
|
234
|
+
start(controller) {
|
|
235
|
+
controller.enqueue(new TextEncoder().encode('{"value":"'));
|
|
236
|
+
controller.enqueue(new TextEncoder().encode('x'.repeat(100)));
|
|
237
|
+
controller.enqueue(new TextEncoder().encode('"}'));
|
|
238
|
+
controller.close();
|
|
239
|
+
},
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
const request = new Request('http://localhost/submit', {
|
|
243
|
+
method: 'POST',
|
|
244
|
+
headers: {
|
|
245
|
+
authorization: 'Bearer expected-token',
|
|
246
|
+
'content-type': 'application/json',
|
|
247
|
+
},
|
|
248
|
+
body,
|
|
249
|
+
duplex: 'half',
|
|
250
|
+
} as RequestInit & { duplex: 'half' });
|
|
251
|
+
const response = await app.request(request);
|
|
252
|
+
|
|
253
|
+
expect(response.status).toBe(413);
|
|
254
|
+
expect(sessionFactory).not.toHaveBeenCalled();
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
it('keeps authentication ahead of the JSON body limit', async () => {
|
|
258
|
+
const sessionFactory = vi.fn(() => createMockSession());
|
|
259
|
+
const app = createAgentRoutes({
|
|
260
|
+
sessionFactory,
|
|
261
|
+
admission: { token: 'expected-token' },
|
|
262
|
+
maxJsonBodyBytes: 16,
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
const response = await app.request('/submit', {
|
|
266
|
+
method: 'POST',
|
|
267
|
+
headers: { 'content-type': 'application/json', 'content-length': '128' },
|
|
268
|
+
body: JSON.stringify({ value: 'x'.repeat(100) }),
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
expect(response.status).toBe(401);
|
|
272
|
+
expect(sessionFactory).not.toHaveBeenCalled();
|
|
273
|
+
});
|
|
274
|
+
|
|
202
275
|
// ── POST /abort ───────────────────────────────────────────────
|
|
203
276
|
|
|
204
277
|
it('POST /abort calls session.abort()', async () => {
|
package/src/routes.ts
CHANGED
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
resolveAdmission,
|
|
13
13
|
} from '@robota-sdk/agent-transport/node';
|
|
14
14
|
import { Hono } from 'hono';
|
|
15
|
+
import { bodyLimit } from 'hono/body-limit';
|
|
15
16
|
|
|
16
17
|
import { createHttpOpenPrompts } from './open-prompts.js';
|
|
17
18
|
import { answerPromptHandler, listPromptsHandler } from './prompt-routes.js';
|
|
@@ -52,8 +53,12 @@ export interface IAgentRoutesOptions {
|
|
|
52
53
|
* body. Absent leaves the session's own default.
|
|
53
54
|
*/
|
|
54
55
|
attribution?: TTurnAttribution;
|
|
56
|
+
/** Maximum bytes accepted by a JSON request route. Default 64 KiB. */
|
|
57
|
+
maxJsonBodyBytes?: number;
|
|
55
58
|
}
|
|
56
59
|
|
|
60
|
+
const DEFAULT_MAX_JSON_BODY_BYTES = 64 * 1024;
|
|
61
|
+
|
|
57
62
|
/**
|
|
58
63
|
* Create a Hono router with all agent HTTP endpoints.
|
|
59
64
|
*
|
|
@@ -72,6 +77,14 @@ export function createAgentRoutes(options: IAgentRoutesOptions): Hono {
|
|
|
72
77
|
// is keyed by the session's declared ID rather than by object identity.
|
|
73
78
|
const claims = createTurnClaims();
|
|
74
79
|
const openPrompts = createHttpOpenPrompts();
|
|
80
|
+
const maxJsonBodyBytes = options.maxJsonBodyBytes ?? DEFAULT_MAX_JSON_BODY_BYTES;
|
|
81
|
+
if (!Number.isSafeInteger(maxJsonBodyBytes) || maxJsonBodyBytes < 1) {
|
|
82
|
+
throw new Error('maxJsonBodyBytes must be a positive integer');
|
|
83
|
+
}
|
|
84
|
+
const limitJsonBody = bodyLimit({
|
|
85
|
+
maxSize: maxJsonBodyBytes,
|
|
86
|
+
onError: (c) => c.json({ error: 'request body too large' }, 413),
|
|
87
|
+
});
|
|
75
88
|
|
|
76
89
|
// SEC-008: resolved ONCE, at construction, so a transport that cannot mint a credential fails to
|
|
77
90
|
// build rather than serving without one. Resolving per request would also mint a new token per
|
|
@@ -109,6 +122,7 @@ export function createAgentRoutes(options: IAgentRoutesOptions): Hono {
|
|
|
109
122
|
// POST /submit — execute prompt, stream events via SSE
|
|
110
123
|
app.post(
|
|
111
124
|
'/submit',
|
|
125
|
+
limitJsonBody,
|
|
112
126
|
submitHandler({ sessionFactory, claims, openPrompts, onStreamFailure, attribution }),
|
|
113
127
|
);
|
|
114
128
|
|
|
@@ -118,11 +132,12 @@ export function createAgentRoutes(options: IAgentRoutesOptions): Hono {
|
|
|
118
132
|
// POST /prompts/:id — answer one of them
|
|
119
133
|
app.post(
|
|
120
134
|
'/prompts/:id',
|
|
135
|
+
limitJsonBody,
|
|
121
136
|
answerPromptHandler({ sessionFactory, claims, openPrompts, attribution }),
|
|
122
137
|
);
|
|
123
138
|
|
|
124
139
|
// POST /command — execute system command
|
|
125
|
-
app.post('/command', async (c) => {
|
|
140
|
+
app.post('/command', limitJsonBody, async (c) => {
|
|
126
141
|
const session = await sessionFactory(c);
|
|
127
142
|
const body = await c.req.json<{ name: string; args?: string }>();
|
|
128
143
|
|