@nextblock-cms/cortex 0.20.3 → 0.21.1

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 (100) hide show
  1. package/README.md +46 -0
  2. package/client.cjs +1 -0
  3. package/client.es.js +3 -7
  4. package/index.cjs +1 -0
  5. package/index.es.js +24 -277
  6. package/lib/ai-block-generation.cjs +4 -0
  7. package/lib/ai-block-generation.es.js +143 -182
  8. package/lib/ai-client.cjs +1 -0
  9. package/lib/ai-client.d.ts +1 -1
  10. package/lib/ai-client.es.js +101 -135
  11. package/lib/ai-config.cjs +1 -0
  12. package/lib/ai-config.es.js +89 -108
  13. package/lib/ai-cortex-widget-builder.cjs +1 -0
  14. package/lib/ai-cortex-widget-builder.es.js +56 -70
  15. package/lib/ai-global-agent-content-ops-tools.cjs +1 -0
  16. package/lib/ai-global-agent-content-ops-tools.d.ts +1943 -68
  17. package/lib/ai-global-agent-content-ops-tools.es.js +185 -199
  18. package/lib/ai-global-agent-custom-block-tools.cjs +1 -0
  19. package/lib/ai-global-agent-custom-block-tools.d.ts +2160 -95
  20. package/lib/ai-global-agent-custom-block-tools.es.js +226 -223
  21. package/lib/ai-global-agent-db-tools.cjs +1 -0
  22. package/lib/ai-global-agent-db-tools.d.ts +2708 -98
  23. package/lib/ai-global-agent-db-tools.es.js +1013 -986
  24. package/lib/ai-global-agent-ecommerce.cjs +1 -0
  25. package/lib/ai-global-agent-ecommerce.es.js +3 -7
  26. package/lib/ai-global-agent-site-tools.cjs +2 -0
  27. package/lib/ai-global-agent-site-tools.d.ts +10695 -500
  28. package/lib/ai-global-agent-site-tools.es.js +750 -757
  29. package/lib/ai-global-agent-theming-tools.cjs +1 -0
  30. package/lib/ai-global-agent-theming-tools.d.ts +2905 -105
  31. package/lib/ai-global-agent-theming-tools.es.js +326 -396
  32. package/lib/ai-global-agent-tools.cjs +15 -0
  33. package/lib/ai-global-agent-tools.d.ts +4 -2230
  34. package/lib/ai-global-agent-tools.es.js +3899 -4328
  35. package/lib/ai-key-crypto.cjs +1 -0
  36. package/lib/ai-key-crypto.es.js +63 -82
  37. package/lib/ai-key-verification.cjs +1 -0
  38. package/lib/ai-key-verification.es.js +74 -63
  39. package/lib/ai-model-catalog.cjs +1 -0
  40. package/lib/ai-model-catalog.es.js +18 -22
  41. package/lib/ai-model-registry.cjs +2 -0
  42. package/lib/ai-model-registry.es.js +246 -309
  43. package/lib/ai-seo-metadata.cjs +3 -0
  44. package/lib/ai-seo-metadata.es.js +143 -185
  45. package/lib/ai-vision.cjs +3 -0
  46. package/lib/ai-vision.d.ts +6 -6
  47. package/lib/ai-vision.es.js +161 -215
  48. package/lib/block-content-schemas.cjs +1 -0
  49. package/lib/block-content-schemas.es.js +324 -254
  50. package/lib/cortex-widget-registry.cjs +1 -0
  51. package/lib/cortex-widget-registry.es.js +35 -43
  52. package/lib/cortex-widget-schema.cjs +4 -0
  53. package/lib/cortex-widget-schema.es.js +280 -309
  54. package/lib/editor-document-from-html.cjs +1 -0
  55. package/lib/editor-document-from-html.es.js +334 -278
  56. package/lib/fetch-host-guard.cjs +1 -0
  57. package/lib/fetch-host-guard.d.ts +2 -0
  58. package/lib/fetch-host-guard.es.js +30 -0
  59. package/lib/mcp-server.cjs +1 -0
  60. package/lib/mcp-server.es.js +155 -173
  61. package/lib/mcp-tokens.cjs +1 -0
  62. package/lib/mcp-tokens.es.js +95 -107
  63. package/lib/mcp-tool-registry.cjs +5 -0
  64. package/lib/mcp-tool-registry.es.js +533 -411
  65. package/lib/site-brief.cjs +2 -0
  66. package/lib/site-brief.es.js +102 -108
  67. package/lib/vision-image-download.cjs +1 -0
  68. package/lib/vision-image-download.d.ts +43 -0
  69. package/lib/vision-image-download.es.js +120 -0
  70. package/lib/zod-config.cjs +1 -0
  71. package/lib/zod-config.es.js +5 -6
  72. package/package.json +13 -12
  73. package/client.cjs.js +0 -1
  74. package/index.cjs.js +0 -1
  75. package/lib/ai-block-generation.cjs.js +0 -5
  76. package/lib/ai-client.cjs.js +0 -1
  77. package/lib/ai-config.cjs.js +0 -1
  78. package/lib/ai-cortex-widget-builder.cjs.js +0 -1
  79. package/lib/ai-global-agent-content-ops-tools.cjs.js +0 -1
  80. package/lib/ai-global-agent-custom-block-tools.cjs.js +0 -1
  81. package/lib/ai-global-agent-db-tools.cjs.js +0 -1
  82. package/lib/ai-global-agent-ecommerce.cjs.js +0 -1
  83. package/lib/ai-global-agent-site-tools.cjs.js +0 -3
  84. package/lib/ai-global-agent-theming-tools.cjs.js +0 -3
  85. package/lib/ai-global-agent-tools.cjs.js +0 -15
  86. package/lib/ai-key-crypto.cjs.js +0 -1
  87. package/lib/ai-key-verification.cjs.js +0 -1
  88. package/lib/ai-model-catalog.cjs.js +0 -1
  89. package/lib/ai-model-registry.cjs.js +0 -2
  90. package/lib/ai-seo-metadata.cjs.js +0 -4
  91. package/lib/ai-vision.cjs.js +0 -3
  92. package/lib/block-content-schemas.cjs.js +0 -1
  93. package/lib/cortex-widget-registry.cjs.js +0 -1
  94. package/lib/cortex-widget-schema.cjs.js +0 -5
  95. package/lib/editor-document-from-html.cjs.js +0 -1
  96. package/lib/mcp-server.cjs.js +0 -1
  97. package/lib/mcp-tokens.cjs.js +0 -1
  98. package/lib/mcp-tool-registry.cjs.js +0 -6
  99. package/lib/site-brief.cjs.js +0 -2
  100. package/lib/zod-config.cjs.js +0 -1
@@ -1,195 +1,156 @@
1
- import { generateText as g } from "ai";
2
- import "./zod-config.es.js";
3
- import { createCortexAiOpenRouterClient as w } from "./ai-client.es.js";
4
- import { buildCortexAiRoutingPolicy as y, runWithCortexAiModelFallback as x, omitUnsupportedCortexAiModelOptions as T, getHttpStatusCode as S, isOpenRouterRecoverableRoutingError as C } from "./ai-model-registry.es.js";
5
- import { z as h } from "zod";
6
- const H = h.strictObject({
7
- context: h.string().max(2e3).optional(),
8
- prompt: h.string().min(3).max(4e3)
9
- }), M = 6e4;
10
- function E() {
11
- return [
12
- "You are NextBlock Cortex AI, an inline rich-text assistant for a Tiptap editor.",
13
- "Return ONLY an HTML fragment. Do not return markdown fences, JSON, prose explanations, or commentary.",
14
- "Do not include <!doctype>, <html>, <head>, or <body>. The output is inserted inside an existing editor document.",
15
- "Use semantic HTML: headings, paragraphs, unordered and ordered lists, blockquotes, pre/code blocks, horizontal rules, and tables.",
16
- "Use the current editor context for continuity, but do not repeat existing copy unless the user explicitly asks for a rewrite.",
17
- "For tables, use valid <table>, <thead>, <tbody>, <tr>, <th>, and <td> markup with aligned rows and non-empty cells.",
18
- "Never use blank table spacer rows, blank spacer columns, empty cells, <colgroup>, colspan, or rowspan unless the user explicitly asks for a blank template.",
19
- "If CSS or JavaScript is explicitly requested, use proper <style> or <script> tags. The editor preserves those tags through its source-mode HTML parser.",
20
- "Keep copy production-ready, editable, and concise unless the user asks for longer content."
21
- ].join(" ");
1
+ import { buildCortexAiRoutingPolicy as e, getHttpStatusCode as t, isOpenRouterRecoverableRoutingError as n, omitUnsupportedCortexAiModelOptions as r, runWithCortexAiModelFallback as i } from "./ai-model-registry.es.js";
2
+ import { z as a } from "./zod-config.es.js";
3
+ import { createCortexAiOpenRouterClient as o } from "./ai-client.es.js";
4
+ import { generateText as s } from "ai";
5
+ //#region src/lib/ai-block-generation.ts
6
+ var c = a.strictObject({
7
+ context: a.string().max(2e3).optional(),
8
+ prompt: a.string().min(3).max(4e3)
9
+ }), l = 6e4;
10
+ function u() {
11
+ return [
12
+ "You are NextBlock Cortex AI, an inline rich-text assistant for a Tiptap editor.",
13
+ "Return ONLY an HTML fragment. Do not return markdown fences, JSON, prose explanations, or commentary.",
14
+ "Do not include <!doctype>, <html>, <head>, or <body>. The output is inserted inside an existing editor document.",
15
+ "Use semantic HTML: headings, paragraphs, unordered and ordered lists, blockquotes, pre/code blocks, horizontal rules, and tables.",
16
+ "Use the current editor context for continuity, but do not repeat existing copy unless the user explicitly asks for a rewrite.",
17
+ "For tables, use valid <table>, <thead>, <tbody>, <tr>, <th>, and <td> markup with aligned rows and non-empty cells.",
18
+ "Never use blank table spacer rows, blank spacer columns, empty cells, <colgroup>, colspan, or rowspan unless the user explicitly asks for a blank template.",
19
+ "If CSS or JavaScript is explicitly requested, use proper <style> or <script> tags. The editor preserves those tags through its source-mode HTML parser.",
20
+ "Keep copy production-ready, editable, and concise unless the user asks for longer content."
21
+ ].join(" ");
22
22
  }
23
- function I(e) {
24
- return [
25
- "Create an HTML fragment for this inline editor request:",
26
- e.prompt,
27
- /\b(table|pricing table|comparison table)\b/i.test(e.prompt) ? [
28
- "Table requirements:",
29
- "- Use a short header row.",
30
- "- Use only the real content columns requested by the user.",
31
- "- Do not add blank spacer columns or blank spacer rows.",
32
- "- Do not use <colgroup>, colspan, or rowspan.",
33
- "- Put normal descriptive prose before or after the table, not inside a table cell.",
34
- "- Body rows must match the header column count.",
35
- "- Every header and body cell must contain meaningful text."
36
- ].join(`
37
- `) : null,
38
- e.context ? `Current editor context:
39
- ${e.context}` : null
40
- ].filter(Boolean).join(`
41
-
42
- `);
23
+ function d(e) {
24
+ return [
25
+ "Create an HTML fragment for this inline editor request:",
26
+ e.prompt,
27
+ /\b(table|pricing table|comparison table)\b/i.test(e.prompt) ? [
28
+ "Table requirements:",
29
+ "- Use a short header row.",
30
+ "- Use only the real content columns requested by the user.",
31
+ "- Do not add blank spacer columns or blank spacer rows.",
32
+ "- Do not use <colgroup>, colspan, or rowspan.",
33
+ "- Put normal descriptive prose before or after the table, not inside a table cell.",
34
+ "- Body rows must match the header column count.",
35
+ "- Every header and body cell must contain meaningful text."
36
+ ].join("\n") : null,
37
+ e.context ? `Current editor context:\n${e.context}` : null
38
+ ].filter(Boolean).join("\n\n");
43
39
  }
44
- function A(e) {
45
- return e.replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&quot;/gi, '"').replace(/&#39;/gi, "'");
40
+ function f(e) {
41
+ return e.replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&quot;/gi, "\"").replace(/&#39;/gi, "'");
46
42
  }
47
- function k(e) {
48
- return A(
49
- e.replace(/<script\b[\s\S]*?<\/script>/gi, "").replace(/<style\b[\s\S]*?<\/style>/gi, "").replace(/<br\s*\/?>/gi, " ").replace(/<[^>]+>/g, " ")
50
- ).replace(/\s+/g, " ").trim();
43
+ function p(e) {
44
+ return f(e.replace(/<script\b[\s\S]*?<\/script>/gi, "").replace(/<style\b[\s\S]*?<\/style>/gi, "").replace(/<br\s*\/?>/gi, " ").replace(/<[^>]+>/g, " ")).replace(/\s+/g, " ").trim();
51
45
  }
52
- function b(e) {
53
- return k(e).length === 0;
46
+ function m(e) {
47
+ return p(e).length === 0;
54
48
  }
55
- function L(e) {
56
- return e.replace(/<(p|h[1-6])\b[^>]*>(?:\s|&nbsp;|<br\s*\/?>)*<\/\1>/gi, "").trim();
49
+ function h(e) {
50
+ return e.replace(/<(p|h[1-6])\b[^>]*>(?:\s|&nbsp;|<br\s*\/?>)*<\/\1>/gi, "").trim();
57
51
  }
58
- function R(e) {
59
- const t = [...e.matchAll(/<tr\b[^>]*>([\s\S]*?)<\/tr>/gi)];
60
- if (t.length === 0)
61
- return e;
62
- const o = t.map((r) => ({ cells: [...r[1].matchAll(/<(td|th)\b[^>]*>([\s\S]*?)<\/\1>/gi)].map(
63
- (l) => ({
64
- innerHtml: l[2].trim(),
65
- tag: l[1].toLowerCase()
66
- })
67
- ) })).filter((r) => r.cells.some((n) => !b(n.innerHtml)));
68
- if (o.length === 0)
69
- return e;
70
- const m = Math.max(...o.map((r) => r.cells.length)), i = /* @__PURE__ */ new Set();
71
- for (let r = 0; r < m; r++)
72
- o.every((l) => {
73
- const p = l.cells[r];
74
- return !p || b(p.innerHtml);
75
- }) && i.add(r);
76
- const s = o.map((r) => ({
77
- cells: r.cells.filter((n, l) => !i.has(l))
78
- })).filter((r) => r.cells.length > 0);
79
- if (s.length === 0)
80
- return e;
81
- const c = (r) => `<tr>${r.cells.map((n) => `<${n.tag}>${n.innerHtml}</${n.tag}>`).join("")}</tr>`;
82
- if (!s[0].cells.some((r) => r.tag === "th"))
83
- return `<table><tbody>${s.map(c).join("")}</tbody></table>`;
84
- const [u, ...d] = s;
85
- return `<table><thead>${c(u)}</thead><tbody>${d.map(c).join("")}</tbody></table>`;
52
+ function g(e) {
53
+ let t = [...e.matchAll(/<tr\b[^>]*>([\s\S]*?)<\/tr>/gi)];
54
+ if (t.length === 0) return e;
55
+ let n = t.map((e) => ({ cells: [...e[1].matchAll(/<(td|th)\b[^>]*>([\s\S]*?)<\/\1>/gi)].map((e) => ({
56
+ innerHtml: e[2].trim(),
57
+ tag: e[1].toLowerCase()
58
+ })) })).filter((e) => e.cells.some((e) => !m(e.innerHtml)));
59
+ if (n.length === 0) return e;
60
+ let r = Math.max(...n.map((e) => e.cells.length)), i = /* @__PURE__ */ new Set();
61
+ for (let e = 0; e < r; e++) n.every((t) => {
62
+ let n = t.cells[e];
63
+ return !n || m(n.innerHtml);
64
+ }) && i.add(e);
65
+ let a = n.map((e) => ({ cells: e.cells.filter((e, t) => !i.has(t)) })).filter((e) => e.cells.length > 0);
66
+ if (a.length === 0) return e;
67
+ let o = (e) => `<tr>${e.cells.map((e) => `<${e.tag}>${e.innerHtml}</${e.tag}>`).join("")}</tr>`;
68
+ if (!a[0].cells.some((e) => e.tag === "th")) return `<table><tbody>${a.map(o).join("")}</tbody></table>`;
69
+ let [s, ...c] = a;
70
+ return `<table><thead>${o(s)}</thead><tbody>${c.map(o).join("")}</tbody></table>`;
86
71
  }
87
- function v(e) {
88
- return e.replace(
89
- /<table\b[\s\S]*?<\/table>/gi,
90
- (t) => R(t)
91
- );
72
+ function _(e) {
73
+ return e.replace(/<table\b[\s\S]*?<\/table>/gi, (e) => g(e));
92
74
  }
93
- function O(e) {
94
- const t = [...e.matchAll(/<table\b[\s\S]*?<\/table>/gi)];
95
- for (const o of t) {
96
- const i = [...o[0].matchAll(/<tr\b[^>]*>([\s\S]*?)<\/tr>/gi)];
97
- if (i.length === 0)
98
- throw new Error("Cortex AI returned a table without rows.");
99
- const s = [];
100
- for (const c of i) {
101
- const a = [...c[1].matchAll(/<(td|th)\b[^>]*>([\s\S]*?)<\/\1>/gi)];
102
- if (a.length === 0)
103
- throw new Error("Cortex AI returned a table row without cells.");
104
- for (const u of a)
105
- if (b(u[2]))
106
- throw new Error("Cortex AI returned a table with empty cells.");
107
- s.push(a.length);
108
- }
109
- if (new Set(s).size > 1)
110
- throw new Error("Cortex AI returned a table with uneven row widths.");
111
- }
75
+ function v(e) {
76
+ let t = [...e.matchAll(/<table\b[\s\S]*?<\/table>/gi)];
77
+ for (let e of t) {
78
+ let t = [...e[0].matchAll(/<tr\b[^>]*>([\s\S]*?)<\/tr>/gi)];
79
+ if (t.length === 0) throw Error("Cortex AI returned a table without rows.");
80
+ let n = [];
81
+ for (let e of t) {
82
+ let t = [...e[1].matchAll(/<(td|th)\b[^>]*>([\s\S]*?)<\/\1>/gi)];
83
+ if (t.length === 0) throw Error("Cortex AI returned a table row without cells.");
84
+ for (let e of t) if (m(e[2])) throw Error("Cortex AI returned a table with empty cells.");
85
+ n.push(t.length);
86
+ }
87
+ if (new Set(n).size > 1) throw Error("Cortex AI returned a table with uneven row widths.");
88
+ }
112
89
  }
113
- function N(e) {
114
- let t = e.trim();
115
- (t.startsWith('"') && t.endsWith('"') || t.startsWith("'") && t.endsWith("'")) && t.slice(1, -1).includes("<") && (t = t.slice(1, -1).trim());
116
- const o = t.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i);
117
- return o?.[1] && (t = o[1].trim()), L(v(t));
90
+ function y(e) {
91
+ let t = e.trim();
92
+ (t.startsWith("\"") && t.endsWith("\"") || t.startsWith("'") && t.endsWith("'")) && t.slice(1, -1).includes("<") && (t = t.slice(1, -1).trim());
93
+ let n = t.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i);
94
+ return n?.[1] && (t = n[1].trim()), h(_(t));
118
95
  }
119
- function q(e) {
120
- const t = N(e);
121
- if (!t.trim())
122
- throw new Error("Cortex AI returned empty HTML.");
123
- if (/```/.test(t))
124
- throw new Error("Cortex AI returned markdown code fences instead of an HTML fragment.");
125
- if (/<!doctype\b|<html\b|<head\b|<body\b/i.test(t))
126
- throw new Error("Cortex AI returned a full HTML document instead of an HTML fragment.");
127
- if (/^(sure|certainly|of course|here(?:'s| is)|below is|i can)\b/i.test(t))
128
- throw new Error("Cortex AI returned a conversational response instead of an HTML fragment.");
129
- if (!/<[a-z][\w:-]*(?:\s[^>]*)?>/i.test(t))
130
- throw new Error("Cortex AI returned plain text instead of semantic HTML.");
131
- return O(t), t;
96
+ function b(e) {
97
+ let t = y(e);
98
+ if (!t.trim()) throw Error("Cortex AI returned empty HTML.");
99
+ if (/```/.test(t)) throw Error("Cortex AI returned markdown code fences instead of an HTML fragment.");
100
+ if (/<!doctype\b|<html\b|<head\b|<body\b/i.test(t)) throw Error("Cortex AI returned a full HTML document instead of an HTML fragment.");
101
+ if (/^(sure|certainly|of course|here(?:'s| is)|below is|i can)\b/i.test(t)) throw Error("Cortex AI returned a conversational response instead of an HTML fragment.");
102
+ if (!/<[a-z][\w:-]*(?:\s[^>]*)?>/i.test(t)) throw Error("Cortex AI returned plain text instead of semantic HTML.");
103
+ return v(t), t;
132
104
  }
133
- function P(e) {
134
- const t = S(e);
135
- if (t === 401 || t === 402 || t === 403)
136
- return !1;
137
- if (C(e) || t && t >= 500)
138
- return !0;
139
- const o = e instanceof Error ? e.message : String(e);
140
- return /NoContentGenerated|No content generated|Provider returned error|empty HTML|markdown code fences|full HTML document|conversational response|plain text|aborted|abort|timeout|timed out/i.test(
141
- o
142
- );
105
+ function x(e) {
106
+ let r = t(e);
107
+ if (r === 401 || r === 402 || r === 403) return !1;
108
+ if (n(e) || r && r >= 500) return !0;
109
+ let i = e instanceof Error ? e.message : String(e);
110
+ return /NoContentGenerated|No content generated|Provider returned error|empty HTML|markdown code fences|full HTML document|conversational response|plain text|aborted|abort|timeout|timed out/i.test(i);
143
111
  }
144
- async function G(e) {
145
- const { apiKey: t, fallbackModelIds: o, modelId: m, modelSelection: i, ...s } = e, c = H.parse(s), a = await w({ apiKey: t, modelSelection: i }), u = y({
146
- credentialSource: a.credentialSource,
147
- fallbackModelIds: o,
148
- requestedModelId: m,
149
- selectedModel: a.modelSelection
150
- }), d = await x({
151
- modelIds: u.modelIds,
152
- shouldRetry: P,
153
- execute: async (r) => {
154
- const n = new AbortController(), l = setTimeout(
155
- () => n.abort(),
156
- M
157
- );
158
- try {
159
- const p = T(
160
- {
161
- abortSignal: n.signal,
162
- maxOutputTokens: 5e3,
163
- maxRetries: 0,
164
- prompt: I(c),
165
- system: E(),
166
- temperature: 0.2
167
- },
168
- {
169
- modelId: r,
170
- modelSelection: u.modelSelection
171
- }
172
- ), f = await g({
173
- ...p,
174
- model: a.model(r)
175
- });
176
- return q(f.text);
177
- } finally {
178
- clearTimeout(l);
179
- }
180
- }
181
- });
182
- return {
183
- attempts: d.attempts,
184
- credentialSource: a.credentialSource,
185
- html: d.result,
186
- modelId: d.modelId
187
- };
112
+ async function S(t) {
113
+ let { apiKey: n, fallbackModelIds: a, modelId: f, modelSelection: p, ...m } = t, h = c.parse(m), g = await o({
114
+ apiKey: n,
115
+ modelSelection: p
116
+ }), _ = e({
117
+ credentialSource: g.credentialSource,
118
+ fallbackModelIds: a,
119
+ requestedModelId: f,
120
+ selectedModel: g.modelSelection
121
+ }), v = await i({
122
+ modelIds: _.modelIds,
123
+ shouldRetry: x,
124
+ execute: async (e) => {
125
+ let t = new AbortController(), n = setTimeout(() => t.abort(), l);
126
+ try {
127
+ let n = r({
128
+ abortSignal: t.signal,
129
+ maxOutputTokens: 5e3,
130
+ maxRetries: 0,
131
+ prompt: d(h),
132
+ instructions: u(),
133
+ temperature: .2
134
+ }, {
135
+ modelId: e,
136
+ modelSelection: _.modelSelection
137
+ });
138
+ return b((await s({
139
+ ...n,
140
+ model: g.model(e)
141
+ })).text);
142
+ } finally {
143
+ clearTimeout(n);
144
+ }
145
+ }
146
+ });
147
+ return {
148
+ attempts: v.attempts,
149
+ credentialSource: g.credentialSource,
150
+ html: v.result,
151
+ modelId: v.modelId
152
+ };
188
153
  }
189
- const U = "Built at runtime for HTML-fragment rich-text assistance.";
190
- export {
191
- U as INLINE_HTML_ASSISTANT_SYSTEM_PROMPT,
192
- H as generateEditorBlocksRequestSchema,
193
- G as generateEditorHtmlFragment,
194
- q as validateGeneratedEditorHtmlFragment
195
- };
154
+ var C = "Built at runtime for HTML-fragment rich-text assistance.";
155
+ //#endregion
156
+ export { C as INLINE_HTML_ASSISTANT_SYSTEM_PROMPT, c as generateEditorBlocksRequestSchema, S as generateEditorHtmlFragment, b as validateGeneratedEditorHtmlFragment };
@@ -0,0 +1 @@
1
+ const e=require("./ai-model-registry.cjs"),t=require("./ai-config.cjs"),n=require("./ai-model-catalog.cjs");let r=require("ai"),i=require("@ai-sdk/openai-compatible");var a=`Cortex AI OpenRouter client can only be imported from server-side code.`;function o(){if(typeof window<`u`)throw Error(a)}function s(){return o(),{"HTTP-Referer":process.env.NEXT_PUBLIC_URL?.trim()||`https://nextblock.dev`,"X-Title":t.CORTEX_AI_PACKAGE_NAME}}function c(t){return o(),(0,i.createOpenAICompatible)({apiKey:t.apiKey,baseURL:e.CORTEX_AI_OPENROUTER_BASE_URL,fetch:t.fetch,headers:s(),includeUsage:!0,name:`openrouter`,supportsStructuredOutputs:!0})}async function l(){o();let{getServiceRoleSupabaseClient:e}=await import(`@nextblock-cms/db/server`),{data:n,error:r}=await e().from(`site_settings`).select(`value`).eq(`key`,t.CORTEX_AI_OPENROUTER_SETTING_KEY).maybeSingle();if(r)throw Error(`Failed to load stored Cortex AI OpenRouter key: ${r.message}`);return n?.value?t.decryptStoredOpenRouterApiKey(n.value):null}async function u(){o();let{getServiceRoleSupabaseClient:n}=await import(`@nextblock-cms/db/server`),{data:r,error:i}=await n().from(`site_settings`).select(`value`).eq(`key`,t.CORTEX_AI_OPENROUTER_MODEL_SELECTION_SETTING_KEY).maybeSingle();if(i)throw Error(`Failed to load Cortex AI OpenRouter model selection: ${i.message}`);return e.safeParseCortexAiModelSelection(r?.value)}async function d(e){o();let n=e?.apiKey?.trim();if(n)return{apiKey:n,source:`manual`};let r=await l();if(r)return{apiKey:r,source:`stored`};let i=t.getOpenRouterEnvApiKey();return i?{apiKey:i,source:`env`}:{apiKey:null,source:`none`}}async function f(e){o();let t=await d({apiKey:e?.apiKey});if(!t.apiKey||t.source===`none`)throw Error(`Cortex AI requires OPENROUTER_API_KEY or an encrypted OpenRouter BYOK in site settings.`);let n=c({apiKey:t.apiKey,fetch:e?.fetch}),r=e?.modelSelection===void 0?t.source===`stored`?await u():null:e.modelSelection;return{credentialSource:t.source,model:e=>n.chatModel(e||`openrouter/free`),modelSelection:r}}async function p({apiKey:t,fallbackModelIds:n,modelId:i,...a}){o();let s=await f({apiKey:t,modelSelection:a.modelSelection}),c=e.buildCortexAiRoutingPolicy({credentialSource:s.credentialSource,fallbackModelIds:n,requestedModelId:i,selectedModel:s.modelSelection}),l=await e.runWithCortexAiModelFallback({modelIds:c.modelIds,execute:t=>{let n=e.omitUnsupportedCortexAiModelOptions({...a,maxRetries:0},{modelId:t,modelSelection:c.modelSelection});return(0,r.generateText)({...n,model:s.model(t)})}});return{attempts:l.attempts,credentialSource:s.credentialSource,modelId:l.modelId,result:l.result}}exports.CORTEX_AI_FREE_MODEL_FALLBACK_REGISTRY=e.CORTEX_AI_FREE_MODEL_FALLBACK_REGISTRY,exports.CORTEX_AI_MODEL_REGISTRY=e.CORTEX_AI_MODEL_REGISTRY,exports.CORTEX_AI_OPENROUTER_BASE_URL=e.CORTEX_AI_OPENROUTER_BASE_URL,exports.CORTEX_AI_OPENROUTER_FREE_ROUTER_MODEL=e.CORTEX_AI_OPENROUTER_FREE_ROUTER_MODEL,exports.CORTEX_AI_REQUIRED_MODEL_PARAMETERS=e.CORTEX_AI_REQUIRED_MODEL_PARAMETERS,exports.CortexAiRoutingError=e.CortexAiRoutingError,exports.buildCortexAiModelFallbackChain=e.buildCortexAiModelFallbackChain,exports.buildCortexAiRoutingPolicy=e.buildCortexAiRoutingPolicy,exports.createCortexAiOpenRouterClient=f,exports.createCortexAiOpenRouterProvider=c,exports.generateCortexAiText=p,exports.getStoredCortexAiModelSelection=u,exports.isOpenRouterRateLimitError=e.isOpenRouterRateLimitError,exports.isOpenRouterRecoverableRoutingError=e.isOpenRouterRecoverableRoutingError,exports.listCortexAiCompatibleOpenRouterModels=n.listCortexAiCompatibleOpenRouterModels,exports.omitUnsupportedCortexAiModelOptions=e.omitUnsupportedCortexAiModelOptions,exports.resolveCortexAiOpenRouterCredential=d,exports.runWithCortexAiModelFallback=e.runWithCortexAiModelFallback,exports.summarizeCortexAiRoutingError=e.summarizeCortexAiRoutingError;
@@ -38,7 +38,7 @@ export declare function createCortexAiOpenRouterClient(params?: {
38
38
  modelSelection?: CortexAiStoredModelSelection | null;
39
39
  }): Promise<{
40
40
  credentialSource: "env" | "manual" | "stored";
41
- model: (modelId?: CortexAiOpenRouterModelId) => import('@ai-sdk/provider').LanguageModelV3;
41
+ model: (modelId?: CortexAiOpenRouterModelId) => import('@ai-sdk/provider').LanguageModelV4;
42
42
  modelSelection: CortexAiStoredModelSelection | null;
43
43
  }>;
44
44
  export declare function generateCortexAiText({ apiKey, fallbackModelIds, modelId, ...options }: CortexAiGenerateTextOptions & {
@@ -1,143 +1,109 @@
1
- import { createOpenAICompatible as s } from "@ai-sdk/openai-compatible";
2
- import { generateText as d } from "ai";
3
- import { CORTEX_AI_OPENROUTER_MODEL_SELECTION_SETTING_KEY as R, getOpenRouterEnvApiKey as p, CORTEX_AI_PACKAGE_NAME as E, CORTEX_AI_OPENROUTER_SETTING_KEY as m, decryptStoredOpenRouterApiKey as O } from "./ai-config.es.js";
4
- import { CORTEX_AI_OPENROUTER_BASE_URL as _, buildCortexAiRoutingPolicy as A, runWithCortexAiModelFallback as f, omitUnsupportedCortexAiModelOptions as C, safeParseCortexAiModelSelection as S } from "./ai-model-registry.es.js";
5
- import { CORTEX_AI_FREE_MODEL_FALLBACK_REGISTRY as N, CORTEX_AI_MODEL_REGISTRY as X, CORTEX_AI_OPENROUTER_FREE_ROUTER_MODEL as F, CORTEX_AI_REQUIRED_MODEL_PARAMETERS as Y, CortexAiRoutingError as k, buildCortexAiModelFallbackChain as D, isOpenRouterRateLimitError as G, isOpenRouterRecoverableRoutingError as q, summarizeCortexAiRoutingError as B } from "./ai-model-registry.es.js";
6
- import { listCortexAiCompatibleOpenRouterModels as $ } from "./ai-model-catalog.es.js";
7
- const y = "Cortex AI OpenRouter client can only be imported from server-side code.";
8
- function n() {
9
- if (!(typeof window > "u"))
10
- throw new Error(y);
1
+ import { CORTEX_AI_FREE_MODEL_FALLBACK_REGISTRY as e, CORTEX_AI_MODEL_REGISTRY as t, CORTEX_AI_OPENROUTER_BASE_URL as n, CORTEX_AI_OPENROUTER_FREE_ROUTER_MODEL as r, CORTEX_AI_REQUIRED_MODEL_PARAMETERS as i, CortexAiRoutingError as a, buildCortexAiModelFallbackChain as o, buildCortexAiRoutingPolicy as s, isOpenRouterRateLimitError as c, isOpenRouterRecoverableRoutingError as l, omitUnsupportedCortexAiModelOptions as u, runWithCortexAiModelFallback as d, safeParseCortexAiModelSelection as f, summarizeCortexAiRoutingError as p } from "./ai-model-registry.es.js";
2
+ import { CORTEX_AI_OPENROUTER_MODEL_SELECTION_SETTING_KEY as m, CORTEX_AI_OPENROUTER_SETTING_KEY as h, CORTEX_AI_PACKAGE_NAME as g, decryptStoredOpenRouterApiKey as _, getOpenRouterEnvApiKey as v } from "./ai-config.es.js";
3
+ import { listCortexAiCompatibleOpenRouterModels as y } from "./ai-model-catalog.es.js";
4
+ import { generateText as b } from "ai";
5
+ import { createOpenAICompatible as x } from "@ai-sdk/openai-compatible";
6
+ //#region src/lib/ai-client.ts
7
+ var S = "Cortex AI OpenRouter client can only be imported from server-side code.";
8
+ function C() {
9
+ if (typeof window < "u") throw Error(S);
11
10
  }
12
- function T() {
13
- return n(), {
14
- "HTTP-Referer": process.env.NEXT_PUBLIC_URL?.trim() || "https://nextblock.dev",
15
- "X-Title": E
16
- };
11
+ function w() {
12
+ return C(), {
13
+ "HTTP-Referer": process.env.NEXT_PUBLIC_URL?.trim() || "https://nextblock.dev",
14
+ "X-Title": g
15
+ };
17
16
  }
18
- function I(e) {
19
- return n(), s({
20
- apiKey: e.apiKey,
21
- baseURL: _,
22
- fetch: e.fetch,
23
- headers: T(),
24
- includeUsage: !0,
25
- name: "openrouter",
26
- supportsStructuredOutputs: !0
27
- });
17
+ function T(e) {
18
+ return C(), x({
19
+ apiKey: e.apiKey,
20
+ baseURL: n,
21
+ fetch: e.fetch,
22
+ headers: w(),
23
+ includeUsage: !0,
24
+ name: "openrouter",
25
+ supportsStructuredOutputs: !0
26
+ });
28
27
  }
29
- async function x() {
30
- n();
31
- const { getServiceRoleSupabaseClient: e } = await import("@nextblock-cms/db/server"), t = e(), { data: o, error: r } = await t.from("site_settings").select("value").eq("key", m).maybeSingle();
32
- if (r)
33
- throw new Error(`Failed to load stored Cortex AI OpenRouter key: ${r.message}`);
34
- return o?.value ? O(o.value) : null;
28
+ async function E() {
29
+ C();
30
+ let { getServiceRoleSupabaseClient: e } = await import("@nextblock-cms/db/server"), { data: t, error: n } = await e().from("site_settings").select("value").eq("key", h).maybeSingle();
31
+ if (n) throw Error(`Failed to load stored Cortex AI OpenRouter key: ${n.message}`);
32
+ return t?.value ? _(t.value) : null;
35
33
  }
36
- async function K() {
37
- n();
38
- const { getServiceRoleSupabaseClient: e } = await import("@nextblock-cms/db/server"), t = e(), { data: o, error: r } = await t.from("site_settings").select("value").eq("key", R).maybeSingle();
39
- if (r)
40
- throw new Error(`Failed to load Cortex AI OpenRouter model selection: ${r.message}`);
41
- return S(o?.value);
34
+ async function D() {
35
+ C();
36
+ let { getServiceRoleSupabaseClient: e } = await import("@nextblock-cms/db/server"), { data: t, error: n } = await e().from("site_settings").select("value").eq("key", m).maybeSingle();
37
+ if (n) throw Error(`Failed to load Cortex AI OpenRouter model selection: ${n.message}`);
38
+ return f(t?.value);
42
39
  }
43
- async function g(e) {
44
- n();
45
- const t = e?.apiKey?.trim();
46
- if (t)
47
- return {
48
- apiKey: t,
49
- source: "manual"
50
- };
51
- const o = await x();
52
- if (o)
53
- return {
54
- apiKey: o,
55
- source: "stored"
56
- };
57
- const r = p();
58
- return r ? {
59
- apiKey: r,
60
- source: "env"
61
- } : {
62
- apiKey: null,
63
- source: "none"
64
- };
40
+ async function O(e) {
41
+ C();
42
+ let t = e?.apiKey?.trim();
43
+ if (t) return {
44
+ apiKey: t,
45
+ source: "manual"
46
+ };
47
+ let n = await E();
48
+ if (n) return {
49
+ apiKey: n,
50
+ source: "stored"
51
+ };
52
+ let r = v();
53
+ return r ? {
54
+ apiKey: r,
55
+ source: "env"
56
+ } : {
57
+ apiKey: null,
58
+ source: "none"
59
+ };
65
60
  }
66
- async function v(e) {
67
- n();
68
- const t = await g({
69
- apiKey: e?.apiKey
70
- });
71
- if (!t.apiKey || t.source === "none")
72
- throw new Error(
73
- "Cortex AI requires OPENROUTER_API_KEY or an encrypted OpenRouter BYOK in site settings."
74
- );
75
- const o = I({
76
- apiKey: t.apiKey,
77
- fetch: e?.fetch
78
- }), r = e?.modelSelection !== void 0 ? e.modelSelection : t.source === "stored" ? await K() : null;
79
- return {
80
- credentialSource: t.source,
81
- model: (i) => o.chatModel(i || "openrouter/free"),
82
- modelSelection: r
83
- };
61
+ async function k(e) {
62
+ C();
63
+ let t = await O({ apiKey: e?.apiKey });
64
+ if (!t.apiKey || t.source === "none") throw Error("Cortex AI requires OPENROUTER_API_KEY or an encrypted OpenRouter BYOK in site settings.");
65
+ let n = T({
66
+ apiKey: t.apiKey,
67
+ fetch: e?.fetch
68
+ }), r = e?.modelSelection === void 0 ? t.source === "stored" ? await D() : null : e.modelSelection;
69
+ return {
70
+ credentialSource: t.source,
71
+ model: (e) => n.chatModel(e || "openrouter/free"),
72
+ modelSelection: r
73
+ };
84
74
  }
85
- async function P({
86
- apiKey: e,
87
- fallbackModelIds: t,
88
- modelId: o,
89
- ...r
90
- }) {
91
- n();
92
- const i = await v({ apiKey: e, modelSelection: r.modelSelection }), l = A({
93
- credentialSource: i.credentialSource,
94
- fallbackModelIds: t,
95
- requestedModelId: o,
96
- selectedModel: i.modelSelection
97
- }), a = await f({
98
- modelIds: l.modelIds,
99
- execute: (c) => {
100
- const u = C(
101
- {
102
- ...r,
103
- maxRetries: 0
104
- },
105
- {
106
- modelId: c,
107
- modelSelection: l.modelSelection
108
- }
109
- );
110
- return d({
111
- ...u,
112
- model: i.model(c)
113
- });
114
- }
115
- });
116
- return {
117
- attempts: a.attempts,
118
- credentialSource: i.credentialSource,
119
- modelId: a.modelId,
120
- result: a.result
121
- };
75
+ async function A({ apiKey: e, fallbackModelIds: t, modelId: n, ...r }) {
76
+ C();
77
+ let i = await k({
78
+ apiKey: e,
79
+ modelSelection: r.modelSelection
80
+ }), a = s({
81
+ credentialSource: i.credentialSource,
82
+ fallbackModelIds: t,
83
+ requestedModelId: n,
84
+ selectedModel: i.modelSelection
85
+ }), o = await d({
86
+ modelIds: a.modelIds,
87
+ execute: (e) => {
88
+ let t = u({
89
+ ...r,
90
+ maxRetries: 0
91
+ }, {
92
+ modelId: e,
93
+ modelSelection: a.modelSelection
94
+ });
95
+ return b({
96
+ ...t,
97
+ model: i.model(e)
98
+ });
99
+ }
100
+ });
101
+ return {
102
+ attempts: o.attempts,
103
+ credentialSource: i.credentialSource,
104
+ modelId: o.modelId,
105
+ result: o.result
106
+ };
122
107
  }
123
- export {
124
- N as CORTEX_AI_FREE_MODEL_FALLBACK_REGISTRY,
125
- X as CORTEX_AI_MODEL_REGISTRY,
126
- _ as CORTEX_AI_OPENROUTER_BASE_URL,
127
- F as CORTEX_AI_OPENROUTER_FREE_ROUTER_MODEL,
128
- Y as CORTEX_AI_REQUIRED_MODEL_PARAMETERS,
129
- k as CortexAiRoutingError,
130
- D as buildCortexAiModelFallbackChain,
131
- A as buildCortexAiRoutingPolicy,
132
- v as createCortexAiOpenRouterClient,
133
- I as createCortexAiOpenRouterProvider,
134
- P as generateCortexAiText,
135
- K as getStoredCortexAiModelSelection,
136
- G as isOpenRouterRateLimitError,
137
- q as isOpenRouterRecoverableRoutingError,
138
- $ as listCortexAiCompatibleOpenRouterModels,
139
- C as omitUnsupportedCortexAiModelOptions,
140
- g as resolveCortexAiOpenRouterCredential,
141
- f as runWithCortexAiModelFallback,
142
- B as summarizeCortexAiRoutingError
143
- };
108
+ //#endregion
109
+ export { e as CORTEX_AI_FREE_MODEL_FALLBACK_REGISTRY, t as CORTEX_AI_MODEL_REGISTRY, n as CORTEX_AI_OPENROUTER_BASE_URL, r as CORTEX_AI_OPENROUTER_FREE_ROUTER_MODEL, i as CORTEX_AI_REQUIRED_MODEL_PARAMETERS, a as CortexAiRoutingError, o as buildCortexAiModelFallbackChain, s as buildCortexAiRoutingPolicy, k as createCortexAiOpenRouterClient, T as createCortexAiOpenRouterProvider, A as generateCortexAiText, D as getStoredCortexAiModelSelection, c as isOpenRouterRateLimitError, l as isOpenRouterRecoverableRoutingError, y as listCortexAiCompatibleOpenRouterModels, u as omitUnsupportedCortexAiModelOptions, O as resolveCortexAiOpenRouterCredential, d as runWithCortexAiModelFallback, p as summarizeCortexAiRoutingError };
@@ -0,0 +1 @@
1
+ const e=require("./ai-key-crypto.cjs");let t=require("@nextblock-cms/db/secrets");var n=`Cortex AI configuration can only be imported from server-side code.`;function r(){if(typeof window<`u`)throw Error(n)}var i=`cortex-ai`,a=`NextBlock Cortex AI`,o=`cortex_ai_openrouter_api_key`,s=`cortex_ai_openrouter_model_selection`,c=`cortex_ai_pexels_api_key`,l=`cortex_ai_unsplash_access_key`,u=`cortex_ai_unsplash_app_name`,d=`cortex_ai_agent_settings`,f={maxOutputTokens:16e3,maxSteps:8,responseTimeoutMs:12e4,temperature:.1},p={maxOutputTokens:{max:2e5,min:256},maxSteps:{max:100,min:2},responseTimeoutMs:{max:6e5,min:15e3},temperature:{max:2,min:0}};function m(e,t,n,r){let i=typeof e==`number`?e:Number(e);return Number.isFinite(i)?Math.min(n,Math.max(t,i)):r}function h(e){let t=e&&typeof e==`object`&&!Array.isArray(e)?e:{},n=p,r=f,i=t.maxOutputTokens;return{maxOutputTokens:i===null||i===`unlimited`||i===``?null:m(i,n.maxOutputTokens.min,n.maxOutputTokens.max,r.maxOutputTokens??16e3),maxSteps:Math.round(m(t.maxSteps,n.maxSteps.min,n.maxSteps.max,r.maxSteps)),responseTimeoutMs:Math.round(m(t.responseTimeoutMs,n.responseTimeoutMs.min,n.responseTimeoutMs.max,r.responseTimeoutMs)),temperature:m(t.temperature,n.temperature.min,n.temperature.max,r.temperature)}}async function g(e){if(e)try{let{data:t}=await e.from(`site_settings`).select(`value`).eq(`key`,d).maybeSingle();if(t?.value)return h(t.value)}catch{}return{...f}}function _(e){return process.env[e]?.trim()||null}function v(){return r(),_(`PEXELS_API_KEY`)}function y(){return r(),_(`UNSPLASH_ACCESS_KEY`)}function b(){return r(),_(`OPENROUTER_API_KEY`)}function x(){r();let e=b();return{encryptionKey:_(`CORTEX_AI_ENCRYPTION_KEY`),freemiusSandboxKey:_(`FREEMIUS_AI_SANDBOX_KEY`),hasEncryptionKey:(0,t.hasSecretEncryptionKey)(),hasOpenRouterEnvKey:!!e,openRouterEnvKeyLast4:e?e.slice(-4):null}}function S(){r();let e=(0,t.resolveSecretEncryptionKey)();if(!e)throw Error(`An encryption key (NEXTBLOCK_ENCRYPTION_KEY, CORTEX_AI_ENCRYPTION_KEY, or a Supabase service-role key) is required to manage stored OpenRouter keys.`);return e}function C(t){return e.encryptOpenRouterApiKey({apiKey:t,encryptionSecret:S()})}function w(e){r();let n=(0,t.tryDecryptWithEnvKey)(e);if(n===null)throw Error(`Failed to decrypt stored OpenRouter key.`);return n}function T(t){return e.getOpenRouterKeyEnvelopeStatus(t)}function E(){r();let t=x();return{hasEnvOpenRouterKey:t.hasOpenRouterEnvKey,maskedEnvOpenRouterKey:t.openRouterEnvKeyLast4?e.getMaskedOpenRouterKey(t.openRouterEnvKeyLast4):null}}exports.CORTEX_AI_AGENT_SETTINGS_BOUNDS=p,exports.CORTEX_AI_AGENT_SETTINGS_DEFAULTS=f,exports.CORTEX_AI_AGENT_SETTINGS_KEY=d,exports.CORTEX_AI_OPENROUTER_MODEL_SELECTION_SETTING_KEY=s,exports.CORTEX_AI_OPENROUTER_SETTING_KEY=o,exports.CORTEX_AI_PACKAGE_ID=i,exports.CORTEX_AI_PACKAGE_NAME=a,exports.CORTEX_AI_PEXELS_SETTING_KEY=c,exports.CORTEX_AI_UNSPLASH_APP_NAME_SETTING_KEY=u,exports.CORTEX_AI_UNSPLASH_SETTING_KEY=l,exports.decryptStoredOpenRouterApiKey=w,exports.encryptStoredOpenRouterApiKey=C,exports.getCortexAiEnvConfig=x,exports.getEnvOpenRouterKeyStatus=E,exports.getOpenRouterEnvApiKey=b,exports.getPexelsEnvApiKey=v,exports.getStoredOpenRouterKeyStatus=T,exports.getUnsplashEnvApiKey=y,exports.normalizeCortexAiAgentSettings=h,exports.resolveCortexAiAgentSettings=g;