@nextblock-cms/cortex 0.17.7 → 0.17.8

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.
@@ -1,14 +1,125 @@
1
- import { tool as w } from "ai";
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";
2
4
  import "./zod-config.es.js";
3
- import { z as n } from "zod";
4
- const G = 100, J = 20, A = 100, k = 20, P = "[REDACTED]", M = "cortex_ai_openrouter_api_key", T = /* @__PURE__ */ new Set([
5
- M,
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,
6
8
  "bot_protection_secret",
7
9
  "cortex_ai_pexels_api_key",
8
10
  "cortex_ai_unsplash_access_key",
9
11
  "email_secret",
10
12
  "payment_secret"
11
- ]), I = {
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)
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("; ");
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)}`);
44
+ }
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("; ")}`);
66
+ }
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
+ }
121
+ }
122
+ const O = {
12
123
  blocks: {
13
124
  columns: ["id", "page_id", "post_id", "language_id", "block_type", "content", "order", "created_at", "updated_at"],
14
125
  description: "CMS page/post content blocks.",
@@ -446,35 +557,35 @@ const G = 100, J = 20, A = 100, k = 20, P = "[REDACTED]", M = "cortex_ai_openrou
446
557
  description: "Variant to attribute-term join rows.",
447
558
  primaryKey: ["variant_id", "attribute_term_id"]
448
559
  }
449
- }, Q = n.enum(["eq", "neq", "gt", "gte", "lt", "lte", "ilike", "in", "is"]), R = n.strictObject({
450
- column: n.string().trim().min(1).max(120),
451
- operator: Q.default("eq"),
452
- value: n.unknown()
453
- }), W = n.strictObject({
454
- ascending: n.boolean().default(!0),
455
- column: n.string().trim().min(1).max(120)
456
- }), D = n.strictObject({
457
- includeReadOnly: n.boolean().default(!0),
458
- table: n.string().trim().min(1).max(120).optional()
459
- }), N = n.strictObject({
460
- columns: n.array(n.string().trim().min(1).max(120)).min(1).max(40).optional(),
461
- filters: n.array(R).max(12).default([]),
462
- limit: n.number().int().min(1).max(G).default(J),
463
- offset: n.number().int().min(0).max(1e4).default(0),
464
- orderBy: W.optional(),
465
- table: n.string().trim().min(1).max(120)
466
- }), O = n.strictObject({
467
- filters: n.array(R).max(12).optional(),
468
- operation: n.enum(["delete", "insert", "update", "upsert"]),
469
- rows: n.array(n.record(n.string(), n.unknown())).min(1).max(k).optional(),
470
- summary: n.string().trim().min(1).max(500).optional(),
471
- table: n.string().trim().min(1).max(120),
472
- values: n.record(n.string(), n.unknown()).optional()
473
- }), L = n.strictObject({
474
- actions: n.array(O).min(1).max(8),
475
- summary: n.string().trim().min(1).max(500).optional()
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()
476
587
  });
477
- function E(e) {
588
+ function g(e) {
478
589
  if (!e?.supabase)
479
590
  throw new Error("Cortex AI database tools require a Supabase client.");
480
591
  return e.supabase;
@@ -482,104 +593,104 @@ function E(e) {
482
593
  function f(e) {
483
594
  return e ? typeof e == "object" && "message" in e ? String(e.message || "Unknown database error.") : String(e) : "Unknown database error.";
484
595
  }
485
- function C(e) {
486
- return e === null || typeof e != "object" ? JSON.stringify(e) : Array.isArray(e) ? `[${e.map((t) => C(t)).join(",")}]` : `{${Object.keys(e).sort().map((t) => `${JSON.stringify(t)}:${C(e[t])}`).join(",")}}`;
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(",")}}`;
487
598
  }
488
- function q(e) {
599
+ function U(e) {
489
600
  let t = 2166136261;
490
- const r = C(e);
601
+ const r = $(e);
491
602
  for (let a = 0; a < r.length; a++)
492
603
  t ^= r.charCodeAt(a), t = Math.imul(t, 16777619);
493
604
  return (t >>> 0).toString(16).padStart(8, "0");
494
605
  }
495
- function K(e) {
606
+ function T(e) {
496
607
  return e.replace(/\s+/g, " ").trim().toUpperCase();
497
608
  }
498
- function Y(e, t, r) {
499
- return `${K(`CONFIRM ${e} ${t}`)} #${q(r)}`;
609
+ function ce(e, t, r) {
610
+ return `${T(`CONFIRM ${e} ${t}`)} #${U(r)}`;
500
611
  }
501
- function H(e) {
612
+ function de(e) {
502
613
  return {
503
- confirmationPhrase: Y(e.action, e.subject, e.payload),
614
+ confirmationPhrase: ce(e.action, e.subject, e.payload),
504
615
  mutationExecuted: !1,
505
616
  preview: e.preview,
506
617
  requiresConfirmation: !0,
507
618
  success: !0
508
619
  };
509
620
  }
510
- function z(e) {
621
+ function V(e) {
511
622
  if (e.context?.skipConfirmation)
512
623
  return null;
513
- const t = H(e), r = K(e.context?.latestUserMessage || ""), a = K(t.confirmationPhrase);
624
+ const t = de(e), r = T(e.context?.latestUserMessage || ""), a = T(t.confirmationPhrase);
514
625
  return r && !r.includes(a) ? {
515
626
  ...t,
516
627
  message: "The database target changed or the confirmation did not match. Please review and confirm again."
517
628
  } : r.includes(a) ? null : t;
518
629
  }
519
- function Z(e) {
520
- return Object.prototype.hasOwnProperty.call(I, e);
630
+ function ue(e) {
631
+ return Object.prototype.hasOwnProperty.call(O, e);
521
632
  }
522
- function j(e) {
633
+ function M(e) {
523
634
  const t = e.trim();
524
635
  if (t.includes(".") || t.toLowerCase().startsWith("auth"))
525
636
  throw new Error("Cortex AI cannot access auth schema tables.");
526
- if (!Z(t))
637
+ if (!ue(t))
527
638
  throw new Error(`Table "${t}" is not available to Cortex AI database tools.`);
528
639
  return t;
529
640
  }
530
- function _(e) {
531
- return I[e];
641
+ function p(e) {
642
+ return O[e];
532
643
  }
533
- function h(e) {
644
+ function v(e) {
534
645
  return /(?:password|token|secret|api[_-]?key|private[_-]?key|credential)/i.test(e);
535
646
  }
536
- function g(e, t) {
537
- if (!_(e).columns.includes(t))
647
+ function b(e, t) {
648
+ if (!p(e).columns.includes(t))
538
649
  throw new Error(`Column "${t}" is not available on table "${e}".`);
539
- if (h(t))
650
+ if (v(t))
540
651
  throw new Error(`Column "${t}" is protected and cannot be used through Cortex AI.`);
541
652
  }
542
- function $(e, t = "payload") {
653
+ function I(e, t = "payload") {
543
654
  if (Array.isArray(e)) {
544
- e.forEach((r, a) => $(r, `${t}[${a}]`));
655
+ e.forEach((r, a) => I(r, `${t}[${a}]`));
545
656
  return;
546
657
  }
547
658
  if (!(!e || typeof e != "object"))
548
659
  for (const [r, a] of Object.entries(e)) {
549
- if (h(r))
660
+ if (v(r))
550
661
  throw new Error(`Protected field "${t}.${r}" cannot be written through Cortex AI.`);
551
- $(a, `${t}.${r}`);
662
+ I(a, `${t}.${r}`);
552
663
  }
553
664
  }
554
- function b(e) {
665
+ function h(e) {
555
666
  if (Array.isArray(e))
556
- return e.map((r) => b(r));
667
+ return e.map((r) => h(r));
557
668
  if (!e || typeof e != "object")
558
669
  return e;
559
670
  const t = {};
560
671
  for (const [r, a] of Object.entries(e))
561
- t[r] = h(r) ? P : b(a);
672
+ t[r] = v(r) ? D : h(a);
562
673
  return t;
563
674
  }
564
- function ee(e) {
675
+ function le(e) {
565
676
  return e.map((t) => {
566
677
  if (t && typeof t == "object" && !Array.isArray(t)) {
567
678
  const r = t.key;
568
- if (typeof r == "string" && T.has(r))
569
- return { key: r, value: P };
679
+ if (typeof r == "string" && K.has(r))
680
+ return { key: r, value: D };
570
681
  }
571
- return b(t);
682
+ return h(t);
572
683
  });
573
684
  }
574
- function te(e, t) {
685
+ function _e(e, t) {
575
686
  if (e !== "site_settings")
576
687
  return;
577
688
  const r = JSON.stringify(t).toLowerCase();
578
- for (const a of T)
689
+ for (const a of K)
579
690
  if (r.includes(a))
580
691
  throw new Error(`The "${a}" site setting is protected.`);
581
692
  }
582
- function re(e, t) {
693
+ function me(e, t) {
583
694
  switch (t.operator) {
584
695
  case "eq":
585
696
  return e.eq(t.column, t.value);
@@ -605,77 +716,77 @@ function re(e, t) {
605
716
  return e.is(t.column, t.value);
606
717
  }
607
718
  }
608
- function v(e, t, r) {
719
+ function w(e, t, r) {
609
720
  let a = t;
610
- for (const o of r)
611
- g(e, o.column), a = re(a, o);
612
- return e === "site_settings" && (a = a.neq("key", M)), a;
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;
613
724
  }
614
- function ae(e, t) {
615
- const r = _(e), a = t?.length ? t : r.columns.filter((o) => !h(o));
616
- return a.forEach((o) => g(e, o)), a.join(",");
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(",");
617
728
  }
618
- function F(e, t) {
729
+ function G(e, t) {
619
730
  return t.map((r) => `${r}=${String(e[r] ?? "")}`).join("|");
620
731
  }
621
- async function U(e, t, r) {
622
- const a = _(t);
623
- let o = e.from(t).select(a.primaryKey.join(",")).limit(A + 1);
624
- o = v(t, o, r);
625
- const { data: i, error: s } = await o;
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;
626
737
  if (s)
627
738
  throw new Error(`Failed to preview database mutation: ${f(s)}`);
628
- const d = Array.isArray(i) ? i : [];
629
- if (d.length > A)
630
- throw new Error(`Refusing to mutate more than ${A} rows.`);
631
- return d;
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;
632
743
  }
633
- function B(e) {
634
- const t = j(e.table), r = _(t), a = e.operation;
744
+ function J(e) {
745
+ const t = M(e.table), r = p(t), a = e.operation;
635
746
  if (r.readOnly)
636
747
  throw new Error(`Table "${t}" is read-only for Cortex AI.`);
637
- if (te(t, e), (a === "update" || a === "delete") && (!e.filters || e.filters.length === 0))
748
+ if (_e(t, e), (a === "update" || a === "delete") && (!e.filters || e.filters.length === 0))
638
749
  throw new Error(`${a} operations require at least one filter.`);
639
750
  if ((a === "insert" || a === "upsert") && (!e.rows || e.rows.length === 0))
640
751
  throw new Error(`${a} operations require rows.`);
641
752
  if (a === "update" && (!e.values || Object.keys(e.values).length === 0))
642
753
  throw new Error("update operations require values.");
643
- if (e.rows && e.rows.length > k)
644
- throw new Error(`Refusing to mutate more than ${k} input rows.`);
645
- const o = e.rows ?? (e.values ? [e.values] : []);
646
- for (const i of o) {
647
- $(i);
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);
648
759
  for (const s of Object.keys(i))
649
- g(t, s);
760
+ b(t, s);
650
761
  }
651
762
  for (const i of e.filters ?? [])
652
- g(t, i.column);
763
+ b(t, i.column);
653
764
  return t;
654
765
  }
655
- function X(e) {
656
- const { input: t, table: r, targetRows: a } = e, o = _(r), i = a.map((p) => F(p, o.primaryKey)).sort(), s = t.rows?.length ?? 0, d = t.operation === "insert" || t.operation === "upsert" ? s : a.length, l = t.summary || `${t.operation} ${d} ${d === 1 ? "row" : "rows"} in ${r}.`;
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}.`;
657
768
  return {
658
- affectedCount: d,
769
+ affectedCount: c,
659
770
  operation: t.operation,
660
771
  sampleTargetIds: i.slice(0, 10),
661
- summary: l,
772
+ summary: u,
662
773
  table: r,
663
774
  targetIds: i
664
775
  };
665
776
  }
666
- async function x(e) {
777
+ async function E(e) {
667
778
  const t = e.context?.actorUserId;
668
779
  if (!t)
669
780
  return { auditError: "Missing actor user id.", auditLogged: !1 };
670
781
  try {
671
- const { error: r } = await E(e.context).from("cortex_ai_db_mutation_audit").insert({
782
+ const { error: r } = await g(e.context).from("cortex_ai_db_mutation_audit").insert({
672
783
  action_name: e.toolName,
673
784
  actor_user_id: t,
674
785
  error_message: e.errorMessage ?? null,
675
786
  operation_summary: e.summary,
676
- payload: b(e.input),
677
- payload_hash: q(e.input),
678
- preview: b(e.preview),
787
+ payload: h(e.input),
788
+ payload_hash: U(e.input),
789
+ preview: h(e.preview),
679
790
  status: e.status,
680
791
  target_tables: e.targetTables,
681
792
  tool_name: e.toolName
@@ -685,24 +796,24 @@ async function x(e) {
685
796
  return { auditError: f(r), auditLogged: !1 };
686
797
  }
687
798
  }
688
- async function ie(e, t, r) {
689
- const o = _(t).primaryKey.join(",");
799
+ async function ye(e, t, r) {
800
+ const n = p(t).primaryKey.join(",");
690
801
  let i;
691
- e.operation === "insert" ? i = r.from(t).insert(e.rows).select(o) : e.operation === "upsert" ? i = r.from(t).upsert(e.rows).select(o) : e.operation === "update" ? (i = r.from(t).update(e.values), i = v(t, i, e.filters ?? []), i = i.select(o)) : (i = r.from(t).delete(), i = v(t, i, e.filters ?? []), i = i.select(o));
692
- const { data: s, error: d } = await i;
693
- if (d)
694
- throw new Error(f(d));
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));
695
806
  return Array.isArray(s) ? s : [];
696
807
  }
697
- async function oe(e) {
698
- const t = D.parse(e), a = (t.table ? [j(t.table)] : Object.keys(I)).filter((o) => t.includeReadOnly || !_(o).readOnly).map((o) => {
699
- const i = _(o);
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);
700
811
  return {
701
- columns: i.columns.filter((s) => !h(s)),
812
+ columns: i.columns.filter((s) => !v(s)),
702
813
  description: i.description,
703
814
  primaryKey: i.primaryKey,
704
815
  readOnly: !!i.readOnly,
705
- table: o
816
+ table: n
706
817
  };
707
818
  });
708
819
  return {
@@ -710,46 +821,50 @@ async function oe(e) {
710
821
  "Use read_database_records for reads and execute_database_mutation/action_plan for writes.",
711
822
  "No auth schema access, no arbitrary SQL, no password/secret/API-key fields.",
712
823
  "profiles, user_addresses, and cortex_ai_db_mutation_audit are read-only.",
713
- `Protected site_settings keys (never readable or writable): ${[...T].sort().join(", ")}.`
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."
714
827
  ],
715
828
  success: !0,
716
829
  tables: a
717
830
  };
718
831
  }
719
- async function ne(e, t) {
720
- const r = N.parse(e), a = j(r.table), o = ae(a, r.columns);
721
- let i = E(t).from(a).select(o).range(r.offset, r.offset + r.limit - 1);
722
- i = v(a, i, r.filters), r.orderBy && (g(a, r.orderBy.column), i = i.order(r.orderBy.column, { ascending: r.orderBy.ascending }));
723
- const { data: s, error: d } = await i;
724
- if (d)
725
- throw new Error(`Failed to read database records: ${f(d)}`);
726
- const l = Array.isArray(s) ? s : [];
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 : [];
727
840
  return {
728
- columns: o.split(","),
841
+ columns: n.split(","),
729
842
  limit: r.limit,
730
843
  offset: r.offset,
731
- rows: ee(l),
844
+ rows: le(u),
732
845
  success: !0,
733
846
  table: a
734
847
  };
735
848
  }
736
- async function V(e, t) {
737
- const r = O.parse(e), a = B(r), o = E(t), i = r.operation === "update" || r.operation === "delete" ? await U(o, a, r.filters ?? []) : [], s = X({ input: r, table: a, targetRows: i }), d = {
849
+ 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 = {
738
853
  input: r,
739
854
  targetIds: s.targetIds
740
- }, l = z({
855
+ }, u = V({
741
856
  action: `DATABASE ${r.operation}`,
742
857
  context: t,
743
- payload: d,
858
+ payload: c,
744
859
  preview: s,
745
860
  subject: a
746
861
  });
747
- if (l)
748
- return l;
862
+ if (u)
863
+ return u;
749
864
  try {
750
- const p = await ie(r, a, o), m = t?.skipAudit ? { auditLogged: !1 } : await x({
865
+ const _ = await ye(r, a, n), m = t?.skipAudit ? { auditLogged: !1 } : await E({
751
866
  context: t,
752
- input: d,
867
+ input: c,
753
868
  preview: s,
754
869
  status: "success",
755
870
  summary: String(s.summary),
@@ -757,21 +872,21 @@ async function V(e, t) {
757
872
  toolName: "execute_database_mutation"
758
873
  });
759
874
  return {
760
- affectedCount: p.length || s.affectedCount,
875
+ affectedCount: _.length || s.affectedCount,
761
876
  auditLogged: m.auditLogged,
762
877
  ...m.auditError ? { auditError: m.auditError } : {},
763
878
  mutationExecuted: !0,
764
879
  operation: r.operation,
765
- sampleTargetIds: p.map((c) => F(c, _(a).primaryKey)).slice(0, 10),
880
+ sampleTargetIds: _.map((d) => G(d, p(a).primaryKey)).slice(0, 10),
766
881
  success: !0,
767
882
  summary: s.summary,
768
883
  table: a
769
884
  };
770
- } catch (p) {
771
- const m = f(p), c = t?.skipAudit ? { auditLogged: !1 } : await x({
885
+ } catch (_) {
886
+ const m = f(_), d = t?.skipAudit ? { auditLogged: !1 } : await E({
772
887
  context: t,
773
888
  errorMessage: m,
774
- input: d,
889
+ input: c,
775
890
  preview: s,
776
891
  status: "failure",
777
892
  summary: String(s.summary),
@@ -779,8 +894,8 @@ async function V(e, t) {
779
894
  toolName: "execute_database_mutation"
780
895
  });
781
896
  return {
782
- auditLogged: c.auditLogged,
783
- ...c.auditError ? { auditError: c.auditError } : {},
897
+ auditLogged: d.auditLogged,
898
+ ...d.auditError ? { auditError: d.auditError } : {},
784
899
  message: `Database mutation failed: ${m}`,
785
900
  mutationExecuted: !1,
786
901
  operation: r.operation,
@@ -789,46 +904,48 @@ async function V(e, t) {
789
904
  };
790
905
  }
791
906
  }
792
- async function se(e, t) {
793
- const r = L.parse(e), a = [];
794
- for (const c of r.actions) {
795
- const y = B(c), u = c.operation === "update" || c.operation === "delete" ? await U(E(t), y, c.filters ?? []) : [];
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 ?? []) : [];
796
913
  a.push({
797
- input: c,
798
- preview: X({ input: c, table: y, targetRows: u }),
914
+ input: d,
915
+ preview: W({ input: d, table: y, targetRows: l }),
799
916
  table: y
800
917
  });
801
918
  }
802
- const o = a.map(({ preview: c }) => String(c.summary)), i = {
919
+ const n = a.map(({ preview: d }) => String(d.summary)), i = {
803
920
  actionCount: a.length,
804
- actionSummaries: o,
921
+ actionSummaries: n,
805
922
  summary: r.summary || `Run ${a.length} confirmed database actions.`,
806
- tables: Array.from(new Set(a.map((c) => c.table)))
807
- }, s = a.map(({ input: c, preview: y, table: u }) => ({
808
- input: c,
809
- table: u,
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,
810
927
  targetIds: y.targetIds
811
- })), d = z({
928
+ })), c = V({
812
929
  action: "DATABASE ACTION PLAN",
813
930
  context: t,
814
931
  payload: s,
815
932
  preview: i,
816
933
  subject: `${a.length} actions`
817
934
  });
818
- if (d)
819
- return d;
820
- const l = [];
821
- let p = !1;
822
- for (const [c, y] of a.entries()) {
823
- const u = await V(y.input, {
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, {
824
941
  ...t,
825
942
  skipAudit: !0,
826
943
  skipConfirmation: !0
827
944
  });
828
- if (l.push(u), u && typeof u == "object" && u.mutationExecuted === !0 && (p = !0), !u || typeof u != "object" || u.success === !1) {
829
- const S = await x({
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({
830
947
  context: t,
831
- errorMessage: u && typeof u == "object" && typeof u.message == "string" ? u.message : `Database action ${c + 1} failed.`,
948
+ errorMessage: l && typeof l == "object" && typeof l.message == "string" ? l.message : `Database action ${d + 1} failed.`,
832
949
  input: s,
833
950
  preview: i,
834
951
  status: "failure",
@@ -840,15 +957,15 @@ async function se(e, t) {
840
957
  actionCount: a.length,
841
958
  auditLogged: S.auditLogged,
842
959
  ...S.auditError ? { auditError: S.auditError } : {},
843
- failedActionIndex: c,
844
- message: u && typeof u == "object" && typeof u.message == "string" ? u.message : `Database action ${c + 1} failed.`,
845
- mutationExecuted: p,
846
- results: l,
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,
847
964
  success: !1
848
965
  };
849
966
  }
850
967
  }
851
- const m = await x({
968
+ const m = await E({
852
969
  context: t,
853
970
  input: s,
854
971
  preview: i,
@@ -861,48 +978,48 @@ async function se(e, t) {
861
978
  actionCount: a.length,
862
979
  auditLogged: m.auditLogged,
863
980
  ...m.auditError ? { auditError: m.auditError } : {},
864
- mutationExecuted: p,
865
- results: l,
981
+ mutationExecuted: _,
982
+ results: u,
866
983
  success: !0,
867
984
  summary: r.summary ?? null
868
985
  };
869
986
  }
870
- function le(e) {
987
+ function Ee(e) {
871
988
  return {
872
- describe_database_schema: w({
989
+ describe_database_schema: k({
873
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.",
874
- execute: (t) => oe(t),
875
- inputSchema: D,
991
+ execute: (t) => fe(t),
992
+ inputSchema: F,
876
993
  strict: !0
877
994
  }),
878
- execute_database_action_plan: w({
995
+ execute_database_action_plan: k({
879
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.",
880
- execute: (t) => se(t, e),
881
- inputSchema: L,
997
+ execute: (t) => be(t, e),
998
+ inputSchema: z,
882
999
  strict: !0
883
1000
  }),
884
- execute_database_mutation: w({
1001
+ execute_database_mutation: k({
885
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.",
886
- execute: (t) => V(t, e),
887
- inputSchema: O,
1003
+ execute: (t) => Q(t, e),
1004
+ inputSchema: P,
888
1005
  strict: !0
889
1006
  }),
890
- read_database_records: w({
1007
+ read_database_records: k({
891
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.",
892
- execute: (t) => ne(t, e),
893
- inputSchema: N,
1009
+ execute: (t) => ge(t, e),
1010
+ inputSchema: B,
894
1011
  strict: !0
895
1012
  })
896
1013
  };
897
1014
  }
898
1015
  export {
899
- le as createCortexDatabaseAgentTools,
900
- D as describeDatabaseSchemaInputSchema,
901
- se as executeDatabaseActionPlan,
902
- L as executeDatabaseActionPlanInputSchema,
903
- V as executeDatabaseMutation,
904
- O as executeDatabaseMutationInputSchema,
905
- oe as executeDescribeDatabaseSchema,
906
- ne as executeReadDatabaseRecords,
907
- N as readDatabaseRecordsInputSchema
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
908
1025
  };