@robota-sdk/agent-transport-http 3.0.0-beta.78 → 3.0.0-beta.81

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.
@@ -0,0 +1,162 @@
1
+ /**
2
+ * `POST /submit` — the admission decision and the handler that hands an admitted turn to the relay.
3
+ *
4
+ * Split from `routes.ts` under the file-size ceiling, along the same seam the review rounds carved:
5
+ * the route factory is a LIST of routes, and this one carries the concurrency-admission decision
6
+ * plus the claim lifecycle, which is a different job from mounting endpoints.
7
+ */
8
+
9
+ import { streamSSE } from 'hono/streaming';
10
+
11
+ import { relayTurn } from './submit-stream.js';
12
+
13
+ import type { IHttpTransportSession } from './http-session.js';
14
+ import type { TStreamFailureListener } from './submit-stream.js';
15
+ import type { ITurnClaims } from './turn-claims.js';
16
+ import type { Context } from 'hono';
17
+
18
+ /**
19
+ * Callback that resolves an HTTP session port from the request context.
20
+ *
21
+ * It need NOT return the same object twice for the same logical session. It briefly did: `/submit`
22
+ * keyed its concurrent-turn claim on object identity, so a factory building a fresh wrapper per
23
+ * call — a proxy, an adapter, a `{...session}` copy — defeated the guard in silence. The first
24
+ * answer was to document that as a requirement callers had to keep, and a requirement neither the
25
+ * type system nor a test can check is not a contract, it is a hope.
26
+ *
27
+ * What the session already promises is enough. `getSession(): { getSessionId(): string }` names the
28
+ * session, the claim is keyed by that name, and the requirement is gone rather than written down.
29
+ *
30
+ * The session must therefore BE nameable. `/submit` refuses with 500 when `getSessionId()` returns
31
+ * nothing, because without an id the concurrent-turn guarantee does not exist and serving anyway
32
+ * would hand back the bug to whoever could least tell. The contract types that method as returning
33
+ * a `string`, so a conformant session never meets it.
34
+ *
35
+ * (Review moved this block here: it sat on the RE-EXPORT in `routes.ts` after the split, where the
36
+ * person editing the definition would never see it.)
37
+ */
38
+ export type TSessionFactory = (
39
+ c: Context,
40
+ ) => IHttpTransportSession | Promise<IHttpTransportSession>;
41
+
42
+ /**
43
+ * Admit this request to ONE turn on its session, or answer why not.
44
+ *
45
+ * Returns the claim key it HOLDS on success — the caller owes its release — or the refusal
46
+ * Response. A named unit, and review is why: the admission decision (nameable? busy? claim) is what
47
+ * this route decides, independently testable from the stream wiring it hands the turn to.
48
+ */
49
+ function admitTurn(
50
+ c: Context,
51
+ session: IHttpTransportSession,
52
+ claims: ITurnClaims,
53
+ ): Response | { claim: string } {
54
+ // RUNTIME-38: the session is single-threaded (one turn at a time) and shared across requests, so a
55
+ // concurrent /submit would cross-subscribe to the same emitter and interleave two clients' events.
56
+ //
57
+ // The route CLAIMS the turn rather than asking whether one is running, and that difference is the
58
+ // whole fix. `session.isExecuting()` is set inside `submit()` past an `await ensureInitialized()`
59
+ // — an unconditional suspension point — so two requests both read `false`, both call `submit`, and
60
+ // the loser coalesces into the pending queue while its HTTP response streams back the WINNER'S
61
+ // events. One turn delivered to two clients as if each had asked for it, which is worse than the
62
+ // race the earlier comment described and then wrongly declared absent.
63
+ //
64
+ // A synchronous flag on the route closes it because there is no suspension point between reading
65
+ // and setting it. It is released in the stream's `finally`, so a turn that throws does not leave
66
+ // the route wedged.
67
+ //
68
+ // BOTH are asked because neither subsumes the other. The claim is what this ROUTE knows;
69
+ // `isExecuting()` is what the SESSION knows, including a turn started by another surface — the
70
+ // TUI, a WS client, a previous process — which the claim cannot see.
71
+ // A session that cannot name itself is REFUSED, not served racily. The busy check is a guarantee
72
+ // only while the claim is keyed by a real id: with no id it falls back to `isExecuting()` alone,
73
+ // which the comment above documents as the racy read this route exists to stop relying on.
74
+ // Serving anyway would degrade the fix back into the bug for exactly the callers who could not
75
+ // be told they were affected.
76
+ //
77
+ // `getSession(): { getSessionId(): string }` is required by the contract, so this is unreachable
78
+ // for a conformant session. It is a 500 rather than a 503: the session is not temporarily
79
+ // unavailable, it does not meet the contract this route is built on, which is a defect on the
80
+ // server side of the boundary and not a condition that clears on retry.
81
+ const claim = claims.keyFor(session);
82
+ if (claim === undefined) {
83
+ return c.json(
84
+ {
85
+ // No internal method signature: this route can be mounted outside a trust boundary, and
86
+ // the caller cannot act on `getSession().getSessionId()` anyway — it names a contract
87
+ // they do not implement. The HOST needs the detail and gets it from the comment above
88
+ // this branch; the client needs to know its request was refused and why in its own terms.
89
+ error:
90
+ 'concurrent-turn tracking is unavailable for this session, so this request cannot be ' +
91
+ 'served safely. Refusing rather than starting a turn that cannot be guaranteed to be ' +
92
+ 'yours.',
93
+ },
94
+ 500,
95
+ );
96
+ }
97
+ if (claims.isHeld(claim) || session.isExecuting()) {
98
+ return c.json({ error: 'session busy — a turn is already in flight' }, 409);
99
+ }
100
+ claims.hold(claim);
101
+ return { claim };
102
+ }
103
+
104
+ export function submitHandler(
105
+ sessionFactory: TSessionFactory,
106
+ claims: ITurnClaims,
107
+ onStreamFailure?: TStreamFailureListener,
108
+ ) {
109
+ return async (c: Context) => {
110
+ const session = await sessionFactory(c);
111
+ const body = await c.req.json<{ prompt: string }>();
112
+
113
+ if (!body.prompt || typeof body.prompt !== 'string') {
114
+ return c.json({ error: 'prompt is required' }, 400);
115
+ }
116
+
117
+ const admitted = admitTurn(c, session, claims);
118
+ if (admitted instanceof Response) {
119
+ return admitted;
120
+ }
121
+ const { claim } = admitted;
122
+ // SINGLE-SHOT, and review traced the double-release it prevents: the relay's teardown releases
123
+ // this claim on the normal path, and if a future Hono ever rejected the outer promise AFTER the
124
+ // callback completed, the catch below would release the SAME KEY a second time — by which point
125
+ // another request may hold it, and the second release would free that request's claim, which is
126
+ // the cross-talk this registry exists to prevent. A release that has happened is not a release
127
+ // that can happen again.
128
+ let released = false;
129
+ const releaseOnce = (): void => {
130
+ if (!released) {
131
+ released = true;
132
+ claims.release(claim);
133
+ }
134
+ };
135
+
136
+ // The claim is taken OUTSIDE the callback, so its release cannot live only in the callback's
137
+ // `finally` — a claim whose release is not in the same protected region is a lock, not a claim,
138
+ // which this file states one level in. If `streamSSE` throws before it ever runs the callback,
139
+ // this releases and rethrows; the callback's own `finally` covers everything after it starts.
140
+ //
141
+ // REPRODUCED at the module boundary: `routes-streamsse-throw.test.ts` mocks `hono/streaming`
142
+ // to throw before the callback ever runs and asserts the second request is not 409 — a leaked
143
+ // claim is what this catch exists to prevent. Two rounds shipped it as honestly-labelled
144
+ // unverified code (a throw from `session.on` lands INSIDE the callback, where the inner
145
+ // `finally` releases — measured, a case built that way is green with this catch removed), and
146
+ // review supplied the third option: stub the boundary, not Hono's internals.
147
+ try {
148
+ // NO third argument, deliberately: Hono's runner follows any `onError` by writing the raw
149
+ // `e.message` to the stream, so the only leak-proof shape is a callback nothing escapes —
150
+ // `relayTurn` catches its own failures and reports them generically. An onError here would be
151
+ // dead code that turns into a leak the day it stops being dead.
152
+ // `await`, so the catch below covers a REJECTION as well as a synchronous throw. Today's
153
+ // Hono returns the Response synchronously and only the sync path is real — but review is
154
+ // right that a version returning a rejecting promise would sail past a bare `return`, and
155
+ // the cost of closing that class is one keyword.
156
+ return await streamSSE(c, relayTurn(session, body.prompt, releaseOnce, onStreamFailure));
157
+ } catch (error) {
158
+ releaseOnce();
159
+ throw error;
160
+ }
161
+ };
162
+ }
@@ -0,0 +1,233 @@
1
+ /**
2
+ * RUNTIME-14 / RUNTIME-38 — relaying ONE turn to an SSE client, and letting go of it afterwards.
3
+ *
4
+ * Split out of `routes.ts` under the file-size ceiling. The route's job is to decide whether this
5
+ * request may start a turn; relaying the turn's events, tearing the subscriptions down, and telling
6
+ * a client whose stream broke after the headers went out is a different job with its own failure
7
+ * modes, and it was four fifths of the handler.
8
+ */
9
+
10
+ import type { IHttpTransportSession } from './http-session.js';
11
+ import type { SSEStreamingApi } from 'hono/streaming';
12
+
13
+ /**
14
+ * Where the DETAIL of a post-headers stream failure goes — injected, never imported.
15
+ *
16
+ * The first version imported `createLogger` from `agent-core`, and review held it against two
17
+ * authorities at once: `project-structure.md` declares this package contract-pure (transports
18
+ * depend on the contracts and the protocol, nothing else), and its side-concern rule says a logging
19
+ * destination "must be injected, not imported directly". The host that mounts this router decides
20
+ * where diagnostics go; a module-level singleton decided it for every host, with no override.
21
+ *
22
+ * Absent, the detail is dropped — by the HOST's explicit default, which is a different thing from
23
+ * this module deleting it: the client still learns the stream failed, and the host was offered the
24
+ * detail at the boundary where it mounts the route.
25
+ */
26
+ export type TStreamFailureListener = (error: Error) => void;
27
+
28
+ /**
29
+ * Wire every relay subscription and the abort path; answer with the promise that settles when the
30
+ * turn is over (or refused one).
31
+ *
32
+ * The subscriptions are wired OUTSIDE the promise executor. Inside it, a throw from `session.on` —
33
+ * a bad handler, an EventEmitter listener cap — is caught by the Promise constructor and becomes an
34
+ * already-rejected `done` instead of propagating. Execution then reaches `await session.submit`, so
35
+ * a REAL TURN is consumed with only some of its listeners attached and nothing to relay it, and the
36
+ * rejection surfaces afterwards at `await done` — by which point the turn is gone.
37
+ */
38
+ function wireRelay(
39
+ session: IHttpTransportSession,
40
+ stream: SSEStreamingApi,
41
+ cleanup: Array<() => void>,
42
+ onFailure: TStreamFailureListener | undefined,
43
+ ): Promise<void> {
44
+ const subscribe = <T>(event: string, handler: (data: T) => void): void => {
45
+ session.on(event as 'text_delta', handler as () => void);
46
+ cleanup.push(() => session.off(event as 'text_delta', handler as () => void));
47
+ };
48
+
49
+ // RUNTIME-14: await + catch every SSE write so a write to a client-closed stream is a blessed
50
+ // no-op, not an unhandled rejection (post-headers errors bypass Hono's onError).
51
+ const write = (event: string, data: unknown): Promise<void> =>
52
+ stream.writeSSE({ event, data: JSON.stringify(data) }).catch(() => {
53
+ // allow-fallback: client closed the stream mid-write — nothing to deliver; the finally teardown
54
+ // (RUNTIME-14) removes the listeners, so this write has nothing left to do.
55
+ });
56
+
57
+ let settle!: () => void;
58
+ const done = new Promise<void>((resolve) => {
59
+ settle = resolve;
60
+ });
61
+
62
+ subscribe('text_delta', (delta: string) => void write('text_delta', { delta }));
63
+ subscribe('tool_start', (state) => void write('tool_start', state));
64
+ subscribe('tool_end', (state) => void write('tool_end', state));
65
+ subscribe('thinking', (isThinking: boolean) => void write('thinking', { isThinking }));
66
+
67
+ // Flush the terminal event before resolving, so the resolve → cleanup → stream-close
68
+ // continuation cannot race ahead of the write.
69
+ subscribe('complete', async (result) => {
70
+ await write('complete', result);
71
+ settle();
72
+ });
73
+ subscribe('interrupted', async (result) => {
74
+ await write('interrupted', result);
75
+ settle();
76
+ });
77
+ subscribe('error', async (error: Error) => {
78
+ await write('error', { message: error.message });
79
+ settle();
80
+ });
81
+
82
+ // RUNTIME-14: on client disconnect, CANCEL the underlying run (not merely stop writing) and
83
+ // unblock `done` so the finally teardown runs — otherwise `done` would never resolve and the
84
+ // listeners leak.
85
+ stream.onAbort(() => onClientAbort(session, onFailure, settle));
86
+
87
+ return done;
88
+ }
89
+
90
+ /**
91
+ * The abort path, alone, because every clause of it is load-bearing and review shaped each one.
92
+ *
93
+ * `settle` in a `finally`: an `abort()` that throws used to cost a listener leak, and with the
94
+ * claim registry it costs the SESSION — `done` never resolves, the teardown never runs, the claim
95
+ * is held forever, and every future /submit is 409.
96
+ *
97
+ * The throw is REPORTED, not rethrown: this handler runs inside Hono's abort dispatch, OUTSIDE the
98
+ * relay's try/catch, so a rethrow is an unhandled rejection rather than a reported failure. The
99
+ * detail goes where every other stream failure's detail goes.
100
+ */
101
+ function onClientAbort(
102
+ session: IHttpTransportSession,
103
+ onFailure: TStreamFailureListener | undefined,
104
+ settle: () => void,
105
+ ): void {
106
+ try {
107
+ session.abort();
108
+ } catch (error) {
109
+ // allow-fallback: an abort that throws is the HOST's news, not the runner's
110
+ try {
111
+ onFailure?.(error instanceof Error ? error : new Error(String(error)));
112
+ } catch {
113
+ // allow-fallback: a listener that throws must not replace the abort path's settle
114
+ // Same rule as reportStreamFailure: the host's listener failing is the host's to see.
115
+ }
116
+ } finally {
117
+ settle();
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Teardown that cannot take the claim with it.
123
+ *
124
+ * Each entry individually, and review is why: these are `session.off` calls, and one that throws
125
+ * inside a bare loop would end the caller's `finally` before `release()` ran — the same
126
+ * claim-held-forever the abort path closes, reintroduced two lines down. A failed unsubscribe
127
+ * forfeits one listener; taking the release with it forfeits the session.
128
+ */
129
+ function teardown(cleanup: Array<() => void>, release: () => void): void {
130
+ for (const fn of cleanup) {
131
+ try {
132
+ fn();
133
+ } catch {
134
+ // allow-fallback: a failed unsubscribe must not take the claim release with it
135
+ // The listener stays attached — the lesser loss, and the one the next turn can survive.
136
+ }
137
+ }
138
+ // RUNTIME-38: released here for the same reason — a turn that throws must not wedge the session
139
+ // it claimed.
140
+ release();
141
+ }
142
+
143
+ /**
144
+ * The `streamSSE` callback for one submitted prompt.
145
+ *
146
+ * `release` is called in the teardown, ALWAYS — on completion, on error, and on client disconnect.
147
+ * It is passed in rather than taken here because the claim is made before the stream opens: a claim
148
+ * whose release lives only inside the stream is a lock that outlives the request that took it.
149
+ * (This block sat on `wireRelay` for one round after the split stranded it — the stale-doc shape
150
+ * this file keeps writing about, caught doing it.)
151
+ */
152
+ export function relayTurn(
153
+ session: IHttpTransportSession,
154
+ prompt: string,
155
+ release: () => void,
156
+ onFailure?: TStreamFailureListener,
157
+ ): (stream: SSEStreamingApi) => Promise<void> {
158
+ return async (stream) => {
159
+ // NOTHING may escape this callback, and the reason is measured rather than stylistic. Hono's
160
+ // `streamSSE` runner calls its `onError` argument and then UNCONDITIONALLY writes
161
+ // `event: error, data: e.message` to the stream — so an escaped exception reaches the client
162
+ // verbatim no matter what the handler withheld. The probe that found it saw TWO error events:
163
+ // this module's generic line, then Hono's raw one. The only place the trust boundary can be
164
+ // held is here, before the throw reaches the runner at all.
165
+ try {
166
+ // The inner `try` opens BEFORE the wiring: a throw from `session.on` inside `wireRelay`
167
+ // leaves the session claimed, and the `finally` is what releases it — opened later, every
168
+ // later request gets 409 forever.
169
+ const cleanup: Array<() => void> = [];
170
+ try {
171
+ const done = wireRelay(session, stream, cleanup, onFailure);
172
+ await session.submit(prompt);
173
+ await done;
174
+ } finally {
175
+ // RUNTIME-14: teardown ALWAYS runs — on completion, error, OR client disconnect — so the
176
+ // session event listeners can never leak, and the claim always comes back.
177
+ teardown(cleanup, release);
178
+ }
179
+ } catch (error) {
180
+ await reportStreamFailure(
181
+ error instanceof Error ? error : new Error(String(error)),
182
+ stream,
183
+ onFailure,
184
+ );
185
+ }
186
+ };
187
+ }
188
+
189
+ /**
190
+ * What to tell a client whose stream failed AFTER the response headers were sent.
191
+ *
192
+ * A throw at that point cannot become an error status — the client already has a 200 and an open
193
+ * stream. Without this the throw is an UNHANDLED rejection: it left the process silently in a
194
+ * browser and turned the `quality` job red under vitest, which is how it was found.
195
+ *
196
+ * By the time this runs, `relayTurn`'s teardown has removed the listeners and released the claim.
197
+ * This handler owes only the telling.
198
+ *
199
+ * The CLIENT gets a generic line and the HOST gets the detail, and review moved this three times.
200
+ * The first version sent `error.message` verbatim; the second sent it to a package logger imported
201
+ * from `agent-core`, which the layering rule refuses (see `TStreamFailureListener`). What survives
202
+ * both rounds is the boundary itself: an exception escaping the stream callback is not a message
203
+ * anything composed for a client — it can carry provider internals, paths, or stack fragments,
204
+ * exactly what the 500 branch in `routes.ts` withholds at the same boundary.
205
+ *
206
+ * The session's own `error` EVENT is different and stays verbatim in `relayTurn` above: that is the
207
+ * session's client-facing error channel, worded by the session (`humanizeApiError`) and relayed
208
+ * identically by the WS transport. One is a message meant for the client; this one never was.
209
+ */
210
+ export async function reportStreamFailure(
211
+ error: Error,
212
+ stream: SSEStreamingApi,
213
+ onFailure?: TStreamFailureListener,
214
+ ): Promise<void> {
215
+ try {
216
+ onFailure?.(error);
217
+ } catch {
218
+ // allow-fallback: a listener that throws must not take the client's only notification with it
219
+ // The listener is the host's code; its failure is the host's to see, and the write below is the
220
+ // one thing this function owes the client either way.
221
+ }
222
+ await stream
223
+ .writeSSE({
224
+ event: 'error',
225
+ data: JSON.stringify({
226
+ message: 'the stream failed on the server after it opened — the turn may not have run',
227
+ }),
228
+ })
229
+ .catch(() => {
230
+ // allow-fallback: the stream is already gone, which is the one case where there is nobody
231
+ // left to tell. Rethrowing here would restore the unhandled rejection this exists to remove.
232
+ });
233
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * RUNTIME-38 — who currently holds the one turn a session can run.
3
+ *
4
+ * Split out of `routes.ts`, which had grown past its size ceiling: routing is one job and deciding
5
+ * whether a second turn may start on a session is another, and the second is the only part of that
6
+ * file with state of its own.
7
+ *
8
+ * PER SESSION, not one flag for the router. `sessionFactory` resolves a session per request (the
9
+ * documented multi-tenant shape), so a single flag made one tenant's turn refuse every other
10
+ * tenant's — a busy neighbour is not a reason to refuse you, and that is a worse defect than the
11
+ * race it closed.
12
+ */
13
+
14
+ import type { IHttpTransportSession } from './http-session.js';
15
+
16
+ export interface ITurnClaims {
17
+ /** The key this session is claimed under, or `undefined` when it will not name itself. */
18
+ keyFor(session: IHttpTransportSession): string | undefined;
19
+ isHeld(key: string): boolean;
20
+ hold(key: string): void;
21
+ release(key: string): void;
22
+ }
23
+
24
+ /**
25
+ * A claim registry keyed by the session's declared ID, not by object identity.
26
+ *
27
+ * Keying on the OBJECT makes identity-stability a requirement of every caller that nothing can
28
+ * check: a `sessionFactory` returning a fresh wrapper per call for the same logical session — a
29
+ * proxy, an adapter, a spread copy — defeats the guard in silence, and every request looks
30
+ * unclaimed. `getSession(): { getSessionId(): string }` already names the session, so asking for the
31
+ * id turns an unenforceable requirement into no requirement at all.
32
+ *
33
+ * A claim is released in the caller's `finally`, so this does not grow with the number of sessions
34
+ * the host has ever served — which is what weak keying would otherwise buy.
35
+ */
36
+ export function createTurnClaims(): ITurnClaims {
37
+ const held = new Set<string>();
38
+
39
+ return {
40
+ keyFor(session) {
41
+ try {
42
+ // No `?.`: `getSession(): { getSessionId(): string }` is non-nullable, and optional chaining
43
+ // here would suggest the contract allows an absent session when it does not. A session that
44
+ // breaks the contract anyway is caught below.
45
+ const id = session.getSession().getSessionId();
46
+ return typeof id === 'string' && id !== '' ? id : undefined;
47
+ } catch {
48
+ // allow-fallback: an unnameable session must not be guessed at
49
+ // A session that throws while naming itself has not told us who it is, and guessing would
50
+ // claim the wrong turn. The CALLER refuses on `undefined`, so nothing is swallowed here.
51
+ //
52
+ // `undefined` rather than a placeholder — a shared fallback key would collide every
53
+ // unnameable session into one claim and refuse them all as each other's neighbours. There is
54
+ // no `isExecuting()` fallback on the submit path, and an earlier comment said there was.
55
+ return undefined;
56
+ }
57
+ },
58
+ isHeld: (key) => held.has(key),
59
+ hold: (key) => void held.add(key),
60
+ release: (key) => void held.delete(key),
61
+ };
62
+ }