dal-code 1.0.59 → 1.0.60
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/CHANGELOG.md +4 -0
- package/dist/bundle/chunks/{anthropic-messages-HVFHIIGX.js → anthropic-messages-XQHIW2F5.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-RMWKIGFW.js → azure-openai-responses-2STR7FU2.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
- package/dist/bundle/chunks/{chunk-4PBY6OYS.js → chunk-2SQ577MS.js} +1 -1
- package/dist/bundle/chunks/{chunk-KQRRELCF.js → chunk-2TJCPBNY.js} +1 -1
- package/dist/bundle/chunks/{chunk-QU2VEHMW.js → chunk-3KEFLXX2.js} +2 -2
- package/dist/bundle/chunks/{chunk-4BOWD7PQ.js → chunk-425HIJ4E.js} +1 -1
- package/dist/bundle/chunks/{chunk-VDPDHGGJ.js → chunk-4KCKRVPN.js} +1 -1
- package/dist/bundle/chunks/{chunk-X63WCLSX.js → chunk-4TEICWYC.js} +7 -7
- package/dist/bundle/chunks/{chunk-HF334NQU.js → chunk-B66W54NL.js} +1 -1
- package/dist/bundle/chunks/{chunk-F52JQCLE.js → chunk-CIJDL6I3.js} +1 -1
- package/dist/bundle/chunks/{chunk-J6H2LYOZ.js → chunk-E6RWRE6C.js} +1 -1
- package/dist/bundle/chunks/chunk-EXWCUM6H.js +9 -0
- package/dist/bundle/chunks/{chunk-C5ELI234.js → chunk-H3KG4L7I.js} +1 -1
- package/dist/bundle/chunks/{chunk-TPOKZ2EU.js → chunk-HZWPNFQO.js} +1 -1
- package/dist/bundle/chunks/{chunk-GZJEAFRS.js → chunk-KMTIPRJ5.js} +1 -1
- package/dist/bundle/chunks/{chunk-F5SIUTR7.js → chunk-LGD3AMTG.js} +1 -1
- package/dist/bundle/chunks/{chunk-AL3DFAIM.js → chunk-NRQYSXAU.js} +1 -1
- package/dist/bundle/chunks/{chunk-IONGABQF.js → chunk-O5BJV54H.js} +1 -1
- package/dist/bundle/chunks/{chunk-KT7CXVDN.js → chunk-P3KSBU23.js} +8 -8
- package/dist/bundle/chunks/{chunk-R47JBGS3.js → chunk-QM5JU2GS.js} +1 -1
- package/dist/bundle/chunks/{chunk-YOQ3KBG5.js → chunk-RNSD5PAD.js} +1 -1
- package/dist/bundle/chunks/{chunk-MPLE6M5C.js → chunk-RRLI6IMC.js} +1 -1
- package/dist/bundle/chunks/{chunk-PMFHJN7I.js → chunk-SI4QX273.js} +1 -1
- package/dist/bundle/chunks/{chunk-BBNE2TWS.js → chunk-THJSXCE4.js} +1 -1
- package/dist/bundle/chunks/{chunk-IKSSB5ZJ.js → chunk-X2O23QIN.js} +1 -1
- package/dist/bundle/chunks/{chunk-XQF5XDEM.js → chunk-XQ6Z77K4.js} +2 -2
- package/dist/bundle/chunks/{cli-NQ7B7BGV.js → cli-H3PJUN3W.js} +1 -1
- package/dist/bundle/chunks/{cli-BFWJUYZ5.js → cli-OEEFOWRC.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-RXFI2EBV.js → cloudflare-workers-ai-system-one-55VRUHTE.js} +1 -1
- package/dist/bundle/chunks/{easter-egg-3d-W2F3ROZ6.js → easter-egg-3d-JQUBBOXE.js} +1 -1
- package/dist/bundle/chunks/{execute-NJRE4WBO.js → execute-DAF3F222.js} +1 -1
- package/dist/bundle/chunks/{google-generative-ai-5F5544G4.js → google-generative-ai-BQMG6OLH.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-4PSVELDG.js → google-vertex-WUZF5EYV.js} +1 -1
- package/dist/bundle/chunks/{llama-cpp-classify-IPNT4VOW.js → llama-cpp-classify-MADWJYHP.js} +1 -1
- package/dist/bundle/chunks/{mcp-F3BQ6MQW.js → mcp-GYBI424O.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-RSYLYGE4.js → mistral-conversations-GSSWAQLZ.js} +1 -1
- package/dist/bundle/chunks/{office-UBOUFRAU.js → office-OKOPPNJS.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-OKPZLYIS.js → openai-codex-responses-LJCENL64.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-BFCQZRZ2.js → openai-completions-MT4XYSLH.js} +1 -1
- package/dist/bundle/chunks/{openai-decisions-RJ4MH5XI.js → openai-decisions-Y3TPPQUQ.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-PT5MXG3Q.js → openai-responses-5EXHN2JI.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-ICCH2YHW.js → openrouter-images-4YZGO774.js} +1 -1
- package/dist/bundle/chunks/{pi-messages-Z2XWHIYT.js → pi-messages-EGKKYUGE.js} +1 -1
- package/dist/bundle/chunks/{review-WTYIVWYR.js → review-GXC4JNBH.js} +1 -1
- package/dist/bundle/chunks/{router-V3EIAYOF.js → router-6IBMTBKX.js} +1 -1
- package/dist/bundle/chunks/{runtime-FNCZJKOC.js → runtime-MD23I2NI.js} +1 -1
- package/dist/bundle/chunks/{sdk-32L63XRF.js → sdk-Z2BPQBYQ.js} +1 -1
- package/dist/bundle/chunks/{sync-Z5USQ7AN.js → sync-Q7ZHP4AB.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-6UYWINOZ.js → typesafe-system-one-ZIS4YIPV.js} +1 -1
- package/dist/bundle/chunks/{usage-JODQIC2H.js → usage-WQOCA772.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-ERCLFZEY.js → virtual-modules-SEIIF76E.js} +1 -1
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/config.d.ts +1 -0
- package/dist/config.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-advisor/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-awake/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-bridge/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-capabilities/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-codeindex/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-compat/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-dap/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-goal/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-guard/src/attribution.js +1 -1
- package/dist/node_modules/@dalcode/dal-guard/src/index.js +4 -4
- package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-learn/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-lsp/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-mcp/package.json +6 -6
- package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +3 -3
- package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-recall/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-remote/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-router/package.json +6 -6
- package/dist/node_modules/@dalcode/dal-rtk/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-statusline/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-structured/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-sync/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-telemetry/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-usage/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
- package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/radius.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.d.ts +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-schema/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/bundle/chunks/chunk-WLQ33LIH.js +0 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
var Oe=Object.defineProperty;var n=(e,t)=>Oe(e,"name",{value:t,configurable:!0});import{createRequire as Ie}from"node:module";const or=Ie(import.meta.url);import{__commonJS as S,__require as k,__toESM as Re}from"./chunk-JXWJOIH4.js";var Le=S({"node_modules/isexe/windows.js"(e,t){t.exports=a,a.sync=d;var r=k("fs");function s(i,u){var m=u.pathExt!==void 0?u.pathExt:process.env.PATHEXT;if(!m||(m=m.split(";"),m.indexOf("")!==-1))return!0;for(var c=0;c<m.length;c++){var l=m[c].toLowerCase();if(l&&i.substr(-l.length).toLowerCase()===l)return!0}return!1}n(s,"checkPathExt");function o(i,u,m){return!i.isSymbolicLink()&&!i.isFile()?!1:s(u,m)}n(o,"checkStat");function a(i,u,m){r.stat(i,function(c,l){m(c,c?!1:o(l,i,u))})}n(a,"isexe");function d(i,u){return o(r.statSync(i),i,u)}n(d,"sync")}}),Ue=S({"node_modules/isexe/mode.js"(e,t){t.exports=s,s.sync=o;var r=k("fs");function s(i,u,m){r.stat(i,function(c,l){m(c,c?!1:a(l,u))})}n(s,"isexe");function o(i,u){return a(r.statSync(i),u)}n(o,"sync");function a(i,u){return i.isFile()&&d(i,u)}n(a,"checkStat");function d(i,u){var m=i.mode,c=i.uid,l=i.gid,p=u.uid!==void 0?u.uid:process.getuid&&process.getuid(),f=u.gid!==void 0?u.gid:process.getgid&&process.getgid(),g=parseInt("100",8),E=parseInt("010",8),b=parseInt("001",8),w=g|E,P=m&b||m&E&&l===f||m&g&&c===p||m&w&&p===0;return P}n(d,"checkMode")}}),je=S({"node_modules/isexe/index.js"(e,t){var r=k("fs"),s;process.platform==="win32"||global.TESTING_WINDOWS?s=Le():s=Ue(),t.exports=o,o.sync=a;function o(d,i,u){if(typeof i=="function"&&(u=i,i={}),!u){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(m,c){o(d,i||{},function(l,p){l?c(l):m(p)})})}s(d,i||{},function(m,c){m&&(m.code==="EACCES"||i&&i.ignoreErrors)&&(m=null,c=!1),u(m,c)})}n(o,"isexe");function a(d,i){try{return s.sync(d,i||{})}catch(u){if(i&&i.ignoreErrors||u.code==="EACCES")return!1;throw u}}n(a,"sync")}}),We=S({"node_modules/which/which.js"(e,t){var r=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",s=k("path"),o=r?";":":",a=je(),d=n(c=>Object.assign(new Error(`not found: ${c}`),{code:"ENOENT"}),"getNotFoundError"),i=n((c,l)=>{let p=l.colon||o,f=c.match(/\//)||r&&c.match(/\\/)?[""]:[...r?[process.cwd()]:[],...(l.path||process.env.PATH||"").split(p)],g=r?l.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",E=r?g.split(p):[""];return r&&c.indexOf(".")!==-1&&E[0]!==""&&E.unshift(""),{pathEnv:f,pathExt:E,pathExtExe:g}},"getPathInfo"),u=n((c,l,p)=>{typeof l=="function"&&(p=l,l={}),l||(l={});let{pathEnv:f,pathExt:g,pathExtExe:E}=i(c,l),b=[],w=n(v=>new Promise((N,A)=>{if(v===f.length)return l.all&&b.length?N(b):A(d(c));let y=f[v],z=/^".*"$/.test(y)?y.slice(1,-1):y,L=s.join(z,c),H=!z&&/^\.[\\\/]/.test(c)?c.slice(0,2)+L:L;N(P(H,v,0))}),"step"),P=n((v,N,A)=>new Promise((y,z)=>{if(A===g.length)return y(w(N+1));let L=g[A];a(v+L,{pathExt:E},(H,Te)=>{if(!H&&Te)if(l.all)b.push(v+L);else return y(v+L);return y(P(v,N,A+1))})}),"subStep");return p?w(0).then(v=>p(null,v),p):w(0)},"which"),m=n((c,l)=>{l=l||{};let{pathEnv:p,pathExt:f,pathExtExe:g}=i(c,l),E=[];for(let b=0;b<p.length;b++){let w=p[b],P=/^".*"$/.test(w)?w.slice(1,-1):w,v=s.join(P,c),N=!P&&/^\.[\\\/]/.test(c)?c.slice(0,2)+v:v;for(let A=0;A<f.length;A++){let y=N+f[A];try{if(a.sync(y,{pathExt:g}))if(l.all)E.push(y);else return y}catch{}}}if(l.all&&E.length)return E;if(l.nothrow)return null;throw d(c)},"whichSync");t.exports=u,u.sync=m}}),qe=S({"node_modules/path-key/index.js"(e,t){"use strict";var r=n((s={})=>{let o=s.env||process.env;return(s.platform||process.platform)!=="win32"?"PATH":Object.keys(o).reverse().find(a=>a.toUpperCase()==="PATH")||"Path"},"pathKey");t.exports=r,t.exports.default=r}}),Fe=S({"node_modules/cross-spawn/lib/util/resolveCommand.js"(e,t){"use strict";var r=k("path"),s=We(),o=qe();function a(i,u){let m=i.options.env||process.env,c=process.cwd(),l=i.options.cwd!=null,p=l&&process.chdir!==void 0&&!process.chdir.disabled;if(p)try{process.chdir(i.options.cwd)}catch{}let f;try{f=s.sync(i.command,{path:m[o({env:m})],pathExt:u?r.delimiter:void 0})}catch{}finally{p&&process.chdir(c)}return f&&(f=r.resolve(l?i.options.cwd:"",f)),f}n(a,"resolveCommandAttempt");function d(i){return a(i)||a(i,!0)}n(d,"resolveCommand"),t.exports=d}}),Me=S({"node_modules/cross-spawn/lib/util/escape.js"(e,t){"use strict";var r=/([()\][%!^"`<>&|;, *?])/g;function s(a){return a=a.replace(r,"^$1"),a}n(s,"escapeCommand");function o(a,d){return a=`${a}`,a=a.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),a=a.replace(/(?=(\\+?)?)\1$/,"$1$1"),a=`"${a}"`,a=a.replace(r,"^$1"),d&&(a=a.replace(r,"^$1")),a}n(o,"escapeArgument"),t.exports.command=s,t.exports.argument=o}}),Be=S({"node_modules/shebang-regex/index.js"(e,t){"use strict";t.exports=/^#!(.*)/}}),Ge=S({"node_modules/shebang-command/index.js"(e,t){"use strict";var r=Be();t.exports=(s="")=>{let o=s.match(r);if(!o)return null;let[a,d]=o[0].replace(/#! ?/,"").split(" "),i=a.split("/").pop();return i==="env"?d:d?`${i} ${d}`:i}}}),ze=S({"node_modules/cross-spawn/lib/util/readShebang.js"(e,t){"use strict";var r=k("fs"),s=Ge();function o(a){let d=Buffer.alloc(150),i;try{i=r.openSync(a,"r"),r.readSync(i,d,0,150,0),r.closeSync(i)}catch{}return s(d.toString())}n(o,"readShebang"),t.exports=o}}),He=S({"node_modules/cross-spawn/lib/parse.js"(e,t){"use strict";var r=k("path"),s=Fe(),o=Me(),a=ze(),d=process.platform==="win32",i=/\.(?:com|exe)$/i,u=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function m(p){p.file=s(p);let f=p.file&&a(p.file);return f?(p.args.unshift(p.file),p.command=f,s(p)):p.file}n(m,"detectShebang");function c(p){if(!d)return p;let f=m(p),g=!i.test(f);if(p.options.forceShell||g){let E=u.test(f);p.command=r.normalize(p.command),p.command=o.command(p.command),p.args=p.args.map(w=>o.argument(w,E));let b=[p.command].concat(p.args).join(" ");p.args=["/d","/s","/c",`"${b}"`],p.command=process.env.comspec||"cmd.exe",p.options.windowsVerbatimArguments=!0}return p}n(c,"parseNonShell");function l(p,f,g){f&&!Array.isArray(f)&&(g=f,f=null),f=f?f.slice(0):[],g=Object.assign({},g);let E={command:p,args:f,options:g,file:void 0,original:{command:p,args:f}};return g.shell?E:c(E)}n(l,"parse"),t.exports=l}}),Ke=S({"node_modules/cross-spawn/lib/enoent.js"(e,t){"use strict";var r=process.platform==="win32";function s(i,u){return Object.assign(new Error(`${u} ${i.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${u} ${i.command}`,path:i.command,spawnargs:i.args})}n(s,"notFoundError");function o(i,u){if(!r)return;let m=i.emit;i.emit=function(c,l){if(c==="exit"){let p=a(l,u);if(p)return m.call(i,"error",p)}return m.apply(i,arguments)}}n(o,"hookChildProcess");function a(i,u){return r&&i===1&&!u.file?s(u.original,"spawn"):null}n(a,"verifyENOENT");function d(i,u){return r&&i===1&&!u.file?s(u.original,"spawnSync"):null}n(d,"verifyENOENTSync"),t.exports={hookChildProcess:o,verifyENOENT:a,verifyENOENTSync:d,notFoundError:s}}}),X=S({"node_modules/cross-spawn/index.js"(e,t){"use strict";var r=k("child_process"),s=He(),o=Ke();function a(i,u,m){let c=s(i,u,m),l=r.spawn(c.command,c.args,c.options);return o.hookChildProcess(l,c),l}n(a,"spawn");function d(i,u,m){let c=s(i,u,m),l=r.spawnSync(c.command,c.args,c.options);return l.error=l.error||o.verifyENOENTSync(l.status,c),l}n(d,"spawnSync"),t.exports=a,t.exports.spawn=a,t.exports.sync=d,t.exports._parse=s,t.exports._enoent=o}});import{accessSync as Y,constants as Q,existsSync as C,readFileSync as q,realpathSync as Je}from"fs";import{createRequire as Ve}from"module";import{homedir as K}from"os";import{basename as Z,dirname as _,join as h,resolve as T,sep as ee,win32 as Xe}from"path";import{fileURLToPath as Ye}from"url";var te=Re(X(),1);import{spawn as Qe,spawnSync as Ze}from"node:child_process";var et=100;function tt(e,t,r){return process.platform==="win32"?(0,te.default)(e,t,r):Qe(e,t,r)}n(tt,"spawnProcess");function F(e,t,r){return process.platform==="win32"?te.default.sync(e,t,r):Ze(e,t,r)}n(F,"spawnProcessSync");function rt(e){return new Promise((t,r)=>{let s=!1,o=!1,a=null,d,i=e.stdout===null,u=e.stderr===null,m=n(()=>{d&&(clearTimeout(d),d=void 0),e.removeListener("error",b),e.removeListener("exit",w),e.removeListener("close",P),e.stdout?.removeListener("end",g),e.stderr?.removeListener("end",E),e.stdout?.removeListener("data",f),e.stderr?.removeListener("data",f)},"cleanup"),c=n(v=>{s||(s=!0,m(),e.stdout?.destroy(),e.stderr?.destroy(),t(v))},"finalize"),l=n(()=>{!o||s||i&&u&&c(a)},"maybeFinalizeAfterExit"),p=n(()=>{d&&clearTimeout(d),d=setTimeout(()=>c(a),et)},"armIdleTimer"),f=n(()=>{o&&!s&&p()},"onData"),g=n(()=>{i=!0,l()},"onStdoutEnd"),E=n(()=>{u=!0,l()},"onStderrEnd"),b=n(v=>{s||(s=!0,m(),r(v))},"onError"),w=n(v=>{o=!0,a=v,l(),s||p()},"onExit"),P=n(v=>{c(v)},"onClose");e.stdout?.once("end",g),e.stderr?.once("end",E),e.stdout?.on("data",f),e.stderr?.on("data",f),e.once("error",b),e.once("exit",w),e.once("close",P)})}n(rt,"waitForChildProcess");import{realpathSync as nt,statSync as st}from"node:fs";import{homedir as re}from"node:os";import{isAbsolute as ne,join as it,resolve as se,posix as ot,relative as at,sep as ie,win32 as oe}from"node:path";import{fileURLToPath as ut}from"node:url";var ct=/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;function lt(e){try{return nt(e)}catch{return e}}n(lt,"canonicalizePath");function j(e){let t=J(),r=t.resolve(e);return t===oe?r.toLowerCase():r}n(j,"getPathComparisonKey");function J(){return process.platform==="win32"?oe:ot}n(J,"getPlatformPathApi");function pt(e,t){return j(e)===j(t)}n(pt,"pathsEqual");function ae(e,t){let r=j(e),s=j(t);if(s===r)return!0;let o=J().sep;return s.startsWith(r.endsWith(o)?r:`${r}${o}`)}n(ae,"isPathWithin");function mt(e,t=re()){let r=J();if(!t||!r.isAbsolute(e)||!ae(t,e))return e;let s=r.relative(t,e);return s?`~${r.sep}${s}`:"~"}n(mt,"shortenHomePath");function dt(e){try{let t=st(e,{bigint:!0});return`${t.dev}:${t.ino}:${t.size}:${t.mtimeNs}:${t.ctimeNs}`}catch{return}}n(dt,"getFileRevision");function ft(e){let t=e.trim();return!(t.startsWith("npm:")||t.startsWith("git:")||t.startsWith("github:")||t.startsWith("http:")||t.startsWith("https:")||t.startsWith("ssh:")||t.startsWith("builtin:"))}n(ft,"isLocalPath");function ht(e){if(!e.startsWith("/")||e.startsWith("//")||e.includes("\\"))return e;let t=e.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i);if(!t)return e;let r=t[2]?.replaceAll("/","\\");return`${t[1].toUpperCase()}:\\${r??""}`}n(ht,"normalizeWindowsShellPath");function W(e,t={}){let r=t.trim?e.trim():e;if(t.normalizeUnicodeSpaces&&(r=r.replace(ct," ")),t.stripAtPrefix&&r.startsWith("@")&&(r=r.slice(1)),process.platform==="win32"&&(r=ht(r)),t.expandTilde??!0){let s=t.homeDir??re();if(r==="~")return s;if(r.startsWith("~/")||process.platform==="win32"&&r.startsWith("~\\"))return it(s,r.slice(2))}return/^file:\/\//.test(r)?ut(r):r}n(W,"normalizePath");function M(e,t=process.cwd(),r={}){let s=W(e,r),o=W(t);return ne(s)?se(s):se(o,s)}n(M,"resolvePath");function ue(e,t){let r=M(t),s=M(e,r),o=at(r,s);return o===""||o!==".."&&!o.startsWith(`..${ie}`)&&!ne(o)?o||".":void 0}n(ue,"getCwdRelativePath");function gt(e,t){let r=M(e,t);return(ue(r,t)??r).split(ie).join("/")}n(gt,"formatPathRelativeToCwdOrAbsolute");function vt(e){let t=process.platform==="darwin"?["com.dropbox.ignored","com.apple.fileprovider.ignore#P"]:process.platform==="linux"?["user.com.dropbox.ignored"]:[];for(let r of t)process.platform==="darwin"?F("xattr",["-w",r,"1",e],{encoding:"utf-8",stdio:"ignore"}):F("setfattr",["-n",r,"-v","1",e],{encoding:"utf-8",stdio:"ignore"})}n(vt,"markPathIgnoredByCloudSync");function ce(e){return e.startsWith("\uFEFF")?{bom:"\uFEFF",text:e.slice(1)}:{bom:"",text:e}}n(ce,"splitBom");function B(e){return ce(e).text}n(B,"stripBom");var Et=Ye(import.meta.url),le=_(Et),D=import.meta.url.includes("$bunfs")||import.meta.url.includes("~BUN")||import.meta.url.includes("%7EBUN"),xt=!!process.versions.bun,pe=!0;function _t(e){return e.startsWith("https://")||e.startsWith("http://")}n(_t,"isUrlInstallSpec");function me(e){return typeof e=="string"?{packageName:e,installSpec:e}:{packageName:e.packageName,installSpec:e.installSpec??e.packageName}}n(me,"normalizeSelfUpdatePackageTarget");function G(e,t){return t?{...e,display:`${t.display} && ${e.display}`,steps:[t,e]}:e}n(G,"makeSelfUpdateCommand");function $(e,t){return{command:e,args:t,display:[e,...t].map(r=>/\s/.test(r)?`"${r}"`:r).join(" ")}}n($,"makeSelfUpdateCommandStep");function V(){if(D)return"bun-binary";let e=`${le}\0${process.execPath||""}`.toLowerCase().replace(/\\/g,"/");return e.includes("/pnpm/")||e.includes("/.pnpm/")?"pnpm":e.includes("/yarn/")||e.includes("/.yarn/")?"yarn":xt||e.includes("/install/global/node_modules/")?"bun":e.includes("/npm/")||e.includes("/node_modules/")?"npm":"unknown"}n(V,"detectInstallMethod");function de(){let e=x(),t=process.platform==="win32"||e.includes("\\")?Xe:{basename:Z,dirname:_},r=t.dirname(e),s;if(t.basename(r).startsWith("@")&&t.basename(t.dirname(r))==="node_modules"?s=t.dirname(r):t.basename(r)==="node_modules"&&(s=r),!s)return;let o=t.dirname(s);if(t.basename(o)==="lib")return{root:s,prefix:t.dirname(o)}}n(de,"getInferredNpmInstall");function fe(e,t,r=t,s){let o=me(r),a=o.packageName===Ae&&!_t(o.installSpec)?[`--${Jt}:registry=${ke}/`]:[];switch(e){case"bun-binary":return;case"pnpm":{let d=U("pnpm",["root","-g"])?void 0:/^(.*[\\/]global[\\/][^\\/]+)[\\/]\.pnpm[\\/]/.exec(x()),i=d?[`--config.global-bin-dir=${process.env.PNPM_HOME||_(_(d[1]))}`]:[];return G($("pnpm",["install","-g","--ignore-scripts","--config.minimumReleaseAge=0",...i,...a,o.installSpec]),o.packageName===t?void 0:$("pnpm",["remove","-g",...i,t]))}case"yarn":return G($("yarn",["global","add","--ignore-scripts",...a,o.installSpec]),o.packageName===t?void 0:$("yarn",["global","remove",t]));case"bun":return G($("bun",["install","-g","--ignore-scripts","--minimum-release-age=0",...a,o.installSpec]),o.packageName===t?void 0:$("bun",["uninstall","-g",t]));case"npm":{let[d="npm",...i]=s??[],u=s?.length?void 0:de(),m=[...i,...u?["--prefix",u.prefix]:[]],c=$(d,[...m,"install","-g","--ignore-scripts","--min-release-age=0",...a,o.installSpec]),l=o.packageName===t?void 0:$(d,[...m,"uninstall","-g",t]);return G(c,l)}case"unknown":return}}n(fe,"getSelfUpdateCommandForMethod");function U(e,t,r={}){let s=F(e,t,{encoding:"utf-8",stdio:["ignore","pipe","pipe"]});if(s.status===0)return s.stdout.trim()||void 0;if(r.requireSuccess){let o=s.error?.message||s.stderr.trim()||`exit code ${s.status??"unknown"}`;throw new Error(`Failed to run ${[e,...t].join(" ")}: ${o}`)}}n(U,"readCommandOutput");function bt(e,t,r){switch(e){case"npm":{let s=!!r?.length,[o="npm",...a]=r??[];if(s&&o==="bun"){let u=U(o,[...a,"pm","bin","-g"],{requireSuccess:!0}),m=[h(K(),".bun","install","global","node_modules")];return u&&m.push(h(_(u),"install","global","node_modules")),m}let d=U(o,[...a,"root","-g"],{requireSuccess:s}),i=s?void 0:de();return[d,i?.root].filter(u=>!!u)}case"pnpm":{let s=U("pnpm",["root","-g"]);if(s)return[s,_(s)];let o=/^(.*[\\/]global[\\/][^\\/]+)[\\/]\.pnpm[\\/]/.exec(x());return o?[o[1]]:[]}case"yarn":{let s=U("yarn",["global","dir"]);return s?[s,h(s,"node_modules")]:[]}case"bun":{let s=U("bun",["pm","bin","-g"]),o=[h(K(),".bun","install","global","node_modules")];return s&&o.push(h(_(s),"install","global","node_modules")),o}case"bun-binary":case"unknown":return[]}}n(bt,"getGlobalPackageRoots");function he(e,t){let r=T(e);if(!C(r))return;let s=r;if(t)try{s=Je(r)}catch{return}return process.platform==="win32"&&(s=s.toLowerCase()),s}n(he,"normalizeExistingPathForComparison");function ge(e){return Array.from(new Set([he(e,!1),he(e,!0)].filter(t=>!!t)))}n(ge,"getPathComparisonCandidates");function wt(){let e=process.argv[1];if(!e)return;let t=_(e);for(;t!==_(t);){if(C(h(t,"package.json")))return t;t=_(t)}}n(wt,"getEntrypointPackageDir");function ve(){let e=x();try{return Y(e,Q.W_OK),Y(_(e),Q.W_OK),!0}catch{return!1}}n(ve,"isSelfUpdatePathWritable");function Ee(e,t,r){let s=[x(),wt()].filter(o=>!!o).flatMap(o=>ge(o));return bt(e,t,r).some(o=>ge(o).some(a=>{let d=a.endsWith(ee)?a:`${a}${ee}`;return s.some(i=>i.startsWith(d))}))}n(Ee,"isManagedByGlobalPackageManager");function St(e,t,r=e){let s=V(),o=fe(s,e,r,t);if(!(!o||!Ee(s,e,t)||!ve()))return o}n(St,"getSelfUpdateCommand");function yt(e){let t=process.env.PI_SELF_UPDATE_COMMAND?.trim().split(/\s+/).filter(Boolean);return t?.length?t:e?.length?e:void 0}n(yt,"getConfiguredSelfUpdateArgv");function Pt(e,t){let r={packageName:t.packageName,version:t.version,installSpec:`${t.packageName}@${t.version}`},[s="",...o]=e.map(a=>a.replace(/\{(packageName|version|installSpec)\}/g,(d,i)=>r[i]));return $(s,o)}n(Pt,"makeConfiguredSelfUpdateCommand");function At(e,t,r=e){let s=V(),o=me(r);if(s==="bun-binary")return`Download from: ${I==="pi"?"https://github.com/earendil-works/pi/releases/latest":$e}`;let a=fe(s,e,o,t);return a&&Ee(s,e,t)&&!ve()?`This installation is managed by a global ${s} install, but the install path is not writable. Update it yourself with: ${a.display}`:`Update ${o.installSpec} using the package manager, wrapper, or source checkout that provides this installation.`}n(At,"getSelfUpdateUnavailableInstruction");function Ct(e){let t=e;for(;t!==_(t);){if(C(h(t,"package.json"))){let r=_(t);return Z(t)==="dist"&&C(h(r,"package.json"))?r:t}t=_(t)}return e}n(Ct,"findNodePackageDir");function x(){let e=process.env.PI_PACKAGE_DIR;return e?W(e):D?_(process.execPath):Ct(le)}n(x,"getPackageDir");function $t(){if(D)return h(x(),"theme");let e=x(),t=C(h(e,"src"))?"src":"dist";return h(e,t,"modes","interactive","theme")}n($t,"getThemesDir");function kt(){if(D)return h(x(),"export-html");let e=x(),t=C(h(e,"src"))?"src":"dist";return h(e,t,"core","export-html")}n(kt,"getExportTemplateDir");function Dt(){return h(x(),"package.json")}n(Dt,"getPackageJsonPath");function Nt(){return T(h(x(),"README.md"))}n(Nt,"getReadmePath");function Tt(){return T(h(x(),"docs"))}n(Tt,"getDocsPath");function xe(){return T(h(x(),"examples"))}n(xe,"getExamplesPath");function Ot(){return T(h(x(),"dal-docs"))}n(Ot,"getDalDocsPath");function It(){return T(h(xe(),"extensions","official"))}n(It,"getOfficialExtensionsPath");var Rt="@deepailab/dal-official-extensions";function Lt(e){try{return JSON.parse(B(q(h(e,"package.json"),"utf-8"))).name===Rt}catch{return!1}}n(Lt,"isOfficialExtensionsPackage");function Ut(){return T(h(x(),"CHANGELOG.md"))}n(Ut,"getChangelogPath");function jt(){if(D)return h(x(),"assets");let e=x(),t=C(h(e,"src"))?"src":"dist";return h(e,t,"modes","interactive","assets")}n(jt,"getInteractiveAssetsDir");function Wt(e){return h(jt(),e)}n(Wt,"getBundledInteractiveAssetPath");var _e;function qt(){return _e??=Ve(import.meta.url).resolve("quickjs-wasi/quickjs.wasm"),_e}n(qt,"getQuickJSWasmPath");function Ft(e,t){if(e==="bun-binary")return"./src/extensions/codemode/worker.ts";if(e==="bundled-node")return new URL("./codemode-worker.js",t)}n(Ft,"resolveCodemodeWorkerSpecifier");var be;function Mt(){let e=D?"bun-binary":pe?"bundled-node":"unbundled",t=Ft(e,import.meta.url);return e!=="bundled-node"||!(t instanceof URL)?t:(be??=new URL(`data:text/javascript;base64,${q(t).toString("base64")}`),be)}n(Mt,"getCodemodeWorkerSpecifier");function Bt(e=we){if(D||!e)return;let t;try{t=JSON.parse(B(q(e,"utf-8")))}catch(r){return r.code==="ENOENT"?{kind:"removed"}:void 0}return t.version&&t.version!==Pe?{kind:"updated",version:t.version}:void 0}n(Bt,"detectInstallChange");var O={},we;try{let e=Dt();O=JSON.parse(B(q(e,"utf-8"))),we=e}catch(e){if(e.code!=="ENOENT")throw e}var Se=O.piConfig?.name,Gt=O.name||"@earendil-works/pi-coding-agent",I=Se||"pi",zt=O.piConfig?.title||(Se?I:"\u03C0"),ye=O.piConfig?.configDir||".dal",Ht=I!=="pi",Kt=[".agents",".claude"],Pe=O.version||"0.0.0",Er=O.piConfig?.upstreamPi,Ae="@deepailab/dal",Jt="@deepailab",Ce="DeepAILab-Team/dal-dist",$e=`https://github.com/${Ce}/releases`,ke="https://git.siweibot.com/api/packages/gitea/npm",De=`${I.toUpperCase()}_CODING_AGENT_DIR`,Vt=`${I.toUpperCase()}_CODING_AGENT_SESSION_DIR`;function Ne(e){return W(e)}n(Ne,"expandTildePath");function Xt(e,t=`https://gist.github.com/${e}`){let r=process.env.DAL_SHARE_VIEWER_URL||process.env.PI_SHARE_VIEWER_URL;return r?`${r}#${e}`:t}n(Xt,"getShareViewerUrl");function R(){let e=process.env[De];return e?Ne(e):h(K(),ye,"agent")}n(R,"getAgentDir");function Yt(){return h(R(),"themes")}n(Yt,"getCustomThemesDir");function Qt(){return h(R(),"auth.json")}n(Qt,"getAuthPath");function Zt(){return h(R(),"settings.json")}n(Zt,"getSettingsPath");function er(){return h(R(),"bin")}n(er,"getBinDir");function tr(e){let t=h(e,"prompts"),r=h(e,"commands");return!C(t)&&C(r)?r:t}n(tr,"getProjectPromptsDir");function rr(){return h(R(),"sessions")}n(rr,"getSessionsDir");function nr(){return h(R(),`${I}-debug.log`)}n(nr,"getDebugLogPath");export{I as APP_NAME,zt as APP_TITLE,ye as CONFIG_DIR_NAME,$e as DAL_RELEASES_URL,Ce as DAL_RELEASE_REPO,Ae as DAL_UPDATE_PACKAGE,ke as DAL_UPDATE_REGISTRY,De as ENV_AGENT_DIR,Vt as ENV_SESSION_DIR,Ht as IS_WHITE_LABEL_BUILD,Gt as PACKAGE_NAME,Kt as SHARED_SKILL_CONFIG_DIRS,Pe as VERSION,lt as canonicalizePath,Bt as detectInstallChange,V as detectInstallMethod,Ne as expandTildePath,gt as formatPathRelativeToCwdOrAbsolute,R as getAgentDir,Qt as getAuthPath,er as getBinDir,Wt as getBundledInteractiveAssetPath,Ut as getChangelogPath,Mt as getCodemodeWorkerSpecifier,yt as getConfiguredSelfUpdateArgv,Yt as getCustomThemesDir,ue as getCwdRelativePath,Ot as getDalDocsPath,nr as getDebugLogPath,Tt as getDocsPath,xe as getExamplesPath,kt as getExportTemplateDir,dt as getFileRevision,It as getOfficialExtensionsPath,x as getPackageDir,j as getPathComparisonKey,tr as getProjectPromptsDir,qt as getQuickJSWasmPath,Nt as getReadmePath,St as getSelfUpdateCommand,At as getSelfUpdateUnavailableInstruction,rr as getSessionsDir,Zt as getSettingsPath,Xt as getShareViewerUrl,$t as getThemesDir,D as isBunBinary,pe as isBundledNode,ft as isLocalPath,Lt as isOfficialExtensionsPackage,ae as isPathWithin,Pt as makeConfiguredSelfUpdateCommand,vt as markPathIgnoredByCloudSync,W as normalizePath,pt as pathsEqual,X as require_cross_spawn,M as resolvePath,mt as shortenHomePath,tt as spawnProcess,F as spawnProcessSync,ce as splitBom,B as stripBom,rt as waitForChildProcess};
|
|
1
|
+
var Oe=Object.defineProperty;var n=(e,t)=>Oe(e,"name",{value:t,configurable:!0});import{createRequire as Ie}from"node:module";const ar=Ie(import.meta.url);import{__commonJS as S,__require as D,__toESM as Re}from"./chunk-JXWJOIH4.js";var Le=S({"node_modules/isexe/windows.js"(e,t){t.exports=a,a.sync=d;var r=D("fs");function s(i,u){var m=u.pathExt!==void 0?u.pathExt:process.env.PATHEXT;if(!m||(m=m.split(";"),m.indexOf("")!==-1))return!0;for(var c=0;c<m.length;c++){var l=m[c].toLowerCase();if(l&&i.substr(-l.length).toLowerCase()===l)return!0}return!1}n(s,"checkPathExt");function o(i,u,m){return!i.isSymbolicLink()&&!i.isFile()?!1:s(u,m)}n(o,"checkStat");function a(i,u,m){r.stat(i,function(c,l){m(c,c?!1:o(l,i,u))})}n(a,"isexe");function d(i,u){return o(r.statSync(i),i,u)}n(d,"sync")}}),Ue=S({"node_modules/isexe/mode.js"(e,t){t.exports=s,s.sync=o;var r=D("fs");function s(i,u,m){r.stat(i,function(c,l){m(c,c?!1:a(l,u))})}n(s,"isexe");function o(i,u){return a(r.statSync(i),u)}n(o,"sync");function a(i,u){return i.isFile()&&d(i,u)}n(a,"checkStat");function d(i,u){var m=i.mode,c=i.uid,l=i.gid,p=u.uid!==void 0?u.uid:process.getuid&&process.getuid(),f=u.gid!==void 0?u.gid:process.getgid&&process.getgid(),g=parseInt("100",8),E=parseInt("010",8),b=parseInt("001",8),w=g|E,P=m&b||m&E&&l===f||m&g&&c===p||m&w&&p===0;return P}n(d,"checkMode")}}),je=S({"node_modules/isexe/index.js"(e,t){var r=D("fs"),s;process.platform==="win32"||global.TESTING_WINDOWS?s=Le():s=Ue(),t.exports=o,o.sync=a;function o(d,i,u){if(typeof i=="function"&&(u=i,i={}),!u){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(m,c){o(d,i||{},function(l,p){l?c(l):m(p)})})}s(d,i||{},function(m,c){m&&(m.code==="EACCES"||i&&i.ignoreErrors)&&(m=null,c=!1),u(m,c)})}n(o,"isexe");function a(d,i){try{return s.sync(d,i||{})}catch(u){if(i&&i.ignoreErrors||u.code==="EACCES")return!1;throw u}}n(a,"sync")}}),We=S({"node_modules/which/which.js"(e,t){var r=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",s=D("path"),o=r?";":":",a=je(),d=n(c=>Object.assign(new Error(`not found: ${c}`),{code:"ENOENT"}),"getNotFoundError"),i=n((c,l)=>{let p=l.colon||o,f=c.match(/\//)||r&&c.match(/\\/)?[""]:[...r?[process.cwd()]:[],...(l.path||process.env.PATH||"").split(p)],g=r?l.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",E=r?g.split(p):[""];return r&&c.indexOf(".")!==-1&&E[0]!==""&&E.unshift(""),{pathEnv:f,pathExt:E,pathExtExe:g}},"getPathInfo"),u=n((c,l,p)=>{typeof l=="function"&&(p=l,l={}),l||(l={});let{pathEnv:f,pathExt:g,pathExtExe:E}=i(c,l),b=[],w=n(v=>new Promise((N,A)=>{if(v===f.length)return l.all&&b.length?N(b):A(d(c));let y=f[v],z=/^".*"$/.test(y)?y.slice(1,-1):y,L=s.join(z,c),H=!z&&/^\.[\\\/]/.test(c)?c.slice(0,2)+L:L;N(P(H,v,0))}),"step"),P=n((v,N,A)=>new Promise((y,z)=>{if(A===g.length)return y(w(N+1));let L=g[A];a(v+L,{pathExt:E},(H,Te)=>{if(!H&&Te)if(l.all)b.push(v+L);else return y(v+L);return y(P(v,N,A+1))})}),"subStep");return p?w(0).then(v=>p(null,v),p):w(0)},"which"),m=n((c,l)=>{l=l||{};let{pathEnv:p,pathExt:f,pathExtExe:g}=i(c,l),E=[];for(let b=0;b<p.length;b++){let w=p[b],P=/^".*"$/.test(w)?w.slice(1,-1):w,v=s.join(P,c),N=!P&&/^\.[\\\/]/.test(c)?c.slice(0,2)+v:v;for(let A=0;A<f.length;A++){let y=N+f[A];try{if(a.sync(y,{pathExt:g}))if(l.all)E.push(y);else return y}catch{}}}if(l.all&&E.length)return E;if(l.nothrow)return null;throw d(c)},"whichSync");t.exports=u,u.sync=m}}),qe=S({"node_modules/path-key/index.js"(e,t){"use strict";var r=n((s={})=>{let o=s.env||process.env;return(s.platform||process.platform)!=="win32"?"PATH":Object.keys(o).reverse().find(a=>a.toUpperCase()==="PATH")||"Path"},"pathKey");t.exports=r,t.exports.default=r}}),Fe=S({"node_modules/cross-spawn/lib/util/resolveCommand.js"(e,t){"use strict";var r=D("path"),s=We(),o=qe();function a(i,u){let m=i.options.env||process.env,c=process.cwd(),l=i.options.cwd!=null,p=l&&process.chdir!==void 0&&!process.chdir.disabled;if(p)try{process.chdir(i.options.cwd)}catch{}let f;try{f=s.sync(i.command,{path:m[o({env:m})],pathExt:u?r.delimiter:void 0})}catch{}finally{p&&process.chdir(c)}return f&&(f=r.resolve(l?i.options.cwd:"",f)),f}n(a,"resolveCommandAttempt");function d(i){return a(i)||a(i,!0)}n(d,"resolveCommand"),t.exports=d}}),Me=S({"node_modules/cross-spawn/lib/util/escape.js"(e,t){"use strict";var r=/([()\][%!^"`<>&|;, *?])/g;function s(a){return a=a.replace(r,"^$1"),a}n(s,"escapeCommand");function o(a,d){return a=`${a}`,a=a.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),a=a.replace(/(?=(\\+?)?)\1$/,"$1$1"),a=`"${a}"`,a=a.replace(r,"^$1"),d&&(a=a.replace(r,"^$1")),a}n(o,"escapeArgument"),t.exports.command=s,t.exports.argument=o}}),Be=S({"node_modules/shebang-regex/index.js"(e,t){"use strict";t.exports=/^#!(.*)/}}),Ge=S({"node_modules/shebang-command/index.js"(e,t){"use strict";var r=Be();t.exports=(s="")=>{let o=s.match(r);if(!o)return null;let[a,d]=o[0].replace(/#! ?/,"").split(" "),i=a.split("/").pop();return i==="env"?d:d?`${i} ${d}`:i}}}),ze=S({"node_modules/cross-spawn/lib/util/readShebang.js"(e,t){"use strict";var r=D("fs"),s=Ge();function o(a){let d=Buffer.alloc(150),i;try{i=r.openSync(a,"r"),r.readSync(i,d,0,150,0),r.closeSync(i)}catch{}return s(d.toString())}n(o,"readShebang"),t.exports=o}}),He=S({"node_modules/cross-spawn/lib/parse.js"(e,t){"use strict";var r=D("path"),s=Fe(),o=Me(),a=ze(),d=process.platform==="win32",i=/\.(?:com|exe)$/i,u=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function m(p){p.file=s(p);let f=p.file&&a(p.file);return f?(p.args.unshift(p.file),p.command=f,s(p)):p.file}n(m,"detectShebang");function c(p){if(!d)return p;let f=m(p),g=!i.test(f);if(p.options.forceShell||g){let E=u.test(f);p.command=r.normalize(p.command),p.command=o.command(p.command),p.args=p.args.map(w=>o.argument(w,E));let b=[p.command].concat(p.args).join(" ");p.args=["/d","/s","/c",`"${b}"`],p.command=process.env.comspec||"cmd.exe",p.options.windowsVerbatimArguments=!0}return p}n(c,"parseNonShell");function l(p,f,g){f&&!Array.isArray(f)&&(g=f,f=null),f=f?f.slice(0):[],g=Object.assign({},g);let E={command:p,args:f,options:g,file:void 0,original:{command:p,args:f}};return g.shell?E:c(E)}n(l,"parse"),t.exports=l}}),Ke=S({"node_modules/cross-spawn/lib/enoent.js"(e,t){"use strict";var r=process.platform==="win32";function s(i,u){return Object.assign(new Error(`${u} ${i.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${u} ${i.command}`,path:i.command,spawnargs:i.args})}n(s,"notFoundError");function o(i,u){if(!r)return;let m=i.emit;i.emit=function(c,l){if(c==="exit"){let p=a(l,u);if(p)return m.call(i,"error",p)}return m.apply(i,arguments)}}n(o,"hookChildProcess");function a(i,u){return r&&i===1&&!u.file?s(u.original,"spawn"):null}n(a,"verifyENOENT");function d(i,u){return r&&i===1&&!u.file?s(u.original,"spawnSync"):null}n(d,"verifyENOENTSync"),t.exports={hookChildProcess:o,verifyENOENT:a,verifyENOENTSync:d,notFoundError:s}}}),X=S({"node_modules/cross-spawn/index.js"(e,t){"use strict";var r=D("child_process"),s=He(),o=Ke();function a(i,u,m){let c=s(i,u,m),l=r.spawn(c.command,c.args,c.options);return o.hookChildProcess(l,c),l}n(a,"spawn");function d(i,u,m){let c=s(i,u,m),l=r.spawnSync(c.command,c.args,c.options);return l.error=l.error||o.verifyENOENTSync(l.status,c),l}n(d,"spawnSync"),t.exports=a,t.exports.spawn=a,t.exports.sync=d,t.exports._parse=s,t.exports._enoent=o}});import{accessSync as Y,constants as Q,existsSync as C,readFileSync as q,realpathSync as Je}from"fs";import{createRequire as Ve}from"module";import{homedir as K}from"os";import{basename as Z,dirname as _,join as h,resolve as T,sep as ee,win32 as Xe}from"path";import{fileURLToPath as Ye}from"url";var te=Re(X(),1);import{spawn as Qe,spawnSync as Ze}from"node:child_process";var et=100;function tt(e,t,r){return process.platform==="win32"?(0,te.default)(e,t,r):Qe(e,t,r)}n(tt,"spawnProcess");function F(e,t,r){return process.platform==="win32"?te.default.sync(e,t,r):Ze(e,t,r)}n(F,"spawnProcessSync");function rt(e){return new Promise((t,r)=>{let s=!1,o=!1,a=null,d,i=e.stdout===null,u=e.stderr===null,m=n(()=>{d&&(clearTimeout(d),d=void 0),e.removeListener("error",b),e.removeListener("exit",w),e.removeListener("close",P),e.stdout?.removeListener("end",g),e.stderr?.removeListener("end",E),e.stdout?.removeListener("data",f),e.stderr?.removeListener("data",f)},"cleanup"),c=n(v=>{s||(s=!0,m(),e.stdout?.destroy(),e.stderr?.destroy(),t(v))},"finalize"),l=n(()=>{!o||s||i&&u&&c(a)},"maybeFinalizeAfterExit"),p=n(()=>{d&&clearTimeout(d),d=setTimeout(()=>c(a),et)},"armIdleTimer"),f=n(()=>{o&&!s&&p()},"onData"),g=n(()=>{i=!0,l()},"onStdoutEnd"),E=n(()=>{u=!0,l()},"onStderrEnd"),b=n(v=>{s||(s=!0,m(),r(v))},"onError"),w=n(v=>{o=!0,a=v,l(),s||p()},"onExit"),P=n(v=>{c(v)},"onClose");e.stdout?.once("end",g),e.stderr?.once("end",E),e.stdout?.on("data",f),e.stderr?.on("data",f),e.once("error",b),e.once("exit",w),e.once("close",P)})}n(rt,"waitForChildProcess");import{realpathSync as nt,statSync as st}from"node:fs";import{homedir as re}from"node:os";import{isAbsolute as ne,join as it,resolve as se,posix as ot,relative as at,sep as ie,win32 as oe}from"node:path";import{fileURLToPath as ut}from"node:url";var ct=/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;function lt(e){try{return nt(e)}catch{return e}}n(lt,"canonicalizePath");function j(e){let t=J(),r=t.resolve(e);return t===oe?r.toLowerCase():r}n(j,"getPathComparisonKey");function J(){return process.platform==="win32"?oe:ot}n(J,"getPlatformPathApi");function pt(e,t){return j(e)===j(t)}n(pt,"pathsEqual");function ae(e,t){let r=j(e),s=j(t);if(s===r)return!0;let o=J().sep;return s.startsWith(r.endsWith(o)?r:`${r}${o}`)}n(ae,"isPathWithin");function mt(e,t=re()){let r=J();if(!t||!r.isAbsolute(e)||!ae(t,e))return e;let s=r.relative(t,e);return s?`~${r.sep}${s}`:"~"}n(mt,"shortenHomePath");function dt(e){try{let t=st(e,{bigint:!0});return`${t.dev}:${t.ino}:${t.size}:${t.mtimeNs}:${t.ctimeNs}`}catch{return}}n(dt,"getFileRevision");function ft(e){let t=e.trim();return!(t.startsWith("npm:")||t.startsWith("git:")||t.startsWith("github:")||t.startsWith("http:")||t.startsWith("https:")||t.startsWith("ssh:")||t.startsWith("builtin:"))}n(ft,"isLocalPath");function ht(e){if(!e.startsWith("/")||e.startsWith("//")||e.includes("\\"))return e;let t=e.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i);if(!t)return e;let r=t[2]?.replaceAll("/","\\");return`${t[1].toUpperCase()}:\\${r??""}`}n(ht,"normalizeWindowsShellPath");function W(e,t={}){let r=t.trim?e.trim():e;if(t.normalizeUnicodeSpaces&&(r=r.replace(ct," ")),t.stripAtPrefix&&r.startsWith("@")&&(r=r.slice(1)),process.platform==="win32"&&(r=ht(r)),t.expandTilde??!0){let s=t.homeDir??re();if(r==="~")return s;if(r.startsWith("~/")||process.platform==="win32"&&r.startsWith("~\\"))return it(s,r.slice(2))}return/^file:\/\//.test(r)?ut(r):r}n(W,"normalizePath");function M(e,t=process.cwd(),r={}){let s=W(e,r),o=W(t);return ne(s)?se(s):se(o,s)}n(M,"resolvePath");function ue(e,t){let r=M(t),s=M(e,r),o=at(r,s);return o===""||o!==".."&&!o.startsWith(`..${ie}`)&&!ne(o)?o||".":void 0}n(ue,"getCwdRelativePath");function gt(e,t){let r=M(e,t);return(ue(r,t)??r).split(ie).join("/")}n(gt,"formatPathRelativeToCwdOrAbsolute");function vt(e){let t=process.platform==="darwin"?["com.dropbox.ignored","com.apple.fileprovider.ignore#P"]:process.platform==="linux"?["user.com.dropbox.ignored"]:[];for(let r of t)process.platform==="darwin"?F("xattr",["-w",r,"1",e],{encoding:"utf-8",stdio:"ignore"}):F("setfattr",["-n",r,"-v","1",e],{encoding:"utf-8",stdio:"ignore"})}n(vt,"markPathIgnoredByCloudSync");function ce(e){return e.startsWith("\uFEFF")?{bom:"\uFEFF",text:e.slice(1)}:{bom:"",text:e}}n(ce,"splitBom");function B(e){return ce(e).text}n(B,"stripBom");var Et=Ye(import.meta.url),le=_(Et),k=import.meta.url.includes("$bunfs")||import.meta.url.includes("~BUN")||import.meta.url.includes("%7EBUN"),xt=!!process.versions.bun,pe=!0;function _t(e){return e.startsWith("https://")||e.startsWith("http://")}n(_t,"isUrlInstallSpec");function me(e){return typeof e=="string"?{packageName:e,installSpec:e}:{packageName:e.packageName,installSpec:e.installSpec??e.packageName}}n(me,"normalizeSelfUpdatePackageTarget");function G(e,t){return t?{...e,display:`${t.display} && ${e.display}`,steps:[t,e]}:e}n(G,"makeSelfUpdateCommand");function $(e,t){return{command:e,args:t,display:[e,...t].map(r=>/\s/.test(r)?`"${r}"`:r).join(" ")}}n($,"makeSelfUpdateCommandStep");function V(){if(k)return"bun-binary";let e=`${le}\0${process.execPath||""}`.toLowerCase().replace(/\\/g,"/");return e.includes("/pnpm/")||e.includes("/.pnpm/")?"pnpm":e.includes("/yarn/")||e.includes("/.yarn/")?"yarn":xt||e.includes("/install/global/node_modules/")?"bun":e.includes("/npm/")||e.includes("/node_modules/")?"npm":"unknown"}n(V,"detectInstallMethod");function de(){let e=x(),t=process.platform==="win32"||e.includes("\\")?Xe:{basename:Z,dirname:_},r=t.dirname(e),s;if(t.basename(r).startsWith("@")&&t.basename(t.dirname(r))==="node_modules"?s=t.dirname(r):t.basename(r)==="node_modules"&&(s=r),!s)return;let o=t.dirname(s);if(t.basename(o)==="lib")return{root:s,prefix:t.dirname(o)}}n(de,"getInferredNpmInstall");function fe(e,t,r=t,s){let o=me(r),a=o.packageName===Ae&&!_t(o.installSpec)?[`--${Vt}:registry=${De}/`]:[];switch(e){case"bun-binary":return;case"pnpm":{let d=U("pnpm",["root","-g"])?void 0:/^(.*[\\/]global[\\/][^\\/]+)[\\/]\.pnpm[\\/]/.exec(x()),i=d?[`--config.global-bin-dir=${process.env.PNPM_HOME||_(_(d[1]))}`]:[];return G($("pnpm",["install","-g","--ignore-scripts","--config.minimumReleaseAge=0",...i,...a,o.installSpec]),o.packageName===t?void 0:$("pnpm",["remove","-g",...i,t]))}case"yarn":return G($("yarn",["global","add","--ignore-scripts",...a,o.installSpec]),o.packageName===t?void 0:$("yarn",["global","remove",t]));case"bun":return G($("bun",["install","-g","--ignore-scripts","--minimum-release-age=0",...a,o.installSpec]),o.packageName===t?void 0:$("bun",["uninstall","-g",t]));case"npm":{let[d="npm",...i]=s??[],u=s?.length?void 0:de(),m=[...i,...u?["--prefix",u.prefix]:[]],c=$(d,[...m,"install","-g","--ignore-scripts","--min-release-age=0",...a,o.installSpec]),l=o.packageName===t?void 0:$(d,[...m,"uninstall","-g",t]);return G(c,l)}case"unknown":return}}n(fe,"getSelfUpdateCommandForMethod");function U(e,t,r={}){let s=F(e,t,{encoding:"utf-8",stdio:["ignore","pipe","pipe"]});if(s.status===0)return s.stdout.trim()||void 0;if(r.requireSuccess){let o=s.error?.message||s.stderr.trim()||`exit code ${s.status??"unknown"}`;throw new Error(`Failed to run ${[e,...t].join(" ")}: ${o}`)}}n(U,"readCommandOutput");function bt(e,t,r){switch(e){case"npm":{let s=!!r?.length,[o="npm",...a]=r??[];if(s&&o==="bun"){let u=U(o,[...a,"pm","bin","-g"],{requireSuccess:!0}),m=[h(K(),".bun","install","global","node_modules")];return u&&m.push(h(_(u),"install","global","node_modules")),m}let d=U(o,[...a,"root","-g"],{requireSuccess:s}),i=s?void 0:de();return[d,i?.root].filter(u=>!!u)}case"pnpm":{let s=U("pnpm",["root","-g"]);if(s)return[s,_(s)];let o=/^(.*[\\/]global[\\/][^\\/]+)[\\/]\.pnpm[\\/]/.exec(x());return o?[o[1]]:[]}case"yarn":{let s=U("yarn",["global","dir"]);return s?[s,h(s,"node_modules")]:[]}case"bun":{let s=U("bun",["pm","bin","-g"]),o=[h(K(),".bun","install","global","node_modules")];return s&&o.push(h(_(s),"install","global","node_modules")),o}case"bun-binary":case"unknown":return[]}}n(bt,"getGlobalPackageRoots");function he(e,t){let r=T(e);if(!C(r))return;let s=r;if(t)try{s=Je(r)}catch{return}return process.platform==="win32"&&(s=s.toLowerCase()),s}n(he,"normalizeExistingPathForComparison");function ge(e){return Array.from(new Set([he(e,!1),he(e,!0)].filter(t=>!!t)))}n(ge,"getPathComparisonCandidates");function wt(){let e=process.argv[1];if(!e)return;let t=_(e);for(;t!==_(t);){if(C(h(t,"package.json")))return t;t=_(t)}}n(wt,"getEntrypointPackageDir");function ve(){let e=x();try{return Y(e,Q.W_OK),Y(_(e),Q.W_OK),!0}catch{return!1}}n(ve,"isSelfUpdatePathWritable");function Ee(e,t,r){let s=[x(),wt()].filter(o=>!!o).flatMap(o=>ge(o));return bt(e,t,r).some(o=>ge(o).some(a=>{let d=a.endsWith(ee)?a:`${a}${ee}`;return s.some(i=>i.startsWith(d))}))}n(Ee,"isManagedByGlobalPackageManager");function St(e,t,r=e){let s=V(),o=fe(s,e,r,t);if(!(!o||!Ee(s,e,t)||!ve()))return o}n(St,"getSelfUpdateCommand");function yt(e){let t=process.env.PI_SELF_UPDATE_COMMAND?.trim().split(/\s+/).filter(Boolean);return t?.length?t:e?.length?e:void 0}n(yt,"getConfiguredSelfUpdateArgv");function Pt(e,t){let r={packageName:t.packageName,version:t.version,installSpec:`${t.packageName}@${t.version}`},[s="",...o]=e.map(a=>a.replace(/\{(packageName|version|installSpec)\}/g,(d,i)=>r[i]));return $(s,o)}n(Pt,"makeConfiguredSelfUpdateCommand");function At(e,t,r=e){let s=V(),o=me(r);if(s==="bun-binary")return`Download from: ${I==="pi"?"https://github.com/earendil-works/pi/releases/latest":$e}`;let a=fe(s,e,o,t);return a&&Ee(s,e,t)&&!ve()?`This installation is managed by a global ${s} install, but the install path is not writable. Update it yourself with: ${a.display}`:`Update ${o.installSpec} using the package manager, wrapper, or source checkout that provides this installation.`}n(At,"getSelfUpdateUnavailableInstruction");function Ct(e){let t=e;for(;t!==_(t);){if(C(h(t,"package.json"))){let r=_(t);return Z(t)==="dist"&&C(h(r,"package.json"))?r:t}t=_(t)}return e}n(Ct,"findNodePackageDir");function x(){let e=process.env.PI_PACKAGE_DIR;return e?W(e):k?_(process.execPath):Ct(le)}n(x,"getPackageDir");function $t(){if(k)return h(x(),"theme");let e=x(),t=C(h(e,"src"))?"src":"dist";return h(e,t,"modes","interactive","theme")}n($t,"getThemesDir");function Dt(){if(k)return h(x(),"export-html");let e=x(),t=C(h(e,"src"))?"src":"dist";return h(e,t,"core","export-html")}n(Dt,"getExportTemplateDir");function kt(){return h(x(),"package.json")}n(kt,"getPackageJsonPath");function Nt(){return T(h(x(),"README.md"))}n(Nt,"getReadmePath");function Tt(){return T(h(x(),"docs"))}n(Tt,"getDocsPath");function xe(){return T(h(x(),"examples"))}n(xe,"getExamplesPath");function Ot(){return T(h(x(),"dal-docs"))}n(Ot,"getDalDocsPath");function It(){return T(h(xe(),"extensions","official"))}n(It,"getOfficialExtensionsPath");var Rt="@deepailab/dal-official-extensions";function Lt(e){try{return JSON.parse(B(q(h(e,"package.json"),"utf-8"))).name===Rt}catch{return!1}}n(Lt,"isOfficialExtensionsPackage");function Ut(){return T(h(x(),"CHANGELOG.md"))}n(Ut,"getChangelogPath");function jt(){if(k)return h(x(),"assets");let e=x(),t=C(h(e,"src"))?"src":"dist";return h(e,t,"modes","interactive","assets")}n(jt,"getInteractiveAssetsDir");function Wt(e){return h(jt(),e)}n(Wt,"getBundledInteractiveAssetPath");var _e;function qt(){return _e??=Ve(import.meta.url).resolve("quickjs-wasi/quickjs.wasm"),_e}n(qt,"getQuickJSWasmPath");function Ft(e,t){if(e==="bun-binary")return"./src/extensions/codemode/worker.ts";if(e==="bundled-node")return new URL("./codemode-worker.js",t)}n(Ft,"resolveCodemodeWorkerSpecifier");var be;function Mt(){let e=k?"bun-binary":pe?"bundled-node":"unbundled",t=Ft(e,import.meta.url);return e!=="bundled-node"||!(t instanceof URL)?t:(be??=new URL(`data:text/javascript;base64,${q(t).toString("base64")}`),be)}n(Mt,"getCodemodeWorkerSpecifier");function Bt(e=we){if(k||!e)return;let t;try{t=JSON.parse(B(q(e,"utf-8")))}catch(r){return r.code==="ENOENT"?{kind:"removed"}:void 0}return t.version&&t.version!==Pe?{kind:"updated",version:t.version}:void 0}n(Bt,"detectInstallChange");var O={},we;try{let e=kt();O=JSON.parse(B(q(e,"utf-8"))),we=e}catch(e){if(e.code!=="ENOENT")throw e}var Se=O.piConfig?.name,Gt=O.name||"@earendil-works/pi-coding-agent",I=Se||"pi";function zt(e){let t=e?.trim();if(!(!t||t.length>40||/[\u0000-\u001f\u007f<>]/.test(t)))return t}n(zt,"hostProductTitle");var Ht=zt(process.env.DAL_PRODUCT_TITLE)||O.piConfig?.title||(Se?I:"\u03C0"),ye=O.piConfig?.configDir||".dal",Kt=I!=="pi",Jt=[".agents",".claude"],Pe=O.version||"0.0.0",xr=O.piConfig?.upstreamPi,Ae="@deepailab/dal",Vt="@deepailab",Ce="DeepAILab-Team/dal-dist",$e=`https://github.com/${Ce}/releases`,De="https://git.siweibot.com/api/packages/gitea/npm",ke=`${I.toUpperCase()}_CODING_AGENT_DIR`,Xt=`${I.toUpperCase()}_CODING_AGENT_SESSION_DIR`;function Ne(e){return W(e)}n(Ne,"expandTildePath");function Yt(e,t=`https://gist.github.com/${e}`){let r=process.env.DAL_SHARE_VIEWER_URL||process.env.PI_SHARE_VIEWER_URL;return r?`${r}#${e}`:t}n(Yt,"getShareViewerUrl");function R(){let e=process.env[ke];return e?Ne(e):h(K(),ye,"agent")}n(R,"getAgentDir");function Qt(){return h(R(),"themes")}n(Qt,"getCustomThemesDir");function Zt(){return h(R(),"auth.json")}n(Zt,"getAuthPath");function er(){return h(R(),"settings.json")}n(er,"getSettingsPath");function tr(){return h(R(),"bin")}n(tr,"getBinDir");function rr(e){let t=h(e,"prompts"),r=h(e,"commands");return!C(t)&&C(r)?r:t}n(rr,"getProjectPromptsDir");function nr(){return h(R(),"sessions")}n(nr,"getSessionsDir");function sr(){return h(R(),`${I}-debug.log`)}n(sr,"getDebugLogPath");export{I as APP_NAME,Ht as APP_TITLE,ye as CONFIG_DIR_NAME,$e as DAL_RELEASES_URL,Ce as DAL_RELEASE_REPO,Ae as DAL_UPDATE_PACKAGE,De as DAL_UPDATE_REGISTRY,ke as ENV_AGENT_DIR,Xt as ENV_SESSION_DIR,Kt as IS_WHITE_LABEL_BUILD,Gt as PACKAGE_NAME,Jt as SHARED_SKILL_CONFIG_DIRS,Pe as VERSION,lt as canonicalizePath,Bt as detectInstallChange,V as detectInstallMethod,Ne as expandTildePath,gt as formatPathRelativeToCwdOrAbsolute,R as getAgentDir,Zt as getAuthPath,tr as getBinDir,Wt as getBundledInteractiveAssetPath,Ut as getChangelogPath,Mt as getCodemodeWorkerSpecifier,yt as getConfiguredSelfUpdateArgv,Qt as getCustomThemesDir,ue as getCwdRelativePath,Ot as getDalDocsPath,sr as getDebugLogPath,Tt as getDocsPath,xe as getExamplesPath,Dt as getExportTemplateDir,dt as getFileRevision,It as getOfficialExtensionsPath,x as getPackageDir,j as getPathComparisonKey,rr as getProjectPromptsDir,qt as getQuickJSWasmPath,Nt as getReadmePath,St as getSelfUpdateCommand,At as getSelfUpdateUnavailableInstruction,nr as getSessionsDir,er as getSettingsPath,Yt as getShareViewerUrl,$t as getThemesDir,k as isBunBinary,pe as isBundledNode,ft as isLocalPath,Lt as isOfficialExtensionsPackage,ae as isPathWithin,Pt as makeConfiguredSelfUpdateCommand,vt as markPathIgnoredByCloudSync,W as normalizePath,pt as pathsEqual,X as require_cross_spawn,M as resolvePath,mt as shortenHomePath,tt as spawnProcess,F as spawnProcessSync,ce as splitBom,B as stripBom,rt as waitForChildProcess};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Yt=Object.defineProperty;var o=(e,t)=>Yt(e,"name",{value:t,configurable:!0});import{createRequire as Vt}from"node:module";const ks=Vt(import.meta.url);import{getProviderEnvValue as qt}from"./chunk-7DDKXS2Q.js";import{ToolCallArgumentsStream as Ht}from"./chunk-FFMDRXC4.js";import{calculateCost as Kt,createProvider as Jt}from"./chunk-
|
|
1
|
+
var Yt=Object.defineProperty;var o=(e,t)=>Yt(e,"name",{value:t,configurable:!0});import{createRequire as Vt}from"node:module";const ks=Vt(import.meta.url);import{getProviderEnvValue as qt}from"./chunk-7DDKXS2Q.js";import{ToolCallArgumentsStream as Ht}from"./chunk-FFMDRXC4.js";import{calculateCost as Kt,createProvider as Jt}from"./chunk-4KCKRVPN.js";import{createAssistantMessageEventStream as be}from"./chunk-4LDEEFCY.js";import{getSystemMessageText as Xt}from"./chunk-CIJDL6I3.js";function Zt(e,t){return{name:e,login:o(async r=>{r.signal.throwIfAborted();let n=await r.prompt({type:"secret",message:`Enter ${e}`});return r.signal.throwIfAborted(),{type:"api_key",key:n}},"login"),resolve:o(async({ctx:r,credential:n,signal:i})=>{if(i.throwIfAborted(),n?.key)return{auth:{apiKey:n.key},env:n.env,source:"stored credential"};for(let s of t){let a=await r.env(s);if(i.throwIfAborted(),a)return{auth:{apiKey:a},source:s}}},"resolve")}}o(Zt,"envApiKeyAuth");function Qt(e){let t,r=o(()=>(t??=e.load(),t),"loaded");return{name:e.name,isSubscription:e.isSubscription,loginLabel:e.loginLabel,login:o(async(n,i)=>(await r()).login(n,i),"login"),refresh:o(async(n,i)=>(await r()).refresh(n,i),"refresh"),toAuth:o(async n=>(await r()).toAuth(n),"toAuth")}}o(Qt,"lazyOAuth");var er=60*6e4,tr=30*6e4,Oe=.05,ke=.15;function rr(e){if(!(e<=1e4))return Math.max(1,Math.floor(Math.min(e*.9,e-1e4)))}o(rr,"getCacheWarmingDelayMs");function nr(e,t){let r=t?.cacheRetention??(qt("PI_CACHE_RETENTION",t?.env)==="long"?"long":"short");if(r==="none")return;let n=e.promptCache?.[r];return n===void 0?void 0:n*1e3}o(nr,"getPromptCacheTtlMs");function ir(e,t){return!t?.reasoning||e.api!=="anthropic-messages"?!0:e.compat?.forceAdaptiveThinking===!0}o(ir,"isCacheWarmingReplayable");function sr(e,t){return{...e,maxTokens:1,disableContinuation:!0,maxRetries:0,signal:t}}o(sr,"getCacheWarmingRequestOptions");function or(e,t,r){let n=ie(e,{cacheRead:t}),i=ie(e,e.cost.cacheWrite>0?{cacheWrite:t}:{input:t}),s=ie(e,{cacheRead:t,output:1}),a=Math.max(0,i-n),f=r==="idle"?ke:1,u=t>0&&(n>0||i>0),c=f*a-s;return{phase:r,warmCost:s,missCost:a,continuationProbability:f,expectedSavings:c,economicsAvailable:u,action:c>=Oe?"warm":"stop"}}o(or,"evaluateCacheWarming");function ie(e,t){let r={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},...t};return Kt(e,r).total}o(ie,"price");var Ee="faux",xe="faux",we="faux-1",ar="Faux Model",fr="http://localhost:0",ur=3,Re=5,V={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function _e(e){return{type:"text",text:e}}o(_e,"fauxText");function cr(e){return{type:"thinking",thinking:e}}o(cr,"fauxThinking");function lr(e,t,r={}){return{type:"toolCall",id:r.id??se("tool"),name:e,arguments:t}}o(lr,"fauxToolCall");function dr(e){return typeof e=="string"?[_e(e)]:Array.isArray(e)?e:[e]}o(dr,"normalizeFauxAssistantContent");function hr(e,t={}){return{role:"assistant",content:dr(e),api:Ee,provider:xe,model:we,usage:V,stopReason:t.stopReason??"stop",...t.deferred===void 0?{}:{deferred:t.deferred},...t.errorMessage===void 0?{}:{errorMessage:t.errorMessage},...t.responseId===void 0?{}:{responseId:t.responseId},timestamp:t.timestamp??Date.now()}}o(hr,"fauxAssistantMessage");function Ne(e){return Math.ceil(e.length/4)}o(Ne,"estimateTokens");function se(e){return`${e}:${Date.now()}:${Math.random().toString(36).slice(2)}`}o(se,"randomId");function $e(e){return typeof e=="string"?e:e.map(t=>t.type==="text"?t.text:`[image:${t.mimeType}:${t.data.length}]`).join(`
|
|
2
2
|
`)}o($e,"contentToText");function Se(e){return e.map(t=>t.type==="text"?t.text:t.type==="thinking"?t.thinking:`${t.name}:${JSON.stringify(t.arguments)}`).join(`
|
|
3
3
|
`)}o(Se,"assistantContentToText");function pr(e){return[e.toolName,...e.content.map(t=>$e([t]))].join(`
|
|
4
4
|
`)}o(pr,"toolResultToText");function mr(e){return e.role==="system"?[Xt(e),...e.toolsRemoved?.map(t=>`tool-:${JSON.stringify(t)}`)??[],...e.toolsAdded?.map(t=>`tool+:${JSON.stringify(t)}`)??[]].filter(t=>t.length>0).join(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var $=Object.defineProperty;var p=(e,r)=>$(e,"name",{value:r,configurable:!0});import{createRequire as h}from"node:module";const q=h(import.meta.url);import{isRecord as u,parseClassifierUsage as y,postClassifierRequest as b,requiredNumber as f}from"./chunk-
|
|
1
|
+
var $=Object.defineProperty;var p=(e,r)=>$(e,"name",{value:r,configurable:!0});import{createRequire as h}from"node:module";const q=h(import.meta.url);import{isRecord as u,parseClassifierUsage as y,postClassifierRequest as b,requiredNumber as f}from"./chunk-X2O23QIN.js";import{formatProviderError as E,normalizeProviderError as _}from"./chunk-THJSXCE4.js";var l={"TypeSafe-Danger-Zone-Images":"true"};function I(e,r,a){if(!u(r))throw new Error(`${e} returned invalid probabilities for ${a}`);return Object.fromEntries(Object.entries(r).map(([o,t])=>[o,f(e,t,`probability for ${a}.${o}`)]))}p(I,"probabilities");function O(e,r,a){if(!u(r))throw new Error(`${e} returned an unexpected response`);let o=[];for(let[t,s]of Object.entries(a.questions)){let i=r[t];if(!u(i))throw new Error(`${e} did not return an answer for ${t}`);if(s.type==="choice"){if(i.type!=="choice"||typeof i.choice!="string")throw new Error(`${e} did not return a choice answer for ${t}`);o.push([t,{type:"choice",choice:i.choice,probabilities:I(e,i.probabilities,t),confidence:f(e,i.confidence,`confidence for ${t}`)}])}else if(s.type==="score"){if(i.type!=="score")throw new Error(`${e} did not return a score answer for ${t}`);o.push([t,{type:"score",score:f(e,i.score,`score for ${t}`),confidence:f(e,i.confidence,`confidence for ${t}`)}])}else{if(i.type!=="noul")throw new Error(`${e} did not return a bool answer for ${t}`);o.push([t,{type:"bool",probability:f(e,i.noul,`probability for ${t}`)}])}}return Object.fromEntries(o)}p(O,"parseAnswers");var T={"image/png":"png","image/jpeg":"jpeg"},A=new Set(["image/png","image/jpeg","image/webp"]),w=4;function R(e,r,a,o,t){if(a==="images"){if(o.length>w)throw new Error(`${e} accepts at most ${w} images for ${r.id}, got ${o.length}`);t.images=o.map(i=>{if(!A.has(i.mimeType))throw new Error(`${e} accepts PNG, JPEG, and WebP images for ${r.id}, got ${i.mimeType}`);return`data:${i.mimeType};base64,${i.data}`});return}if(a==="state-image-urls"){let i=o.map(n=>({type:"image_url",image_url:{url:`data:${n.mimeType};base64,${n.data}`}}));t.state=[...i,t.state];return}let s={};o.forEach((i,n)=>{let c=T[i.mimeType];if(!c)throw new Error(`${e} accepts PNG and JPEG images for ${r.id}, got ${i.mimeType}`);s[`<image-${n+1}>`]={type:"image",format:c,data_base64:i.data}}),t.assets=s,t.state=[...Object.keys(s),t.state]}p(R,"addImages");function j(e){return{state:e.state,questions:Object.fromEntries(Object.entries(e.questions).map(([r,a])=>[r,a.type==="bool"?{...a,type:"noul"}:a]))}}p(j,"wireRequest");async function P(e,r,a,o){let t={api:r.api,provider:r.provider,model:r.id,answers:{},stopReason:"stop",timestamp:Date.now()};try{if(r.api!==e.api)throw new Error(`Unsupported classifier API: ${r.api}`);let s=j(a),i=o;if(a.images?.length){if(!r.input.includes("image"))throw new Error(`${e.label} does not support image input for ${r.id}`);let m=e.detectCompat(r),g=r.compat?.imageInput??m.imageInput;R(e.label,r,g,a.images,s),(r.compat?.sendImageOptInHeader??m.sendImageOptInHeader)&&(i={...o,headers:{...l,...o?.headers}})}let n=await b(e.label,e.url(r),r,e.payload(r,s),i),c=e.output(n),d=y(c.usage,r);return d&&(t.usage=d),t.answers=O(e.label,c.answers,a),t}catch(s){return t.stopReason=o?.signal?.aborted?"aborted":"error",t.errorMessage=E(_(s),`${e.label} error`),t}}p(P,"classifySystemOne");export{P as classifySystemOne};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Oe=Object.defineProperty;var s=(e,t)=>Oe(e,"name",{value:t,configurable:!0});import{createRequire as Le}from"node:module";const fr=Le(import.meta.url);import{FileAuthStorageBackend as xe,JSON_RPC_ERROR_CODES as $e,LATEST_PROTOCOL_VERSION as T,McpAuthRequiredError as De,McpClient as He,McpError as Ne,McpHttpError as K,McpSessionExpiredError as Fe,StdioTransport as z,StreamableHttpTransport as Ve,isClientMetadataDocumentCallback as je,isObject as W,mcpNamespace as Be,require_proper_lockfile as qe,resolveConfigValueOrThrow as J,resolveHeadersOrThrow as Ke}from"./chunk-C5ELI234.js";import{sliceTail as Y}from"./chunk-HF334NQU.js";import{APP_NAME as Z,VERSION as We,getAgentDir as G}from"./chunk-R47JBGS3.js";import{__toESM as Je}from"./chunk-JXWJOIH4.js";import{homedir as Q}from"node:os";import{basename as Ye,join as Ze,resolve as Ge}from"node:path";import{setTimeout as Qe}from"node:timers/promises";import{pathToFileURL as Xe}from"node:url";import{createHash as et}from"node:crypto";var tt=class{static{s(this,"MemoryOAuthStateStore")}value;load(){return this.value===void 0?void 0:structuredClone(this.value)}save(e){this.value=structuredClone(e)}},rt=class{static{s(this,"McpOAuthProvider")}redirectUrl;clientMetadata;clientMetadataDocument;serverUrl;configuredClient;store;onRedirect;writes=Promise.resolve();constructor(e){this.serverUrl=String(new URL(e.serverUrl)),this.redirectUrl=String(e.redirectUrl),this.clientMetadata={...e.clientMetadata,redirect_uris:e.clientMetadata.redirect_uris??[this.redirectUrl],grant_types:e.clientMetadata.grant_types??["authorization_code","refresh_token"],response_types:e.clientMetadata.response_types??["code"],token_endpoint_auth_method:e.clientMetadata.token_endpoint_auth_method??(e.clientSecret?"client_secret_post":"none")},this.clientMetadataDocument=e.clientMetadataDocument,this.configuredClient=e.clientId?{client_id:e.clientId,...e.clientSecret?{client_secret:e.clientSecret}:{}}:void 0,this.store=e.store??new tt,this.onRedirect=e.onRedirect}async state(){let e=(await this.load()).oauthState;if(e)return e;let t=Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");return await this.update(r=>({...r,oauthState:t})),t}async clientInformation(){return this.configuredClient??(await this.load()).clientInformation}async saveClientInformation(e){this.configuredClient||await this.update(t=>({...t,clientInformation:e}))}async tokens(){return(await this.load()).tokens}async saveTokens(e){let t=e.expires_in===void 0?void 0:Date.now()+e.expires_in*1e3;await this.update(r=>{let i={...r,tokens:e};return t===void 0?delete i.tokensExpireAt:i.tokensExpireAt=t,i})}async redirectToAuthorization(e){await this.onRedirect(e)}async saveCodeVerifier(e){await this.update(t=>({...t,codeVerifier:e}))}async codeVerifier(){let e=(await this.load()).codeVerifier;if(!e)throw new Error("No OAuth PKCE code verifier is stored");return e}async invalidateCredentials(e){await this.update(t=>{let r={...t};return(e==="all"||e==="client")&&delete r.clientInformation,(e==="all"||e==="tokens")&&(delete r.tokens,delete r.tokensExpireAt),(e==="all"||e==="verifier")&&delete r.codeVerifier,(e==="all"||e==="discovery")&&delete r.discovery,e==="all"&&delete r.oauthState,r})}async saveDiscoveryState(e){await this.update(t=>({...t,discovery:e}))}async discoveryState(){return(await this.load()).discovery}async load(){return await this.writes,this.own(await this.store.load())}async update(e){this.writes=this.writes.then(async()=>{await this.store.save(e(this.own(await this.store.load())))}),await this.writes}own(e){return e?.serverUrl===this.serverUrl?e:{serverUrl:this.serverUrl}}};function P(e,t,r=()=>{}){let{serverUrl:i,settings:n,clientMetadataDocuments:a}=e;return new rt({serverUrl:i,redirectUrl:t,clientMetadata:{client_name:n.clientName??e.clientName},clientMetadataDocument:I(n,a,t)?o=>{if(!a?.listsRedirectUrl(t))throw new Error(`oauth.clientRegistration "cimd" needs Client ID Metadata Documents that list the redirect URI ${t}`);let c=it(i,t,o,a.baseUrl);if(!c&&n.clientRegistration==="cimd")throw new Error('The authorization server does not support Client ID Metadata Documents for public clients; remove oauth.clientRegistration "cimd"');return c}:void 0,clientId:n.clientId,clientSecret:n.clientSecret,store:e.store,onRedirect:r})}s(P,"createOAuthClientProvider");function I(e,t,r){let i=e.clientRegistration??"auto";return i!=="auto"?i==="cimd":!e.clientId&&!e.clientName&&t?.listsRedirectUrl(r)===!0}s(I,"offersClientMetadataDocument");function it(e,t,r,i){if(!r?.client_id_metadata_document_supported||!r.token_endpoint_auth_methods_supported?.includes("none"))return;if(r.authorization_response_iss_parameter_supported)return{url:`${i}/client.json`,redirectUrl:t};let n=new URL(t);return n.pathname=X(n.pathname,e),{url:`${i}/${ee(e)}/client.json`,redirectUrl:n.href}}s(it,"clientMetadataDocument");function X(e,t){return`${e.replace(/\/$/,"")}/${ee(t)}`}s(X,"serverSpecificPath");function ee(e){let t=new URL(e);return t.hash="",et("sha256").update(t.href).digest().subarray(0,9).toString("base64url")}s(ee,"callbackId");function O(e){return e&&"redirect_uris"in e?e.redirect_uris:[]}s(O,"registeredRedirectUrls");var nt=15e3;function te(e=globalThis.fetch){return(t,r)=>{let i=AbortSignal.timeout(nt);return e(t,{...r,signal:r?.signal?AbortSignal.any([r.signal,i]):i})}}s(te,"timedFetch");var re="127.0.0.1",at="/callback",ie=`http://${re}${at}`;function ne(e){let t=e.callbackUrl??ie,r=new URL(t),i=r.hostname.replace(/^\[|\]$/g,""),n=r.port?Number(r.port):e.callbackPort,a;return r.port?a=e.callbackUrl:n!==void 0&&(r.port=String(n),a=r.href),{url:t,host:i==="localhost"?re:i,redirectHost:i,port:n,path:r.pathname,fixedRedirectUrl:a}}s(ne,"loopbackSettings");var _=class extends Error{static{s(this,"OAuthError")}code;errorUri;constructor(e,t,r){super(t||e),this.name="OAuthError",this.code=e,this.errorUri=r}},ae=class extends Error{static{s(this,"OAuthIssuerMismatchError")}expected;received;constructor(e,t){let r=s(i=>i===void 0?"none":JSON.stringify(i),"format");super(`OAuth issuer mismatch: expected ${r(e)}, received ${r(t)}`),this.name="OAuthIssuerMismatchError",this.expected=e,this.received=t}},se=class extends Error{static{s(this,"OAuthInsecureEndpointError")}endpoint;constructor(e){super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${e}`),this.name="OAuthInsecureEndpointError",this.endpoint=e}},st=class extends Error{static{s(this,"OAuthRegistrationError")}status;body;constructor(e,t){super(`OAuth dynamic client registration failed with status ${e}: ${t}`),this.name="OAuthRegistrationError",this.status=e,this.body=t}},v=class extends Error{static{s(this,"McpOAuthAuthorizationRequiredError")}constructor(){super("MCP OAuth authorization requires user interaction"),this.name="McpOAuthAuthorizationRequiredError"}},oe=class extends Error{static{s(this,"McpRefreshLockBusyError")}constructor(){super("Another process is refreshing the MCP server's tokens"),this.name="McpRefreshLockBusyError"}};function U(e,t){if(!W(e))throw new Error(`Invalid ${t}`);return e}s(U,"object");function S(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}s(S,"compact");function y(e,t){if(typeof e!="string"||e.length===0)throw new Error(`Invalid ${t}`);return e}s(y,"requiredString");function L(e){return e==null||e===""}s(L,"absent");function k(e,t){if(!L(e))return y(e,t)}s(k,"optionalString");function p(e,t){if(e!=null){if(!Array.isArray(e)||e.some(r=>typeof r!="string"))throw new Error(`Invalid ${t}`);return[...e]}}s(p,"optionalStrings");function m(e,t){let r=y(e,t);if(!URL.canParse(r)||!ce(new URL(r)))throw new Error(`Invalid ${t}`);return r}s(m,"safeUrl");function ce(e){return e.protocol==="http:"||e.protocol==="https:"}s(ce,"isHttpUrl");function ot(e,t){return L(e)?void 0:m(e,t)}s(ot,"optionalUrl");function ct(e){let t=U(e,"OAuth protected resource metadata");return S({...t,resource:m(t.resource,"OAuth protected resource metadata resource"),authorization_servers:p(t.authorization_servers,"authorization_servers")?.map(r=>m(r,"authorization server URL")),scopes_supported:p(t.scopes_supported,"scopes_supported")})}s(ct,"parseProtectedResourceMetadata");function le(e){let t=U(e,"authorization server metadata"),r=p(t.response_types_supported,"response_types_supported");if(!r)throw new Error("Invalid response_types_supported");return S({...t,issuer:m(t.issuer,"authorization server issuer"),authorization_endpoint:m(t.authorization_endpoint,"authorization endpoint"),token_endpoint:m(t.token_endpoint,"token endpoint"),registration_endpoint:ot(t.registration_endpoint,"registration endpoint"),scopes_supported:p(t.scopes_supported,"scopes_supported"),response_types_supported:r,grant_types_supported:p(t.grant_types_supported,"grant_types_supported"),token_endpoint_auth_methods_supported:p(t.token_endpoint_auth_methods_supported,"token_endpoint_auth_methods_supported"),code_challenge_methods_supported:p(t.code_challenge_methods_supported,"code_challenge_methods_supported"),client_id_metadata_document_supported:typeof t.client_id_metadata_document_supported=="boolean"?t.client_id_metadata_document_supported:void 0,authorization_response_iss_parameter_supported:typeof t.authorization_response_iss_parameter_supported=="boolean"?t.authorization_response_iss_parameter_supported:void 0})}s(le,"parseAuthorizationServerMetadata");function lt(e){let t=U(e,"OAuth token response"),r=L(t.expires_in)?void 0:Number(t.expires_in);if(r!==void 0&&!Number.isFinite(r))throw new Error("Invalid expires_in");return S({access_token:y(t.access_token,"access_token"),token_type:y(t.token_type,"token_type"),expires_in:r,scope:k(t.scope,"scope"),refresh_token:k(t.refresh_token,"refresh_token"),id_token:k(t.id_token,"id_token")})}s(lt,"parseOAuthTokens");function ht(e){let t=U(e,"OAuth client registration response");return S({...t,client_id:y(t.client_id,"client_id"),client_secret:k(t.client_secret,"client_secret"),client_id_issued_at:typeof t.client_id_issued_at=="number"?t.client_id_issued_at:void 0,client_secret_expires_at:typeof t.client_secret_expires_at=="number"?t.client_secret_expires_at:void 0,redirect_uris:p(t.redirect_uris,"redirect_uris")??[]})}s(ht,"parseClientInformation");function R(e){e?.body?.cancel().catch(()=>{})}s(R,"discard");function he(e){return e>=400&&e<500||e===502}s(he,"isDiscoveryMiss");function de(e){return e.endsWith("/")?e.slice(0,-1):e}s(de,"pathSuffix");function E(e,t){let r=e.match(new RegExp(String.raw`(?:^|[,\s])${t}=(?:"([^"]*)"|([^\s,]+))`,"i"));return r?.[1]||r?.[2]||void 0}s(E,"field");function dt(e){if(!e)return{};let t=e.trimStart().split(/\s+/,1)[0]?.toLowerCase();if(t!=="bearer"&&t!=="dpop")return{};let r=E(e,"resource_metadata"),i;if(r)try{i=new URL(r)}catch{}return{resourceMetadataUrl:i,scope:E(e,"scope"),error:E(e,"error"),errorDescription:E(e,"error_description")}}s(dt,"parseWwwAuthenticate");async function M(e,t,r,i){return t(e,{headers:{Accept:"application/json","MCP-Protocol-Version":r},signal:i})}s(M,"fetchMetadata");async function ut(e,t={}){let r=new URL(e),i=t.fetch??globalThis.fetch,n=t.protocolVersion??T,a=await M(t.resourceMetadataUrl?new URL(t.resourceMetadataUrl):new URL(`/.well-known/oauth-protected-resource${de(r.pathname)}`,r.origin),i,n,t.signal);if(!t.resourceMetadataUrl&&r.pathname!=="/"&&he(a.status)&&(R(a),a=await M(new URL("/.well-known/oauth-protected-resource",r.origin),i,n,t.signal)),!a.ok)throw R(a),new Error(`HTTP ${a.status} loading OAuth protected resource metadata`);return ct(await a.json())}s(ut,"discoverProtectedResourceMetadata");function ft(e){let t=new URL(e),r=de(t.pathname),i=[{url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"}];return r&&i.push({url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}),i}s(ft,"buildAuthorizationServerDiscoveryUrls");async function ue(e,t={}){let r=t.fetch??globalThis.fetch;for(let{url:i}of ft(e)){let n=await M(i,r,t.protocolVersion??T,t.signal);if(!n.ok){if(R(n),he(n.status))continue;throw new Error(`HTTP ${n.status} loading authorization server metadata from ${i}`)}let a=le(await n.json());if(!t.skipIssuerValidation){let o=String(e),c=s(l=>l.endsWith("/")?l.slice(0,-1):l,"trim");if(c(a.issuer)!==c(o))throw new ae(o,a.issuer)}return a}}s(ue,"discoverAuthorizationServerMetadata");async function pt(e,t={}){let r;try{r=await ut(e,{resourceMetadataUrl:t.resourceMetadataUrl,fetch:t.fetch,signal:t.signal})}catch(n){if(n instanceof TypeError)throw n}if(t.authorizationServerMetadataUrl){let n=t.authorizationServerMetadataUrl,a=await M(n,t.fetch??globalThis.fetch,T,t.signal);if(!a.ok)throw R(a),new Error(`HTTP ${a.status} loading authorization server metadata from ${n}`);let o=le(await a.json());return{authorizationServerUrl:o.issuer,authorizationServerMetadata:o,resourceMetadata:r}}let i=r?.authorization_servers?.[0]??String(new URL("/",e));return{authorizationServerUrl:i,authorizationServerMetadata:await ue(i,{fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal}),resourceMetadata:r}}s(pt,"discoverOAuthServerInfo");function wt(e){let t=new URL(e);return t.hash="",t}s(wt,"resourceUrlFromServerUrl");function gt(e,t){if(!t)return;let r=wt(e),i=new URL(t.resource);if(r.origin!==i.origin)throw new Error(`Protected resource ${t.resource} does not match MCP server ${r}`);let n=r.pathname.endsWith("/")?r.pathname:`${r.pathname}/`,a=i.pathname.endsWith("/")?i.pathname:`${i.pathname}/`;if(!n.startsWith(a))throw new Error(`Protected resource ${t.resource} does not match MCP server ${r}`);return t.resource}s(gt,"selectResource");function fe(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}s(fe,"loopback");function mt(e){return e.some(t=>{if(!URL.canParse(t))return!1;let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"||fe(r.hostname)})?"native":"web"}s(mt,"applicationType");function pe(e){let t=new URL(e);if(t.protocol!=="https:"&&!fe(t.hostname))throw new se(t.href);return t}s(pe,"secureEndpoint");function _t(e,t){let r="token_endpoint_auth_method"in e?e.token_endpoint_auth_method:void 0;return r&&["client_secret_basic","client_secret_post","none"].includes(r)&&(t.length===0||t.includes(r))?r:t.length===0?e.client_secret?"client_secret_basic":"none":e.client_secret&&t.includes("client_secret_basic")?"client_secret_basic":e.client_secret&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":e.client_secret?"client_secret_post":"none"}s(_t,"selectClientAuthMethod");function vt(e,t,r,i){if(e==="client_secret_basic"){if(!t.client_secret)throw new Error("client_secret_basic requires a client secret");r.set("Authorization",`Basic ${Buffer.from(`${t.client_id}:${t.client_secret}`).toString("base64")}`)}else i.set("client_id",t.client_id),e==="client_secret_post"&&t.client_secret&&i.set("client_secret",t.client_secret)}s(vt,"applyClientAuthentication");async function yt(){let e=crypto.getRandomValues(new Uint8Array(32)),t=Buffer.from(e).toString("base64url"),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return{verifier:t,challenge:Buffer.from(r).toString("base64url")}}s(yt,"pkce");async function Ut(e,t){let r=t.metadata;if(r&&!r.response_types_supported.includes("code"))throw new Error("Authorization server does not support authorization codes");if(r?.code_challenge_methods_supported&&!r.code_challenge_methods_supported.includes("S256"))throw new Error("Authorization server does not support PKCE S256");let i=new URL(r?.authorization_endpoint??new URL("/authorize",e));if(!ce(i))throw new Error(`Invalid authorization endpoint ${i.href}`);let{verifier:n,challenge:a}=await yt();return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",t.clientInformation.client_id),i.searchParams.set("code_challenge",a),i.searchParams.set("code_challenge_method","S256"),i.searchParams.set("redirect_uri",String(t.redirectUrl)),t.state&&i.searchParams.set("state",t.state),t.scope&&i.searchParams.set("scope",t.scope),t.scope?.split(/\s+/).includes("offline_access")&&i.searchParams.set("prompt","consent"),t.resource&&i.searchParams.set("resource",t.resource),{authorizationUrl:i,codeVerifier:n}}s(Ut,"startAuthorization");async function we(e,t,r){let i=pe(t.metadata?.token_endpoint??new URL("/token",e)),n=new Headers({Accept:"application/json","content-type":"application/x-www-form-urlencoded"});t.resource&&r.set("resource",t.resource),t.addClientAuthentication?await t.addClientAuthentication(n,r,i,t.metadata):vt(_t(t.clientInformation,t.metadata?.token_endpoint_auth_methods_supported??[]),t.clientInformation,n,r);let a=await(t.fetch??globalThis.fetch)(i,{method:"POST",headers:n,body:r,signal:t.signal}),o=await a.text(),c;try{c=JSON.parse(o)}catch{}if(W(c)&&typeof c.error=="string")throw new _(c.error,typeof c.error_description=="string"?c.error_description:c.error,typeof c.error_uri=="string"?c.error_uri:void 0);if(!a.ok)throw new _("server_error",`HTTP ${a.status}: ${o}`);return lt(c)}s(we,"tokenRequest");async function St(e,t){let r=t.metadata?.registration_endpoint;if(t.metadata&&!r)throw new Error("Authorization server does not support dynamic client registration");let i=await(t.fetch??globalThis.fetch)(new URL(r??new URL("/register",e)),{method:"POST",headers:{Accept:"application/json","content-type":"application/json"},body:JSON.stringify({...t.clientMetadata,application_type:t.clientMetadata.application_type??mt(t.clientMetadata.redirect_uris),...t.scope?{scope:t.scope}:{}}),signal:t.signal});if(!i.ok)throw new st(i.status,await i.text());return ht(await i.json())}s(St,"registerClient");async function kt(e,t){return we(e,t,new URLSearchParams({grant_type:"authorization_code",code:t.code,code_verifier:t.codeVerifier,redirect_uri:String(t.redirectUrl)}))}s(kt,"exchangeAuthorizationCode");async function Rt(e,t){let r=await we(e,t,new URLSearchParams({grant_type:"refresh_token",refresh_token:t.refreshToken}));return{refresh_token:t.refreshToken,...r}}s(Rt,"refreshAuthorization");function ge(e,t){return e.scope===void 0&&t?{...e,scope:t}:e}s(ge,"withScope");function Et(e,t){if(!t)return;let r=[e,t].flatMap(i=>i?.split(/\s+/).filter(Boolean)??[]);return[...new Set(r)].join(" ")}s(Et,"stepUpScope");async function x(e,t,r={}){let i=t.authorizationServerMetadataUrl&&pe(t.authorizationServerMetadataUrl),n=i?void 0:await e.discoveryState?.(),a=n?.authorizationServerUrl?{authorizationServerUrl:n.authorizationServerUrl,authorizationServerMetadata:n.authorizationServerMetadata??await ue(n.authorizationServerUrl,{fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal}),resourceMetadata:n.resourceMetadata}:await pt(t.serverUrl,{resourceMetadataUrl:t.resourceMetadataUrl,authorizationServerMetadataUrl:i,fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal});i||await e.saveDiscoveryState?.({...a,...t.resourceMetadataUrl?{resourceMetadataUrl:t.resourceMetadataUrl.href}:{}});let o=a.authorizationServerMetadata,c=gt(t.serverUrl,a.resourceMetadata),l=t.scope||a.resourceMetadata?.scopes_supported?.join(" ")||e.clientMetadata.scope,h=await e.clientInformation();r.storedClientId=h?.client_id;let d=h?void 0:e.clientMetadataDocument?.(o);if(d){let u=new URL(d.url);if(u.protocol!=="https:"||u.pathname==="/")throw new Error("Invalid OAuth client metadata URL")}let f=d?.redirectUrl??String(e.redirectUrl);if(t.authorizationCode&&t.authorizationRedirectUrl!==void 0&&f!==t.authorizationRedirectUrl)throw new Error(`The code exchange would use the redirect URI ${f}, but the authorization request used ${t.authorizationRedirectUrl}`);let w=h??(d&&{client_id:d.url});if(!w){if(t.refreshOnly)return"REDIRECT";if(t.authorizationCode)throw new Error("OAuth client information is missing during code exchange: the authorization request's client was removed, or the client settings changed");if(!e.saveClientInformation)throw new Error("OAuth client information cannot be persisted");w=await St(a.authorizationServerUrl,{metadata:o,clientMetadata:e.clientMetadata,scope:l,fetch:t.fetch,signal:t.signal}),await e.saveClientInformation(w)}let B={metadata:o,clientInformation:w,resource:c,addClientAuthentication:e.addClientAuthentication,fetch:t.fetch,signal:t.signal};if(t.authorizationCode){let u=t.iss;if((u!==void 0||o?.authorization_response_iss_parameter_supported)&&u!==o?.issuer)throw new ae(o?.issuer,u);let Ie=await kt(a.authorizationServerUrl,{...B,code:t.authorizationCode,codeVerifier:await e.codeVerifier(),redirectUrl:f});return await e.saveTokens(ge(Ie,l)),"AUTHORIZED"}let b=t.skipRefresh?void 0:await e.tokens();if(b?.refresh_token)try{let u=await Rt(a.authorizationServerUrl,{...B,refreshToken:b.refresh_token});return await e.saveTokens(ge(u,b.scope)),"AUTHORIZED"}catch(u){if(t.signal?.aborted||u instanceof se||u instanceof _&&u.code!=="server_error")throw u}if(t.refreshOnly)return"REDIRECT";let Pe=await e.state?.(),q=await Ut(a.authorizationServerUrl,{metadata:o,clientInformation:w,redirectUrl:f,scope:l,state:Pe,resource:c});return await e.saveCodeVerifier(q.codeVerifier),await e.redirectToAuthorization(q.authorizationUrl),"REDIRECT"}s(x,"runFlow");async function $(e,t){let r={};try{return await x(e,t,r)}catch(i){if(i instanceof _&&["invalid_client","unauthorized_client"].includes(i.code)){if(t.refreshOnly){if((await e.clientInformation())?.client_id===r.storedClientId)for(let n of["client","tokens","discovery"])await e.invalidateCredentials?.(n)}else await e.invalidateCredentials?.("all");return x(e,t)}if(i instanceof _&&i.code==="invalid_grant")return await e.invalidateCredentials?.("tokens"),x(e,t);throw i}}s($,"authorizeMcp");var Mt=3e4;function At(e){let{store:t,redirectUrl:r}=e,i,n=s((a,o=globalThis.fetch,c)=>(i??=t.withRefreshLock(async()=>{let l=await t.load();if(l?.tokens?.access_token!==a)return;if(!l?.tokens?.refresh_token)throw new v;let h={...e,settings:e.settings()};if(await me(h,l,{fetch:o,challenge:c,redirectUrl:r})==="REDIRECT")throw new v}).finally(()=>{i=void 0}),i),"refresh");return{token:s(async()=>{await i?.catch(()=>{});let a=await t.load(),o=a?.tokens?.access_token;return!(a?.tokensExpireAt!==void 0&&a.tokensExpireAt-Mt<=Date.now())||!a?.tokens?.refresh_token?o:(await n(o).catch(()=>{}),(await t.load())?.tokens?.access_token)},"token"),onUnauthorized:s(async a=>{let o=dt(a.response.headers.get("www-authenticate"));if(e.onChallenge(o),o.error==="insufficient_scope")throw new v;await n(a.token,a.fetch,o)},"onUnauthorized"),settled:s(async()=>{await i?.catch(()=>{})},"settled")}}s(At,"createMcpAuthProvider");async function me(e,t,r={}){let i=[r.redirectUrl,ne(e.settings).fixedRedirectUrl,O(t.clientInformation)[0]].filter(n=>n!==void 0).find(n=>e.clientMetadataDocuments?.listsRedirectUrl(n))??ie;return $(P(e,i),{serverUrl:e.serverUrl,resourceMetadataUrl:r.challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:e.settings.authServerMetadataUrl,fetch:te(r.fetch),refreshOnly:!0})}s(me,"refreshStoredTokens");import{createServer as Ct}from"node:http";function bt(e){return e.ok?"Authorization complete. You may close this window.":e.details?`${e.message}
|
|
1
|
+
var Oe=Object.defineProperty;var s=(e,t)=>Oe(e,"name",{value:t,configurable:!0});import{createRequire as Le}from"node:module";const fr=Le(import.meta.url);import{FileAuthStorageBackend as xe,JSON_RPC_ERROR_CODES as $e,LATEST_PROTOCOL_VERSION as T,McpAuthRequiredError as De,McpClient as He,McpError as Ne,McpHttpError as K,McpSessionExpiredError as Fe,StdioTransport as z,StreamableHttpTransport as Ve,isClientMetadataDocumentCallback as je,isObject as W,mcpNamespace as Be,require_proper_lockfile as qe,resolveConfigValueOrThrow as J,resolveHeadersOrThrow as Ke}from"./chunk-H3KG4L7I.js";import{sliceTail as Y}from"./chunk-B66W54NL.js";import{APP_NAME as Z,VERSION as We,getAgentDir as G}from"./chunk-QM5JU2GS.js";import{__toESM as Je}from"./chunk-JXWJOIH4.js";import{homedir as Q}from"node:os";import{basename as Ye,join as Ze,resolve as Ge}from"node:path";import{setTimeout as Qe}from"node:timers/promises";import{pathToFileURL as Xe}from"node:url";import{createHash as et}from"node:crypto";var tt=class{static{s(this,"MemoryOAuthStateStore")}value;load(){return this.value===void 0?void 0:structuredClone(this.value)}save(e){this.value=structuredClone(e)}},rt=class{static{s(this,"McpOAuthProvider")}redirectUrl;clientMetadata;clientMetadataDocument;serverUrl;configuredClient;store;onRedirect;writes=Promise.resolve();constructor(e){this.serverUrl=String(new URL(e.serverUrl)),this.redirectUrl=String(e.redirectUrl),this.clientMetadata={...e.clientMetadata,redirect_uris:e.clientMetadata.redirect_uris??[this.redirectUrl],grant_types:e.clientMetadata.grant_types??["authorization_code","refresh_token"],response_types:e.clientMetadata.response_types??["code"],token_endpoint_auth_method:e.clientMetadata.token_endpoint_auth_method??(e.clientSecret?"client_secret_post":"none")},this.clientMetadataDocument=e.clientMetadataDocument,this.configuredClient=e.clientId?{client_id:e.clientId,...e.clientSecret?{client_secret:e.clientSecret}:{}}:void 0,this.store=e.store??new tt,this.onRedirect=e.onRedirect}async state(){let e=(await this.load()).oauthState;if(e)return e;let t=Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");return await this.update(r=>({...r,oauthState:t})),t}async clientInformation(){return this.configuredClient??(await this.load()).clientInformation}async saveClientInformation(e){this.configuredClient||await this.update(t=>({...t,clientInformation:e}))}async tokens(){return(await this.load()).tokens}async saveTokens(e){let t=e.expires_in===void 0?void 0:Date.now()+e.expires_in*1e3;await this.update(r=>{let i={...r,tokens:e};return t===void 0?delete i.tokensExpireAt:i.tokensExpireAt=t,i})}async redirectToAuthorization(e){await this.onRedirect(e)}async saveCodeVerifier(e){await this.update(t=>({...t,codeVerifier:e}))}async codeVerifier(){let e=(await this.load()).codeVerifier;if(!e)throw new Error("No OAuth PKCE code verifier is stored");return e}async invalidateCredentials(e){await this.update(t=>{let r={...t};return(e==="all"||e==="client")&&delete r.clientInformation,(e==="all"||e==="tokens")&&(delete r.tokens,delete r.tokensExpireAt),(e==="all"||e==="verifier")&&delete r.codeVerifier,(e==="all"||e==="discovery")&&delete r.discovery,e==="all"&&delete r.oauthState,r})}async saveDiscoveryState(e){await this.update(t=>({...t,discovery:e}))}async discoveryState(){return(await this.load()).discovery}async load(){return await this.writes,this.own(await this.store.load())}async update(e){this.writes=this.writes.then(async()=>{await this.store.save(e(this.own(await this.store.load())))}),await this.writes}own(e){return e?.serverUrl===this.serverUrl?e:{serverUrl:this.serverUrl}}};function P(e,t,r=()=>{}){let{serverUrl:i,settings:n,clientMetadataDocuments:a}=e;return new rt({serverUrl:i,redirectUrl:t,clientMetadata:{client_name:n.clientName??e.clientName},clientMetadataDocument:I(n,a,t)?o=>{if(!a?.listsRedirectUrl(t))throw new Error(`oauth.clientRegistration "cimd" needs Client ID Metadata Documents that list the redirect URI ${t}`);let c=it(i,t,o,a.baseUrl);if(!c&&n.clientRegistration==="cimd")throw new Error('The authorization server does not support Client ID Metadata Documents for public clients; remove oauth.clientRegistration "cimd"');return c}:void 0,clientId:n.clientId,clientSecret:n.clientSecret,store:e.store,onRedirect:r})}s(P,"createOAuthClientProvider");function I(e,t,r){let i=e.clientRegistration??"auto";return i!=="auto"?i==="cimd":!e.clientId&&!e.clientName&&t?.listsRedirectUrl(r)===!0}s(I,"offersClientMetadataDocument");function it(e,t,r,i){if(!r?.client_id_metadata_document_supported||!r.token_endpoint_auth_methods_supported?.includes("none"))return;if(r.authorization_response_iss_parameter_supported)return{url:`${i}/client.json`,redirectUrl:t};let n=new URL(t);return n.pathname=X(n.pathname,e),{url:`${i}/${ee(e)}/client.json`,redirectUrl:n.href}}s(it,"clientMetadataDocument");function X(e,t){return`${e.replace(/\/$/,"")}/${ee(t)}`}s(X,"serverSpecificPath");function ee(e){let t=new URL(e);return t.hash="",et("sha256").update(t.href).digest().subarray(0,9).toString("base64url")}s(ee,"callbackId");function O(e){return e&&"redirect_uris"in e?e.redirect_uris:[]}s(O,"registeredRedirectUrls");var nt=15e3;function te(e=globalThis.fetch){return(t,r)=>{let i=AbortSignal.timeout(nt);return e(t,{...r,signal:r?.signal?AbortSignal.any([r.signal,i]):i})}}s(te,"timedFetch");var re="127.0.0.1",at="/callback",ie=`http://${re}${at}`;function ne(e){let t=e.callbackUrl??ie,r=new URL(t),i=r.hostname.replace(/^\[|\]$/g,""),n=r.port?Number(r.port):e.callbackPort,a;return r.port?a=e.callbackUrl:n!==void 0&&(r.port=String(n),a=r.href),{url:t,host:i==="localhost"?re:i,redirectHost:i,port:n,path:r.pathname,fixedRedirectUrl:a}}s(ne,"loopbackSettings");var _=class extends Error{static{s(this,"OAuthError")}code;errorUri;constructor(e,t,r){super(t||e),this.name="OAuthError",this.code=e,this.errorUri=r}},ae=class extends Error{static{s(this,"OAuthIssuerMismatchError")}expected;received;constructor(e,t){let r=s(i=>i===void 0?"none":JSON.stringify(i),"format");super(`OAuth issuer mismatch: expected ${r(e)}, received ${r(t)}`),this.name="OAuthIssuerMismatchError",this.expected=e,this.received=t}},se=class extends Error{static{s(this,"OAuthInsecureEndpointError")}endpoint;constructor(e){super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${e}`),this.name="OAuthInsecureEndpointError",this.endpoint=e}},st=class extends Error{static{s(this,"OAuthRegistrationError")}status;body;constructor(e,t){super(`OAuth dynamic client registration failed with status ${e}: ${t}`),this.name="OAuthRegistrationError",this.status=e,this.body=t}},v=class extends Error{static{s(this,"McpOAuthAuthorizationRequiredError")}constructor(){super("MCP OAuth authorization requires user interaction"),this.name="McpOAuthAuthorizationRequiredError"}},oe=class extends Error{static{s(this,"McpRefreshLockBusyError")}constructor(){super("Another process is refreshing the MCP server's tokens"),this.name="McpRefreshLockBusyError"}};function U(e,t){if(!W(e))throw new Error(`Invalid ${t}`);return e}s(U,"object");function S(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}s(S,"compact");function y(e,t){if(typeof e!="string"||e.length===0)throw new Error(`Invalid ${t}`);return e}s(y,"requiredString");function L(e){return e==null||e===""}s(L,"absent");function k(e,t){if(!L(e))return y(e,t)}s(k,"optionalString");function p(e,t){if(e!=null){if(!Array.isArray(e)||e.some(r=>typeof r!="string"))throw new Error(`Invalid ${t}`);return[...e]}}s(p,"optionalStrings");function m(e,t){let r=y(e,t);if(!URL.canParse(r)||!ce(new URL(r)))throw new Error(`Invalid ${t}`);return r}s(m,"safeUrl");function ce(e){return e.protocol==="http:"||e.protocol==="https:"}s(ce,"isHttpUrl");function ot(e,t){return L(e)?void 0:m(e,t)}s(ot,"optionalUrl");function ct(e){let t=U(e,"OAuth protected resource metadata");return S({...t,resource:m(t.resource,"OAuth protected resource metadata resource"),authorization_servers:p(t.authorization_servers,"authorization_servers")?.map(r=>m(r,"authorization server URL")),scopes_supported:p(t.scopes_supported,"scopes_supported")})}s(ct,"parseProtectedResourceMetadata");function le(e){let t=U(e,"authorization server metadata"),r=p(t.response_types_supported,"response_types_supported");if(!r)throw new Error("Invalid response_types_supported");return S({...t,issuer:m(t.issuer,"authorization server issuer"),authorization_endpoint:m(t.authorization_endpoint,"authorization endpoint"),token_endpoint:m(t.token_endpoint,"token endpoint"),registration_endpoint:ot(t.registration_endpoint,"registration endpoint"),scopes_supported:p(t.scopes_supported,"scopes_supported"),response_types_supported:r,grant_types_supported:p(t.grant_types_supported,"grant_types_supported"),token_endpoint_auth_methods_supported:p(t.token_endpoint_auth_methods_supported,"token_endpoint_auth_methods_supported"),code_challenge_methods_supported:p(t.code_challenge_methods_supported,"code_challenge_methods_supported"),client_id_metadata_document_supported:typeof t.client_id_metadata_document_supported=="boolean"?t.client_id_metadata_document_supported:void 0,authorization_response_iss_parameter_supported:typeof t.authorization_response_iss_parameter_supported=="boolean"?t.authorization_response_iss_parameter_supported:void 0})}s(le,"parseAuthorizationServerMetadata");function lt(e){let t=U(e,"OAuth token response"),r=L(t.expires_in)?void 0:Number(t.expires_in);if(r!==void 0&&!Number.isFinite(r))throw new Error("Invalid expires_in");return S({access_token:y(t.access_token,"access_token"),token_type:y(t.token_type,"token_type"),expires_in:r,scope:k(t.scope,"scope"),refresh_token:k(t.refresh_token,"refresh_token"),id_token:k(t.id_token,"id_token")})}s(lt,"parseOAuthTokens");function ht(e){let t=U(e,"OAuth client registration response");return S({...t,client_id:y(t.client_id,"client_id"),client_secret:k(t.client_secret,"client_secret"),client_id_issued_at:typeof t.client_id_issued_at=="number"?t.client_id_issued_at:void 0,client_secret_expires_at:typeof t.client_secret_expires_at=="number"?t.client_secret_expires_at:void 0,redirect_uris:p(t.redirect_uris,"redirect_uris")??[]})}s(ht,"parseClientInformation");function R(e){e?.body?.cancel().catch(()=>{})}s(R,"discard");function he(e){return e>=400&&e<500||e===502}s(he,"isDiscoveryMiss");function de(e){return e.endsWith("/")?e.slice(0,-1):e}s(de,"pathSuffix");function E(e,t){let r=e.match(new RegExp(String.raw`(?:^|[,\s])${t}=(?:"([^"]*)"|([^\s,]+))`,"i"));return r?.[1]||r?.[2]||void 0}s(E,"field");function dt(e){if(!e)return{};let t=e.trimStart().split(/\s+/,1)[0]?.toLowerCase();if(t!=="bearer"&&t!=="dpop")return{};let r=E(e,"resource_metadata"),i;if(r)try{i=new URL(r)}catch{}return{resourceMetadataUrl:i,scope:E(e,"scope"),error:E(e,"error"),errorDescription:E(e,"error_description")}}s(dt,"parseWwwAuthenticate");async function M(e,t,r,i){return t(e,{headers:{Accept:"application/json","MCP-Protocol-Version":r},signal:i})}s(M,"fetchMetadata");async function ut(e,t={}){let r=new URL(e),i=t.fetch??globalThis.fetch,n=t.protocolVersion??T,a=await M(t.resourceMetadataUrl?new URL(t.resourceMetadataUrl):new URL(`/.well-known/oauth-protected-resource${de(r.pathname)}`,r.origin),i,n,t.signal);if(!t.resourceMetadataUrl&&r.pathname!=="/"&&he(a.status)&&(R(a),a=await M(new URL("/.well-known/oauth-protected-resource",r.origin),i,n,t.signal)),!a.ok)throw R(a),new Error(`HTTP ${a.status} loading OAuth protected resource metadata`);return ct(await a.json())}s(ut,"discoverProtectedResourceMetadata");function ft(e){let t=new URL(e),r=de(t.pathname),i=[{url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"}];return r&&i.push({url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}),i}s(ft,"buildAuthorizationServerDiscoveryUrls");async function ue(e,t={}){let r=t.fetch??globalThis.fetch;for(let{url:i}of ft(e)){let n=await M(i,r,t.protocolVersion??T,t.signal);if(!n.ok){if(R(n),he(n.status))continue;throw new Error(`HTTP ${n.status} loading authorization server metadata from ${i}`)}let a=le(await n.json());if(!t.skipIssuerValidation){let o=String(e),c=s(l=>l.endsWith("/")?l.slice(0,-1):l,"trim");if(c(a.issuer)!==c(o))throw new ae(o,a.issuer)}return a}}s(ue,"discoverAuthorizationServerMetadata");async function pt(e,t={}){let r;try{r=await ut(e,{resourceMetadataUrl:t.resourceMetadataUrl,fetch:t.fetch,signal:t.signal})}catch(n){if(n instanceof TypeError)throw n}if(t.authorizationServerMetadataUrl){let n=t.authorizationServerMetadataUrl,a=await M(n,t.fetch??globalThis.fetch,T,t.signal);if(!a.ok)throw R(a),new Error(`HTTP ${a.status} loading authorization server metadata from ${n}`);let o=le(await a.json());return{authorizationServerUrl:o.issuer,authorizationServerMetadata:o,resourceMetadata:r}}let i=r?.authorization_servers?.[0]??String(new URL("/",e));return{authorizationServerUrl:i,authorizationServerMetadata:await ue(i,{fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal}),resourceMetadata:r}}s(pt,"discoverOAuthServerInfo");function wt(e){let t=new URL(e);return t.hash="",t}s(wt,"resourceUrlFromServerUrl");function gt(e,t){if(!t)return;let r=wt(e),i=new URL(t.resource);if(r.origin!==i.origin)throw new Error(`Protected resource ${t.resource} does not match MCP server ${r}`);let n=r.pathname.endsWith("/")?r.pathname:`${r.pathname}/`,a=i.pathname.endsWith("/")?i.pathname:`${i.pathname}/`;if(!n.startsWith(a))throw new Error(`Protected resource ${t.resource} does not match MCP server ${r}`);return t.resource}s(gt,"selectResource");function fe(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}s(fe,"loopback");function mt(e){return e.some(t=>{if(!URL.canParse(t))return!1;let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"||fe(r.hostname)})?"native":"web"}s(mt,"applicationType");function pe(e){let t=new URL(e);if(t.protocol!=="https:"&&!fe(t.hostname))throw new se(t.href);return t}s(pe,"secureEndpoint");function _t(e,t){let r="token_endpoint_auth_method"in e?e.token_endpoint_auth_method:void 0;return r&&["client_secret_basic","client_secret_post","none"].includes(r)&&(t.length===0||t.includes(r))?r:t.length===0?e.client_secret?"client_secret_basic":"none":e.client_secret&&t.includes("client_secret_basic")?"client_secret_basic":e.client_secret&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":e.client_secret?"client_secret_post":"none"}s(_t,"selectClientAuthMethod");function vt(e,t,r,i){if(e==="client_secret_basic"){if(!t.client_secret)throw new Error("client_secret_basic requires a client secret");r.set("Authorization",`Basic ${Buffer.from(`${t.client_id}:${t.client_secret}`).toString("base64")}`)}else i.set("client_id",t.client_id),e==="client_secret_post"&&t.client_secret&&i.set("client_secret",t.client_secret)}s(vt,"applyClientAuthentication");async function yt(){let e=crypto.getRandomValues(new Uint8Array(32)),t=Buffer.from(e).toString("base64url"),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return{verifier:t,challenge:Buffer.from(r).toString("base64url")}}s(yt,"pkce");async function Ut(e,t){let r=t.metadata;if(r&&!r.response_types_supported.includes("code"))throw new Error("Authorization server does not support authorization codes");if(r?.code_challenge_methods_supported&&!r.code_challenge_methods_supported.includes("S256"))throw new Error("Authorization server does not support PKCE S256");let i=new URL(r?.authorization_endpoint??new URL("/authorize",e));if(!ce(i))throw new Error(`Invalid authorization endpoint ${i.href}`);let{verifier:n,challenge:a}=await yt();return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",t.clientInformation.client_id),i.searchParams.set("code_challenge",a),i.searchParams.set("code_challenge_method","S256"),i.searchParams.set("redirect_uri",String(t.redirectUrl)),t.state&&i.searchParams.set("state",t.state),t.scope&&i.searchParams.set("scope",t.scope),t.scope?.split(/\s+/).includes("offline_access")&&i.searchParams.set("prompt","consent"),t.resource&&i.searchParams.set("resource",t.resource),{authorizationUrl:i,codeVerifier:n}}s(Ut,"startAuthorization");async function we(e,t,r){let i=pe(t.metadata?.token_endpoint??new URL("/token",e)),n=new Headers({Accept:"application/json","content-type":"application/x-www-form-urlencoded"});t.resource&&r.set("resource",t.resource),t.addClientAuthentication?await t.addClientAuthentication(n,r,i,t.metadata):vt(_t(t.clientInformation,t.metadata?.token_endpoint_auth_methods_supported??[]),t.clientInformation,n,r);let a=await(t.fetch??globalThis.fetch)(i,{method:"POST",headers:n,body:r,signal:t.signal}),o=await a.text(),c;try{c=JSON.parse(o)}catch{}if(W(c)&&typeof c.error=="string")throw new _(c.error,typeof c.error_description=="string"?c.error_description:c.error,typeof c.error_uri=="string"?c.error_uri:void 0);if(!a.ok)throw new _("server_error",`HTTP ${a.status}: ${o}`);return lt(c)}s(we,"tokenRequest");async function St(e,t){let r=t.metadata?.registration_endpoint;if(t.metadata&&!r)throw new Error("Authorization server does not support dynamic client registration");let i=await(t.fetch??globalThis.fetch)(new URL(r??new URL("/register",e)),{method:"POST",headers:{Accept:"application/json","content-type":"application/json"},body:JSON.stringify({...t.clientMetadata,application_type:t.clientMetadata.application_type??mt(t.clientMetadata.redirect_uris),...t.scope?{scope:t.scope}:{}}),signal:t.signal});if(!i.ok)throw new st(i.status,await i.text());return ht(await i.json())}s(St,"registerClient");async function kt(e,t){return we(e,t,new URLSearchParams({grant_type:"authorization_code",code:t.code,code_verifier:t.codeVerifier,redirect_uri:String(t.redirectUrl)}))}s(kt,"exchangeAuthorizationCode");async function Rt(e,t){let r=await we(e,t,new URLSearchParams({grant_type:"refresh_token",refresh_token:t.refreshToken}));return{refresh_token:t.refreshToken,...r}}s(Rt,"refreshAuthorization");function ge(e,t){return e.scope===void 0&&t?{...e,scope:t}:e}s(ge,"withScope");function Et(e,t){if(!t)return;let r=[e,t].flatMap(i=>i?.split(/\s+/).filter(Boolean)??[]);return[...new Set(r)].join(" ")}s(Et,"stepUpScope");async function x(e,t,r={}){let i=t.authorizationServerMetadataUrl&&pe(t.authorizationServerMetadataUrl),n=i?void 0:await e.discoveryState?.(),a=n?.authorizationServerUrl?{authorizationServerUrl:n.authorizationServerUrl,authorizationServerMetadata:n.authorizationServerMetadata??await ue(n.authorizationServerUrl,{fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal}),resourceMetadata:n.resourceMetadata}:await pt(t.serverUrl,{resourceMetadataUrl:t.resourceMetadataUrl,authorizationServerMetadataUrl:i,fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal});i||await e.saveDiscoveryState?.({...a,...t.resourceMetadataUrl?{resourceMetadataUrl:t.resourceMetadataUrl.href}:{}});let o=a.authorizationServerMetadata,c=gt(t.serverUrl,a.resourceMetadata),l=t.scope||a.resourceMetadata?.scopes_supported?.join(" ")||e.clientMetadata.scope,h=await e.clientInformation();r.storedClientId=h?.client_id;let d=h?void 0:e.clientMetadataDocument?.(o);if(d){let u=new URL(d.url);if(u.protocol!=="https:"||u.pathname==="/")throw new Error("Invalid OAuth client metadata URL")}let f=d?.redirectUrl??String(e.redirectUrl);if(t.authorizationCode&&t.authorizationRedirectUrl!==void 0&&f!==t.authorizationRedirectUrl)throw new Error(`The code exchange would use the redirect URI ${f}, but the authorization request used ${t.authorizationRedirectUrl}`);let w=h??(d&&{client_id:d.url});if(!w){if(t.refreshOnly)return"REDIRECT";if(t.authorizationCode)throw new Error("OAuth client information is missing during code exchange: the authorization request's client was removed, or the client settings changed");if(!e.saveClientInformation)throw new Error("OAuth client information cannot be persisted");w=await St(a.authorizationServerUrl,{metadata:o,clientMetadata:e.clientMetadata,scope:l,fetch:t.fetch,signal:t.signal}),await e.saveClientInformation(w)}let B={metadata:o,clientInformation:w,resource:c,addClientAuthentication:e.addClientAuthentication,fetch:t.fetch,signal:t.signal};if(t.authorizationCode){let u=t.iss;if((u!==void 0||o?.authorization_response_iss_parameter_supported)&&u!==o?.issuer)throw new ae(o?.issuer,u);let Ie=await kt(a.authorizationServerUrl,{...B,code:t.authorizationCode,codeVerifier:await e.codeVerifier(),redirectUrl:f});return await e.saveTokens(ge(Ie,l)),"AUTHORIZED"}let b=t.skipRefresh?void 0:await e.tokens();if(b?.refresh_token)try{let u=await Rt(a.authorizationServerUrl,{...B,refreshToken:b.refresh_token});return await e.saveTokens(ge(u,b.scope)),"AUTHORIZED"}catch(u){if(t.signal?.aborted||u instanceof se||u instanceof _&&u.code!=="server_error")throw u}if(t.refreshOnly)return"REDIRECT";let Pe=await e.state?.(),q=await Ut(a.authorizationServerUrl,{metadata:o,clientInformation:w,redirectUrl:f,scope:l,state:Pe,resource:c});return await e.saveCodeVerifier(q.codeVerifier),await e.redirectToAuthorization(q.authorizationUrl),"REDIRECT"}s(x,"runFlow");async function $(e,t){let r={};try{return await x(e,t,r)}catch(i){if(i instanceof _&&["invalid_client","unauthorized_client"].includes(i.code)){if(t.refreshOnly){if((await e.clientInformation())?.client_id===r.storedClientId)for(let n of["client","tokens","discovery"])await e.invalidateCredentials?.(n)}else await e.invalidateCredentials?.("all");return x(e,t)}if(i instanceof _&&i.code==="invalid_grant")return await e.invalidateCredentials?.("tokens"),x(e,t);throw i}}s($,"authorizeMcp");var Mt=3e4;function At(e){let{store:t,redirectUrl:r}=e,i,n=s((a,o=globalThis.fetch,c)=>(i??=t.withRefreshLock(async()=>{let l=await t.load();if(l?.tokens?.access_token!==a)return;if(!l?.tokens?.refresh_token)throw new v;let h={...e,settings:e.settings()};if(await me(h,l,{fetch:o,challenge:c,redirectUrl:r})==="REDIRECT")throw new v}).finally(()=>{i=void 0}),i),"refresh");return{token:s(async()=>{await i?.catch(()=>{});let a=await t.load(),o=a?.tokens?.access_token;return!(a?.tokensExpireAt!==void 0&&a.tokensExpireAt-Mt<=Date.now())||!a?.tokens?.refresh_token?o:(await n(o).catch(()=>{}),(await t.load())?.tokens?.access_token)},"token"),onUnauthorized:s(async a=>{let o=dt(a.response.headers.get("www-authenticate"));if(e.onChallenge(o),o.error==="insufficient_scope")throw new v;await n(a.token,a.fetch,o)},"onUnauthorized"),settled:s(async()=>{await i?.catch(()=>{})},"settled")}}s(At,"createMcpAuthProvider");async function me(e,t,r={}){let i=[r.redirectUrl,ne(e.settings).fixedRedirectUrl,O(t.clientInformation)[0]].filter(n=>n!==void 0).find(n=>e.clientMetadataDocuments?.listsRedirectUrl(n))??ie;return $(P(e,i),{serverUrl:e.serverUrl,resourceMetadataUrl:r.challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:e.settings.authServerMetadataUrl,fetch:te(r.fetch),refreshOnly:!0})}s(me,"refreshStoredTokens");import{createServer as Ct}from"node:http";function bt(e){return e.ok?"Authorization complete. You may close this window.":e.details?`${e.message}
|
|
2
2
|
|
|
3
3
|
${e.details}`:e.message}s(bt,"plainText");var _e=class ze{static{s(this,"_OAuthCallbackServer")}redirectUrl;server;paths;timeoutMs;renderPage;pending=new Map;constructor(t,r,i,n,a){this.server=t,this.redirectUrl=r,this.paths=i,this.timeoutMs=n,this.renderPage=a}static async listen(t={}){let r=t.host??"127.0.0.1",i=t.redirectHost??r,n=t.path??"/callback",a,o=Ct((l,h)=>a?.handle(l.url??"/",h));await new Promise((l,h)=>{o.once("error",h),o.listen(t.port??0,r,()=>{o.off("error",h),l()})});let c=o.address();if(!c||typeof c=="string")throw new Error("OAuth callback server did not bind to TCP");return a=new ze(o,`http://${i.includes(":")?`[${i}]`:i}:${c.port}${n}`,[n,...t.extraPaths??[]],t.timeoutMs??5*6e4,t.renderPage),a}waitForCallback(t,r){if(this.pending.has(t))throw new Error("OAuth state is already pending");return new Promise((i,n)=>{let a=setTimeout(()=>{this.pending.delete(t),n(new Error("OAuth callback timed out"))},this.timeoutMs);this.pending.set(t,{resolve:i,reject:n,timer:a,path:r})})}async close(){for(let r of this.pending.values())clearTimeout(r.timer),r.reject(new Error("OAuth callback server closed"));this.pending.clear();let t=new Promise((r,i)=>{this.server.close(n=>n?i(n):r())});this.server.closeAllConnections(),await t}reply(t,r,i){this.renderPage?(t.writeHead(r,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),t.end(this.renderPage(i))):t.writeHead(r,{"content-type":"text/plain; charset=utf-8"}).end(bt(i))}handle(t,r){let i=new URL(t,this.redirectUrl);if(!this.paths.includes(i.pathname)){this.reply(r,404,{ok:!1,message:"Not found"});return}let n=i.searchParams.get("state"),a=n?this.pending.get(n):void 0;if(!n||!a){this.reply(r,400,{ok:!1,message:"Invalid or expired OAuth state"});return}if(clearTimeout(a.timer),this.pending.delete(n),a.path!==void 0&&i.pathname!==a.path){a.reject(new Error("The authorization response arrived on another redirect URI")),this.reply(r,400,{ok:!1,message:"Unexpected redirect URI"});return}let o=i.searchParams.get("error");if(o){let h=i.searchParams.get("error_description")??o;a.reject(new Error(h)),this.reply(r,200,{ok:!1,message:"Authorization failed. You may close this window.",details:h});return}let c=i.searchParams.get("code");if(!c){a.reject(new Error("OAuth callback did not include an authorization code")),this.reply(r,400,{ok:!1,message:"Missing authorization code"});return}let l=i.searchParams.get("iss");a.resolve({code:c,state:n,...l?{iss:l}:{}}),this.reply(r,200,{ok:!0})}},g=class extends Error{static{s(this,"McpSignInCancelledError")}constructor(){super("Sign-in cancelled"),this.name="McpSignInCancelledError"}};async function Tt(e){if(e.signal?.aborted)throw new g;let t=e.challenge?.error==="insufficient_scope";return!t&&await zt(e)==="AUTHORIZED"?{kind:"authorized"}:D(e.signal,()=>It(e,t))}s(Tt,"startMcpSignIn");async function zt(e){let{store:t,settings:r,challenge:i,redirectUrl:n,signal:a}=e,o=t.withRefreshLock(async()=>{if(a?.aborted)return"REDIRECT";let c=await t.load();return!c?.tokens?.refresh_token||r.clientRegistration==="cimd"&&c.clientInformation&&!r.clientId?"REDIRECT":me(e,c,{challenge:i,redirectUrl:n})});try{return await Pt(a,o)}catch(c){if(c instanceof oe)return"REDIRECT";throw c}}s(zt,"refreshBeforeSignIn");function Pt(e,t){return e?new Promise((r,i)=>{let n=s(()=>i(new g),"abort");e.addEventListener("abort",n,{once:!0}),t.then(r,i).finally(()=>e.removeEventListener("abort",n))}):t}s(Pt,"untilAborted");async function It(e,t){let{store:r,settings:i,redirectUrl:n,challenge:a}=e,o=await r.load();o&&await r.save(Ot(o,e));let c,l=P(e,n,f=>{c=f}),h=Lt(i.scope,t?Et(o?.tokens?.scope,a?.scope):a?.scope);if(await $(l,{...ve(e),scope:h,skipRefresh:!0}),!c)throw new Error("OAuth flow did not produce an authorization URL");let d=c.searchParams.get("scope");return{kind:"redirect",authorizationUrl:c.href,redirectUrl:c.searchParams.get("redirect_uri")??n,state:await l.state(),...d?{scope:d}:{}}}s(It,"startBrowserStep");function Ot(e,t){let{settings:r,redirectUrl:i}=t,n={...e};return delete n.oauthState,r.clientId||(e.clientInformation?r.clientRegistration!=="cimd"&&O(e.clientInformation).includes(i):I(r,t.clientMetadataDocuments,i))||(delete n.clientInformation,delete n.tokens,delete n.tokensExpireAt),n}s(Ot,"stateForSignIn");function Lt(...e){let t=[...new Set(e.flatMap(r=>r?.split(/\s+/).filter(Boolean)??[]))];return t.length>0?t.join(" "):void 0}s(Lt,"mergeScopes");async function xt(e){await D(e.signal,async()=>{let{authorization:t,response:r}=e;if(r.state!==t.state)throw new Error("The authorization response belongs to a different sign-in");if((await e.store.load())?.oauthState!==t.state)throw new Error("Another sign-in to this MCP server started since; sign in again");await $(P(e,e.redirectUrl),{...ve(e),scope:t.scope,authorizationRedirectUrl:t.redirectUrl,authorizationCode:r.code,iss:r.iss})})}s(xt,"completeMcpSignIn");function ve(e){return{serverUrl:e.serverUrl,fetch:te(),signal:e.signal,resourceMetadataUrl:e.challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:e.settings.authServerMetadataUrl}}s(ve,"flowOptions");async function D(e,t){if(e?.aborted)throw new g;try{return await t()}catch(r){throw e?.aborted?new g:r}}s(D,"cancellable");async function $t(e){let{settings:t}=e,r=ne(t),i=O((await e.store.load())?.clientInformation)[0],n=r.port??(i&&Number(new URL(i).port)||void 0),a=I(t,e.clientMetadataDocuments,r.url),o={host:r.host,redirectHost:r.redirectHost,path:r.path,extraPaths:a?[X(r.path,e.serverUrl)]:[],renderPage:e.renderPage},c;try{c=await _e.listen({...o,port:n??0})}catch(l){if(r.port!==void 0||n===void 0)throw l;c=await _e.listen(o)}return{callback:c,redirectUrl:r.fixedRedirectUrl??c.redirectUrl}}s($t,"listenForLoopbackSignIn");async function Dt(e){let{authorization:t}=e,r=new AbortController,i=e.signal?AbortSignal.any([r.signal,e.signal]):r.signal,n=e.callback.waitForCallback(t.state,new URL(t.redirectUrl).pathname),a=e.promptForRedirectUrl?e.promptForRedirectUrl(i).then(o=>{if(!o?.trim())throw new g;return Ht(o,t)}):new Promise((o,c)=>{i.addEventListener("abort",()=>c(new g),{once:!0})});try{return await D(e.signal,()=>Promise.race([n,a]))}finally{r.abort(),n.catch(()=>{}),a.catch(()=>{})}}s(Dt,"waitForLoopbackSignIn");function Ht(e,t){let r;try{r=new URL(e.trim())}catch{throw new Error("Expected the full redirect URL from the browser address bar")}let i=new URL(t.redirectUrl);if(r.origin!==i.origin||r.pathname!==i.pathname)throw new Error("The redirect URL does not match this sign-in's redirect URI");let n=r.searchParams.get("error");if(n)throw new Error(r.searchParams.get("error_description")??n);let a=r.searchParams.get("state");if(a!==t.state)throw new Error("The redirect URL belongs to a different sign-in");let o=r.searchParams.get("code");if(!o)throw new Error("The redirect URL does not contain an authorization code");let c=r.searchParams.get("iss");return{code:o,state:a,...c?{iss:c}:{}}}s(Ht,"responseFromRedirectUrl");import{createHash as Nt}from"node:crypto";import{mkdirSync as Ft}from"node:fs";import{join as ye}from"node:path";var Vt='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800" aria-hidden="true"><path fill="#F09082" d="M165.29 165.29H517.36V400H400V282.65H165.29Z"/><path fill="#4D9ABF" d="M165.29 282.65H282.65V400H400V517.36H282.65V634.72H165.29Z"/><path fill="#F1BE58" d="M517.36 400H634.72V634.72H517.36Z"/></svg>';function A(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}s(A,"escapeHtml");function Ue(e){let t=A(e.title),r=A(e.heading),i=A(e.message),n=e.details?A(e.details):void 0;return`<!doctype html>
|
|
4
4
|
<html lang="en">
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var c=Object.defineProperty;var i=(t,e)=>c(t,"name",{value:e,configurable:!0});import{createRequire as y}from"node:module";const h=y(import.meta.url);import{ownedSlice as p}from"./chunk-
|
|
1
|
+
var c=Object.defineProperty;var i=(t,e)=>c(t,"name",{value:e,configurable:!0});import{createRequire as y}from"node:module";const h=y(import.meta.url);import{ownedSlice as p}from"./chunk-CIJDL6I3.js";var g=4e3;function m(t){if(!(t instanceof Error))return{message:a(t),messageCarriesBody:!1};let e=t,n=b(e),s=$(e),o=s===void 0||t.message.includes(s),u=n===void 0&&s===void 0?r(t):t.message;return{status:n,body:s,message:u,messageCarriesBody:o}}i(m,"normalizeProviderError");var l=5;function r(t){let e,n=t.cause;for(let u=0;u<l&&n instanceof Error;u++)e=n,n=n.cause;if(!e)return t.message;let s=(e.message||e.name).trim(),o=e.code;return(typeof o=="string"||typeof o=="number")&&!s.includes(String(o))&&(s=s?`${s} (${o})`:String(o)),!s||t.message.includes(s)?t.message:t.message?`${t.message}: ${s}`:s}i(r,"withCauseDetail");function b(t){if(typeof t.statusCode=="number")return t.statusCode;if(typeof t.status=="number")return t.status;if(typeof t.$metadata?.httpStatusCode=="number")return t.$metadata.httpStatusCode;if(typeof t.$response?.statusCode=="number")return t.$response.statusCode}i(b,"extractStatus");function $(t){let e=S(t);if(e===void 0)return;let n=e.trim();if(n.length!==0)return f(n,g)}i($,"extractBody");function S(t){if(typeof t.body=="string")return t.body;if(d(t.error))return a(t.error);let e=t.$response?.body;if(typeof e=="string")return e;if(!C(e)&&d(e))return a(e)}i(S,"pickBodyText");function C(t){return typeof t=="object"&&t!==null&&"pipe"in t&&typeof t.pipe=="function"}i(C,"isReadableStreamLike");function d(t){if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return e!==Object.prototype&&e!==null?!1:Object.keys(t).length>0}i(d,"isPlainNonEmptyObject");function E(t,e){return t.messageCarriesBody||t.status===void 0||t.body===void 0?e!==void 0&&t.status!==void 0?`${e} (${t.status}): ${t.message}`:t.message:e!==void 0?`${e} (${t.status}): ${t.body}`:`${t.status}: ${t.body}`}i(E,"formatProviderError");function f(t,e){return t.length<=e?t:`${p(t,0,e)}... [truncated ${t.length-e} chars]`}i(f,"truncateErrorText");function a(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}i(a,"safeJsonStringify");export{E as formatProviderError,m as normalizeProviderError,f as truncateErrorText,r as withCauseDetail};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var R=Object.defineProperty;var o=(e,r)=>R(e,"name",{value:r,configurable:!0});import{createRequire as b}from"node:module";const S=b(import.meta.url);import{retryProviderRequest as w}from"./chunk-ML5DIOWR.js";import{headersToRecord as q,providerHeadersToRecord as k}from"./chunk-UTB4DTYQ.js";import{calculateCost as x}from"./chunk-
|
|
1
|
+
var R=Object.defineProperty;var o=(e,r)=>R(e,"name",{value:r,configurable:!0});import{createRequire as b}from"node:module";const S=b(import.meta.url);import{retryProviderRequest as w}from"./chunk-ML5DIOWR.js";import{headersToRecord as q,providerHeadersToRecord as k}from"./chunk-UTB4DTYQ.js";import{calculateCost as x}from"./chunk-4KCKRVPN.js";import{getIdentityHeaders as E}from"./chunk-CIJDL6I3.js";function $(e,r,a){let i=new Error(`${e} returned ${r.status}`);return i.status=r.status,i.headers=r.headers,i.body=a,i}o($,"httpError");function T(e){let r=new Error(`Request timed out after ${e}ms`);return r.name="TimeoutError",r.status=void 0,r.headers=void 0,r.body="",r}o(T,"timeoutError");function m(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(m,"isRecord");function _(e,r,a){if(typeof r!="number"||!Number.isFinite(r))throw new Error(`${e} returned an invalid ${a}`);return r}o(_,"requiredNumber");function j(e,r,a,i){return k(E(e,i),{authorization:`Bearer ${r}`,"content-type":"application/json"},e.headers,a)??{}}o(j,"requestHeaders");async function A(e,r,a,i,t,y){if(!t?.apiKey)throw new Error(`No API key for provider: ${a.provider}`);let h=t.apiKey,u=i,d=await t.onPayload?.(u,a);d!==void 0&&(u=d);let l=t.fetch??globalThis.fetch,{response:c,json:p}=await w(async()=>{let s=t.timeoutMs!==void 0?AbortSignal.timeout(t.timeoutMs):void 0,g=t.signal&&s?AbortSignal.any([t.signal,s]):t.signal??s;try{let n=await l(r,{method:"POST",headers:j(a,h,t.headers,t.identity),body:JSON.stringify(u),signal:g});if(!n.ok)throw $(e,n,await n.text());return{response:n,json:await n.json()}}catch(n){throw s?.aborted&&!t.signal?.aborted?T(t.timeoutMs):n}},{maxRetries:t.maxRetries??2,maxRetryDelayMs:t.maxRetryDelayMs,signal:t.signal,noRetryStatuses:y});return await t.onResponse?.({status:c.status,headers:q(c.headers)},a),p}o(A,"postClassifierRequest");function f(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}o(f,"tokenCount");function C(e,r){if(!m(e)||e.input_tokens===void 0&&e.output_tokens===void 0)return;let a=f(e.input_tokens),i=f(e.output_tokens),t={input:a,output:i,cacheRead:0,cacheWrite:0,totalTokens:a+i,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return x(r,t),t}o(C,"parseClassifierUsage");export{m as isRecord,C as parseClassifierUsage,A as postClassifierRequest,_ as requiredNumber};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Le=Object.defineProperty;var a=(e,t)=>Le(e,"name",{value:t,configurable:!0});import{createRequire as Ie}from"node:module";const Dr=Ie(import.meta.url);import{typebox_exports as T}from"./chunk-JUUJCOIR.js";import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS as De}from"./chunk-NJDCSLWK.js";import{sanitizeBinaryOutput as Pe}from"./chunk-
|
|
1
|
+
var Le=Object.defineProperty;var a=(e,t)=>Le(e,"name",{value:t,configurable:!0});import{createRequire as Ie}from"node:module";const Dr=Ie(import.meta.url);import{typebox_exports as T}from"./chunk-JUUJCOIR.js";import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS as De}from"./chunk-NJDCSLWK.js";import{sanitizeBinaryOutput as Pe}from"./chunk-B66W54NL.js";import{fill as E}from"./chunk-G5AMLGXC.js";import{CodeHighlighter as Fe,Container as V,Spacer as I,Text as $,getCapabilities as Y,getImageDimensions as je,hyperlink as We,imageFallback as Be,keyHint as K,truncateToWidth as Ue}from"./chunk-NRQYSXAU.js";import{getDocsPath as He,resolvePath as Ge,shortenHomePath as Je}from"./chunk-QM5JU2GS.js";import{t as g}from"./chunk-3KEFLXX2.js";import{createWriteStream as ze}from"node:fs";import{writeFile as qe}from"node:fs/promises";import{randomBytes as Xe}from"node:crypto";import{lstatSync as Ze,mkdtempSync as Ve,readdirSync as Ye,rmSync as Q}from"node:fs";import{tmpdir as D}from"node:os";import{join as P}from"node:path";var Ke=1440*60*1e3,Qe=10080*60*1e3,et=/^(?:dal-(?:sandbox|bg|bash|powershell|output|mxc)|pi-codemode|pi-mcp)-(\d+)-/,tt=/^(?:dal-(?:sandbox|mxc)-[A-Za-z0-9]{6}|(?:dal-(?:bash|powershell|output)|pi-codemode|pi-mcp)-[0-9a-f]{16}(?:\.[A-Za-z0-9]+)?)$/,O=new Set,ee=!1;function te(e){try{Q(e,{recursive:!0,force:!0})}catch{}}a(te,"removePath");function rt(){for(let e of O)te(e);O.clear()}a(rt,"cleanupOwnedTempFiles");function nt(){ee||(ee=!0,process.on("exit",rt))}a(nt,"installExitHook");function F(e){nt(),O.add(e)}a(F,"registerTempPath");function it(e){O.delete(e),te(e)}a(it,"removeTempPath");function ot(e){let t=Ve(P(D(),`dal-${e}-${process.pid}-`));return F(t),t}a(ot,"createTempDir");function at(e,t,r=D()){return P(r,`${e}-${process.pid}-${Xe(8).toString("hex")}${t}`)}a(at,"tempFilePath");function st(e){if(e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}a(st,"processExists");function lt(e={}){let t=e.dir??D(),r=e.now??Date.now(),n=e.maxAgeMs??Ke,i=e.legacyMaxAgeMs??Qe,o=e.exists??st,s=process.getuid?.(),c={removed:[],kept:0},l;try{l=Ye(t)}catch{return c}for(let p of l){let d=et.exec(p),u=!d&&tt.test(p);if(!d&&!u)continue;let m=P(t,p);try{let f=Ze(m);if(s!==void 0&&f.uid!==s)continue;if(!(r-f.mtimeMs>=(d?n:i))||d&&o(Number(d[1]))){c.kept++;continue}Q(m,{recursive:!0,force:!0}),c.removed.push(m)}catch{}}return c}a(lt,"sweepStaleTempFiles");var re=384,C;function ut(e){return C=e,()=>{C===e&&(C=void 0)}}a(ut,"setOutputFileDirectory");function ne(e,t){let r=C?.(),n=at(e,t,r);return r||F(n),n}a(ne,"createOutputFilePath");async function ct(e,t,r){let n=ne(e,t);return await qe(n,r,{mode:re,flag:"wx"}),n}a(ct,"writeOutputFile");function dt(e,t){let r=ne(e,t);return{path:r,stream:ze(r,{mode:re,flags:"wx"})}}a(dt,"createOutputFileStream");function ie(){return{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0}}a(ie,"createUsageTotals");function oe(e,t){e.input+=t.input,e.output+=t.output,e.cacheRead+=t.cacheRead,e.cacheWrite+=t.cacheWrite,e.cost+=t.cost.total}a(oe,"addUsageToTotals");function pt(e,t){return{input:e.input+t.input,output:e.output+t.output,cacheRead:e.cacheRead+t.cacheRead,cacheWrite:e.cacheWrite+t.cacheWrite,...e.cacheWrite1h!==void 0||t.cacheWrite1h!==void 0?{cacheWrite1h:(e.cacheWrite1h??0)+(t.cacheWrite1h??0)}:{},...e.reasoning!==void 0||t.reasoning!==void 0?{reasoning:(e.reasoning??0)+(t.reasoning??0)}:{},totalTokens:e.totalTokens+t.totalTokens,cost:{input:e.cost.input+t.cost.input,output:e.cost.output+t.cost.output,cacheRead:e.cost.cacheRead+t.cost.cacheRead,cacheWrite:e.cost.cacheWrite+t.cost.cacheWrite,total:e.cost.total+t.cost.total,totalFromProvider:e.cost.totalFromProvider===!0&&t.cost.totalFromProvider===!0}}}a(pt,"combineUsage");function mt(e){let t=new Map;for(let r of e){let n,i;if(r.type==="message"&&r.message.role==="assistant"?(n=`${r.message.provider}/${r.message.responseModel??r.message.model}`,i=r.message.usage):r.type==="usage"?(n=`${r.provider}/${r.model}`,i=r.usage):r.type==="message"&&r.message.role==="toolResult"&&r.message.usage?(n="Tools/summaries",i=r.message.usage):(r.type==="branch_summary"||r.type==="compaction")&&r.usage&&(n="Tools/summaries",i=r.usage),!n||!i)continue;let o=t.get(n);o||(o=ie(),t.set(n,o)),oe(o,i)}return Array.from(t,([r,n])=>({key:r,cost:n.cost,tokens:n.input+n.output+n.cacheRead+n.cacheWrite})).filter(r=>r.cost>0||r.tokens>0).sort((r,n)=>n.cost-r.cost)}a(mt,"getUsageCostBreakdown");function ae(e,t,r,n=0,i="end"){if(!e)return{visualLines:[],skippedCount:0};let o=new $(e,n,0).render(r);if(o.length<=t)return{visualLines:o,skippedCount:0};let s=i==="start"?o.slice(0,t):o.slice(-t),c=o.length-t;return{visualLines:s,skippedCount:c}}a(ae,"truncateToVisualLines");var j=class{static{a(this,"VisualLinePreview")}options;cachedWidth;cachedLines;constructor(e){this.options=e}render(e){if(this.cachedLines===void 0||this.cachedWidth!==e){let{text:t,maxVisualLines:r,keep:n,formatHint:i}=this.options,o=ae(t,r,e,0,n),s=o.visualLines;if(o.skippedCount>0){let c=Ue(i(o.skippedCount),e,"...");this.cachedLines=n==="start"?[...s,c]:[c,...s]}else this.cachedLines=s;this.cachedWidth=e}return this.cachedLines}invalidate(){this.cachedWidth=void 0,this.cachedLines=void 0}};import{pathToFileURL as ft}from"node:url";var gt="(?:\\u0007|\\u001B\\u005C|\\u009C)",se="\\u001B\\]",le="(?:(?:\\u001B\\[|\\u009B)[<=>]|[\\u001B\\u009B][[\\]()#;?]*)(?:\\d{1,4}(?:[;:]\\d{0,4})*)?",ht="[\\dA-PR-TZcf-nq-uy=><~]",yt=new RegExp(`(?:${se}[\\s\\S]*?${gt})|${le}${ht}`,"g"),St=new RegExp(`(?:${se}(?:[^\\u0007\\u009C\\u001B]|\\u001B(?!\\\\))*|${le})$`),At=256;function $t(e){if(!e.includes("\x1B")&&!e.includes("\x9B"))return{complete:e,pending:""};let t=Math.max(0,e.length-At),r=St.exec(e.slice(t));if(!r)return{complete:e,pending:""};let n=t+r.index;return{complete:e.slice(0,n),pending:e.slice(n)}}a($t,"splitIncompleteAnsiSuffix");function ue(e){if(typeof e!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return!e.includes("\x1B")&&!e.includes("\x9B")?e:e.replace(yt,"")}a(ue,"stripAnsi");function ce(e){return typeof e!="string"?"":Je(e)}a(ce,"shortenPath");function Tt(e,t,r){if(!Y().hyperlinks)return e;let n=Ge(t,r);return We(e,ft(n).href)}a(Tt,"linkPath");function de(e){return typeof e=="string"?e:e==null?"":null}a(de,"str");function pe(e){return typeof e=="string"&&e.trim()!==""&&(e=Number(e)),typeof e=="number"&&Number.isFinite(e)?e:void 0}a(pe,"parseLineNumber");function wt(e,t){if(e==null&&t==null)return"";let r=e==null?1:pe(e);if(r===void 0)return"";if(t==null)return`:${r}`;let n=pe(t);if(n===void 0)return"";let i=r+n-1;return`:${r}${i?`-${i}`:""}`}a(wt,"formatReadLineRange");function k(e){return e.replace(/\t/g," ")}a(k,"replaceTabs");function vt(e){return e.replace(/\r/g,"")}a(vt,"normalizeDisplayText");function me(e,t){if(!e)return"";let r=e.content.filter(s=>s.type==="text"),n=e.content.filter(s=>s.type==="image"),i=r.map(s=>Pe(ue(s.text||"")).replace(/\r/g,"")).join(`
|
|
2
2
|
`),o=Y();if(n.length>0&&(!o.images||!t)){let s=n.map(c=>{let l=c.mimeType??"image/unknown",p=c.data&&c.mimeType?je(c.data,c.mimeType)??void 0:void 0;return Be(l,p)}).join(`
|
|
3
3
|
`);i=i?`${i}
|
|
4
4
|
${s}`:s}return i}a(me,"getTextOutput");var fe=100;function _t(e,t,r,n){let i=r.fg("toolTitle",r.bold(e));if(t==null)return i;let o=typeof t=="object"&&!Array.isArray(t)?Object.entries(t):[["args",t]];if(o.length===0)return i;if(n){let l=o.map(([p,d])=>{let u=typeof d=="string"?d:JSON.stringify(d,null,2)??String(d);return` ${p}: ${k(u).replace(/\r/g,"").split(`
|
|
@@ -31,7 +31,7 @@ Searches over deferred tool metadata with BM25 and exposes matching tools for th
|
|
|
31
31
|
|
|
32
32
|
Some of the tools, such as tools of MCP servers, may not have been provided to you upfront, and you should use this tool (\`${w}\`) to search for the required tools. For MCP tool discovery, always use \`${w}\`.`;function or(e={}){return{name:w,label:w,description:ir,promptSnippet:"Search for tools that are not loaded yet and load the matches",parameters:tr,exposure:"model-only",reachesTools:a(()=>"all","reachesTools"),async execute(t,{query:r,limit:n}){if(r.trim()==="")throw new Error("query must not be empty");let i=n??U;if(!Number.isInteger(i)||i<=0)throw new Error("limit must be a positive integer");let o=e.tools?nr(e.tools,r,i):[];return{content:[{type:"text",text:o.length===0?"No matching tools found.":`Loaded ${o.length} tool${o.length===1?"":"s"}. They are available from your next call:
|
|
33
33
|
${o.map(s=>`- ${s.name}: ${s.description.trim().split(/\r?\n/)[0]}`).join(`
|
|
34
|
-
`)}`}],details:{loaded:o.map(s=>s.name)}}}}}a(or,"createToolSearchToolDefinition");import{join as ar}from"node:path";var G={transport:"auto",sessionShareDestination:"auto",steeringMode:"one-at-a-time",followUpMode:"one-at-a-time",compaction:{enabled:!0,reserveTokens:16384,keepRecentTokens:2e4},branchSummary:{reserveTokens:16384,skipPrompt:!1},retry:{enabled:!0,maxRetries:3,baseDelayMs:2e3,maxAgentDelayMs:De,provider:{maxRetryDelayMs:6e4}},hideThinkingBlock:!1,showCacheMissNotices:!1,quietStartup:!1,defaultProjectTrust:"ask",collapseChangelog:!1,enableInstallTelemetry:!0,enableAnalytics:!1,enableSkillCommands:!0,terminal:{showImages:!0,imageWidthCells:60,clearOnShrink:!1,showTerminalProgress:!1},images:{autoResize:!0,blockImages:!1},doubleEscapeAction:"tree",treeFilterMode:"default",editorPaddingX:0,outputPad:1,autocompleteMaxVisible:5,markdown:{codeBlockIndent:" ",mermaid:"streaming"},warnings:{anthropicExtraUsage:!0},codemode:{mode:"on",inlineBudget:3e3},cacheWarming:"idle",tuiMode:"fullscreen",fullscreenExitOutput:"transcript",fullscreenScrollbar:"auto",fullscreenCopyOnSelect:!0,fullscreenWheelScrollLines:"auto"};function sr(e,t){return{name:e.name,label:e.label,description:e.description,parameters:e.parameters,outputSchema:e.outputSchema,constrainedSampling:e.constrainedSampling,prepareArguments:e.prepareArguments,executionMode:e.executionMode,executionModeFor:e.executionModeFor,execute:a((r,n,i,o,s)=>e.execute(r,n,i,o,s??t?.(r,i)),"execute")}}a(sr,"wrapToolDefinition");function lr(e){return{name:e.name,label:e.label,description:e.description,parameters:e.parameters,outputSchema:e.outputSchema,constrainedSampling:e.constrainedSampling,prepareArguments:e.prepareArguments,executionMode:e.executionMode,executionModeFor:e.executionModeFor,execute:a(async(t,r,n,i)=>e.execute(t,r,n,i),"execute")}}a(lr,"createToolDefinitionFromAgentTool");var ur=a(()=>import("./execute-
|
|
34
|
+
`)}`}],details:{loaded:o.map(s=>s.name)}}}}}a(or,"createToolSearchToolDefinition");import{join as ar}from"node:path";var G={transport:"auto",sessionShareDestination:"auto",steeringMode:"one-at-a-time",followUpMode:"one-at-a-time",compaction:{enabled:!0,reserveTokens:16384,keepRecentTokens:2e4},branchSummary:{reserveTokens:16384,skipPrompt:!1},retry:{enabled:!0,maxRetries:3,baseDelayMs:2e3,maxAgentDelayMs:De,provider:{maxRetryDelayMs:6e4}},hideThinkingBlock:!1,showCacheMissNotices:!1,quietStartup:!1,defaultProjectTrust:"ask",collapseChangelog:!1,enableInstallTelemetry:!0,enableAnalytics:!1,enableSkillCommands:!0,terminal:{showImages:!0,imageWidthCells:60,clearOnShrink:!1,showTerminalProgress:!1},images:{autoResize:!0,blockImages:!1},doubleEscapeAction:"tree",treeFilterMode:"default",editorPaddingX:0,outputPad:1,autocompleteMaxVisible:5,markdown:{codeBlockIndent:" ",mermaid:"streaming"},warnings:{anthropicExtraUsage:!0},codemode:{mode:"on",inlineBudget:3e3},cacheWarming:"idle",tuiMode:"fullscreen",fullscreenExitOutput:"transcript",fullscreenScrollbar:"auto",fullscreenCopyOnSelect:!0,fullscreenWheelScrollLines:"auto"};function sr(e,t){return{name:e.name,label:e.label,description:e.description,parameters:e.parameters,outputSchema:e.outputSchema,constrainedSampling:e.constrainedSampling,prepareArguments:e.prepareArguments,executionMode:e.executionMode,executionModeFor:e.executionModeFor,execute:a((r,n,i,o,s)=>e.execute(r,n,i,o,s??t?.(r,i)),"execute")}}a(sr,"wrapToolDefinition");function lr(e){return{name:e.name,label:e.label,description:e.description,parameters:e.parameters,outputSchema:e.outputSchema,constrainedSampling:e.constrainedSampling,prepareArguments:e.prepareArguments,executionMode:e.executionMode,executionModeFor:e.executionModeFor,execute:a(async(t,r,n,i)=>e.execute(t,r,n,i),"execute")}}a(lr,"createToolDefinitionFromAgentTool");var ur=a(()=>import("./execute-DAF3F222.js"),"loadCodemodeExecutor"),cr=10,dr=8,pr=5,Oe=80,mr=/^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n$/;function Ce(e,t){return`${e.fg("muted",E(g("\u2026\uFF08\u8FD8\u6709 {count} \u884C\uFF0C"),{count:t}))}${K("app.tools.expand",g("\u5C55\u5F00"))}${e.fg("muted",g("\uFF09"))}`}a(Ce,"expandHint");function fr(e){return e===void 0?"":e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`}a(fr,"formatDuration");function ke(e){return`$${e>=.01?e.toFixed(2):e.toPrecision(2)}`}a(ke,"formatCost");function gr(e,t){switch(e.status){case"running":return t.fg("warning","\u2026");case"ok":return t.fg("success","\u2713");case"error":return t.fg("error","\u2717");case"cancelled":return t.fg("muted","\u2298")}}a(gr,"statusIcon");function hr(e,t,r){let n=!r&&e.args.length>Oe?`${e.args.slice(0,Oe-3)}...`:e.args,i=fr(e.durationMs),o=`${gr(e,t)} ${t.fg("toolTitle",e.name)}`;return n&&(o+=` ${t.fg("muted",n)}`),i&&(o+=` ${t.fg("dim",i)}`),e.cost&&(o+=` ${t.fg("dim",ke(e.cost))}`),r&&e.error&&(o+=`
|
|
35
35
|
${t.fg("error",e.error.split(`
|
|
36
36
|
`).join(`
|
|
37
37
|
`))}`),o}a(hr,"formatCall");var yr={renderCall(e,t,r){bt(r);let n=de(e?.code),i=t.fg("toolTitle",t.bold("codemode")),o=r.lastComponent??new V;if(o.clear(),n===null)return o.addChild(new $(`${i} ${t.fg("error",g("[\u53C2\u6570\u65E0\u6548]"))}`,0,0)),o;if(o.addChild(new $(i,0,0)),n){let s=r.state;s.scriptHighlighter??=new Fe;let c=s.scriptHighlighter.highlight(k(n.replace(/\r/g,"").trimEnd()),"javascript").join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var pe=Object.defineProperty;var i=(e,u)=>pe(e,"name",{value:u,configurable:!0});import{createRequire as ye}from"node:module";const Du=ye(import.meta.url);import{t as o}from"./chunk-
|
|
1
|
+
var pe=Object.defineProperty;var i=(e,u)=>pe(e,"name",{value:u,configurable:!0});import{createRequire as ye}from"node:module";const Du=ye(import.meta.url);import{t as o}from"./chunk-3KEFLXX2.js";import"./chunk-JXWJOIH4.js";import{chmodSync as Be,existsSync as B,mkdirSync as C,readFileSync as v,rmSync as we,writeFileSync as k}from"node:fs";import{homedir as he,userInfo as Ce}from"node:os";import{dirname as ve}from"node:path";import{spawn as ke}from"node:child_process";import{createHash as be}from"node:crypto";import{existsSync as $e,mkdirSync as q,readFileSync as V,realpathSync as Se,renameSync as Ne,rmSync as b,writeFileSync as $}from"node:fs";import{join as D}from"node:path";import{join as g}from"node:path";var Y="dal-remote",E="com.deepailab.dal-remote";function w(e){let u=g(e,"remote"),t=g(u,"logs"),r=g(u,"bin");return{root:u,daemonRoot:g(u,"daemon"),home:g(u,"home"),binDir:r,dalWrapper:g(r,"dal"),logDir:t,logFile:g(t,"daemon.log"),stateFile:g(u,"state.json"),accountTokenFile:g(u,"account-token")}}i(w,"remotePaths");function z(e,u){return g(e.daemonRoot,u)}i(z,"daemonInstallDir");var Re=200*1024*1024,Q=12e4,x=".dal-remote-installed",m=class extends Error{static{i(this,"RemoteInstallError")}code;constructor(e,u){super(u),this.code=e}},_e=i((e,u,t)=>new Promise(r=>{let n="",a="",l;try{l=ke(e,[...u],{cwd:t?.cwd,env:t?.env??process.env,stdio:["ignore","pipe","pipe"]})}catch(s){r({code:127,stdout:n,stderr:s instanceof Error?s.message:String(s)});return}l.stdout?.on("data",s=>{n+=String(s)}),l.stderr?.on("data",s=>{a+=String(s)}),l.on("error",s=>r({code:127,stdout:n,stderr:a||s.message})),l.on("close",s=>r({code:s??1,stdout:n,stderr:a}))}),"runCommand");function Te(e){return`sha512-${be("sha512").update(e).digest("base64")}`}i(Te,"sha512Integrity");function Oe(e){let u=(e.PI_OFFLINE??e.DAL_OFFLINE)?.toLowerCase();return u==="1"||u==="true"||u==="yes"}i(Oe,"offline");function S(e,u){let t=z(e,u.version);try{let r=JSON.parse(V(D(t,x),"utf8"));return r.name===u.packageName&&r.integrity===u.integrity?t:void 0}catch{return}}i(S,"installedDaemonDir");function N(e,u){let t=D(e,"node_modules",".bin",u.bin);if($e(t))try{return Se(t)}catch{return}}i(N,"daemonBinPath");async function Ie(e,u){let t=[],r=0;for(let n of e.registries){let a=`${n.replace(/\/+$/,"")}/${e.packageName}/${e.version}`;try{let l=await u(a,{signal:AbortSignal.timeout(Q)});if(l.status===404){r++,await l.body?.cancel();continue}if(!l.ok){t.push(`${n}: HTTP ${l.status}`),await l.body?.cancel();continue}let s=await l.json(),F=typeof s.dist?.tarball=="string"?s.dist.tarball:void 0;if(!F){t.push(`${n}: ${o("\u6CA1\u6709\u4E0B\u8F7D\u5730\u5740")}`);continue}return{registry:n,tarball:F,integrity:typeof s.dist?.integrity=="string"?s.dist.integrity:void 0}}catch(l){t.push(`${n}: ${l instanceof Error?l.message:String(l)}`)}}throw r>0&&t.length===0?new m("not-published",o("\u624B\u673A\u7AEF\u5B88\u62A4\u8FDB\u7A0B {pkg} \u8FD8\u6CA1\u6709\u53D1\u5E03\uFF0C\u6682\u65F6\u65E0\u6CD5\u5F00\u542F\u3002\u53D1\u5E03\u540E\u5347\u7EA7 dal \u5373\u53EF\u4F7F\u7528\u3002").replace("{pkg}",`${e.packageName}@${e.version}`)):new m("network",`${o("\u65E0\u6CD5\u4ECE\u8F6F\u4EF6\u6E90\u83B7\u53D6\u624B\u673A\u7AEF\u5B88\u62A4\u8FDB\u7A0B\uFF1A")}
|
|
2
2
|
${t.map(n=>` ${n}`).join(`
|
|
3
3
|
`)}`)}i(Ie,"lookUp");async function Pe(e,u){let t=await u(e,{signal:AbortSignal.timeout(Q)});if(!t.ok)throw await t.body?.cancel(),new m("network",`${e}: HTTP ${t.status}`);let r=t.body?.getReader();if(!r)throw new m("network",`${e}: ${o("\u54CD\u5E94\u6CA1\u6709\u5185\u5BB9")}`);let n=[],a=0;for(;;){let{done:l,value:s}=await r.read();if(l)break;if(a+=s.byteLength,a>Re)throw await r.cancel(),new m("network",o("\u5B88\u62A4\u8FDB\u7A0B\u5B89\u88C5\u5305\u8D85\u8FC7 200 MB\uFF0C\u5DF2\u505C\u6B62\u4E0B\u8F7D"));n.push(s)}return Buffer.concat(n)}i(Pe,"download");async function Le(e,u,t){let r=S(e,u);if(r)return r;let n=`${u.packageName}@${u.version}`,a,l;if(u.tarball)a=V(u.tarball);else{if(Oe(t.env))throw new m("offline",o("\u79BB\u7EBF\u6A21\u5F0F\u4E0B\u65E0\u6CD5\u4E0B\u8F7D\u624B\u673A\u7AEF\u5B88\u62A4\u8FDB\u7A0B\u3002"));t.progress?.(o("\u6B63\u5728\u67E5\u627E {pkg} \u2026").replace("{pkg}",n));let c=await Ie(u,t.fetch);if(!u.integrity)throw new m("not-pinned",o("\u8FD9\u4E2A\u7248\u672C\u7684 dal \u6CA1\u6709\u8BB0\u5F55 {pkg} \u7684\u6821\u9A8C\u503C\uFF0C\u4E0D\u80FD\u5B89\u88C5\u3002\u8BF7\u5347\u7EA7 dal \u540E\u518D\u8BD5\u3002").replace("{pkg}",n));if(c.integrity&&c.integrity!==u.integrity)throw new m("integrity",o("\u8F6F\u4EF6\u6E90\u4E0A\u7684 {pkg} \u4E0E dal \u8BB0\u5F55\u7684\u6821\u9A8C\u503C\u4E0D\u4E00\u81F4\uFF0C\u5DF2\u505C\u6B62\u5B89\u88C5\u3002").replace("{pkg}",n));l=c.registry,t.progress?.(o("\u6B63\u5728\u4E0B\u8F7D {pkg} \u2026").replace("{pkg}",n)),a=await Pe(c.tarball,t.fetch)}let s=Te(a);if(s!==u.integrity)throw new m("integrity",o("\u4E0B\u8F7D\u5230\u7684 {pkg} \u6821\u9A8C\u503C\u4E0D\u7B26\uFF08{got}\uFF09\uFF0C\u5DF2\u4E22\u5F03\u3002").replace("{pkg}",n).replace("{got}",s.slice(0,20)));q(e.daemonRoot,{recursive:!0});let F=D(e.daemonRoot,`.stage-${process.pid}-${Date.now()}`);q(F,{recursive:!0});try{let c=D(F,"daemon.tgz");$(c,a),$(D(F,"package.json"),`${JSON.stringify({name:"dal-remote-host",private:!0})}
|
|
4
4
|
`),t.progress?.(o("\u6B63\u5728\u5B89\u88C5 {pkg} \u2026").replace("{pkg}",n));let d=await t.run(t.npm,["install","--prefix",F,"--no-audit","--no-fund","--ignore-scripts","--omit=dev",...l?["--registry",l]:[],c],{cwd:F,env:t.env});if(d.code!==0){let y=d.stderr.trim().split(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var q=Object.defineProperty;var h=(t,r)=>q(t,"name",{value:r,configurable:!0});import{createRequire as Y}from"node:module";const we=Y(import.meta.url);import{McpOAuthCredentialStore as z,McpServerConnection as K,McpServerLog as V,McpSignInCancelledError as B,createDefaultTransport as W,signInMcpServer as G}from"./chunk-
|
|
1
|
+
var q=Object.defineProperty;var h=(t,r)=>q(t,"name",{value:r,configurable:!0});import{createRequire as Y}from"node:module";const we=Y(import.meta.url);import{McpOAuthCredentialStore as z,McpServerConnection as K,McpServerLog as V,McpSignInCancelledError as B,createDefaultTransport as W,signInMcpServer as G}from"./chunk-SI4QX273.js";import{ModelRuntime as J,ProjectTrustStore as U,addMcpServerConfig as Q,loadMcpConfig as I,openBrowser as X,questionTerminal as Z,removeMcpServerConfig as ee}from"./chunk-P3KSBU23.js";import"./chunk-RNSD5PAD.js";import"./chunk-JUUJCOIR.js";import"./chunk-NJDCSLWK.js";import{getMcpToolExposure as re,validateMcpServerConfig as te}from"./chunk-H3KG4L7I.js";import"./chunk-425HIJ4E.js";import"./chunk-B66W54NL.js";import{fill as oe}from"./chunk-G5AMLGXC.js";import{source_default as D}from"./chunk-6QGV3IWD.js";import{APP_NAME as v,CONFIG_DIR_NAME as y}from"./chunk-QM5JU2GS.js";import"./chunk-XJFQKN3N.js";import{t as R}from"./chunk-3KEFLXX2.js";import"./chunk-IEBK4HQA.js";import"./chunk-723ZGEZ2.js";import"./chunk-ZG74NES2.js";import"./chunk-TMTOQ7H7.js";import"./chunk-7DDKXS2Q.js";import"./chunk-FFMDRXC4.js";import"./chunk-4KCKRVPN.js";import"./chunk-4LDEEFCY.js";import"./chunk-CIJDL6I3.js";import"./chunk-JXWJOIH4.js";import{existsSync as ne}from"node:fs";import{join as M}from"node:path";var ie=`${D.bold(R("\u7528\u6CD5\uFF1A"))}
|
|
2
2
|
${v} mcp add <server> [options] -- <command> [args...]
|
|
3
3
|
${v} mcp add <server> [options] --url <url>
|
|
4
4
|
${v} mcp remove <server> [-l]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var a=Object.defineProperty;var s=(e,r)=>a(e,"name",{value:r,configurable:!0});import{createRequire as n}from"node:module";const c=n(import.meta.url);import{classifySystemOne as u}from"./chunk-
|
|
1
|
+
var a=Object.defineProperty;var s=(e,r)=>a(e,"name",{value:r,configurable:!0});import{createRequire as n}from"node:module";const c=n(import.meta.url);import{classifySystemOne as u}from"./chunk-RRLI6IMC.js";import{isRecord as i}from"./chunk-X2O23QIN.js";import"./chunk-ML5DIOWR.js";import"./chunk-THJSXCE4.js";import"./chunk-UTB4DTYQ.js";import"./chunk-4KCKRVPN.js";import"./chunk-4LDEEFCY.js";import"./chunk-CIJDL6I3.js";import"./chunk-JXWJOIH4.js";var o="Cloudflare Workers AI";function p(e){if(Array.isArray(e)){let r=e.map(t=>i(t)&&typeof t.message=="string"?t.message:void 0).filter(t=>t!==void 0);if(r.length>0)return`${o} error: ${r.join("; ")}`}return`${o} request failed`}s(p,"cloudflareErrorMessage");var l={api:"cloudflare-workers-ai-system-one",label:o,detectCompat:s(e=>({imageInput:e.id.startsWith("@cf/cloudflare/clef")?"images":"assets",sendImageOptInHeader:!1}),"detectCompat"),url:s(e=>new URL("run",`${e.baseUrl.replace(/\/+$/u,"")}/`),"url"),payload:s((e,r)=>({model:e.id,input:r}),"payload"),output:s(e=>{if(!i(e))throw new Error(`${o} returned an unexpected response`);if(e.success===!1)throw new Error(p(e.errors));let r=e.result;if(!i(r))throw new Error(`${o} returned an unexpected response`);if("answers"in r)return r;if(r.state!=="Completed")throw new Error(`${o} run did not complete (state: ${String(r.state)})`);if(!i(r.result))throw new Error(`${o} returned an unexpected response`);return r.result},"output")},m=s((e,r,t)=>u(l,e,r,t),"classify");export{m as classify};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var Ft=Object.defineProperty;var S=(t,e)=>Ft(t,"name",{value:e,configurable:!0});import{createRequire as Ht}from"node:module";const ve=Ht(import.meta.url);import{ARMIN_HEIGHT as zt,ARMIN_WIDTH as Vt,isArminPixel as Zt}from"./chunk-F5SIUTR7.js";import{backgroundAnsi as Wt,colorToRgb as Bt,foregroundAnsi as Gt,formatKeyText as Kt,getKeybindings as St,indexedColor as qt,rgbColor as $t,theme as G,visibleWidth as Jt}from"./chunk-AL3DFAIM.js";import"./chunk-6QGV3IWD.js";import"./chunk-R47JBGS3.js";import"./chunk-5AGIVGSV.js";import"./chunk-JXWJOIH4.js";var it=.7,W=.1,nt=1.3,jt=.1;function Yt(t,e,r,n){let i=[];for(let a=0;a<e;a++)for(let c=0;c<t;c++){let y=r(c,a);y&&i.push({home:[c,a,0],color:y})}return{columns:t,rows:e,blocks:i,cameraDistance:n.cameraDistance,radius:Math.hypot(t/2,e/2,1+it/2),widthShare:n.widthShare,puzzleMoves:S(a=>n.puzzleMoves(a,i.length),"puzzleMoves"),origin:n.origin}}S(Yt,"createModel");var Qt=[228,138,122],te=[79,142,179],ee=[234,182,93],re=["ccc.","b.c.","bb.y","b..y"],ie={c:Qt,b:te,y:ee};function ne(t){return Yt(4,4,(e,r)=>ie[re[r][e]],{cameraDistance:10,widthShare:.35,puzzleMoves:S(e=>e<.4?2:1,"puzzleMoves"),origin:t})}S(ne,"piLogoModel");function ae(t){return Yt(Vt,zt,(e,r)=>Zt(e,r)?t:void 0,{cameraDistance:80,widthShare:.45,puzzleMoves:S((e,r)=>Math.round(r*(.03+e*.04)),"puzzleMoves"),origin:void 0})}S(ae,"arminModel");var at=W+nt+3,K=.3,Q=12,lt=1,_t=.6,mt=K*Q+lt+_t,le=[[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]];function se(t,e){let{columns:r,rows:n}=t,i=t.blocks.map(l=>l.home),a=[i],c=new Set,y=e*7919+1,o=S(()=>tt(y++),"next"),f=S(([l,M,h])=>((h+1)*n+M)*r+l,"key");for(let l=0;l<Q;l++){let M=new Set(i.map(f)),h=[...i],d=new Set,Y=t.puzzleMoves(o());for(let x=0;x<Y;x++){let s=[];for(let _=0;_<i.length;_++){if(d.has(_))continue;let[k,X,g]=i[_];for(let[I,v,L]of le){let R=[k+I,X+v,g+L];R[0]<0||R[0]>=r||R[1]<0||R[1]>=n||R[2]<-1||R[2]>1||M.has(f(R))||s.push({block:_,target:R})}}let p=s.filter(_=>!c.has(_.block)),m=p.length>0?p:s,u=m[Math.floor(o()*m.length)];if(!u)break;M.add(f(u.target)),h[u.block]=u.target,d.add(u.block)}c.clear();for(let x of d)c.add(x);i=h,a.push(i)}return a}S(se,"shuffleSteps");var oe=1e3/30,wt=.35,Et=.55,Rt=.12,vt=W+Et+Rt+wt,he=.5,ce=1.1,me=2.5,fe=2,ue=.018,It=[[255,255,255],[170,195,255],[255,225,170],[255,190,205]],z=5,de=.3,q=6,$=3,Tt=32,Lt=8,Xt=3,ge=.5,ft=[1,8,2,16,4,32,64,128],ut=Array.from({length:256},(t,e)=>String.fromCharCode(10240+e)),J=Dt([-.45,-.6,.75]),dt=Dt([J[0],J[1],J[2]+1]);function Dt(t){let e=Math.hypot(t[0],t[1],t[2]);return[t[0]/e,t[1]/e,t[2]/e]}S(Dt,"normalize");function Z(t){return t<0?0:t>1?1:t}S(Z,"clamp01");function U(t){let e=Z(t);return e*e*e*(e*(e*6-15)+10)}S(U,"smooth");function xe(t){let e=1-Z(t);return 1-e*e*e}S(xe,"easeOut");function V(t,e,r){return[t[0]+(e[0]-t[0])*r,t[1]+(e[1]-t[1])*r,t[2]+(e[2]-t[2])*r]}S(V,"mix");function tt(t){let e=Math.imul(t^2654435769,2246822507);return e^=e>>>13,e=Math.imul(e,3266489909),e^=e>>>16,(e>>>0)/4294967296}S(tt,"hash");function kt([t,e,r]){return .2126*t+.7152*e+.0722*r>128}S(kt,"isLight");function et(t){let{r:e,g:r,b:n}=Bt(t);return[e,r,n]}S(et,"toRgb");function pe(t,e){return t.trim()===""?0:/^[.,:;'`\-_·]$/.test(t)?2:/^[\u2500-\u257f]$/.test(t)?3:4+Math.floor(e*3)}S(pe,"glyphInk");var Me=new Intl.Segmenter;function ye(t,e,r,n){let i=S(a=>et(qt(a)),"palette");return t.map(a=>{let c=[],y,o,f=!1,l=!1,M=S(Y=>{let x=Y===""?["0"]:Y.split(";");for(let s=0;s<x.length;s++){let p=x[s].split(":").map(u=>Number.parseInt(u,10)),m=p[0]??0;if(m===38||m===48){let u;if(p.length>1)u=p.slice(1).filter(k=>!Number.isNaN(k));else{let k=Number.parseInt(x[s+1]??"",10),X=k===5?2:k===2?4:1;u=x.slice(s+1,s+1+X).map(g=>Number.parseInt(g,10)),s+=X}let _;u[0]===5&&u[1]!==void 0?_=i(u[1]):u[0]===2&&u.length>=4&&(_=[u[1],u[2],u[3]]),_&&(m===38?y=_:o=_)}else m===0?(y=void 0,o=void 0,f=!1,l=!1):m===2?f=!0:m===22?f=!1:m===7?l=!0:m===27?l=!1:m>=30&&m<=37?y=i(m-30):m>=90&&m<=97?y=i(m-90+8):m===39?y=void 0:m>=40&&m<=47?o=i(m-40):m>=100&&m<=107?o=i(m-100+8):m===49&&(o=void 0)}},"applySgr"),h=S(Y=>{for(let{segment:x}of Me.segment(Y)){let s=Jt(x);if(s===0||c.length+s>e)continue;let p=y??r,m=o;l&&(p=o??n,m=y??r),f&&(p=V(p,m??n,.4));let u={text:x,width:s,fg:p,bg:m,delay:0,ink:0,seed:0};c.push(u),s===2&&c.push({...u,text:"",width:0})}},"pushText"),d=0;for(;d<a.length;){let Y=a.indexOf("\x1B",d);if(Y===-1){h(a.slice(d));break}Y>d&&h(a.slice(d,Y));let x=a[Y+1];if(x==="["){let s=Y+2;for(;s<a.length&&(a.charCodeAt(s)<64||a.charCodeAt(s)>126);)s++;a[s]==="m"&&M(a.slice(Y+2,s)),d=s+1}else if(x==="]"||x==="_"||x==="P"||x==="^"){let s=a.indexOf("\x07",Y+2),p=a.indexOf("\x1B\\",Y+2);if(s===-1&&p===-1)break;d=s!==-1&&(p===-1||s<p)?s+1:p+2}else d=Y+2}return c})}S(ye,"parseScreen");function Ae(t,e,r){let[n,i,a,c,y,o]=[Math.sin(t),Math.cos(t),Math.sin(e),Math.cos(e),Math.sin(r),Math.cos(r)],f=[i,0,n,0,1,0,-n,0,i],l=[1,0,0,0,c,-a,0,a,c],M=[o,-y,0,y,o,0,0,0,1];return Pt(M,Pt(l,f))}S(Ae,"rotation");function Pt(t,e){let r=new Array(9);for(let n=0;n<3;n++)for(let i=0;i<3;i++)r[n*3+i]=t[n*3]*e[i]+t[n*3+1]*e[3+i]+t[n*3+2]*e[6+i];return r}S(Pt,"multiply");var st=1.4,Ot=Math.PI*2/mt,be=.6,Se=at+K*Q+lt+_t/2;function Ct(t){let e=t-W;if(e<=0)return 0;let r=e/st;return r<1?Ot*st*(r**6-3*r**5+2.5*r**4):Ot*(st*.5+e-st)}S(Ct,"baseSpinPhase");var Ye=Math.PI*2-Ct(Se)%(Math.PI*2);function gt(t){return Ct(t)+Ye*U((t-W)/nt)}S(gt,"spinPhase");function Ut(t){let e=gt(t);return e-be*Math.sin(e)}S(Ut,"spinAngle");var _e=class{static{S(this,"BlockRaster")}bits=new Uint8Array(0);counts=new Uint8Array(0);rgb=new Float32Array(0);haloAmount=new Float32Array(0);haloRgb=new Float32Array(0);width=0;height=0;depth=new Float32Array(0);faceIds=new Uint16Array(0);dirty;haloDirty;cameraDistance;constructor(t){this.cameraDistance=t}render(t,e,r,n,i,a){let c=t*2,y=e*4;if(t!==this.width||e!==this.height)this.width=t,this.height=e,this.bits=new Uint8Array(t*e),this.counts=new Uint8Array(t*e),this.rgb=new Float32Array(t*e*3),this.haloAmount=new Float32Array(t*e),this.haloRgb=new Float32Array(t*e*3),this.haloDirty=void 0,this.depth=new Float32Array(c*y).fill(1/0),this.faceIds=new Uint16Array(c*y),this.dirty=void 0;else if(this.dirty){let{minX:A,minY:w,maxX:b,maxY:D}=this.dirty;for(let E=w;E<=D;E++)this.bits.fill(0,E*t+A,E*t+b+1),this.counts.fill(0,E*t+A,E*t+b+1),this.rgb.fill(0,(E*t+A)*3,(E*t+b+1)*3);this.dirty=void 0}if(this.haloDirty){let{minX:A,minY:w,maxX:b,maxY:D}=this.haloDirty;for(let E=w;E<=D;E++)this.haloAmount.fill(0,E*t+A,E*t+b+1),this.haloRgb.fill(0,(E*t+A)*3,(E*t+b+1)*3);this.haloDirty=void 0}let o=Ae(r.yaw,r.pitch,r.roll),{centerX:f,centerY:l,scale:M}=r,h=this.cameraDistance,d=[o[6]*h,o[7]*h,o[8]*h],Y=kt(i),x=this.visibleFaces(o,d,r,n,c,y,Y);if(x.length===0)return;let s=c,p=y,m=-1,u=-1;for(let A of x)s=Math.min(s,A.minX),p=Math.min(p,A.minY),m=Math.max(m,A.maxX),u=Math.max(u,A.maxY);if(m<s||u<p)return;let _=this.depth,k=this.faceIds;for(let A=0;A<x.length;A++){let w=x[A],b=w.axis,D=(b+1)%3,E=(b+2)%3,O=d[b],C=d[D],N=d[E],F=o[b]/M,ht=o[D]/M,P=o[E]/M,H=(w.minX+.5-f)/M;for(let B=w.minY;B<=w.maxY;B++){let ct=(B+.5-l)/M,xt=o[b]*H+o[3+b]*ct-o[6+b]*h,pt=o[D]*H+o[3+D]*ct-o[6+D]*h,Mt=o[E]*H+o[3+E]*ct-o[6+E]*h,rt=B*c+w.minX;for(let yt=w.minX;yt<=w.maxX;yt++,rt++){let j=(w.plane-O)/xt;if(j>0&&j<_[rt]){let At=C+j*pt,bt=N+j*Mt;At>=w.uMin&&At<=w.uMax&&bt>=w.vMin&&bt<=w.vMax&&(_[rt]=j,k[rt]=A+1)}xt+=F,pt+=ht,Mt+=P}}}let X=this.bits,g=this.counts,I=this.rgb,v=t,L=e,R=-1,T=-1;for(let A=p;A<=u;A++){let w=A*c+s;for(let b=s;b<=m;b++,w++){let D=k[w];if(D===0)continue;let E=x[D-1],O=Z(.15-h*(1-_[w])*.12)*(Y?.5:1);k[w]=0,_[w]=1/0;let C=b>>1,N=A>>2,F=N*t+C;X[F]|=ft[(A&3)*2+(b&1)],g[F]++,I[F*3]+=E.red+(i[0]-E.red)*O,I[F*3+1]+=E.green+(i[1]-E.green)*O,I[F*3+2]+=E.blue+(i[2]-E.blue)*O,C<v&&(v=C),C>R&&(R=C),N<L&&(L=N),N>T&&(T=N)}}R>=0&&(this.dirty={minX:v,minY:L,maxX:R,maxY:T}),a>0&&this.renderHalo(a)}renderHalo(t){let e=this.dirty;if(!e)return;let{width:r,height:n,counts:i,rgb:a}=this,c=Math.max(0,e.minX-q),y=Math.min(r-1,e.maxX+q),o=Math.max(0,e.minY-$),f=Math.min(n-1,e.maxY+$),l=y-c+1,M=S(s=>{let p=Array.from({length:s*2+1},(u,_)=>s+1-Math.abs(_-s)),m=p.reduce((u,_)=>u+_,0);return p.map(u=>u/m)},"tent"),h=M(q),d=M($),Y=e.maxY-e.minY+1,x=new Float32Array(Y*l*4);for(let s=e.minY;s<=e.maxY;s++)for(let p=c;p<=y;p++){let m=0,u=0,_=0,k=0;for(let g=-q;g<=q;g++){let I=p+g;if(I<e.minX||I>e.maxX)continue;let v=s*r+I,L=i[v];if(L===0)continue;let R=h[g+q]/8;m+=L*R,u+=a[v*3]*R,_+=a[v*3+1]*R,k+=a[v*3+2]*R}let X=((s-e.minY)*l+(p-c))*4;x[X]=m,x[X+1]=u,x[X+2]=_,x[X+3]=k}for(let s=o;s<=f;s++)for(let p=c;p<=y;p++){let m=0,u=0,_=0,k=0;for(let v=-$;v<=$;v++){let L=s+v;if(L<e.minY||L>e.maxY)continue;let R=d[v+$],T=((L-e.minY)*l+(p-c))*4;m+=x[T]*R,u+=x[T+1]*R,_+=x[T+2]*R,k+=x[T+3]*R}let X=s*r+p,g=i[X];if(g>0&&g/8>m&&(m=g/8,u=a[X*3]/g*m,_=a[X*3+1]/g*m,k=a[X*3+2]/g*m),m<=0)continue;let I=Math.round(t*Math.min(1,m)**.7*Tt)/Tt;I<=0||(this.haloAmount[X]=I,this.haloRgb[X*3]=Math.round(u/m/z)*z,this.haloRgb[X*3+1]=Math.round(_/m/z)*z,this.haloRgb[X*3+2]=Math.round(k/m/z)*z)}this.haloDirty={minX:c,minY:o,maxX:y,maxY:f}}visibleFaces(t,e,r,n,i,a,c){let y=[],o=this.cameraDistance;for(let f of n)for(let l=0;l<3;l++){let M=(l+1)%3,h=(l+2)%3;for(let d of[-1,1]){let Y=d>0?f.max[l]:f.min[l];if((e[l]-Y)*d<=0||n.some(T=>T!==f&&(d>0?T.min[l]:T.max[l])===Y&&T.min[M]<=f.min[M]&&T.max[M]>=f.max[M]&&T.min[h]<=f.min[h]&&T.max[h]>=f.max[h]))continue;let x=1/0,s=1/0,p=-1/0,m=-1/0,u=[0,0,0];for(let T of[f.min[M],f.max[M]])for(let A of[f.min[h],f.max[h]]){u[l]=Y,u[M]=T,u[h]=A;let w=t[0]*u[0]+t[1]*u[1]+t[2]*u[2],b=t[3]*u[0]+t[4]*u[1]+t[5]*u[2],D=t[6]*u[0]+t[7]*u[1]+t[8]*u[2],E=r.scale*o/(o-D),O=r.centerX+w*E,C=r.centerY+b*E;x=Math.min(x,O),s=Math.min(s,C),p=Math.max(p,O),m=Math.max(m,C)}let _={minX:Math.max(0,Math.floor(x)),minY:Math.max(0,Math.floor(s)),maxX:Math.min(i-1,Math.ceil(p)),maxY:Math.min(a-1,Math.ceil(m))};if(_.maxX<_.minX||_.maxY<_.minY)continue;let k=t[l]*d,X=t[3+l]*d,g=t[6+l]*d,I=Math.max(0,k*J[0]+X*J[1]+g*J[2]),v=Math.max(0,k*.8-g*.3),L=c?0:Math.max(0,k*dt[0]+X*dt[1]+g*dt[2])**24*.6*255,R=c?Math.min(1,.55+I*.45+v*.1):.45+I*.78+v*.25;y.push({axis:l,plane:Y,uMin:f.min[M],uMax:f.max[M],vMin:f.min[h],vMax:f.max[h],..._,red:Math.min(255,f.color[0]*R+L),green:Math.min(255,f.color[1]*R+L),blue:Math.min(255,f.color[2]*R+L)})}}return y}},ot=!1;async function we(t,e,r){if(ot)return;ot=!0;let n=await t.queryTerminalColors({timeoutMs:100}),i=G.appearance==="dark",a=S((l,M)=>l?[l.r,l.g,l.b]:M,"toRgbTuple"),c={foreground:a(n.foreground,et(G.colors.text)),background:a(n.background,i?[0,0,0]:[255,255,255])};if(t.hasOverlay()){ot=!1;return}let y=r.kind==="armin"?ae(et(G.colors.accent)):ne({column:r.column,row:r.row}),o=new Nt(t,e,y,c,()=>{ot=!1,f.hide()}),f=t.showOverlay(o,{anchor:"top-left",width:"100%",maxHeight:"100%"})}S(we,"playEasterEgg3d");var Nt=class{static{S(this,"EasterEgg3dAnimation")}tui;screen;model;foreground;background;onDone;startTime=performance.now();lastRender=performance.now();timer;exit;shuffle;screenWidth=-1;screenHeight=-1;stars=[];cells=[];ansiCache=new Map;raster;constructor(t,e,r,n,i){this.tui=t,this.screen=e,this.model=r,this.raster=new _e(r.cameraDistance),this.foreground=n.foreground,this.background=n.background,this.onDone=i,this.timer=setInterval(()=>{this.exit&&this.exitProgress()>=1||performance.now()-this.lastRender>1e3?this.finish():this.tui.requestRender()},oe),this.timer.unref?.()}close(){if(this.exit){this.finish();return}let t=this.elapsed(),e=Ut(t),r=Math.PI*2;this.exit={start:performance.now(),time:t,yaw:e,targetYaw:Math.ceil(e/r)*r,offsets:this.blockOffsets(t)}}handleInput(t){let e=St();(e.matches(t,"tui.select.cancel")||e.matches(t,"app.clear"))&&this.close()}handleMouse(t){return t.type==="click"&&this.close(),{handled:!0,render:!1}}invalidate(){this.screenWidth=-1,this.screenHeight=-1,this.ansiCache.clear()}render(t){let e=Math.max(1,this.tui.terminal.rows),r=this.foreground,n=this.background;this.lastRender=performance.now(),(t!==this.screenWidth||e!==this.screenHeight)&&(this.screenWidth=t,this.screenHeight=e,this.cells=this.prepareCells(t,r),this.stars=this.prepareStars(t,e));let i,a,c,y,o;if(this.exit){let g=this.exitProgress(),I=Z(g/.8),v=1-U(I);i=Math.min(this.exit.time,vt)*(1-g),a=this.pose(t,e,this.flyProgress(this.exit.time)*v,this.exit.time),a.yaw=this.exit.yaw+(this.exit.targetYaw-this.exit.yaw)*xe(I),a.pitch*=v,a.roll*=v,c=this.hintAlpha(this.exit.time)*(1-U(g/.2)),y=this.starAlpha(this.exit.time)*(1-U(g/.3));let L=1-U(g/.5);o=this.exit.offsets.map(([R,T,A])=>[R*L,T*L,A*L])}else{let g=this.elapsed();i=g,a=this.pose(t,e,this.flyProgress(g),g),c=this.hintAlpha(g),y=this.starAlpha(g),o=this.blockOffsets(g)}let{columns:f,rows:l}=this.model,M=this.model.blocks.map((g,I)=>{let[v,L,R]=o[I],T=g.home[0]-f/2+v,A=g.home[1]-l/2+L;return{min:[T,A,R-it/2],max:[T+1,A+1,R+it/2],color:g.color}}),h=this.raster;h.render(t,e,a,M,n,kt(n)?de:0);let d=S((g,I)=>{let v=h.haloAmount[g];if(v<=0)return I;let L=h.haloRgb;return V(I??n,[L[g*3],L[g*3+1],L[g*3+2]],v)},"halo"),Y=U(i/he),x=U(i/.6)*.3,s=i<vt||Y<1,p=this.hint(t,e,c,n),m=Math.floor(i*14),u=this.elapsed(),_=Math.round(y*Lt)/Lt,k=S(g=>{if(_<=0)return;let I=this.stars[g];if(!I)return;let v=Math.round((.5+.5*Math.sin(u*I.speed+I.phase))*Xt)/Xt;return{text:I.glyph,fg:V(n,V(r,I.tint,.5),I.strength*(.7+.3*v)*_)}},"starfield"),X=[];for(let g=0;g<e;g++){let I=this.cells[g]??[],v="",L=-1,R=-1,T=S((A,w,b)=>{let D=w?this.pack(w):-1,E=b?this.pack(b):-1;D!==L&&A!==" "&&(v+=w?this.ansi(D,!1):"\x1B[39m",L=D),E!==R&&(v+=b?this.ansi(E,!0):"\x1B[49m",R=E),v+=A},"emit");for(let A=0;A<t;A++){let w=g*t+A,b=s?I[A]:void 0,D=d(w,b?.bg&&Y<1?V(b.bg,n,Y):void 0);if(p&&g===p.row&&A>=p.start&&A<p.start+p.text.length){let P=A-p.start;T(p.text[P],P<p.keyLength?p.keyColor:p.color,D);continue}let E=h.bits[w];if(E){let P=z*h.counts[w],H=h.rgb,B=[Math.round(H[w*3]/P)*z,Math.round(H[w*3+1]/P)*z,Math.round(H[w*3+2]/P)*z];T(ut[E],B,D);continue}if(!b){let P=k(w);T(P?.text??" ",P?.fg,D);continue}let O=(i-b.delay)/wt;if(O<0&&b.width===2&&!h.bits[w+1]){T(b.text,V(b.fg,n,x),D),A++;continue}if(O<0&&b.width===1){T(b.text,V(b.fg,n,x),D);continue}let C=O<0?b.ink:Math.round(b.ink*(1-Z(O)));if(C<=0){let P=k(w);T(P?.text??" ",P?.fg,D);continue}let N=0,F=0;for(let P=0;F<C&&P<32;P++){let H=ft[Math.floor(tt(b.seed*7919+m*131+P)*8)];N&H||(N|=H,F++)}let ht=x+(1-x)*Z(O)**.8;T(ut[N],V(b.fg,n,ht),D)}X.push(`${v}\x1B[0m`)}return X}elapsed(){return(performance.now()-this.startTime)/1e3}exitProgress(){return this.exit?Z((performance.now()-this.exit.start)/1e3/ce):0}finish(){this.timer&&(clearInterval(this.timer),this.timer=void 0,this.onDone())}blockOffsets(t){let e=this.model.blocks,r=S(()=>e.map(()=>[0,0,0]),"home");if(t<at)return r();let n=Math.floor((t-at)/mt),i=t-at-n*mt;this.shuffle?.cycle!==n&&(this.shuffle={cycle:n,steps:se(this.model,n)});let a=this.shuffle.steps,c=S((o,f)=>{let l=e[f].home;return[o[0]-l[0],o[1]-l[1],o[2]-l[2]]},"offset"),y=K*Q;if(i<y){let o=Math.floor(i/K),f=U((i-o*K)/K);return a[o].map((l,M)=>{let h=c(l,M),d=c(a[o+1][M],M);return[h[0]+(d[0]-h[0])*f,h[1]+(d[1]-h[1])*f,h[2]+(d[2]-h[2])*f]})}if(i<y+lt){let o=(i-y)/lt,f=1-U(o),l=Math.sin(Math.PI*Z(o))*.8;return a[Q].map((M,h)=>{let[d,Y,x]=c(M,h);return[d*f,Y*f,x*f+(h%2===0?l:-l)]})}return r()}flyProgress(t){return U((t-W)/nt)}starAlpha(t){return U((t-me)/fe)}hintAlpha(t){return U((t-W-nt)/ge)}pose(t,e,r,n){let{columns:i,rows:a,cameraDistance:c,radius:y,widthShare:o,origin:f}=this.model,l=y*(c/(c-y)),M=f?2*(c-it/2)/c:jt,h=Math.max(M,Math.min(t*2*o,(e*4-8)*.48)/l),d=t,Y=e*2-2,x=f?f.column*2+i:d,s=f?f.row*4+a:Y;return{centerX:x+(d-x)*r,centerY:s+(Y-s)*r,scale:M*(h/M)**r,yaw:Ut(n),pitch:.3*Math.sin(gt(n))*r,roll:.06*Math.sin(2*gt(n))*r}}hint(t,e,r,n){if(r<=0)return;let i=Kt(St().getKeys("tui.select.cancel")[0]??"escape"),a=`${i} to return`;if(!(a.length>t))return{row:e-2,start:Math.floor((t-a.length)/2),text:a,keyLength:i.length,keyColor:V(n,et(G.colors.muted),r),color:V(n,et(G.colors.dim),r)}}prepareStars(t,e){let r=new Array(t*e);for(let n=0;n<t*e;n++){if(tt(n*3+20973)>=ue)continue;let i=S(a=>tt(n*7+a*40503),"random");r[n]={glyph:ut[ft[Math.floor(i(1)*8)]],tint:It[Math.floor(i(2)*It.length)],strength:.1+i(3)*.12,phase:i(4)*Math.PI*2,speed:.4+i(5)*.8}}return r}prepareCells(t,e){let r=ye(this.screen,t,e,this.background),n=Math.max(1,this.tui.terminal.rows),{columns:i,rows:a,origin:c}=this.model,y=c?c.column+i/2:t/2,o=c?c.row+a/4:n/2,f=Math.hypot(Math.max(y,t-y),Math.max(o,n-o)*2);for(let l=0;l<r.length;l++){let M=r[l];for(let h=0;h<M.length;h++){let d=M[h],Y=d.width===0?M[h-1]:d,x=tt(l*65537+h);if(d.width!==0){let s=Math.hypot(h-y,(l-o)*2)/f;d.delay=W+s*Et+x*Rt}else d.delay=Y.delay;d.seed=l*65537+h,d.ink=pe(Y.text,x)}}if(c)for(let l=c.row;l<c.row+Math.ceil(a/2);l++){let M=r[l];if(M)for(let h=c.column;h<c.column+i;h++){let d=M[h];d&&(d.text=" ",d.width=1,d.ink=0,d.bg=void 0)}}return r}pack(t){return Math.round(t[0])<<16|Math.round(t[1])<<8|Math.round(t[2])}ansi(t,e){let r=t*2+(e?1:0),n=this.ansiCache.get(r);if(n===void 0){let i=$t(t>>16&255,t>>8&255,t&255),a=G.getColorMode();n=e?Wt(i,a):Gt(i,a),this.ansiCache.set(r,n)}return n}};export{Nt as EasterEgg3dAnimation,we as playEasterEgg3d};
|
|
1
|
+
var Ft=Object.defineProperty;var S=(t,e)=>Ft(t,"name",{value:e,configurable:!0});import{createRequire as Ht}from"node:module";const ve=Ht(import.meta.url);import{ARMIN_HEIGHT as zt,ARMIN_WIDTH as Vt,isArminPixel as Zt}from"./chunk-LGD3AMTG.js";import{backgroundAnsi as Wt,colorToRgb as Bt,foregroundAnsi as Gt,formatKeyText as Kt,getKeybindings as St,indexedColor as qt,rgbColor as $t,theme as G,visibleWidth as Jt}from"./chunk-NRQYSXAU.js";import"./chunk-6QGV3IWD.js";import"./chunk-QM5JU2GS.js";import"./chunk-5AGIVGSV.js";import"./chunk-JXWJOIH4.js";var it=.7,W=.1,nt=1.3,jt=.1;function Yt(t,e,r,n){let i=[];for(let a=0;a<e;a++)for(let c=0;c<t;c++){let y=r(c,a);y&&i.push({home:[c,a,0],color:y})}return{columns:t,rows:e,blocks:i,cameraDistance:n.cameraDistance,radius:Math.hypot(t/2,e/2,1+it/2),widthShare:n.widthShare,puzzleMoves:S(a=>n.puzzleMoves(a,i.length),"puzzleMoves"),origin:n.origin}}S(Yt,"createModel");var Qt=[228,138,122],te=[79,142,179],ee=[234,182,93],re=["ccc.","b.c.","bb.y","b..y"],ie={c:Qt,b:te,y:ee};function ne(t){return Yt(4,4,(e,r)=>ie[re[r][e]],{cameraDistance:10,widthShare:.35,puzzleMoves:S(e=>e<.4?2:1,"puzzleMoves"),origin:t})}S(ne,"piLogoModel");function ae(t){return Yt(Vt,zt,(e,r)=>Zt(e,r)?t:void 0,{cameraDistance:80,widthShare:.45,puzzleMoves:S((e,r)=>Math.round(r*(.03+e*.04)),"puzzleMoves"),origin:void 0})}S(ae,"arminModel");var at=W+nt+3,K=.3,Q=12,lt=1,_t=.6,mt=K*Q+lt+_t,le=[[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]];function se(t,e){let{columns:r,rows:n}=t,i=t.blocks.map(l=>l.home),a=[i],c=new Set,y=e*7919+1,o=S(()=>tt(y++),"next"),f=S(([l,M,h])=>((h+1)*n+M)*r+l,"key");for(let l=0;l<Q;l++){let M=new Set(i.map(f)),h=[...i],d=new Set,Y=t.puzzleMoves(o());for(let x=0;x<Y;x++){let s=[];for(let _=0;_<i.length;_++){if(d.has(_))continue;let[k,X,g]=i[_];for(let[I,v,L]of le){let R=[k+I,X+v,g+L];R[0]<0||R[0]>=r||R[1]<0||R[1]>=n||R[2]<-1||R[2]>1||M.has(f(R))||s.push({block:_,target:R})}}let p=s.filter(_=>!c.has(_.block)),m=p.length>0?p:s,u=m[Math.floor(o()*m.length)];if(!u)break;M.add(f(u.target)),h[u.block]=u.target,d.add(u.block)}c.clear();for(let x of d)c.add(x);i=h,a.push(i)}return a}S(se,"shuffleSteps");var oe=1e3/30,wt=.35,Et=.55,Rt=.12,vt=W+Et+Rt+wt,he=.5,ce=1.1,me=2.5,fe=2,ue=.018,It=[[255,255,255],[170,195,255],[255,225,170],[255,190,205]],z=5,de=.3,q=6,$=3,Tt=32,Lt=8,Xt=3,ge=.5,ft=[1,8,2,16,4,32,64,128],ut=Array.from({length:256},(t,e)=>String.fromCharCode(10240+e)),J=Dt([-.45,-.6,.75]),dt=Dt([J[0],J[1],J[2]+1]);function Dt(t){let e=Math.hypot(t[0],t[1],t[2]);return[t[0]/e,t[1]/e,t[2]/e]}S(Dt,"normalize");function Z(t){return t<0?0:t>1?1:t}S(Z,"clamp01");function U(t){let e=Z(t);return e*e*e*(e*(e*6-15)+10)}S(U,"smooth");function xe(t){let e=1-Z(t);return 1-e*e*e}S(xe,"easeOut");function V(t,e,r){return[t[0]+(e[0]-t[0])*r,t[1]+(e[1]-t[1])*r,t[2]+(e[2]-t[2])*r]}S(V,"mix");function tt(t){let e=Math.imul(t^2654435769,2246822507);return e^=e>>>13,e=Math.imul(e,3266489909),e^=e>>>16,(e>>>0)/4294967296}S(tt,"hash");function kt([t,e,r]){return .2126*t+.7152*e+.0722*r>128}S(kt,"isLight");function et(t){let{r:e,g:r,b:n}=Bt(t);return[e,r,n]}S(et,"toRgb");function pe(t,e){return t.trim()===""?0:/^[.,:;'`\-_·]$/.test(t)?2:/^[\u2500-\u257f]$/.test(t)?3:4+Math.floor(e*3)}S(pe,"glyphInk");var Me=new Intl.Segmenter;function ye(t,e,r,n){let i=S(a=>et(qt(a)),"palette");return t.map(a=>{let c=[],y,o,f=!1,l=!1,M=S(Y=>{let x=Y===""?["0"]:Y.split(";");for(let s=0;s<x.length;s++){let p=x[s].split(":").map(u=>Number.parseInt(u,10)),m=p[0]??0;if(m===38||m===48){let u;if(p.length>1)u=p.slice(1).filter(k=>!Number.isNaN(k));else{let k=Number.parseInt(x[s+1]??"",10),X=k===5?2:k===2?4:1;u=x.slice(s+1,s+1+X).map(g=>Number.parseInt(g,10)),s+=X}let _;u[0]===5&&u[1]!==void 0?_=i(u[1]):u[0]===2&&u.length>=4&&(_=[u[1],u[2],u[3]]),_&&(m===38?y=_:o=_)}else m===0?(y=void 0,o=void 0,f=!1,l=!1):m===2?f=!0:m===22?f=!1:m===7?l=!0:m===27?l=!1:m>=30&&m<=37?y=i(m-30):m>=90&&m<=97?y=i(m-90+8):m===39?y=void 0:m>=40&&m<=47?o=i(m-40):m>=100&&m<=107?o=i(m-100+8):m===49&&(o=void 0)}},"applySgr"),h=S(Y=>{for(let{segment:x}of Me.segment(Y)){let s=Jt(x);if(s===0||c.length+s>e)continue;let p=y??r,m=o;l&&(p=o??n,m=y??r),f&&(p=V(p,m??n,.4));let u={text:x,width:s,fg:p,bg:m,delay:0,ink:0,seed:0};c.push(u),s===2&&c.push({...u,text:"",width:0})}},"pushText"),d=0;for(;d<a.length;){let Y=a.indexOf("\x1B",d);if(Y===-1){h(a.slice(d));break}Y>d&&h(a.slice(d,Y));let x=a[Y+1];if(x==="["){let s=Y+2;for(;s<a.length&&(a.charCodeAt(s)<64||a.charCodeAt(s)>126);)s++;a[s]==="m"&&M(a.slice(Y+2,s)),d=s+1}else if(x==="]"||x==="_"||x==="P"||x==="^"){let s=a.indexOf("\x07",Y+2),p=a.indexOf("\x1B\\",Y+2);if(s===-1&&p===-1)break;d=s!==-1&&(p===-1||s<p)?s+1:p+2}else d=Y+2}return c})}S(ye,"parseScreen");function Ae(t,e,r){let[n,i,a,c,y,o]=[Math.sin(t),Math.cos(t),Math.sin(e),Math.cos(e),Math.sin(r),Math.cos(r)],f=[i,0,n,0,1,0,-n,0,i],l=[1,0,0,0,c,-a,0,a,c],M=[o,-y,0,y,o,0,0,0,1];return Pt(M,Pt(l,f))}S(Ae,"rotation");function Pt(t,e){let r=new Array(9);for(let n=0;n<3;n++)for(let i=0;i<3;i++)r[n*3+i]=t[n*3]*e[i]+t[n*3+1]*e[3+i]+t[n*3+2]*e[6+i];return r}S(Pt,"multiply");var st=1.4,Ot=Math.PI*2/mt,be=.6,Se=at+K*Q+lt+_t/2;function Ct(t){let e=t-W;if(e<=0)return 0;let r=e/st;return r<1?Ot*st*(r**6-3*r**5+2.5*r**4):Ot*(st*.5+e-st)}S(Ct,"baseSpinPhase");var Ye=Math.PI*2-Ct(Se)%(Math.PI*2);function gt(t){return Ct(t)+Ye*U((t-W)/nt)}S(gt,"spinPhase");function Ut(t){let e=gt(t);return e-be*Math.sin(e)}S(Ut,"spinAngle");var _e=class{static{S(this,"BlockRaster")}bits=new Uint8Array(0);counts=new Uint8Array(0);rgb=new Float32Array(0);haloAmount=new Float32Array(0);haloRgb=new Float32Array(0);width=0;height=0;depth=new Float32Array(0);faceIds=new Uint16Array(0);dirty;haloDirty;cameraDistance;constructor(t){this.cameraDistance=t}render(t,e,r,n,i,a){let c=t*2,y=e*4;if(t!==this.width||e!==this.height)this.width=t,this.height=e,this.bits=new Uint8Array(t*e),this.counts=new Uint8Array(t*e),this.rgb=new Float32Array(t*e*3),this.haloAmount=new Float32Array(t*e),this.haloRgb=new Float32Array(t*e*3),this.haloDirty=void 0,this.depth=new Float32Array(c*y).fill(1/0),this.faceIds=new Uint16Array(c*y),this.dirty=void 0;else if(this.dirty){let{minX:A,minY:w,maxX:b,maxY:D}=this.dirty;for(let E=w;E<=D;E++)this.bits.fill(0,E*t+A,E*t+b+1),this.counts.fill(0,E*t+A,E*t+b+1),this.rgb.fill(0,(E*t+A)*3,(E*t+b+1)*3);this.dirty=void 0}if(this.haloDirty){let{minX:A,minY:w,maxX:b,maxY:D}=this.haloDirty;for(let E=w;E<=D;E++)this.haloAmount.fill(0,E*t+A,E*t+b+1),this.haloRgb.fill(0,(E*t+A)*3,(E*t+b+1)*3);this.haloDirty=void 0}let o=Ae(r.yaw,r.pitch,r.roll),{centerX:f,centerY:l,scale:M}=r,h=this.cameraDistance,d=[o[6]*h,o[7]*h,o[8]*h],Y=kt(i),x=this.visibleFaces(o,d,r,n,c,y,Y);if(x.length===0)return;let s=c,p=y,m=-1,u=-1;for(let A of x)s=Math.min(s,A.minX),p=Math.min(p,A.minY),m=Math.max(m,A.maxX),u=Math.max(u,A.maxY);if(m<s||u<p)return;let _=this.depth,k=this.faceIds;for(let A=0;A<x.length;A++){let w=x[A],b=w.axis,D=(b+1)%3,E=(b+2)%3,O=d[b],C=d[D],N=d[E],F=o[b]/M,ht=o[D]/M,P=o[E]/M,H=(w.minX+.5-f)/M;for(let B=w.minY;B<=w.maxY;B++){let ct=(B+.5-l)/M,xt=o[b]*H+o[3+b]*ct-o[6+b]*h,pt=o[D]*H+o[3+D]*ct-o[6+D]*h,Mt=o[E]*H+o[3+E]*ct-o[6+E]*h,rt=B*c+w.minX;for(let yt=w.minX;yt<=w.maxX;yt++,rt++){let j=(w.plane-O)/xt;if(j>0&&j<_[rt]){let At=C+j*pt,bt=N+j*Mt;At>=w.uMin&&At<=w.uMax&&bt>=w.vMin&&bt<=w.vMax&&(_[rt]=j,k[rt]=A+1)}xt+=F,pt+=ht,Mt+=P}}}let X=this.bits,g=this.counts,I=this.rgb,v=t,L=e,R=-1,T=-1;for(let A=p;A<=u;A++){let w=A*c+s;for(let b=s;b<=m;b++,w++){let D=k[w];if(D===0)continue;let E=x[D-1],O=Z(.15-h*(1-_[w])*.12)*(Y?.5:1);k[w]=0,_[w]=1/0;let C=b>>1,N=A>>2,F=N*t+C;X[F]|=ft[(A&3)*2+(b&1)],g[F]++,I[F*3]+=E.red+(i[0]-E.red)*O,I[F*3+1]+=E.green+(i[1]-E.green)*O,I[F*3+2]+=E.blue+(i[2]-E.blue)*O,C<v&&(v=C),C>R&&(R=C),N<L&&(L=N),N>T&&(T=N)}}R>=0&&(this.dirty={minX:v,minY:L,maxX:R,maxY:T}),a>0&&this.renderHalo(a)}renderHalo(t){let e=this.dirty;if(!e)return;let{width:r,height:n,counts:i,rgb:a}=this,c=Math.max(0,e.minX-q),y=Math.min(r-1,e.maxX+q),o=Math.max(0,e.minY-$),f=Math.min(n-1,e.maxY+$),l=y-c+1,M=S(s=>{let p=Array.from({length:s*2+1},(u,_)=>s+1-Math.abs(_-s)),m=p.reduce((u,_)=>u+_,0);return p.map(u=>u/m)},"tent"),h=M(q),d=M($),Y=e.maxY-e.minY+1,x=new Float32Array(Y*l*4);for(let s=e.minY;s<=e.maxY;s++)for(let p=c;p<=y;p++){let m=0,u=0,_=0,k=0;for(let g=-q;g<=q;g++){let I=p+g;if(I<e.minX||I>e.maxX)continue;let v=s*r+I,L=i[v];if(L===0)continue;let R=h[g+q]/8;m+=L*R,u+=a[v*3]*R,_+=a[v*3+1]*R,k+=a[v*3+2]*R}let X=((s-e.minY)*l+(p-c))*4;x[X]=m,x[X+1]=u,x[X+2]=_,x[X+3]=k}for(let s=o;s<=f;s++)for(let p=c;p<=y;p++){let m=0,u=0,_=0,k=0;for(let v=-$;v<=$;v++){let L=s+v;if(L<e.minY||L>e.maxY)continue;let R=d[v+$],T=((L-e.minY)*l+(p-c))*4;m+=x[T]*R,u+=x[T+1]*R,_+=x[T+2]*R,k+=x[T+3]*R}let X=s*r+p,g=i[X];if(g>0&&g/8>m&&(m=g/8,u=a[X*3]/g*m,_=a[X*3+1]/g*m,k=a[X*3+2]/g*m),m<=0)continue;let I=Math.round(t*Math.min(1,m)**.7*Tt)/Tt;I<=0||(this.haloAmount[X]=I,this.haloRgb[X*3]=Math.round(u/m/z)*z,this.haloRgb[X*3+1]=Math.round(_/m/z)*z,this.haloRgb[X*3+2]=Math.round(k/m/z)*z)}this.haloDirty={minX:c,minY:o,maxX:y,maxY:f}}visibleFaces(t,e,r,n,i,a,c){let y=[],o=this.cameraDistance;for(let f of n)for(let l=0;l<3;l++){let M=(l+1)%3,h=(l+2)%3;for(let d of[-1,1]){let Y=d>0?f.max[l]:f.min[l];if((e[l]-Y)*d<=0||n.some(T=>T!==f&&(d>0?T.min[l]:T.max[l])===Y&&T.min[M]<=f.min[M]&&T.max[M]>=f.max[M]&&T.min[h]<=f.min[h]&&T.max[h]>=f.max[h]))continue;let x=1/0,s=1/0,p=-1/0,m=-1/0,u=[0,0,0];for(let T of[f.min[M],f.max[M]])for(let A of[f.min[h],f.max[h]]){u[l]=Y,u[M]=T,u[h]=A;let w=t[0]*u[0]+t[1]*u[1]+t[2]*u[2],b=t[3]*u[0]+t[4]*u[1]+t[5]*u[2],D=t[6]*u[0]+t[7]*u[1]+t[8]*u[2],E=r.scale*o/(o-D),O=r.centerX+w*E,C=r.centerY+b*E;x=Math.min(x,O),s=Math.min(s,C),p=Math.max(p,O),m=Math.max(m,C)}let _={minX:Math.max(0,Math.floor(x)),minY:Math.max(0,Math.floor(s)),maxX:Math.min(i-1,Math.ceil(p)),maxY:Math.min(a-1,Math.ceil(m))};if(_.maxX<_.minX||_.maxY<_.minY)continue;let k=t[l]*d,X=t[3+l]*d,g=t[6+l]*d,I=Math.max(0,k*J[0]+X*J[1]+g*J[2]),v=Math.max(0,k*.8-g*.3),L=c?0:Math.max(0,k*dt[0]+X*dt[1]+g*dt[2])**24*.6*255,R=c?Math.min(1,.55+I*.45+v*.1):.45+I*.78+v*.25;y.push({axis:l,plane:Y,uMin:f.min[M],uMax:f.max[M],vMin:f.min[h],vMax:f.max[h],..._,red:Math.min(255,f.color[0]*R+L),green:Math.min(255,f.color[1]*R+L),blue:Math.min(255,f.color[2]*R+L)})}}return y}},ot=!1;async function we(t,e,r){if(ot)return;ot=!0;let n=await t.queryTerminalColors({timeoutMs:100}),i=G.appearance==="dark",a=S((l,M)=>l?[l.r,l.g,l.b]:M,"toRgbTuple"),c={foreground:a(n.foreground,et(G.colors.text)),background:a(n.background,i?[0,0,0]:[255,255,255])};if(t.hasOverlay()){ot=!1;return}let y=r.kind==="armin"?ae(et(G.colors.accent)):ne({column:r.column,row:r.row}),o=new Nt(t,e,y,c,()=>{ot=!1,f.hide()}),f=t.showOverlay(o,{anchor:"top-left",width:"100%",maxHeight:"100%"})}S(we,"playEasterEgg3d");var Nt=class{static{S(this,"EasterEgg3dAnimation")}tui;screen;model;foreground;background;onDone;startTime=performance.now();lastRender=performance.now();timer;exit;shuffle;screenWidth=-1;screenHeight=-1;stars=[];cells=[];ansiCache=new Map;raster;constructor(t,e,r,n,i){this.tui=t,this.screen=e,this.model=r,this.raster=new _e(r.cameraDistance),this.foreground=n.foreground,this.background=n.background,this.onDone=i,this.timer=setInterval(()=>{this.exit&&this.exitProgress()>=1||performance.now()-this.lastRender>1e3?this.finish():this.tui.requestRender()},oe),this.timer.unref?.()}close(){if(this.exit){this.finish();return}let t=this.elapsed(),e=Ut(t),r=Math.PI*2;this.exit={start:performance.now(),time:t,yaw:e,targetYaw:Math.ceil(e/r)*r,offsets:this.blockOffsets(t)}}handleInput(t){let e=St();(e.matches(t,"tui.select.cancel")||e.matches(t,"app.clear"))&&this.close()}handleMouse(t){return t.type==="click"&&this.close(),{handled:!0,render:!1}}invalidate(){this.screenWidth=-1,this.screenHeight=-1,this.ansiCache.clear()}render(t){let e=Math.max(1,this.tui.terminal.rows),r=this.foreground,n=this.background;this.lastRender=performance.now(),(t!==this.screenWidth||e!==this.screenHeight)&&(this.screenWidth=t,this.screenHeight=e,this.cells=this.prepareCells(t,r),this.stars=this.prepareStars(t,e));let i,a,c,y,o;if(this.exit){let g=this.exitProgress(),I=Z(g/.8),v=1-U(I);i=Math.min(this.exit.time,vt)*(1-g),a=this.pose(t,e,this.flyProgress(this.exit.time)*v,this.exit.time),a.yaw=this.exit.yaw+(this.exit.targetYaw-this.exit.yaw)*xe(I),a.pitch*=v,a.roll*=v,c=this.hintAlpha(this.exit.time)*(1-U(g/.2)),y=this.starAlpha(this.exit.time)*(1-U(g/.3));let L=1-U(g/.5);o=this.exit.offsets.map(([R,T,A])=>[R*L,T*L,A*L])}else{let g=this.elapsed();i=g,a=this.pose(t,e,this.flyProgress(g),g),c=this.hintAlpha(g),y=this.starAlpha(g),o=this.blockOffsets(g)}let{columns:f,rows:l}=this.model,M=this.model.blocks.map((g,I)=>{let[v,L,R]=o[I],T=g.home[0]-f/2+v,A=g.home[1]-l/2+L;return{min:[T,A,R-it/2],max:[T+1,A+1,R+it/2],color:g.color}}),h=this.raster;h.render(t,e,a,M,n,kt(n)?de:0);let d=S((g,I)=>{let v=h.haloAmount[g];if(v<=0)return I;let L=h.haloRgb;return V(I??n,[L[g*3],L[g*3+1],L[g*3+2]],v)},"halo"),Y=U(i/he),x=U(i/.6)*.3,s=i<vt||Y<1,p=this.hint(t,e,c,n),m=Math.floor(i*14),u=this.elapsed(),_=Math.round(y*Lt)/Lt,k=S(g=>{if(_<=0)return;let I=this.stars[g];if(!I)return;let v=Math.round((.5+.5*Math.sin(u*I.speed+I.phase))*Xt)/Xt;return{text:I.glyph,fg:V(n,V(r,I.tint,.5),I.strength*(.7+.3*v)*_)}},"starfield"),X=[];for(let g=0;g<e;g++){let I=this.cells[g]??[],v="",L=-1,R=-1,T=S((A,w,b)=>{let D=w?this.pack(w):-1,E=b?this.pack(b):-1;D!==L&&A!==" "&&(v+=w?this.ansi(D,!1):"\x1B[39m",L=D),E!==R&&(v+=b?this.ansi(E,!0):"\x1B[49m",R=E),v+=A},"emit");for(let A=0;A<t;A++){let w=g*t+A,b=s?I[A]:void 0,D=d(w,b?.bg&&Y<1?V(b.bg,n,Y):void 0);if(p&&g===p.row&&A>=p.start&&A<p.start+p.text.length){let P=A-p.start;T(p.text[P],P<p.keyLength?p.keyColor:p.color,D);continue}let E=h.bits[w];if(E){let P=z*h.counts[w],H=h.rgb,B=[Math.round(H[w*3]/P)*z,Math.round(H[w*3+1]/P)*z,Math.round(H[w*3+2]/P)*z];T(ut[E],B,D);continue}if(!b){let P=k(w);T(P?.text??" ",P?.fg,D);continue}let O=(i-b.delay)/wt;if(O<0&&b.width===2&&!h.bits[w+1]){T(b.text,V(b.fg,n,x),D),A++;continue}if(O<0&&b.width===1){T(b.text,V(b.fg,n,x),D);continue}let C=O<0?b.ink:Math.round(b.ink*(1-Z(O)));if(C<=0){let P=k(w);T(P?.text??" ",P?.fg,D);continue}let N=0,F=0;for(let P=0;F<C&&P<32;P++){let H=ft[Math.floor(tt(b.seed*7919+m*131+P)*8)];N&H||(N|=H,F++)}let ht=x+(1-x)*Z(O)**.8;T(ut[N],V(b.fg,n,ht),D)}X.push(`${v}\x1B[0m`)}return X}elapsed(){return(performance.now()-this.startTime)/1e3}exitProgress(){return this.exit?Z((performance.now()-this.exit.start)/1e3/ce):0}finish(){this.timer&&(clearInterval(this.timer),this.timer=void 0,this.onDone())}blockOffsets(t){let e=this.model.blocks,r=S(()=>e.map(()=>[0,0,0]),"home");if(t<at)return r();let n=Math.floor((t-at)/mt),i=t-at-n*mt;this.shuffle?.cycle!==n&&(this.shuffle={cycle:n,steps:se(this.model,n)});let a=this.shuffle.steps,c=S((o,f)=>{let l=e[f].home;return[o[0]-l[0],o[1]-l[1],o[2]-l[2]]},"offset"),y=K*Q;if(i<y){let o=Math.floor(i/K),f=U((i-o*K)/K);return a[o].map((l,M)=>{let h=c(l,M),d=c(a[o+1][M],M);return[h[0]+(d[0]-h[0])*f,h[1]+(d[1]-h[1])*f,h[2]+(d[2]-h[2])*f]})}if(i<y+lt){let o=(i-y)/lt,f=1-U(o),l=Math.sin(Math.PI*Z(o))*.8;return a[Q].map((M,h)=>{let[d,Y,x]=c(M,h);return[d*f,Y*f,x*f+(h%2===0?l:-l)]})}return r()}flyProgress(t){return U((t-W)/nt)}starAlpha(t){return U((t-me)/fe)}hintAlpha(t){return U((t-W-nt)/ge)}pose(t,e,r,n){let{columns:i,rows:a,cameraDistance:c,radius:y,widthShare:o,origin:f}=this.model,l=y*(c/(c-y)),M=f?2*(c-it/2)/c:jt,h=Math.max(M,Math.min(t*2*o,(e*4-8)*.48)/l),d=t,Y=e*2-2,x=f?f.column*2+i:d,s=f?f.row*4+a:Y;return{centerX:x+(d-x)*r,centerY:s+(Y-s)*r,scale:M*(h/M)**r,yaw:Ut(n),pitch:.3*Math.sin(gt(n))*r,roll:.06*Math.sin(2*gt(n))*r}}hint(t,e,r,n){if(r<=0)return;let i=Kt(St().getKeys("tui.select.cancel")[0]??"escape"),a=`${i} to return`;if(!(a.length>t))return{row:e-2,start:Math.floor((t-a.length)/2),text:a,keyLength:i.length,keyColor:V(n,et(G.colors.muted),r),color:V(n,et(G.colors.dim),r)}}prepareStars(t,e){let r=new Array(t*e);for(let n=0;n<t*e;n++){if(tt(n*3+20973)>=ue)continue;let i=S(a=>tt(n*7+a*40503),"random");r[n]={glyph:ut[ft[Math.floor(i(1)*8)]],tint:It[Math.floor(i(2)*It.length)],strength:.1+i(3)*.12,phase:i(4)*Math.PI*2,speed:.4+i(5)*.8}}return r}prepareCells(t,e){let r=ye(this.screen,t,e,this.background),n=Math.max(1,this.tui.terminal.rows),{columns:i,rows:a,origin:c}=this.model,y=c?c.column+i/2:t/2,o=c?c.row+a/4:n/2,f=Math.hypot(Math.max(y,t-y),Math.max(o,n-o)*2);for(let l=0;l<r.length;l++){let M=r[l];for(let h=0;h<M.length;h++){let d=M[h],Y=d.width===0?M[h-1]:d,x=tt(l*65537+h);if(d.width!==0){let s=Math.hypot(h-y,(l-o)*2)/f;d.delay=W+s*Et+x*Rt}else d.delay=Y.delay;d.seed=l*65537+h,d.ink=pe(Y.text,x)}}if(c)for(let l=c.row;l<c.row+Math.ceil(a/2);l++){let M=r[l];if(M)for(let h=c.column;h<c.column+i;h++){let d=M[h];d&&(d.text=" ",d.width=1,d.ink=0,d.bg=void 0)}}return r}pack(t){return Math.round(t[0])<<16|Math.round(t[1])<<8|Math.round(t[2])}ansi(t,e){let r=t*2+(e?1:0),n=this.ansiCache.get(r);if(n===void 0){let i=$t(t>>16&255,t>>8&255,t&255),a=G.getColorMode();n=e?Wt(i,a):Gt(i,a),this.ansiCache.set(r,n)}return n}};export{Nt as EasterEgg3dAnimation,we as playEasterEgg3d};
|