@persql/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1772 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ApprovalRequiredError: () => ApprovalRequiredError,
24
+ PerSQL: () => PerSQL,
25
+ PerSQLApprovals: () => PerSQLApprovals,
26
+ PerSQLBlob: () => PerSQLBlob,
27
+ PerSQLBranches: () => PerSQLBranches,
28
+ PerSQLDatabase: () => PerSQLDatabase,
29
+ PerSQLError: () => PerSQLError,
30
+ PerSQLProposals: () => PerSQLProposals,
31
+ PerSQLVectors: () => PerSQLVectors,
32
+ RateLimitError: () => RateLimitError
33
+ });
34
+ module.exports = __toCommonJS(index_exports);
35
+
36
+ // src/local.ts
37
+ var PROPOSAL_TTL_DEFAULT_SEC = 600;
38
+ var PROPOSAL_TTL_MAX_SEC = 3600;
39
+ function newLocalProposalId() {
40
+ const buf = new Uint8Array(8);
41
+ crypto.getRandomValues(buf);
42
+ let hex = "";
43
+ for (const b of buf) hex += b.toString(16).padStart(2, "0");
44
+ return `pmut_local_${hex}`;
45
+ }
46
+ var LocalDriver = class {
47
+ constructor(path) {
48
+ this.path = path;
49
+ }
50
+ db = null;
51
+ proposals = /* @__PURE__ */ new Map();
52
+ async open() {
53
+ if (this.db) return this.db;
54
+ const moduleName = "better-sqlite3";
55
+ let mod;
56
+ try {
57
+ mod = await import(moduleName);
58
+ } catch {
59
+ throw new Error(
60
+ "PerSQL local mode requires the `better-sqlite3` peer dep. Install with `npm i -D better-sqlite3` (or pnpm/yarn equivalent)."
61
+ );
62
+ }
63
+ const m = mod;
64
+ const Ctor = m.default ?? mod;
65
+ this.db = new Ctor(this.path);
66
+ this.db.pragma("foreign_keys = ON");
67
+ return this.db;
68
+ }
69
+ async query(sql, params) {
70
+ const db = await this.open();
71
+ return runOne(db, sql, params);
72
+ }
73
+ async batch(statements, transaction) {
74
+ const db = await this.open();
75
+ const exec = () => statements.map((s) => runOne(db, s.sql, s.params ?? []));
76
+ if (transaction) return db.transaction(exec)();
77
+ return exec();
78
+ }
79
+ async tables() {
80
+ const db = await this.open();
81
+ const rows = runOne(
82
+ db,
83
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name",
84
+ []
85
+ ).rows;
86
+ return rows.map(([name]) => {
87
+ const c = runOne(db, `SELECT COUNT(*) FROM "${name.replace(/"/g, '""')}"`, []).rows[0];
88
+ return { name, rowCount: Number(c?.[0] ?? 0) };
89
+ });
90
+ }
91
+ async explain(sql, params) {
92
+ const db = await this.open();
93
+ const r = runOne(db, `EXPLAIN QUERY PLAN ${sql}`, params);
94
+ return r.rows.map((row) => ({
95
+ id: Number(row[0]),
96
+ parent: Number(row[1]),
97
+ detail: String(row[3])
98
+ }));
99
+ }
100
+ async propose(sql, params, ttlSec) {
101
+ const db = await this.open();
102
+ const planRaw = runOne(db, `EXPLAIN QUERY PLAN ${sql}`, params).rows;
103
+ const plan = planRaw;
104
+ const ttl = Math.min(
105
+ Math.max(1, Math.floor(ttlSec ?? PROPOSAL_TTL_DEFAULT_SEC)),
106
+ PROPOSAL_TTL_MAX_SEC
107
+ );
108
+ const expiresAt = Date.now() + ttl * 1e3;
109
+ const executionToken = newLocalProposalId();
110
+ this.proposals.set(executionToken, { sql, params, expiresAt });
111
+ this.gcProposals();
112
+ return {
113
+ sql,
114
+ plan,
115
+ estimatedAffectedRows: null,
116
+ executionToken,
117
+ expiresAt: new Date(expiresAt).toISOString(),
118
+ action: actionForSql(sql)
119
+ };
120
+ }
121
+ async apply(executionToken) {
122
+ const rec = this.proposals.get(executionToken);
123
+ if (!rec) {
124
+ throw new Error(
125
+ "PerSQL: executionToken is unknown, expired, or already redeemed"
126
+ );
127
+ }
128
+ this.proposals.delete(executionToken);
129
+ if (rec.expiresAt < Date.now()) {
130
+ throw new Error("PerSQL: executionToken has expired");
131
+ }
132
+ return this.query(rec.sql, rec.params);
133
+ }
134
+ gcProposals() {
135
+ const now = Date.now();
136
+ for (const [k, v] of this.proposals) {
137
+ if (v.expiresAt < now) this.proposals.delete(k);
138
+ }
139
+ }
140
+ close() {
141
+ if (this.db) {
142
+ try {
143
+ this.db.close();
144
+ } catch {
145
+ }
146
+ this.db = null;
147
+ }
148
+ }
149
+ };
150
+ function actionForSql(sql) {
151
+ const head = sql.trim().slice(0, 24).toLowerCase();
152
+ if (head.startsWith("create") || head.startsWith("drop") || head.startsWith("alter")) {
153
+ return "admin";
154
+ }
155
+ if (head.startsWith("insert") || head.startsWith("update") || head.startsWith("delete") || head.startsWith("replace")) {
156
+ return "write";
157
+ }
158
+ return "read";
159
+ }
160
+ function runOne(db, sql, params) {
161
+ const stmt = db.prepare(sql);
162
+ if (stmt.reader) {
163
+ const cols = stmt.columns().map((c) => c.name);
164
+ const rows = stmt.raw(true).all(...params);
165
+ return { columns: cols, rows, rowsRead: rows.length, rowsWritten: 0 };
166
+ }
167
+ const info = stmt.run(...params);
168
+ return { columns: [], rows: [], rowsRead: 0, rowsWritten: info.changes ?? 0 };
169
+ }
170
+
171
+ // src/index.ts
172
+ var PerSQLError = class extends Error {
173
+ status;
174
+ // Set on /v1/query and /v1/batch failures with a parsed envelope
175
+ // (kind, table, column, hint, etc.) so callers can branch on
176
+ // `error.detail.kind` instead of string-matching the message.
177
+ detail;
178
+ constructor(status, message, detail) {
179
+ super(message);
180
+ this.name = "PerSQLError";
181
+ this.status = status;
182
+ this.detail = detail;
183
+ }
184
+ };
185
+ var RateLimitError = class extends PerSQLError {
186
+ retryAfterSeconds;
187
+ constructor(retryAfterSeconds, message = "Rate limit exceeded") {
188
+ super(429, message);
189
+ this.name = "RateLimitError";
190
+ this.retryAfterSeconds = retryAfterSeconds;
191
+ }
192
+ };
193
+ var ApprovalRequiredError = class extends PerSQLError {
194
+ approvalToken;
195
+ approvalUrl;
196
+ hits;
197
+ expiresAt;
198
+ constructor(opts) {
199
+ super(403, opts.message);
200
+ this.name = "ApprovalRequiredError";
201
+ this.approvalToken = opts.approvalToken;
202
+ this.approvalUrl = opts.approvalUrl;
203
+ this.hits = opts.hits;
204
+ this.expiresAt = opts.expiresAt;
205
+ }
206
+ };
207
+ var PerSQL = class _PerSQL {
208
+ /** @internal — exposed read-only so PerSQLDatabase can build URLs. */
209
+ token;
210
+ /** @internal — same. */
211
+ baseURL;
212
+ /** @internal — set when running in local mode. */
213
+ local;
214
+ _fetch;
215
+ constructor(opts) {
216
+ if (opts.local) {
217
+ this.local = new LocalDriver(opts.local);
218
+ this.token = "";
219
+ this.baseURL = "";
220
+ this._fetch = opts.fetch ?? globalThis.fetch?.bind(globalThis);
221
+ return;
222
+ }
223
+ if (!opts.token) {
224
+ throw new Error(
225
+ 'PerSQL: token is required (or pass { local: ":memory:" } for tests)'
226
+ );
227
+ }
228
+ this.local = null;
229
+ this.token = opts.token;
230
+ this.baseURL = (opts.baseURL ?? "https://api.persql.com").replace(/\/$/, "");
231
+ this._fetch = opts.fetch ?? globalThis.fetch.bind(globalThis);
232
+ }
233
+ /** Close the local SQLite connection (no-op in HTTP mode). */
234
+ close() {
235
+ this.local?.close();
236
+ }
237
+ /**
238
+ * Redeem a handoff token (`phand_…`) for a regular PerSQL client
239
+ * scoped to the handed-off (database, branch, role). Single use:
240
+ * the handoff token is consumed by the call.
241
+ *
242
+ * Common pattern — agent A pins a branch and hands the token to
243
+ * agent B; agent B does:
244
+ *
245
+ * const persql = await PerSQL.fromHandoff(handoffToken);
246
+ * const db = persql.database(persql.handedOff!.namespaceSlug, persql.handedOff!.databaseSlug);
247
+ */
248
+ static async fromHandoff(handoffToken, opts = {}) {
249
+ const baseURL = (opts.baseURL ?? "https://api.persql.com").replace(/\/$/, "");
250
+ const fetcher = opts.fetch ?? globalThis.fetch.bind(globalThis);
251
+ const res = await fetcher(`${baseURL}/v1/handoff/claim`, {
252
+ method: "POST",
253
+ headers: { "Content-Type": "application/json" },
254
+ body: JSON.stringify({ token: handoffToken, name: opts.name })
255
+ });
256
+ const envelope = await res.json().catch(() => null);
257
+ if (!res.ok || !envelope?.success || !envelope.data) {
258
+ throw new PerSQLError(
259
+ res.status,
260
+ envelope?.error ?? `Handoff claim failed (${res.status})`
261
+ );
262
+ }
263
+ const { plaintext, ...handedOff } = envelope.data;
264
+ const client = new _PerSQL({ token: plaintext, baseURL, fetch: opts.fetch });
265
+ return Object.assign(client, { handedOff });
266
+ }
267
+ database(a, b) {
268
+ if (b !== void 0) return new PerSQLDatabase(this, a, b);
269
+ const [ns, slug] = a.split("/");
270
+ if (!ns || !slug) {
271
+ throw new Error('PerSQL: database path must be "<namespace>/<slug>"');
272
+ }
273
+ return new PerSQLDatabase(this, ns, slug);
274
+ }
275
+ /** @internal */
276
+ async request(method, path, body, headers) {
277
+ const res = await this._fetch(`${this.baseURL}${path}`, {
278
+ method,
279
+ headers: {
280
+ Authorization: `Bearer ${this.token}`,
281
+ "Content-Type": "application/json",
282
+ ...headers ?? {}
283
+ },
284
+ body: body !== void 0 ? JSON.stringify(body) : void 0
285
+ });
286
+ if (res.status === 429) {
287
+ const retryAfter = Number(res.headers.get("retry-after") ?? "60");
288
+ throw new RateLimitError(retryAfter);
289
+ }
290
+ let envelope = null;
291
+ try {
292
+ envelope = await res.json();
293
+ } catch {
294
+ }
295
+ if (!res.ok || !envelope?.success) {
296
+ const message = envelope?.error ?? `Request failed (${res.status})`;
297
+ if (res.status === 403 && envelope?.approvalToken && envelope?.approvalUrl && envelope?.expiresAt) {
298
+ throw new ApprovalRequiredError({
299
+ message,
300
+ approvalToken: envelope.approvalToken,
301
+ approvalUrl: envelope.approvalUrl,
302
+ hits: envelope.hits ?? [],
303
+ expiresAt: envelope.expiresAt
304
+ });
305
+ }
306
+ throw new PerSQLError(res.status, message, envelope?.errorDetail);
307
+ }
308
+ return envelope.data;
309
+ }
310
+ /** @internal — raw upload (e.g. blob PUT) returning the ApiResponse data. */
311
+ async requestRaw(method, path, body, contentType) {
312
+ const res = await this._fetch(`${this.baseURL}${path}`, {
313
+ method,
314
+ headers: {
315
+ Authorization: `Bearer ${this.token}`,
316
+ "Content-Type": contentType ?? "application/octet-stream"
317
+ },
318
+ body,
319
+ // @ts-expect-error — duplex is required by Node fetch for streaming bodies
320
+ duplex: "half"
321
+ });
322
+ if (res.status === 429) {
323
+ const retryAfter = Number(res.headers.get("retry-after") ?? "60");
324
+ throw new RateLimitError(retryAfter);
325
+ }
326
+ let envelope = null;
327
+ try {
328
+ envelope = await res.json();
329
+ } catch {
330
+ }
331
+ if (!res.ok || !envelope?.success) {
332
+ const message = envelope?.error ?? `Request failed (${res.status})`;
333
+ throw new PerSQLError(res.status, message, envelope?.errorDetail);
334
+ }
335
+ return envelope.data;
336
+ }
337
+ /** @internal — raw fetch returning the underlying Response (used by blob GET). */
338
+ fetchRaw(method, path) {
339
+ return this._fetch(`${this.baseURL}${path}`, {
340
+ method,
341
+ headers: { Authorization: `Bearer ${this.token}` }
342
+ });
343
+ }
344
+ };
345
+ var PerSQLDatabase = class {
346
+ constructor(client, namespace, slug) {
347
+ this.client = client;
348
+ this.namespace = namespace;
349
+ this.slug = slug;
350
+ }
351
+ /** Run a single SQL statement. */
352
+ async query(sql, params = [], options = {}) {
353
+ if (this.client.local) {
354
+ const raw2 = await this.client.local.query(sql, params);
355
+ return { ...raw2, data: rowsToObjects(raw2.columns, raw2.rows) };
356
+ }
357
+ const headers = {};
358
+ if (options.idempotencyKey) headers["Idempotency-Key"] = options.idempotencyKey;
359
+ if (options.planKey) headers["Plan-Key"] = options.planKey;
360
+ if (options.planStep) headers["Plan-Step"] = options.planStep;
361
+ const raw = await this.client.request(
362
+ "POST",
363
+ `/v1/db/${this.namespace}/${this.slug}/query`,
364
+ { sql, params },
365
+ headers
366
+ );
367
+ return {
368
+ ...raw,
369
+ data: rowsToObjects(raw.columns, raw.rows)
370
+ };
371
+ }
372
+ /** Run multiple statements in one round-trip, optionally in a transaction. */
373
+ async batch(statements, options = {}) {
374
+ if (this.client.local) {
375
+ const raw2 = await this.client.local.batch(
376
+ statements,
377
+ options.transaction ?? false
378
+ );
379
+ return raw2.map((r) => ({ ...r, data: rowsToObjects(r.columns, r.rows) }));
380
+ }
381
+ const headers = {};
382
+ if (options.idempotencyKey) headers["Idempotency-Key"] = options.idempotencyKey;
383
+ if (options.planKey) headers["Plan-Key"] = options.planKey;
384
+ if (options.planStep) headers["Plan-Step"] = options.planStep;
385
+ const raw = await this.client.request(
386
+ "POST",
387
+ `/v1/db/${this.namespace}/${this.slug}/batch`,
388
+ { statements, transaction: options.transaction ?? false },
389
+ headers
390
+ );
391
+ return raw.map((r) => ({ ...r, data: rowsToObjects(r.columns, r.rows) }));
392
+ }
393
+ /** Convenience for a transactional batch. */
394
+ transaction(statements, options = {}) {
395
+ return this.batch(statements, { ...options, transaction: true });
396
+ }
397
+ /**
398
+ * Engine telemetry — recent /v1/query and /v1/batch calls issued
399
+ * against this database. Backed by the in-DO `_persql_meta_query_log`
400
+ * table; 7-day retention. Useful for agents that need to replay
401
+ * what they (or another agent) did, audit cost, or stream a live
402
+ * tail via `db.subscribe`.
403
+ */
404
+ async queryLog(opts = {}) {
405
+ if (this.client.local) {
406
+ throw new Error("PerSQL: queryLog is not available in local mode.");
407
+ }
408
+ const qs = new URLSearchParams();
409
+ if (opts.since) {
410
+ qs.set(
411
+ "since",
412
+ typeof opts.since === "string" ? opts.since : opts.since.toISOString()
413
+ );
414
+ }
415
+ if (opts.until) {
416
+ qs.set(
417
+ "until",
418
+ typeof opts.until === "string" ? opts.until : opts.until.toISOString()
419
+ );
420
+ }
421
+ if (opts.tokenId) qs.set("tokenId", opts.tokenId);
422
+ if (opts.status) qs.set("status", opts.status);
423
+ if (opts.cursor) qs.set("cursor", opts.cursor);
424
+ if (opts.pageSize) qs.set("pageSize", String(opts.pageSize));
425
+ const tail = qs.toString() ? `?${qs.toString()}` : "";
426
+ const res = await this.client.fetchRaw(
427
+ "GET",
428
+ `/v1/db/${this.namespace}/${this.slug}/queries${tail}`
429
+ );
430
+ const body = await res.json();
431
+ if (!res.ok || !body.success) {
432
+ throw new PerSQLError(res.status, body.error ?? `Request failed (${res.status})`);
433
+ }
434
+ return { data: body.data ?? [], nextCursor: body.nextCursor ?? null };
435
+ }
436
+ /**
437
+ * Returns a structured description of the database — columns, FK
438
+ * graph, and any human-/AI-authored docs persisted via
439
+ * `db.describe(...)`. The shape is designed for direct injection
440
+ * into an LLM prompt: one round-trip and the agent has everything
441
+ * it needs to write correct SQL.
442
+ */
443
+ async describe() {
444
+ if (this.client.local) {
445
+ throw new Error(
446
+ "PerSQL: describe is not available in local mode (yet)."
447
+ );
448
+ }
449
+ return this.client.request(
450
+ "GET",
451
+ `/v1/db/${this.namespace}/${this.slug}/describe`
452
+ );
453
+ }
454
+ /**
455
+ * Persist semantic descriptions for the database / tables / columns.
456
+ * Pass any subset — only the fields you set are updated. Requires
457
+ * an admin-role token because docs change how every other client
458
+ * (and every agent) interprets the schema.
459
+ */
460
+ async setDescription(input) {
461
+ if (this.client.local) {
462
+ throw new Error("PerSQL: setDescription is not available in local mode.");
463
+ }
464
+ return this.client.request(
465
+ "PUT",
466
+ `/v1/db/${this.namespace}/${this.slug}/describe`,
467
+ input
468
+ );
469
+ }
470
+ /**
471
+ * Natural-language ranked search across table names, column names,
472
+ * and any descriptions you've stored via `setDescription`. Use this
473
+ * before writing SQL when you don't know the schema cold — one call
474
+ * narrows a 200-table DB down to the handful that match the intent.
475
+ */
476
+ async search(query, opts = {}) {
477
+ if (this.client.local) {
478
+ throw new Error("PerSQL: search is not available in local mode.");
479
+ }
480
+ const qs = new URLSearchParams({ q: query });
481
+ if (opts.limit) qs.set("limit", String(opts.limit));
482
+ return this.client.request(
483
+ "GET",
484
+ `/v1/db/${this.namespace}/${this.slug}/search?${qs.toString()}`
485
+ );
486
+ }
487
+ /**
488
+ * Lints the schema for issues that hurt LLM consumption: missing
489
+ * primary keys, ambiguous column names ("data", "value"), unindexed
490
+ * foreign keys, etc. Pure read-only analysis — emits suggestions
491
+ * for the agent to act on, never modifies the schema itself.
492
+ */
493
+ async doctor() {
494
+ if (this.client.local) {
495
+ throw new Error("PerSQL: doctor is not available in local mode.");
496
+ }
497
+ return this.client.request(
498
+ "GET",
499
+ `/v1/db/${this.namespace}/${this.slug}/doctor`
500
+ );
501
+ }
502
+ /** List user-defined tables in this database. */
503
+ async tables() {
504
+ if (this.client.local) return this.client.local.tables();
505
+ return this.client.request(
506
+ "GET",
507
+ `/v1/db/${this.namespace}/${this.slug}/tables`
508
+ );
509
+ }
510
+ /**
511
+ * Returns SQLite's `EXPLAIN QUERY PLAN` output for the given SQL.
512
+ * Read-only — does not execute the statement.
513
+ */
514
+ async explain(sql, params = []) {
515
+ if (this.client.local) return this.client.local.explain(sql, params);
516
+ return this.client.request("POST", `/v1/db/${this.namespace}/${this.slug}/explain`, { sql, params });
517
+ }
518
+ /**
519
+ * Introspect the database schema. Returns one entry per user table
520
+ * with column definitions, suitable for codegen tools (the
521
+ * `persql-codegen` CLI uses this to emit Drizzle schema files).
522
+ */
523
+ async schema() {
524
+ const tables = await this.tables();
525
+ const out = { tables: [] };
526
+ for (const t of tables) {
527
+ const r = await this.query(`PRAGMA table_info("${t.name.replace(/"/g, '""')}")`);
528
+ out.tables.push({
529
+ name: t.name,
530
+ columns: r.data.map((c) => ({
531
+ name: c.name,
532
+ type: c.type,
533
+ notNull: !!c.notnull,
534
+ primaryKey: !!c.pk,
535
+ default: c.dflt_value === null ? null : String(c.dflt_value)
536
+ }))
537
+ });
538
+ }
539
+ return out;
540
+ }
541
+ /**
542
+ * Per-database semantic search via Cloudflare Vectorize. Use
543
+ * `vectors.upsert` to embed and store rows; `vectors.query` to
544
+ * retrieve the most similar by free text. Embeddings are computed
545
+ * server-side using bge-base-en-v1.5 (768 dim, cosine distance).
546
+ */
547
+ get vectors() {
548
+ if (this.client.local) {
549
+ throw new Error(
550
+ "PerSQL: vectors require Cloudflare Vectorize and Workers AI \u2014 not available in local mode. Use a server-mode token (psql_live_/psql_test_) to call vectors.upsert/query/delete."
551
+ );
552
+ }
553
+ return new PerSQLVectors(this.client, this.namespace, this.slug);
554
+ }
555
+ /**
556
+ * Manage preview/PR-style branches of this database. Each branch is
557
+ * its own DO with its own SQLite file; create-or-reset by ref is
558
+ * idempotent (PUT semantics) so CI pipelines can call it on every
559
+ * build. Requires an admin-role bearer token for create / delete /
560
+ * merge; list is open to any role.
561
+ */
562
+ get branches() {
563
+ if (this.client.local) {
564
+ throw new Error(
565
+ "PerSQL: branches model fork-by-Durable-Object \u2014 not available in local mode. Use a server-mode token to call branches.upsert/claim/merge, or stub branch isolation in tests by spinning up multiple `new PerSQL({ local: ':memory:' })` instances."
566
+ );
567
+ }
568
+ return new PerSQLBranches(this.client, this.namespace, this.slug);
569
+ }
570
+ /**
571
+ * Redeem an approval that was minted when a write hit a
572
+ * `require_approval` rule. Throws `ApprovalRequiredError` until a
573
+ * namespace member decides; on approve, runs the original SQL.
574
+ */
575
+ get approvals() {
576
+ if (this.client.local) {
577
+ throw new Error(
578
+ "PerSQL: approvals require a server-side approval gate \u2014 not available in local mode. Local mode runs every statement immediately; use a server-mode token if you need the require_approval rule."
579
+ );
580
+ }
581
+ return new PerSQLApprovals(this.client, this.namespace, this.slug);
582
+ }
583
+ /**
584
+ * Pre-flight a write before running it. `propose()` validates the
585
+ * SQL via EXPLAIN, estimates affected rows, and returns a single-use
586
+ * `executionToken` to redeem with `apply()`. Use this when an agent
587
+ * (or its parent / a human) should review a mutation before it runs.
588
+ * Works in both HTTP and local modes — local mode keeps the
589
+ * executionToken in-process.
590
+ */
591
+ get proposals() {
592
+ return new PerSQLProposals(this.client, this.namespace, this.slug);
593
+ }
594
+ /**
595
+ * Per-database BLOB storage backed by R2. Use this for anything
596
+ * larger than a SQLite cell (images, PDFs, model weights). Each
597
+ * database has its own private namespace; keys may be hierarchical
598
+ * (`avatars/2025/foo.jpg`) but never start with `/`.
599
+ */
600
+ get blob() {
601
+ if (this.client.local) {
602
+ throw new Error(
603
+ "PerSQL: blob storage is backed by R2 \u2014 not available in local mode. Use a server-mode token, or store blobs in your test fixtures directly."
604
+ );
605
+ }
606
+ return new PerSQLBlob(this.client, this.namespace, this.slug);
607
+ }
608
+ /**
609
+ * Subscribe to row-changes via WebSocket — the SQL equivalent of
610
+ * Postgres `LISTEN`. The callback fires once per write that
611
+ * matches the table filter. Returns an `unsubscribe` function;
612
+ * call it to close the socket.
613
+ *
614
+ * ```ts
615
+ * const off = db.subscribe({
616
+ * tables: ["orders"],
617
+ * onChange: (e) => console.log(e.kind, e.table),
618
+ * });
619
+ * // …later
620
+ * off();
621
+ * ```
622
+ *
623
+ * Authentication uses the `persql.bearer.<token>` sub-protocol so
624
+ * the token doesn't leak via URL logs. In environments without
625
+ * sub-protocol support (some serverless WebSocket clients), the
626
+ * fallback `?token=` query string is also accepted by the
627
+ * server.
628
+ */
629
+ subscribe(options) {
630
+ if (this.client.local) {
631
+ throw new Error(
632
+ "PerSQL: subscribe requires the DO's WebSocket fan-out \u2014 not available in local mode. Use a server-mode token to call subscribe()."
633
+ );
634
+ }
635
+ const baseHttp = this.client.baseURL;
636
+ const wsBase = baseHttp.replace(/^http/, "ws");
637
+ const tablesParam = options.tables && options.tables.length > 0 ? `?tables=${encodeURIComponent(options.tables.join(","))}` : "";
638
+ const url = `${wsBase}/v1/db/${this.namespace}/${this.slug}/subscribe${tablesParam}`;
639
+ const ws = new WebSocket(url, [`persql.bearer.${this.client.token}`]);
640
+ let closed = false;
641
+ ws.addEventListener("message", (ev) => {
642
+ try {
643
+ const msg = JSON.parse(String(ev.data));
644
+ if (msg.type === "change" && msg.table && msg.kind) {
645
+ options.onChange({ table: msg.table, kind: msg.kind });
646
+ } else if (msg.type === "error") {
647
+ options.onError?.(new Error(msg.message ?? "Subscription error"));
648
+ } else if (msg.type === "subscribed") {
649
+ options.onReady?.(msg.tables ?? "*");
650
+ }
651
+ } catch {
652
+ }
653
+ });
654
+ ws.addEventListener("error", () => {
655
+ options.onError?.(new Error("WebSocket error"));
656
+ });
657
+ ws.addEventListener("close", () => {
658
+ if (!closed) options.onClose?.();
659
+ });
660
+ return () => {
661
+ closed = true;
662
+ try {
663
+ ws.close();
664
+ } catch {
665
+ }
666
+ };
667
+ }
668
+ /**
669
+ * Returns the callback shape `drizzle-orm/sqlite-proxy` expects.
670
+ * Pair with `drizzle()` from that module to get a typed,
671
+ * fluent ORM client over the PerSQL HTTP API:
672
+ *
673
+ * ```ts
674
+ * import { drizzle } from "drizzle-orm/sqlite-proxy";
675
+ * import { PerSQL } from "@persql/sdk";
676
+ *
677
+ * const persql = new PerSQL({ token });
678
+ * const db = drizzle(persql.database("acme/orders").driver());
679
+ * ```
680
+ *
681
+ * Drizzle's `prepare` interface maps onto our `query` /
682
+ * `batch`; `method` tells us how to shape the rows.
683
+ */
684
+ driver() {
685
+ const callback = async (sql, params, method) => {
686
+ const result = await this.query(sql, params ?? []);
687
+ if (method === "values" || method === "get") {
688
+ return { rows: result.rows[0] ?? [] };
689
+ }
690
+ return { rows: result.rows };
691
+ };
692
+ return callback;
693
+ }
694
+ /**
695
+ * Returns a tool definition for use with Anthropic / OpenAI / function-calling
696
+ * agents. Pair it with `runTool` to execute the call.
697
+ */
698
+ asTool(name = "persql_query") {
699
+ return {
700
+ anthropic: {
701
+ name,
702
+ description: `Run a SQL query against the PerSQL database "${this.namespace}/${this.slug}". Returns up to 1000 rows. Use parameter binding (?) to avoid injection.`,
703
+ input_schema: {
704
+ type: "object",
705
+ properties: {
706
+ sql: { type: "string", description: "SQLite SQL statement" },
707
+ params: {
708
+ type: "array",
709
+ items: {},
710
+ description: "Positional parameters for the SQL statement"
711
+ }
712
+ },
713
+ required: ["sql"]
714
+ }
715
+ },
716
+ openai: {
717
+ type: "function",
718
+ function: {
719
+ name,
720
+ description: `Run a SQL query against the PerSQL database "${this.namespace}/${this.slug}".`,
721
+ parameters: {
722
+ type: "object",
723
+ properties: {
724
+ sql: { type: "string" },
725
+ params: { type: "array", items: {} }
726
+ },
727
+ required: ["sql"]
728
+ }
729
+ }
730
+ }
731
+ };
732
+ }
733
+ /**
734
+ * Executes a tool-call payload returned from the model. Pair with `asTool`.
735
+ */
736
+ runTool(input) {
737
+ return this.query(input.sql, input.params ?? []);
738
+ }
739
+ /**
740
+ * Generate a *bundle* of typed tools — one per table — instead of one
741
+ * generic `query` tool. Agents perform dramatically better with narrow
742
+ * typed surfaces than they do with one fat SQL function. Each table
743
+ * gets:
744
+ * - `select_<table>(where?, limit?, orderBy?)` — typed column filter
745
+ * - `count_<table>(where?)` — quick row count
746
+ * - `describe_<table>()` — columns, row count, foreign keys
747
+ * Plus a fallback `sql_query(sql, params)` for anything the typed
748
+ * tools can't express.
749
+ *
750
+ * The returned `run(name, input)` dispatcher executes whichever tool
751
+ * the model invoked. Format the tools for the LLM via the
752
+ * `anthropic` or `openai` arrays (matches the shapes of `asTool`).
753
+ *
754
+ * ```ts
755
+ * const tools = await db.asTools();
756
+ * const reply = await anthropic.messages.create({
757
+ * model: "claude-opus-4-7",
758
+ * tools: tools.anthropic,
759
+ * messages: [...],
760
+ * });
761
+ * for (const block of reply.content) {
762
+ * if (block.type === "tool_use") {
763
+ * const result = await tools.run(block.name, block.input);
764
+ * }
765
+ * }
766
+ * ```
767
+ */
768
+ async asTools() {
769
+ const schema = await this.schema();
770
+ const anthropic = [];
771
+ const openai = [];
772
+ for (const t of schema.tables) {
773
+ const safe = sanitizeToolPart(t.name);
774
+ const columnList = t.columns.map((c) => `${c.name} ${c.type}${c.notNull ? " NOT NULL" : ""}${c.primaryKey ? " PRIMARY KEY" : ""}`).join(", ");
775
+ const whereProps = {};
776
+ for (const c of t.columns) {
777
+ whereProps[c.name] = {
778
+ type: ["string", "number", "boolean", "null"],
779
+ description: `Equality filter on ${t.name}.${c.name} (${c.type})`
780
+ };
781
+ }
782
+ const selectName = `select_${safe}`;
783
+ const selectDesc = `Read rows from ${t.name}. Columns: ${columnList}. Use \`where\` for equality predicates, \`orderBy\` to sort, \`limit\` to bound the result (default 100, max 1000).`;
784
+ const selectInput = {
785
+ type: "object",
786
+ properties: {
787
+ where: {
788
+ type: "object",
789
+ description: "Equality filter \u2014 keys are column names, values are scalars.",
790
+ properties: whereProps,
791
+ additionalProperties: false
792
+ },
793
+ orderBy: {
794
+ type: "string",
795
+ description: "Column name optionally followed by ASC/DESC."
796
+ },
797
+ limit: {
798
+ type: "integer",
799
+ minimum: 1,
800
+ maximum: 1e3,
801
+ default: 100
802
+ }
803
+ },
804
+ additionalProperties: false
805
+ };
806
+ anthropic.push({ name: selectName, description: selectDesc, input_schema: selectInput });
807
+ openai.push({
808
+ type: "function",
809
+ function: { name: selectName, description: selectDesc, parameters: selectInput }
810
+ });
811
+ const countName = `count_${safe}`;
812
+ const countDesc = `Count rows in ${t.name}, optionally filtered by equality on any column.`;
813
+ const countInput = {
814
+ type: "object",
815
+ properties: {
816
+ where: {
817
+ type: "object",
818
+ properties: whereProps,
819
+ additionalProperties: false
820
+ }
821
+ },
822
+ additionalProperties: false
823
+ };
824
+ anthropic.push({ name: countName, description: countDesc, input_schema: countInput });
825
+ openai.push({
826
+ type: "function",
827
+ function: { name: countName, description: countDesc, parameters: countInput }
828
+ });
829
+ const descName = `describe_${safe}`;
830
+ const descDesc = `Return columns, row count, and foreign keys for ${t.name}.`;
831
+ const descInput = {
832
+ type: "object",
833
+ properties: {},
834
+ additionalProperties: false
835
+ };
836
+ anthropic.push({ name: descName, description: descDesc, input_schema: descInput });
837
+ openai.push({
838
+ type: "function",
839
+ function: { name: descName, description: descDesc, parameters: descInput }
840
+ });
841
+ const valueProps = {};
842
+ const requiredForInsert = [];
843
+ for (const c of t.columns) {
844
+ valueProps[c.name] = {
845
+ type: ["string", "number", "boolean", "null"],
846
+ description: `${t.name}.${c.name} (${c.type})${c.notNull ? " NOT NULL" : ""}`
847
+ };
848
+ if (c.notNull && !c.primaryKey) {
849
+ requiredForInsert.push(c.name);
850
+ }
851
+ }
852
+ const insertName = `insert_${safe}`;
853
+ const insertDesc = `Insert one row into ${t.name}. Provide column values in \`values\`. Required (NOT NULL): ${requiredForInsert.join(", ") || "(none)"}.`;
854
+ const insertInput = {
855
+ type: "object",
856
+ properties: {
857
+ values: {
858
+ type: "object",
859
+ description: "Column \u2192 value map for the new row.",
860
+ properties: valueProps,
861
+ required: requiredForInsert,
862
+ additionalProperties: false
863
+ }
864
+ },
865
+ required: ["values"],
866
+ additionalProperties: false
867
+ };
868
+ anthropic.push({ name: insertName, description: insertDesc, input_schema: insertInput });
869
+ openai.push({
870
+ type: "function",
871
+ function: { name: insertName, description: insertDesc, parameters: insertInput }
872
+ });
873
+ const updateName = `update_${safe}`;
874
+ const updateDesc = `Update rows in ${t.name} matching \`where\` (equality on any column) with the columns provided in \`set\`. Both must be non-empty \u2014 to clear the filter use \`sql_query\`.`;
875
+ const updateInput = {
876
+ type: "object",
877
+ properties: {
878
+ where: {
879
+ type: "object",
880
+ properties: whereProps,
881
+ additionalProperties: false
882
+ },
883
+ set: {
884
+ type: "object",
885
+ properties: valueProps,
886
+ additionalProperties: false
887
+ }
888
+ },
889
+ required: ["where", "set"],
890
+ additionalProperties: false
891
+ };
892
+ anthropic.push({ name: updateName, description: updateDesc, input_schema: updateInput });
893
+ openai.push({
894
+ type: "function",
895
+ function: { name: updateName, description: updateDesc, parameters: updateInput }
896
+ });
897
+ const deleteName = `delete_${safe}`;
898
+ const deleteDesc = `Delete rows from ${t.name} matching \`where\`. \`where\` must be non-empty \u2014 to truncate use \`sql_query\` with an explicit DELETE.`;
899
+ const deleteInput = {
900
+ type: "object",
901
+ properties: {
902
+ where: {
903
+ type: "object",
904
+ properties: whereProps,
905
+ additionalProperties: false
906
+ }
907
+ },
908
+ required: ["where"],
909
+ additionalProperties: false
910
+ };
911
+ anthropic.push({ name: deleteName, description: deleteDesc, input_schema: deleteInput });
912
+ openai.push({
913
+ type: "function",
914
+ function: { name: deleteName, description: deleteDesc, parameters: deleteInput }
915
+ });
916
+ }
917
+ const sqlName = "sql_query";
918
+ const sqlDesc = `Run an arbitrary parameterised SQL statement against the PerSQL database "${this.namespace}/${this.slug}". Prefer the table-specific select_/count_/describe_ tools when they fit; fall back to this for joins, aggregates, or DDL.`;
919
+ const sqlInput = {
920
+ type: "object",
921
+ properties: {
922
+ sql: { type: "string" },
923
+ params: { type: "array", items: {} }
924
+ },
925
+ required: ["sql"],
926
+ additionalProperties: false
927
+ };
928
+ anthropic.push({ name: sqlName, description: sqlDesc, input_schema: sqlInput });
929
+ openai.push({
930
+ type: "function",
931
+ function: { name: sqlName, description: sqlDesc, parameters: sqlInput }
932
+ });
933
+ const describeDbName = "describe_database";
934
+ const describeDbDesc = `Return the full schema graph plus stored semantic descriptions for "${this.namespace}/${this.slug}". Call this FIRST on any unfamiliar database \u2014 it includes table descriptions, column docs, and foreign keys in one shot, sized to JSON-stringify into a system prompt.`;
935
+ const describeDbInput = {
936
+ type: "object",
937
+ properties: {},
938
+ additionalProperties: false
939
+ };
940
+ anthropic.push({
941
+ name: describeDbName,
942
+ description: describeDbDesc,
943
+ input_schema: describeDbInput
944
+ });
945
+ openai.push({
946
+ type: "function",
947
+ function: {
948
+ name: describeDbName,
949
+ description: describeDbDesc,
950
+ parameters: describeDbInput
951
+ }
952
+ });
953
+ const searchSchemaName = "search_schema";
954
+ const searchSchemaDesc = `Natural-language ranked search across table names, column names, and stored descriptions. Use this when you have a goal ("billing addresses", "abandoned carts") but don't know which table holds it.`;
955
+ const searchSchemaInput = {
956
+ type: "object",
957
+ properties: {
958
+ q: {
959
+ type: "string",
960
+ description: "Free-text query \u2014 table/column/description tokens are matched."
961
+ },
962
+ limit: {
963
+ type: "integer",
964
+ minimum: 1,
965
+ maximum: 100,
966
+ default: 25
967
+ }
968
+ },
969
+ required: ["q"],
970
+ additionalProperties: false
971
+ };
972
+ anthropic.push({
973
+ name: searchSchemaName,
974
+ description: searchSchemaDesc,
975
+ input_schema: searchSchemaInput
976
+ });
977
+ openai.push({
978
+ type: "function",
979
+ function: {
980
+ name: searchSchemaName,
981
+ description: searchSchemaDesc,
982
+ parameters: searchSchemaInput
983
+ }
984
+ });
985
+ const doctorName = "schema_doctor";
986
+ const doctorDesc = `Lint the schema for LLM-hostile patterns \u2014 missing primary keys, ambiguous column names, unindexed foreign keys. Read-only; useful before generating SQL so you know what the schema gets wrong.`;
987
+ const doctorInput = {
988
+ type: "object",
989
+ properties: {},
990
+ additionalProperties: false
991
+ };
992
+ anthropic.push({
993
+ name: doctorName,
994
+ description: doctorDesc,
995
+ input_schema: doctorInput
996
+ });
997
+ openai.push({
998
+ type: "function",
999
+ function: {
1000
+ name: doctorName,
1001
+ description: doctorDesc,
1002
+ parameters: doctorInput
1003
+ }
1004
+ });
1005
+ const proposeName = "propose_mutation";
1006
+ const proposeDesc = `Pre-flight a SQL write \u2014 EXPLAIN-validate, estimate affected rows, and return a single-use executionToken. Nothing is mutated until apply_mutation is called with that token. Use for any UPDATE/DELETE that isn't tightly scoped to a single PK, or any INSERT batch you want to verify.`;
1007
+ const proposeInput = {
1008
+ type: "object",
1009
+ properties: {
1010
+ sql: { type: "string", description: "SQLite SQL statement." },
1011
+ params: { type: "array", items: {} },
1012
+ ttlSec: {
1013
+ type: "integer",
1014
+ minimum: 30,
1015
+ maximum: 3600,
1016
+ description: "Token TTL in seconds. Default 600 (10 min)."
1017
+ }
1018
+ },
1019
+ required: ["sql"],
1020
+ additionalProperties: false
1021
+ };
1022
+ anthropic.push({
1023
+ name: proposeName,
1024
+ description: proposeDesc,
1025
+ input_schema: proposeInput
1026
+ });
1027
+ openai.push({
1028
+ type: "function",
1029
+ function: {
1030
+ name: proposeName,
1031
+ description: proposeDesc,
1032
+ parameters: proposeInput
1033
+ }
1034
+ });
1035
+ const applyName = "apply_mutation";
1036
+ const applyDesc = `Redeem an executionToken returned by propose_mutation. Single-use \u2014 calling twice fails. The actual write runs through the same auto-snapshot + query-log + pricing pipeline as a normal SQL call.`;
1037
+ const applyInput = {
1038
+ type: "object",
1039
+ properties: {
1040
+ executionToken: {
1041
+ type: "string",
1042
+ description: "pmut_\u2026 token from propose_mutation."
1043
+ }
1044
+ },
1045
+ required: ["executionToken"],
1046
+ additionalProperties: false
1047
+ };
1048
+ anthropic.push({
1049
+ name: applyName,
1050
+ description: applyDesc,
1051
+ input_schema: applyInput
1052
+ });
1053
+ openai.push({
1054
+ type: "function",
1055
+ function: {
1056
+ name: applyName,
1057
+ description: applyDesc,
1058
+ parameters: applyInput
1059
+ }
1060
+ });
1061
+ const queryLogName = "recent_queries";
1062
+ const queryLogDesc = `Recent /query and /batch calls against this database \u2014 durations, errors, statement counts. Use to debug a failed write you just made, or to spot N+1 patterns in your own behavior.`;
1063
+ const queryLogInput = {
1064
+ type: "object",
1065
+ properties: {
1066
+ since: {
1067
+ type: "string",
1068
+ description: "ISO timestamp lower bound."
1069
+ },
1070
+ status: {
1071
+ type: "string",
1072
+ enum: ["ok", "error"]
1073
+ },
1074
+ pageSize: {
1075
+ type: "integer",
1076
+ minimum: 1,
1077
+ maximum: 200,
1078
+ default: 50
1079
+ }
1080
+ },
1081
+ additionalProperties: false
1082
+ };
1083
+ anthropic.push({
1084
+ name: queryLogName,
1085
+ description: queryLogDesc,
1086
+ input_schema: queryLogInput
1087
+ });
1088
+ openai.push({
1089
+ type: "function",
1090
+ function: {
1091
+ name: queryLogName,
1092
+ description: queryLogDesc,
1093
+ parameters: queryLogInput
1094
+ }
1095
+ });
1096
+ const dbRef = `"${this.namespace}/${this.slug}"`;
1097
+ const branchesList = "branches_list";
1098
+ const branchesListInput = {
1099
+ type: "object",
1100
+ properties: {},
1101
+ additionalProperties: false
1102
+ };
1103
+ const branchesListDesc = `List preview branches of ${dbRef}. Each branch is its own SQLite database forked from the parent at create time.`;
1104
+ anthropic.push({
1105
+ name: branchesList,
1106
+ description: branchesListDesc,
1107
+ input_schema: branchesListInput
1108
+ });
1109
+ openai.push({
1110
+ type: "function",
1111
+ function: {
1112
+ name: branchesList,
1113
+ description: branchesListDesc,
1114
+ parameters: branchesListInput
1115
+ }
1116
+ });
1117
+ const branchesCreate = "branches_create";
1118
+ const branchesCreateInput = {
1119
+ type: "object",
1120
+ properties: {
1121
+ ref: {
1122
+ type: "string",
1123
+ description: "Stable identifier for the branch (e.g. 'pr-42' or 'agent-run-7c2f'). PUT semantics \u2014 the same ref re-runs as a reset from the parent's current state."
1124
+ },
1125
+ name: {
1126
+ type: "string",
1127
+ description: "Optional human-readable name."
1128
+ },
1129
+ ttlDays: {
1130
+ type: ["integer", "null"],
1131
+ minimum: 1,
1132
+ maximum: 30,
1133
+ description: "Auto-delete after N days (1..30). Use for ephemeral / scratch experiments."
1134
+ }
1135
+ },
1136
+ required: ["ref"],
1137
+ additionalProperties: false
1138
+ };
1139
+ const branchesCreateDesc = `Create-or-reset a branch of ${dbRef} keyed by ref. Idempotent: repeat the same ref to refresh from the current parent. Requires an admin-role token.`;
1140
+ anthropic.push({
1141
+ name: branchesCreate,
1142
+ description: branchesCreateDesc,
1143
+ input_schema: branchesCreateInput
1144
+ });
1145
+ openai.push({
1146
+ type: "function",
1147
+ function: {
1148
+ name: branchesCreate,
1149
+ description: branchesCreateDesc,
1150
+ parameters: branchesCreateInput
1151
+ }
1152
+ });
1153
+ const branchesDelete = "branches_delete";
1154
+ const branchesDeleteInput = {
1155
+ type: "object",
1156
+ properties: {
1157
+ ref: { type: "string", description: "The branch ref to delete." }
1158
+ },
1159
+ required: ["ref"],
1160
+ additionalProperties: false
1161
+ };
1162
+ const branchesDeleteDesc = `Delete a branch of ${dbRef}. Removes the branch's database and all of its data. Requires an admin-role token.`;
1163
+ anthropic.push({
1164
+ name: branchesDelete,
1165
+ description: branchesDeleteDesc,
1166
+ input_schema: branchesDeleteInput
1167
+ });
1168
+ openai.push({
1169
+ type: "function",
1170
+ function: {
1171
+ name: branchesDelete,
1172
+ description: branchesDeleteDesc,
1173
+ parameters: branchesDeleteInput
1174
+ }
1175
+ });
1176
+ const branchesMergeInput = {
1177
+ type: "object",
1178
+ properties: {
1179
+ ref: { type: "string", description: "The branch ref to apply." },
1180
+ mode: {
1181
+ type: "string",
1182
+ enum: ["schema", "promote"],
1183
+ description: "schema (default): apply the DDL delta \u2014 adds, plus replaces for views/triggers/indexes. Refuses table-shape changes. promote: replace the parent's full contents with the branch's (the parent keeps its identity)."
1184
+ },
1185
+ dropRemoved: {
1186
+ type: "boolean",
1187
+ description: "Schema mode only \u2014 also drop objects present in the parent but absent in the branch."
1188
+ }
1189
+ },
1190
+ required: ["ref"],
1191
+ additionalProperties: false
1192
+ };
1193
+ const branchesPreview = "branches_preview_merge";
1194
+ const branchesPreviewDesc = `Preview merging a branch of ${dbRef} back into its parent \u2014 returns the plan (added/changed/removed objects) without writing. Use this before branches_merge to show the user what will happen.`;
1195
+ anthropic.push({
1196
+ name: branchesPreview,
1197
+ description: branchesPreviewDesc,
1198
+ input_schema: branchesMergeInput
1199
+ });
1200
+ openai.push({
1201
+ type: "function",
1202
+ function: {
1203
+ name: branchesPreview,
1204
+ description: branchesPreviewDesc,
1205
+ parameters: branchesMergeInput
1206
+ }
1207
+ });
1208
+ const claimBranchName = "claim_branch";
1209
+ const claimBranchDesc = `One-shot lease: create a fresh branch of ${dbRef} AND mint a scoped psql_live_ token in the same call. Use this when delegating work to a sub-agent \u2014 return the token to the sub-agent, walk away, and the branch + token both expire when the lease ends. Requires an admin-role token.`;
1210
+ const claimBranchInput = {
1211
+ type: "object",
1212
+ properties: {
1213
+ purpose: {
1214
+ type: "string",
1215
+ description: "Free-text label baked into the auto-generated branch ref (e.g. 'agent-run-fix-issue-742')."
1216
+ },
1217
+ ttlSec: {
1218
+ type: "integer",
1219
+ minimum: 60,
1220
+ maximum: 60 * 60 * 24 * 30,
1221
+ description: "Lease duration in seconds. Default 3600 (1 hour)."
1222
+ },
1223
+ role: {
1224
+ type: "string",
1225
+ enum: ["read", "write", "admin"],
1226
+ description: "Role for the minted token. Default 'write'."
1227
+ }
1228
+ },
1229
+ additionalProperties: false
1230
+ };
1231
+ anthropic.push({
1232
+ name: claimBranchName,
1233
+ description: claimBranchDesc,
1234
+ input_schema: claimBranchInput
1235
+ });
1236
+ openai.push({
1237
+ type: "function",
1238
+ function: {
1239
+ name: claimBranchName,
1240
+ description: claimBranchDesc,
1241
+ parameters: claimBranchInput
1242
+ }
1243
+ });
1244
+ const branchesMerge = "branches_merge";
1245
+ const branchesMergeDesc = `Apply a branch back into ${dbRef}. Auto-snapshots the parent first (rollback via /restore with the returned snapshotId). Requires an admin-role token.`;
1246
+ anthropic.push({
1247
+ name: branchesMerge,
1248
+ description: branchesMergeDesc,
1249
+ input_schema: branchesMergeInput
1250
+ });
1251
+ openai.push({
1252
+ type: "function",
1253
+ function: {
1254
+ name: branchesMerge,
1255
+ description: branchesMergeDesc,
1256
+ parameters: branchesMergeInput
1257
+ }
1258
+ });
1259
+ const tableBySafe = /* @__PURE__ */ new Map();
1260
+ for (const t of schema.tables) tableBySafe.set(sanitizeToolPart(t.name), t);
1261
+ const run = async (name, input = {}) => {
1262
+ if (name === sqlName) {
1263
+ const sql = String(input.sql ?? "");
1264
+ const params2 = Array.isArray(input.params) ? input.params : [];
1265
+ return this.query(sql, params2);
1266
+ }
1267
+ if (name === describeDbName) {
1268
+ return this.describe();
1269
+ }
1270
+ if (name === searchSchemaName) {
1271
+ const q = String(input.q ?? "");
1272
+ if (!q) throw new Error("q is required");
1273
+ const limit2 = typeof input.limit === "number" ? input.limit : void 0;
1274
+ return this.search(q, limit2 !== void 0 ? { limit: limit2 } : {});
1275
+ }
1276
+ if (name === doctorName) {
1277
+ return this.doctor();
1278
+ }
1279
+ if (name === proposeName) {
1280
+ const sql = String(input.sql ?? "");
1281
+ if (!sql) throw new Error("sql is required");
1282
+ const params2 = Array.isArray(input.params) ? input.params : void 0;
1283
+ const ttlSec = typeof input.ttlSec === "number" ? input.ttlSec : void 0;
1284
+ return this.proposals.propose(sql, {
1285
+ params: params2,
1286
+ ttlSec
1287
+ });
1288
+ }
1289
+ if (name === applyName) {
1290
+ const token = String(input.executionToken ?? "");
1291
+ if (!token) throw new Error("executionToken is required");
1292
+ return this.proposals.apply(token);
1293
+ }
1294
+ if (name === queryLogName) {
1295
+ const opts = {};
1296
+ if (typeof input.since === "string") opts.since = input.since;
1297
+ if (input.status === "ok" || input.status === "error")
1298
+ opts.status = input.status;
1299
+ if (typeof input.pageSize === "number") opts.pageSize = input.pageSize;
1300
+ return this.queryLog(opts);
1301
+ }
1302
+ if (name === claimBranchName) {
1303
+ const opts = {};
1304
+ if (typeof input.purpose === "string") opts.purpose = input.purpose;
1305
+ if (typeof input.ttlSec === "number") opts.ttlSec = input.ttlSec;
1306
+ if (input.role === "read" || input.role === "write" || input.role === "admin")
1307
+ opts.role = input.role;
1308
+ return this.branches.claim(opts);
1309
+ }
1310
+ if (name === branchesList) {
1311
+ return this.branches.list();
1312
+ }
1313
+ if (name === branchesCreate) {
1314
+ const ref = String(input.ref ?? "");
1315
+ if (!ref) throw new Error("ref is required");
1316
+ const ttl = input.ttlDays;
1317
+ return this.branches.upsert(ref, {
1318
+ name: typeof input.name === "string" ? input.name : void 0,
1319
+ ttlDays: typeof ttl === "number" ? ttl : ttl === null ? null : void 0
1320
+ });
1321
+ }
1322
+ if (name === branchesDelete) {
1323
+ const ref = String(input.ref ?? "");
1324
+ if (!ref) throw new Error("ref is required");
1325
+ return this.branches.delete(ref);
1326
+ }
1327
+ if (name === branchesPreview || name === branchesMerge) {
1328
+ const ref = String(input.ref ?? "");
1329
+ if (!ref) throw new Error("ref is required");
1330
+ const mode = input.mode === "promote" ? "promote" : "schema";
1331
+ return this.branches.merge(ref, {
1332
+ mode,
1333
+ preview: name === branchesPreview,
1334
+ dropRemoved: input.dropRemoved === true
1335
+ });
1336
+ }
1337
+ const m = name.match(/^(select|count|describe|insert|update|delete)_(.+)$/);
1338
+ if (!m) throw new Error(`Unknown tool: ${name}`);
1339
+ const [, op, tableSafe] = m;
1340
+ const t = tableBySafe.get(tableSafe);
1341
+ if (!t) throw new Error(`Unknown table for tool ${name}`);
1342
+ const ident = quoteIdent(t.name);
1343
+ const colSetForT = new Set(t.columns.map((c) => c.name));
1344
+ if (op === "insert") {
1345
+ const values = input.values ?? {};
1346
+ const cols = Object.keys(values);
1347
+ if (cols.length === 0) throw new Error("values must be non-empty");
1348
+ for (const k of cols) {
1349
+ if (!colSetForT.has(k)) throw new Error(`Unknown column: ${k}`);
1350
+ }
1351
+ const placeholders = cols.map(() => "?").join(", ");
1352
+ const colSql = cols.map(quoteIdent).join(", ");
1353
+ return this.query(
1354
+ `INSERT INTO ${ident} (${colSql}) VALUES (${placeholders})`,
1355
+ cols.map((c) => values[c])
1356
+ );
1357
+ }
1358
+ if (op === "update") {
1359
+ const where2 = input.where ?? {};
1360
+ const setObj = input.set ?? {};
1361
+ const setKeys = Object.keys(setObj);
1362
+ const whereKeys = Object.keys(where2);
1363
+ if (setKeys.length === 0) throw new Error("set must be non-empty");
1364
+ if (whereKeys.length === 0)
1365
+ throw new Error("where must be non-empty \u2014 use sql_query for unfiltered updates");
1366
+ for (const k of [...setKeys, ...whereKeys]) {
1367
+ if (!colSetForT.has(k)) throw new Error(`Unknown column: ${k}`);
1368
+ }
1369
+ const setSql = setKeys.map((k) => `${quoteIdent(k)} = ?`).join(", ");
1370
+ const whereSqlParts = [];
1371
+ const whereParams = [];
1372
+ for (const k of whereKeys) {
1373
+ const v = where2[k];
1374
+ if (v === null) {
1375
+ whereSqlParts.push(`${quoteIdent(k)} IS NULL`);
1376
+ } else {
1377
+ whereSqlParts.push(`${quoteIdent(k)} = ?`);
1378
+ whereParams.push(v);
1379
+ }
1380
+ }
1381
+ return this.query(
1382
+ `UPDATE ${ident} SET ${setSql} WHERE ${whereSqlParts.join(" AND ")}`,
1383
+ [...setKeys.map((k) => setObj[k]), ...whereParams]
1384
+ );
1385
+ }
1386
+ if (op === "delete") {
1387
+ const where2 = input.where ?? {};
1388
+ const whereKeys = Object.keys(where2);
1389
+ if (whereKeys.length === 0)
1390
+ throw new Error("where must be non-empty \u2014 use sql_query for unfiltered deletes");
1391
+ for (const k of whereKeys) {
1392
+ if (!colSetForT.has(k)) throw new Error(`Unknown column: ${k}`);
1393
+ }
1394
+ const whereSqlParts = [];
1395
+ const whereParams = [];
1396
+ for (const k of whereKeys) {
1397
+ const v = where2[k];
1398
+ if (v === null) {
1399
+ whereSqlParts.push(`${quoteIdent(k)} IS NULL`);
1400
+ } else {
1401
+ whereSqlParts.push(`${quoteIdent(k)} = ?`);
1402
+ whereParams.push(v);
1403
+ }
1404
+ }
1405
+ return this.query(
1406
+ `DELETE FROM ${ident} WHERE ${whereSqlParts.join(" AND ")}`,
1407
+ whereParams
1408
+ );
1409
+ }
1410
+ if (op === "describe") {
1411
+ const [info, fks, count] = await Promise.all([
1412
+ this.query(`PRAGMA table_info(${ident})`),
1413
+ this.query(`PRAGMA foreign_key_list(${ident})`),
1414
+ this.query(`SELECT COUNT(*) AS n FROM ${ident}`)
1415
+ ]);
1416
+ return {
1417
+ table: t.name,
1418
+ rowCount: Number(count.rows[0]?.[0] ?? 0),
1419
+ columns: info.data,
1420
+ foreignKeys: fks.data
1421
+ };
1422
+ }
1423
+ const where = input.where ?? {};
1424
+ const colSet = new Set(t.columns.map((c) => c.name));
1425
+ const clauses = [];
1426
+ const params = [];
1427
+ for (const [k, v] of Object.entries(where)) {
1428
+ if (!colSet.has(k)) throw new Error(`Unknown column: ${k}`);
1429
+ if (v === null) {
1430
+ clauses.push(`${quoteIdent(k)} IS NULL`);
1431
+ } else {
1432
+ clauses.push(`${quoteIdent(k)} = ?`);
1433
+ params.push(v);
1434
+ }
1435
+ }
1436
+ const whereSql = clauses.length ? ` WHERE ${clauses.join(" AND ")}` : "";
1437
+ if (op === "count") {
1438
+ const r2 = await this.query(`SELECT COUNT(*) AS n FROM ${ident}${whereSql}`, params);
1439
+ return { count: Number(r2.rows[0]?.[0] ?? 0) };
1440
+ }
1441
+ const limit = Math.min(1e3, Math.max(1, Number(input.limit ?? 100)));
1442
+ let orderSql = "";
1443
+ if (typeof input.orderBy === "string" && input.orderBy.trim()) {
1444
+ const ob = input.orderBy.trim();
1445
+ const obMatch = ob.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(asc|desc)?$/i);
1446
+ if (!obMatch) throw new Error("orderBy must be `<col>` or `<col> ASC|DESC`");
1447
+ const [, col, dir] = obMatch;
1448
+ if (!colSet.has(col)) throw new Error(`Unknown column: ${col}`);
1449
+ orderSql = ` ORDER BY ${quoteIdent(col)} ${(dir ?? "ASC").toUpperCase()}`;
1450
+ }
1451
+ const r = await this.query(
1452
+ `SELECT * FROM ${ident}${whereSql}${orderSql} LIMIT ${limit}`,
1453
+ params
1454
+ );
1455
+ return r;
1456
+ };
1457
+ const aiSdk = () => {
1458
+ const out = {};
1459
+ for (const t of anthropic) {
1460
+ out[t.name] = {
1461
+ description: t.description,
1462
+ inputSchema: t.input_schema,
1463
+ execute: (input) => run(t.name, input)
1464
+ };
1465
+ }
1466
+ return out;
1467
+ };
1468
+ const mastra = () => {
1469
+ const out = {};
1470
+ for (const t of anthropic) {
1471
+ out[t.name] = {
1472
+ id: t.name,
1473
+ description: t.description,
1474
+ inputSchema: t.input_schema,
1475
+ execute: ({ context }) => run(t.name, context)
1476
+ };
1477
+ }
1478
+ return out;
1479
+ };
1480
+ const langchain = () => anthropic.map((t) => ({
1481
+ name: t.name,
1482
+ description: t.description,
1483
+ schema: t.input_schema,
1484
+ invoke: (input) => run(t.name, input)
1485
+ }));
1486
+ const openaiAgents = () => anthropic.map((t) => ({
1487
+ type: "function",
1488
+ name: t.name,
1489
+ description: t.description,
1490
+ parameters: t.input_schema,
1491
+ invoke: (input) => run(t.name, input)
1492
+ }));
1493
+ return { anthropic, openai, run, aiSdk, mastra, langchain, openaiAgents };
1494
+ }
1495
+ };
1496
+ function sanitizeToolPart(s) {
1497
+ return s.replace(/[^A-Za-z0-9_]/g, "_");
1498
+ }
1499
+ function quoteIdent(s) {
1500
+ return `"${s.replace(/"/g, '""')}"`;
1501
+ }
1502
+ var PerSQLBlob = class {
1503
+ constructor(client, namespace, slug) {
1504
+ this.client = client;
1505
+ this.namespace = namespace;
1506
+ this.slug = slug;
1507
+ }
1508
+ /** Upload a blob. Body can be ArrayBuffer, Blob, ReadableStream, or string. */
1509
+ async put(key, body, opts = {}) {
1510
+ const path = `/v1/db/${this.namespace}/${this.slug}/blobs/${encodeBlobKey(key)}`;
1511
+ return this.client.requestRaw(
1512
+ "PUT",
1513
+ path,
1514
+ body,
1515
+ opts.contentType
1516
+ );
1517
+ }
1518
+ /** Fetch a blob. Returns null if missing. */
1519
+ async get(key) {
1520
+ const path = `/v1/db/${this.namespace}/${this.slug}/blobs/${encodeBlobKey(key)}`;
1521
+ const res = await this.client.fetchRaw("GET", path);
1522
+ if (res.status === 404) return null;
1523
+ if (!res.ok) {
1524
+ throw new PerSQLError(res.status, `Blob fetch failed (${res.status})`);
1525
+ }
1526
+ return res;
1527
+ }
1528
+ /** Delete a blob. */
1529
+ async delete(key) {
1530
+ const path = `/v1/db/${this.namespace}/${this.slug}/blobs/${encodeBlobKey(key)}`;
1531
+ await this.client.request("DELETE", path);
1532
+ }
1533
+ /** List blobs by prefix. */
1534
+ async list(opts = {}) {
1535
+ const params = new URLSearchParams();
1536
+ if (opts.prefix) params.set("prefix", opts.prefix);
1537
+ if (opts.cursor) params.set("cursor", opts.cursor);
1538
+ if (opts.limit) params.set("limit", String(opts.limit));
1539
+ const qs = params.toString();
1540
+ const path = `/v1/db/${this.namespace}/${this.slug}/blobs` + (qs ? `?${qs}` : "");
1541
+ return this.client.request("GET", path);
1542
+ }
1543
+ };
1544
+ function encodeBlobKey(key) {
1545
+ return key.split("/").map(encodeURIComponent).join("/");
1546
+ }
1547
+ var PerSQLVectors = class {
1548
+ constructor(client, namespace, slug) {
1549
+ this.client = client;
1550
+ this.namespace = namespace;
1551
+ this.slug = slug;
1552
+ }
1553
+ /** Embed and upsert up to 100 items in one call. */
1554
+ async upsert(items) {
1555
+ return this.client.request(
1556
+ "POST",
1557
+ `/v1/db/${this.namespace}/${this.slug}/vectors`,
1558
+ { items }
1559
+ );
1560
+ }
1561
+ /** Top-K nearest neighbours by free-text query. */
1562
+ async query(text, opts = {}) {
1563
+ return this.client.request(
1564
+ "POST",
1565
+ `/v1/db/${this.namespace}/${this.slug}/vectors/query`,
1566
+ { query: text, topK: opts.topK, filter: opts.filter }
1567
+ );
1568
+ }
1569
+ /** Delete vectors by id. Up to 1000 ids per call. */
1570
+ async delete(ids) {
1571
+ return this.client.request(
1572
+ "DELETE",
1573
+ `/v1/db/${this.namespace}/${this.slug}/vectors`,
1574
+ { ids }
1575
+ );
1576
+ }
1577
+ };
1578
+ var PerSQLApprovals = class {
1579
+ constructor(client, namespace, slug) {
1580
+ this.client = client;
1581
+ this.namespace = namespace;
1582
+ this.slug = slug;
1583
+ }
1584
+ /**
1585
+ * Redeem an approved approvalToken. The bearer must be the same one
1586
+ * that minted it, and the request must target the same database.
1587
+ * Returns the result of the originally-blocked query or batch.
1588
+ */
1589
+ async redeem(approvalToken) {
1590
+ const raw = await this.client.request("POST", `/v1/db/${this.namespace}/${this.slug}/redeem_approval`, {
1591
+ approvalToken
1592
+ });
1593
+ if (Array.isArray(raw)) {
1594
+ return raw.map((r) => ({
1595
+ ...r,
1596
+ data: rowsToObjects(r.columns, r.rows)
1597
+ }));
1598
+ }
1599
+ return { ...raw, data: rowsToObjects(raw.columns, raw.rows) };
1600
+ }
1601
+ };
1602
+ var PerSQLProposals = class {
1603
+ constructor(client, namespace, slug) {
1604
+ this.client = client;
1605
+ this.namespace = namespace;
1606
+ this.slug = slug;
1607
+ }
1608
+ /**
1609
+ * Pre-flight an SQL statement. EXPLAIN-validates, estimates affected
1610
+ * rows, and returns a single-use `executionToken` valid for 10 min
1611
+ * (override with `ttlSec`, max 1 hour). Nothing is mutated until
1612
+ * `apply()` is called.
1613
+ */
1614
+ async propose(sql, opts = {}) {
1615
+ if (this.client.local) {
1616
+ return this.client.local.propose(sql, opts.params ?? [], opts.ttlSec);
1617
+ }
1618
+ return this.client.request(
1619
+ "POST",
1620
+ `/v1/db/${this.namespace}/${this.slug}/propose`,
1621
+ {
1622
+ sql,
1623
+ params: opts.params ?? [],
1624
+ ttlSec: opts.ttlSec
1625
+ }
1626
+ );
1627
+ }
1628
+ /**
1629
+ * Redeem an `executionToken` from `propose()`. Single-use — calling
1630
+ * twice with the same token throws 404. The token is also pinned to
1631
+ * the originating bearer + database; cross-token redemption throws
1632
+ * 403.
1633
+ */
1634
+ async apply(executionToken) {
1635
+ if (this.client.local) {
1636
+ const raw2 = await this.client.local.apply(executionToken);
1637
+ return { ...raw2, data: rowsToObjects(raw2.columns, raw2.rows) };
1638
+ }
1639
+ const raw = await this.client.request("POST", `/v1/db/${this.namespace}/${this.slug}/apply`, { executionToken });
1640
+ return {
1641
+ ...raw,
1642
+ data: rowsToObjects(raw.columns, raw.rows)
1643
+ };
1644
+ }
1645
+ };
1646
+ var PerSQLBranches = class {
1647
+ constructor(client, namespace, slug) {
1648
+ this.client = client;
1649
+ this.namespace = namespace;
1650
+ this.slug = slug;
1651
+ }
1652
+ /**
1653
+ * One-shot lease — create or reset a branch with a TTL and mint a
1654
+ * scoped token in the same call. Use at the start of an agent run
1655
+ * instead of chaining create + token mint.
1656
+ */
1657
+ async claim(opts = {}) {
1658
+ return this.client.request(
1659
+ "POST",
1660
+ `/v1/db/${this.namespace}/${this.slug}/claim_branch`,
1661
+ opts
1662
+ );
1663
+ }
1664
+ /** List branches of this database. Any-role token. */
1665
+ async list(opts = {}) {
1666
+ const qs = new URLSearchParams();
1667
+ if (opts.cursor) qs.set("cursor", opts.cursor);
1668
+ if (opts.pageSize) qs.set("pageSize", String(opts.pageSize));
1669
+ const tail = qs.toString() ? `?${qs.toString()}` : "";
1670
+ const res = await this.client.fetchRaw(
1671
+ "GET",
1672
+ `/v1/db/${this.namespace}/${this.slug}/branches${tail}`
1673
+ );
1674
+ const body = await res.json();
1675
+ if (!res.ok || !body.success) {
1676
+ throw new PerSQLError(res.status, body.error ?? `Request failed (${res.status})`);
1677
+ }
1678
+ return { data: body.data ?? [], nextCursor: body.nextCursor ?? null };
1679
+ }
1680
+ /**
1681
+ * Create-or-reset a branch by ref. Idempotent: re-PUTting the same
1682
+ * ref refreshes the branch from the parent's current state.
1683
+ * Requires an admin-role token.
1684
+ */
1685
+ async upsert(ref, opts = {}) {
1686
+ return this.client.request(
1687
+ "PUT",
1688
+ `/v1/db/${this.namespace}/${this.slug}/branches/${encodeURIComponent(ref)}`,
1689
+ {
1690
+ name: opts.name,
1691
+ region: opts.region,
1692
+ ttlDays: opts.ttlDays ?? null
1693
+ }
1694
+ );
1695
+ }
1696
+ /** Delete a branch by ref. Requires an admin-role token. */
1697
+ async delete(ref) {
1698
+ return this.client.request(
1699
+ "DELETE",
1700
+ `/v1/db/${this.namespace}/${this.slug}/branches/${encodeURIComponent(ref)}`
1701
+ );
1702
+ }
1703
+ /**
1704
+ * Apply a branch back into its parent. `preview: true` returns the
1705
+ * plan without writing. Requires an admin-role token.
1706
+ */
1707
+ async merge(ref, opts = {}) {
1708
+ return this.client.request(
1709
+ "POST",
1710
+ `/v1/db/${this.namespace}/${this.slug}/branches/${encodeURIComponent(ref)}/merge`,
1711
+ {
1712
+ mode: opts.mode ?? "schema",
1713
+ preview: opts.preview === true,
1714
+ dropRemoved: opts.dropRemoved === true,
1715
+ snapshot: opts.snapshot !== false
1716
+ }
1717
+ );
1718
+ }
1719
+ /** Convenience for `merge(ref, { preview: true, ...opts })`. */
1720
+ preview(ref, opts = {}) {
1721
+ return this.merge(ref, { ...opts, preview: true });
1722
+ }
1723
+ /**
1724
+ * Mint a single-use handoff token for this branch. The receiving
1725
+ * agent calls `PerSQL.fromHandoff(token)` to redeem it for a
1726
+ * regular bearer token scoped to exactly this (database, branch,
1727
+ * role) — the agent that minted the handoff never has to share
1728
+ * its own token. Single-use, ≤24h TTL.
1729
+ */
1730
+ async pin(ref, opts = {}) {
1731
+ return this.client.request(
1732
+ "POST",
1733
+ `/v1/db/${this.namespace}/${this.slug}/branches/${encodeURIComponent(ref)}/pin`,
1734
+ { role: opts.role ?? "write", ttlSec: opts.ttlSec }
1735
+ );
1736
+ }
1737
+ /**
1738
+ * Render the branch's schema delta as a committable SQL migration.
1739
+ * Read-only. Returns `{ name, sql, plan, summary }` — `name` is a
1740
+ * timestamped filename (`YYYYMMDDHHMMSS_branch_<ref>.sql`) safe to
1741
+ * write to disk; `sql` is the migration body wrapped in a single
1742
+ * BEGIN/COMMIT.
1743
+ */
1744
+ async migration(ref, opts = {}) {
1745
+ return this.client.request(
1746
+ "POST",
1747
+ `/v1/db/${this.namespace}/${this.slug}/branches/${encodeURIComponent(ref)}/migration`,
1748
+ { dropRemoved: opts.dropRemoved === true }
1749
+ );
1750
+ }
1751
+ };
1752
+ function rowsToObjects(columns, rows) {
1753
+ return rows.map((r) => {
1754
+ const obj = {};
1755
+ for (let i = 0; i < columns.length; i++) obj[columns[i]] = r[i];
1756
+ return obj;
1757
+ });
1758
+ }
1759
+ // Annotate the CommonJS export names for ESM import in node:
1760
+ 0 && (module.exports = {
1761
+ ApprovalRequiredError,
1762
+ PerSQL,
1763
+ PerSQLApprovals,
1764
+ PerSQLBlob,
1765
+ PerSQLBranches,
1766
+ PerSQLDatabase,
1767
+ PerSQLError,
1768
+ PerSQLProposals,
1769
+ PerSQLVectors,
1770
+ RateLimitError
1771
+ });
1772
+ //# sourceMappingURL=index.cjs.map