@dahawa/hawa-code 2.5.1 → 2.6.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 +747 -768
- package/hands.js +658 -679
- package/hawa.js +3 -3
- package/package.json +1 -1
- package/webServer/app.js +5 -5
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{spawn as ie}from"child_process";import k from"path";import{fileURLToPath as ae}from"url";import{existsSync as U,readFileSync as
|
|
11
|
-
${s.stack.replace(/^/gm," ")}`:s);
|
|
12
|
-
`;q(o)?me(o,s,"utf8"):fe(o,s,"utf8")}var ct=5*1024*1024,lt=1024*1024,ut=Buffer.from('"compact_boundary"');var R=class o{static getTools=e=>[];static getMCPCommands=()=>[];static getMcpServer=e=>{};static getClients=async()=>[];static reloadClients=async()=>[];static reconnect=async(e,t,n)=>{};static registerIDEClient=(e,t)=>{};static cache=[];static add(e){o.cache.push(e)}static clear(){o.cache.forEach(e=>{e.cache.clear?.()})}};var j={env:{},permissions:{allow:[],deny:[],ask:[]},enableAllProjectMcpServers:!1,enabledMcpjsonServers:[],autoCompactEnabled:!0,language:"auto",thinking:"medium",disableSuggestion:!1,lazyTool:"loading",memo:!1,messageArchiving:!1,archiveToolUseInputs:!1,autoMode:{enabled:!0,model:"",maxConsecutiveDenials:3,maxTotalDenials:20},autoMemory:{enabled:!0,minTokens:3e3,minTurns:3,teamMemoryEnabled:!1},autoDream:{enabled:!0,minHours:24,minSessions:5},proxy:!1,agentDepth:1,plugins:{pluginClaudeCompat:!0}},L=class o{static test=!1;static testSettings;static setSettings(e){o.testSettings=e}static instance;static isTasksEnable(){return process.env.HAWA_CODE_ENABLE_TASKS=="true"||o.isAgentTeamEnable()}static isAgentTeamEnable(){return process.env.HAWA_CODE_EXPERIMENTAL_AGENT_TEAMS=="1"}static getLazyToolMode(){let t=x().lazyTool;return t==="proxy"||t==="loading"||t==="off"?t:t===!0?"loading":t===!1?"off":"loading"}static isLazyToolEnable(){return o.getLazyToolMode()==="loading"}static isProxyToolEnable(){return o.getLazyToolMode()==="proxy"}static isLazyOrProxyEnable(){return o.getLazyToolMode()!=="off"}static isPowerShellToolEnable(){return H()}static isMemoEnable(){return x().memo===!0}static isMessageArchivingEnable(){return x().messageArchiving===!0}static isArchiveToolUseInputsEnable(){return x().archiveToolUseInputs===!0}constructor(){this.initializeConfigDirectories()}initializeConfigDirectories(){let e=this.getUserSettingsPath(),t=this.getProjectSettingsPath();this.ensureDirExists(e),U(e)||I(e,JSON.stringify(this.getDefaultSettingsStructure(),null,2),"utf-8"),this.ensureDirExists(t),U(t)||I(t,JSON.stringify(this.getDefaultSettingsStructure(),null,2),"utf-8")}getDefaultSettingsStructure(){return{env:{},permissions:{allow:[],deny:[],ask:[]},autoMode:{enabled:!0,model:"",maxConsecutiveDenials:3,maxTotalDenials:20},thinking:"medium"}}static getInstance(){return o.instance||(o.instance=new o),o.instance}addProjectAllowedTools(e){let t=this.loadSettingsFromFile(this.getProjectSettingsPath()),n=t.permissions||{allow:[],deny:[]};if(n.allow||(n.allow=[]),n.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{n.allow.push(e),n.allow.sort();let s={...t,permissions:{...n}};this.saveSettingsToFile(this.getProjectSettingsPath(),s,j),O(`\u5DF2\u5C06\u5DE5\u5177 '${e}' \u6DFB\u52A0\u5230\u9879\u76EE\u5141\u8BB8\u5217\u8868`)}}getUserSettingsPath(){return se(Ae(),".hcode","settings.json")}getProjectSettingsPath(){let e=process.cwd();return se(e,".hcode","settings.json")}ensureDirExists(e){let t=we(e);U(t)||Ee(t,{recursive:!0})}loadSettingsFromFile(e){if(!U(e))return{};let t="";try{return t=xe(e,"utf-8"),JSON.parse(t)}catch(n){return console.error(`Error reading settings file ${e} => ${t} `,n),{}}}saveSettingsToFile(e,t,n){let s={...t};for(let[r,i]of Object.entries(t))if(r in n)if(typeof i=="object"&&typeof n[r]=="object"){if(JSON.stringify(i)===JSON.stringify(n[r]))delete s[r];else if(r==="permissions"&&i&&typeof i=="object"){let l=n.permissions||{},c=i;Array.isArray(c.allow)&&Array.isArray(l.allow)&&JSON.stringify(c.allow)===JSON.stringify(l.allow)&&delete c.allow,Array.isArray(c.deny)&&Array.isArray(l.deny)&&JSON.stringify(c.deny)===JSON.stringify(l.deny)&&delete c.deny,Object.keys(c).length===0&&delete s[r]}}else i===n[r]&&delete s[r];this.ensureDirExists(e),Object.keys(s).length===0?I(e,"{}","utf-8"):I(e,JSON.stringify(s,null,2),"utf-8")}mergeStringArrays(e,t){if(!e&&!t)return;let n=[...e||[]];return(t||[]).forEach(s=>{n.includes(s)||n.push(s)}),n}loadSettings(){let e=this.loadSettingsFromFile(this.getUserSettingsPath()),t=this.loadSettingsFromFile(this.getProjectSettingsPath()),n={...e.env,...t.env},s={...e.permissions};if(e.permissions?.allow&&t.permissions?.allow){let a=[...e.permissions.allow];t.permissions.allow.forEach(u=>{a.includes(u)||a.push(u)}),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(u=>{a.includes(u)||a.push(u)}),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(u=>{a.includes(u)||a.push(u)}),s.ask=a}else t.permissions?.ask&&(s.ask=[...t.permissions.ask]);let r={...j,...e,...t};n&&Object.keys(n).length>0&&(r.env=n),s&&(s.allow||s.deny||s.ask)&&(r.permissions=s);let i=e.sandbox,l=t.sandbox;if(i||l){let a={...i,...l},u=i?.filesystem,b=l?.filesystem;(u||b)&&(a.filesystem={...u,...b,allowWrite:this.mergeStringArrays(u?.allowWrite,b?.allowWrite),denyWrite:this.mergeStringArrays(u?.denyWrite,b?.denyWrite),denyRead:this.mergeStringArrays(u?.denyRead,b?.denyRead),allowRead:this.mergeStringArrays(u?.allowRead,b?.allowRead)});let A=i?.network,C=l?.network;(A||C)&&(a.network={...A,...C,allowedDomains:this.mergeStringArrays(A?.allowedDomains,C?.allowedDomains),deniedDomains:this.mergeStringArrays(A?.deniedDomains,C?.deniedDomains),allowUnixSockets:this.mergeStringArrays(A?.allowUnixSockets,C?.allowUnixSockets)});let F=i?.ignoreViolations,B=l?.ignoreViolations;if(F||B){let _={};if(F)for(let[M,D]of Object.entries(F))_[M]=[...D];if(B)for(let[M,D]of Object.entries(B))_[M]?_[M]=this.mergeStringArrays(_[M],D)??[]:_[M]=[...D];a.ignoreViolations=_}r.sandbox=a}let c=e.plugins,d=t.plugins;if(c||d){let a={...c,...d};(c?.enabledPlugins||d?.enabledPlugins)&&(a.enabledPlugins=this.mergeStringArrays(c?.enabledPlugins,d?.enabledPlugins)),(c?.disabledPlugins||d?.disabledPlugins)&&(a.disabledPlugins=this.mergeStringArrays(c?.disabledPlugins,d?.disabledPlugins)),(c?.pluginMarketplaceAllowlist||d?.pluginMarketplaceAllowlist)&&(a.pluginMarketplaceAllowlist=this.mergeStringArrays(c?.pluginMarketplaceAllowlist,d?.pluginMarketplaceAllowlist)),(c?.pluginConfigs||d?.pluginConfigs)&&(a.pluginConfigs={...c?.pluginConfigs,...d?.pluginConfigs}),r.plugins=a}return r}saveUserSettings(e){let t=this.getUserSettingsPath();this.saveSettingsToFile(t,e,j)}saveProjectSettings(e){let t=this.getProjectSettingsPath();this.saveSettingsToFile(t,e,j)}getSetting(e){return this.loadSettings()[e]}updateSetting(e,t){let s={...this.loadSettings(),[e]:t};this.saveProjectSettings(s),p=s}resetSetting(e){let n={...this.loadSettings()};delete n[e],this.saveProjectSettings(n),p=n}getAllSettings(){return this.loadSettings()}},E=L.getInstance(),p=E.getAllSettings(),x=function(){return L.test?L.testSettings:(p||(p=E.getAllSettings(),R.clear(),p.env&&Object.keys(p.env).length>0&&(Object.entries(p.env).forEach(([o,e])=>{let t;typeof e=="string"?t=e:t=String(e),t.length>0&&(process.env[o]=t)}),O(`\u5DF2\u4ECE\u914D\u7F6E\u6587\u4EF6\u52A0\u8F7D ${Object.keys(p.env).length} \u4E2A\u73AF\u5883\u53D8\u91CF`,p.env))),p)};function J(){let o=E.getUserSettingsPath(),e=E.getProjectSettingsPath();ne(o,(t,n)=>{t==="change"&&(p=null,y.emit("webserver:settings_changed",{scope:"user"}),O("\u7528\u6237\u7EA7\u914D\u7F6E\u5DF2\u70ED\u52A0\u8F7D"))}).on("error",t=>{h("\u7528\u6237\u7EA7\u914D\u7F6E\u76D1\u63A7\u51FA\u9519:",t),setTimeout(()=>J(),100)}).unref(),ne(e,(t,n)=>{t==="change"&&(p=null,y.emit("webserver:settings_changed",{scope:"project"}),O("\u9879\u76EE\u7EA7\u914D\u7F6E\u5DF2\u70ED\u52A0\u8F7D",n))}).on("error",t=>{h("\u9879\u76EE\u7EA7\u914D\u7F6E\u76D1\u63A7\u51FA\u9519:",t),setTimeout(()=>J(),100)}).unref()}J();import Ce from"os";import re from"path";import S from"fs";var Q={sources:{openai:{base_url:"https://api.openai.com/v1",auth_token:"{apikey}",api_type:"openai",models:["gpt-5.5","gpt-5.4-mini"]},kimi:{base_url:"https://api.kimi.com/coding",auth_token:"{apikey}",api_type:"anthropic",models:["K2.5","K2.6"]},"qwen-coding":{base_url:"https://coding.dashscope.aliyuncs.com/apps/anthropic",auth_token:"{apikey}",api_type:"anthropic",models:["qwen3-coder-plus"]}},routing:{MODEL:[{source:"kimi",model:"K2.6",weight:60},{source:"openai",model:"gpt-5.5",weight:40}],SMALL_FAST_MODEL:[{source:"qwen-coding",model:"qwen3-coder-plus",weight:50},{source:"kimi",model:"K2.5",weight:50}]}};function Pe(){let o=Ce.homedir();return re.join(o,T,"config.json")}function oe(o){if(o.length===0)throw new Error("No items to select from");if(o.length===1)return o[0];let e=o.reduce((n,s)=>n+(s.weight??100),0),t=Math.random()*e;for(let n of o){let s=n.weight??100;if(t-=s,t<=0)return n}return o[o.length-1]}var V=class{config;configPath;constructor(e){this.configPath=e||Pe();try{this.config=this.loadModelConfig()}catch(t){console.log(t)}}initConfig(){if(!S.existsSync(this.configPath))try{let e=re.dirname(this.configPath);S.mkdirSync(e,{recursive:!0}),S.writeFileSync(this.configPath,JSON.stringify(Q,null,2))}catch(e){v(e)}}reload(){this.config=this.loadModelConfig()}loadModelConfig(){try{if(!S.existsSync(this.configPath))return Q;let e=S.readFileSync(this.configPath,"utf-8"),t=JSON.parse(e);return t.sources&&t.routing?t:Q}catch(e){throw v(e),e}}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=oe(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=oe(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()}updateConfig(e){this.config=e,this.saveConfig()}getAvailableModels(){let e=[];for(let[t,n]of Object.entries(this.config.sources||{}))for(let s of n.models||[])e.push(`${t}__${s}`);return e}saveConfig(){try{let e={};if(S.existsSync(this.configPath)){let n=S.readFileSync(this.configPath,"utf-8");e=JSON.parse(n)}let t={...e,sources:this.config.sources,routing:this.config.routing};S.writeFileSync(this.configPath,JSON.stringify(t,null,2))}catch(e){v(e)}}},w=new V;import Le from"os";function ke(){return k.join(Le.homedir(),T,"config.json")}function De(){try{w.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: ${ke()}`),!1}let o=w.hasModelRouting(),e=w.hasSmallFastModelRouting();if(!o&&!e)return!1;let t=w.getConfig(),n=t.routing||{};for(let[s,r]of Object.entries(n))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 Ne(){if(w.initConfig(),!De()){process.exit(0);return}(async()=>{let o=E.getSetting("env")||{},e=ae(import.meta.url),t=k.dirname(e),n=k.join(t,"cli.js"),s=ie(process.execPath,["--no-deprecation",n,...process.argv.slice(2)],{env:{...process.env,...o},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 ve(){let o=ae(import.meta.url),e=k.dirname(o),t=k.join(e,"cli.js"),n=ie(process.execPath,["--no-deprecation",t,...process.argv.slice(2)],{env:process.env,stdio:"inherit",cwd:process.cwd()});n.on("error",s=>{console.error("Failed to start command:",s.message),process.exit(1)}),n.on("close",s=>{process.exit(s||0)})}async function Re(){process.argv.length<=2?Ne():await ve()}await Re();
|
|
10
|
+
import{spawn as ie}from"child_process";import k from"path";import{fileURLToPath as ae}from"url";import{existsSync as U,readFileSync as Oe,writeFileSync as I,mkdirSync as Ee,watch as ne}from"fs";import{join as se,dirname as we}from"path";import{homedir as Ae}from"os";import{existsSync as q,mkdirSync as pe}from"fs";import{dirname as de,join as g}from"path";import{writeFileSync as fe,readFileSync as Ze,appendFileSync as me}from"fs";import{randomUUID as Se}from"crypto";import{homedir as he}from"os";var Y="hcode",x=".hcode";var ce="HAWA_CODE_GIT_BASH_PATH";var le="Bash",ue="PowerShell";var Ue=H()?ue:le;function H(){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[ce])}import*as Z from"os";import{randomUUID as ge}from"crypto";var W=class{listeners=new Map;registry=new FinalizationRegistry(e=>{for(let[t,n]of this.listeners.entries()){for(let s of Array.from(n))s.token===e&&n.delete(s);n.size===0&&this.listeners.delete(t)}});on(e,t,n){let s=this.listeners.get(e);s||(s=new Set,this.listeners.set(e,s));let r={callback:t,thisRef:n?new WeakRef(n):void 0};if(n){let i={};r.token=i,this.registry.register(n,i,i)}return s.add(r),()=>{this.off(e,t,n)}}off(e,t,n){let s=this.listeners.get(e);if(s){if(!t&&n===void 0){for(let r of s)r.token&&this.registry.unregister(r.token);this.listeners.delete(e);return}for(let r of Array.from(s)){let i=t?r.callback===t:!0,l=!0;n!==void 0&&(l=r.thisRef?.deref()===n),i&&l&&(r.token&&this.registry.unregister(r.token),s.delete(r))}s.size===0&&this.listeners.delete(e)}}emit(e,t){let n=this.listeners.get(e);if(n)for(let s of Array.from(n)){let r;if(s.thisRef&&(r=s.thisRef.deref(),!r)){n.delete(s);continue}try{let i=s.callback.call(r,t);i instanceof Promise&&i.catch(l=>{h(`Async error in listener for "${e}"`,l)})}catch(i){h(`Error in listener for "${e}"`,i)}}}},y=new W;var N=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={}}},P=class extends N{startTime;constructor(e=null){super(),this.startTime=e}},K=ge(),$=class extends N{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 n=Date.now(),s=e*1e3;for(;Date.now()-n<s;){let r=this.getPendingPrompts();if(r.length>0)return r;await new Promise(i=>setTimeout(i,200))}return[]}getSessionId(){return K}switchSessionId(e){K=e}},z=class o{static sessionContext={};static inQueryContextHolder={};static queryContext={};onQueryStart(e="defalt",t){e||(e="defalt");let n=o.inQueryContextHolder[e+""];n&&n.startTime&&n.startTime>0||(o.inQueryContextHolder[e+""]=new P(Date.now()),y.emit("webserver:agent_status",{agentId:e,status:"started",agentType:t?.agentType,agentName:t?.agentName,description:t?.description,timestamp:Date.now()}))}onQueryEnd(e="defalt",t=!1){e||(e="defalt"),o.inQueryContextHolder[e+""]=new P(-1),t||(o.queryContext[e+""]={}),y.emit("webserver:agent_status",{agentId:e,status:"ended",timestamp:Date.now()})}getSessionContext(e="defalt"){e||(e="defalt");let t=o.sessionContext[e+""];return t||(t=new $,o.sessionContext[e+""]=t),t}getInQueryContext(e="defalt"){e||(e="defalt");let t=o.inQueryContextHolder[e+""];return t||(t=new P,o.inQueryContextHolder[e+""]=t),t}getQueryContext(e="defalt"){e||(e="defalt");let t=o.queryContext[e+""];return t||(t={},o.queryContext[e+""]=t),t}isQuerying(e="defalt"){return e||(e="defalt"),this.getInQueryContext(e).startTime>0}},X=new z;var at=Se(),f=g(he(),x);function m(o){return o.replace(/[^a-zA-Z0-9]/g,"-")}function ye(){return X.getSessionContext().getSessionId()||G}function be(){try{let o=b().planDirectory;if(o)return o}catch{}return g(f,"plan")}var ee={temp:()=>g(Z.tmpdir(),`${Y}`),plan:()=>be(),memory:()=>g(f,"projects",m(process.cwd()),"memory"),apis:()=>g(f,"projects",m(process.cwd()),"apis"),errors:()=>g(f,"projects",m(process.cwd()),"errors"),messages:()=>g(f,"projects",m(process.cwd()),"messages"),mcpLogs:o=>g(f,"projects",m(process.cwd()),`mcp-logs-${o}`),log:()=>g(f,"projects",m(process.cwd()),"log"),vcrFixtures:()=>g(f,"projects",m(process.cwd()),"vcr-fixtures"),sessionSummary:()=>g(f,"projects",m(process.cwd()),"messages",ye(),"session-summary")};function _e(o){return o.toISOString().replace(/[:.]/g,"-")}var G=_e(new Date);function Me(){return g(ee.log(),G+".log")}function Te(){return g(ee.log(),"error-"+G+".log")}function te(o,e,...t){let n=t.map(s=>s instanceof Error?`${s.name}: ${s.message}
|
|
11
|
+
${s.stack.replace(/^/gm," ")}`:s);xe(e,{level:o,message:n.length==1?n[0]:n})}function O(...o){te("info",Me(),...o)}function h(...o){te("error",Te(),...o)}function v(...o){h(...o)}function xe(o,e){let t=de(o);q(t)||pe(t,{recursive:!0});let s=(typeof e=="string"?e:JSON.stringify(e))+`
|
|
12
|
+
`;q(o)?me(o,s,"utf8"):fe(o,s,"utf8")}var ct=5*1024*1024,lt=1024*1024,ut=Buffer.from('"compact_boundary"');var R=class o{static getTools=e=>[];static getMCPCommands=()=>[];static getMcpServer=e=>{};static getClients=async()=>[];static reloadClients=async()=>[];static reconnect=async(e,t,n)=>{};static registerIDEClient=(e,t)=>{};static cache=[];static add(e){o.cache.push(e)}static clear(){o.cache.forEach(e=>{e.cache.clear?.()})}};var j={env:{},permissions:{allow:[],deny:[],ask:[]},enableAllProjectMcpServers:!1,enabledMcpjsonServers:[],autoCompactEnabled:!0,language:"auto",thinking:"medium",disableSuggestion:!1,lazyTool:"proxy",memo:!1,messageArchiving:!1,archiveToolUseInputs:!1,autoMode:{enabled:!0,model:"",maxConsecutiveDenials:3,maxTotalDenials:20},autoMemory:{enabled:!1,minTokens:3e3,minTurns:3,teamMemoryEnabled:!1},autoDream:{enabled:!1,minHours:24,minSessions:5},proxy:!1,agentDepth:1,codemodeMethodsMax:20,plugins:{pluginClaudeCompat:!0}},L=class o{static test=!1;static testSettings;static setSettings(e){o.testSettings=e}static instance;static isTasksEnable(){return process.env.HAWA_CODE_ENABLE_TASKS=="true"||o.isAgentTeamEnable()}static isAgentTeamEnable(){return process.env.HAWA_CODE_EXPERIMENTAL_AGENT_TEAMS=="1"}static getLazyToolMode(){let t=b().lazyTool;return t==="proxy"||t==="loading"||t==="off"?t:"proxy"}static isLazyToolEnable(){return o.getLazyToolMode()==="loading"}static isProxyToolEnable(){return o.getLazyToolMode()==="proxy"}static isLazyOrProxyEnable(){return o.getLazyToolMode()!=="off"}static isPowerShellToolEnable(){return H()}static isMemoEnable(){return b().memo===!0}static isMessageArchivingEnable(){return b().messageArchiving===!0}static isArchiveToolUseInputsEnable(){return b().archiveToolUseInputs===!0}static getCodemodeMethodsMax(){let e=b().codemodeMethodsMax;return typeof e!="number"||Number.isNaN(e)?20:Math.min(100,Math.max(1,Math.floor(e)))}constructor(){this.initializeConfigDirectories()}initializeConfigDirectories(){let e=this.getUserSettingsPath(),t=this.getProjectSettingsPath();this.ensureDirExists(e),U(e)||I(e,JSON.stringify(this.getDefaultSettingsStructure(),null,2),"utf-8"),this.ensureDirExists(t),U(t)||I(t,JSON.stringify(this.getDefaultSettingsStructure(),null,2),"utf-8")}getDefaultSettingsStructure(){return{env:{},permissions:{allow:[],deny:[],ask:[]},autoMode:{enabled:!0,model:"",maxConsecutiveDenials:3,maxTotalDenials:20},thinking:"medium"}}static getInstance(){return o.instance||(o.instance=new o),o.instance}addProjectAllowedTools(e){let t=this.loadSettingsFromFile(this.getProjectSettingsPath()),n=t.permissions||{allow:[],deny:[]};if(n.allow||(n.allow=[]),n.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{n.allow.push(e),n.allow.sort();let s={...t,permissions:{...n}};this.saveSettingsToFile(this.getProjectSettingsPath(),s,j),O(`\u5DF2\u5C06\u5DE5\u5177 '${e}' \u6DFB\u52A0\u5230\u9879\u76EE\u5141\u8BB8\u5217\u8868`)}}getUserSettingsPath(){return se(Ae(),".hcode","settings.json")}getProjectSettingsPath(){let e=process.cwd();return se(e,".hcode","settings.json")}ensureDirExists(e){let t=we(e);U(t)||Ee(t,{recursive:!0})}loadSettingsFromFile(e){if(!U(e))return{};let t="";try{return t=Oe(e,"utf-8"),JSON.parse(t)}catch(n){return console.error(`Error reading settings file ${e} => ${t} `,n),{}}}saveSettingsToFile(e,t,n){let s={...t};for(let[r,i]of Object.entries(t))if(r in n)if(typeof i=="object"&&typeof n[r]=="object"){if(JSON.stringify(i)===JSON.stringify(n[r]))delete s[r];else if(r==="permissions"&&i&&typeof i=="object"){let l=n.permissions||{},c=i;Array.isArray(c.allow)&&Array.isArray(l.allow)&&JSON.stringify(c.allow)===JSON.stringify(l.allow)&&delete c.allow,Array.isArray(c.deny)&&Array.isArray(l.deny)&&JSON.stringify(c.deny)===JSON.stringify(l.deny)&&delete c.deny,Object.keys(c).length===0&&delete s[r]}}else i===n[r]&&delete s[r];this.ensureDirExists(e),Object.keys(s).length===0?I(e,"{}","utf-8"):I(e,JSON.stringify(s,null,2),"utf-8")}mergeStringArrays(e,t){if(!e&&!t)return;let n=[...e||[]];return(t||[]).forEach(s=>{n.includes(s)||n.push(s)}),n}loadSettings(){let e=this.loadSettingsFromFile(this.getUserSettingsPath()),t=this.loadSettingsFromFile(this.getProjectSettingsPath()),n={...e.env,...t.env},s={...e.permissions};if(e.permissions?.allow&&t.permissions?.allow){let a=[...e.permissions.allow];t.permissions.allow.forEach(u=>{a.includes(u)||a.push(u)}),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(u=>{a.includes(u)||a.push(u)}),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(u=>{a.includes(u)||a.push(u)}),s.ask=a}else t.permissions?.ask&&(s.ask=[...t.permissions.ask]);let r={...j,...e,...t};n&&Object.keys(n).length>0&&(r.env=n),s&&(s.allow||s.deny||s.ask)&&(r.permissions=s);let i=e.sandbox,l=t.sandbox;if(i||l){let a={...i,...l},u=i?.filesystem,_=l?.filesystem;(u||_)&&(a.filesystem={...u,..._,allowWrite:this.mergeStringArrays(u?.allowWrite,_?.allowWrite),denyWrite:this.mergeStringArrays(u?.denyWrite,_?.denyWrite),denyRead:this.mergeStringArrays(u?.denyRead,_?.denyRead),allowRead:this.mergeStringArrays(u?.allowRead,_?.allowRead)});let A=i?.network,C=l?.network;(A||C)&&(a.network={...A,...C,allowedDomains:this.mergeStringArrays(A?.allowedDomains,C?.allowedDomains),deniedDomains:this.mergeStringArrays(A?.deniedDomains,C?.deniedDomains),allowUnixSockets:this.mergeStringArrays(A?.allowUnixSockets,C?.allowUnixSockets)});let F=i?.ignoreViolations,B=l?.ignoreViolations;if(F||B){let M={};if(F)for(let[T,D]of Object.entries(F))M[T]=[...D];if(B)for(let[T,D]of Object.entries(B))M[T]?M[T]=this.mergeStringArrays(M[T],D)??[]:M[T]=[...D];a.ignoreViolations=M}r.sandbox=a}let c=e.plugins,d=t.plugins;if(c||d){let a={...c,...d};(c?.enabledPlugins||d?.enabledPlugins)&&(a.enabledPlugins=this.mergeStringArrays(c?.enabledPlugins,d?.enabledPlugins)),(c?.disabledPlugins||d?.disabledPlugins)&&(a.disabledPlugins=this.mergeStringArrays(c?.disabledPlugins,d?.disabledPlugins)),(c?.pluginMarketplaceAllowlist||d?.pluginMarketplaceAllowlist)&&(a.pluginMarketplaceAllowlist=this.mergeStringArrays(c?.pluginMarketplaceAllowlist,d?.pluginMarketplaceAllowlist)),(c?.pluginConfigs||d?.pluginConfigs)&&(a.pluginConfigs={...c?.pluginConfigs,...d?.pluginConfigs}),r.plugins=a}return r}saveUserSettings(e){let t=this.getUserSettingsPath();this.saveSettingsToFile(t,e,j)}saveProjectSettings(e){let t=this.getProjectSettingsPath();this.saveSettingsToFile(t,e,j)}getSetting(e){return this.loadSettings()[e]}updateSetting(e,t){let s={...this.loadSettings(),[e]:t};this.saveProjectSettings(s),p=s}resetSetting(e){let n={...this.loadSettings()};delete n[e],this.saveProjectSettings(n),p=n}getAllSettings(){return this.loadSettings()}},E=L.getInstance(),p=E.getAllSettings(),b=function(){return L.test?L.testSettings:(p||(p=E.getAllSettings(),R.clear(),p.env&&Object.keys(p.env).length>0&&(Object.entries(p.env).forEach(([o,e])=>{let t;typeof e=="string"?t=e:t=String(e),t.length>0&&(process.env[o]=t)}),O(`\u5DF2\u4ECE\u914D\u7F6E\u6587\u4EF6\u52A0\u8F7D ${Object.keys(p.env).length} \u4E2A\u73AF\u5883\u53D8\u91CF`,p.env))),p)};function J(){let o=E.getUserSettingsPath(),e=E.getProjectSettingsPath();ne(o,(t,n)=>{t==="change"&&(p=null,y.emit("webserver:settings_changed",{scope:"user"}),O("\u7528\u6237\u7EA7\u914D\u7F6E\u5DF2\u70ED\u52A0\u8F7D"))}).on("error",t=>{h("\u7528\u6237\u7EA7\u914D\u7F6E\u76D1\u63A7\u51FA\u9519:",t),setTimeout(()=>J(),100)}).unref(),ne(e,(t,n)=>{t==="change"&&(p=null,y.emit("webserver:settings_changed",{scope:"project"}),O("\u9879\u76EE\u7EA7\u914D\u7F6E\u5DF2\u70ED\u52A0\u8F7D",n))}).on("error",t=>{h("\u9879\u76EE\u7EA7\u914D\u7F6E\u76D1\u63A7\u51FA\u9519:",t),setTimeout(()=>J(),100)}).unref()}J();import Ce from"os";import re from"path";import S from"fs";var Q={sources:{openai:{base_url:"https://api.openai.com/v1",auth_token:"{apikey}",api_type:"openai",models:["gpt-5.5","gpt-5.4-mini"]},kimi:{base_url:"https://api.kimi.com/coding",auth_token:"{apikey}",api_type:"anthropic",models:["K2.5","K2.6"]},"qwen-coding":{base_url:"https://coding.dashscope.aliyuncs.com/apps/anthropic",auth_token:"{apikey}",api_type:"anthropic",models:["qwen3-coder-plus"]}},routing:{MODEL:[{source:"kimi",model:"K2.6",weight:60},{source:"openai",model:"gpt-5.5",weight:40}],SMALL_FAST_MODEL:[{source:"qwen-coding",model:"qwen3-coder-plus",weight:50},{source:"kimi",model:"K2.5",weight:50}]}};function Pe(){let o=Ce.homedir();return re.join(o,x,"config.json")}function oe(o){if(o.length===0)throw new Error("No items to select from");if(o.length===1)return o[0];let e=o.reduce((n,s)=>n+(s.weight??100),0),t=Math.random()*e;for(let n of o){let s=n.weight??100;if(t-=s,t<=0)return n}return o[o.length-1]}var V=class{config;configPath;constructor(e){this.configPath=e||Pe();try{this.config=this.loadModelConfig()}catch(t){console.log(t)}}initConfig(){if(!S.existsSync(this.configPath))try{let e=re.dirname(this.configPath);S.mkdirSync(e,{recursive:!0}),S.writeFileSync(this.configPath,JSON.stringify(Q,null,2))}catch(e){v(e)}}reload(){this.config=this.loadModelConfig()}loadModelConfig(){try{if(!S.existsSync(this.configPath))return Q;let e=S.readFileSync(this.configPath,"utf-8"),t=JSON.parse(e);return t.sources&&t.routing?t:Q}catch(e){throw v(e),e}}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=oe(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=oe(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()}updateConfig(e){this.config=e,this.saveConfig()}getAvailableModels(){let e=[];for(let[t,n]of Object.entries(this.config.sources||{}))for(let s of n.models||[])e.push(`${t}__${s}`);return e}saveConfig(){try{let e={};if(S.existsSync(this.configPath)){let n=S.readFileSync(this.configPath,"utf-8");e=JSON.parse(n)}let t={...e,sources:this.config.sources,routing:this.config.routing};S.writeFileSync(this.configPath,JSON.stringify(t,null,2))}catch(e){v(e)}}},w=new V;import Le from"os";function ke(){return k.join(Le.homedir(),x,"config.json")}function De(){try{w.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: ${ke()}`),!1}let o=w.hasModelRouting(),e=w.hasSmallFastModelRouting();if(!o&&!e)return!1;let t=w.getConfig(),n=t.routing||{};for(let[s,r]of Object.entries(n))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 Ne(){if(w.initConfig(),!De()){process.exit(0);return}(async()=>{let o=E.getSetting("env")||{},e=ae(import.meta.url),t=k.dirname(e),n=k.join(t,"cli.js"),s=ie(process.execPath,["--no-deprecation",n,...process.argv.slice(2)],{env:{...process.env,...o},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 ve(){let o=ae(import.meta.url),e=k.dirname(o),t=k.join(e,"cli.js"),n=ie(process.execPath,["--no-deprecation",t,...process.argv.slice(2)],{env:process.env,stdio:"inherit",cwd:process.cwd()});n.on("error",s=>{console.error("Failed to start command:",s.message),process.exit(1)}),n.on("close",s=>{process.exit(s||0)})}async function Re(){process.argv.length<=2?Ne():await ve()}await Re();
|