ezllm 0.0.45 → 0.0.47
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.
- package/README.md +5 -5
- package/dist/cli.js +24 -23
- package/dist/daemon.js +14 -6
- package/dist/plugin-host.js +3 -3
- package/dist/server.js +75 -75
- package/dist/web-ui/assets/DashboardView-CNsnnzad.css +1 -0
- package/dist/web-ui/assets/DashboardView-CqupMCmm.js +2 -0
- package/dist/web-ui/assets/LayoutView-CyOrx1rA.js +1 -0
- package/dist/web-ui/assets/LayoutView-cQeiOjLU.css +1 -0
- package/dist/web-ui/assets/LoginView-YolyK2Q0.js +1 -0
- package/dist/web-ui/assets/{LogsView-CXFJ_22b.css → LogsView-DPmB8dy8.css} +1 -1
- package/dist/web-ui/assets/LogsView-E64a6PIt.js +5 -0
- package/dist/web-ui/assets/ManagedServicesView-DVCADa1y.css +1 -0
- package/dist/web-ui/assets/ManagedServicesView-mk_mSWzE.js +6 -0
- package/dist/web-ui/assets/PluginsView-DTJeufic.js +2 -0
- package/dist/web-ui/assets/PluginsView-DzHAW2gO.css +1 -0
- package/dist/web-ui/assets/ProvidersView-BrirhwQN.js +14 -0
- package/dist/web-ui/assets/ProvidersView-BwX8Y3kP.css +1 -0
- package/dist/web-ui/assets/SettingsView-BGMZbskz.css +1 -0
- package/dist/web-ui/assets/SettingsView-p3uvWhGh.js +1 -0
- package/dist/web-ui/assets/SetupView-6BYv_B5n.css +1 -0
- package/dist/web-ui/assets/SetupView-CGQibXHs.js +1 -0
- package/dist/web-ui/assets/config-Dzo6AFZx.js +1 -0
- package/dist/web-ui/assets/{format-CPPf8IfM.js → format-Deb1hfjO.js} +1 -1
- package/dist/web-ui/assets/{index-s_h6GEbv.css → index-DodsqGDu.css} +1 -1
- package/dist/web-ui/assets/index-wQG3qUgW.js +49 -0
- package/dist/web-ui/assets/message-C8pR37GK.js +2 -0
- package/dist/web-ui/assets/navVisibility-CPbwxq3d.js +1 -0
- package/dist/web-ui/assets/pluginProviders-DeHPKGnd.js +1 -0
- package/dist/web-ui/assets/providers-Dbg0NkwB.js +1 -0
- package/dist/web-ui/assets/router-JpU_7F6L.js +6 -0
- package/dist/web-ui/assets/{useCopyToast-BeWZ6lSF.js → useCopyToast-GaJ4QVNE.js} +1 -1
- package/dist/web-ui/assets/useManagerApi-DEPhOKWy.js +1 -0
- package/dist/web-ui/assets/{useQuickRangeFilter-DQQ8QAr5.js → useQuickRangeFilter-DeKORPZt.js} +1 -1
- package/dist/web-ui/assets/useToast-DVCDN-da.js +1 -0
- package/dist/web-ui/index.html +4 -4
- package/ezllm.config.example.json +0 -1
- package/package.json +2 -1
- package/dist/web-ui/assets/DashboardView-CkTFY0Da.js +0 -1
- package/dist/web-ui/assets/LayoutView-CcXUd-b0.js +0 -1
- package/dist/web-ui/assets/LayoutView-D84C9Iqp.css +0 -1
- package/dist/web-ui/assets/LoginView-Dq7gaxB9.js +0 -1
- package/dist/web-ui/assets/LogsView-CO6GNtfl.js +0 -5
- package/dist/web-ui/assets/ManagedServicesView-CNLHAVAL.js +0 -6
- package/dist/web-ui/assets/ManagedServicesView-D29NyvP6.css +0 -1
- package/dist/web-ui/assets/PluginsView-B2H4xfag.css +0 -1
- package/dist/web-ui/assets/PluginsView-Dljy9HZq.js +0 -2
- package/dist/web-ui/assets/ProvidersView-CD3QYu3i.js +0 -14
- package/dist/web-ui/assets/ProvidersView-Cwe2Q81Y.css +0 -1
- package/dist/web-ui/assets/ServiceStatusView-BgHmV09I.js +0 -2
- package/dist/web-ui/assets/ServiceStatusView-DmUKbS8w.css +0 -1
- package/dist/web-ui/assets/SettingsView-BLQl0mEB.js +0 -1
- package/dist/web-ui/assets/SettingsView-NXkxZUgr.css +0 -1
- package/dist/web-ui/assets/SetupView-BzZqIZpo.js +0 -1
- package/dist/web-ui/assets/SetupView-CSBKlfcJ.css +0 -1
- package/dist/web-ui/assets/config-CLbcTOt9.js +0 -1
- package/dist/web-ui/assets/index-yak1S-7W.js +0 -49
- package/dist/web-ui/assets/message-K5WVknE-.js +0 -2
- package/dist/web-ui/assets/pluginProviders-CB38zjhC.js +0 -1
- package/dist/web-ui/assets/providers-BuzQNH1W.js +0 -1
- package/dist/web-ui/assets/router-tvNif7bs.js +0 -6
- package/dist/web-ui/assets/updateNote-CttDt8SZ.js +0 -1
- package/dist/web-ui/assets/useManagerApi-Wm9Nz3_p.js +0 -1
- package/dist/web-ui/assets/useToast-D_jja27E.js +0 -1
package/dist/plugin-host.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{dirname as e,join as t,resolve as n}from"node:path";import{fileURLToPath as r,pathToFileURL as i}from"node:url";import{cwd as a}from"node:process";import{existsSync as o,mkdirSync as s,readFileSync as c,readdirSync as l,renameSync as u,rmSync as d,statSync as f,writeFileSync as p}from"node:fs";import{homedir as m}from"node:os";import{createHash as h,randomBytes as g}from"node:crypto";import{AsyncLocalStorage as _}from"node:async_hooks";import{spawn as ee}from"node:child_process";import{createServer as te}from"node:http";function v(e,...t){console.log(e,...t)}function y(e,...t){console.warn(e,...t)}function ne(e,...t){console.error(e,...t)}function b(e){if(e===void 0)return;let t=e.trim();return t===``?void 0:t}function x(e){let t=`--${e}`,n=`${t}=`,r=process.argv;for(let e=0;e<r.length;e+=1){let i=r[e]??``;if(i.startsWith(n))return b(i.slice(n.length));if(i===t){let t=r[e+1]??``;return t.startsWith(`-`)?void 0:b(t)}}}function S(e,t){return x(e)??b(process.env[t])}var re=65535;function ie(e){let t=b(e);if(t===void 0)return;let n=Number(t);return Number.isInteger(n)&&n>0&&n<=re?n:void 0}var ae=(()=>{let e=S(`app-dir`,`ELLM_APP_DIR`),t=e===void 0?void 0:n(a(),e),r=x(`port`),i=ie(r??b(process.env.ELLM_PORT));r!==void 0&&i===void 0&&y(`--port=${r} 无效(需为 1-65535 的整数),已忽略:本次不生效、也不会写入配置文件。`);let o=S(`node-mirror`,`ELLM_NODE_MIRROR`),s=S(`node-bin`,`ELLM_NODE_BIN`);return t!==void 0&&(process.env.ELLM_APP_DIR=t),o!==void 0&&(process.env.ELLM_NODE_MIRROR=o),s!==void 0&&(process.env.ELLM_NODE_BIN=s),{appDir:t,port:i,nodeMirror:o,nodeBin:s}})(),oe=e(r(import.meta.url)),C;function se(){return t(m(),`.ezllm`)}function w(){return C===void 0&&(C=ae.appDir??se()),C}function ce(){return n(w(),`plugins`)}function le(){return n(w(),`plugin-auth.json`)}function ue(e){try{let n=c(t(e,`package.json`),`utf-8`).replace(/^\uFEFF/,``);return JSON.parse(n)}catch{return null}}function T(t,n){let r=oe;for(let i=0;i<n;i++){if(ue(r)?.name===t)return r;r=e(r)}return null}T(`ezllm`,5)??n(oe,`..`),T(`ellm`,6);function de(e,t){let n=`${e}.${`${process.pid}.${g(6).toString(`hex`)}`}.tmp`;try{p(n,JSON.stringify(t,null,2)+`
|
|
3
|
-
`,`utf-8`),u(n,e)}finally{try{d(n,{force:!0})}catch{}}}var fe=`https://registry.npmmirror.com/`,pe=`https://registry.npmjs.org/`;function me(){return[fe,pe]}async function E(e,t=me()){let n;for(let r of t)try{return{value:await e(r),registry:r}}catch(e){n=e}throw n??Error(`没有任何可用的 npm registry`)}function he(e){try{let t=JSON.parse(c(e,`utf-8`));if(typeof t!=`object`||!t||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t))typeof r==`object`&&r&&!Array.isArray(r)&&(n[e]=r);return n}catch{return{}}}function ge(e,t){de(e,t)}var _e=class{#e;#t;#n=new Map;#r=new Set;constructor(e){this.#e=e,this.#t=he(e)}reload(){this.#t=he(this.#e);for(let e of Object.keys(this.#t))this.#r.delete(e)}generation(e){return this.#n.get(e)??0}locked(e){return this.#r.has(e)}lock(e){this.#r.add(e)}beginLogin(e){let t=this.generation(e)+1;return this.#n.set(e,t),this.#r.delete(e),t}get(e){let t=this.#t[e];return t===void 0?void 0:{...t}}has(e){return e in this.#t}providers(){return Object.keys(this.#t)}save(e,t,n){if(n?.generation!==void 0&&n.generation!==this.generation(e)||this.#r.has(e))return!1;let r={...this.#t,[e]:{...t}};return ge(this.#e,r),this.#t=r,!0}remove(e){let t=this.generation(e)+1;if(this.#n.set(e,t),this.#r.add(e),!(e in this.#t))return t;let n={...this.#t};return delete n[e],ge(this.#e,n),this.#t=n,t}},D=new _;function O(e,t,n){return D.run({providerId:e,generation:t},n)}var ve=/^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*(@[a-zA-Z0-9.^~<>=*|xX -]+)?$/,k=3e5,ye=65536,be=`npm_config_`;function A(e){let t=e.trim();if(t===``||!ve.test(t))return null;let n=t.lastIndexOf(`@`);return n<=0?{name:t,version:``}:{name:t.slice(0,n),version:t.slice(n+1)}}function xe(e,t=e=>e){let n=e.trim();if(n===``)return null;if(n.startsWith(`./`)||n.startsWith(`../`)||n.startsWith(`file:`)||n.startsWith(`/`)||/^[a-zA-Z]:[\\/]/.test(n)||n.startsWith(`\\\\`)){let e=n.startsWith(`file:`)?n.slice(5):n;return e.trim()===``?null:{kind:`path`,path:t(e.trim())}}let r=A(n);return r===null?null:{kind:`npm`,name:r.name,version:r.version}}function Se(e){return o(e)?f(e).isDirectory()?o(t(e,`package.json`))?null:`目录里没有 package.json:${e}`:`不是目录:${e}`:`目录不存在:${e}`}function j(e){return A(e)?.name??null}function Ce(e,n){return t(e,`node_modules`,...n.split(`/`))}function we(n,r){let i=e=>e.endsWith(`npm-cli.js`)&&o(e),a=e=>{for(let n of[[`node_modules`,`npm`,`bin`,`npm-cli.js`],[`lib`,`node_modules`,`npm`,`bin`,`npm-cli.js`],[`bin`,`npm-cli.js`]]){let r=t(e,...n);if(i(r))return r}return null};if(n!==``){let e=a(n);if(e!==null)return e;if(i(n))return n;let r=t(n,`npm`,`bin`,`npm-cli.js`);if(i(r))return r}let s=t(e(process.execPath),`node_modules`,`npm`,`bin`,`npm-cli.js`);if(i(s))return s;let c=t(e(process.execPath),`..`,`lib`,`node_modules`,`npm`,`bin`,`npm-cli.js`);if(i(c))return c;if(r!==null){let e=t(r,`node`),n=a(e);if(n!==null)return n;try{for(let n of l(e)){let r=a(t(e,n));if(r!==null)return r}}catch{}}return null}function M(e,t,n){return new Promise(r=>{let i=ee(e,[...t],{shell:n.shell,cwd:n.cwd,windowsHide:!0,...n.env===void 0?{}:{env:n.env}}),a=``,o=e=>{a.length<ye&&(a+=e.toString(`utf8`))};i.stdout.on(`data`,o),i.stderr.on(`data`,o);let s=setTimeout(()=>{a+=`\n[npm 超时 ${String(k/1e3)}s,已终止]`,i.kill()},k);i.on(`error`,e=>{clearTimeout(s),r({code:null,output:`${a}\n${e.message}`})}),i.on(`close`,e=>{clearTimeout(s),r({code:e,output:a})})})}function Te(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(n.toLowerCase().startsWith(be)||(t[n]=r));return t}async function N(e,t,n,r,i){let a={...r??{}};i!==void 0&&(a.NPM_CONFIG_USERCONFIG=i,a.NPM_CONFIG_GLOBALCONFIG=`${i}.global-empty`);let o={...Te(process.env),...a};return e===null?M(process.platform===`win32`?`npm.cmd`:`npm`,t,{shell:process.platform===`win32`,cwd:n,env:o}):M(process.execPath,[e,...t],{shell:!1,cwd:n,env:o})}async function Ee(e,t){let n=await E(async n=>{let r=await N(e.npmCli,[`view`,t,`version`,`--json`,`--registry`,n],e.pluginsDir,e.env,e.userconfig),i=r.code===0?De(r.output):null;if(i===null)throw Error(`npm view 未能取到 ${t} 的版本(源 ${n})`);return i}).catch(()=>null);return n===null?null:n.value}function De(e){let t=e=>{try{let t=JSON.parse(e);return typeof t==`string`&&t!==``?t:null}catch{return null}},n=e.trim(),r=t(n);if(r!==null)return r;let i=n.split(/\r?\n/);for(let e=i.length-1;e>=0;e--){let n=(i[e]??``).trim();if(n===``)continue;let r=t(n);if(r!==null)return r}return null}function Oe(e){s(e,{recursive:!0});let n=t(e,`package.json`);o(n)||p(n,`${JSON.stringify({name:`ezllm-plugins`,private:!0,version:`0.0.0`},null,2)}\n`,`utf8`)}async function ke(e,t){let r=xe(t,e=>n(e));if(r===null)return{ok:!1,message:`不是合法的 npm 包规格,也不是本机目录:${t}`};if(r.kind===`path`){let e=Se(r.path);if(e!==null)return{ok:!1,message:e}}Oe(e.pluginsDir);let i=r.kind===`npm`?r.version===``?r.name:`${r.name}@${r.version}`:`file:${r.path}`,a=[`install`,`--no-audit`,`--no-fund`,`--save`,i];return e.log(`[plugin-host] npm install ${i}`),await E(async t=>{let n=await N(e.npmCli,[...a,`--registry`,t],e.pluginsDir,e.env,e.userconfig);if(n.code!==0)throw Error(`npm install 失败(退出码 ${String(n.code)},源 ${t}):\n${n.output.trim().slice(-2e3)}`);return{ok:!0,output:n.output.trim()}}).then(({value:e})=>e).catch(e=>({ok:!1,message:e instanceof Error?e.message:`npm install 失败:${String(e)}`}))}async function Ae(e,t){let n=j(t);if(n===null)return{ok:!1,message:`不是合法的 npm 包名:${t}`};let r=Ce(e.pluginsDir,n);if(!o(r))return{ok:!1,message:`未安装:${n}`};e.log(`[plugin-host] npm uninstall ${n}`);let i=await N(e.npmCli,[`uninstall`,`--no-audit`,`--no-fund`,n],e.pluginsDir,e.env,e.userconfig);if(o(r))try{d(r,{recursive:!0,force:!0}),e.log(i.code===0?`[plugin-host] npm 未清理 ${n} 的目录,已手动删除`:`[plugin-host] npm uninstall 退出码 ${String(i.code)},已手动删除 ${n} 的目录`)}catch(e){return{ok:!1,message:`卸载 ${n} 未完成:npm 退出码 ${String(i.code)},且目录残留删除失败(${e instanceof Error?e.message:String(e)})\n${i.output.trim().slice(-1500)}`}}return i.code!==0&&!o(r)?{ok:!0,output:`npm 退出码 ${String(i.code)}(目录已删除)\n${i.output.trim().slice(-1500)}`}:i.code===0?{ok:!0,output:i.output.trim()}:{ok:!1,message:`npm uninstall 失败(退出码 ${String(i.code)}):\n${i.output.trim().slice(-2e3)}`}}function je(e){for(let n of[`README.md`,`readme.md`,`README.MD`,`README`]){let r=t(e,n);if(o(r))try{return c(r,`utf8`).slice(0,204800)}catch{return null}}return null}var Me=[{npm:`@ai-sdk/openai-compatible`,protocol:`openai`,path:`chat/completions`},{npm:`@ai-sdk/anthropic`,protocol:`anthropic`,path:`messages`},{npm:`@ai-sdk/openai`,protocol:`openai-responses`,path:`responses`}];function Ne(e){return typeof e!=`string`||e===``?null:Me.find(t=>t.npm===e)??null}function Pe(e){return new Proxy(async()=>({data:void 0}),{get(t,n){if(n!==`then`)return Pe(`${e}.${String(n)}`)},apply(){return Promise.resolve({data:void 0})}})}function Fe(e){let t={auth:{set:async t=>{let n=t?.path?.id??t?.id??t?.providerID,r=typeof n==`string`&&n!==``?n:e.scope?.key??D.getStore()?.providerId,i=t?.body??t?.auth;return typeof r==`string`&&r!==``&&typeof i==`object`&&i&&await e.saveAuth(r,i),{data:!0}},remove:async()=>({data:!0})},tui:{showToast:async()=>({data:!0})},app:{log:async()=>({data:!0})},config:{get:async()=>({data:{provider:{}}})}},n=(e,t)=>new Proxy(e,{get(e,r){if(typeof r==`symbol`)return Reflect.get(e,r);if(r in e){let i=e[r];return typeof i==`object`&&i?n(i,`${t}.${r}`):i}if(r!==`then`)return Pe(`${t}.${r}`)}});return n(t,`client`)}function Ie(e){return{client:Fe(e),directory:e.directory,worktree:e.directory,project:{id:`ezllm`,worktree:e.directory},serverUrl:new URL(`http://127.0.0.1:4096`),$:()=>{throw Error("插件请求了 shell(`$`),但 ezllm 的插件宿主不提供:当前插件生态没有任何插件使用它;若某个插件真的需要,请提交 issue 说明用途(提供 shell 等于给第三方代码任意命令执行能力)")}}}var Le=`@magpie-community`,Re=`ezllmPlugin`;function ze(e){let t=e.exports,n=typeof t==`string`?t:typeof t==`object`&&t?t[`.`]:void 0,r=typeof e.main==`string`?e.main:n;return typeof r==`string`&&r!==``?r:void 0}function Be(e,r){let i=t(e,`package.json`);if(!o(i))return null;let a;try{let e=JSON.parse(c(i,`utf-8`));if(typeof e!=`object`||!e||Array.isArray(e))return null;a=e}catch{return null}let s=typeof a.name==`string`&&a.name!==``?a.name:r;if(!s.startsWith(`${Le}/`)&&a[Re]!==!0)return null;let l=ze(a);if(l===void 0)return null;let u=a.repository,d=typeof u==`string`?u:typeof u==`object`&&u&&typeof u.url==`string`?String(u.url):``;return{name:s,version:typeof a.version==`string`?a.version:`0.0.0`,main:l,description:typeof a.description==`string`?a.description:``,license:typeof a.license==`string`?a.license:``,repository:d,dir:n(e)}}function P(e){let n=t(e,`node_modules`);if(!o(n))return[];let r;try{r=l(n,{withFileTypes:!0})}catch{return[]}let i=[];for(let e of r){if(e.name.startsWith(`.`))continue;if(!e.name.startsWith(`@`)){let r=Be(t(n,e.name),e.name);r!==null&&i.push(r);continue}let r=t(n,e.name),a;try{a=l(r,{withFileTypes:!0})}catch{continue}for(let n of a){let a=Be(t(r,n.name),`${e.name}/${n.name}`);a!==null&&i.push(a)}}return i}function Ve(e){return t(e.dir,e.main)}function F(e,t){return P(e).find(e=>e.name===t)}function He(e){let t=[];for(let[n,r]of Object.entries(e))n==="default"||n.startsWith(`_`)||typeof r==`function`&&t.push([n,r]);return t}function Ue(e,t,n){let r=[],i=e=>{let t=n.find(t=>t.auth?.provider===e)??n.find(t=>t.provider?.id===e);return t===void 0||t.auth===void 0?null:{hooks:t,auth:t.auth}};for(let[n,a]of Object.entries(t.provider??{})){let t=a??{},o=i(n),s=Ne(typeof t.npm==`string`?t.npm:void 0);r.push({id:n,name:typeof t.name==`string`&&t.name!==``?t.name:n,source:{package:e.name,version:e.version},protocol:s?.protocol??null,path:s?.path??``,models:Object.keys(t.models??{}),config:t,hooks:o,capabilities:{models:typeof o?.hooks.provider?.models==`function`,usage:typeof o?.auth.usage==`function`,checkin:typeof o?.auth.checkin==`function`,refresh:typeof o?.auth.refresh==`function`,chatHeaders:typeof o?.hooks[`chat.headers`]==`function`}})}return r}async function We(e,t){let n=[],r=[];for(let a of P(e)){let e=Ve(a);if(!o(e)){r.push(`${a.name}: 入口不存在(${e})`);continue}let s;try{s=await import(i(e).href)}catch(e){r.push(`${a.name}: 导入失败(${e instanceof Error?e.message:String(e)})`);continue}let c=He(s);if(c.length===0){r.push(`${a.name}: 没有导出插件工厂函数`);continue}let l=[],u={provider:{}};for(let[e,n]of c)try{let e=await n(Ie(t));l.push(e),typeof e.config==`function`&&await e.config(u)}catch(t){r.push(`${a.name}#${e}: 工厂/config 失败(${t instanceof Error?t.message:String(t)})`)}if(l.length===0)continue;let d=Ue(a,u,l);n.push({package:a.name,version:a.version,providers:d,hooks:l})}return{plugins:n,errors:r}}function I(e){let t=new Set,n=[],r=[...e.errors];for(let i of e.plugins)for(let e of i.providers){if(t.has(e.id)){r.push(`${e.id}: provider id 重复(${e.source.package}),已忽略后一个`);continue}t.add(e.id),n.push(e)}return{providers:n,errors:r}}function Ge(e,t=process.env){let n={host:`127.0.0.1`,port:Number(t.PORT||29772),pluginsDir:t.PLUGIN_DIR||``,authFile:``,apiKey:t.PLUGIN_HOST_KEY||``,nodeDir:t.NODE_DIR||``,mainPort:Number(t.MAIN_PORT||0),skipCheck:!1,help:!1};for(let t=0;t<e.length;t+=1){let r=e[t]??``,i=r.indexOf(`=`),a=r.startsWith(`--`)&&i>=0?r.slice(0,i):r,o=r.startsWith(`--`)&&i>=0?r.slice(i+1):void 0,s=()=>o===void 0?e[++t]:o;switch(a){case`--host`:n.host=s()||n.host;break;case`--port`:n.port=Number(s());break;case`--plugins-dir`:n.pluginsDir=s()||n.pluginsDir;break;case`--auth-file`:n.authFile=s()||n.authFile;break;case`--api-key`:n.apiKey=s()||``;break;case`--node-dir`:n.nodeDir=s()||``;break;case`--skip-check`:n.skipCheck=!0;break;case`--help`:case`-h`:n.help=!0}}return{help:n.help,options:{host:n.host,port:n.port,pluginsDir:n.pluginsDir,authFile:n.authFile,apiKey:n.apiKey,nodeDir:n.nodeDir,mainPort:n.mainPort,skipCheck:n.skipCheck}}}function Ke(){return[`plugin-host(OpenCode 插件服务:加载订阅插件并暴露成 OpenAI 兼容端点)`,``,`用法: plugin-host [选项]`,` --host HOST 监听地址(默认 127.0.0.1)`,` --port PORT 监听端口(默认 29772;托管形态由 daemon 注入 PORT = 主端口+2)`,` --plugins-dir DIR 插件安装目录(默认 <APP_DIR>/plugins;托管形态由 daemon 注入 PLUGIN_DIR)`,` --auth-file PATH 凭据文件(默认 <APP_DIR>/plugin-auth.json)`,` --api-key KEY 要求客户端携带的 API key(默认不校验;安装面是写操作,建议设)`,` --node-dir DIR 托管 Node 目录(安装面用其中的 node+npm;默认自动探测)`,` --skip-check 跳过启动预检`,``,`端点: GET /health · GET /plugins · GET / · GET /packages · GET /packages/<name>`,` POST /packages({package, version?})· DELETE /packages/<name>`,` GET /p/<id>/v1/models · POST /p/<id>/v1/{chat/completions|messages|responses}`,` GET /login/<id>(登录方式与状态)· POST /login/<id>(起登录,{method?})`,` DELETE /login/<id>(退出登录:删本机凭据 + 清会话)`,``,`环境变量(托管形态注入): PLUGIN_DIR · PORT · NODE_DIR`,``].join(`
|
|
2
|
+
import{basename as e,dirname as t,join as n,resolve as r}from"node:path";import{fileURLToPath as i,pathToFileURL as a}from"node:url";import{createHash as o,randomBytes as s}from"node:crypto";import{existsSync as c,mkdirSync as l,readFileSync as u,readdirSync as d,renameSync as f,rmSync as p,statSync as m,writeFileSync as h}from"node:fs";import{AsyncLocalStorage as ee}from"node:async_hooks";import{homedir as te}from"node:os";import{cwd as ne}from"node:process";import{spawn as re}from"node:child_process";import{createServer as ie}from"node:http";var ae=20,oe=2e3,se=1e4,g=3e4;function ce(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function le(e){return e instanceof Error?e.message:String(e)}var _=class extends Error{constructor(){super(`凭据文件内容异常(非合法 JSON 或形状不符),已拒绝写入以免覆盖现有凭据;请修复或备份后删除该文件`),this.name=`AuthFileCorruptError`}};function ue(e){let t;try{t=u(e,`utf-8`)}catch{throw new _}let n;try{n=JSON.parse(t)}catch{throw new _}if(typeof n!=`object`||!n||Array.isArray(n))throw new _;let r={};for(let[e,t]of Object.entries(n)){if(typeof t!=`object`||!t||Array.isArray(t))throw new _;r[e]=t}return r}function de(e){try{let t=JSON.parse(u(e,`utf-8`));if(typeof t!=`object`||!t||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t))typeof r==`object`&&r&&!Array.isArray(r)&&(n[e]=r);return n}catch{return{}}}function fe(e,n){let r=`${e}.${`${process.pid}.${s(6).toString(`hex`)}`}.tmp`;try{l(t(e),{recursive:!0}),h(r,`${JSON.stringify(n,null,2)}\n`,{encoding:`utf-8`,mode:384}),f(r,e)}finally{try{p(r,{force:!0})}catch{}}}function v(e,t){return c(e)?e:t.find(e=>c(e))??null}var pe=class{#e;#t;#n;#r=null;#i=null;#a=-1;#o=!1;#s=0;constructor(e){this.#e=e.file,this.#t=e.legacyFiles??[],this.#n=e.log,this.#l()}get path(){return this.#e}read(){this.#o&&Date.now()>=this.#s&&this.#l();let e=v(this.#e,this.#t);if(e===null)return{};try{let t=m(e).mtimeMs;if(this.#r!==null&&this.#i===e&&this.#a===t)return{...this.#r};let n=de(e);return this.#r=n,this.#i=e,this.#a=t,{...n}}catch{return{}}}invalidate(){this.#r=null,this.#i=null,this.#a=-1}mutate(e){return this.#d(()=>{let t=e(this.#c());return t===null?null:(fe(this.#e,t),this.#u(),this.#r=t,this.#i=this.#e,this.#a=m(this.#e).mtimeMs,{...t})})}#c(){let e=v(this.#e,this.#t);return e===null?{}:ue(e)}#l(){let e=this.#t.find(e=>c(e));if(e===void 0){this.#o=!1;return}try{let t=this.#d(()=>c(e)?c(this.#e)?(p(e,{force:!0}),this.#n?.(`[auth] 已清理旧凭据文件:${e}(新文件已存在)`),!0):(f(e,this.#e),this.#n?.(`[auth] 凭据文件已迁移:${e} → ${this.#e}`),!0):!0);this.#o=!t,this.#s=t?0:Date.now()+g}catch(e){this.#o=!0,this.#s=Date.now()+g,this.#n?.(`[auth] 旧凭据文件处理失败(继续只读旧文件,${String(g/1e3)}s 后重试):${le(e)}`)}}#u(){for(let e of this.#t)if(c(e))try{p(e,{force:!0}),this.#n?.(`[auth] 已清理旧凭据文件:${e}`)}catch{}this.#o=!1}#d(r){let i=`${this.#e}.lock`,a=`${process.pid}.${s(8).toString(`hex`)}`;l(t(i),{recursive:!0});let o=Date.now()+oe;for(;;)try{l(i),h(n(i,`owner`),a,`utf-8`);break}catch(t){if(t.code!==`EEXIST`)throw t;try{if(Date.now()-m(i).mtimeMs>se&&this.#m(i))continue}catch{}if(Date.now()>o)throw Error(`获取凭据文件锁超时:${e(i)}`);ce(ae)}try{return r()}finally{this.#p(i,a)}}#f(e){try{return u(n(e,`owner`),`utf-8`)}catch{return null}}#p(e,t){try{if(this.#f(e)!==t)return;p(e,{recursive:!0,force:!0})}catch{}}#m(e){let t=this.#f(e),n=`${e}.stale.${s(4).toString(`hex`)}`;try{f(e,n)}catch{return!1}let r=this.#f(n);if(t!==null&&r!==null&&t!==r){try{f(n,e)}catch{}return!1}try{p(n,{recursive:!0,force:!0})}catch{}return!0}},y=new ee;function b(e,t,n){return y.run({providerId:e,generation:t},n)}var me=3e5,he=864e5,ge=15e3,_e=3e4,x=new class{renewing=new Map;failed=new Map;clear(e){let t=`${e}\0`;for(let e of[...this.renewing.keys()])e.startsWith(t)&&this.renewing.delete(e);for(let e of[...this.failed.keys()])e.startsWith(t)&&this.failed.delete(e)}};function S(e){let t=`${String(e?.refresh??``)}\0${String(e?.access??``)}`;return o(`sha256`).update(t).digest(`hex`).slice(0,16)}function ve(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.min(e,he):me}function ye(e,t){if(t.type!==`oauth`)return 0;let n=Number(t.expires);return Number.isFinite(n)&&n>0?Math.max(1,n-e):0}var be=class{#e;constructor(e){this.#e=e}clear(e){(this.#e.registry??x).clear(e)}async ensureFresh(e){let t=this.#e.get(e),n=this.#e.refreshOf(e);if(t===void 0||n===void 0)return;let r=this.#n(),i=ye(ve(this.#e.leadOf(e)),t);if(!i||r<i)return;let a=this.#r(),o=`${e}\0${S(t)}`,s=a.failed.get(o);if(s!==void 0){if(r-s<_e)return;a.failed.delete(o)}let c=a.renewing.get(o);c===void 0&&(c=this.#t(e,t,n,o).finally(()=>a.renewing.delete(o)),a.renewing.set(o,c));let l;await Promise.race([c,new Promise(e=>{l=setTimeout(e,ge)})]),clearTimeout(l)}async#t(e,t,n,r){let i=this.#r(),a=this.#e.generation(e);try{let o=await b(e,a,()=>n({...t}));if(typeof o!=`object`||!o||Array.isArray(o)){i.failed.delete(r);return}let s=this.#e.get(e);if(s===void 0||this.#e.generation(e)!==a){i.failed.delete(r),this.#e.log?.(`[auth] 已丢弃过期的续期结果:${e}`);return}if(S(s)!==S(t)){i.failed.delete(r),this.#e.log?.(`[auth] 凭据已由供应商续期:${e}`);return}if(!this.#e.save(e,{...t,...o},{generation:a})){i.failed.delete(r),this.#e.log?.(`[auth] 已丢弃过期的续期结果:${e}`);return}i.failed.delete(r),this.#e.log?.(`[auth] 凭据已续期:${e}`)}catch(t){i.failed.set(r,this.#n()),this.#e.log?.(`[auth] 凭据续期失败:${e}(${t instanceof Error?t.message:String(t)})`)}}#n(){return this.#e.now?.()??Date.now()}#r(){return this.#e.registry??x}},C=class extends Error{status;constructor(e,t){super(t),this.name=`AuthError`,this.status=e}},xe=class extends Error{constructor(e){super(e),this.name=`AuthFailure`}},Se=2e3,Ce=6e5;function w(e){return e instanceof Error?e.message:String(e)}function we(e){return`auth`in e}function Te(e,t){let n=e.when;if(n!==void 0){let e=typeof n.key==`string`?t[n.key]:void 0;if(e===void 0)return!1;let r=e===n.value;if(n.op===`eq`?!r:r)return!1}return!(typeof e.condition==`function`&&!e.condition(t))}function Ee(e,t){let n=[];for(let r of e.prompts??[])typeof r.key!=`string`||r.key===``||r.key in t||Te(r,t)&&n.push(r);return n}function De(e){return e.map(e=>({type:typeof e.type==`string`?e.type:`text`,key:typeof e.key==`string`?e.key:``,message:typeof e.message==`string`?e.message:``,placeholder:typeof e.placeholder==`string`?e.placeholder:``,options:Array.isArray(e.options)?e.options:[]}))}function Oe(e){for(let t of[`accountId`,`email`,`name`,`account`,`uid`]){let n=e[t];if(typeof n==`string`&&n.trim()!==``)return n}return null}function T(e,t){return t==null||t===``||typeof e.accountId==`string`&&e.accountId!==``?e:{...e,accountId:t}}var ke=class{#e;#t;#n;#r;#i=new Map;#a=new Set;#o=new Map;#s=new Map;constructor(e){this.#e=new pe({file:e.file,legacyFiles:e.legacyFiles??[],log:e.log}),this.#t=e.now??Date.now,this.#n=e.log,this.#r=new be({get:e=>this.get(e),generation:e=>this.generation(e),save:(e,t,n)=>this.save(e,t,n),refreshOf:e=>this.#c(e)?.refresh,leadOf:e=>this.#c(e)?.refreshLead,now:e.now,log:e.log,registry:e.registry});for(let t of e.adapters??[])this.register(t)}register(e){let t=this.#s.get(e.id)??[];return this.#s.set(e.id,[...t,e].sort((e,t)=>(t.priority??10)-(e.priority??10))),()=>{let t=this.#s.get(e.id);if(t===void 0)return;let n=t.filter(t=>t!==e);if(n.length===0?this.#s.delete(e.id):this.#s.set(e.id,n),n.length===0){let t=this.#o.get(e.id);t!==void 0&&this.#u(t),this.#o.delete(e.id),this.#r.clear(e.id)}e.dispose?.()}}#c(e){return this.#s.get(e)?.[0]}hasAdapter(e){return this.#c(e)!==void 0}methodsOf(e){return(this.#c(e)?.methods()??[]).map(e=>({type:e.type,label:e.label??``}))}reload(){this.#e.invalidate()}generation(e){return this.#i.get(e)??0}locked(e){return this.#a.has(e)}lock(e){this.#a.add(e)}beginLogin(e){let t=this.generation(e)+1;return this.#i.set(e,t),this.#a.delete(e),t}get(e){let t=this.#e.read()[e];return t===void 0?void 0:{...t}}has(e){return e in this.#e.read()}providers(){return Object.keys(this.#e.read())}save(e,t,n){return n?.generation!==void 0&&n.generation!==this.generation(e)||this.#a.has(e)?!1:(this.#e.mutate(n=>({...n,[e]:{...t}})),!0)}saveFromPlugin(e,t){let n=y.getStore(),r=n?.providerId===e?{generation:n.generation}:void 0;return this.save(e,t,r)}remove(e){let t=this.generation(e)+1;return this.#i.set(e,t),this.#a.add(e),this.#e.mutate(t=>{if(!(e in t))return null;let n={...t};return delete n[e],n}),t}status(e){let t=this.get(e),n=t!==void 0&&typeof t.expires==`number`&&Number.isFinite(t.expires)?t.expires:null;return{provider:e,signedIn:t!==void 0,type:t!==void 0&&typeof t.type==`string`?t.type:null,account:t===void 0?null:Oe(t),expires:n,expiresInMs:n===null?null:Math.max(0,n-this.#t())}}list(){return[...new Set([...this.#s.keys(),...this.providers()])].sort().map(e=>this.status(e))}view(e){let t=this.#o.get(e);return{provider:e,signedIn:this.has(e),methods:this.methodsOf(e),state:t?.state??`idle`,...t===void 0?{}:{url:t.url,instructions:t.instructions,...t.error===void 0?{}:{error:t.error},...t.accountId===void 0?{}:{accountId:t.accountId},...t.expiresAt===null?{}:{expiresAt:t.expiresAt}}}}async signIn(e,t={}){let n=this.#c(e),r=n?.methods()??[];if(n===void 0||r.length===0)throw new C(400,`${e} 未声明登录方式(auth.methods),无法登录;该供应商可能不需要登录`);if(t.restart!==!0&&this.#o.get(e)?.state===`pending`)return this.view(e);let i=t.method??``,a=t.inputs??{};if(i===``&&r.length>1)return{...this.view(e),needMethod:!0};let o=i===``?r[0]:r.find(e=>(e.label??e.type)===i);if(o===void 0)throw new C(400,`未知登录方式:${i}(可选:${r.map(e=>e.label??`(未命名)`).join(`、`)})`);let s=Ee(o,a);if(s.length>0)return{...this.view(e),needInputs:De(s),inputs:a};let c=(t.key??``).trim();if(o.type===`api`&&c===``)return{...this.view(e),needKey:!0,placeholder:o.placeholder??``,label:o.label??o.type,inputs:a};let l=this.beginLogin(e),u;try{let t={key:c,inputs:a};u=await b(e,l,()=>n.authorize(o,t))}catch(t){if(this.#p(e,l),t instanceof xe)return this.#o.set(e,{state:`failed`,url:``,instructions:``,expiresAt:null,attempt:null,error:t.message,generation:l}),this.#n?.(`[auth] ✗ ${e} 登录失败:${t.message}`),this.view(e);throw t instanceof C?t:new C(502,`起登录流程失败:${w(t)}`)}if(we(u))return this.save(e,T(u.auth,u.account),{generation:l})?(this.#o.set(e,{state:`success`,url:``,instructions:``,expiresAt:null,attempt:null,generation:l,...u.account===void 0||u.account===null||u.account===``?{}:{accountId:u.account}}),this.#n?.(`[auth] ✓ ${e} 登录完成${u.account?`(${u.account})`:``}`),this.view(e)):(this.#o.set(e,{state:`failed`,url:``,instructions:``,expiresAt:null,attempt:null,error:`登录结果已过期(已登出或被新的登录流程取代)`,generation:l}),this.view(e));let d={state:`pending`,url:u.url,instructions:u.instructions,expiresAt:u.expiresAt,attempt:u,generation:l};return this.#o.set(e,d),this.#l(e,d),this.#n?.(`[auth] ▶ ${e} 登录已发起(${o.label??o.type}${u.url===``?``:`,等待浏览器完成`})`),this.view(e)}async poll(e){let t=this.#o.get(e);return t===void 0||t.state!==`pending`||t.attempt===null?this.view(e):this.#d(e,t)}#l(e,t){t.deadline=t.expiresAt??this.#t()+Ce;let n=()=>{if(this.#o.get(e)!==t||t.state!==`pending`)return;let r=setTimeout(()=>{this.#o.get(e)===t&&t.state===`pending`&&this.#d(e,t).catch(()=>void 0).finally(n)},Se);r.unref?.(),t.timer=r};n()}#u(e){e.timer!==null&&e.timer!==void 0&&clearTimeout(e.timer),e.timer=null}#d(e,t){if(t.polling!==null&&t.polling!==void 0)return t.polling;let n=this.#f(e,t).finally(()=>{t.polling===n&&(t.polling=null)});return t.polling=n,n}async#f(e,t){let n=t.deadline??t.expiresAt;if(n!=null&&this.#t()>n)return this.#u(t),this.#o.delete(e),this.#n?.(`[auth] ✗ ${e} 授权已超时`),{...this.view(e),state:`failed`,error:`授权已超时,请重新发起`};let r=t.attempt;if(r===null)return this.view(e);let i;try{i=await r.poll()}catch(n){let r=w(n);return this.#o.get(e)===t?(this.#p(e,t.generation),this.#u(t),this.#o.delete(e),this.#n?.(`[auth] ✗ ${e} 登录失败:${r}`),{...this.view(e),state:`failed`,error:r}):this.view(e)}return this.#o.get(e)!==t||i===null?this.view(e):this.save(e,T(i.auth,i.account),{generation:t.generation})?(t.state=`success`,t.attempt=null,t.error=void 0,this.#u(t),i.account!==void 0&&i.account!==null&&i.account!==``&&(t.accountId=i.account),this.#n?.(`[auth] ✓ ${e} 登录完成${t.accountId?`(${t.accountId})`:``}`),this.view(e)):(t.state=`failed`,t.error=`登录结果已过期(已登出或被新的登录流程取代)`,t.attempt=null,this.#u(t),this.view(e))}signOut(e){let t=this.has(e),n=this.#o.get(e);return n!==void 0&&this.#u(n),this.remove(e),this.#r.clear(e),this.#o.delete(e),this.#c(e)?.dispose?.(),t&&this.#n?.(`[auth] ⏏ ${e} 已退出登录`),this.view(e)}async ensureFresh(e){await this.#r.ensureFresh(e)}#p(e,t){this.generation(e)===t&&this.get(e)===void 0&&this.#a.add(e)}};function E(e,...t){console.log(e,...t)}function D(e,...t){console.warn(e,...t)}function Ae(e,...t){console.error(e,...t)}function O(e){if(e===void 0)return;let t=e.trim();return t===``?void 0:t}function je(e){let t=`--${e}`,n=`${t}=`,r=process.argv;for(let e=0;e<r.length;e+=1){let i=r[e]??``;if(i.startsWith(n))return O(i.slice(n.length));if(i===t){let t=r[e+1]??``;return t.startsWith(`-`)?void 0:O(t)}}}function k(e,t){return je(e)??O(process.env[t])}var Me=65535;function Ne(e){let t=O(e);if(t===void 0)return;let n=Number(t);return Number.isInteger(n)&&n>0&&n<=Me?n:void 0}var Pe=(()=>{let e=k(`app-dir`,`ELLM_APP_DIR`),t=e===void 0?void 0:r(ne(),e),n=je(`port`),i=Ne(n??O(process.env.ELLM_PORT));n!==void 0&&i===void 0&&D(`--port=${n} 无效(需为 1-65535 的整数),已忽略:本次不生效、也不会写入配置文件。`);let a=k(`node-mirror`,`ELLM_NODE_MIRROR`),o=k(`node-bin`,`ELLM_NODE_BIN`);return t!==void 0&&(process.env.ELLM_APP_DIR=t),a!==void 0&&(process.env.ELLM_NODE_MIRROR=a),o!==void 0&&(process.env.ELLM_NODE_BIN=o),{appDir:t,port:i,nodeMirror:a,nodeBin:o}})(),A=t(i(import.meta.url)),j;function Fe(){return n(te(),`.ezllm`)}function M(){return j===void 0&&(j=Pe.appDir??Fe()),j}function Ie(){return r(M(),`plugins`)}function Le(){return r(M(),`provider-auth.json`)}function Re(){return r(M(),`plugin-auth.json`)}function ze(e){try{let t=u(n(e,`package.json`),`utf-8`).replace(/^\uFEFF/,``);return JSON.parse(t)}catch{return null}}function N(e,n){let r=A;for(let i=0;i<n;i++){if(ze(r)?.name===e)return r;r=t(r)}return null}N(`ezllm`,5)??r(A,`..`),N(`ellm`,6);var Be=`https://registry.npmmirror.com/`,Ve=`https://registry.npmjs.org/`;function He(){return[Be,Ve]}async function P(e,t=He()){let n=[];for(let r of t)try{return{value:await e(r),registry:r}}catch(e){n.push({registry:r,message:e instanceof Error?e.message:String(e),error:e})}if(n.length===0)throw Error(`没有任何可用的 npm registry`);let r=[...new Set(n.map(e=>e.message))],i=r.length===1?`所有源返回相同错误(已依次尝试:${t.join(`、`)}):\n${r[0]??``}`:`所有源都失败:\n${n.map(e=>`- ${e.registry}:${e.message}`).join(`
|
|
3
|
+
`)}`,a=Error(i);throw a.cause=n[n.length-1]?.error,a}var Ue=/^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*(@[a-zA-Z0-9.^~<>=*|xX -]+)?$/,F=3e5,We=65536,Ge=`npm_config_`;function I(e){let t=e.trim();if(t===``||!Ue.test(t))return null;let n=t.lastIndexOf(`@`);return n<=0?{name:t,version:``}:{name:t.slice(0,n),version:t.slice(n+1)}}function Ke(e,t=e=>e){let n=e.trim();if(n===``)return null;if(n.startsWith(`./`)||n.startsWith(`../`)||n.startsWith(`file:`)||n.startsWith(`/`)||/^[a-zA-Z]:[\\/]/.test(n)||n.startsWith(`\\\\`)){let e=n.startsWith(`file:`)?n.slice(5):n;return e.trim()===``?null:{kind:`path`,path:t(e.trim())}}let r=I(n);return r===null?null:{kind:`npm`,name:r.name,version:r.version}}function qe(e){return c(e)?m(e).isDirectory()?c(n(e,`package.json`))?null:`目录里没有 package.json:${e}`:`不是目录:${e}`:`目录不存在:${e}`}function L(e){return I(e)?.name??null}function Je(e,t){return n(e,`node_modules`,...t.split(`/`))}function Ye(e,r){let i=e=>e.endsWith(`npm-cli.js`)&&c(e),a=e=>{for(let t of[[`node_modules`,`npm`,`bin`,`npm-cli.js`],[`lib`,`node_modules`,`npm`,`bin`,`npm-cli.js`],[`bin`,`npm-cli.js`]]){let r=n(e,...t);if(i(r))return r}return null};if(e!==``){let t=a(e);if(t!==null)return t;if(i(e))return e;let r=n(e,`npm`,`bin`,`npm-cli.js`);if(i(r))return r}let o=n(t(process.execPath),`node_modules`,`npm`,`bin`,`npm-cli.js`);if(i(o))return o;let s=n(t(process.execPath),`..`,`lib`,`node_modules`,`npm`,`bin`,`npm-cli.js`);if(i(s))return s;if(r!==null){let e=n(r,`node`),t=a(e);if(t!==null)return t;try{for(let t of d(e)){let r=a(n(e,t));if(r!==null)return r}}catch{}}return null}function Xe(e,t,n){return new Promise(r=>{let i=re(e,[...t],{shell:n.shell,cwd:n.cwd,windowsHide:!0,...n.env===void 0?{}:{env:n.env}}),a=``,o=e=>{a.length<We&&(a+=e.toString(`utf8`))};i.stdout.on(`data`,o),i.stderr.on(`data`,o);let s=setTimeout(()=>{a+=`\n[npm 超时 ${String(F/1e3)}s,已终止]`,i.kill()},F);i.on(`error`,e=>{clearTimeout(s),r({code:null,output:`${a}\n${e.message}`})}),i.on(`close`,e=>{clearTimeout(s),r({code:e,output:a})})})}function Ze(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(n.toLowerCase().startsWith(Ge)||(t[n]=r));return t}async function R(e,t,n,r,i){let a={...r??{}};i!==void 0&&(a.NPM_CONFIG_USERCONFIG=i,a.NPM_CONFIG_GLOBALCONFIG=`${i}.global-empty`);let o={...Ze(process.env),...a};return e===null?Xe(process.platform===`win32`?`npm.cmd`:`npm`,t,{shell:process.platform===`win32`,cwd:n,env:o}):Xe(process.execPath,[e,...t],{shell:!1,cwd:n,env:o})}async function Qe(e,t){let n=await P(async n=>{let r=await R(e.npmCli,[`view`,t,`version`,`--json`,`--registry`,n],e.pluginsDir,e.env,e.userconfig),i=r.code===0?$e(r.output):null;if(i===null)throw Error(`npm view 未能取到 ${t} 的版本(源 ${n})`);return i}).catch(()=>null);return n===null?null:n.value}function $e(e){let t=e=>{try{let t=JSON.parse(e);return typeof t==`string`&&t!==``?t:null}catch{return null}},n=e.trim(),r=t(n);if(r!==null)return r;let i=n.split(/\r?\n/);for(let e=i.length-1;e>=0;e--){let n=(i[e]??``).trim();if(n===``)continue;let r=t(n);if(r!==null)return r}return null}function et(e){l(e,{recursive:!0});let t=n(e,`package.json`);c(t)||h(t,`${JSON.stringify({name:`ezllm-plugins`,private:!0,version:`0.0.0`},null,2)}\n`,`utf8`)}async function tt(e,t){let n=Ke(t,e=>r(e));if(n===null)return{ok:!1,message:`不是合法的 npm 包规格,也不是本机目录:${t}`};if(n.kind===`path`){let e=qe(n.path);if(e!==null)return{ok:!1,message:e}}et(e.pluginsDir);let i=n.kind===`npm`?n.version===``?n.name:`${n.name}@${n.version}`:`file:${n.path}`,a=[`install`,`--no-audit`,`--no-fund`,`--save`,i];return e.log(`[plugin-host] npm install ${i}`),await P(async t=>{let n=await R(e.npmCli,[...a,`--registry`,t],e.pluginsDir,e.env,e.userconfig);if(n.code!==0){let e=n.output.trim().slice(-2e3),t=/npm (?:error|ERR!)\s*(?:code\s*)?E404|is not in this registry/i.test(n.output);throw Error(t?`npm 源里没有 ${i}(404)——请确认包名与版本已发布\n${e}`:`npm install 失败(退出码 ${String(n.code)}):\n${e}`)}return{ok:!0,output:n.output.trim()}}).then(({value:e})=>e).catch(e=>({ok:!1,message:e instanceof Error?e.message:`npm install 失败:${String(e)}`}))}async function nt(e,t){let n=L(t);if(n===null)return{ok:!1,message:`不是合法的 npm 包名:${t}`};let r=Je(e.pluginsDir,n);if(!c(r))return{ok:!1,message:`未安装:${n}`};e.log(`[plugin-host] npm uninstall ${n}`);let i=await R(e.npmCli,[`uninstall`,`--no-audit`,`--no-fund`,n],e.pluginsDir,e.env,e.userconfig);if(c(r))try{p(r,{recursive:!0,force:!0}),e.log(i.code===0?`[plugin-host] npm 未清理 ${n} 的目录,已手动删除`:`[plugin-host] npm uninstall 退出码 ${String(i.code)},已手动删除 ${n} 的目录`)}catch(e){return{ok:!1,message:`卸载 ${n} 未完成:npm 退出码 ${String(i.code)},且目录残留删除失败(${e instanceof Error?e.message:String(e)})\n${i.output.trim().slice(-1500)}`}}return i.code!==0&&!c(r)?{ok:!0,output:`npm 退出码 ${String(i.code)}(目录已删除)\n${i.output.trim().slice(-1500)}`}:i.code===0?{ok:!0,output:i.output.trim()}:{ok:!1,message:`npm uninstall 失败(退出码 ${String(i.code)}):\n${i.output.trim().slice(-2e3)}`}}function rt(e){for(let t of[`README.md`,`readme.md`,`README.MD`,`README`]){let r=n(e,t);if(c(r))try{return u(r,`utf8`).slice(0,204800)}catch{return null}}return null}var it=[{npm:`@ai-sdk/openai-compatible`,protocol:`openai`,path:`chat/completions`},{npm:`@ai-sdk/anthropic`,protocol:`anthropic`,path:`messages`},{npm:`@ai-sdk/openai`,protocol:`openai-responses`,path:`responses`}];function at(e){return typeof e!=`string`||e===``?null:it.find(t=>t.npm===e)??null}function ot(e){return new Proxy(async()=>({data:void 0}),{get(t,n){if(n!==`then`)return ot(`${e}.${String(n)}`)},apply(){return Promise.resolve({data:void 0})}})}function st(e){let t={auth:{set:async t=>{let n=t?.path?.id??t?.id??t?.providerID,r=typeof n==`string`&&n!==``?n:e.scope?.key??y.getStore()?.providerId,i=t?.body??t?.auth;return typeof r==`string`&&r!==``&&typeof i==`object`&&i&&await e.saveAuth(r,i),{data:!0}},remove:async()=>({data:!0})},tui:{showToast:async()=>({data:!0})},app:{log:async()=>({data:!0})},config:{get:async()=>({data:{provider:{}}})}},n=(e,t)=>new Proxy(e,{get(e,r){if(typeof r==`symbol`)return Reflect.get(e,r);if(r in e){let i=e[r];return typeof i==`object`&&i?n(i,`${t}.${r}`):i}if(r!==`then`)return ot(`${t}.${r}`)}});return n(t,`client`)}function ct(e){return{client:st(e),directory:e.directory,worktree:e.directory,project:{id:`ezllm`,worktree:e.directory},serverUrl:new URL(`http://127.0.0.1:4096`),$:()=>{throw Error("插件请求了 shell(`$`),但 ezllm 的插件宿主不提供:当前插件生态没有任何插件使用它;若某个插件真的需要,请提交 issue 说明用途(提供 shell 等于给第三方代码任意命令执行能力)")}}}var lt=`@magpie-community`,ut=`ezllmPlugin`;function dt(e){let t=e.exports,n=typeof t==`string`?t:typeof t==`object`&&t?t[`.`]:void 0,r=typeof e.main==`string`?e.main:n;return typeof r==`string`&&r!==``?r:void 0}function ft(e,t){let i=n(e,`package.json`);if(!c(i))return null;let a;try{let e=JSON.parse(u(i,`utf-8`));if(typeof e!=`object`||!e||Array.isArray(e))return null;a=e}catch{return null}let o=typeof a.name==`string`&&a.name!==``?a.name:t;if(!o.startsWith(`${lt}/`)&&a[ut]!==!0)return null;let s=dt(a);if(s===void 0)return null;let l=a.repository,d=typeof l==`string`?l:typeof l==`object`&&l&&typeof l.url==`string`?String(l.url):``;return{name:o,version:typeof a.version==`string`?a.version:`0.0.0`,main:s,description:typeof a.description==`string`?a.description:``,license:typeof a.license==`string`?a.license:``,repository:d,dir:r(e)}}function z(e){let t=n(e,`node_modules`);if(!c(t))return[];let r;try{r=d(t,{withFileTypes:!0})}catch{return[]}let i=[];for(let e of r){if(e.name.startsWith(`.`))continue;if(!e.name.startsWith(`@`)){let r=ft(n(t,e.name),e.name);r!==null&&i.push(r);continue}let r=n(t,e.name),a;try{a=d(r,{withFileTypes:!0})}catch{continue}for(let t of a){let a=ft(n(r,t.name),`${e.name}/${t.name}`);a!==null&&i.push(a)}}return i}function pt(e){return n(e.dir,e.main)}function B(e,t){return z(e).find(e=>e.name===t)}function mt(e){let t=[];for(let[n,r]of Object.entries(e))n==="default"||n.startsWith(`_`)||typeof r==`function`&&t.push([n,r]);return t}function ht(e,t,n){let r=[],i=e=>{let t=n.find(t=>t.auth?.provider===e)??n.find(t=>t.provider?.id===e);return t===void 0||t.auth===void 0?null:{hooks:t,auth:t.auth}};for(let[n,a]of Object.entries(t.provider??{})){let t=a??{},o=i(n),s=at(typeof t.npm==`string`?t.npm:void 0);r.push({id:n,name:typeof t.name==`string`&&t.name!==``?t.name:n,source:{package:e.name,version:e.version},protocol:s?.protocol??null,path:s?.path??``,models:Object.keys(t.models??{}),config:t,hooks:o,capabilities:{models:typeof o?.hooks.provider?.models==`function`,usage:typeof o?.auth.usage==`function`,checkin:typeof o?.auth.checkin==`function`,refresh:typeof o?.auth.refresh==`function`,chatHeaders:typeof o?.hooks[`chat.headers`]==`function`}})}return r}async function gt(e,t){let n=[],r=[];for(let i of z(e)){let e=pt(i);if(!c(e)){r.push(`${i.name}: 入口不存在(${e})`);continue}let o;try{o=await import(a(e).href)}catch(e){r.push(`${i.name}: 导入失败(${e instanceof Error?e.message:String(e)})`);continue}let s=mt(o);if(s.length===0){r.push(`${i.name}: 没有导出插件工厂函数`);continue}let l=[],u={provider:{}};for(let[e,n]of s)try{let e=await n(ct(t));l.push(e),typeof e.config==`function`&&await e.config(u)}catch(t){r.push(`${i.name}#${e}: 工厂/config 失败(${t instanceof Error?t.message:String(t)})`)}if(l.length===0)continue;let d=ht(i,u,l);n.push({package:i.name,version:i.version,providers:d,hooks:l})}return{plugins:n,errors:r}}function V(e){let t=new Set,n=[],r=[...e.errors];for(let i of e.plugins)for(let e of i.providers){if(t.has(e.id)){r.push(`${e.id}: provider id 重复(${e.source.package}),已忽略后一个`);continue}t.add(e.id),n.push(e)}return{providers:n,errors:r}}function _t(e,t=process.env){let n={host:`127.0.0.1`,port:Number(t.PORT||29772),pluginsDir:t.PLUGIN_DIR||``,authFile:``,apiKey:t.PLUGIN_HOST_KEY||``,nodeDir:t.NODE_DIR||``,mainPort:Number(t.MAIN_PORT||0),skipCheck:!1,help:!1};for(let t=0;t<e.length;t+=1){let r=e[t]??``,i=r.indexOf(`=`),a=r.startsWith(`--`)&&i>=0?r.slice(0,i):r,o=r.startsWith(`--`)&&i>=0?r.slice(i+1):void 0,s=()=>o===void 0?e[++t]:o;switch(a){case`--host`:n.host=s()||n.host;break;case`--port`:n.port=Number(s());break;case`--plugins-dir`:n.pluginsDir=s()||n.pluginsDir;break;case`--auth-file`:n.authFile=s()||n.authFile;break;case`--api-key`:n.apiKey=s()||``;break;case`--node-dir`:n.nodeDir=s()||``;break;case`--skip-check`:n.skipCheck=!0;break;case`--help`:case`-h`:n.help=!0}}return{help:n.help,options:{host:n.host,port:n.port,pluginsDir:n.pluginsDir,authFile:n.authFile,apiKey:n.apiKey,nodeDir:n.nodeDir,mainPort:n.mainPort,skipCheck:n.skipCheck}}}function vt(){return[`plugin-host(OpenCode 插件服务:加载订阅插件并暴露成 OpenAI 兼容端点)`,``,`用法: plugin-host [选项]`,` --host HOST 监听地址(默认 127.0.0.1)`,` --port PORT 监听端口(默认 29772;托管形态由 daemon 注入 PORT = 主端口+2)`,` --plugins-dir DIR 插件安装目录(默认 <APP_DIR>/plugins;托管形态由 daemon 注入 PLUGIN_DIR)`,` --auth-file PATH 凭据文件(默认 <APP_DIR>/provider-auth.json;旧名 plugin-auth.json 自动迁移)`,` --api-key KEY 要求客户端携带的 API key(默认不校验;安装面是写操作,建议设)`,` --node-dir DIR 托管 Node 目录(安装面用其中的 node+npm;默认自动探测)`,` --skip-check 跳过启动预检`,``,`端点: GET /health · GET /plugins · GET / · GET /packages · GET /packages/<name>`,` POST /packages({package, version?})· DELETE /packages/<name>`,` GET /p/<id>/v1/models · POST /p/<id>/v1/{chat/completions|messages|responses}`,` GET /login/<id>(登录方式与状态)· POST /login/<id>(起登录,{method?})`,` DELETE /login/<id>(退出登录:删本机凭据 + 清会话)`,``,`环境变量(托管形态注入): PLUGIN_DIR · PORT · NODE_DIR`,``].join(`
|
|
4
4
|
`)+`
|
|
5
|
-
`}var qe=3e5,Je=864e5,Ye=15e3,Xe=3e4,L=new class{renewing=new Map;failed=new Map;clear(e){let t=`${e}\0`;for(let e of[...this.renewing.keys()])e.startsWith(t)&&this.renewing.delete(e);for(let e of[...this.failed.keys()])e.startsWith(t)&&this.failed.delete(e)}};function R(e){let t=`${String(e?.refresh??``)}\0${String(e?.access??``)}`;return h(`sha256`).update(t).digest(`hex`).slice(0,16)}function Ze(e){let t=e.refreshLead;return typeof t==`number`&&Number.isFinite(t)&&t>=0?Math.min(t,Je):qe}function Qe(e,t){if(typeof e.refresh!=`function`||t.type!==`oauth`)return 0;let n=Number(t.expires);return Number.isFinite(n)&&n>0?Math.max(1,n-Ze(e)):0}var $e=class{#e;#t;#n;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}current(){return this.#n.store.get(this.#e)}generation(){return this.#n.store.generation(this.#e)}getAuth=async()=>this.current();async ensureFresh(){let e=this.#n.now?.()??Date.now(),t=this.current();if(t===void 0)return;let n=Qe(this.#t,t);if(!n||e<n)return;let r=this.#n.registry??L,i=`${this.#e}\0${R(t)}`,a=r.failed.get(i);if(a!==void 0){if(e-a<Xe)return;r.failed.delete(i)}let o=r.renewing.get(i);o===void 0&&(o=this.#r(t,i).finally(()=>r.renewing.delete(i)),r.renewing.set(i,o));let s;await Promise.race([o,new Promise(e=>{s=setTimeout(e,Ye)})]),clearTimeout(s)}async#r(e,t){let n=this.#n.registry??L,r=this.#t.refresh;if(r===void 0)return;let i=this.#n.store.generation(this.#e);try{let a=await O(this.#e,i,()=>r({...e},this.#n.providerInfo));if(typeof a!=`object`||!a||Array.isArray(a)){n.failed.delete(t);return}let o=this.current();if(o===void 0||this.#n.store.generation(this.#e)!==i){n.failed.delete(t),this.#n.log?.(`[plugin-host] 已丢弃过期的续期结果:${this.#e}`);return}if(R(o)!==R(e)){n.failed.delete(t),this.#n.log?.(`[plugin-host] 凭据已由插件续期:${this.#e}`);return}if(!this.#n.store.save(this.#e,{...e,...a},{generation:i})){n.failed.delete(t),this.#n.log?.(`[plugin-host] 已丢弃过期的续期结果:${this.#e}`);return}n.failed.delete(t),this.#n.log?.(`[plugin-host] 凭据已续期:${this.#e}`)}catch(e){n.failed.set(t,this.#n.now?.()??Date.now()),this.#n.log?.(`[plugin-host] 凭据续期失败:${this.#e}(${e instanceof Error?e.message:String(e)})`)}}},et=class extends Error{status;detail;constructor(e,t,n){super(t),this.name=`HttpError`,this.status=e,this.detail=n}};function z(e,t){return{error:{message:e,type:t}}}function B(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function tt(e){let t=e.search(/[?#]/);return t>=0?e.slice(0,t):e}function V(e,t,n){if(e.headersSent){try{e.end()}catch{}return}e.writeHead(t,{"Content-Type":`application/json`}),e.end(JSON.stringify(n))}function H(e,t,n){V(e,t,{detail:n})}function U(e=process.env){return Number(e.PLUGIN_HOST_MAX_BODY||33554432)}function W(e,t){return new Promise((n,r)=>{let i=[],a=0;e.on(`data`,n=>{if(a+=n.length,a>t){e.destroy(),r(new et(413,`request body too large`,z(`request body too large`,`invalid_request_error`)));return}i.push(n)}),e.on(`end`,()=>{n(Buffer.concat(i))}),e.on(`error`,r)})}async function*nt(e){if(!e)return;let t=e.getReader();try{for(;;){let{done:e,value:n}=await t.read();if(e)break;n&&(yield Buffer.isBuffer(n)?n:Buffer.from(n))}}finally{try{t.releaseLock()}catch{}}}var rt=new Set([`host`,`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`content-length`,`authorization`,`x-api-key`,`x-plugin-session`]),it=`x-plugin-session`;function at(e,t){return t===void 0||t===``?{}:e===`anthropic`?{"x-api-key":t}:{authorization:`Bearer ${t}`}}function ot(e){let t={};for(let[n,r]of Object.entries(e.headers)){let e=n.toLowerCase();rt.has(e)||r!==void 0&&(t[e]=Array.isArray(r)?r.join(`, `):r)}return t}function st(e,t){let n=new Headers;for(let[r,i]of Object.entries(at(e.provider.protocol,t.apiKey)))n.set(r,i);for(let[e,r]of Object.entries(t.headers??{}))n.set(e,String(r));for(let[t,r]of Object.entries(ot(e.req)))n.set(t,r);return{headers:n,baseURL:typeof t.baseURL==`string`?t.baseURL:``,fetchFn:typeof t.fetch==`function`?t.fetch:fetch}}async function ct(e,t,n){let r=t.provider.hooks?.hooks[`chat.headers`];if(typeof r!=`function`)return;let i={headers:{}};try{await r({sessionID:t.sessionId,agent:`build`,model:{id:t.model,providerID:t.provider.id,api:{id:t.model,npm:t.provider.config.npm}},provider:{source:`custom`,info:t.provider.config,options:t.provider.config.options??{}},message:{id:``,sessionID:t.sessionId,role:`user`,time:{created:Date.now()},agent:`build`,model:{providerID:t.provider.id,modelID:t.model}}},i)}catch(e){n(`[plugin-host] ${t.provider.id}: chat.headers 失败(${e instanceof Error?e.message:String(e)})`);return}for(let[t,n]of Object.entries(i.headers))e.set(t,String(n))}async function lt(e,t){return W(e,t)}async function ut(e,t){let{provider:n,credentials:r}=e;if(n.hooks===null)return{kind:`error`,status:501,message:`插件 ${n.source.package} 声明了 provider「${n.id}」但没有实现 auth 钩子(无登录/转发能力)`};if(await r.ensureFresh(),r.current()===void 0)return{kind:`error`,status:401,message:`${n.id} 尚未登录:请在管理台完成登录后重试`};let i=n.hooks.auth.loader;if(i===void 0)return{kind:`error`,status:501,message:`插件 ${n.source.package} 未实现 auth.loader,无法转发`};let a=r.generation(),o;try{o=await O(n.id,a,()=>i(r.getAuth,n.config))??{}}catch(e){return{kind:`error`,status:502,message:`插件 loader 失败:${e instanceof Error?e.message:String(e)}`}}if(o.baseURL===void 0||o.baseURL===``)return{kind:`error`,status:502,message:`插件 ${n.source.package} 未给出 baseURL(登录态可能已失效)`};let s=st(e,o);await O(n.id,a,()=>ct(s.headers,e,t));let c=`${s.baseURL.replace(/\/+$/,``)}/${e.path.replace(/^\/+/,``)}`;try{return{kind:`ok`,response:await O(n.id,a,()=>s.fetchFn(c,{method:e.method,headers:s.headers,body:e.body.length>0?new Uint8Array(e.body):void 0}))}}catch(e){return{kind:`error`,status:502,message:`上游请求失败:${e instanceof Error?e.message:String(e)}`}}}async function dt(e,t,n){let r={};e.headers.forEach((e,t)=>{let n=t.toLowerCase();n!==`content-encoding`&&n!==`content-length`&&n!==`transfer-encoding`&&(r[n]=e)}),t(e.status,r);for await(let t of nt(e.body))n(t)}function ft(e){return(e.headers.get(`content-type`)??``).includes(`text/event-stream`)}function pt(e,t){try{let t=JSON.parse(e.toString(`utf8`));if(B(t)&&typeof t.model==`string`&&t.model!==``)return t.model}catch{}return t.models[0]??``}function mt(e,t){let n=e.apiKey;if(!n)return;let r=t.headers.authorization,i=t.headers[`x-api-key`],a=``;if(r&&r.startsWith(`Bearer `)&&(a=r.slice(7).trim()),!a&&i&&(a=String(i)),a!==n)throw Error(`invalid api key`)}var ht=[`127.0.0.1`,`localhost`,`[::1]`,`::1`],G=`拒绝的 `;function gt(e){let t=e.trim();if(t===``)return``;if(t.startsWith(`[`)){let e=t.indexOf(`]`);return e<0?t.toLowerCase():t.slice(0,e+1).toLowerCase()}let n=t.lastIndexOf(`:`);return(n<0?t:t.slice(0,n)).toLowerCase()}function _t(e){return e===`0.0.0.0`||e===`::`||e===``}function vt(e,t){if(_t(e.host))return;let n=[...ht,e.host.trim().toLowerCase()],r=gt(String(t.headers.host??``));if(!n.includes(r))throw Error(`${G}Host:${r===``?`(空)`:r}(只接受本机回环地址)`);let i=t.headers.origin;if(typeof i==`string`&&i!==``&&i!==`null`){let e=(()=>{try{return new URL(i).hostname.toLowerCase()}catch{return i.toLowerCase()}})();if(!n.includes(e))throw Error(`拒绝的 Origin:${e}`)}}function K(e,t){return{id:e.id,name:e.name,package:e.source.package,version:e.source.version,protocol:e.protocol,basePath:e.protocol===null?null:`/${e.id}/v1`,models:e.models,signedIn:t,needsLogin:Y(e).length>0,hooks:e.capabilities}}function yt(e,t){let{providers:n}=I(e.loadResult());V(t,200,{status:`ok`,platform:process.platform,node:process.version.replace(/^v/,``),mode:`plugin-host (forwarding + package install)`,port:e.options.port,pluginsDir:e.options.pluginsDir,authFile:e.options.authFile,providers:n.length})}function bt(e,t){let n=e.loadResult(),{providers:r,errors:i}=I(n);V(t,200,{status:`ok`,pluginsDir:e.options.pluginsDir,packages:n.plugins.map(e=>({package:e.package,version:e.version,providers:e.providers.length})),providers:r.map(t=>K(t,e.auth.has(t.id))),errors:i})}function q(e,t){return I(e.loadResult()).providers.filter(e=>e.source.package===t)}function xt(e,t){let n=P(e.options.pluginsDir).map(t=>{let n=q(e,t.name);return{package:t.name,version:t.version,description:t.description,license:t.license,repository:t.repository,loaded:n.length>0,providers:n.map(t=>({id:t.id,name:t.name,protocol:t.protocol,models:t.models.length,signedIn:e.auth.has(t.id),needsLogin:Y(t).length>0}))}});V(t,200,{status:`ok`,pluginsDir:e.options.pluginsDir,count:n.length,packages:n,errors:e.loadResult().errors,canInstall:e.install!==void 0&&e.reload!==void 0})}function St(e,t,n){let r=F(e.options.pluginsDir,t);if(r===void 0)return H(n,404,z(`未安装:${t}`,`not_found`));let i=q(e,r.name);V(n,200,{status:`ok`,package:r.name,version:r.version,description:r.description,license:r.license,repository:r.repository,dir:r.dir,entry:r.main,readme:e.install===void 0?null:je(r.dir),loaded:i.length>0,providers:i.map(t=>K(t,e.auth.has(t.id))),errors:e.loadResult().errors.filter(e=>e.includes(r.name))})}async function J(e){if(e.reload===void 0)return[];try{return await e.reload()}catch(t){return e.log(`[plugin-host] 重载失败:${t instanceof Error?t.message:String(t)}`),[`重载失败:${t instanceof Error?t.message:String(t)}`]}}function Ct(e){let t=e.options.mainPort;if(!Number.isFinite(t)||t<=0){e.log(`[plugin-host] 未由 ezllm 托管(MAIN_PORT 未注入),装/卸后的重启需手动执行`);return}let n=`http://127.0.0.1:${String(t)}/api/service/plugins/restart`;fetch(n,{method:`POST`}).then(t=>{t.ok||e.log(`[plugin-host] 自请重启失败:HTTP ${String(t.status)}(插件已装,重启需手动)`)}).catch(t=>{e.log(`[plugin-host] 自请重启失败:${t instanceof Error?t.message:String(t)}(插件已装,重启需手动)`)})}var wt=Promise.resolve();function Tt(e){let t=wt.then(e,e);return wt=t.then(()=>void 0,()=>void 0),t}async function Et(e,t,n){if(e.install===void 0||e.reload===void 0)return H(n,501,z(`本进程未启用安装能力(未注入 npm 依赖)`,`not_implemented`));let r;try{r=await W(t,U())}catch(e){return H(n,413,z(e instanceof Error?e.message:String(e),`invalid_request_error`))}let i;try{i=r.length===0?{}:JSON.parse(r.toString(`utf8`))}catch{return H(n,400,z(`body 不是合法 JSON`,`invalid_request_error`))}if(!B(i)||typeof i.package!=`string`||i.package.trim()===``)return H(n,400,z(`缺少 package(npm 包名,可带 @版本)`,`invalid_request_error`));let a=i.package.trim(),o=typeof i.version==`string`&&i.version.trim()!==``?i.version.trim():``,s=o===``?a:`${j(a)??a}@${o}`;if(A(s)===null)return H(n,400,z(`不是合法的 npm 包规格:${s}`,`invalid_request_error`));e.log(`[plugin-host] 安装 ${s}`);let c=await ke(e.install,s);if(!c.ok)return e.log(`[plugin-host] ✗ 安装失败:${s}`),H(n,502,z(c.message,`install_error`));let l=await J(e),u=j(s)??s,d=F(e.options.pluginsDir,u);e.log(`[plugin-host] ✓ 已安装 ${u}${d?`@${d.version}`:``}`),V(n,200,{status:`ok`,package:u,version:d?.version??``,loaded:q(e,u).length>0,providers:q(e,u).map(e=>({id:e.id,protocol:e.protocol,models:e.models.length})),npmOutput:c.output.slice(-2e3),reloadErrors:l,restartRequested:e.options.mainPort>0}),Ct(e)}async function Dt(e,t,n){if(e.install===void 0||e.reload===void 0)return H(n,501,z(`本进程未启用卸载能力(未注入 npm 依赖)`,`not_implemented`));e.log(`[plugin-host] 卸载 ${t}`);let r=await Ae(e.install,t);if(!r.ok)return H(n,r.message.startsWith(`未安装`)?404:502,z(r.message,r.message.startsWith(`未安装`)?`not_found`:`install_error`));let i=await J(e);e.log(`[plugin-host] ✓ 已卸载 ${t}`),V(n,200,{status:`ok`,package:t,npmOutput:r.output.slice(-2e3),reloadErrors:i,restartRequested:e.options.mainPort>0}),Ct(e)}var Ot=36e5;async function kt(e,t){let n=e.versionCache??=new Map,r=Date.now(),i=[];for(let t of P(e.options.pluginsDir)){let a=null;if(e.install!==void 0){let i=n.get(t.name);i!==void 0&&r-i.at<Ot?a=i.latest:(a=await Ee(e.install,t.name),a!==null&&n.set(t.name,{latest:a,at:r}))}i.push({package:t.name,current:t.version,latest:a,updateAvailable:a!==null&&a!==t.version})}V(t,200,{status:`ok`,canCheck:e.install!==void 0,packages:i})}function Y(e){let t=e.hooks?.hooks.auth?.methods;return Array.isArray(t)?t:[]}function X(e,t){let n=e.signIns?.get(t.id);return{provider:t.id,signedIn:e.auth.has(t.id),methods:Y(t).map(e=>({type:e.type,label:e.label??``})),state:n?.state??`idle`,...n===void 0?{}:{url:n.url,instructions:n.instructions,...n.error===void 0?{}:{error:n.error},...n.accountId===void 0?{}:{accountId:n.accountId}}}}function At(e,t,n){V(n,200,X(e,t))}function jt(e,t,n){let r=e.auth.has(t.id);e.auth.remove(t.id),L.clear(t.id),e.signIns?.delete(t.id),r&&e.log(`[plugin-host] ⏏ ${t.id} 已退出登录`),V(n,200,X(e,t))}function Mt(e,t){let n=e.when;if(n!==void 0){let e=typeof n.key==`string`?t[n.key]:void 0;if(e===void 0)return!1;let r=e===n.value;if(n.op===`eq`?!r:r)return!1}return!(typeof e.condition==`function`&&!e.condition(t))}function Nt(e,t){let n=[];for(let r of e.prompts??[])typeof r.key!=`string`||r.key===``||r.key in t||Mt(r,t)&&n.push(r);return n}function Pt(e){return e.map(e=>({type:typeof e.type==`string`?e.type:`text`,key:typeof e.key==`string`?e.key:``,message:typeof e.message==`string`?e.message:``,placeholder:typeof e.placeholder==`string`?e.placeholder:``,options:Array.isArray(e.options)?e.options:[]}))}function Z(e,t,n){e.auth.generation(t)===n&&e.auth.get(t)===void 0&&e.auth.lock(t)}async function Ft(e,t,n,r,i,a){let o=e.signIns??=new Map,s=typeof n.placeholder==`string`?n.placeholder:``,c=n.label??n.type;if(i===``)return V(a,200,{...X(e,t),needKey:!0,placeholder:s,label:c,inputs:r});let l=e.auth.beginLogin(t.id),u=()=>e.auth.generation(t.id)===l,d=n.authorize;if(typeof d!=`function`){let n={type:`api`,key:i,...Object.keys(r).length>0?{metadata:r}:{}};return!e.auth.save(t.id,n,{generation:l})||!u()?V(a,200,X(e,t)):(o.set(t.id,{state:`success`,url:``,instructions:``}),e.log(`[plugin-host] ✓ ${t.id} 登录完成(API key 已保存)`),V(a,200,X(e,t)))}let f;try{let e=await O(t.id,l,()=>d(r));f=B(e)?e:{}}catch(n){return Z(e,t.id,l),H(a,502,z(`起登录流程失败:${n instanceof Error?n.message:String(n)}`,`upstream_error`))}if(f.type!==`success`){let n=typeof f.error==`string`&&f.error!==``?f.error:`登录未完成`;return Z(e,t.id,l),u()&&o.set(t.id,{state:`failed`,url:``,instructions:``,error:n}),e.log(`[plugin-host] ✗ ${t.id} 登录失败:${n}`),V(a,200,X(e,t))}let p;if(`refresh`in f){let e={...f};delete e.type,delete e.provider,p={...e,type:`oauth`}}else{let e=typeof f.key==`string`&&f.key!==``?f.key:i,t={...r,...B(f.metadata)?f.metadata:{}};p={type:`api`,key:e,...Object.keys(t).length>0?{metadata:t}:{}}}if(!e.auth.save(t.id,p,{generation:l})||!u())return V(a,200,X(e,t));let m=typeof f.accountId==`string`?f.accountId:``;return o.set(t.id,{state:`success`,url:``,instructions:``,...m===``?{}:{accountId:m}}),e.log(`[plugin-host] ✓ ${t.id} 登录完成${m===``?``:`(${m})`}`),V(a,200,X(e,t))}async function It(e,t,n,r){let i=Y(t);if(i.length===0)return H(r,400,z(`${t.id} 未声明登录方式(auth.methods),无法登录;该插件可能不需要登录`,`invalid_request_error`));let a={};try{let e=await W(n,U());if(e.length>0){let t=JSON.parse(e.toString(`utf-8`));a=B(t)?t:{}}}catch{return H(r,400,z(`请求体不是合法 JSON`,`invalid_request_error`))}let o=e.signIns??=new Map;if(o.get(t.id)?.state===`pending`)return V(r,200,X(e,t));let s=typeof a.method==`string`?a.method:``;if(s===``&&i.length>1)return V(r,200,{...X(e,t),needMethod:!0});let c=s===``?i[0]:i.find(e=>e.label===s);if(c===void 0)return H(r,400,z(`未知登录方式:${s}(可选:${i.map(e=>e.label??`(未命名)`).join(`、`)})`,`invalid_request_error`));let l={};if(B(a.inputs))for(let[e,t]of Object.entries(a.inputs))typeof t==`string`&&(l[e]=t);let u=typeof a.key==`string`?a.key.trim():``,d=Nt(c,l);if(d.length>0)return V(r,200,{...X(e,t),needInputs:Pt(d),inputs:l});if(c.type===`api`)return await Ft(e,t,c,l,u,r);let f=c.authorize;if(typeof f!=`function`)return H(r,400,z(`登录方式「${c.label??c.type}」缺少 authorize 实现(插件声明与实现不一致)`,`invalid_request_error`));let p={state:`pending`,url:``,instructions:``};o.set(t.id,p);let m=e.auth.beginLogin(t.id),h=()=>o.get(t.id)===p,g;try{g=await O(t.id,m,()=>f(c.prompts?.length?l:void 0))}catch(n){return h()&&o.delete(t.id),Z(e,t.id,m),H(r,502,z(`起登录流程失败:${n instanceof Error?n.message:String(n)}`,`upstream_error`))}if(!h())return V(r,200,X(e,t));let _=g.callback;if(typeof _!=`function`)return o.delete(t.id),Z(e,t.id,m),H(r,400,z(`登录流程没有 callback(插件声明与实现不一致)`,`invalid_request_error`));p.url=typeof g.url==`string`?g.url:``,p.instructions=typeof g.instructions==`string`?g.instructions:``;let ee=s===``?c.label??c.type:s;return e.log(`[plugin-host] ▶ ${t.id} 登录已发起(${ee}${p.url===``?`,读取本机凭据`:`,等待浏览器完成`})`),(async()=>{try{let n=await O(t.id,m,()=>_());if(!h())return;let r=B(n)?n:{};if(r.type===`success`){if(!e.auth.save(t.id,{...r,type:`oauth`},{generation:m})){e.log(`[plugin-host] ${t.id} 登录结果已过期(已登出或被新登录取代),丢弃`);return}let n=typeof r.accountId==`string`?r.accountId:``;p.state=`success`,p.accountId=n,e.log(`[plugin-host] ✓ ${t.id} 登录完成${n===``?``:`(${n})`}`)}else{let n=typeof r.error==`string`&&r.error!==``?r.error:`登录未完成`;p.state=`failed`,p.error=n,Z(e,t.id,m),e.log(`[plugin-host] ✗ ${t.id} 登录失败:${n}`)}}catch(n){if(!h())return;p.state=`failed`,p.error=n instanceof Error?n.message:String(n),Z(e,t.id,m),e.log(`[plugin-host] ✗ ${t.id} 登录异常:${p.error}`)}})(),V(r,200,X(e,t))}function Lt(e,t){let{providers:n}=I(e.loadResult());V(t,200,{service:`ezllm-plugin-host`,endpoints:[`GET /health`,`GET /plugins`,`GET /p/<id>/v1/models`,`GET /p/<id>/usage`,`POST /p/<id>/v1/{chat/completions|messages|responses}`,`GET /packages`,`GET /packages/updates`,`GET /packages/<name>`,`POST /packages`,`DELETE /packages/<name>`,`GET /login/<id>`,`POST /login/<id>`,`DELETE /login/<id>`],providers:n.map(e=>({id:e.id,apiBase:e.protocol===null?null:`/p/${e.id}/v1`,protocol:e.protocol}))})}function Rt(e){let t=/^\/p\/([^/]+)\/v1(?:\/(.*))?$/.exec(e);if(t===null)return null;let n=decodeURIComponent(t[1]??``);return n===``?null:{id:n,rest:(t[2]??``).replace(/\/+$/,``)}}function Q(e,t){return I(e.loadResult()).providers.find(e=>e.id===t)}function $(e,t){if(t.hooks===null)throw Error(`provider「${t.id}」没有 auth 钩子(插件声明与实现不一致)`);return new $e(t.id,t.hooks.auth,{store:e.auth,providerInfo:t.config,log:e.log})}async function zt(e,t,n){let r=t.models,i=!1,a=t.hooks?.hooks.provider?.models;if(typeof a==`function`&&t.hooks!==null&&e.auth.has(t.id)){let n=$(e,t);await n.ensureFresh();let o=n.current();if(o!==void 0)try{let e=await O(t.id,n.generation(),()=>a(t.config,{auth:o})),s=Object.keys(e??{});s.length>0&&(r=s,i=!0)}catch(n){e.log(`[plugin-host] ${t.id}: provider.models 失败,回落声明表(${n instanceof Error?n.message:String(n)})`)}}V(n,200,{object:`list`,provider:t.id,fromHook:i,data:r.map(e=>({id:e,object:`model`,owned_by:t.id}))})}async function Bt(e,t,n){let r=t.hooks?.auth.usage;if(t.hooks===null||t.capabilities.usage===!1||typeof r!=`function`)return H(n,400,z(`该插件未实现额度查询`,`invalid_request_error`));let i=$(e,t);await i.ensureFresh();let a;try{a=await O(t.id,i.generation(),()=>r(i.getAuth,t.config))}catch(r){let i=r instanceof Error?r.message:String(r);return e.log(`[plugin-host] ✗ ${t.id} 额度查询失败:${i}`),H(n,502,z(`额度查询失败:${i}`,`upstream_error`))}V(n,200,a)}async function Vt(e,t,n,r,i){if(t.protocol===null)return H(i,501,z(`${t.id} 的协议未知(插件未声明可识别的 npm),不可转发`,`not_implemented`));if(n!==t.path)return H(i,404,z(`${t.id} 只提供 /p/${t.id}/v1/${t.path}(插件声明的协议是 ${t.protocol})`,`not_found`));let a;try{a=await lt(r,U())}catch(e){return H(i,413,z(e instanceof Error?e.message:String(e),`invalid_request_error`))}let o=r.headers[it],s=typeof o==`string`?o:``,c=pt(a,t),l=Date.now();e.log(`[plugin-host] ▶ ${t.id} ${n} model=${c} bytes=${String(a.length)}${s?` session=${s}`:``}`);let u=await ut({provider:t,credentials:$(e,t),model:c,path:n,method:`POST`,req:r,body:a,sessionId:s},e.log);if(u.kind===`error`)return e.log(`[plugin-host] ✗ ${t.id} ${n} ${String(u.status)} ${u.message}`),H(i,u.status,z(u.message,u.status===401?`auth_error`:`upstream_error`));let d=u.response,f=ft(d);e.log(`[plugin-host] ◀ ${t.id} ${n} status=${String(d.status)} ${f?`stream`:`json`} ${String(Date.now()-l)}ms`),await dt(d,(e,t)=>{i.headersSent||i.writeHead(e,t)},e=>{i.write(e)}),i.end()}async function Ht(e,t,n){let r=tt(t.url??`/`),i=(t.method??`GET`).toUpperCase();try{if(vt(e.options,t),mt(e.options,t),i===`GET`&&r===`/health`)return yt(e,n);if(i===`GET`&&r===`/plugins`)return bt(e,n);if(i===`GET`&&r===`/`)return Lt(e,n);if(r===`/packages`)return i===`GET`?xt(e,n):i===`POST`?await Tt(()=>Et(e,t,n)):H(n,405,z(`不支持的方法:${i} ${r}`,`invalid_request_error`));if(r===`/packages/updates`)return i===`GET`?await kt(e,n):H(n,405,z(`不支持的方法:${i} ${r}`,`invalid_request_error`));let a=/^\/packages\/(.+)$/.exec(r);if(a!==null){let t=decodeURIComponent(a[1]??``);return t===``?H(n,404,z(`未找到:${i} ${r}`,`not_found`)):i===`GET`?St(e,t,n):i===`DELETE`?await Tt(()=>Dt(e,t,n)):H(n,405,z(`不支持的方法:${i} ${r}`,`invalid_request_error`))}let o=/^\/login\/(.+)$/.exec(r);if(o!==null){let a=decodeURIComponent(o[1]??``),s=a===``?void 0:Q(e,a);return s===void 0?H(n,404,z(`未加载 provider:${a}`,`not_found`)):i===`GET`?At(e,s,n):i===`POST`?await It(e,s,t,n):i===`DELETE`?jt(e,s,n):H(n,405,z(`不支持的方法:${i} ${r}`,`invalid_request_error`))}let s=/^\/p\/([^/]+)\/usage$/.exec(r);if(s!==null){let t=decodeURIComponent(s[1]??``),a=Q(e,t);return a===void 0?H(n,404,z(`未加载 provider:${t}`,`not_found`)):i===`GET`?await Bt(e,a,n):H(n,405,z(`不支持的方法:${i} ${r}`,`invalid_request_error`))}let c=Rt(r);if(c!==null){let a=Q(e,c.id);return a===void 0?H(n,404,z(`未加载 provider:${c.id}`,`not_found`)):i===`GET`&&c.rest===`models`?await zt(e,a,n):i===`POST`?await Vt(e,a,c.rest,t,n):H(n,405,z(`不支持的方法:${i} ${r}`,`invalid_request_error`))}H(n,404,z(`未找到:${i} ${r}`,`not_found`))}catch(e){let t=e instanceof Error?e.message:String(e),r=t===`invalid api key`?401:t.startsWith(G)?403:500;H(n,r,z(t,r===500?`internal_error`:`invalid_request_error`))}}function Ut(e){return te((t,n)=>{Ht(e,t,n).catch(t=>{e.log(`[fatal] handler error: ${t instanceof Error&&t.stack?t.stack:String(t)}`);try{n.headersSent||n.writeHead(500,{"Content-Type":`application/json`}),n.end(JSON.stringify({detail:z(String(t),`internal_error`)}))}catch{}})})}function Wt(e){return{...e,pluginsDir:e.pluginsDir===``?ce():e.pluginsDir,authFile:e.authFile===``?le():e.authFile}}function Gt(e,t,n){let{providers:r,errors:i}=I(t);v(`==== 插件宿主预检 ====`),v(`平台 : ${process.platform}`),v(`Node : ${process.version}`),v(`插件目录 : ${e.pluginsDir}`),v(`凭据文件 : ${e.authFile}`),v(`已装插件 : ${String(t.plugins.length)} 个(provider ${String(r.length)} 个)`);for(let e of r){let t=e.protocol??`未知协议(不可用)`,r=n(e.id)?`已登录`:`未登录`;v(` - ${e.id}(${e.name}): ${t} | ${String(e.models.length)} 模型 | ${r}`)}for(let e of i)y(` ! ${e}`);r.length===0&&y(" 未加载到任何 provider——用 `npm install <plugin> --prefix` 装进插件目录后重启"),v(`======================`)}async function Kt(e=process.argv.slice(2),t=process.env){let{options:n,help:r}=Ge(e,t);if(r)return process.stdout.write(Ke()),null;let i=Wt(n),a=new _e(i.authFile),o={plugins:[],errors:[]},s=()=>o,c={directory:i.pluginsDir,saveAuth:(e,t)=>{let n=D.getStore(),r=n?.providerId===e?{generation:n.generation}:void 0;if(!a.save(e,t,r)){v(`[plugin-host] 已忽略过期/登出后的凭据写入:${e}`);return}v(`[plugin-host] 凭据已保存:${e}`)}},l=async()=>{let e=await We(i.pluginsDir,c);return o=e,e.errors};try{await l()}catch(e){y(`[plugin-host] 加载插件失败:${e instanceof Error?e.message:String(e)}`)}i.skipCheck||Gt(i,s(),e=>a.has(e));let u=we(i.nodeDir,w()),d={pluginsDir:i.pluginsDir,npmCli:u,log:e=>v(e)};v(`[plugin-host] ✅ 监听 http://${i.host}:${String(i.port)}`),v(`[plugin-host] GET /health`),v(`[plugin-host] GET /plugins`),v(`[plugin-host] GET /packages · POST /packages · DELETE /packages/<name>`),v(`[plugin-host] GET /login/<id> · POST /login/<id> · DELETE /login/<id>`),v(`[plugin-host] 安装能力: ${u===null?`npm 未找到(仅可运行已装插件)`:`已启用(${u})`}`),i.apiKey&&v(`[plugin-host] 鉴权已启用(API key 已设置)`),v(`[plugin-host] 按 Ctrl+C 退出。`);let f=Ut({options:i,auth:a,loadResult:s,reload:l,install:d,log:e=>v(e)});return await new Promise((e,t)=>{f.once(`error`,t),f.listen(i.port,i.host,()=>{f.off(`error`,t),e()})}),v(`[plugin-host] listening on ${i.host}:${String(i.port)}`),{server:f,options:i,auth:a,loadResult:s,reload:l}}var qt=process.argv[1];qt!==void 0&&import.meta.url===i(n(qt)).href&&Kt().catch(e=>{ne(`[plugin-host] 启动失败:${e instanceof Error?e.message:String(e)}`),process.exitCode=1});export{Kt as main};
|
|
5
|
+
`}var yt=class extends Error{status;detail;constructor(e,t,n){super(t),this.name=`HttpError`,this.status=e,this.detail=n}};function H(e,t){return{error:{message:e,type:t}}}function U(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bt(e){let t=e.search(/[?#]/);return t>=0?e.slice(0,t):e}function W(e,t,n){if(e.headersSent){try{e.end()}catch{}return}e.writeHead(t,{"Content-Type":`application/json`}),e.end(JSON.stringify(n))}function G(e,t,n){W(e,t,{detail:n})}function K(e=process.env){return Number(e.PLUGIN_HOST_MAX_BODY||33554432)}function q(e,t){return new Promise((n,r)=>{let i=[],a=0;e.on(`data`,n=>{if(a+=n.length,a>t){e.destroy(),r(new yt(413,`request body too large`,H(`request body too large`,`invalid_request_error`)));return}i.push(n)}),e.on(`end`,()=>{n(Buffer.concat(i))}),e.on(`error`,r)})}async function*xt(e){if(!e)return;let t=e.getReader();try{for(;;){let{done:e,value:n}=await t.read();if(e)break;n&&(yield Buffer.isBuffer(n)?n:Buffer.from(n))}}finally{try{t.releaseLock()}catch{}}}function St(e,t,n){let r=typeof e.accountId==`string`?e.accountId:null;if(`refresh`in e){let t={...e};return delete t.type,delete t.provider,{auth:{...t,type:`oauth`},account:r}}let i=typeof e.key==`string`&&e.key!==``?e.key:t,a={...n,...U(e.metadata)?e.metadata:{}};return{auth:{type:`api`,key:i,...Object.keys(a).length>0?{metadata:a}:{}},account:r}}function Ct(e){let t={...e};return delete t.type,delete t.provider,{auth:{...t,type:`oauth`},account:typeof e.accountId==`string`?e.accountId:null}}function wt(e,t){return e.prompts!==void 0&&e.prompts.length>0?t.inputs:void 0}function Tt(e){return e instanceof Error?e:Error(String(e))}function Et(e){let t=e.hooks;if(t===null)return null;let n=t.auth,r=Array.isArray(n.methods)?n.methods:[];return{id:e.id,priority:100,methods:()=>r,authorize:async(e,t)=>{let n=e,r=n.authorize,i=wt(n,t);if(n.type===`api`){if(typeof r!=`function`)return{auth:{type:`api`,key:t.key,...Object.keys(t.inputs).length>0?{metadata:t.inputs}:{}}};let e=await r(i),n=U(e)?e:{};if(n.type!==`success`)throw new xe(typeof n.error==`string`&&n.error!==``?n.error:`登录未完成`);return St(n,t.key,t.inputs)}if(typeof r!=`function`)throw new C(400,`登录方式「${n.label??n.type}」缺少 authorize 实现(插件声明与实现不一致)`);let a=await r(i),o=U(a)?a:{},s=o.callback;if(typeof s!=`function`)throw new C(400,`登录流程没有 callback(插件声明与实现不一致)`);let c=null,l=null;return(async()=>{try{let e=await s(),t=U(e)?e:{};if(t.type===`success`)c=Ct(t);else{let e=typeof t.error==`string`&&t.error!==``?t.error:`登录未完成`;l=Error(e)}}catch(e){l=Tt(e)}})(),{url:typeof o.url==`string`?o.url:``,instructions:typeof o.instructions==`string`?o.instructions:``,expiresAt:null,poll:async()=>{if(l!==null)throw l;return c}}},...typeof n.refresh==`function`?{refresh:async t=>await n.refresh({...t},e.config)??null}:{},...typeof n.refreshLead==`number`?{refreshLead:n.refreshLead}:{}}}var Dt=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t.auth}current(){return this.#t.get(this.#e)}generation(){return this.#t.generation(this.#e)}getAuth=async()=>this.current();async ensureFresh(){await this.#t.ensureFresh(this.#e)}},Ot=new Set([`host`,`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`content-length`,`authorization`,`x-api-key`,`x-plugin-session`]),kt=`x-plugin-session`;function At(e,t){if(t!==``)return t;let n=e.provider.config.models?.[e.model],r=n?.provider?.api??n?.api?.url;if(typeof r==`string`&&r!==``)return r;let i=e.provider.config.api;return typeof i==`string`?i:``}function jt(e,t){return t===void 0||t===``?{}:e===`anthropic`?{"x-api-key":t}:{authorization:`Bearer ${t}`}}function Mt(e){let t={};for(let[n,r]of Object.entries(e.headers)){let e=n.toLowerCase();Ot.has(e)||r!==void 0&&(t[e]=Array.isArray(r)?r.join(`, `):r)}return t}function Nt(e,t){let n=new Headers;for(let[r,i]of Object.entries(jt(e.provider.protocol,t.apiKey)))n.set(r,i);for(let[e,r]of Object.entries(t.headers??{}))n.set(e,String(r));for(let[t,r]of Object.entries(Mt(e.req)))n.set(t,r);return{headers:n,baseURL:At(e,typeof t.baseURL==`string`?t.baseURL:``),fetchFn:typeof t.fetch==`function`?t.fetch:fetch}}async function Pt(e,t,n){let r=t.provider.hooks?.hooks[`chat.headers`];if(typeof r!=`function`)return;let i={headers:{}};try{await r({sessionID:t.sessionId,agent:`build`,model:{id:t.model,providerID:t.provider.id,api:{id:t.model,npm:t.provider.config.npm}},provider:{source:`custom`,info:t.provider.config,options:t.provider.config.options??{}},message:{id:``,sessionID:t.sessionId,role:`user`,time:{created:Date.now()},agent:`build`,model:{providerID:t.provider.id,modelID:t.model}}},i)}catch(e){n(`[plugin-host] ${t.provider.id}: chat.headers 失败(${e instanceof Error?e.message:String(e)})`);return}for(let[t,n]of Object.entries(i.headers))e.set(t,String(n))}async function Ft(e,t){return q(e,t)}async function It(e,t){let{provider:n,credentials:r}=e;if(n.hooks===null)return{kind:`error`,status:501,message:`插件 ${n.source.package} 声明了 provider「${n.id}」但没有实现 auth 钩子(无登录/转发能力)`};if(await r.ensureFresh(),r.current()===void 0)return{kind:`error`,status:401,message:`${n.id} 尚未登录:请在管理台完成登录后重试`};let i=n.hooks.auth.loader;if(i===void 0)return{kind:`error`,status:501,message:`插件 ${n.source.package} 未实现 auth.loader,无法转发`};let a=r.generation(),o;try{o=await b(n.id,a,()=>i(r.getAuth,n.config))??{}}catch(e){return{kind:`error`,status:502,message:`插件 loader 失败:${e instanceof Error?e.message:String(e)}`}}let s=Nt(e,o);if(s.baseURL===``)return{kind:`error`,status:502,message:`插件 ${n.source.package} 与 provider「${n.id}」都没有给出上游地址(loader.baseURL 与 config.api 均为空)`};await b(n.id,a,()=>Pt(s.headers,e,t));let c=`${s.baseURL.replace(/\/+$/,``)}/${e.path.replace(/^\/+/,``)}`;try{return{kind:`ok`,response:await b(n.id,a,()=>s.fetchFn(c,{method:e.method,headers:s.headers,body:e.body.length>0?e.body:void 0}))}}catch(e){return{kind:`error`,status:502,message:`上游请求失败:${e instanceof Error?e.message:String(e)}`}}}async function Lt(e,t,n){let r={};e.headers.forEach((e,t)=>{let n=t.toLowerCase();n!==`content-encoding`&&n!==`content-length`&&n!==`transfer-encoding`&&(r[n]=e)}),t(e.status,r);for await(let t of xt(e.body))n(t)}function Rt(e){return(e.headers.get(`content-type`)??``).includes(`text/event-stream`)}function zt(e,t){try{let t=JSON.parse(e.toString(`utf8`));if(U(t)&&typeof t.model==`string`&&t.model!==``)return t.model}catch{}return t.models[0]??``}var J=new WeakMap,Y=new WeakMap;function Bt(e){let t=e.loadResult();if(J.get(e.auth)===t)return;for(let t of Y.get(e.auth)??[])t();let n=[];for(let r of V(t).providers){let t=Et(r);t!==null&&n.push(e.auth.register(t))}Y.set(e.auth,n),J.set(e.auth,t)}function Vt(e,t){let n=e.apiKey;if(!n)return;let r=t.headers.authorization,i=t.headers[`x-api-key`],a=``;if(r&&r.startsWith(`Bearer `)&&(a=r.slice(7).trim()),!a&&i&&(a=String(i)),a!==n)throw Error(`invalid api key`)}var Ht=[`127.0.0.1`,`localhost`,`[::1]`,`::1`],Ut=`拒绝的 `;function Wt(e){let t=e.trim();if(t===``)return``;if(t.startsWith(`[`)){let e=t.indexOf(`]`);return e<0?t.toLowerCase():t.slice(0,e+1).toLowerCase()}let n=t.lastIndexOf(`:`);return(n<0?t:t.slice(0,n)).toLowerCase()}function Gt(e){return e===`0.0.0.0`||e===`::`||e===``}function Kt(e,t){if(Gt(e.host))return;let n=[...Ht,e.host.trim().toLowerCase()],r=Wt(String(t.headers.host??``));if(!n.includes(r))throw Error(`${Ut}Host:${r===``?`(空)`:r}(只接受本机回环地址)`);let i=t.headers.origin;if(typeof i==`string`&&i!==``&&i!==`null`){let e=(()=>{try{return new URL(i).hostname.toLowerCase()}catch{return i.toLowerCase()}})();if(!n.includes(e))throw Error(`拒绝的 Origin:${e}`)}}function qt(e){let t=e.hooks?.auth.methods;return Array.isArray(t)&&t.length>0}function Jt(e,t){return{id:e.id,name:e.name,package:e.source.package,version:e.source.version,protocol:e.protocol,basePath:e.protocol===null?null:`/${e.id}/v1`,models:e.models,signedIn:t,needsLogin:qt(e),hooks:e.capabilities}}function Yt(e,t){let{providers:n}=V(e.loadResult());W(t,200,{status:`ok`,platform:process.platform,node:process.version.replace(/^v/,``),mode:`plugin-host (forwarding + package install)`,port:e.options.port,pluginsDir:e.options.pluginsDir,authFile:e.options.authFile,providers:n.length})}function Xt(e,t){let n=e.loadResult(),{providers:r,errors:i}=V(n);W(t,200,{status:`ok`,pluginsDir:e.options.pluginsDir,packages:n.plugins.map(e=>({package:e.package,version:e.version,providers:e.providers.length})),providers:r.map(t=>Jt(t,e.auth.has(t.id))),errors:i})}function X(e,t){return V(e.loadResult()).providers.filter(e=>e.source.package===t)}function Zt(e,t){let n=z(e.options.pluginsDir).map(t=>{let n=X(e,t.name);return{package:t.name,version:t.version,description:t.description,license:t.license,repository:t.repository,loaded:n.length>0,providers:n.map(t=>({id:t.id,name:t.name,protocol:t.protocol,models:t.models.length,signedIn:e.auth.has(t.id),needsLogin:qt(t)}))}});W(t,200,{status:`ok`,pluginsDir:e.options.pluginsDir,count:n.length,packages:n,errors:e.loadResult().errors,canInstall:e.install!==void 0&&e.reload!==void 0})}function Qt(e,t,n){let r=B(e.options.pluginsDir,t);if(r===void 0)return G(n,404,H(`未安装:${t}`,`not_found`));let i=X(e,r.name);W(n,200,{status:`ok`,package:r.name,version:r.version,description:r.description,license:r.license,repository:r.repository,dir:r.dir,entry:r.main,readme:e.install===void 0?null:rt(r.dir),loaded:i.length>0,providers:i.map(t=>Jt(t,e.auth.has(t.id))),errors:e.loadResult().errors.filter(e=>e.includes(r.name))})}async function $t(e){if(e.reload===void 0)return[];try{return await e.reload()}catch(t){return e.log(`[plugin-host] 重载失败:${t instanceof Error?t.message:String(t)}`),[`重载失败:${t instanceof Error?t.message:String(t)}`]}}function en(e){let t=e.options.mainPort;if(!Number.isFinite(t)||t<=0){e.log(`[plugin-host] 未由 ezllm 托管(MAIN_PORT 未注入),装/卸后的重启需手动执行`);return}let n=`http://127.0.0.1:${String(t)}/api/service/plugins/restart`;fetch(n,{method:`POST`}).then(t=>{t.ok||e.log(`[plugin-host] 自请重启失败:HTTP ${String(t.status)}(插件已装,重启需手动)`)}).catch(t=>{e.log(`[plugin-host] 自请重启失败:${t instanceof Error?t.message:String(t)}(插件已装,重启需手动)`)})}var Z=Promise.resolve();function tn(e){let t=Z.then(e,e);return Z=t.then(()=>void 0,()=>void 0),t}async function nn(e,t,n){if(e.install===void 0||e.reload===void 0)return G(n,501,H(`本进程未启用安装能力(未注入 npm 依赖)`,`not_implemented`));let r;try{r=await q(t,K())}catch(e){return G(n,413,H(e instanceof Error?e.message:String(e),`invalid_request_error`))}let i;try{i=r.length===0?{}:JSON.parse(r.toString(`utf8`))}catch{return G(n,400,H(`body 不是合法 JSON`,`invalid_request_error`))}if(!U(i)||typeof i.package!=`string`||i.package.trim()===``)return G(n,400,H(`缺少 package(npm 包名,可带 @版本)`,`invalid_request_error`));let a=i.package.trim(),o=typeof i.version==`string`&&i.version.trim()!==``?i.version.trim():``,s=o===``?a:`${L(a)??a}@${o}`;if(I(s)===null)return G(n,400,H(`不是合法的 npm 包规格:${s}`,`invalid_request_error`));e.log(`[plugin-host] 安装 ${s}`);let c=await tt(e.install,s);if(!c.ok)return e.log(`[plugin-host] ✗ 安装失败:${s}`),G(n,502,H(c.message,`install_error`));let l=await $t(e),u=L(s)??s,d=B(e.options.pluginsDir,u);e.log(`[plugin-host] ✓ 已安装 ${u}${d?`@${d.version}`:``}`),W(n,200,{status:`ok`,package:u,version:d?.version??``,loaded:X(e,u).length>0,providers:X(e,u).map(e=>({id:e.id,protocol:e.protocol,models:e.models.length})),npmOutput:c.output.slice(-2e3),reloadErrors:l,restartRequested:e.options.mainPort>0}),en(e)}async function rn(e,t,n){if(e.install===void 0||e.reload===void 0)return G(n,501,H(`本进程未启用卸载能力(未注入 npm 依赖)`,`not_implemented`));e.log(`[plugin-host] 卸载 ${t}`);let r=await nt(e.install,t);if(!r.ok)return G(n,r.message.startsWith(`未安装`)?404:502,H(r.message,r.message.startsWith(`未安装`)?`not_found`:`install_error`));let i=await $t(e);e.log(`[plugin-host] ✓ 已卸载 ${t}`),W(n,200,{status:`ok`,package:t,npmOutput:r.output.slice(-2e3),reloadErrors:i,restartRequested:e.options.mainPort>0}),en(e)}var an=36e5;async function on(e,t){let n=e.versionCache??=new Map,r=Date.now(),i=[];for(let t of z(e.options.pluginsDir)){let a=null;if(e.install!==void 0){let i=n.get(t.name);i!==void 0&&r-i.at<an?a=i.latest:(a=await Qe(e.install,t.name),a!==null&&n.set(t.name,{latest:a,at:r}))}i.push({package:t.name,current:t.version,latest:a,updateAvailable:a!==null&&a!==t.version})}W(t,200,{status:`ok`,canCheck:e.install!==void 0,packages:i})}async function sn(e){let t=await q(e,K());if(t.length===0)return{};let n;try{n=JSON.parse(t.toString(`utf-8`))}catch{throw Error(`请求体不是合法 JSON`)}let r=U(n)?n:{},i={};if(U(r.inputs))for(let[e,t]of Object.entries(r.inputs))typeof t==`string`&&(i[e]=t);return{...typeof r.method==`string`?{method:r.method}:{},...typeof r.key==`string`?{key:r.key}:{},...Object.keys(i).length>0?{inputs:i}:{}}}async function cn(e,t,n){W(n,200,await e.auth.poll(t.id))}async function ln(e,t,n,r){let i;try{i=await sn(n)}catch(e){return G(r,400,H(e instanceof Error?e.message:String(e),`invalid_request_error`))}try{W(r,200,await e.auth.signIn(t.id,i))}catch(e){if(e instanceof C)return G(r,e.status,H(e.message,e.status===502?`upstream_error`:`invalid_request_error`));throw e}}function un(e,t,n){W(n,200,e.auth.signOut(t.id))}function dn(e,t){let{providers:n}=V(e.loadResult());W(t,200,{service:`ezllm-plugin-host`,endpoints:[`GET /health`,`GET /plugins`,`GET /p/<id>/v1/models`,`GET /p/<id>/usage`,`POST /p/<id>/v1/{chat/completions|messages|responses}`,`GET /packages`,`GET /packages/updates`,`GET /packages/<name>`,`POST /packages`,`DELETE /packages/<name>`,`GET /login/<id>`,`POST /login/<id>`,`DELETE /login/<id>`],providers:n.map(e=>({id:e.id,apiBase:e.protocol===null?null:`/p/${e.id}/v1`,protocol:e.protocol}))})}function fn(e){let t=/^\/p\/([^/]+)\/v1(?:\/(.*))?$/.exec(e);if(t===null)return null;let n=decodeURIComponent(t[1]??``);return n===``?null:{id:n,rest:(t[2]??``).replace(/\/+$/,``)}}function Q(e,t){return V(e.loadResult()).providers.find(e=>e.id===t)}function $(e,t){if(t.hooks===null)throw Error(`provider「${t.id}」没有 auth 钩子(插件声明与实现不一致)`);return new Dt(t.id,{auth:e.auth})}async function pn(e,t,n){let r=t.models,i=!1,a=t.hooks?.hooks.provider?.models;if(typeof a==`function`&&t.hooks!==null&&e.auth.has(t.id)){let n=$(e,t);await n.ensureFresh();let o=n.current();if(o!==void 0)try{let e=await b(t.id,n.generation(),()=>a(t.config,{auth:o})),s=Object.keys(e??{});s.length>0&&(r=s,i=!0)}catch(n){e.log(`[plugin-host] ${t.id}: provider.models 失败,回落声明表(${n instanceof Error?n.message:String(n)})`)}}W(n,200,{object:`list`,provider:t.id,fromHook:i,data:r.map(e=>({id:e,object:`model`,owned_by:t.id}))})}async function mn(e,t,n){let r=t.hooks?.auth.usage;if(t.hooks===null||t.capabilities.usage===!1||typeof r!=`function`)return G(n,400,H(`该插件未实现额度查询`,`invalid_request_error`));let i=$(e,t);await i.ensureFresh();let a;try{a=await b(t.id,i.generation(),()=>r(i.getAuth,t.config))}catch(r){let i=r instanceof Error?r.message:String(r);return e.log(`[plugin-host] ✗ ${t.id} 额度查询失败:${i}`),G(n,502,H(`额度查询失败:${i}`,`upstream_error`))}W(n,200,a)}async function hn(e,t,n,r,i){if(t.protocol===null)return G(i,501,H(`${t.id} 的协议未知(插件未声明可识别的 npm),不可转发`,`not_implemented`));if(n!==t.path)return G(i,404,H(`${t.id} 只提供 /p/${t.id}/v1/${t.path}(插件声明的协议是 ${t.protocol})`,`not_found`));let a;try{a=await Ft(r,K())}catch(e){return G(i,413,H(e instanceof Error?e.message:String(e),`invalid_request_error`))}let o=r.headers[kt],s=typeof o==`string`?o:``,c=zt(a,t),l=Date.now();e.log(`[plugin-host] ▶ ${t.id} ${n} model=${c} bytes=${String(a.length)}${s?` session=${s}`:``}`);let u=await It({provider:t,credentials:$(e,t),model:c,path:n,method:`POST`,req:r,body:a,sessionId:s},e.log);if(u.kind===`error`)return e.log(`[plugin-host] ✗ ${t.id} ${n} ${String(u.status)} ${u.message}`),G(i,u.status,H(u.message,u.status===401?`auth_error`:`upstream_error`));let d=u.response,f=Rt(d);e.log(`[plugin-host] ◀ ${t.id} ${n} status=${String(d.status)} ${f?`stream`:`json`} ${String(Date.now()-l)}ms`),await Lt(d,(e,t)=>{i.headersSent||i.writeHead(e,t)},e=>{i.write(e)}),i.end()}async function gn(e,t,n){let r=bt(t.url??`/`),i=(t.method??`GET`).toUpperCase();try{if(Bt(e),Kt(e.options,t),Vt(e.options,t),i===`GET`&&r===`/health`)return Yt(e,n);if(i===`GET`&&r===`/plugins`)return Xt(e,n);if(i===`GET`&&r===`/`)return dn(e,n);if(r===`/packages`)return i===`GET`?Zt(e,n):i===`POST`?await tn(()=>nn(e,t,n)):G(n,405,H(`不支持的方法:${i} ${r}`,`invalid_request_error`));if(r===`/packages/updates`)return i===`GET`?await on(e,n):G(n,405,H(`不支持的方法:${i} ${r}`,`invalid_request_error`));let a=/^\/packages\/(.+)$/.exec(r);if(a!==null){let t=decodeURIComponent(a[1]??``);return t===``?G(n,404,H(`未找到:${i} ${r}`,`not_found`)):i===`GET`?Qt(e,t,n):i===`DELETE`?await tn(()=>rn(e,t,n)):G(n,405,H(`不支持的方法:${i} ${r}`,`invalid_request_error`))}let o=/^\/login\/(.+)$/.exec(r);if(o!==null){let a=decodeURIComponent(o[1]??``),s=a===``?void 0:Q(e,a);return s===void 0?G(n,404,H(`未加载 provider:${a}`,`not_found`)):i===`GET`?cn(e,s,n):i===`POST`?await ln(e,s,t,n):i===`DELETE`?un(e,s,n):G(n,405,H(`不支持的方法:${i} ${r}`,`invalid_request_error`))}let s=/^\/p\/([^/]+)\/usage$/.exec(r);if(s!==null){let t=decodeURIComponent(s[1]??``),a=Q(e,t);return a===void 0?G(n,404,H(`未加载 provider:${t}`,`not_found`)):i===`GET`?await mn(e,a,n):G(n,405,H(`不支持的方法:${i} ${r}`,`invalid_request_error`))}let c=fn(r);if(c!==null){let a=Q(e,c.id);return a===void 0?G(n,404,H(`未加载 provider:${c.id}`,`not_found`)):i===`GET`&&c.rest===`models`?await pn(e,a,n):i===`POST`?await hn(e,a,c.rest,t,n):G(n,405,H(`不支持的方法:${i} ${r}`,`invalid_request_error`))}G(n,404,H(`未找到:${i} ${r}`,`not_found`))}catch(e){let t=e instanceof Error?e.message:String(e),r=t===`invalid api key`?401:t.startsWith(Ut)?403:500;G(n,r,H(t,r===500?`internal_error`:`invalid_request_error`))}}function _n(e){return ie((t,n)=>{gn(e,t,n).catch(t=>{e.log(`[fatal] handler error: ${t instanceof Error&&t.stack?t.stack:String(t)}`);try{n.headersSent||n.writeHead(500,{"Content-Type":`application/json`}),n.end(JSON.stringify({detail:H(String(t),`internal_error`)}))}catch{}})})}function vn(e){return{...e,pluginsDir:e.pluginsDir===``?Ie():e.pluginsDir,authFile:e.authFile===``?Le():e.authFile}}function yn(e,t,n){let{providers:r,errors:i}=V(t);E(`==== 插件宿主预检 ====`),E(`平台 : ${process.platform}`),E(`Node : ${process.version}`),E(`插件目录 : ${e.pluginsDir}`),E(`凭据文件 : ${e.authFile}`),E(`已装插件 : ${String(t.plugins.length)} 个(provider ${String(r.length)} 个)`);for(let e of r){let t=e.protocol??`未知协议(不可用)`,r=n(e.id)?`已登录`:`未登录`;E(` - ${e.id}(${e.name}): ${t} | ${String(e.models.length)} 模型 | ${r}`)}for(let e of i)D(` ! ${e}`);r.length===0&&D(" 未加载到任何 provider——用 `npm install <plugin> --prefix` 装进插件目录后重启"),E(`======================`)}async function bn(e=process.argv.slice(2),t=process.env){let{options:n,help:r}=_t(e,t);if(r)return process.stdout.write(vt()),null;let i=vn(n),a=new ke({file:i.authFile,legacyFiles:n.authFile===``?[Re()]:[],log:e=>E(e)}),o={plugins:[],errors:[]},s=()=>o,c={directory:i.pluginsDir,saveAuth:(e,t)=>{if(!a.saveFromPlugin(e,t)){E(`[plugin-host] 已忽略过期/登出后的凭据写入:${e}`);return}E(`[plugin-host] 凭据已保存:${e}`)}},l=async()=>{let e=await gt(i.pluginsDir,c);return o=e,e.errors};try{await l()}catch(e){D(`[plugin-host] 加载插件失败:${e instanceof Error?e.message:String(e)}`)}i.skipCheck||yn(i,s(),e=>a.has(e));let u=Ye(i.nodeDir,M()),d={pluginsDir:i.pluginsDir,npmCli:u,log:e=>E(e)};E(`[plugin-host] ✅ 监听 http://${i.host}:${String(i.port)}`),E(`[plugin-host] GET /health`),E(`[plugin-host] GET /plugins`),E(`[plugin-host] GET /packages · POST /packages · DELETE /packages/<name>`),E(`[plugin-host] GET /login/<id> · POST /login/<id> · DELETE /login/<id>`),E(`[plugin-host] 安装能力: ${u===null?`npm 未找到(仅可运行已装插件)`:`已启用(${u})`}`),i.apiKey&&E(`[plugin-host] 鉴权已启用(API key 已设置)`),E(`[plugin-host] 按 Ctrl+C 退出。`);let f=_n({options:i,auth:a,loadResult:s,reload:l,install:d,log:e=>E(e)});return await new Promise((e,t)=>{f.once(`error`,t),f.listen(i.port,i.host,()=>{f.off(`error`,t),e()})}),E(`[plugin-host] listening on ${i.host}:${String(i.port)}`),{server:f,options:i,auth:a,loadResult:s,reload:l}}var xn=process.argv[1];xn!==void 0&&import.meta.url===a(r(xn)).href&&bn().catch(e=>{Ae(`[plugin-host] 启动失败:${e instanceof Error?e.message:String(e)}`),process.exitCode=1});export{bn as main};
|