plugin-ai-api 1.0.24 → 1.0.25

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 (54) hide show
  1. package/dist/client/757.56952e321dc399b7.js +10 -0
  2. package/dist/client/index.js +1 -1
  3. package/dist/client-v2/757.db678ca1aa6c422c.js +10 -0
  4. package/dist/client-v2/index.js +1 -1
  5. package/dist/externalVersion.js +8 -8
  6. package/dist/locale/en-US.json +1 -0
  7. package/dist/locale/vi-VN.json +1 -0
  8. package/dist/locale/zh-CN.json +1 -0
  9. package/dist/server/billing.js +6 -1
  10. package/dist/server/collections/ai-api-config.js +6 -0
  11. package/dist/server/collections/ai-api-usage-records.js +1 -0
  12. package/dist/server/migrations/20260813000000-add-prompt-cache-tokens.js +69 -0
  13. package/dist/server/plugin.js +10 -0
  14. package/dist/server/resource/ai-api-config.js +5 -0
  15. package/dist/server/resource/ai-api-usage-monitor.js +3 -1
  16. package/dist/server/routes/chat-completions.js +89 -10
  17. package/dist/server/routes/completions.js +32 -10
  18. package/dist/server/services/file-processor.js +262 -0
  19. package/dist/server/usage.js +33 -3
  20. package/dist/server/utils/direct-llm-context.js +150 -15
  21. package/dist/server/utils/openai-format.js +21 -2
  22. package/dist/swagger.js +42 -3
  23. package/package.json +1 -1
  24. package/src/client-v2/pages/UsagePage.tsx +9 -0
  25. package/src/locale/en-US.json +1 -0
  26. package/src/locale/vi-VN.json +1 -0
  27. package/src/locale/zh-CN.json +1 -0
  28. package/src/server/__tests__/direct-llm-context.test.ts +87 -6
  29. package/src/server/__tests__/openai-format.test.ts +12 -2
  30. package/src/server/__tests__/request-body.test.ts +45 -2
  31. package/src/server/__tests__/usage-route.test.ts +120 -3
  32. package/src/server/__tests__/usage.test.ts +19 -0
  33. package/src/server/billing.ts +6 -1
  34. package/src/server/collections/ai-api-config.ts +8 -0
  35. package/src/server/collections/ai-api-role-permissions.ts +41 -41
  36. package/src/server/collections/ai-api-usage-records.ts +1 -0
  37. package/src/server/index.ts +10 -10
  38. package/src/server/middleware/rate-limit.ts +70 -70
  39. package/src/server/migrations/20260813000000-add-prompt-cache-tokens.ts +46 -0
  40. package/src/server/plugin.ts +20 -0
  41. package/src/server/resource/ai-api-config.ts +5 -0
  42. package/src/server/resource/ai-api-usage-monitor.ts +3 -0
  43. package/src/server/routes/chat-completions.ts +134 -11
  44. package/src/server/routes/completions.ts +33 -7
  45. package/src/server/services/__tests__/file-processor.test.ts +184 -0
  46. package/src/server/services/file-processor.ts +323 -0
  47. package/src/server/usage.ts +47 -1
  48. package/src/server/utils/direct-llm-context.ts +198 -20
  49. package/src/server/utils/openai-format.ts +25 -2
  50. package/src/server/utils/rate-limiter.ts +83 -83
  51. package/src/server/utils/resolve-service.ts +82 -82
  52. package/src/swagger.ts +45 -3
  53. package/dist/client/757.a01403fb7a1bea01.js +0 -10
  54. package/dist/client-v2/757.a117ce1cf7119cea.js +0 -10
@@ -0,0 +1,10 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ "use strict";(self.webpackChunkplugin_ai_api=self.webpackChunkplugin_ai_api||[]).push([["757"],{364:function(e,t,r){r.r(t),r.d(t,{default:function(){return y}});var n=r(155),a=r.n(n),l=r(59),o=r(185),s=r.n(o),u=r(694),i=r(650),c=r(630);function d(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function m(e,t,r,n,a,l,o){try{var s=e[l](o),u=s.value}catch(e){r(e);return}s.done?t(u):Promise.resolve(u).then(n,a)}function p(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r,n,a=null==e?null:"u">typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=a){var l=[],o=!0,s=!1;try{for(a=a.call(e);!(o=(r=a.next()).done)&&(l.push(r.value),!t||l.length!==t);o=!0);}catch(e){s=!0,n=e}finally{try{o||null==a.return||a.return()}finally{if(s)throw n}}return l}}(e,t)||function(e,t){if(e){if("string"==typeof e)return d(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if("Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r)return Array.from(r);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return d(e,t)}}(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var f=function(){return[s()().subtract(29,"day").startOf("day"),s()().endOf("day")]},v={requestCount:0,inputTokens:0,outputTokens:0,totalTokens:0,promptCacheTokens:0,costsByCurrency:[]};function y(){var e=(0,u.useFlowContext)(),t=(0,i.k)(),r=p(l.Form.useForm(),1)[0],o=p((0,n.useState)([]),2),s=o[0],d=o[1],y=p((0,n.useState)(v),2),h=y[0],S=y[1],b=p((0,n.useState)([]),2),g=b[0],k=b[1],I=p((0,n.useState)(!1),2),E=I[0],w=I[1],C=(0,n.useCallback)(function(t){var n;return(n=function(){var n,a,o,s,u,i,m,y,h,b,g;return function(e,t){var r,n,a,l={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),s=Object.defineProperty;return s(o,"next",{value:u(0)}),s(o,"throw",{value:u(1)}),s(o,"return",{value:u(2)}),"function"==typeof Symbol&&s(o,Symbol.iterator,{value:function(){return this}}),o;function u(s){return function(u){var i=[s,u];if(r)throw TypeError("Generator is already executing.");for(;o&&(o=0,i[0]&&(l=0)),l;)try{if(r=1,n&&(a=2&i[0]?n.return:i[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,i[1])).done)return a;switch(n=0,a&&(i=[2&i[0],a.value]),i[0]){case 0:case 1:a=i;break;case 4:return l.label++,{value:i[1],done:!1};case 5:l.label++,n=i[1],i=[0];continue;case 7:i=l.ops.pop(),l.trys.pop();continue;default:if(!(a=(a=l.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){l=0;continue}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){l.label=i[1];break}if(6===i[0]&&l.label<a[1]){l.label=a[1],a=i;break}if(a&&l.label<a[2]){l.label=a[2],l.ops.push(i);break}a[2]&&l.ops.pop(),l.trys.pop();continue}i=t.call(e,l)}catch(e){i=[6,e],n=0}finally{r=a=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}}}(this,function(k){switch(k.label){case 0:s=(o=p(null!=(n=(a=null!=t?t:r.getFieldsValue()).range)?n:f(),2))[0],u=o[1],i=[{startedAt:{$gte:s.toISOString(),$lte:u.toISOString()}}],void 0!==a.userId&&i.push({userId:a.userId}),a.resolvedService&&i.push({resolvedService:a.resolvedService}),a.resolvedModel&&i.push({resolvedModel:a.resolvedModel}),a.status&&i.push({status:a.status}),m={start:s.toISOString(),end:u.toISOString(),userId:a.userId,resolvedService:a.resolvedService,resolvedModel:a.resolvedModel,status:a.status},w(!0),k.label=1;case 1:return k.trys.push([1,3,4,5]),[4,Promise.all([e.api.request({url:"aiApiUsageRecords:list",method:"get",params:{pageSize:100,sort:"-startedAt",filter:{$and:i}}}),e.api.request({url:"aiApiUsageMonitor:summary",method:"get",params:m})])];case 2:return h=(y=p.apply(void 0,[k.sent(),2]))[0],b=y[1],d((0,c.m)(h,[])),S((0,c.m)(b,v)),[3,5];case 3:return g=k.sent(),l.message.error((0,c.g)(g)),[3,5];case 4:return w(!1),[7];case 5:return[2]}})},function(){var e=this,t=arguments;return new Promise(function(r,a){var l=n.apply(e,t);function o(e){m(l,r,a,o,s,"next",e)}function s(e){m(l,r,a,o,s,"throw",e)}o(void 0)})})()},[e.api,r]);(0,n.useEffect)(function(){var t=f();r.setFieldsValue({range:t}),C({range:t}),e.api.request({url:"ai:listLLMServices",method:"get"}).then(function(e){return k((0,c.m)(e,[]))}).catch(function(e){return l.message.error((0,c.g)(e))})},[e.api,r,C]);var x=h.costsByCurrency.length?h.costsByCurrency.map(function(e){return"".concat(e.totalCost," ").concat(e.currency)}).join(" + "):"0",T=[{title:t("Started at"),dataIndex:"startedAt",key:"startedAt",width:180},{title:t("User"),dataIndex:"userId",key:"userId",width:90},{title:t("Requested model"),dataIndex:"model",key:"model",width:170},{title:t("Resolved service"),dataIndex:"resolvedService",key:"resolvedService",width:170},{title:t("Resolved model"),dataIndex:"resolvedModel",key:"resolvedModel",width:170},{title:t("Input tokens"),dataIndex:"inputTokens",key:"inputTokens",width:110},{title:t("Output tokens"),dataIndex:"outputTokens",key:"outputTokens",width:110},{title:t("Total tokens"),dataIndex:"totalTokens",key:"totalTokens",width:110},{title:t("Prompt cache tokens"),dataIndex:"promptCacheTokens",key:"promptCacheTokens",width:140},{title:t("Cost"),key:"cost",width:130,render:function(e,t){var r;return null==t.estimatedCost?"-":"".concat(t.estimatedCost," ").concat(null!=(r=t.currency)?r:"")}},{title:t("Cost status"),dataIndex:"costStatus",key:"costStatus",width:130,render:function(e){return e?a().createElement(l.Tag,null,e):"-"}},{title:t("Status"),dataIndex:"status",key:"status",width:100},{title:t("Request ID"),dataIndex:"requestId",key:"requestId",width:240}];return a().createElement(l.Space,{direction:"vertical",size:16,style:{width:"100%"}},a().createElement(l.Card,{title:t("Usage filters"),size:"small"},a().createElement(l.Form,{form:r,layout:"inline",onFinish:function(e){return C(e)}},a().createElement(l.Form.Item,{name:"range",label:t("Time range"),rules:[{required:!0}]},a().createElement(l.DatePicker.RangePicker,{showTime:!0})),a().createElement(l.Form.Item,{name:"userId",label:t("User ID")},a().createElement(l.InputNumber,{min:1,style:{width:110}})),a().createElement(l.Form.Item,{name:"resolvedService",label:t("Resolved service")},a().createElement(l.Select,{allowClear:!0,showSearch:!0,optionFilterProp:"label",style:{width:190},options:g.map(function(e){return{label:e.title||e.name,value:e.name}})})),a().createElement(l.Form.Item,{name:"resolvedModel",label:t("Resolved model")},a().createElement(l.Input,{allowClear:!0,style:{width:180}})),a().createElement(l.Form.Item,{name:"status",label:t("Status")},a().createElement(l.Select,{allowClear:!0,style:{width:130},options:[{label:t("Succeeded"),value:"succeeded"},{label:t("Failed"),value:"failed"},{label:t("Started"),value:"started"}]})),a().createElement(l.Form.Item,null,a().createElement(l.Space,null,a().createElement(l.Button,{type:"primary",htmlType:"submit",loading:E},t("Apply filters")),a().createElement(l.Button,{onClick:function(){var e=f();r.setFieldsValue({range:e,userId:void 0,resolvedService:void 0,resolvedModel:void 0,status:void 0}),C({range:e})}},t("Reset")))))),a().createElement(l.Row,{gutter:[16,16]},a().createElement(l.Col,{xs:24,sm:12,lg:6},a().createElement(l.Card,{size:"small"},a().createElement(l.Statistic,{title:t("Requests"),value:h.requestCount}))),a().createElement(l.Col,{xs:24,sm:12,lg:6},a().createElement(l.Card,{size:"small"},a().createElement(l.Statistic,{title:t("Input tokens"),value:h.inputTokens}))),a().createElement(l.Col,{xs:24,sm:12,lg:6},a().createElement(l.Card,{size:"small"},a().createElement(l.Statistic,{title:t("Output tokens"),value:h.outputTokens}))),a().createElement(l.Col,{xs:24,sm:12,lg:6},a().createElement(l.Card,{size:"small"},a().createElement(l.Statistic,{title:t("Total tokens"),value:h.totalTokens}))),a().createElement(l.Col,{xs:24,sm:12,lg:6},a().createElement(l.Card,{size:"small"},a().createElement(l.Statistic,{title:t("Prompt cache tokens"),value:h.promptCacheTokens}))),a().createElement(l.Col,{xs:24},a().createElement(l.Card,{size:"small"},a().createElement(l.Statistic,{title:t("Total cost"),value:x})))),a().createElement(l.Card,{title:t("Usage records"),extra:a().createElement(l.Button,{onClick:function(){return C()}},t("Refresh"))},a().createElement(l.Table,{rowKey:"id",columns:T,dataSource:s,loading:E,scroll:{x:1600}})))}},650:function(e,t,r){r.d(t,{k:function(){return l}});var n=r(694),a=JSON.parse('{"UU":"plugin-ai-api"}');function l(){var e=(0,n.useFlowEngine)();return function(t){return e.context.t(t,{ns:[a.UU,"client"]})}}},630:function(e,t,r){function n(e,t){var r,n;return e&&(void 0===e?"undefined":e&&"u">typeof Symbol&&e.constructor===Symbol?"symbol":typeof e)=="object"?null!=(r=null==(n=e.data)?void 0:n.data)?r:t:t}function a(e){var t;return(null!=(t=Error)&&"u">typeof Symbol&&t[Symbol.hasInstance]?!!t[Symbol.hasInstance](e):e instanceof t)?e.message:String(e)}r.d(t,{g:function(){return a},m:function(){return n}})}}]);
@@ -7,4 +7,4 @@
7
7
  * For more information, please refer to: https://www.nocobase.com/agreement.
8
8
  */
9
9
 
10
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("@nocobase/client-v2"),require("dayjs"),require("react"),require("antd"),require("@nocobase/client"),require("@nocobase/plugin-acl/client"),require("@nocobase/flow-engine")):"function"==typeof define&&define.amd?define("plugin-ai-api",["@nocobase/client-v2","dayjs","react","antd","@nocobase/client","@nocobase/plugin-acl/client","@nocobase/flow-engine"],t):"object"==typeof exports?exports["plugin-ai-api"]=t(require("@nocobase/client-v2"),require("dayjs"),require("react"),require("antd"),require("@nocobase/client"),require("@nocobase/plugin-acl/client"),require("@nocobase/flow-engine")):e["plugin-ai-api"]=t(e["@nocobase/client-v2"],e.dayjs,e.react,e.antd,e["@nocobase/client"],e["@nocobase/plugin-acl/client"],e["@nocobase/flow-engine"])}(self,function(e,t,n,r,i,o,a){return function(){"use strict";var u,c,l,p={342:function(e){e.exports=i},485:function(t){t.exports=e},694:function(e){e.exports=a},79:function(e){e.exports=o},59:function(e){e.exports=r},185:function(e){e.exports=t},155:function(e){e.exports=n}},s={};function f(e){var t=s[e];if(void 0!==t)return t.exports;var n=s[e]={exports:{}};return p[e](n,n.exports,f),n.exports}f.m=p,f.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return f.d(t,{a:t}),t},f.d=function(e,t){for(var n in t)f.o(t,n)&&!f.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},f.f={},f.e=function(e){return Promise.all(Object.keys(f.f).reduce(function(t,n){return f.f[n](e,t),t},[]))},f.u=function(e){return""+e+"."+({123:"e6fe04c856ce6417",286:"01c0e3c5fff3cccb",302:"fc3a3491b4ec2dfd",562:"17a0a299d2e5152c",757:"a01403fb7a1bea01",902:"e74518750f1e4201",97:"72979a11a067a7c9"})[e]+".js"},f.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}}(),f.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},d={},f.l=function(e,t,n,r){if(d[e])return void d[e].push(t);if(void 0!==n)for(var i,o,a=document.getElementsByTagName("script"),u=0;u<a.length;u++){var c=a[u];if(c.getAttribute("src")==e||c.getAttribute("data-rspack")=="plugin-ai-api:"+n){i=c;break}}i||(o=!0,(i=document.createElement("script")).timeout=120,f.nc&&i.setAttribute("nonce",f.nc),i.setAttribute("data-rspack","plugin-ai-api:"+n),i.src=e),d[e]=[t];var l=function(t,n){i.onerror=i.onload=null,clearTimeout(p);var r=d[e];if(delete d[e],i.parentNode&&i.parentNode.removeChild(i),r&&r.forEach(function(e){return e(n)}),t)return t(n)},p=setTimeout(l.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=l.bind(null,i.onerror),i.onload=l.bind(null,i.onload),o&&document.head.appendChild(i)},f.r=function(e){"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},f.g.importScripts&&(b=f.g.location+"");var d,b,g=f.g.document;if(!b&&g&&(g.currentScript&&"SCRIPT"===g.currentScript.tagName.toUpperCase()&&(b=g.currentScript.src),!b)){var h=g.getElementsByTagName("script");if(h.length)for(var y=h.length-1;y>-1&&(!b||!/^http(s?):/.test(b));)b=h[y--].src}if(!b)throw Error("Automatic publicPath is not supported in this browser");f.p=b.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),u={889:0},f.f.j=function(e,t){var n=f.o(u,e)?u[e]:void 0;if(0!==n)if(n)t.push(n[2]);else{var r=new Promise(function(t,r){n=u[e]=[t,r]});t.push(n[2]=r);var i=f.p+f.u(e),o=Error();f.l(i,function(t){if(f.o(u,e)&&(0!==(n=u[e])&&(u[e]=void 0),n)){var r=t&&("load"===t.type?"missing":t.type),i=t&&t.target&&t.target.src;o.message="Loading chunk "+e+" failed.\n("+r+": "+i+")",o.name="ChunkLoadError",o.type=r,o.request=i,n[1](o)}},"chunk-"+e,e)}},c=function(e,t){var n,r,i=t[0],o=t[1],a=t[2],c=0;if(i.some(function(e){return 0!==u[e]})){for(n in o)f.o(o,n)&&(f.m[n]=o[n]);a&&a(f)}for(e&&e(t);c<i.length;c++)r=i[c],f.o(u,r)&&u[r]&&u[r][0](),u[r]=0},(l=self.webpackChunkplugin_ai_api=self.webpackChunkplugin_ai_api||[]).forEach(c.bind(null,0)),l.push=c.bind(null,l.push.bind(l));var v={};return!function(){var e="",t="u">typeof document?document.currentScript:null;if(t&&t.src){var n=t.src.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"");n.indexOf("/static/plugins/plugin-ai-api/dist/client/")>=0&&(e=n.replace(/\/[^\/]+$/,"/"))}if(!e){var r=window.__webpack_public_path__||"";r&&("/"!==r.charAt(r.length-1)&&(r+="/"),e=r+"static/plugins/plugin-ai-api/dist/client/")}if(!e){var i=window.__nocobase_modern_client_prefix__||"v",o="/"+(i=String(i).replace(/^\/+|\/+$/g,"")||"v")+"/";if(!(e=window.__nocobase_public_path__||"")&&window.location&&window.location.pathname){var a=window.location.pathname||"/",u=a.indexOf(o);e=u>=0?a.slice(0,u+1):"/"}e&&(e=e.replace(RegExp("/"+i+"/?$"),"/")),e||(e="/"),"/"!==e.charAt(e.length-1)&&(e+="/"),e+="static/plugins/plugin-ai-api/dist/client/"}f.p=e}(),!function(){f.r(v),f.d(v,{default:function(){return _}});var e=f(342),t=f(79),n=f.n(t),r="pm.plugin-ai-api.configuration",i=f(155),o=f.n(i);function a(e,t,n,r,i,o,a){try{var u=e[o](a),c=u.value}catch(e){n(e);return}u.done?t(c):Promise.resolve(c).then(r,i)}function u(e,t,n){return(u=s()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&l(i,n.prototype),i}).apply(null,arguments)}function c(e){return(c=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function l(e,t){return(l=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function p(e){var t="function"==typeof Map?new Map:void 0;return(p=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return u(e,arguments,c(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),l(n,e)})(e)}function s(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(s=function(){return!!e})()}var d=o().lazy(function(){return f.e("302").then(f.bind(f,581))}),b=o().lazy(function(){return f.e("97").then(f.bind(f,760))}),g=o().lazy(function(){return f.e("562").then(f.bind(f,641))}),h=o().lazy(function(){return f.e("123").then(f.bind(f,46))}),y=o().lazy(function(){return f.e("902").then(f.bind(f,77))}),m=o().lazy(function(){return f.e("757").then(f.bind(f,364))}),w=(0,e.lazy)(function(){return f.e("286").then(f.bind(f,421))},"AiApiRolePermissions").AiApiRolePermissions,_=function(e){var t;if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function i(){var e,t;if(!(this instanceof i))throw TypeError("Cannot call a class as a function");return e=i,t=arguments,e=c(e),function(e,t){var n;if(t&&("object"==((n=t)&&"u">typeof Symbol&&n.constructor===Symbol?"symbol":typeof n)||"function"==typeof t))return t;if(void 0===e)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(this,s()?Reflect.construct(e,t||[],c(this).constructor):e.apply(this,t))}return i.prototype=Object.create(e&&e.prototype,{constructor:{value:i,writable:!0,configurable:!0}}),e&&l(i,e),t=[{key:"load",value:function(){var e;return(e=function(){var e;return function(e,t){var n,r,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),u=Object.defineProperty;return u(a,"next",{value:c(0)}),u(a,"throw",{value:c(1)}),u(a,"return",{value:c(2)}),"function"==typeof Symbol&&u(a,Symbol.iterator,{value:function(){return this}}),a;function c(u){return function(c){var l=[u,c];if(n)throw TypeError("Generator is already executing.");for(;a&&(a=0,l[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&l[0]?r.return:l[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,l[1])).done)return i;switch(r=0,i&&(l=[2&l[0],i.value]),l[0]){case 0:case 1:i=l;break;case 4:return o.label++,{value:l[1],done:!1};case 5:o.label++,r=l[1],l=[0];continue;case 7:l=o.ops.pop(),o.trys.pop();continue;default:if(!(i=(i=o.trys).length>0&&i[i.length-1])&&(6===l[0]||2===l[0])){o=0;continue}if(3===l[0]&&(!i||l[1]>i[0]&&l[1]<i[3])){o.label=l[1];break}if(6===l[0]&&o.label<i[1]){o.label=i[1],i=l;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(l);break}i[2]&&o.ops.pop(),o.trys.pop();continue}l=t.call(e,o)}catch(e){l=[6,e],r=0}finally{n=i=0}if(5&l[0])throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}}(this,function(t){return this.app.pluginSettingsManager.add("ai-api",{icon:"ApiOutlined",title:this.t("AI API Gateway"),aclSnippet:r}),this.app.pluginSettingsManager.add("ai-api.config",{title:this.t("Configuration"),Component:d,aclSnippet:r,sort:1}),this.app.pluginSettingsManager.add("ai-api.model-pricing",{title:this.t("Model pricing"),Component:b,aclSnippet:r,sort:2}),this.app.pluginSettingsManager.add("ai-api.model-metadata",{title:this.t("Model metadata"),Component:g,aclSnippet:r,sort:3}),this.app.pluginSettingsManager.add("ai-api.user-permissions",{title:this.t("User LLM permissions"),Component:h,aclSnippet:"pm.plugin-ai-api.user-permissions",sort:4}),this.app.pluginSettingsManager.add("ai-api.user-quotas",{title:this.t("User quotas"),Component:y,aclSnippet:r,sort:5}),this.app.pluginSettingsManager.add("ai-api.usage",{title:this.t("Usage"),Component:m,aclSnippet:r,sort:6}),(null==(e=this.app.pm.get(n()))?void 0:e.settingsUI)&&e.settingsUI.addPermissionsTab(function(e){var t=e.t,n=e.TabLayout,r=e.activeRole;return{key:"aiApi",label:t("AI API",{ns:["plugin-ai-api","client"]}),sort:25,children:o().createElement(n,null,o().createElement(w,{role:r}))}}),[2]})},function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function u(e){a(o,r,i,u,c,"next",e)}function c(e){a(o,r,i,u,c,"throw",e)}u(void 0)})}).call(this)}}],function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}(i.prototype,t),i}(p(e.Plugin))}(),v}()});
10
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("@nocobase/client-v2"),require("dayjs"),require("react"),require("antd"),require("@nocobase/client"),require("@nocobase/plugin-acl/client"),require("@nocobase/flow-engine")):"function"==typeof define&&define.amd?define("plugin-ai-api",["@nocobase/client-v2","dayjs","react","antd","@nocobase/client","@nocobase/plugin-acl/client","@nocobase/flow-engine"],t):"object"==typeof exports?exports["plugin-ai-api"]=t(require("@nocobase/client-v2"),require("dayjs"),require("react"),require("antd"),require("@nocobase/client"),require("@nocobase/plugin-acl/client"),require("@nocobase/flow-engine")):e["plugin-ai-api"]=t(e["@nocobase/client-v2"],e.dayjs,e.react,e.antd,e["@nocobase/client"],e["@nocobase/plugin-acl/client"],e["@nocobase/flow-engine"])}(self,function(e,t,n,r,i,o,a){return function(){"use strict";var u,c,l,p={342:function(e){e.exports=i},485:function(t){t.exports=e},694:function(e){e.exports=a},79:function(e){e.exports=o},59:function(e){e.exports=r},185:function(e){e.exports=t},155:function(e){e.exports=n}},s={};function f(e){var t=s[e];if(void 0!==t)return t.exports;var n=s[e]={exports:{}};return p[e](n,n.exports,f),n.exports}f.m=p,f.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return f.d(t,{a:t}),t},f.d=function(e,t){for(var n in t)f.o(t,n)&&!f.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},f.f={},f.e=function(e){return Promise.all(Object.keys(f.f).reduce(function(t,n){return f.f[n](e,t),t},[]))},f.u=function(e){return""+e+"."+({123:"e6fe04c856ce6417",286:"01c0e3c5fff3cccb",302:"fc3a3491b4ec2dfd",562:"17a0a299d2e5152c",757:"56952e321dc399b7",902:"e74518750f1e4201",97:"72979a11a067a7c9"})[e]+".js"},f.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}}(),f.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},d={},f.l=function(e,t,n,r){if(d[e])return void d[e].push(t);if(void 0!==n)for(var i,o,a=document.getElementsByTagName("script"),u=0;u<a.length;u++){var c=a[u];if(c.getAttribute("src")==e||c.getAttribute("data-rspack")=="plugin-ai-api:"+n){i=c;break}}i||(o=!0,(i=document.createElement("script")).timeout=120,f.nc&&i.setAttribute("nonce",f.nc),i.setAttribute("data-rspack","plugin-ai-api:"+n),i.src=e),d[e]=[t];var l=function(t,n){i.onerror=i.onload=null,clearTimeout(p);var r=d[e];if(delete d[e],i.parentNode&&i.parentNode.removeChild(i),r&&r.forEach(function(e){return e(n)}),t)return t(n)},p=setTimeout(l.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=l.bind(null,i.onerror),i.onload=l.bind(null,i.onload),o&&document.head.appendChild(i)},f.r=function(e){"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},f.g.importScripts&&(b=f.g.location+"");var d,b,g=f.g.document;if(!b&&g&&(g.currentScript&&"SCRIPT"===g.currentScript.tagName.toUpperCase()&&(b=g.currentScript.src),!b)){var h=g.getElementsByTagName("script");if(h.length)for(var y=h.length-1;y>-1&&(!b||!/^http(s?):/.test(b));)b=h[y--].src}if(!b)throw Error("Automatic publicPath is not supported in this browser");f.p=b.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),u={889:0},f.f.j=function(e,t){var n=f.o(u,e)?u[e]:void 0;if(0!==n)if(n)t.push(n[2]);else{var r=new Promise(function(t,r){n=u[e]=[t,r]});t.push(n[2]=r);var i=f.p+f.u(e),o=Error();f.l(i,function(t){if(f.o(u,e)&&(0!==(n=u[e])&&(u[e]=void 0),n)){var r=t&&("load"===t.type?"missing":t.type),i=t&&t.target&&t.target.src;o.message="Loading chunk "+e+" failed.\n("+r+": "+i+")",o.name="ChunkLoadError",o.type=r,o.request=i,n[1](o)}},"chunk-"+e,e)}},c=function(e,t){var n,r,i=t[0],o=t[1],a=t[2],c=0;if(i.some(function(e){return 0!==u[e]})){for(n in o)f.o(o,n)&&(f.m[n]=o[n]);a&&a(f)}for(e&&e(t);c<i.length;c++)r=i[c],f.o(u,r)&&u[r]&&u[r][0](),u[r]=0},(l=self.webpackChunkplugin_ai_api=self.webpackChunkplugin_ai_api||[]).forEach(c.bind(null,0)),l.push=c.bind(null,l.push.bind(l));var v={};return!function(){var e="",t="u">typeof document?document.currentScript:null;if(t&&t.src){var n=t.src.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"");n.indexOf("/static/plugins/plugin-ai-api/dist/client/")>=0&&(e=n.replace(/\/[^\/]+$/,"/"))}if(!e){var r=window.__webpack_public_path__||"";r&&("/"!==r.charAt(r.length-1)&&(r+="/"),e=r+"static/plugins/plugin-ai-api/dist/client/")}if(!e){var i=window.__nocobase_modern_client_prefix__||"v",o="/"+(i=String(i).replace(/^\/+|\/+$/g,"")||"v")+"/";if(!(e=window.__nocobase_public_path__||"")&&window.location&&window.location.pathname){var a=window.location.pathname||"/",u=a.indexOf(o);e=u>=0?a.slice(0,u+1):"/"}e&&(e=e.replace(RegExp("/"+i+"/?$"),"/")),e||(e="/"),"/"!==e.charAt(e.length-1)&&(e+="/"),e+="static/plugins/plugin-ai-api/dist/client/"}f.p=e}(),!function(){f.r(v),f.d(v,{default:function(){return _}});var e=f(342),t=f(79),n=f.n(t),r="pm.plugin-ai-api.configuration",i=f(155),o=f.n(i);function a(e,t,n,r,i,o,a){try{var u=e[o](a),c=u.value}catch(e){n(e);return}u.done?t(c):Promise.resolve(c).then(r,i)}function u(e,t,n){return(u=s()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&l(i,n.prototype),i}).apply(null,arguments)}function c(e){return(c=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function l(e,t){return(l=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function p(e){var t="function"==typeof Map?new Map:void 0;return(p=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return u(e,arguments,c(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),l(n,e)})(e)}function s(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(s=function(){return!!e})()}var d=o().lazy(function(){return f.e("302").then(f.bind(f,581))}),b=o().lazy(function(){return f.e("97").then(f.bind(f,760))}),g=o().lazy(function(){return f.e("562").then(f.bind(f,641))}),h=o().lazy(function(){return f.e("123").then(f.bind(f,46))}),y=o().lazy(function(){return f.e("902").then(f.bind(f,77))}),m=o().lazy(function(){return f.e("757").then(f.bind(f,364))}),w=(0,e.lazy)(function(){return f.e("286").then(f.bind(f,421))},"AiApiRolePermissions").AiApiRolePermissions,_=function(e){var t;if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function i(){var e,t;if(!(this instanceof i))throw TypeError("Cannot call a class as a function");return e=i,t=arguments,e=c(e),function(e,t){var n;if(t&&("object"==((n=t)&&"u">typeof Symbol&&n.constructor===Symbol?"symbol":typeof n)||"function"==typeof t))return t;if(void 0===e)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(this,s()?Reflect.construct(e,t||[],c(this).constructor):e.apply(this,t))}return i.prototype=Object.create(e&&e.prototype,{constructor:{value:i,writable:!0,configurable:!0}}),e&&l(i,e),t=[{key:"load",value:function(){var e;return(e=function(){var e;return function(e,t){var n,r,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),u=Object.defineProperty;return u(a,"next",{value:c(0)}),u(a,"throw",{value:c(1)}),u(a,"return",{value:c(2)}),"function"==typeof Symbol&&u(a,Symbol.iterator,{value:function(){return this}}),a;function c(u){return function(c){var l=[u,c];if(n)throw TypeError("Generator is already executing.");for(;a&&(a=0,l[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&l[0]?r.return:l[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,l[1])).done)return i;switch(r=0,i&&(l=[2&l[0],i.value]),l[0]){case 0:case 1:i=l;break;case 4:return o.label++,{value:l[1],done:!1};case 5:o.label++,r=l[1],l=[0];continue;case 7:l=o.ops.pop(),o.trys.pop();continue;default:if(!(i=(i=o.trys).length>0&&i[i.length-1])&&(6===l[0]||2===l[0])){o=0;continue}if(3===l[0]&&(!i||l[1]>i[0]&&l[1]<i[3])){o.label=l[1];break}if(6===l[0]&&o.label<i[1]){o.label=i[1],i=l;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(l);break}i[2]&&o.ops.pop(),o.trys.pop();continue}l=t.call(e,o)}catch(e){l=[6,e],r=0}finally{n=i=0}if(5&l[0])throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}}(this,function(t){return this.app.pluginSettingsManager.add("ai-api",{icon:"ApiOutlined",title:this.t("AI API Gateway"),aclSnippet:r}),this.app.pluginSettingsManager.add("ai-api.config",{title:this.t("Configuration"),Component:d,aclSnippet:r,sort:1}),this.app.pluginSettingsManager.add("ai-api.model-pricing",{title:this.t("Model pricing"),Component:b,aclSnippet:r,sort:2}),this.app.pluginSettingsManager.add("ai-api.model-metadata",{title:this.t("Model metadata"),Component:g,aclSnippet:r,sort:3}),this.app.pluginSettingsManager.add("ai-api.user-permissions",{title:this.t("User LLM permissions"),Component:h,aclSnippet:"pm.plugin-ai-api.user-permissions",sort:4}),this.app.pluginSettingsManager.add("ai-api.user-quotas",{title:this.t("User quotas"),Component:y,aclSnippet:r,sort:5}),this.app.pluginSettingsManager.add("ai-api.usage",{title:this.t("Usage"),Component:m,aclSnippet:r,sort:6}),(null==(e=this.app.pm.get(n()))?void 0:e.settingsUI)&&e.settingsUI.addPermissionsTab(function(e){var t=e.t,n=e.TabLayout,r=e.activeRole;return{key:"aiApi",label:t("AI API",{ns:["plugin-ai-api","client"]}),sort:25,children:o().createElement(n,null,o().createElement(w,{role:r}))}}),[2]})},function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function u(e){a(o,r,i,u,c,"next",e)}function c(e){a(o,r,i,u,c,"throw",e)}u(void 0)})}).call(this)}}],function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}(i.prototype,t),i}(p(e.Plugin))}(),v}()});
@@ -0,0 +1,10 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ "use strict";(self.webpackChunkplugin_ai_api_client_v2=self.webpackChunkplugin_ai_api_client_v2||[]).push([["757"],{364:function(e,t,r){r.r(t),r.d(t,{default:function(){return y}});var n=r(155),a=r.n(n),l=r(59),o=r(185),s=r.n(o),i=r(694),u=r(650),c=r(630);function d(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function m(e,t,r,n,a,l,o){try{var s=e[l](o),i=s.value}catch(e){r(e);return}s.done?t(i):Promise.resolve(i).then(n,a)}function p(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r,n,a=null==e?null:"u">typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=a){var l=[],o=!0,s=!1;try{for(a=a.call(e);!(o=(r=a.next()).done)&&(l.push(r.value),!t||l.length!==t);o=!0);}catch(e){s=!0,n=e}finally{try{o||null==a.return||a.return()}finally{if(s)throw n}}return l}}(e,t)||function(e,t){if(e){if("string"==typeof e)return d(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if("Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r)return Array.from(r);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return d(e,t)}}(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var v=function(){return[s()().subtract(29,"day").startOf("day"),s()().endOf("day")]},f={requestCount:0,inputTokens:0,outputTokens:0,totalTokens:0,promptCacheTokens:0,costsByCurrency:[]};function y(){var e=(0,i.useFlowContext)(),t=(0,u.k)(),r=p(l.Form.useForm(),1)[0],o=p((0,n.useState)([]),2),s=o[0],d=o[1],y=p((0,n.useState)(f),2),h=y[0],S=y[1],b=p((0,n.useState)([]),2),g=b[0],k=b[1],I=p((0,n.useState)(!1),2),E=I[0],w=I[1],C=(0,n.useCallback)(function(t){var n;return(n=function(){var n,a,o,s,i,u,m,y,h,b,g;return function(e,t){var r,n,a,l={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),s=Object.defineProperty;return s(o,"next",{value:i(0)}),s(o,"throw",{value:i(1)}),s(o,"return",{value:i(2)}),"function"==typeof Symbol&&s(o,Symbol.iterator,{value:function(){return this}}),o;function i(s){return function(i){var u=[s,i];if(r)throw TypeError("Generator is already executing.");for(;o&&(o=0,u[0]&&(l=0)),l;)try{if(r=1,n&&(a=2&u[0]?n.return:u[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,u[1])).done)return a;switch(n=0,a&&(u=[2&u[0],a.value]),u[0]){case 0:case 1:a=u;break;case 4:return l.label++,{value:u[1],done:!1};case 5:l.label++,n=u[1],u=[0];continue;case 7:u=l.ops.pop(),l.trys.pop();continue;default:if(!(a=(a=l.trys).length>0&&a[a.length-1])&&(6===u[0]||2===u[0])){l=0;continue}if(3===u[0]&&(!a||u[1]>a[0]&&u[1]<a[3])){l.label=u[1];break}if(6===u[0]&&l.label<a[1]){l.label=a[1],a=u;break}if(a&&l.label<a[2]){l.label=a[2],l.ops.push(u);break}a[2]&&l.ops.pop(),l.trys.pop();continue}u=t.call(e,l)}catch(e){u=[6,e],n=0}finally{r=a=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}}(this,function(k){switch(k.label){case 0:s=(o=p(null!=(n=(a=null!=t?t:r.getFieldsValue()).range)?n:v(),2))[0],i=o[1],u=[{startedAt:{$gte:s.toISOString(),$lte:i.toISOString()}}],void 0!==a.userId&&u.push({userId:a.userId}),a.resolvedService&&u.push({resolvedService:a.resolvedService}),a.resolvedModel&&u.push({resolvedModel:a.resolvedModel}),a.status&&u.push({status:a.status}),m={start:s.toISOString(),end:i.toISOString(),userId:a.userId,resolvedService:a.resolvedService,resolvedModel:a.resolvedModel,status:a.status},w(!0),k.label=1;case 1:return k.trys.push([1,3,4,5]),[4,Promise.all([e.api.request({url:"aiApiUsageRecords:list",method:"get",params:{pageSize:100,sort:"-startedAt",filter:{$and:u}}}),e.api.request({url:"aiApiUsageMonitor:summary",method:"get",params:m})])];case 2:return h=(y=p.apply(void 0,[k.sent(),2]))[0],b=y[1],d((0,c.m)(h,[])),S((0,c.m)(b,f)),[3,5];case 3:return g=k.sent(),l.message.error((0,c.g)(g)),[3,5];case 4:return w(!1),[7];case 5:return[2]}})},function(){var e=this,t=arguments;return new Promise(function(r,a){var l=n.apply(e,t);function o(e){m(l,r,a,o,s,"next",e)}function s(e){m(l,r,a,o,s,"throw",e)}o(void 0)})})()},[e.api,r]);(0,n.useEffect)(function(){var t=v();r.setFieldsValue({range:t}),C({range:t}),e.api.request({url:"ai:listLLMServices",method:"get"}).then(function(e){return k((0,c.m)(e,[]))}).catch(function(e){return l.message.error((0,c.g)(e))})},[e.api,r,C]);var x=h.costsByCurrency.length?h.costsByCurrency.map(function(e){return"".concat(e.totalCost," ").concat(e.currency)}).join(" + "):"0",T=[{title:t("Started at"),dataIndex:"startedAt",key:"startedAt",width:180},{title:t("User"),dataIndex:"userId",key:"userId",width:90},{title:t("Requested model"),dataIndex:"model",key:"model",width:170},{title:t("Resolved service"),dataIndex:"resolvedService",key:"resolvedService",width:170},{title:t("Resolved model"),dataIndex:"resolvedModel",key:"resolvedModel",width:170},{title:t("Input tokens"),dataIndex:"inputTokens",key:"inputTokens",width:110},{title:t("Output tokens"),dataIndex:"outputTokens",key:"outputTokens",width:110},{title:t("Total tokens"),dataIndex:"totalTokens",key:"totalTokens",width:110},{title:t("Prompt cache tokens"),dataIndex:"promptCacheTokens",key:"promptCacheTokens",width:140},{title:t("Cost"),key:"cost",width:130,render:function(e,t){var r;return null==t.estimatedCost?"-":"".concat(t.estimatedCost," ").concat(null!=(r=t.currency)?r:"")}},{title:t("Cost status"),dataIndex:"costStatus",key:"costStatus",width:130,render:function(e){return e?a().createElement(l.Tag,null,e):"-"}},{title:t("Status"),dataIndex:"status",key:"status",width:100},{title:t("Request ID"),dataIndex:"requestId",key:"requestId",width:240}];return a().createElement(l.Space,{direction:"vertical",size:16,style:{width:"100%"}},a().createElement(l.Card,{title:t("Usage filters"),size:"small"},a().createElement(l.Form,{form:r,layout:"inline",onFinish:function(e){return C(e)}},a().createElement(l.Form.Item,{name:"range",label:t("Time range"),rules:[{required:!0}]},a().createElement(l.DatePicker.RangePicker,{showTime:!0})),a().createElement(l.Form.Item,{name:"userId",label:t("User ID")},a().createElement(l.InputNumber,{min:1,style:{width:110}})),a().createElement(l.Form.Item,{name:"resolvedService",label:t("Resolved service")},a().createElement(l.Select,{allowClear:!0,showSearch:!0,optionFilterProp:"label",style:{width:190},options:g.map(function(e){return{label:e.title||e.name,value:e.name}})})),a().createElement(l.Form.Item,{name:"resolvedModel",label:t("Resolved model")},a().createElement(l.Input,{allowClear:!0,style:{width:180}})),a().createElement(l.Form.Item,{name:"status",label:t("Status")},a().createElement(l.Select,{allowClear:!0,style:{width:130},options:[{label:t("Succeeded"),value:"succeeded"},{label:t("Failed"),value:"failed"},{label:t("Started"),value:"started"}]})),a().createElement(l.Form.Item,null,a().createElement(l.Space,null,a().createElement(l.Button,{type:"primary",htmlType:"submit",loading:E},t("Apply filters")),a().createElement(l.Button,{onClick:function(){var e=v();r.setFieldsValue({range:e,userId:void 0,resolvedService:void 0,resolvedModel:void 0,status:void 0}),C({range:e})}},t("Reset")))))),a().createElement(l.Row,{gutter:[16,16]},a().createElement(l.Col,{xs:24,sm:12,lg:6},a().createElement(l.Card,{size:"small"},a().createElement(l.Statistic,{title:t("Requests"),value:h.requestCount}))),a().createElement(l.Col,{xs:24,sm:12,lg:6},a().createElement(l.Card,{size:"small"},a().createElement(l.Statistic,{title:t("Input tokens"),value:h.inputTokens}))),a().createElement(l.Col,{xs:24,sm:12,lg:6},a().createElement(l.Card,{size:"small"},a().createElement(l.Statistic,{title:t("Output tokens"),value:h.outputTokens}))),a().createElement(l.Col,{xs:24,sm:12,lg:6},a().createElement(l.Card,{size:"small"},a().createElement(l.Statistic,{title:t("Total tokens"),value:h.totalTokens}))),a().createElement(l.Col,{xs:24,sm:12,lg:6},a().createElement(l.Card,{size:"small"},a().createElement(l.Statistic,{title:t("Prompt cache tokens"),value:h.promptCacheTokens}))),a().createElement(l.Col,{xs:24},a().createElement(l.Card,{size:"small"},a().createElement(l.Statistic,{title:t("Total cost"),value:x})))),a().createElement(l.Card,{title:t("Usage records"),extra:a().createElement(l.Button,{onClick:function(){return C()}},t("Refresh"))},a().createElement(l.Table,{rowKey:"id",columns:T,dataSource:s,loading:E,scroll:{x:1600}})))}},650:function(e,t,r){r.d(t,{k:function(){return l}});var n=r(694),a=JSON.parse('{"UU":"plugin-ai-api"}');function l(){var e=(0,n.useFlowEngine)();return function(t){return e.context.t(t,{ns:[a.UU,"client"]})}}},630:function(e,t,r){function n(e,t){var r,n;return e&&(void 0===e?"undefined":e&&"u">typeof Symbol&&e.constructor===Symbol?"symbol":typeof e)=="object"?null!=(r=null==(n=e.data)?void 0:n.data)?r:t:t}function a(e){var t;return(null!=(t=Error)&&"u">typeof Symbol&&t[Symbol.hasInstance]?!!t[Symbol.hasInstance](e):e instanceof t)?e.message:String(e)}r.d(t,{g:function(){return a},m:function(){return n}})}}]);
@@ -7,4 +7,4 @@
7
7
  * For more information, please refer to: https://www.nocobase.com/agreement.
8
8
  */
9
9
 
10
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("@nocobase/client-v2"),require("dayjs"),require("react"),require("antd"),require("@nocobase/flow-engine")):"function"==typeof define&&define.amd?define("plugin-ai-api/client-v2",["@nocobase/client-v2","dayjs","react","antd","@nocobase/flow-engine"],t):"object"==typeof exports?exports["plugin-ai-api/client-v2"]=t(require("@nocobase/client-v2"),require("dayjs"),require("react"),require("antd"),require("@nocobase/flow-engine")):e["plugin-ai-api/client-v2"]=t(e["@nocobase/client-v2"],e.dayjs,e.react,e.antd,e["@nocobase/flow-engine"])}(self,function(e,t,n,r,i){return function(){"use strict";var o,a,u,c={485:function(t){t.exports=e},694:function(e){e.exports=i},59:function(e){e.exports=r},185:function(e){e.exports=t},155:function(e){e.exports=n}},l={};function p(e){var t=l[e];if(void 0!==t)return t.exports;var n=l[e]={exports:{}};return c[e](n,n.exports,p),n.exports}p.m=c,p.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return p.d(t,{a:t}),t},p.d=function(e,t){for(var n in t)p.o(t,n)&&!p.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},p.f={},p.e=function(e){return Promise.all(Object.keys(p.f).reduce(function(t,n){return p.f[n](e,t),t},[]))},p.u=function(e){return""+e+"."+({123:"05f1f649923f93eb",302:"d27fe4ea9b0b3bf5",562:"fb2948ee6402de95",757:"a117ce1cf7119cea",902:"c7c00a565085438a",952:"94100128b7757f56",97:"29c663318eebbd57"})[e]+".js"},p.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}}(),p.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s={},p.l=function(e,t,n,r){if(s[e])return void s[e].push(t);if(void 0!==n)for(var i,o,a=document.getElementsByTagName("script"),u=0;u<a.length;u++){var c=a[u];if(c.getAttribute("src")==e||c.getAttribute("data-rspack")=="plugin-ai-api/client-v2:"+n){i=c;break}}i||(o=!0,(i=document.createElement("script")).timeout=120,p.nc&&i.setAttribute("nonce",p.nc),i.setAttribute("data-rspack","plugin-ai-api/client-v2:"+n),i.src=e),s[e]=[t];var l=function(t,n){i.onerror=i.onload=null,clearTimeout(f);var r=s[e];if(delete s[e],i.parentNode&&i.parentNode.removeChild(i),r&&r.forEach(function(e){return e(n)}),t)return t(n)},f=setTimeout(l.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=l.bind(null,i.onerror),i.onload=l.bind(null,i.onload),o&&document.head.appendChild(i)},p.r=function(e){"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},p.g.importScripts&&(f=p.g.location+"");var s,f,d=p.g.document;if(!f&&d&&(d.currentScript&&"SCRIPT"===d.currentScript.tagName.toUpperCase()&&(f=d.currentScript.src),!f)){var b=d.getElementsByTagName("script");if(b.length)for(var g=b.length-1;g>-1&&(!f||!/^http(s?):/.test(f));)f=b[g--].src}if(!f)throw Error("Automatic publicPath is not supported in this browser");p.p=f.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),o={889:0},p.f.j=function(e,t){var n=p.o(o,e)?o[e]:void 0;if(0!==n)if(n)t.push(n[2]);else{var r=new Promise(function(t,r){n=o[e]=[t,r]});t.push(n[2]=r);var i=p.p+p.u(e),a=Error();p.l(i,function(t){if(p.o(o,e)&&(0!==(n=o[e])&&(o[e]=void 0),n)){var r=t&&("load"===t.type?"missing":t.type),i=t&&t.target&&t.target.src;a.message="Loading chunk "+e+" failed.\n("+r+": "+i+")",a.name="ChunkLoadError",a.type=r,a.request=i,n[1](a)}},"chunk-"+e,e)}},a=function(e,t){var n,r,i=t[0],a=t[1],u=t[2],c=0;if(i.some(function(e){return 0!==o[e]})){for(n in a)p.o(a,n)&&(p.m[n]=a[n]);u&&u(p)}for(e&&e(t);c<i.length;c++)r=i[c],p.o(o,r)&&o[r]&&o[r][0](),o[r]=0},(u=self.webpackChunkplugin_ai_api_client_v2=self.webpackChunkplugin_ai_api_client_v2||[]).forEach(a.bind(null,0)),u.push=a.bind(null,u.push.bind(u));var h={};return!function(){var e="",t="u">typeof document?document.currentScript:null;if(t&&t.src){var n=t.src.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"");n.indexOf("/static/plugins/plugin-ai-api/dist/client-v2/")>=0&&(e=n.replace(/\/[^\/]+$/,"/"))}if(!e){var r=window.__webpack_public_path__||"";r&&("/"!==r.charAt(r.length-1)&&(r+="/"),e=r+"static/plugins/plugin-ai-api/dist/client-v2/")}if(!e){var i=window.__nocobase_modern_client_prefix__||"v",o="/"+(i=String(i).replace(/^\/+|\/+$/g,"")||"v")+"/";if(!(e=window.__nocobase_public_path__||"")&&window.location&&window.location.pathname){var a=window.location.pathname||"/",u=a.indexOf(o);e=u>=0?a.slice(0,u+1):"/"}e&&(e=e.replace(RegExp("/"+i+"/?$"),"/")),e||(e="/"),"/"!==e.charAt(e.length-1)&&(e+="/"),e+="static/plugins/plugin-ai-api/dist/client-v2/"}p.p=e}(),!function(){p.r(h),p.d(h,{default:function(){return c}}),p(155);var e=p(485),t="pm.plugin-ai-api.configuration";function n(e,t,n,r,i,o,a){try{var u=e[o](a),c=u.value}catch(e){n(e);return}u.done?t(c):Promise.resolve(c).then(r,i)}function r(e,t,n){return(r=u()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&o(i,n.prototype),i}).apply(null,arguments)}function i(e){return(i=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function o(e,t){return(o=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function a(e){var t="function"==typeof Map?new Map:void 0;return(a=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return r(e,arguments,i(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),o(n,e)})(e)}function u(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(u=function(){return!!e})()}var c=function(e){var r;if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function a(){var e,t;if(!(this instanceof a))throw TypeError("Cannot call a class as a function");return e=a,t=arguments,e=i(e),function(e,t){var n;if(t&&("object"==((n=t)&&"u">typeof Symbol&&n.constructor===Symbol?"symbol":typeof n)||"function"==typeof t))return t;if(void 0===e)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(this,u()?Reflect.construct(e,t||[],i(this).constructor):e.apply(this,t))}return a.prototype=Object.create(e&&e.prototype,{constructor:{value:a,writable:!0,configurable:!0}}),e&&o(a,e),r=[{key:"load",value:function(){var e;return(e=function(){var e,n,r;return function(e,t){var n,r,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),u=Object.defineProperty;return u(a,"next",{value:c(0)}),u(a,"throw",{value:c(1)}),u(a,"return",{value:c(2)}),"function"==typeof Symbol&&u(a,Symbol.iterator,{value:function(){return this}}),a;function c(u){return function(c){var l=[u,c];if(n)throw TypeError("Generator is already executing.");for(;a&&(a=0,l[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&l[0]?r.return:l[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,l[1])).done)return i;switch(r=0,i&&(l=[2&l[0],i.value]),l[0]){case 0:case 1:i=l;break;case 4:return o.label++,{value:l[1],done:!1};case 5:o.label++,r=l[1],l=[0];continue;case 7:l=o.ops.pop(),o.trys.pop();continue;default:if(!(i=(i=o.trys).length>0&&i[i.length-1])&&(6===l[0]||2===l[0])){o=0;continue}if(3===l[0]&&(!i||l[1]>i[0]&&l[1]<i[3])){o.label=l[1];break}if(6===l[0]&&o.label<i[1]){o.label=i[1],i=l;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(l);break}i[2]&&o.ops.pop(),o.trys.pop();continue}l=t.call(e,o)}catch(e){l=[6,e],r=0}finally{n=i=0}if(5&l[0])throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}}(this,function(i){return this.pluginSettingsManager.addMenuItem({key:"ai-api",title:this.t("AI API Gateway"),icon:"ApiOutlined",aclSnippet:t}),this.pluginSettingsManager.addPageTabItem({menuKey:"ai-api",key:"index",title:this.t("Configuration"),aclSnippet:t,sort:1,componentLoader:function(){return p.e("302").then(p.bind(p,581))}}),this.pluginSettingsManager.addPageTabItem({menuKey:"ai-api",key:"model-pricing",title:this.t("Model pricing"),aclSnippet:t,sort:2,componentLoader:function(){return p.e("97").then(p.bind(p,760))}}),this.pluginSettingsManager.addPageTabItem({menuKey:"ai-api",key:"model-metadata",title:this.t("Model metadata"),aclSnippet:t,sort:3,componentLoader:function(){return p.e("562").then(p.bind(p,641))}}),this.pluginSettingsManager.addPageTabItem({menuKey:"ai-api",key:"user-permissions",title:this.t("User LLM permissions"),aclSnippet:"pm.plugin-ai-api.user-permissions",sort:4,componentLoader:function(){return p.e("123").then(p.bind(p,46))}}),this.pluginSettingsManager.addPageTabItem({menuKey:"ai-api",key:"user-quotas",title:this.t("User quotas"),aclSnippet:t,sort:5,componentLoader:function(){return p.e("902").then(p.bind(p,77))}}),this.pluginSettingsManager.addPageTabItem({menuKey:"ai-api",key:"usage",title:this.t("Usage"),aclSnippet:t,sort:6,componentLoader:function(){return p.e("757").then(p.bind(p,364))}}),null==(r=this.app.pm.get("@nocobase/plugin-acl"))||null==(n=r.settingsUI)||null==(e=n.addPermissionsTab)||e.call(n,{key:"aiApi",label:this.t("AI API"),sort:25,componentLoader:function(){return p.e("952").then(p.bind(p,699))}}),[2]})},function(){var t=this,r=arguments;return new Promise(function(i,o){var a=e.apply(t,r);function u(e){n(a,i,o,u,c,"next",e)}function c(e){n(a,i,o,u,c,"throw",e)}u(void 0)})}).call(this)}}],function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}(a.prototype,r),a}(a(e.Plugin))}(),h}()});
10
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("@nocobase/client-v2"),require("dayjs"),require("react"),require("antd"),require("@nocobase/flow-engine")):"function"==typeof define&&define.amd?define("plugin-ai-api/client-v2",["@nocobase/client-v2","dayjs","react","antd","@nocobase/flow-engine"],t):"object"==typeof exports?exports["plugin-ai-api/client-v2"]=t(require("@nocobase/client-v2"),require("dayjs"),require("react"),require("antd"),require("@nocobase/flow-engine")):e["plugin-ai-api/client-v2"]=t(e["@nocobase/client-v2"],e.dayjs,e.react,e.antd,e["@nocobase/flow-engine"])}(self,function(e,t,n,r,i){return function(){"use strict";var o,a,u,c={485:function(t){t.exports=e},694:function(e){e.exports=i},59:function(e){e.exports=r},185:function(e){e.exports=t},155:function(e){e.exports=n}},l={};function p(e){var t=l[e];if(void 0!==t)return t.exports;var n=l[e]={exports:{}};return c[e](n,n.exports,p),n.exports}p.m=c,p.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return p.d(t,{a:t}),t},p.d=function(e,t){for(var n in t)p.o(t,n)&&!p.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},p.f={},p.e=function(e){return Promise.all(Object.keys(p.f).reduce(function(t,n){return p.f[n](e,t),t},[]))},p.u=function(e){return""+e+"."+({123:"05f1f649923f93eb",302:"d27fe4ea9b0b3bf5",562:"fb2948ee6402de95",757:"db678ca1aa6c422c",902:"c7c00a565085438a",952:"94100128b7757f56",97:"29c663318eebbd57"})[e]+".js"},p.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}}(),p.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s={},p.l=function(e,t,n,r){if(s[e])return void s[e].push(t);if(void 0!==n)for(var i,o,a=document.getElementsByTagName("script"),u=0;u<a.length;u++){var c=a[u];if(c.getAttribute("src")==e||c.getAttribute("data-rspack")=="plugin-ai-api/client-v2:"+n){i=c;break}}i||(o=!0,(i=document.createElement("script")).timeout=120,p.nc&&i.setAttribute("nonce",p.nc),i.setAttribute("data-rspack","plugin-ai-api/client-v2:"+n),i.src=e),s[e]=[t];var l=function(t,n){i.onerror=i.onload=null,clearTimeout(f);var r=s[e];if(delete s[e],i.parentNode&&i.parentNode.removeChild(i),r&&r.forEach(function(e){return e(n)}),t)return t(n)},f=setTimeout(l.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=l.bind(null,i.onerror),i.onload=l.bind(null,i.onload),o&&document.head.appendChild(i)},p.r=function(e){"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},p.g.importScripts&&(f=p.g.location+"");var s,f,d=p.g.document;if(!f&&d&&(d.currentScript&&"SCRIPT"===d.currentScript.tagName.toUpperCase()&&(f=d.currentScript.src),!f)){var b=d.getElementsByTagName("script");if(b.length)for(var g=b.length-1;g>-1&&(!f||!/^http(s?):/.test(f));)f=b[g--].src}if(!f)throw Error("Automatic publicPath is not supported in this browser");p.p=f.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),o={889:0},p.f.j=function(e,t){var n=p.o(o,e)?o[e]:void 0;if(0!==n)if(n)t.push(n[2]);else{var r=new Promise(function(t,r){n=o[e]=[t,r]});t.push(n[2]=r);var i=p.p+p.u(e),a=Error();p.l(i,function(t){if(p.o(o,e)&&(0!==(n=o[e])&&(o[e]=void 0),n)){var r=t&&("load"===t.type?"missing":t.type),i=t&&t.target&&t.target.src;a.message="Loading chunk "+e+" failed.\n("+r+": "+i+")",a.name="ChunkLoadError",a.type=r,a.request=i,n[1](a)}},"chunk-"+e,e)}},a=function(e,t){var n,r,i=t[0],a=t[1],u=t[2],c=0;if(i.some(function(e){return 0!==o[e]})){for(n in a)p.o(a,n)&&(p.m[n]=a[n]);u&&u(p)}for(e&&e(t);c<i.length;c++)r=i[c],p.o(o,r)&&o[r]&&o[r][0](),o[r]=0},(u=self.webpackChunkplugin_ai_api_client_v2=self.webpackChunkplugin_ai_api_client_v2||[]).forEach(a.bind(null,0)),u.push=a.bind(null,u.push.bind(u));var h={};return!function(){var e="",t="u">typeof document?document.currentScript:null;if(t&&t.src){var n=t.src.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"");n.indexOf("/static/plugins/plugin-ai-api/dist/client-v2/")>=0&&(e=n.replace(/\/[^\/]+$/,"/"))}if(!e){var r=window.__webpack_public_path__||"";r&&("/"!==r.charAt(r.length-1)&&(r+="/"),e=r+"static/plugins/plugin-ai-api/dist/client-v2/")}if(!e){var i=window.__nocobase_modern_client_prefix__||"v",o="/"+(i=String(i).replace(/^\/+|\/+$/g,"")||"v")+"/";if(!(e=window.__nocobase_public_path__||"")&&window.location&&window.location.pathname){var a=window.location.pathname||"/",u=a.indexOf(o);e=u>=0?a.slice(0,u+1):"/"}e&&(e=e.replace(RegExp("/"+i+"/?$"),"/")),e||(e="/"),"/"!==e.charAt(e.length-1)&&(e+="/"),e+="static/plugins/plugin-ai-api/dist/client-v2/"}p.p=e}(),!function(){p.r(h),p.d(h,{default:function(){return c}}),p(155);var e=p(485),t="pm.plugin-ai-api.configuration";function n(e,t,n,r,i,o,a){try{var u=e[o](a),c=u.value}catch(e){n(e);return}u.done?t(c):Promise.resolve(c).then(r,i)}function r(e,t,n){return(r=u()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&o(i,n.prototype),i}).apply(null,arguments)}function i(e){return(i=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function o(e,t){return(o=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function a(e){var t="function"==typeof Map?new Map:void 0;return(a=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return r(e,arguments,i(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),o(n,e)})(e)}function u(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(u=function(){return!!e})()}var c=function(e){var r;if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function a(){var e,t;if(!(this instanceof a))throw TypeError("Cannot call a class as a function");return e=a,t=arguments,e=i(e),function(e,t){var n;if(t&&("object"==((n=t)&&"u">typeof Symbol&&n.constructor===Symbol?"symbol":typeof n)||"function"==typeof t))return t;if(void 0===e)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(this,u()?Reflect.construct(e,t||[],i(this).constructor):e.apply(this,t))}return a.prototype=Object.create(e&&e.prototype,{constructor:{value:a,writable:!0,configurable:!0}}),e&&o(a,e),r=[{key:"load",value:function(){var e;return(e=function(){var e,n,r;return function(e,t){var n,r,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),u=Object.defineProperty;return u(a,"next",{value:c(0)}),u(a,"throw",{value:c(1)}),u(a,"return",{value:c(2)}),"function"==typeof Symbol&&u(a,Symbol.iterator,{value:function(){return this}}),a;function c(u){return function(c){var l=[u,c];if(n)throw TypeError("Generator is already executing.");for(;a&&(a=0,l[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&l[0]?r.return:l[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,l[1])).done)return i;switch(r=0,i&&(l=[2&l[0],i.value]),l[0]){case 0:case 1:i=l;break;case 4:return o.label++,{value:l[1],done:!1};case 5:o.label++,r=l[1],l=[0];continue;case 7:l=o.ops.pop(),o.trys.pop();continue;default:if(!(i=(i=o.trys).length>0&&i[i.length-1])&&(6===l[0]||2===l[0])){o=0;continue}if(3===l[0]&&(!i||l[1]>i[0]&&l[1]<i[3])){o.label=l[1];break}if(6===l[0]&&o.label<i[1]){o.label=i[1],i=l;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(l);break}i[2]&&o.ops.pop(),o.trys.pop();continue}l=t.call(e,o)}catch(e){l=[6,e],r=0}finally{n=i=0}if(5&l[0])throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}}(this,function(i){return this.pluginSettingsManager.addMenuItem({key:"ai-api",title:this.t("AI API Gateway"),icon:"ApiOutlined",aclSnippet:t}),this.pluginSettingsManager.addPageTabItem({menuKey:"ai-api",key:"index",title:this.t("Configuration"),aclSnippet:t,sort:1,componentLoader:function(){return p.e("302").then(p.bind(p,581))}}),this.pluginSettingsManager.addPageTabItem({menuKey:"ai-api",key:"model-pricing",title:this.t("Model pricing"),aclSnippet:t,sort:2,componentLoader:function(){return p.e("97").then(p.bind(p,760))}}),this.pluginSettingsManager.addPageTabItem({menuKey:"ai-api",key:"model-metadata",title:this.t("Model metadata"),aclSnippet:t,sort:3,componentLoader:function(){return p.e("562").then(p.bind(p,641))}}),this.pluginSettingsManager.addPageTabItem({menuKey:"ai-api",key:"user-permissions",title:this.t("User LLM permissions"),aclSnippet:"pm.plugin-ai-api.user-permissions",sort:4,componentLoader:function(){return p.e("123").then(p.bind(p,46))}}),this.pluginSettingsManager.addPageTabItem({menuKey:"ai-api",key:"user-quotas",title:this.t("User quotas"),aclSnippet:t,sort:5,componentLoader:function(){return p.e("902").then(p.bind(p,77))}}),this.pluginSettingsManager.addPageTabItem({menuKey:"ai-api",key:"usage",title:this.t("Usage"),aclSnippet:t,sort:6,componentLoader:function(){return p.e("757").then(p.bind(p,364))}}),null==(r=this.app.pm.get("@nocobase/plugin-acl"))||null==(n=r.settingsUI)||null==(e=n.addPermissionsTab)||e.call(n,{key:"aiApi",label:this.t("AI API"),sort:25,componentLoader:function(){return p.e("952").then(p.bind(p,699))}}),[2]})},function(){var t=this,r=arguments;return new Promise(function(i,o){var a=e.apply(t,r);function u(e){n(a,i,o,u,c,"next",e)}function c(e){n(a,i,o,u,c,"throw",e)}u(void 0)})}).call(this)}}],function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}(a.prototype,r),a}(a(e.Plugin))}(),h}()});
@@ -8,16 +8,16 @@
8
8
  */
9
9
 
10
10
  module.exports = {
11
- "@nocobase/client": "2.1.34",
12
- "@nocobase/plugin-acl": "2.1.34",
11
+ "@nocobase/client": "2.1.39",
12
+ "@nocobase/plugin-acl": "2.1.39",
13
13
  "react": "18.2.0",
14
- "@nocobase/flow-engine": "2.1.34",
15
- "@nocobase/client-v2": "2.1.34",
16
- "@nocobase/actions": "2.1.34",
14
+ "@nocobase/flow-engine": "2.1.39",
15
+ "@nocobase/client-v2": "2.1.39",
16
+ "@nocobase/actions": "2.1.39",
17
17
  "dayjs": "1.11.13",
18
- "@nocobase/database": "2.1.34",
18
+ "@nocobase/database": "2.1.39",
19
19
  "sequelize": "6.35.2",
20
- "@nocobase/server": "2.1.34",
20
+ "@nocobase/server": "2.1.39",
21
21
  "antd": "5.24.2",
22
- "@nocobase/resourcer": "2.1.34"
22
+ "@nocobase/resourcer": "2.1.39"
23
23
  };
@@ -63,6 +63,7 @@
63
63
  "Input tokens": "Input tokens",
64
64
  "Output tokens": "Output tokens",
65
65
  "Total tokens": "Total tokens",
66
+ "Prompt cache tokens": "Prompt cache tokens",
66
67
  "Cost": "Cost",
67
68
  "Cost status": "Cost status",
68
69
  "Request ID": "Request ID",
@@ -63,6 +63,7 @@
63
63
  "Input tokens": "Input token",
64
64
  "Output tokens": "Output token",
65
65
  "Total tokens": "Tổng token",
66
+ "Prompt cache tokens": "Prompt cache token",
66
67
  "Cost": "Chi phí",
67
68
  "Cost status": "Trạng thái chi phí",
68
69
  "Request ID": "Request ID",
@@ -63,6 +63,7 @@
63
63
  "Input tokens": "输入令牌",
64
64
  "Output tokens": "输出令牌",
65
65
  "Total tokens": "总令牌",
66
+ "Prompt cache tokens": "提示缓存令牌",
66
67
  "Cost": "费用",
67
68
  "Cost status": "费用状态",
68
69
  "Request ID": "请求 ID",
@@ -310,7 +310,12 @@ async function finalizeLlmBilling(ctx, providerUsage, succeeded) {
310
310
  });
311
311
  }
312
312
  return {
313
- usage: numbers ? { prompt_tokens: numbers.input, completion_tokens: numbers.output, total_tokens: numbers.total } : providerUsage,
313
+ usage: numbers ? {
314
+ prompt_tokens: numbers.input,
315
+ completion_tokens: numbers.output,
316
+ total_tokens: numbers.total,
317
+ prompt_cache_tokens: (providerUsage == null ? void 0 : providerUsage.prompt_cache_tokens) ?? null
318
+ } : providerUsage,
314
319
  estimatedCost: cost,
315
320
  currency: (_b = billing.price) == null ? void 0 : _b.currency,
316
321
  costStatus,
@@ -68,6 +68,12 @@ var ai_api_config_default = (0, import_database.defineCollection)({
68
68
  defaultValue: 10,
69
69
  comment: "Max request body size in MB. Raise this to accept inline base64 images in vision requests."
70
70
  },
71
+ {
72
+ name: "pdfRenderPagesAsImages",
73
+ type: "boolean",
74
+ defaultValue: false,
75
+ comment: "When true, PDF file/file_url blocks are rendered to per-page PNG images and sent as image_url blocks. Requires a registered PdfToImageRenderer. When false or no renderer is available, PDFs are forwarded as file blocks."
76
+ },
71
77
  {
72
78
  name: "quotaEnabled",
73
79
  type: "boolean",
@@ -62,6 +62,7 @@ var ai_api_usage_records_default = (0, import_database.defineCollection)({
62
62
  { name: "inputTokens", type: "integer", allowNull: true },
63
63
  { name: "outputTokens", type: "integer", allowNull: true },
64
64
  { name: "totalTokens", type: "integer", allowNull: true },
65
+ { name: "promptCacheTokens", type: "integer", allowNull: true },
65
66
  { name: "estimatedCost", type: "decimal", allowNull: true, precision: 20, scale: 8 },
66
67
  { name: "currency", type: "string", allowNull: true },
67
68
  { name: "costStatus", type: "string", allowNull: true, index: true },
@@ -0,0 +1,69 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var add_prompt_cache_tokens_exports = {};
28
+ __export(add_prompt_cache_tokens_exports, {
29
+ default: () => AddPromptCacheTokensToUsageRecords
30
+ });
31
+ module.exports = __toCommonJS(add_prompt_cache_tokens_exports);
32
+ var import_server = require("@nocobase/server");
33
+ class AddPromptCacheTokensToUsageRecords extends import_server.Migration {
34
+ on = "beforeLoad";
35
+ async up() {
36
+ const collection = this.db.getCollection("aiApiUsageRecords");
37
+ if (!collection) return;
38
+ const field = collection.getField("promptCacheTokens");
39
+ if (!field) {
40
+ collection.addField("promptCacheTokens", { type: "integer", allowNull: true });
41
+ }
42
+ if (await collection.existsInDb()) {
43
+ const tableName = collection.getTableNameWithSchema();
44
+ const exists = await this.tableColumnExists(tableName, "promptCacheTokens");
45
+ if (!exists) {
46
+ await this.queryInterface.addColumn(tableName, "promptCacheTokens", {
47
+ type: this.db.sequelize.getDialect() === "sqlite" ? "INTEGER" : "INTEGER",
48
+ allowNull: true
49
+ });
50
+ }
51
+ }
52
+ }
53
+ async down() {
54
+ const collection = this.db.getCollection("aiApiUsageRecords");
55
+ if (!collection) return;
56
+ if (await collection.existsInDb()) {
57
+ const tableName = collection.getTableNameWithSchema();
58
+ const exists = await this.tableColumnExists(tableName, "promptCacheTokens");
59
+ if (exists) {
60
+ await this.queryInterface.removeColumn(tableName, "promptCacheTokens");
61
+ }
62
+ }
63
+ collection.removeField("promptCacheTokens");
64
+ }
65
+ async tableColumnExists(tableName, columnName) {
66
+ const columns = await this.queryInterface.describeTable(tableName);
67
+ return Object.prototype.hasOwnProperty.call(columns, columnName);
68
+ }
69
+ }
@@ -50,6 +50,7 @@ var import_role_permission = require("./middleware/role-permission");
50
50
  var import_user_permissions = require("./utils/user-permissions");
51
51
  var import_validation = require("./validation");
52
52
  var import_constants = require("../constants");
53
+ var import_file_processor = require("./services/file-processor");
53
54
  var import_dayjs = __toESM(require("dayjs"));
54
55
  var import_utc = __toESM(require("dayjs/plugin/utc"));
55
56
  var import_timezone = __toESM(require("dayjs/plugin/timezone"));
@@ -61,6 +62,11 @@ class PluginAiApiServer extends import_server.Plugin {
61
62
  * Uses a 1-minute sliding window to enforce rateLimitPerMinute from aiApiConfig.
62
63
  */
63
64
  rateLimiter = new import_rate_limiter.RateLimiter(6e4);
65
+ /**
66
+ * Extensible file processor service. Other plugins can register custom processors
67
+ * to transform file/file_url content blocks before they reach the LLM.
68
+ */
69
+ fileProcessorService = new import_file_processor.FileProcessorService();
64
70
  gcInterval = null;
65
71
  async afterAdd() {
66
72
  }
@@ -76,6 +82,9 @@ class PluginAiApiServer extends import_server.Plugin {
76
82
  });
77
83
  }
78
84
  async load() {
85
+ this.fileProcessorService.register(import_file_processor.base64FileForwarder);
86
+ this.fileProcessorService.register(import_file_processor.httpFileUrlFetcher);
87
+ this.fileProcessorService.register(import_file_processor.pdfFileProcessor);
79
88
  this.app.use(
80
89
  async (ctx, next) => {
81
90
  if (ctx.path.startsWith(import_router.AI_LLM_PREFIX)) ctx.disableBodyParser = true;
@@ -149,6 +158,7 @@ class PluginAiApiServer extends import_server.Plugin {
149
158
  enabledLlmServices: [],
150
159
  rateLimitPerMinute: 60,
151
160
  quotaEnabled: false,
161
+ pdfRenderPagesAsImages: false,
152
162
  defaultReservationOutputTokens: 4096
153
163
  }
154
164
  });
@@ -55,6 +55,7 @@ const aiApiConfigResource = {
55
55
  enabledLlmServices: [],
56
56
  rateLimitPerMinute: 60,
57
57
  maxRequestBodyMb: 10,
58
+ pdfRenderPagesAsImages: false,
58
59
  quotaEnabled: false,
59
60
  defaultReservationOutputTokens: 4096,
60
61
  options: {}
@@ -77,6 +78,7 @@ const aiApiConfigResource = {
77
78
  enabledLlmServices: values.enabledLlmServices ?? [],
78
79
  rateLimitPerMinute: values.rateLimitPerMinute ?? 60,
79
80
  maxRequestBodyMb: coerceMaxRequestBodyMb(values.maxRequestBodyMb ?? DEFAULT_MAX_REQUEST_BODY_MB),
81
+ pdfRenderPagesAsImages: values.pdfRenderPagesAsImages ?? false,
80
82
  quotaEnabled: values.quotaEnabled ?? false,
81
83
  defaultReservationOutputTokens: values.defaultReservationOutputTokens ?? 4096,
82
84
  options: values.options ?? {}
@@ -92,6 +94,9 @@ const aiApiConfigResource = {
92
94
  if (values.maxRequestBodyMb !== void 0) {
93
95
  updateData.maxRequestBodyMb = coerceMaxRequestBodyMb(values.maxRequestBodyMb);
94
96
  }
97
+ if (values.pdfRenderPagesAsImages !== void 0) {
98
+ updateData.pdfRenderPagesAsImages = Boolean(values.pdfRenderPagesAsImages);
99
+ }
95
100
  if (values.quotaEnabled !== void 0) updateData.quotaEnabled = values.quotaEnabled;
96
101
  if (values.defaultReservationOutputTokens !== void 0) {
97
102
  updateData.defaultReservationOutputTokens = values.defaultReservationOutputTokens;
@@ -58,7 +58,8 @@ const aiApiUsageMonitorResource = {
58
58
  [(0, import_sequelize.fn)("COUNT", (0, import_sequelize.col)("id")), "requestCount"],
59
59
  [(0, import_sequelize.fn)("COALESCE", (0, import_sequelize.fn)("SUM", (0, import_sequelize.col)("inputTokens")), 0), "inputTokens"],
60
60
  [(0, import_sequelize.fn)("COALESCE", (0, import_sequelize.fn)("SUM", (0, import_sequelize.col)("outputTokens")), 0), "outputTokens"],
61
- [(0, import_sequelize.fn)("COALESCE", (0, import_sequelize.fn)("SUM", (0, import_sequelize.col)("totalTokens")), 0), "totalTokens"]
61
+ [(0, import_sequelize.fn)("COALESCE", (0, import_sequelize.fn)("SUM", (0, import_sequelize.col)("totalTokens")), 0), "totalTokens"],
62
+ [(0, import_sequelize.fn)("COALESCE", (0, import_sequelize.fn)("SUM", (0, import_sequelize.col)("promptCacheTokens")), 0), "promptCacheTokens"]
62
63
  ],
63
64
  where,
64
65
  raw: true
@@ -74,6 +75,7 @@ const aiApiUsageMonitorResource = {
74
75
  inputTokens: Number((totals == null ? void 0 : totals.inputTokens) ?? 0),
75
76
  outputTokens: Number((totals == null ? void 0 : totals.outputTokens) ?? 0),
76
77
  totalTokens: Number((totals == null ? void 0 : totals.totalTokens) ?? 0),
78
+ promptCacheTokens: Number((totals == null ? void 0 : totals.promptCacheTokens) ?? 0),
77
79
  costsByCurrency: costs.map((item) => ({
78
80
  currency: item.currency || "USD",
79
81
  totalCost: String(item.totalCost ?? 0)
@@ -43,6 +43,7 @@ var import_usage = require("../usage");
43
43
  var import_billing = require("../billing");
44
44
  var import_direct_llm_context = require("../utils/direct-llm-context");
45
45
  var import_app_observability = require("../utils/app-observability");
46
+ var import_file_processor = require("../services/file-processor");
46
47
  async function handleChatCompletions(ctx, plugin) {
47
48
  var _a;
48
49
  const body = ctx.request.body;
@@ -171,6 +172,12 @@ async function handleChatCompletions(ctx, plugin) {
171
172
  if (systemPrompt && !hasSystemMessage) {
172
173
  messages.unshift({ role: "system", content: systemPrompt });
173
174
  }
175
+ messages = await Promise.all(
176
+ messages.map(async (msg) => ({
177
+ ...msg,
178
+ content: await processMessageContentFileBlocks(msg.content, ctx, plugin)
179
+ }))
180
+ );
174
181
  const preparedContext = await (0, import_direct_llm_context.prepareDirectLlmContext)(ctx, {
175
182
  serviceName: service.name,
176
183
  modelId,
@@ -232,13 +239,14 @@ async function handleChatCompletions(ctx, plugin) {
232
239
  if (!((_a = ctx.res) == null ? void 0 : _a.headersSent)) {
233
240
  const isQuotaError = err instanceof import_billing.AiApiQuotaError;
234
241
  const isContextError = err instanceof import_direct_llm_context.DirectLlmContextError;
235
- ctx.status = isQuotaError ? 429 : isContextError ? 400 : 500;
242
+ const isFileError = err instanceof import_file_processor.FileProcessorError;
243
+ ctx.status = isQuotaError ? 429 : isContextError || isFileError ? 400 : 500;
236
244
  if (isQuotaError) ctx.set("X-RateLimit-Reason", err.code);
237
245
  ctx.body = (0, import_openai_format.toOpenAIError)(
238
246
  ctx.status,
239
247
  getErrorMessage(err, "Internal server error"),
240
- isQuotaError ? "quota_error" : isContextError ? "invalid_request_error" : "server_error",
241
- isQuotaError || isContextError ? err.code : void 0
248
+ isQuotaError ? "quota_error" : isContextError || isFileError ? "invalid_request_error" : "server_error",
249
+ isQuotaError || isContextError || isFileError ? err.code : void 0
242
250
  );
243
251
  }
244
252
  }
@@ -252,10 +260,15 @@ async function handleNonStreamingCompletion(ctx, chatModel, messages, completion
252
260
  const textPart = result.content.find((c) => c.type === "text");
253
261
  content = (textPart == null ? void 0 : textPart.text) || JSON.stringify(result.content);
254
262
  }
255
- const usage = (0, import_usage.setAiApiUsageResult)(ctx, result.usage_metadata, {
256
- gatewayResponseId: completionId,
257
- providerRequestId: (0, import_usage.extractProviderRequestId)(result)
258
- });
263
+ const usage = (0, import_usage.setAiApiUsageResult)(
264
+ ctx,
265
+ result.usage_metadata,
266
+ {
267
+ gatewayResponseId: completionId,
268
+ providerRequestId: (0, import_usage.extractProviderRequestId)(result)
269
+ },
270
+ result.response_metadata
271
+ );
259
272
  ctx.status = 200;
260
273
  const toolCalls = normalizeToolCalls(result.tool_calls);
261
274
  ctx.body = (0, import_openai_format.toOpenAIResponse)({
@@ -387,8 +400,9 @@ async function handleStreamingCompletion(ctx, chatModel, messages, completionId,
387
400
  function getErrorMessage(error, fallback) {
388
401
  return error instanceof Error && error.message ? error.message : fallback;
389
402
  }
390
- const SUPPORTED_CONTENT_BLOCK_TYPES = /* @__PURE__ */ new Set(["text", "image_url"]);
403
+ const SUPPORTED_CONTENT_BLOCK_TYPES = /* @__PURE__ */ new Set(["text", "image_url", "file", "file_url"]);
391
404
  const BASE64_DATA_URL_PATTERN = /^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/;
405
+ const FILE_BASE64_DATA_URL_PATTERN = /^data:([^;\s]+);base64,([A-Za-z0-9+/]+=*)$/;
392
406
  function isDecodableBase64(payload) {
393
407
  try {
394
408
  return Buffer.from(payload, "base64").toString("base64") === payload;
@@ -440,13 +454,50 @@ function describeContentBlockProblem(block) {
440
454
  const type = typeof block.type === "string" ? block.type : void 0;
441
455
  if (!type) return "each content block requires a 'type' field";
442
456
  if (!SUPPORTED_CONTENT_BLOCK_TYPES.has(type)) {
443
- return `content block type '${type}' is not supported \u2014 this gateway forwards 'text' and 'image_url' only. Send documents as text, or inline them as an 'image_url' data URL if the model reads images`;
457
+ return `content block type '${type}' is not supported \u2014 this gateway forwards 'text', 'image_url', 'file', and 'file_url' only. Send documents as text, or inline them as a 'file' / 'file_url' block`;
444
458
  }
445
459
  if (type === "text") {
446
460
  return typeof block.text === "string" ? void 0 : "a 'text' block requires a string 'text' field";
447
461
  }
462
+ if (type === "file") {
463
+ return describeFileProblem(block.file);
464
+ }
465
+ if (type === "file_url") {
466
+ return describeFileUrlProblem(block.file_url);
467
+ }
448
468
  return describeImageUrlProblem(block.image_url);
449
469
  }
470
+ function describeFileProblem(file) {
471
+ if (!isRecord(file)) return "a 'file' block requires an object 'file' field";
472
+ const fileData = typeof file.file_data === "string" ? file.file_data : void 0;
473
+ if (!fileData) return "a 'file' block requires a string 'file.file_data' field";
474
+ if (!fileData.startsWith("data:")) {
475
+ return "a 'file' block's 'file_data' must be a base64 data URL starting with 'data:'";
476
+ }
477
+ const match = FILE_BASE64_DATA_URL_PATTERN.exec(fileData);
478
+ if (!match || !match[1].includes("/")) {
479
+ return `malformed base64 data URL. Expected 'data:<mime-type>;base64,<base64>' with a valid type/subtype and standard base64 (no whitespace or URL-safe characters)`;
480
+ }
481
+ if (!isDecodableBase64(match[2])) {
482
+ return `base64 payload is not decodable. Check the padding and length \u2014 the data must be a multiple of 4 characters with at most two trailing '='`;
483
+ }
484
+ return void 0;
485
+ }
486
+ function describeFileUrlProblem(fileUrl) {
487
+ if (!isRecord(fileUrl)) return "a 'file_url' block requires an object 'file_url' field";
488
+ const url = typeof fileUrl.url === "string" ? fileUrl.url : void 0;
489
+ if (!url) return "a 'file_url' block requires a string 'file_url.url' field";
490
+ let protocol;
491
+ try {
492
+ protocol = new URL(url).protocol;
493
+ } catch {
494
+ return `'${url}' is not a valid URL. Use an http(s) URL`;
495
+ }
496
+ if (protocol !== "http:" && protocol !== "https:") {
497
+ return `URL protocol '${protocol}' is not supported. Use an http(s) URL`;
498
+ }
499
+ return void 0;
500
+ }
450
501
  function describeImageUrlProblem(imageUrl) {
451
502
  const url = typeof imageUrl === "string" ? imageUrl : isRecord(imageUrl) ? imageUrl.url : void 0;
452
503
  if (typeof url !== "string" || url === "") {
@@ -492,7 +543,35 @@ function normalizeMessageContent(content) {
492
543
  if (content === null || content === void 0) return "";
493
544
  return JSON.stringify(content);
494
545
  }
495
- const GATEWAY_MANAGED_PARAMETERS = /* @__PURE__ */ new Set(["model", "messages", "tools", "tool_choice", "stream", "n"]);
546
+ async function processMessageContentFileBlocks(content, ctx, plugin) {
547
+ if (!Array.isArray(content)) return content;
548
+ const processed = [];
549
+ for (const block of content) {
550
+ processed.push(...await processFileBlockChain(block, ctx, plugin, 0));
551
+ }
552
+ return processed;
553
+ }
554
+ const MAX_FILE_PROCESSOR_CHAIN_DEPTH = 3;
555
+ async function processFileBlockChain(block, ctx, plugin, depth) {
556
+ if (!isRecord(block) || block.type !== "file" && block.type !== "file_url") {
557
+ return [block];
558
+ }
559
+ if (depth > MAX_FILE_PROCESSOR_CHAIN_DEPTH) {
560
+ return [block];
561
+ }
562
+ const result = await plugin.fileProcessorService.process(block, { ctx });
563
+ const results = Array.isArray(result) ? result : [result];
564
+ const next = [];
565
+ for (const item of results) {
566
+ if (isRecord(item) && (item.type === "file" || item.type === "file_url")) {
567
+ next.push(...await processFileBlockChain(item, ctx, plugin, depth + 1));
568
+ } else {
569
+ next.push(item);
570
+ }
571
+ }
572
+ return next;
573
+ }
574
+ const GATEWAY_MANAGED_PARAMETERS = /* @__PURE__ */ new Set(["model", "messages", "prompt", "tools", "tool_choice", "stream", "n"]);
496
575
  function getProviderRequestParameters(body) {
497
576
  return Object.fromEntries(
498
577
  Object.entries(body).filter(([name, value]) => !GATEWAY_MANAGED_PARAMETERS.has(name) && value !== void 0)