blade-code 0.7.6 → 0.7.8

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 (81) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-npaj13y3.js → chunk-0e0z8yc1.js} +2 -2
  3. package/dist/{chunk-fceeqn6k.js → chunk-1w6tqkxd.js} +2 -2
  4. package/dist/{chunk-ttf06k8y.js → chunk-2049tv49.js} +3 -3
  5. package/dist/chunk-4745ktjj.js +1570 -0
  6. package/dist/chunk-48q9msfk.js +615 -0
  7. package/dist/chunk-4dmdn3a9.js +2 -0
  8. package/dist/{chunk-zr71r1z1.js → chunk-5be6qr2v.js} +1 -1
  9. package/dist/chunk-67vzgcs5.js +2 -0
  10. package/dist/{chunk-krrm6bjr.js → chunk-6811kbxn.js} +1 -1
  11. package/dist/{chunk-d9qh7bat.js → chunk-6hn2jgw5.js} +1 -1
  12. package/dist/chunk-6js5wp6t.js +1 -0
  13. package/dist/chunk-6kp3z956.js +9 -0
  14. package/dist/{chunk-pf45ctn7.js → chunk-71n472hj.js} +1 -1
  15. package/dist/chunk-78txnq4n.js +151 -0
  16. package/dist/chunk-7r1hm0qz.js +6 -0
  17. package/dist/{chunk-1y33d6xh.js → chunk-9kejtkey.js} +1 -1
  18. package/dist/chunk-a7yjnqhd.js +3 -0
  19. package/dist/chunk-bwaqaktn.js +1 -0
  20. package/dist/chunk-cb82rf5h.js +1 -0
  21. package/dist/chunk-ce11m8bq.js +1 -0
  22. package/dist/{chunk-m3hsaaq5.js → chunk-cjmxggke.js} +1 -1
  23. package/dist/chunk-e4rhdg3h.js +1 -0
  24. package/dist/{chunk-64x50qbc.js → chunk-f9ybv4ph.js} +1 -1
  25. package/dist/{chunk-x4fx52e7.js → chunk-faq7ay4j.js} +3 -3
  26. package/dist/{chunk-jhzf05kz.js → chunk-fb7amc2s.js} +1 -1
  27. package/dist/chunk-g6ted982.js +4 -0
  28. package/dist/{chunk-qyfdt8h1.js → chunk-g7caymjr.js} +1 -1
  29. package/dist/{chunk-ezkbqmvd.js → chunk-jm2xhnrv.js} +1 -1
  30. package/dist/chunk-ky8ctbdc.js +1 -0
  31. package/dist/chunk-mpskff34.js +1 -0
  32. package/dist/chunk-pd1yqxcv.js +9 -0
  33. package/dist/{chunk-arwynrtf.js → chunk-phhmmybg.js} +2 -2
  34. package/dist/chunk-qnevwq1q.js +2 -0
  35. package/dist/{chunk-ebynn53v.js → chunk-r1spf93b.js} +2 -2
  36. package/dist/{chunk-r0hc7wad.js → chunk-rnfd5ebv.js} +1 -1
  37. package/dist/{chunk-wg5nxtb2.js → chunk-s4mke0t6.js} +1 -1
  38. package/dist/{chunk-wstkn75a.js → chunk-t2spryz0.js} +1 -1
  39. package/dist/{chunk-rhvxr82g.js → chunk-t70aqrm4.js} +1 -1
  40. package/dist/{chunk-10q3krvh.js → chunk-z4c68ve0.js} +1 -1
  41. package/dist/chunk-z9zbcenc.js +6 -0
  42. package/dist/web/assets/{CodeBlockHighlighter-C86flFwh.js → CodeBlockHighlighter-C1cp8dDv.js} +1 -1
  43. package/dist/web/assets/FilePreview-DRKRs8i2.js +7 -0
  44. package/dist/web/assets/{MarkdownRenderer-CW8WpEw1.js → MarkdownRenderer-DFqPpAnM.js} +1 -1
  45. package/dist/web/assets/{McpModal-DnqrgBON.js → McpModal-CX5-hlNv.js} +1 -1
  46. package/dist/web/assets/{SettingsModal-CRNT-LCq.js → SettingsModal-CfR_q6N7.js} +1 -1
  47. package/dist/web/assets/{SettingsStore-B2GIhfKs.js → SettingsStore-jup_Kikq.js} +1 -1
  48. package/dist/web/assets/{SkillsModal-COQMbIdT.js → SkillsModal-DaAUrwXO.js} +1 -1
  49. package/dist/web/assets/{TerminalPanel-dCMUvQaH.js → TerminalPanel-DzlllDH7.js} +1 -1
  50. package/dist/web/assets/index-BJTSF3fc.js +9 -0
  51. package/dist/web/assets/index-CL6apjgo.css +1 -0
  52. package/dist/web/assets/{useRequest-C7k7cDPD.js → useRequest-DITGl55G.js} +1 -1
  53. package/dist/web/assets/{vendor-icons-BKXQ7ALf.js → vendor-icons-BuFpOlRn.js} +38 -28
  54. package/dist/web/assets/{vendor-markdown-DIcugY1e.js → vendor-markdown-Bo4W9Tae.js} +1 -1
  55. package/dist/web/assets/vendor-radix-CESj0OOY.js +45 -0
  56. package/dist/web/assets/{vendor-react-Dm1xU4bP.js → vendor-react-BalntB5F.js} +2 -2
  57. package/dist/web/index.html +2 -2
  58. package/package.json +1 -1
  59. package/dist/chunk-1tzcptyb.js +0 -3
  60. package/dist/chunk-5accz8n9.js +0 -1
  61. package/dist/chunk-8raa4q9y.js +0 -1564
  62. package/dist/chunk-ad19yrq6.js +0 -1
  63. package/dist/chunk-bvn4e2vq.js +0 -1
  64. package/dist/chunk-cadngkwr.js +0 -2
  65. package/dist/chunk-cdx3hp1r.js +0 -9
  66. package/dist/chunk-g60w2r7f.js +0 -6
  67. package/dist/chunk-h7qab07x.js +0 -2
  68. package/dist/chunk-k76q8cyc.js +0 -151
  69. package/dist/chunk-n2yq1wn8.js +0 -9
  70. package/dist/chunk-q6sj33v8.js +0 -6
  71. package/dist/chunk-qedtzcp2.js +0 -1
  72. package/dist/chunk-t6qek6xk.js +0 -1
  73. package/dist/chunk-tyjns370.js +0 -1
  74. package/dist/chunk-ve6bvba4.js +0 -615
  75. package/dist/chunk-wdxbjvd5.js +0 -2
  76. package/dist/chunk-xj63cr29.js +0 -1
  77. package/dist/chunk-zmndvdgb.js +0 -4
  78. package/dist/web/assets/FilePreview-CbtOITD1.js +0 -7
  79. package/dist/web/assets/index-21gV5nOE.css +0 -1
  80. package/dist/web/assets/index-Cnz-_jPt.js +0 -10
  81. package/dist/web/assets/vendor-radix-2yBsoRqx.js +0 -45
@@ -1,9 +0,0 @@
1
- import{B as f,I as R,L as y,M as K,O as h,R as N,U as q,W as k,X as A}from"./chunk-8raa4q9y.js";import"./chunk-qyfdt8h1.js";import{$ as S}from"./chunk-fceeqn6k.js";import"./chunk-npaj13y3.js";import{sa as b}from"./chunk-x4fx52e7.js";import"./chunk-ebynn53v.js";import"./chunk-arwynrtf.js";import{Wa as O}from"./chunk-ve6bvba4.js";import{mb as E}from"./chunk-ezkbqmvd.js";import"./chunk-ttf06k8y.js";import{qb as x}from"./chunk-rhvxr82g.js";import{wb as L}from"./chunk-cadngkwr.js";import"./chunk-cdx3hp1r.js";import{Qb as w}from"./chunk-1tzcptyb.js";import"./chunk-64x50qbc.js";import{Readable as p,Writable as g}from"node:stream";import*as B from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as c}from"@agentclientprotocol/sdk";import{nanoid as j}from"nanoid";var $=w("Agent");function M(z){return Object.fromEntries(z.map((H)=>[H.name,H.value]))}function u(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:M(z.env)};return{type:z.type,url:z.url,headers:M(z.headers)}}function v(z){return Object.fromEntries(z.map((H)=>[H.name,u(H)]))}function T(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((H)=>{if(H.type==="text")return H.text?[{type:"text",text:H.text}]:[];let J=H.image_url.url,Q=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Q)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Q[1]??"image/png",data:Q[2]??""}]})}class _{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingResumeRequested=!1;messages;mode="default";constructor(z,H,J,Q,Y={}){this.id=z;this.cwd=H;this.connection=J;this.clientCapabilities=Q;this.options=Y;this.messages=[...Y.initialMessages??[]]}async initialize(){$.debug(`[AcpSession ${this.id}] Initializing...`),f.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),$.debug(`[AcpSession ${this.id}] ACP service context initialized`);let z=this.options.mcpServers?v(this.options.mcpServers):void 0;this.runtime=await R.create({sessionId:this.id,workspaceRoot:this.cwd,...z?{mcpServers:z}:{}}),this.agent=await h.createWithRuntime(this.runtime,{sessionId:this.id}),$.debug(`[AcpSession ${this.id}] Agent created successfully`);let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let z of this.messages){let H=z.role==="user"?"user_message_chunk":z.role==="assistant"?"agent_message_chunk":void 0;if(!H)continue;for(let J of T(z.content))await this.connection.sessionUpdate({sessionId:this.id,update:{sessionUpdate:H,content:J}})}if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){$.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),setTimeout(()=>{this.sendAvailableCommands()},500)}async handleSlashCommand(z,H){try{$.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let J={cwd:this.cwd,workspaceRoot:this.cwd,sessionId:this.id,signal:H,acp:{sendMessage:(Z)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Z}})},sendToolStart:(Z,V,F)=>{let W=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,G=this.mapToolKind(F);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:W,status:"in_progress",title:`${Z}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(V,null,2)}}],kind:G})},sendToolResult:(Z,V)=>{if(V.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:V.summary}})}}},Q=await k(z,J),Y=Q.data?.action;if(Y==="start_goal"||Y==="resume_goal")this.schedulePendingResume();let X=Q.content||Q.message;if(X)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X}});if(Q.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Q.error}`}});return{stopReason:Q.success?"end_turn":"cancelled"}}catch(J){return $.error(`[AcpSession ${this.id}] Slash command error:`,J),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let z=A(),H=["model","permissions","theme","config","exit","ide"],Q=z.filter((Y)=>!H.includes(Y.name)).map((Y)=>{let X;if(Y.usage){let Z=Y.usage.replace(/^\/\w+\s*/,"").trim();if(Z)X=Z}if(Y.aliases?.length){let Z=`Aliases: ${Y.aliases.join(", ")}`;X=X?`${X} | ${Z}`:Z}return{name:Y.name,description:Y.description,input:X?{hint:X}:void 0}});$.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Q.map((Y)=>Y.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Q}),$.info(`[AcpSession ${this.id}] Sent ${Q.length} available commands`)}catch(z){$.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,H={}){if(f.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let J=this.resolvePrompt(z.prompt);if(this.pendingPrompt){if(/^\/goal(?:\s|$)/i.test(J.trim()))return this.handleSlashCommand(J,this.pendingPrompt.signal);let Y=await this.runtime.enqueueSteering(J,{allowBeforeTurn:!0});if(!Y.accepted)throw Error(Y.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if($.debug(`[AcpSession ${this.id}] Queued steering for active turn (${Y.queued})`),Y.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let Q=new AbortController;this.pendingPrompt=Q;try{if($.debug(`[AcpSession ${this.id}] Received prompt: ${J.slice(0,100)}...`),q(J))return await this.handleSlashCommand(J,Q.signal);let Y={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:Q.signal,permissionMode:this.mapModeToPermissionMode(),confirmationHandler:{requestConfirmation:async(X)=>{return this.requestPermission(X)}}};if(await O(this.agent.chatStream(J,Y,{pendingInputOnly:H.pendingInputOnly,goalContinuationOnly:H.goalContinuationOnly}),async(X)=>{switch(X.kind){case"content_delta":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:X.delta}});break;case"tool_start":{let Z=X.toolCall,V="function"in Z?Z.function.name:Z.type,F=this.mapToolKind(X.toolKind);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z.id,status:"in_progress",title:`Executing ${V}`,content:[],kind:F});break}case"tool_result":{let{toolCall:Z,result:V}=X,F=[],W=V.metadata;if(W?.kind==="edit"&&typeof W.file_path==="string"&&typeof W.oldContent==="string"&&(typeof W.newContent==="string"||W.newContent===void 0))F.push({type:"diff",path:W.file_path,oldText:W.oldContent,newText:W.newContent??null});else{let D="function"in Z?Z.function.name:Z.type,I=K(y(D,V));F.push({type:"content",content:{type:"text",text:I}})}let G=V.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Z.id,status:G,content:F});break}case"task_update":this.sendPlanUpdate(X.tasks);break;case"steering_applied":break;case"follow_up_started":for(let Z of X.messages){if(!Z.recovered||Z.persisted)continue;for(let V of T(Z.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:V})}if(X.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${X.recovered} queued instruction${X.recovered===1?"":"s"} recovered after restart]
2
- `}});break;case"goal_updated":if(X.goal&&X.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${X.goal.status}: ${X.goal.objective}]
3
- `}});break;case"goal_continuation_started":break;default:break}}),this.messages=[...Y.messages],Q.signal.aborted)return{stopReason:"cancelled"};return{stopReason:"end_turn"}}catch(Y){if(Q.signal.aborted||Y instanceof Error&&Y.name==="AbortError")return{stopReason:"cancelled"};throw $.error(`[AcpSession ${this.id}] Prompt error:`,Y),Y}finally{if(this.pendingPrompt===Q){if(this.pendingPrompt=null,this.pendingResumeRequested)this.schedulePendingResume()}}}schedulePendingResume(){this.pendingResumeRequested=!0,queueMicrotask(()=>{this.resumePendingIfIdle()})}async resumePendingIfIdle(){if(this.pendingPrompt||!this.runtime||!this.agent)return;let z=this.runtime.getPendingSteeringCount()>0,J=(z?null:await this.runtime.getGoal())?.status==="active";if(!z&&!J){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:z,goalContinuationOnly:J}).catch((Q)=>{$.error(`[AcpSession ${this.id}] Failed to resume pending input:`,Q)})}cancel(){if($.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1,this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,$.info(`[AcpSession ${this.id}] Cancelled successfully`);else $.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let H=["default","auto-edit","yolo","plan"];this.mode=H.includes(z)?z:"default",$.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($.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;f.destroySession(this.id),$.debug(`[AcpSession ${this.id}] Destroyed`)}resolvePrompt(z){let H=[];for(let J of z)if(J.type==="text")H.push(J.text);else if(J.type==="image")H.push(`[Image: ${J.mimeType}]`);else if(J.type==="resource"){let Q=J.resource;if("text"in Q)H.push(`<file path="${Q.uri}">
4
- ${Q.text}
5
- </file>`)}else if(J.type==="resource_link")H.push(`[Resource: ${J.uri}]`);return H.join(`
6
- `)}sendUpdate(z){let H={sessionId:this.id,update:z};this.connection.sessionUpdate(H).catch((J)=>{$.warn(`[AcpSession ${this.id}] Failed to send update:`,J)})}sendPlanUpdate(z){let H=z.map((J)=>({content:J.subject,priority:J.priority,status:J.status}));$.debug(`[AcpSession ${this.id}] Sending plan update with ${H.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:H})}async requestPermission(z){let H=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,H);let J=z.kind?.toLowerCase()||"execute";if(this.shouldAutoApprove(J))return $.debug(`[AcpSession ${this.id}] Auto-approving ${J} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(J==="write"||J==="execute"))return $.debug(`[AcpSession ${this.id}] Rejecting ${J} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Q=j(),Y=[];if(z.message)Y.push({type:"content",content:{type:"text",text:z.message}});if(z.risks&&z.risks.length>0)Y.push({type:"content",content:{type:"text",text:`Risks:
7
- - ${z.risks.join(`
8
- - `)}`}});let X=this.mapToolKind(J),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:Q,status:"pending",title:z.title||"Permission Required",content:Y,kind:X}},V=await this.waitForClientInteraction(this.connection.requestPermission(Z),H);if(!V)return{approved:!1,reason:E};let F=V.outcome;if(F.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let W=F.optionId;if(W==="allow_always")return{approved:!0,scope:"project"};if(W==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let G=W==="allow_once";return{approved:G,scope:"once",reason:G?void 0:"User denied the operation"}}catch(Q){return $.warn(`[AcpSession ${this.id}] Permission request failed:`,Q),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,H){let J=z.questions??[];if(J.length===0)return{approved:!1,reason:"No structured questions were provided"};if(J.some((Y)=>Y.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Q={};try{for(let[Y,X]of J.entries()){let Z=X.options.map((G,D)=>`answer:${Y}:${D}`),V=`answer:${Y}:cancel`,F=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...X.options.map((G,D)=>({optionId:Z[D],name:G.label,kind:"allow_once"})),{optionId:V,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:j(),status:"pending",title:X.header,kind:"think",content:[{type:"content",content:{type:"text",text:[X.question,...X.options.map((G)=>`${G.label}: ${G.description}`)].join(`
9
- `)}}]}}),H);if(!F)return{approved:!1,reason:E};if(F.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let W=Z.indexOf(F.outcome.optionId);if(W<0)return{approved:!1,reason:"User cancelled the question prompt"};Q[X.header]=X.options[W].label}return{approved:!0,answers:Q}}catch(Y){return $.warn(`[AcpSession ${this.id}] Question request failed:`,Y),{approved:!1,reason:"Question request failed"}}}async waitForClientInteraction(z,H){if(!H)return z;if(H.aborted)return;return new Promise((J,Q)=>{let Y=!1,X=(V)=>{if(Y)return;Y=!0,H.removeEventListener("abort",Z),V()},Z=()=>X(()=>J(void 0));if(H.addEventListener("abort",Z,{once:!0}),H.aborted)Z();z.then((V)=>X(()=>J(V)),(V)=>X(()=>Q(V)))})}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 U=w("Agent");class P{connection;sessions=new Map;clientCapabilities;constructor(z){this.connection=z}async initialize(z){return U.info("[BladeAgent] Initializing ACP connection"),U.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,{protocolVersion:c,agentCapabilities:{loadSession:!0,promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){let H=x("acp");U.info(`[BladeAgent] Creating new session: ${H}`),U.debug(`[BladeAgent] Session cwd: ${z.cwd||L()}`);let J=new _(H,z.cwd||L(),this.connection,this.clientCapabilities,{mcpServers:z.mcpServers});try{await J.initialize()}catch(Q){throw await J.destroy().catch(()=>{return}),Q}return this.sessions.set(H,J),U.info(`[BladeAgent] Session ${H} created, scheduling available commands update`),J.sendAvailableCommandsDelayed(),{sessionId:H,...this.buildSessionState()}}async loadSession(z){U.info(`[BladeAgent] Loading session: ${z.sessionId}`);let H=await N.loadSession(z.sessionId,z.cwd),J=this.sessions.get(z.sessionId);if(J)await J.destroy(),this.sessions.delete(z.sessionId),H=await N.loadSession(z.sessionId,z.cwd);let Q=new _(z.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:H,mcpServers:z.mcpServers});try{await Q.initialize(),await Q.replayHistory()}catch(Y){throw await Q.destroy().catch(()=>{return}),Y}return this.sessions.set(z.sessionId,Q),Q.sendAvailableCommandsDelayed(),this.buildSessionState()}buildSessionState(){let z=b(),H=z?.models||[],J=z?.currentModelId||H[0]?.id,Q=H.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:Q.length>0?{availableModels:Q,currentModelId:J}:void 0}}async prompt(z){let H=this.sessions.get(z.sessionId);if(!H)throw Error(`Session not found: ${z.sessionId}`);return H.prompt(z)}async cancel(z){U.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let H=this.sessions.get(z.sessionId);if(H)U.info("[BladeAgent] Found session, calling session.cancel()"),H.cancel();else U.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){U.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let H=this.sessions.get(z.sessionId);if(H)await H.setMode(z.modeId);return{}}async unstable_setSessionModel(z){U.info(`[BladeAgent] Setting session model: ${z.modelId}`);let H=this.sessions.get(z.sessionId);if(!H)throw Error(`Session not found: ${z.sessionId}`);return await H.setModel(z.modelId),{}}async destroy(){for(let z of this.sessions.values())await z.destroy();this.sessions.clear(),await S.getInstance().disconnectAll()}}async function Uz(){let z=g.toWeb(process.stdout),H=p.toWeb(process.stdin),J=B.ndJsonStream(z,H);await new B.AgentSideConnection((Y)=>new P(Y),J).closed}export{Uz as runAcpIntegration};
@@ -1,6 +0,0 @@
1
- import{y as w}from"./chunk-h7qab07x.js";import{oa as y}from"./chunk-x4fx52e7.js";import{Aa as u,Ba as b}from"./chunk-ebynn53v.js";import{sb as r,vb as m}from"./chunk-cadngkwr.js";import{Qb as f}from"./chunk-1tzcptyb.js";import{promises as S}from"node:fs";import h from"node:path";import{z as o}from"zod";var P=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],M=new Set([...Object.keys(u),...P]),T=o.object({currentModelId:o.string().optional(),models:o.array(o.object({id:o.string().min(1),name:o.string().min(1),provider:o.string().min(1),apiKey:o.string(),baseUrl:o.string(),model:o.string().min(1),temperature:o.number().optional(),maxContextTokens:o.number().positive().optional(),maxOutputTokens:o.number().positive().optional(),topP:o.number().optional(),topK:o.number().optional(),supportsThinking:o.boolean().optional(),thinkingBudget:o.number().positive().optional(),thinkingMode:o.enum(["off","budget","adaptive"]).optional(),apiVersion:o.string().optional(),projectId:o.string().optional(),fallbackModels:o.array(o.string()).optional(),enablePromptCaching:o.boolean().optional(),customHeaders:o.record(o.string()).optional(),timeout:o.number().positive().optional(),maxRetries:o.number().int().min(0).optional()})).optional(),temperature:o.number().optional(),maxContextTokens:o.number().positive().optional(),maxOutputTokens:o.number().positive().optional(),stream:o.boolean().optional(),topP:o.number().optional(),topK:o.number().optional(),timeout:o.number().positive().optional(),theme:o.string().optional(),uiTheme:o.enum(["light","dark","system"]).optional(),language:o.string().optional(),fontSize:o.number().positive().optional(),autoSaveSessions:o.boolean().optional(),notifyBuild:o.boolean().optional(),notifyErrors:o.boolean().optional(),notifySounds:o.boolean().optional(),privacyTelemetry:o.boolean().optional(),privacyCrash:o.boolean().optional(),debug:o.union([o.boolean(),o.string()]).optional(),mcpEnabled:o.boolean().optional(),mcpServers:o.record(o.record(o.unknown())).optional(),permissionMode:o.nativeEnum(m).optional(),maxTurns:o.number().int().min(-1).optional(),systemPrompt:o.string().optional(),appendSystemPrompt:o.string().optional(),initialMessage:o.string().optional(),resumeSessionId:o.string().optional(),forkSession:o.boolean().optional(),allowedTools:o.array(o.string().min(1)).optional(),disallowedTools:o.array(o.string().min(1)).optional(),mcpConfigPaths:o.array(o.string().min(1)).optional(),strictMcpConfig:o.boolean().optional(),model:o.string().min(1).optional(),addDirs:o.array(o.string().min(1)).optional(),outputFormat:o.enum(["text","json","stream-json","jsonl"]).optional(),inputFormat:o.enum(["text","stream-json"]).optional(),print:o.boolean().optional(),includePartialMessages:o.boolean().optional(),replayUserMessages:o.boolean().optional(),agentsConfig:o.string().optional(),settingSources:o.string().optional(),permissions:o.object({allow:o.array(o.string()).optional(),ask:o.array(o.string()).optional(),deny:o.array(o.string()).optional()}).optional(),env:o.record(o.string()).optional(),hooks:o.record(o.unknown()).optional(),disableAllHooks:o.boolean().optional()}).passthrough(),k=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"]];function a(n,i){let t;try{t=JSON.parse(n)}catch(e){let l=e instanceof Error?`: ${e.message}`:"";throw Error(`Invalid JSON provided to --settings (${i})${l}`)}if(!t||typeof t!=="object"||Array.isArray(t))throw Error("--settings must contain a JSON object");for(let e of Object.keys(t))if(!M.has(e))throw Error(`Unknown --settings field: ${e}`);let s=T.safeParse(t);if(!s.success){let e=s.error.issues.map((l)=>`${l.path.join(".")||"settings"}: ${l.message}`).join("; ");throw Error(`Invalid --settings value: ${e}`)}return s.data}async function d(n){if(n===void 0)return;let i=n.trim();if(!i)throw Error("--settings requires a JSON object or file path");if(i.startsWith("{"))return a(i,"inline JSON");let t=h.resolve(r(),i),s;try{s=await S.readFile(t,"utf8")}catch(e){let l=e instanceof Error?`: ${e.message}`:"";throw Error(`Unable to read --settings file ${t}${l}`)}return a(s,t)}function c(n,i){if(!i)return;let t=i;for(let[s,e]of k){if(s==="permissionMode"&&n.yolo===!0)continue;if(n[e]===void 0&&t[s]!==void 0)n[e]=t[s]}}var p=f("General"),A=(n)=>{if(n.yolo){if(n.permissionMode&&n.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");n.permissionMode="yolo"}if(Array.isArray(n.allowedTools))n.allowedTools=n.allowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(n.disallowedTools))n.disallowedTools=n.disallowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(n.allowedTools)&&Array.isArray(n.disallowedTools)){let i=n.allowedTools.filter((t)=>n.disallowedTools.includes(t));if(i.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${i.join(", ")}`)}},G=async(n)=>{let i=await d(typeof n.settings==="string"?n.settings:void 0);if(c(n,i),typeof n.agents==="string")w(n.agents);C(n);try{let s=await b.getInstance().initialize(i);if(y().config.actions.setConfig(s),n.debug)p.info("[CLI] 配置已加载到 Store")}catch(t){p.error("[CLI] [FAIL] 配置初始化失败",t instanceof Error?t.message:t),console.error(`
2
- [FAIL] 配置初始化失败
3
- `),console.error("原因:",t instanceof Error?t.message:"未知错误"),console.error(`
4
- 请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
5
- `),process.exit(1)}};function C(n){if(n.continue&&n.resume)throw Error("Cannot use both --continue and --resume flags simultaneously");if(n.forkSession&&!n.continue&&!n.resume)throw Error("--fork-session requires --resume or --continue");if(n.sessionId&&(n.continue||n.resume)&&!n.forkSession)throw Error("--session-id can only be combined with --resume or --continue when --fork-session is set")}var K=(n)=>{if(n.outputFormat&&n.outputFormat!=="text"&&!n.print&&!n.headless)throw Error("--output-format can only be used with --print or --headless");if(n.headless&&n.outputFormat&&!["text","jsonl"].includes(n.outputFormat))throw Error(`--headless only supports --output-format text|jsonl, but got "${n.outputFormat}". Use --print for json|stream-json support.`);if(n.print&&n.outputFormat&&!["text","json","stream-json"].includes(n.outputFormat))throw Error(`--print only supports --output-format text|json|stream-json, but got "${n.outputFormat}". Use --headless for jsonl support.`);if(n.inputFormat==="stream-json"&&n.print)p.warn("[WARN] Warning: stream-json input format may not work as expected with --print")};
6
- export{A as v,G as w,K as x};
@@ -1 +0,0 @@
1
- import{a,b,c,d,e}from"./chunk-m3hsaaq5.js";import"./chunk-64x50qbc.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1 +0,0 @@
1
- import{t as a,u as b}from"./chunk-wg5nxtb2.js";import"./chunk-arwynrtf.js";import"./chunk-64x50qbc.js";export{a as globalOptions,b as cliConfig};
@@ -1 +0,0 @@
1
- import{Ea as a,Fa as b,Ga as c,Ha as d,Ia as e,Ja as f}from"./chunk-arwynrtf.js";import"./chunk-64x50qbc.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};