blade-code 0.4.3 → 0.4.5
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/dist/blade.js +2 -2
- package/dist/{chunk-tf0m57f5.js → chunk-2e3pajfb.js} +1 -1
- package/dist/{chunk-p0n9ggyv.js → chunk-2ymnexz1.js} +1 -1
- package/dist/{chunk-1dvhq0mn.js → chunk-45f363j6.js} +1 -1
- package/dist/{chunk-ehcjnwnr.js → chunk-9syksrkj.js} +1 -1
- package/dist/{chunk-hhnst8br.js → chunk-9tgyev1k.js} +1 -1
- package/dist/chunk-b67w51zf.js +1 -0
- package/dist/chunk-c6ts8bd9.js +26 -0
- package/dist/{chunk-420vamtq.js → chunk-cfbp6h36.js} +1 -1
- package/dist/{chunk-5zkcs06z.js → chunk-d1hwbcne.js} +1 -1
- package/dist/{chunk-hbv7nxdh.js → chunk-g8e0gb93.js} +1 -1
- package/dist/{chunk-7g20yr9m.js → chunk-gsbd4yph.js} +1 -1
- package/dist/chunk-hhgbhadg.js +76 -0
- package/dist/{chunk-qbm9qrtg.js → chunk-hj714bc0.js} +127 -104
- package/dist/{chunk-njy55zd2.js → chunk-kdpafv9g.js} +1 -1
- package/dist/{chunk-q4hrt6r4.js → chunk-ksd0cxtf.js} +1 -1
- package/dist/{chunk-hwkdy2ez.js → chunk-ksh07whh.js} +1 -1
- package/dist/{chunk-52k9k0w8.js → chunk-mjgch1nt.js} +1 -1
- package/dist/{chunk-zs7xeymy.js → chunk-n466beq9.js} +1 -1
- package/dist/{chunk-094ekgv6.js → chunk-nhp35rk0.js} +2 -2
- package/dist/chunk-pkmw32r0.js +8 -0
- package/dist/chunk-pmtfesmc.js +1 -0
- package/dist/{chunk-phzbecpx.js → chunk-r7dz28wh.js} +1 -1
- package/dist/{chunk-jz59sjzb.js → chunk-r8wmg3fc.js} +1 -1
- package/dist/{chunk-c7e33j6k.js → chunk-rjfq5mqt.js} +1 -1
- package/dist/chunk-v19vaykx.js +157 -0
- package/dist/{chunk-8jwqy5d0.js → chunk-v1c9xwen.js} +1 -1
- package/dist/{chunk-80jc465v.js → chunk-vnpzrswh.js} +1 -1
- package/dist/{chunk-vwn39c84.js → chunk-xcpjsrem.js} +1 -1
- package/dist/{chunk-zszvkp6z.js → chunk-xh33jnv4.js} +1 -1
- package/dist/{chunk-gm59f5pe.js → chunk-zp8pmxw9.js} +1 -1
- package/package.json +2 -2
- package/dist/chunk-5mtjqqav.js +0 -8
- package/dist/chunk-76emdpxa.js +0 -76
- package/dist/chunk-h3ccyfqj.js +0 -1
- package/dist/chunk-hwhz4m2c.js +0 -157
- package/dist/chunk-y5g06jmk.js +0 -24
- package/dist/chunk-yjs7nvr5.js +0 -1
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{n as B}from"./chunk-
|
|
2
|
+
import{n as B}from"./chunk-2e3pajfb.js";import{$ as F,_ as D}from"./chunk-esnkk33h.js";import"./chunk-hhgbhadg.js";import"./chunk-c6ts8bd9.js";import"./chunk-nhp35rk0.js";import{vb as E,xb as q}from"./chunk-7ycmx7c2.js";import{Ab as H}from"./chunk-set7v1rf.js";import{Db as J}from"./chunk-j2ag7hh6.js";var X=process.argv.slice(2),$=v(X),w=$!==null;if($!==null)H.setGlobalDebug($);function v(Q){for(let W=0;W<Q.length;W+=1){let T=Q[W];if(T==="--debug"||T==="-d"){let N=Q[W+1];return N&&!N.startsWith("-")?N:!0}if(T.startsWith("--debug="))return T.slice(8)||!0}return null}function C(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function z(Q,...W){return Q.some((T)=>W.some((N)=>T===N||T.startsWith(`${N}=`)))}async function f(){if(C(X)){let{getVersion:K}=await import("./chunk-gsbd4yph.js");console.log(K());return}let Q=D(process.cwd());if(F(Q),E(q()),process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,U=!!process.env.BLADE_ALLOW_ROOT;if(K&&!U)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(B(),z(X,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-g8e0gb93.js");if(await K())return}if(z(X,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-rjfq5mqt.js");if(await K())return}if(X.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-2ymnexz1.js");await K();return}let[{default:W},{hideBin:T},{cliConfig:N,globalOptions:G},{loadConfiguration:I,validateOutput:L,validatePermissions:M},{doctorCommands:_},{installCommands:y},{mcpCommands:R},{serveCommand:S},{updateCommands:k},{webCommand:O}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-b67w51zf.js"),import("./chunk-n466beq9.js"),import("./chunk-d1hwbcne.js"),import("./chunk-g5pasj7t.js"),import("./chunk-vnpzrswh.js"),import("./chunk-zp8pmxw9.js"),import("./chunk-bhjw4b73.js"),import("./chunk-xh33jnv4.js")]),x=W(T(process.argv)).scriptName(N.scriptName).usage(N.usage).version(N.version).locale(N.locale).showHelpOnFail(N.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(N.strict).parserConfiguration({"populate--":!0}).options(G).middleware([M,I,L]).command(R).command(_).command(k).command(y).command(O).command(S).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,U,Z)=>{if(U){if(console.error("An error occurred:"),console.error(U.message),w&&U.stack)console.error(`
|
|
3
3
|
Stack trace:`),console.error(U.stack);else console.error(`
|
|
4
4
|
Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
|
|
5
|
-
Hint: Did you mean:`),Z.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let U=K._.slice(1),Z=U.length>0?U.join(" "):void 0,V=import("./chunk-th432d0b.js").then(({checkVersionOnStartup:A})=>A()),[{render:b},{createElement:P},{AppWrapper:h}]=await Promise.all([import("ink"),import("react"),import("./chunk-
|
|
5
|
+
Hint: Did you mean:`),Z.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let U=K._.slice(1),Z=U.length>0?U.join(" "):void 0,V=import("./chunk-th432d0b.js").then(({checkVersionOnStartup:A})=>A()),[{render:b},{createElement:P},{AppWrapper:h}]=await Promise.all([import("ink"),import("react"),import("./chunk-v19vaykx.js")]),Y={...K,initialMessage:Z,debug:K.debug,print:Boolean(K.print),versionCheckPromise:V};delete Y._,delete Y.$0,delete Y.message,b(P(h,Y),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await x.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)f().catch(console.error);export{f as main};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{va as Q}from"./chunk-
|
|
1
|
+
import{va as Q}from"./chunk-hhgbhadg.js";import{nb as U}from"./chunk-nhp35rk0.js";import{xb as O}from"./chunk-7ycmx7c2.js";import{Bb as N,zb as K}from"./chunk-set7v1rf.js";function Y(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var A=N("Service");function Z(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class D{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!D.instance)D.instance=new D;return D.instance}initialize(){if(this.initialized){A.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{A.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)A.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else A.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
|
|
2
2
|
再按一次 Ctrl+C 退出
|
|
3
3
|
`)}),this.initialized=!0,A.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),A.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),A.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){A.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0,A.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);try{await K()}catch(z){}try{let z=U.getInstance();if(z.isEnabled()){let F=Q(),W=F.session?.sessionId||"unknown",X=F.config?.config?.permissionMode||"default";await z.executeSessionEndHooks(Z(b),{projectDir:O(),sessionId:W,permissionMode:X})}}catch(z){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",z)}let B=5000,V=new Promise((z,F)=>{setTimeout(()=>{F(Error(`清理超时 (${B}ms)`))},B)});try{let z=this.runCleanupHandlers();await Promise.race([z,V])}catch(z){console.error("[GracefulShutdown] 清理过程中发生错误:",z)}finally{Y(),setTimeout(()=>{process.exit(q)},100)}}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let B=q();if(B instanceof Promise)await B}catch(B){console.error("[GracefulShutdown] 清理函数执行失败:",B)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var J=()=>{return D.getInstance()},H=(b)=>{return J().registerCleanup(b)},P=()=>{J().initialize()},L=(b=0)=>{J().shutdown("normal",b)};
|
|
4
4
|
export{J as l,H as m,P as n,L as o};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as V,G as f,J as N,K as L,M as T,S as h,U as P,V as R}from"./chunk-
|
|
1
|
+
import{A as V,G as f,J as N,K as L,M as T,S as h,U as P,V as R}from"./chunk-hj714bc0.js";import{Y as M}from"./chunk-kdpafv9g.js";import"./chunk-esnkk33h.js";import"./chunk-r7dz28wh.js";import"./chunk-v1c9xwen.js";import{za as y}from"./chunk-hhgbhadg.js";import"./chunk-c6ts8bd9.js";import{Sa as O}from"./chunk-9syksrkj.js";import"./chunk-yddnm9n2.js";import"./chunk-nhp35rk0.js";import"./chunk-pkmw32r0.js";import{xb as D}from"./chunk-7ycmx7c2.js";import{Bb as W}from"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import{Readable as K,Writable as k}from"node:stream";import*as _ from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as I}from"@agentclientprotocol/sdk";import{nanoid as S}from"nanoid";import{nanoid as x}from"nanoid";var X=W("Agent");class B{id;cwd;connection;clientCapabilities;agent=null;runtime=null;pendingPrompt=null;messages=[];mode="default";sessionApprovals=new Set;constructor(z,G,H,Q){this.id=z;this.cwd=G;this.connection=H;this.clientCapabilities=Q}async initialize(){X.debug(`[AcpSession ${this.id}] Initializing...`),V.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),X.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.runtime=await f.create({sessionId:this.id}),this.agent=await T.createWithRuntime(this.runtime,{sessionId:this.id}),X.debug(`[AcpSession ${this.id}] Agent created successfully`)}sendAvailableCommandsDelayed(){X.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),setTimeout(()=>{this.sendAvailableCommands()},500)}async handleSlashCommand(z,G){try{X.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,signal:G,acp:{sendMessage:(U)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:U}})},sendToolStart:(U,Y,q)=>{let Z=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,E=this.mapToolKind(q);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z,status:"in_progress",title:`${U}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(Y,null,2)}}],kind:E})},sendToolResult:(U,Y)=>{if(Y.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y.summary}})}}},Q=await P(z,H),J=Q.content||Q.message;if(J)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J}});if(Q.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Q.error}`}});return{stopReason:Q.success?"end_turn":"cancelled"}}catch(H){return X.error(`[AcpSession ${this.id}] Slash command error:`,H),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${H instanceof Error?H.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let z=R(),G=["model","permissions","theme","config","exit","ide"],Q=z.filter((J)=>!G.includes(J.name)).map((J)=>{let U;if(J.usage){let Y=J.usage.replace(/^\/\w+\s*/,"").trim();if(Y)U=Y}if(J.aliases?.length){let Y=`Aliases: ${J.aliases.join(", ")}`;U=U?`${U} | ${Y}`:Y}return{name:J.name,description:J.description,input:U?{hint:U}:void 0}});X.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Q.map((J)=>J.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Q}),X.info(`[AcpSession ${this.id}] Sent ${Q.length} available commands`)}catch(z){X.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z){V.setCurrentSession(this.id),this.pendingPrompt?.abort();let G=new AbortController;if(this.pendingPrompt=G,!this.agent)throw Error("Session not initialized");try{let H=this.resolvePrompt(z.prompt);if(X.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),h(H))return await this.handleSlashCommand(H,G.signal);let Q={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:G.signal,permissionMode:this.mapModeToPermissionMode(),confirmationHandler:{requestConfirmation:async(J)=>{return this.requestPermission(J)}}};if(await O(this.agent.chatStream(H,Q),async(J)=>{switch(J.kind){case"content_delta":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:J.delta}});break;case"tool_start":{let U=J.toolCall,Y="function"in U?U.function.name:U.type,q=this.mapToolKind(J.toolKind);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.id,status:"in_progress",title:`Executing ${Y}`,content:[],kind:q});break}case"tool_result":{let{toolCall:U,result:Y}=J,q=[],Z=Y.metadata;if(Z?.kind==="edit"&&typeof Z.file_path==="string"&&typeof Z.oldContent==="string"&&(typeof Z.newContent==="string"||Z.newContent===void 0))q.push({type:"diff",path:Z.file_path,oldText:Z.oldContent,newText:Z.newContent??null});else{let F="function"in U?U.function.name:U.type,j=L(N(F,Y));q.push({type:"content",content:{type:"text",text:j}})}let E=Y.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.id,status:E,content:q});break}case"task_update":this.sendPlanUpdate(J.tasks);break;default:break}}),this.messages=[...Q.messages],G.signal.aborted)return{stopReason:"cancelled"};return{stopReason:"end_turn"}}catch(H){if(G.signal.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};throw X.error(`[AcpSession ${this.id}] Prompt error:`,H),H}finally{if(this.pendingPrompt===G)this.pendingPrompt=null}}cancel(){if(X.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,X.info(`[AcpSession ${this.id}] Cancelled successfully`);else X.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let G=["default","auto-edit","yolo","plan"];this.mode=G.includes(z)?z:"default",X.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){switch(this.mode){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(X.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.agent)X.warn(`[AcpSession ${this.id}] Runtime model switching not yet implemented`)}async destroy(){if(this.cancel(),this.agent)await this.agent.destroy(),this.agent=null;if(this.runtime)await this.runtime.dispose(),this.runtime=null;V.destroySession(this.id),X.debug(`[AcpSession ${this.id}] Destroyed`)}resolvePrompt(z){let G=[];for(let H of z)if(H.type==="text")G.push(H.text);else if(H.type==="image")G.push(`[Image: ${H.mimeType}]`);else if(H.type==="resource"){let Q=H.resource;if("text"in Q)G.push(`<file path="${Q.uri}">
|
|
2
2
|
${Q.text}
|
|
3
3
|
</file>`)}else if(H.type==="resource_link")G.push(`[Resource: ${H.uri}]`);return G.join(`
|
|
4
4
|
`)}sendUpdate(z){let G={sessionId:this.id,update:z};this.connection.sessionUpdate(G).catch((H)=>{X.warn(`[AcpSession ${this.id}] Failed to send update:`,H)})}sendPlanUpdate(z){let G=z.map((H)=>({content:H.subject,priority:H.priority,status:H.status}));X.debug(`[AcpSession ${this.id}] Sending plan update with ${G.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:G})}async requestPermission(z){let G=z.kind?.toLowerCase()||"execute";if(this.shouldAutoApprove(G))return X.debug(`[AcpSession ${this.id}] Auto-approving ${G} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(G==="write"||G==="execute"))return X.debug(`[AcpSession ${this.id}] Rejecting ${G} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};let H=`${G}:${z.title||"unknown"}`;if(this.sessionApprovals.has(H))return X.debug(`[AcpSession ${this.id}] Using cached approval for: ${H}`),{approved:!0};try{let Q=x(),J=[];if(z.message)J.push({type:"content",content:{type:"text",text:z.message}});if(z.risks&&z.risks.length>0)J.push({type:"content",content:{type:"text",text:`Risks:
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ba as d,da as h}from"./chunk-
|
|
1
|
+
import{ba as d,da as h}from"./chunk-r7dz28wh.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
|
|
2
2
|
export{q as t,w as u};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{nb as W0}from"./chunk-
|
|
1
|
+
import{nb as W0}from"./chunk-nhp35rk0.js";import{rb as s0}from"./chunk-pkmw32r0.js";import{xb as h}from"./chunk-7ycmx7c2.js";import{Bb as M}from"./chunk-set7v1rf.js";import{Db as bQ}from"./chunk-j2ag7hh6.js";function G0(Q){return Q.role==="system"&&Array.isArray(Q.content)}class q0{systemMessages;_history;_pending=[];context;constructor(Q,$){this.context=Q;let Z=Q.messages.find(G0);if(Z)this.systemMessages=[Z];else if($)this.systemMessages=[{role:"system",content:[{type:"text",text:$,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]}];else this.systemMessages=[];this._history=Q.messages.filter((J)=>!G0(J))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending(Q){this._pending.push(Q)}appendUser(Q){this._pending.push(Q)}appendAssistant(Q){this._pending.push(Q)}appendToolResult(Q){this._pending.push(Q)}appendControl(Q,$){if(Q==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push($)}appendToHistory(Q){this._history.push(Q)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory(Q){this._history=Q.filter(($)=>!G0($))}writeback(){this.commitPending(),this.context.messages=this._history}get hasSystemPrompt(){return this.systemMessages.length>0}}async function _Q(Q,$){let Z;while(!(Z=await Q.next()).done)if($)await $(Z.value);return Z.value}function m0(Q){if(Q.isSubagent)return"continue";if(!Q.budget||Q.budget<=0)return"continue";if(Q.consecutiveContinuations>=3&&Q.lastOutputDelta<500)return"stop";if(Q.usage/Q.budget>=0.9)return"stop";return"continue"}function g0(Q){return{budget:Q.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:Q.isSubagent??!1}}function c0(Q,$,Z){return{...Q,usage:Q.usage+$,lastOutputDelta:$,consecutiveContinuations:Z?Q.consecutiveContinuations+1:0}}var a=M("Agent"),NQ=3;function U0(Q,$,Z){if(Q!=="length")return{action:"none"};if($>=NQ)return{action:"truncated"};if(m0(Z)==="stop")return a.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var EQ=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i],IQ="请执行你提到的操作,不要只是描述。",UQ=2;function v0(Q,$){if(!Q||$>=UQ)return{action:"none"};let Z=Q.slice(-200),J=Z.match(/```/g);if(J&&J.length%2!==0)return{action:"none"};if(EQ.some((G)=>G.test(Z)))return{action:"retry",prompt:IQ};return{action:"none"}}var u0=30000;async function A0(Q){try{let Z=W0.getInstance().executeStopHooks({projectDir:h(),sessionId:Q.sessionId,permissionMode:Q.permissionMode,reason:Q.reason,abortSignal:Q.abortSignal}),J,z=new Promise((G)=>{J=setTimeout(()=>G("timeout"),u0)});try{let G=await Promise.race([Z,z]);if(G==="timeout")return a.warn(`[Loop] Stop hook 超时 (${u0}ms),按 shouldStop: true 处理`),{action:"stop"};let q=G;if(!q.shouldStop)return{action:"continue",reason:q.continueReason};return{action:"stop"}}finally{clearTimeout(J)}}catch($){return a.warn("[Loop] Stop hook execution failed:",$),{action:"stop"}}}var vQ=0.9;async function i0(Q){try{let{SpecManager:$}=await import("./chunk-pmtfesmc.js"),Z=$.getInstance();if(!Z.isActive())return{action:"none"};let J=Z.getCurrentSpec();if(!J||J.phase!=="implementation")return{action:"none"};if(Q.maxTurns>0&&Q.turnsCount>=Q.maxTurns*vQ)return a.info(`[RalphLoop] 轮次接近上限 (${Q.turnsCount}/${Q.maxTurns}),停止自动继续`),{action:"none"};let z=J.tasks??[],G=z.filter((K)=>K.status==="completed"||K.status==="skipped").length,q=z.length;if(G>=q)return{action:"none"};let W=z.find((K)=>K.status==="pending"||K.status==="in_progress"),V=`[Ralph Loop] Spec "${J.name}" 仍有未完成任务。
|
|
2
2
|
`+`进度: ${G}/${q} 任务已完成。
|
|
3
3
|
`+(W?`下一个任务: ${W.title}${W.description?` — ${W.description}`:""}
|
|
4
4
|
`:"")+"请继续执行下一个未完成的任务,不要停止。";return a.info(`[RalphLoop] Spec "${J.name}" 进度 ${G}/${q},自动继续`),{action:"continue",reason:V}}catch{return{action:"none"}}}var o=M("Agent");function s(Q){return Q.executionEngine?.getContextManager()}async function m(Q,$,Z,J=null){try{let z=s(Q),G=typeof Z==="string"?Z.trim()!=="":Z.some((q)=>q.type==="text"?q.text.trim()!=="":!0);if(z&&$.sessionId&&G)return await z.saveMessage($.sessionId,"user",Z,J,void 0,$.subagentInfo)}catch(z){o.warn("[Loop] 保存用户消息失败:",z)}return null}async function k(Q,$,Z,J){try{let z=s(Q);if(z&&$.sessionId&&Z.trim())return await z.saveMessage($.sessionId,"assistant",Z,J,void 0,$.subagentInfo)}catch(z){o.warn("[Loop] 保存助手消息失败:",z)}return null}async function y0(Q,$,Z,J,z){try{let G=s(Q);if(G&&$.sessionId)return await G.saveToolUse($.sessionId,Z,J,z,$.subagentInfo)}catch(G){o.warn("[Loop] 保存工具调用失败:",G)}return null}async function S0(Q,$,Z,J,z,G,q,W){try{let V=s(Q);if(V&&$.sessionId)return await V.saveToolResult($.sessionId,Z,J,z,G,q,$.subagentInfo,W)}catch(V){o.warn("[Loop] 保存工具结果失败:",V)}return null}async function V0(Q,$,Z,J){try{let z=s(Q);if(z&&$.sessionId)return await z.saveCompaction($.sessionId,Z,J,null)}catch(z){o.warn("[Loop] 保存压缩数据失败:",z)}return null}function n0(Q,$){if(!["TaskCreate","TaskUpdate","TaskList"].includes(Q.function.name)||!$.success||!$.llmContent&&!$.metadata)return null;let Z=typeof $.llmContent==="object"?$.llmContent:{};return{kind:"task_update",tasks:$.metadata?.tasks||Z.tasks||[]}}function l0(Q,$,Z){if(Q.function.name!=="Skill"||!$.success||!$.metadata)return;let J=$.metadata;if(J.skillName)Z.onSkillActivated?.({skillName:J.skillName,allowedTools:J.allowedTools,basePath:J.basePath||""})}function a0(Q){let $=Q.metadata;if(!$)return;return $.modelId?.toString().trim()||$.model?.toString().trim()||void 0||void 0}async function P0(Q,$,Z){let J=n0(Q,$);l0(Q,$,Z);let z=a0($);if(z)await Z.onModelSwitch?.(z);return J}import{nanoid as rQ}from"nanoid";import{promises as SQ}from"node:fs";import{nanoid as c}from"nanoid";import{promises as Y0}from"node:fs";var t=M("Tool");class C{static instance=null;accessedFiles=new Map;constructor(){}static getInstance(){if(!C.instance)C.instance=new C;return C.instance}async recordFileRead(Q,$){try{let Z=await Y0.stat(Q),J={filePath:Q,accessTime:Date.now(),mtime:Z.mtimeMs,sessionId:$,lastOperation:"read"};this.accessedFiles.set(Q,J),t.debug(`记录文件读取: ${Q}`)}catch(Z){t.warn(`记录文件读取失败: ${Q}`,Z)}}async recordFileEdit(Q,$,Z="edit"){try{let J=await Y0.stat(Q),z={filePath:Q,accessTime:Date.now(),mtime:J.mtimeMs,sessionId:$,lastOperation:Z};this.accessedFiles.set(Q,z),t.debug(`记录文件${Z==="edit"?"编辑":"写入"}: ${Q}`)}catch(J){t.warn(`记录文件${Z==="edit"?"编辑":"写入"}失败: ${Q}`,J)}}hasFileBeenRead(Q,$){let Z=this.accessedFiles.get(Q);if(!Z)return!1;if($&&Z.sessionId!==$)return!1;return!0}async checkFileModification(Q){let $=this.accessedFiles.get(Q);if(!$)return{modified:!1,message:"文件未被跟踪"};try{let Z=await Y0.stat(Q);if(Math.abs(Z.mtimeMs-$.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date($.accessTime).toISOString()}, 当前修改时间: ${Z.mtime.toISOString()})`};return{modified:!1}}catch(Z){let J=Z;if(J.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${J.message}`}}}async checkExternalModification(Q){let $=this.accessedFiles.get(Q);if(!$)return{isExternal:!1,message:"文件未被跟踪"};try{let Z=await Y0.stat(Q);if(Z.mtimeMs-$.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date($.accessTime).toISOString()} (${$.lastOperation}) 之后被外部程序修改(当前修改时间: ${Z.mtime.toISOString()})`};return{isExternal:!1}}catch(Z){let J=Z;if(J.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return t.warn(`检查文件外部修改失败: ${Q}`,Z),{isExternal:!1,message:`无法检查文件状态: ${J.message}`}}}getFileRecord(Q){return this.accessedFiles.get(Q)}clearFileRecord(Q){this.accessedFiles.delete(Q)}clearAll(){this.accessedFiles.clear()}clearSession(Q){for(let[$,Z]of this.accessedFiles.entries())if(Z.sessionId===Q)this.accessedFiles.delete($)}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){C.instance=null}}import{readFile as AQ}from"node:fs/promises";import{basename as yQ}from"node:path";class X0{static MAX_FILES=5;static MAX_LINES_PER_FILE=1000;static analyzeFiles(Q){let $=new Map;return Q.forEach((J,z)=>{let G=typeof J.content==="string"?J.content:(J.content||[]).filter((W)=>W.type==="text").map((W)=>W.text).join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{N as l,O as c,P as m,S as g,U as d}from"./chunk-
|
|
1
|
+
import{N as l,O as c,P as m,S as g,U as d}from"./chunk-hj714bc0.js";import{xb as u}from"./chunk-7ycmx7c2.js";async function C(){if((await l().initialize(u(),[])).plugins.length>0)await c()}async function h(t){let e=t.message||t._?.[0];if(typeof e==="string"&&e.trim())return e;let n=t.stdin??process.stdin;if(!n.isTTY){let a=[];for await(let i of n)a.push(i);return Buffer.concat(a).toString("utf-8").trim()}if(t.defaultMessage!==void 0)return t.defaultMessage;throw Error("No input provided")}async function R(t){if(!g(t))return{mode:"agent",content:t};let e=await d(t,{cwd:u(),workspaceRoot:u()});if(!e.success)return{mode:"output",content:`Error: ${e.error||"未知错误"}`,exitCode:1};let n=e.data;if(n?.action==="invoke_skill"){let{skillName:a,skillArgs:i}=n;return{mode:"agent",content:i?`Please use the "${a}" skill to help me with: ${i}`:`Please use the "${a}" skill.`}}if(n?.action==="invoke_custom_command"||n?.action==="invoke_plugin_command"){let a=n.processedContent;return{mode:"agent",content:`# Custom Command: /${n.commandName}
|
|
2
2
|
|
|
3
3
|
${a}`}}return{mode:"output",content:e.content||e.message||"",exitCode:0}}function r(t){if(!(t instanceof Error))return!1;return t.message.includes("未找到会话")||t.message.includes("ENOENT")||t.message.includes("no such file")}async function s(t){try{return await m.loadSession(t,u())}catch(e){if(r(e))return null;throw e}}async function N(t){if(t.resume===!0||t.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof t.resume==="string"&&t.resume.length>0)return{sessionId:t.resume,messages:await m.loadSession(t.resume)};if(t.continue){let e=await m.listSessions();if(e.length>0){let n=e[0].sessionId;return{sessionId:n,messages:await m.loadSession(n)}}}if(t.sessionId)return{sessionId:t.sessionId,messages:await s(t.sessionId)??[]};return{sessionId:`${t.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
|
|
4
4
|
export{C as p,h as q,R as r,N as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as a,u as b}from"./chunk-45f363j6.js";import"./chunk-r7dz28wh.js";import"./chunk-j2ag7hh6.js";export{a as globalOptions,b as cliConfig};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import{xb as Z}from"./chunk-7ycmx7c2.js";import{Bb as E}from"./chunk-set7v1rf.js";var G={currentModelId:"",models:[],temperature:0,maxContextTokens:128000,maxOutputTokens:void 0,stream:!0,topP:0.9,topK:50,timeout:180000,theme:"dracula",uiTheme:"system",language:"zh-CN",fontSize:14,autoSaveSessions:!0,notifyBuild:!0,notifyErrors:!1,notifySounds:!1,privacyTelemetry:!1,privacyCrash:!0,debug:!1,mcpEnabled:!1,mcpServers:{},permissions:{allow:["Bash(pwd)","Bash(which *)","Bash(whoami)","Bash(hostname)","Bash(uname *)","Bash(date)","Bash(echo *)","Bash(ls *)","Bash(tree *)","Bash(git status)","Bash(git status -*)","Bash(git log *)","Bash(git diff *)","Bash(git show *)","Bash(git branch -* *)","Bash(git branch)","Bash(git tag -l *)","Bash(git tag --list *)","Bash(git stash list *)","Bash(git stash show *)","Bash(git rev-parse *)","Bash(git describe *)","Bash(git blame *)","Bash(git ls-files *)","Bash(git config --get *)","Bash(git config --list *)","Bash(git shortlog *)","Bash(git merge-base *)","Bash(git cat-file *)","Bash(git for-each-ref *)","Bash(git grep *)","Bash(git worktree list *)","Bash(git reflog show *)","Bash(git reflog)","Bash(git rev-list *)","Bash(git ls-remote *)","Bash(git remote -v)","Bash(git remote --verbose)","Bash(git remote)","Bash(gh pr view *)","Bash(gh pr list *)","Bash(gh pr diff *)","Bash(gh pr checks *)","Bash(gh pr status *)","Bash(gh issue view *)","Bash(gh issue list *)","Bash(gh issue status *)","Bash(gh run list *)","Bash(gh run view *)","Bash(gh repo view *)","Bash(gh auth status)","Bash(npm list *)","Bash(bun pm ls *)","Bash(npm view *)","Bash(npm outdated *)","Bash(pnpm list *)","Bash(yarn list *)","Bash(pip list *)","Bash(pip show *)"],ask:["Bash(curl *)","Bash(wget *)","Bash(aria2c *)","Bash(axel *)","Bash(rm -rf *)","Bash(rm -r *)","Bash(rm --recursive *)","Bash(nc *)","Bash(netcat *)","Bash(telnet *)","Bash(ncat *)"],deny:["Read(./.env)","Read(./.env.*)","Bash(rm -rf /)","Bash(rm -rf /*)","Bash(sudo *)","Bash(chmod 777 *)","Bash(bash *)","Bash(sh *)","Bash(zsh *)","Bash(fish *)","Bash(dash *)","Bash(eval *)","Bash(source *)","Bash(mkfs *)","Bash(fdisk *)","Bash(dd *)","Bash(format *)","Bash(parted *)","Bash(open http*)","Bash(open https*)","Bash(xdg-open http*)","Bash(xdg-open https*)"]},permissionMode:"default",hooks:{enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionRequest:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]},env:{},disableAllHooks:!1,maxTurns:-1};import{promises as N}from"fs";import{merge as U}from"lodash-es";import _ from"os";import D from"path";class B{static instance=null;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}static resetInstance(){B.instance=null}async initialize(){try{let J=await this.loadConfigFiles(),q=await this.loadSettingsFiles(),H={...J,...q},K=this.normalizeConfig(H),Q={...G,...K};if(this.resolveEnvInterpolation(Q),Q.debug)console.log("[ConfigManager] Configuration loaded successfully");return Q}catch(J){return console.error("[ConfigManager] Failed to initialize:",J),G}}async loadConfigFiles(){let J=D.join(_.homedir(),".blade","config.json"),q=D.join(Z(),".blade","config.json"),H={},K=await this.loadJsonFile(J);if(K)H={...H,...K};let Q=await this.loadJsonFile(q);if(Q){let W={...H.mcpServers||{},...Q.mcpServers||{}};if(H={...H,...Q},Object.keys(W).length>0)H.mcpServers=W}return H}async loadSettingsFiles(){let J=D.join(_.homedir(),".blade","settings.json"),q=D.join(Z(),".blade","settings.json"),H=D.join(Z(),".blade","settings.local.json"),K={},Q=await this.loadJsonFile(J);if(Q)K=this.mergeSettings(K,Q);let W=await this.loadJsonFile(q);if(W)K=this.mergeSettings(K,W);let X=await this.loadJsonFile(H);if(X)K=this.mergeSettings(K,X);return K}mergeSettings(J,q){let H=JSON.parse(JSON.stringify(J));if(q.permissions){if(!H.permissions)H.permissions={allow:[],ask:[],deny:[]};if(q.permissions.allow){let K=[...H.permissions.allow||[],...q.permissions.allow];H.permissions.allow=Array.from(new Set(K))}if(q.permissions.ask){let K=[...H.permissions.ask||[],...q.permissions.ask];H.permissions.ask=Array.from(new Set(K))}if(q.permissions.deny){let K=[...H.permissions.deny||[],...q.permissions.deny];H.permissions.deny=Array.from(new Set(K))}}if(q.hooks)H.hooks=U({},H.hooks,q.hooks);if(q.env)H.env=U({},H.env,q.env);if(q.mcpServers)H.mcpServers={...H.mcpServers||{},...q.mcpServers};if(q.disableAllHooks!==void 0)H.disableAllHooks=q.disableAllHooks;if(q.permissionMode!==void 0)H.permissionMode=q.permissionMode;if(q.maxTurns!==void 0)H.maxTurns=q.maxTurns;return H}resolveEnvInterpolation(J){let q=/\$\{?([A-Z_][A-Z0-9_]*)(:-([^}]+))?\}?/g,H=(Q)=>{if(typeof Q==="string")return Q.replace(q,(W,X,Y,V)=>{return process.env[X]||V||W});if(Array.isArray(Q))return Q.map(H);if(typeof Q==="object"&&Q!==null){let W=Q;for(let[X,Y]of Object.entries(W))W[X]=H(Y);return W}return Q},K=J;for(let[Q,W]of Object.entries(K))K[Q]=H(W)}async loadJsonFile(J){try{if(await this.fileExists(J)){let q=await N.readFile(J,"utf-8");return JSON.parse(q)}}catch(q){console.warn(`[ConfigManager] Failed to load ${J}:`,q)}return null}async fileExists(J){try{return await N.access(J),!0}catch{return!1}}normalizeConfig(J){let q=JSON.parse(JSON.stringify(J)),H=(Q)=>Q.trim().replace(/^`|`$/g,""),K=(Q)=>{for(let[W,X]of Object.entries(Q))if(typeof X==="string")Q[W]=H(X);else if(Array.isArray(X))X.forEach((Y,V)=>{if(typeof Y==="string")X[V]=H(Y);else if(typeof Y==="object"&&Y!==null)K(Y)});else if(typeof X==="object"&&X!==null)K(X)};return K(q),q}validateConfig(J){let q=[],H=[];if(!J.models||J.models.length===0)q.push("没有可用的模型配置");if(J.models&&J.models.length>0){if(!J.currentModelId)q.push("未设置当前模型 ID");else if(!J.models.find((Q)=>Q.id===J.currentModelId))q.push(`当前模型 ID "${J.currentModelId}" 在 models 列表中不存在`);for(let K of J.models){let Q=`模型 "${K.name||K.id}"`;if(!K.apiKey)H.push(`${Q}: apiKey 为空`);if(!K.model)q.push(`${Q}: model 字段必填`);if(!K.provider)q.push(`${Q}: provider 字段必填`);if(K.baseUrl&&!K.baseUrl.startsWith("http"))H.push(`${Q}: baseUrl "${K.baseUrl}" 不是有效的 HTTP URL`)}}if(H.length>0)console.warn(`[ConfigManager] 配置警告:
|
|
2
|
+
${H.map((K)=>` ⚠ ${K}`).join(`
|
|
3
|
+
`)}`);if(q.length>0)throw Error(`配置验证失败:
|
|
4
|
+
${q.map((K)=>` - ${K}`).join(`
|
|
5
|
+
`)}
|
|
6
|
+
|
|
7
|
+
`+`请通过以下方式之一提供配置:
|
|
8
|
+
`+` 1. 首次启动: 运行 blade,系统会自动引导配置
|
|
9
|
+
`+` 2. 添加模型: blade 后输入 /model add
|
|
10
|
+
`+` 3. 初始化向导: 输入 /init
|
|
11
|
+
|
|
12
|
+
`+`配置文件示例 (~/.blade/config.json):
|
|
13
|
+
`+`{
|
|
14
|
+
"currentModelId": "model-id-123",
|
|
15
|
+
"models": [
|
|
16
|
+
{
|
|
17
|
+
"id": "model-id-123",
|
|
18
|
+
`+` "name": "默认模型",
|
|
19
|
+
`+` "provider": "openai-compatible",
|
|
20
|
+
"apiKey": "your-api-key",
|
|
21
|
+
"baseUrl": "https://api.example.com/v1",
|
|
22
|
+
"model": "model-name"
|
|
23
|
+
}
|
|
24
|
+
]
|
|
25
|
+
}
|
|
26
|
+
`)}}function L(J,q={}){let H={...J};if(q.debug!==void 0)H.debug=q.debug===""?!0:q.debug;if(q.model){if(!J.models.some((Q)=>Q.id===q.model))throw Error(`模型配置未找到: ${q.model}`);H.currentModelId=q.model}if(q.yolo===!0)H.permissionMode="yolo";else if(q.permissionMode!==void 0)H.permissionMode=q.permissionMode;if(q.maxTurns!==void 0)H.maxTurns=q.maxTurns;return H.systemPrompt=q.systemPrompt,H.appendSystemPrompt=q.appendSystemPrompt,H.model=q.model,H.resumeSessionId=q.sessionId,H.forkSession=q.forkSession,H.allowedTools=q.allowedTools,H.disallowedTools=q.disallowedTools,H.mcpConfigPaths=q.mcpConfig,H.strictMcpConfig=q.strictMcpConfig,H.addDirs=q.addDir,H.outputFormat=q.outputFormat,H.inputFormat=q.inputFormat,H.print=q.print,H.includePartialMessages=q.includePartialMessages,H.replayUserMessages=q.replayUserMessages,H.agentsConfig=q.agents,H.settingSources=q.settingSources,H}import{Mutex as I}from"async-mutex";import{merge as w}from"lodash-es";import{promises as A}from"node:fs";import M from"node:os";import z from"node:path";import S from"write-file-atomic";var T=E("Service"),R={models:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},currentModelId:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},temperature:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxContextTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxOutputTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},timeout:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},theme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},uiTheme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},language:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},debug:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},fontSize:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},autoSaveSessions:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyBuild:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyErrors:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifySounds:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyTelemetry:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyCrash:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},permissionMode:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},permissions:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},hooks:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},env:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},disableAllHooks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxTurns:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},mcpServers:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},stream:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topP:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topK:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},mcpEnabled:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},systemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},appendSystemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},initialMessage:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},resumeSessionId:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},forkSession:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},allowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},disallowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},mcpConfigPaths:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},strictMcpConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},addDirs:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},outputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},inputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},print:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},includePartialMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},replayUserMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},agentsConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},settingSources:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1}},t=new Set(Object.entries(R).filter(([J,q])=>q.persistable).map(([J])=>J)),i=new Set(Object.entries(R).filter(([J,q])=>!q.persistable).map(([J])=>J));class ${static instance=null;pendingUpdates=new Map;timers=new Map;fileLocks=new Map;lastSaveError=null;debounceDelay=300;constructor(){}static getInstance(){if(!$.instance)$.instance=new $;return $.instance}static resetInstance(){if($.instance)for(let J of $.instance.timers.values())clearTimeout(J);$.instance=null}async save(J,q={}){this.validatePersistableFields(J);let H=this.groupUpdatesByTarget(J,q.scope);if(q.immediate)await Promise.all(Array.from(H.entries()).map(([K,Q])=>this.flushTarget(K,Q)));else for(let[K,Q]of H)this.scheduleSave(K,Q)}async flush(){for(let q of this.timers.values())clearTimeout(q);this.timers.clear();let J=Array.from(this.pendingUpdates.entries()).map(([q,H])=>this.flushTarget(q,H));this.pendingUpdates.clear(),await Promise.all(J)}getLastSaveError(){return this.lastSaveError}clearLastSaveError(){this.lastSaveError=null}async appendPermissionRule(J,q={}){let H=q.scope??"local",K=this.resolveFilePath("settings",H);await this.flushTargetWithModifier(K,(Q)=>{let W=Q.permissions??{allow:[],ask:[],deny:[]},X={allow:this.dedupeArray([...W.allow||[],J]),ask:W.ask||[],deny:W.deny||[]};return{...Q,permissions:X}})}async appendLocalPermissionRule(J,q={}){await this.appendPermissionRule(J,{...q,scope:"local"})}validatePersistableFields(J){for(let q of Object.keys(J)){let H=R[q];if(!H)throw Error(`Unknown config field: ${q}`);if(!H.persistable)throw Error(`Field "${q}" is non-persistable and cannot be saved to config files. Non-persistable fields are runtime-only and only valid for the current session.`)}}groupUpdatesByTarget(J,q){let H=new Map;for(let[K,Q]of Object.entries(J)){let W=R[K];if(!W)continue;let X=q??W.defaultScope,Y=this.resolveFilePath(W.target,X);if(!H.has(Y))H.set(Y,{});H.get(Y)[K]=Q}return H}resolveFilePath(J,q){if(J==="config")return q==="global"?z.join(M.homedir(),".blade","config.json"):z.join(Z(),".blade","config.json");switch(q){case"local":return z.join(Z(),".blade","settings.local.json");case"project":return z.join(Z(),".blade","settings.json");case"global":return z.join(M.homedir(),".blade","settings.json");default:return z.join(Z(),".blade","settings.local.json")}}scheduleSave(J,q){let H=this.pendingUpdates.get(J)??{},K=this.mergePendingUpdates(H,q);this.pendingUpdates.set(J,K);let Q=this.timers.get(J);if(Q)clearTimeout(Q);let W=setTimeout(async()=>{let X=this.pendingUpdates.get(J);if(X){this.pendingUpdates.delete(J),this.timers.delete(J);try{await this.flushTarget(J,X),this.lastSaveError=null}catch(Y){let V=Y instanceof Error?Y:Error(String(Y));this.lastSaveError=V,T.error(`Failed to save config to ${J}:`,V.message),T.error("Stack trace:",V.stack)}}},this.debounceDelay);this.timers.set(J,W)}mergePendingUpdates(J,q){let H={...J};for(let[K,Q]of Object.entries(q)){let W=R[K];if(!W){H[K]=Q;continue}switch(W.mergeStrategy){case"replace":H[K]=Q;break;case"append-dedupe":this.applyAppendDedupe(H,K,Q);break;case"deep-merge":this.applyDeepMerge(H,K,Q);break}}return H}async flushTarget(J,q){let H=this.fileLocks.get(J);if(!H)H=new I,this.fileLocks.set(J,H);await H.runExclusive(async()=>{await this.performWrite(J,q)})}async flushTargetWithModifier(J,q){let H=this.fileLocks.get(J);if(!H)H=new I,this.fileLocks.set(J,H);await H.runExclusive(async()=>{await A.mkdir(z.dirname(J),{recursive:!0,mode:493});let K={};try{let W=await A.readFile(J,"utf-8");K=JSON.parse(W)}catch{K={}}let Q=q(K);await this.atomicWrite(J,Q)})}async performWrite(J,q){await A.mkdir(z.dirname(J),{recursive:!0,mode:493});let H={};try{let Q=await A.readFile(J,"utf-8");H=JSON.parse(Q)}catch{H={}}let K={...H};for(let[Q,W]of Object.entries(q)){let X=R[Q];if(!X){K[Q]=W;continue}switch(X.mergeStrategy){case"replace":K[Q]=W;break;case"append-dedupe":this.applyAppendDedupe(K,Q,W);break;case"deep-merge":this.applyDeepMerge(K,Q,W);break}}await this.atomicWrite(J,K)}applyAppendDedupe(J,q,H){if(q==="permissions"&&typeof H==="object"&&H!==null){let K=J[q]??{allow:[],ask:[],deny:[]},Q=H;J[q]={allow:this.dedupeArray([...K.allow||[],...Q.allow||[]]),ask:this.dedupeArray([...K.ask||[],...Q.ask||[]]),deny:this.dedupeArray([...K.deny||[],...Q.deny||[]])}}else if(Array.isArray(H)){let K=Array.isArray(J[q])?J[q]:[];J[q]=this.dedupeArray([...K,...H])}else J[q]=H}applyDeepMerge(J,q,H){if(typeof H==="object"&&H!==null&&!Array.isArray(H)){let K=typeof J[q]==="object"&&J[q]!==null?J[q]:{};J[q]=w({},K,H)}else J[q]=H}dedupeArray(J){return Array.from(new Set(J))}async atomicWrite(J,q){await S(J,JSON.stringify(q,null,2),{mode:384,encoding:"utf-8"})}}function b(){return $.getInstance()}export{G as Ha,B as Ia,L as Ja,b as Ka};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Aa as g,Ba as h,Ca as i,Da as j,Ea as k,Fa as l,Ga as m,ua as a,va as b,wa as c,xa as d,ya as e,za as f}from"./chunk-
|
|
1
|
+
import{Aa as g,Ba as h,Ca as i,Da as j,Ea as k,Fa as l,Ga as m,ua as a,va as b,wa as c,xa as d,ya as e,za as f}from"./chunk-hhgbhadg.js";import"./chunk-c6ts8bd9.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,h as getAllModels,g as ensureStoreInitialized,m as configActions,d as appActions};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{Ia as t}from"./chunk-
|
|
1
|
+
import{Ia as t}from"./chunk-c6ts8bd9.js";import{xb as r}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import{Db as s}from"./chunk-j2ag7hh6.js";var m={command:"doctor",describe:"Check the health of your Blade installation",handler:async()=>{console.log(`Running Blade health check...
|
|
2
2
|
`);let e=0;try{await t.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(o){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${o instanceof Error?o.message:"未知错误"}`),e++}let n=process.version;if(parseInt(n.slice(1).split(".")[0])>=18)console.log(`[OK] Node.js version: ${n}`);else console.log(`[WARN] Node.js version: ${n} (recommended: v18+)`),e++;try{let o=await import("fs/promises"),i=r();await o.access(i,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(o){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),e++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(o){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),e++}if(console.log(`
|
|
3
3
|
Health Check Summary:`),e===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${e} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{m as doctorCommands};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{p as z,q as g,r as v,s as p}from"./chunk-
|
|
1
|
+
import{p as z,q as g,r as v,s as p}from"./chunk-9tgyev1k.js";import{t as E}from"./chunk-45f363j6.js";import{v as S,w as h,x as c}from"./chunk-r8wmg3fc.js";import{G as w,I as F,J as y,L as x,M as C}from"./chunk-hj714bc0.js";import"./chunk-kdpafv9g.js";import"./chunk-esnkk33h.js";import"./chunk-r7dz28wh.js";import"./chunk-v1c9xwen.js";import"./chunk-hhgbhadg.js";import"./chunk-c6ts8bd9.js";import{Sa as O}from"./chunk-9syksrkj.js";import"./chunk-yddnm9n2.js";import"./chunk-nhp35rk0.js";import"./chunk-pkmw32r0.js";import{wb as H,xb as T}from"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";import bq from"yargs";import{hideBin as Uq}from"yargs/helpers";import{z as b}from"zod";import{z as Q}from"zod";var L=1,V=Q.object({event_version:Q.literal(L)}),i=V.extend({type:Q.literal("content_delta"),delta:Q.string()}),n=V.extend({type:Q.literal("thinking_delta"),delta:Q.string()}),r=V.extend({type:Q.literal("thinking"),content:Q.string()}),s=V.extend({type:Q.literal("stream_end")}),o=V.extend({type:Q.literal("content"),content:Q.string()}),a=V.extend({type:Q.literal("tool_start"),tool_name:Q.string(),summary:Q.string(),target:Q.string().optional(),tool_kind:Q.enum(["readonly","write","execute"]).optional()}),t=V.extend({type:Q.literal("tool_result"),tool_name:Q.string(),summary:Q.string(),target:Q.string().optional(),tool_kind:Q.enum(["readonly","write","execute"]).optional()}),e=V.extend({type:Q.literal("phase"),phase:Q.enum(["turn","searching","inspecting","target_hit","executing","completed"]),status:Q.enum(["ongoing","hit","done"]),message:Q.string(),turn:Q.number().optional(),tool_name:Q.string().optional(),target:Q.string().optional()}),qq=V.extend({type:Q.literal("tool_detail"),tool_name:Q.string(),detail:Q.string()}),Gq=V.extend({type:Q.literal("task_update"),tasks:Q.array(x)}),Qq=V.extend({type:Q.literal("token_usage"),input_tokens:Q.number(),output_tokens:Q.number(),total_tokens:Q.number(),max_context_tokens:Q.number()}),Xq=V.extend({type:Q.literal("compacting"),state:Q.enum(["started","completed"])}),Yq=V.extend({type:Q.literal("turn_limit"),turns_count:Q.number(),action:Q.literal("continue")}),Zq=V.extend({type:Q.literal("output"),content:Q.string(),exit_code:Q.number()}),$q=V.extend({type:Q.literal("error"),message:Q.string()}),Nq=Q.discriminatedUnion("type",[i,n,r,s,o,a,t,e,qq,Gq,Qq,Xq,Yq,Zq,$q]);function N(G,X){return{event_version:L,type:G,...X}}var Kq=b.enum(["text","jsonl"]),Aq=b.object({headless:b.boolean().optional(),message:b.string().optional(),_:b.array(b.union([b.string(),b.number()])).optional(),model:b.string().optional(),systemPrompt:b.string().optional(),appendSystemPrompt:b.string().optional(),maxTurns:b.number().int().refine((G)=>G===-1||G>0,{message:"must be -1 or a positive integer"}).optional(),permissionMode:b.nativeEnum(H).optional(),mcpConfig:b.array(b.string()).optional(),strictMcpConfig:b.boolean().optional(),sessionId:b.string().optional(),allowedTools:b.array(b.string()).optional(),disallowedTools:b.array(b.string()).optional(),continue:b.boolean().optional(),resume:b.union([b.string(),b.boolean()]).optional(),outputFormat:Kq.optional()});class d{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(G){this.openedThinking=G}hasOpenThinking(){return this.openedThinking}completeStream(){let G={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,G}}function Rq(G){return G.issues.map((X)=>`${X.path.join(".")||"options"}: ${X.message}`).join("; ")}function Vq(G){let X=Aq.safeParse(G);if(!X.success)throw Error(`Invalid headless options: ${Rq(X.error)}`);return X.data}function _q(G){return G.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(X)=>X.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}),async(X)=>{if(!X.headless)return;let Y=await Bq(X);process.exit(Y)})}function _(G,X=""){G.write(`${X}
|
|
2
2
|
`)}function Dq(G){return`[task] [${G.status}] ${G.subject}`}function Mq(){return{requestConfirmation:async(G)=>({approved:!0,reason:"headless-auto-approved",scope:"session"})}}function jq(G){if(!(G instanceof Error))return"Unknown error";let q=G.lastError??G;if(q.responseBody)try{let A=JSON.parse(q.responseBody)?.error?.message;if(A)return q.statusCode?`${A} (HTTP ${q.statusCode})`:A}catch{}let Z=G.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return G.message}function fq(G){return G==="jsonl"?"jsonl":"text"}function W(G,X){let Y=(...q)=>{for(let Z of q){let U=X[Z];if(typeof U==="string"&&U.trim()!=="")return U}return};switch(G){case"Read":case"Edit":case"Write":case"UndoEdit":return Y("file_path");case"NotebookEdit":return Y("notebook_path");case"Grep":return Y("path","pattern");case"Glob":return Y("pattern");case"WebFetch":return Y("url");case"WebSearch":return Y("query");case"Bash":return Y("description","command");case"Task":return Y("description");case"LSP":return Y("filePath","operation");default:return}}function Pq(G,X,Y,q){let Z=new Set(["Glob","Grep","WebSearch","LS"]),U=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","NotebookEdit","Bash","LSP","UndoEdit"]).has(G)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${X}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:Y?`Working within target: ${X}`:`Executing: ${X}`,shouldLockTarget:!1};if(Z.has(G))return{phase:"searching",status:"ongoing",message:`Still searching: ${X}`,shouldLockTarget:!1};if(U.has(G))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${X}`,shouldLockTarget:!1};return{phase:"executing",status:q.targetLocked?"hit":"ongoing",message:`Executing: ${X}`,shouldLockTarget:!1}}function k(G,X){let Y=(q,Z)=>{G.stdout.write(`${JSON.stringify(N(q,Z))}
|
|
3
3
|
`)};return{contentDelta(q){if(X==="jsonl"){Y("content_delta",{delta:q});return}G.stdout.write(q)},thinkingDelta(q,Z){if(X==="jsonl")return Y("thinking_delta",{delta:q}),Z;if(!Z)G.stderr.write("[thinking] ");return G.stderr.write(q),!0},thinking(q){if(X==="jsonl"){Y("thinking",{content:q});return}_(G.stderr,`[thinking] ${q}`)},streamEnd(q,Z){if(X==="jsonl"){Y("stream_end",{});return}if(Z)G.stderr.write(`
|
|
4
4
|
`);if(q)G.stdout.write(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{aa as a,ba as b,ca as c,da as d,ea as e,fa as f}from"./chunk-
|
|
1
|
+
import{aa as a,ba as b,ca as c,da as d,ea as e,fa as f}from"./chunk-r7dz28wh.js";import"./chunk-j2ag7hh6.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import{Ia as q0,Ka as A}from"./chunk-c6ts8bd9.js";import{Bb as K0}from"./chunk-set7v1rf.js";import{nanoid as i0}from"nanoid";import{devtools as o0,subscribeWithSelector as n0}from"zustand/middleware";import{createStore as s0}from"zustand/vanilla";var x0={name:"ayu-dark",colors:{primary:"#ffcc66",secondary:"#bae67e",accent:"#73d0ff",success:"#bae67e",warning:"#ffcc66",error:"#ff3333",info:"#73d0ff",light:"#f0f0f0",dark:"#000000",muted:"#5c6773",highlight:"#2d323b",text:{primary:"#e6e1cf",secondary:"#bae67e",muted:"#5c6773",light:"#ffffff"},background:{primary:"#0f1419",secondary:"#14191f",dark:"#000000"},border:{light:"#2d323b",dark:"#000000"},syntax:{comment:"#5c6773",string:"#bae67e",number:"#ffcc66",keyword:"#ff8f40",function:"#73d0ff",variable:"#e6e1cf",operator:"#f29e74",type:"#73d0ff",tag:"#ff8f40",attr:"#ffd580",default:"#e6e1cf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.2)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.3), 0 1px 2px 0 rgba(0, 0, 0, 0.2)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -2px rgba(0, 0, 0, 0.2)"}},B0={name:"dracula",colors:{primary:"#bd93f9",secondary:"#ffb86c",accent:"#ff79c6",success:"#50fa7b",warning:"#f1fa8c",error:"#ff5555",info:"#8be9fd",light:"#f8f8f2",dark:"#282a36",muted:"#6272a4",highlight:"#44475a",text:{primary:"#f8f8f2",secondary:"#f1fa8c",muted:"#6272a4",light:"#ffffff"},background:{primary:"#282a36",secondary:"#44475a",dark:"#21222c"},border:{light:"#44475a",dark:"#000000"},syntax:{comment:"#6272a4",string:"#f1fa8c",number:"#bd93f9",keyword:"#ff79c6",function:"#50fa7b",variable:"#f8f8f2",operator:"#ff79c6",type:"#8be9fd",tag:"#ff79c6",attr:"#50fa7b",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 42, 54, 0.2)",base:"0 1px 3px 0 rgba(40, 42, 54, 0.3), 0 1px 2px 0 rgba(40, 42, 54, 0.2)",lg:"0 10px 15px -3px rgba(40, 42, 54, 0.3), 0 4px 6px -2px rgba(40, 42, 54, 0.2)"}},w0={name:"monokai",colors:{primary:"#66d9ef",secondary:"#a6e22e",accent:"#f92672",success:"#a6e22e",warning:"#e6db74",error:"#f92672",info:"#66d9ef",light:"#f8f8f2",dark:"#272822",muted:"#75715e",highlight:"#3e3d32",text:{primary:"#f8f8f2",secondary:"#e6db74",muted:"#75715e",light:"#ffffff"},background:{primary:"#272822",secondary:"#3e3d32",dark:"#1e1f1c"},border:{light:"#3e3d32",dark:"#000000"},syntax:{comment:"#75715e",string:"#e6db74",number:"#ae81ff",keyword:"#f92672",function:"#a6e22e",variable:"#f8f8f2",operator:"#f92672",type:"#66d9ef",tag:"#f92672",attr:"#a6e22e",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(39, 40, 34, 0.2)",base:"0 1px 3px 0 rgba(39, 40, 34, 0.3), 0 1px 2px 0 rgba(39, 40, 34, 0.2)",lg:"0 10px 15px -3px rgba(39, 40, 34, 0.3), 0 4px 6px -2px rgba(39, 40, 34, 0.2)"}},A0={name:"nord",colors:{primary:"#88c0d0",secondary:"#81a1c1",accent:"#b48ead",success:"#a3be8c",warning:"#ebcb8b",error:"#bf616a",info:"#88c0d0",light:"#eceff4",dark:"#2e3440",muted:"#4c566a",highlight:"#434c5e",text:{primary:"#eceff4",secondary:"#d8dee9",muted:"#4c566a",light:"#ffffff"},background:{primary:"#2e3440",secondary:"#3b4252",dark:"#242933"},border:{light:"#434c5e",dark:"#000000"},syntax:{comment:"#616e88",string:"#a3be8c",number:"#b48ead",keyword:"#81a1c1",function:"#88c0d0",variable:"#d8dee9",operator:"#81a1c1",type:"#8fbcbb",tag:"#81a1c1",attr:"#8fbcbb",default:"#eceff4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(46, 52, 64, 0.2)",base:"0 1px 3px 0 rgba(46, 52, 64, 0.3), 0 1px 2px 0 rgba(46, 52, 64, 0.2)",lg:"0 10px 15px -3px rgba(46, 52, 64, 0.3), 0 4px 6px -2px rgba(46, 52, 64, 0.2)"}},D0={name:"solarized-light",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#cb4b16",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#93a1a1",highlight:"#eee8d5",text:{primary:"#586e75",secondary:"#657b83",muted:"#93a1a1",light:"#002b36"},background:{primary:"#fdf6e3",secondary:"#eee8d5",dark:"#073642"},border:{light:"#eee8d5",dark:"#073642"},syntax:{comment:"#93a1a1",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#657b83",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#657b83"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(253, 246, 227, 0.2)",base:"0 1px 3px 0 rgba(253, 246, 227, 0.3), 0 1px 2px 0 rgba(253, 246, 227, 0.2)",lg:"0 10px 15px -3px rgba(253, 246, 227, 0.3), 0 4px 6px -2px rgba(253, 246, 227, 0.2)"}},L0={name:"solarized-dark",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#b58900",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#586e75",highlight:"#073642",text:{primary:"#839496",secondary:"#93a1a1",muted:"#586e75",light:"#fdf6e3"},background:{primary:"#002b36",secondary:"#073642",dark:"#001f29"},border:{light:"#073642",dark:"#000000"},syntax:{comment:"#586e75",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#839496",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#839496"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 43, 54, 0.2)",base:"0 1px 3px 0 rgba(0, 43, 54, 0.3), 0 1px 2px 0 rgba(0, 43, 54, 0.2)",lg:"0 10px 15px -3px rgba(0, 43, 54, 0.3), 0 4px 6px -2px rgba(0, 43, 54, 0.2)"}},v0={name:"tokyo-night",colors:{primary:"#7aa2f7",secondary:"#7dcfff",accent:"#bb9af7",success:"#9ece6a",warning:"#e0af68",error:"#f7768e",info:"#7aa2f7",light:"#c0caf5",dark:"#1a1b26",muted:"#565f89",highlight:"#292e42",text:{primary:"#a9b1d6",secondary:"#c0caf5",muted:"#565f89",light:"#ffffff"},background:{primary:"#1a1b26",secondary:"#292e42",dark:"#16161e"},border:{light:"#292e42",dark:"#000000"},syntax:{comment:"#565f89",string:"#9ece6a",number:"#ff9e64",keyword:"#bb9af7",function:"#7aa2f7",variable:"#c0caf5",operator:"#89ddff",type:"#7dcfff",tag:"#f7768e",attr:"#7aa2f7",default:"#a9b1d6"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(26, 27, 38, 0.2)",base:"0 1px 3px 0 rgba(26, 27, 38, 0.3), 0 1px 2px 0 rgba(26, 27, 38, 0.2)",lg:"0 10px 15px -3px rgba(26, 27, 38, 0.3), 0 4px 6px -2px rgba(26, 27, 38, 0.2)"}},E0={name:"github",colors:{primary:"#0969da",secondary:"#8250df",accent:"#bc4c00",success:"#1a7f37",warning:"#bc4c00",error:"#d1242f",info:"#0969da",light:"#f6f8fa",dark:"#24292f",muted:"#6e7781",highlight:"#ddf4ff",text:{primary:"#24292f",secondary:"#57606a",muted:"#6e7781",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f6f8fa",dark:"#24292f"},border:{light:"#d0d7de",dark:"#24292f"},syntax:{comment:"#6e7781",string:"#0a3069",number:"#0550ae",keyword:"#cf222e",function:"#8250df",variable:"#24292f",operator:"#cf222e",type:"#0550ae",tag:"#116329",attr:"#0550ae",default:"#24292f"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(255, 255, 255, 0.2)",base:"0 1px 3px 0 rgba(255, 255, 255, 0.3), 0 1px 2px 0 rgba(255, 255, 255, 0.2)",lg:"0 10px 15px -3px rgba(255, 255, 255, 0.3), 0 4px 6px -2px rgba(255, 255, 255, 0.2)"}},y0={name:"gruvbox",colors:{primary:"#83a598",secondary:"#8ec07c",accent:"#d3869b",success:"#b8bb26",warning:"#fabd2f",error:"#fb4934",info:"#83a598",light:"#fbf1c7",dark:"#282828",muted:"#928374",highlight:"#3c3836",text:{primary:"#ebdbb2",secondary:"#d5c4a1",muted:"#928374",light:"#ffffff"},background:{primary:"#282828",secondary:"#3c3836",dark:"#1d2021"},border:{light:"#3c3836",dark:"#000000"},syntax:{comment:"#928374",string:"#b8bb26",number:"#d3869b",keyword:"#fb4934",function:"#8ec07c",variable:"#ebdbb2",operator:"#fe8019",type:"#fabd2f",tag:"#fb4934",attr:"#b8bb26",default:"#ebdbb2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 40, 40, 0.2)",base:"0 1px 3px 0 rgba(40, 40, 40, 0.3), 0 1px 2px 0 rgba(40, 40, 40, 0.2)",lg:"0 10px 15px -3px rgba(40, 40, 40, 0.3), 0 4px 6px -2px rgba(40, 40, 40, 0.2)"}},R0={name:"one-dark",colors:{primary:"#61afef",secondary:"#c678dd",accent:"#e5c07b",success:"#98c379",warning:"#e5c07b",error:"#e06c75",info:"#56b6c2",light:"#abb2bf",dark:"#282c34",muted:"#5c6370",highlight:"#3e4451",text:{primary:"#abb2bf",secondary:"#c6c8d0",muted:"#5c6370",light:"#ffffff"},background:{primary:"#282c34",secondary:"#3e4451",dark:"#21252b"},border:{light:"#3e4451",dark:"#000000"},syntax:{comment:"#5c6370",string:"#98c379",number:"#d19a66",keyword:"#c678dd",function:"#61afef",variable:"#e06c75",operator:"#56b6c2",type:"#e5c07b",tag:"#e06c75",attr:"#d19a66",default:"#abb2bf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 44, 52, 0.2)",base:"0 1px 3px 0 rgba(40, 44, 52, 0.3), 0 1px 2px 0 rgba(40, 44, 52, 0.2)",lg:"0 10px 15px -3px rgba(40, 44, 52, 0.3), 0 4px 6px -2px rgba(40, 44, 52, 0.2)"}},P0={name:"catppuccin",colors:{primary:"#89b4fa",secondary:"#cba6f7",accent:"#f5c2e7",success:"#a6e3a1",warning:"#f9e2af",error:"#f38ba8",info:"#89dceb",light:"#cdd6f4",dark:"#11111b",muted:"#6c7086",highlight:"#181825",text:{primary:"#cdd6f4",secondary:"#bac2de",muted:"#6c7086",light:"#ffffff"},background:{primary:"#1e1e2e",secondary:"#181825",dark:"#11111b"},border:{light:"#181825",dark:"#000000"},syntax:{comment:"#6c7086",string:"#a6e3a1",number:"#fab387",keyword:"#cba6f7",function:"#89b4fa",variable:"#cdd6f4",operator:"#89dceb",type:"#f5c2e7",tag:"#f38ba8",attr:"#89b4fa",default:"#cdd6f4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(30, 30, 46, 0.2)",base:"0 1px 3px 0 rgba(30, 30, 46, 0.3), 0 1px 2px 0 rgba(30, 30, 46, 0.2)",lg:"0 10px 15px -3px rgba(30, 30, 46, 0.3), 0 4px 6px -2px rgba(30, 30, 46, 0.2)"}},C0={name:"rose-pine",colors:{primary:"#9ccfd8",secondary:"#c4a7e7",accent:"#f6c177",success:"#31748f",warning:"#f6c177",error:"#eb6f92",info:"#9ccfd8",light:"#e0def4",dark:"#191724",muted:"#6e6a86",highlight:"#1f1d2e",text:{primary:"#e0def4",secondary:"#cecacd",muted:"#6e6a86",light:"#ffffff"},background:{primary:"#191724",secondary:"#1f1d2e",dark:"#12101a"},border:{light:"#1f1d2e",dark:"#000000"},syntax:{comment:"#6e6a86",string:"#9ccfd8",number:"#ea9a97",keyword:"#c4a7e7",function:"#31748f",variable:"#e0def4",operator:"#f6c177",type:"#9ccfd8",tag:"#eb6f92",attr:"#f6c177",default:"#e0def4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(25, 23, 36, 0.2)",base:"0 1px 3px 0 rgba(25, 23, 36, 0.3), 0 1px 2px 0 rgba(25, 23, 36, 0.2)",lg:"0 10px 15px -3px rgba(25, 23, 36, 0.3), 0 4px 6px -2px rgba(25, 23, 36, 0.2)"}},I0={name:"kanagawa",colors:{primary:"#8ba4b0",secondary:"#a292a3",accent:"#c47fd5",success:"#76946a",warning:"#c0a36e",error:"#c34043",info:"#7e9cd8",light:"#dcd7ba",dark:"#1f1f28",muted:"#727169",highlight:"#2a2a37",text:{primary:"#dcd7ba",secondary:"#c8c093",muted:"#727169",light:"#ffffff"},background:{primary:"#1f1f28",secondary:"#2a2a37",dark:"#16161d"},border:{light:"#2a2a37",dark:"#000000"},syntax:{comment:"#727169",string:"#98bb6c",number:"#d27e99",keyword:"#957fb8",function:"#7e9cd8",variable:"#dcd7ba",operator:"#c0a36e",type:"#7aa89f",tag:"#c34043",attr:"#7fb4ca",default:"#dcd7ba"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(31, 31, 40, 0.2)",base:"0 1px 3px 0 rgba(31, 31, 40, 0.3), 0 1px 2px 0 rgba(31, 31, 40, 0.2)",lg:"0 10px 15px -3px rgba(31, 31, 40, 0.3), 0 4px 6px -2px rgba(31, 31, 40, 0.2)"}},t=[{id:"ayu-dark",label:"Ayu Dark",theme:x0,tags:["dark","popular"]},{id:"dracula",label:"Dracula",theme:B0,tags:["dark","popular"]},{id:"monokai",label:"Monokai",theme:w0,tags:["dark","classic"]},{id:"nord",label:"Nord",theme:A0,tags:["dark","minimal"]},{id:"solarized-light",label:"Solarized Light",theme:D0,tags:["light"]},{id:"solarized-dark",label:"Solarized Dark",theme:L0,tags:["dark"]},{id:"tokyo-night",label:"Tokyo Night",theme:v0,tags:["dark","popular"]},{id:"github",label:"GitHub",theme:E0,tags:["light","minimal"]},{id:"gruvbox",label:"Gruvbox",theme:y0,tags:["dark","warm"]},{id:"one-dark",label:"One Dark",theme:R0,tags:["dark","popular"]},{id:"catppuccin",label:"Catppuccin",theme:P0,tags:["dark","pastel"]},{id:"rose-pine",label:"Rose Pine",theme:C0,tags:["dark","elegant"]},{id:"kanagawa",label:"Kanagawa",theme:I0,tags:["dark","japanese"]}];var e={primary:"#0066cc",secondary:"#6c757d",accent:"#e83e8c",success:"#28a745",warning:"#ffc107",error:"#dc3545",info:"#17a2b8",light:"#f8f9fa",dark:"#343a40",muted:"#6c757d",highlight:"#fff3cd",text:{primary:"#212529",secondary:"#6c757d",muted:"#6c757d",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f8f9fa",dark:"#343a40"},border:{light:"#dee2e6",dark:"#495057"},syntax:{comment:"#6c757d",string:"#28a745",number:"#e83e8c",keyword:"#007bff",function:"#17a2b8",variable:"#495057",operator:"#ffc107",type:"#007bff",tag:"#dc3545",attr:"#ffc107",default:"#212529"}},p={name:"default",colors:e,spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)"}},b0={...p,name:"dark",colors:{...e,text:{primary:"#ffffff",secondary:"#e2e8f0",muted:"#94a3b8",light:"#000000"},background:{primary:"#1e293b",secondary:"#334155",dark:"#0f172a"},border:{light:"#475569",dark:"#64748b"},syntax:{comment:"#94a3b8",string:"#34d399",number:"#f472b6",keyword:"#60a5fa",function:"#06b6d4",variable:"#e2e8f0",operator:"#fbbf24",type:"#60a5fa",tag:"#fb7185",attr:"#fbbf24",default:"#ffffff"}}};class Q0{currentTheme=p;themes=new Map;constructor(){this.themes.set("default",p),this.themes.set("dark",b0);for(let X of t)this.themes.set(X.id,X.theme)}setTheme(X){let Z=this.themes.get(X);if(Z)this.currentTheme=Z;else throw Error(`Theme '${X}' not found`)}getTheme(){return this.currentTheme}getAvailableThemes(){return Array.from(this.themes.keys())}getCurrentThemeName(){return this.currentTheme.name}getThemeByName(X){return this.themes.get(X)}hasTheme(X){return this.themes.has(X)}}var X0=new Q0;var M0={initializationStatus:"idle",initializationError:null,activeModal:"none",sessionSelectorData:void 0,modelEditorTarget:null,tasks:[],awaitingSecondCtrlC:!1,thinkingModeEnabled:!1,subagentProgress:null},g=(X)=>({...M0,actions:{setInitializationStatus:(Z)=>{X((Q)=>({app:{...Q.app,initializationStatus:Z}}))},setInitializationError:(Z)=>{X((Q)=>({app:{...Q.app,initializationError:Z}}))},setActiveModal:(Z)=>{X((Q)=>({app:{...Q.app,activeModal:Z}}))},showSessionSelector:(Z)=>{X((Q)=>({app:{...Q.app,activeModal:"sessionSelector",sessionSelectorData:Z}}))},showModelEditWizard:(Z)=>{X((Q)=>({app:{...Q.app,activeModal:"modelEditWizard",modelEditorTarget:Z}}))},closeModal:()=>{X((Z)=>({app:{...Z.app,activeModal:"none",sessionSelectorData:void 0,modelEditorTarget:null}}))},setTasks:(Z)=>{X((Q)=>({app:{...Q.app,tasks:Z}}))},updateTask:(Z)=>{X((Q)=>({app:{...Q.app,tasks:Q.app.tasks.map(($)=>$.id===Z.id?Z:$)}}))},setAwaitingSecondCtrlC:(Z)=>{X((Q)=>({app:{...Q.app,awaitingSecondCtrlC:Z}}))},setThinkingModeEnabled:(Z)=>{X((Q)=>({app:{...Q.app,thinkingModeEnabled:Z}}))},toggleThinkingMode:()=>{X((Z)=>({app:{...Z.app,thinkingModeEnabled:!Z.app.thinkingModeEnabled}}))},startSubagentProgress:(Z,Q,$)=>{X((Y)=>({app:{...Y.app,subagentProgress:{id:Z,type:Q,description:$,status:"running",startTime:Date.now()}}}))},updateSubagentTool:(Z)=>{X((Q)=>{if(!Q.app.subagentProgress)return Q;return{app:{...Q.app,subagentProgress:{...Q.app.subagentProgress,currentTool:Z}}}})},completeSubagentProgress:(Z)=>{X((Q)=>{if(!Q.app.subagentProgress)return Q;return{app:{...Q.app,subagentProgress:{...Q.app.subagentProgress,status:Z?"completed":"failed",currentTool:void 0}}}}),setTimeout(()=>{X((Q)=>({app:{...Q.app,subagentProgress:null}}))},1500)}}});var T0={isProcessing:!1,abortController:null,pendingCommands:[]},d=(X,Z)=>({...T0,actions:{setProcessing:(Q)=>{X(($)=>({command:{...$.command,isProcessing:Q}}))},createAbortController:()=>{let Q=Z().command.abortController;if(Q&&!Q.signal.aborted)Q.abort("interrupted-by-new-command");let $=new AbortController;return X((Y)=>({command:{...Y.command,abortController:$}})),$},getAbortController:()=>{return Z().command.abortController},clearAbortController:(Q)=>{let $=Z().command.abortController;if(Q!==void 0&&$!==Q)return;X((Y)=>({command:{...Y.command,abortController:null}}))},abort:(Q)=>{let{abortController:$}=Z().command;if($&&!$.signal.aborted)$.abort(Q??"user-cancel");X((Y)=>({command:{...Y.command,isProcessing:!1,pendingCommands:[]}}))},enqueueCommand:(Q)=>{X(($)=>({command:{...$.command,pendingCommands:[...$.command.pendingCommands,Q]}}))},dequeueCommand:()=>{let{pendingCommands:Q}=Z().command;if(Q.length===0)return;let[$,...Y]=Q;return X((V)=>({command:{...V.command,pendingCommands:Y}})),$},clearQueue:()=>{X((Q)=>({command:{...Q.command,pendingCommands:[]}}))}}});var N0={config:null},m=(X)=>({...N0,actions:{setConfig:(Z)=>{X((Q)=>({config:{...Q.config,config:Z}}))},updateConfig:(Z)=>{X((Q)=>{if(!Q.config.config)throw Error(`[ConfigSlice] Config not initialized. Cannot update: ${JSON.stringify(Z)}`);return{config:{...Q.config,config:{...Q.config.config,...Z}}}})}}});var u0={currentFocus:"main-input",previousFocus:null},r=(X)=>({...u0,actions:{setFocus:(Z)=>{X((Q)=>({focus:{...Q.focus,currentFocus:Z,previousFocus:Q.focus.currentFocus}}))},restorePreviousFocus:()=>{X((Z)=>({focus:{...Z.focus,currentFocus:Z.focus.previousFocus||"main-input",previousFocus:null}}))}}});import{nanoid as p0}from"nanoid";var c={"deepseek-chat":{input:0.27,output:1.1},"deepseek-coder":{input:0.14,output:0.28},"deepseek-reasoner":{input:0.55,output:2.19},"deepseek-v3":{input:0.27,output:1.1},"deepseek-v4-pro":{input:0.27,output:1.1},"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:0.15,output:0.6},"gpt-4-turbo":{input:10,output:30},"gpt-4":{input:30,output:60},"gpt-3.5-turbo":{input:0.5,output:1.5},o1:{input:15,output:60},"o1-mini":{input:3,output:12},"o1-pro":{input:150,output:600},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4},"claude-3.5-sonnet":{input:3,output:15,cacheRead:0.3,cacheWrite:3.75},"claude-3.5-haiku":{input:0.8,output:4,cacheRead:0.08,cacheWrite:1},"claude-sonnet-4":{input:3,output:15,cacheRead:0.3,cacheWrite:3.75},"claude-4-opus":{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},"qwen-plus":{input:0.8,output:2},"qwen-max":{input:2,output:6},"qwen-turbo":{input:0.3,output:0.6}};function h0(X){let Z=X.toLowerCase();if(c[Z])return c[Z];for(let[Q,$]of Object.entries(c))if(Z.includes(Q)||Q.includes(Z))return $;return}function Z0(X,Z,Q,$,Y){let V=h0(X);if(!V)return 0;let J=Z/1e6*V.input+Q/1e6*V.output;if($&&V.cacheRead)J+=$/1e6*V.cacheRead;if(Y&&V.cacheWrite)J+=Y/1e6*V.cacheWrite;return Math.round(J*1e6)/1e6}var K={codeBlock:/^```(\w+)?\s*$/,heading:/^ *(#{1,4}) +(.+)/,blockquote:/^(>+)\s?(.*)/,ulItem:/^([ \t]*)([-*+]) +(.+)/,olItem:/^([ \t]*)(\d+)\. +(.+)/,hr:/^ *([-*_] *){3,} *$/,table:/^\|(.+)\|$/,tableSeparator:/^\|[\s]*:?-+:?[\s]*(\|[\s]*:?-+:?[\s]*)+\|?$/,diffStart:/^<<<DIFF>>>$/,diffEnd:/^<<<\/DIFF>>>$/,commandMessage:/<command-message>(.*?)<\/command-message>/};function G1(X){let Z=[],Q=X.split(/\r?\n/),$=!1,Y=[],V=null,J=0,G=!1,U=[],H=[],W=!1,D=[],v=!1,O=[],z=0,j=!0;for(let L=0;L<Q.length;L++){let _=Q[L];if(W){if(_.match(K.diffEnd)){try{let B=JSON.parse(D.join(`
|
|
2
|
+
`));Z.push({type:"diff",content:"",diffData:{patch:B.patch,startLine:B.startLine,matchLine:B.matchLine}})}catch(B){Z.push({type:"text",content:D.join(`
|
|
3
|
+
`)})}W=!1,D=[],j=!1;continue}D.push(_);continue}if(_.match(K.diffStart)){W=!0,D=[],j=!1;continue}if($){let B=_.match(K.codeBlock),E=_.trim()==="```";if(B&&B[1])J++,Y.push(_);else if(E)if(J>0)J--,Y.push(_);else{let _0=Y.join(`
|
|
4
|
+
`);Z.push({type:"code",content:_0,language:V||void 0}),$=!1,Y=[],V=null,J=0,j=!1}else Y.push(_);continue}let s=_.match(K.codeBlock);if(s){$=!0,V=s[1]||null,J=0,j=!1;continue}let b=_.match(K.table),O0=_.match(K.tableSeparator);if(b&&!G){if(L+1<Q.length){if(Q[L+1].match(K.tableSeparator)){G=!0,U=b[1].split("|").map((E)=>E.trim()).filter((E)=>E.length>0),H=[],j=!1;continue}}}if(G&&O0)continue;if(G&&b){let B=b[1].split("|").map((E)=>E.trim()).filter((E)=>E.length>0);while(B.length<U.length)B.push("");if(B.length>U.length)B.length=U.length;H.push(B);continue}if(G&&!b){if(U.length>0&&H.length>0)Z.push({type:"table",content:"",tableData:{headers:U,rows:H}});G=!1,U=[],H=[]}let f=_.match(K.blockquote);if(f){let B=f[1].length,E=f[2]||"";if(v&&B===z)O.push(E);else{if(v)Z.push({type:"blockquote",content:O.join(`
|
|
5
|
+
`),blockquoteLevel:z,blockquoteLines:[...O]});v=!0,z=B,O=[E]}j=!1;continue}if(v)Z.push({type:"blockquote",content:O.join(`
|
|
6
|
+
`),blockquoteLevel:z,blockquoteLines:[...O]}),v=!1,O=[],z=0;let S=_.match(K.heading);if(S){Z.push({type:"heading",content:S[2],level:S[1].length}),j=!1;continue}let u=_.match(K.ulItem);if(u){Z.push({type:"list",content:u[3],listType:"ul",marker:u[2],indentation:u[1].length}),j=!1;continue}let h=_.match(K.olItem);if(h){Z.push({type:"list",content:h[3],listType:"ol",marker:h[2],indentation:h[1].length}),j=!1;continue}if(_.match(K.hr)){Z.push({type:"hr",content:""}),j=!1;continue}if(_.trim().length===0){if(!j)Z.push({type:"empty",content:""}),j=!0;continue}let a=_.match(K.commandMessage);if(a){Z.push({type:"command-message",content:a[1]}),j=!1;continue}Z.push({type:"text",content:_}),j=!1}if($){let L=Y.join(`
|
|
7
|
+
`);Z.push({type:"code",content:L,language:V||void 0})}if(G&&U.length>0&&H.length>0)Z.push({type:"table",content:"",tableData:{headers:U,rows:H}});if(v&&O.length>0)Z.push({type:"blockquote",content:O.join(`
|
|
8
|
+
`),blockquoteLevel:z,blockquoteLines:[...O]});while(Z.length>0&&Z[Z.length-1].type==="empty")Z.pop();return Z}var R=new Map;function k0(){return{inCodeBlock:!1,codeBlockContent:[],codeBlockLang:null,codeBlockDepth:0,inTable:!1,tableHeaders:[],tableRows:[],inDiff:!1,diffContent:[],inBlockquote:!1,blockquoteLines:[],blockquoteLevel:0,lastLineEmpty:!0,pendingTableHeader:null}}function f0(X){let Z=R.get(X);if(Z)return Z;let Q={state:k0(),blocks:[],pendingLine:"",finalized:!1};return R.set(X,Q),Q}function $0(X){return X.endsWith("\r")?X.slice(0,-1):X}function Y0(X,Z){if(X.tableHeaders.length>0&&X.tableRows.length>0)Z.push({type:"table",content:"",tableData:{headers:X.tableHeaders,rows:X.tableRows}});X.inTable=!1,X.tableHeaders=[],X.tableRows=[]}function l(X,Z){if(X.blockquoteLines.length>0)Z.push({type:"blockquote",content:X.blockquoteLines.join(`
|
|
9
|
+
`),blockquoteLevel:X.blockquoteLevel,blockquoteLines:[...X.blockquoteLines]});X.inBlockquote=!1,X.blockquoteLines=[],X.blockquoteLevel=0}function V0(X,Z){let Q=X.codeBlockContent.join(`
|
|
10
|
+
`);Z.push({type:"code",content:Q,language:X.codeBlockLang||void 0}),X.inCodeBlock=!1,X.codeBlockContent=[],X.codeBlockLang=null,X.codeBlockDepth=0,X.lastLineEmpty=!1}function i(X,Z,Q=!0){let{state:$,blocks:Y}=Z;if($.pendingTableHeader!==null){if(X.match(K.tableSeparator)){$.inTable=!0,$.tableHeaders=$.pendingTableHeader.slice(1,-1).split("|").map((z)=>z.trim()).filter((z)=>z.length>0),$.tableRows=[],$.pendingTableHeader=null,$.lastLineEmpty=!1;return}Y.push({type:"text",content:$.pendingTableHeader}),$.pendingTableHeader=null,$.lastLineEmpty=!1}if($.inDiff){if(X.match(K.diffEnd)){try{let z=JSON.parse($.diffContent.join(`
|
|
11
|
+
`));Y.push({type:"diff",content:"",diffData:{patch:z.patch,startLine:z.startLine,matchLine:z.matchLine}})}catch(z){Y.push({type:"text",content:$.diffContent.join(`
|
|
12
|
+
`)})}$.inDiff=!1,$.diffContent=[],$.lastLineEmpty=!1;return}$.diffContent.push(X);return}if(X.match(K.diffStart)){$.inDiff=!0,$.diffContent=[],$.lastLineEmpty=!1;return}if($.inCodeBlock){let z=X.match(K.codeBlock),j=X.trim()==="```";if(z&&z[1])$.codeBlockDepth++,$.codeBlockContent.push(X);else if(j)if($.codeBlockDepth>0)$.codeBlockDepth--,$.codeBlockContent.push(X);else V0($,Y);else $.codeBlockContent.push(X);return}let V=X.match(K.codeBlock);if(V){$.inCodeBlock=!0,$.codeBlockLang=V[1]||null,$.codeBlockDepth=0,$.lastLineEmpty=!1;return}let J=X.match(K.table),G=X.match(K.tableSeparator);if(J&&!$.inTable){$.pendingTableHeader=X;return}if($.inTable&&G)return;if($.inTable&&J){let z=J[1].split("|").map((j)=>j.trim()).filter((j)=>j.length>0);while(z.length<$.tableHeaders.length)z.push("");if(z.length>$.tableHeaders.length)z.length=$.tableHeaders.length;$.tableRows.push(z);return}if($.inTable&&!J){if(Y0($,Y),Q){i(X,Z,!1);return}}let U=X.match(K.blockquote);if(U){let z=U[1].length,j=U[2]||"";if($.inBlockquote&&z===$.blockquoteLevel)$.blockquoteLines.push(j);else{if($.inBlockquote)l($,Y);$.inBlockquote=!0,$.blockquoteLevel=z,$.blockquoteLines=[j]}$.lastLineEmpty=!1;return}if($.inBlockquote)l($,Y);let H=X.match(K.heading);if(H){Y.push({type:"heading",content:H[2],level:H[1].length}),$.lastLineEmpty=!1;return}let W=X.match(K.ulItem);if(W){Y.push({type:"list",content:W[3],listType:"ul",marker:W[2],indentation:W[1].length}),$.lastLineEmpty=!1;return}let D=X.match(K.olItem);if(D){Y.push({type:"list",content:D[3],listType:"ol",marker:D[2],indentation:D[1].length}),$.lastLineEmpty=!1;return}if(X.match(K.hr)){Y.push({type:"hr",content:""}),$.lastLineEmpty=!1;return}if(X.trim().length===0){if(!$.lastLineEmpty)Y.push({type:"empty",content:""}),$.lastLineEmpty=!0;return}let O=X.match(K.commandMessage);if(O){Y.push({type:"command-message",content:O[1]}),$.lastLineEmpty=!1;return}Y.push({type:"text",content:X}),$.lastLineEmpty=!1}function H1(X,Z){if(!X||!Z)return;let Q=f0(X);if(Q.finalized)return;let $=Q.pendingLine+Z,Y=$.split(`
|
|
13
|
+
`),V=$.endsWith(`
|
|
14
|
+
`),J=V?Y:Y.slice(0,-1);Q.pendingLine=V?"":Y[Y.length-1]??"";for(let G of J)i($0(G),Q)}function z1(X){let Z=R.get(X);if(!Z||Z.finalized)return;if(Z.pendingLine)i($0(Z.pendingLine),Z),Z.pendingLine="";if(Z.state.pendingTableHeader!==null)Z.blocks.push({type:"text",content:Z.state.pendingTableHeader}),Z.state.pendingTableHeader=null;if(Z.state.inCodeBlock)V0(Z.state,Z.blocks);if(Z.state.inTable)Y0(Z.state,Z.blocks);if(Z.state.inBlockquote)l(Z.state,Z.blocks);if(Z.state.inDiff)Z.blocks.push({type:"text",content:Z.state.diffContent.join(`
|
|
15
|
+
`)}),Z.state.inDiff=!1,Z.state.diffContent=[];while(Z.blocks.length>0&&Z.blocks[Z.blocks.length-1].type==="empty")Z.blocks.pop();Z.finalized=!0}function W1(X){let Z=R.get(X);if(!Z||!Z.finalized)return null;return Z.blocks}function F1(X){let Z=R.get(X);if(!Z)return null;return Z.blocks}function S0(X){let Z=R.get(X);if(!Z)return null;let Q=[],$=Z.state;if($.inDiff)Q.push("<<<DIFF>>>"),Q.push(...$.diffContent);else if($.inCodeBlock){let Y=$.codeBlockLang?`\`\`\`${$.codeBlockLang}`:"```";Q.push(Y),Q.push(...$.codeBlockContent)}else if($.inTable){if($.tableHeaders.length>0){Q.push(`| ${$.tableHeaders.join(" | ")} |`),Q.push(`| ${$.tableHeaders.map(()=>"---").join(" | ")} |`);for(let Y of $.tableRows)Q.push(`| ${Y.join(" | ")} |`)}}else if($.inBlockquote){let Y=">".repeat($.blockquoteLevel)+" ";for(let V of $.blockquoteLines)Q.push(Y+V)}else if($.pendingTableHeader)Q.push($.pendingTableHeader);if(Z.pendingLine)Q.push(Z.pendingLine);return Q.length>0?Q:null}function K1(X){let Z=R.get(X);if(!Z)return null;let Q="text";if(Z.state.inDiff)Q="diff";else if(Z.state.inCodeBlock)Q="code";else if(Z.state.inTable||Z.state.pendingTableHeader)Q="table";let $=S0(X);if(!$||$.length===0)return null;return{lines:$,mode:Q}}function q1(X){R.delete(X)}function k(){R.clear()}var J0=2000,M=[];function g0(){let X=M;return M=[],X}var U0={inputTokens:0,outputTokens:0,totalTokens:0,maxContextTokens:200000,totalInputTokens:0,totalOutputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,turnCount:0,estimatedCostUsd:0},G0={sessionId:p0(),messages:[],restoredContextMessages:null,restoredVisibleMessageCount:0,isCompacting:!1,currentCommand:null,error:null,isActive:!0,tokenUsage:{...U0},currentThinkingContent:null,thinkingExpanded:!1,clearCount:0,historyExpanded:!1,expandedMessageCount:100,currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,finalizingStreamingMessageId:null},o=(X,Z)=>({...G0,actions:{addMessage:(Q)=>{X(($)=>({session:{...$.session,messages:[...$.session.messages,Q],error:null}}))},addUserMessage:(Q)=>{let $={id:`user-${Date.now()}-${Math.random()}`,role:"user",content:Q,timestamp:Date.now()};Z().session.actions.addMessage($)},addAssistantMessage:(Q,$)=>{let Y={id:`assistant-${Date.now()}-${Math.random()}`,role:"assistant",content:Q,timestamp:Date.now(),thinkingContent:$};Z().session.actions.addMessage(Y)},addAssistantMessageAndClearThinking:(Q)=>{let $=Z().session.currentThinkingContent,Y={id:`assistant-${Date.now()}-${Math.random()}`,role:"assistant",content:Q,timestamp:Date.now(),thinkingContent:$||void 0};X((V)=>({session:{...V.session,messages:[...V.session.messages,Y],currentThinkingContent:null,error:null}}))},addToolMessage:(Q,$)=>{let Y={id:`tool-${Date.now()}-${Math.random()}`,role:"tool",content:Q,timestamp:Date.now(),metadata:$};Z().session.actions.addMessage(Y)},setCompacting:(Q)=>{X(($)=>({session:{...$.session,isCompacting:Q}}))},setCommand:(Q)=>{X(($)=>({session:{...$.session,currentCommand:Q}}))},setError:(Q)=>{X(($)=>({session:{...$.session,error:Q}}))},clearMessages:()=>{k(),X((Q)=>({session:{...Q.session,messages:[],restoredContextMessages:null,restoredVisibleMessageCount:0,error:null,clearCount:Q.session.clearCount+1}}))},resetSession:()=>{k(),X((Q)=>({session:{...Q.session,...G0,sessionId:Q.session.sessionId,isActive:!0}}))},restoreSession:(Q,$,Y)=>{k(),X((V)=>({session:{...V.session,sessionId:Q,messages:$,restoredContextMessages:Y??null,restoredVisibleMessageCount:Y?$.length:0,error:null,isActive:!0}}))},updateTokenUsage:(Q)=>{X(($)=>{let Y=$.session.tokenUsage,V=(Q.inputTokens??0)-(Q.inputTokens!==void 0?Y.inputTokens:0),J=(Q.outputTokens??0)-(Q.outputTokens!==void 0?Y.outputTokens:0),G=Y.totalInputTokens+Math.max(0,V),U=Y.totalOutputTokens+Math.max(0,J),H=Y.cacheReadTokens+(Q.cacheReadTokens??0),W=Y.cacheWriteTokens+(Q.cacheWriteTokens??0),D=$.config?.config,O=D?.models?.find((j)=>j.id===D.currentModelId)?.model??"",z=Z0(O,G,U,H,W);return{session:{...$.session,tokenUsage:{...Y,...Q,totalInputTokens:G,totalOutputTokens:U,cacheReadTokens:H,cacheWriteTokens:W,estimatedCostUsd:z}}}})},resetTokenUsage:()=>{X((Q)=>({session:{...Q.session,tokenUsage:{...U0}}}))},setCurrentThinkingContent:(Q)=>{if(Z().session.currentThinkingContent===Q)return;X(($)=>({session:{...$.session,currentThinkingContent:Q}}))},appendThinkingContent:(Q)=>{X(($)=>({session:{...$.session,currentThinkingContent:($.session.currentThinkingContent||"")+Q}}))},setThinkingExpanded:(Q)=>{X(($)=>({session:{...$.session,thinkingExpanded:Q}}))},toggleThinkingExpanded:()=>{X((Q)=>({session:{...Q.session,thinkingExpanded:!Q.session.thinkingExpanded}}))},setHistoryExpanded:(Q)=>{X(($)=>({session:{...$.session,historyExpanded:Q}}))},toggleHistoryExpanded:()=>{X((Q)=>({session:{...Q.session,historyExpanded:!Q.session.historyExpanded}}))},setExpandedMessageCount:(Q)=>{X(($)=>({session:{...$.session,expandedMessageCount:Q}}))},incrementClearCount:()=>{X((Q)=>({session:{...Q.session,clearCount:Q.session.clearCount+1}}))},startStreamingAssistantMessage:()=>{let Q=`assistant-${Date.now()}-${Math.random()}`,$={id:Q,role:"assistant",content:"",timestamp:Date.now()};return M=[],X((Y)=>({session:{...Y.session,messages:[...Y.session.messages,$],currentStreamingMessageId:Q,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,error:null}})),Q},appendAssistantContent:(Q)=>{let $=Z().session.currentStreamingMessageId,Y=$??`assistant-${Date.now()}-${Math.random()}`;return M.push(Q),X((V)=>{let J=(L)=>L.endsWith("\r")?L.slice(0,-1):L,G=$?V.session.currentStreamingLines:[],U=$?V.session.currentStreamingTail:"",H=$?V.session.currentStreamingLineCount:0,W=$?V.session.currentStreamingVersion:0,v=(U+Q).split(`
|
|
16
|
+
`),O=v.slice(0,-1).map(J),z=J(v[v.length-1]??""),j=G;if(O.length>0){if(j=[...G,...O],j.length>J0){let L=j.length-J0;j=j.slice(L)}}return{session:{...V.session,currentStreamingMessageId:Y,currentStreamingLines:j,currentStreamingTail:z,currentStreamingLineCount:H+O.length,currentStreamingVersion:W+1,error:null}}}),Y},finalizeStreamingMessage:(Q,$)=>{let Y=g0();X((V)=>{let J=V.session.currentStreamingMessageId,U=Y.join("")+(Q||""),H=(V.session.currentThinkingContent||"")+($||"");if(U.length>0){let W={id:J||`assistant-${Date.now()}-${Math.random()}`,role:"assistant",content:U,timestamp:Date.now(),thinkingContent:H||void 0};return{session:{...V.session,messages:[...V.session.messages,W],currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,currentThinkingContent:null,finalizingStreamingMessageId:W.id}}}return{session:{...V.session,currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,currentThinkingContent:null,finalizingStreamingMessageId:null}}})},clearFinalizingStreamingMessageId:()=>{X((Q)=>({session:{...Q.session,finalizingStreamingMessageId:null}}))},discardStreamingMessage:()=>{M=[],X((Q)=>({session:{...Q.session,currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,finalizingStreamingMessageId:null}}))}}});import{nanoid as l0}from"nanoid";import{promises as w}from"node:fs";import*as F from"node:path";import{fileURLToPath as d0}from"node:url";import{nanoid as m0}from"nanoid";var j0={proposal:"proposal.md",spec:"spec.md",requirements:"requirements.md",design:"design.md",tasks:"tasks.md",meta:".meta.json"},P={SPECS:"specs",CHANGES:"changes",ARCHIVE:"archive",STEERING:"steering",SPEC_DELTA:"specs"},C={CONSTITUTION:"constitution.md",PRODUCT:"product.md",TECH:"tech.md",STRUCTURE:"structure.md"};var T={init:["requirements"],requirements:["design","tasks"],design:["tasks"],tasks:["implementation"],implementation:["done","tasks"],done:[]},A1={init:"初始化",requirements:"需求定义",design:"架构设计",tasks:"任务分解",implementation:"实现中",done:"已完成"},H0={init:"proposal",requirements:"requirements",design:"design",tasks:"tasks",implementation:"tasks",done:null};var r0=d0(import.meta.url),c0=F.dirname(r0),z0=F.join(c0,"templates");class N{workspaceRoot;bladeDir;constructor(X){this.workspaceRoot=X,this.bladeDir=F.join(X,".blade")}getSpecsDir(){return F.join(this.bladeDir,P.SPECS)}getChangesDir(){return F.join(this.bladeDir,P.CHANGES)}getArchiveDir(){return F.join(this.bladeDir,P.ARCHIVE)}getSteeringDir(){return F.join(this.bladeDir,P.STEERING)}getChangePath(X){return F.join(this.getChangesDir(),X)}getChangeFilePath(X,Z){return F.join(this.getChangePath(X),j0[Z])}async initializeDirectories(){await w.mkdir(this.getChangesDir(),{recursive:!0,mode:493})}async createChangeDir(X){let Z=this.getChangePath(X);return await w.mkdir(Z,{recursive:!0,mode:493}),await w.mkdir(F.join(Z,P.SPEC_DELTA),{recursive:!0,mode:493}),Z}async readFile(X){try{return await w.readFile(X,"utf-8")}catch(Z){if(Z.code==="ENOENT")return null;throw Z}}async writeFile(X,Z){let Q=F.dirname(X);await w.mkdir(Q,{recursive:!0,mode:493}),await w.writeFile(X,Z,"utf-8")}async fileExists(X){try{return await w.access(X),!0}catch{return!1}}async dirExists(X){try{return(await w.stat(X)).isDirectory()}catch{return!1}}createMetadata(X,Z){let Q=new Date().toISOString();return{id:m0(),name:X,description:Z,phase:"init",createdAt:Q,updatedAt:Q,tasks:[]}}async readMetadata(X){let Z=this.getChangeFilePath(X,"meta"),Q=await this.readFile(Z);if(!Q)return null;try{return JSON.parse(Q)}catch{return null}}async writeMetadata(X,Z){let Q=this.getChangeFilePath(X,"meta");Z.updatedAt=new Date().toISOString(),await this.writeFile(Q,JSON.stringify(Z,null,2))}async updatePhase(X,Z){let Q=await this.readMetadata(X);if(!Q)return null;return Q.phase=Z,await this.writeMetadata(X,Q),Q}async readSpecFile(X,Z){let Q=this.getChangeFilePath(X,Z);return this.readFile(Q)}async writeSpecFile(X,Z,Q){let $=this.getChangeFilePath(X,Z);await this.writeFile($,Q);let Y=await this.readMetadata(X);if(Y)await this.writeMetadata(X,Y)}async getPhaseContent(X,Z){let Q=H0[Z];if(!Q)return null;return this.readSpecFile(X,Q)}async readSteeringContext(){let X=this.getSteeringDir(),[Z,Q,$,Y]=await Promise.all([this.readFile(F.join(X,C.CONSTITUTION)),this.readFile(F.join(X,C.PRODUCT)),this.readFile(F.join(X,C.TECH)),this.readFile(F.join(X,C.STRUCTURE))]);return{constitution:Z||void 0,product:Q||void 0,tech:$||void 0,structure:Y||void 0}}async writeSteeringFile(X,Z){let Q=F.join(this.getSteeringDir(),C[X]);await this.writeFile(Q,Z)}async hasSteeringDocs(){let X=this.getSteeringDir();if(!await this.dirExists(X))return!1;return(await w.readdir(X)).length>0}async listActiveChanges(){let X=this.getChangesDir();if(!await this.dirExists(X))return[];return(await w.readdir(X,{withFileTypes:!0})).filter((Q)=>Q.isDirectory()).map((Q)=>Q.name)}async listArchivedChanges(){let X=this.getArchiveDir();if(!await this.dirExists(X))return[];return(await w.readdir(X,{withFileTypes:!0})).filter((Q)=>Q.isDirectory()).map((Q)=>Q.name)}async changeExists(X){return this.dirExists(this.getChangePath(X))}async archiveChange(X){let Z=this.getChangePath(X),Q=F.join(this.getArchiveDir(),X);await w.mkdir(F.dirname(Q),{recursive:!0,mode:493}),await w.rename(Z,Q)}async restoreChange(X){let Z=F.join(this.getArchiveDir(),X),Q=this.getChangePath(X);await w.rename(Z,Q)}async listSpecDomains(){let X=this.getSpecsDir();if(!await this.dirExists(X))return[];return(await w.readdir(X,{withFileTypes:!0})).filter((Q)=>Q.isDirectory()).map((Q)=>Q.name)}async readAuthorativeSpec(X){let Z=F.join(this.getSpecsDir(),X,"spec.md");return this.readFile(Z)}async writeAuthorativeSpec(X,Z){let Q=F.join(this.getSpecsDir(),X,"spec.md");await this.writeFile(Q,Z)}async mergeSpecDeltas(X){let Z=F.join(this.getChangePath(X),P.SPEC_DELTA);if(!await this.dirExists(Z))return[];let Q=[],$=await w.readdir(Z,{withFileTypes:!0});for(let Y of $){if(!Y.isDirectory())continue;let V=F.join(Z,Y.name,"spec.md"),J=await this.readFile(V);if(J){let G=await this.readAuthorativeSpec(Y.name),U=G?`${G}
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
<!-- Merged from ${X} -->
|
|
21
|
+
|
|
22
|
+
${J}`:J;await this.writeAuthorativeSpec(Y.name,U),Q.push(Y.name)}}return Q}static TEMPLATE_NAMES={proposal:"proposal.md.template",spec:"spec.md.template",requirements:"requirements.md.template",design:"design.md.template",tasks:"tasks.md.template",meta:""};static STEERING_TEMPLATE_NAMES={CONSTITUTION:"steering/constitution.md.template",PRODUCT:"steering/product.md.template",TECH:"steering/tech.md.template",STRUCTURE:"steering/structure.md.template"};async readTemplate(X){let Z=N.TEMPLATE_NAMES[X];if(!Z)return null;let Q=F.join(z0,Z);return this.readFile(Q)}async readSteeringTemplate(X){let Z=N.STEERING_TEMPLATE_NAMES[X],Q=F.join(z0,Z);return this.readFile(Q)}fillTemplate(X,Z){let Q=X;for(let[$,Y]of Object.entries(Z))Q=Q.replace(new RegExp(`\\{\\{${$}\\}\\}`,"g"),Y);return Q}async createFromTemplate(X,Z,Q){let $=await this.readTemplate(Z);if(!$)return null;let Y=this.fillTemplate($,{name:X,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),...Q});return await this.writeSpecFile(X,Z,Y),Y}async createSteeringFromTemplate(X,Z={}){let Q=await this.readSteeringTemplate(X);if(!Q)return null;let $=this.fillTemplate(Q,{createdAt:new Date().toISOString(),...Z});return await this.writeSteeringFile(X,$),$}async initializeSteeringDocs(){let X=[],Z=this.getSteeringDir();for(let[Q,$]of Object.entries(C)){let Y=F.join(Z,$);if(!await this.fileExists(Y))await this.createSteeringFromTemplate(Q),X.push($)}return X}}class x{static instance=null;fileManager=null;workspaceRoot=null;constructor(){}static getInstance(){if(!x.instance)x.instance=new x;return x.instance}static resetInstance(){x.instance=null}async initialize(X){if(this.workspaceRoot===X&&this.fileManager)return;this.workspaceRoot=X,this.fileManager=new N(X),await this.fileManager.initializeDirectories()}getFileManager(){if(!this.fileManager)throw Error("SpecService not initialized. Call initialize() first.");return this.fileManager}async readSteeringContext(){return this.getFileManager().readSteeringContext()}async readSpecMetadata(X){return this.getFileManager().readMetadata(X)}async specExists(X){return this.getFileManager().changeExists(X)}getSpecPath(X){return this.getFileManager().getChangePath(X)}async createSpec(X,Z){let Q=this.getFileManager();if(await Q.changeExists(X))return{success:!1,message:`Spec "${X}" already exists`,error:"SPEC_EXISTS"};let $=await Q.createChangeDir(X),Y=Q.createMetadata(X,Z);await Q.writeMetadata(X,Y);let V=this.generateProposalTemplate(X,Z);return await Q.writeSpecFile(X,"proposal",V),{success:!0,message:`Spec "${X}" created successfully`,data:{spec:Y,path:$}}}async loadSpec(X){let Z=this.getFileManager(),Q=await Z.readMetadata(X);if(!Q)return{success:!1,message:`Spec "${X}" not found`,error:"SPEC_NOT_FOUND"};let $=Z.getChangePath(X);return{success:!0,message:`Spec "${X}" loaded successfully`,data:{spec:Q,path:$}}}canTransitionPhase(X,Z){return T[X].includes(Z)}getAllowedTransitions(X){return T[X]}async updatePhase(X,Z){return this.getFileManager().updatePhase(X,Z)}createTask(X,Z,Q){return{id:l0(8),title:X,description:Z,status:"pending",dependencies:Q?.dependencies||[],affectedFiles:Q?.affectedFiles||[],complexity:Q?.complexity||"medium"}}async saveMetadata(X,Z){await this.getFileManager().writeMetadata(X,Z)}getNextTask(X){return X.find((Z)=>{if(Z.status!=="pending")return!1;return Z.dependencies.every((Q)=>{return X.find((Y)=>Y.id===Q)?.status==="completed"})})||null}getTaskProgress(X){if(X.length===0)return{total:0,completed:0,percentage:0};let Z=X.length,Q=X.filter((Y)=>Y.status==="completed").length,$=Math.round(Q/Z*100);return{total:Z,completed:Q,percentage:$}}async listActiveSpecs(){return this.getFileManager().listActiveChanges()}async listArchivedSpecs(){return this.getFileManager().listArchivedChanges()}async archiveSpec(X){let Z=this.getFileManager();return await Z.mergeSpecDeltas(X),await Z.updatePhase(X,"done"),await Z.archiveChange(X),{success:!0,message:`Spec "${X}" archived successfully`}}async validateSpec(X){let Z=this.getFileManager(),Q=[],$=[],[Y,V,J,G,U]=await Promise.all([Z.readSpecFile(X.name,"proposal"),Z.readSpecFile(X.name,"spec"),Z.readSpecFile(X.name,"requirements"),Z.readSpecFile(X.name,"design"),Z.readSpecFile(X.name,"tasks")]),H={proposal:!!Y,spec:!!V,requirements:!!J,design:!!G,tasks:!!U};if(X.phase==="requirements"&&!H.requirements)Q.push({severity:"warning",file:"requirements",message:"Requirements document is missing"}),$.push("Generate requirements using EARS format");if(X.phase==="design"&&!H.design)Q.push({severity:"warning",file:"design",message:"Design document is missing"}),$.push("Create architecture diagrams and API contracts");if(X.phase==="tasks"&&X.tasks.length===0)Q.push({severity:"warning",file:"tasks",message:"No tasks defined"}),$.push("Break down the spec into atomic tasks");if(X.phase==="implementation"){let W=this.getTaskProgress(X.tasks);if(W.completed<W.total)Q.push({severity:"info",file:"tasks",message:`${W.total-W.completed} tasks remaining`})}return{valid:Q.filter((W)=>W.severity==="error").length===0,phase:X.phase,completeness:H,issues:Q,suggestions:$}}generateProposalTemplate(X,Z){return`# ${X}
|
|
23
|
+
|
|
24
|
+
## Summary
|
|
25
|
+
|
|
26
|
+
${Z}
|
|
27
|
+
|
|
28
|
+
## Background
|
|
29
|
+
|
|
30
|
+
<!-- Why is this change needed? What problem does it solve? -->
|
|
31
|
+
|
|
32
|
+
## Goals
|
|
33
|
+
|
|
34
|
+
<!-- What are the specific objectives of this change? -->
|
|
35
|
+
|
|
36
|
+
- [ ] Goal 1
|
|
37
|
+
- [ ] Goal 2
|
|
38
|
+
|
|
39
|
+
## Non-Goals
|
|
40
|
+
|
|
41
|
+
<!-- What is explicitly out of scope? -->
|
|
42
|
+
|
|
43
|
+
## Risks and Mitigations
|
|
44
|
+
|
|
45
|
+
<!-- What could go wrong? How will you address it? -->
|
|
46
|
+
|
|
47
|
+
| Risk | Mitigation |
|
|
48
|
+
|------|------------|
|
|
49
|
+
| | |
|
|
50
|
+
|
|
51
|
+
## Open Questions
|
|
52
|
+
|
|
53
|
+
<!-- What needs to be clarified before proceeding? -->
|
|
54
|
+
|
|
55
|
+
1.
|
|
56
|
+
`}}var W0=K0("Spec"),F0={currentSpec:null,specPath:null,isActive:!1,steeringContext:null,recentSpecs:[],isLoading:!1,error:null,workspaceRoot:null},n=(X,Z)=>({...F0,actions:{initialize:async(Q)=>{let $=x.getInstance();await $.initialize(Q);let Y=await $.readSteeringContext();X((V)=>({spec:{...V.spec,workspaceRoot:Q,steeringContext:Y}}))},createSpec:async(Q,$)=>{let V=await x.getInstance().createSpec(Q,$);if(V.success&&V.data){let{spec:J,path:G}=V.data,U=Z().spec.recentSpecs.filter((H)=>H!==Q);U.unshift(Q),X((H)=>({spec:{...H.spec,currentSpec:J,specPath:G,isActive:!0,recentSpecs:U.slice(0,10)}}))}return V},loadSpec:async(Q)=>{let Y=await x.getInstance().loadSpec(Q);if(Y.success&&Y.data){let{spec:V,path:J}=Y.data,G=Z().spec.recentSpecs.filter((U)=>U!==Q);G.unshift(Q),X((U)=>({spec:{...U.spec,currentSpec:V,specPath:J,isActive:!0,recentSpecs:G.slice(0,10)}}))}return Y},closeSpec:()=>{X((Q)=>({spec:{...Q.spec,currentSpec:null,specPath:null,isActive:!1}}))},exitSpecMode:()=>{Z().spec.actions.closeSpec()},transitionPhase:async(Q)=>{let $=Z().spec.currentSpec;if(!$)return{success:!1,message:"No active spec",error:"NO_ACTIVE_SPEC"};let Y=x.getInstance();if(!Y.canTransitionPhase($.phase,Q))return{success:!1,message:`Cannot transition from "${$.phase}" to "${Q}"`,error:"INVALID_TRANSITION"};let V=await Y.updatePhase($.name,Q);if(!V)return{success:!1,message:"Failed to update phase",error:"UPDATE_FAILED"};if(X((J)=>({spec:{...J.spec,currentSpec:V}})),Q==="done")try{let{config:J}=Z();if(J.actions)J.actions.updateConfig({permissionMode:"default"});W0.info("Spec 已完成,已自动退出 Spec 模式")}catch(J){W0.error("自动退出 Spec 模式失败:",J)}return{success:!0,message:`Transitioned to "${Q}" phase`,data:{spec:V,phase:Q}}},getAllowedTransitions:()=>{let Q=Z().spec.currentSpec;if(!Q)return[];return T[Q.phase]},addTask:async(Q,$,Y)=>{let V=Z().spec.currentSpec;if(!V)return{success:!1,message:"No active spec",error:"NO_ACTIVE_SPEC"};let J=x.getInstance(),G=J.createTask(Q,$,Y),U={...V,tasks:[...V.tasks,G],updatedAt:new Date().toISOString()};return await J.saveMetadata(V.name,U),X((H)=>({spec:{...H.spec,currentSpec:U}})),{success:!0,message:`Task "${Q}" added`,data:{task:G}}},updateTaskStatus:async(Q,$)=>{let Y=Z().spec.currentSpec;if(!Y)return{success:!1,message:"No active spec",error:"NO_ACTIVE_SPEC"};let V=Y.tasks.find((W)=>W.id===Q);if(!V)return{success:!1,message:`Task "${Q}" not found`,error:"TASK_NOT_FOUND"};let J={...V,status:$,completedAt:$==="completed"?new Date().toISOString():V.completedAt},G=Y.tasks.map((W)=>W.id===Q?J:W),U={...Y,tasks:G,currentTaskId:$==="in_progress"?Q:Y.currentTaskId===Q?void 0:Y.currentTaskId,updatedAt:new Date().toISOString()};return await x.getInstance().saveMetadata(Y.name,U),X((W)=>({spec:{...W.spec,currentSpec:U}})),{success:!0,message:`Task status updated to "${$}"`,data:{task:J}}},getNextTask:()=>{let Q=Z().spec.currentSpec;if(!Q)return null;return x.getInstance().getNextTask(Q.tasks)},getTaskProgress:()=>{let Q=Z().spec.currentSpec;if(!Q)return{total:0,completed:0,percentage:0};return x.getInstance().getTaskProgress(Q.tasks)},listSpecs:async(Q)=>{let $=x.getInstance(),Y=[],V=await $.listActiveSpecs();for(let J of V){let G=await $.readSpecMetadata(J);if(!G)continue;if(Q?.phase&&G.phase!==Q.phase)continue;if(Q?.tags&&!Q.tags.some((H)=>G.tags?.includes(H)))continue;if(Q?.query&&!G.name.toLowerCase().includes(Q.query.toLowerCase())&&!G.description.toLowerCase().includes(Q.query.toLowerCase()))continue;let U=$.getTaskProgress(G.tasks);Y.push({name:G.name,description:G.description,phase:G.phase,updatedAt:G.updatedAt,path:$.getSpecPath(J),isArchived:!1,taskProgress:{total:U.total,completed:U.completed}})}if(Q?.includeArchived){let J=await $.listArchivedSpecs();for(let G of J)Y.push({name:G,description:"(archived)",phase:"done",updatedAt:"",path:`archive/${G}`,isArchived:!0,taskProgress:{total:0,completed:0}})}return Y.sort((J,G)=>{if(J.isArchived!==G.isArchived)return J.isArchived?1:-1;return new Date(G.updatedAt).getTime()-new Date(J.updatedAt).getTime()}),Y},archiveCurrentSpec:async()=>{let Q=Z().spec.currentSpec;if(!Q)return{success:!1,message:"No active spec",error:"NO_ACTIVE_SPEC"};let Y=await x.getInstance().archiveSpec(Q.name);if(Y.success)Z().spec.actions.closeSpec();return Y},validateCurrentSpec:async()=>{let Q=Z().spec.currentSpec;if(!Q)return{valid:!1,phase:"init",completeness:{proposal:!1,spec:!1,requirements:!1,design:!1,tasks:!1},issues:[{severity:"error",file:"meta",message:"No active spec"}],suggestions:["Create a new spec with /spec proposal <name>"]};return x.getInstance().validateSpec(Q)},getSteeringContextString:async()=>{let Q=Z().spec.steeringContext;if(!Q)return null;let $=[];if(Q.constitution)$.push(`## Constitution (Project Governance)
|
|
57
|
+
|
|
58
|
+
${Q.constitution}`);if(Q.product)$.push(`## Product Vision
|
|
59
|
+
|
|
60
|
+
${Q.product}`);if(Q.tech)$.push(`## Technology Stack
|
|
61
|
+
|
|
62
|
+
${Q.tech}`);if(Q.structure)$.push(`## Code Structure
|
|
63
|
+
|
|
64
|
+
${Q.structure}`);return $.length>0?$.join(`
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
`):null},setError:(Q)=>{X(($)=>({spec:{...$.spec,error:Q}}))},setLoading:(Q)=>{X(($)=>({spec:{...$.spec,isLoading:Q}}))},reset:()=>{X((Q)=>({spec:{...F0,actions:Q.spec.actions}}))}}});var a0=s0()(o0(n0((...X)=>({session:o(...X),app:g(...X),config:m(...X),focus:r(...X),command:d(...X),spec:n(...X)})),{name:"BladeStore",enabled:!0})),q=()=>a0.getState(),t1=()=>q().session.actions,e1=()=>q().app.actions,Q5=()=>q().session.messages,y=()=>q().config.config,I=null;async function X5(){if(y()!==null)return;if(I)return I;return I=(async()=>{try{let Q=await q0.getInstance().initialize();q().config.actions.setConfig(Q)}catch(Z){throw I=null,Error(`[FAIL] Store 未初始化且无法自动初始化
|
|
69
|
+
|
|
70
|
+
`+`原因: ${Z instanceof Error?Z.message:"未知错误"}
|
|
71
|
+
|
|
72
|
+
`+`请确保:
|
|
73
|
+
`+`1. 配置文件格式正确 (~/.blade/config.json)
|
|
74
|
+
`+`2. 运行 blade 进行首次配置
|
|
75
|
+
`+"3. 配置文件权限正确")}finally{I=null}})(),I}var Z5=()=>q().config.config?.models??[],$5=()=>{let X=y();if(!X)return;let Z=X.currentModelId;return X.models.find(($)=>$.id===Z)??X.models[0]},Y5=(X)=>{let Z=y();if(!Z)return;return Z.models.find((Q)=>Q.id===X)},V5=()=>q().config.config?.mcpServers??{},J5=()=>q().app.thinkingModeEnabled,G5=()=>({setPermissionMode:async(X)=>{q().config.actions.updateConfig({permissionMode:X})},setTheme:async(X,Z={})=>{try{X0.setTheme(X)}catch{return}q().config.actions.updateConfig({theme:X}),await A().save({theme:X},{scope:"global",...Z})},setLanguage:async(X,Z={})=>{q().config.actions.updateConfig({language:X}),await A().save({language:X},{scope:"global",...Z})},setDebug:async(X,Z={})=>{q().config.actions.updateConfig({debug:X}),await A().save({debug:X},{scope:"global",...Z})},setTemperature:async(X,Z={})=>{q().config.actions.updateConfig({temperature:X}),await A().save({temperature:X},{scope:"global",...Z})},updateConfig:async(X,Z={})=>{let Q=y();if(!Q)throw Error("Config not initialized");let $={...Q};q().config.actions.updateConfig(X);try{await A().save(X,Z)}catch(Y){throw q().config.actions.setConfig($),Y}},flush:async()=>{await A().flush()},appendPermissionAllowRule:async(X,Z={})=>{let Q=y();if(!Q)throw Error("Config not initialized");let $=Q.permissions?.allow||[];if(!$.includes(X)){let Y=[...$,X];q().config.actions.updateConfig({permissions:{...Q.permissions,allow:Y}})}await A().appendPermissionRule(X,Z)},appendLocalPermissionAllowRule:async(X,Z={})=>{let Q=y();if(!Q)throw Error("Config not initialized");let $=Q.permissions?.allow||[];if(!$.includes(X)){let Y=[...$,X];q().config.actions.updateConfig({permissions:{...Q.permissions,allow:Y}})}await A().appendLocalPermissionRule(X,Z)},setCurrentModel:async(X,Z={})=>{let Q=y();if(!Q)throw Error("Config not initialized");if(!Q.models.find((Y)=>Y.id===X))throw Error(`Model not found: ${X}`);q().config.actions.updateConfig({currentModelId:X}),await A().save({currentModelId:X},{scope:"global",...Z})},addModel:async(X,Z={})=>{let Q=y();if(!Q)throw Error("Config not initialized");let $="id"in X?X:{id:i0(),...X},V={models:[...Q.models,$]};if(Q.models.length===0)V.currentModelId=$.id;return q().config.actions.updateConfig(V),await A().save(V,{scope:"global",...Z}),$},updateModel:async(X,Z,Q={})=>{let $=y();if(!$)throw Error("Config not initialized");let Y=$.models.findIndex((J)=>J.id===X);if(Y===-1)throw Error(`Model not found: ${X}`);let V=[...$.models];V[Y]={...V[Y],...Z},q().config.actions.updateConfig({models:V}),await A().save({models:V},{scope:"global",...Q})},removeModel:async(X,Z={})=>{let Q=y();if(!Q)throw Error("Config not initialized");if(Q.models.length===1)throw Error("Cannot remove the only model");let $=Q.models.filter((V)=>V.id!==X),Y={models:$};if(Q.currentModelId===X)Y.currentModelId=$[0].id;q().config.actions.updateConfig(Y),await A().save(Y,{scope:"global",...Z})},addMcpServer:async(X,Z,Q={})=>{let $=y();if(!$)throw Error("Config not initialized");let V={...$.mcpServers??{},[X]:Z};q().config.actions.updateConfig({mcpServers:V}),await A().save({mcpServers:V},{scope:"project",...Q})},removeMcpServer:async(X,Z={})=>{let Q=y();if(!Q)throw Error("Config not initialized");let Y={...Q.mcpServers??{}};delete Y[X],q().config.actions.updateConfig({mcpServers:Y}),await A().save({mcpServers:Y},{scope:"project",...Z})}});
|
|
76
|
+
export{t as ha,X0 as ia,K as ja,G1 as ka,H1 as la,z1 as ma,W1 as na,F1 as oa,K1 as pa,q1 as qa,T as ra,A1 as sa,N as ta,a0 as ua,q as va,t1 as wa,e1 as xa,Q5 as ya,y as za,X5 as Aa,Z5 as Ba,$5 as Ca,Y5 as Da,V5 as Ea,J5 as Fa,G5 as Ga};
|