@dahawa/hawa-code 1.32.0 → 1.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.js +663 -663
- package/hawa.js +2 -2
- package/package.json +1 -1
package/hawa.js
CHANGED
|
@@ -7,6 +7,6 @@ const require = createRequire(import.meta.url);
|
|
|
7
7
|
const __filename = fileURLToPath(import.meta.url);
|
|
8
8
|
const __dirname = dirname(__filename);
|
|
9
9
|
|
|
10
|
-
import re from"os";import G from"path";import P from"fs";var
|
|
10
|
+
import re from"os";import G from"path";import P from"fs";var B="hcode",p=".hcode";var W="HAWA_CODE_GIT_BASH_PATH";var ie={sources:{"qwen-coding":{base_url:"https://dashscope.aliyuncs.com/apps/anthropic",auth_token:"sk-{ \u4F7F\u7528\u81EA\u5DF1\u7684 token }",api_type:"anthropic",models:["qwen3-coder-plus"]},"kimi-k2":{base_url:"https://api.moonshot.cn/anthropic",auth_token:"sk-{ \u4F7F\u7528\u81EA\u5DF1\u7684 token }",api_type:"anthropic",models:["kimi-k2-0905-preview"]},deepseek:{base_url:"https://api.deepseek.com/anthropic",auth_token:"sk-{ \u4F7F\u7528\u81EA\u5DF1\u7684 token }",api_type:"anthropic",models:["deepseek-chat"]},openrouter:{base_url:"https://openrouter.ai/api/v1",auth_token:"sk-or-v1-{ \u4F7F\u7528\u81EA\u5DF1\u7684 token }",api_type:"openai",models:["anthropic/claude-sonnet-4"]},gemini:{base_url:"https://generativelanguage.googleapis.com",auth_token:"AI{ \u4F7F\u7528\u81EA\u5DF1\u7684 token }",api_type:"gemini",models:["gemini-2.5-pro"]}},routing:{MODEL:[{source:"qwen-coding",model:"qwen3-coder-plus",weight:50},{source:"kimi-k2",model:"kimi-k2-0905-preview",weight:50}],SMALL_FAST_MODEL:[{source:"deepseek",model:"deepseek-chat",weight:50},{source:"openrouter",model:"anthropic/claude-sonnet-4",weight:50}]}};function ae(){let n=re.homedir();return G.join(n,p,"config.json")}function $(){let n=ae();P.existsSync(n)||(P.mkdirSync(G.dirname(n),{recursive:!0}),P.writeFileSync(n,JSON.stringify(ie,null,2)))}import{spawn as se}from"child_process";import T from"path";import{fileURLToPath as oe}from"url";import{existsSync as C,readFileSync as Oe,writeFileSync as L,mkdirSync as Me,watch as X}from"fs";import{join as q,dirname as Ee}from"path";import{homedir as be}from"os";import{existsSync as K,mkdirSync as le}from"fs";import{dirname as ue,join as l}from"path";import{writeFileSync as ge,readFileSync as Xe,appendFileSync as pe}from"fs";import{randomUUID as de}from"crypto";import{homedir as fe}from"os";import*as Y from"os";import{randomUUID as ce}from"crypto";var w=class{datas={};setData(e,t){this.datas[e]=t}getData(e){return this.datas[e]}takeData(e){let t=this.datas[e];return delete this.datas[e],t}clear(){this.datas={}}},_=class extends w{startTime;constructor(e=null){super(),this.startTime=e}},J=ce(),v=class extends w{PENDING_PROMPTS_KEY="pendingPrompts";addPendingPrompt(e){let t=this.getPendingPrompts();t.push(e),this.setData(this.PENDING_PROMPTS_KEY,t)}getPendingPrompts(){let e=this.getData(this.PENDING_PROMPTS_KEY);return Array.isArray(e)?e:[]}takePendingPrompts(){let e=this.getPendingPrompts();return this.setData(this.PENDING_PROMPTS_KEY,[]),e}async waitGetPendingPrompts(e){let o=Date.now(),s=e*1e3;for(;Date.now()-o<s;){let r=this.getPendingPrompts();if(r.length>0)return r;await new Promise(i=>setTimeout(i,200))}return[]}getSessionId(){return J}switchSessionId(e){J=e}},R=class n{static sessionContext={};static inQueryContextHolder={};static queryContext={};onQueryStart(e="defalt"){e||(e="defalt");let t=n.inQueryContextHolder[e+""];t&&t.startTime&&t.startTime>0||(n.inQueryContextHolder[e+""]=new _(Date.now()))}onQueryEnd(e="defalt",t=!1){e||(e="defalt"),n.inQueryContextHolder[e+""]=new _(-1),t||(n.queryContext[e+""]={})}getSessionContext(e="defalt"){e||(e="defalt");let t=n.sessionContext[e+""];return t||(t=new v,n.sessionContext[e+""]=t),t}getInQueryContext(e="defalt"){e||(e="defalt");let t=n.inQueryContextHolder[e+""];return t||(t=new _,n.inQueryContextHolder[e+""]=t),t}getQueryContext(e="defalt"){e||(e="defalt");let t=n.queryContext[e+""];return t||(t={},n.queryContext[e+""]=t),t}isQuerying(e="defalt"){return e||(e="defalt"),this.getInQueryContext(e).startTime>0}},z=new R;var st=de(),g=l(fe(),p);function d(n){return n.replace(/[^a-zA-Z0-9]/g,"-")}function me(){return z.getSessionContext().getSessionId()||U}var V={temp:()=>l(Y.tmpdir(),`${B}`),plan:()=>l(g,"plan"),memory:()=>l(g,"projects",d(process.cwd()),"memory"),apis:()=>l(g,"projects",d(process.cwd()),"apis"),errors:()=>l(g,"projects",d(process.cwd()),"errors"),messages:()=>l(g,"projects",d(process.cwd()),"messages"),mcpLogs:n=>l(g,"projects",d(process.cwd()),`mcp-logs-${n}`),log:()=>l(g,"projects",d(process.cwd()),"log"),vcrFixtures:()=>l(g,"projects",d(process.cwd()),"vcr-fixtures"),sessionSummary:()=>l(g,"projects",d(process.cwd()),"messages",me(),"session-summary")};function Se(n){return n.toISOString().replace(/[:.]/g,"-")}var U=Se(new Date);function he(){return l(V.log(),U+".log")}function ye(){return l(V.log(),"error-"+U+".log")}function Q(n,e,...t){let o=t.map(s=>s instanceof Error?`${s.name}: ${s.message}
|
|
11
11
|
${s.stack.replace(/^/gm," ")}`:s);_e(e,{level:n,message:o.length==1?o[0]:o})}function O(...n){Q("info",he(),...n)}function x(...n){Q("error",ye(),...n)}function I(...n){x(...n)}function _e(n,e){let t=ue(n);K(t)||le(t,{recursive:!0});let s=(typeof e=="string"?e:JSON.stringify(e))+`
|
|
12
|
-
`;K(n)?pe(n,s,"utf8"):ge(n,s,"utf8")}var ot=5*1024*1024,rt=1024*1024,it=Buffer.from('"compact_boundary"');var k={env:{},permissions:{allow:[],deny:[],ask:[]},enableAllProjectMcpServers:!1,enabledMcpjsonServers:[],autoCompactEnabled:!0,language:"auto",thinking:"medium",disableSuggestion:!1,autoMemory:{enabled:!0,minTokens:3e3,minTurns:3,teamMemoryEnabled:!1},autoDream:{enabled:!0,minHours:24,minSessions:5}},j=class n{static test=!1;static testSettings;static setSettings(e){n.testSettings=e}static instance;static isTasksEnable(){return process.env.HAWA_CODE_ENABLE_TASKS=="true"||n.isAgentTeamEnable()}static isAgentTeamEnable(){return process.env.HAWA_CODE_EXPERIMENTAL_AGENT_TEAMS=="1"}static isLazyToolEnable(){return process.env.HAWA_CODE_LAZY_TOOL==="true"||process.env.HAWA_CODE_LAZY_TOOL==="1"}static isPowerShellToolEnable(){return process.platform!=="win32"?!1:process.env.HAWA_CODE_POWER_SHELL_ENABLE==="true"||process.env.HAWA_CODE_POWER_SHELL_ENABLE==="1"?!0:!(process.env.HAWA_CODE_POWER_SHELL_ENABLE==="false"||process.env.HAWA_CODE_POWER_SHELL_ENABLE==="0"||process.env[W])}constructor(){this.initializeConfigDirectories()}initializeConfigDirectories(){let e=this.getUserSettingsPath(),t=this.getProjectSettingsPath();this.ensureDirExists(e),C(e)||L(e,JSON.stringify(this.getDefaultSettingsStructure(),null,2),"utf-8"),this.ensureDirExists(t),C(t)||L(t,JSON.stringify(this.getDefaultSettingsStructure(),null,2),"utf-8")}getDefaultSettingsStructure(){return{env:{},permissions:{allow:[],deny:[],ask:[]},autoMode:{enabled:!1,model:"",maxConsecutiveDenials:3,maxTotalDenials:20},thinking:"medium"}}static getInstance(){return n.instance||(n.instance=new n),n.instance}addProjectAllowedTools(e){let t=this.loadSettingsFromFile(this.getProjectSettingsPath()),o=t.permissions||{allow:[],deny:[]};if(o.allow||(o.allow=[]),o.allow.includes(e))O(`\u5DE5\u5177 '${e}' \u5DF2\u5B58\u5728\u4E8E\u9879\u76EE\u5141\u8BB8\u5217\u8868\u4E2D\uFF0C\u65E0\u9700\u91CD\u590D\u6DFB\u52A0`);else{o.allow.push(e),o.allow.sort();let s={...t,permissions:{...o}};this.saveSettingsToFile(this.getProjectSettingsPath(),s,k),O(`\u5DF2\u5C06\u5DE5\u5177 '${e}' \u6DFB\u52A0\u5230\u9879\u76EE\u5141\u8BB8\u5217\u8868`)}}getUserSettingsPath(){return q(be(),".hcode","settings.json")}getProjectSettingsPath(){let e=process.cwd();return q(e,".hcode","settings.json")}ensureDirExists(e){let t=Ee(e);C(t)||Me(t,{recursive:!0})}loadSettingsFromFile(e){if(!C(e))return{};let t="";try{return t=Oe(e,"utf-8"),JSON.parse(t)}catch(o){return console.error(`Error reading settings file ${e} => ${t} `,o),{}}}saveSettingsToFile(e,t,o){let s={...t};for(let[r,i]of Object.entries(t))if(r in o)if(typeof i=="object"&&typeof o[r]=="object"){if(JSON.stringify(i)===JSON.stringify(o[r]))delete s[r];else if(r==="permissions"&&i&&typeof i=="object"){let u=o.permissions||{},a=i;Array.isArray(a.allow)&&Array.isArray(u.allow)&&JSON.stringify(a.allow)===JSON.stringify(u.allow)&&delete a.allow,Array.isArray(a.deny)&&Array.isArray(u.deny)&&JSON.stringify(a.deny)===JSON.stringify(u.deny)&&delete a.deny,Object.keys(a).length===0&&delete s[r]}}else i===o[r]&&delete s[r];this.ensureDirExists(e),Object.keys(s).length===0?L(e,"{}","utf-8"):L(e,JSON.stringify(s,null,2),"utf-8")}mergeStringArrays(e,t){if(!e&&!t)return;let o=[...e||[]];return(t||[]).forEach(s=>{o.includes(s)||o.push(s)}),o}loadSettings(){let e=this.loadSettingsFromFile(this.getUserSettingsPath()),t=this.loadSettingsFromFile(this.getProjectSettingsPath()),o={...e.env,...t.env},s={...e.permissions};if(e.permissions?.allow&&t.permissions?.allow){let a=[...e.permissions.allow];t.permissions.allow.forEach(c=>{a.includes(c)||a.push(c)}),s.allow=a}else t.permissions?.allow&&(s.allow=[...t.permissions.allow]);if(e.permissions?.deny&&t.permissions?.deny){let a=[...e.permissions.deny];t.permissions.deny.forEach(c=>{a.includes(c)||a.push(c)}),s.deny=a}else t.permissions?.deny&&(s.deny=[...t.permissions.deny]);if(e.permissions?.ask&&t.permissions?.ask){let a=[...e.permissions.ask];t.permissions.ask.forEach(c=>{a.includes(c)||a.push(c)}),s.ask=a}else t.permissions?.ask&&(s.ask=[...t.permissions.ask]);let r={...k,...e,...t};o&&Object.keys(o).length>0&&(r.env=o),s&&(s.allow||s.deny||s.ask)&&(r.permissions=s);let i=e.sandbox,u=t.sandbox;if(i||u){let a={...i,...u},c=i?.filesystem,f=u?.filesystem;(c||f)&&(a.filesystem={...c,...f,allowWrite:this.mergeStringArrays(c?.allowWrite,f?.allowWrite),denyWrite:this.mergeStringArrays(c?.denyWrite,f?.denyWrite),denyRead:this.mergeStringArrays(c?.denyRead,f?.denyRead),allowRead:this.mergeStringArrays(c?.allowRead,f?.allowRead)});let h=i?.network,y=u?.network;(h||y)&&(a.network={...h,...y,allowedDomains:this.mergeStringArrays(h?.allowedDomains,y?.allowedDomains),deniedDomains:this.mergeStringArrays(h?.deniedDomains,y?.deniedDomains),allowUnixSockets:this.mergeStringArrays(h?.allowUnixSockets,y?.allowUnixSockets)});let D=i?.ignoreViolations,N=u?.ignoreViolations;if(D||N){let m={};if(D)for(let[S,A]of Object.entries(D))m[S]=[...A];if(N)for(let[S,A]of Object.entries(N))m[S]?m[S]=this.mergeStringArrays(m[S],A)??[]:m[S]=[...A];a.ignoreViolations=m}r.sandbox=a}return r}saveUserSettings(e){let t=this.getUserSettingsPath();this.saveSettingsToFile(t,e,k)}saveProjectSettings(e){let t=this.getProjectSettingsPath();this.saveSettingsToFile(t,e,k)}getSetting(e){return this.loadSettings()[e]}updateSetting(e,t){let s={...this.loadSettings(),[e]:t};this.saveProjectSettings(s)}resetSetting(e){let o={...this.loadSettings()};delete o[e],this.saveProjectSettings(o)}getAllSettings(){return this.loadSettings()}},M=j.getInstance(),Z=M.getAllSettings();function F(){let n=M.getUserSettingsPath(),e=M.getProjectSettingsPath();X(n,(t,o)=>{t==="change"&&(Z=null,O("\u7528\u6237\u7EA7\u914D\u7F6E\u5DF2\u70ED\u52A0\u8F7D"))}).on("error",t=>{x("\u7528\u6237\u7EA7\u914D\u7F6E\u76D1\u63A7\u51FA\u9519:",t),setTimeout(()=>F(),100)}),X(e,(t,o)=>{t==="change"&&(Z=null,O("\u9879\u76EE\u7EA7\u914D\u7F6E\u5DF2\u70ED\u52A0\u8F7D",o))}).on("error",t=>{x("\u9879\u76EE\u7EA7\u914D\u7F6E\u76D1\u63A7\u51FA\u9519:",t),setTimeout(()=>F(),100)})}F();import Te from"os";import Ae from"path";import E from"fs";var we={sources:{},routing:{}};function ne(){let n=Te.homedir();return Ae.join(n,p,"config.json")}function ee(){try{let n=ne();if(!E.existsSync(n))return we;let e=E.readFileSync(n,"utf-8"),t=JSON.parse(e);return t.sources&&t.routing?t:xe(t)}catch(n){throw I(n),n}}function xe(n){let e={},t={};for(let[o,s]of Object.entries(n))if(s?.enable===!0&&s?.env){let r=s.env,i=o;e[i]={base_url:r.BASE_URL||"",auth_token:r.AUTH_TOKEN||"",api_type:r.API_TYPE||"anthropic",models:[]},r.MODEL&&(t.MODEL=[{source:i,model:r.MODEL,weight:100}],e[i].models.push(r.MODEL)),r.SMALL_FAST_MODEL&&(t.SMALL_FAST_MODEL=[{source:i,model:r.SMALL_FAST_MODEL,weight:100}],e[i].models.includes(r.SMALL_FAST_MODEL)||e[i].models.push(r.SMALL_FAST_MODEL));break}return{sources:e,routing:t}}function te(n){if(n.length===0)throw new Error("No items to select from");if(n.length===1)return n[0];let e=n.reduce((o,s)=>o+(s.weight??100),0),t=Math.random()*e;for(let o of n){let s=o.weight??100;if(t-=s,t<=0)return o}return n[n.length-1]}var B=class{config;constructor(){try{this.config=ee()}catch(e){console.log(e)}}reload(){this.config=ee()}getConfig(){return this.config}hasModelRouting(){return!!(this.config.routing?.MODEL&&this.config.routing.MODEL.length>0)}getModelRoutingModels(){let e=this.config.routing?.MODEL;return!e||e.length===0?[]:e.map(t=>t.model)}hasSmallFastModelRouting(){return!!(this.config.routing?.SMALL_FAST_MODEL&&this.config.routing.SMALL_FAST_MODEL.length>0)}getModel(){let e=this.config.routing?.MODEL;if(!e||e.length===0)throw new Error("No MODEL routing configuration found");let t=te(e);return`${t.source}__${t.model}`}getSmallFastModel(){let e=this.config.routing?.SMALL_FAST_MODEL;if(!e||e.length===0)throw new Error("No SMALL_FAST_MODEL routing configuration found");let t=te(e);return`${t.source}__${t.model}`}getSourceConfig(e){return this.config.sources?.[e]}parseModelKey(e){let t=e.indexOf("__");return t===-1?{source:"",model:e}:{source:e.slice(0,t),model:e.slice(t+2)}}getModelSourceConfig(e){let{source:t}=this.parseModelKey(e);if(t)return this.getSourceConfig(t)}setModelRouting(e){this.config.routing.MODEL=e,this.saveConfig()}setSmallFastModelRouting(e){this.config.routing.SMALL_FAST_MODEL=e,this.saveConfig()}getAvailableModels(){let e=[];for(let[t,o]of Object.entries(this.config.sources||{}))for(let s of o.models||[])e.push(`${t}__${s}`);return e}saveConfig(){try{let e=ne(),t={};if(E.existsSync(e)){let s=E.readFileSync(e,"utf-8");t=JSON.parse(s)}let o={...t,sources:this.config.sources,routing:this.config.routing};E.writeFileSync(e,JSON.stringify(o,null,2))}catch(e){I(e)}}},b=new B;import Ce from"os";function Le(){return T.join(Ce.homedir(),p,"config.json")}function ke(){try{b.reload()}catch(s){return console.error(`\u914D\u7F6E\u6587\u4EF6\u9519\u8BEF: ${s instanceof Error?s.message:String(s)}`),console.error(`\u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84: ${Le()}`),!1}let n=b.hasModelRouting(),e=b.hasSmallFastModelRouting();if(!n&&!e)return!1;let t=b.getConfig(),o=t.routing||{};for(let[s,r]of Object.entries(o))for(let i of r)if(!t.sources[i.source])return console.error(`\u914D\u7F6E\u9519\u8BEF: routing.${s} \u4E2D\u5F15\u7528\u7684 source "${i.source}" \u5728 sources \u4E2D\u4E0D\u5B58\u5728`),!1;return!0}function De(){if($(),!ke()){process.exit(0);return}(async()=>{let n=M.getSetting("env")||{},e=oe(import.meta.url),t=T.dirname(e),o=T.join(t,"cli.js"),s=se(process.execPath,["--no-deprecation",o,...process.argv.slice(2)],{env:{...process.env,...n},stdio:"inherit",cwd:process.cwd()});s.on("error",r=>{console.error("Failed to start command:",r.message),process.exit(1)}),s.on("close",r=>{process.exit(r||0)})})()}async function Ne(){let n=oe(import.meta.url),e=T.dirname(n),t=T.join(e,"cli.js"),o=se(process.execPath,["--no-deprecation",t,...process.argv.slice(2)],{env:process.env,stdio:"inherit",cwd:process.cwd()});o.on("error",s=>{console.error("Failed to start command:",s.message),process.exit(1)}),o.on("close",s=>{process.exit(s||0)})}async function Pe(){process.argv.length<=2?De():await Ne()}await Pe();
|
|
12
|
+
`;K(n)?pe(n,s,"utf8"):ge(n,s,"utf8")}var ot=5*1024*1024,rt=1024*1024,it=Buffer.from('"compact_boundary"');var k={env:{},permissions:{allow:[],deny:[],ask:[]},enableAllProjectMcpServers:!1,enabledMcpjsonServers:[],autoCompactEnabled:!0,language:"auto",thinking:"medium",disableSuggestion:!1,autoMemory:{enabled:!0,minTokens:3e3,minTurns:3,teamMemoryEnabled:!1},autoDream:{enabled:!0,minHours:24,minSessions:5}},j=class n{static test=!1;static testSettings;static setSettings(e){n.testSettings=e}static instance;static isTasksEnable(){return process.env.HAWA_CODE_ENABLE_TASKS=="true"||n.isAgentTeamEnable()}static isAgentTeamEnable(){return process.env.HAWA_CODE_EXPERIMENTAL_AGENT_TEAMS=="1"}static isLazyToolEnable(){return process.env.HAWA_CODE_LAZY_TOOL==="true"||process.env.HAWA_CODE_LAZY_TOOL==="1"}static isPowerShellToolEnable(){return process.platform!=="win32"?!1:process.env.HAWA_CODE_POWER_SHELL_ENABLE==="true"||process.env.HAWA_CODE_POWER_SHELL_ENABLE==="1"?!0:!(process.env.HAWA_CODE_POWER_SHELL_ENABLE==="false"||process.env.HAWA_CODE_POWER_SHELL_ENABLE==="0"||process.env[W])}constructor(){this.initializeConfigDirectories()}initializeConfigDirectories(){let e=this.getUserSettingsPath(),t=this.getProjectSettingsPath();this.ensureDirExists(e),C(e)||L(e,JSON.stringify(this.getDefaultSettingsStructure(),null,2),"utf-8"),this.ensureDirExists(t),C(t)||L(t,JSON.stringify(this.getDefaultSettingsStructure(),null,2),"utf-8")}getDefaultSettingsStructure(){return{env:{},permissions:{allow:[],deny:[],ask:[]},autoMode:{enabled:!1,model:"",maxConsecutiveDenials:3,maxTotalDenials:20},thinking:"medium"}}static getInstance(){return n.instance||(n.instance=new n),n.instance}addProjectAllowedTools(e){let t=this.loadSettingsFromFile(this.getProjectSettingsPath()),o=t.permissions||{allow:[],deny:[]};if(o.allow||(o.allow=[]),o.allow.includes(e))O(`\u5DE5\u5177 '${e}' \u5DF2\u5B58\u5728\u4E8E\u9879\u76EE\u5141\u8BB8\u5217\u8868\u4E2D\uFF0C\u65E0\u9700\u91CD\u590D\u6DFB\u52A0`);else{o.allow.push(e),o.allow.sort();let s={...t,permissions:{...o}};this.saveSettingsToFile(this.getProjectSettingsPath(),s,k),O(`\u5DF2\u5C06\u5DE5\u5177 '${e}' \u6DFB\u52A0\u5230\u9879\u76EE\u5141\u8BB8\u5217\u8868`)}}getUserSettingsPath(){return q(be(),".hcode","settings.json")}getProjectSettingsPath(){let e=process.cwd();return q(e,".hcode","settings.json")}ensureDirExists(e){let t=Ee(e);C(t)||Me(t,{recursive:!0})}loadSettingsFromFile(e){if(!C(e))return{};let t="";try{return t=Oe(e,"utf-8"),JSON.parse(t)}catch(o){return console.error(`Error reading settings file ${e} => ${t} `,o),{}}}saveSettingsToFile(e,t,o){let s={...t};for(let[r,i]of Object.entries(t))if(r in o)if(typeof i=="object"&&typeof o[r]=="object"){if(JSON.stringify(i)===JSON.stringify(o[r]))delete s[r];else if(r==="permissions"&&i&&typeof i=="object"){let u=o.permissions||{},a=i;Array.isArray(a.allow)&&Array.isArray(u.allow)&&JSON.stringify(a.allow)===JSON.stringify(u.allow)&&delete a.allow,Array.isArray(a.deny)&&Array.isArray(u.deny)&&JSON.stringify(a.deny)===JSON.stringify(u.deny)&&delete a.deny,Object.keys(a).length===0&&delete s[r]}}else i===o[r]&&delete s[r];this.ensureDirExists(e),Object.keys(s).length===0?L(e,"{}","utf-8"):L(e,JSON.stringify(s,null,2),"utf-8")}mergeStringArrays(e,t){if(!e&&!t)return;let o=[...e||[]];return(t||[]).forEach(s=>{o.includes(s)||o.push(s)}),o}loadSettings(){let e=this.loadSettingsFromFile(this.getUserSettingsPath()),t=this.loadSettingsFromFile(this.getProjectSettingsPath()),o={...e.env,...t.env},s={...e.permissions};if(e.permissions?.allow&&t.permissions?.allow){let a=[...e.permissions.allow];t.permissions.allow.forEach(c=>{a.includes(c)||a.push(c)}),s.allow=a}else t.permissions?.allow&&(s.allow=[...t.permissions.allow]);if(e.permissions?.deny&&t.permissions?.deny){let a=[...e.permissions.deny];t.permissions.deny.forEach(c=>{a.includes(c)||a.push(c)}),s.deny=a}else t.permissions?.deny&&(s.deny=[...t.permissions.deny]);if(e.permissions?.ask&&t.permissions?.ask){let a=[...e.permissions.ask];t.permissions.ask.forEach(c=>{a.includes(c)||a.push(c)}),s.ask=a}else t.permissions?.ask&&(s.ask=[...t.permissions.ask]);let r={...k,...e,...t};o&&Object.keys(o).length>0&&(r.env=o),s&&(s.allow||s.deny||s.ask)&&(r.permissions=s);let i=e.sandbox,u=t.sandbox;if(i||u){let a={...i,...u},c=i?.filesystem,f=u?.filesystem;(c||f)&&(a.filesystem={...c,...f,allowWrite:this.mergeStringArrays(c?.allowWrite,f?.allowWrite),denyWrite:this.mergeStringArrays(c?.denyWrite,f?.denyWrite),denyRead:this.mergeStringArrays(c?.denyRead,f?.denyRead),allowRead:this.mergeStringArrays(c?.allowRead,f?.allowRead)});let h=i?.network,y=u?.network;(h||y)&&(a.network={...h,...y,allowedDomains:this.mergeStringArrays(h?.allowedDomains,y?.allowedDomains),deniedDomains:this.mergeStringArrays(h?.deniedDomains,y?.deniedDomains),allowUnixSockets:this.mergeStringArrays(h?.allowUnixSockets,y?.allowUnixSockets)});let D=i?.ignoreViolations,N=u?.ignoreViolations;if(D||N){let m={};if(D)for(let[S,A]of Object.entries(D))m[S]=[...A];if(N)for(let[S,A]of Object.entries(N))m[S]?m[S]=this.mergeStringArrays(m[S],A)??[]:m[S]=[...A];a.ignoreViolations=m}r.sandbox=a}return r}saveUserSettings(e){let t=this.getUserSettingsPath();this.saveSettingsToFile(t,e,k)}saveProjectSettings(e){let t=this.getProjectSettingsPath();this.saveSettingsToFile(t,e,k)}getSetting(e){return this.loadSettings()[e]}updateSetting(e,t){let s={...this.loadSettings(),[e]:t};this.saveProjectSettings(s)}resetSetting(e){let o={...this.loadSettings()};delete o[e],this.saveProjectSettings(o)}getAllSettings(){return this.loadSettings()}},M=j.getInstance(),Z=M.getAllSettings();function F(){let n=M.getUserSettingsPath(),e=M.getProjectSettingsPath();X(n,(t,o)=>{t==="change"&&(Z=null,O("\u7528\u6237\u7EA7\u914D\u7F6E\u5DF2\u70ED\u52A0\u8F7D"))}).on("error",t=>{x("\u7528\u6237\u7EA7\u914D\u7F6E\u76D1\u63A7\u51FA\u9519:",t),setTimeout(()=>F(),100)}),X(e,(t,o)=>{t==="change"&&(Z=null,O("\u9879\u76EE\u7EA7\u914D\u7F6E\u5DF2\u70ED\u52A0\u8F7D",o))}).on("error",t=>{x("\u9879\u76EE\u7EA7\u914D\u7F6E\u76D1\u63A7\u51FA\u9519:",t),setTimeout(()=>F(),100)})}F();import Te from"os";import Ae from"path";import E from"fs";var we={sources:{},routing:{}};function ne(){let n=Te.homedir();return Ae.join(n,p,"config.json")}function ee(){try{let n=ne();if(!E.existsSync(n))return we;let e=E.readFileSync(n,"utf-8"),t=JSON.parse(e);return t.sources&&t.routing?t:xe(t)}catch(n){throw I(n),n}}function xe(n){let e={},t={};for(let[o,s]of Object.entries(n))if(s?.enable===!0&&s?.env){let r=s.env,i=o;e[i]={base_url:r.BASE_URL||"",auth_token:r.AUTH_TOKEN||"",api_type:r.API_TYPE||"anthropic",models:[]},r.MODEL&&(t.MODEL=[{source:i,model:r.MODEL,weight:100}],e[i].models.push(r.MODEL)),r.SMALL_FAST_MODEL&&(t.SMALL_FAST_MODEL=[{source:i,model:r.SMALL_FAST_MODEL,weight:100}],e[i].models.includes(r.SMALL_FAST_MODEL)||e[i].models.push(r.SMALL_FAST_MODEL));break}return{sources:e,routing:t}}function te(n){if(n.length===0)throw new Error("No items to select from");if(n.length===1)return n[0];let e=n.reduce((o,s)=>o+(s.weight??100),0),t=Math.random()*e;for(let o of n){let s=o.weight??100;if(t-=s,t<=0)return o}return n[n.length-1]}var H=class{config;constructor(){try{this.config=ee()}catch(e){console.log(e)}}reload(){this.config=ee()}getConfig(){return this.config}hasModelRouting(){return!!(this.config.routing?.MODEL&&this.config.routing.MODEL.length>0)}getModelRoutingModels(){let e=this.config.routing?.MODEL;return!e||e.length===0?[]:e.map(t=>t.model)}hasSmallFastModelRouting(){return!!(this.config.routing?.SMALL_FAST_MODEL&&this.config.routing.SMALL_FAST_MODEL.length>0)}getModel(){let e=this.config.routing?.MODEL;if(!e||e.length===0)throw new Error("No MODEL routing configuration found");let t=te(e);return`${t.source}__${t.model}`}getSmallFastModel(){let e=this.config.routing?.SMALL_FAST_MODEL;if(!e||e.length===0)throw new Error("No SMALL_FAST_MODEL routing configuration found");let t=te(e);return`${t.source}__${t.model}`}getSourceConfig(e){return this.config.sources?.[e]}parseModelKey(e){let t=e.indexOf("__");return t===-1?{source:"",model:e}:{source:e.slice(0,t),model:e.slice(t+2)}}getModelSourceConfig(e){let{source:t}=this.parseModelKey(e);if(t)return this.getSourceConfig(t)}setModelRouting(e){this.config.routing.MODEL=e,this.saveConfig()}setSmallFastModelRouting(e){this.config.routing.SMALL_FAST_MODEL=e,this.saveConfig()}getAvailableModels(){let e=[];for(let[t,o]of Object.entries(this.config.sources||{}))for(let s of o.models||[])e.push(`${t}__${s}`);return e}saveConfig(){try{let e=ne(),t={};if(E.existsSync(e)){let s=E.readFileSync(e,"utf-8");t=JSON.parse(s)}let o={...t,sources:this.config.sources,routing:this.config.routing};E.writeFileSync(e,JSON.stringify(o,null,2))}catch(e){I(e)}}},b=new H;import Ce from"os";function Le(){return T.join(Ce.homedir(),p,"config.json")}function ke(){try{b.reload()}catch(s){return console.error(`\u914D\u7F6E\u6587\u4EF6\u9519\u8BEF: ${s instanceof Error?s.message:String(s)}`),console.error(`\u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84: ${Le()}`),!1}let n=b.hasModelRouting(),e=b.hasSmallFastModelRouting();if(!n&&!e)return!1;let t=b.getConfig(),o=t.routing||{};for(let[s,r]of Object.entries(o))for(let i of r)if(!t.sources[i.source])return console.error(`\u914D\u7F6E\u9519\u8BEF: routing.${s} \u4E2D\u5F15\u7528\u7684 source "${i.source}" \u5728 sources \u4E2D\u4E0D\u5B58\u5728`),!1;return!0}function De(){if($(),!ke()){process.exit(0);return}(async()=>{let n=M.getSetting("env")||{},e=oe(import.meta.url),t=T.dirname(e),o=T.join(t,"cli.js"),s=se(process.execPath,["--no-deprecation",o,...process.argv.slice(2)],{env:{...process.env,...n},stdio:"inherit",cwd:process.cwd()});s.on("error",r=>{console.error("Failed to start command:",r.message),process.exit(1)}),s.on("close",r=>{process.exit(r||0)})})()}async function Ne(){let n=oe(import.meta.url),e=T.dirname(n),t=T.join(e,"cli.js"),o=se(process.execPath,["--no-deprecation",t,...process.argv.slice(2)],{env:process.env,stdio:"inherit",cwd:process.cwd()});o.on("error",s=>{console.error("Failed to start command:",s.message),process.exit(1)}),o.on("close",s=>{process.exit(s||0)})}async function Pe(){process.argv.length<=2?De():await Ne()}await Pe();
|