@llmnative/agentico 0.23.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1072 @@
1
+ import { RunnerClient as e, RunnerError as t } from "@llmnative/runner/client";
2
+ import { AI_PROVIDER_DEFINITIONS as n, createAIProvider as r, createCloudflareProviderDefinition as i, createOpenAICompatibleProviderDefinition as a, createVertexAIProvider as o, resolveServerCredentials as s } from "@llmnative/react/server";
3
+ import { installOverSsh as c } from "@llmnative/runner/setup";
4
+ import { existsSync as l, mkdirSync as u, readFileSync as d, renameSync as f, writeFileSync as p } from "node:fs";
5
+ import { join as m } from "node:path";
6
+ //#region src/server/connections.ts
7
+ var h = "agentico_connections", g = /* @__PURE__ */ new Set([
8
+ "accountId",
9
+ "baseUrl",
10
+ "projectId",
11
+ "location",
12
+ "model"
13
+ ]), _ = /^[a-z][a-z0-9-]{1,40}$/, v = async (e, t) => {
14
+ if (e === "vertex") return o({
15
+ ...t.serviceAccount ? { serviceAccount: t.serviceAccount } : {},
16
+ projectId: t.projectId,
17
+ location: t.location || "eu"
18
+ });
19
+ if (e === "cloudflare") return r(i({ accountId: t.accountId ?? "" }), t.apiKey ?? "");
20
+ if (e === "openai-compatible") return r(a({
21
+ id: "openai-compatible",
22
+ label: "OpenAI-compatible",
23
+ baseUrl: t.baseUrl ?? ""
24
+ }), t.apiKey ?? "");
25
+ if (!n.some((t) => t.id === e)) throw Error(`unknown provider ${e}`);
26
+ return r(e, t.apiKey ?? "");
27
+ }, y = (e, t, n) => `ai/${e}/${t}/${n}`, b = () => crypto.randomUUID().replace(/-/g, "").slice(0, 8);
28
+ function x(e) {
29
+ let t = {}, n = {};
30
+ for (let [r, i] of Object.entries(e ?? {})) typeof i == "string" && i.trim() && ((g.has(r) ? t : n)[r] = i.trim());
31
+ return {
32
+ plain: t,
33
+ secret: n
34
+ };
35
+ }
36
+ function S(e) {
37
+ let { records: t, secrets: n } = e, r = e.adapter ?? v, i = e.now ?? (() => /* @__PURE__ */ new Date()), a = async (e) => await t.get("agentico_connections", e) ?? {
38
+ id: e,
39
+ providers: []
40
+ }, o = (e) => t.put(h, e), c = async (e, t, r) => {
41
+ let i = await n.get(y(e, t.id, r.id)), a = i ? JSON.parse(i) : {};
42
+ return {
43
+ ...t.fields ?? {},
44
+ ...a
45
+ };
46
+ }, l = async (e, t) => {
47
+ try {
48
+ let n = await (await r(e, t)).validateApiKey();
49
+ return n.valid ? { ok: !0 } : {
50
+ ok: !1,
51
+ error: n.error ?? "rejected"
52
+ };
53
+ } catch (e) {
54
+ return {
55
+ ok: !1,
56
+ error: e instanceof Error ? e.message : String(e)
57
+ };
58
+ }
59
+ }, u = async (e, t, r, s) => {
60
+ if (!_.test(t)) return {
61
+ ok: !1,
62
+ error: "invalid provider"
63
+ };
64
+ let c = await l(t, r);
65
+ if (!c.ok) return c;
66
+ let { plain: u, secret: d } = x(r), f = await a(e), p = {
67
+ id: b(),
68
+ at: i().toISOString(),
69
+ ...s ? { label: s } : {}
70
+ };
71
+ await n.set(y(e, t, p.id), JSON.stringify(d));
72
+ let m = f.providers.find((e) => e.id === t);
73
+ return m ? (m.accounts.push(p), m.fields = {
74
+ ...m.fields ?? {},
75
+ ...u
76
+ }) : f.providers.push({
77
+ id: t,
78
+ at: p.at,
79
+ ...Object.keys(u).length ? { fields: u } : {},
80
+ accounts: [p]
81
+ }), await o(f), { ok: !0 };
82
+ }, d = {
83
+ async snapshot(e) {
84
+ let t = await a(e);
85
+ return {
86
+ providers: t.providers.map(({ id: e, at: t, fields: n, accounts: r }) => ({
87
+ id: e,
88
+ at: t,
89
+ ...n ? { fields: n } : {},
90
+ accounts: r.map((e) => ({ ...e }))
91
+ })),
92
+ ...t.order ? { order: t.order } : {}
93
+ };
94
+ },
95
+ async connect(e, t, n) {
96
+ return await d.disconnect(e, t), u(e, t, n);
97
+ },
98
+ async addAccount(e, t, n) {
99
+ let { label: r, ...i } = n;
100
+ return u(e, t, i, r?.trim() || void 0);
101
+ },
102
+ async disconnect(e, t) {
103
+ let r = await a(e), i = r.providers.find((e) => e.id === t);
104
+ if (i) {
105
+ for (let r of i.accounts) await n.delete(y(e, t, r.id));
106
+ r.providers = r.providers.filter((e) => e.id !== t), r.order &&= {
107
+ ...r.order,
108
+ list: r.order.list.filter((e) => e !== t)
109
+ }, await o(r);
110
+ }
111
+ },
112
+ async removeAccount(e, t, r) {
113
+ let i = await a(e), s = i.providers.find((e) => e.id === t);
114
+ s && (await n.delete(y(e, t, r)), s.accounts = s.accounts.filter((e) => e.id !== r), s.accounts.length || (i.providers = i.providers.filter((e) => e.id !== t)), await o(i));
115
+ },
116
+ async orderAccounts(e, t, n) {
117
+ let r = await a(e), i = r.providers.find((e) => e.id === t);
118
+ if (!i) return;
119
+ let s = (e) => {
120
+ let t = n.indexOf(e);
121
+ return t < 0 ? n.length : t;
122
+ };
123
+ i.accounts = [...i.accounts].sort((e, t) => s(e.id) - s(t.id)), await o(r);
124
+ },
125
+ async setOrder(e, t) {
126
+ let n = await a(e);
127
+ t === null ? delete n.order : n.order = {
128
+ list: t.filter((e) => typeof e == "string"),
129
+ manual: !0
130
+ }, await o(n);
131
+ },
132
+ async adapter(e, t) {
133
+ let n = (await a(e)).providers.find((e) => e.id === t), i = n?.accounts[0];
134
+ return !n || !i ? null : r(t, await c(e, n, i));
135
+ },
136
+ async models(e, t) {
137
+ let n = await d.adapter(e, t);
138
+ return n ? (await n.getCapabilities()).models : [];
139
+ },
140
+ async complete(e, t, n) {
141
+ let r = await d.adapter(e, t);
142
+ if (!r) throw Error("no-provider");
143
+ return r.complete(n);
144
+ },
145
+ async resolve(e, t) {
146
+ let n = await a(e);
147
+ return s(t, async (t, r) => {
148
+ if (t !== e) return;
149
+ let i = n.providers.find((e) => e.id === r), a = i?.accounts[0];
150
+ if (!i || !a) return;
151
+ let o = await c(e, i, a), s = o.apiKey ?? o.serviceAccount;
152
+ return s ? {
153
+ id: r,
154
+ apiKey: s,
155
+ ...o.accountId ? { accountId: o.accountId } : {},
156
+ ...o.baseUrl ? { baseUrl: o.baseUrl } : {},
157
+ ...o.projectId ? { projectId: o.projectId } : {},
158
+ ...o.location ? { location: o.location } : {}
159
+ } : void 0;
160
+ });
161
+ }
162
+ };
163
+ return d;
164
+ }
165
+ //#endregion
166
+ //#region src/server/memories.ts
167
+ var C = "agentico_memories", w = class extends Error {
168
+ code;
169
+ constructor(e, t) {
170
+ super(t), this.name = "MemoryError", this.code = e;
171
+ }
172
+ }, T = (e) => `memory/${e}/key`, ee = /^[A-Za-z0-9_.:-]{1,120}$/;
173
+ function E(e, t) {
174
+ let n = String(e ?? "").trim().replace(/\/+$/, "");
175
+ if (!n) {
176
+ if (t) throw new w("invalid", "URL_REQUIRED");
177
+ return;
178
+ }
179
+ let r;
180
+ try {
181
+ r = new URL(n);
182
+ } catch {
183
+ throw new w("invalid", "INVALID_URL");
184
+ }
185
+ if (r.protocol !== "https:" && !(r.protocol === "http:" && ["localhost", "127.0.0.1"].includes(r.hostname))) throw new w("invalid", "INVALID_URL");
186
+ return n;
187
+ }
188
+ function D(e) {
189
+ let { records: t, secrets: n } = e, r = e.fetch ?? fetch, i = e.newId ?? (() => crypto.randomUUID().replace(/-/g, "").slice(0, 12)), a = e.now ?? Date.now, o = async (e) => {
190
+ let n = await t.get(C, e);
191
+ if (!n) throw new w("not-found", "MEMORY_NOT_FOUND");
192
+ return n;
193
+ }, s = async (e, t, n, i, a) => {
194
+ try {
195
+ return await r(`${e}${i}`, {
196
+ method: n,
197
+ headers: {
198
+ "content-type": "application/json",
199
+ authorization: `Bearer ${t}`,
200
+ "x-api-key": t
201
+ },
202
+ ...a === void 0 ? {} : { body: JSON.stringify(a) },
203
+ signal: AbortSignal.timeout(2e4)
204
+ });
205
+ } catch {
206
+ throw new w("unreachable", "MEMORY_UNREACHABLE");
207
+ }
208
+ }, c = (e) => `/ns/${encodeURIComponent(e)}`, l = async (e) => {
209
+ let t = await o(e), r = await n.get(T(e));
210
+ if (!r) throw new w("not-found", "KEY_NOT_FOUND");
211
+ return {
212
+ record: t,
213
+ key: r
214
+ };
215
+ }, u = {
216
+ async list() {
217
+ return (await t.list(C)).map(({ createdAt: e, ...t }) => t).sort((e, t) => e.name.localeCompare(t.name));
218
+ },
219
+ async check(e) {
220
+ let t;
221
+ try {
222
+ t = E(e.apiUrl, !0);
223
+ } catch {
224
+ return {
225
+ ok: !1,
226
+ error: "invalid"
227
+ };
228
+ }
229
+ if (!String(e.key ?? "").trim()) return {
230
+ ok: !1,
231
+ error: "invalid"
232
+ };
233
+ try {
234
+ let n = await s(t, e.key.trim(), "POST", `${c("agentico-connection-check")}/search`, {
235
+ query: "connection check",
236
+ limit: 1
237
+ });
238
+ return n.ok ? { ok: !0 } : {
239
+ ok: !1,
240
+ error: n.status === 401 || n.status === 403 ? "rejected" : "unreachable",
241
+ status: n.status
242
+ };
243
+ } catch {
244
+ return {
245
+ ok: !1,
246
+ error: "unreachable"
247
+ };
248
+ }
249
+ },
250
+ async add(e) {
251
+ let r = E(e.apiUrl, !0), o = E(e.mcpUrl, !1);
252
+ if ((await t.list("agentico_memories")).some((e) => e.apiUrl === r)) throw new w("conflict", "MEMORY_ALREADY_CONNECTED");
253
+ let s = await u.check({
254
+ apiUrl: r,
255
+ key: e.key
256
+ });
257
+ if (!s.ok) throw new w(s.error === "invalid" ? "invalid" : s.error, s.error.toUpperCase());
258
+ let c = i();
259
+ await n.set(T(c), e.key.trim());
260
+ let l = {
261
+ id: c,
262
+ name: String(e.name ?? "").trim().slice(0, 100) || new URL(r).hostname,
263
+ apiUrl: r,
264
+ ...o ? { mcpUrl: o } : {},
265
+ createdAt: a()
266
+ };
267
+ await t.put(C, l);
268
+ let { createdAt: d, ...f } = l;
269
+ return f;
270
+ },
271
+ async update(e, r) {
272
+ let i = await o(e);
273
+ if (r.key?.trim()) {
274
+ let t = await u.check({
275
+ apiUrl: i.apiUrl,
276
+ key: r.key
277
+ });
278
+ if (!t.ok) throw new w(t.error === "invalid" ? "invalid" : t.error, t.error.toUpperCase());
279
+ await n.set(T(e), r.key.trim());
280
+ }
281
+ let a = { ...i };
282
+ typeof r.name == "string" && r.name.trim() && (a.name = r.name.trim().slice(0, 100)), r.mcpUrl === null || r.mcpUrl === "" ? delete a.mcpUrl : typeof r.mcpUrl == "string" && (a.mcpUrl = E(r.mcpUrl, !1)), await t.put(C, a);
283
+ let { createdAt: s, ...c } = a;
284
+ return c;
285
+ },
286
+ async remove(e, r) {
287
+ if (await o(e), r) throw new w("conflict", "MEMORY_IN_USE");
288
+ await n.delete(T(e)), await t.delete(C, e);
289
+ },
290
+ async search(e, t, n, r = 10) {
291
+ if (!String(n ?? "").trim()) throw new w("invalid", "QUERY_REQUIRED");
292
+ let { record: i, key: a } = await l(e), o = await s(i.apiUrl, a, "POST", `${c(t)}/search`, {
293
+ query: n.trim().slice(0, 2e3),
294
+ limit: Math.min(Math.max(Math.trunc(r) || 10, 1), 50)
295
+ });
296
+ if (!o.ok) throw new w(o.status === 401 || o.status === 403 ? "rejected" : "unreachable", `MEMORY_${o.status}`);
297
+ return ((await o.json().catch(() => ({}))).results ?? []).map((e) => {
298
+ let t = e.metadata && typeof e.metadata == "object" ? e.metadata : void 0;
299
+ return {
300
+ ...typeof e.id == "string" ? { id: e.id } : {},
301
+ ...typeof t?.title == "string" ? { title: t.title } : {},
302
+ content: String(e.chunk ?? e.content ?? ""),
303
+ ...typeof e.similarity == "number" ? { score: e.similarity } : typeof e.score == "number" ? { score: e.score } : {},
304
+ ...t ? { metadata: t } : {}
305
+ };
306
+ });
307
+ },
308
+ async write(e, t, n) {
309
+ let r = String(n.title ?? "").trim().slice(0, 200), i = String(n.content ?? "").trim();
310
+ if (!r || !i || i.length > 2e5) throw new w("invalid", "DOCUMENT_INVALID");
311
+ if (n.documentId !== void 0 && !ee.test(n.documentId)) throw new w("invalid", "DOCUMENT_ID_INVALID");
312
+ let { record: a, key: o } = await l(e), u = {
313
+ content: `# ${r}\n\n${i}`,
314
+ metadata: {
315
+ title: r,
316
+ tags: t
317
+ }
318
+ };
319
+ if (n.documentId) {
320
+ let e = await s(a.apiUrl, o, "PATCH", `${c(t)}/document/${encodeURIComponent(n.documentId)}`, u);
321
+ if (e.ok) return { id: n.documentId };
322
+ if (e.status !== 404) throw new w(e.status === 401 || e.status === 403 ? "rejected" : "unreachable", `MEMORY_${e.status}`);
323
+ }
324
+ let d = await s(a.apiUrl, o, "POST", `${c(t)}/document`, {
325
+ ...u,
326
+ ...n.documentId ? { id: n.documentId } : {}
327
+ });
328
+ if (!d.ok) throw new w(d.status === 401 || d.status === 403 ? "rejected" : "unreachable", `MEMORY_${d.status}`);
329
+ let f = await d.json().catch(() => ({}));
330
+ return typeof f.id == "string" ? { id: f.id } : {};
331
+ },
332
+ async coordinates(e, t) {
333
+ let n = await o(e);
334
+ return {
335
+ apiUrl: n.apiUrl,
336
+ ...n.mcpUrl ? { mcpUrl: n.mcpUrl } : {},
337
+ namespace: t
338
+ };
339
+ }
340
+ };
341
+ return u;
342
+ }
343
+ //#endregion
344
+ //#region src/server/namespace.ts
345
+ var O = /^[a-z0-9]{1,32}$/, k = /^[a-z0-9][a-z0-9-]{0,29}$/, A = class extends Error {
346
+ constructor(e) {
347
+ super(e), this.name = "NamespaceError";
348
+ }
349
+ };
350
+ function j(e, t) {
351
+ if (!O.test(e)) throw new A(`invalid project "${e}"`);
352
+ if (t === void 0 || t === "") return e;
353
+ if (!k.test(t)) throw new A(`invalid tenant "${t}"`);
354
+ return `${e}-${t}`;
355
+ }
356
+ var M = (e, t) => t === e || t.startsWith(`${e}-`), N = (e, t) => t === e ? void 0 : t.slice(e.length + 1), P = "agentico_runners", F = "agentico_runner_pairings", I = "agentico_namespaces", L = "agentico_runner_chats", R = "agentico_runner_installs", z = class extends Error {
357
+ code;
358
+ constructor(e, t) {
359
+ super(t), this.name = "FleetError", this.code = e;
360
+ }
361
+ }, B = [
362
+ "complete",
363
+ "chat",
364
+ "chat:tools",
365
+ "accounts",
366
+ "act-as-user"
367
+ ], V = [...B, "accounts:tenant"], H = (e) => `runner/${e}/platform`, U = (e) => `runner-pairing/${e}`, W = (e, t) => `namespace/${e}/runner/${t}`;
368
+ function G(e) {
369
+ let t;
370
+ try {
371
+ t = new URL(e.trim().replace(/\/+$/, ""));
372
+ } catch {
373
+ throw new z("invalid", "INVALID_URL");
374
+ }
375
+ if (t.protocol !== "https:" || t.pathname !== "/" || t.search || t.hash) throw new z("invalid", "INVALID_URL");
376
+ return t.origin;
377
+ }
378
+ var K = (e) => ({
379
+ id: e.id,
380
+ name: e.name,
381
+ url: e.url,
382
+ isDefault: e.isDefault,
383
+ draining: e.draining
384
+ });
385
+ function q(t) {
386
+ let { project: n, records: r, secrets: i } = t, a = t.connect ?? ((t, n) => new e({
387
+ url: t,
388
+ ...n ? { key: n } : {}
389
+ })), o = t.install ?? c, s = t.newId ?? (() => crypto.randomUUID().replace(/-/g, "").slice(0, 12)), l = t.now ?? Date.now, u = async (e) => {
390
+ let t = await r.get(P, e);
391
+ if (!t) throw new z("not-found", "RUNNER_NOT_FOUND");
392
+ return t;
393
+ }, d = async (e) => {
394
+ let t = await i.get(e);
395
+ if (!t) throw new z("not-found", "KEY_NOT_FOUND");
396
+ return t;
397
+ }, f = async (e) => a(e.url, await d(H(e.id))), p = async (e) => {
398
+ let t = G(e);
399
+ if ((await r.list("agentico_runners")).some((e) => e.url === t)) throw new z("conflict", "RUNNER_ALREADY_CONNECTED");
400
+ return t;
401
+ }, m = (e, t) => String(t ?? "").trim() || new URL(e).hostname, h = async (e) => {
402
+ let t = s(), n = l();
403
+ await i.set(H(t), e.key);
404
+ let a = {
405
+ id: t,
406
+ name: e.name,
407
+ url: e.url,
408
+ isDefault: (await r.list(P)).length === 0,
409
+ draining: !1,
410
+ ...e.keyId ? { keyId: e.keyId } : {},
411
+ ...e.hostFingerprint ? { hostFingerprint: e.hostFingerprint } : {},
412
+ createdAt: n,
413
+ updatedAt: n
414
+ };
415
+ return await r.put(P, a), K(a);
416
+ }, g = async (e) => await r.get("agentico_namespaces", e) ?? { id: e }, _ = {
417
+ async list() {
418
+ return (await r.list(P)).map(K).sort((e, t) => e.name.localeCompare(t.name));
419
+ },
420
+ async add(e, r = {}) {
421
+ let i = await p(String(e.url ?? "")), o = m(i, e.name);
422
+ if (e.code) {
423
+ let s = await a(i).pair(String(e.code).trim(), t.platformName, n);
424
+ return h({
425
+ name: o,
426
+ url: i,
427
+ key: s.key,
428
+ keyId: s.record.id,
429
+ ...r
430
+ });
431
+ }
432
+ if (e.key) {
433
+ let t = String(e.key).trim();
434
+ return await a(i, t).platform.status(), h({
435
+ name: o,
436
+ url: i,
437
+ key: t,
438
+ ...r
439
+ });
440
+ }
441
+ throw new z("invalid", "CODE_OR_KEY_REQUIRED");
442
+ },
443
+ async startPairing(e, o) {
444
+ let c = await p(String(e.url ?? "")), l = await a(c).requestPairing(t.platformName, n), u = s();
445
+ return await i.set(U(u), l.request), await r.put(F, {
446
+ id: u,
447
+ name: m(c, e.name),
448
+ url: c,
449
+ startedBy: o,
450
+ expiresAt: l.expiresAt
451
+ }), {
452
+ id: u,
453
+ code: l.code,
454
+ approveUrl: l.approveUrl,
455
+ expiresAt: l.expiresAt
456
+ };
457
+ },
458
+ async pairingStatus(e, t) {
459
+ let n = await r.get(F, e), o = await i.get(U(e)), s = async () => {
460
+ await r.delete(F, e), await i.delete(U(e));
461
+ };
462
+ if (!n || n.startedBy !== t || !o) return { status: "expired" };
463
+ if (Date.parse(n.expiresAt) <= l()) return await s(), { status: "expired" };
464
+ let c = await a(n.url).pollPairing(o);
465
+ return c.status === "pending" ? { status: "pending" } : (await s(), c.status === "approved" ? {
466
+ status: "approved",
467
+ runner: await h({
468
+ name: n.name,
469
+ url: n.url,
470
+ key: c.key,
471
+ keyId: c.record.id
472
+ })
473
+ } : { status: c.status });
474
+ },
475
+ async update(e, t) {
476
+ let n = {
477
+ ...await u(e),
478
+ updatedAt: l()
479
+ };
480
+ if (typeof t.name == "string" && t.name.trim() && (n.name = t.name.trim().slice(0, 100)), typeof t.draining == "boolean" && (n.draining = t.draining), typeof t.isDefault == "boolean" && (n.isDefault = t.isDefault, t.isDefault)) for (let t of await r.list(P)) t.id !== e && t.isDefault && await r.put(P, {
481
+ ...t,
482
+ isDefault: !1,
483
+ updatedAt: l()
484
+ });
485
+ await r.put(P, n);
486
+ },
487
+ async remove(e) {
488
+ let t = await u(e);
489
+ if ((await r.list("agentico_namespaces")).some((t) => t.runnerId === e)) throw new z("conflict", "RUNNER_HAS_NAMESPACES");
490
+ t.keyId && await f(t).then((e) => e.platform.revokePlatformKey(t.keyId)).catch(() => !1), await i.delete(H(e)), await r.delete(P, e);
491
+ },
492
+ async status(e) {
493
+ return (await f(await u(e))).platform.status();
494
+ },
495
+ async assign(e, n, a = {}) {
496
+ let o = await g(e), s = await u(n);
497
+ if (o.runnerId === n && await i.get(W(e, n))) return;
498
+ if (s.draining) throw new z("conflict", "RUNNER_DRAINING");
499
+ let c = await f(s), l = (await c.platform.tenants()).some((t) => t.id === e), d, p;
500
+ if (l) {
501
+ let n = await c.platform.createKey(e, {
502
+ name: t.platformName,
503
+ permissions: V
504
+ });
505
+ d = n.key, p = n.record.id;
506
+ } else {
507
+ let t = await c.platform.createTenant(e, {
508
+ ...a.name ? { name: a.name } : {},
509
+ keyPermissions: V
510
+ });
511
+ if (!t.key || !t.keyRecord) throw Error("the runner made the tenant without a key");
512
+ d = t.key, p = t.keyRecord.id;
513
+ }
514
+ if (await i.set(W(e, n), d), !a.keepBefore && o.runnerId && o.runnerId !== n && o.runnerKeyId) {
515
+ let t = await r.get(P, o.runnerId);
516
+ t && await f(t).then((t) => t.platform.revokeKey(e, o.runnerKeyId)).catch(() => !1), await i.delete(W(e, o.runnerId));
517
+ }
518
+ await r.put(I, {
519
+ ...o,
520
+ runnerId: n,
521
+ runnerKeyId: p
522
+ });
523
+ },
524
+ async route(e, t = {}) {
525
+ if (t.chat && t.user) {
526
+ let n = await r.get(L, `${e}_${t.user}_${t.chat}`), a = n ? await r.get(P, n.runnerId) : null, o = a ? await i.get(W(e, a.id)) : null;
527
+ if (a && o) return {
528
+ runnerId: a.id,
529
+ url: a.url,
530
+ key: o
531
+ };
532
+ }
533
+ let n = await r.list(P), a = await g(e), o = a.runnerId ? n.find((e) => e.id === a.runnerId) : void 0, s = n.find((e) => e.isDefault && !e.draining && e.id !== o?.id) ?? (o ? void 0 : n.find((e) => !e.draining));
534
+ if (o) t.newChat && o.draining && s && (await _.assign(e, s.id, { keepBefore: !0 }), a = await g(e));
535
+ else {
536
+ if (!s) return null;
537
+ await _.assign(e, s.id), a = await g(e);
538
+ }
539
+ let c = a.runnerId ? await r.get(P, a.runnerId) : null, l = c ? await i.get(W(e, c.id)) : null;
540
+ return c && l ? {
541
+ runnerId: c.id,
542
+ url: c.url,
543
+ key: l
544
+ } : null;
545
+ },
546
+ async chatStarted(e, t, n, i) {
547
+ await r.put(L, {
548
+ id: `${e}_${t}_${n}`,
549
+ runnerId: i
550
+ });
551
+ },
552
+ async chatClosed(e, t, n) {
553
+ await r.delete(L, `${e}_${t}_${n}`);
554
+ },
555
+ async install(e, t, n) {
556
+ if (!e.access?.host || !e.access.username || !e.access.privateKey && !e.access.password) throw new z("invalid", "SSH_ACCESS_REQUIRED");
557
+ if (!String(e.domain ?? "").trim()) throw new z("invalid", "DOMAIN_REQUIRED");
558
+ let i = s(), a = {
559
+ id: i,
560
+ status: "running",
561
+ lines: [],
562
+ startedBy: t
563
+ };
564
+ await r.put(R, a);
565
+ let c = Promise.resolve(), l = (e) => {
566
+ n?.(e), a.lines = [...a.lines, e.line].slice(-2e3), c = c.then(() => r.put(R, a)).catch(() => void 0);
567
+ }, u = (async () => {
568
+ try {
569
+ let t = await o(e.access, {
570
+ domain: e.domain,
571
+ ...e.version ? { version: e.version } : {},
572
+ onProgress: l
573
+ }), n = await _.add({
574
+ name: e.name,
575
+ url: t.url,
576
+ code: t.pairingCode
577
+ }, { hostFingerprint: t.hostFingerprint });
578
+ return await c, await r.put(R, {
579
+ ...a,
580
+ status: "done",
581
+ runnerId: n.id
582
+ }), n;
583
+ } catch (e) {
584
+ throw await c, await r.put(R, {
585
+ ...a,
586
+ status: "error",
587
+ error: e instanceof Error ? e.message : String(e)
588
+ }), e;
589
+ }
590
+ })();
591
+ return u.catch(() => void 0), {
592
+ installId: i,
593
+ done: u
594
+ };
595
+ },
596
+ async installState(e, t, n = 0) {
597
+ let i = await r.get(R, e);
598
+ return !i || i.startedBy !== t ? null : {
599
+ status: i.status,
600
+ lines: i.lines.slice(n),
601
+ next: i.lines.length,
602
+ ...i.runnerId ? { runnerId: i.runnerId } : {},
603
+ ...i.error ? { error: i.error } : {}
604
+ };
605
+ }
606
+ };
607
+ return _;
608
+ }
609
+ //#endregion
610
+ //#region src/server/server.ts
611
+ var J = class extends Error {
612
+ status;
613
+ constructor(e, t) {
614
+ super(t), this.status = e;
615
+ }
616
+ }, Y = {
617
+ member: 0,
618
+ admin: 1,
619
+ platform: 2
620
+ }, X = (e, t) => new Response(JSON.stringify(t), {
621
+ status: e,
622
+ headers: {
623
+ "content-type": "application/json",
624
+ "cache-control": "no-store"
625
+ }
626
+ }), te = /^\/v1\/(info|models|complete|accounts(\/.*)?|chats(\/.*)?)$/, ne = /^\/v1\/chats\/([a-f0-9]{8})(\/.*)?$/, re = /* @__PURE__ */ new Set([
627
+ "host",
628
+ "cookie",
629
+ "content-length",
630
+ "connection",
631
+ "origin",
632
+ "referer",
633
+ "x-llmnative-proxy"
634
+ ]);
635
+ function ie(e) {
636
+ let { records: n, secrets: r } = e, i = e.log ?? (() => void 0), a = e.fetch ?? fetch, o = S({
637
+ records: n,
638
+ secrets: r,
639
+ ...e.adapter ? { adapter: e.adapter } : {}
640
+ }), s = D({
641
+ records: n,
642
+ secrets: r,
643
+ fetch: a,
644
+ ...e.now ? { now: e.now } : {}
645
+ }), c = /* @__PURE__ */ new Map(), l = (t) => {
646
+ let i = c.get(t);
647
+ return i || (i = q({
648
+ project: t,
649
+ platformName: e.platformName,
650
+ records: n,
651
+ secrets: r,
652
+ ...e.connectRunner ? { connect: e.connectRunner } : {},
653
+ ...e.install ? { install: e.install } : {},
654
+ ...e.now ? { now: e.now } : {}
655
+ }), c.set(t, i)), i;
656
+ }, u = (e, t) => {
657
+ if (Y[e.role] < Y[t]) throw new J(403, "forbidden");
658
+ }, d = async (e) => {
659
+ try {
660
+ let t = await e.json();
661
+ return t && typeof t == "object" ? t : {};
662
+ } catch {
663
+ return {};
664
+ }
665
+ }, f = (e, t) => {
666
+ let n = j(e.project, e.tenant), r = t.searchParams.get("namespace");
667
+ if (!r || r === n) return n;
668
+ if (u(e, "platform"), !M(e.project, r)) throw new J(404, "not found");
669
+ return j(e.project, N(e.project, r)), r;
670
+ }, p = async (e) => (await n.list(I)).filter((t) => M(e, t.id)), m = async (e) => await n.get("agentico_namespaces", e) ?? { id: e };
671
+ async function h(e, t, n, r) {
672
+ if (!te.test(n) || r && !n.startsWith("/v1/accounts") || ![
673
+ "GET",
674
+ "POST",
675
+ "PUT",
676
+ "DELETE"
677
+ ].includes(e.method)) return X(404, { error: "not found" });
678
+ let o = j(t.project, t.tenant), s = l(t.project), c = ne.exec(n)?.[1], u = n === "/v1/chats" && e.method === "POST", d = e.method === "GET" || e.method === "DELETE" ? void 0 : await e.arrayBuffer(), f = u && d ? (() => {
679
+ try {
680
+ let e = JSON.parse(new TextDecoder().decode(d));
681
+ return typeof e.id == "string" ? e.id : void 0;
682
+ } catch {
683
+ return;
684
+ }
685
+ })() : void 0, p = await s.route(o, {
686
+ newChat: u,
687
+ ...c ? {
688
+ chat: c,
689
+ user: t.user.id
690
+ } : {}
691
+ }).catch(() => null);
692
+ if (!p) return X(409, { error: "no-runner" });
693
+ let m = { authorization: `Bearer ${p.key}` };
694
+ r || (m["x-runner-user"] = t.user.id);
695
+ let h = e.headers.get("content-type");
696
+ h && (m["content-type"] = h);
697
+ let g;
698
+ try {
699
+ g = await a(`${p.url}${n}${new URL(e.url).search}`, {
700
+ method: e.method,
701
+ headers: m,
702
+ ...d ? { body: d } : {},
703
+ signal: e.signal
704
+ });
705
+ } catch {
706
+ return X(502, { error: "unreachable" });
707
+ }
708
+ return f && g.ok && await s.chatStarted(o, t.user.id, f, p.runnerId), c && e.method === "DELETE" && n === `/v1/chats/${c}` && await s.chatClosed(o, t.user.id, c).catch(() => void 0), i("runner request", {
709
+ namespace: o,
710
+ user: t.user.id,
711
+ path: n.replace(/[a-f0-9]{8}/, ":chat"),
712
+ status: g.status
713
+ }), new Response(g.body, {
714
+ status: g.status,
715
+ headers: {
716
+ "content-type": g.headers.get("content-type") ?? "application/json",
717
+ "cache-control": "no-store",
718
+ "x-accel-buffering": "no"
719
+ }
720
+ });
721
+ }
722
+ async function g(t, r, c, g) {
723
+ let _ = c.split("/").filter(Boolean).map(decodeURIComponent), [v, y, b, x] = _, S = t.method, C = r.project;
724
+ if (v === "me" && S === "GET") return X(200, {
725
+ user: r.user,
726
+ role: r.role,
727
+ project: C,
728
+ ...r.tenant ? { tenant: r.tenant } : {},
729
+ namespace: j(C, r.tenant)
730
+ });
731
+ if (v === "connections") {
732
+ let e = f(r, g);
733
+ if (!y && S === "GET") return X(200, await o.snapshot(e));
734
+ if (y === "order" && !b && S === "PUT") {
735
+ u(r, "admin");
736
+ let n = (await d(t)).order;
737
+ return await o.setOrder(e, Array.isArray(n) ? n.map(String) : null), X(200, { ok: !0 });
738
+ }
739
+ if (y && !b && S === "GET") return X(404, { error: "not found" });
740
+ if (y && b === "models" && S === "GET") return X(200, { models: await o.models(e, y) });
741
+ u(r, "admin");
742
+ let n = async () => {
743
+ let e = (await d(t)).fields;
744
+ return Object.fromEntries(Object.entries(e && typeof e == "object" ? e : {}).map(([e, t]) => [e, String(t ?? "")]));
745
+ };
746
+ if (y && !b && S === "POST") {
747
+ let t = await o.connect(e, y, await n());
748
+ return i("connection", {
749
+ namespace: e,
750
+ provider: y,
751
+ ok: t.ok,
752
+ by: r.user.id
753
+ }), X(t.ok ? 200 : 422, t);
754
+ }
755
+ if (y && !b && S === "DELETE") return await o.disconnect(e, y), X(200, { ok: !0 });
756
+ if (y && b === "accounts" && !x && S === "POST") {
757
+ let t = await o.addAccount(e, y, await n());
758
+ return X(t.ok ? 200 : 422, t);
759
+ }
760
+ if (y && b === "accounts" && x === "order" && S === "PUT") {
761
+ let n = (await d(t)).ids;
762
+ return await o.orderAccounts(e, y, Array.isArray(n) ? n.map(String) : []), X(200, { ok: !0 });
763
+ }
764
+ if (y && b === "accounts" && x && S === "DELETE") return await o.removeAccount(e, y, x), X(200, { ok: !0 });
765
+ }
766
+ if (v === "ai" && y === "complete" && S === "POST") {
767
+ let e = await d(t), n = String(e.provider ?? ""), a = await o.complete(j(C, r.tenant), n, e.request).catch((e) => {
768
+ throw new J(e instanceof Error && e.message === "no-provider" ? 409 : 502, e instanceof Error && e.message === "no-provider" ? "no-provider" : "failed");
769
+ });
770
+ return i("ai complete", {
771
+ namespace: j(C, r.tenant),
772
+ provider: n,
773
+ user: r.user.id
774
+ }), X(200, { result: a });
775
+ }
776
+ if (v === "ai" && y === "proxy") {
777
+ let n = g.searchParams.get("url") ?? "", i = /* @__PURE__ */ new Set([...re, ...(e.sessionHeaders ?? []).map((e) => e.toLowerCase())]), s = {};
778
+ t.headers.forEach((e, t) => {
779
+ i.has(t.toLowerCase()) || (s[t] = e);
780
+ });
781
+ let c = await o.resolve(j(C, r.tenant), {
782
+ url: n,
783
+ headers: s
784
+ });
785
+ if (!c.ok) return X(c.status, { error: c.error });
786
+ if (new URL(c.url).protocol !== "https:") return X(403, { error: "forbidden-target" });
787
+ let l = S === "GET" || S === "HEAD" ? void 0 : await t.arrayBuffer(), u = await a(c.url, {
788
+ method: S,
789
+ headers: c.headers,
790
+ ...l && l.byteLength ? { body: l } : {},
791
+ signal: t.signal
792
+ }).catch(() => null);
793
+ return u ? new Response(u.body, {
794
+ status: u.status,
795
+ headers: {
796
+ "content-type": u.headers.get("content-type") ?? "application/json",
797
+ "cache-control": "no-store"
798
+ }
799
+ }) : X(502, { error: "unreachable" });
800
+ }
801
+ if (v === "runner") return h(t, r, `/${_.slice(1).map(encodeURIComponent).join("/")}`, !1);
802
+ if (v === "runner-namespace") return u(r, "admin"), h(t, r, `/${_.slice(1).map(encodeURIComponent).join("/")}`, !0);
803
+ if (v === "runners") {
804
+ u(r, "platform");
805
+ let e = l(C);
806
+ if (!y && S === "GET") return X(200, { runners: await e.list() });
807
+ if (!y && S === "POST") {
808
+ let n = await d(t), a = await e.add({
809
+ url: String(n.url ?? ""),
810
+ ...typeof n.name == "string" ? { name: n.name } : {},
811
+ ...typeof n.code == "string" ? { code: n.code } : {},
812
+ ...typeof n.key == "string" ? { key: n.key } : {}
813
+ });
814
+ return i("runner connected", {
815
+ project: C,
816
+ runner: a.id,
817
+ by: r.user.id
818
+ }), X(201, { runner: a });
819
+ }
820
+ if (y === "pairings" && !b && S === "POST") {
821
+ let n = await d(t);
822
+ return X(201, await e.startPairing({
823
+ url: String(n.url ?? ""),
824
+ ...typeof n.name == "string" ? { name: n.name } : {}
825
+ }, r.user.id));
826
+ }
827
+ if (y === "pairings" && b && S === "GET") return X(200, await e.pairingStatus(b, r.user.id));
828
+ if (y === "installs" && !b && S === "POST") {
829
+ let n = await d(t), a = await e.install({
830
+ domain: String(n.domain ?? ""),
831
+ access: n.access ?? {},
832
+ ...typeof n.name == "string" ? { name: n.name } : {},
833
+ ...typeof n.version == "string" ? { version: n.version } : {}
834
+ }, r.user.id);
835
+ return i("runner install", {
836
+ project: C,
837
+ install: a.installId,
838
+ by: r.user.id
839
+ }), X(202, { installId: a.installId });
840
+ }
841
+ if (y === "installs" && b && S === "GET") {
842
+ let t = await e.installState(b, r.user.id, Number(g.searchParams.get("from")) || 0);
843
+ return t ? X(200, t) : X(404, { error: "not found" });
844
+ }
845
+ if (y && !b && S === "PATCH") {
846
+ let n = await d(t);
847
+ return await e.update(y, {
848
+ ...typeof n.name == "string" ? { name: n.name } : {},
849
+ ...typeof n.isDefault == "boolean" ? { isDefault: n.isDefault } : {},
850
+ ...typeof n.draining == "boolean" ? { draining: n.draining } : {}
851
+ }), X(200, { ok: !0 });
852
+ }
853
+ if (y && !b && S === "DELETE") return await e.remove(y), X(200, { ok: !0 });
854
+ if (y && b === "status" && S === "GET") return X(200, await e.status(y));
855
+ }
856
+ if (v === "memories") {
857
+ if (u(r, "platform"), !y && S === "GET") return X(200, { memories: await s.list() });
858
+ if (y === "check" && S === "POST") {
859
+ let e = await d(t);
860
+ return X(200, await s.check({
861
+ apiUrl: String(e.apiUrl ?? ""),
862
+ key: String(e.key ?? "")
863
+ }));
864
+ }
865
+ if (!y && S === "POST") {
866
+ let e = await d(t), n = await s.add({
867
+ apiUrl: String(e.apiUrl ?? ""),
868
+ key: String(e.key ?? ""),
869
+ ...typeof e.name == "string" ? { name: e.name } : {},
870
+ ...typeof e.mcpUrl == "string" ? { mcpUrl: e.mcpUrl } : {}
871
+ });
872
+ return i("memory connected", {
873
+ project: C,
874
+ memory: n.id,
875
+ by: r.user.id
876
+ }), X(201, { memory: n });
877
+ }
878
+ if (y && S === "PATCH") {
879
+ let e = await d(t);
880
+ return X(200, { memory: await s.update(y, {
881
+ ...typeof e.name == "string" ? { name: e.name } : {},
882
+ ...e.mcpUrl === null || typeof e.mcpUrl == "string" ? { mcpUrl: e.mcpUrl } : {},
883
+ ...typeof e.key == "string" ? { key: e.key } : {}
884
+ }) });
885
+ }
886
+ if (y && S === "DELETE") return await s.remove(y, (await n.list(I)).some((e) => e.memoryId === y)), X(200, { ok: !0 });
887
+ }
888
+ if (v === "memory") {
889
+ let e = j(C, r.tenant), n = (await m(e)).memoryId;
890
+ if (!y && S === "GET") return X(200, n ? {
891
+ configured: !0,
892
+ ...await s.coordinates(n, e)
893
+ } : { configured: !1 });
894
+ if (!n) return X(409, { error: "no-memory" });
895
+ let a = await d(t);
896
+ if (y === "search" && S === "POST") return X(200, { results: await s.search(n, e, String(a.query ?? ""), Number(a.limit) || 10) });
897
+ if (y === "write" && S === "POST") {
898
+ let t = await s.write(n, e, {
899
+ title: String(a.title ?? ""),
900
+ content: String(a.content ?? ""),
901
+ ...typeof a.documentId == "string" ? { documentId: a.documentId } : {}
902
+ });
903
+ return i("memory write", {
904
+ namespace: e,
905
+ user: r.user.id
906
+ }), X(200, t);
907
+ }
908
+ }
909
+ if (v === "projects" && !y && S === "GET") {
910
+ u(r, "admin");
911
+ let [t, n, i, a] = await Promise.all([
912
+ Y[r.role] >= Y.platform ? l(C).list() : Promise.resolve([]),
913
+ Y[r.role] >= Y.platform ? s.list() : Promise.resolve([]),
914
+ p(C),
915
+ e.tenants && r.role === "platform" ? e.tenants(r) : Promise.resolve([])
916
+ ]), o = j(C, r.tenant), c = /* @__PURE__ */ new Map();
917
+ if (c.set(o, void 0), r.role === "platform") {
918
+ for (let e of i) c.set(e.id, void 0);
919
+ for (let e of a) try {
920
+ c.set(j(C, e.id), e.name);
921
+ } catch {}
922
+ }
923
+ return X(200, {
924
+ project: C,
925
+ namespaces: [...c.entries()].map(([e, r]) => {
926
+ let a = i.find((t) => t.id === e), o = t.find((e) => e.id === a?.runnerId), s = n.find((e) => e.id === a?.memoryId), c = N(C, e);
927
+ return {
928
+ namespace: e,
929
+ ...c ? { tenant: c } : {},
930
+ ...r ? { name: r } : {},
931
+ ...a?.runnerId ? { runner: {
932
+ id: a.runnerId,
933
+ ...o ? { name: o.name } : {}
934
+ } } : {},
935
+ ...a?.memoryId ? { memory: {
936
+ id: a.memoryId,
937
+ ...s ? { name: s.name } : {}
938
+ } } : {}
939
+ };
940
+ }).sort((e, t) => e.namespace.localeCompare(t.namespace))
941
+ });
942
+ }
943
+ if (v === "namespaces" && y && !b && S === "PUT") {
944
+ if (u(r, "platform"), !M(C, y)) throw new J(404, "not found");
945
+ j(C, N(C, y));
946
+ let e = await d(t);
947
+ if (typeof e.runnerId == "string" && e.runnerId && await l(C).assign(y, e.runnerId), e.memoryId !== void 0) {
948
+ let t = await m(y);
949
+ if (e.memoryId === null || e.memoryId === "") delete t.memoryId;
950
+ else {
951
+ if (!(await s.list()).some((t) => t.id === e.memoryId)) throw new J(404, "memory not found");
952
+ t.memoryId = String(e.memoryId);
953
+ }
954
+ await n.put(I, t);
955
+ }
956
+ return i("namespace set", {
957
+ namespace: y,
958
+ by: r.user.id
959
+ }), X(200, { ok: !0 });
960
+ }
961
+ return X(404, { error: "not found" });
962
+ }
963
+ return {
964
+ connections: o,
965
+ memories: s,
966
+ fleet: l,
967
+ async handle(n) {
968
+ let r = new URL(n.url), a = (e.basePath ?? "").replace(/\/+$/, "");
969
+ if (a && r.pathname !== a && !r.pathname.startsWith(`${a}/`)) return X(404, { error: "not found" });
970
+ let o = r.pathname.slice(a.length) || "/";
971
+ try {
972
+ let t = await e.identity(n);
973
+ return t ? await g(n, t, o, r) : X(401, { error: "unauthenticated" });
974
+ } catch (e) {
975
+ if (e instanceof J) return X(e.status, { error: e.message });
976
+ if (e instanceof A) return X(400, { error: "invalid namespace" });
977
+ if (e instanceof z) return X(e.code === "invalid" ? 400 : e.code === "not-found" ? 404 : 409, { error: e.message });
978
+ if (e instanceof w) {
979
+ let t = {
980
+ invalid: 400,
981
+ "not-found": 404,
982
+ conflict: 409,
983
+ unreachable: 502,
984
+ rejected: 422
985
+ }[e.code];
986
+ return X(t, { error: e.message });
987
+ }
988
+ return e instanceof t ? X(502, { error: e.code }) : (i("agentico server error", {
989
+ path: o,
990
+ error: e instanceof Error ? e.name : "error"
991
+ }), X(500, { error: "failed" }));
992
+ }
993
+ }
994
+ };
995
+ }
996
+ //#endregion
997
+ //#region src/server/stores.ts
998
+ function Z(e, t) {
999
+ return {
1000
+ async get(t, n) {
1001
+ return e()[t]?.[n] ?? null;
1002
+ },
1003
+ async list(t) {
1004
+ return Object.values(e()[t] ?? {});
1005
+ },
1006
+ async put(n, r) {
1007
+ let i = e();
1008
+ i[n] = {
1009
+ ...i[n] ?? {},
1010
+ [r.id]: structuredClone(r)
1011
+ }, t(i);
1012
+ },
1013
+ async delete(n, r) {
1014
+ let i = e();
1015
+ i[n]?.[r] && (delete i[n][r], t(i));
1016
+ }
1017
+ };
1018
+ }
1019
+ function Q(e, t) {
1020
+ return {
1021
+ async get(t) {
1022
+ return e()[t] ?? null;
1023
+ },
1024
+ async set(n, r) {
1025
+ t({
1026
+ ...e(),
1027
+ [n]: r
1028
+ });
1029
+ },
1030
+ async delete(n) {
1031
+ let r = e();
1032
+ delete r[n], t(r);
1033
+ }
1034
+ };
1035
+ }
1036
+ function ae() {
1037
+ let e = {}, t = {};
1038
+ return {
1039
+ records: Z(() => structuredClone(e), (t) => {
1040
+ e = t;
1041
+ }),
1042
+ secrets: Q(() => ({ ...t }), (e) => {
1043
+ t = e;
1044
+ })
1045
+ };
1046
+ }
1047
+ function $(e, t) {
1048
+ try {
1049
+ return l(e) ? JSON.parse(d(e, "utf8")) : t;
1050
+ } catch {
1051
+ return t;
1052
+ }
1053
+ }
1054
+ function oe(e, t) {
1055
+ let n = `${e}.tmp`;
1056
+ p(n, JSON.stringify(t, null, 2), { mode: 384 }), f(n, e);
1057
+ }
1058
+ function se(e) {
1059
+ u(e, {
1060
+ recursive: !0,
1061
+ mode: 448
1062
+ });
1063
+ let t = m(e, "records.json"), n = m(e, "secrets.json");
1064
+ return {
1065
+ records: Z(() => $(t, {}), (e) => oe(t, e)),
1066
+ secrets: Q(() => $(n, {}), (e) => oe(n, e))
1067
+ };
1068
+ }
1069
+ //#endregion
1070
+ export { h as CONNECTIONS, z as FleetError, C as MEMORIES, w as MemoryError, I as NAMESPACES, B as NAMESPACE_KEY_PERMISSIONS, A as NamespaceError, O as PROJECT_ID, P as RUNNERS, k as TENANT_ID, ie as createAgenticoServer, S as createConnections, q as createFleet, D as createMemories, v as defaultAdapterFactory, se as fileStores, M as inProject, ae as memoryStores, j as namespaceOf, G as normalizeRunnerUrl, N as tenantOf };
1071
+
1072
+ //# sourceMappingURL=server.mjs.map