blade-code 0.8.1 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-ctqf59q1.js → chunk-1m63zddw.js} +1 -1
  3. package/dist/chunk-23h9grdr.js +1 -0
  4. package/dist/{chunk-k47ssv3b.js → chunk-2c69g6t9.js} +2 -2
  5. package/dist/{chunk-9xkjb87h.js → chunk-5sccs44n.js} +1 -1
  6. package/dist/{chunk-kawv31m3.js → chunk-5yt80bn2.js} +1 -1
  7. package/dist/chunk-6msfa7jh.js +9 -0
  8. package/dist/chunk-6spmzx13.js +6 -0
  9. package/dist/chunk-724djh7r.js +1 -0
  10. package/dist/{chunk-jt62ctz7.js → chunk-7bqkkjxf.js} +1 -1
  11. package/dist/chunk-804j7say.js +1 -0
  12. package/dist/chunk-8yk5w2ks.js +1 -0
  13. package/dist/chunk-97qxd4yb.js +2 -0
  14. package/dist/chunk-9cr3jexy.js +2 -0
  15. package/dist/{chunk-9ad7tt9s.js → chunk-ar5564sf.js} +1 -1
  16. package/dist/{chunk-49g067ek.js → chunk-b922cq7k.js} +3 -3
  17. package/dist/{chunk-dr06x0cw.js → chunk-be7qz4cv.js} +1 -1
  18. package/dist/chunk-bqhghfmt.js +6 -0
  19. package/dist/{chunk-wmes2tt9.js → chunk-crbh6x86.js} +1 -1
  20. package/dist/{chunk-0dj326ms.js → chunk-d7nrqg5b.js} +2 -2
  21. package/dist/{chunk-34pdtz4q.js → chunk-eyypmc9m.js} +2 -2
  22. package/dist/{chunk-61952mn3.js → chunk-fma9cbq5.js} +1 -1
  23. package/dist/chunk-ghf5tgjr.js +1 -0
  24. package/dist/{chunk-d4ex0qvs.js → chunk-hqtskyc1.js} +2 -2
  25. package/dist/chunk-jc7k8pfn.js +22 -0
  26. package/dist/chunk-kf43f8sy.js +1577 -0
  27. package/dist/{chunk-gsfkrr25.js → chunk-kjc2aqww.js} +1 -1
  28. package/dist/chunk-kjddt9xy.js +1 -0
  29. package/dist/{chunk-1pt090dg.js → chunk-m0ded6ky.js} +27 -27
  30. package/dist/{chunk-bm8vwfez.js → chunk-mqqajem9.js} +2 -2
  31. package/dist/{chunk-06h100e2.js → chunk-msr67f6q.js} +1 -1
  32. package/dist/{chunk-x6gt63vz.js → chunk-mvww9cmc.js} +32 -32
  33. package/dist/{chunk-neenhtxw.js → chunk-nbpjzzrg.js} +1 -1
  34. package/dist/chunk-ncvr73ev.js +1 -0
  35. package/dist/{chunk-yhpm9azy.js → chunk-qvtahmff.js} +1 -1
  36. package/dist/chunk-qwn46cd6.js +2 -0
  37. package/dist/{chunk-pdydx73a.js → chunk-sva5bdgz.js} +2 -2
  38. package/dist/{chunk-twem6p0g.js → chunk-t9cqscfq.js} +2 -2
  39. package/dist/chunk-tzr992v4.js +1 -0
  40. package/dist/{chunk-xhnyy54e.js → chunk-vxpdjtqc.js} +1 -1
  41. package/dist/{chunk-1smf2dj3.js → chunk-wcf80p9y.js} +1 -1
  42. package/dist/chunk-x8xfx9nv.js +1 -0
  43. package/dist/{chunk-tv4r86ez.js → chunk-yewg510f.js} +2 -2
  44. package/dist/{chunk-sr3bzb95.js → chunk-zj3q4btp.js} +2 -2
  45. package/dist/chunk-zjks0ncc.js +6 -0
  46. package/dist/{chunk-hjx5n3dw.js → chunk-zsyff0ky.js} +2 -2
  47. package/dist/web/assets/FilePreview-B5g8yi8d.js +7 -0
  48. package/dist/web/assets/{MarkdownRenderer-JJScfgAO.js → MarkdownRenderer-qBCxzEb_.js} +1 -1
  49. package/dist/web/assets/{McpModal-CiCuIUxC.js → McpModal-C7y2Fsqc.js} +2 -2
  50. package/dist/web/assets/{SettingsModal-Bew818xl.js → SettingsModal-Dmc7Dw_E.js} +1 -1
  51. package/dist/web/assets/{SettingsStore-B_4zN-c-.js → SettingsStore-BfoB9tNV.js} +1 -1
  52. package/dist/web/assets/{SkillsModal-Cot4Rb89.js → SkillsModal-CqFAIfj5.js} +1 -1
  53. package/dist/web/assets/{TerminalPanel-DxB67ObY.js → TerminalPanel-EHh8-9b9.js} +1 -1
  54. package/dist/web/assets/index-B-BRpW1c.js +16 -0
  55. package/dist/web/assets/index-Ch0eqSLM.css +1 -0
  56. package/dist/web/assets/{vendor-icons-DqO8ishN.js → vendor-icons-DBM55KTG.js} +70 -40
  57. package/dist/web/index.html +2 -2
  58. package/package.json +1 -1
  59. package/dist/chunk-04920kz2.js +0 -1570
  60. package/dist/chunk-07jvw0kn.js +0 -1
  61. package/dist/chunk-14erxdhd.js +0 -1
  62. package/dist/chunk-42ch5zg4.js +0 -1
  63. package/dist/chunk-6yqzfz8t.js +0 -2
  64. package/dist/chunk-7j6rxyt8.js +0 -9
  65. package/dist/chunk-a12tmmfr.js +0 -1
  66. package/dist/chunk-cnftrx3g.js +0 -1
  67. package/dist/chunk-epp5jx5f.js +0 -6
  68. package/dist/chunk-j39q2kx7.js +0 -1
  69. package/dist/chunk-j6hpzkpq.js +0 -6
  70. package/dist/chunk-n4f8tseg.js +0 -2
  71. package/dist/chunk-nc4kfwef.js +0 -1
  72. package/dist/chunk-qwdbqjh7.js +0 -22
  73. package/dist/chunk-syj3anec.js +0 -6
  74. package/dist/chunk-v3ctg84r.js +0 -1
  75. package/dist/chunk-v5rn5r1h.js +0 -1
  76. package/dist/web/assets/FilePreview-Chqi7chf.js +0 -7
  77. package/dist/web/assets/index-B-b3Yc5H.css +0 -1
  78. package/dist/web/assets/index-B3dW1Scg.js +0 -16
@@ -1 +0,0 @@
1
- import{$a as e,Wa as a,Xa as b,Za as c,_a as d,ab as f,bb as g,cb as h,db as i,eb as j,fb as k,gb as l,hb as m,ib as n,jb as o,mb as p,nb as q,ob as r}from"./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";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,l as handleTaskListUpdate,m as handleSkillActivation,n as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,o as applyToolDomainEffects,p as StreamingToolExecutor,e as ConversationState};
@@ -1 +0,0 @@
1
- import{v as a,w as b,x as c}from"./chunk-syj3anec.js";import"./chunk-twem6p0g.js";import"./chunk-9ad7tt9s.js";import"./chunk-tv4r86ez.js";import"./chunk-qwdbqjh7.js";import"./chunk-ctqf59q1.js";import"./chunk-jt62ctz7.js";import"./chunk-gsfkrr25.js";import"./chunk-34pdtz4q.js";import"./chunk-hjx5n3dw.js";import"./chunk-dr06x0cw.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -1 +0,0 @@
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,2 +0,0 @@
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
- export{q as t,w as u};
@@ -1,9 +0,0 @@
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 +0,0 @@
1
- import{Ha as a,Ia as b}from"./chunk-d4ex0qvs.js";import"./chunk-hjx5n3dw.js";import"./chunk-dr06x0cw.js";export{a as resolveModelConfig,b as getModelDisplayName};
@@ -1 +0,0 @@
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,6 +0,0 @@
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
- `);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
- `);else if(k.outputFormat==="stream-json")F.stdout.write(`${JSON.stringify({type:"response",content:H})}
4
- `);else F.stdout.write(`${H}
5
- `);return 0}catch(J){return F.stderr.write(`Error: ${J instanceof Error?J.message:"未知错误"}
6
- `),1}finally{await q?.dispose()}}async function d(){if(process.argv.slice(2).findIndex((q)=>q==="--print"||q==="-p")===-1)return!1;try{let{print:q,"output-format":J,"include-partial-messages":G,"input-format":Q,"system-prompt":K,"append-system-prompt":U,"max-turns":V,...W}=D,H=h(R(process.argv)).scriptName("blade").strict(!1).options(W).middleware([_,L,x]);return M(H),await H.parse(),!0}catch(q){console.error(`Print mode error: ${q instanceof Error?q.message:"未知错误"}`),process.exit(1)}}export{O as runPrint,d as handlePrintMode};
@@ -1 +0,0 @@
1
- import{Aa as k,Ba as l,Ca as m,qa as a,ra as b,sa as c,ta as d,ua as e,va as f,wa as g,xa as h,ya as i,za as j}from"./chunk-tv4r86ez.js";import"./chunk-qwdbqjh7.js";import"./chunk-jt62ctz7.js";import"./chunk-gsfkrr25.js";import"./chunk-34pdtz4q.js";import"./chunk-hjx5n3dw.js";import"./chunk-dr06x0cw.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,h as getAllModels,g as ensureStoreInitialized,m as configActions,d as appActions};
@@ -1,6 +0,0 @@
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
- `)}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
- `)};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
- `);if(Q)Y.stdout.write(`
5
- `)},content(Q){if($==="jsonl"){B("content",{content:Q});return}b(Y.stdout,Q)},toolStart(Q,Z,D,U){if($==="jsonl"){B("tool_start",{tool_name:Q,summary:Z,target:D,tool_kind:U});return}b(Y.stderr,`[tool:start] ${Z}`)},toolResult(Q,Z,D,U,_){if($==="jsonl"){B("tool_result",{tool_name:Q,summary:Z,target:D,tool_kind:U,success:_?.success,error_type:_?.errorType,error_message:_?.errorMessage});return}b(Y.stderr,`[tool:result] ${Z}`)},phase(Q,Z,D,U={}){if($==="jsonl"){B("phase",{phase:Q,status:Z,message:D,turn:U.turn,tool_name:U.toolName,target:U.target});return}b(Y.stderr,`[phase:${Q}] ${D}`)},toolDetail(Q,Z){if($==="jsonl"){B("tool_detail",{tool_name:Q,detail:Z});return}b(Y.stderr,Z)},taskUpdate(Q){if($==="jsonl"){B("task_update",{tasks:Q});return}for(let Z of Q)b(Y.stderr,xq(Z))},subagent(Q){let Z=Q.kind==="subagent_spawned";if($==="jsonl"){B("subagent",{state:Z?"spawned":"completed",session_id:Q.sessionId,subagent_type:Z?Q.type:void 0,success:Z?void 0:Q.success,summary:Z?void 0:Q.summary,resumed_from:Q.resumedFrom,root_agent_id:Q.rootAgentId,resume_depth:Q.resumeDepth});return}b(Y.stderr,`[subagent:${Z?"spawned":"completed"}] ${Q.sessionId}${Q.resumedFrom?` resumed from ${Q.resumedFrom}`:""}`)},tokenUsage(Q){if($==="jsonl"){B("token_usage",{input_tokens:Q.inputTokens,output_tokens:Q.outputTokens,total_tokens:Q.totalTokens,max_context_tokens:Q.maxContextTokens,cache_read_tokens:Q.cacheReadTokens,cache_write_tokens:Q.cacheWriteTokens,cost_usd:Q.costUsd});return}b(Y.stderr,`[tokens] in=${Q.inputTokens} out=${Q.outputTokens} total=${Q.totalTokens} / ${Q.maxContextTokens}`)},compacting(Q){if($==="jsonl"){B("compacting",{state:Q?"started":"completed"});return}b(Y.stderr,Q?"[context] compacting started":"[context] compacting completed")},turnLimit(Q){if($==="jsonl"){B("turn_limit",{turns_count:Q,action:"continue"});return}b(Y.stderr,`[turn-limit] continuing after ${Q} turns`)},output(Q,Z=0){if($==="jsonl"){B("output",{content:Q,exit_code:Z});return}b(Z===0?Y.stdout:Y.stderr,Q)},error(Q){if($==="jsonl"){B("error",{message:Q});return}b(Y.stderr,Q)}}}async function Fq(Y,$={stdout:process.stdout,stderr:process.stderr},B){let Q="text",Z=w($,Q),D=new n,U={targetLocked:!1},_,A=jq(B);try{let X=Pq(Y);Q=kq(X.outputFormat),Z=w($,Q),await p();let o=await i(X),M=await s(o);if(M.mode==="output"){if(M.content)Z.output(M.content,M.exitCode??0);return M.exitCode??0}let L=X.permissionMode??"yolo",{sessionId:I,messages:a}=await r({sessionId:X.sessionId,continue:X.continue,resume:X.resume,forkSession:X.forkSession,fallbackSessionPrefix:"headless"}),t={messages:[...a],userId:"cli-user",sessionId:I,workspaceRoot:P(),permissionMode:L,signal:A.signal,confirmationHandler:Nq()};_=await c.create({sessionId:I,workspaceRoot:P(),modelId:X.model,mcpConfig:X.mcpConfig,strictMcpConfig:X.strictMcpConfig,agents:X.agents?v(X.agents):void 0});let e=X.maxTurns??_.getConfig().maxTurns,qq=await T.createWithRuntime(_,{sessionId:I,systemPrompt:X.systemPrompt,appendSystemPrompt:X.appendSystemPrompt,maxTurns:X.maxTurns,modelId:X.model,permissionMode:L,toolWhitelist:X.allowedTools,toolBlacklist:X.disallowedTools,mcpConfig:X.mcpConfig,strictMcpConfig:X.strictMcpConfig}),J=await h(qq.chatStream(M.content,t,{stream:!0,signal:A.signal,maxTurns:X.maxTurns,...e===-1?{onTurnLimitReached:async(V)=>{return Z.turnLimit(V.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async(V)=>{switch(V.kind){case"content_delta":D.markAssistantContent(),Z.contentDelta(V.delta);break;case"thinking_delta":D.setThinkingOpened(Z.thinkingDelta(V.delta,D.hasOpenThinking()));break;case"stream_end":{let G=D.completeStream();Z.streamEnd(G.wroteAssistantContent,G.openedThinking);break}case"tool_start":{let G=V.toolCall;if(!("function"in G))break;if(["TaskCreate","TaskUpdate","TaskList"].includes(G.function.name))break;try{let R=JSON.parse(G.function.arguments),H=g(G.function.name,R),j=F(G.function.name,R),f=Oq(G.function.name,H,j,U);if(f.shouldLockTarget)U.targetLocked=!0;Z.phase(f.phase,f.status,f.message,{toolName:G.function.name,target:j}),Z.toolStart(G.function.name,H,j,V.toolKind)}catch{Z.phase(U.targetLocked?"executing":"searching",U.targetLocked?"hit":"ongoing",U.targetLocked?`Working within target: ${G.function.name}`:`Still searching: ${G.function.name}`,{toolName:G.function.name}),Z.toolStart(G.function.name,G.function.name,void 0,V.toolKind)}break}case"tool_result":{let G=V.toolCall;if(!("function"in G))break;let R;try{let j=JSON.parse(G.function.arguments);R=F(G.function.name,j)}catch{R=void 0}let H=d(G.function.name,V.result);if(Z.toolResult(G.function.name,H.summary,R,void 0,{success:V.result.success,errorType:V.result.error?.type,errorMessage:V.result.error?.message}),H.detail)Z.toolDetail(G.function.name,H.detail);break}case"token_usage":Z.tokenUsage(V.usage);break;case"compaction":Z.compacting(V.phase==="start");break;case"task_update":Z.taskUpdate(V.tasks);break;case"steering_applied":case"follow_up_started":case"goal_updated":case"goal_continuation_started":break;case"subagent_spawned":case"subagent_completed":Z.subagent(V);break;case"model_fallback":break;case"turn_start":if(V.turn===1)U.targetLocked=!1;Z.phase("turn",U.targetLocked?"hit":"ongoing",`Turn ${V.turn} started`,{turn:V.turn});break;default:{let G=V}}});if(J.metadata?.outputTruncated)Z.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(!J.success)return Z.error(`Error: ${J.error?.message??"Agent execution failed"}`),1;return Z.phase("completed","done","Headless run completed"),0}catch(X){if(D.hasOpenThinking()&&Q==="text")$.stderr.write(`
6
- `);return Z.error(`Error: ${Wq(X)}`),1}finally{try{await _?.dispose()}finally{A.dispose()}}}async function tq(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:B,"output-format":Q,"system-prompt":Z,"append-system-prompt":D,"max-turns":U,..._}=y,A=Rq(Hq(process.argv)).scriptName("blade").strict(!1).options(_).middleware([m,u,l]);return Lq(A),await A.parse(),!0}export{Fq as runHeadless,tq as handleHeadlessMode,Iq as HeadlessOptionsSchema};
@@ -1,2 +0,0 @@
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 +0,0 @@
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,22 +0,0 @@
1
- import{Ib as V,Kb as L,Lb as M}from"./chunk-gsfkrr25.js";import{Tb as b}from"./chunk-34pdtz4q.js";import{dc as E}from"./chunk-hjx5n3dw.js";var G={currentModelId:"",models:[],temperature:0,maxOutputTokens:void 0,stream:!0,topP:0.9,topK:50,timeout:180000,theme:"dracula",uiTheme:"system",language:"zh-CN",fontSize:14,autoSaveSessions:!0,notifyBuild:!0,notifyErrors:!1,notifySounds:!1,privacyTelemetry:!1,privacyCrash:!0,debug:!1,mcpEnabled:!1,mcpServers:{},permissions:{allow:["Bash(pwd)","Bash(which *)","Bash(whoami)","Bash(hostname)","Bash(uname *)","Bash(date)","Bash(echo *)","Bash(ls *)","Bash(tree *)","Bash(git status)","Bash(git status -*)","Bash(git log *)","Bash(git diff *)","Bash(git show *)","Bash(git branch -* *)","Bash(git branch)","Bash(git tag -l *)","Bash(git tag --list *)","Bash(git stash list *)","Bash(git stash show *)","Bash(git rev-parse *)","Bash(git describe *)","Bash(git blame *)","Bash(git ls-files *)","Bash(git config --get *)","Bash(git config --list *)","Bash(git shortlog *)","Bash(git merge-base *)","Bash(git cat-file *)","Bash(git for-each-ref *)","Bash(git grep *)","Bash(git worktree list *)","Bash(git reflog show *)","Bash(git reflog)","Bash(git rev-list *)","Bash(git ls-remote *)","Bash(git remote -v)","Bash(git remote --verbose)","Bash(git remote)","Bash(gh pr view *)","Bash(gh pr list *)","Bash(gh pr diff *)","Bash(gh pr checks *)","Bash(gh pr status *)","Bash(gh issue view *)","Bash(gh issue list *)","Bash(gh issue status *)","Bash(gh run list *)","Bash(gh run view *)","Bash(gh repo view *)","Bash(gh auth status)","Bash(npm list *)","Bash(bun pm ls *)","Bash(npm view *)","Bash(npm outdated *)","Bash(pnpm list *)","Bash(yarn list *)","Bash(pip list *)","Bash(pip show *)"],ask:["Bash(curl *)","Bash(wget *)","Bash(aria2c *)","Bash(axel *)","Bash(rm -rf *)","Bash(rm -r *)","Bash(rm --recursive *)","Bash(nc *)","Bash(netcat *)","Bash(telnet *)","Bash(ncat *)"],deny:["Read(./.env)","Read(./.env.*)","Bash(rm -rf /)","Bash(rm -rf /*)","Bash(sudo *)","Bash(chmod 777 *)","Bash(bash *)","Bash(sh *)","Bash(zsh *)","Bash(fish *)","Bash(dash *)","Bash(eval *)","Bash(source *)","Bash(mkfs *)","Bash(fdisk *)","Bash(dd *)","Bash(format *)","Bash(parted *)","Bash(open http*)","Bash(open https*)","Bash(xdg-open http*)","Bash(xdg-open https*)"]},permissionMode:"default",hooks:{enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionRequest:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]},env:{},disableAllHooks:!1,maxTurns:-1};import{promises as T}from"fs";import{merge as A}from"lodash-es";import R from"os";import $ from"path";var x={sonnet:"claude-sonnet-4-20250514",opus:"claude-opus-4-20250514",haiku:"claude-3-5-haiku-20241022",claude:"claude-sonnet-4-20250514",gpt4o:"gpt-4o",gpt4:"gpt-4o",o1:"o1",o3:"o3","o4-mini":"o4-mini",deepseek:"deepseek-chat","deepseek-v3":"deepseek-chat","deepseek-r1":"deepseek-reasoner","deepseek-v4":"deepseek-v4-0324",gemini:"gemini-2.5-pro",flash:"gemini-2.5-flash",qwen:"qwen3-235b-a22b","qwen-max":"qwen-max","qwen-plus":"qwen-plus"};function _(J){let q=J.toLowerCase().trim();return x[q]??J}class N{static instance=null;runtimePermissionOverrides;constructor(){}static getInstance(){if(!N.instance)N.instance=new N;return N.instance}static resetInstance(){N.instance=null}async initialize(J){try{this.runtimePermissionOverrides=J?.permissions;let q=await this.loadConfigFiles(),H=await this.loadSettingsFiles(),K={...q,...H};if(J)K=this.mergeSettings(K,J);let Q=this.normalizeConfig(K),W={...G,...Q};if(this.resolveEnvInterpolation(W),process.env.BLADE_MODEL&&W.models?.length>0){let X=_(process.env.BLADE_MODEL),Y=W.models.find((Z)=>Z.id===X||Z.model===X||Z.id===process.env.BLADE_MODEL||Z.model===process.env.BLADE_MODEL);if(Y)W.currentModelId=Y.id}if(process.env.BLADE_DEBUG)W.debug=process.env.BLADE_DEBUG==="1"||process.env.BLADE_DEBUG==="true"||process.env.BLADE_DEBUG;if(W.models.length>0)this.validateConfig(W);if(W.debug)console.log("[ConfigManager] Configuration loaded successfully");return W}catch(q){return console.error("[ConfigManager] Failed to initialize:",q),G}}async loadConfigFiles(){let J=$.join(R.homedir(),".blade","config.json"),q=$.join(V(),".blade","config.json"),H={},K=await this.loadJsonFile(J);if(K)H={...H,...K};let Q=await this.loadJsonFile(q);if(Q){let W={...H.mcpServers||{},...Q.mcpServers||{}};if(H={...H,...Q},Object.keys(W).length>0)H.mcpServers=W}return H}async loadSettingsFiles(){let J=$.join(R.homedir(),".blade","settings.json"),q=$.join(V(),".blade","settings.json"),H=$.join(V(),".blade","settings.local.json"),K={},Q=await this.loadJsonFile(J);if(Q)K=this.mergeSettings(K,Q);let W=await this.loadJsonFile(q);if(W)K=this.mergeSettings(K,W);let X=await this.loadJsonFile(H);if(X)K=this.mergeSettings(K,X);return K}async loadWorkspacePermissions(J,q){let H={allow:[...q.allow],ask:[...q.ask],deny:[...q.deny]};if($.resolve(J)!==$.resolve(V())){let Q=await this.loadWorkspacePermissionOverrides(V()),W=await this.loadJsonFile($.join(R.homedir(),".blade","settings.json")),X={allow:Array.from(new Set([...G.permissions.allow,...W?.permissions?.allow||[],...this.runtimePermissionOverrides?.allow||[]])),ask:Array.from(new Set([...G.permissions.ask,...W?.permissions?.ask||[],...this.runtimePermissionOverrides?.ask||[]])),deny:Array.from(new Set([...G.permissions.deny,...W?.permissions?.deny||[],...this.runtimePermissionOverrides?.deny||[]]))};for(let Y of["allow","ask","deny"]){let Z=new Set(Q[Y].filter((F)=>!X[Y].includes(F)));H[Y]=H[Y].filter((F)=>!Z.has(F))}}let K=await this.loadWorkspacePermissionOverrides(J);for(let Q of["allow","ask","deny"])H[Q]=Array.from(new Set([...H[Q],...K[Q]]));return H}async loadWorkspacePermissionOverrides(J){let q={allow:[],ask:[],deny:[]},H=[$.join(J,".blade","settings.json"),$.join(J,".blade","settings.local.json")];for(let K of H){let Q=await this.loadJsonFile(K);if(!Q?.permissions)continue;for(let W of["allow","ask","deny"])q[W]=Array.from(new Set([...q[W],...Q.permissions[W]||[]]))}return q}mergeSettings(J,q){let H={...JSON.parse(JSON.stringify(J)),...JSON.parse(JSON.stringify(q))};if(q.permissions)H.permissions={allow:Array.from(new Set([...J.permissions?.allow||[],...q.permissions.allow||[]])),ask:Array.from(new Set([...J.permissions?.ask||[],...q.permissions.ask||[]])),deny:Array.from(new Set([...J.permissions?.deny||[],...q.permissions.deny||[]]))};if(q.hooks)H.hooks=A({},H.hooks,q.hooks);if(q.env)H.env=A({},H.env,q.env);if(q.mcpServers)H.mcpServers={...H.mcpServers||{},...q.mcpServers};if(q.disableAllHooks!==void 0)H.disableAllHooks=q.disableAllHooks;if(q.permissionMode!==void 0)H.permissionMode=q.permissionMode;if(q.maxTurns!==void 0)H.maxTurns=q.maxTurns;return H}resolveEnvInterpolation(J){let q=/\$\{?([A-Z_][A-Z0-9_]*)(:-([^}]+))?\}?/g,H=(Q)=>{if(typeof Q==="string")return Q.replace(q,(W,X,Y,Z)=>{return process.env[X]||Z||W});if(Array.isArray(Q))return Q.map(H);if(typeof Q==="object"&&Q!==null){let W=Q;for(let[X,Y]of Object.entries(W))W[X]=H(Y);return W}return Q},K=J;for(let[Q,W]of Object.entries(K))K[Q]=H(W)}async loadJsonFile(J){try{if(await this.fileExists(J)){let q=await T.readFile(J,"utf-8");return JSON.parse(q)}}catch(q){console.warn(`[ConfigManager] Failed to load ${J}:`,q)}return null}async fileExists(J){try{return await T.access(J),!0}catch{return!1}}normalizeConfig(J){let q=JSON.parse(JSON.stringify(J)),H=(Q)=>Q.trim().replace(/^`|`$/g,""),K=(Q)=>{for(let[W,X]of Object.entries(Q))if(typeof X==="string")Q[W]=H(X);else if(Array.isArray(X))X.forEach((Y,Z)=>{if(typeof Y==="string")X[Z]=H(Y);else if(typeof Y==="object"&&Y!==null)K(Y)});else if(typeof X==="object"&&X!==null)K(X)};return K(q),q}validateConfig(J){let q=[];if(!J.models||J.models.length===0)q.push("没有可用的模型配置");if(!L(J.maxTurns))q.push(`maxTurns 必须是 ${M()}`);if(J.models&&J.models.length>0){if(!J.currentModelId)q.push("未设置当前模型 ID");else if(!J.models.find((K)=>K.id===J.currentModelId))q.push(`当前模型 ID "${J.currentModelId}" 在 models 列表中不存在`);for(let H of J.models){let K=`模型 "${H.displayName||H.id}"`,Q=["name","apiKey","baseUrl","maxContextTokens","maxOutputTokens","supportsThinking","thinkingBudget","thinkingMode"].filter((W)=>(W in H));if(Q.length>0)q.push(`${K}: 不再支持旧字段 ${Q.join(", ")};请重新配置模型`);if(!H.model)q.push(`${K}: model 字段必填`);if(!H.provider)q.push(`${K}: provider 字段必填`);if(H.overrides?.baseUrl&&!H.overrides.baseUrl.startsWith("http"))q.push(`${K}: overrides.baseUrl "${H.overrides.baseUrl}" 不是有效的 HTTP URL`);try{E().getModel(H.provider,H.model)}catch{q.push(`${K}: 内置 catalog 中不存在 ${H.provider}/${H.model}`)}}}if(q.length>0)throw Error(`配置验证失败:
2
- ${q.map((H)=>` - ${H}`).join(`
3
- `)}
4
-
5
- `+`请通过以下方式之一提供配置:
6
- `+` 1. 首次启动: 运行 blade,系统会自动引导配置
7
- `+` 2. 添加模型: blade 后输入 /model add
8
- `+` 3. 初始化向导: 输入 /init
9
-
10
- `+`配置文件示例 (~/.blade/config.json):
11
- `+`{
12
- "currentModelId": "model-id-123",
13
- "models": [
14
- {
15
- "id": "model-id-123",
16
- `+` "displayName": "默认模型",
17
- `+` "provider": "deepseek",
18
- "model": "deepseek-v4-pro"
19
- }
20
- ]
21
- }
22
- `)}}function y(J,q={}){let H={...J};if(q.debug!==void 0)H.debug=q.debug===""?!0:q.debug;if(q.model){if(!J.models.some((Q)=>Q.id===q.model))throw Error(`模型配置未找到: ${q.model}`);H.currentModelId=q.model}if(q.yolo===!0)H.permissionMode="yolo";else if(q.permissionMode!==void 0)H.permissionMode=q.permissionMode;if(q.maxTurns!==void 0)H.maxTurns=q.maxTurns;return H.systemPrompt=q.systemPrompt,H.appendSystemPrompt=q.appendSystemPrompt,H.model=q.model,H.resumeSessionId=q.sessionId,H.forkSession=q.forkSession,H.allowedTools=q.allowedTools,H.disallowedTools=q.disallowedTools,H.mcpConfigPaths=q.mcpConfig,H.strictMcpConfig=q.strictMcpConfig,H.addDirs=q.addDir,H.outputFormat=q.outputFormat,H.inputFormat=q.inputFormat,H.print=q.print,H.includePartialMessages=q.includePartialMessages,H.replayUserMessages=q.replayUserMessages,H.agentsConfig=q.agents,H.settingSources=q.settingSources,H}import{promises as D}from"node:fs";import w from"node:os";import B from"node:path";import{Mutex as j}from"async-mutex";import{merge as k}from"lodash-es";import C from"write-file-atomic";var S=b("Service"),U={models:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},currentModelId:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},temperature:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxOutputTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},timeout:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},theme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},uiTheme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},language:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},debug:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},fontSize:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},autoSaveSessions:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyBuild:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyErrors:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifySounds:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyTelemetry:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyCrash:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},permissionMode:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},permissions:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},hooks:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},env:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},disableAllHooks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxTurns:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},mcpServers:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},stream:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topP:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topK:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},mcpEnabled:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},systemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},appendSystemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},initialMessage:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},resumeSessionId:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},forkSession:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},allowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},disallowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},mcpConfigPaths:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},strictMcpConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},addDirs:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},outputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},inputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},print:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},includePartialMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},replayUserMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},agentsConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},settingSources:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1}},Yq=new Set(Object.entries(U).filter(([J,q])=>q.persistable).map(([J])=>J)),Zq=new Set(Object.entries(U).filter(([J,q])=>!q.persistable).map(([J])=>J));class z{static instance=null;pendingUpdates=new Map;timers=new Map;fileLocks=new Map;lastSaveError=null;debounceDelay=300;constructor(){}static getInstance(){if(!z.instance)z.instance=new z;return z.instance}static resetInstance(){if(z.instance)for(let J of z.instance.timers.values())clearTimeout(J);z.instance=null}async save(J,q={}){this.validatePersistableFields(J);let H=this.groupUpdatesByTarget(J,q.scope,q.projectDir);if(q.immediate)await Promise.all(Array.from(H.entries()).map(([K,Q])=>this.flushTarget(K,Q)));else for(let[K,Q]of H)this.scheduleSave(K,Q)}async flush(){for(let q of this.timers.values())clearTimeout(q);this.timers.clear();let J=Array.from(this.pendingUpdates.entries()).map(([q,H])=>this.flushTarget(q,H));this.pendingUpdates.clear(),await Promise.all(J)}getLastSaveError(){return this.lastSaveError}clearLastSaveError(){this.lastSaveError=null}async appendPermissionRule(J,q={}){await this.appendPermissionRuleForDecision(J,"allow",q)}async appendPermissionDenyRule(J,q={}){await this.appendPermissionRuleForDecision(J,"deny",q)}async appendPermissionRuleForDecision(J,q,H){let K=H.scope??"local",Q=this.resolveFilePath("settings",K,H.projectDir);await this.flushTargetWithModifier(Q,(W)=>{let X=W.permissions??{allow:[],ask:[],deny:[]},Y={allow:q==="allow"?this.dedupeArray([...X.allow||[],J]):X.allow||[],ask:X.ask||[],deny:q==="deny"?this.dedupeArray([...X.deny||[],J]):X.deny||[]};return{...W,permissions:Y}})}async appendLocalPermissionRule(J,q={}){await this.appendPermissionRule(J,{...q,scope:"local"})}async appendLocalPermissionDenyRule(J,q={}){await this.appendPermissionDenyRule(J,{...q,scope:"local"})}validatePersistableFields(J){for(let q of Object.keys(J)){let H=U[q];if(!H)throw Error(`Unknown config field: ${q}`);if(!H.persistable)throw Error(`Field "${q}" is non-persistable and cannot be saved to config files. Non-persistable fields are runtime-only and only valid for the current session.`)}}groupUpdatesByTarget(J,q,H){let K=new Map;for(let[Q,W]of Object.entries(J)){let X=U[Q];if(!X)continue;let Y=q??X.defaultScope,Z=this.resolveFilePath(X.target,Y,H);if(!K.has(Z))K.set(Z,{});K.get(Z)[Q]=W}return K}resolveFilePath(J,q,H){let K=H??V();if(J==="config")return q==="global"?B.join(w.homedir(),".blade","config.json"):B.join(K,".blade","config.json");switch(q){case"local":return B.join(K,".blade","settings.local.json");case"project":return B.join(K,".blade","settings.json");case"global":return B.join(w.homedir(),".blade","settings.json");default:return B.join(K,".blade","settings.local.json")}}scheduleSave(J,q){let H=this.pendingUpdates.get(J)??{},K=this.mergePendingUpdates(H,q);this.pendingUpdates.set(J,K);let Q=this.timers.get(J);if(Q)clearTimeout(Q);let W=setTimeout(async()=>{let X=this.pendingUpdates.get(J);if(X){this.pendingUpdates.delete(J),this.timers.delete(J);try{await this.flushTarget(J,X),this.lastSaveError=null}catch(Y){let Z=Y instanceof Error?Y:Error(String(Y));this.lastSaveError=Z,S.error(`Failed to save config to ${J}:`,Z.message),S.error("Stack trace:",Z.stack)}}},this.debounceDelay);this.timers.set(J,W)}mergePendingUpdates(J,q){let H={...J};for(let[K,Q]of Object.entries(q)){let W=U[K];if(!W){H[K]=Q;continue}switch(W.mergeStrategy){case"replace":H[K]=Q;break;case"append-dedupe":this.applyAppendDedupe(H,K,Q);break;case"deep-merge":this.applyDeepMerge(H,K,Q);break}}return H}async flushTarget(J,q){let H=this.fileLocks.get(J);if(!H)H=new j,this.fileLocks.set(J,H);await H.runExclusive(async()=>{await this.performWrite(J,q)})}async flushTargetWithModifier(J,q){let H=this.fileLocks.get(J);if(!H)H=new j,this.fileLocks.set(J,H);await H.runExclusive(async()=>{await D.mkdir(B.dirname(J),{recursive:!0,mode:493});let K={};try{let W=await D.readFile(J,"utf-8");K=JSON.parse(W)}catch{K={}}let Q=q(K);await this.atomicWrite(J,Q)})}async performWrite(J,q){await D.mkdir(B.dirname(J),{recursive:!0,mode:493});let H={};try{let Q=await D.readFile(J,"utf-8");H=JSON.parse(Q)}catch{H={}}let K={...H};for(let[Q,W]of Object.entries(q)){let X=U[Q];if(!X){K[Q]=W;continue}switch(X.mergeStrategy){case"replace":K[Q]=W;break;case"append-dedupe":this.applyAppendDedupe(K,Q,W);break;case"deep-merge":this.applyDeepMerge(K,Q,W);break}}await this.atomicWrite(J,K)}applyAppendDedupe(J,q,H){if(q==="permissions"&&typeof H==="object"&&H!==null){let K=J[q]??{allow:[],ask:[],deny:[]},Q=H;J[q]={allow:this.dedupeArray([...K.allow||[],...Q.allow||[]]),ask:this.dedupeArray([...K.ask||[],...Q.ask||[]]),deny:this.dedupeArray([...K.deny||[],...Q.deny||[]])}}else if(Array.isArray(H)){let K=Array.isArray(J[q])?J[q]:[];J[q]=this.dedupeArray([...K,...H])}else J[q]=H}applyDeepMerge(J,q,H){if(typeof H==="object"&&H!==null&&!Array.isArray(H)){let K=typeof J[q]==="object"&&J[q]!==null?J[q]:{};J[q]=k({},K,H)}else J[q]=H}dedupeArray(J){return Array.from(new Set(J))}async atomicWrite(J,q){await C(J,JSON.stringify(q,null,2),{mode:384,encoding:"utf-8"})}}function O(){return z.getInstance()}export{G as Da,N as Ea,y as Fa,O as Ga};
@@ -1,6 +0,0 @@
1
- import{y as b}from"./chunk-twem6p0g.js";import{ra as T}from"./chunk-tv4r86ez.js";import{Da as S,Ea as h}from"./chunk-qwdbqjh7.js";import{Bb as r,wb as f,yb as n}from"./chunk-ctqf59q1.js";import{Eb as c,Hb as O,Jb as y}from"./chunk-gsfkrr25.js";import{Tb as M}from"./chunk-34pdtz4q.js";import{promises as N}from"node:fs";import E from"node:path";var k=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],B=new Set([...Object.keys(S),...k]),a=n.Number({exclusiveMinimum:0}),l=n.String({minLength:1}),m=n.Array(n.String()),C=n.Object({currentModelId:n.Optional(n.String()),models:n.Optional(n.Array(n.Object({id:l,displayName:n.Optional(l),provider:l,model:l,overrides:n.Optional(n.Object({baseUrl:n.Optional(n.String()),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(a),timeout:n.Optional(a),apiVersion:n.Optional(n.String()),customHeaders:n.Optional(n.Record(n.String(),n.String())),maxRetries:n.Optional(n.Integer({minimum:0})),enablePromptCaching:n.Optional(n.Boolean())})),fallbackModels:n.Optional(n.Array(n.Object({provider:l,model:l})))}))),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(a),stream:n.Optional(n.Boolean()),topP:n.Optional(n.Number()),topK:n.Optional(n.Number()),timeout:n.Optional(a),theme:n.Optional(n.String()),uiTheme:n.Optional(r(["light","dark","system"])),language:n.Optional(n.String()),fontSize:n.Optional(a),autoSaveSessions:n.Optional(n.Boolean()),notifyBuild:n.Optional(n.Boolean()),notifyErrors:n.Optional(n.Boolean()),notifySounds:n.Optional(n.Boolean()),privacyTelemetry:n.Optional(n.Boolean()),privacyCrash:n.Optional(n.Boolean()),debug:n.Optional(n.Union([n.Boolean(),n.String()])),mcpEnabled:n.Optional(n.Boolean()),mcpServers:n.Optional(n.Record(n.String(),n.Record(n.String(),n.Unknown()))),permissionMode:n.Optional(n.Enum(O)),maxTurns:n.Optional(n.Integer({minimum:-1,maximum:y})),systemPrompt:n.Optional(n.String()),appendSystemPrompt:n.Optional(n.String()),initialMessage:n.Optional(n.String()),resumeSessionId:n.Optional(n.String()),forkSession:n.Optional(n.Boolean()),allowedTools:n.Optional(n.Array(l)),disallowedTools:n.Optional(n.Array(l)),mcpConfigPaths:n.Optional(n.Array(l)),strictMcpConfig:n.Optional(n.Boolean()),model:n.Optional(l),addDirs:n.Optional(n.Array(l)),outputFormat:n.Optional(r(["text","json","stream-json","jsonl"])),inputFormat:n.Optional(r(["text","stream-json"])),print:n.Optional(n.Boolean()),includePartialMessages:n.Optional(n.Boolean()),replayUserMessages:n.Optional(n.Boolean()),agentsConfig:n.Optional(n.String()),settingSources:n.Optional(n.String()),permissions:n.Optional(n.Object({allow:n.Optional(m),ask:n.Optional(m),deny:n.Optional(m)})),env:n.Optional(n.Record(n.String(),n.String())),hooks:n.Optional(n.Record(n.String(),n.Unknown())),disableAllHooks:n.Optional(n.Boolean())}),R=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"]];function u(o,e){let t;try{t=JSON.parse(o)}catch(i){let p=i instanceof Error?`: ${i.message}`:"";throw Error(`Invalid JSON provided to --settings (${e})${p}`)}if(!t||typeof t!=="object"||Array.isArray(t))throw Error("--settings must contain a JSON object");for(let i of Object.keys(t))if(!B.has(i))throw Error(`Unknown --settings field: ${i}`);let s=f(C,t);if(!s.success){let i=s.error.issues.map((p)=>`${p.path.join(".")||"settings"}: ${p.message}`).join("; ");throw Error(`Invalid --settings value: ${i}`)}return s.data}async function w(o){if(o===void 0)return;let e=o.trim();if(!e)throw Error("--settings requires a JSON object or file path");if(e.startsWith("{"))return u(e,"inline JSON");let t=E.resolve(c(),e),s;try{s=await N.readFile(t,"utf8")}catch(i){let p=i instanceof Error?`: ${i.message}`:"";throw Error(`Unable to read --settings file ${t}${p}`)}return u(s,t)}function P(o,e){if(!e)return;let t=e;for(let[s,i]of R){if(s==="permissionMode"&&o.yolo===!0)continue;if(o[i]===void 0&&t[s]!==void 0)o[i]=t[s]}}var d=M("General"),z=(o)=>{if(o.yolo){if(o.permissionMode&&o.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");o.permissionMode="yolo"}if(Array.isArray(o.allowedTools))o.allowedTools=o.allowedTools.flatMap((e)=>e.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.disallowedTools))o.disallowedTools=o.disallowedTools.flatMap((e)=>e.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.allowedTools)&&Array.isArray(o.disallowedTools)){let e=o.allowedTools.filter((t)=>o.disallowedTools.includes(t));if(e.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${e.join(", ")}`)}},L=async(o)=>{let e=await w(typeof o.settings==="string"?o.settings:void 0);if(P(o,e),typeof o.agents==="string")b(o.agents);I(o);try{let s=await h.getInstance().initialize(e);if(T().config.actions.setConfig(s),o.debug)d.info("[CLI] 配置已加载到 Store")}catch(t){d.error("[CLI] [FAIL] 配置初始化失败",t instanceof Error?t.message:t),console.error(`
2
- [FAIL] 配置初始化失败
3
- `),console.error("原因:",t instanceof Error?t.message:"未知错误"),console.error(`
4
- 请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
5
- `),process.exit(1)}};function I(o){if(o.continue&&o.resume)throw Error("Cannot use both --continue and --resume flags simultaneously");if(o.forkSession&&!o.continue&&!o.resume)throw Error("--fork-session requires --resume or --continue");if(o.sessionId&&(o.continue||o.resume)&&!o.forkSession)throw Error("--session-id can only be combined with --resume or --continue when --fork-session is set")}var V=(o)=>{if(o.outputFormat&&o.outputFormat!=="text"&&!o.print&&!o.headless)throw Error("--output-format can only be used with --print or --headless");if(o.headless&&o.outputFormat&&!["text","jsonl"].includes(o.outputFormat))throw Error(`--headless only supports --output-format text|jsonl, but got "${o.outputFormat}". Use --print for json|stream-json support.`);if(o.print&&o.outputFormat&&!["text","json","stream-json"].includes(o.outputFormat))throw Error(`--print only supports --output-format text|json|stream-json, but got "${o.outputFormat}". Use --headless for jsonl support.`);if(o.inputFormat==="stream-json"&&o.print)d.warn("[WARN] Warning: stream-json input format may not work as expected with --print")};
6
- export{z as v,L as w,V as x};
@@ -1 +0,0 @@
1
- import{g as a,h as b,i as c,j as d,k as e}from"./chunk-1smf2dj3.js";import"./chunk-dr06x0cw.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1 +0,0 @@
1
- import{Pb as a}from"./chunk-0dj326ms.js";import"./chunk-34pdtz4q.js";import"./chunk-hjx5n3dw.js";import"./chunk-dr06x0cw.js";export{a as createChatServiceAsync};
@@ -1,7 +0,0 @@
1
- import{_ as ue}from"./vendor-markdown-b9iCqZWK.js";import{r as i,j as e}from"./vendor-react-FPIC4Czm.js";import{c as F,u as Fe,e as $,s as re,B as Ce,f as ae}from"./index-B3dW1Scg.js";import{n as Be,L as xe,o as me,p as pe}from"./vendor-radix-DyP_DOwV.js";import{u as Se}from"./SettingsStore-B_4zN-c-.js";import{X as Le,a as ne,c as se,F as be,x as Re,y as De}from"./vendor-icons-DqO8ishN.js";import"./vendor-monaco-w6PwaWGP.js";const Te=Be,ge=i.forwardRef(({className:t,...a},r)=>e.jsx(xe,{ref:r,className:F("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",t),...a}));ge.displayName=xe.displayName;const z=i.forwardRef(({className:t,...a},r)=>e.jsx(me,{ref:r,className:F("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",t),...a}));z.displayName=me.displayName;const W=i.forwardRef(({className:t,...a},r)=>e.jsx(pe,{ref:r,className:F("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...a}));W.displayName=pe.displayName;const Ae={"ayu-dark":{background:{primary:"#0f1419",secondary:"#14191f"},text:{primary:"#e6e1cf",secondary:"#bae67e",muted:"#5c6773"},border:{light:"#2d323b"},syntax:{comment:"#5c6773",string:"#bae67e",number:"#ffcc66",keyword:"#ff8f40",function:"#73d0ff",variable:"#e6e1cf",operator:"#f29e74",type:"#73d0ff",tag:"#ff8f40",attr:"#ffd580",default:"#e6e1cf"}},dracula:{background:{primary:"#282a36",secondary:"#44475a"},text:{primary:"#f8f8f2",secondary:"#f1fa8c",muted:"#6272a4"},border:{light:"#44475a"},syntax:{comment:"#6272a4",string:"#f1fa8c",number:"#bd93f9",keyword:"#ff79c6",function:"#50fa7b",variable:"#f8f8f2",operator:"#ff79c6",type:"#8be9fd",tag:"#ff79c6",attr:"#50fa7b",default:"#f8f8f2"}},monokai:{background:{primary:"#272822",secondary:"#3e3d32"},text:{primary:"#f8f8f2",secondary:"#e6db74",muted:"#75715e"},border:{light:"#3e3d32"},syntax:{comment:"#75715e",string:"#e6db74",number:"#ae81ff",keyword:"#f92672",function:"#a6e22e",variable:"#f8f8f2",operator:"#f92672",type:"#66d9ef",tag:"#f92672",attr:"#a6e22e",default:"#f8f8f2"}},nord:{background:{primary:"#2e3440",secondary:"#3b4252"},text:{primary:"#eceff4",secondary:"#d8dee9",muted:"#4c566a"},border:{light:"#434c5e"},syntax:{comment:"#616e88",string:"#a3be8c",number:"#b48ead",keyword:"#81a1c1",function:"#88c0d0",variable:"#d8dee9",operator:"#81a1c1",type:"#8fbcbb",tag:"#81a1c1",attr:"#8fbcbb",default:"#eceff4"}},"solarized-light":{background:{primary:"#fdf6e3",secondary:"#eee8d5"},text:{primary:"#586e75",secondary:"#657b83",muted:"#93a1a1"},border:{light:"#eee8d5"},syntax:{comment:"#93a1a1",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#657b83",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#657b83"}},"solarized-dark":{background:{primary:"#002b36",secondary:"#073642"},text:{primary:"#839496",secondary:"#93a1a1",muted:"#586e75"},border:{light:"#073642"},syntax:{comment:"#586e75",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#839496",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#839496"}},"tokyo-night":{background:{primary:"#1a1b26",secondary:"#292e42"},text:{primary:"#a9b1d6",secondary:"#c0caf5",muted:"#565f89"},border:{light:"#292e42"},syntax:{comment:"#565f89",string:"#9ece6a",number:"#ff9e64",keyword:"#bb9af7",function:"#7aa2f7",variable:"#c0caf5",operator:"#89ddff",type:"#7dcfff",tag:"#f7768e",attr:"#7aa2f7",default:"#a9b1d6"}},github:{background:{primary:"#ffffff",secondary:"#f6f8fa"},text:{primary:"#24292f",secondary:"#57606a",muted:"#6e7781"},border:{light:"#d0d7de"},syntax:{comment:"#6e7781",string:"#0a3069",number:"#0550ae",keyword:"#cf222e",function:"#8250df",variable:"#24292f",operator:"#cf222e",type:"#0550ae",tag:"#116329",attr:"#0550ae",default:"#24292f"}},gruvbox:{background:{primary:"#282828",secondary:"#3c3836"},text:{primary:"#ebdbb2",secondary:"#d5c4a1",muted:"#928374"},border:{light:"#3c3836"},syntax:{comment:"#928374",string:"#b8bb26",number:"#d3869b",keyword:"#fb4934",function:"#b8bb26",variable:"#ebdbb2",operator:"#fe8019",type:"#fabd2f",tag:"#fb4934",attr:"#fabd2f",default:"#ebdbb2"}},"one-dark":{background:{primary:"#282c34",secondary:"#21252b"},text:{primary:"#abb2bf",secondary:"#e5c07b",muted:"#5c6370"},border:{light:"#3e4451"},syntax:{comment:"#5c6370",string:"#98c379",number:"#d19a66",keyword:"#c678dd",function:"#61afef",variable:"#e06c75",operator:"#56b6c2",type:"#e5c07b",tag:"#e06c75",attr:"#d19a66",default:"#abb2bf"}},catppuccin:{background:{primary:"#1e1e2e",secondary:"#313244"},text:{primary:"#cdd6f4",secondary:"#f5e0dc",muted:"#6c7086"},border:{light:"#313244"},syntax:{comment:"#6c7086",string:"#a6e3a1",number:"#fab387",keyword:"#cba6f7",function:"#89b4fa",variable:"#f5e0dc",operator:"#89dceb",type:"#f9e2af",tag:"#f38ba8",attr:"#f9e2af",default:"#cdd6f4"}},"rose-pine":{background:{primary:"#191724",secondary:"#1f1d2e"},text:{primary:"#e0def4",secondary:"#908caa",muted:"#6e6a86"},border:{light:"#26233a"},syntax:{comment:"#6e6a86",string:"#f6c177",number:"#ebbcba",keyword:"#c4a7e7",function:"#9ccfd8",variable:"#e0def4",operator:"#31748f",type:"#eb6f92",tag:"#eb6f92",attr:"#c4a7e7",default:"#e0def4"}},kanagawa:{background:{primary:"#1f1f28",secondary:"#2a2a37"},text:{primary:"#dcd7ba",secondary:"#c8c093",muted:"#727169"},border:{light:"#2a2a37"},syntax:{comment:"#727169",string:"#98bb6c",number:"#d27e99",keyword:"#957fb8",function:"#7e9cd8",variable:"#dcd7ba",operator:"#c0a36e",type:"#7aa89f",tag:"#e46876",attr:"#ffa066",default:"#dcd7ba"}}};function _e(t){const a=t.replace("#",""),r=parseInt(a.substring(0,2),16),s=parseInt(a.substring(2,4),16),o=parseInt(a.substring(4,6),16);return(.299*r+.587*s+.114*o)/255<.5}function $e(t){return{base:_e(t.background.primary)?"vs-dark":"vs",inherit:!0,rules:[{token:"",foreground:t.text.primary.replace("#",""),background:t.background.primary.replace("#","")},{token:"comment",foreground:t.syntax.comment.replace("#",""),fontStyle:"italic"},{token:"string",foreground:t.syntax.string.replace("#","")},{token:"number",foreground:t.syntax.number.replace("#","")},{token:"keyword",foreground:t.syntax.keyword.replace("#","")},{token:"type",foreground:t.syntax.type.replace("#","")},{token:"identifier",foreground:t.syntax.variable.replace("#","")},{token:"function",foreground:t.syntax.function.replace("#","")},{token:"variable",foreground:t.syntax.variable.replace("#","")},{token:"operator",foreground:t.syntax.operator.replace("#","")},{token:"delimiter",foreground:t.syntax.operator.replace("#","")},{token:"tag",foreground:t.syntax.tag.replace("#","")},{token:"attribute.name",foreground:t.syntax.attr.replace("#","")},{token:"attribute.value",foreground:t.syntax.string.replace("#","")}],colors:{"editor.background":t.background.primary,"editor.foreground":t.text.primary,"editor.lineHighlightBackground":t.background.secondary,"editor.selectionBackground":`${t.syntax.function}40`,"editorLineNumber.foreground":t.text.muted,"editorLineNumber.activeForeground":t.text.secondary,"editorCursor.foreground":t.text.primary,"editorIndentGuide.background":t.border.light,"editorWidget.background":t.background.secondary,"editorWidget.border":t.border.light,"scrollbarSlider.background":`${t.text.muted}40`,"scrollbarSlider.hoverBackground":`${t.text.muted}60`}}}const oe=new Set;function de(t,a){const r=a.toLowerCase().replace(/\s+/g,"-"),s=Ae[r];if(!s)return"vs-dark";if(!oe.has(r)){const o=$e(s);t.editor.defineTheme(r,o),oe.add(r)}return r}i.lazy(async()=>({default:(await ue(()=>import("./vendor-react-FPIC4Czm.js").then(a=>a.i),[])).DiffEditor}));const ze=i.lazy(async()=>({default:(await ue(()=>import("./vendor-react-FPIC4Czm.js").then(a=>a.i),[])).Editor}));function ie(t,a){return t instanceof Error?t.message:a}function Ye(){const{toggleFilePreview:t}=Fe(),{messages:a,currentSessionRef:r}=$(),[s,o]=i.useState("diff"),[l,c]=i.useState([]),[d,u]=i.useState({}),[x,m]=i.useState(!1),[b,p]=i.useState(null),[q,E]=i.useState({}),[C,I]=i.useState({}),[v,Q]=i.useState(null),[ye,P]=i.useState(""),[G,O]=i.useState(!1),[V,J]=i.useState(null),[Y,H]=i.useState(!1),Z=i.useRef(r),B=i.useRef(0),D=i.useRef(0),T=i.useRef({}),K=i.useRef(0),S=i.useRef({}),j=i.useRef({}),U=i.useRef(null);i.useLayoutEffect(()=>{re(Z.current,r)||(B.current+=1),Z.current=r},[r]);const X=(n,f)=>f===B.current&&re($.getState().currentSessionRef,n),M=async(n,f="")=>{const g=f?`/suggestions/files/tree?path=${encodeURIComponent(f)}`:"/suggestions/files/tree",h=await fetch(g,{headers:ae(n)});if(!h.ok)throw new Error("Failed to load tree");return(await h.json()).map(y=>({...y,children:y.type==="dir"?[]:void 0}))};i.useEffect(()=>{const n=++D.current;return(async()=>{if(!r){c([]),m(!1),p(null);return}const g={...r},h=B.current,k=()=>n===D.current&&X(g,h);if(k()){c([]),m(!0),p(null);try{const y=await M(g);k()&&c(y)}catch(y){k()&&p(ie(y,"Failed to load tree"))}finally{k()&&m(!1)}}})(),()=>{D.current===n&&(D.current+=1)}},[r==null?void 0:r.projectPath,r==null?void 0:r.sessionId]),i.useEffect(()=>{U.current=null,S.current={},j.current={},T.current={},K.current+=1,Q(null),P(""),O(!1),J(null),H(!1),E({}),u({})},[r==null?void 0:r.projectPath,r==null?void 0:r.sessionId]);const A=i.useMemo(()=>Ie(a),[a]),ee=i.useMemo(()=>qe(a),[a]),[ke,ve]=i.useState({}),Ee=n=>{ve(f=>({...f,[n]:!f[n]}))},je=async n=>{const f=$.getState().currentSessionRef;if(!f)return;const g=B.current,h=++K.current,k=()=>h===K.current&&U.current===n&&X(f,g);U.current=n,Q(n),P(""),O(!0),J(null),H(!1);try{const y=await fetch(`/suggestions/files/content?path=${encodeURIComponent(n)}`,{headers:ae(f)});if(!y.ok)throw new Error("Failed to load file");const L=await y.json();k()&&(P(L.content||""),H(!!L.truncated))}catch(y){k()&&J(ie(y,"Failed to load file"))}finally{k()&&O(!1)}},we=async n=>{const f=(T.current[n]??0)+1;T.current[n]=f;const g=!S.current[n],h={...S.current,[n]:g};if(S.current=h,E(h),!g||j.current[n])return;const k=$.getState().currentSessionRef;if(!k)return;const y=B.current,L=()=>T.current[n]===f&&S.current[n]===!0&&X(k,y);try{const _=await M(k,n);if(L()){const te={...j.current,[n]:_};j.current=te,u(te)}}catch{if(L()){const _={...j.current,[n]:[]};j.current=_,u(_)}}},Ne=n=>{I(f=>({...f,[n]:!f[n]}))};return e.jsxs("div",{className:"w-[55%] min-w-[420px] max-w-[860px] border-l border-[#E5E7EB] dark:border-zinc-800 bg-white dark:bg-[#09090b] flex flex-col h-full shadow-xl shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 h-12 border-b border-[#E5E7EB] dark:border-zinc-800 shrink-0",children:[e.jsx("span",{className:"font-normal text-[13px] text-[#6B7280] dark:text-zinc-400 font-mono",children:"Preview"}),e.jsx(Ce,{variant:"ghost",size:"icon",onClick:t,className:"h-8 w-8 text-[#9CA3AF] hover:text-[#111827] hover:bg-[#E5E7EB]/60 dark:text-zinc-500 dark:hover:text-zinc-300 dark:hover:bg-zinc-800/50",children:e.jsx(Le,{className:"w-4 h-4"})})]}),e.jsxs(Te,{value:s,onValueChange:n=>o(n),className:"flex flex-col flex-1 min-h-0",children:[e.jsx("div",{className:"px-4 py-3 border-b border-[#E5E7EB] dark:border-zinc-800",children:e.jsxs(ge,{className:"bg-white dark:bg-[#111113] border border-[#E5E7EB] dark:border-[#27272a] h-9 p-1 rounded-md w-full justify-start",children:[e.jsx(z,{value:"diff",className:"text-[12px] font-mono px-3 text-[#6B7280] dark:text-[#a1a1aa] data-[state=active]:bg-[#E5E7EB] data-[state=active]:text-[#111827] dark:data-[state=active]:bg-[#27272a] dark:data-[state=active]:text-white",children:"Diff"}),e.jsx(z,{value:"files",className:"text-[12px] font-mono px-3 text-[#6B7280] dark:text-[#a1a1aa] data-[state=active]:bg-[#E5E7EB] data-[state=active]:text-[#111827] dark:data-[state=active]:bg-[#27272a] dark:data-[state=active]:text-white",children:"Files"}),e.jsx(z,{value:"logs",className:"text-[12px] font-mono px-3 text-[#6B7280] dark:text-[#a1a1aa] data-[state=active]:bg-[#E5E7EB] data-[state=active]:text-[#111827] dark:data-[state=active]:bg-[#27272a] dark:data-[state=active]:text-white",children:"Logs"})]})}),e.jsx(W,{value:"diff",className:"overflow-hidden flex-1 mt-0",children:e.jsx("div",{className:"overflow-y-auto px-4 py-4 space-y-3 h-full",children:A.length===0?e.jsx(R,{title:"No patch yet",subtitle:"Run a tool that changes files to see diffs here."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-[12px] text-[#6B7280] dark:text-[#71717a] font-mono mb-2",children:[A.length," changed file",A.length>1?"s":""]}),A.map(n=>{var h;const f=((h=n.filePath)==null?void 0:h.split("/").pop())||"unknown",g=ke[n.filePath||""]!==!1;return e.jsxs("div",{className:"border border-[#E5E7EB] dark:border-[#27272a] rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>Ee(n.filePath||""),className:"w-full flex items-center gap-2 px-3 py-2 bg-[#F9FAFB] dark:bg-[#111113] hover:bg-[#F3F4F6] dark:hover:bg-[#18181b] transition-colors",children:[g?e.jsx(ne,{className:"w-4 h-4 text-[#6B7280] dark:text-[#71717a]"}):e.jsx(se,{className:"w-4 h-4 text-[#6B7280] dark:text-[#71717a]"}),e.jsx(be,{className:"w-4 h-4 text-[#6B7280] dark:text-[#71717a]"}),e.jsx("span",{className:"text-[13px] text-[#111827] dark:text-[#E5E5E5] font-mono flex-1 text-left truncate",children:f}),n.summary&&e.jsx("span",{className:"text-[11px] text-[#6B7280] dark:text-[#a1a1aa] font-mono",children:n.summary})]}),g&&e.jsxs("div",{className:"border-t border-[#E5E7EB] dark:border-[#27272a]",children:[e.jsx("div",{className:"px-3 py-1 text-[11px] text-[#9CA3AF] dark:text-[#52525b] font-mono truncate",children:n.filePath}),e.jsx(Oe,{diff:n.diff})]})]},n.filePath)})]})})}),e.jsx(W,{value:"files",className:"overflow-hidden flex-1 mt-0",children:e.jsxs("div",{className:"px-4 py-4 h-full",children:[x&&e.jsx(R,{title:"Loading files…",subtitle:"Fetching workspace tree."}),!x&&b&&e.jsx(R,{title:"Failed to load files",subtitle:b}),!x&&!b&&l.length===0&&e.jsx(R,{title:"No files yet",subtitle:"Start a session to load the workspace tree."}),!x&&!b&&l.length>0&&e.jsxs("div",{className:"h-full grid grid-cols-[220px_1fr] gap-4 min-h-0",children:[e.jsx("div",{className:"border border-[#E5E7EB] dark:border-[#27272a] rounded-lg p-2 overflow-y-auto min-h-0",children:l.map(n=>e.jsx(he,{node:n,depth:0,expandedDirs:q,childrenCache:d,toggleDir:we,selectedPath:v,onSelectFile:je},n.path))}),e.jsxs("div",{className:"border border-[#E5E7EB] dark:border-[#27272a] rounded-lg overflow-hidden flex flex-col min-h-0",children:[e.jsxs("div",{className:"px-3 py-2 bg-[#F9FAFB] dark:bg-[#111113] border-b border-[#E5E7EB] dark:border-[#27272a] text-[12px] text-[#6B7280] dark:text-[#71717a] font-mono flex items-center justify-between",children:[e.jsx("span",{children:v||"Select a file to preview"}),v&&e.jsx("span",{className:"text-[11px] text-[#9CA3AF] dark:text-[#a1a1aa] font-mono",children:G?"Loading…":Y?"Truncated":"Ready"})]}),Y&&!G&&e.jsx("div",{className:"px-3 py-2 bg-[#FEF3C7] dark:bg-[#111113] border-b border-[#E5E7EB] dark:border-[#27272a] text-[11px] text-[#b45309] dark:text-[#facc15] font-mono",children:"Preview truncated to 200k characters."}),e.jsxs("div",{className:"flex-1 min-h-0",children:[!v&&e.jsx("div",{className:"h-full flex items-center justify-center text-[12px] text-[#6B7280] dark:text-[#71717a] font-mono",children:"Pick a file from the tree to preview."}),v&&V&&e.jsx("div",{className:"h-full flex items-center justify-center text-[12px] text-[#DC2626] dark:text-[#fca5a5] font-mono",children:V}),v&&!V&&e.jsx("div",{className:"h-full",children:G?e.jsx(fe,{}):e.jsx(i.Suspense,{fallback:e.jsx(fe,{}),children:e.jsx(Pe,{content:ye,filename:v})})})]})]})]})]})}),e.jsx(W,{value:"logs",className:"overflow-hidden flex-1 mt-0",children:e.jsx("div",{className:"overflow-y-auto px-4 py-4 space-y-3 h-full",children:ee.length===0?e.jsx(R,{title:"No logs yet",subtitle:"Tool runs will appear here."}):ee.map(n=>{var y;const f=C[n.id],g=(n.content||"").split(`
2
- `),h=g.length>10||(((y=n.content)==null?void 0:y.length)||0)>800,k=f||!h?g:g.slice(0,8);return e.jsxs("div",{className:"border border-[#E5E7EB] dark:border-[#27272a] rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 bg-[#F9FAFB] dark:bg-[#111113] border-b border-[#E5E7EB] dark:border-[#27272a]",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"text-[12px] text-[#111827] dark:text-[#E5E5E5] font-mono",children:n.title}),n.subtitle&&e.jsx("div",{className:"text-[11px] text-[#6B7280] dark:text-[#71717a] font-mono",children:n.subtitle})]}),e.jsx(We,{status:n.status})]}),n.content&&e.jsxs("div",{className:"px-3 py-3 space-y-2",children:[e.jsxs("pre",{className:"text-[12px] text-[#374151] dark:text-[#d4d4d8] bg-[#F3F4F6] dark:bg-[#09090b] border border-[#E5E7EB] dark:border-[#27272a] rounded-md p-3 overflow-x-auto whitespace-pre-wrap font-mono",children:[k.join(`
3
- `),!f&&h&&`
4
- …`]}),h&&e.jsxs("button",{onClick:()=>Ne(n.id),className:"flex items-center gap-1 text-[12px] text-[#6B7280] dark:text-[#a1a1aa] font-mono hover:text-[#111827] dark:hover:text-[#E5E5E5] transition-colors",children:[f?e.jsx(ne,{className:"w-3 h-3"}):e.jsx(se,{className:"w-3 h-3"}),f?"Collapse":"Expand"]})]})]},n.id)})})})]})]})}function R({title:t,subtitle:a}){return e.jsxs("div",{className:"border border-dashed border-[#E5E7EB] dark:border-[#27272a] rounded-lg p-6 text-center",children:[e.jsx("div",{className:"text-[13px] text-[#111827] dark:text-[#E5E5E5] font-mono",children:t}),e.jsx("div",{className:"text-[12px] text-[#6B7280] dark:text-[#71717a] font-mono mt-1",children:a})]})}function We({status:t}){const a=t==="success"?"Success":t==="error"?"Failed":"Running",r=t==="success"?"bg-[#22C55E] text-white":t==="error"?"bg-[#FEE2E2] text-[#b91c1c] dark:bg-[#EF4444]/20 dark:text-[#fca5a5]":"bg-[#E5E7EB] text-[#6B7280] dark:bg-[#27272a] dark:text-[#a1a1aa]";return e.jsx("span",{className:F("text-[11px] px-2 py-0.5 rounded-full font-mono",r),children:a})}function he({node:t,depth:a,expandedDirs:r,childrenCache:s,toggleDir:o,onSelectFile:l,selectedPath:c}){const d=t.type==="dir",u=r[t.path],x=!d&&c===t.path,m=s[t.path]||[];return e.jsxs("div",{children:[e.jsx("button",{onClick:()=>{d?o(t.path):l(t.path)},className:F("flex items-center gap-2 w-full text-left text-[12px] font-mono px-2 py-1 rounded-md transition-colors",x?"bg-[#16A34A]/10 text-[#111827] dark:bg-[#22C55E]/10 dark:text-[#E5E5E5]":"hover:bg-[#F3F4F6] text-[#6B7280] dark:hover:bg-[#111113] dark:text-[#a1a1aa]",d&&"cursor-pointer",x&&"border border-[#16A34A]/30 dark:border-[#22C55E]/30"),style:{paddingLeft:a*14+8},children:d?e.jsxs(e.Fragment,{children:[u?e.jsx(Re,{className:"h-3.5 w-3.5 shrink-0 text-[#111827] dark:text-[#E5E5E5]"}):e.jsx(De,{className:"h-3.5 w-3.5 shrink-0 text-[#6B7280] dark:text-[#a1a1aa]"}),e.jsx("span",{className:"text-[#111827] dark:text-[#E5E5E5] truncate",children:t.name})]}):e.jsxs(e.Fragment,{children:[e.jsx(be,{className:"h-3.5 w-3.5 shrink-0 text-[#9CA3AF] dark:text-[#71717a]"}),e.jsx("span",{className:"text-[#111827] dark:text-[#E5E5E5] truncate",children:t.name})]})}),d&&u&&e.jsx("div",{children:m.map(b=>e.jsx(he,{node:b,depth:a+1,expandedDirs:r,childrenCache:s,toggleDir:o,onSelectFile:l,selectedPath:c},b.path))})]})}function qe(t){return t.flatMap(a=>{var o,l,c;const r=[];if((o=a.agentContent)!=null&&o.toolCalls)for(const d of a.agentContent.toolCalls){const u=le(d.arguments),x=d.output,m=x?(l=N(x))!=null&&l.diff?ce(x):x:void 0;r.push({id:`${a.id}-${d.toolCallId}`,title:d.toolName||"Tool",subtitle:d.summary,status:d.status==="success"?"success":d.status==="error"?"error":"running",content:m||(u?`Arguments:
5
- ${u}`:void 0),timestamp:a.timestamp})}const s=a.metadata;if(s){if(s.kind==="tool_call"){const d=s.toolName||"Tool",u=le(s.arguments);r.push({id:a.id,title:`Tool Call · ${d}`,subtitle:s.toolKind?String(s.toolKind):void 0,status:s.status==="success"?"success":s.status==="error"?"error":"running",content:u?`Arguments:
6
- ${u}`:void 0,timestamp:a.timestamp})}if(s.kind==="tool_result"){const d=s.toolName||"Tool",u=s.success,x=s.summary,m=s.output,b=m?(c=N(m))!=null&&c.diff?ce(m):m:void 0;r.push({id:a.id,title:`Tool Result · ${d}`,subtitle:x,status:u===void 0?"running":u?"success":"error",content:b,timestamp:a.timestamp})}}return r})}function Ie(t){var s;const a=[],r=new Set;for(let o=t.length-1;o>=0;o-=1){const l=t[o];if((s=l.agentContent)!=null&&s.toolCalls)for(let m=l.agentContent.toolCalls.length-1;m>=0;m-=1){const b=l.agentContent.toolCalls[m],p=b.metadata,q=b.output||"",E=N(q)||N((p==null?void 0:p.diff_snippet)||"");if(E!=null&&E.diff){const C=(p==null?void 0:p.file_path)||b.toolName||"unknown";if(!r.has(C)){r.add(C);const I=typeof(p==null?void 0:p.oldContent)=="string"?p.oldContent:void 0,v=typeof(p==null?void 0:p.newContent)=="string"?p.newContent:void 0;a.push({diff:E.diff,filePath:C,summary:b.summary,oldContent:I,newContent:v})}}}const c=l.metadata;if(!c||c.kind!=="tool_result")continue;const d=c.metadata,u=c.output||(typeof l.content=="string"?l.content:"")||"",x=N(u)||N((d==null?void 0:d.diff_snippet)||"");if(x!=null&&x.diff){const m=(d==null?void 0:d.file_path)||c.toolName||"unknown";if(!r.has(m)){r.add(m);const b=typeof(d==null?void 0:d.oldContent)=="string"?d.oldContent:void 0,p=typeof(d==null?void 0:d.newContent)=="string"?d.newContent:void 0;a.push({diff:x.diff,filePath:m,summary:c.summary,oldContent:b,newContent:p})}}}return a.reverse()}function N(t){if(!t)return null;const a=/<<<DIFF>>>\s*([\s\S]*?)\s*<<<\/DIFF>>>/m,r=t.match(a);if(!r)return null;try{return{diff:JSON.parse(r[1])}}catch{return null}}function ce(t){return t?t.replace(/<<<DIFF>>>[\s\S]*?<<<\/DIFF>>>/m,"").trim():""}function le(t){if(!t)return"";if(typeof t=="string")try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}return JSON.stringify(t,null,2)}function fe(){return e.jsx("div",{className:"h-full flex items-center justify-center text-[12px] text-[#6B7280] dark:text-[#71717a] font-mono",children:"Loading editor…"})}function Pe({content:t,filename:a}){const{theme:r}=Se(),s=i.useRef(null),[o,l]=i.useState("vs-dark"),c=Ge(a),d=u=>{s.current=u;const x=de(u,r);l(x)};return i.useEffect(()=>{if(s.current){const u=de(s.current,r);l(u)}},[r]),e.jsx(ze,{value:t,language:c,theme:o,height:"100%",beforeMount:d,options:{readOnly:!0,minimap:{enabled:!1},fontSize:12,lineNumbers:"on",wordWrap:"on",scrollBeyondLastLine:!1,automaticLayout:!0}},a)}function Ge(t){var s;const a=((s=t.split(".").pop())==null?void 0:s.toLowerCase())||"";return{ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",json:"json",md:"markdown",css:"css",scss:"scss",html:"html",yml:"yaml",yaml:"yaml",go:"go",rs:"rust",py:"python",java:"java",c:"c",cpp:"cpp",h:"cpp",hpp:"cpp",sh:"shell",zsh:"shell",toml:"toml",xml:"xml"}[a]||"plaintext"}function Oe({diff:t}){const a=t.patch.split(`
7
- `);let r=0,s=0;return e.jsxs("div",{className:"border border-[#E5E7EB] dark:border-[#27272a] rounded-md overflow-hidden bg-white dark:bg-[#111113]",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-[#E5E7EB] dark:border-[#27272a] bg-[#F9FAFB] dark:bg-[#111113] text-[12px] text-[#6B7280] dark:text-[#71717a] font-mono",children:[e.jsx("span",{children:"Patch"}),t.matchLine&&e.jsxs("span",{children:["Line ",t.matchLine]})]}),e.jsx("div",{className:"text-[12px] font-mono",children:a.map((o,l)=>{if(o.startsWith("@@")){const c=/@@ -(?<old>\d+),?(?<oldCount>\d*) \+(?<new>\d+),?(?<newCount>\d*) @@/.exec(o);return c!=null&&c.groups&&(r=parseInt(c.groups.old,10),s=parseInt(c.groups.new,10)),e.jsx(w,{line:o},`${o}-${l}`)}if(o.startsWith("---")||o.startsWith("+++")||o.startsWith("Index:")||o.startsWith("==="))return e.jsx(w,{line:o},`${o}-${l}`);if(o.startsWith("+")){const c=s;return s+=1,e.jsx(w,{line:o,oldLine:null,newLine:c},`${o}-${l}`)}if(o.startsWith("-")){const c=r;return r+=1,e.jsx(w,{line:o,oldLine:c,newLine:null},`${o}-${l}`)}if(o.startsWith(" ")){const c=r,d=s;return r+=1,s+=1,e.jsx(w,{line:o,oldLine:c,newLine:d},`${o}-${l}`)}return e.jsx(w,{line:o},`${o}-${l}`)})})]})}function w({line:t,oldLine:a,newLine:r}){const s=t.startsWith("---")||t.startsWith("+++")||t.startsWith("Index:")||t.startsWith("==="),o=t.startsWith("@@"),l=t[0],c=s||o?t:t.slice(1),d=s?"text-[#6B7280] dark:text-[#a1a1aa]":l==="+"?"text-[#166534] bg-[#22C55E]/10 dark:text-[#86efac] dark:bg-[#22C55E]/10":l==="-"?"text-[#b91c1c] bg-[#EF4444]/10 dark:text-[#fca5a5] dark:bg-[#EF4444]/10":o?"text-[#1d4ed8] bg-[#DBEAFE] dark:text-[#93c5fd] dark:bg-[#1e3a8a]/30":"text-[#374151] dark:text-[#d4d4d8]";return e.jsxs("div",{className:F("grid grid-cols-[40px_40px_1fr] gap-2 px-3 py-0.5",d),children:[e.jsx("span",{className:"text-right text-[#9CA3AF] dark:text-[#71717a]",children:a?String(a).padStart(2," "):""}),e.jsx("span",{className:"text-right text-[#9CA3AF] dark:text-[#71717a]",children:r?String(r).padStart(2," "):""}),e.jsx("span",{className:"whitespace-pre",children:c})]})}export{Ye as FilePreview};