@nextblock-cms/cortex 0.20.3 → 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 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("crypto"),n="aes-256-gcm",u=1;function c(t){const e=t.trim();if(!e)throw new Error("CORTEX_AI_ENCRYPTION_KEY is required to manage stored OpenRouter keys.");return o.createHash("sha256").update(e).digest()}function p(t){if(!t||typeof t!="object")throw new Error("Invalid encrypted OpenRouter key payload.");const e=t;if(e.algorithm!==n||e.version!==u||typeof e.authTag!="string"||typeof e.ciphertext!="string"||typeof e.iv!="string")throw new Error("Invalid encrypted OpenRouter key payload.");return{algorithm:e.algorithm,authTag:e.authTag,ciphertext:e.ciphertext,iv:e.iv,last4:typeof e.last4=="string"?e.last4:"",updatedAt:typeof e.updatedAt=="string"?e.updatedAt:"",version:e.version}}function s(t){const e=(t||"").trim();return e?`**** ${e}`:"Stored key"}function l(t){const e=t.apiKey.trim();if(!e)throw new Error("OpenRouter API key is required.");const a=c(t.encryptionSecret),r=o.randomBytes(12),i=o.createCipheriv(n,a,r),y=Buffer.concat([i.update(e,"utf8"),i.final()]),d=i.getAuthTag();return{algorithm:n,authTag:d.toString("base64"),ciphertext:y.toString("base64"),iv:r.toString("base64"),last4:e.slice(-4),updatedAt:(t.now||new Date).toISOString(),version:u}}function f(t){const e=p(t.encryptedKey),a=c(t.encryptionSecret);try{const r=o.createDecipheriv(n,a,Buffer.from(e.iv,"base64"));return r.setAuthTag(Buffer.from(e.authTag,"base64")),Buffer.concat([r.update(Buffer.from(e.ciphertext,"base64")),r.final()]).toString("utf8")}catch{throw new Error("Failed to decrypt stored OpenRouter key.")}}function h(t){try{const e=p(t);return{hasStoredKey:!0,last4:e.last4||null,maskedKey:s(e.last4),updatedAt:e.updatedAt||null}}catch{return{hasStoredKey:!1,last4:null,maskedKey:null,updatedAt:null}}}exports.CORTEX_AI_KEY_ALGORITHM=n;exports.CORTEX_AI_KEY_ENVELOPE_VERSION=u;exports.decryptOpenRouterApiKey=f;exports.encryptOpenRouterApiKey=l;exports.getMaskedOpenRouterKey=s;exports.getOpenRouterKeyEnvelopeStatus=h;
1
+ let e=require("crypto");var t=`aes-256-gcm`,n=1;function r(t){let n=t.trim();if(!n)throw Error(`CORTEX_AI_ENCRYPTION_KEY is required to manage stored OpenRouter keys.`);return(0,e.createHash)(`sha256`).update(n).digest()}function i(e){if(!e||typeof e!=`object`)throw Error(`Invalid encrypted OpenRouter key payload.`);let t=e;if(t.algorithm!==`aes-256-gcm`||t.version!==1||typeof t.authTag!=`string`||typeof t.ciphertext!=`string`||typeof t.iv!=`string`)throw Error(`Invalid encrypted OpenRouter key payload.`);return{algorithm:t.algorithm,authTag:t.authTag,ciphertext:t.ciphertext,iv:t.iv,last4:typeof t.last4==`string`?t.last4:``,updatedAt:typeof t.updatedAt==`string`?t.updatedAt:``,version:t.version}}function a(e){let t=(e||``).trim();return t?`**** ${t}`:`Stored key`}function o(n){let i=n.apiKey.trim();if(!i)throw Error(`OpenRouter API key is required.`);let a=r(n.encryptionSecret),o=(0,e.randomBytes)(12),s=(0,e.createCipheriv)(t,a,o),c=Buffer.concat([s.update(i,`utf8`),s.final()]);return{algorithm:t,authTag:s.getAuthTag().toString(`base64`),ciphertext:c.toString(`base64`),iv:o.toString(`base64`),last4:i.slice(-4),updatedAt:(n.now||new Date).toISOString(),version:1}}function s(n){let a=i(n.encryptedKey),o=r(n.encryptionSecret);try{let n=(0,e.createDecipheriv)(t,o,Buffer.from(a.iv,`base64`));return n.setAuthTag(Buffer.from(a.authTag,`base64`)),Buffer.concat([n.update(Buffer.from(a.ciphertext,`base64`)),n.final()]).toString(`utf8`)}catch{throw Error(`Failed to decrypt stored OpenRouter key.`)}}function c(e){try{let t=i(e);return{hasStoredKey:!0,last4:t.last4||null,maskedKey:a(t.last4),updatedAt:t.updatedAt||null}}catch{return{hasStoredKey:!1,last4:null,maskedKey:null,updatedAt:null}}}exports.CORTEX_AI_KEY_ALGORITHM=t,exports.CORTEX_AI_KEY_ENVELOPE_VERSION=n,exports.decryptOpenRouterApiKey=s,exports.encryptOpenRouterApiKey=o,exports.getMaskedOpenRouterKey=a,exports.getOpenRouterKeyEnvelopeStatus=c;
@@ -1,88 +1,69 @@
1
- import { createDecipheriv as d, randomBytes as y, createCipheriv as l, createHash as f } from "crypto";
2
- const n = "aes-256-gcm", i = 1;
3
- function s(t) {
4
- const e = t.trim();
5
- if (!e)
6
- throw new Error("CORTEX_AI_ENCRYPTION_KEY is required to manage stored OpenRouter keys.");
7
- return f("sha256").update(e).digest();
1
+ import { createCipheriv as e, createDecipheriv as t, createHash as n, randomBytes as r } from "crypto";
2
+ //#region libs/cortex/src/lib/ai-key-crypto.ts
3
+ var i = "aes-256-gcm", a = 1;
4
+ function o(e) {
5
+ let t = e.trim();
6
+ if (!t) throw Error("CORTEX_AI_ENCRYPTION_KEY is required to manage stored OpenRouter keys.");
7
+ return n("sha256").update(t).digest();
8
8
  }
9
- function c(t) {
10
- if (!t || typeof t != "object")
11
- throw new Error("Invalid encrypted OpenRouter key payload.");
12
- const e = t;
13
- if (e.algorithm !== n || e.version !== i || typeof e.authTag != "string" || typeof e.ciphertext != "string" || typeof e.iv != "string")
14
- throw new Error("Invalid encrypted OpenRouter key payload.");
15
- return {
16
- algorithm: e.algorithm,
17
- authTag: e.authTag,
18
- ciphertext: e.ciphertext,
19
- iv: e.iv,
20
- last4: typeof e.last4 == "string" ? e.last4 : "",
21
- updatedAt: typeof e.updatedAt == "string" ? e.updatedAt : "",
22
- version: e.version
23
- };
9
+ function s(e) {
10
+ if (!e || typeof e != "object") throw Error("Invalid encrypted OpenRouter key payload.");
11
+ let t = e;
12
+ if (t.algorithm !== "aes-256-gcm" || t.version !== 1 || typeof t.authTag != "string" || typeof t.ciphertext != "string" || typeof t.iv != "string") throw Error("Invalid encrypted OpenRouter key payload.");
13
+ return {
14
+ algorithm: t.algorithm,
15
+ authTag: t.authTag,
16
+ ciphertext: t.ciphertext,
17
+ iv: t.iv,
18
+ last4: typeof t.last4 == "string" ? t.last4 : "",
19
+ updatedAt: typeof t.updatedAt == "string" ? t.updatedAt : "",
20
+ version: t.version
21
+ };
24
22
  }
25
- function h(t) {
26
- const e = (t || "").trim();
27
- return e ? `**** ${e}` : "Stored key";
23
+ function c(e) {
24
+ let t = (e || "").trim();
25
+ return t ? `**** ${t}` : "Stored key";
28
26
  }
29
- function E(t) {
30
- const e = t.apiKey.trim();
31
- if (!e)
32
- throw new Error("OpenRouter API key is required.");
33
- const o = s(t.encryptionSecret), r = y(12), a = l(n, o, r), u = Buffer.concat([
34
- a.update(e, "utf8"),
35
- a.final()
36
- ]), p = a.getAuthTag();
37
- return {
38
- algorithm: n,
39
- authTag: p.toString("base64"),
40
- ciphertext: u.toString("base64"),
41
- iv: r.toString("base64"),
42
- last4: e.slice(-4),
43
- updatedAt: (t.now || /* @__PURE__ */ new Date()).toISOString(),
44
- version: i
45
- };
27
+ function l(t) {
28
+ let n = t.apiKey.trim();
29
+ if (!n) throw Error("OpenRouter API key is required.");
30
+ let a = o(t.encryptionSecret), s = r(12), c = e(i, a, s), l = Buffer.concat([c.update(n, "utf8"), c.final()]);
31
+ return {
32
+ algorithm: i,
33
+ authTag: c.getAuthTag().toString("base64"),
34
+ ciphertext: l.toString("base64"),
35
+ iv: s.toString("base64"),
36
+ last4: n.slice(-4),
37
+ updatedAt: (t.now || /* @__PURE__ */ new Date()).toISOString(),
38
+ version: 1
39
+ };
46
40
  }
47
- function m(t) {
48
- const e = c(t.encryptedKey), o = s(t.encryptionSecret);
49
- try {
50
- const r = d(
51
- n,
52
- o,
53
- Buffer.from(e.iv, "base64")
54
- );
55
- return r.setAuthTag(Buffer.from(e.authTag, "base64")), Buffer.concat([
56
- r.update(Buffer.from(e.ciphertext, "base64")),
57
- r.final()
58
- ]).toString("utf8");
59
- } catch {
60
- throw new Error("Failed to decrypt stored OpenRouter key.");
61
- }
41
+ function u(e) {
42
+ let n = s(e.encryptedKey), r = o(e.encryptionSecret);
43
+ try {
44
+ let e = t(i, r, Buffer.from(n.iv, "base64"));
45
+ return e.setAuthTag(Buffer.from(n.authTag, "base64")), Buffer.concat([e.update(Buffer.from(n.ciphertext, "base64")), e.final()]).toString("utf8");
46
+ } catch {
47
+ throw Error("Failed to decrypt stored OpenRouter key.");
48
+ }
62
49
  }
63
- function v(t) {
64
- try {
65
- const e = c(t);
66
- return {
67
- hasStoredKey: !0,
68
- last4: e.last4 || null,
69
- maskedKey: h(e.last4),
70
- updatedAt: e.updatedAt || null
71
- };
72
- } catch {
73
- return {
74
- hasStoredKey: !1,
75
- last4: null,
76
- maskedKey: null,
77
- updatedAt: null
78
- };
79
- }
50
+ function d(e) {
51
+ try {
52
+ let t = s(e);
53
+ return {
54
+ hasStoredKey: !0,
55
+ last4: t.last4 || null,
56
+ maskedKey: c(t.last4),
57
+ updatedAt: t.updatedAt || null
58
+ };
59
+ } catch {
60
+ return {
61
+ hasStoredKey: !1,
62
+ last4: null,
63
+ maskedKey: null,
64
+ updatedAt: null
65
+ };
66
+ }
80
67
  }
81
- export {
82
- n as CORTEX_AI_KEY_ALGORITHM,
83
- i as CORTEX_AI_KEY_ENVELOPE_VERSION,
84
- m as decryptOpenRouterApiKey,
85
- E as encryptOpenRouterApiKey,
86
- h as getMaskedOpenRouterKey,
87
- v as getOpenRouterKeyEnvelopeStatus
88
- };
68
+ //#endregion
69
+ export { i as CORTEX_AI_KEY_ALGORITHM, a as CORTEX_AI_KEY_ENVELOPE_VERSION, u as decryptOpenRouterApiKey, l as encryptOpenRouterApiKey, c as getMaskedOpenRouterKey, d as getOpenRouterKeyEnvelopeStatus };
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=1e4,h="https://openrouter.ai/api/v1/auth/key",y="https://api.pexels.com/v1/curated?per_page=1",p="https://api.unsplash.com/photos?per_page=1";async function c(t,s,e){const n=new AbortController,u=setTimeout(()=>n.abort(),f);try{const r=await t(s,{cache:"no-store",headers:{Accept:"application/json",...e},signal:n.signal});return{body:await r.json().catch(()=>null),status:r.status}}catch(r){return{failed:r instanceof Error&&r.name==="AbortError"?"The provider did not answer within 10 seconds.":r instanceof Error?r.message:"The provider could not be reached."}}finally{clearTimeout(u)}}function a(t,s){return{message:`${t} could not be reached to check the key (${s}). Check the connection and try again.`,ok:!1,reason:"unreachable"}}function i(t){return{message:t,ok:!1,reason:"invalid"}}async function d(t){const s=t.apiKey.trim();if(!s)return i("Enter an OpenRouter API key.");if(!s.startsWith("sk-or-"))return i('That does not look like an OpenRouter key: they start with "sk-or-".');const e=await c(t.fetch||globalThis.fetch,h,{Authorization:`Bearer ${s}`});if("failed"in e)return a("OpenRouter",e.failed);if(e.status===401||e.status===403)return i("OpenRouter rejected this key. Copy it again from openrouter.ai/keys.");if(e.status<200||e.status>=300)return a("OpenRouter",`HTTP ${e.status}`);const n=e.body&&typeof e.body=="object"&&"data"in e.body?e.body.data:void 0,u=typeof n?.label=="string"?n.label.trim():"",r=n?.is_free_tier===!0,l=typeof n?.limit_remaining=="number"?n.limit_remaining:null,o=[];return u&&o.push(`key "${u}"`),r?o.push("free tier: only free models until you add credits"):l!==null&&o.push(`$${l.toFixed(2)} of credit left`),{detail:o.length>0?o.join(" · "):null,isFreeTier:n?r:null,ok:!0}}async function k(t){const s=t.apiKey.trim();if(!s)return i("Enter a Pexels API key.");const e=await c(t.fetch||globalThis.fetch,y,{Authorization:s});return"failed"in e?a("Pexels",e.failed):e.status===401||e.status===403?i("Pexels rejected this key. Copy it again from pexels.com/api."):e.status===429?{detail:"Pexels accepted the key (its hourly quota is currently exhausted).",isFreeTier:null,ok:!0}:e.status<200||e.status>=300?a("Pexels",`HTTP ${e.status}`):{detail:null,isFreeTier:null,ok:!0}}async function T(t){const s=t.accessKey.trim();if(!s)return i("Enter an Unsplash access key.");const e=await c(t.fetch||globalThis.fetch,p,{Authorization:`Client-ID ${s}`});return"failed"in e?a("Unsplash",e.failed):e.status===401?i("Unsplash rejected this key. Use the Access Key (not the Secret Key) from unsplash.com/developers."):e.status===403||e.status===429?{detail:"Unsplash accepted the key (its demo quota is currently exhausted).",isFreeTier:null,ok:!0}:e.status<200||e.status>=300?a("Unsplash",`HTTP ${e.status}`):{detail:null,isFreeTier:null,ok:!0}}exports.verifyOpenRouterApiKey=d;exports.verifyPexelsApiKey=k;exports.verifyUnsplashAccessKey=T;
1
+ async function e(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),1e4);try{let i=await e(t,{cache:`no-store`,headers:{Accept:`application/json`,...n},signal:r.signal});return{body:await i.json().catch(()=>null),status:i.status}}catch(e){return{failed:e instanceof Error&&e.name===`AbortError`?`The provider did not answer within 10 seconds.`:e instanceof Error?e.message:`The provider could not be reached.`}}finally{clearTimeout(i)}}function t(e,t){return{message:`${e} could not be reached to check the key (${t}). Check the connection and try again.`,ok:!1,reason:`unreachable`}}function n(e){return{message:e,ok:!1,reason:`invalid`}}async function r(r){let i=r.apiKey.trim();if(!i)return n(`Enter an OpenRouter API key.`);if(!i.startsWith(`sk-or-`))return n(`That does not look like an OpenRouter key: they start with "sk-or-".`);let a=await e(r.fetch||globalThis.fetch,`https://openrouter.ai/api/v1/auth/key`,{Authorization:`Bearer ${i}`});if(`failed`in a)return t(`OpenRouter`,a.failed);if(a.status===401||a.status===403)return n(`OpenRouter rejected this key. Copy it again from openrouter.ai/keys.`);if(a.status<200||a.status>=300)return t(`OpenRouter`,`HTTP ${a.status}`);let o=a.body&&typeof a.body==`object`&&`data`in a.body?a.body.data:void 0,s=typeof o?.label==`string`?o.label.trim():``,c=o?.is_free_tier===!0,l=typeof o?.limit_remaining==`number`?o.limit_remaining:null,u=[];return s&&u.push(`key "${s}"`),c?u.push(`free tier: only free models until you add credits`):l!==null&&u.push(`$${l.toFixed(2)} of credit left`),{detail:u.length>0?u.join(` · `):null,isFreeTier:o?c:null,ok:!0}}async function i(r){let i=r.apiKey.trim();if(!i)return n(`Enter a Pexels API key.`);let a=await e(r.fetch||globalThis.fetch,`https://api.pexels.com/v1/curated?per_page=1`,{Authorization:i});return`failed`in a?t(`Pexels`,a.failed):a.status===401||a.status===403?n(`Pexels rejected this key. Copy it again from pexels.com/api.`):a.status===429?{detail:`Pexels accepted the key (its hourly quota is currently exhausted).`,isFreeTier:null,ok:!0}:a.status<200||a.status>=300?t(`Pexels`,`HTTP ${a.status}`):{detail:null,isFreeTier:null,ok:!0}}async function a(r){let i=r.accessKey.trim();if(!i)return n(`Enter an Unsplash access key.`);let a=await e(r.fetch||globalThis.fetch,`https://api.unsplash.com/photos?per_page=1`,{Authorization:`Client-ID ${i}`});return`failed`in a?t(`Unsplash`,a.failed):a.status===401?n(`Unsplash rejected this key. Use the Access Key (not the Secret Key) from unsplash.com/developers.`):a.status===403||a.status===429?{detail:`Unsplash accepted the key (its demo quota is currently exhausted).`,isFreeTier:null,ok:!0}:a.status<200||a.status>=300?t(`Unsplash`,`HTTP ${a.status}`):{detail:null,isFreeTier:null,ok:!0}}exports.verifyOpenRouterApiKey=r,exports.verifyPexelsApiKey=i,exports.verifyUnsplashAccessKey=a;
@@ -1,69 +1,80 @@
1
- const h = "https://openrouter.ai/api/v1/auth/key", f = "https://api.pexels.com/v1/curated?per_page=1", d = "https://api.unsplash.com/photos?per_page=1";
2
- async function c(t, s, e) {
3
- const n = new AbortController(), u = setTimeout(() => n.abort(), 1e4);
4
- try {
5
- const r = await t(s, {
6
- cache: "no-store",
7
- headers: { Accept: "application/json", ...e },
8
- signal: n.signal
9
- });
10
- return { body: await r.json().catch(() => null), status: r.status };
11
- } catch (r) {
12
- return {
13
- failed: r instanceof Error && r.name === "AbortError" ? "The provider did not answer within 10 seconds." : r instanceof Error ? r.message : "The provider could not be reached."
14
- };
15
- } finally {
16
- clearTimeout(u);
17
- }
1
+ async function e(e, t, n) {
2
+ let r = new AbortController(), i = setTimeout(() => r.abort(), 1e4);
3
+ try {
4
+ let i = await e(t, {
5
+ cache: "no-store",
6
+ headers: {
7
+ Accept: "application/json",
8
+ ...n
9
+ },
10
+ signal: r.signal
11
+ });
12
+ return {
13
+ body: await i.json().catch(() => null),
14
+ status: i.status
15
+ };
16
+ } catch (e) {
17
+ return { failed: e instanceof Error && e.name === "AbortError" ? "The provider did not answer within 10 seconds." : e instanceof Error ? e.message : "The provider could not be reached." };
18
+ } finally {
19
+ clearTimeout(i);
20
+ }
18
21
  }
19
- function a(t, s) {
20
- return {
21
- message: `${t} could not be reached to check the key (${s}). Check the connection and try again.`,
22
- ok: !1,
23
- reason: "unreachable"
24
- };
22
+ function t(e, t) {
23
+ return {
24
+ message: `${e} could not be reached to check the key (${t}). Check the connection and try again.`,
25
+ ok: !1,
26
+ reason: "unreachable"
27
+ };
25
28
  }
26
- function i(t) {
27
- return { message: t, ok: !1, reason: "invalid" };
29
+ function n(e) {
30
+ return {
31
+ message: e,
32
+ ok: !1,
33
+ reason: "invalid"
34
+ };
28
35
  }
29
- async function p(t) {
30
- const s = t.apiKey.trim();
31
- if (!s)
32
- return i("Enter an OpenRouter API key.");
33
- if (!s.startsWith("sk-or-"))
34
- return i('That does not look like an OpenRouter key: they start with "sk-or-".');
35
- const e = await c(t.fetch || globalThis.fetch, h, {
36
- Authorization: `Bearer ${s}`
37
- });
38
- if ("failed" in e)
39
- return a("OpenRouter", e.failed);
40
- if (e.status === 401 || e.status === 403)
41
- return i("OpenRouter rejected this key. Copy it again from openrouter.ai/keys.");
42
- if (e.status < 200 || e.status >= 300)
43
- return a("OpenRouter", `HTTP ${e.status}`);
44
- const n = e.body && typeof e.body == "object" && "data" in e.body ? e.body.data : void 0, u = typeof n?.label == "string" ? n.label.trim() : "", r = n?.is_free_tier === !0, l = typeof n?.limit_remaining == "number" ? n.limit_remaining : null, o = [];
45
- return u && o.push(`key "${u}"`), r ? o.push("free tier: only free models until you add credits") : l !== null && o.push(`$${l.toFixed(2)} of credit left`), { detail: o.length > 0 ? o.join(" · ") : null, isFreeTier: n ? r : null, ok: !0 };
36
+ async function r(r) {
37
+ let i = r.apiKey.trim();
38
+ if (!i) return n("Enter an OpenRouter API key.");
39
+ if (!i.startsWith("sk-or-")) return n("That does not look like an OpenRouter key: they start with \"sk-or-\".");
40
+ let a = await e(r.fetch || globalThis.fetch, "https://openrouter.ai/api/v1/auth/key", { Authorization: `Bearer ${i}` });
41
+ if ("failed" in a) return t("OpenRouter", a.failed);
42
+ if (a.status === 401 || a.status === 403) return n("OpenRouter rejected this key. Copy it again from openrouter.ai/keys.");
43
+ if (a.status < 200 || a.status >= 300) return t("OpenRouter", `HTTP ${a.status}`);
44
+ let o = a.body && typeof a.body == "object" && "data" in a.body ? a.body.data : void 0, s = typeof o?.label == "string" ? o.label.trim() : "", c = o?.is_free_tier === !0, l = typeof o?.limit_remaining == "number" ? o.limit_remaining : null, u = [];
45
+ return s && u.push(`key "${s}"`), c ? u.push("free tier: only free models until you add credits") : l !== null && u.push(`$${l.toFixed(2)} of credit left`), {
46
+ detail: u.length > 0 ? u.join(" · ") : null,
47
+ isFreeTier: o ? c : null,
48
+ ok: !0
49
+ };
46
50
  }
47
- async function y(t) {
48
- const s = t.apiKey.trim();
49
- if (!s)
50
- return i("Enter a Pexels API key.");
51
- const e = await c(t.fetch || globalThis.fetch, f, {
52
- Authorization: s
53
- });
54
- return "failed" in e ? a("Pexels", e.failed) : e.status === 401 || e.status === 403 ? i("Pexels rejected this key. Copy it again from pexels.com/api.") : e.status === 429 ? { detail: "Pexels accepted the key (its hourly quota is currently exhausted).", isFreeTier: null, ok: !0 } : e.status < 200 || e.status >= 300 ? a("Pexels", `HTTP ${e.status}`) : { detail: null, isFreeTier: null, ok: !0 };
51
+ async function i(r) {
52
+ let i = r.apiKey.trim();
53
+ if (!i) return n("Enter a Pexels API key.");
54
+ let a = await e(r.fetch || globalThis.fetch, "https://api.pexels.com/v1/curated?per_page=1", { Authorization: i });
55
+ return "failed" in a ? t("Pexels", a.failed) : a.status === 401 || a.status === 403 ? n("Pexels rejected this key. Copy it again from pexels.com/api.") : a.status === 429 ? {
56
+ detail: "Pexels accepted the key (its hourly quota is currently exhausted).",
57
+ isFreeTier: null,
58
+ ok: !0
59
+ } : a.status < 200 || a.status >= 300 ? t("Pexels", `HTTP ${a.status}`) : {
60
+ detail: null,
61
+ isFreeTier: null,
62
+ ok: !0
63
+ };
55
64
  }
56
- async function k(t) {
57
- const s = t.accessKey.trim();
58
- if (!s)
59
- return i("Enter an Unsplash access key.");
60
- const e = await c(t.fetch || globalThis.fetch, d, {
61
- Authorization: `Client-ID ${s}`
62
- });
63
- return "failed" in e ? a("Unsplash", e.failed) : e.status === 401 ? i("Unsplash rejected this key. Use the Access Key (not the Secret Key) from unsplash.com/developers.") : e.status === 403 || e.status === 429 ? { detail: "Unsplash accepted the key (its demo quota is currently exhausted).", isFreeTier: null, ok: !0 } : e.status < 200 || e.status >= 300 ? a("Unsplash", `HTTP ${e.status}`) : { detail: null, isFreeTier: null, ok: !0 };
65
+ async function a(r) {
66
+ let i = r.accessKey.trim();
67
+ if (!i) return n("Enter an Unsplash access key.");
68
+ let a = await e(r.fetch || globalThis.fetch, "https://api.unsplash.com/photos?per_page=1", { Authorization: `Client-ID ${i}` });
69
+ return "failed" in a ? t("Unsplash", a.failed) : a.status === 401 ? n("Unsplash rejected this key. Use the Access Key (not the Secret Key) from unsplash.com/developers.") : a.status === 403 || a.status === 429 ? {
70
+ detail: "Unsplash accepted the key (its demo quota is currently exhausted).",
71
+ isFreeTier: null,
72
+ ok: !0
73
+ } : a.status < 200 || a.status >= 300 ? t("Unsplash", `HTTP ${a.status}`) : {
74
+ detail: null,
75
+ isFreeTier: null,
76
+ ok: !0
77
+ };
64
78
  }
65
- export {
66
- p as verifyOpenRouterApiKey,
67
- y as verifyPexelsApiKey,
68
- k as verifyUnsplashAccessKey
69
- };
79
+ //#endregion
80
+ export { r as verifyOpenRouterApiKey, i as verifyPexelsApiKey, a as verifyUnsplashAccessKey };
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./ai-model-registry.cjs.js"),r="Cortex AI OpenRouter model catalog can only be imported from server-side code.";function n(){if(!(typeof window>"u"))throw new Error(r)}function s(){const e=new URL(`${o.CORTEX_AI_OPENROUTER_BASE_URL}/models`);return e.searchParams.set("supported_parameters",o.CORTEX_AI_REQUIRED_MODEL_PARAMETERS.join(",")),e.searchParams.set("output_modalities","text"),e.toString()}async function i(e){n();const t=await(e?.fetch||globalThis.fetch)(s(),{cache:"no-store",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Failed to load OpenRouter models: ${t.status} ${t.statusText}`);return o.filterCortexAiCompatibleOpenRouterModels(await t.json(),e?.now)}exports.listCortexAiCompatibleOpenRouterModels=i;
1
+ const e=require("./ai-model-registry.cjs.js");var t=`Cortex AI OpenRouter model catalog can only be imported from server-side code.`;function n(){if(typeof window<`u`)throw Error(t)}function r(){let t=new URL(`${e.CORTEX_AI_OPENROUTER_BASE_URL}/models`);return t.searchParams.set(`supported_parameters`,e.CORTEX_AI_REQUIRED_MODEL_PARAMETERS.join(`,`)),t.searchParams.set(`output_modalities`,`text`),t.toString()}async function i(t){n();let i=await(t?.fetch||globalThis.fetch)(r(),{cache:`no-store`,headers:{Accept:`application/json`}});if(!i.ok)throw Error(`Failed to load OpenRouter models: ${i.status} ${i.statusText}`);return e.filterCortexAiCompatibleOpenRouterModels(await i.json(),t?.now)}exports.listCortexAiCompatibleOpenRouterModels=i;
@@ -1,25 +1,21 @@
1
- import { filterCortexAiCompatibleOpenRouterModels as o, CORTEX_AI_OPENROUTER_BASE_URL as r, CORTEX_AI_REQUIRED_MODEL_PARAMETERS as n } from "./ai-model-registry.es.js";
2
- const s = "Cortex AI OpenRouter model catalog can only be imported from server-side code.";
3
- function a() {
4
- if (!(typeof window > "u"))
5
- throw new Error(s);
6
- }
1
+ import { CORTEX_AI_OPENROUTER_BASE_URL as e, CORTEX_AI_REQUIRED_MODEL_PARAMETERS as t, filterCortexAiCompatibleOpenRouterModels as n } from "./ai-model-registry.es.js";
2
+ //#region libs/cortex/src/lib/ai-model-catalog.ts
3
+ var r = "Cortex AI OpenRouter model catalog can only be imported from server-side code.";
7
4
  function i() {
8
- const e = new URL(`${r}/models`);
9
- return e.searchParams.set("supported_parameters", n.join(",")), e.searchParams.set("output_modalities", "text"), e.toString();
5
+ if (typeof window < "u") throw Error(r);
6
+ }
7
+ function a() {
8
+ let n = new URL(`${e}/models`);
9
+ return n.searchParams.set("supported_parameters", t.join(",")), n.searchParams.set("output_modalities", "text"), n.toString();
10
10
  }
11
- async function p(e) {
12
- a();
13
- const t = await (e?.fetch || globalThis.fetch)(i(), {
14
- cache: "no-store",
15
- headers: {
16
- Accept: "application/json"
17
- }
18
- });
19
- if (!t.ok)
20
- throw new Error(`Failed to load OpenRouter models: ${t.status} ${t.statusText}`);
21
- return o(await t.json(), e?.now);
11
+ async function o(e) {
12
+ i();
13
+ let t = await (e?.fetch || globalThis.fetch)(a(), {
14
+ cache: "no-store",
15
+ headers: { Accept: "application/json" }
16
+ });
17
+ if (!t.ok) throw Error(`Failed to load OpenRouter models: ${t.status} ${t.statusText}`);
18
+ return n(await t.json(), e?.now);
22
19
  }
23
- export {
24
- p as listCortexAiCompatibleOpenRouterModels
25
- };
20
+ //#endregion
21
+ export { o as listCortexAiCompatibleOpenRouterModels };
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("ai"),N="https://openrouter.ai/api/v1",b="openrouter/free",u=["nvidia/nemotron-3-super-120b-a12b:free","nvidia/nemotron-3-ultra-550b-a55b:free","thinkingmachines/inkling:free","nex-agi/nex-n2.5-pro:free","poolside/laguna-s-2.1:free","thinkingmachines/inkling-small:free","inclusionai/ling-3.0-flash-vl:free"],x=["tools","structured_outputs"],k={frequencyPenalty:"frequency_penalty",logitBias:"logit_bias",presencePenalty:"presence_penalty",seed:"seed",stopSequences:"stop",temperature:"temperature",topK:"top_k",topP:"top_p"},F={defaultFreeRouter:b,defaultStructuredOutputModel:u[0],defaultToolCallingModel:u[0],freeFallbacks:u,structuredJsonPreferred:u,toolCallingPreferred:u};class R extends Error{attempts;constructor(t,r,n){super(t),this.name="CortexAiRoutingError",this.attempts=r,this.cause=n}}function m(e){return Array.from(new Set(e.filter(Boolean)))}function c(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function d(e){return typeof e=="string"&&e.trim()?e.trim():null}function A(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function f(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function C(e){const t=c(e);return t?Object.fromEntries(Object.entries(t).filter(([,r])=>r!=null).map(([r,n])=>[r,String(n)])):{}}function I(e){const t=new Set(e);return x.every(r=>t.has(r))}function w(e){const t=c(e.architecture);return A(t?.output_modalities).includes("text")}function U(e){if(e==null)return null;if(typeof e=="number")return e>1e10?e:e*1e3;if(typeof e=="string"&&e.trim()){const t=Date.parse(e);return Number.isFinite(t)?t:null}return null}function B(e,t){const r=U(e);return r!==null&&r<=t.getTime()}function q(e){const t=c(e.top_provider);return f(e.context_length)??f(e.contextLength)??f(t?.context_length)??null}function X(e){const t=e.expiration_date??e.expirationDate;return typeof t=="string"&&t.trim()?t.trim():null}function y(e){return!!(e&&u.includes(e))}function j(e){const t=c(e);if(!t)return null;const r=d(t.modelId),n=d(t.name),i=A(t.supportedParameters),s=d(t.updatedAt);return!r||!n||!s||!I(i)?null:{contextLength:f(t.contextLength),modelId:r,name:n,pricing:C(t.pricing),supportedParameters:i,updatedAt:s}}function G(e,t=new Date){return{contextLength:e.contextLength,modelId:e.id,name:e.name,pricing:e.pricing,supportedParameters:[...e.supportedParameters],updatedAt:t.toISOString()}}function K(e,t=new Date){const r=c(e),n=Array.isArray(e)?e:Array.isArray(r?.data)?r.data:[],i=[];for(const s of n){const o=c(s),l=d(o?.id),a=d(o?.name),M=A(o?.supported_parameters);!o||!l||!a||!w(o)||B(o.expiration_date,t)||!I(M)||i.push({contextLength:q(o),created:f(o.created),expirationDate:X(o),id:l,name:a,pricing:C(o.pricing),supportedParameters:M})}return i.sort((s,o)=>s.name.localeCompare(o.name))}function Y(e){return m([e?.modelId||u[0],...e?.fallbackModelIds||u])}function $(e){const t=e.requestedModelId?.trim()||null;if(e.credentialSource==="env")return{credentialSource:e.credentialSource,ignoredRequestedModelId:t&&!y(t)?t:null,modelIds:[...u],modelSelection:null};const r=m(e.fallbackModelIds?.length?e.fallbackModelIds:u),n=e.credentialSource==="stored"?e.selectedModel?.modelId||r[0]:t||e.selectedModel?.modelId||r[0];return{credentialSource:e.credentialSource,ignoredRequestedModelId:e.credentialSource==="stored"&&t&&t!==n?t:null,modelIds:m([n,...r]),modelSelection:e.selectedModel||null}}function z(e,t){const r=t.modelSelection;if(!r||r.modelId!==t.modelId)return e;const n=new Set(r.supportedParameters),i=Object.entries(k).filter(([o,l])=>o in e&&!n.has(l)).map(([o])=>o);if(i.length===0)return e;const s={...e};for(const o of i)delete s[o];return s}function p(e,t){if(!e||typeof e!="object"||!(t in e))return null;const r=e[t],n=typeof r=="number"?r:Number(r);return Number.isFinite(n)?n:null}function _(e){if(D.APICallError.isInstance(e))return e.statusCode??null;const t=p(e,"statusCode")??p(e,"status");if(t)return t;if(e&&typeof e=="object"&&"response"in e){const r=e.response,n=p(r,"status");if(n)return n}return e&&typeof e=="object"&&"cause"in e?_(e.cause):null}function h(e){return e!==null&&Number.isInteger(e)&&e>=100&&e<=599}function S(e){if(typeof e!="string"||!e.trim().startsWith("{"))return null;try{return c(JSON.parse(e))}catch{return null}}function T(e,t=0){const r=c(e);if(!r||t>8)return null;const n=[r,c(r.data),S(r.responseBody),S(r.text)];for(const i of n){const s=c(i?.error),o=p(s,"code")??p(s,"status");if(h(o))return o}return T(r.cause,t+1)}function O(e){const t=_(e);return h(t)?t:T(e)}function P(e){return O(e)===429}const H=["message","error","text","responseBody","data","cause"];function E(e,t=0){if(!e||t>8)return"";if(typeof e!="object")return String(e);const r=e,n=e instanceof Error?[e.message]:[];for(const i of H)i==="message"&&e instanceof Error||n.push(E(r[i],t+1));return Array.from(new Set(n.filter(Boolean))).join(`
2
- `)}const J=/No endpoints found|no longer available|not available as a free model|transitioned to a paid model|unavailable for free|paid version is available|is not a valid model ID/i,W=/not found|does not exist|unknown model|no such model/i;function L(e){const t=O(e);if(t===429||t===404)return!0;const r=E(e);return J.test(r)?!0:t===400&&W.test(r)}function g(e,t=900){const r=e.replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t-1).trimEnd()}...`:r}function Q(e){const t=E(e);return t?g(t):"Unknown OpenRouter error."}function V(e,t="Cortex AI request failed."){if(e instanceof R){const r=e.attempts.map(o=>o.errorMessage).filter(o=>!!o?.trim()),n=r[0],i=r[r.length-1],s=g(E(e.cause));return n&&i&&n!==i?`First model error: ${n} Last model error: ${i}`:i||n||s||e.message}return g(E(e))||t}async function Z(e){const t=m(e.modelIds),r=e.shouldRetry||L;let n=[],i=null;for(const s of t)try{const o=await e.execute(s);return n=[...n,{modelId:s,rateLimited:!1,status:"success"}],{attempts:n,modelId:s,result:o}}catch(o){const l=P(o),a=r(o);if(i=o,n=[...n,{errorMessage:Q(o),modelId:s,rateLimited:l,status:l?"rate_limited":a?"retried":"failed"}],!a)throw new R(`OpenRouter request failed for model "${s}".`,n,o)}throw new R("OpenRouter fallback exhausted all configured Cortex AI models.",n,i)}exports.CORTEX_AI_FREE_MODEL_FALLBACK_REGISTRY=u;exports.CORTEX_AI_MODEL_REGISTRY=F;exports.CORTEX_AI_OPENROUTER_BASE_URL=N;exports.CORTEX_AI_OPENROUTER_FREE_ROUTER_MODEL=b;exports.CORTEX_AI_REQUIRED_MODEL_PARAMETERS=x;exports.CortexAiRoutingError=R;exports.buildCortexAiModelFallbackChain=Y;exports.buildCortexAiRoutingPolicy=$;exports.createCortexAiStoredModelSelection=G;exports.filterCortexAiCompatibleOpenRouterModels=K;exports.getHttpStatusCode=_;exports.getOpenRouterErrorStatus=O;exports.isCortexAiFreeModelId=y;exports.isOpenRouterRateLimitError=P;exports.isOpenRouterRecoverableRoutingError=L;exports.omitUnsupportedCortexAiModelOptions=z;exports.runWithCortexAiModelFallback=Z;exports.safeParseCortexAiModelSelection=j;exports.summarizeCortexAiRoutingError=V;
1
+ let e=require("ai");var t=`https://openrouter.ai/api/v1`,n=`openrouter/free`,r=[`nvidia/nemotron-3-super-120b-a12b:free`,`nvidia/nemotron-3-ultra-550b-a55b:free`,`thinkingmachines/inkling:free`,`nex-agi/nex-n2.5-pro:free`,`poolside/laguna-s-2.1:free`,`thinkingmachines/inkling-small:free`,`inclusionai/ling-3.0-flash-vl:free`],i=[`tools`,`structured_outputs`],a={frequencyPenalty:`frequency_penalty`,logitBias:`logit_bias`,presencePenalty:`presence_penalty`,seed:`seed`,stopSequences:`stop`,temperature:`temperature`,topK:`top_k`,topP:`top_p`},o={defaultFreeRouter:n,defaultStructuredOutputModel:r[0],defaultToolCallingModel:r[0],freeFallbacks:r,structuredJsonPreferred:r,toolCallingPreferred:r},s=class extends Error{attempts;constructor(e,t,n){super(e),this.name=`CortexAiRoutingError`,this.attempts=t,this.cause=n}};function c(e){return Array.from(new Set(e.filter(Boolean)))}function l(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function u(e){return typeof e==`string`&&e.trim()?e.trim():null}function d(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim().length>0):[]}function f(e){let t=typeof e==`number`?e:Number(e);return Number.isFinite(t)?t:null}function p(e){let t=l(e);return t?Object.fromEntries(Object.entries(t).filter(([,e])=>e!=null).map(([e,t])=>[e,String(t)])):{}}function m(e){let t=new Set(e);return i.every(e=>t.has(e))}function h(e){return d(l(e.architecture)?.output_modalities).includes(`text`)}function g(e){if(e==null)return null;if(typeof e==`number`)return e>1e10?e:e*1e3;if(typeof e==`string`&&e.trim()){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}function _(e,t){let n=g(e);return n!==null&&n<=t.getTime()}function v(e){let t=l(e.top_provider);return f(e.context_length)??f(e.contextLength)??f(t?.context_length)??null}function y(e){let t=e.expiration_date??e.expirationDate;return typeof t==`string`&&t.trim()?t.trim():null}function b(e){return!!(e&&r.includes(e))}function x(e){let t=l(e);if(!t)return null;let n=u(t.modelId),r=u(t.name),i=d(t.supportedParameters),a=u(t.updatedAt);return!n||!r||!a||!m(i)?null:{contextLength:f(t.contextLength),modelId:n,name:r,pricing:p(t.pricing),supportedParameters:i,updatedAt:a}}function S(e,t=new Date){return{contextLength:e.contextLength,modelId:e.id,name:e.name,pricing:e.pricing,supportedParameters:[...e.supportedParameters],updatedAt:t.toISOString()}}function C(e,t=new Date){let n=l(e),r=Array.isArray(e)?e:Array.isArray(n?.data)?n.data:[],i=[];for(let e of r){let n=l(e),r=u(n?.id),a=u(n?.name),o=d(n?.supported_parameters);n&&r&&a&&h(n)&&!_(n.expiration_date,t)&&m(o)&&i.push({contextLength:v(n),created:f(n.created),expirationDate:y(n),id:r,name:a,pricing:p(n.pricing),supportedParameters:o})}return i.sort((e,t)=>e.name.localeCompare(t.name))}function w(e){return c([e?.modelId||r[0],...e?.fallbackModelIds||r])}function T(e){let t=e.requestedModelId?.trim()||null;if(e.credentialSource===`env`)return{credentialSource:e.credentialSource,ignoredRequestedModelId:t&&!b(t)?t:null,modelIds:[...r],modelSelection:null};let n=c(e.fallbackModelIds?.length?e.fallbackModelIds:r),i=e.credentialSource===`stored`?e.selectedModel?.modelId||n[0]:t||e.selectedModel?.modelId||n[0];return{credentialSource:e.credentialSource,ignoredRequestedModelId:e.credentialSource===`stored`&&t&&t!==i?t:null,modelIds:c([i,...n]),modelSelection:e.selectedModel||null}}function E(e,t){let n=t.modelSelection;if(!n||n.modelId!==t.modelId)return e;let r=new Set(n.supportedParameters),i=Object.entries(a).filter(([t,n])=>t in e&&!r.has(n)).map(([e])=>e);if(i.length===0)return e;let o={...e};for(let e of i)delete o[e];return o}function D(e,t){if(!e||typeof e!=`object`||!(t in e))return null;let n=e[t],r=typeof n==`number`?n:Number(n);return Number.isFinite(r)?r:null}function O(t){if(e.APICallError.isInstance(t))return t.statusCode??null;let n=D(t,`statusCode`)??D(t,`status`);if(n)return n;if(t&&typeof t==`object`&&`response`in t){let e=t.response,n=D(e,`status`);if(n)return n}return t&&typeof t==`object`&&`cause`in t?O(t.cause):null}function k(e){return e!==null&&Number.isInteger(e)&&e>=100&&e<=599}function A(e){if(typeof e!=`string`||!e.trim().startsWith(`{`))return null;try{return l(JSON.parse(e))}catch{return null}}function j(e,t=0){let n=l(e);if(!n||t>8)return null;let r=[n,l(n.data),A(n.responseBody),A(n.text)];for(let e of r){let t=l(e?.error),n=D(t,`code`)??D(t,`status`);if(k(n))return n}return j(n.cause,t+1)}function M(e){let t=O(e);return k(t)?t:j(e)}function N(e){return M(e)===429}var P=[`message`,`error`,`text`,`responseBody`,`data`,`cause`];function F(e,t=0){if(!e||t>8)return``;if(typeof e!=`object`)return String(e);let n=e,r=e instanceof Error?[e.message]:[];for(let i of P)i===`message`&&e instanceof Error||r.push(F(n[i],t+1));return Array.from(new Set(r.filter(Boolean))).join(`
2
+ `)}var I=/No endpoints found|no longer available|not available as a free model|transitioned to a paid model|unavailable for free|paid version is available|is not a valid model ID/i,L=/not found|does not exist|unknown model|no such model/i;function R(e){let t=M(e);if(t===429||t===404)return!0;let n=F(e);return I.test(n)?!0:t===400&&L.test(n)}function z(e,t=900){let n=e.replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t-1).trimEnd()}...`:n}function B(e){let t=F(e);return t?z(t):`Unknown OpenRouter error.`}function V(e,t=`Cortex AI request failed.`){if(e instanceof s){let t=e.attempts.map(e=>e.errorMessage).filter(e=>!!e?.trim()),n=t[0],r=t[t.length-1],i=z(F(e.cause));return n&&r&&n!==r?`First model error: ${n} Last model error: ${r}`:r||n||i||e.message}return z(F(e))||t}async function H(e){let t=c(e.modelIds),n=e.shouldRetry||R,r=[],i=null;for(let a of t)try{let t=await e.execute(a);return r=[...r,{modelId:a,rateLimited:!1,status:`success`}],{attempts:r,modelId:a,result:t}}catch(e){let t=N(e),o=n(e);if(i=e,r=[...r,{errorMessage:B(e),modelId:a,rateLimited:t,status:t?`rate_limited`:o?`retried`:`failed`}],!o)throw new s(`OpenRouter request failed for model "${a}".`,r,e)}throw new s(`OpenRouter fallback exhausted all configured Cortex AI models.`,r,i)}exports.CORTEX_AI_FREE_MODEL_FALLBACK_REGISTRY=r,exports.CORTEX_AI_MODEL_REGISTRY=o,exports.CORTEX_AI_OPENROUTER_BASE_URL=t,exports.CORTEX_AI_OPENROUTER_FREE_ROUTER_MODEL=n,exports.CORTEX_AI_REQUIRED_MODEL_PARAMETERS=i,exports.CortexAiRoutingError=s,exports.buildCortexAiModelFallbackChain=w,exports.buildCortexAiRoutingPolicy=T,exports.createCortexAiStoredModelSelection=S,exports.filterCortexAiCompatibleOpenRouterModels=C,exports.getHttpStatusCode=O,exports.getOpenRouterErrorStatus=M,exports.isCortexAiFreeModelId=b,exports.isOpenRouterRateLimitError=N,exports.isOpenRouterRecoverableRoutingError=R,exports.omitUnsupportedCortexAiModelOptions=E,exports.runWithCortexAiModelFallback=H,exports.safeParseCortexAiModelSelection=x,exports.summarizeCortexAiRoutingError=V;