blade-code 0.8.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/{chunk-jakzknh3.js → chunk-04920kz2.js} +268 -268
- package/dist/chunk-42ch5zg4.js +1 -0
- package/dist/{chunk-ydb9myhe.js → chunk-61952mn3.js} +1 -1
- package/dist/{chunk-nned222j.js → chunk-6yqzfz8t.js} +1 -1
- package/dist/chunk-7j6rxyt8.js +9 -0
- package/dist/{chunk-d08wbxjr.js → chunk-cnftrx3g.js} +1 -1
- package/dist/{chunk-gytwh5y1.js → chunk-epp5jx5f.js} +1 -1
- package/dist/{chunk-hrnd3wjg.js → chunk-j6hpzkpq.js} +1 -1
- package/dist/{chunk-e4a240t7.js → chunk-k47ssv3b.js} +1 -1
- package/dist/chunk-n4f8tseg.js +2 -0
- package/dist/{chunk-bggvft3z.js → chunk-nc4kfwef.js} +1 -1
- package/dist/{chunk-ychj0e5q.js → chunk-neenhtxw.js} +1 -1
- package/dist/{chunk-6es6av6j.js → chunk-pdydx73a.js} +1 -1
- package/dist/{chunk-yqxw7zz4.js → chunk-sr3bzb95.js} +1 -1
- package/dist/{chunk-jqr2pknb.js → chunk-x6gt63vz.js} +15 -15
- package/dist/web/assets/{CodeBlockHighlighter-C1cp8dDv.js → CodeBlockHighlighter-D8_cOYpG.js} +1 -1
- package/dist/web/assets/{FilePreview-DvgnEspB.js → FilePreview-Chqi7chf.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-e1ZUy6jV.js → MarkdownRenderer-JJScfgAO.js} +1 -1
- package/dist/web/assets/{McpModal-Raois2g1.js → McpModal-CiCuIUxC.js} +2 -2
- package/dist/web/assets/{SettingsModal-Dzuatoea.js → SettingsModal-Bew818xl.js} +1 -1
- package/dist/web/assets/{SettingsStore-BxDA0Usw.js → SettingsStore-B_4zN-c-.js} +1 -1
- package/dist/web/assets/{SkillsModal-Cg2-befH.js → SkillsModal-Cot4Rb89.js} +1 -1
- package/dist/web/assets/{TerminalPanel-CEoQI9Lu.js → TerminalPanel-DxB67ObY.js} +1 -1
- package/dist/web/assets/index-B-b3Yc5H.css +1 -0
- package/dist/web/assets/index-B3dW1Scg.js +16 -0
- package/dist/web/assets/{useRequest-DITGl55G.js → useRequest-B4kP-cmG.js} +1 -1
- package/dist/web/assets/{vendor-icons-BuFpOlRn.js → vendor-icons-DqO8ishN.js} +2 -2
- package/dist/web/assets/{vendor-markdown-Bo4W9Tae.js → vendor-markdown-b9iCqZWK.js} +1 -1
- package/dist/web/assets/vendor-radix-DyP_DOwV.js +45 -0
- package/dist/web/assets/{vendor-react-BalntB5F.js → vendor-react-FPIC4Czm.js} +2 -2
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-3gw66r7a.js +0 -2
- package/dist/chunk-bxbagv76.js +0 -9
- package/dist/chunk-n8ymp6nd.js +0 -1
- package/dist/web/assets/index-BvGeIa_-.js +0 -16
- package/dist/web/assets/index-DDJnZJcp.css +0 -1
- package/dist/web/assets/vendor-radix-CESj0OOY.js +0 -45
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as a,u as b}from"./chunk-6yqzfz8t.js";import"./chunk-pdydx73a.js";import"./chunk-dr06x0cw.js";export{a as globalOptions,b as cliConfig};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Q,b as R,c as T,d as W}from"./chunk-
|
|
1
|
+
import{a as Q,b as R,c as T,d as W}from"./chunk-n4f8tseg.js";import"./chunk-xhnyy54e.js";import"./chunk-04920kz2.js";import"./chunk-9ad7tt9s.js";import"./chunk-k47ssv3b.js";import"./chunk-bm8vwfez.js";import{wa as J}from"./chunk-tv4r86ez.js";import"./chunk-qwdbqjh7.js";import"./chunk-d4ex0qvs.js";import{Ka as M}from"./chunk-pdydx73a.js";import"./chunk-1pt090dg.js";import"./chunk-9xkjb87h.js";import"./chunk-49g067ek.js";import"./chunk-ctqf59q1.js";import"./chunk-jt62ctz7.js";import"./chunk-gsfkrr25.js";import"./chunk-0dj326ms.js";import"./chunk-34pdtz4q.js";import"./chunk-hjx5n3dw.js";import"./chunk-dr06x0cw.js";import b from"chalk";import H from"open";var $=`
|
|
2
2
|
____ _ _
|
|
3
3
|
| __ )| | __ _ __| | ___
|
|
4
4
|
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Ka as d,Ma as h}from"./chunk-
|
|
1
|
+
import{Ka as d,Ma as h}from"./chunk-pdydx73a.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
|
|
2
2
|
export{q as t,w as u};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{B as L,J as T,L as P,N as h,P as q,Q as A,S as N,X as b,Z as x,_ as k}from"./chunk-04920kz2.js";import"./chunk-9ad7tt9s.js";import{ca as v}from"./chunk-k47ssv3b.js";import"./chunk-bm8vwfez.js";import{va as C}from"./chunk-tv4r86ez.js";import"./chunk-qwdbqjh7.js";import{Ia as u}from"./chunk-d4ex0qvs.js";import"./chunk-pdydx73a.js";import{ab as K}from"./chunk-1pt090dg.js";import{sb as E}from"./chunk-9xkjb87h.js";import"./chunk-49g067ek.js";import"./chunk-ctqf59q1.js";import{Cb as I}from"./chunk-jt62ctz7.js";import{Ib as M}from"./chunk-gsfkrr25.js";import"./chunk-0dj326ms.js";import{Tb as B}from"./chunk-34pdtz4q.js";import"./chunk-hjx5n3dw.js";import"./chunk-dr06x0cw.js";import{Readable as m,Writable as l}from"node:stream";import*as j from"@agentclientprotocol/sdk";import S from"node:path";import{PROTOCOL_VERSION as p}from"@agentclientprotocol/sdk";import{nanoid as O}from"nanoid";var V=B("Agent");function f(z){return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function g(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:f(z.env)};return{type:z.type,url:z.url,headers:f(z.headers)}}function d(z){return Object.fromEntries(z.map((J)=>[J.name,g(J)]))}function y(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let H=J.image_url.url,Q=/^data:([^;,]+);base64,(.+)$/s.exec(H);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;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;messages;mode="default";constructor(z,J,H,Q,X={}){this.id=z;this.cwd=J;this.connection=H;this.clientCapabilities=Q;this.options=X;this.messages=[...X.initialMessages??[]]}async initialize(){V.debug(`[AcpSession ${this.id}] Initializing...`),L.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),V.debug(`[AcpSession ${this.id}] ACP service context initialized`);let z=this.options.mcpServers?d(this.options.mcpServers):void 0;this.runtime=await h.create({sessionId:this.id,workspaceRoot:this.cwd,...z?{mcpServers:z}:{}}),this.agent=await N.createWithRuntime(this.runtime,{sessionId:this.id}),V.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=T.subscribe((H)=>{if(H.type!=="task.status"||H.sessionId!==this.id||H.projectPath!==this.cwd)return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof H.properties.updatedAt==="string"?H.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":H.properties.taskStatus,...typeof H.properties.taskStatusReason==="string"?{"blade/taskStatusReason":H.properties.taskStatusReason}:{},...typeof H.properties.taskStartedAt==="string"?{"blade/taskStartedAt":H.properties.taskStartedAt}:{},...typeof H.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":H.properties.taskCompletedAt}:{}}})});let J=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||J?.status==="active")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let z of this.messages){if(!this.canSendUpdates())return;let J=z.role==="user"?"user_message_chunk":z.role==="assistant"?"agent_message_chunk":void 0;if(!J)continue;for(let H of y(z.content)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:J,content:H}))return}}if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);V.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,J){try{V.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.messages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let $=await this.runtime.rewindSession(Z);return this.messages=[...$.messages],await this.agent?.destroy(),this.agent=await N.createWithRuntime(this.runtime,{sessionId:this.id}),$}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let U=!1,W,G=(F)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.id,status:F.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:F.result?.message||F.result?.error||`Subagent ${F.status}`}}]})},w=this.runtime.resumeSubagent({agentId:Z,prompt:$,onCompleted:(F)=>{if(U)G(F);else W=F}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:w.session.id,status:"in_progress",title:`Resuming ${w.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${w.source.id} at depth ${w.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),U=!0,W)G(W);return w}},signal:J,acp:{sendMessage:(Z)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Z}})},sendToolStart:(Z,$,U)=>{let W=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,G=this.mapToolKind(U);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:W,status:"in_progress",title:`${Z}`,content:[{type:"content",content:{type:"text",text:JSON.stringify($,null,2)}}],kind:G})},sendToolResult:(Z,$)=>{if($.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.summary}})}}},Q=await x(z,H),X=Q.data?.action;if(X==="start_goal"||X==="resume_goal")this.schedulePendingResume();if(X==="rewind_session"&&Array.isArray(Q.data?.messages))this.messages=[...Q.data.messages];if((Q.message==="compact_completed"||Q.message==="compact_fallback")&&Q.data?.compactedMessages)this.messages=[...Q.data.compactedMessages];let Y=Q.content||Q.message;if(Y)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y}});if(Q.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Q.error}`}});return{stopReason:Q.success?"end_turn":"cancelled"}}catch(H){return V.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=k(),J=["model","permissions","theme","config","exit","ide"],Q=z.filter((X)=>!J.includes(X.name)).map((X)=>{let Y;if(X.usage){let Z=X.usage.replace(/^\/\w+\s*/,"").trim();if(Z)Y=Z}if(X.aliases?.length){let Z=`Aliases: ${X.aliases.join(", ")}`;Y=Y?`${Y} | ${Z}`:Z}return{name:X.name,description:X.description,input:Y?{hint:Y}:void 0}});V.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Q.map((X)=>X.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Q}),V.info(`[AcpSession ${this.id}] Sent ${Q.length} available commands`)}catch(z){V.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,J={}){if(L.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let H=this.resolvePrompt(z.prompt);if(this.pendingPrompt){if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let X=await this.runtime.enqueueSteering(H,{allowBeforeTurn:!0});if(!X.accepted)throw Error(X.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(V.debug(`[AcpSession ${this.id}] Queued steering for active turn (${X.queued})`),X.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let Q=new AbortController;this.pendingPrompt=Q;try{if(V.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),b(H))return await this.handleSlashCommand(H,Q.signal);let X={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:Q.signal,permissionMode:this.mapModeToPermissionMode(),confirmationHandler:{requestConfirmation:async(Y)=>{return this.requestPermission(Y)}}};if(await K(this.agent.chatStream(H,X,{pendingInputOnly:J.pendingInputOnly,goalContinuationOnly:J.goalContinuationOnly}),async(Y)=>{switch(Y.kind){case"content_delta":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:Y.delta}});break;case"tool_start":{let Z=Y.toolCall,$="function"in Z?Z.function.name:Z.type,U=this.mapToolKind(Y.toolKind),W=`Executing ${$}`;if($==="Task"&&"function"in Z)try{let G=JSON.parse(Z.function.arguments),w=G.resume_from??G.resume;if(typeof w==="string")W=`Resuming ${String(G.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z.id,status:"in_progress",title:W,content:[],kind:U});break}case"tool_result":{let{toolCall:Z,result:$}=Y,U=[],W=$.metadata;if(W?.kind==="edit"&&typeof W.file_path==="string"&&typeof W.oldContent==="string"&&(typeof W.newContent==="string"||W.newContent===void 0))U.push({type:"diff",path:W.file_path,oldText:W.oldContent,newText:W.newContent??null});else{let w="function"in Z?Z.function.name:Z.type,F=A(q(w,$));U.push({type:"content",content:{type:"text",text:F}})}let G=$.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Z.id,status:G,content:U});break}case"task_update":this.sendPlanUpdate(Y.tasks);break;case"steering_applied":break;case"follow_up_started":for(let Z of Y.messages){if(!Z.recovered||Z.persisted)continue;for(let $ of y(Z.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:$})}if(Y.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${Y.recovered} queued instruction${Y.recovered===1?"":"s"} recovered after restart]
|
|
2
|
+
`}});break;case"goal_updated":if(Y.goal&&Y.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${Y.goal.status}: ${Y.goal.objective}]
|
|
3
|
+
`}});break;case"goal_continuation_started":break;default:break}}),this.messages=[...X.messages],Q.signal.aborted)return{stopReason:"cancelled"};return{stopReason:"end_turn"}}catch(X){if(Q.signal.aborted||X instanceof Error&&X.name==="AbortError")return{stopReason:"cancelled"};throw V.error(`[AcpSession ${this.id}] Prompt error:`,X),X}finally{if(this.pendingPrompt===Q){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.schedulePendingResume()}}}schedulePendingResume(){if(this.destroyed||this.connection.signal.aborted)return;this.pendingResumeRequested=!0,queueMicrotask(()=>{this.resumePendingIfIdle()})}async resumePendingIfIdle(){if(this.destroyed||this.connection.signal.aborted)return;if(this.pendingPrompt||!this.runtime||!this.agent)return;let z=this.runtime.getPendingSteeringCount()>0,H=(z?null:await this.runtime.getGoal())?.status==="active";if(!z&&!H){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:z,goalContinuationOnly:H}).catch((Q)=>{V.error(`[AcpSession ${this.id}] Failed to resume pending input:`,Q)})}cancel(){if(V.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1,this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,V.info(`[AcpSession ${this.id}] Cancelled successfully`);else V.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let J=["default","auto-edit","yolo","plan"];this.mode=J.includes(z)?z:"default",V.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(V.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.destroyed)return;if(this.destroyed=!0,this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let z=this.agent,J=this.runtime;this.agent=null,this.runtime=null;let H,Q=async(X)=>{try{await X()}catch(Y){H??=Y}};if(await Q(()=>this.cancel()),z)await Q(()=>z.destroy());if(J)await Q(()=>J.dispose());if(await Q(()=>L.destroySession(this.id)),V.debug(`[AcpSession ${this.id}] Destroyed`),H!==void 0)throw H}resolvePrompt(z){let J=[];for(let H of z)if(H.type==="text")J.push(H.text);else if(H.type==="image")J.push(`[Image: ${H.mimeType}]`);else if(H.type==="resource"){let Q=H.resource;if("text"in Q)J.push(`<file path="${Q.uri}">
|
|
4
|
+
${Q.text}
|
|
5
|
+
</file>`)}else if(H.type==="resource_link")J.push(`[Resource: ${H.uri}]`);return J.join(`
|
|
6
|
+
`)}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;return await this.connection.sessionUpdate({sessionId:this.id,update:z}),this.canSendUpdates()}sendUpdate(z){if(!this.canSendUpdates())return;let J={sessionId:this.id,update:z};this.connection.sessionUpdate(J).catch((H)=>{V.warn(`[AcpSession ${this.id}] Failed to send update:`,H)})}sendPlanUpdate(z){let J=z.map((H)=>({content:H.subject,priority:H.priority,status:H.status}));V.debug(`[AcpSession ${this.id}] Sending plan update with ${J.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:J})}async requestPermission(z){let J=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,J);let H=z.kind?.toLowerCase()||"execute";if(this.shouldAutoApprove(H))return V.debug(`[AcpSession ${this.id}] Auto-approving ${H} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(H==="write"||H==="execute"))return V.debug(`[AcpSession ${this.id}] Rejecting ${H} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Q=O(),X=[];if(z.message)X.push({type:"content",content:{type:"text",text:z.message}});if(z.risks&&z.risks.length>0)X.push({type:"content",content:{type:"text",text:`Risks:
|
|
7
|
+
- ${z.risks.join(`
|
|
8
|
+
- `)}`}});let Y=this.mapToolKind(H),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:X,kind:Y}},$=await this.waitForClientInteraction(this.connection.requestPermission(Z),J);if(!$)return{approved:!1,reason:E};let U=$.outcome;if(U.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let W=U.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 V.warn(`[AcpSession ${this.id}] Permission request failed:`,Q),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,J){let H=z.questions??[];if(H.length===0)return{approved:!1,reason:"No structured questions were provided"};if(H.some((X)=>X.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Q={};try{for(let[X,Y]of H.entries()){let Z=Y.options.map((G,w)=>`answer:${X}:${w}`),$=`answer:${X}:cancel`,U=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Y.options.map((G,w)=>({optionId:Z[w],name:G.label,kind:"allow_once"})),{optionId:$,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:O(),status:"pending",title:Y.header,kind:"think",content:[{type:"content",content:{type:"text",text:[Y.question,...Y.options.map((G)=>`${G.label}: ${G.description}`)].join(`
|
|
9
|
+
`)}}]}}),J);if(!U)return{approved:!1,reason:E};if(U.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let W=Z.indexOf(U.outcome.optionId);if(W<0)return{approved:!1,reason:"User cancelled the question prompt"};Q[Y.header]=Y.options[W].label}return{approved:!0,answers:Q}}catch(X){return V.warn(`[AcpSession ${this.id}] Question request failed:`,X),{approved:!1,reason:"Question request failed"}}}async waitForClientInteraction(z,J){if(!J)return z;if(J.aborted)return;return new Promise((H,Q)=>{let X=!1,Y=($)=>{if(X)return;X=!0,J.removeEventListener("abort",Z),$()},Z=()=>Y(()=>H(void 0));if(J.addEventListener("abort",Z,{once:!0}),J.aborted)Z();z.then(($)=>Y(()=>H($)),($)=>Y(()=>Q($)))})}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 D=B("Agent");class R{connection;sessions=new Map;sessionLoadQueues=new Map;clientCapabilities;destroyed=!1;constructor(z){this.connection=z}async initialize(z){return D.info("[BladeAgent] Initializing ACP connection"),D.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,{protocolVersion:p,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let J=I("acp");D.info(`[BladeAgent] Creating new session: ${J}`),D.debug(`[BladeAgent] Session cwd: ${z.cwd||M()}`);let H=new _(J,z.cwd||M(),this.connection,this.clientCapabilities,{mcpServers:z.mcpServers});try{await H.initialize(),this.assertNotDestroyed()}catch(Q){throw await H.destroy().catch(()=>{return}),Q}return this.sessions.set(J,H),D.info(`[BladeAgent] Session ${J} created, scheduling available commands update`),H.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(J)}async unstable_listSessions(z){if(z.cwd!=null&&!S.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let J=await P.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:J.sessions.map((H)=>({sessionId:H.sessionId,cwd:H.projectPath,title:H.title??null,updatedAt:H.lastMessageTime,_meta:{"blade/taskStatus":H.taskStatus,...H.taskStatusReason?{"blade/taskStatusReason":H.taskStatusReason}:{},...H.taskStartedAt?{"blade/taskStartedAt":H.taskStartedAt}:{},...H.taskCompletedAt?{"blade/taskCompletedAt":H.taskCompletedAt}:{}}})),nextCursor:J.nextCursor}}async unstable_forkSession(z){if(this.assertNotDestroyed(),!S.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let J=await P.forkSession(z.sessionId,{sourceProjectPath:z.cwd,targetProjectPath:z.cwd});this.assertNotDestroyed();let H=new _(J.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:J.messages,mcpServers:z.mcpServers});try{await H.initialize(),this.assertNotDestroyed()}catch(Q){throw await H.destroy().catch(()=>{return}),Q}return this.sessions.set(J.sessionId,H),H.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(J.sessionId)}async loadSession(z){this.assertNotDestroyed(),D.info(`[BladeAgent] Loading session: ${z.sessionId}`);let H=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),Q=H.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Q);try{return await H}finally{if(this.sessionLoadQueues.get(z.sessionId)===Q)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){this.assertNotDestroyed();let J=this.sessions.get(z.sessionId);if(J)try{await J.destroy()}finally{if(this.sessions.get(z.sessionId)===J)this.sessions.delete(z.sessionId)}let H=await P.loadSession(z.sessionId,z.cwd),Q=new _(z.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:H,mcpServers:z.mcpServers});try{await Q.initialize(),await Q.replayHistory(),this.assertNotDestroyed()}catch(X){throw await Q.destroy().catch(()=>{return}),X}return this.sessions.set(z.sessionId,Q),Q.sendAvailableCommandsDelayed(),this.buildSessionSetup()}buildChildSessionResponse(z){return{sessionId:z,...this.buildSessionSetup()}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}buildSessionSetup(){let z=C(),J=z?.models||[],H=z?.currentModelId||J[0]?.id,Q=J.map((Y)=>({modelId:Y.id,name:u(Y),description:`${Y.provider}/${Y.model}`}));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:H}:void 0}}async prompt(z){let J=this.sessions.get(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);return J.prompt(z)}async cancel(z){D.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let J=this.sessions.get(z.sessionId);if(J)D.info("[BladeAgent] Found session, calling session.cancel()"),J.cancel();else D.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){D.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let J=this.sessions.get(z.sessionId);if(J)await J.setMode(z.modeId);return{}}async unstable_setSessionModel(z){D.info(`[BladeAgent] Setting session model: ${z.modelId}`);let J=this.sessions.get(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);return await J.setModel(z.modelId),{}}async destroy(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let J of this.sessions.values())try{await J.destroy()}catch(H){z??=H}this.sessions.clear();try{await v.getInstance().disconnectAll()}catch(J){z??=J}if(z!==void 0)throw z}}async function Pz(){let z=l.toWeb(process.stdout),J=m.toWeb(process.stdin),H=j.ndJsonStream(z,J);await new j.AgentSideConnection((X)=>new R(X),H).closed}export{Pz as runAcpIntegration};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as y,b as A,c as C,d as D}from"./chunk-
|
|
1
|
+
import{a as y,b as A,c as C,d as D}from"./chunk-n4f8tseg.js";import"./chunk-xhnyy54e.js";import"./chunk-04920kz2.js";import"./chunk-9ad7tt9s.js";import"./chunk-k47ssv3b.js";import"./chunk-bm8vwfez.js";import{wa as q}from"./chunk-tv4r86ez.js";import"./chunk-qwdbqjh7.js";import"./chunk-d4ex0qvs.js";import"./chunk-pdydx73a.js";import"./chunk-1pt090dg.js";import"./chunk-9xkjb87h.js";import"./chunk-49g067ek.js";import"./chunk-ctqf59q1.js";import"./chunk-jt62ctz7.js";import"./chunk-gsfkrr25.js";import"./chunk-0dj326ms.js";import"./chunk-34pdtz4q.js";import"./chunk-hjx5n3dw.js";import"./chunk-dr06x0cw.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,4 +1,4 @@
|
|
|
1
|
-
import{p as A,q as E,r as N,s as f}from"./chunk-
|
|
1
|
+
import{p as A,q as E,r as N,s as f}from"./chunk-sr3bzb95.js";import{t as D}from"./chunk-6yqzfz8t.js";import{v as L,w as _,x}from"./chunk-syj3anec.js";import{y as B}from"./chunk-twem6p0g.js";import{N as $,S as b}from"./chunk-04920kz2.js";import"./chunk-9ad7tt9s.js";import"./chunk-k47ssv3b.js";import"./chunk-bm8vwfez.js";import"./chunk-tv4r86ez.js";import"./chunk-qwdbqjh7.js";import"./chunk-d4ex0qvs.js";import"./chunk-pdydx73a.js";import{ab as Z}from"./chunk-1pt090dg.js";import"./chunk-9xkjb87h.js";import"./chunk-49g067ek.js";import"./chunk-ctqf59q1.js";import"./chunk-jt62ctz7.js";import{Hb as Y,Ib as T}from"./chunk-gsfkrr25.js";import"./chunk-0dj326ms.js";import"./chunk-34pdtz4q.js";import"./chunk-hjx5n3dw.js";import"./chunk-dr06x0cw.js";import h from"yargs";import{hideBin as R}from"yargs/helpers";var w=new Set(Object.values(Y));function X(k){if(k&&w.has(k))return k;return}function M(k){return k.command("* [message]","Print response and exit (useful for pipes)",(F)=>F.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(F)=>{if(!F.p)return;let q=await O(F);process.exit(q)})}async function O(k,F=process){let q;try{await A();let J=await E({message:k.message,_:k._,defaultMessage:"Hello"}),G=await N(J);if(G.mode==="output"){if(G.content)F.stdout.write(`${G.content}
|
|
2
2
|
`);return G.exitCode??0}let Q=G.content,{sessionId:K,messages:U}=await f({sessionId:k.sessionId,continue:k.continue,resume:k.resume,forkSession:k.forkSession,fallbackSessionPrefix:"print"});q=await $.create({sessionId:K,workspaceRoot:T(),modelId:k.model,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig,agents:k.agents?B(k.agents):void 0});let V=await b.createWithRuntime(q,{sessionId:K,systemPrompt:k.systemPrompt,appendSystemPrompt:k.appendSystemPrompt,maxTurns:k.maxTurns,modelId:k.model,permissionMode:X(k.permissionMode),toolWhitelist:k.allowedTools,toolBlacklist:k.disallowedTools,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig}),H=(await Z(V.chatStream(Q,{messages:[...U],userId:"cli-user",sessionId:K,workspaceRoot:T(),permissionMode:X(k.permissionMode)}))).finalMessage||"";if(k.outputFormat==="json")F.stdout.write(`${JSON.stringify({response:H,input:Q,model:k.model,timestamp:new Date().toISOString()},null,2)}
|
|
3
3
|
`);else if(k.outputFormat==="stream-json")F.stdout.write(`${JSON.stringify({type:"response",content:H})}
|
|
4
4
|
`);else F.stdout.write(`${H}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{p,q as i,r as s,s as r}from"./chunk-
|
|
1
|
+
import{p,q as i,r as s,s as r}from"./chunk-sr3bzb95.js";import{t as y}from"./chunk-6yqzfz8t.js";import{v as u,w as m,x as l}from"./chunk-syj3anec.js";import{y as v}from"./chunk-twem6p0g.js";import{N as c,O as g,P as d,R as N,S as T}from"./chunk-04920kz2.js";import"./chunk-9ad7tt9s.js";import"./chunk-k47ssv3b.js";import"./chunk-bm8vwfez.js";import"./chunk-tv4r86ez.js";import"./chunk-qwdbqjh7.js";import"./chunk-d4ex0qvs.js";import"./chunk-pdydx73a.js";import{ab as h}from"./chunk-1pt090dg.js";import"./chunk-9xkjb87h.js";import"./chunk-49g067ek.js";import{Bb as z,wb as C,yb as q,zb as x}from"./chunk-ctqf59q1.js";import"./chunk-jt62ctz7.js";import{Hb as E,Ib as P,Jb as S}from"./chunk-gsfkrr25.js";import"./chunk-0dj326ms.js";import"./chunk-34pdtz4q.js";import"./chunk-hjx5n3dw.js";import"./chunk-dr06x0cw.js";import Rq from"yargs";import{hideBin as Hq}from"yargs/helpers";var W=1;function K(Y){return q.Object({event_version:q.Literal(W),...Y})}var Qq=K({type:q.Literal("content_delta"),delta:q.String()}),Yq=K({type:q.Literal("thinking_delta"),delta:q.String()}),Zq=K({type:q.Literal("thinking"),content:q.String()}),$q=K({type:q.Literal("stream_end")}),Bq=K({type:q.Literal("content"),content:q.String()}),k=z(["readonly","write","execute"]),Gq=K({type:q.Literal("tool_start"),tool_name:q.String(),summary:q.String(),target:q.Optional(q.String()),tool_kind:q.Optional(k)}),Xq=K({type:q.Literal("tool_result"),tool_name:q.String(),summary:q.String(),target:q.Optional(q.String()),tool_kind:q.Optional(k),success:q.Optional(q.Boolean()),error_type:q.Optional(q.String()),error_message:q.Optional(q.String())}),Uq=K({type:q.Literal("phase"),phase:z(["turn","searching","inspecting","target_hit","executing","completed"]),status:z(["ongoing","hit","done"]),message:q.String(),turn:q.Optional(q.Number()),tool_name:q.Optional(q.String()),target:q.Optional(q.String())}),Vq=K({type:q.Literal("tool_detail"),tool_name:q.String(),detail:q.String()}),Dq=K({type:q.Literal("task_update"),tasks:q.Array(N)}),Kq=K({type:q.Literal("subagent"),state:z(["spawned","completed"]),session_id:q.String(),subagent_type:q.Optional(q.String()),success:q.Optional(q.Boolean()),summary:q.Optional(q.String()),resumed_from:q.Optional(q.String()),root_agent_id:q.Optional(q.String()),resume_depth:q.Optional(q.Integer({minimum:0}))}),bq=K({type:q.Literal("token_usage"),input_tokens:q.Number(),output_tokens:q.Number(),total_tokens:q.Number(),max_context_tokens:q.Number(),cache_read_tokens:q.Optional(q.Number()),cache_write_tokens:q.Optional(q.Number()),cost_usd:q.Optional(q.Number())}),_q=K({type:q.Literal("compacting"),state:z(["started","completed"])}),zq=K({type:q.Literal("turn_limit"),turns_count:q.Number(),action:q.Literal("continue")}),Aq=K({type:q.Literal("output"),content:q.String(),exit_code:q.Number()}),Mq=K({type:q.Literal("error"),message:q.String()}),Sq=x(q.Union([Qq,Yq,Zq,$q,Bq,Gq,Xq,Uq,Vq,Dq,Kq,bq,_q,zq,Aq,Mq]));function O(Y,$){return{event_version:W,type:Y,...$}}function jq(Y){if(Y?.signal)return{signal:Y.signal,dispose:()=>{return}};let $=new AbortController,B=()=>$.abort("interrupt");return process.once("SIGINT",B),process.once("SIGTERM",B),{signal:$.signal,dispose:()=>{process.removeListener("SIGINT",B),process.removeListener("SIGTERM",B)}}}var fq=z(["text","jsonl"]),Iq=q.Object({headless:q.Optional(q.Boolean()),message:q.Optional(q.String()),_:q.Optional(q.Array(q.Union([q.String(),q.Number()]))),model:q.Optional(q.String()),systemPrompt:q.Optional(q.String()),appendSystemPrompt:q.Optional(q.String()),maxTurns:q.Optional(q.Refine(q.Integer({maximum:S}),(Y)=>Y===-1||Y>0,()=>"must be -1 or a positive integer")),permissionMode:q.Optional(q.Enum(E)),mcpConfig:q.Optional(q.Array(q.String())),strictMcpConfig:q.Optional(q.Boolean()),sessionId:q.Optional(q.String()),allowedTools:q.Optional(q.Array(q.String())),disallowedTools:q.Optional(q.Array(q.String())),agents:q.Optional(q.String()),continue:q.Optional(q.Boolean()),resume:q.Optional(q.Union([q.String(),q.Boolean()])),forkSession:q.Optional(q.Boolean()),outputFormat:q.Optional(fq)});class n{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(Y){this.openedThinking=Y}hasOpenThinking(){return this.openedThinking}completeStream(){let Y={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,Y}}function Jq(Y){return Y.issues.map(($)=>`${$.path.join(".")||"options"}: ${$.message}`).join("; ")}function Pq(Y){let $=C(Iq,Y);if(!$.success)throw Error(`Invalid headless options: ${Jq($.error)}`);return $.data}function Lq(Y){return Y.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",($)=>$.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}),async($)=>{if(!$.headless)return;let B=await Fq($);process.exit(B)})}function b(Y,$=""){Y.write(`${$}
|
|
2
2
|
`)}function xq(Y){return`[task] [${Y.status}] ${Y.subject}`}function Nq(){return{requestConfirmation:async(Y)=>({approved:!0,reason:"headless-auto-approved",scope:"session"})}}function Wq(Y){if(!(Y instanceof Error))return"Unknown error";let Q=Y.lastError??Y;if(Q.responseBody)try{let U=JSON.parse(Q.responseBody)?.error?.message;if(U)return Q.statusCode?`${U} (HTTP ${Q.statusCode})`:U}catch{}let Z=Y.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return Y.message}function kq(Y){return Y==="jsonl"?"jsonl":"text"}function F(Y,$){let B=(...Q)=>{for(let Z of Q){let D=$[Z];if(typeof D==="string"&&D.trim()!=="")return D}return};switch(Y){case"Read":case"Edit":case"Write":case"UndoEdit":return B("file_path");case"NotebookEdit":return B("notebook_path");case"Grep":return B("path","pattern");case"Glob":return B("pattern");case"WebFetch":return B("url");case"WebSearch":return B("query");case"Bash":return B("command","description");case"Task":return B("description");case"LSP":return B("filePath","operation");case"EnterWorktree":return B("name");case"ExitWorktree":return B("action");default:return}}function Oq(Y,$,B,Q){let Z=new Set(["Glob","Grep","WebSearch","LS"]),D=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(Y)&&!Q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${$}`,shouldLockTarget:!0};if(Q.targetLocked)return{phase:"executing",status:"hit",message:B?`Working within target: ${$}`:`Executing: ${$}`,shouldLockTarget:!1};if(Z.has(Y))return{phase:"searching",status:"ongoing",message:`Still searching: ${$}`,shouldLockTarget:!1};if(D.has(Y))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${$}`,shouldLockTarget:!1};return{phase:"executing",status:Q.targetLocked?"hit":"ongoing",message:`Executing: ${$}`,shouldLockTarget:!1}}function w(Y,$){let B=(Q,Z)=>{Y.stdout.write(`${JSON.stringify(O(Q,Z))}
|
|
3
3
|
`)};return{contentDelta(Q){if($==="jsonl"){B("content_delta",{delta:Q});return}Y.stdout.write(Q)},thinkingDelta(Q,Z){if($==="jsonl")return B("thinking_delta",{delta:Q}),Z;if(!Z)Y.stderr.write("[thinking] ");return Y.stderr.write(Q),!0},thinking(Q){if($==="jsonl"){B("thinking",{content:Q});return}b(Y.stderr,`[thinking] ${Q}`)},streamEnd(Q,Z){if($==="jsonl"){B("stream_end",{});return}if(Z)Y.stderr.write(`
|
|
4
4
|
`);if(Q)Y.stdout.write(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ka as I,La as C}from"./chunk-
|
|
1
|
+
import{Ka as I,La as C}from"./chunk-pdydx73a.js";import{rb as R}from"./chunk-9xkjb87h.js";import{wb as E,yb as U}from"./chunk-ctqf59q1.js";import{ec as f}from"./chunk-dr06x0cw.js";import{EventEmitter as t}from"events";function p($){if($===void 0)return"undefined";if(typeof $==="string")return $;try{let L=JSON.stringify($);return L===void 0?String($):L}catch{return String($)}}function g($){let L=$;switch($.code){case"type":return`类型错误:${$.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${$.message}`;case"maxLength":return`字符串过长:${$.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${$.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${$.message}`;case"minItems":return`数组元素过少:${$.message}`;case"maxItems":return`数组元素过多:${$.message}`;case"format":return`格式错误:${$.message}`;case"enum":return`必须是枚举允许的值之一:${$.message}`;case"const":return`必须是指定的字面量值:${$.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${$.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return $.message||"自定义验证失败";default:return $.message||`验证失败:${p(L)}`}}class D extends Error{issues;type;constructor($,L,G="validation_error"){super($);this.issues=L;this.type=G;this.name="ToolValidationError"}}function N($,L){let G=E($,L);if(G.success)return G.data;let Q=G.error.issues.map((X)=>({field:X.path.length>0?X.path.join("."):"root",message:g(X),value:X.value})),W=Q.length===1?`参数验证失败 [${Q[0].field}]: ${Q[0].message}`:`参数验证失败 (${Q.length} 个错误):
|
|
2
2
|
${Q.map((X)=>` - ${X.field}: ${X.message}`).join(`
|
|
3
3
|
`)}`;throw new D(W,Q)}function K($){if(!$||typeof $!=="object")return;let L=$;if(L.type==="object"&&L.properties)L.required??=[],L.additionalProperties??=!1;for(let G of Object.values(L))if(Array.isArray(G))for(let Q of G)K(Q);else K(G)}function x($){let L=JSON.parse(JSON.stringify($,(G,Q)=>G.startsWith("~")?void 0:Q));return K(L),L}class O{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor($,L,G,Q,W){this.toolName=$;this.params=L;this.executeFn=G;this.descriptionFn=Q;this.affectedPathsFn=W}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute($,L,G){let Q={signal:$,updateOutput:L,...G};return this.executeFn(this.params,Q)}}function h($){return{name:$.name,displayName:$.displayName,kind:$.kind,isReadOnly:$.isReadOnly??R($.kind),isConcurrencySafe:$.isConcurrencySafe??!1,strict:$.strict??!1,description:$.description,version:$.version||"1.0.0",category:$.category,tags:$.tags||[],getFunctionDeclaration(){let L=x($.schema),G=$.description.short;if($.description.long)G+=`
|
|
4
4
|
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{e as TS,f as MS}from"./chunk-xhnyy54e.js";import{$ as zS,A as DS,C as GS,D as BO,E as kO,G as XO,H as QO,I as L,J as E,K as YS,L as P,N as jS,P as FO,Q as fO,S as QS}from"./chunk-04920kz2.js";import{ca as n}from"./chunk-k47ssv3b.js";import{Ca as o,va as $O,xa as cO,ya as dO,za as aO}from"./chunk-tv4r86ez.js";import{Ka as VO}from"./chunk-pdydx73a.js";import{Qa as HS,Sa as wO,ab as yO}from"./chunk-1pt090dg.js";import{sb as JS}from"./chunk-9xkjb87h.js";import{Ab as zO,Bb as C,wb as g,yb as x,zb as b}from"./chunk-ctqf59q1.js";import{Cb as NS}from"./chunk-jt62ctz7.js";import{Ib as m}from"./chunk-gsfkrr25.js";import{Tb as q}from"./chunk-34pdtz4q.js";import{Yb as VS,dc as r}from"./chunk-hjx5n3dw.js";import{ec as PO}from"./chunk-dr06x0cw.js";var ox={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function ix(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as mS,readFileSync as HO}from"node:fs";import{createServer as kx}from"node:http";import{networkInterfaces as Px}from"node:os";import{dirname as Rx,extname as Ix,join as SO}from"node:path";import{fileURLToPath as gx}from"node:url";import{Hono as vx}from"hono";import{cors as ux}from"hono/cors";import{WebSocketServer as tx}from"ws";class I extends Error{code;statusCode;constructor(O,$,S=500){super($);this.code=O;this.statusCode=S;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class f extends I{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class p extends I{constructor(O){super("BAD_REQUEST",O,400)}}class i extends I{constructor(O){super("CONFLICT",O,409)}}class t extends I{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class d extends I{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var sx=x.Object({error:x.Object({code:x.String(),message:x.String()})});import{Hono as PS}from"hono";var DO=q("Service"),RS=x.Object({updates:x.Record(x.String(),x.Any()),options:x.Optional(x.Object({scope:x.Optional(C(["local","project","global"])),immediate:x.Optional(x.Boolean())}))});function IS(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,theme:O.theme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash}}var vO=()=>{let O=new PS;return O.get("/",async($)=>{try{let S=$O();return $.json(S?IS(S):{})}catch(S){return DO.error("[ConfigRoutes] Failed to get config:",S),$.json({})}}),O.put("/",async($)=>{try{let S=await $.req.json(),V=g(RS,S);if(!V.success)throw new p("Invalid config update format");let{updates:J,options:j}=V.data;return await o().updateConfig(J,j),$.json({success:!0,updates:J})}catch(S){throw DO.error("[ConfigRoutes] Failed to update config:",S),S}}),O.get("/permissions",async($)=>{try{let S=$O();return $.json(S?.permissions||{})}catch(S){return DO.error("[ConfigRoutes] Failed to get permissions:",S),$.json({})}}),O};import{Hono as gS}from"hono";import{streamSSE as vS}from"hono/streaming";var uS=15000,tS=new Set(["task.status"]),lS=new Set(["queued","running","completed","failed","cancelled","interrupted"]),uO=()=>{let O=new gS;return O.get("/",($)=>vS($,async(S)=>{let V,J,j=!1,G=()=>{if(J!==void 0)clearInterval(J),J=void 0;V?.(),V=void 0},X=()=>{if(j)return;j=!0,G()};S.onAbort(X),V=E.subscribe((A)=>{if(!tS.has(A.type))return;let w=A.properties.taskStatus;if(typeof w!=="string"||!lS.has(w))return;S.writeSSE({data:JSON.stringify({type:A.type,properties:{sessionId:A.sessionId,projectPath:A.projectPath,taskStatus:w,...typeof A.properties.taskStatusReason==="string"?{taskStatusReason:A.properties.taskStatusReason}:{},...typeof A.properties.taskStartedAt==="string"?{taskStartedAt:A.properties.taskStartedAt}:{},...typeof A.properties.taskCompletedAt==="string"?{taskCompletedAt:A.properties.taskCompletedAt}:{},...typeof A.properties.updatedAt==="string"?{updatedAt:A.properties.updatedAt}:{}}})}).catch(X)});try{if(S.aborted||j)return;if(await S.writeSSE({data:JSON.stringify({type:"connected",properties:{timestamp:Date.now()}})}),S.aborted||j)return;J=setInterval(()=>{if(S.aborted||j)return;S.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(X)},uS);while(!S.aborted&&!j)await new Promise((A)=>setTimeout(A,1000))}finally{X()}})),O};import{Hono as cS}from"hono";var tO=()=>{let O=new cS;return O.get("/health",($)=>{return $.json({healthy:!0,version:VO()})}),O.get("/info",($)=>{return $.json({version:VO(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:m()})}),O};import{Hono as dS}from"hono";var jO=q("Service"),lO=()=>{let O=new dS;return O.get("/",async($)=>{try{let V=n.getInstance().getAllServers(),J=Array.from(V.entries()).map(([j,G])=>({id:j,name:j,status:G.status==="connected"?"connected":G.status==="connecting"?"connecting":G.lastError?"error":"offline",endpoint:G.config.command?`${G.config.command} ${(G.config.args||[]).join(" ")}`.trim():G.config.url||"Unknown",description:`MCP server: ${j}`,tools:G.tools.map((X)=>X.name),connectedAt:G.connectedAt?.toISOString(),error:G.lastError?.message}));return $.json(J)}catch(S){return jO.error("[McpRoutes] Failed to get MCP servers:",S),$.json([])}}),O.post("/:name/connect",async($)=>{try{let S=$.req.param("name");return await n.getInstance().connectServer(S),$.json({success:!0})}catch(S){return jO.error("[McpRoutes] Failed to connect MCP server:",S),$.json({success:!1,error:S.message},500)}}),O.post("/:name/disconnect",async($)=>{try{let S=$.req.param("name");return await n.getInstance().disconnectServer(S),$.json({success:!0})}catch(S){return jO.error("[McpRoutes] Failed to disconnect MCP server:",S),$.json({success:!1,error:S.message},500)}}),O.delete("/:name",async($)=>{try{let S=$.req.param("name");await n.getInstance().unregisterServer(S);let J=$O();if(J?.mcpServers){let{[S]:j,...G}=J.mcpServers;await o().updateConfig({mcpServers:G})}return $.json({success:!0})}catch(S){return jO.error("[McpRoutes] Failed to delete MCP server:",S),$.json({success:!1,error:S.message},500)}}),O.post("/",async($)=>{try{let S=await $.req.json(),{name:V,config:J}=S;if(!V||!J)return $.json({success:!1,error:"Missing name or config"},400);await n.getInstance().registerServer(V,J);let G=$O();return await o().updateConfig({mcpServers:{...G?.mcpServers,[V]:J}}),$.json({success:!0})}catch(S){return jO.error("[McpRoutes] Failed to add MCP server:",S),$.json({success:!1,error:S.message},500)}}),O};import{Hono as aS}from"hono";var AO=q("Service");function oS(O,$){return{id:O.id,displayName:O.displayName,provider:O.provider,model:O.model,overrides:O.overrides,fallbackModels:O.fallbackModels,contextWindow:$.contextWindow,maxTokens:$.maxTokens,reasoning:$.reasoning,input:$.input}}function iS(O){let $={displayName:O.displayName||void 0,overrides:O.overrides||void 0};if(O.model)$.model=O.model;return $}var oO=()=>{let O=new aS;return O.get("/",async($)=>{try{let S=cO(),V=dO(),J=r(),j=(G)=>oS(G,J.resolveConfig(G));return $.json({configured:S.map(j),current:V?j(V):null})}catch(S){return AO.error("[ModelsRoutes] Failed to get models:",S),$.json({configured:[],current:null})}}),O.post("/",async($)=>{try{let S=await $.req.json(),{provider:V,displayName:J,model:j,overrides:G,apiKey:X}=S;if(!V||!j)throw new p("provider and model are required");if(r().getModel(V,j),X?.trim())await r().setApiKey(V,X.trim());let A=await o().addModel({provider:V,displayName:J||void 0,model:j,overrides:G||void 0});return $.json({success:!0,model:A})}catch(S){throw AO.error("[ModelsRoutes] Failed to add model:",S),S}}),O.put("/:modelId",async($)=>{try{let S=$.req.param("modelId"),V=await $.req.json(),{displayName:J,overrides:j,model:G}=V,X=aO(S);if(!X)throw new p("model config not found");if(G)r().getModel(X.provider,G);return await o().updateModel(S,iS({displayName:J,overrides:j,model:G})),$.json({success:!0})}catch(S){throw AO.error("[ModelsRoutes] Failed to update model:",S),S}}),O.delete("/:modelId",async($)=>{try{let S=$.req.param("modelId");return await o().removeModel(S),$.json({success:!0})}catch(S){throw AO.error("[ModelsRoutes] Failed to delete model:",S),S}}),O};import{Hono as Mx}from"hono";import $S from"node:path";import{Mutex as $x}from"async-mutex";import{Hono as Vx}from"hono";import{streamSSE as Nx}from"hono/streaming";import{LRUCache as Jx}from"lru-cache";import{nanoid as NO}from"nanoid";var nO=b(C(["default","autoEdit","yolo","plan"]));var pO=b(C(["user","assistant","system","tool"])),nS=b(x.Union([x.Object({type:x.Literal("text"),text:x.String()}),x.Object({type:x.Literal("image_url"),image_url:x.Object({url:x.String()})})])),rO=x.Union([x.String(),x.Array(nS)]),q0=b(x.Object({id:x.String(),role:pO,content:rO,timestamp:x.Number(),metadata:x.Optional(x.Record(x.String(),x.Unknown())),thinkingContent:x.Optional(x.String()),tool_call_id:x.Optional(x.String()),name:x.Optional(x.String()),tool_calls:x.Optional(x.Unknown())})),rS=b(C(["queued","running","completed","failed","cancelled","interrupted"])),sS=b(x.Object({sessionId:x.String(),projectPath:x.String(),title:x.Optional(x.String()),gitBranch:x.Optional(x.String()),rootId:x.String(),parentId:x.Optional(x.String()),relationType:x.Optional(C(["subagent","fork"])),resumedFrom:x.Optional(x.String()),rootAgentId:x.Optional(x.String()),resumeDepth:x.Optional(x.Integer({minimum:0})),taskStatus:zO(rS,"completed"),taskStatusReason:x.Optional(x.String()),taskStartedAt:x.Optional(x.String()),taskCompletedAt:x.Optional(x.String()),messageCount:x.Number(),firstMessageTime:x.String(),lastMessageTime:x.String(),hasErrors:x.Boolean()})),C0=b(x.Object({version:x.Literal(1),sessionId:x.String(),goalId:x.String(),objective:x.String(),status:C(["active","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:x.Optional(x.Number()),tokensUsed:x.Number(),timeUsedSeconds:x.Number(),continuationCount:x.Number(),statusReason:x.Optional(x.String()),createdAt:x.String(),updatedAt:x.String()})),sO=b(x.Object({role:pO,content:rO,metadata:x.Optional(x.Unknown()),reasoningContent:x.Optional(x.String()),thinkingContent:x.Optional(x.String()),tool_call_id:x.Optional(x.String()),name:x.Optional(x.String()),tool_calls:x.Optional(x.Unknown())})),L0=b(x.Object({session:sS,messages:x.Array(sO)})),eO=b(C(["conversation","code","both"])),eS=b(x.Object({messageId:x.String(),preview:x.String(),createdAt:x.String(),fileCount:x.Integer({minimum:0})})),OS=b(x.Object({targetMessageId:x.String({minLength:1}),mode:zO(eO,"conversation")})),F0=b(x.Object({checkpoint:eS,mode:eO,removedTurns:x.Integer({minimum:1}),restoredFiles:x.Array(x.String()),messages:x.Array(sO)})),Ox=C(["running","completed","failed","cancelled"]),iO=b(x.Object({id:x.String(),subagentType:x.String(),description:x.String(),status:Ox,rootAgentId:x.String(),resumedFrom:x.Optional(x.String()),resumeDepth:x.Integer({minimum:0}),createdAt:x.Number(),lastActiveAt:x.Number(),completedAt:x.Optional(x.Number()),result:x.Optional(x.Object({success:x.Boolean(),message:x.String(),error:x.Optional(x.String()),verificationCommands:x.Optional(x.Array(x.String()))})),stats:x.Optional(x.Object({tokens:x.Optional(x.Number()),toolCalls:x.Optional(x.Number()),duration:x.Optional(x.Number())}))})),SS=b(x.Object({prompt:x.String({minLength:1,maxLength:32000,pattern:"\\S"})})),f0=b(x.Object({source:iO,session:iO})),m0=b(x.Object({sessionId:x.String(),projectPath:x.String()})),h0=b(x.Object({type:x.String(),properties:x.Record(x.String(),x.Unknown())})),xS=b(x.Object({content:x.String(),projectPath:x.Optional(x.String()),permissionMode:x.Optional(nO),attachments:x.Optional(x.Array(x.Object({type:C(["file","image","url"]),path:x.Optional(x.String()),url:x.Optional(x.String()),content:x.Optional(x.String()),mimeType:x.Optional(x.String()),name:x.Optional(x.String())})))})),k0=b(x.Object({messageId:x.String(),role:pO,content:x.String(),timestamp:x.String()})),P0=b(x.Object({approved:x.Boolean(),remember:x.Optional(x.Boolean()),scope:x.Optional(C(["once","session","project"])),targetMode:x.Optional(nO),feedback:x.Optional(x.String()),answers:x.Optional(x.Record(x.String(),x.Union([x.String(),x.Array(x.String())])))})),R0=b(x.Object({id:x.String(),displayName:x.Optional(x.String()),provider:x.String(),model:x.String(),contextWindow:x.Optional(x.Number()),maxTokens:x.Optional(x.Number()),reasoning:x.Optional(x.Boolean()),input:x.Optional(x.Array(C(["text","image"]))),overrides:x.Optional(x.Object({baseUrl:x.Optional(x.String()),temperature:x.Optional(x.Number()),maxOutputTokens:x.Optional(x.Number()),timeout:x.Optional(x.Number())}))})),I0=b(C(["vs-dark","vs-light","hc-black"])),Sx=b(C(["light","dark","system"])),xx=b(x.Object({language:x.String(),theme:x.String(),uiTheme:Sx,autoSaveSessions:x.Boolean(),notifyBuild:x.Boolean(),notifyErrors:x.Boolean(),notifySounds:x.Boolean(),privacyTelemetry:x.Boolean(),privacyCrash:x.Boolean()})),g0=b(x.Partial(xx));var y=q("Service"),Gx=x.Object({title:x.Optional(x.String()),projectPath:x.Optional(x.String())}),Yx=xS,jx=x.Object({title:x.Optional(x.String()),projectPath:x.Optional(x.String())}),Qx=x.Object({projectPath:x.String()}),Ux=x.Object({objective:x.String({minLength:1}),tokenBudget:x.Optional(x.Integer({minimum:1})),permissionMode:x.Optional(C(["default","autoEdit","plan","yolo"]))}),Zx=x.Union([x.Object({action:x.Literal("pause")}),x.Object({action:x.Literal("resume")}),x.Object({action:x.Literal("edit"),objective:x.String({minLength:1})})]),k=new Map,F=new Jx({max:100,ttl:1800000,dispose:(O,$)=>{if(O.status==="running"||O.status==="waiting_permission")O.abortController.abort(),y.debug(`[SessionRoutes] Run ${$} disposed due to cache eviction`)}});function Ax(O){return{sessionId:O.sessionId,projectPath:O.projectPath}}function _O(O,$="user-cancel"){if(O.status==="cancelled"||O.status==="completed"||O.status==="failed")return!1;let S=O.pendingPermission;return O.pendingPermission=void 0,S?.resolve({approved:!1,reason:JS}),O.abortController.abort($),O.status="cancelled",E.publish(Ax(O),"run.cancelled",{runId:O.id}),!0}function US(O,$=!1){let{permissionId:S,details:V}=O;if(V.type==="askUserQuestion"&&V.questions)return{type:"question.required",properties:{requestId:S,toolCallId:S,questions:V.questions,details:V,...$?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:S,toolName:V.toolName,description:V.message,args:V.args,details:V,...$?{replayed:!0}:{}}}}function Xx(){for(let O of F.values())_O(O,"route-reset");F.clear(),k.clear()}var ZS=(O)=>{if(!O||typeof O!=="object")return O;let $={...O},S=200000;if(typeof $.oldContent==="string"&&$.oldContent.length>S)delete $.oldContent;if(typeof $.newContent==="string"&&$.newContent.length>S)delete $.newContent;return $};function _x(O,$,S){switch(S.kind){case"tool_start":if("function"in S.toolCall)E.publish(O,"subagent.update",{subagentSessionId:$,toolName:S.toolCall.function.name}),E.publish(O,"subagent.tool.start",{subagentSessionId:$,toolCallId:S.toolCall.id,toolName:S.toolCall.function.name,arguments:S.toolCall.function.arguments,toolKind:S.toolKind});break;case"tool_result":if("function"in S.toolCall)E.publish(O,"subagent.tool.result",{subagentSessionId:$,toolCallId:S.toolCall.id,toolName:S.toolCall.function.name,success:!S.result.error,summary:S.result.metadata?.summary,output:fO(FO(S.toolCall.function.name,S.result)),metadata:ZS(S.result.metadata)});break;case"content_delta":E.publish(O,"subagent.delta",{subagentSessionId:$,delta:S.delta});break;case"thinking_delta":E.publish(O,"subagent.thinking.delta",{subagentSessionId:$,delta:S.delta});break;case"stream_end":E.publish(O,"subagent.stream.end",{subagentSessionId:$});break;default:break}}function qO(O,$="projectPath"){if(!$S.isAbsolute(O))throw new p(`${$} must be absolute`);return $S.resolve(O)}function CO(O){try{VS(O)}catch($){throw new p($ instanceof Error?$.message:`Invalid session ID: ${O}`)}}function v(O){return{sessionId:O.id,projectPath:O.projectPath}}function bO(O,$){return{id:O.sessionId,projectPath:O.projectPath,title:O.title??`Session ${O.sessionId.slice(0,6)}`,createdAt:new Date(O.firstMessageTime),updatedAt:new Date(O.lastMessageTime),rootId:O.rootId,parentId:O.parentId,relationType:O.relationType,taskStatus:O.taskStatus,taskStatusReason:O.taskStatusReason,taskStartedAt:O.taskStartedAt,taskCompletedAt:O.taskCompletedAt,messages:$}}function EO(O){let $=O.currentRunId?F.get(O.currentRunId):void 0,S=$?.status==="waiting_permission"?"running":$?.status??O.taskStatus;return{sessionId:O.id,projectPath:O.projectPath,title:O.title,rootId:O.rootId,parentId:O.parentId,relationType:O.relationType,status:void 0,taskStatus:S,taskStatusReason:O.taskStatusReason,taskStartedAt:O.taskStartedAt,taskCompletedAt:O.taskCompletedAt,agentType:void 0,model:void 0,messageCount:O.messages.length,firstMessageTime:O.createdAt.toISOString(),lastMessageTime:O.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function l(O,$){if(CO(O),$!==void 0){let V=QO({sessionId:O,projectPath:qO($)});if(k.has(L(V)))return V;let J=await P.findSessionMetadata(V.sessionId,V.projectPath);if(!J)throw new f("Session",O);return QO({sessionId:J.sessionId,projectPath:J.projectPath})}let S=new Map;for(let V of k.values()){if(V.id!==O)continue;let J=v(V);S.set(L(J),J)}for(let V of await P.listSessions()){if(V.sessionId!==O)continue;let J=QO({sessionId:V.sessionId,projectPath:V.projectPath});S.set(L(J),J)}if(S.size===0)try{let V=await P.findSessionMetadata(O);if(!V)throw new f("Session",O);return QO({sessionId:V.sessionId,projectPath:V.projectPath})}catch(V){if(V instanceof f)throw V;if(V instanceof Error&&V.message.startsWith("Ambiguous session ID:"))throw new t;throw V}if(S.size>1)throw new t;return S.values().next().value}function LO(O){if(typeof O==="string")return O;return O.filter(($)=>$.type==="text").map(($)=>$.text).join(`
|
|
2
|
+
`)}function wx(O,$){let S=($??[]).filter((J)=>J.type==="image"&&typeof J.content==="string").map((J)=>({type:"image_url",image_url:{url:J.content}}));if(S.length===0)return O;let V=[];if(O.trim())V.push({type:"text",text:O});return V.push(...S),V}var AS=()=>{Xx();let O=new Vx;O.onError((N,U)=>{if(N instanceof I)return U.json(N.toObject(),N.statusCode);return y.error("[SessionRoutes] Unhandled route error:",N),U.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let $=new Map,S=new Map,V=new Map,J=new Map,j=(N)=>{let U=L(N),Y=J.get(U);if(!Y)Y=new $x,J.set(U,Y);return Y},G=async(N)=>{let U=L(v(N)),Y=$.get(U);if(Y)return Y;let Q=S.get(U);if(!Q)Q=jS.create({sessionId:N.id,workspaceRoot:N.projectPath}),S.set(U,Q);try{let Z=await Q;return $.set(U,Z),Z}finally{if(S.get(U)===Q)S.delete(U)}},X=async(N)=>{let U=L(N),Y=k.get(U);if(Y)return Y;let Q=V.get(U);if(!Q)Q=(async()=>{let Z=await P.findSessionMetadata(N.sessionId,N.projectPath);if(!Z)throw new f("Session",N.sessionId);let T=bO(Z,await P.loadSession(N.sessionId,N.projectPath));return k.set(U,T),T})(),V.set(U,Q);try{return await Q}finally{if(V.get(U)===Q)V.delete(U)}},A=async(N,U)=>{return X(await l(N,U))},w=(N,U,Y,Q={})=>{let Z=NO(12),T={id:Z,sessionId:N.id,projectPath:N.projectPath,status:"running",abortController:new AbortController,createdAt:new Date};return F.set(Z,T),N.currentRunId=Z,T.completion=Tx(T,N,U,Y,G,{pendingInputOnly:Q.pendingInputOnly,preparedInputTurn:Q.preparedInputTurn,goalContinuationOnly:Q.goalContinuationOnly}).catch((_)=>{y.error(`[SessionRoutes] Run ${Z} failed:`,_)}),T},D=async(N)=>{let U=N.currentRunId?F.get(N.currentRunId):void 0;if(U&&(U.status==="running"||U.status==="waiting_permission"))return;let Y=await G(N),Q=N.currentRunId?F.get(N.currentRunId):void 0;if(Q&&(Q.status==="running"||Q.status==="waiting_permission"))return;let Z=Y.getPendingSteeringCount()>0,_=(Z?null:await Y.getGoal())?.status==="active";if(!Z&&!_||Y.hasTurnOwner())return;w(N,"","default",{pendingInputOnly:Z,goalContinuationOnly:_})};return O.get("/",async(N)=>{try{let U=await P.listSessions(),Y=new Set(U.filter((H)=>H.relationType==="subagent").map((H)=>L({sessionId:H.sessionId,projectPath:H.projectPath}))),Q=Array.from(k.values()).filter((H)=>!Y.has(L(v(H)))&&H.relationType!=="subagent").map((H)=>EO(H)),Z=new Set(Q.map((H)=>L({sessionId:H.sessionId,projectPath:H.projectPath}))),T=U.filter((H)=>{if(H.relationType==="subagent")return!1;return!Z.has(L({sessionId:H.sessionId,projectPath:H.projectPath}))}),_=new Set(Z),W=T.filter((H)=>{let B=L({sessionId:H.sessionId,projectPath:H.projectPath});if(_.has(B))return!1;return _.add(B),!0}),K=[...Q,...W];return N.json(K)}catch(U){throw y.error("[SessionRoutes] Failed to list sessions:",U),new d("Failed to list sessions")}}),O.post("/",async(N)=>{try{let U=await N.req.json(),Y=g(Gx,U);if(!Y.success)throw new p("Invalid request body");let{title:Q,projectPath:Z}=Y.data,T=NS("web",12),_=qO(Z||N.get("directory")||m(),Z?"projectPath":"directory"),W=await P.createSessionMetadata(T,_,{title:Q}),K=bO(W,[]),H=v(K);return k.set(L(H),K),E.publish(H,"task.status",{taskStatus:W.taskStatus,updatedAt:W.lastMessageTime}),N.json({...EO(K),status:void 0,agentType:void 0,model:void 0})}catch(U){if(y.error("[SessionRoutes] Failed to create session:",U),U instanceof p)throw U;throw new d("Failed to create session")}}),O.post("/:sessionId/fork",async(N)=>{let U=N.req.param("sessionId");try{CO(U);let Y=await N.req.json(),Q=g(Qx,Y);if(!Q.success)throw new p("Invalid request body");let Z=qO(Q.data.projectPath),T=await P.findSessionMetadata(U,Z);if(!T)throw new f("Session",U);let _=await P.forkSession(U,{sourceProjectPath:T.projectPath,targetProjectPath:T.projectPath}),W=bO(_.metadata,_.messages),K=v(W);return k.set(L(K),W),E.publish(K,"task.status",{taskStatus:_.metadata.taskStatus,..._.metadata.taskCompletedAt?{taskCompletedAt:_.metadata.taskCompletedAt}:{},updatedAt:_.metadata.lastMessageTime}),N.json({session:_.metadata,messages:_.messages},201)}catch(Y){if(Y instanceof p||Y instanceof f||Y instanceof i)throw Y;if(Y instanceof YS)throw new i("Session has no durable creation record");throw y.error("[SessionRoutes] Failed to fork session:",Y),new d("Failed to fork session")}}),O.get("/:sessionId",async(N)=>{let U=N.req.param("sessionId");try{let Y=await l(U,N.req.query("projectPath")),Q=k.get(L(Y));if(Q)return N.json(EO(Q));let Z=await P.findSessionMetadata(Y.sessionId,Y.projectPath);if(!Z)throw new f("Session",U);return N.json(Z)}catch(Y){if(Y instanceof p||Y instanceof f||Y instanceof t)throw Y;throw y.error("[SessionRoutes] Failed to get session:",Y),new d("Failed to get session")}}),O.patch("/:sessionId",async(N)=>{let U=N.req.param("sessionId");try{let Y=await N.req.json(),Q=g(jx,Y);if(!Q.success)throw new p("Invalid request body");if(Q.data.title===void 0)throw new p("title is required");let Z=await l(U,Q.data.projectPath),T=await P.updateSessionMetadata(Z.sessionId,Z.projectPath,{title:Q.data.title}),_=k.get(L(Z));if(_)_.title=T.title??_.title,_.updatedAt=new Date(T.lastMessageTime);return N.json({success:!0,title:T.title})}catch(Y){if(y.error("[SessionRoutes] Failed to update session:",Y),Y instanceof p||Y instanceof f||Y instanceof t)throw Y;throw new d("Failed to update session")}}),O.get("/:sessionId/rewind",async(N)=>{let U=await A(N.req.param("sessionId"),N.req.query("projectPath")),Y=await G(U);return N.json({checkpoints:await Y.listRewindCheckpoints()})}),O.post("/:sessionId/rewind",async(N)=>{let U=g(OS,await N.req.json());if(!U.success)throw new p("Invalid rewind request");let Y=await A(N.req.param("sessionId"),N.req.query("projectPath")),Q=v(Y);return j(Q).runExclusive(async()=>{let Z=Y.currentRunId?F.get(Y.currentRunId):void 0;if(Z&&(Z.status==="running"||Z.status==="waiting_permission"))throw new i("Cannot rewind while a run is active");let T=await G(Y),_;try{_=await T.rewindSession(U.data)}catch(W){if(W instanceof Error&&W.message.startsWith("Cannot rewind while"))throw new i(W.message);throw W}return Y.messages=[..._.messages],Y.updatedAt=new Date,E.publish(Q,"session.rewound",{targetMessageId:_.checkpoint.messageId,mode:_.mode,removedTurns:_.removedTurns,restoredFiles:_.restoredFiles,messages:_.messages}),N.json(_)})}),O.get("/:sessionId/subagents",async(N)=>{let U=await A(N.req.param("sessionId"),N.req.query("projectPath")),Y=await G(U);return N.json({subagents:Y.listSubagents().map(XO)})}),O.post("/:sessionId/subagents/:agentId/resume",async(N)=>{CO(N.req.param("agentId"));let U=SS.safeParse(await N.req.json());if(!U.success)throw new p("Invalid subagent resume request");let Y=await A(N.req.param("sessionId"),N.req.query("projectPath")),Q=v(Y);return j(Q).runExclusive(async()=>{let Z=Y.currentRunId?F.get(Y.currentRunId):void 0;if(Z&&(Z.status==="running"||Z.status==="waiting_permission"))throw new i("Cannot resume a subagent while a parent run is active");let T=await G(Y),_=!1,W,K=(B)=>{E.publish(Q,"subagent.complete",{subagentSessionId:B.id,success:B.status==="completed",status:B.status,summary:B.result?.message?.slice(0,500),resumedFrom:B.resumedFrom,rootAgentId:B.rootAgentId,resumeDepth:B.resumeDepth})},H;try{H=T.resumeSubagent({agentId:N.req.param("agentId"),prompt:U.data.prompt,onEvent:(B,M)=>{_x(Q,M,B)},onCompleted:(B)=>{if(_)K(B);else W=B}})}catch(B){if(B instanceof Error&&(B.message.startsWith("Cannot resume")||B.message.startsWith("Subagent cannot")))throw new i(B.message);if(B instanceof Error&&B.message.startsWith("Subagent not found"))throw new f(B.message);throw B}if(E.publish(Q,"subagent.start",{subagentSessionId:H.session.id,type:H.session.subagentType,description:H.session.description,resumedFrom:H.source.id,rootAgentId:H.session.rootAgentId,resumeDepth:H.session.resumeDepth}),_=!0,W)K(W);return N.json({source:XO(H.source),session:XO(H.session)})})}),O.get("/:sessionId/goal",async(N)=>{let U=await A(N.req.param("sessionId"),N.req.query("projectPath"));return N.json({goal:await new GS(U.projectPath,U.id).get()})}),O.put("/:sessionId/goal",async(N)=>{let U=g(Ux,await N.req.json());if(!U.success)throw new p("Invalid goal request");let Y=await A(N.req.param("sessionId"),N.req.query("projectPath")),Q=v(Y);return j(Q).runExclusive(async()=>{let Z=Y.currentRunId?F.get(Y.currentRunId):void 0;if(Z&&(Z.status==="running"||Z.status==="waiting_permission"))return N.json({status:"rejected",reason:"run_active"},409);let _=await(await G(Y)).createGoal(U.data);E.publish(Q,"goal.updated",{goal:_});let W=U.data.permissionMode??"default",K=w(Y,"",W,{goalContinuationOnly:!0});return N.json({status:"running",runId:K.id,goal:_},202)})}),O.patch("/:sessionId/goal",async(N)=>{let U=g(Zx,await N.req.json());if(!U.success)throw new p("Invalid goal update");let Y=await A(N.req.param("sessionId"),N.req.query("projectPath")),Q=v(Y);return j(Q).runExclusive(async()=>{let Z=await G(Y),T;if(U.data.action==="pause")T=await Z.pauseGoal();else if(U.data.action==="edit")T=await Z.editGoal(U.data.objective);else T=await Z.resumeGoal();if(E.publish(Q,"goal.updated",{goal:T}),T.status==="active"&&(!Y.currentRunId||!["running","waiting_permission"].includes(F.get(Y.currentRunId)?.status??""))){let _=w(Y,"","default",{goalContinuationOnly:!0});return N.json({status:"running",runId:_.id,goal:T},202)}return N.json({status:T.status,goal:T})})}),O.delete("/:sessionId/goal",async(N)=>{let U=await A(N.req.param("sessionId"),N.req.query("projectPath")),Y=v(U),Z=await(await G(U)).clearGoal();if(Z)E.publish(Y,"goal.cleared",{});return N.json({cleared:Z})}),O.delete("/:sessionId",async(N)=>{let U=N.req.param("sessionId"),Y=N.req.query("projectPath");try{let Q=await l(U,Y),Z=L(Q),T=k.get(Z),_=$.get(Z),W;if(T?.currentRunId){let K=F.get(T.currentRunId);if(K)_O(K),await K.completion,W=K.id}if(_)await _.clearGoal().catch((K)=>{y.warn("[SessionRoutes] Failed to clear session goal:",K)});if(await P.deleteSession(Q.sessionId,Q.projectPath),W)F.delete(W);if(k.delete(Z),V.delete(Z),S.delete(Z),J.delete(Z),_){if(await _.dispose(),$.delete(Z),$.size===0)await n.getInstance().disconnectAll()}return N.json({success:!0})}catch(Q){if(y.error("[SessionRoutes] Failed to delete session:",Q),Q instanceof p||Q instanceof f||Q instanceof t)throw Q;throw new d("Failed to delete session")}}),O.get("/:sessionId/message",async(N)=>{let U=N.req.param("sessionId");try{let Y=await l(U,N.req.query("projectPath")),Q=k.get(L(Y)),Z=Q?.messages?Q.messages:await P.loadSession(Y.sessionId,Y.projectPath);return N.json(Z)}catch(Y){if(y.error("[SessionRoutes] Failed to get messages:",Y),Y instanceof p||Y instanceof f||Y instanceof t)throw Y;throw new d("Failed to get messages")}}),O.get("/:sessionId/events",async(N)=>{let U=N.req.param("sessionId"),Y=await l(U,N.req.query("projectPath")),Q=await X(Y);return Nx(N,async(Z)=>{let _,W,K=!1,H=()=>{if(W!==void 0)clearInterval(W),W=void 0;_?.(),_=void 0},B=()=>{if(K)return;K=!0,H()},M=new Set;Z.onAbort(B),_=E.subscribe((z)=>{if(z.sessionId!==Y.sessionId||z.projectPath!==Y.projectPath)return;let c=z.properties.requestId;if((z.type==="permission.asked"||z.type==="question.required")&&typeof c==="string"){if(M.has(c))return;M.add(c)}Z.writeSSE({data:JSON.stringify({type:z.type,properties:{...z.properties,sessionId:z.sessionId,projectPath:z.projectPath}})}).catch(B)});try{if(Z.aborted||K)return;if(await Z.writeSSE({data:JSON.stringify({type:"connected",properties:{sessionId:Y.sessionId,projectPath:Y.projectPath,timestamp:Date.now()}})}).catch((h)=>{throw B(),h}),Z.aborted||K)return;let c=(Q.currentRunId?F.get(Q.currentRunId):void 0)?.pendingPermission;if(c){M.add(c.permissionId);let h=US(c,!0);await Z.writeSSE({data:JSON.stringify({type:h.type,properties:{...h.properties,sessionId:Y.sessionId,projectPath:Y.projectPath}})})}D(Q).catch((h)=>{y.error(`[SessionRoutes] Failed to resume pending input for ${U}:`,h)}),W=setInterval(()=>{if(!Z.aborted)Z.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(B)},15000);while(!Z.aborted&&!K)await new Promise((h)=>setTimeout(h,1000))}finally{B()}})}),O.post("/:sessionId/message",async(N)=>{let U=N.req.param("sessionId"),Y=await N.req.json(),Q=g(Yx,Y);if(!Q.success)throw new p("Invalid message format");let{content:Z,attachments:T,permissionMode:_,projectPath:W}=Q.data,K=_||"default",H=wx(Z,T),B=await A(U,W??N.req.query("projectPath")),M=v(B);return j(M).runExclusive(async()=>{let z=B.currentRunId?F.get(B.currentRunId):void 0;if(z&&(z.status==="running"||z.status==="waiting_permission")){let u=await(await G(B)).enqueueSteering(H,{allowBeforeTurn:!0});if(!u.accepted)return N.json({status:"rejected",reason:u.reason??"turn_unavailable"},409);let xO=u.messageId??NO(12),ZO=u.queued;E.publish(M,"message.created",{messageId:xO,role:"user",content:LO(H)});let KO=u.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(E.publish(M,KO,{runId:z.id,messageId:xO,queued:ZO}),u.delivery==="next_turn"&&z.status!=="running"&&z.status!=="waiting_permission")D(B).catch((kS)=>{y.error(`[SessionRoutes] Failed to wake queued follow-up for ${U}:`,kS)});if(u.delivery==="next_turn")z.pendingFollowUpRequested=!0;return N.json({runId:z.id,messageId:xO,status:u.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:ZO},202)}let h=await(await G(B)).prepareInputTurn(H);if(!h.accepted)return N.json({status:"rejected",reason:h.reason},h.reason==="queue_full"?429:409);let YO=w(B,H,K,{preparedInputTurn:h});return N.json({runId:YO.id,messageId:h.messageId,status:"running"},202)})}),O.post("/:sessionId/abort",async(N)=>{let U=N.req.param("sessionId"),Y=await l(U,N.req.query("projectPath")),Q=k.get(L(Y));if(Q?.currentRunId){let Z=F.get(Q.currentRunId);if(Z)_O(Z),await Z.completion}return N.json({success:!0})}),O.get("/:sessionId/status",async(N)=>{let U=N.req.param("sessionId"),Y=await l(U,N.req.query("projectPath")),Q=k.get(L(Y));if(!Q?.currentRunId)return N.json({sessionId:U,projectPath:Y.projectPath,status:"idle"});let Z=F.get(Q.currentRunId);return N.json({sessionId:U,projectPath:Y.projectPath,runId:Q.currentRunId,status:Z?.status||"idle"})}),O};async function Tx(O,$,S,V,J,j={}){let{abortController:G,sessionId:X,id:A}=O,w=j.preparedInputTurn?.messageId??NO(12),N=j.pendingInputOnly===!0||j.preparedInputTurn?.mode==="pending"||j.goalContinuationOnly===!0?void 0:NO(12),U,Y=v($),Q=(Z,T)=>{E.publish(Y,Z,T)};try{if($.taskStatus="running",$.taskStatusReason=void 0,$.taskStartedAt=new Date().toISOString(),$.taskCompletedAt=void 0,!j.pendingInputOnly&&!j.goalContinuationOnly)Q("message.created",{messageId:w,role:"user",content:LO(S)});if(Q("session.status",{status:"running"}),N)Q("message.created",{messageId:N,role:"assistant",content:""});U=await J($);let Z=U,T=await QS.createWithRuntime(Z,{sessionId:X}),_=async(M)=>{let z=NO(12),c=300000;O.status="waiting_permission";let h=new Promise((xO)=>{let ZO=setTimeout(()=>{y.warn(`[SessionRoutes] Permission ${z} timed out after 300000ms`),Q("permission.timeout",{requestId:z}),xO({approved:!1,reason:"timeout"})},300000);O.pendingPermission={permissionId:z,resolve:(KO)=>{clearTimeout(ZO),xO(KO)},details:M}}),YO=O.pendingPermission;if(!YO)throw Error("Permission request was not registered");let WO=US(YO);Q(WO.type,WO.properties),y.info(`[SessionRoutes] Permission request created: ${z}, runId: ${A}`);let u=await h;if(y.info(`[SessionRoutes] Permission response received: ${z}, approved: ${u.approved}`),!G.signal.aborted)O.status="running";if(O.pendingPermission===YO)O.pendingPermission=void 0;return u},W={messages:[...$.messages],userId:"web-user",sessionId:X,workspaceRoot:$.projectPath,signal:G.signal,permissionMode:V,confirmationHandler:{requestConfirmation:_}},K=()=>{if(!N)N=NO(12),Q("message.created",{messageId:N,role:"assistant",content:""});return N},H=async(M)=>{switch(M.kind){case"content_delta":Q("message.delta",{messageId:K(),delta:M.delta});break;case"thinking_delta":Q("thinking.delta",{delta:M.delta});break;case"tool_start":if("function"in M.toolCall)Q("tool.start",{messageId:K(),toolName:M.toolCall.function.name,toolCallId:M.toolCall.id,arguments:M.toolCall.function.arguments,toolKind:M.toolKind});break;case"tool_result":if("function"in M.toolCall)Q("tool.result",{messageId:K(),toolName:M.toolCall.function.name,toolCallId:M.toolCall.id,success:M.result.success,summary:M.result.metadata?.summary,output:fO(FO(M.toolCall.function.name,M.result)),metadata:ZS(M.result.metadata)});break;case"token_usage":Q("token.usage",{...M.usage});break;case"turn_start":Q("turn.started",{turn:M.turn,maxTurns:M.maxTurns});break;case"steering_applied":Q("steering.applied",{runId:A,messageIds:M.messageIds,count:M.count,recovered:M.recovered,delivery:M.delivery,queued:Z.getPendingSteeringCount()});break;case"follow_up_started":{if(N)Q("message.complete",{messageId:N}),N=void 0;for(let z of M.messages){if(!z.recovered||z.persisted)continue;Q("message.created",{messageId:z.id,role:"user",content:LO(z.content),recovered:!0})}Q("follow_up.started",{runId:A,queued:M.queued,recovered:M.recovered}),K();break}case"goal_updated":Q("goal.updated",{goal:M.goal});break;case"goal_continuation_started":Q("goal.continuation.started",{goal:M.goal,continuation:M.continuation}),K();break;case"compaction":Q(M.phase==="start"?"compaction.started":"compaction.completed",{});break;case"model_fallback":Q("model.fallback",{});break;case"task_update":Q("task.updated",{tasks:M.tasks});break;default:break}},B=await yO(T.chatStream(S,W,{stream:!0,pendingInputOnly:j.pendingInputOnly,preparedInputTurn:j.preparedInputTurn,goalContinuationOnly:j.goalContinuationOnly}),H);if(!B.success)throw Error(B.error?.message??"Agent run failed");for(let M=0;M<20;M++){let z=O.pendingFollowUpRequested===!0;if(O.pendingFollowUpRequested=!1,Z.getPendingSteeringCount()===0){if(!z)break;continue}if(G.signal.aborted)break;if(B=await yO(T.chatStream("",W,{stream:!0,pendingInputOnly:!0}),H),!B.success)throw Error(B.error?.message??"Agent follow-up failed")}if($.messages=[...W.messages],$.updatedAt=new Date,G.signal.aborted||O.status==="cancelled"){$.taskStatus="cancelled",$.taskCompletedAt=new Date().toISOString(),Q("session.status",{status:"idle"});return}if(N)Q("message.complete",{messageId:N});Q("thinking.completed",{}),O.status="completed",$.taskStatus="completed",$.taskCompletedAt=new Date().toISOString(),Q("session.completed",{runId:A,outputTruncated:B.metadata?.outputTruncated??!1}),Q("session.status",{status:"idle"})}catch(Z){if(U&&j.preparedInputTurn)await U.finishTurn(j.preparedInputTurn.handle).catch(()=>{return});if(G.signal.aborted||O.status==="cancelled"){_O(O,"runtime-abort"),$.taskStatus="cancelled",$.taskCompletedAt=new Date().toISOString(),Q("session.status",{status:"idle"});return}y.error("[SessionRoutes] Agent execution error:",Z),O.status="failed",$.taskStatus="failed",$.taskStatusReason="Agent execution failed",$.taskCompletedAt=new Date().toISOString(),Q("session.error",{error:Z instanceof Error?Z.message:"Unknown error"}),Q("session.status",{status:"error"})}}function XS(O,$,S){y.info(`[SessionRoutes] Looking for permission ${$} in session ${O.sessionId}`),y.info(`[SessionRoutes] Active runs: ${F.size}`);for(let[V,J]of F.entries())if(y.info(`[SessionRoutes] Checking run ${V}: sessionId=${J.sessionId}, projectPath=${J.projectPath}, pendingPermission=${J.pendingPermission?.permissionId}`),J.sessionId===O.sessionId&&J.projectPath===O.projectPath&&J.pendingPermission?.permissionId===$)return J.pendingPermission.resolve(S),y.info(`[SessionRoutes] Permission ${$} responded, runId: ${J.id}`),!0;return y.error(`[SessionRoutes] Permission not found: ${$}`),!1}var mO=q("Service"),Bx=x.Object({approved:x.Boolean(),remember:x.Optional(x.Boolean()),scope:x.Optional(C(["once","session","project"])),targetMode:x.Optional(C(["default","autoEdit","plan","yolo"])),feedback:x.Optional(x.String()),answers:x.Optional(x.Record(x.String(),x.Union([x.String(),x.Array(x.String())])))}),_S=()=>{let O=new Mx;return O.post("/:permissionId",async($)=>{let S=$.req.param("permissionId"),V=$.req.query("sessionId"),J=$.req.query("projectPath");mO.info(`[PermissionRoutes] Received permission response: permissionId=${S}, sessionId=${V}`);try{let j=await $.req.json(),G=g(Bx,j);if(!G.success)throw new p("Invalid permission response format");let{approved:X,remember:A,scope:w,targetMode:D,feedback:N,answers:U}=G.data;if(!V)throw new p("sessionId query parameter is required");let Y=await l(V,J);if(!XS(Y,S,{approved:X,reason:N,scope:w,targetMode:D,feedback:N,answers:U}))throw new f("Permission request",S);return mO.info(`[PermissionRoutes] Permission ${S} ${X?"approved":"denied"}`),$.json({success:!0,approved:X,remember:A})}catch(j){if(mO.error("[PermissionRoutes] Failed to respond to permission:",j),j instanceof p||j instanceof t||j instanceof f||j instanceof I)throw j;throw j}}),O};import{Hono as Hx}from"hono";var wS=q("Service"),BS=()=>{let O=new Hx;return O.get("/",async($)=>{try{let S=await TS();return $.json(S)}catch(S){return wS.error("[ProviderRoutes] Failed to list providers:",S),$.json([])}}),O.get("/:provider/models",async($)=>{let S=$.req.param("provider");try{let V=await MS(S);return $.json(V)}catch(V){return wS.error("[ProviderRoutes] Failed to list models:",V),$.json([])}}),O.put("/:provider/credential",async($)=>{let S=$.req.param("provider"),V=await $.req.json();if(!V.apiKey?.trim())throw new p("apiKey is required");return await r().setApiKey(S,V.apiKey.trim()),$.json({success:!0})}),O.delete("/:provider/credential",async($)=>{return await r().clearCredential($.req.param("provider")),$.json({success:!0})}),O};import{Hono as Wx}from"hono";import*as s from"node:fs/promises";import{homedir as Kx}from"node:os";import*as TO from"node:path";var OO=q("Service"),hO=TO.join(Kx(),".blade","skills-config.json");async function WS(){try{let O=await s.readFile(hO,"utf-8");return JSON.parse(O)}catch{return{disabled:[]}}}async function Dx(O){await s.mkdir(TO.dirname(hO),{recursive:!0}),await s.writeFile(hO,JSON.stringify(O,null,2))}async function zx(O,$){let S=await WS();if($)S.disabled=S.disabled.filter((V)=>V!==O);else if(!S.disabled.includes(O))S.disabled.push(O);await Dx(S)}var JO=null,px=300000;async function bx(){if(JO&&Date.now()-JO.timestamp<px)return JO.data;try{let O=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!O.ok)return OO.warn(`GitHub API returned ${O.status}`),JO?.data||[];let $=await O.json(),S=[];for(let V of $){if(V.type!=="dir")continue;let J=`Official ${V.name} skill`;try{let j=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${V.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(j.ok){let X=(await j.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(X)J=X[1].trim().slice(0,100)}}catch{}S.push({name:V.name,description:J,tag:"Official",author:"Anthropic"})}return JO={data:S,timestamp:Date.now()},S}catch(O){return OO.warn("Failed to fetch skills catalog from GitHub:",O),JO?.data||[]}}var KS=()=>{let O=new Wx;return O.get("/",async($)=>{try{let S=wO();await S.initialize();let V=S.getAll(),J=await WS(),j=V.map((G)=>({id:G.name,name:G.name,enabled:!J.disabled.includes(G.name),description:G.description||"",version:G.version||"1.0.0",provider:"Local",location:G.source==="builtin"?"Built-in":G.basePath,capabilities:["prompts"],allowedTools:G.allowedTools||[]}));return $.json(j)}catch(S){return OO.error("[SkillsRoutes] Failed to get skills:",S),$.json([])}}),O.post("/:name/toggle",async($)=>{try{let S=$.req.param("name"),V=await $.req.json();return await zx(S,V.enabled),$.json({success:!0,enabled:V.enabled})}catch(S){return OO.error("[SkillsRoutes] Failed to toggle skill:",S),$.json({success:!1,error:S.message},500)}}),O.delete("/:name",async($)=>{try{let S=$.req.param("name"),V=`${process.env.HOME}/.blade/skills/${S}`;return await s.rm(V,{recursive:!0,force:!0}),await wO().refresh(),$.json({success:!0})}catch(S){return OO.error("[SkillsRoutes] Failed to uninstall skill:",S),$.json({success:!1,error:S.message},500)}}),O.post("/install",async($)=>{try{let S=await $.req.json(),V=HS(),J=wO(),j=!1;if(S.source==="catalog"&&S.name){if(j=await V.installOfficialSkill(S.name),!j)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(S.source==="repo"&&S.url){if(j=await V.installFromRepo(S.url,S.name),!j)return $.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(S.source==="local"&&S.path){if(j=await V.installFromLocal(S.path,S.name),!j)return $.json({success:!1,error:"Failed to install skill from local path. Make sure the path exists and contains a SKILL.md file."},500)}else return $.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await J.refresh(),$.json({success:!0})}catch(S){return OO.error("[SkillsRoutes] Failed to install skill:",S),$.json({success:!1,error:S.message},500)}}),O.get("/catalog",async($)=>{try{let S=await bx();return $.json(S)}catch(S){return OO.error("[SkillsRoutes] Failed to get catalog:",S),$.json([])}}),O};import Ex from"fast-glob";import{Hono as yx}from"hono";import{execSync as qx}from"node:child_process";import{readdir as Cx}from"node:fs/promises";import MO from"node:path";var UO=q("Service"),Lx=(O)=>{try{return qx("git rev-parse --abbrev-ref HEAD",{cwd:O,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},Fx=[...BO.map((O)=>`${O}/**`),...BO,...kO.map((O)=>`**/${O}`)],fx=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),pS=()=>{let O=new yx;return O.get("/commands",async($)=>{try{let S=$.req.query("q")||"",V=zS(S).filter((J)=>!fx.has(J.command));return $.json(V)}catch(S){return UO.error("[SuggestionsRoutes] Failed to get command suggestions:",S),$.json([])}}),O.get("/files",async($)=>{try{let S=$.req.query("q")||"",V=$.get("directory")||m(),J=Math.min(Number($.req.query("limit"))||100,1000),G=(await Ex("**/*",{cwd:V,dot:!1,followSymbolicLinks:!1,onlyFiles:!1,markDirectories:!0,unique:!0,ignore:Fx})).map((w)=>w.replace(/\\/g,"/"));if(!S)return $.json(G.slice(0,J));let X=S.toLowerCase(),A=G.filter((w)=>w.toLowerCase().includes(X)).slice(0,J);return $.json(A)}catch(S){return UO.error("[SuggestionsRoutes] Failed to get file suggestions:",S),$.json([])}}),O.get("/files/tree",async($)=>{try{let S=$.get("directory")||m(),V=$.req.query("path")||"",J=V?MO.join(S,V):S,G=(await Cx(J,{withFileTypes:!0})).map((w)=>({name:w.name,path:V?`${V}/${w.name}`:w.name,type:w.isDirectory()?"dir":"file"}));G.sort((w,D)=>{if(w.type!==D.type)return w.type==="dir"?-1:1;return w.name.localeCompare(D.name)});let X=new Set(BO),A=G.filter((w)=>{let D=w.name;if(D.startsWith("."))return!1;if(X.has(D))return!1;for(let N of kO)if(D.match(new RegExp(N.replace("*",".*"))))return!1;return!0});return $.json(A)}catch(S){return UO.error("[SuggestionsRoutes] Failed to get file tree:",S),$.json([])}}),O.get("/files/content",async($)=>{try{let S=$.req.query("path");if(!S)return $.json({error:"Missing file path"},400);let V=$.get("directory")||m(),J=MO.resolve(V,S),j=MO.relative(V,J);if(j.startsWith("..")||MO.isAbsolute(j))return $.json({error:"Invalid file path"},400);let G=DS(),X=await G.stat(J);if(!X?.isFile)return $.json({error:"File not found"},404);let A=200000,w=await G.readTextFile(J),D=w.length>A;return $.json({path:S,content:D?w.slice(0,A):w,truncated:D,size:X.size})}catch(S){return UO.error("[SuggestionsRoutes] Failed to get file content:",S),$.json({error:"Failed to read file"},500)}}),O.get("/git-info",async($)=>{try{let S=$.get("directory")||m(),V=Lx(S);return $.json({branch:V})}catch(S){return UO.error("[SuggestionsRoutes] Failed to get git info:",S),$.json({branch:null})}}),O};import{Hono as mx}from"hono";var e=q("Service"),GO=new Map,bS=2097152,ES=65536;function yS(){return typeof globalThis.Bun<"u"}async function hx(O,$,S){if(yS()){let{spawn:j}=await import("bun-pty"),G=j(O,$,{name:"xterm-256color",cwd:S.cwd,env:S.env});return{pid:G.pid,write:(X)=>G.write(X),resize:(X,A)=>G.resize(X,A),kill:()=>G.kill(),onData:(X)=>G.onData(X),onExit:(X)=>G.onExit(X)}}let J=(await import("node-pty")).spawn(O,$,{name:"xterm-256color",cwd:S.cwd,env:S.env,cols:80,rows:24});return{pid:J.pid,write:(j)=>J.write(j),resize:(j,G)=>J.resize(j,G),kill:()=>J.kill(),onData:(j)=>{J.onData(j)},onExit:(j)=>{J.onExit(j)}}}var IO=void 0,RO;if(yS())try{let{createBunWebSocket:O}=await import("hono/bun"),$=O();RO=$.upgradeWebSocket,IO=$.websocket}catch(O){e.warn("[Terminal] Failed to initialize Bun WebSocket support:",O)}async function qS(O,$){let S=`term-${Date.now()}`;e.info(`[Terminal] New connection: ${S}, cwd: ${O}`);let V=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",J=V.endsWith("sh")?["-l"]:[],j=await hx(V,J,{cwd:O,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),G={id:S,process:j,cwd:O,buffer:"",subscribers:new Set};if(GO.set(S,G),G.subscribers.add($),j.onData((X)=>{let A=!1;for(let w of G.subscribers)try{w.send(X),A=!0}catch{G.subscribers.delete(w)}if(A)return;if(G.buffer+=X,G.buffer.length>bS)G.buffer=G.buffer.slice(-bS)}),j.onExit(({exitCode:X})=>{e.info(`[Terminal] Process exited: ${S}, code: ${X}`);for(let A of G.subscribers)try{A.close()}catch{}GO.delete(S)}),G.buffer){let X=G.buffer;G.buffer="";for(let A=0;A<X.length;A+=ES)$.send(X.slice(A,A+ES))}return{session:G,cleanup:()=>{if(e.info(`[Terminal] Connection closed: ${S}`),G.subscribers.delete($),G.subscribers.size===0){try{G.process.kill()}catch{}GO.delete(S)}}}}function CS(O,$){O.on("connection",async(S,V)=>{let J=new URL(V.url||"/",`http://${V.headers.host}`);if(!J.pathname.endsWith("/terminal/ws")){S.close();return}let j=J.searchParams.get("cwd")||$()||m();try{let{session:G,cleanup:X}=await qS(j,{send:(A)=>S.send(A),close:()=>S.close()});S.on("message",(A)=>{try{G.process.write(String(A))}catch(w){e.error("[Terminal] Failed to write to PTY:",w)}}),S.on("close",X),S.on("error",X)}catch(G){e.error("[Terminal] Failed to spawn PTY:",G),S.close()}})}var LS=()=>{let O=new mx;if(O.get("/status",($)=>{let S=Array.from(GO.values()).map((V)=>({id:V.id,cwd:V.cwd}));return $.json({active:S.length,terminals:S})}),O.post("/kill/:terminalId",($)=>{let S=$.req.param("terminalId"),V=GO.get(S);if(V){try{V.process.kill()}catch{}for(let J of V.subscribers)J.close();return GO.delete(S),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),RO)O.get("/ws",RO(($)=>{let S=$.req.query("cwd")||$.get("directory")||m(),V;return{async onOpen(J,j){try{V=await qS(S,{send:(G)=>j.send(G),close:()=>j.close()})}catch(G){e.error("[Terminal] Failed to spawn PTY:",G),j.close()}},onMessage(J){if(!V)return;try{V.session.process.write(String(J.data))}catch(j){e.error("[Terminal] Failed to write to PTY:",j)}},onClose(){V?.cleanup()}}}));else O.get("/ws",($)=>{return $.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return O};var R=q("Service"),gO=[];function lx(){let O=Rx(gx(import.meta.url)),$=[SO(O,"web"),SO(m(),"dist/web"),SO(m(),"packages/cli/dist/web")];for(let S of $){let V=SO(S,"index.html");if(mS(V)){if(HO(V,"utf-8").includes("/assets/"))return R.debug(`[Server] Found web dist at: ${S}`),S}}return null}function cx(){let O=new vx;O.onError((S,V)=>{if(R.error("[Server] Request error:",S),S instanceof I)return V.json(S.toObject(),S.statusCode);let J=S instanceof Error?S.message:String(S);return V.json({error:{code:"INTERNAL_ERROR",message:J}},500)}),O.use(async(S,V)=>{let J=process.env.BLADE_SERVER_PASSWORD;if(!J)return V();let j=S.req.path;if(j==="/"||j.startsWith("/assets/")||j.endsWith(".html")||j.endsWith(".js")||j.endsWith(".css"))return V();let G=S.req.header("Authorization");if(!G?.startsWith("Basic "))return S.header("WWW-Authenticate",'Basic realm="Blade Server"'),S.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let X=Buffer.from(G.slice(6),"base64").toString(),[A,w]=X.split(":"),D=process.env.BLADE_SERVER_USERNAME??"blade";if(A!==D||w!==J)return S.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return V()}),O.use(async(S,V)=>{let J=S.req.path==="/health"||S.req.path==="/global/health"||S.req.path.startsWith("/assets/");if(!J)R.debug(`[Server] ${S.req.method} ${S.req.path}`);let j=Date.now();if(await V(),!J){let G=Date.now()-j;R.debug(`[Server] ${S.req.method} ${S.req.path} - ${S.res.status} (${G}ms)`)}}),O.use(ux({origin(S){if(!S)return;if(S.startsWith("http://localhost:"))return S;if(S.startsWith("http://127.0.0.1:"))return S;if(S==="tauri://localhost"||S==="http://tauri.localhost")return S;if(gO.includes(S))return S;return}})),O.use(async(S,V)=>{let J=S.req.query("directory")||S.req.header("x-blade-directory")||m();try{J=decodeURIComponent(J)}catch{}return S.set("directory",J),V()}),O.route("/global",tO()),O.route("/events",uO()),O.route("/sessions",AS()),O.route("/configs",vO()),O.route("/permissions",_S()),O.route("/providers",BS()),O.route("/models",oO()),O.route("/suggestions",pS()),O.route("/terminal",LS()),O.route("/mcp",lO()),O.route("/skills",KS()),O.get("/health",(S)=>{return S.json({healthy:!0,version:VO()})});let $=lx();if($)R.info(`[Server] Serving static files from ${$}`),O.get("/assets/*",(S)=>{let V=SO($,S.req.path);if(!mS(V))return S.json({error:{code:"NOT_FOUND",message:`File not found: ${S.req.path}`}},404);let J=HO(V),j=Ix(V).toLowerCase(),X={".js":"application/javascript",".css":"text/css",".html":"text/html",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject"}[j]||"application/octet-stream";return new Response(J,{headers:{"Content-Type":X,"Cache-Control":"public, max-age=31536000, immutable"}})}),O.get("/",(S)=>{let V=SO($,"index.html"),J=HO(V,"utf-8");return S.html(J)}),O.get("*",(S)=>{let V=S.req.path;if(V.includes("."))return S.json({error:{code:"NOT_FOUND",message:`File not found: ${V}`}},404);let J=SO($,"index.html"),j=HO(J,"utf-8");return S.html(j)});else R.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),O.get("/",(S)=>{return S.json({message:"Blade API Server",version:VO(),webUI:!1,hint:'Web UI not built. Run "cd packages/cli/web && bun run build" to enable.',endpoints:{health:"/health",sessions:"/sessions",configs:"/configs",permissions:"/permissions",providers:"/providers"}})}),O.all("*",(S)=>{return S.json({error:{code:"NOT_FOUND",message:`Route not found: ${S.req.path}`}},404)});return O}function dx(){let O=Px(),$=[];for(let S of Object.keys(O)){let V=O[S];if(!V)continue;for(let J of V){if(J.internal||J.family!=="IPv4")continue;if(J.address.startsWith("172."))continue;$.push(J.address)}}return $}function FS(){return typeof globalThis.Bun<"u"}function fS(O,$){let S=globalThis.Bun,V=(j)=>{try{return S.serve({hostname:$.hostname,port:j,fetch:O.fetch,idleTimeout:0,websocket:IO})}catch(G){R.error("Failed to start Bun server:",G);return}},J=$.port===0?V(4096)??V(0):V($.port);if(!J)throw Error(`Failed to start Bun server on port ${$.port}`);return{url:J.url,port:J.port,hostname:J.hostname,stop:async()=>{J.stop(!0)}}}function ax(O,$){return new Promise((S,V)=>{let J=kx(async(w,D)=>{let N=new URL(w.url||"/",`http://${w.headers.host}`),U=new Headers;for(let[Z,T]of Object.entries(w.headers))if(T)if(Array.isArray(T))for(let _ of T)U.append(Z,_);else U.set(Z,T);let Y;if(w.method!=="GET"&&w.method!=="HEAD")Y=(await new Promise((T)=>{let _=[];w.on("data",(W)=>_.push(W)),w.on("end",()=>T(Buffer.concat(_)))})).toString();let Q=new Request(N.toString(),{method:w.method,headers:U,body:Y});try{let Z=await O.fetch(Q);if(D.statusCode=Z.status,Z.headers.forEach((T,_)=>{D.setHeader(_,T)}),Z.body){let T=Z.body.getReader(),_=async()=>{let{done:W,value:K}=await T.read();if(W){D.end();return}return D.write(K),_()};await _()}else{let T=await Z.text();D.end(T)}}catch(Z){R.error("[Server] Node request error:",Z),D.statusCode=500,D.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),j=new tx({noServer:!0}),G=m();CS(j,()=>G),J.on("upgrade",(w,D,N)=>{if(new URL(w.url||"/",`http://${w.headers.host}`).pathname==="/terminal/ws")j.handleUpgrade(w,D,N,(Y)=>{j.emit("connection",Y,w)});else D.destroy()});let X=(w)=>{return new Promise((D,N)=>{J.once("error",(U)=>{if(U.code==="EADDRINUSE")N(U);else N(U)}),J.listen(w,$.hostname,()=>{let U=J.address();if(U&&typeof U==="object")D(U.port);else D(w)})})};(async()=>{let w;if($.port===0)try{w=await X(4096)}catch{w=await X(0)}else w=await X($.port);let D=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${w}`);S({url:D,port:w,hostname:$.hostname,stop:async()=>{return new Promise((N)=>{j.close(()=>{J.close(()=>N())})})}})})().catch(V)})}var hS;((M$)=>{let O,$;function S(){if(!$)$=cx();return $}M$.getApp=S;function V(G){gO=G.cors??[];let X=S();if(FS())O=fS(X,G),R.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else throw Error("Blade web server requires Bun runtime. Please run with Bun: `bun run blade web` or install Bun from https://bun.sh");let A=O;return{url:A.url,port:A.port,hostname:A.hostname,stop:async()=>{if(O)await O.stop(),O=void 0,$=void 0,R.info("[Server] Blade server stopped")}}}M$.listen=V;async function J(G){gO=G.cors??[];let X=S();if(FS())O=fS(X,G),R.info(`[Server] Blade server listening on ${O.url} (Bun runtime)`);else O=await ax(X,G),R.info(`[Server] Blade server listening on ${O.url} (Node.js runtime)`);let A=O;return{url:A.url,port:A.port,hostname:A.hostname,stop:async()=>{if(O)await O.stop(),O=void 0,$=void 0,R.info("[Server] Blade server stopped")}}}M$.listenAsync=J;function j(){return O!==void 0}M$.isRunning=j})(hS||={});export{ox as a,ix as b,dx as c,hS as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ja as a,Ka as b,La as c,Ma as d,Na as e,Oa as f}from"./chunk-
|
|
1
|
+
import{Ja as a,Ka as b,La as c,Ma as d,Na as e,Oa as f}from"./chunk-pdydx73a.js";import"./chunk-dr06x0cw.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{ca as O}from"./chunk-
|
|
1
|
+
import{ca as O}from"./chunk-k47ssv3b.js";import{Aa as J,Ca as L}from"./chunk-tv4r86ez.js";import"./chunk-qwdbqjh7.js";import"./chunk-pdydx73a.js";import"./chunk-9xkjb87h.js";import"./chunk-ctqf59q1.js";import"./chunk-jt62ctz7.js";import{Ib as H}from"./chunk-gsfkrr25.js";import"./chunk-34pdtz4q.js";import"./chunk-hjx5n3dw.js";import"./chunk-dr06x0cw.js";import P from"os";import E from"path";function _(q){return typeof q==="string"?q:void 0}function T(q){if(!Array.isArray(q))return;let z=[];for(let F of q)if(typeof F==="string")z.push(F);else if(F!=null)z.push(String(F));return z}function G(){console.log(`
|
|
2
2
|
blade mcp
|
|
3
3
|
`),console.log(`管理 MCP 服务器
|
|
4
4
|
`),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e={name:"blade-code",version:"0.8.
|
|
1
|
+
var e={name:"blade-code",version:"0.8.1",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.17.0","bun-pty":"^0.4.8","node-pty":"1.0.0"},dependencies:{"@agentclientprotocol/sdk":"^0.12.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.83.0","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.17.4",ahooks:"^3.9.6","ansi-escapes":"^7.2.0","async-mutex":"^0.5.0",axios:"^1.12.2",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.1.0","gray-matter":"^4.0.3",hono:"^4.7.10",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.17.21",lowlight:"^3.3.0","lru-cache":"^11.2.4",nanoid:"^5.1.6",open:"^10.1.2",openai:"^6.2.0",picomatch:"^4.0.3",react:"^19.1.1","react-dom":"^19.1.1",semver:"^7.7.3","string-width":"^8.1.0",undici:"^7.16.0","write-file-atomic":"^7.0.0",ws:"^8.18.0",yaml:"^2.8.1",yargs:"^18.0.0",typebox:"1.3.7",zustand:"^5.0.9"},devDependencies:{"@biomejs/biome":"^2.2.4","@types/bun":"^1.3.4","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.2","@types/react":"^19.1.1","@types/react-dom":"^19.1.1","@types/semver":"^7.7.1","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.5.12","@types/yargs":"^17.0.33","@vitest/coverage-v8":"^3.0.0",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^3.0.0"}};function r(){return{name:e.name,version:e.version,description:e.description}}function n(){return e.version}function o(){return e.name}function c(){return e.description}function d(){return`v${e.version}`}function a(){return`v${e.version} © 2025 Blade Code`}
|
|
2
2
|
export{r as Ja,n as Ka,o as La,c as Ma,d as Na,a as Oa};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{L as m,T as g,U as c,X as d,Z as f}from"./chunk-04920kz2.js";import{Ib as u}from"./chunk-gsfkrr25.js";async function R(){if((await g().initialize(u(),[])).plugins.length>0)await c()}async function x(t){let e=t.message||t._?.[0];if(typeof e==="string"&&e.trim())return e;let n=t.stdin??process.stdin;if(!n.isTTY){let a=[];for await(let l of n)a.push(l);return Buffer.concat(a).toString("utf-8").trim()}if(t.defaultMessage!==void 0)return t.defaultMessage;throw Error("No input provided")}async function P(t){if(!d(t))return{mode:"agent",content:t};let e=await f(t,{cwd:u(),workspaceRoot:u()});if(!e.success)return{mode:"output",content:`Error: ${e.error||"未知错误"}`,exitCode:1};let n=e.data;if(n?.action==="invoke_skill"){let{skillName:a,skillArgs:l}=n;return{mode:"agent",content:l?`Please use the "${a}" skill to help me with: ${l}`:`Please use the "${a}" skill.`}}if(n?.action==="invoke_custom_command"||n?.action==="invoke_plugin_command"){let a=n.processedContent;return{mode:"agent",content:`# Custom Command: /${n.commandName}
|
|
2
2
|
|
|
3
3
|
${a}`}}return{mode:"output",content:e.content||e.message||"",exitCode:0}}function r(t){if(!(t instanceof Error))return!1;return t.message.includes("未找到会话")||t.message.includes("ENOENT")||t.message.includes("no such file")}async function i(t){try{return await m.loadSession(t,u())}catch(e){if(r(e))return null;throw e}}async function y(t){if(t.resume===!0||t.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof t.resume==="string"&&t.resume.length>0){if(t.forkSession){let e=u();return m.forkSession(t.resume,{newSessionId:t.sessionId,sourceProjectPath:e,targetProjectPath:e})}return{sessionId:t.resume,messages:await m.loadSession(t.resume)}}if(t.continue){let e=t.forkSession?await m.listSessions({cwd:u()}):await m.listSessions();if(e.length>0){let n=e[0].sessionId;if(t.forkSession){let a=u();return m.forkSession(n,{newSessionId:t.sessionId,sourceProjectPath:a,targetProjectPath:a})}return{sessionId:n,messages:await m.loadSession(n)}}if(t.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(t.sessionId)return{sessionId:t.sessionId,messages:await i(t.sessionId)??[]};return{sessionId:`${t.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
|
|
4
4
|
export{R as p,x as q,P as r,y as s};
|