blade-code 0.7.0 → 0.7.2

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.
Files changed (73) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-108p1xw7.js +1 -0
  3. package/dist/{chunk-nsbhtvqd.js → chunk-1mge0pzv.js} +1 -1
  4. package/dist/{chunk-hc08zg54.js → chunk-1w719wd9.js} +1 -1
  5. package/dist/{chunk-q6c9qs9b.js → chunk-22gxb9qs.js} +2 -2
  6. package/dist/{chunk-sw6ngzbg.js → chunk-275gt6q1.js} +1 -1
  7. package/dist/chunk-42q476bq.js +1 -0
  8. package/dist/{chunk-mt1c5da4.js → chunk-4hk7wfat.js} +2 -2
  9. package/dist/{chunk-tn3xjczg.js → chunk-67zx7ymj.js} +1 -1
  10. package/dist/chunk-7d1pn8a1.js +2 -0
  11. package/dist/{chunk-kk8akm7s.js → chunk-8xdqtspw.js} +1 -1
  12. package/dist/{chunk-c2b6ekqx.js → chunk-9zwf87ne.js} +2 -2
  13. package/dist/chunk-abpvdaq2.js +6 -0
  14. package/dist/{chunk-m22zeqdy.js → chunk-b6mxeey0.js} +2 -2
  15. package/dist/chunk-cadngkwr.js +2 -0
  16. package/dist/{chunk-0afbeec0.js → chunk-cfrbsnfb.js} +1 -1
  17. package/dist/{chunk-k4behavv.js → chunk-cqrkeq20.js} +1 -1
  18. package/dist/{chunk-7z6ba6t9.js → chunk-f9b8h03c.js} +1 -1
  19. package/dist/chunk-g0h3rans.js +6 -0
  20. package/dist/chunk-hv0bzn31.js +1 -0
  21. package/dist/chunk-j3k2c6tm.js +1 -0
  22. package/dist/chunk-je6r01h4.js +1 -0
  23. package/dist/{chunk-31chcjw6.js → chunk-k18bq4mn.js} +2 -2
  24. package/dist/{chunk-ft5nt5b5.js → chunk-m2k4h3bs.js} +1 -1
  25. package/dist/chunk-m4a480k7.js +9 -0
  26. package/dist/chunk-nh37erd3.js +1 -0
  27. package/dist/{chunk-rzz6r1g9.js → chunk-p6d7k1x6.js} +3 -3
  28. package/dist/chunk-p9pthxkm.js +6 -0
  29. package/dist/{chunk-96w1szbp.js → chunk-qw2wy4jc.js} +1 -1
  30. package/dist/{chunk-zmp3vdcj.js → chunk-rmtcqc8q.js} +1 -1
  31. package/dist/{chunk-gxnwrec6.js → chunk-rr62k3ar.js} +2 -2
  32. package/dist/{chunk-pkzy724w.js → chunk-t3pyakvc.js} +2 -2
  33. package/dist/chunk-t6y57501.js +1533 -0
  34. package/dist/chunk-wc2xb6ge.js +24 -0
  35. package/dist/{chunk-f76d6jxg.js → chunk-wcm0nc84.js} +1 -1
  36. package/dist/{chunk-pf33bn8s.js → chunk-xa8szzc6.js} +1 -1
  37. package/dist/{chunk-e21htmg4.js → chunk-z0qxaky4.js} +1 -1
  38. package/dist/chunk-z72cp8f5.js +150 -0
  39. package/dist/chunk-zcreym5g.js +615 -0
  40. package/dist/chunk-ztpseq3n.js +1 -0
  41. package/dist/web/assets/{FilePreview-DLnUh-wQ.js → FilePreview-DXDzoFFc.js} +1 -1
  42. package/dist/web/assets/{MarkdownRenderer-C5KTk9XG.js → MarkdownRenderer-BVPOLK1b.js} +1 -1
  43. package/dist/web/assets/{McpModal-B9qJ4ewt.js → McpModal-DeTf34Fw.js} +1 -1
  44. package/dist/web/assets/{SettingsModal-DpeZ6cJb.js → SettingsModal-CDLkPyL-.js} +1 -1
  45. package/dist/web/assets/{SettingsStore-IzKtyAnM.js → SettingsStore-DYKvNeV_.js} +1 -1
  46. package/dist/web/assets/{SkillsModal-BDfzgJIj.js → SkillsModal-D784AUrt.js} +1 -1
  47. package/dist/web/assets/{TerminalPanel-B2iTF_CR.js → TerminalPanel-BosJuIct.js} +1 -1
  48. package/dist/web/assets/{dialog-sI3ihAze.js → dialog-CgyS_4Eo.js} +1 -1
  49. package/dist/web/assets/index-Abieffcr.js +10 -0
  50. package/dist/web/assets/index-CQ3JnuUf.css +1 -0
  51. package/dist/web/index.html +2 -2
  52. package/package.json +1 -1
  53. package/dist/chunk-2nnak657.js +0 -6
  54. package/dist/chunk-64jv62vs.js +0 -1
  55. package/dist/chunk-6f63v1mk.js +0 -2
  56. package/dist/chunk-93xhspe5.js +0 -1
  57. package/dist/chunk-fehae50v.js +0 -1
  58. package/dist/chunk-gertm8dw.js +0 -157
  59. package/dist/chunk-gscq4fmx.js +0 -49
  60. package/dist/chunk-hscq9623.js +0 -1
  61. package/dist/chunk-kpq18y6v.js +0 -6
  62. package/dist/chunk-mnw1xcwn.js +0 -76
  63. package/dist/chunk-p9s685ta.js +0 -1
  64. package/dist/chunk-phnararg.js +0 -1
  65. package/dist/chunk-v97f7je6.js +0 -2138
  66. package/dist/chunk-vzebrztg.js +0 -9
  67. package/dist/chunk-wre40mf1.js +0 -2
  68. package/dist/chunk-x46rv9sv.js +0 -6
  69. package/dist/chunk-ygta7118.js +0 -1
  70. package/dist/chunk-zd9stbct.js +0 -618
  71. package/dist/chunk-zjh9qqvq.js +0 -1
  72. package/dist/web/assets/index-D8mo0jzF.js +0 -10
  73. package/dist/web/assets/index-DmXmCQOW.css +0 -1
@@ -1,49 +0,0 @@
1
- import{Ia as F,ta as $,va as E,wa as q}from"./chunk-mnw1xcwn.js";import{Ob as w}from"./chunk-mt1c5da4.js";import{nanoid as O}from"nanoid";var Z=w("Spec");class X{static instance=null;fileManager=null;constructor(){}static getInstance(){if(!X.instance)X.instance=new X;return X.instance}static resetInstance(){X.instance=null}getStoreState(){return q.getState().spec}updateStoreState(z){q.setState((B)=>({spec:{...B.spec,...z}}))}async initialize(z){if(this.fileManager){Z.debug("SpecManager already initialized, skipping...");return}this.fileManager=new E(z),await this.fileManager.initializeDirectories();let B=await this.fileManager.readSteeringContext();this.updateStoreState({steeringContext:B}),Z.debug("SpecManager initialized successfully")}getFileManager(){if(!this.fileManager)throw Error("SpecManager not initialized. Call initialize() first.");return this.fileManager}getState(){return{...this.getStoreState()}}getCurrentSpec(){return this.getStoreState().currentSpec}isActive(){return this.getStoreState().isActive}getSteeringContext(){return this.getStoreState().steeringContext}async getSteeringContextString(){let z=this.getStoreState().steeringContext;if(!z)return null;let B=[];if(z.constitution)B.push(`## Constitution (Project Governance)
2
-
3
- ${z.constitution}`);if(z.product)B.push(`## Product Vision
4
-
5
- ${z.product}`);if(z.tech)B.push(`## Technology Stack
6
-
7
- ${z.tech}`);if(z.structure)B.push(`## Code Structure
8
-
9
- ${z.structure}`);return B.length>0?B.join(`
10
-
11
- ---
12
-
13
- `):null}async createSpec(z,B){let D=this.getFileManager();if(await D.changeExists(z))return{success:!1,message:`Spec "${z}" already exists`,error:"SPEC_EXISTS"};let K=await D.createChangeDir(z),J=D.createMetadata(z,B);await D.writeMetadata(z,J);let G=this.generateProposalTemplate(z,B);await D.writeSpecFile(z,"proposal",G);let U=this.getStoreState().recentSpecs.filter((Q)=>Q!==z);return U.unshift(z),this.updateStoreState({currentSpec:J,specPath:K,isActive:!0,recentSpecs:U.slice(0,10)}),{success:!0,message:`Spec "${z}" created successfully`,data:{spec:J,path:K}}}async loadSpec(z){let B=this.getFileManager(),D=await B.readMetadata(z);if(!D)return{success:!1,message:`Spec "${z}" not found`,error:"SPEC_NOT_FOUND"};let K=B.getChangePath(z),J=this.getStoreState().recentSpecs.filter((G)=>G!==z);return J.unshift(z),this.updateStoreState({currentSpec:D,specPath:K,isActive:!0,recentSpecs:J.slice(0,10)}),{success:!0,message:`Spec "${z}" loaded successfully`,data:{spec:D,path:K}}}closeSpec(){this.updateStoreState({currentSpec:null,specPath:null,isActive:!1})}exitSpecMode(){this.closeSpec()}async transitionPhase(z){let B=this.getCurrentSpec();if(!B)return{success:!1,message:"No active spec",error:"NO_ACTIVE_SPEC"};if(!$[B.phase].includes(z))return{success:!1,message:`Cannot transition from "${B.phase}" to "${z}"`,error:"INVALID_TRANSITION"};let J=await this.getFileManager().updatePhase(B.name,z);if(!J)return{success:!1,message:"Failed to update phase",error:"UPDATE_FAILED"};if(this.updateStoreState({currentSpec:J}),z==="done")try{await F().setPermissionMode("default"),Z.info("Spec 已完成,已自动退出 Spec 模式")}catch(G){Z.error("自动退出 Spec 模式失败:",G)}return{success:!0,message:`Transitioned to "${z}" phase`,data:{spec:J,phase:z}}}getAllowedTransitions(){let z=this.getCurrentSpec();if(!z)return[];return $[z.phase]}async addTask(z,B,D){let K=this.getCurrentSpec();if(!K)return{success:!1,message:"No active spec",error:"NO_ACTIVE_SPEC"};let J={id:O(8),title:z,description:B,status:"pending",dependencies:D?.dependencies||[],affectedFiles:D?.affectedFiles||[],complexity:D?.complexity||"medium"},G={...K,tasks:[...K.tasks,J],updatedAt:new Date().toISOString()};return await this.getFileManager().writeMetadata(K.name,G),this.updateStoreState({currentSpec:G}),{success:!0,message:`Task "${z}" added`,data:{task:J}}}async updateTaskStatus(z,B){let D=this.getCurrentSpec();if(!D)return{success:!1,message:"No active spec",error:"NO_ACTIVE_SPEC"};let K=D.tasks.find((Q)=>Q.id===z);if(!K)return{success:!1,message:`Task "${z}" not found`,error:"TASK_NOT_FOUND"};let J={...K,status:B,completedAt:B==="completed"?new Date().toISOString():K.completedAt},G=D.tasks.map((Q)=>Q.id===z?J:Q),U={...D,tasks:G,currentTaskId:B==="in_progress"?z:D.currentTaskId===z?void 0:D.currentTaskId,updatedAt:new Date().toISOString()};return await this.getFileManager().writeMetadata(D.name,U),this.updateStoreState({currentSpec:U}),{success:!0,message:`Task status updated to "${B}"`,data:{task:J}}}getNextTask(){let z=this.getCurrentSpec();if(!z)return null;return z.tasks.find((B)=>{if(B.status!=="pending")return!1;return B.dependencies.every((D)=>{return z.tasks.find((J)=>J.id===D)?.status==="completed"})})||null}getTaskProgress(){let z=this.getCurrentSpec();if(!z||z.tasks.length===0)return{total:0,completed:0,percentage:0};let B=z.tasks.length,D=z.tasks.filter((J)=>J.status==="completed").length,K=Math.round(D/B*100);return{total:B,completed:D,percentage:K}}async listSpecs(z){let B=this.getFileManager(),D=[],K=await B.listActiveChanges();for(let J of K){let G=await B.readMetadata(J);if(!G)continue;if(z?.phase&&G.phase!==z.phase)continue;if(z?.tags&&!z.tags.some((Q)=>G.tags?.includes(Q)))continue;if(z?.query&&!G.name.toLowerCase().includes(z.query.toLowerCase())&&!G.description.toLowerCase().includes(z.query.toLowerCase()))continue;let U=this.calculateTaskProgress(G.tasks);D.push({name:G.name,description:G.description,phase:G.phase,updatedAt:G.updatedAt,path:B.getChangePath(J),isArchived:!1,taskProgress:U})}if(z?.includeArchived){let J=await B.listArchivedChanges();for(let G of J)D.push({name:G,description:"(archived)",phase:"done",updatedAt:"",path:`${B.getArchiveDir()}/${G}`,isArchived:!0,taskProgress:{total:0,completed:0}})}return D.sort((J,G)=>{if(J.isArchived!==G.isArchived)return J.isArchived?1:-1;return new Date(G.updatedAt).getTime()-new Date(J.updatedAt).getTime()}),D}async archiveCurrentSpec(){let z=this.getCurrentSpec();if(!z)return{success:!1,message:"No active spec",error:"NO_ACTIVE_SPEC"};let B=this.getFileManager(),D=await B.mergeSpecDeltas(z.name);return await B.updatePhase(z.name,"done"),await B.archiveChange(z.name),this.closeSpec(),{success:!0,message:`Spec "${z.name}" archived successfully`,data:{spec:{...z,phase:"done"}}}}async validateCurrentSpec(){let z=this.getCurrentSpec();if(!z)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>"]};let B=this.getFileManager(),D=[],K=[],[J,G,U,Q,V]=await Promise.all([B.readSpecFile(z.name,"proposal"),B.readSpecFile(z.name,"spec"),B.readSpecFile(z.name,"requirements"),B.readSpecFile(z.name,"design"),B.readSpecFile(z.name,"tasks")]),Y={proposal:!!J,spec:!!G,requirements:!!U,design:!!Q,tasks:!!V};if(z.phase==="requirements"&&!Y.requirements)D.push({severity:"warning",file:"requirements",message:"Requirements document is missing"}),K.push("Generate requirements using EARS format");if(z.phase==="design"&&!Y.design)D.push({severity:"warning",file:"design",message:"Design document is missing"}),K.push("Create architecture diagrams and API contracts");if(z.phase==="tasks"&&z.tasks.length===0)D.push({severity:"warning",file:"tasks",message:"No tasks defined"}),K.push("Break down the spec into atomic tasks");if(z.phase==="implementation"){let W=this.getTaskProgress();if(W.completed<W.total)D.push({severity:"info",file:"tasks",message:`${W.total-W.completed} tasks remaining`})}return{valid:D.filter((W)=>W.severity==="error").length===0,phase:z.phase,completeness:Y,issues:D,suggestions:K}}buildProgressContext(){if(!this.isActive())return null;let z=this.getCurrentSpec();if(!z||z.phase!=="implementation")return null;let B=z.tasks;if(B.length===0)return null;let D=B.filter((V)=>V.status==="completed").length,K=B.filter((V)=>V.status==="skipped").length,J=B.length,G=z.currentTaskId?B.find((V)=>V.id===z.currentTaskId):B.find((V)=>V.status==="in_progress"),U=B.find((V)=>{if(V.status!=="pending")return!1;return V.dependencies.every((Y)=>{return B.find((H)=>H.id===Y)?.status==="completed"})}),Q=[`当前正在执行 Spec: ${z.name} (${z.phase} 阶段)`,`进度: ${D}/${J} 任务已完成${K>0?`,${K} 个已跳过`:""}`];if(G)Q.push(`当前任务: #${B.indexOf(G)+1} - ${G.title}${G.description?` (${G.description})`:""}`);if(U&&U!==G)Q.push(`下一个任务: #${B.indexOf(U)+1} - ${U.title}`);if(D+K>=J)Q.push("所有任务已完成,可以进入验证和归档阶段。");return Q.join(`
14
- `)}generateProposalTemplate(z,B){return`# ${z}
15
-
16
- ## Summary
17
-
18
- ${B}
19
-
20
- ## Background
21
-
22
- <!-- Why is this change needed? What problem does it solve? -->
23
-
24
- ## Goals
25
-
26
- <!-- What are the specific objectives of this change? -->
27
-
28
- - [ ] Goal 1
29
- - [ ] Goal 2
30
-
31
- ## Non-Goals
32
-
33
- <!-- What is explicitly out of scope? -->
34
-
35
- ## Risks and Mitigations
36
-
37
- <!-- What could go wrong? How will you address it? -->
38
-
39
- | Risk | Mitigation |
40
- |------|------------|
41
- | | |
42
-
43
- ## Open Questions
44
-
45
- <!-- What needs to be clarified before proceeding? -->
46
-
47
- 1.
48
- `}calculateTaskProgress(z){let B=z.length,D=z.filter((K)=>K.status==="completed").length;return{total:B,completed:D}}}
49
- export{X as ia};
@@ -1 +0,0 @@
1
- import{a as y,b as A,c as C,d as D}from"./chunk-6f63v1mk.js";import"./chunk-gxnwrec6.js";import"./chunk-v97f7je6.js";import"./chunk-e21htmg4.js";import"./chunk-pkzy724w.js";import"./chunk-q6c9qs9b.js";import"./chunk-31chcjw6.js";import"./chunk-gscq4fmx.js";import{Ca as q}from"./chunk-mnw1xcwn.js";import"./chunk-m22zeqdy.js";import"./chunk-zd9stbct.js";import"./chunk-f76d6jxg.js";import"./chunk-rzz6r1g9.js";import"./chunk-vzebrztg.js";import"./chunk-wre40mf1.js";import"./chunk-mt1c5da4.js";import"./chunk-0afbeec0.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
@@ -1,6 +0,0 @@
1
- import{B as W,H as L,K as P,L as T,N as R,Q as U,T as M,V as h,W as j}from"./chunk-v97f7je6.js";import"./chunk-e21htmg4.js";import{_ as y}from"./chunk-pkzy724w.js";import"./chunk-q6c9qs9b.js";import"./chunk-31chcjw6.js";import"./chunk-gscq4fmx.js";import{Ba as A}from"./chunk-mnw1xcwn.js";import"./chunk-m22zeqdy.js";import{Za as f}from"./chunk-zd9stbct.js";import"./chunk-f76d6jxg.js";import"./chunk-rzz6r1g9.js";import"./chunk-vzebrztg.js";import{Eb as B}from"./chunk-wre40mf1.js";import{Ob as _}from"./chunk-mt1c5da4.js";import"./chunk-0afbeec0.js";import{Readable as v,Writable as c}from"node:stream";import*as w from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as u}from"@agentclientprotocol/sdk";import{nanoid as C}from"nanoid";import{nanoid as K}from"nanoid";var Y=_("Agent");function N(z){return Object.fromEntries(z.map((G)=>[G.name,G.value]))}function b(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:N(z.env)};return{type:z.type,url:z.url,headers:N(z.headers)}}function k(z){return Object.fromEntries(z.map((G)=>[G.name,b(G)]))}function S(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((G)=>{if(G.type==="text")return G.text?[{type:"text",text:G.text}]:[];let H=G.image_url.url,J=/^data:([^;,]+);base64,(.+)$/s.exec(H);if(!J)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:J[1]??"image/png",data:J[2]??""}]})}class D{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;messages;mode="default";sessionApprovals=new Set;constructor(z,G,H,J,Q={}){this.id=z;this.cwd=G;this.connection=H;this.clientCapabilities=J;this.options=Q;this.messages=[...Q.initialMessages??[]]}async initialize(){Y.debug(`[AcpSession ${this.id}] Initializing...`),W.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),Y.debug(`[AcpSession ${this.id}] ACP service context initialized`);let z=this.options.mcpServers?k(this.options.mcpServers):void 0;this.runtime=await L.create({sessionId:this.id,...z?{mcpServers:z}:{}}),this.agent=await R.createWithRuntime(this.runtime,{sessionId:this.id}),Y.debug(`[AcpSession ${this.id}] Agent created successfully`)}async replayHistory(){for(let z of this.messages){let G=z.role==="user"?"user_message_chunk":z.role==="assistant"?"agent_message_chunk":void 0;if(!G)continue;for(let H of S(z.content))await this.connection.sessionUpdate({sessionId:this.id,update:{sessionUpdate:G,content:H}})}}sendAvailableCommandsDelayed(){Y.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),setTimeout(()=>{this.sendAvailableCommands()},500)}async handleSlashCommand(z,G){try{Y.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,signal:G,acp:{sendMessage:(X)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X}})},sendToolStart:(X,Z,E)=>{let $=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,F=this.mapToolKind(E);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:$,status:"in_progress",title:`${X}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(Z,null,2)}}],kind:F})},sendToolResult:(X,Z)=>{if(Z.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Z.summary}})}}},J=await h(z,H),Q=J.content||J.message;if(Q)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}});if(J.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${J.error}`}});return{stopReason:J.success?"end_turn":"cancelled"}}catch(H){return Y.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=j(),G=["model","permissions","theme","config","exit","ide"],J=z.filter((Q)=>!G.includes(Q.name)).map((Q)=>{let X;if(Q.usage){let Z=Q.usage.replace(/^\/\w+\s*/,"").trim();if(Z)X=Z}if(Q.aliases?.length){let Z=`Aliases: ${Q.aliases.join(", ")}`;X=X?`${X} | ${Z}`:Z}return{name:Q.name,description:Q.description,input:X?{hint:X}:void 0}});Y.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(J.map((Q)=>Q.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:J}),Y.info(`[AcpSession ${this.id}] Sent ${J.length} available commands`)}catch(z){Y.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z){W.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(Y.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),M(H))return await this.handleSlashCommand(H,G.signal);let J={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:G.signal,permissionMode:this.mapModeToPermissionMode(),confirmationHandler:{requestConfirmation:async(Q)=>{return this.requestPermission(Q)}}};if(await f(this.agent.chatStream(H,J),async(Q)=>{switch(Q.kind){case"content_delta":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:Q.delta}});break;case"tool_start":{let X=Q.toolCall,Z="function"in X?X.function.name:X.type,E=this.mapToolKind(Q.toolKind);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X.id,status:"in_progress",title:`Executing ${Z}`,content:[],kind:E});break}case"tool_result":{let{toolCall:X,result:Z}=Q,E=[],$=Z.metadata;if($?.kind==="edit"&&typeof $.file_path==="string"&&typeof $.oldContent==="string"&&(typeof $.newContent==="string"||$.newContent===void 0))E.push({type:"diff",path:$.file_path,oldText:$.oldContent,newText:$.newContent??null});else{let V="function"in X?X.function.name:X.type,x=T(P(V,Z));E.push({type:"content",content:{type:"text",text:x}})}let F=Z.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:X.id,status:F,content:E});break}case"task_update":this.sendPlanUpdate(Q.tasks);break;default:break}}),this.messages=[...J.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 Y.error(`[AcpSession ${this.id}] Prompt error:`,H),H}finally{if(this.pendingPrompt===G)this.pendingPrompt=null}}cancel(){if(Y.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,Y.info(`[AcpSession ${this.id}] Cancelled successfully`);else Y.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",Y.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(Y.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");await this.agent.switchModel(z)}async destroy(){if(this.cancel(),this.agent)await this.agent.destroy(),this.agent=null;if(this.runtime)await this.runtime.dispose(),this.runtime=null;W.destroySession(this.id),Y.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 J=H.resource;if("text"in J)G.push(`<file path="${J.uri}">
2
- ${J.text}
3
- </file>`)}else if(H.type==="resource_link")G.push(`[Resource: ${H.uri}]`);return G.join(`
4
- `)}sendUpdate(z){let G={sessionId:this.id,update:z};this.connection.sessionUpdate(G).catch((H)=>{Y.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}));Y.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 Y.debug(`[AcpSession ${this.id}] Auto-approving ${G} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(G==="write"||G==="execute"))return Y.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 Y.debug(`[AcpSession ${this.id}] Using cached approval for: ${H}`),{approved:!0};try{let J=K(),Q=[];if(z.message)Q.push({type:"content",content:{type:"text",text:z.message}});if(z.risks&&z.risks.length>0)Q.push({type:"content",content:{type:"text",text:`Risks:
5
- - ${z.risks.join(`
6
- - `)}`}});let X=this.mapToolKind(G),Z={sessionId:this.id,options:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:J,status:"pending",title:z.title||"Permission Required",content:Q,kind:X}},$=(await this.connection.requestPermission(Z)).outcome;if($.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let F=$.optionId,V=F==="allow_once"||F==="allow_always";if(F==="allow_always")this.sessionApprovals.add(H),Y.debug(`[AcpSession ${this.id}] Cached approval for: ${H}`);return{approved:V,reason:V?void 0:"User denied the operation"}}catch(J){return Y.warn(`[AcpSession ${this.id}] Permission request failed:`,J),{approved:!1,reason:"Permission request failed"}}}mapToolKind(z){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[z||""]||"other"}}var q=_("Agent");class O{connection;sessions=new Map;clientCapabilities;constructor(z){this.connection=z}async initialize(z){return q.info("[BladeAgent] Initializing ACP connection"),q.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,{protocolVersion:u,agentCapabilities:{loadSession:!0,promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){let G=C();q.info(`[BladeAgent] Creating new session: ${G}`),q.debug(`[BladeAgent] Session cwd: ${z.cwd||B()}`);let H=new D(G,z.cwd||B(),this.connection,this.clientCapabilities,{mcpServers:z.mcpServers});try{await H.initialize()}catch(J){throw await H.destroy().catch(()=>{return}),J}return this.sessions.set(G,H),q.info(`[BladeAgent] Session ${G} created, scheduling available commands update`),H.sendAvailableCommandsDelayed(),{sessionId:G,...this.buildSessionState()}}async loadSession(z){q.info(`[BladeAgent] Loading session: ${z.sessionId}`);let G=await U.loadSession(z.sessionId,z.cwd),H=this.sessions.get(z.sessionId);if(H)await H.destroy(),this.sessions.delete(z.sessionId),G=await U.loadSession(z.sessionId,z.cwd);let J=new D(z.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:G,mcpServers:z.mcpServers});try{await J.initialize(),await J.replayHistory()}catch(Q){throw await J.destroy().catch(()=>{return}),Q}return this.sessions.set(z.sessionId,J),J.sendAvailableCommandsDelayed(),this.buildSessionState()}buildSessionState(){let z=A(),G=z?.models||[],H=z?.currentModelId||G[0]?.id,J=G.map((X)=>({modelId:X.id,name:X.name||X.id,description:X.provider?`Provider: ${X.provider}`:void 0}));return{modes:{availableModes:[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],currentModeId:"default"},models:J.length>0?{availableModels:J,currentModelId:H}:void 0}}async prompt(z){let G=this.sessions.get(z.sessionId);if(!G)throw Error(`Session not found: ${z.sessionId}`);return G.prompt(z)}async cancel(z){q.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let G=this.sessions.get(z.sessionId);if(G)q.info("[BladeAgent] Found session, calling session.cancel()"),G.cancel();else q.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){q.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let G=this.sessions.get(z.sessionId);if(G)await G.setMode(z.modeId);return{}}async unstable_setSessionModel(z){q.info(`[BladeAgent] Setting session model: ${z.modelId}`);let G=this.sessions.get(z.sessionId);if(!G)throw Error(`Session not found: ${z.sessionId}`);return await G.setModel(z.modelId),{}}async destroy(){for(let z of this.sessions.values())await z.destroy();this.sessions.clear(),await y.getInstance().disconnectAll()}}async function qz(){let z=c.toWeb(process.stdout),G=v.toWeb(process.stdin),H=w.ndJsonStream(z,G);await new w.AgentSideConnection((Q)=>new O(Q),H).closed}export{qz as runAcpIntegration};
@@ -1,76 +0,0 @@
1
- import{Ka as q0,Ma as A}from"./chunk-m22zeqdy.js";import{Ob as K0}from"./chunk-mt1c5da4.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":{input:0.27,output:1.1},"deepseek-v4-pro":{input:0.27,output:1.1},"deepseek-v4-0724":{input:0.27,output:1.1},"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:0.15,output:0.6},"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:0.4,output:1.6},"gpt-4.1-nano":{input:0.1,output:0.4},"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},"o4-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},"claude-opus-4":{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},"qwen3-235b":{input:2,output:8},"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:0.15,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 ja,X0 as ka,K as la,G1 as ma,H1 as na,z1 as oa,W1 as pa,F1 as qa,K1 as ra,q1 as sa,T as ta,A1 as ua,N as va,a0 as wa,q as xa,t1 as ya,e1 as za,Q5 as Aa,y as Ba,X5 as Ca,Z5 as Da,$5 as Ea,Y5 as Fa,V5 as Ga,J5 as Ha,G5 as Ia};
@@ -1 +0,0 @@
1
- import{t as a,u as b}from"./chunk-96w1szbp.js";import"./chunk-31chcjw6.js";import"./chunk-0afbeec0.js";export{a as globalOptions,b as cliConfig};
@@ -1 +0,0 @@
1
- import{g as a,h as b,i as c,j as d,k as e}from"./chunk-c2b6ekqx.js";import"./chunk-0afbeec0.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};