@tessar/mongodb 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +50 -2
- package/dist/backend.d.ts +4 -0
- package/dist/backend.js +380 -0
- package/dist/backend.js.map +1 -0
- package/dist/database.d.ts +19 -0
- package/dist/database.js +38 -0
- package/dist/database.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +20 -0
- package/dist/index.js.map +1 -0
- package/dist/ownership.d.ts +7 -0
- package/dist/ownership.js +89 -0
- package/dist/ownership.js.map +1 -0
- package/dist/queries.d.ts +10 -0
- package/dist/queries.js +39 -0
- package/dist/queries.js.map +1 -0
- package/dist/schema.d.ts +13 -0
- package/dist/schema.js +79 -0
- package/dist/schema.js.map +1 -0
- package/dist/versions.d.ts +12 -0
- package/dist/versions.js +75 -0
- package/dist/versions.js.map +1 -0
- package/package.json +42 -3
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 2026 hphucdev-04
|
|
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
CHANGED
|
@@ -1,3 +1,51 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tessar/mongodb
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
MongoDB storage for Tessar using the native `mongodb` driver. Requires a replica
|
|
4
|
+
set or sharded MongoDB deployment supporting transactions; standalone servers are
|
|
5
|
+
rejected during setup. Repository CI is configured to test a MongoDB 8 replica set.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { MongoDBStoragePlugin } from "@tessar/mongodb";
|
|
9
|
+
|
|
10
|
+
const storage = new MongoDBStoragePlugin({
|
|
11
|
+
uri: process.env.MONGODB_URL!,
|
|
12
|
+
databaseName: "my_agent",
|
|
13
|
+
clientOptions: { maxPoolSize: 10 },
|
|
14
|
+
});
|
|
15
|
+
// Include storage in your Tessar plugins configuration.
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
`createMongoDBBackend(options)` exposes the same backend directly. The plugin
|
|
19
|
+
registers it with `tessar.storage.register`; the backend owns its MongoClient and
|
|
20
|
+
its idempotent `close()` closes that client. Initialization failures close it too.
|
|
21
|
+
Use `clientOptions` for native TLS and connection-pool configuration.
|
|
22
|
+
|
|
23
|
+
The database contains `tessar_*` collections for sessions, plugin state, thread
|
|
24
|
+
heads, checkpoints, version intervals, staging and commit receipts. Messages and
|
|
25
|
+
execution records are versioned individually; unchanged messages are not copied
|
|
26
|
+
into each checkpoint. Staging uses separate message and record documents, so a
|
|
27
|
+
conversation can exceed MongoDB's 16 MiB document limit. Each individual message,
|
|
28
|
+
record, checkpoint metadata or plugin state must still fit that native limit.
|
|
29
|
+
Large commits are also subject to MongoDB transaction resource/time limits.
|
|
30
|
+
|
|
31
|
+
Publication uses snapshot transactions and majority acknowledgement. Lease
|
|
32
|
+
expiry uses server time. Lease documents retain monotonic fencing tokens after
|
|
33
|
+
release and purge. Thread coordination writes serialize publication, takeover,
|
|
34
|
+
session selection, fork-source validation and purge across clients.
|
|
35
|
+
|
|
36
|
+
Set `TESSAR_TEST_MONGODB_URL` in the repository's ignored `.env.storage`, then run
|
|
37
|
+
`pnpm test:storage`. Tests skip explicitly without a URL. Each test creates and
|
|
38
|
+
drops only its generated `tessar_test_<uuid>` database. The database user needs
|
|
39
|
+
collection/index creation and database deletion privileges; the rollback test
|
|
40
|
+
also uses `collMod` on its generated collection. Never put credentials in tracked
|
|
41
|
+
files. No external Docker setup is required when using an existing replica set.
|
|
42
|
+
|
|
43
|
+
The physical schema is versioned in `tessar_schema` (version 1). Unsupported
|
|
44
|
+
versions fail before creating application collections or indexes. Initial
|
|
45
|
+
unversioned data is retained. Metadata is stamped only after initialization
|
|
46
|
+
finishes, so an interrupted initial setup can be retried without a reset.
|
|
47
|
+
|
|
48
|
+
The adapter separates `schema.ts`, `ownership.ts`, `versions.ts`, `queries.ts`,
|
|
49
|
+
connection/transaction lifecycle in `database.ts`, and contract wiring in
|
|
50
|
+
`backend.ts`. It follows the same logical storage rules as SQLite/PostgreSQL;
|
|
51
|
+
native collections and transactions implement those rules.
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type MongoDBStorageOptions } from "./database.js";
|
|
2
|
+
import { type StorageBackend } from "@tessar/core";
|
|
3
|
+
export type { MongoDBStorageOptions } from "./database.js";
|
|
4
|
+
export declare function createMongoDBBackend(options: MongoDBStorageOptions): Promise<StorageBackend>;
|
package/dist/backend.js
ADDED
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
import { openDatabase } from "./database.js";
|
|
2
|
+
import { ensureThread, touchThread, assertOwnership, createOwnership, } from "./ownership.js";
|
|
3
|
+
import { interval, readVersions, writeVersions, hydrateCheckpoint, writeCheckpoint, } from "./versions.js";
|
|
4
|
+
import { buildThreadInfo, canonicalJson, commitFingerprint, encodeCursor, fail, historyCursor, immutable, limitOf, matchesScope, recordBinding, validateBatch, validateSession, } from "@tessar/core";
|
|
5
|
+
import { decode, mongoPage, scopeFilter, scopeTokens, } from "./queries.js";
|
|
6
|
+
const kinds = [
|
|
7
|
+
"streams",
|
|
8
|
+
"turns",
|
|
9
|
+
"model_attempts",
|
|
10
|
+
"tool_executions",
|
|
11
|
+
"interrupts",
|
|
12
|
+
];
|
|
13
|
+
const key = (...parts) => canonicalJson(parts);
|
|
14
|
+
const validKind = (kind) => {
|
|
15
|
+
if (!kinds.includes(kind))
|
|
16
|
+
fail("InvalidConfiguration", "Unknown record kind");
|
|
17
|
+
};
|
|
18
|
+
export async function createMongoDBBackend(options) {
|
|
19
|
+
const db = await openDatabase(options);
|
|
20
|
+
const { threads, checkpoints, versions, sessions, owned, leases, commits, staging, pieces, transaction, } = db;
|
|
21
|
+
const head = async (id, session) => decode(await threads.findOne({ _id: id }, { session }));
|
|
22
|
+
const cpRow = (id, session) => checkpoints.findOne({ _id: id }, { session });
|
|
23
|
+
async function recordCheckpoint(threadId, atCheckpointId, session) {
|
|
24
|
+
const row = await cpRow(atCheckpointId ??
|
|
25
|
+
(await head(threadId, session))?.currentCheckpointId ??
|
|
26
|
+
"", session);
|
|
27
|
+
return row?.threadId === threadId ? row : null;
|
|
28
|
+
}
|
|
29
|
+
const ownerKey = (value) => key(value.ownerType, value.ownerId, value.pluginId, value.namespace);
|
|
30
|
+
return {
|
|
31
|
+
id: "mongodb",
|
|
32
|
+
capabilities: {
|
|
33
|
+
durable: true,
|
|
34
|
+
atomicPublish: true,
|
|
35
|
+
coordination: "multi-process",
|
|
36
|
+
},
|
|
37
|
+
sessions: {
|
|
38
|
+
get: async (id, query = {}) => decode(await sessions.findOne({ _id: id, ...scopeFilter(query.scope) })),
|
|
39
|
+
page: (query) => mongoPage(sessions, { agentId: query.agentId, ...scopeFilter(query.scope) }, query, canonicalJson({ agentId: query.agentId, scope: query.scope ?? {} })),
|
|
40
|
+
compareAndSet: async (value, expected) => {
|
|
41
|
+
value = immutable(value);
|
|
42
|
+
if (value.selectedThreadId)
|
|
43
|
+
await ensureThread(leases, value.selectedThreadId);
|
|
44
|
+
await transaction(async (session) => {
|
|
45
|
+
if (value.selectedThreadId)
|
|
46
|
+
await touchThread(leases, value.selectedThreadId, session);
|
|
47
|
+
const old = decode(await sessions.findOne({ _id: value.id }, { session }));
|
|
48
|
+
validateSession(value, old, expected, value.selectedThreadId
|
|
49
|
+
? await head(value.selectedThreadId, session)
|
|
50
|
+
: null);
|
|
51
|
+
await sessions.replaceOne({ _id: value.id }, {
|
|
52
|
+
_id: value.id,
|
|
53
|
+
id: value.id,
|
|
54
|
+
agentId: value.agentId,
|
|
55
|
+
selectedThreadId: value.selectedThreadId,
|
|
56
|
+
scopeTokens: scopeTokens(value.scope),
|
|
57
|
+
sortDate: value.createdAt,
|
|
58
|
+
body: canonicalJson(value),
|
|
59
|
+
}, { upsert: true, session });
|
|
60
|
+
});
|
|
61
|
+
},
|
|
62
|
+
},
|
|
63
|
+
ownedState: {
|
|
64
|
+
get: async (value) => decode(await owned.findOne({ _id: ownerKey(value) })),
|
|
65
|
+
compareAndSet: (value, expected) => {
|
|
66
|
+
value = immutable(value);
|
|
67
|
+
return transaction(async (session) => {
|
|
68
|
+
if (!["agent", "session"].includes(value.ownerType))
|
|
69
|
+
fail("InvalidConfiguration", "Execution state must use checkpoints");
|
|
70
|
+
const id = ownerKey(value), old = decode(await owned.findOne({ _id: id }, { session }));
|
|
71
|
+
if ((old?.revision ?? 0) !== expected ||
|
|
72
|
+
value.revision !== expected + 1)
|
|
73
|
+
fail("CommitConflict", "Owned state revision changed");
|
|
74
|
+
await owned.replaceOne({ _id: id }, { _id: id, body: canonicalJson(value) }, { session, upsert: true });
|
|
75
|
+
});
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
ownership: createOwnership(leases),
|
|
79
|
+
threads: {
|
|
80
|
+
get: async (id, options) => {
|
|
81
|
+
const value = await head(id);
|
|
82
|
+
return value && (!value.deleted || options?.includeDeleted)
|
|
83
|
+
? value
|
|
84
|
+
: null;
|
|
85
|
+
},
|
|
86
|
+
list: async (query = {}) => (await threads
|
|
87
|
+
.find({ deleted: false, ...scopeFilter(query.scope) })
|
|
88
|
+
.toArray()).map((row) => decode(row)),
|
|
89
|
+
page: (query) => mongoPage(threads, { deleted: false, ...scopeFilter(query.scope) }, query, canonicalJson(query.scope ?? {})),
|
|
90
|
+
purge: async (id, query = {}) => {
|
|
91
|
+
await ensureThread(leases, id);
|
|
92
|
+
await transaction(async (session) => {
|
|
93
|
+
const free = await leases.updateOne({ _id: id, $expr: { $lte: ["$expiresAt", "$$NOW"] } }, { $inc: { serial: 1 } }, { session });
|
|
94
|
+
const info = await head(id, session);
|
|
95
|
+
if (!info || !matchesScope(info.scope, query.scope))
|
|
96
|
+
fail("ThreadNotFound", "Thread does not match query");
|
|
97
|
+
if (!info.deleted)
|
|
98
|
+
fail("ThreadNotDeleted", "Soft-delete the thread before purging");
|
|
99
|
+
if (!free.matchedCount || info.activeStreamId)
|
|
100
|
+
fail("ThreadBusy", "Thread has active execution or ownership");
|
|
101
|
+
if (await threads.findOne({ parentThreadId: id }, { session }))
|
|
102
|
+
fail("ThreadReferenced", "Retained fork references this thread");
|
|
103
|
+
// A retained fork can also identify its source checkpoint explicitly.
|
|
104
|
+
for await (const cp of checkpoints.find({ threadId: id }, { session }))
|
|
105
|
+
if (await threads.findOne({ sourceCheckpointId: cp._id }, { session }))
|
|
106
|
+
fail("ThreadReferenced", "Retained fork references this thread");
|
|
107
|
+
for (const collection of [
|
|
108
|
+
versions,
|
|
109
|
+
checkpoints,
|
|
110
|
+
commits,
|
|
111
|
+
staging,
|
|
112
|
+
pieces,
|
|
113
|
+
])
|
|
114
|
+
await collection.deleteMany({ threadId: id }, { session });
|
|
115
|
+
await threads.deleteOne({ _id: id }, { session });
|
|
116
|
+
});
|
|
117
|
+
},
|
|
118
|
+
},
|
|
119
|
+
checkpoints: {
|
|
120
|
+
get: (id) => transaction(async (session) => {
|
|
121
|
+
const row = await cpRow(id, session);
|
|
122
|
+
return row ? hydrateCheckpoint(versions, row, session) : null;
|
|
123
|
+
}),
|
|
124
|
+
list: (threadId) => transaction(async (session) => {
|
|
125
|
+
const rows = await checkpoints
|
|
126
|
+
.find({ threadId }, { session })
|
|
127
|
+
.sort({ revision: 1 })
|
|
128
|
+
.toArray(), result = [];
|
|
129
|
+
for (const row of rows)
|
|
130
|
+
result.push(await hydrateCheckpoint(versions, row, session));
|
|
131
|
+
return result;
|
|
132
|
+
}),
|
|
133
|
+
page: (threadId, options) => mongoPage(checkpoints, { threadId }, options, "checkpoints:" + threadId, undefined, (row) => ({
|
|
134
|
+
id: row._id,
|
|
135
|
+
threadId,
|
|
136
|
+
revision: row.revision,
|
|
137
|
+
createdAt: row.sortDate,
|
|
138
|
+
cause: row.cause,
|
|
139
|
+
forkable: row.forkable,
|
|
140
|
+
unsafeReason: row.unsafeReason,
|
|
141
|
+
})),
|
|
142
|
+
history: (threadId, options, query = {}) => transaction(async (session) => {
|
|
143
|
+
const info = await head(threadId, session);
|
|
144
|
+
if (!info || info.deleted || !matchesScope(info.scope, query.scope))
|
|
145
|
+
fail("ThreadNotFound", "Thread does not match query");
|
|
146
|
+
const { binding, cursor } = historyCursor(threadId, options, query), limit = limitOf(options.limit);
|
|
147
|
+
const cp = await recordCheckpoint(threadId, cursor?.checkpointId ??
|
|
148
|
+
options.atCheckpointId ??
|
|
149
|
+
info.currentCheckpointId, session);
|
|
150
|
+
if (!cp)
|
|
151
|
+
fail("CheckpointNotFound", "No checkpoint for history");
|
|
152
|
+
const end = cursor?.end ?? cp.messageCount;
|
|
153
|
+
if (end > cp.messageCount)
|
|
154
|
+
fail("InvalidCursor", "Invalid history position");
|
|
155
|
+
const begin = Math.max(0, end - limit);
|
|
156
|
+
const items = (await versions
|
|
157
|
+
.find({
|
|
158
|
+
...interval(threadId, "messages", cp.revision),
|
|
159
|
+
position: { $gte: begin, $lt: end },
|
|
160
|
+
}, { session })
|
|
161
|
+
.sort({ position: 1 })
|
|
162
|
+
.limit(limit)
|
|
163
|
+
.toArray()).map((row) => decode(row));
|
|
164
|
+
return {
|
|
165
|
+
items,
|
|
166
|
+
checkpointId: cp._id,
|
|
167
|
+
revision: cp.revision,
|
|
168
|
+
nextCursor: begin
|
|
169
|
+
? encodeCursor({
|
|
170
|
+
v: 1,
|
|
171
|
+
binding,
|
|
172
|
+
checkpointId: cp._id,
|
|
173
|
+
end: begin,
|
|
174
|
+
})
|
|
175
|
+
: null,
|
|
176
|
+
};
|
|
177
|
+
}),
|
|
178
|
+
},
|
|
179
|
+
executions: {
|
|
180
|
+
page: (kind, threadId, query) => transaction(async (session) => {
|
|
181
|
+
validKind(kind);
|
|
182
|
+
const cp = await recordCheckpoint(threadId, query.atCheckpointId, session);
|
|
183
|
+
if (!cp)
|
|
184
|
+
fail("CheckpointNotFound", "No checkpoint for records");
|
|
185
|
+
const filter = interval(threadId, kind, cp.revision);
|
|
186
|
+
for (const field of ["streamId", "turnId", "status"])
|
|
187
|
+
if (query[field] !== undefined)
|
|
188
|
+
filter[field] = query[field];
|
|
189
|
+
return mongoPage(versions, filter, query, recordBinding(kind, threadId, query), session);
|
|
190
|
+
}),
|
|
191
|
+
listRecords: (kind, threadId, query) => transaction(async (session) => {
|
|
192
|
+
validKind(kind);
|
|
193
|
+
const cp = await recordCheckpoint(threadId, query?.atCheckpointId, session);
|
|
194
|
+
return cp
|
|
195
|
+
? readVersions(versions, kind, threadId, cp.revision, session)
|
|
196
|
+
: [];
|
|
197
|
+
}),
|
|
198
|
+
get: (kind, id, query) => transaction(async (session) => {
|
|
199
|
+
validKind(kind);
|
|
200
|
+
if (query?.threadId || query?.atCheckpointId) {
|
|
201
|
+
const cp = query.threadId
|
|
202
|
+
? await recordCheckpoint(query.threadId, query.atCheckpointId, session)
|
|
203
|
+
: await cpRow(query.atCheckpointId, session);
|
|
204
|
+
return cp
|
|
205
|
+
? decode(await versions.findOne({ ...interval(cp.threadId, kind, cp.revision), id }, { session }))
|
|
206
|
+
: null;
|
|
207
|
+
}
|
|
208
|
+
for await (const row of versions.find({ kind, id, toRevision: null }, { session })) {
|
|
209
|
+
const info = await head(row.threadId, session);
|
|
210
|
+
if (info && !info.deleted)
|
|
211
|
+
return decode(row);
|
|
212
|
+
}
|
|
213
|
+
return null;
|
|
214
|
+
}),
|
|
215
|
+
},
|
|
216
|
+
commits: {
|
|
217
|
+
lookupCommit: async (id) => decode(await commits.findOne({ _id: id })),
|
|
218
|
+
stage: async (batch) => {
|
|
219
|
+
batch = immutable(batch);
|
|
220
|
+
validateBatch(batch);
|
|
221
|
+
for (const record of batch.records)
|
|
222
|
+
validKind(record.kind);
|
|
223
|
+
const fingerprint = await commitFingerprint(batch);
|
|
224
|
+
await ensureThread(leases, batch.threadId);
|
|
225
|
+
await transaction(async (session) => {
|
|
226
|
+
await touchThread(leases, batch.threadId, session);
|
|
227
|
+
const old = (await commits.findOne({ _id: batch.commitId }, { session })) ??
|
|
228
|
+
(await staging.findOne({ _id: batch.commitId }, { session }));
|
|
229
|
+
if (old) {
|
|
230
|
+
if (old.fingerprint !== fingerprint)
|
|
231
|
+
fail("CommitConflict", "commitId payload mismatch");
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
const { messages, ...state } = batch.checkpoint.state;
|
|
235
|
+
const { records, ...rest } = batch;
|
|
236
|
+
await staging.insertOne({
|
|
237
|
+
_id: batch.commitId,
|
|
238
|
+
threadId: batch.threadId,
|
|
239
|
+
fingerprint,
|
|
240
|
+
body: canonicalJson({
|
|
241
|
+
...rest,
|
|
242
|
+
checkpoint: { ...batch.checkpoint, state },
|
|
243
|
+
}),
|
|
244
|
+
}, { session });
|
|
245
|
+
// Each message/record gets its own document; histories can exceed 16 MiB.
|
|
246
|
+
for (const [position, message] of messages.entries())
|
|
247
|
+
await pieces.insertOne({
|
|
248
|
+
_id: key(batch.commitId, "messages", position),
|
|
249
|
+
commitId: batch.commitId,
|
|
250
|
+
threadId: batch.threadId,
|
|
251
|
+
kind: "messages",
|
|
252
|
+
position,
|
|
253
|
+
body: canonicalJson(message),
|
|
254
|
+
}, { session });
|
|
255
|
+
for (const [position, record] of records.entries())
|
|
256
|
+
await pieces.insertOne({
|
|
257
|
+
_id: key(batch.commitId, "records", position),
|
|
258
|
+
commitId: batch.commitId,
|
|
259
|
+
threadId: batch.threadId,
|
|
260
|
+
kind: "records",
|
|
261
|
+
position,
|
|
262
|
+
body: canonicalJson(record),
|
|
263
|
+
}, { session });
|
|
264
|
+
});
|
|
265
|
+
},
|
|
266
|
+
publish: (request) => {
|
|
267
|
+
request = immutable(request);
|
|
268
|
+
return transaction(async (session) => {
|
|
269
|
+
const prior = decode(await commits.findOne({ _id: request.commitId }, { session }));
|
|
270
|
+
if (prior) {
|
|
271
|
+
if (prior.threadId !== request.threadId ||
|
|
272
|
+
prior.revision !== request.expectedRevision + 1)
|
|
273
|
+
fail("CommitConflict", "Commit request mismatch");
|
|
274
|
+
return prior;
|
|
275
|
+
}
|
|
276
|
+
if (request.lease.threadId !== request.threadId)
|
|
277
|
+
fail("OwnershipLost", "Lease belongs to another thread");
|
|
278
|
+
await assertOwnership(leases, request.lease, session);
|
|
279
|
+
const staged = await staging.findOne({ _id: request.commitId }, { session });
|
|
280
|
+
const batch = decode(staged);
|
|
281
|
+
if (!batch ||
|
|
282
|
+
batch.threadId !== request.threadId ||
|
|
283
|
+
batch.expectedRevision !== request.expectedRevision)
|
|
284
|
+
fail("CommitConflict", "Missing staged batch");
|
|
285
|
+
const messages = (await pieces
|
|
286
|
+
.find({ commitId: batch.commitId, kind: "messages" }, { session })
|
|
287
|
+
.sort({ position: 1 })
|
|
288
|
+
.toArray()).map((row) => decode(row));
|
|
289
|
+
const records = (await pieces
|
|
290
|
+
.find({ commitId: batch.commitId, kind: "records" }, { session })
|
|
291
|
+
.sort({ position: 1 })
|
|
292
|
+
.toArray()).map((row) => decode(row));
|
|
293
|
+
const cp = {
|
|
294
|
+
...batch.checkpoint,
|
|
295
|
+
state: { ...batch.checkpoint.state, messages },
|
|
296
|
+
};
|
|
297
|
+
if (batch.lineage) {
|
|
298
|
+
await touchThread(leases, batch.lineage.parentThreadId, session);
|
|
299
|
+
const parent = await head(batch.lineage.parentThreadId, session);
|
|
300
|
+
const source = await cpRow(batch.lineage.sourceCheckpointId, session);
|
|
301
|
+
if (!parent || parent.deleted || source?.threadId !== parent.id)
|
|
302
|
+
fail("ThreadNotFound", "Fork source is no longer available");
|
|
303
|
+
}
|
|
304
|
+
const old = await head(batch.threadId, session);
|
|
305
|
+
if ((old?.revision ?? 0) !== batch.expectedRevision ||
|
|
306
|
+
old?.deleted ||
|
|
307
|
+
cp.parentCheckpointId !== (old?.currentCheckpointId ?? null))
|
|
308
|
+
fail("CommitConflict", "Head changed");
|
|
309
|
+
if (await cpRow(cp.id, session))
|
|
310
|
+
fail("CommitConflict", "Checkpoint ID already exists");
|
|
311
|
+
const merged = new Map();
|
|
312
|
+
for (const entry of records)
|
|
313
|
+
merged.set(key(entry.kind, entry.id), entry);
|
|
314
|
+
async function record(kind, id) {
|
|
315
|
+
const entry = merged.get(key(kind, id));
|
|
316
|
+
return entry
|
|
317
|
+
? entry.data
|
|
318
|
+
: decode(await versions.findOne({ threadId: batch.threadId, kind, id, toRevision: null }, { session }));
|
|
319
|
+
}
|
|
320
|
+
const stream = cp.execution
|
|
321
|
+
? await record("streams", cp.execution.streamId)
|
|
322
|
+
: null;
|
|
323
|
+
if (cp.execution && !stream)
|
|
324
|
+
fail("CommitConflict", "Missing stream reference");
|
|
325
|
+
if (cp.execution?.pendingInterruptId &&
|
|
326
|
+
!(await record("interrupts", cp.execution.pendingInterruptId)))
|
|
327
|
+
fail("CommitConflict", "Missing interrupt reference");
|
|
328
|
+
await writeCheckpoint(checkpoints, versions, cp, session);
|
|
329
|
+
for (const kind of kinds)
|
|
330
|
+
await writeVersions(versions, kind, cp.threadId, cp.revision, [...merged.values()]
|
|
331
|
+
.filter((entry) => entry.kind === kind)
|
|
332
|
+
.map((entry) => ({
|
|
333
|
+
id: entry.id,
|
|
334
|
+
body: canonicalJson(entry.data),
|
|
335
|
+
})), session);
|
|
336
|
+
const info = buildThreadInfo({ ...batch, checkpoint: cp, records }, old, stream);
|
|
337
|
+
await threads.replaceOne({ _id: info.id }, {
|
|
338
|
+
_id: info.id,
|
|
339
|
+
id: info.id,
|
|
340
|
+
deleted: info.deleted,
|
|
341
|
+
scopeTokens: scopeTokens(info.scope),
|
|
342
|
+
sortDate: info.createdAt,
|
|
343
|
+
parentThreadId: info.parentThreadId,
|
|
344
|
+
sourceCheckpointId: info.sourceCheckpointId,
|
|
345
|
+
body: canonicalJson(info),
|
|
346
|
+
}, { session, upsert: true });
|
|
347
|
+
if (info.deleted)
|
|
348
|
+
for await (const row of sessions.find({ selectedThreadId: info.id }, { session })) {
|
|
349
|
+
const value = decode(row);
|
|
350
|
+
const next = {
|
|
351
|
+
...value,
|
|
352
|
+
selectedThreadId: null,
|
|
353
|
+
revision: value.revision + 1,
|
|
354
|
+
updatedAt: cp.createdAt,
|
|
355
|
+
};
|
|
356
|
+
await sessions.updateOne({ _id: row._id }, { $set: { selectedThreadId: null, body: canonicalJson(next) } }, { session });
|
|
357
|
+
}
|
|
358
|
+
const receipt = {
|
|
359
|
+
commitId: batch.commitId,
|
|
360
|
+
threadId: cp.threadId,
|
|
361
|
+
revision: cp.revision,
|
|
362
|
+
checkpointId: cp.id,
|
|
363
|
+
};
|
|
364
|
+
await commits.insertOne({
|
|
365
|
+
_id: batch.commitId,
|
|
366
|
+
threadId: cp.threadId,
|
|
367
|
+
fingerprint: staged.fingerprint,
|
|
368
|
+
body: canonicalJson(receipt),
|
|
369
|
+
}, { session });
|
|
370
|
+
await staging.deleteOne({ _id: batch.commitId }, { session });
|
|
371
|
+
await pieces.deleteMany({ commitId: batch.commitId }, { session });
|
|
372
|
+
await assertOwnership(leases, request.lease, session);
|
|
373
|
+
return receipt;
|
|
374
|
+
});
|
|
375
|
+
},
|
|
376
|
+
},
|
|
377
|
+
close: db.close,
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
//# sourceMappingURL=backend.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"backend.js","sourceRoot":"","sources":["../src/backend.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAA8B,MAAM,eAAe,CAAC;AACzE,OAAO,EACL,YAAY,EACZ,WAAW,EACX,eAAe,EACf,eAAe,GAChB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,QAAQ,EACR,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,eAAe,GAChB,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,eAAe,EACf,aAAa,EAC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AQ,EAAE,EAAE,CAAC,QAAQ;wBACrB,WAAW,EAAE,MAAO,CAAC,WAAW;wBAChC,IAAI,EAAE,aAAa,CAAC,OAAO,CAAC;qBAC7B,EACD,EAAE,OAAO,EAAE,CACZ,CAAC;oBACF,MAAM,OAAO,CAAC,SAAS,CAAC,EAAE,GAAG,EAAE,KAAK,CAAC,QAAQ,EAAE,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;oBAC9D,MAAM,MAAM,CAAC,UAAU,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,QAAQ,EAAE,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;oBACnE,MAAM,eAAe,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;oBACtD,OAAO,OAAO,CAAC;gBACjB,CAAC,CAAC,CAAC;YACL,CAAC;SACF;QACD,KAAK,EAAE,EAAE,CAAC,KAAK;KAChB,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type MongoClientOptions, type ClientSession } from "mongodb";
|
|
2
|
+
export interface MongoDBStorageOptions {
|
|
3
|
+
uri: string;
|
|
4
|
+
databaseName: string;
|
|
5
|
+
clientOptions?: MongoClientOptions;
|
|
6
|
+
}
|
|
7
|
+
export declare function openDatabase(options: MongoDBStorageOptions): Promise<{
|
|
8
|
+
threads: import("mongodb").Collection<import("./queries.js").Row>;
|
|
9
|
+
checkpoints: import("mongodb").Collection<import("./queries.js").Row>;
|
|
10
|
+
versions: import("mongodb").Collection<import("./queries.js").Row>;
|
|
11
|
+
sessions: import("mongodb").Collection<import("./queries.js").Row>;
|
|
12
|
+
owned: import("mongodb").Collection<import("./queries.js").Row>;
|
|
13
|
+
leases: import("mongodb").Collection<import("./queries.js").Row>;
|
|
14
|
+
commits: import("mongodb").Collection<import("./queries.js").Row>;
|
|
15
|
+
staging: import("mongodb").Collection<import("./queries.js").Row>;
|
|
16
|
+
pieces: import("mongodb").Collection<import("./queries.js").Row>;
|
|
17
|
+
transaction: <T>(action: (session: ClientSession) => Promise<T>) => Promise<T>;
|
|
18
|
+
close: () => Promise<void>;
|
|
19
|
+
}>;
|
package/dist/database.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { MongoClient, MongoServerError, } from "mongodb";
|
|
2
|
+
import { fail } from "@tessar/core";
|
|
3
|
+
import { initializeSchema } from "./schema.js";
|
|
4
|
+
export async function openDatabase(options) {
|
|
5
|
+
if (!options.databaseName)
|
|
6
|
+
fail("InvalidConfiguration", "MongoDB databaseName is required");
|
|
7
|
+
const client = new MongoClient(options.uri, options.clientOptions);
|
|
8
|
+
let closePromise;
|
|
9
|
+
const close = () => (closePromise ??= client.close());
|
|
10
|
+
try {
|
|
11
|
+
await client.connect();
|
|
12
|
+
const collections = await initializeSchema(client.db(options.databaseName));
|
|
13
|
+
async function transaction(action) {
|
|
14
|
+
const session = client.startSession();
|
|
15
|
+
try {
|
|
16
|
+
return (await session.withTransaction(() => action(session), {
|
|
17
|
+
readConcern: { level: "snapshot" },
|
|
18
|
+
writeConcern: { w: "majority" },
|
|
19
|
+
readPreference: "primary",
|
|
20
|
+
}));
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
if (error instanceof MongoServerError && error.code === 11000)
|
|
24
|
+
fail("CommitConflict", "Storage identity or revision already exists");
|
|
25
|
+
throw error;
|
|
26
|
+
}
|
|
27
|
+
finally {
|
|
28
|
+
await session.endSession();
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return { ...collections, transaction, close };
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
await close().catch(() => { });
|
|
35
|
+
throw error;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=database.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"database.js","sourceRoot":"","sources":["../src/database.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,gBA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T,MAAM,OAAO,CAAC,UAAU,EAAE,CAAC;YAC7B,CAAC;QACH,CAAC;QAED,OAAO,EAAE,GAAG,WAAW,EAAE,WAAW,EAAE,KAAK,EAAE,CAAC;IAChD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QAC9B,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export * from "./backend.js";
|
|
2
|
+
import type { Plugin, PluginContext } from "@tessar/core";
|
|
3
|
+
import { type MongoDBStorageOptions } from "./backend.js";
|
|
4
|
+
export declare class MongoDBStoragePlugin implements Plugin {
|
|
5
|
+
private readonly options;
|
|
6
|
+
readonly id = "storage.mongodb";
|
|
7
|
+
constructor(options: MongoDBStorageOptions);
|
|
8
|
+
setup(tessar: PluginContext): Promise<void>;
|
|
9
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export * from "./backend.js";
|
|
2
|
+
import { createMongoDBBackend } from "./backend.js";
|
|
3
|
+
export class MongoDBStoragePlugin {
|
|
4
|
+
options;
|
|
5
|
+
id = "storage.mongodb";
|
|
6
|
+
constructor(options) {
|
|
7
|
+
this.options = options;
|
|
8
|
+
}
|
|
9
|
+
async setup(tessar) {
|
|
10
|
+
const backend = await createMongoDBBackend(this.options);
|
|
11
|
+
try {
|
|
12
|
+
tessar.storage.register(backend);
|
|
13
|
+
}
|
|
14
|
+
catch (error) {
|
|
15
|
+
await backend.close().catch(() => { });
|
|
16
|
+
throw error;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,cAAc,CAAC;AAE7B,OAAO,EAAE,oBAAoB,EAA8B,MAAM,cAAc,CAAC;AAEhF,MAAM,OAAO,oBAAoB;IAEF,OAAO;IAD3B,EAAE,GAAG,iBAAiB,CAAC;IAChC,YAA6B,OAA8B;uBAA9B,OAAO;IAA0B,CAAC;IAC/D,KAAK,CAAC,KAAK,CAAC,MAAqB;QAC/B,MAAM,OAAO,GAAG,MAAM,oBAAoB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACzD,IAAI,CAAC;YACH,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;QACnC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;YACtC,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;CACF"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type Collection, type ClientSession } from "mongodb";
|
|
2
|
+
import { type Lease, type OwnershipPort } from "@tessar/core";
|
|
3
|
+
import type { Row } from "./queries.js";
|
|
4
|
+
export declare function ensureThread(leases: Collection<Row>, id: string): Promise<void>;
|
|
5
|
+
export declare function touchThread(leases: Collection<Row>, id: string, session: ClientSession): Promise<void>;
|
|
6
|
+
export declare function assertOwnership(leases: Collection<Row>, lease: Lease, session: ClientSession): Promise<void>;
|
|
7
|
+
export declare function createOwnership(leases: Collection<Row>): OwnershipPort;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { MongoServerError, } from "mongodb";
|
|
2
|
+
import { fail, immutable } from "@tessar/core";
|
|
3
|
+
const duration = (ttlMs) => {
|
|
4
|
+
if (!Number.isFinite(ttlMs) || ttlMs <= 0)
|
|
5
|
+
fail("InvalidConfiguration", "Invalid lease duration");
|
|
6
|
+
};
|
|
7
|
+
const toLease = (row) => ({
|
|
8
|
+
threadId: row._id,
|
|
9
|
+
ownerToken: row.ownerToken,
|
|
10
|
+
fencingToken: row.fencingToken,
|
|
11
|
+
expiresAt: row.expiresAt.toISOString(),
|
|
12
|
+
});
|
|
13
|
+
const liveLease = (lease) => ({
|
|
14
|
+
_id: lease.threadId,
|
|
15
|
+
ownerToken: lease.ownerToken,
|
|
16
|
+
fencingToken: lease.fencingToken,
|
|
17
|
+
$expr: { $gt: ["$expiresAt", "$$NOW"] },
|
|
18
|
+
});
|
|
19
|
+
export async function ensureThread(leases, id) {
|
|
20
|
+
try {
|
|
21
|
+
await leases.updateOne({ _id: id }, {
|
|
22
|
+
$setOnInsert: {
|
|
23
|
+
fencingToken: 0,
|
|
24
|
+
ownerToken: "",
|
|
25
|
+
expiresAt: new Date(0),
|
|
26
|
+
serial: 0,
|
|
27
|
+
body: "{}",
|
|
28
|
+
},
|
|
29
|
+
}, { upsert: true });
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
if (!(error instanceof MongoServerError && error.code === 11000))
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export async function touchThread(leases, id, session) {
|
|
37
|
+
await leases.updateOne({ _id: id }, { $inc: { serial: 1 } }, { session });
|
|
38
|
+
}
|
|
39
|
+
export async function assertOwnership(leases, lease, session) {
|
|
40
|
+
const result = await leases.updateOne(liveLease(lease), { $inc: { serial: 1 } }, { session });
|
|
41
|
+
if (!result.matchedCount)
|
|
42
|
+
fail("OwnershipLost", "Lease no longer owns thread");
|
|
43
|
+
}
|
|
44
|
+
export function createOwnership(leases) {
|
|
45
|
+
return {
|
|
46
|
+
acquire: async (request) => {
|
|
47
|
+
request = immutable(request);
|
|
48
|
+
duration(request.ttlMs);
|
|
49
|
+
await ensureThread(leases, request.threadId);
|
|
50
|
+
const row = await leases.findOneAndUpdate({ _id: request.threadId, $expr: { $lte: ["$expiresAt", "$$NOW"] } }, [
|
|
51
|
+
{
|
|
52
|
+
$set: {
|
|
53
|
+
ownerToken: { $literal: request.ownerToken },
|
|
54
|
+
fencingToken: { $add: ["$fencingToken", 1] },
|
|
55
|
+
serial: { $add: ["$serial", 1] },
|
|
56
|
+
expiresAt: { $add: ["$$NOW", request.ttlMs] },
|
|
57
|
+
},
|
|
58
|
+
},
|
|
59
|
+
], { returnDocument: "after" });
|
|
60
|
+
if (!row)
|
|
61
|
+
fail("OwnerActive", "Thread has active owner");
|
|
62
|
+
return toLease(row);
|
|
63
|
+
},
|
|
64
|
+
renew: async (lease, ttlMs) => {
|
|
65
|
+
lease = immutable(lease);
|
|
66
|
+
duration(ttlMs);
|
|
67
|
+
const row = await leases.findOneAndUpdate(liveLease(lease), [
|
|
68
|
+
{
|
|
69
|
+
$set: {
|
|
70
|
+
serial: { $add: ["$serial", 1] },
|
|
71
|
+
expiresAt: { $add: ["$$NOW", ttlMs] },
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
], { returnDocument: "after" });
|
|
75
|
+
if (!row)
|
|
76
|
+
fail("OwnershipLost", "Lease no longer owns thread");
|
|
77
|
+
return toLease(row);
|
|
78
|
+
},
|
|
79
|
+
release: async (lease) => {
|
|
80
|
+
lease = immutable(lease);
|
|
81
|
+
await leases.updateOne({
|
|
82
|
+
_id: lease.threadId,
|
|
83
|
+
ownerToken: lease.ownerToken,
|
|
84
|
+
fencingToken: lease.fencingToken,
|
|
85
|
+
}, { $set: { expiresAt: new Date(0) }, $inc: { serial: 1 } });
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
//# sourceMappingURL=ownership.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ownership.js","sourceRoot":"","sources":["../src/ownership.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,GAIjB,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,IAAI,EAAE,SAAS,EAAkC,MAAM,cAAc,CAAC;AAG/E,MAAM,QAAQ,GAAG,CAAC,KAAa,EAAE,EAAE;IACjC,IAAI,CAAC,MAAM,CAAC,QAAQ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AAE,CAC1D,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { ClientSession, Collection, Document, Filter } from "mongodb";
|
|
2
|
+
import { type Page, type PageOptions, type Scope } from "@tessar/core";
|
|
3
|
+
export type Row = Document & {
|
|
4
|
+
_id: string;
|
|
5
|
+
body: string;
|
|
6
|
+
};
|
|
7
|
+
export declare const decode: <T>(row: Row | null) => T | null;
|
|
8
|
+
export declare function scopeTokens(scope?: Scope): string[];
|
|
9
|
+
export declare function scopeFilter(scope?: Scope): Filter<Row>;
|
|
10
|
+
export declare function mongoPage<T>(collection: Collection<Row>, filter: Filter<Row>, options: PageOptions, binding: string, session?: ClientSession, map?: (row: Row) => T): Promise<Page<T>>;
|
package/dist/queries.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { canonicalJson, encodeCursor, immutable, limitOf, normalizeScope, pageAfter, } from "@tessar/core";
|
|
2
|
+
export const decode = (row) => row ? immutable(JSON.parse(row.body)) : null;
|
|
3
|
+
export function scopeTokens(scope = {}) {
|
|
4
|
+
normalizeScope(scope);
|
|
5
|
+
return Object.entries(scope).map(([key, value]) => canonicalJson([key, value]));
|
|
6
|
+
}
|
|
7
|
+
export function scopeFilter(scope) {
|
|
8
|
+
const tokens = scopeTokens(scope);
|
|
9
|
+
return tokens.length ? { scopeTokens: { $all: tokens } } : {};
|
|
10
|
+
}
|
|
11
|
+
export async function mongoPage(collection, filter, options, binding, session, map = (row) => decode(row)) {
|
|
12
|
+
const after = pageAfter(options, binding), limit = limitOf(options.limit);
|
|
13
|
+
const pageFilter = after
|
|
14
|
+
? {
|
|
15
|
+
$and: [
|
|
16
|
+
filter,
|
|
17
|
+
{
|
|
18
|
+
$or: [
|
|
19
|
+
{ sortDate: { $gt: after[0] } },
|
|
20
|
+
{ sortDate: after[0], id: { $gt: after[1] } },
|
|
21
|
+
],
|
|
22
|
+
},
|
|
23
|
+
],
|
|
24
|
+
}
|
|
25
|
+
: filter;
|
|
26
|
+
const rows = await collection
|
|
27
|
+
.find(pageFilter, { session, collation: { locale: "simple" } })
|
|
28
|
+
.sort({ sortDate: 1, id: 1 })
|
|
29
|
+
.limit(limit + 1)
|
|
30
|
+
.toArray();
|
|
31
|
+
const selected = rows.slice(0, limit), last = selected.at(-1);
|
|
32
|
+
return {
|
|
33
|
+
items: selected.map(map),
|
|
34
|
+
nextCursor: rows.length > limit
|
|
35
|
+
? encodeCursor({ v: 2, binding, after: [last.sortDate, last.id] })
|
|
36
|
+
: null,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=queries.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"queries.js","sourceRoot":"","sources":["../src/queries.ts"],"names":[],"mappings":"AACA,OAAO,EACL,aAAa,EACb,YAAY,EACZ,SAAS,EACT,OAAO,EACP,cAAc,EACd,SAAS,GAIV,MAAM,cAAc,CAAC;AAItB,MAAM,CAAC,MAAM,MAAM,GAAG,CAAI,GAAe,EAAY,EAAE,CACrD,GAAG,CAAC,CAAC,CAAE,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAO,CAAC,CAAC,CAAC,IAAI,CAAC;AACtD,MAAM,UAAU,WAAW,CAAC,KAAK,GAAU,EAAE;IAC3C,cAAc,CAAC,KAAK,CAAC,CAAC;IACtB,OAAO,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAChD,aAAa,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAC5B,CAAC;AACJ,CAAC;AACD,MAAM,UAAU,WAAW,CAAC,KAAa;IACvC,MAAM,MAAM,GAAG,WAAW,CAAC,KAAK,CAAC,CAAC;IAClC,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,EAA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U,EACR,IAAI,CAAC,MAAM,GAAG,KAAK;YACjB,CAAC,CAAC,YAAY,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,IAAK,CAAC,QAAQ,EAAE,IAAK,CAAC,EAAE,CAAC,EAAE,CAAC;YACpE,CAAC,CAAC,IAAI;KACX,CAAC;AACJ,CAAC"}
|
package/dist/schema.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type Db } from "mongodb";
|
|
2
|
+
import type { Row } from "./queries.js";
|
|
3
|
+
export declare function initializeSchema(db: Db): Promise<{
|
|
4
|
+
threads: import("mongodb").Collection<Row>;
|
|
5
|
+
checkpoints: import("mongodb").Collection<Row>;
|
|
6
|
+
versions: import("mongodb").Collection<Row>;
|
|
7
|
+
sessions: import("mongodb").Collection<Row>;
|
|
8
|
+
owned: import("mongodb").Collection<Row>;
|
|
9
|
+
leases: import("mongodb").Collection<Row>;
|
|
10
|
+
commits: import("mongodb").Collection<Row>;
|
|
11
|
+
staging: import("mongodb").Collection<Row>;
|
|
12
|
+
pieces: import("mongodb").Collection<Row>;
|
|
13
|
+
}>;
|
package/dist/schema.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { MongoServerError } from "mongodb";
|
|
2
|
+
import { fail } from "@tessar/core";
|
|
3
|
+
export async function initializeSchema(db) {
|
|
4
|
+
const hello = await db.command({ hello: 1 });
|
|
5
|
+
if (!hello.setName && hello.msg !== "isdbgrid")
|
|
6
|
+
fail("InvalidConfiguration", "MongoDB storage requires a replica set or sharded deployment supporting transactions");
|
|
7
|
+
const metadata = db.collection("tessar_schema");
|
|
8
|
+
const previous = await metadata.findOne({ _id: "schema" });
|
|
9
|
+
if (previous && previous.version !== 1)
|
|
10
|
+
fail("InvalidConfiguration", "Unsupported MongoDB schema version");
|
|
11
|
+
const threads = db.collection("tessar_threads"), checkpoints = db.collection("tessar_checkpoints"), versions = db.collection("tessar_versions"), sessions = db.collection("tessar_sessions"), owned = db.collection("tessar_owned_states"), leases = db.collection("tessar_leases"), commits = db.collection("tessar_commits"), staging = db.collection("tessar_staging"), pieces = db.collection("tessar_staging_pieces");
|
|
12
|
+
// Create every collection before entering transactions (including otherwise unindexed ones).
|
|
13
|
+
for (const collection of [
|
|
14
|
+
threads,
|
|
15
|
+
checkpoints,
|
|
16
|
+
versions,
|
|
17
|
+
sessions,
|
|
18
|
+
owned,
|
|
19
|
+
leases,
|
|
20
|
+
commits,
|
|
21
|
+
staging,
|
|
22
|
+
pieces,
|
|
23
|
+
]) {
|
|
24
|
+
try {
|
|
25
|
+
await db.createCollection(collection.collectionName);
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
if (!(error instanceof MongoServerError && error.code === 48))
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
await threads.createIndex({ deleted: 1, sortDate: 1, id: 1 });
|
|
33
|
+
await threads.createIndex({
|
|
34
|
+
scopeTokens: 1,
|
|
35
|
+
deleted: 1,
|
|
36
|
+
sortDate: 1,
|
|
37
|
+
id: 1,
|
|
38
|
+
});
|
|
39
|
+
await threads.createIndex({ parentThreadId: 1 });
|
|
40
|
+
await threads.createIndex({ sourceCheckpointId: 1 });
|
|
41
|
+
await checkpoints.createIndex({ threadId: 1, revision: 1 }, { unique: true });
|
|
42
|
+
await checkpoints.createIndex({ threadId: 1, sortDate: 1, id: 1 });
|
|
43
|
+
await versions.createIndex({ threadId: 1, kind: 1, id: 1, fromRevision: 1 }, { unique: true });
|
|
44
|
+
await versions.createIndex({
|
|
45
|
+
threadId: 1,
|
|
46
|
+
kind: 1,
|
|
47
|
+
toRevision: 1,
|
|
48
|
+
position: 1,
|
|
49
|
+
});
|
|
50
|
+
await versions.createIndex({ threadId: 1, kind: 1, sortDate: 1, id: 1 });
|
|
51
|
+
await versions.createIndex({ kind: 1, id: 1, toRevision: 1 });
|
|
52
|
+
await sessions.createIndex({
|
|
53
|
+
agentId: 1,
|
|
54
|
+
scopeTokens: 1,
|
|
55
|
+
sortDate: 1,
|
|
56
|
+
id: 1,
|
|
57
|
+
});
|
|
58
|
+
await sessions.createIndex({ selectedThreadId: 1 });
|
|
59
|
+
await commits.createIndex({ threadId: 1 });
|
|
60
|
+
await staging.createIndex({ threadId: 1 });
|
|
61
|
+
await pieces.createIndex({ commitId: 1, kind: 1, position: 1 });
|
|
62
|
+
await pieces.createIndex({ threadId: 1 });
|
|
63
|
+
await metadata.updateOne({ _id: "schema" }, { $setOnInsert: { version: 1 } }, { upsert: true });
|
|
64
|
+
const current = await metadata.findOne({ _id: "schema" });
|
|
65
|
+
if (current?.version !== 1)
|
|
66
|
+
fail("InvalidConfiguration", "Unsupported MongoDB schema version");
|
|
67
|
+
return {
|
|
68
|
+
threads,
|
|
69
|
+
checkpoints,
|
|
70
|
+
versions,
|
|
71
|
+
sessions,
|
|
72
|
+
owned,
|
|
73
|
+
leases,
|
|
74
|
+
commits,
|
|
75
|
+
staging,
|
|
76
|
+
pieces,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
//# sourceMappingURL=schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.js","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAW,MAAM,SAAS,CAAC;AACpD,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAGpC,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,EAAM;IAC3C,MAAM,KAAK,GAAG,MAAM,EAAE,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;IAC7C,IAAI,CAAC,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,GAAG,KAAK,UAAU;QAC5C,IAAI,CACF,sBAAsB,EACtB,sFAAsF,CACvF,CAAC;IACJ,MAAM,QAAQ,GAAG,EAAE,CAAC,UAAU,CAC5B,eAAe,CAChB,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";
|
|
3
|
+
import { type Row } from "./queries.js";
|
|
4
|
+
export declare const interval: (threadId: string, kind: string, revision: number) => Filter<Row>;
|
|
5
|
+
export declare function readVersions<T>(versions: Collection<Row>, kind: string, threadId: string, revision: number, session: ClientSession): Promise<T[]>;
|
|
6
|
+
export declare function hydrateCheckpoint(versions: Collection<Row>, row: Row, session: ClientSession): Promise<Checkpoint>;
|
|
7
|
+
export declare function writeVersions(versions: Collection<Row>, kind: string, threadId: string, revision: number, entries: readonly {
|
|
8
|
+
id: string;
|
|
9
|
+
body: string;
|
|
10
|
+
position?: number;
|
|
11
|
+
}[], session: ClientSession, replace?: boolean): Promise<void>;
|
|
12
|
+
export declare function writeCheckpoint(checkpoints: Collection<Row>, versions: Collection<Row>, cp: Checkpoint, session: ClientSession): Promise<void>;
|
package/dist/versions.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { canonicalJson, immutable, checkpointSafety, } from "@tessar/core";
|
|
2
|
+
import { decode } from "./queries.js";
|
|
3
|
+
export const interval = (threadId, kind, revision) => ({
|
|
4
|
+
threadId,
|
|
5
|
+
kind,
|
|
6
|
+
fromRevision: { $lte: revision },
|
|
7
|
+
$or: [{ toRevision: null }, { toRevision: { $gt: revision } }],
|
|
8
|
+
});
|
|
9
|
+
export async function readVersions(versions, kind, threadId, revision, session) {
|
|
10
|
+
return (await versions
|
|
11
|
+
.find(interval(threadId, kind, revision), { session })
|
|
12
|
+
.sort(kind === "messages" ? { position: 1 } : { sortDate: 1, id: 1 })
|
|
13
|
+
.toArray()).map((row) => decode(row));
|
|
14
|
+
}
|
|
15
|
+
export async function hydrateCheckpoint(versions, row, session) {
|
|
16
|
+
const cp = decode(row);
|
|
17
|
+
return immutable({
|
|
18
|
+
...cp,
|
|
19
|
+
state: {
|
|
20
|
+
...cp.state,
|
|
21
|
+
messages: await readVersions(versions, "messages", cp.threadId, cp.revision, session),
|
|
22
|
+
},
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
export async function writeVersions(versions, kind, threadId, revision, entries, session, replace = false) {
|
|
26
|
+
const current = new Map((await versions
|
|
27
|
+
.find({ threadId, kind, toRevision: null }, { session })
|
|
28
|
+
.toArray()).map((row) => [row.id, row]));
|
|
29
|
+
for (const entry of entries) {
|
|
30
|
+
const old = current.get(entry.id);
|
|
31
|
+
current.delete(entry.id);
|
|
32
|
+
if (old?.body === entry.body && old.position === (entry.position ?? null))
|
|
33
|
+
continue;
|
|
34
|
+
if (old)
|
|
35
|
+
await versions.updateOne({ _id: old._id }, { $set: { toRevision: revision } }, { session });
|
|
36
|
+
const value = JSON.parse(entry.body);
|
|
37
|
+
await versions.insertOne({
|
|
38
|
+
_id: canonicalJson([threadId, kind, entry.id, revision]),
|
|
39
|
+
threadId,
|
|
40
|
+
kind,
|
|
41
|
+
id: entry.id,
|
|
42
|
+
fromRevision: revision,
|
|
43
|
+
toRevision: null,
|
|
44
|
+
position: entry.position ?? null,
|
|
45
|
+
streamId: value.streamId ?? null,
|
|
46
|
+
turnId: value.turnId ?? null,
|
|
47
|
+
status: value.status ?? null,
|
|
48
|
+
sortDate: value.createdAt ?? value.startedAt ?? "",
|
|
49
|
+
body: entry.body,
|
|
50
|
+
}, { session });
|
|
51
|
+
}
|
|
52
|
+
if (replace)
|
|
53
|
+
for (const row of current.values())
|
|
54
|
+
await versions.updateOne({ _id: row._id }, { $set: { toRevision: revision } }, { session });
|
|
55
|
+
}
|
|
56
|
+
export async function writeCheckpoint(checkpoints, versions, cp, session) {
|
|
57
|
+
await writeVersions(versions, "messages", cp.threadId, cp.revision, cp.state.messages.map((message, position) => ({
|
|
58
|
+
id: message.id,
|
|
59
|
+
position,
|
|
60
|
+
body: canonicalJson(message),
|
|
61
|
+
})), session, true);
|
|
62
|
+
const { messages, ...state } = cp.state;
|
|
63
|
+
await checkpoints.insertOne({
|
|
64
|
+
_id: cp.id,
|
|
65
|
+
id: cp.id,
|
|
66
|
+
threadId: cp.threadId,
|
|
67
|
+
revision: cp.revision,
|
|
68
|
+
sortDate: cp.createdAt,
|
|
69
|
+
cause: cp.cause,
|
|
70
|
+
messageCount: messages.length,
|
|
71
|
+
...checkpointSafety(cp),
|
|
72
|
+
body: canonicalJson({ ...cp, state }),
|
|
73
|
+
}, { session });
|
|
74
|
+
}
|
|
75
|
+
//# sourceMappingURL=versions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"versions.js","sourceRoot":"","sources":["../src/versions.ts"],"names":[],"mappings":"AACA,OAAO,EACL,aAAa,EACb,SAAS,EACT,gBAAgB,GAGjB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,MAAM,EAAY,MAAM,cAAc,CAAC;AAEhD,MAAM,CAAC,MAAM,QAAQ,GAAG,CACtB,QAAgB,EAChB,IAAY,EACZ,QAAgB,EACH,EAAE,CAAC,CAAC;IACjB,QAAQ;IACR,IAAI;IACJ,YAAY,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;IAChC,GAAG,EAAE,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,EAAE,EAAE,UAAU,EAAE,EAAE,GAAG,EAAE,QAAQ,EAAE,EAAE,CAAC;CAC/D,CAAC,CAAC;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,QAAyB,EACzB,IAAY,EACZ,QAAgB,EAChB,QAAgB,EAChB,OAAsB;IAEtB,OAAO,CACL,MAAM,QAAQ;SACX,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,EAAE,QAAQ,CAAC,EAAE,EAAE,OAAO,EAAE,CAAC;SACrD,IAAI,CAAC,IAAI,KAAK,UAAU,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC;SACpE,OAAO,EAAE,CACb,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,MAAM,CAAI,GAAG,CAAE,CAAC,CA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X,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,QAAQ,EAAE,EAAE,CAAC,CAAC;QAC5C,EAAE,EAAE,OAAO,CAAC,EAAE;QACd,QAAQ;QACR,IAAI,EAAE,aAAa,CAAC,OAAO,CAAC;KAC7B,CAAC,CAAC,EACH,OAAO,EACP,IAAI,CACL,CAAC;IACF,MAAM,EAAE,QAAQ,EAAE,GAAG,KAAK,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC;IACxC,MAAM,WAAW,CAAC,SAAS,CACzB;QACE,GAAG,EAAE,EAAE,CAAC,EAAE;QACV,EAAE,EAAE,EAAE,CAAC,EAAE;QACT,QAAQ,EAAE,EAAE,CAAC,QAAQ;QACrB,QAAQ,EAAE,EAAE,CAAC,QAAQ;QACrB,QAAQ,EAAE,EAAE,CAAC,SAAS;QACtB,KAAK,EAAE,EAAE,CAAC,KAAK;QACf,YAAY,EAAE,QAAQ,CAAC,MAAM;QAC7B,GAAG,gBAAgB,CAAC,EAAE,CAAC;QACvB,IAAI,EAAE,aAAa,CAAC,EAAE,GAAG,EAAE,EAAE,KAAK,EAAE,CAAC;KACtC,EACD,EAAE,OAAO,EAAE,CACZ,CAAC;AACJ,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tessar/mongodb",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"description": "Transactional MongoDB persistence for Tessar state and checkpoints.",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"tessar",
|
|
8
|
+
"ai-agent",
|
|
9
|
+
"mongodb",
|
|
10
|
+
"storage",
|
|
11
|
+
"persistence",
|
|
12
|
+
"checkpoints",
|
|
13
|
+
"typescript"
|
|
14
|
+
],
|
|
15
|
+
"type": "module",
|
|
16
|
+
"files": [
|
|
17
|
+
"dist"
|
|
18
|
+
],
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">=24.14.0"
|
|
21
|
+
},
|
|
22
|
+
"repository": {
|
|
23
|
+
"type": "git",
|
|
24
|
+
"url": "git+https://github.com/tessar-ai/tessar.git",
|
|
25
|
+
"directory": "packages/mongodb"
|
|
26
|
+
},
|
|
27
|
+
"publishConfig": {
|
|
28
|
+
"access": "public",
|
|
29
|
+
"registry": "https://registry.npmjs.org/"
|
|
30
|
+
},
|
|
31
|
+
"exports": {
|
|
32
|
+
".": {
|
|
33
|
+
"types": "./dist/index.d.ts",
|
|
34
|
+
"import": "./dist/index.js"
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"mongodb": "^6.21.0",
|
|
39
|
+
"@tessar/core": "0.1.1"
|
|
40
|
+
},
|
|
41
|
+
"scripts": {
|
|
42
|
+
"build": "tsc -p tsconfig.json",
|
|
43
|
+
"typecheck": "tsc --noEmit -p tsconfig.json"
|
|
44
|
+
}
|
|
6
45
|
}
|