@nextblock-cms/cortex 0.20.1 → 0.21.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.
Files changed (71) hide show
  1. package/client.cjs.js +1 -1
  2. package/client.es.js +3 -7
  3. package/index.cjs.js +1 -1
  4. package/index.es.js +24 -277
  5. package/lib/ai-block-generation.cjs.js +3 -4
  6. package/lib/ai-block-generation.es.js +143 -182
  7. package/lib/ai-client.cjs.js +1 -1
  8. package/lib/ai-client.d.ts +1 -1
  9. package/lib/ai-client.es.js +101 -135
  10. package/lib/ai-config.cjs.js +1 -1
  11. package/lib/ai-config.es.js +89 -108
  12. package/lib/ai-cortex-widget-builder.cjs.js +1 -1
  13. package/lib/ai-cortex-widget-builder.es.js +56 -70
  14. package/lib/ai-global-agent-content-ops-tools.cjs.js +1 -1
  15. package/lib/ai-global-agent-content-ops-tools.d.ts +1943 -68
  16. package/lib/ai-global-agent-content-ops-tools.es.js +185 -199
  17. package/lib/ai-global-agent-custom-block-tools.cjs.js +1 -1
  18. package/lib/ai-global-agent-custom-block-tools.d.ts +2160 -95
  19. package/lib/ai-global-agent-custom-block-tools.es.js +226 -223
  20. package/lib/ai-global-agent-db-tools.cjs.js +1 -1
  21. package/lib/ai-global-agent-db-tools.d.ts +2708 -98
  22. package/lib/ai-global-agent-db-tools.es.js +1013 -986
  23. package/lib/ai-global-agent-ecommerce.cjs.js +1 -1
  24. package/lib/ai-global-agent-ecommerce.es.js +3 -7
  25. package/lib/ai-global-agent-site-tools.cjs.js +2 -3
  26. package/lib/ai-global-agent-site-tools.d.ts +10695 -500
  27. package/lib/ai-global-agent-site-tools.es.js +750 -757
  28. package/lib/ai-global-agent-theming-tools.cjs.js +1 -3
  29. package/lib/ai-global-agent-theming-tools.d.ts +2905 -105
  30. package/lib/ai-global-agent-theming-tools.es.js +326 -396
  31. package/lib/ai-global-agent-tools.cjs.js +2 -2
  32. package/lib/ai-global-agent-tools.d.ts +4 -2230
  33. package/lib/ai-global-agent-tools.es.js +3899 -4328
  34. package/lib/ai-key-crypto.cjs.js +1 -1
  35. package/lib/ai-key-crypto.es.js +63 -82
  36. package/lib/ai-key-verification.cjs.js +1 -1
  37. package/lib/ai-key-verification.es.js +74 -63
  38. package/lib/ai-model-catalog.cjs.js +1 -1
  39. package/lib/ai-model-catalog.es.js +18 -22
  40. package/lib/ai-model-registry.cjs.js +2 -2
  41. package/lib/ai-model-registry.es.js +246 -309
  42. package/lib/ai-seo-metadata.cjs.js +2 -3
  43. package/lib/ai-seo-metadata.es.js +143 -185
  44. package/lib/ai-vision.cjs.js +2 -2
  45. package/lib/ai-vision.d.ts +6 -6
  46. package/lib/ai-vision.es.js +161 -215
  47. package/lib/block-content-schemas.cjs.js +1 -1
  48. package/lib/block-content-schemas.es.js +324 -254
  49. package/lib/cortex-widget-registry.cjs.js +1 -1
  50. package/lib/cortex-widget-registry.es.js +35 -43
  51. package/lib/cortex-widget-schema.cjs.js +2 -3
  52. package/lib/cortex-widget-schema.es.js +280 -309
  53. package/lib/editor-document-from-html.cjs.js +1 -1
  54. package/lib/editor-document-from-html.es.js +334 -278
  55. package/lib/fetch-host-guard.cjs.js +1 -0
  56. package/lib/fetch-host-guard.d.ts +2 -0
  57. package/lib/fetch-host-guard.es.js +30 -0
  58. package/lib/mcp-server.cjs.js +1 -1
  59. package/lib/mcp-server.es.js +155 -173
  60. package/lib/mcp-tokens.cjs.js +1 -1
  61. package/lib/mcp-tokens.es.js +95 -107
  62. package/lib/mcp-tool-registry.cjs.js +5 -6
  63. package/lib/mcp-tool-registry.es.js +533 -411
  64. package/lib/site-brief.cjs.js +2 -2
  65. package/lib/site-brief.es.js +102 -108
  66. package/lib/vision-image-download.cjs.js +1 -0
  67. package/lib/vision-image-download.d.ts +43 -0
  68. package/lib/vision-image-download.es.js +120 -0
  69. package/lib/zod-config.cjs.js +1 -1
  70. package/lib/zod-config.es.js +5 -6
  71. package/package.json +8 -8
@@ -1,1025 +1,1052 @@
1
- import { tool as k } from "ai";
2
- import { isValidBlockType as Y, validateCortexBlockContent as H, validateCustomBlockInstanceContent as Z, loadCustomBlockDefinitions as ee } from "./block-content-schemas.es.js";
3
- import { cortexSiteBriefSchema as te } from "./site-brief.es.js";
4
- import "./zod-config.es.js";
5
- import { z as o } from "zod";
6
- const re = 100, ae = 20, x = 100, C = 20, D = "[REDACTED]", N = "cortex_ai_openrouter_api_key", K = /* @__PURE__ */ new Set([
7
- N,
8
- "bot_protection_secret",
9
- "cortex_ai_pexels_api_key",
10
- "cortex_ai_unsplash_access_key",
11
- "email_secret",
12
- "payment_secret"
13
- ]), j = /* @__PURE__ */ new Set([
14
- "cortex_ai_build_session",
15
- "is_admin_created",
16
- "migration_baseline_generation",
17
- "security_settings"
18
- ]), ie = {
19
- active_logo_id: o.string().uuid().nullable(),
20
- cortex_ai_site_brief: te,
21
- footer_copyright: o.record(o.string().trim().min(2).max(12), o.string().max(500)),
22
- footer_show_attribution: o.boolean(),
23
- global_css: o.string().max(2e5),
24
- onboarding_state: o.record(o.string(), o.unknown()),
25
- site_description: o.string().max(1e3),
26
- site_keywords: o.string().max(1e3),
27
- site_title: o.string().max(200)
1
+ import { z as e } from "./zod-config.es.js";
2
+ import { cortexSiteBriefSchema as t } from "./site-brief.es.js";
3
+ import { isValidBlockType as n, loadCustomBlockDefinitions as r, validateCortexBlockContent as i, validateCustomBlockInstanceContent as a } from "./block-content-schemas.es.js";
4
+ import { tool as o } from "ai";
5
+ //#region libs/cortex/src/lib/ai-global-agent-db-tools.ts
6
+ var s = 100, c = 20, l = 100, u = 20, d = "[REDACTED]", f = "cortex_ai_openrouter_api_key", p = /* @__PURE__ */ new Set([
7
+ f,
8
+ "bot_protection_secret",
9
+ "cortex_ai_pexels_api_key",
10
+ "cortex_ai_unsplash_access_key",
11
+ "email_secret",
12
+ "payment_secret"
13
+ ]), m = /* @__PURE__ */ new Set([
14
+ "cortex_ai_build_session",
15
+ "is_admin_created",
16
+ "migration_baseline_generation",
17
+ "security_settings"
18
+ ]), ee = {
19
+ active_logo_id: e.string().uuid().nullable(),
20
+ cortex_ai_site_brief: t,
21
+ footer_copyright: e.record(e.string().trim().min(2).max(12), e.string().max(500)),
22
+ footer_show_attribution: e.boolean(),
23
+ global_css: e.string().max(2e5),
24
+ onboarding_state: e.record(e.string(), e.unknown()),
25
+ site_description: e.string().max(1e3),
26
+ site_keywords: e.string().max(1e3),
27
+ site_title: e.string().max(200)
28
28
  };
29
- function oe(e) {
30
- return e.map((t) => {
31
- const r = t.path.map(String).join(".");
32
- return r ? `${r}: ${t.message}` : t.message;
33
- }).join("; ");
29
+ function h(e) {
30
+ return e.map((e) => {
31
+ let t = e.path.map(String).join(".");
32
+ return t ? `${t}: ${e.message}` : e.message;
33
+ }).join("; ");
34
34
  }
35
- function A(e, t) {
36
- if (j.has(e))
37
- throw new Error(`The "${e}" site setting cannot be written through Cortex AI database tools.`);
38
- const r = ie[e];
39
- if (!r)
40
- return;
41
- const a = r.safeParse(t);
42
- if (!a.success)
43
- throw new Error(`Invalid value for site setting "${e}": ${oe(a.error.issues)}`);
35
+ function g(e, t) {
36
+ if (m.has(e)) throw Error(`The "${e}" site setting cannot be written through Cortex AI database tools.`);
37
+ let n = ee[e];
38
+ if (!n) return;
39
+ let r = n.safeParse(t);
40
+ if (!r.success) throw Error(`Invalid value for site setting "${e}": ${h(r.error.issues)}`);
44
41
  }
45
- async function R(e) {
46
- const t = typeof e.blockType == "string" ? e.blockType : "";
47
- if (!t)
48
- throw new Error(`${e.label}: block_type is required.`);
49
- if (!e.content || typeof e.content != "object" || Array.isArray(e.content))
50
- throw new Error(`${e.label}: content must be a JSON object.`);
51
- const r = e.content;
52
- if (Y(t)) {
53
- const i = H(t, r, e.context);
54
- if (!i.isValid)
55
- throw new Error(`${e.label}: content is invalid for block type "${t}": ${i.errors.join("; ")}`);
56
- return;
57
- }
58
- const a = (await e.definitions()).find((i) => i.slug === t);
59
- if (!a)
60
- throw new Error(
61
- `${e.label}: "${t}" is neither a built-in block type nor a custom block slug. Use list_custom_blocks to see the custom block definitions.`
62
- );
63
- const n = Z(a, r);
64
- if (!n.isValid)
65
- throw new Error(`${e.label}: content is invalid for custom block "${t}": ${n.errors.join("; ")}`);
42
+ async function _(e) {
43
+ let t = typeof e.blockType == "string" ? e.blockType : "";
44
+ if (!t) throw Error(`${e.label}: block_type is required.`);
45
+ if (!e.content || typeof e.content != "object" || Array.isArray(e.content)) throw Error(`${e.label}: content must be a JSON object.`);
46
+ let r = e.content;
47
+ if (n(t)) {
48
+ let n = i(t, r, e.context);
49
+ if (!n.isValid) throw Error(`${e.label}: content is invalid for block type "${t}": ${n.errors.join("; ")}`);
50
+ return;
51
+ }
52
+ let o = (await e.definitions()).find((e) => e.slug === t);
53
+ if (!o) throw Error(`${e.label}: "${t}" is neither a built-in block type nor a custom block slug. Use list_custom_blocks to see the custom block definitions.`);
54
+ let s = a(o, r);
55
+ if (!s.isValid) throw Error(`${e.label}: content is invalid for custom block "${t}": ${s.errors.join("; ")}`);
66
56
  }
67
- async function L(e, t, r) {
68
- if (t === "site_settings") {
69
- for (const i of e.rows ?? [])
70
- typeof i.key == "string" && A(i.key, i.value);
71
- if (e.operation === "update" && e.values) {
72
- const i = typeof e.values.key == "string" ? e.values.key : null, s = (e.filters ?? []).find(
73
- (u) => u.column === "key" && u.operator === "eq" && typeof u.value == "string"
74
- ), c = i ?? (s ? String(s.value) : null);
75
- c && ("value" in e.values ? A(c, e.values.value) : j.has(c) && A(c, void 0));
76
- }
77
- return;
78
- }
79
- if (t !== "blocks")
80
- return;
81
- let a = null;
82
- const n = () => a ??= ee(g(r));
83
- if (e.operation === "insert" || e.operation === "upsert") {
84
- for (const [i, s] of (e.rows ?? []).entries())
85
- await R({
86
- blockType: s.block_type,
87
- content: s.content ?? {},
88
- context: r,
89
- definitions: n,
90
- label: `rows[${i}]`
91
- });
92
- return;
93
- }
94
- if (e.operation === "update" && e.values) {
95
- const i = "content" in e.values, s = "block_type" in e.values;
96
- if (!i && !s)
97
- return;
98
- if (s && !i)
99
- throw new Error("Changing block_type requires the new content for that type in the same update.");
100
- const c = /* @__PURE__ */ new Set();
101
- if (s)
102
- c.add(String(e.values.block_type));
103
- else {
104
- let u = g(r).from("blocks").select("id, block_type").limit(x + 1);
105
- u = w(t, u, e.filters ?? []);
106
- const { data: _, error: m } = await u;
107
- if (m)
108
- throw new Error(`Failed to read the blocks to update: ${f(m)}`);
109
- for (const d of Array.isArray(_) ? _ : [])
110
- c.add(String(d.block_type ?? ""));
111
- }
112
- for (const u of c)
113
- await R({
114
- blockType: u,
115
- content: e.values.content,
116
- context: r,
117
- definitions: n,
118
- label: `values (block_type "${u}")`
119
- });
120
- }
57
+ async function v(e, t, n) {
58
+ if (t === "site_settings") {
59
+ for (let t of e.rows ?? []) typeof t.key == "string" && g(t.key, t.value);
60
+ if (e.operation === "update" && e.values) {
61
+ let t = typeof e.values.key == "string" ? e.values.key : null, n = (e.filters ?? []).find((e) => e.column === "key" && e.operator === "eq" && typeof e.value == "string"), r = t ?? (n ? String(n.value) : null);
62
+ r && ("value" in e.values ? g(r, e.values.value) : m.has(r) && g(r, void 0));
63
+ }
64
+ return;
65
+ }
66
+ if (t !== "blocks") return;
67
+ let i = null, a = () => i ??= r(D(n));
68
+ if (e.operation === "insert" || e.operation === "upsert") {
69
+ for (let [t, r] of (e.rows ?? []).entries()) await _({
70
+ blockType: r.block_type,
71
+ content: r.content ?? {},
72
+ context: n,
73
+ definitions: a,
74
+ label: `rows[${t}]`
75
+ });
76
+ return;
77
+ }
78
+ if (e.operation === "update" && e.values) {
79
+ let r = "content" in e.values, i = "block_type" in e.values;
80
+ if (!r && !i) return;
81
+ if (i && !r) throw Error("Changing block_type requires the new content for that type in the same update.");
82
+ let o = /* @__PURE__ */ new Set();
83
+ if (i) o.add(String(e.values.block_type));
84
+ else {
85
+ let r = D(n).from("blocks").select("id, block_type").limit(101);
86
+ r = W(t, r, e.filters ?? []);
87
+ let { data: i, error: a } = await r;
88
+ if (a) throw Error(`Failed to read the blocks to update: ${O(a)}`);
89
+ for (let e of Array.isArray(i) ? i : []) o.add(String(e.block_type ?? ""));
90
+ }
91
+ for (let t of o) await _({
92
+ blockType: t,
93
+ content: e.values.content,
94
+ context: n,
95
+ definitions: a,
96
+ label: `values (block_type "${t}")`
97
+ });
98
+ }
121
99
  }
122
- const O = {
123
- blocks: {
124
- columns: ["id", "page_id", "post_id", "language_id", "block_type", "content", "order", "created_at", "updated_at"],
125
- description: "CMS page/post content blocks.",
126
- primaryKey: ["id"]
127
- },
128
- coupon_freemius_mappings: {
129
- columns: [
130
- "id",
131
- "coupon_id",
132
- "product_id",
133
- "freemius_product_id",
134
- "freemius_coupon_id",
135
- "freemius_coupon_code",
136
- "sync_status",
137
- "sync_error",
138
- "remote_payload",
139
- "last_synced_at",
140
- "created_at",
141
- "updated_at"
142
- ],
143
- description: "Freemius coupon sync mappings.",
144
- primaryKey: ["id"]
145
- },
146
- coupon_products: {
147
- columns: ["coupon_id", "product_id", "created_at"],
148
- description: "Coupon product allow-list rows.",
149
- primaryKey: ["coupon_id", "product_id"]
150
- },
151
- coupon_redemptions: {
152
- columns: [
153
- "id",
154
- "coupon_id",
155
- "order_id",
156
- "coupon_code",
157
- "provider",
158
- "discount_total",
159
- "user_id",
160
- "customer_email",
161
- "metadata",
162
- "redeemed_at"
163
- ],
164
- description: "Coupon redemption records.",
165
- primaryKey: ["id"]
166
- },
167
- coupons: {
168
- columns: [
169
- "id",
170
- "code",
171
- "name",
172
- "internal_note",
173
- "provider_scope",
174
- "discount_type",
175
- "discount_amount",
176
- "is_active",
177
- "starts_at",
178
- "ends_at",
179
- "redemption_limit",
180
- "redemptions_count",
181
- "freemius_sync_status",
182
- "freemius_sync_error",
183
- "created_at",
184
- "updated_at"
185
- ],
186
- description: "Commerce coupons.",
187
- primaryKey: ["id"]
188
- },
189
- cortex_ai_db_mutation_audit: {
190
- columns: [
191
- "id",
192
- "actor_user_id",
193
- "tool_name",
194
- "action_name",
195
- "target_tables",
196
- "operation_summary",
197
- "payload_hash",
198
- "payload",
199
- "preview",
200
- "status",
201
- "error_message",
202
- "created_at"
203
- ],
204
- description: "Read-only Cortex AI database mutation audit trail.",
205
- primaryKey: ["id"],
206
- readOnly: !0
207
- },
208
- currencies: {
209
- columns: [
210
- "id",
211
- "code",
212
- "symbol",
213
- "exchange_rate",
214
- "is_default",
215
- "is_active",
216
- "rounding_mode",
217
- "rounding_increment",
218
- "rounding_charm_amount",
219
- "auto_update_exchange_rate",
220
- "exchange_rate_updated_at",
221
- "exchange_rate_source",
222
- "auto_sync_product_prices",
223
- "created_at",
224
- "updated_at"
225
- ],
226
- description: "Storefront currencies and FX settings.",
227
- primaryKey: ["id"]
228
- },
229
- freemius_plans: {
230
- columns: ["id", "product_id", "name", "title", "created_at", "updated_at"],
231
- description: "Freemius plan metadata.",
232
- primaryKey: ["id"]
233
- },
234
- freemius_pricing: {
235
- columns: [
236
- "id",
237
- "plan_id",
238
- "api_monthly_price",
239
- "api_annual_price",
240
- "api_lifetime_price",
241
- "override_monthly_price",
242
- "override_annual_price",
243
- "override_lifetime_price",
244
- "license_quota",
245
- "is_active",
246
- "created_at",
247
- "updated_at"
248
- ],
249
- description: "Freemius pricing metadata.",
250
- primaryKey: ["id"]
251
- },
252
- inventory_items: {
253
- columns: ["sku", "quantity", "created_at", "updated_at"],
254
- description: "Source-of-truth inventory by SKU.",
255
- primaryKey: ["sku"]
256
- },
257
- languages: {
258
- columns: ["id", "code", "name", "is_default", "is_active", "created_at", "updated_at"],
259
- description: "CMS languages/locales.",
260
- primaryKey: ["id"]
261
- },
262
- logos: {
263
- columns: ["id", "name", "media_id", "created_at"],
264
- description: "Brand logos.",
265
- primaryKey: ["id"]
266
- },
267
- media: {
268
- columns: [
269
- "id",
270
- "uploader_id",
271
- "file_name",
272
- "object_key",
273
- "file_type",
274
- "size_bytes",
275
- "description",
276
- "width",
277
- "height",
278
- "blur_data_url",
279
- "variants",
280
- "file_path",
281
- "folder",
282
- "created_at",
283
- "updated_at"
284
- ],
285
- description: "Media metadata for uploaded assets.",
286
- primaryKey: ["id"]
287
- },
288
- navigation_items: {
289
- columns: [
290
- "id",
291
- "language_id",
292
- "menu_key",
293
- "label",
294
- "url",
295
- "parent_id",
296
- "order",
297
- "page_id",
298
- "translation_group_id",
299
- "created_at",
300
- "updated_at"
301
- ],
302
- description: "CMS navigation tree items.",
303
- primaryKey: ["id"]
304
- },
305
- order_items: {
306
- columns: ["id", "order_id", "product_id", "variant_id", "quantity", "price_at_purchase"],
307
- description: "Commerce order line items.",
308
- primaryKey: ["id"]
309
- },
310
- orders: {
311
- columns: [
312
- "id",
313
- "user_id",
314
- "status",
315
- "total",
316
- "stripe_session_id",
317
- "payment_intent_id",
318
- "customer_details",
319
- "provider",
320
- "freemius_product_id",
321
- "freemius_plan_id",
322
- "freemius_license_id",
323
- "freemius_subscription_id",
324
- "freemius_trial_id",
325
- "freemius_user_id",
326
- "freemius_trial_ends_at",
327
- "freemius_last_event_type",
328
- "freemius_last_synced_at",
329
- "currency",
330
- "subtotal",
331
- "shipping_total",
332
- "tax_total",
333
- "tax_details",
334
- "exchange_rate_at_purchase",
335
- "inventory_deducted_at",
336
- "invoice_number",
337
- "paid_at",
338
- "created_at",
339
- "coupon_id",
340
- "coupon_code",
341
- "discount_total",
342
- "discount_details"
343
- ],
344
- description: "Commerce orders.",
345
- primaryKey: ["id"]
346
- },
347
- package_activations: {
348
- columns: ["id", "license_key", "instance_name", "package_id", "status", "meta", "last_validated_at", "created_at"],
349
- description: "NextBlock package activations.",
350
- primaryKey: ["id"]
351
- },
352
- page_revisions: {
353
- columns: ["id", "page_id", "author_id", "version", "revision_type", "content", "created_at"],
354
- description: "Page revision history.",
355
- primaryKey: ["id"],
356
- // Revision history is an audit trail. The agent may read it, but letting it rewrite or
357
- // delete rows would let it erase the record of its own edits — and hand-written rows
358
- // would corrupt the snapshot/diff chain the restore path replays.
359
- readOnly: !0
360
- },
361
- pages: {
362
- columns: [
363
- "id",
364
- "language_id",
365
- "author_id",
366
- "title",
367
- "slug",
368
- "status",
369
- "meta_title",
370
- "meta_description",
371
- "feature_image_id",
372
- "version",
373
- "translation_group_id",
374
- "created_at",
375
- "updated_at"
376
- ],
377
- description: "CMS pages.",
378
- primaryKey: ["id"]
379
- },
380
- post_revisions: {
381
- columns: ["id", "post_id", "author_id", "version", "revision_type", "content", "created_at"],
382
- description: "Post revision history.",
383
- primaryKey: ["id"],
384
- // See page_revisions.
385
- readOnly: !0
386
- },
387
- product_revisions: {
388
- columns: ["id", "product_id", "author_id", "version", "revision_type", "content", "created_at"],
389
- description: "Product revision history.",
390
- primaryKey: ["id"],
391
- // See page_revisions.
392
- readOnly: !0
393
- },
394
- posts: {
395
- columns: [
396
- "id",
397
- "language_id",
398
- "author_id",
399
- "title",
400
- "slug",
401
- "label",
402
- "excerpt",
403
- "subtitle",
404
- "status",
405
- "published_at",
406
- "meta_title",
407
- "meta_description",
408
- "feature_image_id",
409
- "version",
410
- "translation_group_id",
411
- "created_at",
412
- "updated_at"
413
- ],
414
- description: "CMS posts/articles.",
415
- primaryKey: ["id"]
416
- },
417
- product_attribute_terms: {
418
- columns: ["id", "attribute_id", "value", "slug", "sort_order", "value_translations", "created_at", "updated_at"],
419
- description: "Product attribute terms.",
420
- primaryKey: ["id"]
421
- },
422
- product_attributes: {
423
- columns: ["id", "name", "slug", "name_translations", "created_at", "updated_at"],
424
- description: "Product attribute definitions.",
425
- primaryKey: ["id"]
426
- },
427
- product_media: {
428
- columns: ["product_id", "media_id", "sort_order"],
429
- description: "Product media join rows.",
430
- primaryKey: ["product_id", "media_id"]
431
- },
432
- product_variants: {
433
- columns: [
434
- "id",
435
- "product_id",
436
- "sku",
437
- "price_adjustment",
438
- "price",
439
- "prices",
440
- "sale_price",
441
- "sale_prices",
442
- "stock_quantity",
443
- "upc",
444
- "main_media_id",
445
- "created_at",
446
- "updated_at"
447
- ],
448
- description: "Sellable product variants.",
449
- primaryKey: ["id"]
450
- },
451
- products: {
452
- columns: [
453
- "id",
454
- "language_id",
455
- "translation_group_id",
456
- "sku",
457
- "title",
458
- "slug",
459
- "product_type",
460
- "payment_provider",
461
- "price",
462
- "prices",
463
- "sale_price",
464
- "sale_prices",
465
- "stock",
466
- "status",
467
- "meta_title",
468
- "meta_description",
469
- "short_description",
470
- "description_json",
471
- "metadata",
472
- "freemius_plan_id",
473
- "freemius_product_id",
474
- "trial_period_days",
475
- "trial_requires_payment_method",
476
- "upc",
477
- "is_taxable",
478
- "created_at",
479
- "updated_at"
480
- ],
481
- description: "Product catalog records.",
482
- primaryKey: ["id"]
483
- },
484
- profiles: {
485
- columns: ["id", "updated_at", "full_name", "avatar_url", "website", "phone", "role"],
486
- description: "Read-only user profiles. Never mutate through Cortex AI.",
487
- primaryKey: ["id"],
488
- readOnly: !0
489
- },
490
- shipping_zone_locations: {
491
- columns: ["id", "zone_id", "country_code", "state_code", "postal_code", "created_at"],
492
- description: "Shipping zone location match rules.",
493
- primaryKey: ["id"]
494
- },
495
- shipping_zone_methods: {
496
- columns: [
497
- "id",
498
- "zone_id",
499
- "method_type",
500
- "cost_amount",
501
- "cost_currency",
502
- "min_order_amount",
503
- "name",
504
- "name_translations",
505
- "currency_pricing_mode",
506
- "cost_amounts",
507
- "min_order_amounts",
508
- "created_at",
509
- "updated_at"
510
- ],
511
- description: "Shipping methods/rates.",
512
- primaryKey: ["id"]
513
- },
514
- shipping_zones: {
515
- columns: ["id", "name", "priority_order", "created_at", "updated_at"],
516
- description: "Shipping zones.",
517
- primaryKey: ["id"]
518
- },
519
- site_settings: {
520
- columns: ["key", "value"],
521
- description: "Global site settings. Cortex AI API-key setting row is protected.",
522
- primaryKey: ["key"]
523
- },
524
- tax_rates: {
525
- columns: ["id", "country_code", "state_code", "tax_name", "tax_rate", "created_at", "updated_at"],
526
- description: "Manual tax rates.",
527
- primaryKey: ["id"]
528
- },
529
- translations: {
530
- columns: ["key", "translations", "created_at", "updated_at"],
531
- description: "Shared translation strings.",
532
- primaryKey: ["key"]
533
- },
534
- user_addresses: {
535
- columns: [
536
- "id",
537
- "user_id",
538
- "address_type",
539
- "is_default",
540
- "recipient_name",
541
- "company_name",
542
- "line1",
543
- "line2",
544
- "city",
545
- "state",
546
- "postal_code",
547
- "country_code",
548
- "created_at",
549
- "updated_at"
550
- ],
551
- description: "Read-only user addresses. Never mutate through Cortex AI.",
552
- primaryKey: ["id"],
553
- readOnly: !0
554
- },
555
- variant_attribute_mapping: {
556
- columns: ["variant_id", "attribute_term_id"],
557
- description: "Variant to attribute-term join rows.",
558
- primaryKey: ["variant_id", "attribute_term_id"]
559
- }
560
- }, ne = o.enum(["eq", "neq", "gt", "gte", "lt", "lte", "ilike", "in", "is"]), q = o.strictObject({
561
- column: o.string().trim().min(1).max(120),
562
- operator: ne.default("eq"),
563
- value: o.unknown()
564
- }), se = o.strictObject({
565
- ascending: o.boolean().default(!0),
566
- column: o.string().trim().min(1).max(120)
567
- }), F = o.strictObject({
568
- includeReadOnly: o.boolean().default(!0),
569
- table: o.string().trim().min(1).max(120).optional()
570
- }), B = o.strictObject({
571
- columns: o.array(o.string().trim().min(1).max(120)).min(1).max(40).optional(),
572
- filters: o.array(q).max(12).default([]),
573
- limit: o.number().int().min(1).max(re).default(ae),
574
- offset: o.number().int().min(0).max(1e4).default(0),
575
- orderBy: se.optional(),
576
- table: o.string().trim().min(1).max(120)
577
- }), P = o.strictObject({
578
- filters: o.array(q).max(12).optional(),
579
- operation: o.enum(["delete", "insert", "update", "upsert"]),
580
- rows: o.array(o.record(o.string(), o.unknown())).min(1).max(C).optional(),
581
- summary: o.string().trim().min(1).max(500).optional(),
582
- table: o.string().trim().min(1).max(120),
583
- values: o.record(o.string(), o.unknown()).optional()
584
- }), z = o.strictObject({
585
- actions: o.array(P).min(1).max(8),
586
- summary: o.string().trim().min(1).max(500).optional()
100
+ var y = {
101
+ blocks: {
102
+ columns: [
103
+ "id",
104
+ "page_id",
105
+ "post_id",
106
+ "language_id",
107
+ "block_type",
108
+ "content",
109
+ "order",
110
+ "created_at",
111
+ "updated_at"
112
+ ],
113
+ description: "CMS page/post content blocks.",
114
+ primaryKey: ["id"]
115
+ },
116
+ coupon_freemius_mappings: {
117
+ columns: [
118
+ "id",
119
+ "coupon_id",
120
+ "product_id",
121
+ "freemius_product_id",
122
+ "freemius_coupon_id",
123
+ "freemius_coupon_code",
124
+ "sync_status",
125
+ "sync_error",
126
+ "remote_payload",
127
+ "last_synced_at",
128
+ "created_at",
129
+ "updated_at"
130
+ ],
131
+ description: "Freemius coupon sync mappings.",
132
+ primaryKey: ["id"]
133
+ },
134
+ coupon_products: {
135
+ columns: [
136
+ "coupon_id",
137
+ "product_id",
138
+ "created_at"
139
+ ],
140
+ description: "Coupon product allow-list rows.",
141
+ primaryKey: ["coupon_id", "product_id"]
142
+ },
143
+ coupon_redemptions: {
144
+ columns: [
145
+ "id",
146
+ "coupon_id",
147
+ "order_id",
148
+ "coupon_code",
149
+ "provider",
150
+ "discount_total",
151
+ "user_id",
152
+ "customer_email",
153
+ "metadata",
154
+ "redeemed_at"
155
+ ],
156
+ description: "Coupon redemption records.",
157
+ primaryKey: ["id"]
158
+ },
159
+ coupons: {
160
+ columns: [
161
+ "id",
162
+ "code",
163
+ "name",
164
+ "internal_note",
165
+ "provider_scope",
166
+ "discount_type",
167
+ "discount_amount",
168
+ "is_active",
169
+ "starts_at",
170
+ "ends_at",
171
+ "redemption_limit",
172
+ "redemptions_count",
173
+ "freemius_sync_status",
174
+ "freemius_sync_error",
175
+ "created_at",
176
+ "updated_at"
177
+ ],
178
+ description: "Commerce coupons.",
179
+ primaryKey: ["id"]
180
+ },
181
+ cortex_ai_db_mutation_audit: {
182
+ columns: [
183
+ "id",
184
+ "actor_user_id",
185
+ "tool_name",
186
+ "action_name",
187
+ "target_tables",
188
+ "operation_summary",
189
+ "payload_hash",
190
+ "payload",
191
+ "preview",
192
+ "status",
193
+ "error_message",
194
+ "created_at"
195
+ ],
196
+ description: "Read-only Cortex AI database mutation audit trail.",
197
+ primaryKey: ["id"],
198
+ readOnly: !0
199
+ },
200
+ currencies: {
201
+ columns: [
202
+ "id",
203
+ "code",
204
+ "symbol",
205
+ "exchange_rate",
206
+ "is_default",
207
+ "is_active",
208
+ "rounding_mode",
209
+ "rounding_increment",
210
+ "rounding_charm_amount",
211
+ "auto_update_exchange_rate",
212
+ "exchange_rate_updated_at",
213
+ "exchange_rate_source",
214
+ "auto_sync_product_prices",
215
+ "created_at",
216
+ "updated_at"
217
+ ],
218
+ description: "Storefront currencies and FX settings.",
219
+ primaryKey: ["id"]
220
+ },
221
+ freemius_plans: {
222
+ columns: [
223
+ "id",
224
+ "product_id",
225
+ "name",
226
+ "title",
227
+ "created_at",
228
+ "updated_at"
229
+ ],
230
+ description: "Freemius plan metadata.",
231
+ primaryKey: ["id"]
232
+ },
233
+ freemius_pricing: {
234
+ columns: [
235
+ "id",
236
+ "plan_id",
237
+ "api_monthly_price",
238
+ "api_annual_price",
239
+ "api_lifetime_price",
240
+ "override_monthly_price",
241
+ "override_annual_price",
242
+ "override_lifetime_price",
243
+ "license_quota",
244
+ "is_active",
245
+ "created_at",
246
+ "updated_at"
247
+ ],
248
+ description: "Freemius pricing metadata.",
249
+ primaryKey: ["id"]
250
+ },
251
+ inventory_items: {
252
+ columns: [
253
+ "sku",
254
+ "quantity",
255
+ "created_at",
256
+ "updated_at"
257
+ ],
258
+ description: "Source-of-truth inventory by SKU.",
259
+ primaryKey: ["sku"]
260
+ },
261
+ languages: {
262
+ columns: [
263
+ "id",
264
+ "code",
265
+ "name",
266
+ "is_default",
267
+ "is_active",
268
+ "created_at",
269
+ "updated_at"
270
+ ],
271
+ description: "CMS languages/locales.",
272
+ primaryKey: ["id"]
273
+ },
274
+ logos: {
275
+ columns: [
276
+ "id",
277
+ "name",
278
+ "media_id",
279
+ "created_at"
280
+ ],
281
+ description: "Brand logos.",
282
+ primaryKey: ["id"]
283
+ },
284
+ media: {
285
+ columns: [
286
+ "id",
287
+ "uploader_id",
288
+ "file_name",
289
+ "object_key",
290
+ "file_type",
291
+ "size_bytes",
292
+ "description",
293
+ "width",
294
+ "height",
295
+ "blur_data_url",
296
+ "variants",
297
+ "file_path",
298
+ "folder",
299
+ "created_at",
300
+ "updated_at"
301
+ ],
302
+ description: "Media metadata for uploaded assets.",
303
+ primaryKey: ["id"]
304
+ },
305
+ navigation_items: {
306
+ columns: [
307
+ "id",
308
+ "language_id",
309
+ "menu_key",
310
+ "label",
311
+ "url",
312
+ "parent_id",
313
+ "order",
314
+ "page_id",
315
+ "translation_group_id",
316
+ "created_at",
317
+ "updated_at"
318
+ ],
319
+ description: "CMS navigation tree items.",
320
+ primaryKey: ["id"]
321
+ },
322
+ order_items: {
323
+ columns: [
324
+ "id",
325
+ "order_id",
326
+ "product_id",
327
+ "variant_id",
328
+ "quantity",
329
+ "price_at_purchase"
330
+ ],
331
+ description: "Commerce order line items.",
332
+ primaryKey: ["id"]
333
+ },
334
+ orders: {
335
+ columns: /* @__PURE__ */ "id.user_id.status.total.stripe_session_id.payment_intent_id.customer_details.provider.freemius_product_id.freemius_plan_id.freemius_license_id.freemius_subscription_id.freemius_trial_id.freemius_user_id.freemius_trial_ends_at.freemius_last_event_type.freemius_last_synced_at.currency.subtotal.shipping_total.tax_total.tax_details.exchange_rate_at_purchase.inventory_deducted_at.invoice_number.paid_at.created_at.coupon_id.coupon_code.discount_total.discount_details".split("."),
336
+ description: "Commerce orders.",
337
+ primaryKey: ["id"]
338
+ },
339
+ package_activations: {
340
+ columns: [
341
+ "id",
342
+ "license_key",
343
+ "instance_name",
344
+ "package_id",
345
+ "status",
346
+ "meta",
347
+ "last_validated_at",
348
+ "created_at"
349
+ ],
350
+ description: "NextBlock package activations.",
351
+ primaryKey: ["id"]
352
+ },
353
+ page_revisions: {
354
+ columns: [
355
+ "id",
356
+ "page_id",
357
+ "author_id",
358
+ "version",
359
+ "revision_type",
360
+ "content",
361
+ "created_at"
362
+ ],
363
+ description: "Page revision history.",
364
+ primaryKey: ["id"],
365
+ readOnly: !0
366
+ },
367
+ pages: {
368
+ columns: [
369
+ "id",
370
+ "language_id",
371
+ "author_id",
372
+ "title",
373
+ "slug",
374
+ "status",
375
+ "meta_title",
376
+ "meta_description",
377
+ "feature_image_id",
378
+ "version",
379
+ "translation_group_id",
380
+ "created_at",
381
+ "updated_at"
382
+ ],
383
+ description: "CMS pages.",
384
+ primaryKey: ["id"]
385
+ },
386
+ post_revisions: {
387
+ columns: [
388
+ "id",
389
+ "post_id",
390
+ "author_id",
391
+ "version",
392
+ "revision_type",
393
+ "content",
394
+ "created_at"
395
+ ],
396
+ description: "Post revision history.",
397
+ primaryKey: ["id"],
398
+ readOnly: !0
399
+ },
400
+ product_revisions: {
401
+ columns: [
402
+ "id",
403
+ "product_id",
404
+ "author_id",
405
+ "version",
406
+ "revision_type",
407
+ "content",
408
+ "created_at"
409
+ ],
410
+ description: "Product revision history.",
411
+ primaryKey: ["id"],
412
+ readOnly: !0
413
+ },
414
+ posts: {
415
+ columns: [
416
+ "id",
417
+ "language_id",
418
+ "author_id",
419
+ "title",
420
+ "slug",
421
+ "label",
422
+ "excerpt",
423
+ "subtitle",
424
+ "status",
425
+ "published_at",
426
+ "meta_title",
427
+ "meta_description",
428
+ "feature_image_id",
429
+ "version",
430
+ "translation_group_id",
431
+ "created_at",
432
+ "updated_at"
433
+ ],
434
+ description: "CMS posts/articles.",
435
+ primaryKey: ["id"]
436
+ },
437
+ product_attribute_terms: {
438
+ columns: [
439
+ "id",
440
+ "attribute_id",
441
+ "value",
442
+ "slug",
443
+ "sort_order",
444
+ "value_translations",
445
+ "created_at",
446
+ "updated_at"
447
+ ],
448
+ description: "Product attribute terms.",
449
+ primaryKey: ["id"]
450
+ },
451
+ product_attributes: {
452
+ columns: [
453
+ "id",
454
+ "name",
455
+ "slug",
456
+ "name_translations",
457
+ "created_at",
458
+ "updated_at"
459
+ ],
460
+ description: "Product attribute definitions.",
461
+ primaryKey: ["id"]
462
+ },
463
+ product_media: {
464
+ columns: [
465
+ "product_id",
466
+ "media_id",
467
+ "sort_order"
468
+ ],
469
+ description: "Product media join rows.",
470
+ primaryKey: ["product_id", "media_id"]
471
+ },
472
+ product_variants: {
473
+ columns: [
474
+ "id",
475
+ "product_id",
476
+ "sku",
477
+ "price_adjustment",
478
+ "price",
479
+ "prices",
480
+ "sale_price",
481
+ "sale_prices",
482
+ "stock_quantity",
483
+ "upc",
484
+ "main_media_id",
485
+ "created_at",
486
+ "updated_at"
487
+ ],
488
+ description: "Sellable product variants.",
489
+ primaryKey: ["id"]
490
+ },
491
+ products: {
492
+ columns: /* @__PURE__ */ "id.language_id.translation_group_id.sku.title.slug.product_type.payment_provider.price.prices.sale_price.sale_prices.stock.status.meta_title.meta_description.short_description.description_json.metadata.freemius_plan_id.freemius_product_id.trial_period_days.trial_requires_payment_method.upc.is_taxable.created_at.updated_at".split("."),
493
+ description: "Product catalog records.",
494
+ primaryKey: ["id"]
495
+ },
496
+ profiles: {
497
+ columns: [
498
+ "id",
499
+ "updated_at",
500
+ "full_name",
501
+ "avatar_url",
502
+ "website",
503
+ "phone",
504
+ "role"
505
+ ],
506
+ description: "Read-only user profiles. Never mutate through Cortex AI.",
507
+ primaryKey: ["id"],
508
+ readOnly: !0
509
+ },
510
+ shipping_zone_locations: {
511
+ columns: [
512
+ "id",
513
+ "zone_id",
514
+ "country_code",
515
+ "state_code",
516
+ "postal_code",
517
+ "created_at"
518
+ ],
519
+ description: "Shipping zone location match rules.",
520
+ primaryKey: ["id"]
521
+ },
522
+ shipping_zone_methods: {
523
+ columns: [
524
+ "id",
525
+ "zone_id",
526
+ "method_type",
527
+ "cost_amount",
528
+ "cost_currency",
529
+ "min_order_amount",
530
+ "name",
531
+ "name_translations",
532
+ "currency_pricing_mode",
533
+ "cost_amounts",
534
+ "min_order_amounts",
535
+ "created_at",
536
+ "updated_at"
537
+ ],
538
+ description: "Shipping methods/rates.",
539
+ primaryKey: ["id"]
540
+ },
541
+ shipping_zones: {
542
+ columns: [
543
+ "id",
544
+ "name",
545
+ "priority_order",
546
+ "created_at",
547
+ "updated_at"
548
+ ],
549
+ description: "Shipping zones.",
550
+ primaryKey: ["id"]
551
+ },
552
+ site_settings: {
553
+ columns: ["key", "value"],
554
+ description: "Global site settings. Cortex AI API-key setting row is protected.",
555
+ primaryKey: ["key"]
556
+ },
557
+ tax_rates: {
558
+ columns: [
559
+ "id",
560
+ "country_code",
561
+ "state_code",
562
+ "tax_name",
563
+ "tax_rate",
564
+ "created_at",
565
+ "updated_at"
566
+ ],
567
+ description: "Manual tax rates.",
568
+ primaryKey: ["id"]
569
+ },
570
+ translations: {
571
+ columns: [
572
+ "key",
573
+ "translations",
574
+ "created_at",
575
+ "updated_at"
576
+ ],
577
+ description: "Shared translation strings.",
578
+ primaryKey: ["key"]
579
+ },
580
+ user_addresses: {
581
+ columns: [
582
+ "id",
583
+ "user_id",
584
+ "address_type",
585
+ "is_default",
586
+ "recipient_name",
587
+ "company_name",
588
+ "line1",
589
+ "line2",
590
+ "city",
591
+ "state",
592
+ "postal_code",
593
+ "country_code",
594
+ "created_at",
595
+ "updated_at"
596
+ ],
597
+ description: "Read-only user addresses. Never mutate through Cortex AI.",
598
+ primaryKey: ["id"],
599
+ readOnly: !0
600
+ },
601
+ variant_attribute_mapping: {
602
+ columns: ["variant_id", "attribute_term_id"],
603
+ description: "Variant to attribute-term join rows.",
604
+ primaryKey: ["variant_id", "attribute_term_id"]
605
+ }
606
+ }, b = e.enum([
607
+ "eq",
608
+ "neq",
609
+ "gt",
610
+ "gte",
611
+ "lt",
612
+ "lte",
613
+ "ilike",
614
+ "in",
615
+ "is"
616
+ ]), x = e.strictObject({
617
+ column: e.string().trim().min(1).max(120),
618
+ operator: b.default("eq"),
619
+ value: e.unknown()
620
+ }), S = e.strictObject({
621
+ ascending: e.boolean().default(!0),
622
+ column: e.string().trim().min(1).max(120)
623
+ }), C = e.strictObject({
624
+ includeReadOnly: e.boolean().default(!0),
625
+ table: e.string().trim().min(1).max(120).optional()
626
+ }), w = e.strictObject({
627
+ columns: e.array(e.string().trim().min(1).max(120)).min(1).max(40).optional(),
628
+ filters: e.array(x).max(12).default([]),
629
+ limit: e.number().int().min(1).max(s).default(c),
630
+ offset: e.number().int().min(0).max(1e4).default(0),
631
+ orderBy: S.optional(),
632
+ table: e.string().trim().min(1).max(120)
633
+ }), T = e.strictObject({
634
+ filters: e.array(x).max(12).optional(),
635
+ operation: e.enum([
636
+ "delete",
637
+ "insert",
638
+ "update",
639
+ "upsert"
640
+ ]),
641
+ rows: e.array(e.record(e.string(), e.unknown())).min(1).max(u).optional(),
642
+ summary: e.string().trim().min(1).max(500).optional(),
643
+ table: e.string().trim().min(1).max(120),
644
+ values: e.record(e.string(), e.unknown()).optional()
645
+ }), E = e.strictObject({
646
+ actions: e.array(T).min(1).max(8),
647
+ summary: e.string().trim().min(1).max(500).optional()
587
648
  });
588
- function g(e) {
589
- if (!e?.supabase)
590
- throw new Error("Cortex AI database tools require a Supabase client.");
591
- return e.supabase;
649
+ function D(e) {
650
+ if (!e?.supabase) throw Error("Cortex AI database tools require a Supabase client.");
651
+ return e.supabase;
592
652
  }
593
- function f(e) {
594
- return e ? typeof e == "object" && "message" in e ? String(e.message || "Unknown database error.") : String(e) : "Unknown database error.";
653
+ function O(e) {
654
+ return e ? typeof e == "object" && "message" in e ? String(e.message || "Unknown database error.") : String(e) : "Unknown database error.";
595
655
  }
596
- function $(e) {
597
- return e === null || typeof e != "object" ? JSON.stringify(e) : Array.isArray(e) ? `[${e.map((t) => $(t)).join(",")}]` : `{${Object.keys(e).sort().map((t) => `${JSON.stringify(t)}:${$(e[t])}`).join(",")}}`;
656
+ function k(e) {
657
+ return typeof e != "object" || !e ? JSON.stringify(e) : Array.isArray(e) ? `[${e.map((e) => k(e)).join(",")}]` : `{${Object.keys(e).sort().map((t) => `${JSON.stringify(t)}:${k(e[t])}`).join(",")}}`;
598
658
  }
599
- function U(e) {
600
- let t = 2166136261;
601
- const r = $(e);
602
- for (let a = 0; a < r.length; a++)
603
- t ^= r.charCodeAt(a), t = Math.imul(t, 16777619);
604
- return (t >>> 0).toString(16).padStart(8, "0");
659
+ function A(e) {
660
+ let t = 2166136261, n = k(e);
661
+ for (let e = 0; e < n.length; e++) t ^= n.charCodeAt(e), t = Math.imul(t, 16777619);
662
+ return (t >>> 0).toString(16).padStart(8, "0");
605
663
  }
606
- function T(e) {
607
- return e.replace(/\s+/g, " ").trim().toUpperCase();
664
+ function j(e) {
665
+ return e.replace(/\s+/g, " ").trim().toUpperCase();
608
666
  }
609
- function ce(e, t, r) {
610
- return `${T(`CONFIRM ${e} ${t}`)} #${U(r)}`;
667
+ function te(e, t, n) {
668
+ return `${j(`CONFIRM ${e} ${t}`)} #${A(n)}`;
611
669
  }
612
- function de(e) {
613
- return {
614
- confirmationPhrase: ce(e.action, e.subject, e.payload),
615
- mutationExecuted: !1,
616
- preview: e.preview,
617
- requiresConfirmation: !0,
618
- success: !0
619
- };
670
+ function M(e) {
671
+ return {
672
+ confirmationPhrase: te(e.action, e.subject, e.payload),
673
+ mutationExecuted: !1,
674
+ preview: e.preview,
675
+ requiresConfirmation: !0,
676
+ success: !0
677
+ };
620
678
  }
621
- function V(e) {
622
- if (e.context?.skipConfirmation)
623
- return null;
624
- const t = de(e), r = T(e.context?.latestUserMessage || ""), a = T(t.confirmationPhrase);
625
- return r && !r.includes(a) ? {
626
- ...t,
627
- message: "The database target changed or the confirmation did not match. Please review and confirm again."
628
- } : r.includes(a) ? null : t;
679
+ function N(e) {
680
+ if (e.context?.skipConfirmation) return null;
681
+ let t = M(e), n = j(e.context?.latestUserMessage || ""), r = j(t.confirmationPhrase);
682
+ return n && !n.includes(r) ? {
683
+ ...t,
684
+ message: "The database target changed or the confirmation did not match. Please review and confirm again."
685
+ } : n.includes(r) ? null : t;
629
686
  }
630
- function ue(e) {
631
- return Object.prototype.hasOwnProperty.call(O, e);
687
+ function P(e) {
688
+ return Object.prototype.hasOwnProperty.call(y, e);
632
689
  }
633
- function M(e) {
634
- const t = e.trim();
635
- if (t.includes(".") || t.toLowerCase().startsWith("auth"))
636
- throw new Error("Cortex AI cannot access auth schema tables.");
637
- if (!ue(t))
638
- throw new Error(`Table "${t}" is not available to Cortex AI database tools.`);
639
- return t;
690
+ function F(e) {
691
+ let t = e.trim();
692
+ if (t.includes(".") || t.toLowerCase().startsWith("auth")) throw Error("Cortex AI cannot access auth schema tables.");
693
+ if (!P(t)) throw Error(`Table "${t}" is not available to Cortex AI database tools.`);
694
+ return t;
640
695
  }
641
- function p(e) {
642
- return O[e];
696
+ function I(e) {
697
+ return y[e];
643
698
  }
644
- function v(e) {
645
- return /(?:password|token|secret|api[_-]?key|private[_-]?key|credential)/i.test(e);
699
+ function L(e) {
700
+ return /(?:password|token|secret|api[_-]?key|private[_-]?key|credential)/i.test(e);
646
701
  }
647
- function b(e, t) {
648
- if (!p(e).columns.includes(t))
649
- throw new Error(`Column "${t}" is not available on table "${e}".`);
650
- if (v(t))
651
- throw new Error(`Column "${t}" is protected and cannot be used through Cortex AI.`);
702
+ function R(e, t) {
703
+ if (!I(e).columns.includes(t)) throw Error(`Column "${t}" is not available on table "${e}".`);
704
+ if (L(t)) throw Error(`Column "${t}" is protected and cannot be used through Cortex AI.`);
652
705
  }
653
- function I(e, t = "payload") {
654
- if (Array.isArray(e)) {
655
- e.forEach((r, a) => I(r, `${t}[${a}]`));
656
- return;
657
- }
658
- if (!(!e || typeof e != "object"))
659
- for (const [r, a] of Object.entries(e)) {
660
- if (v(r))
661
- throw new Error(`Protected field "${t}.${r}" cannot be written through Cortex AI.`);
662
- I(a, `${t}.${r}`);
663
- }
706
+ function z(e, t = "payload") {
707
+ if (Array.isArray(e)) {
708
+ e.forEach((e, n) => z(e, `${t}[${n}]`));
709
+ return;
710
+ }
711
+ if (e && typeof e == "object") for (let [n, r] of Object.entries(e)) {
712
+ if (L(n)) throw Error(`Protected field "${t}.${n}" cannot be written through Cortex AI.`);
713
+ z(r, `${t}.${n}`);
714
+ }
664
715
  }
665
- function h(e) {
666
- if (Array.isArray(e))
667
- return e.map((r) => h(r));
668
- if (!e || typeof e != "object")
669
- return e;
670
- const t = {};
671
- for (const [r, a] of Object.entries(e))
672
- t[r] = v(r) ? D : h(a);
673
- return t;
716
+ function B(e) {
717
+ if (Array.isArray(e)) return e.map((e) => B(e));
718
+ if (!e || typeof e != "object") return e;
719
+ let t = {};
720
+ for (let [n, r] of Object.entries(e)) t[n] = L(n) ? d : B(r);
721
+ return t;
674
722
  }
675
- function le(e) {
676
- return e.map((t) => {
677
- if (t && typeof t == "object" && !Array.isArray(t)) {
678
- const r = t.key;
679
- if (typeof r == "string" && K.has(r))
680
- return { key: r, value: D };
681
- }
682
- return h(t);
683
- });
723
+ function V(e) {
724
+ return e.map((e) => {
725
+ if (e && typeof e == "object" && !Array.isArray(e)) {
726
+ let t = e.key;
727
+ if (typeof t == "string" && p.has(t)) return {
728
+ key: t,
729
+ value: d
730
+ };
731
+ }
732
+ return B(e);
733
+ });
684
734
  }
685
- function _e(e, t) {
686
- if (e !== "site_settings")
687
- return;
688
- const r = JSON.stringify(t).toLowerCase();
689
- for (const a of K)
690
- if (r.includes(a))
691
- throw new Error(`The "${a}" site setting is protected.`);
735
+ function H(e, t) {
736
+ if (e !== "site_settings") return;
737
+ let n = JSON.stringify(t).toLowerCase();
738
+ for (let e of p) if (n.includes(e)) throw Error(`The "${e}" site setting is protected.`);
692
739
  }
693
- function me(e, t) {
694
- switch (t.operator) {
695
- case "eq":
696
- return e.eq(t.column, t.value);
697
- case "neq":
698
- return e.neq(t.column, t.value);
699
- case "gt":
700
- return e.gt(t.column, t.value);
701
- case "gte":
702
- return e.gte(t.column, t.value);
703
- case "lt":
704
- return e.lt(t.column, t.value);
705
- case "lte":
706
- return e.lte(t.column, t.value);
707
- case "ilike":
708
- if (typeof t.value != "string")
709
- throw new Error(`Filter "${t.column}" with ilike requires a string value.`);
710
- return e.ilike(t.column, t.value);
711
- case "in":
712
- if (!Array.isArray(t.value))
713
- throw new Error(`Filter "${t.column}" with in requires an array value.`);
714
- return e.in(t.column, t.value);
715
- case "is":
716
- return e.is(t.column, t.value);
717
- }
740
+ function U(e, t) {
741
+ switch (t.operator) {
742
+ case "eq": return e.eq(t.column, t.value);
743
+ case "neq": return e.neq(t.column, t.value);
744
+ case "gt": return e.gt(t.column, t.value);
745
+ case "gte": return e.gte(t.column, t.value);
746
+ case "lt": return e.lt(t.column, t.value);
747
+ case "lte": return e.lte(t.column, t.value);
748
+ case "ilike":
749
+ if (typeof t.value != "string") throw Error(`Filter "${t.column}" with ilike requires a string value.`);
750
+ return e.ilike(t.column, t.value);
751
+ case "in":
752
+ if (!Array.isArray(t.value)) throw Error(`Filter "${t.column}" with in requires an array value.`);
753
+ return e.in(t.column, t.value);
754
+ case "is": return e.is(t.column, t.value);
755
+ }
718
756
  }
719
- function w(e, t, r) {
720
- let a = t;
721
- for (const n of r)
722
- b(e, n.column), a = me(a, n);
723
- return e === "site_settings" && (a = a.neq("key", N)), a;
757
+ function W(e, t, n) {
758
+ let r = t;
759
+ for (let t of n) R(e, t.column), r = U(r, t);
760
+ return e === "site_settings" && (r = r.neq("key", f)), r;
724
761
  }
725
- function pe(e, t) {
726
- const r = p(e), a = t?.length ? t : r.columns.filter((n) => !v(n));
727
- return a.forEach((n) => b(e, n)), a.join(",");
762
+ function ne(e, t) {
763
+ let n = I(e), r = t?.length ? t : n.columns.filter((e) => !L(e));
764
+ return r.forEach((t) => R(e, t)), r.join(",");
728
765
  }
729
766
  function G(e, t) {
730
- return t.map((r) => `${r}=${String(e[r] ?? "")}`).join("|");
767
+ return t.map((t) => `${t}=${String(e[t] ?? "")}`).join("|");
731
768
  }
732
- async function X(e, t, r) {
733
- const a = p(t);
734
- let n = e.from(t).select(a.primaryKey.join(",")).limit(x + 1);
735
- n = w(t, n, r);
736
- const { data: i, error: s } = await n;
737
- if (s)
738
- throw new Error(`Failed to preview database mutation: ${f(s)}`);
739
- const c = Array.isArray(i) ? i : [];
740
- if (c.length > x)
741
- throw new Error(`Refusing to mutate more than ${x} rows.`);
742
- return c;
769
+ async function K(e, t, n) {
770
+ let r = I(t), i = e.from(t).select(r.primaryKey.join(",")).limit(101);
771
+ i = W(t, i, n);
772
+ let { data: a, error: o } = await i;
773
+ if (o) throw Error(`Failed to preview database mutation: ${O(o)}`);
774
+ let s = Array.isArray(a) ? a : [];
775
+ if (s.length > l) throw Error(`Refusing to mutate more than ${l} rows.`);
776
+ return s;
743
777
  }
744
- function J(e) {
745
- const t = M(e.table), r = p(t), a = e.operation;
746
- if (r.readOnly)
747
- throw new Error(`Table "${t}" is read-only for Cortex AI.`);
748
- if (_e(t, e), (a === "update" || a === "delete") && (!e.filters || e.filters.length === 0))
749
- throw new Error(`${a} operations require at least one filter.`);
750
- if ((a === "insert" || a === "upsert") && (!e.rows || e.rows.length === 0))
751
- throw new Error(`${a} operations require rows.`);
752
- if (a === "update" && (!e.values || Object.keys(e.values).length === 0))
753
- throw new Error("update operations require values.");
754
- if (e.rows && e.rows.length > C)
755
- throw new Error(`Refusing to mutate more than ${C} input rows.`);
756
- const n = e.rows ?? (e.values ? [e.values] : []);
757
- for (const i of n) {
758
- I(i);
759
- for (const s of Object.keys(i))
760
- b(t, s);
761
- }
762
- for (const i of e.filters ?? [])
763
- b(t, i.column);
764
- return t;
778
+ function q(e) {
779
+ let t = F(e.table), n = I(t), r = e.operation;
780
+ if (n.readOnly) throw Error(`Table "${t}" is read-only for Cortex AI.`);
781
+ if (H(t, e), (r === "update" || r === "delete") && (!e.filters || e.filters.length === 0)) throw Error(`${r} operations require at least one filter.`);
782
+ if ((r === "insert" || r === "upsert") && (!e.rows || e.rows.length === 0)) throw Error(`${r} operations require rows.`);
783
+ if (r === "update" && (!e.values || Object.keys(e.values).length === 0)) throw Error("update operations require values.");
784
+ if (e.rows && e.rows.length > u) throw Error(`Refusing to mutate more than ${u} input rows.`);
785
+ let i = e.rows ?? (e.values ? [e.values] : []);
786
+ for (let e of i) {
787
+ z(e);
788
+ for (let n of Object.keys(e)) R(t, n);
789
+ }
790
+ for (let n of e.filters ?? []) R(t, n.column);
791
+ return t;
765
792
  }
766
- function W(e) {
767
- const { input: t, table: r, targetRows: a } = e, n = p(r), i = a.map((_) => G(_, n.primaryKey)).sort(), s = t.rows?.length ?? 0, c = t.operation === "insert" || t.operation === "upsert" ? s : a.length, u = t.summary || `${t.operation} ${c} ${c === 1 ? "row" : "rows"} in ${r}.`;
768
- return {
769
- affectedCount: c,
770
- operation: t.operation,
771
- sampleTargetIds: i.slice(0, 10),
772
- summary: u,
773
- table: r,
774
- targetIds: i
775
- };
793
+ function J(e) {
794
+ let { input: t, table: n, targetRows: r } = e, i = I(n), a = r.map((e) => G(e, i.primaryKey)).sort(), o = t.rows?.length ?? 0, s = t.operation === "insert" || t.operation === "upsert" ? o : r.length, c = t.summary || `${t.operation} ${s} ${s === 1 ? "row" : "rows"} in ${n}.`;
795
+ return {
796
+ affectedCount: s,
797
+ operation: t.operation,
798
+ sampleTargetIds: a.slice(0, 10),
799
+ summary: c,
800
+ table: n,
801
+ targetIds: a
802
+ };
776
803
  }
777
- async function E(e) {
778
- const t = e.context?.actorUserId;
779
- if (!t)
780
- return { auditError: "Missing actor user id.", auditLogged: !1 };
781
- try {
782
- const { error: r } = await g(e.context).from("cortex_ai_db_mutation_audit").insert({
783
- action_name: e.toolName,
784
- actor_user_id: t,
785
- error_message: e.errorMessage ?? null,
786
- operation_summary: e.summary,
787
- payload: h(e.input),
788
- payload_hash: U(e.input),
789
- preview: h(e.preview),
790
- status: e.status,
791
- target_tables: e.targetTables,
792
- tool_name: e.toolName
793
- });
794
- return r ? { auditError: f(r), auditLogged: !1 } : { auditLogged: !0 };
795
- } catch (r) {
796
- return { auditError: f(r), auditLogged: !1 };
797
- }
804
+ async function Y(e) {
805
+ let t = e.context?.actorUserId;
806
+ if (!t) return {
807
+ auditError: "Missing actor user id.",
808
+ auditLogged: !1
809
+ };
810
+ try {
811
+ let { error: n } = await D(e.context).from("cortex_ai_db_mutation_audit").insert({
812
+ action_name: e.toolName,
813
+ actor_user_id: t,
814
+ error_message: e.errorMessage ?? null,
815
+ operation_summary: e.summary,
816
+ payload: B(e.input),
817
+ payload_hash: A(e.input),
818
+ preview: B(e.preview),
819
+ status: e.status,
820
+ target_tables: e.targetTables,
821
+ tool_name: e.toolName
822
+ });
823
+ return n ? {
824
+ auditError: O(n),
825
+ auditLogged: !1
826
+ } : { auditLogged: !0 };
827
+ } catch (e) {
828
+ return {
829
+ auditError: O(e),
830
+ auditLogged: !1
831
+ };
832
+ }
798
833
  }
799
- async function ye(e, t, r) {
800
- const n = p(t).primaryKey.join(",");
801
- let i;
802
- e.operation === "insert" ? i = r.from(t).insert(e.rows).select(n) : e.operation === "upsert" ? i = r.from(t).upsert(e.rows).select(n) : e.operation === "update" ? (i = r.from(t).update(e.values), i = w(t, i, e.filters ?? []), i = i.select(n)) : (i = r.from(t).delete(), i = w(t, i, e.filters ?? []), i = i.select(n));
803
- const { data: s, error: c } = await i;
804
- if (c)
805
- throw new Error(f(c));
806
- return Array.isArray(s) ? s : [];
834
+ async function re(e, t, n) {
835
+ let r = I(t).primaryKey.join(","), i;
836
+ e.operation === "insert" ? i = n.from(t).insert(e.rows).select(r) : e.operation === "upsert" ? i = n.from(t).upsert(e.rows).select(r) : e.operation === "update" ? (i = n.from(t).update(e.values), i = W(t, i, e.filters ?? []), i = i.select(r)) : (i = n.from(t).delete(), i = W(t, i, e.filters ?? []), i = i.select(r));
837
+ let { data: a, error: o } = await i;
838
+ if (o) throw Error(O(o));
839
+ return Array.isArray(a) ? a : [];
807
840
  }
808
- async function fe(e) {
809
- const t = F.parse(e), a = (t.table ? [M(t.table)] : Object.keys(O)).filter((n) => t.includeReadOnly || !p(n).readOnly).map((n) => {
810
- const i = p(n);
811
- return {
812
- columns: i.columns.filter((s) => !v(s)),
813
- description: i.description,
814
- primaryKey: i.primaryKey,
815
- readOnly: !!i.readOnly,
816
- table: n
817
- };
818
- });
819
- return {
820
- safetyNotes: [
821
- "Use read_database_records for reads and execute_database_mutation/action_plan for writes.",
822
- "No auth schema access, no arbitrary SQL, no password/secret/API-key fields.",
823
- "profiles, user_addresses, and cortex_ai_db_mutation_audit are read-only.",
824
- `Protected site_settings keys (never readable or writable): ${[...K].sort().join(", ")}.`,
825
- `Write-protected site_settings keys (readable, never writable here): ${[...j].sort().join(", ")}.`,
826
- "blocks.content is validated against its block_type (built-in schema or custom block definition) before any insert, upsert, or update; prefer the typed content tools, which also normalize and record revisions."
827
- ],
828
- success: !0,
829
- tables: a
830
- };
841
+ async function X(e) {
842
+ let t = C.parse(e), n = (t.table ? [F(t.table)] : Object.keys(y)).filter((e) => t.includeReadOnly || !I(e).readOnly).map((e) => {
843
+ let t = I(e);
844
+ return {
845
+ columns: t.columns.filter((e) => !L(e)),
846
+ description: t.description,
847
+ primaryKey: t.primaryKey,
848
+ readOnly: !!t.readOnly,
849
+ table: e
850
+ };
851
+ });
852
+ return {
853
+ safetyNotes: [
854
+ "Use read_database_records for reads and execute_database_mutation/action_plan for writes.",
855
+ "No auth schema access, no arbitrary SQL, no password/secret/API-key fields.",
856
+ "profiles, user_addresses, and cortex_ai_db_mutation_audit are read-only.",
857
+ `Protected site_settings keys (never readable or writable): ${[...p].sort().join(", ")}.`,
858
+ `Write-protected site_settings keys (readable, never writable here): ${[...m].sort().join(", ")}.`,
859
+ "blocks.content is validated against its block_type (built-in schema or custom block definition) before any insert, upsert, or update; prefer the typed content tools, which also normalize and record revisions."
860
+ ],
861
+ success: !0,
862
+ tables: n
863
+ };
831
864
  }
832
- async function ge(e, t) {
833
- const r = B.parse(e), a = M(r.table), n = pe(a, r.columns);
834
- let i = g(t).from(a).select(n).range(r.offset, r.offset + r.limit - 1);
835
- i = w(a, i, r.filters), r.orderBy && (b(a, r.orderBy.column), i = i.order(r.orderBy.column, { ascending: r.orderBy.ascending }));
836
- const { data: s, error: c } = await i;
837
- if (c)
838
- throw new Error(`Failed to read database records: ${f(c)}`);
839
- const u = Array.isArray(s) ? s : [];
840
- return {
841
- columns: n.split(","),
842
- limit: r.limit,
843
- offset: r.offset,
844
- rows: le(u),
845
- success: !0,
846
- table: a
847
- };
865
+ async function Z(e, t) {
866
+ let n = w.parse(e), r = F(n.table), i = ne(r, n.columns), a = D(t).from(r).select(i).range(n.offset, n.offset + n.limit - 1);
867
+ a = W(r, a, n.filters), n.orderBy && (R(r, n.orderBy.column), a = a.order(n.orderBy.column, { ascending: n.orderBy.ascending }));
868
+ let { data: o, error: s } = await a;
869
+ if (s) throw Error(`Failed to read database records: ${O(s)}`);
870
+ let c = Array.isArray(o) ? o : [];
871
+ return {
872
+ columns: i.split(","),
873
+ limit: n.limit,
874
+ offset: n.offset,
875
+ rows: V(c),
876
+ success: !0,
877
+ table: r
878
+ };
848
879
  }
849
880
  async function Q(e, t) {
850
- const r = P.parse(e), a = J(r), n = g(t);
851
- await L(r, a, t);
852
- const i = r.operation === "update" || r.operation === "delete" ? await X(n, a, r.filters ?? []) : [], s = W({ input: r, table: a, targetRows: i }), c = {
853
- input: r,
854
- targetIds: s.targetIds
855
- }, u = V({
856
- action: `DATABASE ${r.operation}`,
857
- context: t,
858
- payload: c,
859
- preview: s,
860
- subject: a
861
- });
862
- if (u)
863
- return u;
864
- try {
865
- const _ = await ye(r, a, n), m = t?.skipAudit ? { auditLogged: !1 } : await E({
866
- context: t,
867
- input: c,
868
- preview: s,
869
- status: "success",
870
- summary: String(s.summary),
871
- targetTables: [a],
872
- toolName: "execute_database_mutation"
873
- });
874
- return {
875
- affectedCount: _.length || s.affectedCount,
876
- auditLogged: m.auditLogged,
877
- ...m.auditError ? { auditError: m.auditError } : {},
878
- mutationExecuted: !0,
879
- operation: r.operation,
880
- sampleTargetIds: _.map((d) => G(d, p(a).primaryKey)).slice(0, 10),
881
- success: !0,
882
- summary: s.summary,
883
- table: a
884
- };
885
- } catch (_) {
886
- const m = f(_), d = t?.skipAudit ? { auditLogged: !1 } : await E({
887
- context: t,
888
- errorMessage: m,
889
- input: c,
890
- preview: s,
891
- status: "failure",
892
- summary: String(s.summary),
893
- targetTables: [a],
894
- toolName: "execute_database_mutation"
895
- });
896
- return {
897
- auditLogged: d.auditLogged,
898
- ...d.auditError ? { auditError: d.auditError } : {},
899
- message: `Database mutation failed: ${m}`,
900
- mutationExecuted: !1,
901
- operation: r.operation,
902
- success: !1,
903
- table: a
904
- };
905
- }
881
+ let n = T.parse(e), r = q(n), i = D(t);
882
+ await v(n, r, t);
883
+ let a = J({
884
+ input: n,
885
+ table: r,
886
+ targetRows: n.operation === "update" || n.operation === "delete" ? await K(i, r, n.filters ?? []) : []
887
+ }), o = {
888
+ input: n,
889
+ targetIds: a.targetIds
890
+ }, s = N({
891
+ action: `DATABASE ${n.operation}`,
892
+ context: t,
893
+ payload: o,
894
+ preview: a,
895
+ subject: r
896
+ });
897
+ if (s) return s;
898
+ try {
899
+ let e = await re(n, r, i), s = t?.skipAudit ? { auditLogged: !1 } : await Y({
900
+ context: t,
901
+ input: o,
902
+ preview: a,
903
+ status: "success",
904
+ summary: String(a.summary),
905
+ targetTables: [r],
906
+ toolName: "execute_database_mutation"
907
+ });
908
+ return {
909
+ affectedCount: e.length || a.affectedCount,
910
+ auditLogged: s.auditLogged,
911
+ ...s.auditError ? { auditError: s.auditError } : {},
912
+ mutationExecuted: !0,
913
+ operation: n.operation,
914
+ sampleTargetIds: e.map((e) => G(e, I(r).primaryKey)).slice(0, 10),
915
+ success: !0,
916
+ summary: a.summary,
917
+ table: r
918
+ };
919
+ } catch (e) {
920
+ let i = O(e), s = t?.skipAudit ? { auditLogged: !1 } : await Y({
921
+ context: t,
922
+ errorMessage: i,
923
+ input: o,
924
+ preview: a,
925
+ status: "failure",
926
+ summary: String(a.summary),
927
+ targetTables: [r],
928
+ toolName: "execute_database_mutation"
929
+ });
930
+ return {
931
+ auditLogged: s.auditLogged,
932
+ ...s.auditError ? { auditError: s.auditError } : {},
933
+ message: `Database mutation failed: ${i}`,
934
+ mutationExecuted: !1,
935
+ operation: n.operation,
936
+ success: !1,
937
+ table: r
938
+ };
939
+ }
906
940
  }
907
- async function be(e, t) {
908
- const r = z.parse(e), a = [];
909
- for (const d of r.actions) {
910
- const y = J(d);
911
- await L(d, y, t);
912
- const l = d.operation === "update" || d.operation === "delete" ? await X(g(t), y, d.filters ?? []) : [];
913
- a.push({
914
- input: d,
915
- preview: W({ input: d, table: y, targetRows: l }),
916
- table: y
917
- });
918
- }
919
- const n = a.map(({ preview: d }) => String(d.summary)), i = {
920
- actionCount: a.length,
921
- actionSummaries: n,
922
- summary: r.summary || `Run ${a.length} confirmed database actions.`,
923
- tables: Array.from(new Set(a.map((d) => d.table)))
924
- }, s = a.map(({ input: d, preview: y, table: l }) => ({
925
- input: d,
926
- table: l,
927
- targetIds: y.targetIds
928
- })), c = V({
929
- action: "DATABASE ACTION PLAN",
930
- context: t,
931
- payload: s,
932
- preview: i,
933
- subject: `${a.length} actions`
934
- });
935
- if (c)
936
- return c;
937
- const u = [];
938
- let _ = !1;
939
- for (const [d, y] of a.entries()) {
940
- const l = await Q(y.input, {
941
- ...t,
942
- skipAudit: !0,
943
- skipConfirmation: !0
944
- });
945
- if (u.push(l), l && typeof l == "object" && l.mutationExecuted === !0 && (_ = !0), !l || typeof l != "object" || l.success === !1) {
946
- const S = await E({
947
- context: t,
948
- errorMessage: l && typeof l == "object" && typeof l.message == "string" ? l.message : `Database action ${d + 1} failed.`,
949
- input: s,
950
- preview: i,
951
- status: "failure",
952
- summary: String(i.summary),
953
- targetTables: i.tables,
954
- toolName: "execute_database_action_plan"
955
- });
956
- return {
957
- actionCount: a.length,
958
- auditLogged: S.auditLogged,
959
- ...S.auditError ? { auditError: S.auditError } : {},
960
- failedActionIndex: d,
961
- message: l && typeof l == "object" && typeof l.message == "string" ? l.message : `Database action ${d + 1} failed.`,
962
- mutationExecuted: _,
963
- results: u,
964
- success: !1
965
- };
966
- }
967
- }
968
- const m = await E({
969
- context: t,
970
- input: s,
971
- preview: i,
972
- status: "success",
973
- summary: String(i.summary),
974
- targetTables: i.tables,
975
- toolName: "execute_database_action_plan"
976
- });
977
- return {
978
- actionCount: a.length,
979
- auditLogged: m.auditLogged,
980
- ...m.auditError ? { auditError: m.auditError } : {},
981
- mutationExecuted: _,
982
- results: u,
983
- success: !0,
984
- summary: r.summary ?? null
985
- };
941
+ async function $(e, t) {
942
+ let n = E.parse(e), r = [];
943
+ for (let e of n.actions) {
944
+ let n = q(e);
945
+ await v(e, n, t);
946
+ let i = e.operation === "update" || e.operation === "delete" ? await K(D(t), n, e.filters ?? []) : [];
947
+ r.push({
948
+ input: e,
949
+ preview: J({
950
+ input: e,
951
+ table: n,
952
+ targetRows: i
953
+ }),
954
+ table: n
955
+ });
956
+ }
957
+ let i = r.map(({ preview: e }) => String(e.summary)), a = {
958
+ actionCount: r.length,
959
+ actionSummaries: i,
960
+ summary: n.summary || `Run ${r.length} confirmed database actions.`,
961
+ tables: Array.from(new Set(r.map((e) => e.table)))
962
+ }, o = r.map(({ input: e, preview: t, table: n }) => ({
963
+ input: e,
964
+ table: n,
965
+ targetIds: t.targetIds
966
+ })), s = N({
967
+ action: "DATABASE ACTION PLAN",
968
+ context: t,
969
+ payload: o,
970
+ preview: a,
971
+ subject: `${r.length} actions`
972
+ });
973
+ if (s) return s;
974
+ let c = [], l = !1;
975
+ for (let [e, n] of r.entries()) {
976
+ let i = await Q(n.input, {
977
+ ...t,
978
+ skipAudit: !0,
979
+ skipConfirmation: !0
980
+ });
981
+ if (c.push(i), i && typeof i == "object" && i.mutationExecuted === !0 && (l = !0), !i || typeof i != "object" || i.success === !1) {
982
+ let n = await Y({
983
+ context: t,
984
+ errorMessage: i && typeof i == "object" && typeof i.message == "string" ? i.message : `Database action ${e + 1} failed.`,
985
+ input: o,
986
+ preview: a,
987
+ status: "failure",
988
+ summary: String(a.summary),
989
+ targetTables: a.tables,
990
+ toolName: "execute_database_action_plan"
991
+ });
992
+ return {
993
+ actionCount: r.length,
994
+ auditLogged: n.auditLogged,
995
+ ...n.auditError ? { auditError: n.auditError } : {},
996
+ failedActionIndex: e,
997
+ message: i && typeof i == "object" && typeof i.message == "string" ? i.message : `Database action ${e + 1} failed.`,
998
+ mutationExecuted: l,
999
+ results: c,
1000
+ success: !1
1001
+ };
1002
+ }
1003
+ }
1004
+ let u = await Y({
1005
+ context: t,
1006
+ input: o,
1007
+ preview: a,
1008
+ status: "success",
1009
+ summary: String(a.summary),
1010
+ targetTables: a.tables,
1011
+ toolName: "execute_database_action_plan"
1012
+ });
1013
+ return {
1014
+ actionCount: r.length,
1015
+ auditLogged: u.auditLogged,
1016
+ ...u.auditError ? { auditError: u.auditError } : {},
1017
+ mutationExecuted: l,
1018
+ results: c,
1019
+ success: !0,
1020
+ summary: n.summary ?? null
1021
+ };
986
1022
  }
987
- function Ee(e) {
988
- return {
989
- describe_database_schema: k({
990
- description: "Describe the public database tables Cortex AI can read or mutate, including read-only tables, primary keys, and writable columns. Use before broad database tasks when unsure about schema.",
991
- execute: (t) => fe(t),
992
- inputSchema: F,
993
- strict: !0
994
- }),
995
- execute_database_action_plan: k({
996
- description: "Execute up to 8 typed database mutations as one confirmed plan. Mutating: first returns one combined confirmation preview and Confirm button; after confirmation, runs each action in order and stops on the first failure.",
997
- execute: (t) => be(t, e),
998
- inputSchema: z,
999
- strict: !0
1000
- }),
1001
- execute_database_mutation: k({
1002
- description: "Run one typed insert, update, upsert, or delete against an allowed public database table. Mutating: always previews affected rows and requires exact user confirmation before execution. Does not support arbitrary SQL.",
1003
- execute: (t) => Q(t, e),
1004
- inputSchema: P,
1005
- strict: !0
1006
- }),
1007
- read_database_records: k({
1008
- description: "Read records from an allowed public database table with validated columns, filters, ordering, limit, and offset. Read-only and redacts protected secret-like values.",
1009
- execute: (t) => ge(t, e),
1010
- inputSchema: B,
1011
- strict: !0
1012
- })
1013
- };
1023
+ function ie(e) {
1024
+ return {
1025
+ describe_database_schema: o({
1026
+ description: "Describe the public database tables Cortex AI can read or mutate, including read-only tables, primary keys, and writable columns. Use before broad database tasks when unsure about schema.",
1027
+ execute: (e) => X(e),
1028
+ inputSchema: C,
1029
+ strict: !0
1030
+ }),
1031
+ execute_database_action_plan: o({
1032
+ description: "Execute up to 8 typed database mutations as one confirmed plan. Mutating: first returns one combined confirmation preview and Confirm button; after confirmation, runs each action in order and stops on the first failure.",
1033
+ execute: (t) => $(t, e),
1034
+ inputSchema: E,
1035
+ strict: !0
1036
+ }),
1037
+ execute_database_mutation: o({
1038
+ description: "Run one typed insert, update, upsert, or delete against an allowed public database table. Mutating: always previews affected rows and requires exact user confirmation before execution. Does not support arbitrary SQL.",
1039
+ execute: (t) => Q(t, e),
1040
+ inputSchema: T,
1041
+ strict: !0
1042
+ }),
1043
+ read_database_records: o({
1044
+ description: "Read records from an allowed public database table with validated columns, filters, ordering, limit, and offset. Read-only and redacts protected secret-like values.",
1045
+ execute: (t) => Z(t, e),
1046
+ inputSchema: w,
1047
+ strict: !0
1048
+ })
1049
+ };
1014
1050
  }
1015
- export {
1016
- Ee as createCortexDatabaseAgentTools,
1017
- F as describeDatabaseSchemaInputSchema,
1018
- be as executeDatabaseActionPlan,
1019
- z as executeDatabaseActionPlanInputSchema,
1020
- Q as executeDatabaseMutation,
1021
- P as executeDatabaseMutationInputSchema,
1022
- fe as executeDescribeDatabaseSchema,
1023
- ge as executeReadDatabaseRecords,
1024
- B as readDatabaseRecordsInputSchema
1025
- };
1051
+ //#endregion
1052
+ export { ie as createCortexDatabaseAgentTools, C as describeDatabaseSchemaInputSchema, $ as executeDatabaseActionPlan, E as executeDatabaseActionPlanInputSchema, Q as executeDatabaseMutation, T as executeDatabaseMutationInputSchema, X as executeDescribeDatabaseSchema, Z as executeReadDatabaseRecords, w as readDatabaseRecordsInputSchema };