@openma/matter-store-mysql 0.0.0-stage → 0.2.5
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/dist/index.d.ts +19 -0
- package/dist/index.js +582 -0
- package/dist/index.js.map +1 -0
- package/package.json +36 -3
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for describing the origin of the Work and
|
|
141
|
+
reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Support. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or support.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 Open Managed Agents Contributors
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { Pool } from "mysql2/promise";
|
|
2
|
+
import { OpenMatterStore, StoreError, StoreSnapshot } from "@openma/matter/store";
|
|
3
|
+
import { Effect } from "effect";
|
|
4
|
+
//#region src/index.d.ts
|
|
5
|
+
interface MysqlStore extends OpenMatterStore {
|
|
6
|
+
readonly close: Effect.Effect<void, StoreError>;
|
|
7
|
+
readonly inspect: Effect.Effect<StoreSnapshot, StoreError>;
|
|
8
|
+
readonly inspectScope: (scopeId: string) => Effect.Effect<StoreSnapshot, StoreError>;
|
|
9
|
+
}
|
|
10
|
+
interface MysqlStoreOptions {
|
|
11
|
+
readonly tenantId: string;
|
|
12
|
+
readonly url?: string;
|
|
13
|
+
readonly pool?: Pool;
|
|
14
|
+
}
|
|
15
|
+
/** MySQL adapter for the OpenMatter store port. One instance is bound to one tenant. */
|
|
16
|
+
declare const makeMysqlStore: (options: MysqlStoreOptions) => MysqlStore;
|
|
17
|
+
//#endregion
|
|
18
|
+
export { MysqlStore, MysqlStoreOptions, makeMysqlStore };
|
|
19
|
+
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { createPool } from "mysql2/promise";
|
|
3
|
+
import { JsonValueSchema, ThreadGoalStatusSchema } from "@openma/matter";
|
|
4
|
+
import { ConversationChangedError, StoreError } from "@openma/matter/store";
|
|
5
|
+
import { Effect, Schema } from "effect";
|
|
6
|
+
//#region src/index.ts
|
|
7
|
+
const initialized = /* @__PURE__ */ new WeakSet();
|
|
8
|
+
const schema = [
|
|
9
|
+
`CREATE TABLE IF NOT EXISTS openmatter_store_records (
|
|
10
|
+
tenant_id VARCHAR(191) NOT NULL,
|
|
11
|
+
kind VARCHAR(64) NOT NULL,
|
|
12
|
+
id VARCHAR(191) NOT NULL,
|
|
13
|
+
scope_id VARCHAR(191) NULL,
|
|
14
|
+
parent_id VARCHAR(191) NULL,
|
|
15
|
+
unique_key VARCHAR(191) NULL,
|
|
16
|
+
data LONGTEXT NOT NULL,
|
|
17
|
+
seq BIGINT NOT NULL AUTO_INCREMENT,
|
|
18
|
+
PRIMARY KEY (tenant_id, kind, id),
|
|
19
|
+
UNIQUE KEY openmatter_store_unique (tenant_id, kind, unique_key),
|
|
20
|
+
KEY openmatter_store_scope (tenant_id, kind, scope_id),
|
|
21
|
+
KEY openmatter_store_parent (tenant_id, kind, parent_id),
|
|
22
|
+
KEY openmatter_store_seq (seq)
|
|
23
|
+
)`,
|
|
24
|
+
`CREATE TABLE IF NOT EXISTS openmatter_store_leases (
|
|
25
|
+
tenant_id VARCHAR(191) NOT NULL,
|
|
26
|
+
kind VARCHAR(64) NOT NULL,
|
|
27
|
+
id VARCHAR(191) NOT NULL,
|
|
28
|
+
token VARCHAR(64) NOT NULL,
|
|
29
|
+
owner_id VARCHAR(191) NOT NULL,
|
|
30
|
+
expires_ms BIGINT NOT NULL,
|
|
31
|
+
revision INT NOT NULL,
|
|
32
|
+
attempt INT NOT NULL DEFAULT 0,
|
|
33
|
+
PRIMARY KEY (tenant_id, kind, id)
|
|
34
|
+
)`,
|
|
35
|
+
`CREATE TABLE IF NOT EXISTS openmatter_store_bindings (
|
|
36
|
+
tenant_id VARCHAR(191) NOT NULL,
|
|
37
|
+
binding_key VARCHAR(512) NOT NULL,
|
|
38
|
+
session_id VARCHAR(191) NOT NULL,
|
|
39
|
+
PRIMARY KEY (tenant_id, binding_key)
|
|
40
|
+
)`
|
|
41
|
+
];
|
|
42
|
+
const asNumber = (value) => typeof value === "bigint" ? Number(value) : Number(value);
|
|
43
|
+
/** MySQL adapter for the OpenMatter store port. One instance is bound to one tenant. */
|
|
44
|
+
const makeMysqlStore = (options) => {
|
|
45
|
+
if (!options.tenantId.trim()) throw new StoreError({ message: "MySQL store requires a tenant id" });
|
|
46
|
+
const owned = options.pool === void 0;
|
|
47
|
+
const pool = options.pool ?? createPool(options.url ?? process.env.PROJECT_WORKER_MYSQL_URL ?? "");
|
|
48
|
+
const tenantId = options.tenantId;
|
|
49
|
+
let closed = false;
|
|
50
|
+
let chain = Promise.resolve();
|
|
51
|
+
const fail = (message) => {
|
|
52
|
+
throw new StoreError({ message });
|
|
53
|
+
};
|
|
54
|
+
const exclusive = (body) => {
|
|
55
|
+
const run = chain.then(body, body);
|
|
56
|
+
chain = run.then(() => void 0, () => void 0);
|
|
57
|
+
return run;
|
|
58
|
+
};
|
|
59
|
+
const ensure = async () => {
|
|
60
|
+
if (initialized.has(pool)) return;
|
|
61
|
+
const conn = await pool.getConnection();
|
|
62
|
+
try {
|
|
63
|
+
for (const statement of schema) await conn.query(statement);
|
|
64
|
+
initialized.add(pool);
|
|
65
|
+
} finally {
|
|
66
|
+
conn.release();
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
const encode = (value) => {
|
|
70
|
+
if (!Schema.is(JsonValueSchema)(value)) fail("Store facts must be portable JSON");
|
|
71
|
+
return JSON.stringify(value);
|
|
72
|
+
};
|
|
73
|
+
const query = async (conn, sql, params = []) => {
|
|
74
|
+
const [rows] = await conn.query(sql, params);
|
|
75
|
+
return rows;
|
|
76
|
+
};
|
|
77
|
+
const one = async (conn, sql, params = []) => (await query(conn, sql, params))[0];
|
|
78
|
+
const withTx = async (write, body) => {
|
|
79
|
+
if (closed) fail("MySQL store is closed");
|
|
80
|
+
await ensure();
|
|
81
|
+
const conn = await pool.getConnection();
|
|
82
|
+
try {
|
|
83
|
+
await conn.beginTransaction();
|
|
84
|
+
if (write) await conn.query("SELECT 1 FROM openmatter_store_leases LIMIT 1 FOR UPDATE");
|
|
85
|
+
const result = await body(conn);
|
|
86
|
+
await conn.commit();
|
|
87
|
+
return result;
|
|
88
|
+
} catch (cause) {
|
|
89
|
+
await conn.rollback();
|
|
90
|
+
throw cause;
|
|
91
|
+
} finally {
|
|
92
|
+
conn.release();
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
const op = (body, write = false) => Effect.tryPromise({
|
|
96
|
+
try: () => exclusive(() => withTx(write, body)),
|
|
97
|
+
catch: (cause) => cause instanceof StoreError ? cause : new StoreError({
|
|
98
|
+
message: "MySQL store operation failed",
|
|
99
|
+
cause
|
|
100
|
+
})
|
|
101
|
+
});
|
|
102
|
+
/** As `op`, but a guarded write's ConversationChangedError passes through. */
|
|
103
|
+
const casOp = (body) => op(body, true).pipe(Effect.mapError((error) => error.cause instanceof ConversationChangedError ? error.cause : error));
|
|
104
|
+
const conversationRevision = async (conn, key) => asNumber((await one(conn, "SELECT COUNT(*) AS n FROM openmatter_store_records WHERE tenant_id=? AND kind='conversationEntry' AND parent_id=?", [tenantId, key]))?.n ?? 0);
|
|
105
|
+
const conversationLog = (conn, key) => rows(conn, "conversationEntry", "AND parent_id=?", [key]);
|
|
106
|
+
const clock = async (conn) => asNumber((await one(conn, "SELECT ROUND(UNIX_TIMESTAMP(NOW(3)) * 1000) AS now"))?.now);
|
|
107
|
+
const read = async (conn, sql, params) => {
|
|
108
|
+
const row = await one(conn, sql, params);
|
|
109
|
+
return row ? JSON.parse(row.data) : void 0;
|
|
110
|
+
};
|
|
111
|
+
const get = async (conn, kind, id) => read(conn, "SELECT data FROM openmatter_store_records WHERE tenant_id=? AND kind=? AND id=?", [
|
|
112
|
+
tenantId,
|
|
113
|
+
kind,
|
|
114
|
+
id
|
|
115
|
+
]);
|
|
116
|
+
const rows = async (conn, kind, clause = "", params = []) => (await query(conn, `SELECT data FROM openmatter_store_records WHERE tenant_id=? AND kind=? ${clause} ORDER BY seq`, [
|
|
117
|
+
tenantId,
|
|
118
|
+
kind,
|
|
119
|
+
...params
|
|
120
|
+
])).map((row) => JSON.parse(row.data));
|
|
121
|
+
const put = async (conn, kind, id, value, scope = null, parent = null, key = null) => {
|
|
122
|
+
await conn.query(`INSERT INTO openmatter_store_records (tenant_id, kind, id, scope_id, parent_id, unique_key, data)
|
|
123
|
+
VALUES (?,?,?,?,?,?,?)
|
|
124
|
+
ON DUPLICATE KEY UPDATE data=VALUES(data), scope_id=VALUES(scope_id), parent_id=VALUES(parent_id), unique_key=VALUES(unique_key)`, [
|
|
125
|
+
tenantId,
|
|
126
|
+
kind,
|
|
127
|
+
id,
|
|
128
|
+
scope,
|
|
129
|
+
parent,
|
|
130
|
+
key,
|
|
131
|
+
encode(value)
|
|
132
|
+
]);
|
|
133
|
+
};
|
|
134
|
+
const remove = async (conn, kind, id) => {
|
|
135
|
+
await conn.query("DELETE FROM openmatter_store_records WHERE tenant_id=? AND kind=? AND id=?", [
|
|
136
|
+
tenantId,
|
|
137
|
+
kind,
|
|
138
|
+
id
|
|
139
|
+
]);
|
|
140
|
+
};
|
|
141
|
+
const leaseRow = async (conn, kind, id) => {
|
|
142
|
+
const row = await one(conn, "SELECT token, owner_id, expires_ms, revision FROM openmatter_store_leases WHERE tenant_id=? AND kind=? AND id=?", [
|
|
143
|
+
tenantId,
|
|
144
|
+
kind,
|
|
145
|
+
id
|
|
146
|
+
]);
|
|
147
|
+
return row ? {
|
|
148
|
+
...row,
|
|
149
|
+
expires_ms: asNumber(row.expires_ms),
|
|
150
|
+
revision: asNumber(row.revision)
|
|
151
|
+
} : void 0;
|
|
152
|
+
};
|
|
153
|
+
const asLease = (row) => ({
|
|
154
|
+
token: row.token,
|
|
155
|
+
ownerId: row.owner_id,
|
|
156
|
+
expiresAt: new Date(row.expires_ms).toISOString(),
|
|
157
|
+
revision: row.revision
|
|
158
|
+
});
|
|
159
|
+
const duration = (ms) => {
|
|
160
|
+
if (!Number.isSafeInteger(ms) || ms <= 0) fail("Lease duration must be a positive integer");
|
|
161
|
+
return ms;
|
|
162
|
+
};
|
|
163
|
+
const acquire = async (conn, kind, id, request, attempt = 0) => {
|
|
164
|
+
const row = await leaseRow(conn, kind, id);
|
|
165
|
+
const next = {
|
|
166
|
+
token: randomUUID(),
|
|
167
|
+
owner_id: request.ownerId,
|
|
168
|
+
expires_ms: await clock(conn) + duration(request.durationMs),
|
|
169
|
+
revision: (row?.revision ?? 0) + 1
|
|
170
|
+
};
|
|
171
|
+
await conn.query(`INSERT INTO openmatter_store_leases (tenant_id, kind, id, token, owner_id, expires_ms, revision, attempt)
|
|
172
|
+
VALUES (?,?,?,?,?,?,?,?)
|
|
173
|
+
ON DUPLICATE KEY UPDATE token=VALUES(token), owner_id=VALUES(owner_id), expires_ms=VALUES(expires_ms), revision=VALUES(revision), attempt=VALUES(attempt)`, [
|
|
174
|
+
tenantId,
|
|
175
|
+
kind,
|
|
176
|
+
id,
|
|
177
|
+
next.token,
|
|
178
|
+
next.owner_id,
|
|
179
|
+
next.expires_ms,
|
|
180
|
+
next.revision,
|
|
181
|
+
attempt
|
|
182
|
+
]);
|
|
183
|
+
return asLease(next);
|
|
184
|
+
};
|
|
185
|
+
const fence = async (conn, kind, id, token) => {
|
|
186
|
+
const row = await leaseRow(conn, kind, id);
|
|
187
|
+
if (!row || row.token !== token || row.expires_ms <= await clock(conn)) fail(`Invalid, expired or stale ${kind} lease: ${id}`);
|
|
188
|
+
return row;
|
|
189
|
+
};
|
|
190
|
+
const renew = (kind, id, token, ms) => op(async (conn) => {
|
|
191
|
+
await fence(conn, kind, id, token);
|
|
192
|
+
await conn.query("UPDATE openmatter_store_leases SET expires_ms=? WHERE tenant_id=? AND kind=? AND id=?", [
|
|
193
|
+
await clock(conn) + duration(ms),
|
|
194
|
+
tenantId,
|
|
195
|
+
kind,
|
|
196
|
+
id
|
|
197
|
+
]);
|
|
198
|
+
}, true);
|
|
199
|
+
const release = async (conn, kind, id) => {
|
|
200
|
+
await conn.query("UPDATE openmatter_store_leases SET expires_ms=0 WHERE tenant_id=? AND kind=? AND id=?", [
|
|
201
|
+
tenantId,
|
|
202
|
+
kind,
|
|
203
|
+
id
|
|
204
|
+
]);
|
|
205
|
+
};
|
|
206
|
+
const activeSession = async (conn, key) => {
|
|
207
|
+
const row = await one(conn, "SELECT session_id FROM openmatter_store_bindings WHERE tenant_id=? AND binding_key=?", [tenantId, key]);
|
|
208
|
+
return row ? get(conn, "session", row.session_id) : void 0;
|
|
209
|
+
};
|
|
210
|
+
const receipt = async (conn, eventId) => {
|
|
211
|
+
const reaction = await get(conn, "reaction", eventId);
|
|
212
|
+
if (!reaction) return void 0;
|
|
213
|
+
const deliveries = [];
|
|
214
|
+
for (const effect of reaction.effects) {
|
|
215
|
+
const result = await get(conn, "delivery", effect.id);
|
|
216
|
+
if (result) deliveries.push(result);
|
|
217
|
+
}
|
|
218
|
+
return {
|
|
219
|
+
reaction,
|
|
220
|
+
deliveries,
|
|
221
|
+
duplicate: false
|
|
222
|
+
};
|
|
223
|
+
};
|
|
224
|
+
const goalByThread = (conn, workThreadId) => read(conn, "SELECT data FROM openmatter_store_records WHERE tenant_id=? AND kind='goal' AND unique_key=?", [tenantId, workThreadId]);
|
|
225
|
+
const goalObjective = (objective) => {
|
|
226
|
+
const normalized = objective.trim();
|
|
227
|
+
if (!normalized) fail("Goal objective must not be blank");
|
|
228
|
+
return normalized;
|
|
229
|
+
};
|
|
230
|
+
const goalBudget = (budget) => {
|
|
231
|
+
if (budget !== void 0 && (!Number.isSafeInteger(budget) || budget <= 0)) fail("Goal token budget must be a positive safe integer");
|
|
232
|
+
};
|
|
233
|
+
const requireGoal = async (conn, workThreadId, expectedGoalId) => {
|
|
234
|
+
const goal = await goalByThread(conn, workThreadId);
|
|
235
|
+
if (!goal) return fail(`No goal for WorkThread ${workThreadId}`);
|
|
236
|
+
if (expectedGoalId !== void 0 && goal.id !== expectedGoalId) return fail("Stale goal identity");
|
|
237
|
+
return goal;
|
|
238
|
+
};
|
|
239
|
+
const removeGoalUsage = async (conn, goalId) => {
|
|
240
|
+
await conn.query("DELETE FROM openmatter_store_records WHERE tenant_id=? AND kind='goalUsage' AND parent_id=?", [tenantId, goalId]);
|
|
241
|
+
};
|
|
242
|
+
const snapshot = async (conn, scopeId) => {
|
|
243
|
+
const scopeClause = scopeId === void 0 ? "" : "AND scope_id=?";
|
|
244
|
+
const params = scopeId === void 0 ? [] : [scopeId];
|
|
245
|
+
const contexts = await rows(conn, "context", scopeClause, params);
|
|
246
|
+
const sessions = await rows(conn, "session", scopeClause, params);
|
|
247
|
+
const sessionIds = new Set(sessions.map((session) => session.id));
|
|
248
|
+
const turns = (await rows(conn, "turn")).filter((turn) => scopeId === void 0 || sessionIds.has(turn.sessionId));
|
|
249
|
+
const turnIds = new Set(turns.map((turn) => turn.id));
|
|
250
|
+
const eventIds = /* @__PURE__ */ new Set([...contexts.map((context) => context.triggerEventId), ...turns.map((turn) => turn.triggerEventId)]);
|
|
251
|
+
const events = (await rows(conn, "event")).filter((event) => scopeId === void 0 || eventIds.has(event.id) || event.source.conversationId === scopeId);
|
|
252
|
+
for (const event of events) eventIds.add(event.id);
|
|
253
|
+
const reactions = (await rows(conn, "reaction")).filter((reaction) => scopeId === void 0 || eventIds.has(reaction.eventId));
|
|
254
|
+
const effectIds = new Set(reactions.flatMap((reaction) => reaction.effects.map((effect) => effect.id)));
|
|
255
|
+
return {
|
|
256
|
+
goals: await rows(conn, "goal", scopeClause, params),
|
|
257
|
+
contexts,
|
|
258
|
+
sessions,
|
|
259
|
+
turns,
|
|
260
|
+
events,
|
|
261
|
+
reactions,
|
|
262
|
+
deliveries: (await rows(conn, "delivery")).filter((delivery) => scopeId === void 0 || effectIds.has(delivery.effectId)),
|
|
263
|
+
agentEvents: (await rows(conn, "agentEvent")).filter((event) => scopeId === void 0 || turnIds.has(event.turn_id ?? "")),
|
|
264
|
+
permissionDecisions: (await rows(conn, "permission")).filter((decision) => scopeId === void 0 || turnIds.has(decision.turnId)),
|
|
265
|
+
operationCalls: (await rows(conn, "operationCall")).filter((call) => scopeId === void 0 || turnIds.has(call.turnId)),
|
|
266
|
+
conversationEntries: (await rows(conn, "conversationEntry")).filter((entry) => scopeId === void 0 || eventIds.has(entry.eventId)),
|
|
267
|
+
turnCancellationRequests: (await rows(conn, "cancellation")).filter((request) => scopeId === void 0 || turnIds.has(request.turnId))
|
|
268
|
+
};
|
|
269
|
+
};
|
|
270
|
+
return {
|
|
271
|
+
close: Effect.tryPromise({
|
|
272
|
+
try: async () => {
|
|
273
|
+
if (closed) return;
|
|
274
|
+
closed = true;
|
|
275
|
+
if (owned) await pool.end();
|
|
276
|
+
},
|
|
277
|
+
catch: (cause) => new StoreError({
|
|
278
|
+
message: "Unable to close MySQL store",
|
|
279
|
+
cause
|
|
280
|
+
})
|
|
281
|
+
}),
|
|
282
|
+
inspect: op((conn) => snapshot(conn)),
|
|
283
|
+
inspectScope: (scope) => op((conn) => snapshot(conn, scope)),
|
|
284
|
+
createThreadGoal: (input) => op(async (conn) => {
|
|
285
|
+
if (!input.scopeId.trim() || !input.workThreadId.trim()) fail("Goal scope and WorkThread identities must not be blank");
|
|
286
|
+
const objective = goalObjective(input.objective);
|
|
287
|
+
goalBudget(input.tokenBudget);
|
|
288
|
+
const existing = await goalByThread(conn, input.workThreadId);
|
|
289
|
+
if (existing && existing.scopeId !== input.scopeId) fail("Goal WorkThread belongs to another scope");
|
|
290
|
+
if (existing && existing.status !== "complete") fail("WorkThread already has an unfinished goal");
|
|
291
|
+
const now = new Date(await clock(conn)).toISOString();
|
|
292
|
+
const goal = {
|
|
293
|
+
id: randomUUID(),
|
|
294
|
+
scopeId: input.scopeId,
|
|
295
|
+
workThreadId: input.workThreadId,
|
|
296
|
+
objective,
|
|
297
|
+
status: "active",
|
|
298
|
+
...input.tokenBudget === void 0 ? {} : { tokenBudget: input.tokenBudget },
|
|
299
|
+
tokensUsed: 0,
|
|
300
|
+
timeUsedSeconds: 0,
|
|
301
|
+
createdAt: now,
|
|
302
|
+
updatedAt: now,
|
|
303
|
+
revision: 1
|
|
304
|
+
};
|
|
305
|
+
if (existing) {
|
|
306
|
+
await removeGoalUsage(conn, existing.id);
|
|
307
|
+
await remove(conn, "goal", existing.id);
|
|
308
|
+
}
|
|
309
|
+
await put(conn, "goal", goal.id, goal, goal.scopeId, goal.workThreadId, goal.workThreadId);
|
|
310
|
+
return goal;
|
|
311
|
+
}, true),
|
|
312
|
+
getThreadGoal: (workThreadId) => op((conn) => goalByThread(conn, workThreadId)),
|
|
313
|
+
listThreadGoals: (scopeId) => op((conn) => scopeId === void 0 ? rows(conn, "goal") : rows(conn, "goal", "AND scope_id=?", [scopeId])),
|
|
314
|
+
updateThreadGoal: (workThreadId, input) => op(async (conn) => {
|
|
315
|
+
const goal = await requireGoal(conn, workThreadId, input.expectedGoalId);
|
|
316
|
+
if (input.expectedRevision !== void 0 && input.expectedRevision !== goal.revision) fail("Stale goal revision");
|
|
317
|
+
const objective = input.objective === void 0 ? goal.objective : goalObjective(input.objective);
|
|
318
|
+
const tokenBudget = input.tokenBudget === void 0 ? goal.tokenBudget : input.tokenBudget ?? void 0;
|
|
319
|
+
goalBudget(tokenBudget);
|
|
320
|
+
let status = input.status ?? goal.status;
|
|
321
|
+
if (!Schema.is(ThreadGoalStatusSchema)(status)) fail("Invalid goal status");
|
|
322
|
+
if (status === "active" && tokenBudget !== void 0 && goal.tokensUsed >= tokenBudget) status = "budget_limited";
|
|
323
|
+
const reason = input.reason === void 0 ? input.status === "active" || input.status === "complete" ? void 0 : goal.reason : input.reason.trim() || void 0;
|
|
324
|
+
if (objective === goal.objective && tokenBudget === goal.tokenBudget && status === goal.status && reason === goal.reason) return goal;
|
|
325
|
+
const { tokenBudget: _budget, reason: _reason, ...base } = goal;
|
|
326
|
+
const updated = {
|
|
327
|
+
...base,
|
|
328
|
+
objective,
|
|
329
|
+
status,
|
|
330
|
+
...tokenBudget === void 0 ? {} : { tokenBudget },
|
|
331
|
+
...reason === void 0 ? {} : { reason },
|
|
332
|
+
updatedAt: new Date(await clock(conn)).toISOString(),
|
|
333
|
+
revision: goal.revision + 1
|
|
334
|
+
};
|
|
335
|
+
await put(conn, "goal", goal.id, updated, goal.scopeId, goal.workThreadId, goal.workThreadId);
|
|
336
|
+
return updated;
|
|
337
|
+
}, true),
|
|
338
|
+
accountThreadGoal: (workThreadId, input) => op(async (conn) => {
|
|
339
|
+
const goal = await requireGoal(conn, workThreadId, input.goalId);
|
|
340
|
+
if (!input.turnId.trim()) fail("Goal usage requires a Turn identity");
|
|
341
|
+
for (const value of [input.tokensUsed, input.timeUsedSeconds]) if (!Number.isSafeInteger(value) || value < 0) fail("Goal usage must be nonnegative safe integers");
|
|
342
|
+
const id = `${goal.id}:${input.turnId}`;
|
|
343
|
+
const existing = await get(conn, "goalUsage", id);
|
|
344
|
+
if (existing) {
|
|
345
|
+
if (existing.tokensUsed !== input.tokensUsed || existing.timeUsedSeconds !== input.timeUsedSeconds) fail("Conflicting goal usage for Turn");
|
|
346
|
+
return goal;
|
|
347
|
+
}
|
|
348
|
+
const tokensUsed = goal.tokensUsed + input.tokensUsed;
|
|
349
|
+
const timeUsedSeconds = goal.timeUsedSeconds + input.timeUsedSeconds;
|
|
350
|
+
if (!Number.isSafeInteger(tokensUsed) || !Number.isSafeInteger(timeUsedSeconds)) fail("Goal usage exceeds safe integer range");
|
|
351
|
+
const updated = {
|
|
352
|
+
...goal,
|
|
353
|
+
tokensUsed,
|
|
354
|
+
timeUsedSeconds,
|
|
355
|
+
status: goal.status === "active" && goal.tokenBudget !== void 0 && tokensUsed >= goal.tokenBudget ? "budget_limited" : goal.status,
|
|
356
|
+
updatedAt: new Date(await clock(conn)).toISOString(),
|
|
357
|
+
revision: goal.revision + 1
|
|
358
|
+
};
|
|
359
|
+
await put(conn, "goalUsage", id, input, goal.scopeId, goal.id, id);
|
|
360
|
+
await put(conn, "goal", goal.id, updated, goal.scopeId, goal.workThreadId, goal.workThreadId);
|
|
361
|
+
return updated;
|
|
362
|
+
}, true),
|
|
363
|
+
clearThreadGoal: (workThreadId, expectedGoalId) => op(async (conn) => {
|
|
364
|
+
const goal = await goalByThread(conn, workThreadId);
|
|
365
|
+
if (!goal) return false;
|
|
366
|
+
if (expectedGoalId !== void 0 && goal.id !== expectedGoalId) fail("Stale goal identity");
|
|
367
|
+
await removeGoalUsage(conn, goal.id);
|
|
368
|
+
await remove(conn, "goal", goal.id);
|
|
369
|
+
return true;
|
|
370
|
+
}, true),
|
|
371
|
+
claimEvent: (event, request) => op(async (conn) => {
|
|
372
|
+
const existing = await read(conn, "SELECT data FROM openmatter_store_records WHERE tenant_id=? AND kind='event' AND unique_key=?", [tenantId, event.idempotencyKey]);
|
|
373
|
+
const fact = existing ?? event;
|
|
374
|
+
const terminal = await receipt(conn, fact.id);
|
|
375
|
+
if (terminal) return {
|
|
376
|
+
_tag: "Terminal",
|
|
377
|
+
receipt: terminal
|
|
378
|
+
};
|
|
379
|
+
const current = await leaseRow(conn, "event", fact.id);
|
|
380
|
+
if (current && current.expires_ms > await clock(conn)) return {
|
|
381
|
+
_tag: "Busy",
|
|
382
|
+
lease: asLease(current)
|
|
383
|
+
};
|
|
384
|
+
if (!existing) {
|
|
385
|
+
if (await get(conn, "event", fact.id)) fail("Event ID already belongs to a different idempotency key");
|
|
386
|
+
await put(conn, "event", fact.id, fact, fact.source.conversationId ?? null, null, fact.idempotencyKey);
|
|
387
|
+
}
|
|
388
|
+
return {
|
|
389
|
+
_tag: "Acquired",
|
|
390
|
+
event: fact,
|
|
391
|
+
lease: await acquire(conn, "event", fact.id, request)
|
|
392
|
+
};
|
|
393
|
+
}, true),
|
|
394
|
+
commitTerminalReaction: (reaction, token) => op(async (conn) => {
|
|
395
|
+
await fence(conn, "event", reaction.eventId, token);
|
|
396
|
+
const existing = await get(conn, "reaction", reaction.eventId);
|
|
397
|
+
if (existing) return {
|
|
398
|
+
_tag: "Existing",
|
|
399
|
+
reaction: existing
|
|
400
|
+
};
|
|
401
|
+
await put(conn, "reaction", reaction.eventId, reaction);
|
|
402
|
+
return {
|
|
403
|
+
_tag: "Committed",
|
|
404
|
+
reaction: await get(conn, "reaction", reaction.eventId)
|
|
405
|
+
};
|
|
406
|
+
}, true),
|
|
407
|
+
renewEventLease: (id, token, request) => renew("event", id, token, request.durationMs),
|
|
408
|
+
getReceipt: (id) => op((conn) => receipt(conn, id)),
|
|
409
|
+
claimPendingEffects: (request) => op(async (conn) => {
|
|
410
|
+
if (!Number.isSafeInteger(request.limit) || request.limit < 0) fail("Invalid effect claim limit");
|
|
411
|
+
const effects = (await rows(conn, "reaction")).filter((reaction) => request.eventId === void 0 || reaction.eventId === request.eventId).flatMap((reaction) => reaction.effects).sort((left, right) => left.id.localeCompare(right.id));
|
|
412
|
+
const pending = [];
|
|
413
|
+
const now = await clock(conn);
|
|
414
|
+
for (const effect of effects) {
|
|
415
|
+
if (pending.length >= request.limit) break;
|
|
416
|
+
const delivered = await get(conn, "delivery", effect.id);
|
|
417
|
+
if (delivered && (delivered.status !== "retryable-failed" || delivered.nextRetryAt !== void 0 && Date.parse(delivered.nextRetryAt) > now)) continue;
|
|
418
|
+
const current = await leaseRow(conn, "effect", effect.id);
|
|
419
|
+
if (current && current.expires_ms > now) continue;
|
|
420
|
+
const previous = await one(conn, "SELECT attempt FROM openmatter_store_leases WHERE tenant_id=? AND kind='effect' AND id=?", [tenantId, effect.id]);
|
|
421
|
+
const attempt = Math.max(asNumber(previous?.attempt ?? 0), delivered?.attempt ?? 0) + 1;
|
|
422
|
+
pending.push({
|
|
423
|
+
effect,
|
|
424
|
+
attempt,
|
|
425
|
+
lease: await acquire(conn, "effect", effect.id, request, attempt)
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
return pending;
|
|
429
|
+
}, true),
|
|
430
|
+
recordDelivery: (value, token) => op(async (conn) => {
|
|
431
|
+
await fence(conn, "effect", value.effectId, token);
|
|
432
|
+
await put(conn, "delivery", value.effectId, value);
|
|
433
|
+
await release(conn, "effect", value.effectId);
|
|
434
|
+
}, true),
|
|
435
|
+
renewEffectLease: (id, token, request) => renew("effect", id, token, request.durationMs),
|
|
436
|
+
claimSession: (key, request) => op(async (conn) => {
|
|
437
|
+
const current = await leaseRow(conn, "session", key);
|
|
438
|
+
if (current && current.expires_ms > await clock(conn)) return {
|
|
439
|
+
_tag: "Busy",
|
|
440
|
+
lease: asLease(current)
|
|
441
|
+
};
|
|
442
|
+
const session = await activeSession(conn, key);
|
|
443
|
+
return {
|
|
444
|
+
_tag: "Acquired",
|
|
445
|
+
lease: await acquire(conn, "session", key, request),
|
|
446
|
+
...session ? { session } : {}
|
|
447
|
+
};
|
|
448
|
+
}, true),
|
|
449
|
+
saveSession: (session, token) => op(async (conn) => {
|
|
450
|
+
await fence(conn, "session", session.bindingKey, token);
|
|
451
|
+
const previous = await activeSession(conn, session.bindingKey);
|
|
452
|
+
if (previous && previous.id !== session.id && ["open", "creating"].includes(previous.state)) await put(conn, "session", previous.id, {
|
|
453
|
+
...previous,
|
|
454
|
+
state: "closed"
|
|
455
|
+
}, previous.scopeId, previous.bindingKey);
|
|
456
|
+
await put(conn, "session", session.id, session, session.scopeId, session.bindingKey);
|
|
457
|
+
await conn.query(`INSERT INTO openmatter_store_bindings (tenant_id, binding_key, session_id) VALUES (?,?,?)
|
|
458
|
+
ON DUPLICATE KEY UPDATE session_id=VALUES(session_id)`, [
|
|
459
|
+
tenantId,
|
|
460
|
+
session.bindingKey,
|
|
461
|
+
session.id
|
|
462
|
+
]);
|
|
463
|
+
}, true),
|
|
464
|
+
getSession: (id) => op((conn) => get(conn, "session", id)),
|
|
465
|
+
renewSessionLease: (key, token, request) => renew("session", key, token, request.durationMs),
|
|
466
|
+
releaseSession: (key, token) => op(async (conn) => {
|
|
467
|
+
await fence(conn, "session", key, token);
|
|
468
|
+
await release(conn, "session", key);
|
|
469
|
+
}, true),
|
|
470
|
+
saveTurn: (turn, key, token) => op(async (conn) => {
|
|
471
|
+
await fence(conn, "session", key, token);
|
|
472
|
+
if ((await get(conn, "session", turn.sessionId))?.bindingKey !== key) fail("Turn belongs to another session binding");
|
|
473
|
+
const terminal = (await rows(conn, "agentEvent", "AND parent_id=?", [turn.id])).find((event) => [
|
|
474
|
+
"turn.completed",
|
|
475
|
+
"turn.failed",
|
|
476
|
+
"turn.cancelled",
|
|
477
|
+
"turn.interrupted"
|
|
478
|
+
].includes(event.type));
|
|
479
|
+
if (terminal && turn.state !== (terminal.type === "turn.interrupted" ? "cancelled" : terminal.type.slice(5))) return;
|
|
480
|
+
await put(conn, "turn", turn.id, turn, null, turn.sessionId);
|
|
481
|
+
}, true),
|
|
482
|
+
getTurn: (id) => op((conn) => get(conn, "turn", id)),
|
|
483
|
+
requestTurnCancellation: (key, eventId, at) => op(async (conn) => {
|
|
484
|
+
const session = await activeSession(conn, key);
|
|
485
|
+
if (!session) return void 0;
|
|
486
|
+
const turn = (await rows(conn, "turn", "AND parent_id=?", [session.id])).filter((item) => item.state === "queued" || item.state === "running").sort((left, right) => right.createdAt.localeCompare(left.createdAt))[0];
|
|
487
|
+
if (!turn) return void 0;
|
|
488
|
+
const existing = await get(conn, "cancellation", turn.id);
|
|
489
|
+
if (existing) return existing;
|
|
490
|
+
const value = {
|
|
491
|
+
turnId: turn.id,
|
|
492
|
+
sessionId: session.id,
|
|
493
|
+
bindingKey: key,
|
|
494
|
+
requestedByEventId: eventId,
|
|
495
|
+
requestedAt: at
|
|
496
|
+
};
|
|
497
|
+
await put(conn, "cancellation", turn.id, value);
|
|
498
|
+
return value;
|
|
499
|
+
}, true),
|
|
500
|
+
getTurnCancellation: (id) => op((conn) => get(conn, "cancellation", id)),
|
|
501
|
+
getAgentEvents: (id) => op(async (conn) => (await rows(conn, "agentEvent", "AND parent_id=?", [id])).sort((left, right) => (left.seq ?? 0) - (right.seq ?? 0))),
|
|
502
|
+
getPermissionDecision: (turnId, requestId) => op((conn) => get(conn, "permission", JSON.stringify([turnId, requestId]))),
|
|
503
|
+
commitPermissionDecision: (decision, key, token) => op(async (conn) => {
|
|
504
|
+
await fence(conn, "session", key, token);
|
|
505
|
+
const turn = await get(conn, "turn", decision.turnId);
|
|
506
|
+
if (!turn || (await get(conn, "session", turn.sessionId))?.bindingKey !== key) fail("Permission belongs to another session binding");
|
|
507
|
+
const id = JSON.stringify([decision.turnId, decision.requestId]);
|
|
508
|
+
const existing = await get(conn, "permission", id);
|
|
509
|
+
if (existing) return existing;
|
|
510
|
+
await put(conn, "permission", id, decision);
|
|
511
|
+
return await get(conn, "permission", id);
|
|
512
|
+
}, true),
|
|
513
|
+
getOperationCall: (turnId, callId) => op((conn) => get(conn, "operationCall", JSON.stringify([turnId, callId]))),
|
|
514
|
+
beginOperationCall: (call, key, token) => casOp(async (conn) => {
|
|
515
|
+
await fence(conn, "session", key, token);
|
|
516
|
+
const turn = await get(conn, "turn", call.turnId);
|
|
517
|
+
if (!turn || (await get(conn, "session", turn.sessionId))?.bindingKey !== key) fail("Operation call belongs to another session binding");
|
|
518
|
+
const id = JSON.stringify([call.turnId, call.callId]);
|
|
519
|
+
const existing = await get(conn, "operationCall", id);
|
|
520
|
+
if (existing) return existing;
|
|
521
|
+
if (call.conversation !== void 0) {
|
|
522
|
+
const actual = await conversationRevision(conn, call.conversation.key);
|
|
523
|
+
if (actual !== call.conversation.revision) throw new ConversationChangedError({
|
|
524
|
+
conversationKey: call.conversation.key,
|
|
525
|
+
expected: call.conversation.revision,
|
|
526
|
+
actual
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
await put(conn, "operationCall", id, call);
|
|
530
|
+
return await get(conn, "operationCall", id);
|
|
531
|
+
}),
|
|
532
|
+
recordConversationEntry: (input) => op(async (conn) => {
|
|
533
|
+
const existing = await get(conn, "conversationEntry", input.eventId);
|
|
534
|
+
if (existing) return existing;
|
|
535
|
+
const revision = await conversationRevision(conn, input.conversationKey) + 1;
|
|
536
|
+
const entry = {
|
|
537
|
+
...input,
|
|
538
|
+
revision
|
|
539
|
+
};
|
|
540
|
+
await put(conn, "conversationEntry", input.eventId, entry, null, input.conversationKey, JSON.stringify([input.conversationKey, revision]));
|
|
541
|
+
return entry;
|
|
542
|
+
}, true),
|
|
543
|
+
getConversationEntry: (eventId) => op((conn) => get(conn, "conversationEntry", eventId)),
|
|
544
|
+
findConversationMessage: (key, messageId) => op(async (conn) => (await conversationLog(conn, key)).findLast((e) => e.kind !== "recall" && e.messageId === messageId)),
|
|
545
|
+
listConversationEntries: (key, afterRevision) => op(async (conn) => (await conversationLog(conn, key)).filter((e) => e.revision > afterRevision).sort((a, b) => a.revision - b.revision)),
|
|
546
|
+
completeOperationCall: (turnId, callId, result, completedAt, key, token) => op(async (conn) => {
|
|
547
|
+
await fence(conn, "session", key, token);
|
|
548
|
+
const id = JSON.stringify([turnId, callId]);
|
|
549
|
+
const existing = await get(conn, "operationCall", id);
|
|
550
|
+
if (!existing) fail(`Unknown operation call: ${turnId}/${callId}`);
|
|
551
|
+
if (existing.state === "completed") return existing;
|
|
552
|
+
await put(conn, "operationCall", id, {
|
|
553
|
+
...existing,
|
|
554
|
+
state: "completed",
|
|
555
|
+
result,
|
|
556
|
+
completedAt
|
|
557
|
+
});
|
|
558
|
+
return await get(conn, "operationCall", id);
|
|
559
|
+
}, true),
|
|
560
|
+
appendAgentEvent: (event, key, token) => op(async (conn) => {
|
|
561
|
+
await fence(conn, "session", key, token);
|
|
562
|
+
const turnId = event.turn_id;
|
|
563
|
+
if (!turnId || event.seq === void 0) return fail("Agent event requires turn identity and sequence");
|
|
564
|
+
if ((await get(conn, "session", event.session_id))?.bindingKey !== key || (await get(conn, "turn", turnId))?.sessionId !== event.session_id) return fail("Agent event belongs to another session binding");
|
|
565
|
+
const id = JSON.stringify([turnId, event.seq]);
|
|
566
|
+
const existing = await get(conn, "agentEvent", id);
|
|
567
|
+
if (existing) {
|
|
568
|
+
if (encode(existing) !== encode(event)) fail("Conflicting Agent event sequence");
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
await put(conn, "agentEvent", id, event, null, turnId, event.event_id);
|
|
572
|
+
}, true),
|
|
573
|
+
saveContext: (context) => op(async (conn) => {
|
|
574
|
+
await put(conn, "context", context.id, context, context.scopeId, context.workThreadId);
|
|
575
|
+
}, true),
|
|
576
|
+
getContext: (id) => op((conn) => get(conn, "context", id))
|
|
577
|
+
};
|
|
578
|
+
};
|
|
579
|
+
//#endregion
|
|
580
|
+
export { makeMysqlStore };
|
|
581
|
+
|
|
582
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport {\n createPool,\n type Pool,\n type PoolConnection,\n type RowDataPacket,\n} from \"mysql2/promise\";\nimport {\n JsonValueSchema,\n ThreadGoalStatusSchema,\n type AgentSession,\n type ContextProjection,\n type ConversationEntry,\n type EffectDeliveryReceipt,\n type OperationCall,\n type PermissionDecision,\n type Reaction,\n type ThreadGoal,\n type Turn,\n type TurnCancellationRequest,\n type WorkEvent,\n} from \"@openma/matter\";\nimport type { OpenMAEvent } from \"@openma/matter/agent\";\nimport {\n ConversationChangedError,\n StoreError,\n type AccountThreadGoalInput,\n type LeaseRequest,\n type OpenMatterStore,\n type PendingEffectClaim,\n type StoreSnapshot,\n type WorkLease,\n} from \"@openma/matter/store\";\nimport { Effect, Schema } from \"effect\";\n\nexport interface MysqlStore extends OpenMatterStore {\n readonly close: Effect.Effect<void, StoreError>;\n readonly inspect: Effect.Effect<StoreSnapshot, StoreError>;\n readonly inspectScope: (\n scopeId: string,\n ) => Effect.Effect<StoreSnapshot, StoreError>;\n}\n\nexport interface MysqlStoreOptions {\n readonly tenantId: string;\n readonly url?: string;\n readonly pool?: Pool;\n}\n\ntype LeaseRow = {\n token: string;\n owner_id: string;\n expires_ms: number;\n revision: number;\n};\n\nconst initialized = new WeakSet<Pool>();\n\nconst schema = [\n `CREATE TABLE IF NOT EXISTS openmatter_store_records (\n tenant_id VARCHAR(191) NOT NULL,\n kind VARCHAR(64) NOT NULL,\n id VARCHAR(191) NOT NULL,\n scope_id VARCHAR(191) NULL,\n parent_id VARCHAR(191) NULL,\n unique_key VARCHAR(191) NULL,\n data LONGTEXT NOT NULL,\n seq BIGINT NOT NULL AUTO_INCREMENT,\n PRIMARY KEY (tenant_id, kind, id),\n UNIQUE KEY openmatter_store_unique (tenant_id, kind, unique_key),\n KEY openmatter_store_scope (tenant_id, kind, scope_id),\n KEY openmatter_store_parent (tenant_id, kind, parent_id),\n KEY openmatter_store_seq (seq)\n )`,\n `CREATE TABLE IF NOT EXISTS openmatter_store_leases (\n tenant_id VARCHAR(191) NOT NULL,\n kind VARCHAR(64) NOT NULL,\n id VARCHAR(191) NOT NULL,\n token VARCHAR(64) NOT NULL,\n owner_id VARCHAR(191) NOT NULL,\n expires_ms BIGINT NOT NULL,\n revision INT NOT NULL,\n attempt INT NOT NULL DEFAULT 0,\n PRIMARY KEY (tenant_id, kind, id)\n )`,\n `CREATE TABLE IF NOT EXISTS openmatter_store_bindings (\n tenant_id VARCHAR(191) NOT NULL,\n binding_key VARCHAR(512) NOT NULL,\n session_id VARCHAR(191) NOT NULL,\n PRIMARY KEY (tenant_id, binding_key)\n )`,\n];\n\nconst asNumber = (value: unknown): number =>\n typeof value === \"bigint\" ? Number(value) : Number(value);\n\n/** MySQL adapter for the OpenMatter store port. One instance is bound to one tenant. */\nexport const makeMysqlStore = (options: MysqlStoreOptions): MysqlStore => {\n if (!options.tenantId.trim())\n throw new StoreError({ message: \"MySQL store requires a tenant id\" });\n const owned = options.pool === undefined;\n const pool =\n options.pool ??\n createPool(options.url ?? process.env.PROJECT_WORKER_MYSQL_URL ?? \"\");\n const tenantId = options.tenantId;\n let closed = false;\n let chain = Promise.resolve();\n const fail = (message: string): never => {\n throw new StoreError({ message });\n };\n const exclusive = <T>(body: () => Promise<T>): Promise<T> => {\n const run = chain.then(body, body);\n chain = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n };\n const ensure = async () => {\n if (initialized.has(pool)) return;\n const conn = await pool.getConnection();\n try {\n for (const statement of schema) await conn.query(statement);\n initialized.add(pool);\n } finally {\n conn.release();\n }\n };\n const encode = (value: unknown): string => {\n if (!Schema.is(JsonValueSchema)(value))\n fail(\"Store facts must be portable JSON\");\n return JSON.stringify(value);\n };\n const query = async <T>(\n conn: PoolConnection,\n sql: string,\n params: unknown[] = [],\n ): Promise<T[]> => {\n const [rows] = await conn.query<RowDataPacket[]>(sql, params);\n return rows as T[];\n };\n const one = async <T>(\n conn: PoolConnection,\n sql: string,\n params: unknown[] = [],\n ): Promise<T | undefined> => (await query<T>(conn, sql, params))[0];\n const withTx = async <T>(\n write: boolean,\n body: (conn: PoolConnection) => Promise<T>,\n ): Promise<T> => {\n if (closed) fail(\"MySQL store is closed\");\n await ensure();\n const conn = await pool.getConnection();\n try {\n await conn.beginTransaction();\n if (write)\n await conn.query(\n \"SELECT 1 FROM openmatter_store_leases LIMIT 1 FOR UPDATE\",\n );\n const result = await body(conn);\n await conn.commit();\n return result;\n } catch (cause) {\n await conn.rollback();\n throw cause;\n } finally {\n conn.release();\n }\n };\n const op = <T>(\n body: (conn: PoolConnection) => Promise<T>,\n write = false,\n ): Effect.Effect<T, StoreError> =>\n Effect.tryPromise({\n try: () => exclusive(() => withTx(write, body)),\n catch: (cause) =>\n cause instanceof StoreError\n ? cause\n : new StoreError({\n message: \"MySQL store operation failed\",\n cause,\n }),\n });\n /** As `op`, but a guarded write's ConversationChangedError passes through. */\n const casOp = <T>(\n body: (conn: PoolConnection) => Promise<T>,\n ): Effect.Effect<T, StoreError | ConversationChangedError> =>\n op(body, true).pipe(\n Effect.mapError((error): StoreError | ConversationChangedError =>\n error.cause instanceof ConversationChangedError ? error.cause : error,\n ),\n );\n // The revision is the entry count. Two writers that read the same count\n // collide on the unique (conversation, revision) key; the loser fails and\n // the caller retries, so revisions never repeat.\n const conversationRevision = async (conn: PoolConnection, key: string) =>\n asNumber(\n (\n await one<{ n: unknown }>(\n conn,\n \"SELECT COUNT(*) AS n FROM openmatter_store_records WHERE tenant_id=? AND kind='conversationEntry' AND parent_id=?\",\n [tenantId, key],\n )\n )?.n ?? 0,\n );\n const conversationLog = (conn: PoolConnection, key: string) =>\n rows<ConversationEntry>(conn, \"conversationEntry\", \"AND parent_id=?\", [\n key,\n ]);\n const clock = async (conn: PoolConnection) =>\n asNumber(\n (\n await one<{ now: unknown }>(\n conn,\n \"SELECT ROUND(UNIX_TIMESTAMP(NOW(3)) * 1000) AS now\",\n )\n )?.now,\n );\n const read = async <T>(\n conn: PoolConnection,\n sql: string,\n params: unknown[],\n ): Promise<T | undefined> => {\n const row = await one<{ data: string }>(conn, sql, params);\n return row ? (JSON.parse(row.data) as T) : undefined;\n };\n const get = async <T>(conn: PoolConnection, kind: string, id: string) =>\n read<T>(\n conn,\n \"SELECT data FROM openmatter_store_records WHERE tenant_id=? AND kind=? AND id=?\",\n [tenantId, kind, id],\n );\n const rows = async <T>(\n conn: PoolConnection,\n kind: string,\n clause = \"\",\n params: unknown[] = [],\n ): Promise<T[]> =>\n (\n await query<{ data: string }>(\n conn,\n `SELECT data FROM openmatter_store_records WHERE tenant_id=? AND kind=? ${clause} ORDER BY seq`,\n [tenantId, kind, ...params],\n )\n ).map((row) => JSON.parse(row.data) as T);\n const put = async (\n conn: PoolConnection,\n kind: string,\n id: string,\n value: unknown,\n scope: string | null = null,\n parent: string | null = null,\n key: string | null = null,\n ) => {\n await conn.query(\n `INSERT INTO openmatter_store_records (tenant_id, kind, id, scope_id, parent_id, unique_key, data)\n VALUES (?,?,?,?,?,?,?)\n ON DUPLICATE KEY UPDATE data=VALUES(data), scope_id=VALUES(scope_id), parent_id=VALUES(parent_id), unique_key=VALUES(unique_key)`,\n [tenantId, kind, id, scope, parent, key, encode(value)],\n );\n };\n const remove = async (conn: PoolConnection, kind: string, id: string) => {\n await conn.query(\n \"DELETE FROM openmatter_store_records WHERE tenant_id=? AND kind=? AND id=?\",\n [tenantId, kind, id],\n );\n };\n const leaseRow = async (conn: PoolConnection, kind: string, id: string) => {\n const row = await one<LeaseRow & { expires_ms: unknown }>(\n conn,\n \"SELECT token, owner_id, expires_ms, revision FROM openmatter_store_leases WHERE tenant_id=? AND kind=? AND id=?\",\n [tenantId, kind, id],\n );\n return row\n ? {\n ...row,\n expires_ms: asNumber(row.expires_ms),\n revision: asNumber(row.revision),\n }\n : undefined;\n };\n const asLease = (row: LeaseRow): WorkLease => ({\n token: row.token,\n ownerId: row.owner_id,\n expiresAt: new Date(row.expires_ms).toISOString(),\n revision: row.revision,\n });\n const duration = (ms: number) => {\n if (!Number.isSafeInteger(ms) || ms <= 0)\n fail(\"Lease duration must be a positive integer\");\n return ms;\n };\n const acquire = async (\n conn: PoolConnection,\n kind: string,\n id: string,\n request: LeaseRequest,\n attempt = 0,\n ): Promise<WorkLease> => {\n const row = await leaseRow(conn, kind, id);\n const next: LeaseRow = {\n token: randomUUID(),\n owner_id: request.ownerId,\n expires_ms: (await clock(conn)) + duration(request.durationMs),\n revision: (row?.revision ?? 0) + 1,\n };\n await conn.query(\n `INSERT INTO openmatter_store_leases (tenant_id, kind, id, token, owner_id, expires_ms, revision, attempt)\n VALUES (?,?,?,?,?,?,?,?)\n ON DUPLICATE KEY UPDATE token=VALUES(token), owner_id=VALUES(owner_id), expires_ms=VALUES(expires_ms), revision=VALUES(revision), attempt=VALUES(attempt)`,\n [\n tenantId,\n kind,\n id,\n next.token,\n next.owner_id,\n next.expires_ms,\n next.revision,\n attempt,\n ],\n );\n return asLease(next);\n };\n const fence = async (\n conn: PoolConnection,\n kind: string,\n id: string,\n token: string,\n ) => {\n const row = await leaseRow(conn, kind, id);\n if (!row || row.token !== token || row.expires_ms <= (await clock(conn)))\n fail(`Invalid, expired or stale ${kind} lease: ${id}`);\n return row;\n };\n const renew = (kind: string, id: string, token: string, ms: number) =>\n op(async (conn) => {\n await fence(conn, kind, id, token);\n await conn.query(\n \"UPDATE openmatter_store_leases SET expires_ms=? WHERE tenant_id=? AND kind=? AND id=?\",\n [(await clock(conn)) + duration(ms), tenantId, kind, id],\n );\n }, true);\n const release = async (conn: PoolConnection, kind: string, id: string) => {\n await conn.query(\n \"UPDATE openmatter_store_leases SET expires_ms=0 WHERE tenant_id=? AND kind=? AND id=?\",\n [tenantId, kind, id],\n );\n };\n const activeSession = async (conn: PoolConnection, key: string) => {\n const row = await one<{ session_id: string }>(\n conn,\n \"SELECT session_id FROM openmatter_store_bindings WHERE tenant_id=? AND binding_key=?\",\n [tenantId, key],\n );\n return row ? get<AgentSession>(conn, \"session\", row.session_id) : undefined;\n };\n const receipt = async (conn: PoolConnection, eventId: string) => {\n const reaction = await get<Reaction>(conn, \"reaction\", eventId);\n if (!reaction) return undefined;\n const deliveries: EffectDeliveryReceipt[] = [];\n for (const effect of reaction.effects) {\n const result = await get<EffectDeliveryReceipt>(\n conn,\n \"delivery\",\n effect.id,\n );\n if (result) deliveries.push(result);\n }\n return { reaction, deliveries, duplicate: false as const };\n };\n const goalByThread = (conn: PoolConnection, workThreadId: string) =>\n read<ThreadGoal>(\n conn,\n \"SELECT data FROM openmatter_store_records WHERE tenant_id=? AND kind='goal' AND unique_key=?\",\n [tenantId, workThreadId],\n );\n const goalObjective = (objective: string) => {\n const normalized = objective.trim();\n if (!normalized) fail(\"Goal objective must not be blank\");\n return normalized;\n };\n const goalBudget = (budget: number | undefined) => {\n if (budget !== undefined && (!Number.isSafeInteger(budget) || budget <= 0))\n fail(\"Goal token budget must be a positive safe integer\");\n };\n const requireGoal = async (\n conn: PoolConnection,\n workThreadId: string,\n expectedGoalId?: string,\n ): Promise<ThreadGoal> => {\n const goal = await goalByThread(conn, workThreadId);\n if (!goal) return fail(`No goal for WorkThread ${workThreadId}`);\n if (expectedGoalId !== undefined && goal.id !== expectedGoalId)\n return fail(\"Stale goal identity\");\n return goal;\n };\n const removeGoalUsage = async (conn: PoolConnection, goalId: string) => {\n await conn.query(\n \"DELETE FROM openmatter_store_records WHERE tenant_id=? AND kind='goalUsage' AND parent_id=?\",\n [tenantId, goalId],\n );\n };\n const snapshot = async (\n conn: PoolConnection,\n scopeId?: string,\n ): Promise<StoreSnapshot> => {\n const scopeClause = scopeId === undefined ? \"\" : \"AND scope_id=?\";\n const params = scopeId === undefined ? [] : [scopeId];\n const contexts = await rows<ContextProjection>(\n conn,\n \"context\",\n scopeClause,\n params,\n );\n const sessions = await rows<AgentSession>(\n conn,\n \"session\",\n scopeClause,\n params,\n );\n const sessionIds = new Set(sessions.map((session) => session.id));\n const turns = (await rows<Turn>(conn, \"turn\")).filter(\n (turn) => scopeId === undefined || sessionIds.has(turn.sessionId),\n );\n const turnIds = new Set(turns.map((turn) => turn.id));\n const eventIds = new Set([\n ...contexts.map((context) => context.triggerEventId),\n ...turns.map((turn) => turn.triggerEventId),\n ]);\n const events = (await rows<WorkEvent>(conn, \"event\")).filter(\n (event) =>\n scopeId === undefined ||\n eventIds.has(event.id) ||\n event.source.conversationId === scopeId,\n );\n for (const event of events) eventIds.add(event.id);\n const reactions = (await rows<Reaction>(conn, \"reaction\")).filter(\n (reaction) => scopeId === undefined || eventIds.has(reaction.eventId),\n );\n const effectIds = new Set(\n reactions.flatMap((reaction) =>\n reaction.effects.map((effect) => effect.id),\n ),\n );\n return {\n goals: await rows<ThreadGoal>(conn, \"goal\", scopeClause, params),\n contexts,\n sessions,\n turns,\n events,\n reactions,\n deliveries: (await rows<EffectDeliveryReceipt>(conn, \"delivery\")).filter(\n (delivery) => scopeId === undefined || effectIds.has(delivery.effectId),\n ),\n agentEvents: (await rows<OpenMAEvent>(conn, \"agentEvent\")).filter(\n (event) => scopeId === undefined || turnIds.has(event.turn_id ?? \"\"),\n ),\n permissionDecisions: (\n await rows<PermissionDecision>(conn, \"permission\")\n ).filter(\n (decision) => scopeId === undefined || turnIds.has(decision.turnId),\n ),\n operationCalls: (await rows<OperationCall>(conn, \"operationCall\")).filter(\n (call) => scopeId === undefined || turnIds.has(call.turnId),\n ),\n conversationEntries: (\n await rows<ConversationEntry>(conn, \"conversationEntry\")\n ).filter((entry) => scopeId === undefined || eventIds.has(entry.eventId)),\n turnCancellationRequests: (\n await rows<TurnCancellationRequest>(conn, \"cancellation\")\n ).filter(\n (request) => scopeId === undefined || turnIds.has(request.turnId),\n ),\n };\n };\n\n const store: MysqlStore = {\n close: Effect.tryPromise({\n try: async () => {\n if (closed) return;\n closed = true;\n if (owned) await pool.end();\n },\n catch: (cause) =>\n new StoreError({ message: \"Unable to close MySQL store\", cause }),\n }),\n inspect: op((conn) => snapshot(conn)),\n inspectScope: (scope) => op((conn) => snapshot(conn, scope)),\n createThreadGoal: (input) =>\n op(async (conn) => {\n if (!input.scopeId.trim() || !input.workThreadId.trim())\n fail(\"Goal scope and WorkThread identities must not be blank\");\n const objective = goalObjective(input.objective);\n goalBudget(input.tokenBudget);\n const existing = await goalByThread(conn, input.workThreadId);\n if (existing && existing.scopeId !== input.scopeId)\n fail(\"Goal WorkThread belongs to another scope\");\n if (existing && existing.status !== \"complete\")\n fail(\"WorkThread already has an unfinished goal\");\n const now = new Date(await clock(conn)).toISOString();\n const goal: ThreadGoal = {\n id: randomUUID(),\n scopeId: input.scopeId,\n workThreadId: input.workThreadId,\n objective,\n status: \"active\",\n ...(input.tokenBudget === undefined\n ? {}\n : { tokenBudget: input.tokenBudget }),\n tokensUsed: 0,\n timeUsedSeconds: 0,\n createdAt: now,\n updatedAt: now,\n revision: 1,\n };\n if (existing) {\n await removeGoalUsage(conn, existing.id);\n await remove(conn, \"goal\", existing.id);\n }\n await put(\n conn,\n \"goal\",\n goal.id,\n goal,\n goal.scopeId,\n goal.workThreadId,\n goal.workThreadId,\n );\n return goal;\n }, true),\n getThreadGoal: (workThreadId) =>\n op((conn) => goalByThread(conn, workThreadId)),\n listThreadGoals: (scopeId) =>\n op((conn) =>\n scopeId === undefined\n ? rows<ThreadGoal>(conn, \"goal\")\n : rows<ThreadGoal>(conn, \"goal\", \"AND scope_id=?\", [scopeId]),\n ),\n updateThreadGoal: (workThreadId, input) =>\n op(async (conn) => {\n const goal = await requireGoal(\n conn,\n workThreadId,\n input.expectedGoalId,\n );\n if (\n input.expectedRevision !== undefined &&\n input.expectedRevision !== goal.revision\n )\n fail(\"Stale goal revision\");\n const objective =\n input.objective === undefined\n ? goal.objective\n : goalObjective(input.objective);\n const tokenBudget =\n input.tokenBudget === undefined\n ? goal.tokenBudget\n : (input.tokenBudget ?? undefined);\n goalBudget(tokenBudget);\n let status = input.status ?? goal.status;\n if (!Schema.is(ThreadGoalStatusSchema)(status))\n fail(\"Invalid goal status\");\n if (\n status === \"active\" &&\n tokenBudget !== undefined &&\n goal.tokensUsed >= tokenBudget\n )\n status = \"budget_limited\";\n const reason =\n input.reason === undefined\n ? input.status === \"active\" || input.status === \"complete\"\n ? undefined\n : goal.reason\n : input.reason.trim() || undefined;\n if (\n objective === goal.objective &&\n tokenBudget === goal.tokenBudget &&\n status === goal.status &&\n reason === goal.reason\n )\n return goal;\n const { tokenBudget: _budget, reason: _reason, ...base } = goal;\n const updated: ThreadGoal = {\n ...base,\n objective,\n status,\n ...(tokenBudget === undefined ? {} : { tokenBudget }),\n ...(reason === undefined ? {} : { reason }),\n updatedAt: new Date(await clock(conn)).toISOString(),\n revision: goal.revision + 1,\n };\n await put(\n conn,\n \"goal\",\n goal.id,\n updated,\n goal.scopeId,\n goal.workThreadId,\n goal.workThreadId,\n );\n return updated;\n }, true),\n accountThreadGoal: (workThreadId, input) =>\n op(async (conn) => {\n const goal = await requireGoal(conn, workThreadId, input.goalId);\n if (!input.turnId.trim()) fail(\"Goal usage requires a Turn identity\");\n for (const value of [input.tokensUsed, input.timeUsedSeconds]) {\n if (!Number.isSafeInteger(value) || value < 0)\n fail(\"Goal usage must be nonnegative safe integers\");\n }\n const id = `${goal.id}:${input.turnId}`;\n const existing = await get<AccountThreadGoalInput>(\n conn,\n \"goalUsage\",\n id,\n );\n if (existing) {\n if (\n existing.tokensUsed !== input.tokensUsed ||\n existing.timeUsedSeconds !== input.timeUsedSeconds\n )\n fail(\"Conflicting goal usage for Turn\");\n return goal;\n }\n const tokensUsed = goal.tokensUsed + input.tokensUsed;\n const timeUsedSeconds = goal.timeUsedSeconds + input.timeUsedSeconds;\n if (\n !Number.isSafeInteger(tokensUsed) ||\n !Number.isSafeInteger(timeUsedSeconds)\n )\n fail(\"Goal usage exceeds safe integer range\");\n const updated: ThreadGoal = {\n ...goal,\n tokensUsed,\n timeUsedSeconds,\n status:\n goal.status === \"active\" &&\n goal.tokenBudget !== undefined &&\n tokensUsed >= goal.tokenBudget\n ? \"budget_limited\"\n : goal.status,\n updatedAt: new Date(await clock(conn)).toISOString(),\n revision: goal.revision + 1,\n };\n await put(conn, \"goalUsage\", id, input, goal.scopeId, goal.id, id);\n await put(\n conn,\n \"goal\",\n goal.id,\n updated,\n goal.scopeId,\n goal.workThreadId,\n goal.workThreadId,\n );\n return updated;\n }, true),\n clearThreadGoal: (workThreadId, expectedGoalId) =>\n op(async (conn) => {\n const goal = await goalByThread(conn, workThreadId);\n if (!goal) return false;\n if (expectedGoalId !== undefined && goal.id !== expectedGoalId)\n fail(\"Stale goal identity\");\n await removeGoalUsage(conn, goal.id);\n await remove(conn, \"goal\", goal.id);\n return true;\n }, true),\n claimEvent: (event, request) =>\n op(async (conn) => {\n const existing = await read<WorkEvent>(\n conn,\n \"SELECT data FROM openmatter_store_records WHERE tenant_id=? AND kind='event' AND unique_key=?\",\n [tenantId, event.idempotencyKey],\n );\n const fact = existing ?? event;\n const terminal = await receipt(conn, fact.id);\n if (terminal) return { _tag: \"Terminal\" as const, receipt: terminal };\n const current = await leaseRow(conn, \"event\", fact.id);\n if (current && current.expires_ms > (await clock(conn)))\n return { _tag: \"Busy\" as const, lease: asLease(current) };\n if (!existing) {\n if (await get(conn, \"event\", fact.id))\n fail(\"Event ID already belongs to a different idempotency key\");\n await put(\n conn,\n \"event\",\n fact.id,\n fact,\n fact.source.conversationId ?? null,\n null,\n fact.idempotencyKey,\n );\n }\n return {\n _tag: \"Acquired\" as const,\n event: fact,\n lease: await acquire(conn, \"event\", fact.id, request),\n };\n }, true),\n commitTerminalReaction: (reaction, token) =>\n op(async (conn) => {\n await fence(conn, \"event\", reaction.eventId, token);\n const existing = await get<Reaction>(\n conn,\n \"reaction\",\n reaction.eventId,\n );\n if (existing) return { _tag: \"Existing\" as const, reaction: existing };\n await put(conn, \"reaction\", reaction.eventId, reaction);\n return {\n _tag: \"Committed\" as const,\n reaction: (await get<Reaction>(conn, \"reaction\", reaction.eventId))!,\n };\n }, true),\n renewEventLease: (id, token, request) =>\n renew(\"event\", id, token, request.durationMs),\n getReceipt: (id) => op((conn) => receipt(conn, id)),\n claimPendingEffects: (request) =>\n op(async (conn) => {\n if (!Number.isSafeInteger(request.limit) || request.limit < 0)\n fail(\"Invalid effect claim limit\");\n const effects = (await rows<Reaction>(conn, \"reaction\"))\n .filter(\n (reaction) =>\n request.eventId === undefined ||\n reaction.eventId === request.eventId,\n )\n .flatMap((reaction) => reaction.effects)\n .sort((left, right) => left.id.localeCompare(right.id));\n const pending: PendingEffectClaim[] = [];\n const now = await clock(conn);\n for (const effect of effects) {\n if (pending.length >= request.limit) break;\n const delivered = await get<EffectDeliveryReceipt>(\n conn,\n \"delivery\",\n effect.id,\n );\n if (\n delivered &&\n (delivered.status !== \"retryable-failed\" ||\n (delivered.nextRetryAt !== undefined &&\n Date.parse(delivered.nextRetryAt) > now))\n )\n continue;\n const current = await leaseRow(conn, \"effect\", effect.id);\n if (current && current.expires_ms > now) continue;\n const previous = await one<{ attempt: unknown }>(\n conn,\n \"SELECT attempt FROM openmatter_store_leases WHERE tenant_id=? AND kind='effect' AND id=?\",\n [tenantId, effect.id],\n );\n const attempt =\n Math.max(\n asNumber(previous?.attempt ?? 0),\n delivered?.attempt ?? 0,\n ) + 1;\n pending.push({\n effect,\n attempt,\n lease: await acquire(conn, \"effect\", effect.id, request, attempt),\n });\n }\n return pending;\n }, true),\n recordDelivery: (value, token) =>\n op(async (conn) => {\n await fence(conn, \"effect\", value.effectId, token);\n await put(conn, \"delivery\", value.effectId, value);\n await release(conn, \"effect\", value.effectId);\n }, true),\n renewEffectLease: (id, token, request) =>\n renew(\"effect\", id, token, request.durationMs),\n claimSession: (key, request) =>\n op(async (conn) => {\n const current = await leaseRow(conn, \"session\", key);\n if (current && current.expires_ms > (await clock(conn)))\n return { _tag: \"Busy\" as const, lease: asLease(current) };\n const session = await activeSession(conn, key);\n return {\n _tag: \"Acquired\" as const,\n lease: await acquire(conn, \"session\", key, request),\n ...(session ? { session } : {}),\n };\n }, true),\n saveSession: (session, token) =>\n op(async (conn) => {\n await fence(conn, \"session\", session.bindingKey, token);\n const previous = await activeSession(conn, session.bindingKey);\n if (\n previous &&\n previous.id !== session.id &&\n [\"open\", \"creating\"].includes(previous.state)\n )\n await put(\n conn,\n \"session\",\n previous.id,\n { ...previous, state: \"closed\" },\n previous.scopeId,\n previous.bindingKey,\n );\n await put(\n conn,\n \"session\",\n session.id,\n session,\n session.scopeId,\n session.bindingKey,\n );\n await conn.query(\n `INSERT INTO openmatter_store_bindings (tenant_id, binding_key, session_id) VALUES (?,?,?)\n ON DUPLICATE KEY UPDATE session_id=VALUES(session_id)`,\n [tenantId, session.bindingKey, session.id],\n );\n }, true),\n getSession: (id) => op((conn) => get<AgentSession>(conn, \"session\", id)),\n renewSessionLease: (key, token, request) =>\n renew(\"session\", key, token, request.durationMs),\n releaseSession: (key, token) =>\n op(async (conn) => {\n await fence(conn, \"session\", key, token);\n await release(conn, \"session\", key);\n }, true),\n saveTurn: (turn, key, token) =>\n op(async (conn) => {\n await fence(conn, \"session\", key, token);\n if (\n (await get<AgentSession>(conn, \"session\", turn.sessionId))\n ?.bindingKey !== key\n )\n fail(\"Turn belongs to another session binding\");\n const terminal = (\n await rows<OpenMAEvent>(conn, \"agentEvent\", \"AND parent_id=?\", [\n turn.id,\n ])\n ).find((event) =>\n [\n \"turn.completed\",\n \"turn.failed\",\n \"turn.cancelled\",\n \"turn.interrupted\",\n ].includes(event.type),\n );\n if (\n terminal &&\n turn.state !==\n (terminal.type === \"turn.interrupted\"\n ? \"cancelled\"\n : terminal.type.slice(5))\n )\n return;\n await put(conn, \"turn\", turn.id, turn, null, turn.sessionId);\n }, true),\n getTurn: (id) => op((conn) => get<Turn>(conn, \"turn\", id)),\n requestTurnCancellation: (key, eventId, at) =>\n op(async (conn) => {\n const session = await activeSession(conn, key);\n if (!session) return undefined;\n const turn = (\n await rows<Turn>(conn, \"turn\", \"AND parent_id=?\", [session.id])\n )\n .filter((item) => item.state === \"queued\" || item.state === \"running\")\n .sort((left, right) =>\n right.createdAt.localeCompare(left.createdAt),\n )[0];\n if (!turn) return undefined;\n const existing = await get<TurnCancellationRequest>(\n conn,\n \"cancellation\",\n turn.id,\n );\n if (existing) return existing;\n const value = {\n turnId: turn.id,\n sessionId: session.id,\n bindingKey: key,\n requestedByEventId: eventId,\n requestedAt: at,\n };\n await put(conn, \"cancellation\", turn.id, value);\n return value;\n }, true),\n getTurnCancellation: (id) =>\n op((conn) => get<TurnCancellationRequest>(conn, \"cancellation\", id)),\n getAgentEvents: (id) =>\n op(async (conn) =>\n (\n await rows<OpenMAEvent>(conn, \"agentEvent\", \"AND parent_id=?\", [id])\n ).sort((left, right) => (left.seq ?? 0) - (right.seq ?? 0)),\n ),\n getPermissionDecision: (turnId, requestId) =>\n op((conn) =>\n get<PermissionDecision>(\n conn,\n \"permission\",\n JSON.stringify([turnId, requestId]),\n ),\n ),\n commitPermissionDecision: (decision, key, token) =>\n op(async (conn) => {\n await fence(conn, \"session\", key, token);\n const turn = await get<Turn>(conn, \"turn\", decision.turnId);\n if (\n !turn ||\n (await get<AgentSession>(conn, \"session\", turn.sessionId))\n ?.bindingKey !== key\n )\n fail(\"Permission belongs to another session binding\");\n const id = JSON.stringify([decision.turnId, decision.requestId]);\n const existing = await get<PermissionDecision>(conn, \"permission\", id);\n if (existing) return existing;\n await put(conn, \"permission\", id, decision);\n return (await get<PermissionDecision>(conn, \"permission\", id))!;\n }, true),\n getOperationCall: (turnId, callId) =>\n op((conn) =>\n get<OperationCall>(\n conn,\n \"operationCall\",\n JSON.stringify([turnId, callId]),\n ),\n ),\n beginOperationCall: (call, key, token) =>\n casOp(async (conn) => {\n await fence(conn, \"session\", key, token);\n const turn = await get<Turn>(conn, \"turn\", call.turnId);\n if (\n !turn ||\n (await get<AgentSession>(conn, \"session\", turn.sessionId))\n ?.bindingKey !== key\n )\n fail(\"Operation call belongs to another session binding\");\n const id = JSON.stringify([call.turnId, call.callId]);\n const existing = await get<OperationCall>(conn, \"operationCall\", id);\n if (existing) return existing;\n if (call.conversation !== undefined) {\n const actual = await conversationRevision(\n conn,\n call.conversation.key,\n );\n if (actual !== call.conversation.revision) {\n throw new ConversationChangedError({\n conversationKey: call.conversation.key,\n expected: call.conversation.revision,\n actual,\n });\n }\n }\n await put(conn, \"operationCall\", id, call);\n return (await get<OperationCall>(conn, \"operationCall\", id))!;\n }),\n recordConversationEntry: (input) =>\n op(async (conn) => {\n const existing = await get<ConversationEntry>(\n conn,\n \"conversationEntry\",\n input.eventId,\n );\n if (existing) return existing;\n const revision =\n (await conversationRevision(conn, input.conversationKey)) + 1;\n const entry: ConversationEntry = { ...input, revision };\n await put(\n conn,\n \"conversationEntry\",\n input.eventId,\n entry,\n null,\n input.conversationKey,\n JSON.stringify([input.conversationKey, revision]),\n );\n return entry;\n }, true),\n getConversationEntry: (eventId) =>\n op((conn) => get<ConversationEntry>(conn, \"conversationEntry\", eventId)),\n findConversationMessage: (key, messageId) =>\n op(async (conn) =>\n (await conversationLog(conn, key)).findLast(\n (e) => e.kind !== \"recall\" && e.messageId === messageId,\n ),\n ),\n listConversationEntries: (key, afterRevision) =>\n op(async (conn) =>\n (await conversationLog(conn, key))\n .filter((e) => e.revision > afterRevision)\n .sort((a, b) => a.revision - b.revision),\n ),\n completeOperationCall: (turnId, callId, result, completedAt, key, token) =>\n op(async (conn) => {\n await fence(conn, \"session\", key, token);\n const id = JSON.stringify([turnId, callId]);\n const existing = await get<OperationCall>(conn, \"operationCall\", id);\n if (!existing) fail(`Unknown operation call: ${turnId}/${callId}`);\n if (existing!.state === \"completed\") return existing!;\n await put(conn, \"operationCall\", id, {\n ...existing!,\n state: \"completed\",\n result,\n completedAt,\n });\n return (await get<OperationCall>(conn, \"operationCall\", id))!;\n }, true),\n appendAgentEvent: (event, key, token) =>\n op(async (conn) => {\n await fence(conn, \"session\", key, token);\n const turnId = event.turn_id;\n if (!turnId || event.seq === undefined)\n return fail(\"Agent event requires turn identity and sequence\");\n if (\n (await get<AgentSession>(conn, \"session\", event.session_id))\n ?.bindingKey !== key ||\n (await get<Turn>(conn, \"turn\", turnId))?.sessionId !==\n event.session_id\n )\n return fail(\"Agent event belongs to another session binding\");\n const id = JSON.stringify([turnId, event.seq]);\n const existing = await get<OpenMAEvent>(conn, \"agentEvent\", id);\n if (existing) {\n if (encode(existing) !== encode(event))\n fail(\"Conflicting Agent event sequence\");\n return;\n }\n await put(conn, \"agentEvent\", id, event, null, turnId, event.event_id);\n }, true),\n saveContext: (context) =>\n op(async (conn) => {\n await put(\n conn,\n \"context\",\n context.id,\n context,\n context.scopeId,\n context.workThreadId,\n );\n }, true),\n getContext: (id) =>\n op((conn) => get<ContextProjection>(conn, \"context\", id)),\n };\n return store;\n};\n"],"mappings":";;;;;;AAwDA,MAAM,8BAAc,IAAI,QAAc;AAEtC,MAAM,SAAS;CACb;;;;;;;;;;;;;;;CAeA;;;;;;;;;;;CAWA;;;;;;AAMF;AAEA,MAAM,YAAY,UAChB,OAAO,UAAU,WAAW,OAAO,KAAK,IAAI,OAAO,KAAK;;AAG1D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AI;EACT,mBAAmB,OAAO,KAAK,UAC7B,GAAG,OAAO,SAAS;GACjB,MAAM,MAAM,MAAM,WAAW,KAAK,KAAK;GACvC,MAAM,SAAS,MAAM;GACrB,IAAI,CAAC,UAAU,MAAM,QAAQ,KAAA,GAC3B,OAAO,KAAK,iDAAiD;GAC/D,KACG,MAAM,IAAkB,MAAM,WAAW,MAAM,UAAU,EAAA,EACtD,eAAe,QAClB,MAAM,IAAU,MAAM,QAAQ,MAAM,EAAA,EAAI,cACvC,MAAM,YAER,OAAO,KAAK,gDAAgD;GAC9D,MAAM,KAAK,KAAK,UAAU,CAAC,QAAQ,MAAM,GAAG,CAAC;GAC7C,MAAM,WAAW,MAAM,IAAiB,MAAM,cAAc,EAAE;GAC9D,IAAI,UAAU;IACZ,IAAI,OAAO,QAAQ,MAAM,OAAO,KAAK,GACnC,KAAK,kCAAkC;IACzC;GACF;GACA,MAAM,IAAI,MAAM,cAAc,IAAI,OAAO,MAAM,QAAQ,MAAM,QAAQ;EACvE,GAAG,IAAI;EACT,cAAc,YACZ,GAAG,OAAO,SAAS;GACjB,MAAM,IACJ,MACA,WACA,QAAQ,IACR,SACA,QAAQ,SACR,QAAQ,YACV;EACF,GAAG,IAAI;EACT,aAAa,OACX,IAAI,SAAS,IAAuB,MAAM,WAAW,EAAE,CAAC;CAEjD;AACb"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openma/matter-store-mysql",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.5",
|
|
4
|
+
"description": "MySQL store for OpenMatter: many host replicas share one database, partitioned by tenant.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/openma-ai/OpenMatter.git",
|
|
9
|
+
"directory": "packages/store-mysql"
|
|
10
|
+
},
|
|
11
|
+
"type": "module",
|
|
12
|
+
"sideEffects": false,
|
|
13
|
+
"files": [
|
|
14
|
+
"dist"
|
|
15
|
+
],
|
|
16
|
+
"main": "./dist/index.js",
|
|
17
|
+
"module": "./dist/index.js",
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"import": "./dist/index.js"
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public",
|
|
27
|
+
"provenance": true
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"mysql2": "3.15.3",
|
|
31
|
+
"@openma/matter": "0.2.5"
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"effect": "^3.22.1"
|
|
35
|
+
},
|
|
36
|
+
"engines": {
|
|
37
|
+
"node": ">=22.13"
|
|
38
|
+
}
|
|
6
39
|
}
|
package/README.md
DELETED