@redtuma/store-do 0.1.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 +202 -0
- package/README.md +98 -0
- package/dist/durable-object.d.ts +45 -0
- package/dist/durable-object.d.ts.map +1 -0
- package/dist/durable-object.js +99 -0
- package/dist/durable-object.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +5 -0
- package/dist/storage.d.ts +35 -0
- package/dist/storage.d.ts.map +1 -0
- package/dist/storage.js +33 -0
- package/dist/storage.js.map +1 -0
- package/dist/store.d.ts +33 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +73 -0
- package/dist/store.js.map +1 -0
- package/package.json +50 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# @redtuma/store-do
|
|
2
|
+
|
|
3
|
+
Edge-native agent memory for Redtuma, backed by a **Cloudflare Durable Object**.
|
|
4
|
+
No external database: each conversation thread lives in its own strongly
|
|
5
|
+
consistent, co-located DO instance that hibernates when idle and wakes on the
|
|
6
|
+
next request — the natural home for agent state and human-in-the-loop workflows.
|
|
7
|
+
|
|
8
|
+
It implements the standard Redtuma [`Store`](../../packages/core/src/store/index.ts)
|
|
9
|
+
interface, so anything that takes a `Store` (memory, workflow snapshots) works
|
|
10
|
+
unchanged.
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pnpm add @redtuma/store-do
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Define the Durable Object
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
// src/memory.ts
|
|
22
|
+
import { RedtumaMemoryObject, type KVStorage } from '@redtuma/store-do'
|
|
23
|
+
|
|
24
|
+
export class Memory extends RedtumaMemoryObject {
|
|
25
|
+
constructor(state: DurableObjectState) {
|
|
26
|
+
super(state.storage as unknown as KVStorage)
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Use it from a Worker
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
// src/worker.ts
|
|
35
|
+
import { Agent } from '@redtuma/core'
|
|
36
|
+
import { durableObjectStoreClient } from '@redtuma/store-do'
|
|
37
|
+
export { Memory } from './memory'
|
|
38
|
+
|
|
39
|
+
interface Env {
|
|
40
|
+
MEMORY: DurableObjectNamespace
|
|
41
|
+
ANTHROPIC_API_KEY: string
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export default {
|
|
45
|
+
async fetch(req: Request, env: Env): Promise<Response> {
|
|
46
|
+
const { threadId, message } = await req.json<{ threadId: string; message: string }>()
|
|
47
|
+
|
|
48
|
+
// One Durable Object per thread → strongly consistent per-conversation memory.
|
|
49
|
+
const stub = env.MEMORY.get(env.MEMORY.idFromName(threadId))
|
|
50
|
+
const store = durableObjectStoreClient(stub)
|
|
51
|
+
|
|
52
|
+
const agent = new Agent({
|
|
53
|
+
id: 'assistant',
|
|
54
|
+
instructions: 'You are helpful.',
|
|
55
|
+
model: 'anthropic/claude-opus-4-8',
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
// Persist this turn, then answer using prior history from the DO.
|
|
59
|
+
await store.saveThread({
|
|
60
|
+
id: threadId, resourceId: 'user', createdAt: new Date(), updatedAt: new Date(),
|
|
61
|
+
})
|
|
62
|
+
const history = await store.getMessages({ threadId, last: 20 })
|
|
63
|
+
const res = await agent.generate([
|
|
64
|
+
...history.map((m) => ({ role: m.role, content: m.content })),
|
|
65
|
+
{ role: 'user', content: message },
|
|
66
|
+
])
|
|
67
|
+
|
|
68
|
+
await store.saveMessages([
|
|
69
|
+
{ id: crypto.randomUUID(), role: 'user', content: message, createdAt: new Date(), threadId, resourceId: 'user' },
|
|
70
|
+
{ id: crypto.randomUUID(), role: 'assistant', content: res.text, createdAt: new Date(), threadId, resourceId: 'user' },
|
|
71
|
+
])
|
|
72
|
+
return Response.json({ text: res.text })
|
|
73
|
+
},
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
See [`wrangler.example.toml`](./wrangler.example.toml) for the binding + migration.
|
|
78
|
+
|
|
79
|
+
## Local development & testing
|
|
80
|
+
|
|
81
|
+
`MemoryKVStorage` mirrors the DO storage semantics (structured-clone writes,
|
|
82
|
+
lexicographic key ordering) with no Workers runtime — ideal for unit tests and
|
|
83
|
+
local runs:
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
import { DurableObjectStore, MemoryKVStorage } from '@redtuma/store-do'
|
|
87
|
+
const store = new DurableObjectStore(new MemoryKVStorage())
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
This adapter passes the shared `runStoreConformance` suite — the same contract
|
|
91
|
+
the reference `InMemoryStore` satisfies.
|
|
92
|
+
|
|
93
|
+
## API
|
|
94
|
+
|
|
95
|
+
- `DurableObjectStore(storage: KVStorage)` — the `Store` implementation.
|
|
96
|
+
- `MemoryKVStorage` — in-memory `KVStorage` for dev/test.
|
|
97
|
+
- `RedtumaMemoryObject` — base Durable Object class exposing the store over JSON-RPC.
|
|
98
|
+
- `durableObjectStoreClient(fetcher)` — a `Store` that forwards to a DO stub.
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { KVStorage } from "./storage.js";
|
|
2
|
+
import { Store } from "@redtuma/core/store";
|
|
3
|
+
|
|
4
|
+
//#region src/durable-object.d.ts
|
|
5
|
+
/** Cloudflare's `DurableObjectStorage` is a structural superset of this. */
|
|
6
|
+
type DurableObjectStorageLike = KVStorage;
|
|
7
|
+
/**
|
|
8
|
+
* Base class for a Redtuma memory Durable Object. Each instance owns one
|
|
9
|
+
* conversation's persistent state through a {@link DurableObjectStore}, exposed
|
|
10
|
+
* over a tiny JSON-RPC `fetch` so a Worker can drive it with
|
|
11
|
+
* {@link durableObjectStoreClient}. Subclass it and forward `state.storage`:
|
|
12
|
+
*
|
|
13
|
+
* ```ts
|
|
14
|
+
* export class Memory extends RedtumaMemoryObject {
|
|
15
|
+
* constructor(state: DurableObjectState) {
|
|
16
|
+
* super(state.storage as unknown as KVStorage)
|
|
17
|
+
* }
|
|
18
|
+
* }
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
declare class RedtumaMemoryObject {
|
|
22
|
+
protected readonly memory: Store;
|
|
23
|
+
constructor(storage: KVStorage);
|
|
24
|
+
fetch(request: Request): Promise<Response>;
|
|
25
|
+
}
|
|
26
|
+
/** Anything that can take a `Request` and return a `Response` — e.g. a DO stub. */
|
|
27
|
+
interface Fetcher {
|
|
28
|
+
fetch(request: Request): Promise<Response>;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* A {@link Store} whose calls are forwarded to a remote {@link RedtumaMemoryObject}
|
|
32
|
+
* (or any {@link Fetcher}, such as a Durable Object stub) over JSON-RPC. This is
|
|
33
|
+
* what a Worker uses as its agent/memory storage:
|
|
34
|
+
*
|
|
35
|
+
* ```ts
|
|
36
|
+
* const id = env.MEMORY.idFromName(threadId)
|
|
37
|
+
* const store = durableObjectStoreClient(env.MEMORY.get(id))
|
|
38
|
+
* ```
|
|
39
|
+
*
|
|
40
|
+
* Note: values round-trip through JSON, so `Date` fields arrive as ISO strings.
|
|
41
|
+
*/
|
|
42
|
+
declare function durableObjectStoreClient(fetcher: Fetcher): Store;
|
|
43
|
+
//#endregion
|
|
44
|
+
export { DurableObjectStorageLike, Fetcher, RedtumaMemoryObject, durableObjectStoreClient };
|
|
45
|
+
//# sourceMappingURL=durable-object.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"durable-object.d.ts","names":[],"sources":["../src/durable-object.ts"],"sourcesContent":[],"mappings":";;;;;KAKY,wBAAA,GAA2B;AAAvC;AAoCA;;;;;;;AA+BA;;;;;AAgBA;cA/Ca,mBAAA;6BACgB;uBAEN;iBAIA,UAAU,QAAQ;;;UAwBxB,OAAA;iBACA,UAAU,QAAQ;;;;;;;;;;;;;;iBAenB,wBAAA,UAAkC,UAAU"}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { DurableObjectStore } from "./store.js";
|
|
2
|
+
|
|
3
|
+
//#region src/durable-object.ts
|
|
4
|
+
const STORE_METHODS = new Set([
|
|
5
|
+
"saveThread",
|
|
6
|
+
"getThread",
|
|
7
|
+
"getThreadsByResourceId",
|
|
8
|
+
"deleteThread",
|
|
9
|
+
"saveMessages",
|
|
10
|
+
"getMessages",
|
|
11
|
+
"getResource",
|
|
12
|
+
"saveResource",
|
|
13
|
+
"persistSnapshot",
|
|
14
|
+
"loadSnapshot"
|
|
15
|
+
]);
|
|
16
|
+
function json(data, status = 200) {
|
|
17
|
+
return new Response(JSON.stringify(data), {
|
|
18
|
+
status,
|
|
19
|
+
headers: { "content-type": "application/json" }
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Base class for a Redtuma memory Durable Object. Each instance owns one
|
|
24
|
+
* conversation's persistent state through a {@link DurableObjectStore}, exposed
|
|
25
|
+
* over a tiny JSON-RPC `fetch` so a Worker can drive it with
|
|
26
|
+
* {@link durableObjectStoreClient}. Subclass it and forward `state.storage`:
|
|
27
|
+
*
|
|
28
|
+
* ```ts
|
|
29
|
+
* export class Memory extends RedtumaMemoryObject {
|
|
30
|
+
* constructor(state: DurableObjectState) {
|
|
31
|
+
* super(state.storage as unknown as KVStorage)
|
|
32
|
+
* }
|
|
33
|
+
* }
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
var RedtumaMemoryObject = class {
|
|
37
|
+
memory;
|
|
38
|
+
constructor(storage) {
|
|
39
|
+
this.memory = new DurableObjectStore(storage);
|
|
40
|
+
}
|
|
41
|
+
async fetch(request) {
|
|
42
|
+
let body;
|
|
43
|
+
try {
|
|
44
|
+
body = await request.json();
|
|
45
|
+
} catch {
|
|
46
|
+
return json({ error: "Invalid JSON body." }, 400);
|
|
47
|
+
}
|
|
48
|
+
const method = body.method;
|
|
49
|
+
if (!method || !STORE_METHODS.has(method)) return json({ error: `Unknown store method "${String(method)}".` }, 400);
|
|
50
|
+
try {
|
|
51
|
+
return json({ result: await this.memory[method].apply(this.memory, body.args ?? []) });
|
|
52
|
+
} catch (err) {
|
|
53
|
+
return json({ error: err instanceof Error ? err.message : String(err) }, 500);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* A {@link Store} whose calls are forwarded to a remote {@link RedtumaMemoryObject}
|
|
59
|
+
* (or any {@link Fetcher}, such as a Durable Object stub) over JSON-RPC. This is
|
|
60
|
+
* what a Worker uses as its agent/memory storage:
|
|
61
|
+
*
|
|
62
|
+
* ```ts
|
|
63
|
+
* const id = env.MEMORY.idFromName(threadId)
|
|
64
|
+
* const store = durableObjectStoreClient(env.MEMORY.get(id))
|
|
65
|
+
* ```
|
|
66
|
+
*
|
|
67
|
+
* Note: values round-trip through JSON, so `Date` fields arrive as ISO strings.
|
|
68
|
+
*/
|
|
69
|
+
function durableObjectStoreClient(fetcher) {
|
|
70
|
+
const call = async (method, args) => {
|
|
71
|
+
const res = await fetcher.fetch(new Request("https://redtuma-memory/rpc", {
|
|
72
|
+
method: "POST",
|
|
73
|
+
headers: { "content-type": "application/json" },
|
|
74
|
+
body: JSON.stringify({
|
|
75
|
+
method,
|
|
76
|
+
args
|
|
77
|
+
})
|
|
78
|
+
}));
|
|
79
|
+
const data = await res.json();
|
|
80
|
+
if (!res.ok || data.error) throw new Error(data.error ?? `Memory store RPC failed (HTTP ${res.status}).`);
|
|
81
|
+
return data.result;
|
|
82
|
+
};
|
|
83
|
+
return {
|
|
84
|
+
saveThread: (t) => call("saveThread", [t]),
|
|
85
|
+
getThread: (id) => call("getThread", [id]),
|
|
86
|
+
getThreadsByResourceId: (rid) => call("getThreadsByResourceId", [rid]),
|
|
87
|
+
deleteThread: (id) => call("deleteThread", [id]),
|
|
88
|
+
saveMessages: (m) => call("saveMessages", [m]),
|
|
89
|
+
getMessages: (a) => call("getMessages", [a]),
|
|
90
|
+
getResource: (id) => call("getResource", [id]),
|
|
91
|
+
saveResource: (r) => call("saveResource", [r]),
|
|
92
|
+
persistSnapshot: (k, v) => call("persistSnapshot", [k, v]),
|
|
93
|
+
loadSnapshot: (k) => call("loadSnapshot", [k])
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
//#endregion
|
|
98
|
+
export { RedtumaMemoryObject, durableObjectStoreClient };
|
|
99
|
+
//# sourceMappingURL=durable-object.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"durable-object.js","names":["body: { method?: string; args?: unknown[] }"],"sources":["../src/durable-object.ts"],"sourcesContent":["import type { Store } from '@redtuma/core/store'\nimport { DurableObjectStore } from './store'\nimport type { KVStorage } from './storage'\n\n/** Cloudflare's `DurableObjectStorage` is a structural superset of this. */\nexport type DurableObjectStorageLike = KVStorage\n\nconst STORE_METHODS = new Set<keyof Store>([\n 'saveThread',\n 'getThread',\n 'getThreadsByResourceId',\n 'deleteThread',\n 'saveMessages',\n 'getMessages',\n 'getResource',\n 'saveResource',\n 'persistSnapshot',\n 'loadSnapshot',\n])\n\nfunction json(data: unknown, status = 200): Response {\n return new Response(JSON.stringify(data), {\n status,\n headers: { 'content-type': 'application/json' },\n })\n}\n\n/**\n * Base class for a Redtuma memory Durable Object. Each instance owns one\n * conversation's persistent state through a {@link DurableObjectStore}, exposed\n * over a tiny JSON-RPC `fetch` so a Worker can drive it with\n * {@link durableObjectStoreClient}. Subclass it and forward `state.storage`:\n *\n * ```ts\n * export class Memory extends RedtumaMemoryObject {\n * constructor(state: DurableObjectState) {\n * super(state.storage as unknown as KVStorage)\n * }\n * }\n * ```\n */\nexport class RedtumaMemoryObject {\n protected readonly memory: Store\n\n constructor(storage: KVStorage) {\n this.memory = new DurableObjectStore(storage)\n }\n\n async fetch(request: Request): Promise<Response> {\n let body: { method?: string; args?: unknown[] }\n try {\n body = (await request.json()) as { method?: string; args?: unknown[] }\n } catch {\n return json({ error: 'Invalid JSON body.' }, 400)\n }\n\n const method = body.method\n if (!method || !STORE_METHODS.has(method as keyof Store)) {\n return json({ error: `Unknown store method \"${String(method)}\".` }, 400)\n }\n\n try {\n const fn = this.memory[method as keyof Store] as (...args: unknown[]) => Promise<unknown>\n const result = await fn.apply(this.memory, body.args ?? [])\n return json({ result })\n } catch (err) {\n return json({ error: err instanceof Error ? err.message : String(err) }, 500)\n }\n }\n}\n\n/** Anything that can take a `Request` and return a `Response` — e.g. a DO stub. */\nexport interface Fetcher {\n fetch(request: Request): Promise<Response>\n}\n\n/**\n * A {@link Store} whose calls are forwarded to a remote {@link RedtumaMemoryObject}\n * (or any {@link Fetcher}, such as a Durable Object stub) over JSON-RPC. This is\n * what a Worker uses as its agent/memory storage:\n *\n * ```ts\n * const id = env.MEMORY.idFromName(threadId)\n * const store = durableObjectStoreClient(env.MEMORY.get(id))\n * ```\n *\n * Note: values round-trip through JSON, so `Date` fields arrive as ISO strings.\n */\nexport function durableObjectStoreClient(fetcher: Fetcher): Store {\n const call = async (method: keyof Store, args: unknown[]): Promise<unknown> => {\n const res = await fetcher.fetch(\n new Request('https://redtuma-memory/rpc', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ method, args }),\n }),\n )\n const data = (await res.json()) as { result?: unknown; error?: string }\n if (!res.ok || data.error) {\n throw new Error(data.error ?? `Memory store RPC failed (HTTP ${res.status}).`)\n }\n return data.result\n }\n\n return {\n saveThread: (t) => call('saveThread', [t]) as Promise<never>,\n getThread: (id) => call('getThread', [id]) as Promise<never>,\n getThreadsByResourceId: (rid) => call('getThreadsByResourceId', [rid]) as Promise<never>,\n deleteThread: (id) => call('deleteThread', [id]) as Promise<void>,\n saveMessages: (m) => call('saveMessages', [m]) as Promise<never>,\n getMessages: (a) => call('getMessages', [a]) as Promise<never>,\n getResource: (id) => call('getResource', [id]) as Promise<never>,\n saveResource: (r) => call('saveResource', [r]) as Promise<never>,\n persistSnapshot: (k, v) => call('persistSnapshot', [k, v]) as Promise<void>,\n loadSnapshot: (k) => call('loadSnapshot', [k]) as Promise<never>,\n }\n}\n"],"mappings":";;;AAOA,MAAM,gBAAgB,IAAI,IAAiB;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,SAAS,KAAK,MAAe,SAAS,KAAe;AACnD,QAAO,IAAI,SAAS,KAAK,UAAU,KAAK,EAAE;EACxC;EACA,SAAS,EAAE,gBAAgB,oBAAoB;EAChD,CAAC;;;;;;;;;;;;;;;;AAiBJ,IAAa,sBAAb,MAAiC;CAC/B,AAAmB;CAEnB,YAAY,SAAoB;AAC9B,OAAK,SAAS,IAAI,mBAAmB,QAAQ;;CAG/C,MAAM,MAAM,SAAqC;EAC/C,IAAIA;AACJ,MAAI;AACF,UAAQ,MAAM,QAAQ,MAAM;UACtB;AACN,UAAO,KAAK,EAAE,OAAO,sBAAsB,EAAE,IAAI;;EAGnD,MAAM,SAAS,KAAK;AACpB,MAAI,CAAC,UAAU,CAAC,cAAc,IAAI,OAAsB,CACtD,QAAO,KAAK,EAAE,OAAO,yBAAyB,OAAO,OAAO,CAAC,KAAK,EAAE,IAAI;AAG1E,MAAI;AAGF,UAAO,KAAK,EAAE,QADC,MADJ,KAAK,OAAO,QACC,MAAM,KAAK,QAAQ,KAAK,QAAQ,EAAE,CAAC,EACrC,CAAC;WAChB,KAAK;AACZ,UAAO,KAAK,EAAE,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI,EAAE,EAAE,IAAI;;;;;;;;;;;;;;;;AAsBnF,SAAgB,yBAAyB,SAAyB;CAChE,MAAM,OAAO,OAAO,QAAqB,SAAsC;EAC7E,MAAM,MAAM,MAAM,QAAQ,MACxB,IAAI,QAAQ,8BAA8B;GACxC,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAC/C,MAAM,KAAK,UAAU;IAAE;IAAQ;IAAM,CAAC;GACvC,CAAC,CACH;EACD,MAAM,OAAQ,MAAM,IAAI,MAAM;AAC9B,MAAI,CAAC,IAAI,MAAM,KAAK,MAClB,OAAM,IAAI,MAAM,KAAK,SAAS,iCAAiC,IAAI,OAAO,IAAI;AAEhF,SAAO,KAAK;;AAGd,QAAO;EACL,aAAa,MAAM,KAAK,cAAc,CAAC,EAAE,CAAC;EAC1C,YAAY,OAAO,KAAK,aAAa,CAAC,GAAG,CAAC;EAC1C,yBAAyB,QAAQ,KAAK,0BAA0B,CAAC,IAAI,CAAC;EACtE,eAAe,OAAO,KAAK,gBAAgB,CAAC,GAAG,CAAC;EAChD,eAAe,MAAM,KAAK,gBAAgB,CAAC,EAAE,CAAC;EAC9C,cAAc,MAAM,KAAK,eAAe,CAAC,EAAE,CAAC;EAC5C,cAAc,OAAO,KAAK,eAAe,CAAC,GAAG,CAAC;EAC9C,eAAe,MAAM,KAAK,gBAAgB,CAAC,EAAE,CAAC;EAC9C,kBAAkB,GAAG,MAAM,KAAK,mBAAmB,CAAC,GAAG,EAAE,CAAC;EAC1D,eAAe,MAAM,KAAK,gBAAgB,CAAC,EAAE,CAAC;EAC/C"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { KVStorage, MemoryKVStorage } from "./storage.js";
|
|
2
|
+
import { DurableObjectStore } from "./store.js";
|
|
3
|
+
import { DurableObjectStorageLike, Fetcher, RedtumaMemoryObject, durableObjectStoreClient } from "./durable-object.js";
|
|
4
|
+
export { type DurableObjectStorageLike, DurableObjectStore, type Fetcher, type KVStorage, MemoryKVStorage, RedtumaMemoryObject, durableObjectStoreClient };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { DurableObjectStore } from "./store.js";
|
|
2
|
+
import { MemoryKVStorage } from "./storage.js";
|
|
3
|
+
import { RedtumaMemoryObject, durableObjectStoreClient } from "./durable-object.js";
|
|
4
|
+
|
|
5
|
+
export { DurableObjectStore, MemoryKVStorage, RedtumaMemoryObject, durableObjectStoreClient };
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
//#region src/storage.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* The subset of Cloudflare's `DurableObjectStorage` API that the store uses.
|
|
4
|
+
* Cloudflare's real storage is a structural superset of this, so a Durable
|
|
5
|
+
* Object's `state.storage` satisfies it directly.
|
|
6
|
+
*
|
|
7
|
+
* `list()` returns entries ordered lexicographically by key — the property the
|
|
8
|
+
* store relies on for message ordering via zero-padded sequence keys.
|
|
9
|
+
*/
|
|
10
|
+
interface KVStorage {
|
|
11
|
+
get<T = unknown>(key: string): Promise<T | undefined>;
|
|
12
|
+
put<T = unknown>(key: string, value: T): Promise<void>;
|
|
13
|
+
delete(key: string): Promise<boolean>;
|
|
14
|
+
list<T = unknown>(options?: {
|
|
15
|
+
prefix?: string;
|
|
16
|
+
}): Promise<Map<string, T>>;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* In-memory {@link KVStorage} that mirrors the Durable Object storage semantics
|
|
20
|
+
* (structured-clone on write, lexicographic key ordering on `list`). Use it for
|
|
21
|
+
* local development, tests, and conformance — it behaves like the real DO store
|
|
22
|
+
* without the Workers runtime.
|
|
23
|
+
*/
|
|
24
|
+
declare class MemoryKVStorage implements KVStorage {
|
|
25
|
+
private readonly map;
|
|
26
|
+
get<T = unknown>(key: string): Promise<T | undefined>;
|
|
27
|
+
put<T = unknown>(key: string, value: T): Promise<void>;
|
|
28
|
+
delete(key: string): Promise<boolean>;
|
|
29
|
+
list<T = unknown>(options?: {
|
|
30
|
+
prefix?: string;
|
|
31
|
+
}): Promise<Map<string, T>>;
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
export { KVStorage, MemoryKVStorage };
|
|
35
|
+
//# sourceMappingURL=storage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storage.d.ts","names":[],"sources":["../src/storage.ts"],"sourcesContent":[],"mappings":";;AAQA;;;;;;;AAI4D,UAJ3C,SAAA,CAI2C;EAAR,GAAA,CAAA,IAAA,OAAA,CAAA,CAAA,GAAA,EAAA,MAAA,CAAA,EAHnB,OAGmB,CAHX,CAGW,GAAA,SAAA,CAAA;EAAO,GAAA,CAAA,IAAA,OAAA,CAAA,CAAA,GAAA,EAAA,MAAA,EAAA,KAAA,EAFpB,CAEoB,CAAA,EAFhB,OAEgB,CAAA,IAAA,CAAA;EAe9C,MAAA,CAAA,GAAA,EAAA,MAAgB,CAAA,EAhBN,OAgBM,CAAA,OAAA,CAAA;EAGkB,IAAA,CAAA,IAAA,OAAA,CAAA,CAAA,OAKF,CALE,EAAA;IAAR,MAAA,CAAA,EAAA,MAAA;EAKM,CAAA,CAAA,EAvBO,OAuBP,CAvBe,GAuBf,CAAA,MAAA,EAvB2B,CAuB3B,CAAA,CAAA;;;;;;;;cARhC,eAAA,YAA2B;;iCAGD,QAAQ;uCAKF,IAAI;uBAIpB;;;MAIiC,QAAQ,YAAY"}
|
package/dist/storage.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
//#region src/storage.ts
|
|
2
|
+
function clone(value) {
|
|
3
|
+
return typeof structuredClone === "function" ? structuredClone(value) : JSON.parse(JSON.stringify(value));
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* In-memory {@link KVStorage} that mirrors the Durable Object storage semantics
|
|
7
|
+
* (structured-clone on write, lexicographic key ordering on `list`). Use it for
|
|
8
|
+
* local development, tests, and conformance — it behaves like the real DO store
|
|
9
|
+
* without the Workers runtime.
|
|
10
|
+
*/
|
|
11
|
+
var MemoryKVStorage = class {
|
|
12
|
+
map = /* @__PURE__ */ new Map();
|
|
13
|
+
async get(key) {
|
|
14
|
+
const value = this.map.get(key);
|
|
15
|
+
return value === void 0 ? void 0 : clone(value);
|
|
16
|
+
}
|
|
17
|
+
async put(key, value) {
|
|
18
|
+
this.map.set(key, clone(value));
|
|
19
|
+
}
|
|
20
|
+
async delete(key) {
|
|
21
|
+
return this.map.delete(key);
|
|
22
|
+
}
|
|
23
|
+
async list(options = {}) {
|
|
24
|
+
const prefix = options.prefix ?? "";
|
|
25
|
+
const out = /* @__PURE__ */ new Map();
|
|
26
|
+
for (const key of [...this.map.keys()].sort()) if (key.startsWith(prefix)) out.set(key, clone(this.map.get(key)));
|
|
27
|
+
return out;
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
//#endregion
|
|
32
|
+
export { MemoryKVStorage };
|
|
33
|
+
//# sourceMappingURL=storage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storage.js","names":[],"sources":["../src/storage.ts"],"sourcesContent":["/**\n * The subset of Cloudflare's `DurableObjectStorage` API that the store uses.\n * Cloudflare's real storage is a structural superset of this, so a Durable\n * Object's `state.storage` satisfies it directly.\n *\n * `list()` returns entries ordered lexicographically by key — the property the\n * store relies on for message ordering via zero-padded sequence keys.\n */\nexport interface KVStorage {\n get<T = unknown>(key: string): Promise<T | undefined>\n put<T = unknown>(key: string, value: T): Promise<void>\n delete(key: string): Promise<boolean>\n list<T = unknown>(options?: { prefix?: string }): Promise<Map<string, T>>\n}\n\nfunction clone<T>(value: T): T {\n return typeof structuredClone === 'function'\n ? structuredClone(value)\n : (JSON.parse(JSON.stringify(value)) as T)\n}\n\n/**\n * In-memory {@link KVStorage} that mirrors the Durable Object storage semantics\n * (structured-clone on write, lexicographic key ordering on `list`). Use it for\n * local development, tests, and conformance — it behaves like the real DO store\n * without the Workers runtime.\n */\nexport class MemoryKVStorage implements KVStorage {\n private readonly map = new Map<string, unknown>()\n\n async get<T = unknown>(key: string): Promise<T | undefined> {\n const value = this.map.get(key)\n return value === undefined ? undefined : (clone(value) as T)\n }\n\n async put<T = unknown>(key: string, value: T): Promise<void> {\n this.map.set(key, clone(value))\n }\n\n async delete(key: string): Promise<boolean> {\n return this.map.delete(key)\n }\n\n async list<T = unknown>(options: { prefix?: string } = {}): Promise<Map<string, T>> {\n const prefix = options.prefix ?? ''\n const out = new Map<string, T>()\n for (const key of [...this.map.keys()].sort()) {\n if (key.startsWith(prefix)) out.set(key, clone(this.map.get(key)) as T)\n }\n return out\n }\n}\n"],"mappings":";AAeA,SAAS,MAAS,OAAa;AAC7B,QAAO,OAAO,oBAAoB,aAC9B,gBAAgB,MAAM,GACrB,KAAK,MAAM,KAAK,UAAU,MAAM,CAAC;;;;;;;;AASxC,IAAa,kBAAb,MAAkD;CAChD,AAAiB,sBAAM,IAAI,KAAsB;CAEjD,MAAM,IAAiB,KAAqC;EAC1D,MAAM,QAAQ,KAAK,IAAI,IAAI,IAAI;AAC/B,SAAO,UAAU,SAAY,SAAa,MAAM,MAAM;;CAGxD,MAAM,IAAiB,KAAa,OAAyB;AAC3D,OAAK,IAAI,IAAI,KAAK,MAAM,MAAM,CAAC;;CAGjC,MAAM,OAAO,KAA+B;AAC1C,SAAO,KAAK,IAAI,OAAO,IAAI;;CAG7B,MAAM,KAAkB,UAA+B,EAAE,EAA2B;EAClF,MAAM,SAAS,QAAQ,UAAU;EACjC,MAAM,sBAAM,IAAI,KAAgB;AAChC,OAAK,MAAM,OAAO,CAAC,GAAG,KAAK,IAAI,MAAM,CAAC,CAAC,MAAM,CAC3C,KAAI,IAAI,WAAW,OAAO,CAAE,KAAI,IAAI,KAAK,MAAM,KAAK,IAAI,IAAI,IAAI,CAAC,CAAM;AAEzE,SAAO"}
|
package/dist/store.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { KVStorage } from "./storage.js";
|
|
2
|
+
import { GetMessagesArgs, Resource, Store, Thread } from "@redtuma/core/store";
|
|
3
|
+
import { RedtumaMessage } from "@redtuma/core";
|
|
4
|
+
|
|
5
|
+
//#region src/store.d.ts
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A {@link Store} persisted in a single Cloudflare Durable Object's key/value
|
|
9
|
+
* storage. One Durable Object instance typically owns one conversation thread
|
|
10
|
+
* (or one resource), so its memory is co-located, strongly consistent, and
|
|
11
|
+
* needs no external database. Pass the DO's `state.storage` (or
|
|
12
|
+
* {@link MemoryKVStorage} for local/dev/test).
|
|
13
|
+
*/
|
|
14
|
+
declare class DurableObjectStore implements Store {
|
|
15
|
+
private readonly kv;
|
|
16
|
+
constructor(kv: KVStorage);
|
|
17
|
+
saveThread(thread: Thread): Promise<Thread>;
|
|
18
|
+
getThread(id: string): Promise<Thread | null>;
|
|
19
|
+
getThreadsByResourceId(resourceId: string): Promise<Thread[]>;
|
|
20
|
+
deleteThread(id: string): Promise<void>;
|
|
21
|
+
saveMessages(messages: RedtumaMessage[]): Promise<RedtumaMessage[]>;
|
|
22
|
+
getMessages({
|
|
23
|
+
threadId,
|
|
24
|
+
last
|
|
25
|
+
}: GetMessagesArgs): Promise<RedtumaMessage[]>;
|
|
26
|
+
getResource(id: string): Promise<Resource | null>;
|
|
27
|
+
saveResource(resource: Resource): Promise<Resource>;
|
|
28
|
+
persistSnapshot(k: string, value: unknown): Promise<void>;
|
|
29
|
+
loadSnapshot<T = unknown>(k: string): Promise<T | null>;
|
|
30
|
+
}
|
|
31
|
+
//#endregion
|
|
32
|
+
export { DurableObjectStore };
|
|
33
|
+
//# sourceMappingURL=store.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store.d.ts","names":[],"sources":["../src/store.ts"],"sourcesContent":[],"mappings":";;;;;;;;AA0BA;;;;;AAQuC,cAR1B,kBAAA,YAA8B,KAQJ,CAAA;EAAR,iBAAA,EAAA;EAI6B,WAAA,CAAA,EAAA,EAXzB,SAWyB;EAAR,UAAA,CAAA,MAAA,EATzB,MASyB,CAAA,EAThB,OASgB,CATR,MASQ,CAAA;EAKlB,SAAA,CAAA,EAAA,EAAA,MAAA,CAAA,EATH,OASG,CATK,MASL,GAAA,IAAA,CAAA;EAOH,sBAAA,CAAA,UAAA,EAAA,MAAA,CAAA,EAZqB,OAYrB,CAZ6B,MAY7B,EAAA,CAAA;EAA2B,YAAA,CAAA,EAAA,EAAA,MAAA,CAAA,EAPxB,OAOwB,CAAA,IAAA,CAAA;EAAR,YAAA,CAAA,QAAA,EAAnB,cAAmB,EAAA,CAAA,EAAA,OAAA,CAAQ,cAAR,EAAA,CAAA;EAiB5B,WAAA,CAAA;IAAA,QAAA;IAAA;EAAA,CAAA,EAAkB,eAAlB,CAAA,EAAoC,OAApC,CAA4C,cAA5C,EAAA,CAAA;EAAU,WAAA,CAAA,EAAA,EAAA,MAAA,CAAA,EAMC,OAND,CAMS,QANT,GAAA,IAAA,CAAA;EAAQ,YAAA,CAAA,QAAA,EAUT,QAVS,CAAA,EAUE,OAVF,CAUU,QAVV,CAAA;EAA0B,eAAA,CAAA,CAAA,EAAA,MAAA,EAAA,KAAA,EAAA,OAAA,CAAA,EAed,OAfc,CAAA,IAAA,CAAA;EAAR,YAAA,CAAA,IAAA,OAAA,CAAA,CAAA,CAAA,EAAA,MAAA,CAAA,EAmBZ,OAnBY,CAmBJ,CAnBI,GAAA,IAAA,CAAA"}
|
package/dist/store.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
//#region src/store.ts
|
|
2
|
+
const SEQ_WIDTH = 16;
|
|
3
|
+
const pad = (n) => n.toString().padStart(SEQ_WIDTH, "0");
|
|
4
|
+
const key = {
|
|
5
|
+
thread: (id) => `t:${id}`,
|
|
6
|
+
threadPrefix: "t:",
|
|
7
|
+
message: (threadId, seq) => `m:${threadId}:${pad(seq)}`,
|
|
8
|
+
messagePrefix: (threadId) => `m:${threadId}:`,
|
|
9
|
+
counter: (threadId) => `c:${threadId}`,
|
|
10
|
+
resource: (id) => `r:${id}`,
|
|
11
|
+
snapshot: (k) => `s:${k}`
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* A {@link Store} persisted in a single Cloudflare Durable Object's key/value
|
|
15
|
+
* storage. One Durable Object instance typically owns one conversation thread
|
|
16
|
+
* (or one resource), so its memory is co-located, strongly consistent, and
|
|
17
|
+
* needs no external database. Pass the DO's `state.storage` (or
|
|
18
|
+
* {@link MemoryKVStorage} for local/dev/test).
|
|
19
|
+
*/
|
|
20
|
+
var DurableObjectStore = class {
|
|
21
|
+
constructor(kv) {
|
|
22
|
+
this.kv = kv;
|
|
23
|
+
}
|
|
24
|
+
async saveThread(thread) {
|
|
25
|
+
await this.kv.put(key.thread(thread.id), thread);
|
|
26
|
+
return thread;
|
|
27
|
+
}
|
|
28
|
+
async getThread(id) {
|
|
29
|
+
return await this.kv.get(key.thread(id)) ?? null;
|
|
30
|
+
}
|
|
31
|
+
async getThreadsByResourceId(resourceId) {
|
|
32
|
+
return [...(await this.kv.list({ prefix: key.threadPrefix })).values()].filter((t) => t.resourceId === resourceId);
|
|
33
|
+
}
|
|
34
|
+
async deleteThread(id) {
|
|
35
|
+
await this.kv.delete(key.thread(id));
|
|
36
|
+
await this.kv.delete(key.counter(id));
|
|
37
|
+
const messages = await this.kv.list({ prefix: key.messagePrefix(id) });
|
|
38
|
+
for (const k of messages.keys()) await this.kv.delete(k);
|
|
39
|
+
}
|
|
40
|
+
async saveMessages(messages) {
|
|
41
|
+
const nextSeq = /* @__PURE__ */ new Map();
|
|
42
|
+
for (const m of messages) {
|
|
43
|
+
if (!m.threadId) continue;
|
|
44
|
+
let seq = nextSeq.get(m.threadId);
|
|
45
|
+
if (seq === void 0) seq = await this.kv.get(key.counter(m.threadId)) ?? 0;
|
|
46
|
+
await this.kv.put(key.message(m.threadId, seq), m);
|
|
47
|
+
nextSeq.set(m.threadId, seq + 1);
|
|
48
|
+
}
|
|
49
|
+
for (const [threadId, seq] of nextSeq) await this.kv.put(key.counter(threadId), seq);
|
|
50
|
+
return messages;
|
|
51
|
+
}
|
|
52
|
+
async getMessages({ threadId, last }) {
|
|
53
|
+
const all = [...(await this.kv.list({ prefix: key.messagePrefix(threadId) })).values()];
|
|
54
|
+
return typeof last === "number" ? all.slice(-last) : all;
|
|
55
|
+
}
|
|
56
|
+
async getResource(id) {
|
|
57
|
+
return await this.kv.get(key.resource(id)) ?? null;
|
|
58
|
+
}
|
|
59
|
+
async saveResource(resource) {
|
|
60
|
+
await this.kv.put(key.resource(resource.id), resource);
|
|
61
|
+
return resource;
|
|
62
|
+
}
|
|
63
|
+
async persistSnapshot(k, value) {
|
|
64
|
+
await this.kv.put(key.snapshot(k), value);
|
|
65
|
+
}
|
|
66
|
+
async loadSnapshot(k) {
|
|
67
|
+
return await this.kv.get(key.snapshot(k)) ?? null;
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
//#endregion
|
|
72
|
+
export { DurableObjectStore };
|
|
73
|
+
//# sourceMappingURL=store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store.js","names":["kv: KVStorage"],"sources":["../src/store.ts"],"sourcesContent":["import type { GetMessagesArgs, Resource, Store, Thread } from '@redtuma/core/store'\nimport type { RedtumaMessage } from '@redtuma/core'\nimport type { KVStorage } from './storage'\n\n// Zero-padded sequence width — keeps lexicographic key order equal to numeric\n// order for any realistic thread length.\nconst SEQ_WIDTH = 16\nconst pad = (n: number): string => n.toString().padStart(SEQ_WIDTH, '0')\n\nconst key = {\n thread: (id: string) => `t:${id}`,\n threadPrefix: 't:',\n message: (threadId: string, seq: number) => `m:${threadId}:${pad(seq)}`,\n messagePrefix: (threadId: string) => `m:${threadId}:`,\n counter: (threadId: string) => `c:${threadId}`,\n resource: (id: string) => `r:${id}`,\n snapshot: (k: string) => `s:${k}`,\n}\n\n/**\n * A {@link Store} persisted in a single Cloudflare Durable Object's key/value\n * storage. One Durable Object instance typically owns one conversation thread\n * (or one resource), so its memory is co-located, strongly consistent, and\n * needs no external database. Pass the DO's `state.storage` (or\n * {@link MemoryKVStorage} for local/dev/test).\n */\nexport class DurableObjectStore implements Store {\n constructor(private readonly kv: KVStorage) {}\n\n async saveThread(thread: Thread): Promise<Thread> {\n await this.kv.put(key.thread(thread.id), thread)\n return thread\n }\n\n async getThread(id: string): Promise<Thread | null> {\n return (await this.kv.get<Thread>(key.thread(id))) ?? null\n }\n\n async getThreadsByResourceId(resourceId: string): Promise<Thread[]> {\n const threads = await this.kv.list<Thread>({ prefix: key.threadPrefix })\n return [...threads.values()].filter((t) => t.resourceId === resourceId)\n }\n\n async deleteThread(id: string): Promise<void> {\n await this.kv.delete(key.thread(id))\n await this.kv.delete(key.counter(id))\n const messages = await this.kv.list({ prefix: key.messagePrefix(id) })\n for (const k of messages.keys()) await this.kv.delete(k)\n }\n\n async saveMessages(messages: RedtumaMessage[]): Promise<RedtumaMessage[]> {\n // Per-thread monotonic sequence. DO execution is single-threaded, so this\n // read-modify-write is race-free within an object.\n const nextSeq = new Map<string, number>()\n for (const m of messages) {\n if (!m.threadId) continue\n let seq = nextSeq.get(m.threadId)\n if (seq === undefined) seq = (await this.kv.get<number>(key.counter(m.threadId))) ?? 0\n await this.kv.put(key.message(m.threadId, seq), m)\n nextSeq.set(m.threadId, seq + 1)\n }\n for (const [threadId, seq] of nextSeq) {\n await this.kv.put(key.counter(threadId), seq)\n }\n return messages\n }\n\n async getMessages({ threadId, last }: GetMessagesArgs): Promise<RedtumaMessage[]> {\n const map = await this.kv.list<RedtumaMessage>({ prefix: key.messagePrefix(threadId) })\n const all = [...map.values()]\n return typeof last === 'number' ? all.slice(-last) : all\n }\n\n async getResource(id: string): Promise<Resource | null> {\n return (await this.kv.get<Resource>(key.resource(id))) ?? null\n }\n\n async saveResource(resource: Resource): Promise<Resource> {\n await this.kv.put(key.resource(resource.id), resource)\n return resource\n }\n\n async persistSnapshot(k: string, value: unknown): Promise<void> {\n await this.kv.put(key.snapshot(k), value)\n }\n\n async loadSnapshot<T = unknown>(k: string): Promise<T | null> {\n return (await this.kv.get<T>(key.snapshot(k))) ?? null\n }\n}\n"],"mappings":";AAMA,MAAM,YAAY;AAClB,MAAM,OAAO,MAAsB,EAAE,UAAU,CAAC,SAAS,WAAW,IAAI;AAExE,MAAM,MAAM;CACV,SAAS,OAAe,KAAK;CAC7B,cAAc;CACd,UAAU,UAAkB,QAAgB,KAAK,SAAS,GAAG,IAAI,IAAI;CACrE,gBAAgB,aAAqB,KAAK,SAAS;CACnD,UAAU,aAAqB,KAAK;CACpC,WAAW,OAAe,KAAK;CAC/B,WAAW,MAAc,KAAK;CAC/B;;;;;;;;AASD,IAAa,qBAAb,MAAiD;CAC/C,YAAY,AAAiBA,IAAe;EAAf;;CAE7B,MAAM,WAAW,QAAiC;AAChD,QAAM,KAAK,GAAG,IAAI,IAAI,OAAO,OAAO,GAAG,EAAE,OAAO;AAChD,SAAO;;CAGT,MAAM,UAAU,IAAoC;AAClD,SAAQ,MAAM,KAAK,GAAG,IAAY,IAAI,OAAO,GAAG,CAAC,IAAK;;CAGxD,MAAM,uBAAuB,YAAuC;AAElE,SAAO,CAAC,IADQ,MAAM,KAAK,GAAG,KAAa,EAAE,QAAQ,IAAI,cAAc,CAAC,EACrD,QAAQ,CAAC,CAAC,QAAQ,MAAM,EAAE,eAAe,WAAW;;CAGzE,MAAM,aAAa,IAA2B;AAC5C,QAAM,KAAK,GAAG,OAAO,IAAI,OAAO,GAAG,CAAC;AACpC,QAAM,KAAK,GAAG,OAAO,IAAI,QAAQ,GAAG,CAAC;EACrC,MAAM,WAAW,MAAM,KAAK,GAAG,KAAK,EAAE,QAAQ,IAAI,cAAc,GAAG,EAAE,CAAC;AACtE,OAAK,MAAM,KAAK,SAAS,MAAM,CAAE,OAAM,KAAK,GAAG,OAAO,EAAE;;CAG1D,MAAM,aAAa,UAAuD;EAGxE,MAAM,0BAAU,IAAI,KAAqB;AACzC,OAAK,MAAM,KAAK,UAAU;AACxB,OAAI,CAAC,EAAE,SAAU;GACjB,IAAI,MAAM,QAAQ,IAAI,EAAE,SAAS;AACjC,OAAI,QAAQ,OAAW,OAAO,MAAM,KAAK,GAAG,IAAY,IAAI,QAAQ,EAAE,SAAS,CAAC,IAAK;AACrF,SAAM,KAAK,GAAG,IAAI,IAAI,QAAQ,EAAE,UAAU,IAAI,EAAE,EAAE;AAClD,WAAQ,IAAI,EAAE,UAAU,MAAM,EAAE;;AAElC,OAAK,MAAM,CAAC,UAAU,QAAQ,QAC5B,OAAM,KAAK,GAAG,IAAI,IAAI,QAAQ,SAAS,EAAE,IAAI;AAE/C,SAAO;;CAGT,MAAM,YAAY,EAAE,UAAU,QAAoD;EAEhF,MAAM,MAAM,CAAC,IADD,MAAM,KAAK,GAAG,KAAqB,EAAE,QAAQ,IAAI,cAAc,SAAS,EAAE,CAAC,EACnE,QAAQ,CAAC;AAC7B,SAAO,OAAO,SAAS,WAAW,IAAI,MAAM,CAAC,KAAK,GAAG;;CAGvD,MAAM,YAAY,IAAsC;AACtD,SAAQ,MAAM,KAAK,GAAG,IAAc,IAAI,SAAS,GAAG,CAAC,IAAK;;CAG5D,MAAM,aAAa,UAAuC;AACxD,QAAM,KAAK,GAAG,IAAI,IAAI,SAAS,SAAS,GAAG,EAAE,SAAS;AACtD,SAAO;;CAGT,MAAM,gBAAgB,GAAW,OAA+B;AAC9D,QAAM,KAAK,GAAG,IAAI,IAAI,SAAS,EAAE,EAAE,MAAM;;CAG3C,MAAM,aAA0B,GAA8B;AAC5D,SAAQ,MAAM,KAAK,GAAG,IAAO,IAAI,SAAS,EAAE,CAAC,IAAK"}
|
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@redtuma/store-do",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Redtuma store adapter backed by a Cloudflare Durable Object — edge-native agent memory with no external database.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"files": [
|
|
9
|
+
"dist"
|
|
10
|
+
],
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"import": "./dist/index.js"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@redtuma/core": "0.1.0"
|
|
19
|
+
},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"@types/node": "^22.10.0",
|
|
22
|
+
"typescript": "^5.7.0",
|
|
23
|
+
"vitest": "^2.1.0",
|
|
24
|
+
"@redtuma/spec": "0.0.0"
|
|
25
|
+
},
|
|
26
|
+
"repository": {
|
|
27
|
+
"type": "git",
|
|
28
|
+
"url": "git+https://github.com/redtuma/redtuma.git",
|
|
29
|
+
"directory": "stores/do"
|
|
30
|
+
},
|
|
31
|
+
"homepage": "https://redtuma.ai",
|
|
32
|
+
"bugs": "https://github.com/redtuma/redtuma/issues",
|
|
33
|
+
"keywords": [
|
|
34
|
+
"ai",
|
|
35
|
+
"agents",
|
|
36
|
+
"llm",
|
|
37
|
+
"typescript",
|
|
38
|
+
"redtuma",
|
|
39
|
+
"cloudflare",
|
|
40
|
+
"durable-objects",
|
|
41
|
+
"edge"
|
|
42
|
+
],
|
|
43
|
+
"scripts": {
|
|
44
|
+
"build": "tsdown",
|
|
45
|
+
"test": "vitest run",
|
|
46
|
+
"verify:workerd": "node integration/verify.mjs",
|
|
47
|
+
"typecheck": "tsc --noEmit",
|
|
48
|
+
"clean": "rm -rf dist .turbo"
|
|
49
|
+
}
|
|
50
|
+
}
|