@codemem/core 0.22.0-alpha.0 → 0.22.0-alpha.2

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.
Files changed (42) hide show
  1. package/dist/better-sqlite-coordinator-runtime.d.ts +7 -0
  2. package/dist/better-sqlite-coordinator-runtime.d.ts.map +1 -0
  3. package/dist/better-sqlite-coordinator-store.d.ts +42 -0
  4. package/dist/better-sqlite-coordinator-store.d.ts.map +1 -0
  5. package/dist/coordinator-actions.d.ts +10 -9
  6. package/dist/coordinator-actions.d.ts.map +1 -1
  7. package/dist/coordinator-api-By9BNOCL.js +2397 -0
  8. package/dist/coordinator-api-By9BNOCL.js.map +1 -0
  9. package/dist/coordinator-api.d.ts +10 -3
  10. package/dist/coordinator-api.d.ts.map +1 -1
  11. package/dist/coordinator-store-contract.d.ts +112 -0
  12. package/dist/coordinator-store-contract.d.ts.map +1 -0
  13. package/dist/coordinator-store-test-harness.d.ts +7 -0
  14. package/dist/coordinator-store-test-harness.d.ts.map +1 -0
  15. package/dist/coordinator-store.d.ts +2 -66
  16. package/dist/coordinator-store.d.ts.map +1 -1
  17. package/dist/d1-coordinator-runtime.d.ts +9 -0
  18. package/dist/d1-coordinator-runtime.d.ts.map +1 -0
  19. package/dist/d1-coordinator-store.d.ts +46 -0
  20. package/dist/d1-coordinator-store.d.ts.map +1 -0
  21. package/dist/db.d.ts.map +1 -1
  22. package/dist/index.d.ts +10 -4
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +2365 -4531
  25. package/dist/index.js.map +1 -1
  26. package/dist/internal/cloudflare-coordinator.d.ts +5 -0
  27. package/dist/internal/cloudflare-coordinator.d.ts.map +1 -0
  28. package/dist/internal/cloudflare-coordinator.js +193 -0
  29. package/dist/internal/cloudflare-coordinator.js.map +1 -0
  30. package/dist/schema.d.ts +38 -0
  31. package/dist/schema.d.ts.map +1 -1
  32. package/dist/store.d.ts +9 -0
  33. package/dist/store.d.ts.map +1 -1
  34. package/dist/sync-bootstrap.d.ts +50 -0
  35. package/dist/sync-bootstrap.d.ts.map +1 -0
  36. package/dist/sync-daemon.d.ts +11 -0
  37. package/dist/sync-daemon.d.ts.map +1 -1
  38. package/dist/sync-http-client.d.ts.map +1 -1
  39. package/dist/sync-pass.d.ts.map +1 -1
  40. package/dist/test-schema.generated.d.ts +1 -1
  41. package/dist/test-schema.generated.d.ts.map +1 -1
  42. package/package.json +6 -1
@@ -0,0 +1,2397 @@
1
+ import { createHash as e, createPrivateKey as t, createPublicKey as n, generateKeyPairSync as r, randomBytes as i, randomUUID as a, sign as o, verify as s } from "node:crypto";
2
+ import { copyFileSync as c, existsSync as l, mkdirSync as u, readFileSync as d, renameSync as f, unlinkSync as p, writeFileSync as m } from "node:fs";
3
+ import { homedir as h } from "node:os";
4
+ import { dirname as g, join as _ } from "node:path";
5
+ import v from "better-sqlite3";
6
+ import { eq as ee, lt as te } from "drizzle-orm";
7
+ import { drizzle as y } from "drizzle-orm/better-sqlite3";
8
+ import { index as b, integer as x, primaryKey as ne, real as re, sqliteTable as S, text as C, uniqueIndex as ie } from "drizzle-orm/sqlite-core";
9
+ import { execFileSync as w } from "node:child_process";
10
+ import * as ae from "sqlite-vec";
11
+ //#region \0rolldown/runtime.js
12
+ var oe = Object.defineProperty, se = (e, t) => {
13
+ let n = {};
14
+ for (var r in e) oe(n, r, {
15
+ get: e[r],
16
+ enumerable: !0
17
+ });
18
+ return t || oe(n, Symbol.toStringTag, { value: "Module" }), n;
19
+ }, ce = (e, t, n) => (r, i) => {
20
+ let a = -1;
21
+ return o(0);
22
+ async function o(s) {
23
+ if (s <= a) throw Error("next() called multiple times");
24
+ a = s;
25
+ let c, l = !1, u;
26
+ if (e[s] ? (u = e[s][0][0], r.req.routeIndex = s) : u = s === e.length && i || void 0, u) try {
27
+ c = await u(r, () => o(s + 1));
28
+ } catch (e) {
29
+ if (e instanceof Error && t) r.error = e, c = await t(e, r), l = !0;
30
+ else throw e;
31
+ }
32
+ else r.finalized === !1 && n && (c = await n(r));
33
+ return c && (r.finalized === !1 || l) && (r.res = c), r;
34
+ }
35
+ }, le = /* @__PURE__ */ Symbol(), ue = async (e, t = /* @__PURE__ */ Object.create(null)) => {
36
+ let { all: n = !1, dot: r = !1 } = t, i = (e instanceof je ? e.raw.headers : e.headers).get("Content-Type");
37
+ return i?.startsWith("multipart/form-data") || i?.startsWith("application/x-www-form-urlencoded") ? de(e, {
38
+ all: n,
39
+ dot: r
40
+ }) : {};
41
+ };
42
+ async function de(e, t) {
43
+ let n = await e.formData();
44
+ return n ? fe(n, t) : {};
45
+ }
46
+ function fe(e, t) {
47
+ let n = /* @__PURE__ */ Object.create(null);
48
+ return e.forEach((e, r) => {
49
+ t.all || r.endsWith("[]") ? pe(n, r, e) : n[r] = e;
50
+ }), t.dot && Object.entries(n).forEach(([e, t]) => {
51
+ e.includes(".") && (me(n, e, t), delete n[e]);
52
+ }), n;
53
+ }
54
+ var pe = (e, t, n) => {
55
+ e[t] === void 0 ? t.endsWith("[]") ? e[t] = [n] : e[t] = n : Array.isArray(e[t]) ? e[t].push(n) : e[t] = [e[t], n];
56
+ }, me = (e, t, n) => {
57
+ if (/(?:^|\.)__proto__\./.test(t)) return;
58
+ let r = e, i = t.split(".");
59
+ i.forEach((e, t) => {
60
+ t === i.length - 1 ? r[e] = n : ((!r[e] || typeof r[e] != "object" || Array.isArray(r[e]) || r[e] instanceof File) && (r[e] = /* @__PURE__ */ Object.create(null)), r = r[e]);
61
+ });
62
+ }, he = (e) => {
63
+ let t = e.split("/");
64
+ return t[0] === "" && t.shift(), t;
65
+ }, ge = (e) => {
66
+ let { groups: t, path: n } = _e(e);
67
+ return ve(he(n), t);
68
+ }, _e = (e) => {
69
+ let t = [];
70
+ return e = e.replace(/\{[^}]+\}/g, (e, n) => {
71
+ let r = `@${n}`;
72
+ return t.push([r, e]), r;
73
+ }), {
74
+ groups: t,
75
+ path: e
76
+ };
77
+ }, ve = (e, t) => {
78
+ for (let n = t.length - 1; n >= 0; n--) {
79
+ let [r] = t[n];
80
+ for (let i = e.length - 1; i >= 0; i--) if (e[i].includes(r)) {
81
+ e[i] = e[i].replace(r, t[n][1]);
82
+ break;
83
+ }
84
+ }
85
+ return e;
86
+ }, T = {}, ye = (e, t) => {
87
+ if (e === "*") return "*";
88
+ let n = e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
89
+ if (n) {
90
+ let r = `${e}#${t}`;
91
+ return T[r] || (n[2] ? T[r] = t && t[0] !== ":" && t[0] !== "*" ? [
92
+ r,
93
+ n[1],
94
+ RegExp(`^${n[2]}(?=/${t})`)
95
+ ] : [
96
+ e,
97
+ n[1],
98
+ RegExp(`^${n[2]}$`)
99
+ ] : T[r] = [
100
+ e,
101
+ n[1],
102
+ !0
103
+ ]), T[r];
104
+ }
105
+ return null;
106
+ }, be = (e, t) => {
107
+ try {
108
+ return t(e);
109
+ } catch {
110
+ return e.replace(/(?:%[0-9A-Fa-f]{2})+/g, (e) => {
111
+ try {
112
+ return t(e);
113
+ } catch {
114
+ return e;
115
+ }
116
+ });
117
+ }
118
+ }, xe = (e) => be(e, decodeURI), Se = (e) => {
119
+ let t = e.url, n = t.indexOf("/", t.indexOf(":") + 4), r = n;
120
+ for (; r < t.length; r++) {
121
+ let e = t.charCodeAt(r);
122
+ if (e === 37) {
123
+ let e = t.indexOf("?", r), i = t.indexOf("#", r), a = e === -1 ? i === -1 ? void 0 : i : i === -1 ? e : Math.min(e, i), o = t.slice(n, a);
124
+ return xe(o.includes("%25") ? o.replace(/%25/g, "%2525") : o);
125
+ } else if (e === 63 || e === 35) break;
126
+ }
127
+ return t.slice(n, r);
128
+ }, Ce = (e) => {
129
+ let t = Se(e);
130
+ return t.length > 1 && t.at(-1) === "/" ? t.slice(0, -1) : t;
131
+ }, E = (e, t, ...n) => (n.length && (t = E(t, ...n)), `${e?.[0] === "/" ? "" : "/"}${e}${t === "/" ? "" : `${e?.at(-1) === "/" ? "" : "/"}${t?.[0] === "/" ? t.slice(1) : t}`}`), we = (e) => {
132
+ if (e.charCodeAt(e.length - 1) !== 63 || !e.includes(":")) return null;
133
+ let t = e.split("/"), n = [], r = "";
134
+ return t.forEach((e) => {
135
+ if (e !== "" && !/\:/.test(e)) r += "/" + e;
136
+ else if (/\:/.test(e)) if (/\?/.test(e)) {
137
+ n.length === 0 && r === "" ? n.push("/") : n.push(r);
138
+ let t = e.replace("?", "");
139
+ r += "/" + t, n.push(r);
140
+ } else r += "/" + e;
141
+ }), n.filter((e, t, n) => n.indexOf(e) === t);
142
+ }, Te = (e) => /[%+]/.test(e) ? (e.indexOf("+") !== -1 && (e = e.replace(/\+/g, " ")), e.indexOf("%") === -1 ? e : be(e, ke)) : e, Ee = (e, t, n) => {
143
+ let r;
144
+ if (!n && t && !/[%+]/.test(t)) {
145
+ let n = e.indexOf("?", 8);
146
+ if (n === -1) return;
147
+ for (e.startsWith(t, n + 1) || (n = e.indexOf(`&${t}`, n + 1)); n !== -1;) {
148
+ let r = e.charCodeAt(n + t.length + 1);
149
+ if (r === 61) {
150
+ let r = n + t.length + 2, i = e.indexOf("&", r);
151
+ return Te(e.slice(r, i === -1 ? void 0 : i));
152
+ } else if (r == 38 || isNaN(r)) return "";
153
+ n = e.indexOf(`&${t}`, n + 1);
154
+ }
155
+ if (r = /[%+]/.test(e), !r) return;
156
+ }
157
+ let i = {};
158
+ r ??= /[%+]/.test(e);
159
+ let a = e.indexOf("?", 8);
160
+ for (; a !== -1;) {
161
+ let t = e.indexOf("&", a + 1), o = e.indexOf("=", a);
162
+ o > t && t !== -1 && (o = -1);
163
+ let s = e.slice(a + 1, o === -1 ? t === -1 ? void 0 : t : o);
164
+ if (r && (s = Te(s)), a = t, s === "") continue;
165
+ let c;
166
+ o === -1 ? c = "" : (c = e.slice(o + 1, t === -1 ? void 0 : t), r && (c = Te(c))), n ? (i[s] && Array.isArray(i[s]) || (i[s] = []), i[s].push(c)) : i[s] ??= c;
167
+ }
168
+ return t ? i[t] : i;
169
+ }, De = Ee, Oe = (e, t) => Ee(e, t, !0), ke = decodeURIComponent, Ae = (e) => be(e, ke), je = class {
170
+ raw;
171
+ #e;
172
+ #t;
173
+ routeIndex = 0;
174
+ path;
175
+ bodyCache = {};
176
+ constructor(e, t = "/", n = [[]]) {
177
+ this.raw = e, this.path = t, this.#t = n, this.#e = {};
178
+ }
179
+ param(e) {
180
+ return e ? this.#n(e) : this.#r();
181
+ }
182
+ #n(e) {
183
+ let t = this.#t[0][this.routeIndex][1][e], n = this.#i(t);
184
+ return n && /\%/.test(n) ? Ae(n) : n;
185
+ }
186
+ #r() {
187
+ let e = {}, t = Object.keys(this.#t[0][this.routeIndex][1]);
188
+ for (let n of t) {
189
+ let t = this.#i(this.#t[0][this.routeIndex][1][n]);
190
+ t !== void 0 && (e[n] = /\%/.test(t) ? Ae(t) : t);
191
+ }
192
+ return e;
193
+ }
194
+ #i(e) {
195
+ return this.#t[1] ? this.#t[1][e] : e;
196
+ }
197
+ query(e) {
198
+ return De(this.url, e);
199
+ }
200
+ queries(e) {
201
+ return Oe(this.url, e);
202
+ }
203
+ header(e) {
204
+ if (e) return this.raw.headers.get(e) ?? void 0;
205
+ let t = {};
206
+ return this.raw.headers.forEach((e, n) => {
207
+ t[n] = e;
208
+ }), t;
209
+ }
210
+ async parseBody(e) {
211
+ return this.bodyCache.parsedBody ??= await ue(this, e);
212
+ }
213
+ #a = (e) => {
214
+ let { bodyCache: t, raw: n } = this, r = t[e];
215
+ if (r) return r;
216
+ let i = Object.keys(t)[0];
217
+ return i ? t[i].then((t) => (i === "json" && (t = JSON.stringify(t)), new Response(t)[e]())) : t[e] = n[e]();
218
+ };
219
+ json() {
220
+ return this.#a("text").then((e) => JSON.parse(e));
221
+ }
222
+ text() {
223
+ return this.#a("text");
224
+ }
225
+ arrayBuffer() {
226
+ return this.#a("arrayBuffer");
227
+ }
228
+ blob() {
229
+ return this.#a("blob");
230
+ }
231
+ formData() {
232
+ return this.#a("formData");
233
+ }
234
+ addValidatedData(e, t) {
235
+ this.#e[e] = t;
236
+ }
237
+ valid(e) {
238
+ return this.#e[e];
239
+ }
240
+ get url() {
241
+ return this.raw.url;
242
+ }
243
+ get method() {
244
+ return this.raw.method;
245
+ }
246
+ get [le]() {
247
+ return this.#t;
248
+ }
249
+ get matchedRoutes() {
250
+ return this.#t[0].map(([[, e]]) => e);
251
+ }
252
+ get routePath() {
253
+ return this.#t[0].map(([[, e]]) => e)[this.routeIndex].path;
254
+ }
255
+ }, Me = {
256
+ Stringify: 1,
257
+ BeforeStream: 2,
258
+ Stream: 3
259
+ }, Ne = (e, t) => {
260
+ let n = new String(e);
261
+ return n.isEscaped = !0, n.callbacks = t, n;
262
+ }, Pe = async (e, t, n, r, i) => {
263
+ typeof e == "object" && !(e instanceof String) && (e instanceof Promise || (e = e.toString()), e instanceof Promise && (e = await e));
264
+ let a = e.callbacks;
265
+ if (!a?.length) return Promise.resolve(e);
266
+ i ? i[0] += e : i = [e];
267
+ let o = Promise.all(a.map((e) => e({
268
+ phase: t,
269
+ buffer: i,
270
+ context: r
271
+ }))).then((e) => Promise.all(e.filter(Boolean).map((e) => Pe(e, t, !1, r, i))).then(() => i[0]));
272
+ return n ? Ne(await o, a) : o;
273
+ }, Fe = "text/plain; charset=UTF-8", D = (e, t) => ({
274
+ "Content-Type": e,
275
+ ...t
276
+ }), O = (e, t) => new Response(e, t), Ie = class {
277
+ #e;
278
+ #t;
279
+ env = {};
280
+ #n;
281
+ finalized = !1;
282
+ error;
283
+ #r;
284
+ #i;
285
+ #a;
286
+ #o;
287
+ #s;
288
+ #c;
289
+ #l;
290
+ #u;
291
+ #d;
292
+ constructor(e, t) {
293
+ this.#e = e, t && (this.#i = t.executionCtx, this.env = t.env, this.#c = t.notFoundHandler, this.#d = t.path, this.#u = t.matchResult);
294
+ }
295
+ get req() {
296
+ return this.#t ??= new je(this.#e, this.#d, this.#u), this.#t;
297
+ }
298
+ get event() {
299
+ if (this.#i && "respondWith" in this.#i) return this.#i;
300
+ throw Error("This context has no FetchEvent");
301
+ }
302
+ get executionCtx() {
303
+ if (this.#i) return this.#i;
304
+ throw Error("This context has no ExecutionContext");
305
+ }
306
+ get res() {
307
+ return this.#a ||= O(null, { headers: this.#l ??= new Headers() });
308
+ }
309
+ set res(e) {
310
+ if (this.#a && e) {
311
+ e = O(e.body, e);
312
+ for (let [t, n] of this.#a.headers.entries()) if (t !== "content-type") if (t === "set-cookie") {
313
+ let t = this.#a.headers.getSetCookie();
314
+ e.headers.delete("set-cookie");
315
+ for (let n of t) e.headers.append("set-cookie", n);
316
+ } else e.headers.set(t, n);
317
+ }
318
+ this.#a = e, this.finalized = !0;
319
+ }
320
+ render = (...e) => (this.#s ??= (e) => this.html(e), this.#s(...e));
321
+ setLayout = (e) => this.#o = e;
322
+ getLayout = () => this.#o;
323
+ setRenderer = (e) => {
324
+ this.#s = e;
325
+ };
326
+ header = (e, t, n) => {
327
+ this.finalized && (this.#a = O(this.#a.body, this.#a));
328
+ let r = this.#a ? this.#a.headers : this.#l ??= new Headers();
329
+ t === void 0 ? r.delete(e) : n?.append ? r.append(e, t) : r.set(e, t);
330
+ };
331
+ status = (e) => {
332
+ this.#r = e;
333
+ };
334
+ set = (e, t) => {
335
+ this.#n ??= /* @__PURE__ */ new Map(), this.#n.set(e, t);
336
+ };
337
+ get = (e) => this.#n ? this.#n.get(e) : void 0;
338
+ get var() {
339
+ return this.#n ? Object.fromEntries(this.#n) : {};
340
+ }
341
+ #f(e, t, n) {
342
+ let r = this.#a ? new Headers(this.#a.headers) : this.#l ?? new Headers();
343
+ if (typeof t == "object" && "headers" in t) {
344
+ let e = t.headers instanceof Headers ? t.headers : new Headers(t.headers);
345
+ for (let [t, n] of e) t.toLowerCase() === "set-cookie" ? r.append(t, n) : r.set(t, n);
346
+ }
347
+ if (n) for (let [e, t] of Object.entries(n)) if (typeof t == "string") r.set(e, t);
348
+ else {
349
+ r.delete(e);
350
+ for (let n of t) r.append(e, n);
351
+ }
352
+ return O(e, {
353
+ status: typeof t == "number" ? t : t?.status ?? this.#r,
354
+ headers: r
355
+ });
356
+ }
357
+ newResponse = (...e) => this.#f(...e);
358
+ body = (e, t, n) => this.#f(e, t, n);
359
+ text = (e, t, n) => !this.#l && !this.#r && !t && !n && !this.finalized ? new Response(e) : this.#f(e, t, D(Fe, n));
360
+ json = (e, t, n) => this.#f(JSON.stringify(e), t, D("application/json", n));
361
+ html = (e, t, n) => {
362
+ let r = (e) => this.#f(e, t, D("text/html; charset=UTF-8", n));
363
+ return typeof e == "object" ? Pe(e, Me.Stringify, !1, {}).then(r) : r(e);
364
+ };
365
+ redirect = (e, t) => {
366
+ let n = String(e);
367
+ return this.header("Location", /[^\x00-\xFF]/.test(n) ? encodeURI(n) : n), this.newResponse(null, t ?? 302);
368
+ };
369
+ notFound = () => (this.#c ??= () => O(), this.#c(this));
370
+ }, Le = [
371
+ "get",
372
+ "post",
373
+ "put",
374
+ "delete",
375
+ "options",
376
+ "patch"
377
+ ], Re = "Can not add a route since the matcher is already built.", ze = class extends Error {}, Be = "__COMPOSED_HANDLER", Ve = (e) => e.text("404 Not Found", 404), He = (e, t) => {
378
+ if ("getResponse" in e) {
379
+ let n = e.getResponse();
380
+ return t.newResponse(n.body, n);
381
+ }
382
+ return console.error(e), t.text("Internal Server Error", 500);
383
+ }, Ue = class e {
384
+ get;
385
+ post;
386
+ put;
387
+ delete;
388
+ options;
389
+ patch;
390
+ all;
391
+ on;
392
+ use;
393
+ router;
394
+ getPath;
395
+ _basePath = "/";
396
+ #e = "/";
397
+ routes = [];
398
+ constructor(e = {}) {
399
+ [...Le, "all"].forEach((e) => {
400
+ this[e] = (t, ...n) => (typeof t == "string" ? this.#e = t : this.#r(e, this.#e, t), n.forEach((t) => {
401
+ this.#r(e, this.#e, t);
402
+ }), this);
403
+ }), this.on = (e, t, ...n) => {
404
+ for (let r of [t].flat()) {
405
+ this.#e = r;
406
+ for (let t of [e].flat()) n.map((e) => {
407
+ this.#r(t.toUpperCase(), this.#e, e);
408
+ });
409
+ }
410
+ return this;
411
+ }, this.use = (e, ...t) => (typeof e == "string" ? this.#e = e : (this.#e = "*", t.unshift(e)), t.forEach((e) => {
412
+ this.#r("ALL", this.#e, e);
413
+ }), this);
414
+ let { strict: t, ...n } = e;
415
+ Object.assign(this, n), this.getPath = t ?? !0 ? e.getPath ?? Se : Ce;
416
+ }
417
+ #t() {
418
+ let t = new e({
419
+ router: this.router,
420
+ getPath: this.getPath
421
+ });
422
+ return t.errorHandler = this.errorHandler, t.#n = this.#n, t.routes = this.routes, t;
423
+ }
424
+ #n = Ve;
425
+ errorHandler = He;
426
+ route(e, t) {
427
+ let n = this.basePath(e);
428
+ return t.routes.map((e) => {
429
+ let r;
430
+ t.errorHandler === He ? r = e.handler : (r = async (n, r) => (await ce([], t.errorHandler)(n, () => e.handler(n, r))).res, r[Be] = e.handler), n.#r(e.method, e.path, r);
431
+ }), this;
432
+ }
433
+ basePath(e) {
434
+ let t = this.#t();
435
+ return t._basePath = E(this._basePath, e), t;
436
+ }
437
+ onError = (e) => (this.errorHandler = e, this);
438
+ notFound = (e) => (this.#n = e, this);
439
+ mount(e, t, n) {
440
+ let r, i;
441
+ n && (typeof n == "function" ? i = n : (i = n.optionHandler, r = n.replaceRequest === !1 ? (e) => e : n.replaceRequest));
442
+ let a = i ? (e) => {
443
+ let t = i(e);
444
+ return Array.isArray(t) ? t : [t];
445
+ } : (e) => {
446
+ let t;
447
+ try {
448
+ t = e.executionCtx;
449
+ } catch {}
450
+ return [e.env, t];
451
+ };
452
+ return r ||= (() => {
453
+ let t = E(this._basePath, e), n = t === "/" ? 0 : t.length;
454
+ return (e) => {
455
+ let t = new URL(e.url);
456
+ return t.pathname = t.pathname.slice(n) || "/", new Request(t, e);
457
+ };
458
+ })(), this.#r("ALL", E(e, "*"), async (e, n) => {
459
+ let i = await t(r(e.req.raw), ...a(e));
460
+ if (i) return i;
461
+ await n();
462
+ }), this;
463
+ }
464
+ #r(e, t, n) {
465
+ e = e.toUpperCase(), t = E(this._basePath, t);
466
+ let r = {
467
+ basePath: this._basePath,
468
+ path: t,
469
+ method: e,
470
+ handler: n
471
+ };
472
+ this.router.add(e, t, [n, r]), this.routes.push(r);
473
+ }
474
+ #i(e, t) {
475
+ if (e instanceof Error) return this.errorHandler(e, t);
476
+ throw e;
477
+ }
478
+ #a(e, t, n, r) {
479
+ if (r === "HEAD") return (async () => new Response(null, await this.#a(e, t, n, "GET")))();
480
+ let i = this.getPath(e, { env: n }), a = this.router.match(r, i), o = new Ie(e, {
481
+ path: i,
482
+ matchResult: a,
483
+ env: n,
484
+ executionCtx: t,
485
+ notFoundHandler: this.#n
486
+ });
487
+ if (a[0].length === 1) {
488
+ let e;
489
+ try {
490
+ e = a[0][0][0][0](o, async () => {
491
+ o.res = await this.#n(o);
492
+ });
493
+ } catch (e) {
494
+ return this.#i(e, o);
495
+ }
496
+ return e instanceof Promise ? e.then((e) => e || (o.finalized ? o.res : this.#n(o))).catch((e) => this.#i(e, o)) : e ?? this.#n(o);
497
+ }
498
+ let s = ce(a[0], this.errorHandler, this.#n);
499
+ return (async () => {
500
+ try {
501
+ let e = await s(o);
502
+ if (!e.finalized) throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
503
+ return e.res;
504
+ } catch (e) {
505
+ return this.#i(e, o);
506
+ }
507
+ })();
508
+ }
509
+ fetch = (e, ...t) => this.#a(e, t[1], t[0], e.method);
510
+ request = (e, t, n, r) => e instanceof Request ? this.fetch(t ? new Request(e, t) : e, n, r) : (e = e.toString(), this.fetch(new Request(/^https?:\/\//.test(e) ? e : `http://localhost${E("/", e)}`, t), n, r));
511
+ fire = () => {
512
+ addEventListener("fetch", (e) => {
513
+ e.respondWith(this.#a(e.request, e, void 0, e.request.method));
514
+ });
515
+ };
516
+ }, We = [];
517
+ function Ge(e, t) {
518
+ let n = this.buildAllMatchers(), r = ((e, t) => {
519
+ let r = n[e] || n.ALL, i = r[2][t];
520
+ if (i) return i;
521
+ let a = t.match(r[0]);
522
+ if (!a) return [[], We];
523
+ let o = a.indexOf("", 1);
524
+ return [r[1][o], a];
525
+ });
526
+ return this.match = r, r(e, t);
527
+ }
528
+ //#endregion
529
+ //#region ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/router/reg-exp-router/node.js
530
+ var k = "[^/]+", A = ".*", j = "(?:|/.*)", M = /* @__PURE__ */ Symbol(), Ke = /* @__PURE__ */ new Set(".\\+*[^]$()");
531
+ function qe(e, t) {
532
+ return e.length === 1 ? t.length === 1 ? e < t ? -1 : 1 : -1 : t.length === 1 || e === A || e === j ? 1 : t === A || t === j ? -1 : e === k ? 1 : t === k ? -1 : e.length === t.length ? e < t ? -1 : 1 : t.length - e.length;
533
+ }
534
+ var Je = class e {
535
+ #e;
536
+ #t;
537
+ #n = /* @__PURE__ */ Object.create(null);
538
+ insert(t, n, r, i, a) {
539
+ if (t.length === 0) {
540
+ if (this.#e !== void 0) throw M;
541
+ if (a) return;
542
+ this.#e = n;
543
+ return;
544
+ }
545
+ let [o, ...s] = t, c = o === "*" ? s.length === 0 ? [
546
+ "",
547
+ "",
548
+ A
549
+ ] : [
550
+ "",
551
+ "",
552
+ k
553
+ ] : o === "/*" ? [
554
+ "",
555
+ "",
556
+ j
557
+ ] : o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/), l;
558
+ if (c) {
559
+ let t = c[1], n = c[2] || k;
560
+ if (t && c[2] && (n === ".*" || (n = n.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:"), /\((?!\?:)/.test(n)))) throw M;
561
+ if (l = this.#n[n], !l) {
562
+ if (Object.keys(this.#n).some((e) => e !== A && e !== j)) throw M;
563
+ if (a) return;
564
+ l = this.#n[n] = new e(), t !== "" && (l.#t = i.varIndex++);
565
+ }
566
+ !a && t !== "" && r.push([t, l.#t]);
567
+ } else if (l = this.#n[o], !l) {
568
+ if (Object.keys(this.#n).some((e) => e.length > 1 && e !== A && e !== j)) throw M;
569
+ if (a) return;
570
+ l = this.#n[o] = new e();
571
+ }
572
+ l.insert(s, n, r, i, a);
573
+ }
574
+ buildRegExpStr() {
575
+ let e = Object.keys(this.#n).sort(qe).map((e) => {
576
+ let t = this.#n[e];
577
+ return (typeof t.#t == "number" ? `(${e})@${t.#t}` : Ke.has(e) ? `\\${e}` : e) + t.buildRegExpStr();
578
+ });
579
+ return typeof this.#e == "number" && e.unshift(`#${this.#e}`), e.length === 0 ? "" : e.length === 1 ? e[0] : "(?:" + e.join("|") + ")";
580
+ }
581
+ }, Ye = class {
582
+ #e = { varIndex: 0 };
583
+ #t = new Je();
584
+ insert(e, t, n) {
585
+ let r = [], i = [];
586
+ for (let t = 0;;) {
587
+ let n = !1;
588
+ if (e = e.replace(/\{[^}]+\}/g, (e) => {
589
+ let r = `@\\${t}`;
590
+ return i[t] = [r, e], t++, n = !0, r;
591
+ }), !n) break;
592
+ }
593
+ let a = e.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
594
+ for (let e = i.length - 1; e >= 0; e--) {
595
+ let [t] = i[e];
596
+ for (let n = a.length - 1; n >= 0; n--) if (a[n].indexOf(t) !== -1) {
597
+ a[n] = a[n].replace(t, i[e][1]);
598
+ break;
599
+ }
600
+ }
601
+ return this.#t.insert(a, t, r, this.#e, n), r;
602
+ }
603
+ buildRegExp() {
604
+ let e = this.#t.buildRegExpStr();
605
+ if (e === "") return [
606
+ /^$/,
607
+ [],
608
+ []
609
+ ];
610
+ let t = 0, n = [], r = [];
611
+ return e = e.replace(/#(\d+)|@(\d+)|\.\*\$/g, (e, i, a) => i === void 0 ? (a === void 0 || (r[Number(a)] = ++t), "") : (n[++t] = Number(i), "$()")), [
612
+ RegExp(`^${e}`),
613
+ n,
614
+ r
615
+ ];
616
+ }
617
+ }, Xe = [
618
+ /^$/,
619
+ [],
620
+ /* @__PURE__ */ Object.create(null)
621
+ ], Ze = /* @__PURE__ */ Object.create(null);
622
+ function Qe(e) {
623
+ return Ze[e] ??= RegExp(e === "*" ? "" : `^${e.replace(/\/\*$|([.\\+*[^\]$()])/g, (e, t) => t ? `\\${t}` : "(?:|/.*)")}$`);
624
+ }
625
+ function $e() {
626
+ Ze = /* @__PURE__ */ Object.create(null);
627
+ }
628
+ function et(e) {
629
+ let t = new Ye(), n = [];
630
+ if (e.length === 0) return Xe;
631
+ let r = e.map((e) => [!/\*|\/:/.test(e[0]), ...e]).sort(([e, t], [n, r]) => e ? 1 : n ? -1 : t.length - r.length), i = /* @__PURE__ */ Object.create(null);
632
+ for (let e = 0, a = -1, o = r.length; e < o; e++) {
633
+ let [o, s, c] = r[e];
634
+ o ? i[s] = [c.map(([e]) => [e, /* @__PURE__ */ Object.create(null)]), We] : a++;
635
+ let l;
636
+ try {
637
+ l = t.insert(s, a, o);
638
+ } catch (e) {
639
+ throw e === M ? new ze(s) : e;
640
+ }
641
+ o || (n[a] = c.map(([e, t]) => {
642
+ let n = /* @__PURE__ */ Object.create(null);
643
+ for (--t; t >= 0; t--) {
644
+ let [e, r] = l[t];
645
+ n[e] = r;
646
+ }
647
+ return [e, n];
648
+ }));
649
+ }
650
+ let [a, o, s] = t.buildRegExp();
651
+ for (let e = 0, t = n.length; e < t; e++) for (let t = 0, r = n[e].length; t < r; t++) {
652
+ let r = n[e][t]?.[1];
653
+ if (!r) continue;
654
+ let i = Object.keys(r);
655
+ for (let e = 0, t = i.length; e < t; e++) r[i[e]] = s[r[i[e]]];
656
+ }
657
+ let c = [];
658
+ for (let e in o) c[e] = n[o[e]];
659
+ return [
660
+ a,
661
+ c,
662
+ i
663
+ ];
664
+ }
665
+ function N(e, t) {
666
+ if (e) {
667
+ for (let n of Object.keys(e).sort((e, t) => t.length - e.length)) if (Qe(n).test(t)) return [...e[n]];
668
+ }
669
+ }
670
+ var tt = class {
671
+ name = "RegExpRouter";
672
+ #e;
673
+ #t;
674
+ constructor() {
675
+ this.#e = { ALL: /* @__PURE__ */ Object.create(null) }, this.#t = { ALL: /* @__PURE__ */ Object.create(null) };
676
+ }
677
+ add(e, t, n) {
678
+ let r = this.#e, i = this.#t;
679
+ if (!r || !i) throw Error(Re);
680
+ r[e] || [r, i].forEach((t) => {
681
+ t[e] = /* @__PURE__ */ Object.create(null), Object.keys(t.ALL).forEach((n) => {
682
+ t[e][n] = [...t.ALL[n]];
683
+ });
684
+ }), t === "/*" && (t = "*");
685
+ let a = (t.match(/\/:/g) || []).length;
686
+ if (/\*$/.test(t)) {
687
+ let o = Qe(t);
688
+ e === "ALL" ? Object.keys(r).forEach((e) => {
689
+ r[e][t] ||= N(r[e], t) || N(r.ALL, t) || [];
690
+ }) : r[e][t] ||= N(r[e], t) || N(r.ALL, t) || [], Object.keys(r).forEach((t) => {
691
+ (e === "ALL" || e === t) && Object.keys(r[t]).forEach((e) => {
692
+ o.test(e) && r[t][e].push([n, a]);
693
+ });
694
+ }), Object.keys(i).forEach((t) => {
695
+ (e === "ALL" || e === t) && Object.keys(i[t]).forEach((e) => o.test(e) && i[t][e].push([n, a]));
696
+ });
697
+ return;
698
+ }
699
+ let o = we(t) || [t];
700
+ for (let t = 0, s = o.length; t < s; t++) {
701
+ let c = o[t];
702
+ Object.keys(i).forEach((o) => {
703
+ (e === "ALL" || e === o) && (i[o][c] ||= [...N(r[o], c) || N(r.ALL, c) || []], i[o][c].push([n, a - s + t + 1]));
704
+ });
705
+ }
706
+ }
707
+ match = Ge;
708
+ buildAllMatchers() {
709
+ let e = /* @__PURE__ */ Object.create(null);
710
+ return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach((t) => {
711
+ e[t] ||= this.#n(t);
712
+ }), this.#e = this.#t = void 0, $e(), e;
713
+ }
714
+ #n(e) {
715
+ let t = [], n = e === "ALL";
716
+ return [this.#e, this.#t].forEach((r) => {
717
+ let i = r[e] ? Object.keys(r[e]).map((t) => [t, r[e][t]]) : [];
718
+ i.length === 0 ? e !== "ALL" && t.push(...Object.keys(r.ALL).map((e) => [e, r.ALL[e]])) : (n ||= !0, t.push(...i));
719
+ }), n ? et(t) : null;
720
+ }
721
+ }, nt = class {
722
+ name = "SmartRouter";
723
+ #e = [];
724
+ #t = [];
725
+ constructor(e) {
726
+ this.#e = e.routers;
727
+ }
728
+ add(e, t, n) {
729
+ if (!this.#t) throw Error(Re);
730
+ this.#t.push([
731
+ e,
732
+ t,
733
+ n
734
+ ]);
735
+ }
736
+ match(e, t) {
737
+ if (!this.#t) throw Error("Fatal error");
738
+ let n = this.#e, r = this.#t, i = n.length, a = 0, o;
739
+ for (; a < i; a++) {
740
+ let i = n[a];
741
+ try {
742
+ for (let e = 0, t = r.length; e < t; e++) i.add(...r[e]);
743
+ o = i.match(e, t);
744
+ } catch (e) {
745
+ if (e instanceof ze) continue;
746
+ throw e;
747
+ }
748
+ this.match = i.match.bind(i), this.#e = [i], this.#t = void 0;
749
+ break;
750
+ }
751
+ if (a === i) throw Error("Fatal error");
752
+ return this.name = `SmartRouter + ${this.activeRouter.name}`, o;
753
+ }
754
+ get activeRouter() {
755
+ if (this.#t || this.#e.length !== 1) throw Error("No active router has been determined yet.");
756
+ return this.#e[0];
757
+ }
758
+ }, P = /* @__PURE__ */ Object.create(null), rt = (e) => {
759
+ for (let t in e) return !0;
760
+ return !1;
761
+ }, it = class e {
762
+ #e;
763
+ #t;
764
+ #n;
765
+ #r = 0;
766
+ #i = P;
767
+ constructor(e, t, n) {
768
+ if (this.#t = n || /* @__PURE__ */ Object.create(null), this.#e = [], e && t) {
769
+ let n = /* @__PURE__ */ Object.create(null);
770
+ n[e] = {
771
+ handler: t,
772
+ possibleKeys: [],
773
+ score: 0
774
+ }, this.#e = [n];
775
+ }
776
+ this.#n = [];
777
+ }
778
+ insert(t, n, r) {
779
+ this.#r = ++this.#r;
780
+ let i = this, a = ge(n), o = [];
781
+ for (let t = 0, n = a.length; t < n; t++) {
782
+ let n = a[t], r = a[t + 1], s = ye(n, r), c = Array.isArray(s) ? s[0] : n;
783
+ if (c in i.#t) {
784
+ i = i.#t[c], s && o.push(s[1]);
785
+ continue;
786
+ }
787
+ i.#t[c] = new e(), s && (i.#n.push(s), o.push(s[1])), i = i.#t[c];
788
+ }
789
+ return i.#e.push({ [t]: {
790
+ handler: r,
791
+ possibleKeys: o.filter((e, t, n) => n.indexOf(e) === t),
792
+ score: this.#r
793
+ } }), i;
794
+ }
795
+ #a(e, t, n, r, i) {
796
+ for (let a = 0, o = t.#e.length; a < o; a++) {
797
+ let o = t.#e[a], s = o[n] || o.ALL, c = {};
798
+ if (s !== void 0 && (s.params = /* @__PURE__ */ Object.create(null), e.push(s), r !== P || i && i !== P)) for (let e = 0, t = s.possibleKeys.length; e < t; e++) {
799
+ let t = s.possibleKeys[e], n = c[s.score];
800
+ s.params[t] = i?.[t] && !n ? i[t] : r[t] ?? i?.[t], c[s.score] = !0;
801
+ }
802
+ }
803
+ }
804
+ search(e, t) {
805
+ let n = [];
806
+ this.#i = P;
807
+ let r = [this], i = he(t), a = [], o = i.length, s = null;
808
+ for (let c = 0; c < o; c++) {
809
+ let l = i[c], u = c === o - 1, d = [];
810
+ for (let f = 0, p = r.length; f < p; f++) {
811
+ let p = r[f], m = p.#t[l];
812
+ m && (m.#i = p.#i, u ? (m.#t["*"] && this.#a(n, m.#t["*"], e, p.#i), this.#a(n, m, e, p.#i)) : d.push(m));
813
+ for (let r = 0, f = p.#n.length; r < f; r++) {
814
+ let f = p.#n[r], m = p.#i === P ? {} : { ...p.#i };
815
+ if (f === "*") {
816
+ let t = p.#t["*"];
817
+ t && (this.#a(n, t, e, p.#i), t.#i = m, d.push(t));
818
+ continue;
819
+ }
820
+ let [h, g, _] = f;
821
+ if (!l && !(_ instanceof RegExp)) continue;
822
+ let v = p.#t[h];
823
+ if (_ instanceof RegExp) {
824
+ if (s === null) {
825
+ s = Array(o);
826
+ let e = t[0] === "/" ? 1 : 0;
827
+ for (let t = 0; t < o; t++) s[t] = e, e += i[t].length + 1;
828
+ }
829
+ let r = t.substring(s[c]), l = _.exec(r);
830
+ if (l) {
831
+ if (m[g] = l[0], this.#a(n, v, e, p.#i, m), rt(v.#t)) {
832
+ v.#i = m;
833
+ let e = l[0].match(/\//)?.length ?? 0;
834
+ (a[e] ||= []).push(v);
835
+ }
836
+ continue;
837
+ }
838
+ }
839
+ (_ === !0 || _.test(l)) && (m[g] = l, u ? (this.#a(n, v, e, m, p.#i), v.#t["*"] && this.#a(n, v.#t["*"], e, m, p.#i)) : (v.#i = m, d.push(v)));
840
+ }
841
+ }
842
+ let f = a.shift();
843
+ r = f ? d.concat(f) : d;
844
+ }
845
+ return n.length > 1 && n.sort((e, t) => e.score - t.score), [n.map(({ handler: e, params: t }) => [e, t])];
846
+ }
847
+ }, at = class {
848
+ name = "TrieRouter";
849
+ #e;
850
+ constructor() {
851
+ this.#e = new it();
852
+ }
853
+ add(e, t, n) {
854
+ let r = we(t);
855
+ if (r) {
856
+ for (let t = 0, i = r.length; t < i; t++) this.#e.insert(e, r[t], n);
857
+ return;
858
+ }
859
+ this.#e.insert(e, t, n);
860
+ }
861
+ match(e, t) {
862
+ return this.#e.search(e, t);
863
+ }
864
+ }, ot = class extends Ue {
865
+ constructor(e = {}) {
866
+ super(e), this.router = e.router ?? new nt({ routers: [new tt(), new at()] });
867
+ }
868
+ };
869
+ //#endregion
870
+ //#region src/coordinator-invites.ts
871
+ function st(e) {
872
+ let t = JSON.stringify(e), n = new TextEncoder().encode(t);
873
+ return Buffer.from(n).toString("base64url").replace(/=+$/, "");
874
+ }
875
+ function ct(e) {
876
+ let t = e + "=".repeat((4 - e.length % 4) % 4), n = Buffer.from(t, "base64url").toString("utf-8"), r = JSON.parse(n);
877
+ if (typeof r != "object" || !r) throw Error("invalid invite payload");
878
+ return r;
879
+ }
880
+ function lt(e) {
881
+ return `codemem://join?invite=${encodeURIComponent(e)}`;
882
+ }
883
+ function ut(e) {
884
+ let t = e.trim();
885
+ if (t.startsWith("codemem://")) {
886
+ let e = new URL(t).searchParams.get("invite") ?? "";
887
+ if (!e) throw Error("invite payload missing from link");
888
+ return e;
889
+ }
890
+ return t;
891
+ }
892
+ //#endregion
893
+ //#region src/schema.ts
894
+ var F = /* @__PURE__ */ se({
895
+ actors: () => Ot,
896
+ artifacts: () => dt,
897
+ memoryItems: () => ft,
898
+ opencodeSessions: () => gt,
899
+ rawEventFlushBatches: () => _t,
900
+ rawEventIngestSamples: () => z,
901
+ rawEventIngestStats: () => Dt,
902
+ rawEventSessions: () => ht,
903
+ rawEvents: () => mt,
904
+ replicationCursors: () => xt,
905
+ replicationOps: () => bt,
906
+ schema: () => kt,
907
+ sessionSummaries: () => yt,
908
+ sessions: () => I,
909
+ syncAttempts: () => Ct,
910
+ syncDaemonState: () => wt,
911
+ syncDevice: () => R,
912
+ syncNonces: () => L,
913
+ syncPeers: () => St,
914
+ syncResetState: () => Tt,
915
+ syncRetentionState: () => Et,
916
+ usageEvents: () => pt,
917
+ userPrompts: () => vt
918
+ }), I = S("sessions", {
919
+ id: x("id").primaryKey(),
920
+ started_at: C("started_at").notNull(),
921
+ ended_at: C("ended_at"),
922
+ cwd: C("cwd"),
923
+ project: C("project"),
924
+ git_remote: C("git_remote"),
925
+ git_branch: C("git_branch"),
926
+ user: C("user"),
927
+ tool_version: C("tool_version"),
928
+ metadata_json: C("metadata_json"),
929
+ import_key: C("import_key")
930
+ }), dt = S("artifacts", {
931
+ id: x("id").primaryKey(),
932
+ session_id: x("session_id").notNull().references(() => I.id, { onDelete: "cascade" }),
933
+ kind: C("kind").notNull(),
934
+ path: C("path"),
935
+ content_text: C("content_text"),
936
+ content_hash: C("content_hash"),
937
+ created_at: C("created_at").notNull(),
938
+ metadata_json: C("metadata_json")
939
+ }, (e) => [b("idx_artifacts_session_kind").on(e.session_id, e.kind)]), ft = S("memory_items", {
940
+ id: x("id").primaryKey(),
941
+ session_id: x("session_id").notNull().references(() => I.id, { onDelete: "cascade" }),
942
+ kind: C("kind").notNull(),
943
+ title: C("title").notNull(),
944
+ subtitle: C("subtitle"),
945
+ body_text: C("body_text").notNull(),
946
+ confidence: re("confidence").default(.5),
947
+ tags_text: C("tags_text").default(""),
948
+ active: x("active").default(1),
949
+ created_at: C("created_at").notNull(),
950
+ updated_at: C("updated_at").notNull(),
951
+ metadata_json: C("metadata_json"),
952
+ actor_id: C("actor_id"),
953
+ actor_display_name: C("actor_display_name"),
954
+ visibility: C("visibility"),
955
+ workspace_id: C("workspace_id"),
956
+ workspace_kind: C("workspace_kind"),
957
+ origin_device_id: C("origin_device_id"),
958
+ origin_source: C("origin_source"),
959
+ trust_state: C("trust_state"),
960
+ facts: C("facts"),
961
+ narrative: C("narrative"),
962
+ concepts: C("concepts"),
963
+ files_read: C("files_read"),
964
+ files_modified: C("files_modified"),
965
+ user_prompt_id: x("user_prompt_id"),
966
+ prompt_number: x("prompt_number"),
967
+ deleted_at: C("deleted_at"),
968
+ rev: x("rev").default(0),
969
+ import_key: C("import_key")
970
+ }, (e) => [b("idx_memory_items_active_created").on(e.active, e.created_at), b("idx_memory_items_session").on(e.session_id)]), pt = S("usage_events", {
971
+ id: x("id").primaryKey(),
972
+ session_id: x("session_id").references(() => I.id, { onDelete: "set null" }),
973
+ event: C("event").notNull(),
974
+ tokens_read: x("tokens_read").default(0),
975
+ tokens_written: x("tokens_written").default(0),
976
+ tokens_saved: x("tokens_saved").default(0),
977
+ created_at: C("created_at").notNull(),
978
+ metadata_json: C("metadata_json")
979
+ }, (e) => [b("idx_usage_events_event_created").on(e.event, e.created_at), b("idx_usage_events_session").on(e.session_id)]), mt = S("raw_events", {
980
+ id: x("id").primaryKey(),
981
+ source: C("source").notNull().default("opencode"),
982
+ stream_id: C("stream_id").notNull().default(""),
983
+ opencode_session_id: C("opencode_session_id").notNull(),
984
+ event_id: C("event_id"),
985
+ event_seq: x("event_seq").notNull(),
986
+ event_type: C("event_type").notNull(),
987
+ ts_wall_ms: x("ts_wall_ms"),
988
+ ts_mono_ms: re("ts_mono_ms"),
989
+ payload_json: C("payload_json").notNull(),
990
+ created_at: C("created_at").notNull()
991
+ }, (e) => [
992
+ ie("idx_raw_events_source_stream_seq").on(e.source, e.stream_id, e.event_seq),
993
+ ie("idx_raw_events_source_stream_event_id").on(e.source, e.stream_id, e.event_id),
994
+ b("idx_raw_events_session_seq").on(e.opencode_session_id, e.event_seq),
995
+ b("idx_raw_events_created").on(e.created_at)
996
+ ]), ht = S("raw_event_sessions", {
997
+ source: C("source").notNull().default("opencode"),
998
+ stream_id: C("stream_id").notNull().default(""),
999
+ opencode_session_id: C("opencode_session_id").notNull(),
1000
+ cwd: C("cwd"),
1001
+ project: C("project"),
1002
+ started_at: C("started_at"),
1003
+ last_seen_ts_wall_ms: x("last_seen_ts_wall_ms"),
1004
+ last_received_event_seq: x("last_received_event_seq").notNull().default(-1),
1005
+ last_flushed_event_seq: x("last_flushed_event_seq").notNull().default(-1),
1006
+ updated_at: C("updated_at").notNull()
1007
+ }, (e) => [ne({ columns: [e.source, e.stream_id] })]), gt = S("opencode_sessions", {
1008
+ source: C("source").notNull().default("opencode"),
1009
+ stream_id: C("stream_id").notNull().default(""),
1010
+ opencode_session_id: C("opencode_session_id").notNull(),
1011
+ session_id: x("session_id").references(() => I.id, { onDelete: "cascade" }),
1012
+ created_at: C("created_at").notNull()
1013
+ }, (e) => [ne({ columns: [e.source, e.stream_id] }), b("idx_opencode_sessions_session").on(e.session_id)]), _t = S("raw_event_flush_batches", {
1014
+ id: x("id").primaryKey(),
1015
+ source: C("source").notNull().default("opencode"),
1016
+ stream_id: C("stream_id").notNull().default(""),
1017
+ opencode_session_id: C("opencode_session_id").notNull(),
1018
+ start_event_seq: x("start_event_seq").notNull(),
1019
+ end_event_seq: x("end_event_seq").notNull(),
1020
+ extractor_version: C("extractor_version").notNull(),
1021
+ status: C("status").notNull(),
1022
+ error_message: C("error_message"),
1023
+ error_type: C("error_type"),
1024
+ observer_provider: C("observer_provider"),
1025
+ observer_model: C("observer_model"),
1026
+ observer_runtime: C("observer_runtime"),
1027
+ attempt_count: x("attempt_count").notNull().default(0),
1028
+ created_at: C("created_at").notNull(),
1029
+ updated_at: C("updated_at").notNull()
1030
+ }, (e) => [
1031
+ ie("idx_flush_batches_source_stream_seq_ver").on(e.source, e.stream_id, e.start_event_seq, e.end_event_seq, e.extractor_version),
1032
+ b("idx_flush_batches_session_created").on(e.opencode_session_id, e.created_at),
1033
+ b("idx_flush_batches_status_updated").on(e.status, e.updated_at)
1034
+ ]), vt = S("user_prompts", {
1035
+ id: x("id").primaryKey(),
1036
+ session_id: x("session_id").references(() => I.id, { onDelete: "cascade" }),
1037
+ project: C("project"),
1038
+ prompt_text: C("prompt_text").notNull(),
1039
+ prompt_number: x("prompt_number"),
1040
+ created_at: C("created_at").notNull(),
1041
+ created_at_epoch: x("created_at_epoch").notNull(),
1042
+ metadata_json: C("metadata_json"),
1043
+ import_key: C("import_key")
1044
+ }, (e) => [
1045
+ b("idx_user_prompts_session").on(e.session_id),
1046
+ b("idx_user_prompts_project").on(e.project),
1047
+ b("idx_user_prompts_epoch").on(e.created_at_epoch)
1048
+ ]), yt = S("session_summaries", {
1049
+ id: x("id").primaryKey(),
1050
+ session_id: x("session_id").references(() => I.id, { onDelete: "cascade" }),
1051
+ project: C("project"),
1052
+ request: C("request"),
1053
+ investigated: C("investigated"),
1054
+ learned: C("learned"),
1055
+ completed: C("completed"),
1056
+ next_steps: C("next_steps"),
1057
+ notes: C("notes"),
1058
+ files_read: C("files_read"),
1059
+ files_edited: C("files_edited"),
1060
+ prompt_number: x("prompt_number"),
1061
+ created_at: C("created_at").notNull(),
1062
+ created_at_epoch: x("created_at_epoch").notNull(),
1063
+ metadata_json: C("metadata_json"),
1064
+ import_key: C("import_key")
1065
+ }, (e) => [
1066
+ b("idx_session_summaries_session").on(e.session_id),
1067
+ b("idx_session_summaries_project").on(e.project),
1068
+ b("idx_session_summaries_epoch").on(e.created_at_epoch)
1069
+ ]), bt = S("replication_ops", {
1070
+ op_id: C("op_id").primaryKey(),
1071
+ entity_type: C("entity_type").notNull(),
1072
+ entity_id: C("entity_id").notNull(),
1073
+ op_type: C("op_type").notNull(),
1074
+ payload_json: C("payload_json"),
1075
+ clock_rev: x("clock_rev").notNull(),
1076
+ clock_updated_at: C("clock_updated_at").notNull(),
1077
+ clock_device_id: C("clock_device_id").notNull(),
1078
+ device_id: C("device_id").notNull(),
1079
+ created_at: C("created_at").notNull()
1080
+ }, (e) => [b("idx_replication_ops_created").on(e.created_at, e.op_id), b("idx_replication_ops_entity").on(e.entity_type, e.entity_id)]), xt = S("replication_cursors", {
1081
+ peer_device_id: C("peer_device_id").primaryKey(),
1082
+ last_applied_cursor: C("last_applied_cursor"),
1083
+ last_acked_cursor: C("last_acked_cursor"),
1084
+ updated_at: C("updated_at").notNull()
1085
+ }), St = S("sync_peers", {
1086
+ peer_device_id: C("peer_device_id").primaryKey(),
1087
+ name: C("name"),
1088
+ pinned_fingerprint: C("pinned_fingerprint"),
1089
+ public_key: C("public_key"),
1090
+ addresses_json: C("addresses_json"),
1091
+ claimed_local_actor: x("claimed_local_actor").notNull().default(0),
1092
+ actor_id: C("actor_id"),
1093
+ projects_include_json: C("projects_include_json"),
1094
+ projects_exclude_json: C("projects_exclude_json"),
1095
+ created_at: C("created_at").notNull(),
1096
+ last_seen_at: C("last_seen_at"),
1097
+ last_sync_at: C("last_sync_at"),
1098
+ last_error: C("last_error")
1099
+ }), L = S("sync_nonces", {
1100
+ nonce: C("nonce").primaryKey(),
1101
+ device_id: C("device_id").notNull(),
1102
+ created_at: C("created_at").notNull()
1103
+ }), R = S("sync_device", {
1104
+ device_id: C("device_id").primaryKey(),
1105
+ public_key: C("public_key").notNull(),
1106
+ fingerprint: C("fingerprint").notNull(),
1107
+ created_at: C("created_at").notNull()
1108
+ }), Ct = S("sync_attempts", {
1109
+ id: x("id").primaryKey({ autoIncrement: !0 }),
1110
+ peer_device_id: C("peer_device_id").notNull(),
1111
+ started_at: C("started_at").notNull(),
1112
+ finished_at: C("finished_at"),
1113
+ ok: x("ok").notNull(),
1114
+ ops_in: x("ops_in").notNull(),
1115
+ ops_out: x("ops_out").notNull(),
1116
+ error: C("error")
1117
+ }, (e) => [b("idx_sync_attempts_peer_started").on(e.peer_device_id, e.started_at)]), wt = S("sync_daemon_state", {
1118
+ id: x("id").primaryKey(),
1119
+ last_error: C("last_error"),
1120
+ last_traceback: C("last_traceback"),
1121
+ last_error_at: C("last_error_at"),
1122
+ last_ok_at: C("last_ok_at"),
1123
+ phase: C("phase")
1124
+ }), Tt = S("sync_reset_state", {
1125
+ id: x("id").primaryKey(),
1126
+ generation: x("generation").notNull(),
1127
+ snapshot_id: C("snapshot_id").notNull(),
1128
+ baseline_cursor: C("baseline_cursor"),
1129
+ retained_floor_cursor: C("retained_floor_cursor"),
1130
+ updated_at: C("updated_at").notNull()
1131
+ }), Et = S("sync_retention_state", {
1132
+ id: x("id").primaryKey(),
1133
+ last_run_at: C("last_run_at"),
1134
+ last_duration_ms: x("last_duration_ms"),
1135
+ last_deleted_ops: x("last_deleted_ops").notNull().default(0),
1136
+ last_estimated_bytes_before: x("last_estimated_bytes_before"),
1137
+ last_estimated_bytes_after: x("last_estimated_bytes_after"),
1138
+ retained_floor_cursor: C("retained_floor_cursor"),
1139
+ last_error: C("last_error"),
1140
+ last_error_at: C("last_error_at")
1141
+ }), z = S("raw_event_ingest_samples", {
1142
+ id: x("id").primaryKey({ autoIncrement: !0 }),
1143
+ created_at: C("created_at").notNull(),
1144
+ inserted_events: x("inserted_events").notNull().default(0),
1145
+ skipped_invalid: x("skipped_invalid").notNull().default(0),
1146
+ skipped_duplicate: x("skipped_duplicate").notNull().default(0),
1147
+ skipped_conflict: x("skipped_conflict").notNull().default(0)
1148
+ }), Dt = S("raw_event_ingest_stats", {
1149
+ id: x("id").primaryKey(),
1150
+ inserted_events: x("inserted_events").notNull().default(0),
1151
+ skipped_events: x("skipped_events").notNull().default(0),
1152
+ skipped_invalid: x("skipped_invalid").notNull().default(0),
1153
+ skipped_duplicate: x("skipped_duplicate").notNull().default(0),
1154
+ skipped_conflict: x("skipped_conflict").notNull().default(0),
1155
+ updated_at: C("updated_at").notNull()
1156
+ }), Ot = S("actors", {
1157
+ actor_id: C("actor_id").primaryKey(),
1158
+ display_name: C("display_name").notNull(),
1159
+ is_local: x("is_local").notNull().default(0),
1160
+ status: C("status").notNull().default("active"),
1161
+ merged_into_actor_id: C("merged_into_actor_id"),
1162
+ created_at: C("created_at").notNull(),
1163
+ updated_at: C("updated_at").notNull()
1164
+ }, (e) => ({
1165
+ isLocalIdx: b("idx_actors_is_local").on(e.is_local),
1166
+ statusIdx: b("idx_actors_status").on(e.status)
1167
+ })), kt = {
1168
+ sessions: I,
1169
+ artifacts: dt,
1170
+ memoryItems: ft,
1171
+ usageEvents: pt,
1172
+ rawEvents: mt,
1173
+ rawEventSessions: ht,
1174
+ opencodeSessions: gt,
1175
+ rawEventFlushBatches: _t,
1176
+ userPrompts: vt,
1177
+ sessionSummaries: yt,
1178
+ replicationOps: bt,
1179
+ replicationCursors: xt,
1180
+ syncPeers: St,
1181
+ syncNonces: L,
1182
+ syncDevice: R,
1183
+ syncAttempts: Ct,
1184
+ syncDaemonState: wt,
1185
+ syncResetState: Tt,
1186
+ rawEventIngestSamples: z,
1187
+ rawEventIngestStats: Dt,
1188
+ actors: Ot
1189
+ };
1190
+ //#endregion
1191
+ //#region src/observer-config.ts
1192
+ function At(e) {
1193
+ let t = [], n = !1, r = !1;
1194
+ for (let i = 0; i < e.length; i++) {
1195
+ let a = e.charAt(i);
1196
+ if (r) {
1197
+ t.push(a), r = !1;
1198
+ continue;
1199
+ }
1200
+ if (a === "\\" && n) {
1201
+ t.push(a), r = !0;
1202
+ continue;
1203
+ }
1204
+ if (a === "\"") {
1205
+ n = !n, t.push(a);
1206
+ continue;
1207
+ }
1208
+ if (!n && a === "/" && i + 1 < e.length) {
1209
+ let t = e.charAt(i + 1);
1210
+ if (t === "/") {
1211
+ let t = i + 2;
1212
+ for (; t < e.length && e.charAt(t) !== "\n";) t++;
1213
+ i = t - 1;
1214
+ continue;
1215
+ }
1216
+ if (t === "*") {
1217
+ let t = i + 2;
1218
+ for (; t < e.length - 1;) {
1219
+ if (e.charAt(t) === "*" && e.charAt(t + 1) === "/") {
1220
+ t += 2;
1221
+ break;
1222
+ }
1223
+ t++;
1224
+ }
1225
+ i = t - 1;
1226
+ continue;
1227
+ }
1228
+ }
1229
+ t.push(a);
1230
+ }
1231
+ return t.join("");
1232
+ }
1233
+ function jt(e) {
1234
+ let t = [], n = !1, r = !1;
1235
+ for (let i = 0; i < e.length; i++) {
1236
+ let a = e.charAt(i);
1237
+ if (r) {
1238
+ t.push(a), r = !1;
1239
+ continue;
1240
+ }
1241
+ if (a === "\\" && n) {
1242
+ t.push(a), r = !0;
1243
+ continue;
1244
+ }
1245
+ if (a === "\"") {
1246
+ n = !n, t.push(a);
1247
+ continue;
1248
+ }
1249
+ if (!n && a === ",") {
1250
+ let t = i + 1;
1251
+ for (; t < e.length && /\s/.test(e.charAt(t));) t++;
1252
+ if (t < e.length && (e.charAt(t) === "]" || e.charAt(t) === "}")) continue;
1253
+ }
1254
+ t.push(a);
1255
+ }
1256
+ return t.join("");
1257
+ }
1258
+ function B() {
1259
+ let e = _(h(), ".config", "opencode"), t = [_(e, "opencode.json"), _(e, "opencode.jsonc")].find((e) => l(e));
1260
+ if (!t) return {};
1261
+ let n;
1262
+ try {
1263
+ n = d(t, "utf-8");
1264
+ } catch {
1265
+ return {};
1266
+ }
1267
+ try {
1268
+ return JSON.parse(n);
1269
+ } catch {}
1270
+ try {
1271
+ let e = jt(At(n));
1272
+ return JSON.parse(e);
1273
+ } catch {
1274
+ return {};
1275
+ }
1276
+ }
1277
+ function V(e) {
1278
+ return e.startsWith("~/") ? _(h(), e.slice(2)) : e;
1279
+ }
1280
+ var Mt = {
1281
+ actor_id: "CODEMEM_ACTOR_ID",
1282
+ actor_display_name: "CODEMEM_ACTOR_DISPLAY_NAME",
1283
+ claude_command: "CODEMEM_CLAUDE_COMMAND",
1284
+ observer_provider: "CODEMEM_OBSERVER_PROVIDER",
1285
+ observer_model: "CODEMEM_OBSERVER_MODEL",
1286
+ observer_base_url: "CODEMEM_OBSERVER_BASE_URL",
1287
+ observer_runtime: "CODEMEM_OBSERVER_RUNTIME",
1288
+ observer_auth_source: "CODEMEM_OBSERVER_AUTH_SOURCE",
1289
+ observer_auth_file: "CODEMEM_OBSERVER_AUTH_FILE",
1290
+ observer_auth_command: "CODEMEM_OBSERVER_AUTH_COMMAND",
1291
+ observer_auth_timeout_ms: "CODEMEM_OBSERVER_AUTH_TIMEOUT_MS",
1292
+ observer_auth_cache_ttl_s: "CODEMEM_OBSERVER_AUTH_CACHE_TTL_S",
1293
+ observer_headers: "CODEMEM_OBSERVER_HEADERS",
1294
+ observer_max_chars: "CODEMEM_OBSERVER_MAX_CHARS",
1295
+ pack_observation_limit: "CODEMEM_PACK_OBSERVATION_LIMIT",
1296
+ pack_session_limit: "CODEMEM_PACK_SESSION_LIMIT",
1297
+ sync_enabled: "CODEMEM_SYNC_ENABLED",
1298
+ sync_host: "CODEMEM_SYNC_HOST",
1299
+ sync_port: "CODEMEM_SYNC_PORT",
1300
+ sync_interval_s: "CODEMEM_SYNC_INTERVAL_S",
1301
+ sync_mdns: "CODEMEM_SYNC_MDNS",
1302
+ sync_advertise: "CODEMEM_SYNC_ADVERTISE",
1303
+ sync_coordinator_url: "CODEMEM_SYNC_COORDINATOR_URL",
1304
+ sync_coordinator_group: "CODEMEM_SYNC_COORDINATOR_GROUP",
1305
+ sync_coordinator_groups: "CODEMEM_SYNC_COORDINATOR_GROUPS",
1306
+ sync_coordinator_timeout_s: "CODEMEM_SYNC_COORDINATOR_TIMEOUT_S",
1307
+ sync_coordinator_presence_ttl_s: "CODEMEM_SYNC_COORDINATOR_PRESENCE_TTL_S",
1308
+ sync_coordinator_admin_secret: "CODEMEM_SYNC_COORDINATOR_ADMIN_SECRET",
1309
+ sync_retention_enabled: "CODEMEM_SYNC_RETENTION_ENABLED",
1310
+ sync_retention_max_age_days: "CODEMEM_SYNC_RETENTION_MAX_AGE_DAYS",
1311
+ sync_retention_max_size_mb: "CODEMEM_SYNC_RETENTION_MAX_SIZE_MB",
1312
+ sync_retention_interval_s: "CODEMEM_SYNC_RETENTION_INTERVAL_S",
1313
+ sync_retention_max_runtime_ms: "CODEMEM_SYNC_RETENTION_MAX_RUNTIME_MS",
1314
+ sync_retention_max_ops_per_pass: "CODEMEM_SYNC_RETENTION_MAX_OPS_PER_PASS",
1315
+ sync_projects_include: "CODEMEM_SYNC_PROJECTS_INCLUDE",
1316
+ sync_projects_exclude: "CODEMEM_SYNC_PROJECTS_EXCLUDE",
1317
+ raw_events_sweeper_interval_s: "CODEMEM_RAW_EVENTS_SWEEPER_INTERVAL_S"
1318
+ };
1319
+ function Nt() {
1320
+ let e = process.env.CODEMEM_CONFIG?.trim();
1321
+ if (e) return V(e);
1322
+ let t = _(h(), ".config", "codemem");
1323
+ return [_(t, "config.json"), _(t, "config.jsonc")].find((e) => l(e)) ?? _(t, "config.json");
1324
+ }
1325
+ function Pt() {
1326
+ let e = Nt();
1327
+ if (!l(e)) return {};
1328
+ let t;
1329
+ try {
1330
+ t = d(e, "utf-8");
1331
+ } catch {
1332
+ return {};
1333
+ }
1334
+ if (!t.trim()) return {};
1335
+ try {
1336
+ let e = JSON.parse(t);
1337
+ return typeof e == "object" && e && !Array.isArray(e) ? e : {};
1338
+ } catch {}
1339
+ try {
1340
+ let e = jt(At(t)), n = JSON.parse(e);
1341
+ return typeof n == "object" && n && !Array.isArray(n) ? n : {};
1342
+ } catch {
1343
+ return {};
1344
+ }
1345
+ }
1346
+ function Ft(e, t) {
1347
+ let n = t ? V(t) : Nt();
1348
+ return u(g(n), { recursive: !0 }), m(n, `${JSON.stringify(e, null, 2)}\n`, "utf8"), n;
1349
+ }
1350
+ function It() {
1351
+ let e = {};
1352
+ for (let [t, n] of Object.entries(Mt)) {
1353
+ let r = process.env[n];
1354
+ r != null && r !== "" && (e[t] = n);
1355
+ }
1356
+ return e;
1357
+ }
1358
+ function H(e) {
1359
+ return typeof e == "object" && e && !Array.isArray(e) ? e : null;
1360
+ }
1361
+ function Lt(e) {
1362
+ let t = H(B().provider);
1363
+ return t ? H(t[e]) ?? {} : {};
1364
+ }
1365
+ function Rt() {
1366
+ let e = H(B().provider);
1367
+ return e ? new Set(Object.keys(e)) : /* @__PURE__ */ new Set();
1368
+ }
1369
+ var zt = new Set([
1370
+ "openai",
1371
+ "anthropic",
1372
+ "opencode"
1373
+ ]);
1374
+ function Bt(e) {
1375
+ return typeof e != "string" || !e.includes("/") ? null : e.split("/")[0]?.trim().toLowerCase() || null;
1376
+ }
1377
+ function Vt() {
1378
+ let e = Rt(), t = B();
1379
+ for (let n of ["model", "small_model"]) {
1380
+ let r = Bt(t[n]);
1381
+ r && e.add(r);
1382
+ }
1383
+ return e;
1384
+ }
1385
+ function Ht() {
1386
+ let e = Vt();
1387
+ for (let t of zt) e.add(t);
1388
+ return Array.from(e).sort((e, t) => e.localeCompare(t));
1389
+ }
1390
+ function Ut(e) {
1391
+ let t = Bt(e);
1392
+ return t && zt.has(t) ? t : null;
1393
+ }
1394
+ function Wt(e) {
1395
+ return e === "openai" ? "gpt-5.1-codex-mini" : e === "anthropic" ? "claude-sonnet-4-20250514" : e === "opencode" ? "opencode/gpt-5.1-codex-mini" : null;
1396
+ }
1397
+ function Gt(e, t) {
1398
+ if (e !== "opencode") return [
1399
+ null,
1400
+ t || Wt(e),
1401
+ {}
1402
+ ];
1403
+ let n = t || Wt(e) || "", r = `${e}/`;
1404
+ return [
1405
+ "https://opencode.ai/zen/v1",
1406
+ (n.startsWith(r) ? n.slice(r.length) : n) || null,
1407
+ {}
1408
+ ];
1409
+ }
1410
+ function Kt(e, t) {
1411
+ if (!e || !e.includes("/")) return null;
1412
+ let n = e.split("/")[0] ?? "";
1413
+ return n && t.has(n) ? n : null;
1414
+ }
1415
+ function qt(e) {
1416
+ return Yt(Jt(e));
1417
+ }
1418
+ function Jt(e) {
1419
+ return e.replace(/\$\{([^}]+)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (e, t, n) => {
1420
+ let r = t ?? n;
1421
+ return process.env[r] ?? e;
1422
+ });
1423
+ }
1424
+ function Yt(e) {
1425
+ return e.includes("{file:") ? e.replace(/\{file:([^}]+)\}/g, (e, t) => {
1426
+ let n = t.trim();
1427
+ if (!n) return e;
1428
+ let r = Jt(n).replace(/^~/, h());
1429
+ try {
1430
+ return d(r, "utf-8").trim();
1431
+ } catch {
1432
+ return e;
1433
+ }
1434
+ }) : e;
1435
+ }
1436
+ function U(e) {
1437
+ return H(e.options) ?? {};
1438
+ }
1439
+ function Xt(e) {
1440
+ let t = U(e), n = t.baseURL || t.baseUrl || t.base_url || e.base_url;
1441
+ return typeof n == "string" && n ? n : null;
1442
+ }
1443
+ function Zt(e) {
1444
+ let t = H(U(e).headers);
1445
+ if (!t) return {};
1446
+ let n = {};
1447
+ for (let [e, r] of Object.entries(t)) typeof e != "string" || typeof r != "string" || (n[e] = qt(r));
1448
+ return n;
1449
+ }
1450
+ function Qt(e) {
1451
+ let t = U(e), n = t.apiKey || e.apiKey;
1452
+ if (typeof n == "string" && n) return qt(n);
1453
+ let r = t.apiKeyEnv ?? t.api_key_env;
1454
+ if (typeof r == "string" && r) {
1455
+ let e = process.env[r];
1456
+ if (e) return e;
1457
+ }
1458
+ return null;
1459
+ }
1460
+ function $t(e) {
1461
+ let t = Lt(e), n = U(t), r = n.defaultModel ?? n.default_model ?? t.defaultModel ?? t.default_model;
1462
+ if (typeof r == "string" && r) return r.startsWith(`${e}/`) ? r : `${e}/${r}`;
1463
+ let i = H(t.models);
1464
+ if (i) {
1465
+ let t = Object.keys(i)[0];
1466
+ if (typeof t == "string" && t) return `${e}/${t}`;
1467
+ }
1468
+ return null;
1469
+ }
1470
+ function en(e, t) {
1471
+ let n = Lt(e), r = Xt(n), i = Zt(n), a = t;
1472
+ a ||= $t(e) ?? "";
1473
+ let o = `${e}/`, s = a.startsWith(o) ? a.slice(o.length) : a, c = H(n.models), l = s;
1474
+ if (c) {
1475
+ let e = H(c[s]);
1476
+ e && typeof e.id == "string" && (l = e.id);
1477
+ }
1478
+ return (typeof l != "string" || !l) && (l = null), [
1479
+ r,
1480
+ l,
1481
+ i
1482
+ ];
1483
+ }
1484
+ //#endregion
1485
+ //#region src/db.ts
1486
+ var tn = 6, nn = 6, rn = [
1487
+ "memory_items",
1488
+ "sessions",
1489
+ "artifacts",
1490
+ "raw_events",
1491
+ "raw_event_sessions",
1492
+ "usage_events"
1493
+ ], W = _(h(), ".codemem", "mem.sqlite");
1494
+ function an(e) {
1495
+ if (e) return V(e);
1496
+ let t = process.env.CODEMEM_DB;
1497
+ return t ? V(t) : W;
1498
+ }
1499
+ var on = [_(h(), ".codemem.sqlite"), _(h(), ".opencode-mem.sqlite")], sn = ["-wal", "-shm"];
1500
+ function cn(e, t) {
1501
+ u(g(t), { recursive: !0 });
1502
+ let n = [[e, t], ...sn.map((n) => [e + n, t + n])];
1503
+ for (let [e, t] of n) if (l(e)) try {
1504
+ f(e, t);
1505
+ } catch {
1506
+ try {
1507
+ c(e, t);
1508
+ try {
1509
+ p(e);
1510
+ } catch {}
1511
+ } catch (e) {
1512
+ if (l(t)) continue;
1513
+ throw e;
1514
+ }
1515
+ }
1516
+ }
1517
+ function ln(e) {
1518
+ if (e === W && !l(e)) {
1519
+ for (let t of on) if (l(t)) {
1520
+ cn(t, e);
1521
+ return;
1522
+ }
1523
+ }
1524
+ }
1525
+ function un(e = W) {
1526
+ ln(e), u(g(e), { recursive: !0 });
1527
+ let t = new v(e);
1528
+ t.pragma("foreign_keys = ON"), t.pragma("busy_timeout = 5000");
1529
+ let n = t.pragma("journal_mode = WAL", { simple: !0 });
1530
+ return n.toLowerCase() !== "wal" && console.warn(`Failed to enable WAL mode (got ${n}). Concurrent access may not work correctly.`), t.pragma("synchronous = NORMAL"), t;
1531
+ }
1532
+ function dn(e) {
1533
+ try {
1534
+ return !!e.prepare("SELECT 1 FROM sqlite_stat1 LIMIT 1").pluck().get();
1535
+ } catch {
1536
+ return !1;
1537
+ }
1538
+ }
1539
+ function fn(e) {
1540
+ e.pragma("optimize"), !dn(e) && (!G(e, "memory_items") || !G(e, "memory_fts") || (e.exec("ANALYZE"), e.pragma("optimize")));
1541
+ }
1542
+ function pn(e) {
1543
+ if (!mn() && (ae.load(e), !e.prepare("SELECT vec_version() AS v").get()?.v)) throw Error("sqlite-vec loaded but version check failed");
1544
+ }
1545
+ function mn() {
1546
+ let e = process.env.CODEMEM_EMBEDDING_DISABLED?.toLowerCase();
1547
+ return e === "1" || e === "true" || e === "yes";
1548
+ }
1549
+ function hn(e) {
1550
+ let t = e.pragma("user_version", { simple: !0 });
1551
+ return typeof t == "number" ? t : 0;
1552
+ }
1553
+ function gn(e) {
1554
+ let t = hn(e);
1555
+ if (t === 0) throw Error("Database schema is not initialized. Initialize the SQLite database with the current TypeScript runtime before retrying.");
1556
+ if (t < 6) throw Error(`Database schema version ${t} is older than minimum compatible (6). Upgrade the database schema with the current TypeScript runtime before retrying.`);
1557
+ t > 6 && console.warn(`Database schema version ${t} is newer than this TS runtime (6). Running in compatibility mode — additive schema changes are tolerated.`);
1558
+ let n = rn.filter((t) => !G(e, t));
1559
+ if (n.length > 0) throw Error(`Required tables missing: ${n.join(", ")}. The database may be corrupt or from an incompatible version.`);
1560
+ if (!G(e, "memory_fts")) throw Error("FTS5 index (memory_fts) is missing. Rebuild the database schema with the current TypeScript runtime before retrying.");
1561
+ }
1562
+ function G(e, t) {
1563
+ return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(t) !== void 0;
1564
+ }
1565
+ function _n(e, t, n) {
1566
+ return G(e, t) ? e.prepare("SELECT 1 FROM pragma_table_info(?) WHERE name = ? LIMIT 1").get(t, n) !== void 0 : !1;
1567
+ }
1568
+ function vn(e) {
1569
+ try {
1570
+ e.exec("\n CREATE TABLE IF NOT EXISTS sync_reset_state (\n id INTEGER PRIMARY KEY,\n generation INTEGER NOT NULL,\n snapshot_id TEXT NOT NULL,\n baseline_cursor TEXT,\n retained_floor_cursor TEXT,\n updated_at TEXT NOT NULL\n )\n ");
1571
+ } catch {}
1572
+ if (G(e, "sync_daemon_state") && !_n(e, "sync_daemon_state", "phase")) try {
1573
+ e.exec("ALTER TABLE sync_daemon_state ADD COLUMN phase TEXT");
1574
+ } catch {}
1575
+ if (G(e, "raw_event_flush_batches")) {
1576
+ for (let { name: t, ddl: n } of [
1577
+ {
1578
+ name: "error_message",
1579
+ ddl: "TEXT"
1580
+ },
1581
+ {
1582
+ name: "error_type",
1583
+ ddl: "TEXT"
1584
+ },
1585
+ {
1586
+ name: "observer_provider",
1587
+ ddl: "TEXT"
1588
+ },
1589
+ {
1590
+ name: "observer_model",
1591
+ ddl: "TEXT"
1592
+ },
1593
+ {
1594
+ name: "observer_runtime",
1595
+ ddl: "TEXT"
1596
+ },
1597
+ {
1598
+ name: "attempt_count",
1599
+ ddl: "INTEGER NOT NULL DEFAULT 0"
1600
+ }
1601
+ ]) if (!_n(e, "raw_event_flush_batches", t)) try {
1602
+ e.exec(`ALTER TABLE raw_event_flush_batches ADD COLUMN ${t} ${n}`);
1603
+ } catch (n) {
1604
+ if ((n instanceof Error ? n.message.toLowerCase() : "").includes("duplicate column name") && _n(e, "raw_event_flush_batches", t)) continue;
1605
+ throw n;
1606
+ }
1607
+ }
1608
+ }
1609
+ function yn(e) {
1610
+ if (!e) return {};
1611
+ try {
1612
+ let t = JSON.parse(e);
1613
+ return typeof t != "object" || !t || Array.isArray(t) ? {} : t;
1614
+ } catch {
1615
+ return console.warn(`[codemem] fromJson: invalid JSON (${e.slice(0, 80)}...)`), {};
1616
+ }
1617
+ }
1618
+ function bn(e) {
1619
+ if (!e) return {};
1620
+ let t = JSON.parse(e);
1621
+ if (typeof t != "object" || !t || Array.isArray(t)) throw Error(`fromJsonStrict: expected object, got ${Array.isArray(t) ? "array" : typeof t}`);
1622
+ return t;
1623
+ }
1624
+ function xn(e) {
1625
+ return e == null ? "{}" : JSON.stringify(e);
1626
+ }
1627
+ function Sn(e) {
1628
+ return e == null || typeof e == "object" && !Array.isArray(e) && Object.keys(e).length === 0 ? null : JSON.stringify(e);
1629
+ }
1630
+ //#endregion
1631
+ //#region src/sync-identity.ts
1632
+ var Cn = _(h(), ".config", "codemem", "keys"), wn = "device.key", Tn = "device.key.pub", K = "codemem-sync";
1633
+ function En(t) {
1634
+ return e("sha256").update(t, "utf-8").digest("hex");
1635
+ }
1636
+ function q() {
1637
+ return process.env.CODEMEM_SYNC_KEY_STORE?.toLowerCase() === "keychain" ? "keychain" : "file";
1638
+ }
1639
+ function J(e) {
1640
+ try {
1641
+ return w("which", [e], { stdio: "pipe" }), !0;
1642
+ } catch {
1643
+ return !1;
1644
+ }
1645
+ }
1646
+ function Dn() {
1647
+ process.platform === "darwin" && q() === "keychain" && process.env.CODEMEM_SYNC_KEYCHAIN_WARN !== "0" && console.warn("[codemem] keychain storage on macOS uses the `security` CLI and may expose the key in process arguments.");
1648
+ }
1649
+ function On(e, t) {
1650
+ if (process.platform === "linux") {
1651
+ if (!J("secret-tool")) return !1;
1652
+ try {
1653
+ return w("secret-tool", [
1654
+ "store",
1655
+ "--label",
1656
+ "codemem sync key",
1657
+ "service",
1658
+ K,
1659
+ "account",
1660
+ t
1661
+ ], {
1662
+ input: e,
1663
+ stdio: [
1664
+ "pipe",
1665
+ "pipe",
1666
+ "pipe"
1667
+ ]
1668
+ }), !0;
1669
+ } catch {
1670
+ return !1;
1671
+ }
1672
+ }
1673
+ if (process.platform === "darwin") {
1674
+ if (!J("security")) return !1;
1675
+ try {
1676
+ return w("security", [
1677
+ "add-generic-password",
1678
+ "-a",
1679
+ t,
1680
+ "-s",
1681
+ K,
1682
+ "-w",
1683
+ e.toString("utf-8"),
1684
+ "-U"
1685
+ ], { stdio: [
1686
+ "pipe",
1687
+ "pipe",
1688
+ "pipe"
1689
+ ] }), !0;
1690
+ } catch {
1691
+ return !1;
1692
+ }
1693
+ }
1694
+ return !1;
1695
+ }
1696
+ function kn(e) {
1697
+ if (process.platform === "linux") {
1698
+ if (!J("secret-tool")) return null;
1699
+ try {
1700
+ let t = w("secret-tool", [
1701
+ "lookup",
1702
+ "service",
1703
+ K,
1704
+ "account",
1705
+ e
1706
+ ], { stdio: [
1707
+ "pipe",
1708
+ "pipe",
1709
+ "pipe"
1710
+ ] });
1711
+ return Buffer.from(t);
1712
+ } catch {
1713
+ return null;
1714
+ }
1715
+ }
1716
+ if (process.platform === "darwin") {
1717
+ if (!J("security")) return null;
1718
+ try {
1719
+ let t = w("security", [
1720
+ "find-generic-password",
1721
+ "-a",
1722
+ e,
1723
+ "-s",
1724
+ K,
1725
+ "-w"
1726
+ ], { stdio: [
1727
+ "pipe",
1728
+ "pipe",
1729
+ "pipe"
1730
+ ] });
1731
+ return Buffer.from(t);
1732
+ } catch {
1733
+ return null;
1734
+ }
1735
+ }
1736
+ return null;
1737
+ }
1738
+ function Y(e) {
1739
+ let t = e ?? Cn;
1740
+ return [_(t, wn), _(t, Tn)];
1741
+ }
1742
+ function An(e) {
1743
+ let [, t] = Y(e);
1744
+ return l(t) && d(t, "utf-8").trim() || null;
1745
+ }
1746
+ function jn(e, t) {
1747
+ if (q() === "keychain") {
1748
+ let e = Mn(t);
1749
+ if (e) {
1750
+ let t = kn(e);
1751
+ if (t) return t;
1752
+ }
1753
+ }
1754
+ let [n] = Y(e);
1755
+ return l(n) ? d(n) : null;
1756
+ }
1757
+ function Mn(e) {
1758
+ let t = an(e);
1759
+ if (!l(t)) return null;
1760
+ let n = un(t);
1761
+ try {
1762
+ return y(n, { schema: F }).select({ device_id: R.device_id }).from(R).limit(1).get()?.device_id ?? null;
1763
+ } finally {
1764
+ n.close();
1765
+ }
1766
+ }
1767
+ function Nn(e) {
1768
+ let t = e.trim();
1769
+ return t.startsWith("ssh-ed25519 ") || t.startsWith("ssh-rsa ") || t.startsWith("ecdsa-");
1770
+ }
1771
+ function Pn(e, t) {
1772
+ l(e) && f(e, e.replace(/([^/]+)$/, `$1.invalid-${t}`));
1773
+ }
1774
+ function Fn(e, t) {
1775
+ if (u(g(e), { recursive: !0 }), l(e) && l(t)) return;
1776
+ if (l(e) && !l(t)) {
1777
+ try {
1778
+ let r = In(n(Ln(e)).export({
1779
+ type: "spki",
1780
+ format: "der"
1781
+ }));
1782
+ if (r && Nn(r)) {
1783
+ m(t, `${r}\n`, { mode: 420 });
1784
+ return;
1785
+ }
1786
+ } catch {}
1787
+ f(e, `${e}.orphan-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "")}`);
1788
+ }
1789
+ let { publicKey: i, privateKey: a } = r("ed25519");
1790
+ m(e, a.export({
1791
+ type: "pkcs8",
1792
+ format: "pem"
1793
+ }), { mode: 384 });
1794
+ let o = In(i.export({
1795
+ type: "spki",
1796
+ format: "der"
1797
+ }));
1798
+ if (!o) throw Error("failed to convert public key to SSH format");
1799
+ m(t, `${o}\n`, { mode: 420 });
1800
+ }
1801
+ function In(e) {
1802
+ if (e.length < 32) return null;
1803
+ let t = e.subarray(e.length - 32), n = Buffer.from("ssh-ed25519"), r = Buffer.alloc(4 + n.length + 4 + t.length), i = 0;
1804
+ return r.writeUInt32BE(n.length, i), i += 4, n.copy(r, i), i += n.length, r.writeUInt32BE(t.length, i), i += 4, t.copy(r, i), `ssh-ed25519 ${r.toString("base64")}`;
1805
+ }
1806
+ function Ln(e) {
1807
+ let n = d(e);
1808
+ try {
1809
+ return t(n);
1810
+ } catch {
1811
+ return t({
1812
+ key: n,
1813
+ format: "pem",
1814
+ type: "pkcs8"
1815
+ });
1816
+ }
1817
+ }
1818
+ function Rn(e, t) {
1819
+ if (!l(e) || !l(t)) return !1;
1820
+ let r = d(t, "utf-8").trim();
1821
+ if (!r || !Nn(r)) return !1;
1822
+ try {
1823
+ let i = In(n(Ln(e)).export({
1824
+ type: "spki",
1825
+ format: "der"
1826
+ }));
1827
+ return !i || !Nn(i) ? !1 : (i !== r && m(t, `${i}\n`, "utf-8"), !0);
1828
+ } catch {
1829
+ return !1;
1830
+ }
1831
+ }
1832
+ function zn(e, t) {
1833
+ let [n, r] = Y(t?.keysDir ?? Cn);
1834
+ Dn();
1835
+ let i = y(e, { schema: F }), o = i.select({
1836
+ device_id: R.device_id,
1837
+ public_key: R.public_key,
1838
+ fingerprint: R.fingerprint
1839
+ }).from(R).limit(1).get(), s = o?.device_id ?? "", c = o?.public_key ?? "", u = o?.fingerprint ?? "", f = l(n) && l(r);
1840
+ if (f && !Rn(n, r)) {
1841
+ let e = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:T.Z]/g, "").slice(0, 20);
1842
+ Pn(n, e), Pn(r, e), f = !1;
1843
+ }
1844
+ f || Fn(n, r);
1845
+ let p = d(r, "utf-8").trim();
1846
+ if (!p) throw Error("public key missing");
1847
+ let m = En(p), h = (/* @__PURE__ */ new Date()).toISOString();
1848
+ if (s) {
1849
+ if ((c !== p || u !== m) && i.update(R).set({
1850
+ public_key: p,
1851
+ fingerprint: m
1852
+ }).where(ee(R.device_id, s)).run(), q() === "keychain") {
1853
+ let e = l(n) ? d(n) : kn(s);
1854
+ e && On(e, s);
1855
+ }
1856
+ return [s, m];
1857
+ }
1858
+ let g = t?.deviceId ?? a();
1859
+ if (i.insert(R).values({
1860
+ device_id: g,
1861
+ public_key: p,
1862
+ fingerprint: m,
1863
+ created_at: h
1864
+ }).run(), q() === "keychain") {
1865
+ let e = l(n) ? d(n) : null;
1866
+ e && On(e, g);
1867
+ }
1868
+ return [g, m];
1869
+ }
1870
+ //#endregion
1871
+ //#region src/sync-auth.ts
1872
+ var Bn = "v2", Vn = 300;
1873
+ function X(t, n, r, i, a) {
1874
+ let o = e("sha256").update(a).digest("hex"), s = [
1875
+ t.toUpperCase(),
1876
+ n,
1877
+ r,
1878
+ i,
1879
+ o
1880
+ ].join("\n");
1881
+ return Buffer.from(s, "utf-8");
1882
+ }
1883
+ function Hn(e) {
1884
+ let n = e.timestamp ?? String(Math.floor(Date.now() / 1e3)), r = e.nonce ?? i(16).toString("hex"), a = new URL(e.url), s = a.pathname || "/";
1885
+ a.search && (s = `${s}${a.search}`);
1886
+ let c = X(e.method, s, n, r, e.bodyBytes), l = jn(e.keysDir);
1887
+ if (!l) throw Error("private key missing");
1888
+ let u;
1889
+ try {
1890
+ u = t(l);
1891
+ } catch {
1892
+ u = t({
1893
+ key: l,
1894
+ format: "pem",
1895
+ type: "pkcs8"
1896
+ });
1897
+ }
1898
+ let d = o(null, c, u).toString("base64");
1899
+ return {
1900
+ "X-Opencode-Timestamp": n,
1901
+ "X-Opencode-Nonce": r,
1902
+ "X-Opencode-Signature": `v2:${d}`
1903
+ };
1904
+ }
1905
+ function Un(e) {
1906
+ let t = e.timeWindowS ?? 300;
1907
+ if (!/^\d+$/.test(e.timestamp)) return !1;
1908
+ let n = Number.parseInt(e.timestamp, 10);
1909
+ if (Number.isNaN(n)) return !1;
1910
+ let r = Math.floor(Date.now() / 1e3);
1911
+ if (Math.abs(r - n) > t) return !1;
1912
+ let i = ["v1", "v2"], a = e.signature.indexOf(":");
1913
+ if (a < 1) return !1;
1914
+ let o = e.signature.slice(0, a);
1915
+ if (!i.includes(o)) return !1;
1916
+ let c = e.signature.slice(a + 1);
1917
+ if (!c) return !1;
1918
+ let l;
1919
+ try {
1920
+ if (l = Buffer.from(c, "base64"), l.toString("base64") !== c) return !1;
1921
+ } catch {
1922
+ return !1;
1923
+ }
1924
+ let u = X(e.method, e.pathWithQuery, e.timestamp, e.nonce, e.bodyBytes);
1925
+ try {
1926
+ return s(null, u, Wn(e.publicKey), l);
1927
+ } catch {
1928
+ return !1;
1929
+ }
1930
+ }
1931
+ function Wn(e) {
1932
+ let t = e.trim().split(/\s+/);
1933
+ if (t.length < 2 || t[0] !== "ssh-ed25519") throw Error("not an ssh-ed25519 key");
1934
+ let r = Buffer.from(t[1], "base64");
1935
+ if (r.length < 4) throw Error("truncated wire format");
1936
+ let i = 4 + r.readUInt32BE(0);
1937
+ if (r.length < i + 4) throw Error("truncated wire format");
1938
+ let a = r.readUInt32BE(i), o = i + 4;
1939
+ if (r.length < o + a) throw Error("truncated wire format");
1940
+ let s = r.subarray(o, o + a);
1941
+ if (s.length !== 32) throw Error(`unexpected Ed25519 key length: ${s.length}`);
1942
+ let c = Buffer.from("302a300506032b6570032100", "hex");
1943
+ return n({
1944
+ key: Buffer.concat([c, s]),
1945
+ format: "der",
1946
+ type: "spki"
1947
+ });
1948
+ }
1949
+ function Gn(e) {
1950
+ return {
1951
+ "X-Opencode-Device": e.deviceId,
1952
+ ...Hn({
1953
+ method: e.method,
1954
+ url: e.url,
1955
+ bodyBytes: e.bodyBytes,
1956
+ keysDir: e.keysDir,
1957
+ timestamp: e.timestamp,
1958
+ nonce: e.nonce
1959
+ })
1960
+ };
1961
+ }
1962
+ function Kn(e, t, n, r) {
1963
+ let i = y(e, { schema: F });
1964
+ try {
1965
+ return i.insert(L).values({
1966
+ nonce: n,
1967
+ device_id: t,
1968
+ created_at: r
1969
+ }).run(), !0;
1970
+ } catch (e) {
1971
+ if (e instanceof Error && e.message.includes("UNIQUE constraint failed")) return !1;
1972
+ throw e;
1973
+ }
1974
+ }
1975
+ function qn(e, t) {
1976
+ y(e, { schema: F }).delete(L).where(te(L.created_at, t)).run();
1977
+ }
1978
+ //#endregion
1979
+ //#region src/coordinator-api.ts
1980
+ var Z = 64 * 1024, Q = "X-Codemem-Coordinator-Admin";
1981
+ function Jn() {
1982
+ return (process.env.CODEMEM_SYNC_COORDINATOR_ADMIN_SECRET ?? "").trim() || null;
1983
+ }
1984
+ function $(e, t) {
1985
+ let n = t.adminSecret();
1986
+ if (!n) return {
1987
+ ok: !1,
1988
+ error: "admin_not_configured"
1989
+ };
1990
+ let r = (e ?? "").trim();
1991
+ return r ? r === n ? {
1992
+ ok: !0,
1993
+ error: "ok"
1994
+ } : {
1995
+ ok: !1,
1996
+ error: "invalid_admin_secret"
1997
+ } : {
1998
+ ok: !1,
1999
+ error: "missing_admin_header"
2000
+ };
2001
+ }
2002
+ function Yn(e) {
2003
+ let t = new URL(e);
2004
+ return t.search ? `${t.pathname}${t.search}` : t.pathname;
2005
+ }
2006
+ async function Xn(e, t, n, r) {
2007
+ return await e.recordNonce(t, n, r);
2008
+ }
2009
+ async function Zn(e, t) {
2010
+ await e.cleanupNonces(t);
2011
+ }
2012
+ async function Qn(e, t, n) {
2013
+ let { deviceId: r, signature: i, timestamp: a, nonce: o } = n;
2014
+ if (!r || !i || !a || !o) return {
2015
+ ok: !1,
2016
+ error: "missing_headers",
2017
+ enrollment: null
2018
+ };
2019
+ let s = await e.getEnrollment(n.groupId, r);
2020
+ if (!s) return {
2021
+ ok: !1,
2022
+ error: "unknown_device",
2023
+ enrollment: null
2024
+ };
2025
+ let c;
2026
+ try {
2027
+ c = Un({
2028
+ method: n.method,
2029
+ pathWithQuery: Yn(n.url),
2030
+ bodyBytes: n.body,
2031
+ timestamp: a,
2032
+ nonce: o,
2033
+ signature: i,
2034
+ publicKey: String(s.public_key),
2035
+ deviceId: r
2036
+ });
2037
+ } catch {
2038
+ return {
2039
+ ok: !1,
2040
+ error: "signature_verification_error",
2041
+ enrollment: null
2042
+ };
2043
+ }
2044
+ if (!c) return {
2045
+ ok: !1,
2046
+ error: "invalid_signature",
2047
+ enrollment: null
2048
+ };
2049
+ let l = t.now();
2050
+ return await Xn(e, r, o, l) ? (await Zn(e, (/* @__PURE__ */ new Date(new Date(l).getTime() - 300 * 2 * 1e3)).toISOString()), {
2051
+ ok: !0,
2052
+ error: "ok",
2053
+ enrollment: s
2054
+ }) : {
2055
+ ok: !1,
2056
+ error: "nonce_replay",
2057
+ enrollment: null
2058
+ };
2059
+ }
2060
+ function $n(e) {
2061
+ let t = e?.runtime ?? {
2062
+ adminSecret: Jn,
2063
+ now: () => (/* @__PURE__ */ new Date()).toISOString()
2064
+ };
2065
+ if (!e?.storeFactory) throw Error("createCoordinatorApp requires a storeFactory.");
2066
+ let n = e.storeFactory, r = new ot();
2067
+ return r.post("/v1/presence", async (e) => {
2068
+ let r = Buffer.from(await e.req.arrayBuffer());
2069
+ if (r.length > Z) return e.json({ error: "body_too_large" }, 413);
2070
+ let i;
2071
+ try {
2072
+ if (i = JSON.parse(r.toString("utf-8")), typeof i != "object" || !i || Array.isArray(i)) return e.json({ error: "invalid_json" }, 400);
2073
+ } catch {
2074
+ return e.json({ error: "invalid_json" }, 400);
2075
+ }
2076
+ let a = String(i.group_id ?? "").trim();
2077
+ if (!a) return e.json({ error: "group_id_required" }, 400);
2078
+ let o = n();
2079
+ try {
2080
+ let n = await Qn(o, t, {
2081
+ method: e.req.method,
2082
+ url: e.req.url,
2083
+ groupId: a,
2084
+ body: r,
2085
+ deviceId: e.req.header("X-Opencode-Device") ?? null,
2086
+ signature: e.req.header("X-Opencode-Signature") ?? null,
2087
+ timestamp: e.req.header("X-Opencode-Timestamp") ?? null,
2088
+ nonce: e.req.header("X-Opencode-Nonce") ?? null
2089
+ });
2090
+ if (!n.ok || !n.enrollment) return e.json({ error: n.error }, 401);
2091
+ if (i.fingerprint && String(i.fingerprint) !== String(n.enrollment.fingerprint)) return e.json({ error: "fingerprint_mismatch" }, 401);
2092
+ let s = i.addresses ?? [];
2093
+ if (!Array.isArray(s) || !s.every((e) => typeof e == "string")) return e.json({ error: "addresses_must_be_list_of_strings" }, 400);
2094
+ let c;
2095
+ try {
2096
+ if (c = Math.max(1, Number.parseInt(String(i.ttl_s ?? 180), 10)), Number.isNaN(c)) return e.json({ error: "ttl_s_must_be_int" }, 400);
2097
+ } catch {
2098
+ return e.json({ error: "ttl_s_must_be_int" }, 400);
2099
+ }
2100
+ let l = await o.upsertPresence({
2101
+ groupId: a,
2102
+ deviceId: String(n.enrollment.device_id),
2103
+ addresses: s,
2104
+ ttlS: c,
2105
+ capabilities: typeof i.capabilities == "object" && i.capabilities !== null && !Array.isArray(i.capabilities) ? i.capabilities : void 0
2106
+ });
2107
+ return e.json({
2108
+ ok: !0,
2109
+ ...l
2110
+ });
2111
+ } finally {
2112
+ await o.close();
2113
+ }
2114
+ }), r.get("/v1/peers", async (e) => {
2115
+ let r = (e.req.query("group_id") ?? "").trim();
2116
+ if (!r) return e.json({ error: "group_id_required" }, 400);
2117
+ let i = n();
2118
+ try {
2119
+ let n = await Qn(i, t, {
2120
+ method: e.req.method,
2121
+ url: e.req.url,
2122
+ groupId: r,
2123
+ body: Buffer.alloc(0),
2124
+ deviceId: e.req.header("X-Opencode-Device") ?? null,
2125
+ signature: e.req.header("X-Opencode-Signature") ?? null,
2126
+ timestamp: e.req.header("X-Opencode-Timestamp") ?? null,
2127
+ nonce: e.req.header("X-Opencode-Nonce") ?? null
2128
+ });
2129
+ if (!n.ok || !n.enrollment) return e.json({ error: n.error }, 401);
2130
+ let a = await i.listGroupPeers(r, String(n.enrollment.device_id));
2131
+ return e.json({ items: a });
2132
+ } finally {
2133
+ await i.close();
2134
+ }
2135
+ }), r.post("/v1/admin/devices", async (e) => {
2136
+ let r = $(e.req.header(Q), t);
2137
+ if (!r.ok) return e.json({ error: r.error }, 401);
2138
+ let i = Buffer.from(await e.req.arrayBuffer());
2139
+ if (i.length > Z) return e.json({ error: "body_too_large" }, 413);
2140
+ let a;
2141
+ try {
2142
+ if (a = JSON.parse(i.toString("utf-8")), typeof a != "object" || !a || Array.isArray(a)) return e.json({ error: "invalid_json" }, 400);
2143
+ } catch {
2144
+ return e.json({ error: "invalid_json" }, 400);
2145
+ }
2146
+ let o = String(a.group_id ?? "").trim(), s = String(a.device_id ?? "").trim(), c = String(a.fingerprint ?? "").trim(), l = String(a.public_key ?? "").trim(), u = String(a.display_name ?? "").trim() || null;
2147
+ if (!o || !s || !c || !l) return e.json({ error: "group_id_device_id_fingerprint_public_key_required" }, 400);
2148
+ let d = n();
2149
+ try {
2150
+ await d.createGroup(o), await d.enrollDevice(o, {
2151
+ deviceId: s,
2152
+ fingerprint: c,
2153
+ publicKey: l,
2154
+ displayName: u
2155
+ });
2156
+ } finally {
2157
+ await d.close();
2158
+ }
2159
+ return e.json({ ok: !0 });
2160
+ }), r.get("/v1/admin/devices", async (e) => {
2161
+ let r = $(e.req.header(Q), t);
2162
+ if (!r.ok) return e.json({ error: r.error }, 401);
2163
+ let i = (e.req.query("group_id") ?? "").trim();
2164
+ if (!i) return e.json({ error: "group_id_required" }, 400);
2165
+ let a = [
2166
+ "1",
2167
+ "true",
2168
+ "yes"
2169
+ ].includes((e.req.query("include_disabled") ?? "0").trim().toLowerCase()), o = n();
2170
+ try {
2171
+ return e.json({ items: await o.listEnrolledDevices(i, a) });
2172
+ } finally {
2173
+ await o.close();
2174
+ }
2175
+ }), r.post("/v1/admin/devices/rename", async (e) => {
2176
+ let r = $(e.req.header(Q), t);
2177
+ if (!r.ok) return e.json({ error: r.error }, 401);
2178
+ let i = Buffer.from(await e.req.arrayBuffer());
2179
+ if (i.length > Z) return e.json({ error: "body_too_large" }, 413);
2180
+ let a;
2181
+ try {
2182
+ if (a = JSON.parse(i.toString("utf-8")), typeof a != "object" || !a || Array.isArray(a)) return e.json({ error: "invalid_json" }, 400);
2183
+ } catch {
2184
+ return e.json({ error: "invalid_json" }, 400);
2185
+ }
2186
+ let o = String(a.group_id ?? "").trim(), s = String(a.device_id ?? "").trim(), c = String(a.display_name ?? "").trim();
2187
+ if (!o || !s) return e.json({ error: "group_id_and_device_id_required" }, 400);
2188
+ if (!c) return e.json({ error: "display_name_required" }, 400);
2189
+ let l = n();
2190
+ try {
2191
+ return await l.renameDevice(o, s, c) ? e.json({ ok: !0 }) : e.json({ error: "device_not_found" }, 404);
2192
+ } finally {
2193
+ await l.close();
2194
+ }
2195
+ }), r.post("/v1/admin/devices/disable", async (e) => {
2196
+ let r = $(e.req.header(Q), t);
2197
+ if (!r.ok) return e.json({ error: r.error }, 401);
2198
+ let i = Buffer.from(await e.req.arrayBuffer());
2199
+ if (i.length > Z) return e.json({ error: "body_too_large" }, 413);
2200
+ let a;
2201
+ try {
2202
+ if (a = JSON.parse(i.toString("utf-8")), typeof a != "object" || !a || Array.isArray(a)) return e.json({ error: "invalid_json" }, 400);
2203
+ } catch {
2204
+ return e.json({ error: "invalid_json" }, 400);
2205
+ }
2206
+ let o = String(a.group_id ?? "").trim(), s = String(a.device_id ?? "").trim();
2207
+ if (!o || !s) return e.json({ error: "group_id_and_device_id_required" }, 400);
2208
+ let c = n();
2209
+ try {
2210
+ return await c.setDeviceEnabled(o, s, !1) ? e.json({ ok: !0 }) : e.json({ error: "device_not_found" }, 404);
2211
+ } finally {
2212
+ await c.close();
2213
+ }
2214
+ }), r.post("/v1/admin/devices/remove", async (e) => {
2215
+ let r = $(e.req.header(Q), t);
2216
+ if (!r.ok) return e.json({ error: r.error }, 401);
2217
+ let i = Buffer.from(await e.req.arrayBuffer());
2218
+ if (i.length > Z) return e.json({ error: "body_too_large" }, 413);
2219
+ let a;
2220
+ try {
2221
+ if (a = JSON.parse(i.toString("utf-8")), typeof a != "object" || !a || Array.isArray(a)) return e.json({ error: "invalid_json" }, 400);
2222
+ } catch {
2223
+ return e.json({ error: "invalid_json" }, 400);
2224
+ }
2225
+ let o = String(a.group_id ?? "").trim(), s = String(a.device_id ?? "").trim();
2226
+ if (!o || !s) return e.json({ error: "group_id_and_device_id_required" }, 400);
2227
+ let c = n();
2228
+ try {
2229
+ return await c.removeDevice(o, s) ? e.json({ ok: !0 }) : e.json({ error: "device_not_found" }, 404);
2230
+ } finally {
2231
+ await c.close();
2232
+ }
2233
+ }), r.post("/v1/admin/invites", async (e) => {
2234
+ let r = $(e.req.header(Q), t);
2235
+ if (!r.ok) return e.json({ error: r.error }, 401);
2236
+ let i = Buffer.from(await e.req.arrayBuffer());
2237
+ if (i.length > Z) return e.json({ error: "body_too_large" }, 413);
2238
+ let a;
2239
+ try {
2240
+ if (a = JSON.parse(i.toString("utf-8")), typeof a != "object" || !a || Array.isArray(a)) return e.json({ error: "invalid_json" }, 400);
2241
+ } catch {
2242
+ return e.json({ error: "invalid_json" }, 400);
2243
+ }
2244
+ let o = String(a.group_id ?? "").trim(), s = String(a.policy ?? "auto_admit").trim(), c = String(a.expires_at ?? "").trim(), l = String(a.created_by ?? "").trim() || null;
2245
+ if (!o || !["auto_admit", "approval_required"].includes(s) || !c) return e.json({ error: "group_id_policy_and_expires_at_required" }, 400);
2246
+ let u = n();
2247
+ try {
2248
+ if (!await u.getGroup(o)) return e.json({ error: "group_not_found" }, 404);
2249
+ let t = await u.createInvite({
2250
+ groupId: o,
2251
+ policy: s,
2252
+ expiresAt: c,
2253
+ createdBy: l
2254
+ }), n = {
2255
+ v: 1,
2256
+ kind: "coordinator_team_invite",
2257
+ coordinator_url: String(a.coordinator_url ?? "").trim(),
2258
+ group_id: o,
2259
+ policy: s,
2260
+ token: String(t.token ?? ""),
2261
+ expires_at: c,
2262
+ team_name: t.team_name_snapshot ?? null
2263
+ }, r = st(n), { token: i, ...d } = t;
2264
+ return e.json({
2265
+ ok: !0,
2266
+ invite: d,
2267
+ payload: n,
2268
+ encoded: r,
2269
+ link: lt(r)
2270
+ });
2271
+ } finally {
2272
+ await u.close();
2273
+ }
2274
+ }), r.get("/v1/admin/invites", async (e) => {
2275
+ let r = $(e.req.header(Q), t);
2276
+ if (!r.ok) return e.json({ error: r.error }, 401);
2277
+ let i = (e.req.query("group_id") ?? "").trim();
2278
+ if (!i) return e.json({ error: "group_id_required" }, 400);
2279
+ let a = n();
2280
+ try {
2281
+ let t = (await a.listInvites(i)).map(({ token: e, ...t }) => t);
2282
+ return e.json({ items: t });
2283
+ } finally {
2284
+ await a.close();
2285
+ }
2286
+ }), r.post("/v1/admin/join-requests/approve", async (e) => er(e, !0, {
2287
+ createStore: n,
2288
+ runtime: t
2289
+ })), r.post("/v1/admin/join-requests/deny", async (e) => er(e, !1, {
2290
+ createStore: n,
2291
+ runtime: t
2292
+ })), r.get("/v1/admin/join-requests", async (e) => {
2293
+ let r = $(e.req.header(Q), t);
2294
+ if (!r.ok) return e.json({ error: r.error }, 401);
2295
+ let i = (e.req.query("group_id") ?? "").trim();
2296
+ if (!i) return e.json({ error: "group_id_required" }, 400);
2297
+ let a = n();
2298
+ try {
2299
+ return e.json({ items: await a.listJoinRequests(i) });
2300
+ } finally {
2301
+ await a.close();
2302
+ }
2303
+ }), r.post("/v1/join", async (e) => {
2304
+ let r = Buffer.from(await e.req.arrayBuffer());
2305
+ if (r.length > Z) return e.json({ error: "body_too_large" }, 413);
2306
+ let i;
2307
+ try {
2308
+ if (i = JSON.parse(r.toString("utf-8")), typeof i != "object" || !i || Array.isArray(i)) return e.json({ error: "invalid_json" }, 400);
2309
+ } catch {
2310
+ return e.json({ error: "invalid_json" }, 400);
2311
+ }
2312
+ let a = String(i.token ?? "").trim(), o = String(i.device_id ?? "").trim(), s = String(i.fingerprint ?? "").trim(), c = String(i.public_key ?? "").trim(), l = String(i.display_name ?? "").trim() || null;
2313
+ if (!a || !o || !s || !c) return e.json({ error: "token_device_id_fingerprint_public_key_required" }, 400);
2314
+ let u = n();
2315
+ try {
2316
+ let n = await u.getInviteByToken(a);
2317
+ if (!n) return e.json({ error: "invalid_token" }, 404);
2318
+ if (n.revoked_at) return e.json({ error: "revoked_token" }, 400);
2319
+ let r = String(n.expires_at ?? "");
2320
+ if (r && new Date(r.replace("Z", "+00:00")) <= new Date(t.now())) return e.json({ error: "expired_token" }, 400);
2321
+ let i = String(n.group_id);
2322
+ if (await u.getEnrollment(i, o)) return e.json({
2323
+ ok: !0,
2324
+ status: "already_enrolled",
2325
+ group_id: n.group_id,
2326
+ policy: n.policy
2327
+ });
2328
+ let d = String(n.policy);
2329
+ if (!["auto_admit", "approval_required"].includes(d)) return e.json({ error: `unknown invite policy: ${d}` }, 400);
2330
+ if (d === "approval_required") {
2331
+ let t = await u.createJoinRequest({
2332
+ groupId: i,
2333
+ deviceId: o,
2334
+ publicKey: c,
2335
+ fingerprint: s,
2336
+ displayName: l,
2337
+ token: a
2338
+ });
2339
+ return e.json({
2340
+ ok: !0,
2341
+ status: "pending",
2342
+ group_id: n.group_id,
2343
+ policy: n.policy,
2344
+ request_id: t.request_id
2345
+ });
2346
+ }
2347
+ return await u.enrollDevice(i, {
2348
+ deviceId: o,
2349
+ fingerprint: s,
2350
+ publicKey: c,
2351
+ displayName: l
2352
+ }), e.json({
2353
+ ok: !0,
2354
+ status: "enrolled",
2355
+ group_id: n.group_id,
2356
+ policy: n.policy
2357
+ });
2358
+ } finally {
2359
+ await u.close();
2360
+ }
2361
+ }), r;
2362
+ }
2363
+ async function er(e, t, n) {
2364
+ let r = $(e.req.header(Q), n.runtime);
2365
+ if (!r.ok) return e.json({ error: r.error }, 401);
2366
+ let i = Buffer.from(await e.req.arrayBuffer());
2367
+ if (i.length > Z) return e.json({ error: "body_too_large" }, 413);
2368
+ let a;
2369
+ try {
2370
+ if (a = JSON.parse(i.toString("utf-8")), typeof a != "object" || !a || Array.isArray(a)) return e.json({ error: "invalid_json" }, 400);
2371
+ } catch {
2372
+ return e.json({ error: "invalid_json" }, 400);
2373
+ }
2374
+ let o = String(a.request_id ?? "").trim(), s = String(a.reviewed_by ?? "").trim() || null;
2375
+ if (!o) return e.json({ error: "request_id_required" }, 400);
2376
+ let c = n.createStore();
2377
+ try {
2378
+ let n = await c.reviewJoinRequest({
2379
+ requestId: o,
2380
+ approved: t,
2381
+ reviewedBy: s
2382
+ });
2383
+ return n ? n._no_transition ? e.json({
2384
+ error: "request_not_pending",
2385
+ status: n.status
2386
+ }, 409) : e.json({
2387
+ ok: !0,
2388
+ request: n
2389
+ }) : e.json({ error: "request_not_found" }, 404);
2390
+ } finally {
2391
+ await c.close();
2392
+ }
2393
+ }
2394
+ //#endregion
2395
+ export { $t as $, pn as A, lt as At, Lt as B, un as C, Tt as Ct, bn as D, ct as Dt, yn as E, vt as Et, Sn as F, Vt as G, Xt as H, Mt as I, B as J, Rt as K, V as L, an as M, G as N, hn as O, st as Ot, xn as P, Gt as Q, Nt as R, gn as S, St, fn as T, pt as Tt, Zt as U, Qt as V, U as W, Wt as X, Pt as Y, Ut as Z, On as _, yt as _t, X as a, Ft as at, nn as b, wt as bt, Hn as c, ft as ct, En as d, Dt as dt, Kt as et, Fn as f, ht as ft, Y as g, F as gt, An as h, bt as ht, Gn as i, jt as it, ln as j, se as jt, mn as k, ut as kt, Un as l, _t as lt, kn as m, xt as mt, Vn as n, qt as nt, qn as o, Ot as ot, jn as p, mt as pt, Ht as q, Bn as r, At as rt, Kn as s, dt as st, $n as t, en as tt, zn as u, z as ut, Rn as v, I as vt, vn as w, Et as wt, tn as x, R as xt, W as y, Ct as yt, It as z };
2396
+
2397
+ //# sourceMappingURL=coordinator-api-By9BNOCL.js.map