@oribos/resumable-stream 0.0.0-stage → 0.8.0

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,57 @@
1
- # Temporary Holding Version
1
+ # @oribos/resumable-stream
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Reconnectable agent streams — the resumable-stream capability package. It records a run's
4
+ chunk stream into an event cache and replays-and-follows it with `observe(runId)`: a client
5
+ that disconnects mid-stream reconnects with the run id and loses nothing. One seam, no core
6
+ changes — the core keeps no resume endpoint; the GET endpoint that turns `observe` into HTTP
7
+ is the application's:
8
+
9
+ ```ts
10
+ import { createEventCacheApp } from './app'; // your route layer
11
+ import { withEventCache, observe, createInMemoryEventCache } from '@oribos/resumable-stream';
12
+
13
+ const cache = createInMemoryEventCache();
14
+
15
+ // POST /chat — record the run as it streams (the run id is your key for it)
16
+ const output = withEventCache(agent.stream(input), { runId, cache });
17
+ for await (const chunk of output) response.write(sse(chunk));
18
+
19
+ // GET /stream/<runId> — the reconnect: replay the missed chunks, then follow live
20
+ for await (const chunk of observe(cache, runId)) response.write(sse(chunk));
21
+ ```
22
+
23
+ ## How it works
24
+
25
+ - **`withEventCache(output, { runId, cache })`** wraps the agent's (or durable agent's) stream
26
+ and appends every chunk to the cache as it flows — the returned object has the same shape
27
+ as the original (chunk stream + terminal promises), so it drops into the streaming path you
28
+ already have. The recording survives the consumer: the wrapper's own pump drives the run to
29
+ completion even after its consumer hangs up, which is exactly the reconnect story's other
30
+ half. A cache that refuses an append fails the run — the recording is part of the run, not a
31
+ best-effort side channel.
32
+ - **`observe(cache, runId)`** replays a run's cached chunks in stream order, then follows the
33
+ run live until it ends. A finished run replays from anywhere the cache can be read; a failed
34
+ run replays what it produced and then rejects with the recorded failure. A run that is
35
+ `active` but not being recorded in this process replays and then throws `RunNotLiveError` —
36
+ cross-instance live tails need a PubSub (a different package's seam), and this package does
37
+ not smuggle one in as a polling loop. Unknown runs throw `UnknownRunError`.
38
+ - **`closeOnSuspend` needs no mechanism**: a durable run's stream ends with its
39
+ `finish` chunk (`finishReason: 'suspended'`) and the run's cache entry closes with it, so
40
+ observers see the run end exactly when the stream did; resuming is a new run id.
41
+
42
+ ## The cache port
43
+
44
+ - **`createInMemoryEventCache()`** — the default: a Map of run logs, zero dependencies, zero
45
+ process footprint, no timers. It never evicts on its own; call `drop(runId)` when a run's
46
+ replay window has passed (that knob stays yours).
47
+ - **`createRedisEventCache({ client, prefix? })`** — durable replay for production: one JSON
48
+ log per run under `<prefix>oribos:stream:<runId>`, on any Redis-compatible client
49
+ (`get` / `set` / `del` — the structural subset `ioredis` and `node-redis` both satisfy).
50
+ A run's log survives a process restart, and any instance sharing the database can replay
51
+ it. The client is yours; the dependency stays out of this package.
52
+
53
+ Zero cost when unconfigured: without the wrapper the core's stream path is untouched. No
54
+ resident pipeline: everything happens inline in the request that triggered it.
55
+
56
+ See `examples/resumable-stream` for the disconnect-reconnect story as a runnable script
57
+ (wired into the repo's offline examples gate).
@@ -0,0 +1,160 @@
1
+ /**
2
+ * `@oribos/resumable-stream` — the resumable-stream capability package: reconnectable agent
3
+ * streams (`docs/architecture/harness.md` CUT-H1, ADR-0017 追赶面中层;#184).
4
+ *
5
+ * The carrying seam is the output object, not the core: `withEventCache` wraps the chunk
6
+ * stream an agent (or durable agent) already returned, appending every chunk to an
7
+ * `EventCache` as it flows — and `observe(cache, runId)` replays a run's cached chunks in
8
+ * order, then follows the run live until it ends. A client that disconnects mid-stream
9
+ * reconnects with the run id and loses nothing: the recording pass survives the disconnect
10
+ * (the wrapper keeps pumping the inner run for the cache even after its own consumer leaves),
11
+ * and the reconnected observer replays from the cache and rejoins the live tail.
12
+ *
13
+ * Pins kept (CUT-M1 / ADR-0011): the core has no resume endpoint and gets none — the GET
14
+ * endpoint an application exposes is the application's; this package only caches and replays
15
+ * events, it never re-drives a run. Zero cost when unconfigured: without the wrapper the
16
+ * core's stream path is untouched. No resident pipeline: everything happens inline in the
17
+ * request that triggered it — no timers, no polling loops, no background workers.
18
+ *
19
+ * `closeOnSuspend` needs no mechanism of its own: a durable run's stream ends with a
20
+ * `finish` chunk (`finishReason: 'suspended'`) and the wrapper closes the run's cache entry
21
+ * on stream end, so observers see the run end exactly when the stream did. Resuming is the
22
+ * application's orchestration (a new run id, a fresh recording).
23
+ *
24
+ * The cache is the package's own port: an in-memory default ships here, and
25
+ * `createRedisEventCache` adapts any Redis-compatible client (`get` / `set` / `del` — the
26
+ * structural subset `ioredis` and `node-redis` both satisfy) for durable replay across
27
+ * restarts. Live following is in-process: a run recorded in another process (or a process
28
+ * that died mid-run) replays from the cache, but `observe` refuses to wait on a run no one
29
+ * in this process is recording (`RunNotLiveError`) — cross-instance live tails are the
30
+ * PubSub package's territory, not a polling loop smuggled in here.
31
+ *
32
+ * Package face: [`withEventCache`], [`observe`], [`EventCache`], [`RunEventLog`],
33
+ * [`RunEventStatus`], [`createInMemoryEventCache`], [`createRedisEventCache`],
34
+ * [`RedisLikeClient`], [`UnknownRunError`], [`RunNotLiveError`].
35
+ */
36
+ import type { AgentStreamResult } from '@oribos/core/agent';
37
+ import type { Chunk } from '@oribos/core/model';
38
+ /** Where a recorded run stands: still streaming, ended, or failed. */
39
+ export type RunEventStatus = 'active' | 'done' | 'error';
40
+ /** One run's cached event log: its chunks, in stream order, plus where the run stands. */
41
+ export interface RunEventLog {
42
+ /** The run id the events were recorded under. */
43
+ readonly runId: string;
44
+ /** The run's chunks in stream order — the replay source. */
45
+ readonly chunks: readonly Chunk[];
46
+ /** `active` while the recording pass is still appending; terminal once closed/failed. */
47
+ readonly status: RunEventStatus;
48
+ /** Why an `error` run failed (the error's message); absent otherwise. */
49
+ readonly error?: string | undefined;
50
+ }
51
+ /**
52
+ * The package's event-cache port: the seam an external store rides. The in-memory default
53
+ * ([`createInMemoryEventCache`]) carries no dependency; `createRedisEventCache` adapts any
54
+ * Redis-compatible client. One run has one writer (the `withEventCache` wrapper); readers
55
+ * may be anywhere the cache can be read from.
56
+ */
57
+ export interface EventCache {
58
+ /** Append one chunk to the run's log, creating the log (status `active`) on first append. */
59
+ append(runId: string, chunk: Chunk): Promise<void>;
60
+ /** Mark the run `done` — its stream ended. Keeps the chunks for replay. */
61
+ close(runId: string): Promise<void>;
62
+ /** Mark the run `error` with the failure's message. Keeps the chunks already cached. */
63
+ fail(runId: string, error: unknown): Promise<void>;
64
+ /** The run's log, or `undefined` for a run this cache has never heard of. */
65
+ read(runId: string): Promise<RunEventLog | undefined>;
66
+ /** Forget the run entirely — the retention knob (the defaults never evict on their own). */
67
+ drop(runId: string): Promise<void>;
68
+ }
69
+ /** The in-memory `EventCache` default: a Map of run logs, zero dependencies and zero process footprint. */
70
+ export declare function createInMemoryEventCache(): EventCache;
71
+ /**
72
+ * The structural subset of a Redis-compatible client the adapter calls: `get`, `set`, `del`
73
+ * with string values. `ioredis` and `node-redis` clients both satisfy it as-is — pass yours,
74
+ * keep the dependency yours.
75
+ */
76
+ export interface RedisLikeClient {
77
+ /** GET a key; `null` when absent (both major clients' missing-key convention). */
78
+ get(key: string): Promise<string | null>;
79
+ /** SET a key to a string value. */
80
+ set(key: string, value: string): Promise<unknown>;
81
+ /** DEL a key. */
82
+ del(key: string): Promise<unknown>;
83
+ }
84
+ /** `createRedisEventCache` config: your client, and an optional key prefix. */
85
+ export interface RedisEventCacheConfig {
86
+ /** Any Redis-compatible client (`get` / `set` / `del`). */
87
+ readonly client: RedisLikeClient;
88
+ /** Key prefix for this cache's runs; distinct prefixes never collide. Absent = none. */
89
+ readonly prefix?: string | undefined;
90
+ }
91
+ /**
92
+ * The Redis-backed `EventCache`: one JSON log per run under `<prefix>oribos:stream:<runId>`.
93
+ * Appends are read-modify-write of the whole log (one run has one writer — the wrapper), so
94
+ * the log survives a process restart and any instance sharing the database can replay it.
95
+ * Chunks must be JSON-serializable (the chunk protocol's values are, by construction).
96
+ */
97
+ export declare function createRedisEventCache(config: RedisEventCacheConfig): EventCache;
98
+ /** `observe` on a run this cache has never heard of. The application maps it (HTTP: 404). */
99
+ export declare class UnknownRunError extends Error {
100
+ constructor(runId: string);
101
+ }
102
+ /**
103
+ * `observe` on a run the cache says is `active` but no `withEventCache` in this process is
104
+ * recording: the run lives in another instance, or its process died mid-run. The cached
105
+ * chunks replayed fine; waiting for a tail nobody here can see would hang forever, so the
106
+ * refusal is explicit. The application maps it (HTTP: conflict / retry later); cross-instance
107
+ * live tails need a PubSub, which is a different package's seam.
108
+ */
109
+ export declare class RunNotLiveError extends Error {
110
+ constructor(runId: string);
111
+ }
112
+ /** `withEventCache` config: the app-chosen run id the events are recorded under, and the cache. */
113
+ export interface WithEventCacheConfig {
114
+ /** The id reconnecting clients will `observe` — the application's own key for this run. */
115
+ readonly runId: string;
116
+ /** Where the events go; absent handling = your choice of the two defaults or your own port. */
117
+ readonly cache: EventCache;
118
+ }
119
+ /**
120
+ * Wraps an agent (or durable agent) stream's output object with event recording: the returned
121
+ * object has the same shape — the same chunk stream to `for await`, the same terminal
122
+ * promises (`text` / `object` / `steps` / `finishReason` / …) — and, as a side effect of the
123
+ * same pass, every chunk is appended to the cache and the run's entry is closed (or failed)
124
+ * when the run ends.
125
+ *
126
+ * The recording survives the consumer: the wrapper's own pump drives the inner run to
127
+ * completion regardless of how it is consumed, so an SSE client hanging up mid-stream leaves
128
+ * the cache holding the whole run — that is the reconnect story's other half (`observe` is
129
+ * the first). A cache that refuses an append fails the wrapped run (the recording is part of
130
+ * the run, not a best-effort side channel — the rag package's fail-the-run precedent). One
131
+ * run id may be recorded once per cache at a time; recording it again while live throws.
132
+ *
133
+ * ```ts
134
+ * const output = withEventCache(agent.stream(input, { memory: { thread, resource } }), {
135
+ * runId, cache,
136
+ * });
137
+ * ```
138
+ */
139
+ export declare function withEventCache<T extends AgentStreamResult>(output: T, config: WithEventCacheConfig): T;
140
+ /**
141
+ * Replays a run's cached chunks in stream order, then follows the run live until it ends —
142
+ * the reconnecting client's whole read: one call, first the events it missed, then the tail
143
+ * it would have seen had it never left.
144
+ *
145
+ * - A **finished** run replays from anywhere the cache can be read (with the Redis adapter:
146
+ * from any instance sharing the database) and then ends; a **failed** run replays what it
147
+ * produced and then rejects with the recorded failure.
148
+ * - A **live** run (being recorded by a `withEventCache` wrapper in this process) replays
149
+ * and follows in-process, chunk by chunk, ending exactly when the run does — including a
150
+ * durable run's suspension (`finishReason: 'suspended'`): the observer sees the run end and
151
+ * reconnects later with the resume run's id.
152
+ * - An **active-but-not-live** run (recorded in another instance, or its process died
153
+ * mid-run) replays its cached chunks and then throws [`RunNotLiveError`] — waiting on a tail
154
+ * nobody here can see would hang forever. An unknown run throws [`UnknownRunError`].
155
+ *
156
+ * The application owns the endpoint that turns this into HTTP (SSE or otherwise) — the core
157
+ * keeps no resume endpoint (CUT-M1); this is the read side of that application's route.
158
+ */
159
+ export declare function observe(cache: EventCache, runId: string): AsyncIterable<Chunk>;
160
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAEhD,sEAAsE;AACtE,MAAM,MAAM,cAAc,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAC;AAEzD,0FAA0F;AAC1F,MAAM,WAAW,WAAW;IAC1B,iDAAiD;IACjD,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,4DAA4D;IAC5D,QAAQ,CAAC,MAAM,EAAE,SAAS,KAAK,EAAE,CAAC;IAClC,yFAAyF;IACzF,Q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C;CACtC;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,qBAAqB,GAAG,UAAU,CA6C/E;AAED,6FAA6F;AAC7F,qBAAa,eAAgB,SAAQ,KAAK;IACxC,YAAY,KAAK,EAAE,MAAM,EAGxB;CACF;AAED;;;;;;GAMG;AACH,qBAAa,eAAgB,SAAQ,KAAK;IACxC,YAAY,KAAK,EAAE,MAAM,EAQxB;CACF;AA+CD,mGAAmG;AACnG,MAAM,WAAW,oBAAoB;IACnC,2FAA2F;IAC3F,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,+FAA+F;IAC/F,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC;CAC5B;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,cAAc,CAAC,CAAC,SAAS,iBAAiB,EACxD,MAAM,EAAE,CAAC,EACT,MAAM,EAAE,oBAAoB,GAC3B,CAAC,CA6HH;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,GAAG,aAAa,CAAC,KAAK,CAAC,CAI9E"}
package/dist/index.js ADDED
@@ -0,0 +1,345 @@
1
+ /** The in-memory `EventCache` default: a Map of run logs, zero dependencies and zero process footprint. */
2
+ export function createInMemoryEventCache() {
3
+ const logs = new Map();
4
+ const entry = (runId) => {
5
+ let log = logs.get(runId);
6
+ if (log === undefined) {
7
+ log = { chunks: [], status: 'active' };
8
+ logs.set(runId, log);
9
+ }
10
+ return log;
11
+ };
12
+ return {
13
+ append: async (runId, chunk) => void entry(runId).chunks.push(chunk),
14
+ close: async (runId) => void (entry(runId).status = 'done'),
15
+ fail: async (runId, error) => {
16
+ const log = entry(runId);
17
+ log.status = 'error';
18
+ log.error = errorMessage(error);
19
+ },
20
+ read: async (runId) => {
21
+ const log = logs.get(runId);
22
+ if (log === undefined)
23
+ return undefined;
24
+ return { runId, chunks: [...log.chunks], status: log.status, error: log.error };
25
+ },
26
+ drop: async (runId) => void logs.delete(runId),
27
+ };
28
+ }
29
+ /**
30
+ * The Redis-backed `EventCache`: one JSON log per run under `<prefix>oribos:stream:<runId>`.
31
+ * Appends are read-modify-write of the whole log (one run has one writer — the wrapper), so
32
+ * the log survives a process restart and any instance sharing the database can replay it.
33
+ * Chunks must be JSON-serializable (the chunk protocol's values are, by construction).
34
+ */
35
+ export function createRedisEventCache(config) {
36
+ const { client } = config;
37
+ const scope = config.prefix === undefined || config.prefix === '' ? '' : `${config.prefix}:`;
38
+ const key = (runId) => `${scope}oribos:stream:${runId}`;
39
+ async function load(runId) {
40
+ const raw = await client.get(key(runId));
41
+ if (raw === null)
42
+ return { chunks: [], status: 'active' };
43
+ return JSON.parse(raw);
44
+ }
45
+ async function save(runId, log) {
46
+ await client.set(key(runId), JSON.stringify(log));
47
+ }
48
+ return {
49
+ append: async (runId, chunk) => {
50
+ const log = await load(runId);
51
+ log.chunks.push(chunk);
52
+ await save(runId, log);
53
+ },
54
+ close: async (runId) => {
55
+ const log = await load(runId);
56
+ await save(runId, { ...log, status: 'done' });
57
+ },
58
+ fail: async (runId, error) => {
59
+ const log = await load(runId);
60
+ await save(runId, { ...log, status: 'error', error: errorMessage(error) });
61
+ },
62
+ read: async (runId) => {
63
+ const raw = await client.get(key(runId));
64
+ if (raw === null)
65
+ return undefined;
66
+ const log = JSON.parse(raw);
67
+ return { runId, chunks: log.chunks, status: log.status, error: log.error };
68
+ },
69
+ drop: (runId) => Promise.resolve(client.del(key(runId))).then(() => undefined),
70
+ };
71
+ }
72
+ /** `observe` on a run this cache has never heard of. The application maps it (HTTP: 404). */
73
+ export class UnknownRunError extends Error {
74
+ constructor(runId) {
75
+ super(`observe: unknown run ${JSON.stringify(runId)} — nothing was recorded under this id`);
76
+ this.name = 'UnknownRunError';
77
+ }
78
+ }
79
+ /**
80
+ * `observe` on a run the cache says is `active` but no `withEventCache` in this process is
81
+ * recording: the run lives in another instance, or its process died mid-run. The cached
82
+ * chunks replayed fine; waiting for a tail nobody here can see would hang forever, so the
83
+ * refusal is explicit. The application maps it (HTTP: conflict / retry later); cross-instance
84
+ * live tails need a PubSub, which is a different package's seam.
85
+ */
86
+ export class RunNotLiveError extends Error {
87
+ constructor(runId) {
88
+ super(`observe: run ${JSON.stringify(runId)} is active but not recorded in this process — ` +
89
+ 'its cached events replayed, but its live tail lives elsewhere (cross-instance live ' +
90
+ 'following needs a PubSub; a restarted or crashed recording process leaves the run ' +
91
+ 'permanently active in the cache)');
92
+ this.name = 'RunNotLiveError';
93
+ }
94
+ }
95
+ /** Live recordings by run id, keyed by cache instance — in-process following only, no globals. */
96
+ const liveRuns = new WeakMap();
97
+ function liveMap(cache) {
98
+ let runs = liveRuns.get(cache);
99
+ if (runs === undefined) {
100
+ runs = new Map();
101
+ liveRuns.set(cache, runs);
102
+ }
103
+ return runs;
104
+ }
105
+ function broadcast(run, event) {
106
+ // Chunk events keep the subscribers — a tail has many; a terminal event is one-shot, and
107
+ // detaching on it is what stops a finished run's observer list from growing.
108
+ if (event.kind === 'chunk') {
109
+ for (const subscriber of run.subscribers)
110
+ subscriber(event);
111
+ return;
112
+ }
113
+ for (const subscriber of run.subscribers.splice(0))
114
+ subscriber(event);
115
+ }
116
+ /**
117
+ * Wraps an agent (or durable agent) stream's output object with event recording: the returned
118
+ * object has the same shape — the same chunk stream to `for await`, the same terminal
119
+ * promises (`text` / `object` / `steps` / `finishReason` / …) — and, as a side effect of the
120
+ * same pass, every chunk is appended to the cache and the run's entry is closed (or failed)
121
+ * when the run ends.
122
+ *
123
+ * The recording survives the consumer: the wrapper's own pump drives the inner run to
124
+ * completion regardless of how it is consumed, so an SSE client hanging up mid-stream leaves
125
+ * the cache holding the whole run — that is the reconnect story's other half (`observe` is
126
+ * the first). A cache that refuses an append fails the wrapped run (the recording is part of
127
+ * the run, not a best-effort side channel — the rag package's fail-the-run precedent). One
128
+ * run id may be recorded once per cache at a time; recording it again while live throws.
129
+ *
130
+ * ```ts
131
+ * const output = withEventCache(agent.stream(input, { memory: { thread, resource } }), {
132
+ * runId, cache,
133
+ * });
134
+ * ```
135
+ */
136
+ export function withEventCache(output, config) {
137
+ const { runId, cache } = config;
138
+ const runs = liveMap(cache);
139
+ if (runs.has(runId)) {
140
+ throw new Error(`withEventCache: run ${JSON.stringify(runId)} is already being recorded on this cache — ` +
141
+ 'one run id, one recording');
142
+ }
143
+ const run = { seq: 0, ended: undefined, subscribers: [] };
144
+ runs.set(runId, run);
145
+ let started = false;
146
+ let settled = false;
147
+ let failure;
148
+ /** The consumer left the loop; the pump keeps going — the cache is the point. */
149
+ let abandoned = false;
150
+ const buffered = [];
151
+ const waiting = [];
152
+ const DONE = { value: undefined, done: true };
153
+ function start() {
154
+ if (started)
155
+ return;
156
+ started = true;
157
+ void pump();
158
+ }
159
+ async function pump() {
160
+ const iterator = output[Symbol.asyncIterator]();
161
+ try {
162
+ for (;;) {
163
+ const next = await iterator.next();
164
+ if (next.done)
165
+ break;
166
+ await cache.append(runId, next.value);
167
+ const seq = run.seq;
168
+ run.seq += 1;
169
+ if (run.ended === undefined)
170
+ broadcast(run, { kind: 'chunk', seq, chunk: next.value });
171
+ deliver(next.value);
172
+ }
173
+ }
174
+ catch (error) {
175
+ await endWithFailure(error);
176
+ return;
177
+ }
178
+ await endWithSuccess();
179
+ }
180
+ /** The run completed: close the cache entry, tell the observers, settle the stream. */
181
+ async function endWithSuccess() {
182
+ await guard(() => cache.close(runId));
183
+ run.ended = { kind: 'done' };
184
+ broadcast(run, run.ended);
185
+ runs.delete(runId);
186
+ settled = true;
187
+ for (const waiter of waiting.splice(0))
188
+ waiter.resolve(DONE);
189
+ }
190
+ /** The run failed (or the cache did): record the failure, settle the stream with the error. */
191
+ async function endWithFailure(error) {
192
+ await guard(() => cache.fail(runId, error));
193
+ run.ended = { kind: 'error', error };
194
+ broadcast(run, run.ended);
195
+ runs.delete(runId);
196
+ settled = true;
197
+ failure = { error };
198
+ for (const waiter of waiting.splice(0))
199
+ waiter.reject(error);
200
+ }
201
+ /** A cache that already failed one call may fail the closing call too — never mask the run's own outcome. */
202
+ async function guard(call) {
203
+ try {
204
+ await call();
205
+ }
206
+ catch {
207
+ // The recording is broken; the run's own outcome is what the consumer sees.
208
+ }
209
+ }
210
+ /** Hands a chunk to the waiting iterator, or buffers it until one asks. */
211
+ function deliver(chunk) {
212
+ if (abandoned)
213
+ return;
214
+ const waiter = waiting.shift();
215
+ if (waiter === undefined) {
216
+ buffered.push(chunk);
217
+ return;
218
+ }
219
+ waiter.resolve({ value: chunk, done: false });
220
+ }
221
+ const iterator = {
222
+ next() {
223
+ start();
224
+ if (abandoned)
225
+ return Promise.resolve(DONE);
226
+ const chunk = buffered.shift();
227
+ if (chunk !== undefined)
228
+ return Promise.resolve({ value: chunk, done: false });
229
+ if (failure !== undefined)
230
+ return Promise.reject(failure.error);
231
+ if (settled)
232
+ return Promise.resolve(DONE);
233
+ return new Promise((resolve, reject) => {
234
+ waiting.push({ resolve, reject });
235
+ });
236
+ },
237
+ return() {
238
+ abandoned = true;
239
+ buffered.length = 0;
240
+ return Promise.resolve(DONE);
241
+ },
242
+ };
243
+ const surface = {
244
+ [Symbol.asyncIterator]: () => iterator,
245
+ };
246
+ // The inner terminal keys, each forwarded lazily: reading one starts the recording pass and
247
+ // hands out the inner promise unchanged (same run, same value, same laziness).
248
+ for (const key of Object.keys(output)) {
249
+ Object.defineProperty(surface, key, {
250
+ enumerable: true,
251
+ configurable: true,
252
+ get() {
253
+ start();
254
+ return output[key];
255
+ },
256
+ });
257
+ }
258
+ return surface;
259
+ }
260
+ /**
261
+ * Replays a run's cached chunks in stream order, then follows the run live until it ends —
262
+ * the reconnecting client's whole read: one call, first the events it missed, then the tail
263
+ * it would have seen had it never left.
264
+ *
265
+ * - A **finished** run replays from anywhere the cache can be read (with the Redis adapter:
266
+ * from any instance sharing the database) and then ends; a **failed** run replays what it
267
+ * produced and then rejects with the recorded failure.
268
+ * - A **live** run (being recorded by a `withEventCache` wrapper in this process) replays
269
+ * and follows in-process, chunk by chunk, ending exactly when the run does — including a
270
+ * durable run's suspension (`finishReason: 'suspended'`): the observer sees the run end and
271
+ * reconnects later with the resume run's id.
272
+ * - An **active-but-not-live** run (recorded in another instance, or its process died
273
+ * mid-run) replays its cached chunks and then throws [`RunNotLiveError`] — waiting on a tail
274
+ * nobody here can see would hang forever. An unknown run throws [`UnknownRunError`].
275
+ *
276
+ * The application owns the endpoint that turns this into HTTP (SSE or otherwise) — the core
277
+ * keeps no resume endpoint (CUT-M1); this is the read side of that application's route.
278
+ */
279
+ export function observe(cache, runId) {
280
+ return {
281
+ [Symbol.asyncIterator]: () => replayAndFollow(cache, runId),
282
+ };
283
+ }
284
+ /** The single pass behind `observe`: snapshot the cache, then tail the live broadcast. */
285
+ async function* replayAndFollow(cache, runId) {
286
+ const live = liveRuns.get(cache)?.get(runId);
287
+ // Not being recorded here: everything must come from the cache, and the cache must know it.
288
+ if (live === undefined) {
289
+ const log = await cache.read(runId);
290
+ if (log === undefined)
291
+ throw new UnknownRunError(runId);
292
+ for (const chunk of log.chunks)
293
+ yield chunk;
294
+ if (log.status === 'done')
295
+ return;
296
+ if (log.status === 'error') {
297
+ throw new Error(`observe: run ${JSON.stringify(runId)} failed: ${log.error ?? 'unknown error'}`);
298
+ }
299
+ throw new RunNotLiveError(runId);
300
+ }
301
+ // Live here: subscribe first, snapshot second — a chunk landing between the two is carried
302
+ // by its position in the broadcast and skipped against the snapshot, so it arrives once.
303
+ const queue = [];
304
+ let wake;
305
+ const subscriber = (event) => {
306
+ queue.push(event);
307
+ wake?.();
308
+ };
309
+ if (live.ended === undefined)
310
+ live.subscribers.push(subscriber);
311
+ else
312
+ queue.push(live.ended);
313
+ const log = await cache.read(runId);
314
+ const snapshot = log?.chunks ?? [];
315
+ for (const chunk of snapshot)
316
+ yield chunk;
317
+ for (;;) {
318
+ if (queue.length === 0) {
319
+ await new Promise((resolve) => {
320
+ wake = resolve;
321
+ });
322
+ continue;
323
+ }
324
+ const event = queue.shift();
325
+ if (event === undefined)
326
+ continue;
327
+ if (event.kind === 'chunk') {
328
+ // Already inside the snapshot the run replayed from — position, not timing, decides.
329
+ if (event.seq < snapshot.length)
330
+ continue;
331
+ yield event.chunk;
332
+ }
333
+ else if (event.kind === 'done') {
334
+ return;
335
+ }
336
+ else {
337
+ throw event.error;
338
+ }
339
+ }
340
+ }
341
+ /** The message a failed run's cache entry keeps. */
342
+ function errorMessage(error) {
343
+ return error instanceof Error ? error.message : String(error);
344
+ }
345
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAwEA,2GAA2G;AAC3G,MAAM,UAAU,wBAAwB;IACtC,MAAM,IAAI,GAAG,IAAI,GAAG,EAAuE,CAAC;IAC5F,MAAM,KAAK,GAAG,CAAC,KAAa,EAAE,EAAE;QAC9B,IAAI,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAC1B,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;YACtB,GAAG,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;YACvC,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;QACvB,CAAC;QACD,OAAO,GAAG,CAAC;IACb,CAAC,CAAC;IACF,OAAO;QACL,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC;QACpE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,MAAM,CAAC;QAC3D,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE;YAC3B,MAAM,GAAG,GAAG,KAAK,CAAC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- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.8.0",
4
+ "description": "Oribos resumable-stream capability package — reconnectable agent streams: record a run's chunk stream into an event cache and replay-and-follow it with observe(runId). In-memory cache by default, any Redis-compatible client for durable replay, no dependencies beyond the @oribos/core peer.",
5
+ "keywords": [
6
+ "ai-agents",
7
+ "llm",
8
+ "typescript",
9
+ "agent-framework",
10
+ "resumable-stream",
11
+ "sse",
12
+ "streaming"
13
+ ],
14
+ "license": "Apache-2.0",
15
+ "type": "module",
16
+ "sideEffects": false,
17
+ "engines": {
18
+ "node": ">=22.13.0"
19
+ },
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "default": "./dist/index.js"
24
+ }
25
+ },
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://github.com/0xnicholas/oribos-framework.git",
32
+ "directory": "packages/resumable-stream"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "peerDependencies": {
38
+ "@oribos/core": "^0.8.0"
39
+ },
40
+ "devDependencies": {
41
+ "@oribos/testing": "0.0.0",
42
+ "@oribos/core": "0.8.0"
43
+ },
44
+ "scripts": {
45
+ "build": "tsc -p tsconfig.build.json",
46
+ "typecheck": "tsc -p tsconfig.json --noEmit",
47
+ "check:dist": "node ../../scripts/check-dist.mjs",
48
+ "check:export-surface": "node ../../scripts/check-export-surface.mjs",
49
+ "check:runtime-deps": "node ../../scripts/check-runtime-deps.mjs",
50
+ "check:byte-budget": "node ../../scripts/check-byte-budget.mjs",
51
+ "byte-budget:update": "node ../../scripts/check-byte-budget.mjs --update",
52
+ "check:deps-budget": "node ../../scripts/check-deps-budget.mjs",
53
+ "deps-budget:update": "node ../../scripts/check-deps-budget.mjs --update"
54
+ }
6
55
  }