blade-code 0.10.0 → 0.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-0h9m2fqd.js +160 -0
  3. package/dist/chunk-1wyfb6s7.js +1 -0
  4. package/dist/{chunk-ty2kc6kg.js → chunk-2km4w0ky.js} +1 -1
  5. package/dist/{chunk-2fdjn926.js → chunk-3vyjshqp.js} +1 -1
  6. package/dist/{chunk-61087jc8.js → chunk-5tfzehcg.js} +1 -1
  7. package/dist/{chunk-mvwp3c11.js → chunk-6sc78810.js} +1 -1
  8. package/dist/{chunk-bx50res5.js → chunk-8mepk4tc.js} +1 -1
  9. package/dist/{chunk-hzvp3bc1.js → chunk-bpzv054r.js} +1 -1
  10. package/dist/{chunk-7dcm1aqd.js → chunk-bqk3wqts.js} +1 -1
  11. package/dist/{chunk-949btxxx.js → chunk-cjdnfyy0.js} +3 -3
  12. package/dist/{chunk-vyq9r31h.js → chunk-ct32ngah.js} +1 -1
  13. package/dist/{chunk-bqdc3m0p.js → chunk-d8zj7c0t.js} +1 -1
  14. package/dist/{chunk-zcw7kyf4.js → chunk-e2ccyhgz.js} +1 -1
  15. package/dist/{chunk-w4qsayn6.js → chunk-gr5mzxdf.js} +1 -1
  16. package/dist/{chunk-0aj7gp37.js → chunk-k89phc5j.js} +1 -1
  17. package/dist/{chunk-z5ae4qvf.js → chunk-k9a1vb8a.js} +1 -1
  18. package/dist/{chunk-hh3xw391.js → chunk-m5tjrr5c.js} +1 -1
  19. package/dist/{chunk-vb0t2hhd.js → chunk-m9zpxzg2.js} +1 -1
  20. package/dist/{chunk-v4mr98vm.js → chunk-nqq4sbmv.js} +1 -1
  21. package/dist/{chunk-9jy87d0y.js → chunk-p7ppnewt.js} +1 -1
  22. package/dist/{chunk-93ptxa5p.js → chunk-qhf0knnx.js} +1 -1
  23. package/dist/{chunk-6qe5k7dw.js → chunk-rkzds6k8.js} +2 -2
  24. package/dist/{chunk-cznge1n7.js → chunk-tckfyfsx.js} +1 -1
  25. package/dist/{chunk-e3tk2jna.js → chunk-tm2ckreq.js} +1 -1
  26. package/dist/{chunk-mxhg6jt9.js → chunk-ws3gc024.js} +1 -1
  27. package/dist/{chunk-f8db8ftd.js → chunk-xhpezpjq.js} +1 -1
  28. package/dist/{chunk-yvah5h4x.js → chunk-y0hwzmdn.js} +1 -1
  29. package/dist/{chunk-8rg05w47.js → chunk-y5vq7gek.js} +1 -1
  30. package/dist/{chunk-7eptyk20.js → chunk-ydqeg4p8.js} +1 -1
  31. package/dist/{chunk-mwrn7mcr.js → chunk-yknrffcs.js} +1 -1
  32. package/dist/{chunk-9kd14cwq.js → chunk-ymmtbq2b.js} +1 -1
  33. package/dist/{chunk-3c5gvxr6.js → chunk-z2yzyr9h.js} +1 -1
  34. package/package.json +1 -1
  35. package/dist/chunk-fjp5tvh8.js +0 -1
  36. package/dist/chunk-wsqz3x2e.js +0 -161
@@ -1,161 +0,0 @@
1
- import{e as VJ,f as jJ}from"./chunk-wvj9h7mb.js";import{i as P4,j as y4,k as M4}from"./chunk-th7sxjtk.js";import{$ as s2,E as z$,F as L2,G as B2,J as e$,K as nJ,L as tJ,O as sJ,P as eJ,U as q9,V as K9,W as h4,X as v2,Z as C2,r as t2,u as aQ,v as xQ,w as x2,x as E4}from"./chunk-949btxxx.js";import{da as qJ,ea as KJ,fa as OJ,ia as j4}from"./chunk-mxhg6jt9.js";import{qa as D2}from"./chunk-8rg05w47.js";import{La as J8}from"./chunk-88vy9hh0.js";import{$a as R2,Za as A2,_a as gQ,db as s$,gb as E0}from"./chunk-bx50res5.js";import"./chunk-44wkjs2j.js";import{Eb as A4}from"./chunk-nah0cbnp.js";import{Fb as Y8,Gb as p8,Ib as I1}from"./chunk-61087jc8.js";import"./chunk-kq5my0yy.js";import{$b as WQ,Mb as M$,Nb as l0,Ob as t1,Pb as w6,Qb as k$,Rb as V8,Sb as g9,Tb as h6,Ub as IJ,Vb as m9,Wb as C$,Xb as Y1,Yb as D4,Zb as r0,_b as b4,ac as $8,dc as M2,kc as u0}from"./chunk-vb0t2hhd.js";import"./chunk-gafbzeyk.js";import"./chunk-0h81hxkw.js";import"./chunk-af49jmns.js";import{uc as g6}from"./chunk-px5ck9pf.js";import"./chunk-fjw32ex5.js";import"./chunk-z5ae4qvf.js";import{Ac as X9,Dc as O4,Jc as iJ,Pc as V4}from"./chunk-e3tk2jna.js";import"./chunk-d9ddpapp.js";import"./chunk-sndbq5xt.js";import{Yc as R6,_c as F1}from"./chunk-mvwp3c11.js";import"./chunk-beqaxytd.js";import{ad as k4,dd as i1}from"./chunk-jxv6r0c7.js";import{Hd as S4,Sd as f4}from"./chunk-hzvp3bc1.js";import"./chunk-4vaywb2r.js";import{be as S$,ce as j8}from"./chunk-qev36qrb.js";import{he as A0}from"./chunk-vjpd3nee.js";import{ie as SJ,je as fJ,me as f1}from"./chunk-a7nbn5kf.js";import"./chunk-2beq0syt.js";import{ye as wJ}from"./chunk-0aj7gp37.js";import{ze as l6}from"./chunk-6hj2dk75.js";import"./chunk-6n5xdf2r.js";import"./chunk-8nm1hqr1.js";import{Le as A6}from"./chunk-mjp61rqd.js";import{useMemoizedFn as IQ}from"ahooks";import{useEffect as XX,useState as vQ}from"react";import{useMemoizedFn as t0}from"ahooks";import{Box as G$}from"ink";import{useEffect as q$,useMemo as $X,useRef as PQ}from"react";import{useShallow as m4}from"zustand/react/shallow";import{useStore as g4}from"zustand";function $0($){return g4(C$,$)}var p4=[],R8=()=>$0(($)=>$.session.sessionId),M1=()=>$0(($)=>$.session.workspaceRoot),r6=()=>$0(($)=>$.session.messages),a6=()=>$0(($)=>$.session.clearCount),o6=()=>$0(($)=>$.session.isCompacting),i6=()=>$0(($)=>$.session.tokenUsage.estimatedCostUsd),r1=()=>$0(($)=>$.session.actions),n6=()=>$0(($)=>{let{inputTokens:Q,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let J=Math.max(0,100-Q/Y*100);return Math.round(J)}),t6=()=>$0(($)=>$.app.initializationStatus),s6=()=>$0(($)=>$.app.initializationError),P8=()=>$0(($)=>$.app.activeModal),e6=()=>$0(($)=>$.app.tasks),$2=()=>$0(($)=>$.app.modelEditorTarget),Q2=()=>$0(($)=>$.app.sessionSelectorData),J2=()=>$0(($)=>$.app.awaitingSecondCtrlC),a1=()=>$0(($)=>$.app.actions),y8=()=>$0(($)=>$.app.initializationStatus==="ready"),Y2=()=>$0(($)=>$.app.tasks.length>0),T$=()=>$0(($)=>$.config.config?.permissionMode||"default"),Z2=()=>$0(($)=>$.config.config?.models??p4),M8=()=>$0(($)=>{let Q=$.config.config;if(!Q)return;let Y=Q.currentModelId;return Q.models.find((Z)=>Z.id===Y)??Q.models[0]}),I8=()=>$0(($)=>$.config.config?.currentModelId),b0=()=>$0(($)=>{return l0.getTheme()}),X2=()=>$0(($)=>$.config.config?.theme??"default"),s0=()=>$0(($)=>$.focus.currentFocus),U2=()=>$0(($)=>$.focus.actions),o1=()=>$0(($)=>$.command.isProcessing),G2=()=>$0(($)=>$.command.actions),v8=()=>$0(($)=>$.command.pendingCommands),q2=()=>$0(($)=>$.command.recoveredSteeringCount),C8=()=>$0(($)=>$.app.thinkingModeEnabled),T8=()=>$0(($)=>$.app.reasoningEffort),k8=()=>$0(($)=>$.app.serviceTier),S8=()=>$0(($)=>$.app.responseVerbosity),f8=()=>$0(($)=>$.app.communicationStyle),K2=()=>$0(($)=>$.session.currentThinkingContent),O2=()=>$0(($)=>$.session.thinkingExpanded),z2=()=>$0(($)=>$.session.currentStreamingMessageId),_2=()=>$0(m4(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),N2=()=>$0(($)=>$.session.finalizingStreamingMessageId),F2=()=>$0(($)=>$.session.historyExpanded),H2=()=>$0(($)=>$.session.expandedMessageCount);import{useMemoizedFn as D$}from"ahooks";import{useEffect as EQ,useRef as f2}from"react";function c4($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let U=JSON.parse(J.responseBody)?.error?.message;if(U){let G=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${U}${G}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function x4($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function u4($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function D8($){let Q=x4($),Y=u4($),J;if(Y)J="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else J=c4($);return{displayMessage:J,isAbort:Q,isVisionNotSupported:Y}}import{appendFileSync as d4,mkdirSync as l4,writeFileSync as r4}from"node:fs";import a4 from"node:os";import SQ from"node:path";var W2=null;function o4(){let $=process.env.BLADE_STORAGE_ROOT||SQ.join(a4.homedir(),".blade");return SQ.join($,"logs","stream-debug.log")}function i4($){if(W2===$)return;let Q=SQ.dirname($);l4(Q,{recursive:!0,mode:493}),r4($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
2
- `),W2=$}function fQ($,Q,Y){try{let J=o4();i4(J);let Z=new Date().toISOString(),X=Y?` | ${JSON.stringify(Y)}`:"",U=`[${Z}] [${$}] ${Q}${X}
3
- `;d4(J,U)}catch{}}var t$=i1("UI");function w2($,Q){let Y=!1;return(J)=>{switch(J.kind){case"content_delta":if(Y||$.signal.aborted)break;Q.contentDeltaCount++,Q.contentDeltaTotalLen+=J.delta.length,fQ("loopEventHandler","onContentDelta",{callCount:Q.contentDeltaCount,deltaLen:J.delta.length,totalLen:Q.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(J.delta);break;case"thinking_delta":if(Y||$.signal.aborted)break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(J.delta);break;case"stream_end":{if(t$.debug("[loopEventHandler] stream_end",{contentDeltaCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),fQ("loopEventHandler","onStreamEnd",{contentDeltaCallCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),Y||$.signal.aborted){Y=!0;break}let{extraContent:Z,extraThinking:X}=$.streamingBuffer.drainPendingBuffers(),U=$.getStreamingMessageId();if(U){if(Z)k$(U,Z);V8(U)}$.sessionActions.finalizeStreamingMessage(Z,X),Y=!0;break}case"model_fallback":Y=!0,$.streamingBuffer.resetStreamingBuffers(),$.sessionActions.discardStreamingMessage(),$.sessionActions.setCurrentThinkingContent(null);break;case"tool_start":{let Z=J.toolCall;if(!("function"in Z))break;if(t$.debug("[loopEventHandler] tool_start",{toolName:Z.function.name,toolKind:J.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(Z.function.name))break;try{let X=JSON.parse(Z.function.arguments),U=L2(Z.function.name,X);$.sessionActions.addToolMessage(U,{toolCallId:Z.id,toolName:Z.function.name,phase:"start",summary:U,params:X})}catch(X){t$.error("[loopEventHandler] onToolStart error:",X)}break}case"tool_progress":{let Z=J.toolCall;if(!("function"in Z))break;let X=J.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((J.update.progress??0)/J.update.total*100)))}%`:"",U=`${Z.function.name}${X}: ${J.update.message}`;$.sessionActions.addToolMessage(U,{toolCallId:Z.id,toolName:Z.function.name,phase:"progress",summary:U});break}case"tool_result":{let Z=J.toolCall;if(!("function"in Z))break;t$.debug("[loopEventHandler] tool_result",{toolName:Z.function.name,success:J.result.success});let X=B2(Z.function.name,J.result);$.sessionActions.addToolMessage(X.summary,{toolCallId:Z.id,toolName:Z.function.name,phase:"complete",summary:X.summary,detail:X.detail});break}case"token_usage":$.sessionActions.updateTokenUsage(J.usage);break;case"compaction":if($.sessionActions.setCompacting(J.phase==="start"),J.phase==="end")$.sessionActions.resetContextUsage();break;case"turn_start":t$.debug("[loopEventHandler] turn_start",{turn:J.turn,maxTurns:J.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:J.turn}),Y=!1;break;case"task_update":$.appActions.setTasks(J.tasks);break;case"mcp_catalog_changed":{let Z=`MCP catalog r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Catalog",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
4
- `)});break}case"mcp_content_changed":{let Z=`MCP ${J.contentKind} r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Content",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
5
- `)});break}case"mcp_resource_updated":{let Z=`MCP resource updated: ${J.uri}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Resource",phase:"progress",summary:Z,detail:`${J.serverName} · revision ${J.revision}`});break}case"mcp_connection_changed":{let Z=J.phase==="reconnecting"?"recovering":J.phase==="recovered"?"recovered":"recovery failed",X=`MCP ${J.serverName} ${Z}`+(J.phase==="reconnecting"?` (${J.attempt}/${J.maxAttempts})`:"");$.sessionActions.addToolMessage(X,{toolName:"MCP Connection",phase:"complete",summary:X,detail:[`reason: ${J.reason}`,`revision: ${J.revision}`,J.error?`error: ${J.error}`:""].filter(Boolean).join(`
6
- `)});break}case"mcp_log":{let Z=J.logger?`${J.serverName} · ${J.logger}`:J.serverName,X=`MCP ${J.level} · ${Z}`;$.sessionActions.addToolMessage(X,{toolName:"MCP Log",phase:"complete",summary:X,detail:[J.message,`revision: ${J.revision}`,`sha256: ${J.dataSha256}`,J.truncated?"truncated: true":"",J.detailsOmitted?"details omitted by runtime policy":""].filter(Boolean).join(`
7
- `)});break}case"mcp_instructions_changed":{let Z=`MCP instructions ${J.action}: ${J.serverName}`+(J.truncated?" (truncated)":"");$.sessionActions.addToolMessage(Z,{toolName:"MCP Instructions",phase:"complete",summary:Z,detail:[J.text??"",J.sha256?`sha256: ${J.sha256}`:"",J.detailsOmitted?"details omitted by runtime policy":""].filter(Boolean).join(`
8
- `)});break}case"mcp_task_changed":{let Z=`MCP task ${J.status}: ${J.taskId} (${J.serverName}/${J.toolName})`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Task",phase:"complete",summary:Z,detail:[J.statusMessage??"",`revision: ${J.revision}`,J.hasResult?"result available via TaskOutput":"",J.error?`error: ${J.error}`:""].filter(Boolean).join(`
9
- `)});break}case"project_rules_loaded":{let Z=`Project rules loaded: ${J.files.length}`+(J.blockedWrite?" (write retry required)":"");$.sessionActions.addToolMessage(Z,{toolName:"Project Rules",phase:"complete",summary:Z,detail:J.files.map((X)=>`${X.relativePath} ${X.source} sha256=${X.contentSha256}`).join(`
10
- `)});break}case"steering_applied":for(let Z=0;Z<J.count;Z++)$.commandActions.dequeueCommand();if(J.recovered>0)$.commandActions.setRecoveredSteeringCount(J.recovered);break;case"follow_up_started":for(let Z of J.messages){if(!Z.recovered||Z.persisted)continue;let X=typeof Z.content==="string"?Z.content:Z.content.map((U)=>U.type==="text"?U.text:"[Image]").join(`
11
- `);$.sessionActions.addUserMessage(X)}if(J.recovered>0)$.commandActions.setRecoveredSteeringCount(J.recovered);break;case"goal_updated":case"goal_continuation_started":break;case"subagent_spawned":case"subagent_completed":break;default:{let Z=J}}}}function VQ($){let{text:Q,parts:Y}=$,J=Y.filter((U)=>U.type==="image");if(J.length===0)return Q;if(J.length>S$)throw Error(`最多只能发送 ${S$} 张图片`);if(J.reduce((U,G)=>U+`data:${G.mimeType};base64,`.length+G.base64.length,0)>j8)throw Error("图片编码后总大小不能超过 5 MiB");let X=[];for(let U of Y)if(U.type==="text")X.push({type:"text",text:U.text});else X.push({type:"image_url",image_url:{url:`data:${U.mimeType};base64,${U.base64}`}});return X}function b2($){let Q=R2($.metadata);return{role:$.role,content:Q?A2(Q):$.content,...$.metadata?{metadata:$.metadata}:{}}}function E8($){if(!$.restoredContextMessages||$.restoredVisibleMessageCount<=0)return $.messages.map(b2);let Q=$.messages.slice($.restoredVisibleMessageCount).map(b2);return[...$.restoredContextMessages,...Q]}import n4 from"node:path";function P2($){if($.length<=8)return $;return`${$.slice(0,8)}…`}function t4($){return n4.resolve($)}function y2($){if(!$||!M2($))return;Y1().config.actions.updateConfig({currentModelId:$})}async function h8($,Q){return E0.listSessions({includeSubagents:!1})}async function g8($,Q,Y,J){let{intent:Z,session:X,newSessionId:U,announceFork:G}=$,q=t4(X.projectPath);if(Z==="fork"){let O=await E0.forkSession(X.sessionId,{...U?{newSessionId:U}:{},sourceProjectPath:q,targetProjectPath:q}),B=[...E0.toUISafeMessages(O.messages)];if(G!==!1){let _=Date.parse(O.metadata.lastMessageTime);B.push({id:"fork-announcement-"+O.sessionId,role:"assistant",content:"Forked "+P2(X.sessionId)+" → "+P2(O.sessionId),timestamp:Number.isNaN(_)?0:_})}return await J(),y2(O.metadata.selectedModelId),Y.restoreSession(O.sessionId,B,O.messages,O.metadata.projectPath),{sessionId:O.sessionId,messages:O.messages}}await E0.assertSessionWritable(X.sessionId,X.projectPath);let K=await E0.loadSession(X.sessionId,X.projectPath),W=E0.toUISafeMessages(K);return await J(),y2(X.selectedModelId),Y.restoreSession(X.sessionId,W,K,X.projectPath),{sessionId:X.sessionId,messages:K}}function I2($){return typeof $==="object"&&$!==null&&typeof $.sessionId==="string"&&typeof $.projectPath==="string"&&typeof $.rootId==="string"&&typeof $.messageCount==="number"&&typeof $.firstMessageTime==="string"&&typeof $.lastMessageTime==="string"&&typeof $.hasErrors==="boolean"}function s4($){return typeof $==="object"&&$!==null&&$.action==="invoke_skill"&&typeof $.skillName==="string"}function e4($){return typeof $==="object"&&$!==null&&$.action==="invoke_custom_command"&&typeof $.commandName==="string"&&typeof $.processedContent==="string"}function $Y($){return typeof $==="object"&&$!==null&&$.action==="invoke_plugin_command"&&typeof $.commandName==="string"&&typeof $.processedContent==="string"}function QY($){return typeof $==="object"&&$!==null&&$.action==="invoke_once_model"&&typeof $.modelId==="string"&&typeof $.prompt==="string"}function JY($){return typeof $==="object"&&$!==null&&["start_goal","resume_goal"].includes(String($.action))&&typeof $.goal?.objective==="string"}function YY($){return typeof $==="object"&&$!==null&&$.action==="rewind_session"&&typeof $.sessionId==="string"&&Array.isArray($.messages)&&Array.isArray($.visibleMessages)}function ZY($){if(typeof $!=="object"||$===null)return!1;let Q=$.intent;if(Q!=="resume"&&Q!=="fork")return!1;let Y=$.action;if(Y==="select_session"){let J=$.sessions;return Array.isArray(J)&&J.every((Z)=>I2(Z))}if(Y==="activate_session")return I2($.session);return!1}function XY($,Q,Y,J){switch($){case"show_theme_selector":return Y.setActiveModal("themeSelector"),!0;case"show_model_selector":return Y.setActiveModal("modelSelector"),!0;case"show_model_add_wizard":return Y.setActiveModal("modelAddWizard"),!0;case"show_permissions_manager":return Y.setActiveModal("permissionsManager"),!0;case"show_agents_manager":return Y.setActiveModal("agentsManager"),!0;case"show_skills_manager":return Y.setActiveModal("skillsManager"),!0;case"show_hooks_manager":return Y.setActiveModal("hooksManager"),!0;case"show_plugins_manager":return Y.setActiveModal("pluginsManager"),!0;case"show_agent_creation_wizard":return Y.setActiveModal("agentCreationWizard"),!0;case"show_session_selector":{let Z=Q?.sessions;return Y.showSessionSelector(Z??[],"resume"),!0}case"session_forked":{let Z=Q;if(Z?.action!=="restore_forked_session"||!Z.sessionId||!Array.isArray(Z.messages)||!Array.isArray(Z.visibleMessages))return!1;return J.restoreSession(Z.sessionId,Z.visibleMessages,Z.messages),!0}case"session_archived":{let Z=Q?.session;return J.addAssistantMessage(Z?`会话 ${Z.sessionId} 已归档。`:"当前会话已归档。"),I1(0),!0}case"clear_screen":return J.clearMessages(),J.setError(null),J.resetTokenUsage(),Y.setTasks([]),!0;case"compact_completed":case"compact_fallback":{let Z=Q,X=Z?.compactedMessages;if(X)J.setCompactedContext(X);if(Z?.usage)J.updateTokenUsage({inputTokens:Z.usage.promptTokens,outputTokens:Z.usage.completionTokens,totalTokens:Z.usage.totalTokens,maxContextTokens:Z.maxContextTokens,cacheReadTokens:Z.usage.cacheReadInputTokens??0,cacheWriteTokens:Z.usage.cacheCreationInputTokens??0,costUsd:Z.usage.costUsd});return J.resetContextUsage(),!0}case"exit_application":return I1(0),!0;default:return!1}}async function jQ($,Q,Y,J,Z,X,U,G,q,K,W,O,B,_,b=A0()){let{text:z}=$;if(!v2(z))return{type:"not_slash"};let F=await C2(z,{cwd:b,surface:"tui",workspaceRoot:b,sessionId:X,messages:U,rewind:G,lifecycle:X===void 0?void 0:{archiveCurrent:async()=>{return await Z(),E0.archiveSession(X,b)}},subagents:q,mcp:K,reasoning:W,serviceTier:O,responseVerbosity:B,communicationStyle:_,signal:J});if(F.success&&ZY(F.data)){if(F.data.action==="select_session")return Q.showSessionSelector(F.data.sessions,F.data.intent),{type:"handled",commandResult:{success:!0}};return await g8(F.data,b,Y,Z),{type:"handled",commandResult:{success:!0}}}if(F.success&&YY(F.data))return Y.restoreSession(F.data.sessionId,F.data.visibleMessages,F.data.messages),Q.setTasks([]),{type:"handled",commandResult:{success:!0}};if(F.message){if(XY(F.message,F.data,Q,Y))return{type:"handled",commandResult:{success:!0}}}if(s4(F.data)){let{skillName:v,skillArgs:C}=F.data,N=C?`Please use the "${v}" skill to help me with: ${C}`:`Please use the "${v}" skill.`;return Y.addUserMessage(N),{type:"continue_as_agent",result:{userDisplayMessage:N,agentInput:{displayText:N,text:N,images:[],parts:[{type:"text",text:N}]},userMessageAlreadyAdded:!0}}}if(e4(F.data)){let{commandName:v,processedContent:C}=F.data;Y.addUserMessage(z);let N=`# Custom Command: /${v}
12
-
13
- The user has invoked the custom command "/${v}". Follow the instructions below to complete the task.
14
-
15
- ---
16
-
17
- ${C}
18
-
19
- ---
20
-
21
- Remember: Follow the above instructions carefully to complete the user's request.`;return{type:"continue_as_agent",result:{userDisplayMessage:z,agentInput:{displayText:z,text:N,images:[],parts:[{type:"text",text:N}]},userMessageAlreadyAdded:!0}}}if($Y(F.data)){let{commandName:v,pluginName:C,processedContent:N}=F.data;Y.addUserMessage(z);let P=`# Plugin Command: /${v}
22
-
23
- The user has invoked the plugin command "/${v}" from plugin "${C}". Follow the instructions below to complete the task.
24
-
25
- ---
26
-
27
- ${N}
28
-
29
- ---
30
-
31
- Remember: Follow the above instructions carefully to complete the user's request.`;return{type:"continue_as_agent",result:{userDisplayMessage:z,agentInput:{displayText:z,text:P,images:[],parts:[{type:"text",text:P}]},userMessageAlreadyAdded:!0}}}if(QY(F.data)){let{modelId:v,prompt:C}=F.data;return Y.addUserMessage(C),{type:"continue_as_agent",result:{userDisplayMessage:C,agentInput:{displayText:C,text:C,images:[],parts:[{type:"text",text:C}]},userMessageAlreadyAdded:!0,onceModelId:v}}}if(JY(F.data)){let v=F.data.goal.objective;return Y.addUserMessage(z),{type:"continue_as_agent",result:{userDisplayMessage:z,agentInput:{displayText:z,text:v,images:[],parts:[{type:"text",text:v}]},userMessageAlreadyAdded:!0,goalContinuationOnly:!0}}}if(!F.success&&F.error)return Y.addAssistantMessage(`${F.error}`),{type:"handled",commandResult:{success:F.success,output:F.message,error:F.error,metadata:F.data}};let A=F.message;if(F.success&&typeof A==="string"&&A.trim()!=="")Y.addAssistantMessage(A);return{type:"handled",commandResult:{success:F.success,output:F.message,error:F.error,metadata:F.data}}}import{useMemoizedFn as y0}from"ahooks";import{useEffect as UY,useRef as m8}from"react";function T2($){let Q=m8(void 0),Y=m8(void 0),J=m8(void 0),Z=m8(void 0),X=y0(async()=>{if(Z.current)return Z.current;let I=Q.current,L=Y.current;if(!I&&!L)return;Q.current=void 0,Y.current=void 0,J.current=void 0;let M=(async()=>{try{await I?.destroy()}finally{await L?.dispose()}})();Z.current=M;try{await M}finally{if(Z.current===M)Z.current=void 0}}),U=y0(async(I)=>{let L=$.workspaceRoot??Y.current?.workspaceRoot??A0();if(Y.current&&(Y.current.sessionId!==I||Y.current.workspaceRoot!==L))await X();if(!Y.current){let M=await E0.findSessionMetadata(I,L),V=M!==void 0&&(await E0.loadSession(I,L)).length>0;Y.current=await z$.create({sessionId:I,workspaceRoot:L,modelId:$.modelId,reasoningEffort:M?.reasoningEffort??$.reasoningEffort,serviceTier:M?.serviceTier??$.serviceTier,responseVerbosity:M?.responseVerbosity??$.responseVerbosity,communicationStyle:M?.communicationStyle??$.communicationStyle,communicationStyleDigest:M?.communicationStyleDigest,agents:$.agents,...V?{sessionStart:{isResume:!0,resumeSessionId:I}}:{}});try{J.current={sessionId:I,modelId:M?.selectedModelId,reasoningEffort:M?.reasoningEffort,serviceTier:M?.serviceTier,responseVerbosity:M?.responseVerbosity,communicationStyle:M?.communicationStyle,communicationStyleDigest:M?.communicationStyleDigest},r0().setReasoningEffort(Y.current.getReasoningConfiguration().selection),r0().setServiceTier(Y.current.getServiceTierConfiguration().selection),r0().setResponseVerbosity(Y.current.getResponseVerbosityConfiguration().selection),r0().setCommunicationStyle(Y.current.getCommunicationStyleConfiguration().selection)}catch(k){let u=Y.current;throw Y.current=void 0,await u.dispose().catch(()=>{return}),k}}return Y.current}),G=y0(async(I)=>{let L=I?.sessionId??$.sessionId,M=!!I?.modelId&&I.modelId!==$.modelId,V;if(!M&&L){let k=Y.current!==void 0,u=await U(L),j=I?.modelId??$.modelId,m=I?.reasoningEffort??(k?$.reasoningEffort:u.getReasoningConfiguration().selection),f=I?.serviceTier??(k?$.serviceTier:u.getServiceTierConfiguration().selection),n=I?.responseVerbosity??(k?$.responseVerbosity:u.getResponseVerbosityConfiguration().selection),_0=I?.communicationStyle??(k?$.communicationStyle:u.getCommunicationStyleConfiguration().selection),N0=u.getCurrentModelId(),m0=u.getReasoningConfiguration(),D0=u.getServiceTierConfiguration(),w0=u.getResponseVerbosityConfiguration(),_1=u.getCommunicationStyleConfiguration();await u.refresh({modelId:j,...m?{reasoningEffort:m}:{},...f?{serviceTier:f}:{},...n?{responseVerbosity:n}:{},..._0?{communicationStyle:_0}:{}});let N1=u.getCommunicationStyleConfiguration();if(N1.source!=="built-in"&&!N1.contentSha256)throw Error("Custom communication style has no provenance");let v$={...j&&j!=="inherit"&&(J.current?.sessionId!==L||J.current.modelId!==j)?{selectedModelId:j}:{},...m&&(J.current?.sessionId!==L||J.current.reasoningEffort!==m)?{reasoningEffort:m}:{},...f&&(J.current?.sessionId!==L||J.current.serviceTier!==f)?{serviceTier:f}:{},...n&&(J.current?.sessionId!==L||J.current.responseVerbosity!==n)?{responseVerbosity:n}:{},..._0&&(J.current?.sessionId!==L||J.current.communicationStyle!==_0||J.current.communicationStyleDigest!==N1.contentSha256)?{communicationStyle:_0,communicationStyleDigest:N1.source==="built-in"?null:N1.contentSha256}:{}};if(Object.keys(v$).length>0)try{let G1=await E0.updateSessionMetadata(L,u.workspaceRoot,v$);J.current={sessionId:L,modelId:G1.selectedModelId,reasoningEffort:G1.reasoningEffort,serviceTier:G1.serviceTier,responseVerbosity:G1.responseVerbosity,communicationStyle:G1.communicationStyle,communicationStyleDigest:G1.communicationStyleDigest}}catch(G1){throw await u.refresh({...N0?{modelId:N0}:{},reasoningEffort:m0.selection,serviceTier:D0.selection,responseVerbosity:w0.selection,communicationStyle:_1.selection}).catch(()=>{return}),G1}V=await e$.createWithRuntime(u,{sessionId:L,systemPrompt:I?.systemPrompt??$.systemPrompt,appendSystemPrompt:I?.appendSystemPrompt??$.appendSystemPrompt,maxTurns:I?.maxTurns??$.maxTurns,modelId:I?.modelId??$.modelId,agents:$.agents})}else V=await e$.create({systemPrompt:I?.systemPrompt??$.systemPrompt,appendSystemPrompt:I?.appendSystemPrompt??$.appendSystemPrompt,maxTurns:I?.maxTurns??$.maxTurns,modelId:I?.modelId??$.modelId,agents:$.agents});return Q.current=V,V}),q=y0(async()=>{if(!$.sessionId)throw Error("No active session to rewind");return(await U($.sessionId)).listRewindCheckpoints()}),K=y0(async(I)=>{if(!$.sessionId)throw Error("No active session to rewind");let M=await(await U($.sessionId)).rewindSession(I);return await X(),M}),W=y0(async()=>{if(!$.sessionId)throw Error("No active session for subagent control");return(await U($.sessionId)).listSubagents()}),O=y0(async(I,L)=>{if(!$.sessionId)throw Error("No active session for subagent control");let M=await U($.sessionId),V=!1,k,u=I,j=(f)=>{C$.getState().app.actions.completeSubagentProgress(u,f.status==="completed")},m=M.resumeSubagent({agentId:I,prompt:L,onEvent:(f)=>{if(f.kind==="tool_start"&&"function"in f.toolCall)C$.getState().app.actions.updateSubagentTool(u,f.toolCall.function.name)},onCompleted:(f)=>{if(V)j(f);else k=f}});if(u=m.session.id,C$.getState().app.actions.startSubagentProgress(m.session.id,m.session.subagentType,`Resumed from ${m.source.id}: ${m.session.description}`),V=!0,k)j(k);return m}),B=y0(async()=>{if(!$.sessionId)throw Error("No active session for MCP content");return(await U($.sessionId)).getMcpContentCatalog()}),_=y0(async(I)=>{if(!$.sessionId)throw Error("No active session for MCP content");await(await U($.sessionId)).refreshMcpContentCatalogs(I)}),b=y0(async(I,L,M)=>{if(!$.sessionId)throw Error("No active session for MCP prompts");return(await U($.sessionId)).getMcpPrompt(I,L,M)}),z=y0(async(I,L,M)=>{if(!$.sessionId)throw Error("No active session for MCP completion");return(await U($.sessionId)).completeMcpArgument(I,L,M)}),H=y0(async(I,L={})=>{if(!$.sessionId)throw Error("No active session for MCP logs");return(await U($.sessionId)).getMcpLogs(I,L)}),F=y0(async(I)=>{if(!$.sessionId)throw Error("No active session for MCP tasks");return(await U($.sessionId)).listMcpTasks(I)}),A=y0(async(I)=>{if(!$.sessionId)throw Error("No active session for MCP tasks");return(await U($.sessionId)).getMcpTask(I)}),v=y0(async(I,L)=>{if(!$.sessionId)throw Error("No active session for MCP tasks");return(await U($.sessionId)).cancelMcpTask(I,L)}),C=y0(async(I,L)=>{if(!$.sessionId)throw Error("No active session for MCP logging");await(await U($.sessionId)).setMcpLoggingLevel(I,L)}),N=y0(async()=>{if(!$.sessionId)throw Error("No active session for MCP instructions");return(await U($.sessionId)).getMcpInstructions()}),P=y0(async()=>{if(!$.sessionId)throw Error("No active session for reasoning effort");return(await U($.sessionId)).getReasoningConfiguration()}),w=y0(async(I)=>{if(!$.sessionId)throw Error("No active session for reasoning effort");let L=await U($.sessionId);if(L.hasTurnOwner())throw Error("Cannot switch reasoning effort while a turn is active");let M=L.getReasoningConfiguration();if(L.resolveReasoningConfiguration(I),M.selection===I)return M;await L.refresh({reasoningEffort:I});try{let V;try{V=await E0.updateSessionMetadata($.sessionId,L.workspaceRoot,{reasoningEffort:I})}catch(k){if(!(k instanceof s$)&&k.code!=="ENOENT")throw k;V=await E0.createSessionMetadata($.sessionId,L.workspaceRoot,{taskStatus:"completed",selectedModelId:L.getCurrentModelId(),reasoningEffort:I,serviceTier:L.getServiceTierConfiguration().selection,responseVerbosity:L.getResponseVerbosityConfiguration().selection,communicationStyle:L.getCommunicationStyleConfiguration().selection})}return J.current={sessionId:$.sessionId,modelId:V.selectedModelId,reasoningEffort:V.reasoningEffort,serviceTier:V.serviceTier,responseVerbosity:V.responseVerbosity,communicationStyle:V.communicationStyle,communicationStyleDigest:V.communicationStyleDigest},r0().setReasoningEffort(I),L.getReasoningConfiguration()}catch(V){throw await L.refresh({reasoningEffort:M.selection}),V}}),R=y0(async()=>{if(!$.sessionId)throw Error("No active session for service tier");return(await U($.sessionId)).getServiceTierConfiguration()}),T=y0(async(I)=>{if(!$.sessionId)throw Error("No active session for service tier");let L=await U($.sessionId);if(L.hasTurnOwner())throw Error("Cannot switch service tier while a turn is active");let M=L.getServiceTierConfiguration();if(L.resolveServiceTierConfiguration(I),M.selection===I)return M;await L.refresh({serviceTier:I});try{let V;try{V=await E0.updateSessionMetadata($.sessionId,L.workspaceRoot,{serviceTier:I})}catch(k){if(!(k instanceof s$)&&k.code!=="ENOENT")throw k;V=await E0.createSessionMetadata($.sessionId,L.workspaceRoot,{taskStatus:"completed",selectedModelId:L.getCurrentModelId(),reasoningEffort:L.getReasoningConfiguration().selection,serviceTier:I,responseVerbosity:L.getResponseVerbosityConfiguration().selection,communicationStyle:L.getCommunicationStyleConfiguration().selection})}return J.current={sessionId:$.sessionId,modelId:V.selectedModelId,reasoningEffort:V.reasoningEffort,serviceTier:V.serviceTier,responseVerbosity:V.responseVerbosity,communicationStyle:V.communicationStyle,communicationStyleDigest:V.communicationStyleDigest},r0().setServiceTier(I),L.getServiceTierConfiguration()}catch(V){throw await L.refresh({serviceTier:M.selection}),V}}),y=y0(async()=>{if(!$.sessionId)throw Error("No active session for response verbosity");return(await U($.sessionId)).getResponseVerbosityConfiguration()}),S=y0(async(I)=>{if(!$.sessionId)throw Error("No active session for response verbosity");let L=await U($.sessionId);if(L.hasTurnOwner())throw Error("Cannot switch response verbosity while a turn is active");let M=L.getResponseVerbosityConfiguration();if(L.resolveResponseVerbosityConfiguration(I),M.selection===I)return M;await L.refresh({responseVerbosity:I});try{let V;try{V=await E0.updateSessionMetadata($.sessionId,L.workspaceRoot,{responseVerbosity:I})}catch(k){if(!(k instanceof s$)&&k.code!=="ENOENT")throw k;V=await E0.createSessionMetadata($.sessionId,L.workspaceRoot,{taskStatus:"completed",selectedModelId:L.getCurrentModelId(),reasoningEffort:L.getReasoningConfiguration().selection,serviceTier:L.getServiceTierConfiguration().selection,responseVerbosity:I,communicationStyle:L.getCommunicationStyleConfiguration().selection})}return J.current={sessionId:$.sessionId,modelId:V.selectedModelId,reasoningEffort:V.reasoningEffort,serviceTier:V.serviceTier,responseVerbosity:V.responseVerbosity,communicationStyle:V.communicationStyle,communicationStyleDigest:V.communicationStyleDigest},r0().setResponseVerbosity(I),L.getResponseVerbosityConfiguration()}catch(V){throw await L.refresh({responseVerbosity:M.selection}),V}}),E=y0(async()=>{if(!$.sessionId)throw Error("No active session for communication style");return(await U($.sessionId)).getCommunicationStyleConfiguration()}),c=y0(async(I)=>{if(!$.sessionId)throw Error("No active session for communication style");let L=await U($.sessionId);if(L.hasTurnOwner())throw Error("Cannot switch communication style while a turn is active");let M=L.getCommunicationStyleConfiguration(),V=L.resolveCommunicationStyleConfiguration(I);if(V.source!=="built-in"&&!V.contentSha256)throw Error("Custom communication style has no provenance");if(M.selection===I)return M;await L.refresh({communicationStyle:I});try{let k;try{k=await E0.updateSessionMetadata($.sessionId,L.workspaceRoot,{communicationStyle:I,communicationStyleDigest:V.source==="built-in"?null:V.contentSha256})}catch(u){if(!(u instanceof s$)&&u.code!=="ENOENT")throw u;k=await E0.createSessionMetadata($.sessionId,L.workspaceRoot,{taskStatus:"completed",selectedModelId:L.getCurrentModelId(),reasoningEffort:L.getReasoningConfiguration().selection,serviceTier:L.getServiceTierConfiguration().selection,responseVerbosity:L.getResponseVerbosityConfiguration().selection,communicationStyle:I,...V.source!=="built-in"&&V.contentSha256?{communicationStyleDigest:V.contentSha256}:{}})}return J.current={sessionId:$.sessionId,modelId:k.selectedModelId,reasoningEffort:k.reasoningEffort,serviceTier:k.serviceTier,responseVerbosity:k.responseVerbosity,communicationStyle:k.communicationStyle,communicationStyleDigest:k.communicationStyleDigest},r0().setCommunicationStyle(I),L.getCommunicationStyleConfiguration()}catch(k){throw await L.refresh({communicationStyle:M.selection}),k}}),Q0=y0(async(I)=>{if(!Y.current)return{accepted:!1,queued:0,reason:"no_active_turn"};return Y.current.enqueueSteering(I,{allowBeforeTurn:!0})}),d=y0(async(I,L)=>{let M=$.sessionId;if(!M)throw Error("User shell command requires a Session");return(await U(M)).executeUserShellCommand(I,L)});return UY(()=>{let I=p8(X);return()=>{I(),X().catch(()=>{return})}},[X]),{agentRef:Q,createAgent:G,cleanupAgent:X,steerActiveTurn:Q0,executeUserShellCommand:d,listRewindCheckpoints:q,rewindSession:K,listSubagents:W,resumeSubagent:O,getMcpContentCatalog:B,refreshMcpContentCatalogs:_,getMcpPrompt:b,completeMcpArgument:z,listMcpTasks:F,getMcpTask:A,cancelMcpTask:v,getMcpLogs:H,setMcpLoggingLevel:C,getMcpInstructions:N,getReasoningConfiguration:P,setReasoningEffort:w,getServiceTierConfiguration:R,setServiceTier:T,getResponseVerbosityConfiguration:y,setResponseVerbosity:S,getCommunicationStyleConfiguration:E,setCommunicationStyle:c}}import{useMemoizedFn as f$}from"ahooks";import{useEffect as GY,useRef as c8}from"react";function k2($){let Q=0;for(let Y of $)if(Y===`
32
- `)Q++;return Q}function S2($,Q){let Y=Q?.flushTimeout??300,J=Q?.minLinesToFlush??5,Z=Q?.minCharsToFlush??400,X=c8(""),U=c8(null),G=c8(""),q=c8(null),K=f$(()=>{if(X.current){let z=X.current,H=$.appendAssistantContent(z);k$(H,z),X.current=""}if(U.current)clearTimeout(U.current),U.current=null}),W=f$(()=>{if(G.current)$.appendThinkingContent(G.current),G.current="";if(q.current)clearTimeout(q.current),q.current=null}),O=f$((z)=>{X.current+=z;let H=X.current;if(k2(H)>=J||H.length>=Z){K();return}if(!U.current)U.current=setTimeout(K,Y)}),B=f$((z)=>{G.current+=z;let H=G.current;if(k2(H)>=J||H.length>=Z){W();return}if(!q.current)q.current=setTimeout(W,Y)}),_=f$(()=>{if(X.current="",U.current)clearTimeout(U.current),U.current=null;if(G.current="",q.current)clearTimeout(q.current),q.current=null}),b=f$(()=>{if(U.current)clearTimeout(U.current),U.current=null;if(q.current)clearTimeout(q.current),q.current=null;let z=X.current,H=G.current;return X.current="",G.current="",{extraContent:z,extraThinking:H}});return GY(()=>{return()=>{_()}},[_]),{batchAppendContent:O,batchAppendThinking:B,flushContentBuffer:K,flushThinkingBuffer:W,resetStreamingBuffers:_,drainPendingBuffers:b}}var hQ=i1("UI"),V2=($,Q,Y,J,Z,X)=>{let U=o1(),G=R8(),q=M1(),K=I8(),W=T$(),O=C8(),B=T8(),_=k8(),b=S8(),z=f8(),H=r1(),F=a1(),A=G2(),v=f2(!1),C=f2(!1),{createAgent:N,cleanupAgent:P,steerActiveTurn:w,listRewindCheckpoints:R,rewindSession:T,listSubagents:y,resumeSubagent:S,getMcpContentCatalog:E,refreshMcpContentCatalogs:c,getMcpPrompt:Q0,completeMcpArgument:d,listMcpTasks:I,getMcpTask:L,cancelMcpTask:M,getMcpLogs:V,setMcpLoggingLevel:k,getMcpInstructions:u,getReasoningConfiguration:j,setReasoningEffort:m,getServiceTierConfiguration:f,setServiceTier:n,getResponseVerbosityConfiguration:_0,setResponseVerbosity:N0,getCommunicationStyleConfiguration:m0,setCommunicationStyle:D0,executeUserShellCommand:w0}=T2({sessionId:G,workspaceRoot:q,systemPrompt:$,appendSystemPrompt:Q,maxTurns:J,modelId:K,reasoningEffort:B,serviceTier:_,responseVerbosity:b,communicationStyle:z,agents:X}),_1=S2(H),N1=D$(async(X0,C0)=>{if(X0.images.length>0)return{success:!1,error:"User shell commands do not accept image attachments"};let e=X0.text.trimStart().slice(1).trim();if(!e)return{success:!1,error:"User shell command cannot be empty"};H.setCommand(`! ${e}`);try{let O0=await w0(e,{signal:C0});if(H.addMessage({id:`user-shell-${O0.executionId}`,role:"user",content:gQ(O0.record),timestamp:Date.now(),metadata:{userShellCommand:O0.record}}),O0.delivery==="next_turn")C.current=!0;return{success:O0.record.status!=="spawn_error",output:gQ(O0.record),...O0.record.status==="spawn_error"?{error:O0.record.stderr||"User shell command failed"}:{}}}finally{H.setCommand(null)}});EQ(()=>{return()=>{_1.resetStreamingBuffers()}},[_1.resetStreamingBuffers]),EQ(()=>{if(!O)H.setCurrentThinkingContent(null)},[O,H]);let v$=D$(()=>{if(!U)return;Z?.();let{extraContent:X0,extraThinking:C0}=_1.drainPendingBuffers();A.abort("user-cancel"),F.setTasks([]);let e=Y1().session.currentStreamingMessageId;if(e){if(X0)k$(e,X0);V8(e)}if(H.finalizeStreamingMessage(X0,C0),!v.current)H.addAssistantMessage("任务已停止"),v.current=!0}),G1=D$(async(X0,C0)=>{let e={contentDeltaCount:0,contentDeltaTotalLen:0},O0=w2({sessionActions:H,appActions:F,commandActions:A,streamingBuffer:_1,thinkingModeEnabled:O,getStreamingMessageId:()=>Y1().session.currentStreamingMessageId,signal:C0.signal},e);return{loopResult:await D2(X0,O0),stats:e}}),CQ=D$(async(X0)=>{let C0=!1,e,O0=!1,x0=X0;try{if(X0.text.trimStart().startsWith("!")){let c0=A.getAbortController()??A.createAbortController();return await N1(X0,c0.signal)}await $8();let o0=A.getAbortController()??A.createAbortController(),p0=await jQ(X0,F,H,o0.signal,P,G,E8(Y1().session),{listCheckpoints:R,execute:T},{list:y,resume:S},{getCatalog:E,refresh:c,getPrompt:Q0,complete:d,listTasks:I,getTask:L,cancelTask:M,getLogs:V,setLoggingLevel:k,getInstructions:u},{get:j,set:m},{get:f,set:n},{get:_0,set:N0},{get:m0,set:D0},q);if(p0.type==="handled")return p0.commandResult;if(p0.type==="continue_as_agent")C0=p0.result.userMessageAlreadyAdded,e=p0.result.onceModelId,O0=p0.result.goalContinuationOnly===!0,x0=p0.result.agentInput;let kQ=F1.getInstance(),n$;if(!O0){let c0=await kQ.executeUserPromptSubmitHooks(x0.text,{projectDir:q,sessionId:G,permissionMode:W,hasImages:x0.images.length>0,imageCount:x0.images.length});if(!c0.proceed){if(c0.warning)H.addAssistantMessage(`${c0.warning}`);return{success:!1,error:"blocked by hook"}}if(c0.updatedPrompt)x0={...x0,text:c0.updatedPrompt,displayText:c0.updatedPrompt,parts:[{type:"text",text:c0.updatedPrompt},...x0.parts.filter((b8)=>b8.type==="image")]};if(c0.contextInjection)n$=c0.contextInjection}if(!C0)H.addUserMessage(x0.displayText);let L8=VQ(x0),B8=await N(e?{modelId:e}:void 0);if(o0.signal.aborted)return hQ.info("[handleCommandSubmit] Agent 创建期间已被中止"),{success:!1,error:"aborted"};let r=E8(Y1().session);if(n$)r.push({role:"system",content:`<user-prompt-submit-hook>
33
- ${n$}
34
- </user-prompt-submit-hook>`});let U0={messages:r,userId:"cli-user",sessionId:G,workspaceRoot:q,signal:o0.signal,confirmationHandler:Y,permissionMode:W},{loopResult:T0,stats:w8}=await G1(B8.chatStream(L8,U0,{stream:!0,goalContinuationOnly:O0,onTurnLimitReached:Y?async(c0)=>{let b8=await Y.requestConfirmation({type:"maxTurnsExceeded",message:`已进行 ${c0.turnsCount} 轮对话。是否继续?`,risks:["继续执行可能导致更长的等待时间","可能产生更多的 API 费用"]});return{continue:b8.approved,reason:b8.reason}}:void 0}),o0);if(T0.metadata?.outputTruncated)H.addAssistantMessage("输出因达到 token 上限被截断,部分内容可能不完整。");let S1=T0.finalMessage||"";if(hQ.debug("[handleCommandSubmit] final reply",{success:T0.success,outputLength:S1.length,turnsCount:T0.metadata?.turnsCount,toolCallsCount:T0.metadata?.toolCallsCount}),!T0.success&&T0.error?.type==="api_error"){let c0=T0.error.message||"请求失败,请检查网络连接和 API 配置";return H.addAssistantMessage(c0),{success:!1,error:c0}}if(!S1||S1.trim()===""){let c0=T0.metadata?.abortReason;if(!v.current&&w8.contentDeltaCount===0&&c0!=="interrupt")return H.addAssistantMessage("已取消"),{success:!0,output:"已取消"};return{success:!0,output:S1??""}}return{success:!0,output:S1}}catch(o0){if(v.current)return{success:!1,error:"aborted"};let p0=D8(o0);return H.addAssistantMessage(`${p0.displayMessage}`),{success:!1,error:p0.displayMessage}}}),O$=D$(async()=>{if(Y1().command.isProcessing){C.current=!0;return}let X0=await z$.hasPendingInbox(q,G),C0=!X0&&await z$.hasActiveGoal(q,G);if(!X0&&!C0){C.current=!1;return}if(Y1().command.isProcessing){C.current=!0;return}C.current=!1,await $8();let e=A.createAbortController();_1.resetStreamingBuffers(),H.clearFinalizingStreamingMessageId(),A.setProcessing(!0);try{let O0=await N();if(e.signal.aborted)return;let x0={messages:E8(Y1().session),userId:"cli-user",sessionId:G,workspaceRoot:q,signal:e.signal,confirmationHandler:Y,permissionMode:W},{loopResult:o0}=await G1(O0.chatStream("",x0,{stream:!0,pendingInputOnly:X0,goalContinuationOnly:C0}),e);if(o0.metadata?.outputTruncated)H.addAssistantMessage("输出因达到 token 上限被截断,部分内容可能不完整。");if(!o0.success&&o0.error?.type==="api_error")H.addAssistantMessage(o0.error.message||"恢复排队指令失败,请检查网络和 API 配置")}catch(O0){let x0=D8(O0);if(!x0.isAbort)H.setError(`恢复排队指令失败: ${x0.displayMessage}`)}finally{if(A.getAbortController()===e)A.setProcessing(!1),A.clearAbortController(e),H.setCurrentThinkingContent(null);if(C.current)queueMicrotask(()=>{O$()})}}),TQ=D$(async(X0)=>{if(!X0.text.trim()&&X0.images.length===0)return;if(X0.text.trimStart().startsWith("!")&&U){let e=A.getAbortController();if(!e){H.addAssistantMessage("当前任务没有可用的取消边界,无法执行用户 Shell 命令。");return}let O0=await N1(X0,e.signal);if(!O0.success&&O0.error&&O0.error!=="aborted")H.setError(O0.error);return}if(U){if(X0.text.trimStart().startsWith("/")){if(/^\/goal(?:\s|$)/i.test(X0.text.trim())){await $8();let p0=A.getAbortController()??A.createAbortController();await jQ(X0,F,H,p0.signal,P,G,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,q);return}H.addAssistantMessage("活动回合中不能执行 slash command;请先停止任务或等待完成。");return}await $8();let e=await F1.getInstance().executeUserPromptSubmitHooks(X0.text,{projectDir:q,sessionId:G,permissionMode:W,hasImages:X0.images.length>0,imageCount:X0.images.length});if(!e.proceed){if(e.warning)H.addAssistantMessage(e.warning);return}let O0=X0;if(e.updatedPrompt)O0={...X0,text:e.updatedPrompt,parts:[{type:"text",text:e.updatedPrompt},...X0.parts.filter((p0)=>p0.type==="image")]};if(e.contextInjection){let p0=`<user-prompt-submit-hook>
35
- ${e.contextInjection}
36
- </user-prompt-submit-hook>`;O0={...O0,text:`${O0.text}
37
-
38
- ${p0}`,parts:[...O0.parts,{type:"text",text:`
39
-
40
- ${p0}`}]}}let x0=VQ(O0),o0=await w(x0);if(!o0.accepted){let p0=o0.reason==="queue_full"?"补充指令队列已满,请等待当前任务处理后重试。":"当前任务正在结束,补充指令未入队,请稍后重试。";H.addAssistantMessage(p0);return}if(A.enqueueCommand(X0),H.addUserMessage(X0.displayText),o0.delivery==="next_turn"){if(C.current=!0,!Y1().command.isProcessing)queueMicrotask(()=>{O$()})}return}F.setTasks([]),A.setRecoveredSteeringCount(0),v.current=!1;let C0=A.createAbortController();_1.resetStreamingBuffers(),H.clearFinalizingStreamingMessageId(),A.setProcessing(!0);try{let e=await CQ(X0);if(!e.success&&e.error&&e.error!=="aborted")H.setError(e.error)}catch(e){let O0=D8(e);if(O0.isAbort);else H.setError(`执行失败: ${O0.displayMessage}`)}finally{if(A.getAbortController()===C0){if(A.setProcessing(!1),A.clearAbortController(C0),H.setCurrentThinkingContent(null),C.current)queueMicrotask(()=>{O$()})}}});return EQ(()=>{let X0=!1;return Promise.all([z$.hasPendingInbox(q,G),z$.hasActiveGoal(q,G)]).then(([C0,e])=>{if(!X0&&(C0||e))return O$()}).catch((C0)=>{if(!X0)hQ.warn("[useCommandHandler] Failed to inspect pending inbox",C0)}),()=>{X0=!0}},[O$,G,q]),{executeCommand:TQ,handleAbort:v$,isProcessing:U,cleanupAgent:P}};import{useMemoizedFn as x8}from"ahooks";import{useState as j2}from"react";var E2=()=>{let[$,Q]=j2([]),[Y,J]=j2(-1),Z=x8((q,K)=>{let W={display:q,pasteMappings:K?new Map(K):new Map};Q((O)=>[...O,W]),J(-1)}),X=x8(()=>{if($.length===0)return null;let q=Y===-1?$.length-1:Math.max(0,Y-1);return J(q),$[q]||null}),U=x8(()=>{if(Y===-1)return null;let q=Y+1;if(q>=$.length)return J(-1),null;else return J(q),$[q]||null}),G=x8(()=>{J(-1)});return{commandHistory:$,historyIndex:Y,addToHistory:Z,getPreviousCommand:X,getNextCommand:U,resetHistoryIndex:G}};import{useMemoizedFn as Q8}from"ahooks";import{useMemo as qY,useRef as h2,useState as KY}from"react";var g2=()=>{let[$,Q]=KY({isVisible:!1,details:null,resolver:null}),Y=h2(null),J=h2([]),Z=Q8((W)=>{Y.current=W,Q({isVisible:Boolean(W),details:W?.details??null,resolver:W?.resolve??null})}),X=Q8((W,O)=>{if(W.settled)return;if(W.settled=!0,W.signal&&W.abortListener)W.signal.removeEventListener("abort",W.abortListener);W.resolve(O)}),U=Q8((W,O)=>{return new Promise((B)=>{let _={details:W,resolve:B,signal:O,settled:!1},b=()=>{if(Y.current===_){X(_,{approved:!1,reason:J8}),Z(J.current.shift()??null);return}let z=J.current.indexOf(_);if(z>=0)J.current.splice(z,1);X(_,{approved:!1,reason:J8})};if(_.abortListener=b,O?.aborted){b();return}if(O?.addEventListener("abort",b,{once:!0}),!Y.current){Z(_);return}J.current.push(_)})}),G=Q8((W)=>{let O=Y.current;if(O)X(O,W);let B=J.current.shift()??null;Z(B)}),q=Q8(()=>{if(Y.current)X(Y.current,{approved:!1,reason:J8});for(let W of J.current)X(W,{approved:!1,reason:J8});J.current=[],Z(null)}),K=qY(()=>({requestConfirmation:U}),[U]);return{confirmationState:$,confirmationHandler:K,handleResponse:G,dismissAll:q}};import{useMemoizedFn as _$}from"ahooks";import{useRef as m2,useState as OY}from"react";var u8="␞",d8="␟";function l8($){return`${u8}PASTE:${$}:`}function mQ(){return d8}var T7=new RegExp(`${u8}PASTE:(\\d+):[\\s\\S]*?${d8}`,"g");function zY($){return $.includes(u8)&&$.includes(d8)}function p2($="",Q=0){let[Y,J]=OY({value:$,cursorPosition:Q}),Z=m2(0),X=m2(new Map),U=_$((_)=>{J((b)=>({value:_,cursorPosition:b.cursorPosition}));for(let b of X.current.keys()){let z=l8(b);if(!_.includes(z))X.current.delete(b)}}),G=_$((_)=>{J((b)=>({...b,cursorPosition:Math.max(0,Math.min(_,b.value.length))}))}),q=_$(()=>{J({value:"",cursorPosition:0}),X.current.clear()}),K=_$((_)=>{Z.current+=1;let b=Z.current;return X.current.set(b,{type:"text",data:_}),b}),W=_$((_,b)=>{let z=[...X.current.values()].filter((v)=>v.type==="image");if(z.length>=S$)throw Error(`最多只能粘贴 ${S$} 张图片`);let H=z.reduce((v,C)=>v+`data:${C.mimeType};base64,`.length+C.data.length,0),F=`data:${b};base64,`.length+_.length;if(H+F>j8)throw Error("图片编码后总大小不能超过 5 MiB");Z.current+=1;let A=Z.current;return X.current.set(A,{type:"image",data:_,mimeType:b}),A}),O=_$((_)=>{for(let[b,z]of _)if(X.current.set(b,z),b>=Z.current)Z.current=b}),B=_$((_)=>{let b=[],z=[];if(!zY(_)){let T=_.trim();if(T)z.push({type:"text",text:T});return{displayText:_,text:_,images:b,parts:z}}let H=new RegExp(`${u8}PASTE:(\\d+):[\\s\\S]*?${d8}`,"g"),F=Array.from(_.matchAll(H)),A=0,v="",C="";for(let T of F){let y=T.index,S=y+T[0].length,E=parseInt(T[1],10),c=X.current.get(E);if(y>A){let Q0=_.slice(A,y);z.push({type:"text",text:Q0}),v+=Q0,C+=Q0}if(!c)v+=T[0],C+=T[0],z.push({type:"text",text:T[0]});else if(c.type==="text")v+=c.data,C+=c.data,z.push({type:"text",text:c.data});else{let Q0={id:E,base64:c.data,mimeType:c.mimeType};b.push(Q0),z.push({type:"image",...Q0}),C+=`[Image #${E}]`}A=S}if(A<_.length){let T=_.slice(A);z.push({type:"text",text:T}),v+=T,C+=T}let N=[];for(let T of z)if(T.type==="text"&&N.length>0&&N[N.length-1].type==="text")N[N.length-1].text+=T.text;else N.push(T);let P=0,w=N.length;while(P<N.length&&N[P].type==="text"&&N[P].text.trim()==="")P++;while(w>P&&N[w-1].type==="text"&&N[w-1].text.trim()==="")w--;let R=N.slice(P,w);return{displayText:C.trim(),text:v.trim(),images:b,parts:R}});return{value:Y.value,cursorPosition:Y.cursorPosition,setValue:U,setCursorPosition:G,clear:q,pasteMap:X.current,addPasteMapping:K,addImagePasteMapping:W,restorePasteMappings:O,resolveInput:B}}import{useMemoizedFn as o2}from"ahooks";import{useInput as wY}from"ink";import{useEffect as i2,useRef as n2,useState as uQ}from"react";function _Y($){return{supportsThinking:f1().resolveConfig($).reasoning}}function r8($){return _Y($).supportsThinking}import NY from"fast-glob";import FY from"fuse.js";import{useEffect as c2,useMemo as pQ,useState as cQ}from"react";var V$=null,HY=5000;function WY($,Q){let Y=[...$.matchAll(/(?:^|\s)(@(?:"[^"]*"|(?:[^\\ ]|\\ )*))/g)];for(let J of Y){let Z=J[1],X=J.index+(J[0].length-Z.length),U=X+Z.length;if(Q>=X&&Q<=U){let G=Z.slice(1),q=!1;if(G.startsWith('"')){if(q=!0,G=G.slice(1),G.endsWith('"'))G=G.slice(0,-1)}return{hasQuery:!0,query:G,startIndex:X,endIndex:U,quoted:q}}}return{hasQuery:!1,query:"",startIndex:-1,endIndex:-1,quoted:!1}}var LY=[...xQ.map(($)=>`${$}/**`),...xQ,...x2.map(($)=>`**/${$}`)];function u2($,Q,Y={}){let{cwd:J=A0(),maxSuggestions:Z=15,ignorePatterns:X=LY,debounceDelay:U=300,fuzzyMatch:G=!0}=Y,[q,K]=cQ([]),[W,O]=cQ(!1),[B,_]=cQ(0),b=pQ(()=>JSON.stringify(X),[X]),z=pQ(()=>{if(Q===void 0)return{hasQuery:!1,query:"",startIndex:-1,endIndex:-1,quoted:!1};return WY($,Q)},[$,Q]);c2(()=>{if(!$.includes("@")){K([]),O(!1);return}let F=Date.now();if(V$&&V$.cwd===J&&V$.ignoreKey===b&&F-V$.timestamp<HY){K(V$.files),O(!1);return}let A=!1,C=setTimeout(async()=>{O(!0);try{let P=(await NY("**/*",{cwd:J,dot:!1,followSymbolicLinks:!1,onlyFiles:!1,markDirectories:!0,unique:!0,ignore:X})).map((w)=>w.replace(/\\/g,"/"));if(!A)K(P),V$={cwd:J,ignoreKey:b,files:P,timestamp:F}}catch(N){if(console.error("Failed to load files for @ completion:",N),!A)K([])}finally{if(!A)O(!1)}},U);return()=>{A=!0,clearTimeout(C)}},[$,J,U,b]);let H=pQ(()=>{if(!z.hasQuery||q.length===0)return[];let F=z.query.toLowerCase();if(F==="")return q.slice(0,Z);if(G)return new FY(q,{threshold:0.4,ignoreLocation:!0,minMatchCharLength:1}).search(F).slice(0,Z).map((C)=>C.item);return q.filter((A)=>A.toLowerCase().includes(F)).slice(0,Z)},[z,q,Z,G]);return c2(()=>{_(0)},[H]),{...z,suggestions:H,selectedIndex:B,loading:W}}function BY($,Q=!1){if($.includes(" ")||Q)return`@"${$}"`;return`@${$}`}function d2($,Q,Y){if(!Q.hasQuery)return{newInput:$,newCursorPos:$.length};let J=BY(Y,Q.quoted),Z=$.slice(0,Q.startIndex),X=$.slice(Q.endIndex),U=Z+J+" "+X,G=Q.startIndex+J.length+1;return{newInput:U,newCursorPos:G}}import{useMemoizedFn as l2}from"ahooks";import{useEffect as r2,useRef as a2}from"react";var k0=($,Q)=>{let Y=a2(!1),J=a2(null),Z=l2(()=>{if(J.current)clearTimeout(J.current);J.current=setTimeout(()=>{r0().setAwaitingSecondCtrlC(!1),Y.current=!1,J.current=null},3000)}),X=()=>{Y8().shutdown("SIGINT",0)},U=l2(()=>{if(!Y.current){if(Y.current=!0,$&&Q)Q();r0().setAwaitingSecondCtrlC(!0),Z()}else{if(J.current)clearTimeout(J.current),J.current=null;r0().setAwaitingSecondCtrlC(!1),X()}});return r2(()=>{if($){if(r0().setAwaitingSecondCtrlC(!1),Y.current=!1,J.current)clearTimeout(J.current),J.current=null}},[$]),r2(()=>{return()=>{if(J.current)clearTimeout(J.current)}},[]),U};var a8=i1("UI"),e2=($,Q,Y,J,Z,X,U,G,q,K)=>{let O=s0()==="main-input",B=$.value,_=$.setValue,b=$.cursorPosition,z=r1(),H=M1(),F=a1(),A=M8(),v=A?r8(A):!1,[C,N]=uQ(!1),[P,w]=uQ([]),[R,T]=uQ(0),y=u2(B,b,{cwd:H,maxSuggestions:10}),S=k0(U||!1,X),E=n2(0),c=500,Q0=n2(!1);i2(()=>{if(U)Q0.current=!1},[U]),i2(()=>{if(y.hasQuery&&y.suggestions.length>0){let L=y.suggestions.map((M)=>({command:M,description:t2(M)?`Directory: ${M}`:`File: ${M}`,matchScore:1}));w(L),N(!0),T(0)}else if(B.startsWith("/"))if(B.includes(" "))N(!1),w([]);else{let M=s2(B,H);w(M),N(M.length>0),T(0)}else N(!1),w([])},[B,y.hasQuery,y.suggestions,H]);let d=o2(()=>{z.clearMessages(),z.setError(null)}),I=o2(()=>{a8.debug("[DIAG] handleSubmit called:",{input:B,showSuggestions:C});let L=B.trim();if(L){let M=$.resolveInput(L);a8.debug("[DIAG] Submitting command:",{displayText:L,textLength:M.text.length,imageCount:M.images.length}),N(!1),w([]);let V=$.pasteMap.size>0?new Map($.pasteMap):new Map;Z(L,V),$.clear(),Q(M),a8.debug("[DIAG] Command submitted to onSubmit callback")}else a8.debug("[DIAG] Empty command, not submitting")});return wY((L,M)=>{if(L==="?"&&!B){q?.(),setTimeout(()=>$.clear(),0);return}if(M.backspace||M.delete||M.leftArrow||M.rightArrow||M.pageUp||M.pageDown||!M.ctrl&&!M.meta&&!M.escape&&!M.tab&&!M.upArrow&&!M.downArrow&&!M.return&&!(L==="?"&&!B))return;if(M.ctrl&&L==="c"||M.meta&&L==="c"||M.ctrl&&L==="d"||M.meta&&L==="d"){S();return}if(M.ctrl&&L==="l"||M.meta&&L==="l"){d();return}if(M.ctrl&&L==="t"||M.meta&&L==="t"){z.toggleThinkingExpanded();return}if(M.ctrl&&L==="o"||M.meta&&L==="o"){z.toggleHistoryExpanded();return}if(M.escape){if(K)q?.();else if(U&&X){if(Q0.current)return;Q0.current=!0,X()}else if(C)N(!1),w([]);else if(B){let k=Date.now();if(k-E.current<500)$.clear(),E.current=0;else E.current=k}return}if(M.tab&&M.shift){G?.();return}if(M.tab){if(C&&P.length>0){let k=P[R].command;if(y.hasQuery&&y.suggestions.includes(k)){let{newInput:u,newCursorPos:j}=d2(B,y,k);_(u),$.setCursorPosition(j)}else{let u=k+" ";_(u),$.setCursorPosition(u.length)}N(!1),w([])}else if(v)F.toggleThinkingMode();return}if(M.return){I();return}if(M.upArrow){if(C&&P.length>0){let k=P.length-1;T((u)=>u>0?u-1:k)}else{let k=Y();if(k){if(k.pasteMappings.size>0)$.restorePasteMappings(k.pasteMappings);_(k.display),$.setCursorPosition(k.display.length)}}return}if(M.downArrow){if(C&&P.length>0){let k=P.length-1;T((u)=>u<k?u+1:0)}else{let k=J();if(k){if(k.pasteMappings.size>0)$.restorePasteMappings(k.pasteMappings);_(k.display),$.setCursorPosition(k.display.length)}}return}},{isActive:O}),{handleSubmit:I,showSuggestions:C,suggestions:P,selectedSuggestionIndex:R}};import yY from"ansi-escapes";import{useStdout as MY}from"ink";import{useCallback as IY,useEffect as vY,useRef as CY}from"react";import{useStdout as bY}from"ink";import{debounce as AY}from"lodash-es";import{useEffect as RY,useState as PY}from"react";function j$($=200){let{stdout:Q}=bY(),[Y,J]=PY(Q.columns||80);return RY(()=>{let Z=AY(()=>{J(Q.columns||80)},$);return Z(),Q.on("resize",Z),()=>{Q.off("resize",Z),Z.cancel()}},[Q,$]),Y}function $9(){let{stdout:$}=MY(),Q=j$(),Y=CY(!0),J=$0((X)=>X.session.actions.incrementClearCount),Z=IY(()=>{if($)$.write(yY.clearTerminal);J()},[$,J]);return vY(()=>{if(Y.current){Y.current=!1;return}let X=setTimeout(()=>{Z()},300);return()=>{clearTimeout(X)}},[Q,Z]),{refreshStatic:Z}}import Q9 from"node:fs";import TY from"node:os";import dQ from"node:path";import{MultiSelect as kY}from"@inkjs/ui";import{useMemoizedFn as o8}from"ahooks";import{Box as J0,Text as i,useFocus as SY,useFocusManager as fY,useInput as Y9}from"ink";import i8 from"ink-select-input";import DY from"ink-spinner";import Z8 from"ink-text-input";import{useEffect as J9,useState as E$}from"react";import{jsxDEV as D}from"react/jsx-dev-runtime";var VY=[{label:"Glob - 文件搜索",value:"Glob"},{label:"Grep - 内容搜索",value:"Grep"},{label:"Read - 读取文件",value:"Read"},{label:"Write - 写入文件",value:"Write"},{label:"Edit - 编辑文件",value:"Edit"},{label:"ApplyPatch - 原子多文件补丁",value:"ApplyPatch"},{label:"Bash - 执行命令",value:"Bash"},{label:"所有工具 (不限制)",value:"all"}],jY=[{label:"红色 (red)",value:"red"},{label:"蓝色 (blue)",value:"blue"},{label:"绿色 (green)",value:"green"},{label:"黄色 (yellow)",value:"yellow"},{label:"紫色 (purple)",value:"purple"},{label:"橙色 (orange)",value:"orange"},{label:"粉色 (pink)",value:"pink"},{label:"青色 (cyan)",value:"cyan"},{label:"不设置颜色",value:"none"}];function EY($){if(!$||$.trim()==="")return"名称不能为空";if(!/^[a-z0-9-]+$/.test($))return"名称只能包含小写字母、数字和连字符";if($.startsWith("-")||$.endsWith("-"))return"名称不能以连字符开头或结尾";return null}function X8({onComplete:$,onCancel:Q,initialConfig:Y}){let[J,Z]=E$(Y?"name":"mode"),[X,U]=E$({name:Y?.name||"",description:Y?.description||"",tools:Y?.tools||[],color:Y?.color,location:Y?.location||"project",systemPrompt:Y?.systemPrompt||""}),[G,q]=E$(""),[K,W]=E$(!1),[O,B]=E$(""),[_,b]=E$(Y?"edit":"manual"),{focus:z}=fY(),F={manual:["mode","name","description","tools","color","location","systemPrompt","confirm"],ai:["mode","aiPrompt","aiGenerating","confirm"],edit:["name","description","tools","color","location","systemPrompt","confirm"]}[_];J9(()=>{if(J==="name"||J==="description"||J==="systemPrompt"||J==="aiPrompt")return;z(`step-${J}`)},[J,z]);let A=o8(()=>{let w=F.indexOf(J);if(w<F.length-1)Z(F[w+1])}),v=o8(()=>{if(O)B("");if(J==="confirm"&&_==="ai"){Z("aiPrompt");return}let w=F.indexOf(J);if(w>0)Z(F[w-1]);else Q()}),C=o8(async()=>{W(!0),B("");try{let w=await e$.create(),R=`你是一个 Subagent 配置生成专家。用户会描述他们想要创建的 agent,你需要根据描述生成一个完整的 agent 配置。
41
-
42
- ## 可用工具列表
43
-
44
- - **Glob**: 文件模式匹配(例如:查找所有 .ts 文件)
45
- - **Grep**: 代码内容搜索(例如:搜索特定函数调用)
46
- - **Read**: 读取文件内容
47
- - **Write**: 写入/创建文件
48
- - **Edit**: 编辑文件(字符串替换)
49
- - **ApplyPatch**: 原子应用多文件文本补丁
50
- - **Bash**: 执行命令行命令
51
-
52
- ## 可用颜色
53
-
54
- - red, blue, green, yellow, purple, orange, pink, cyan
55
-
56
- ## 输出格式
57
-
58
- 你必须以 JSON 格式返回配置,格式如下:
59
-
60
- \`\`\`json
61
- {
62
- "name": "agent-name",
63
- "description": "简洁的一句话描述(英文)",
64
- "tools": ["Glob", "Grep", "Read"],
65
- "color": "blue",
66
- "systemPrompt": "详细的系统提示词,说明这个 agent 的职责、工作方式、输出格式等"
67
- }
68
- \`\`\`
69
-
70
- ## 注意事项
71
-
72
- 1. **name**: 只能包含小写字母、数字和连字符(kebab-case),例如:code-reviewer
73
- 2. **description**: 一句话说明用途,建议以 "Fast agent specialized for..." 开头
74
- 3. **tools**: 根据任务选择必要的工具,不要选择太多
75
- 4. **color**: 选择一个合适的颜色用于 UI 区分
76
- 5. **systemPrompt**: 详细说明 agent 的职责、使用的工具、输出格式等,使用 Markdown 格式
77
-
78
- **重要**:请直接返回 JSON,不要添加任何额外的解释或文字。`,y=(await w.chatWithSystem(`你是一个 Subagent 配置生成专家。用户会描述他们想要创建的 agent,你需要根据描述生成一个完整的 agent 配置。
79
-
80
- ## 可用工具列表
81
-
82
- - **Glob**: 文件模式匹配(例如:查找所有 .ts 文件)
83
- - **Grep**: 代码内容搜索(例如:搜索特定函数调用)
84
- - **Read**: 读取文件内容
85
- - **Write**: 写入/创建文件
86
- - **Edit**: 编辑文件(字符串替换)
87
- - **ApplyPatch**: 原子应用多文件文本补丁
88
- - **Bash**: 执行命令行命令
89
-
90
- ## 可用颜色
91
-
92
- - red, blue, green, yellow, purple, orange, pink, cyan
93
-
94
- ## 输出格式
95
-
96
- 你必须以 JSON 格式返回配置,格式如下:
97
-
98
- \`\`\`json
99
- {
100
- "name": "agent-name",
101
- "description": "简洁的一句话描述(英文)",
102
- "tools": ["Glob", "Grep", "Read"],
103
- "color": "blue",
104
- "systemPrompt": "详细的系统提示词,说明这个 agent 的职责、工作方式、输出格式等"
105
- }
106
- \`\`\`
107
-
108
- ## 注意事项
109
-
110
- 1. **name**: 只能包含小写字母、数字和连字符(kebab-case),例如:code-reviewer
111
- 2. **description**: 一句话说明用途,建议以 "Fast agent specialized for..." 开头
112
- 3. **tools**: 根据任务选择必要的工具,不要选择太多
113
- 4. **color**: 选择一个合适的颜色用于 UI 区分
114
- 5. **systemPrompt**: 详细说明 agent 的职责、使用的工具、输出格式等,使用 Markdown 格式
115
-
116
- **重要**:请直接返回 JSON,不要添加任何额外的解释或文字。`,G)).trim(),S=y.match(/```(?:json)?\s*\n([\s\S]*?)\n```/);if(S)y=S[1];let E=JSON.parse(y);if(!E.name||!E.description||!E.systemPrompt)throw Error("Missing required fields: name, description, or systemPrompt");if(!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(E.name))throw Error("Invalid name format. Must be kebab-case (lowercase, numbers, hyphens only)");U({name:E.name,description:E.description,tools:Array.isArray(E.tools)?E.tools:[],color:E.color||"blue",location:"project",systemPrompt:E.systemPrompt}),Z("confirm")}catch(w){B(w instanceof Error?w.message:String(w))}finally{W(!1)}});J9(()=>{if(J==="aiGenerating"&&!K&&!O)C()},[J,K,O,C]);let N=o8(async()=>{try{let w=X.location==="project"?dQ.join(A0(),".blade","agents"):dQ.join(TY.homedir(),".blade","agents");await Q9.promises.mkdir(w,{recursive:!0});let R=["---",`name: ${X.name}`,`description: ${X.description}`];if(X.tools.length>0&&!X.tools.includes("all")){R.push("tools:");for(let S of X.tools)R.push(` - ${S}`)}if(X.color)R.push(`color: ${X.color}`);R.push("---");let T=[R.join(`
117
- `),"",`# ${X.name} Subagent`,"",X.systemPrompt||"你是一个专门的代理,负责执行特定任务。",""].join(`
118
- `),y=dQ.join(w,`${X.name}.md`);await Q9.promises.writeFile(y,T,"utf-8"),$()}catch(w){console.error("保存配置失败:",w)}}),P=k0(!1,Q);if(Y9((w,R)=>{if(R.escape)v();else if(R.ctrl&&w==="c"||R.meta&&w==="c")P()},{isActive:J!=="tools"}),J==="mode")return D(J0,{flexDirection:"column",paddingY:1,children:[D(J0,{marginBottom:1,children:D(i,{bold:!0,color:"cyan",children:"选择创建方式"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(J0,{marginBottom:1,children:D(i,{dimColor:!0,children:"你可以手动配置每个细节,或让 AI 根据你的描述自动生成配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(i8,{items:[{label:"AI 智能生成 - 根据描述自动生成完整配置",value:"ai"},{label:"手动配置 - 逐步配置每个选项",value:"manual"}],onSelect:(w)=>{if(w.value==="ai")b("ai"),Z("aiPrompt");else b("manual"),Z("name")}},void 0,!1,void 0,this),D(J0,{marginTop:1,children:D(i,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 取消"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(J==="aiPrompt")return D(J0,{flexDirection:"column",paddingY:1,children:[D(J0,{marginBottom:1,children:D(i,{bold:!0,color:"cyan",children:"AI 智能生成"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(J0,{marginBottom:1,children:D(i,{dimColor:!0,children:'描述你想要创建的 Agent(例如:"一个专门用于代码审查的 agent,能够分析代码质量和潜在bug")'},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(J0,{marginBottom:1,children:[D(i,{color:"green",children:"描述: "},void 0,!1,void 0,this),D(Z8,{value:G,onChange:q,onSubmit:(w)=>{if(!w.trim())return;Z("aiGenerating")}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D(J0,{children:D(i,{dimColor:!0,children:"按 Enter 开始生成 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(J==="aiGenerating"){if(O)return D(J0,{flexDirection:"column",paddingY:1,children:[D(J0,{marginBottom:1,children:D(i,{bold:!0,color:"red",children:"AI 生成失败"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(J0,{marginBottom:1,children:D(i,{color:"red",children:O},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(J0,{marginBottom:1,children:D(i,{dimColor:!0,children:"按 ESC 返回修改描述"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return D(J0,{flexDirection:"column",paddingY:1,children:[D(J0,{marginBottom:1,children:D(i,{bold:!0,color:"yellow",children:[D(DY,{type:"dots"},void 0,!1,void 0,this)," AI 正在生成配置..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this),D(J0,{marginBottom:1,children:D(i,{dimColor:!0,children:['根据你的描述:"',G,'"']},void 0,!0,void 0,this)},void 0,!1,void 0,this),D(J0,{marginBottom:1,children:D(i,{color:"gray",children:"正在调用 LLM 生成 agent 配置,请稍候..."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}if(J==="name"){let w=_==="edit";return D(J0,{flexDirection:"column",paddingY:1,children:[D(J0,{marginBottom:1,children:D(i,{bold:!0,color:"cyan",children:["Step 1/7: ",w?"Agent 名称(不可修改)":"输入 Agent 名称"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),D(J0,{marginBottom:1,children:D(i,{dimColor:!0,children:w?"编辑模式下名称不可修改(修改名称相当于创建新 Agent)":"名称只能包含小写字母、数字和连字符(例如:code-reviewer)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(J0,{marginBottom:1,children:[D(i,{color:"green",children:"名称: "},void 0,!1,void 0,this),w?D(i,{children:X.name},void 0,!1,void 0,this):D(Z8,{value:X.name,onChange:(R)=>U({...X,name:R}),onSubmit:(R)=>{if(EY(R))return;A()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D(J0,{children:D(i,{dimColor:!0,children:w?"按 Enter 继续 | ESC 返回":"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this),w&&D(Z8,{value:"",onChange:()=>{},onSubmit:A,showCursor:!1},"edit-mode-dummy-input",!1,void 0,this)]},void 0,!0,void 0,this)}if(J==="description")return D(J0,{flexDirection:"column",paddingY:1,children:[D(J0,{marginBottom:1,children:D(i,{bold:!0,color:"cyan",children:"Step 2/7: 输入描述信息"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(J0,{marginBottom:1,children:D(i,{dimColor:!0,children:"简短描述这个 Agent 的用途和使用场景(这将帮助主 Agent 决定何时使用它)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(J0,{marginBottom:1,children:[D(i,{color:"green",children:"描述: "},void 0,!1,void 0,this),D(Z8,{value:X.description,onChange:(w)=>U({...X,description:w}),onSubmit:(w)=>{if(!w.trim())return;A()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D(J0,{children:D(i,{dimColor:!0,children:"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(J==="tools")return D(hY,{config:X,setConfig:U,onNext:A,onPrev:v},void 0,!1,void 0,this);if(J==="color")return D(J0,{flexDirection:"column",paddingY:1,children:[D(J0,{marginBottom:1,children:D(i,{bold:!0,color:"cyan",children:"Step 4/7: 选择背景颜色"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(J0,{marginBottom:1,children:D(i,{dimColor:!0,children:"为 Agent 选择一个颜色标识(用于在 UI 中区分不同的 Agents)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(i8,{items:jY,onSelect:(w)=>{let R=w.value==="none"?void 0:w.value;U({...X,color:R}),A()}},void 0,!1,void 0,this),D(J0,{marginTop:1,children:D(i,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(J==="location")return D(J0,{flexDirection:"column",paddingY:1,children:[D(J0,{marginBottom:1,children:D(i,{bold:!0,color:"cyan",children:"Step 5/7: 选择保存位置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(J0,{marginBottom:1,children:D(i,{dimColor:!0,children:"项目级配置仅在当前项目生效,用户级配置全局可用"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(i8,{items:[{label:"项目级 (.blade/agents/) - 仅当前项目",value:"project"},{label:"用户级 (~/.blade/agents/) - 全局可用",value:"user"}],onSelect:(w)=>{U({...X,location:w.value}),A()}},void 0,!1,void 0,this),D(J0,{marginTop:1,children:D(i,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(J==="systemPrompt")return D(J0,{flexDirection:"column",paddingY:1,children:[D(J0,{marginBottom:1,children:D(i,{bold:!0,color:"cyan",children:"Step 6/7: 输入系统提示词"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(J0,{marginBottom:1,children:D(i,{dimColor:!0,children:"定义 Agent 的行为和职责(可选,留空将使用默认提示)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(J0,{marginBottom:1,children:[D(i,{color:"green",children:"提示词: "},void 0,!1,void 0,this),D(Z8,{value:X.systemPrompt,onChange:(w)=>U({...X,systemPrompt:w}),onSubmit:()=>A()},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D(J0,{children:D(i,{dimColor:!0,children:"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(J==="confirm")return D(J0,{flexDirection:"column",paddingY:1,children:[D(J0,{marginBottom:1,children:D(i,{bold:!0,color:"cyan",children:"Step 7/7: 确认配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(J0,{flexDirection:"column",paddingLeft:2,marginBottom:1,children:[D(i,{children:[D(i,{bold:!0,color:"green",children:["名称:"," "]},void 0,!0,void 0,this),D(i,{children:X.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D(i,{children:[D(i,{bold:!0,color:"green",children:["描述:"," "]},void 0,!0,void 0,this),D(i,{children:X.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D(i,{children:[D(i,{bold:!0,color:"green",children:["工具:"," "]},void 0,!0,void 0,this),D(i,{children:X.tools.includes("all")?"所有工具":X.tools.join(", ")||"所有工具"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D(i,{children:[D(i,{bold:!0,color:"green",children:["颜色:"," "]},void 0,!0,void 0,this),D(i,{children:X.color||"默认"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D(i,{children:[D(i,{bold:!0,color:"green",children:["位置:"," "]},void 0,!0,void 0,this),D(i,{children:X.location==="project"?"项目级":"用户级"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D(i,{children:[D(i,{bold:!0,color:"green",children:["提示词:"," "]},void 0,!0,void 0,this),D(i,{children:X.systemPrompt||"(使用默认)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),D(i8,{items:[{label:"确认并保存",value:"save"},{label:"返回上一步",value:"back"},{label:"取消",value:"cancel"}],onSelect:(w)=>{if(w.value==="save")N();else if(w.value==="back")v();else Q()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null}function hY({config:$,setConfig:Q,onNext:Y,onPrev:J}){let{isFocused:Z}=SY({id:"step-tools"});Y9((U,G)=>{if(G.escape)J()},{isActive:Z});let X=(U)=>{if(U.includes("all"))Q({...$,tools:["all"]});else Q({...$,tools:U});Y()};return D(J0,{flexDirection:"column",paddingY:1,children:[D(J0,{marginBottom:1,children:D(i,{bold:!0,color:"cyan",children:"Step 3/7: 选择可用工具"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(J0,{marginBottom:1,children:D(i,{dimColor:!0,children:"方向键导航,空格切换勾选,Enter 确认进入下一步 | ESC 返回上一步"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(kY,{options:VY,defaultValue:$.tools,onSubmit:X},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import gY from"node:fs";import{useMemoizedFn as N$}from"ahooks";import{Box as M0,Text as S0,useInput as mY}from"ink";import lQ from"ink-select-input";import{useEffect as pY,useMemo as Z9,useState as n8}from"react";import{jsxDEV as a}from"react/jsx-dev-runtime";var rQ=10;function U9({workspaceRoot:$,initialMode:Q="menu",onComplete:Y,onCancel:J}){let Z=X9($),[X,U]=n8(Q),[G,q]=n8(null),[K,W]=n8(0),[O,B]=n8(0),_=N$(()=>{Z.clear(),Z.loadFromStandardLocations(),W((y)=>y+1)}),b=Z9(()=>{return Z.getAllSubagents()},[K]),z=Math.ceil(b.length/rQ)||1,H=Z9(()=>{let y=O*rQ;return b.slice(y,y+rQ)},[b,O]);pY(()=>{let y=Math.max(0,z-1);if(O>y)B(y)},[z,O]);let F=N$(()=>{if(O<z-1)B((y)=>y+1)}),A=N$(()=>{if(O>0)B((y)=>y-1)}),v=[{key:"list",label:"查看所有 Agents",value:"list"},{key:"create",label:"创建新 Agent",value:"create"},{key:"edit",label:"编辑 Agent",value:"edit"},{key:"delete",label:"删除 Agent",value:"delete"},{key:"cancel",label:"取消",value:"cancel"}],C=N$((y)=>{if(y.value==="cancel"){J?.();return}U(y.value)}),N=N$((y)=>{if(q(y.value),X==="edit")U("editWizard");else if(X==="delete")U("deleteConfirm")}),P=N$(async()=>{if(!G?.configPath)return;try{await gY.promises.unlink(G.configPath),_(),w()}catch(y){console.error("删除失败:",y)}}),w=N$(()=>{U("menu"),q(null)}),R=k0(!1,J);if(mY((y,S)=>{if(S.escape){if(X==="menu")J?.();else if(X==="list"||X==="edit"||X==="delete")B(0),w();else if(X==="deleteConfirm")w()}else if(S.ctrl&&y==="c"||S.meta&&y==="c")R();else if(X==="list"){if(S.leftArrow||y==="h")A();else if(S.rightArrow||y==="l")F()}},{isActive:X!=="create"&&X!=="editWizard"}),X==="menu")return a(M0,{flexDirection:"column",paddingY:1,children:[a(M0,{marginBottom:1,children:a(S0,{bold:!0,color:"cyan",children:"Agents 管理"},void 0,!1,void 0,this)},void 0,!1,void 0,this),a(lQ,{items:v,onSelect:C},void 0,!1,void 0,this),a(M0,{marginTop:1,children:a(S0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 退出"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="list"){if(b.length===0)return a(M0,{flexDirection:"column",paddingY:1,children:[a(M0,{marginBottom:1,children:a(S0,{bold:!0,color:"cyan",children:"所有 Agents"},void 0,!1,void 0,this)},void 0,!1,void 0,this),a(M0,{paddingLeft:2,children:a(S0,{color:"gray",children:"没有找到任何 agent 配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),a(M0,{marginTop:1,paddingLeft:2,children:a(S0,{color:"gray",children:"配置文件位置: .blade/agents/ 或 ~/.blade/agents/"},void 0,!1,void 0,this)},void 0,!1,void 0,this),a(M0,{marginTop:1,paddingLeft:2,children:a(S0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return a(M0,{flexDirection:"column",paddingY:1,children:[a(M0,{marginBottom:1,children:[a(S0,{bold:!0,color:"cyan",children:"所有 Agents"},void 0,!1,void 0,this),a(S0,{color:"gray",children:[" (共 ",b.length," 个)"]},void 0,!0,void 0,this),z>1&&a(S0,{color:"yellow",children:[" ","第 ",O+1,"/",z," 页"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),H.map((y)=>a(M0,{flexDirection:"column",paddingLeft:2,children:[a(M0,{children:a(S0,{children:[a(S0,{bold:!0,color:y.color||"white",children:["• ",y.name]},void 0,!0,void 0,this),a(S0,{color:"gray",children:[" - ",y.description]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),y.tools&&y.tools.length>0&&a(M0,{paddingLeft:2,children:a(S0,{color:"gray",children:["工具: ",y.tools.join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this),y.configPath&&a(M0,{paddingLeft:2,children:a(S0,{color:"gray",dimColor:!0,children:y.configPath},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},y.name,!0,void 0,this)),a(M0,{marginTop:1,paddingLeft:2,children:z>1?a(S0,{dimColor:!0,children:"Left/Right to page | ESC 返回菜单"},void 0,!1,void 0,this):a(S0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}let T=(y)=>{if(b.length===0)return a(M0,{flexDirection:"column",paddingY:1,children:[a(M0,{marginBottom:1,children:a(S0,{bold:!0,color:"cyan",children:y},void 0,!1,void 0,this)},void 0,!1,void 0,this),a(M0,{paddingLeft:2,children:a(S0,{color:"gray",children:"没有找到任何 agent 配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),a(M0,{marginTop:1,paddingLeft:2,children:a(S0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);let S=b.map((E)=>({key:E.name,label:`${E.name} - ${E.description}`,value:E}));return a(M0,{flexDirection:"column",paddingY:1,children:[a(M0,{marginBottom:1,children:a(S0,{bold:!0,color:"cyan",children:y},void 0,!1,void 0,this)},void 0,!1,void 0,this),a(lQ,{items:S,onSelect:N},void 0,!1,void 0,this),a(M0,{marginTop:1,children:a(S0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};if(X==="create")return a(X8,{onComplete:()=>{_(),w()},onCancel:w},void 0,!1,void 0,this);if(X==="edit")return T("编辑 Agent");if(X==="editWizard"&&G){let y={name:G.name,description:G.description,tools:G.tools||[],color:G.color,location:G.configPath?.includes(".blade/agents")?"project":"user",systemPrompt:G.systemPrompt||""};return a(X8,{initialConfig:y,onComplete:()=>{_(),w()},onCancel:w},void 0,!1,void 0,this)}if(X==="delete")return T("删除 Agent");if(X==="deleteConfirm"&&G)return a(M0,{flexDirection:"column",paddingY:1,children:[a(M0,{marginBottom:1,children:a(S0,{bold:!0,color:"red",children:"确认删除"},void 0,!1,void 0,this)},void 0,!1,void 0,this),a(M0,{marginBottom:1,paddingLeft:2,children:a(S0,{children:["你确定要删除 Agent"," ",a(S0,{bold:!0,color:"yellow",children:G.name},void 0,!1,void 0,this)," ","吗?"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),a(M0,{marginBottom:1,paddingLeft:2,children:a(S0,{dimColor:!0,children:["文件路径: ",G.configPath]},void 0,!0,void 0,this)},void 0,!1,void 0,this),a(M0,{marginBottom:1,paddingLeft:2,children:a(S0,{color:"red",children:"此操作无法撤销!"},void 0,!1,void 0,this)},void 0,!1,void 0,this),a(lQ,{items:[{label:"确认删除",value:"confirm"},{label:"取消",value:"cancel"}],onSelect:(y)=>{if(y.value==="confirm")P();else w()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null}import{Box as h$,Text as K0}from"ink";import xY,{useEffect as uY,useState as dY}from"react";import{useEffect as cY,useState as G9}from"react";function O9($=A0(),Q=5000){let[Y,J]=G9(null),[Z,X]=G9(!0);return cY(()=>{let U=!0,G=async()=>{try{let K=await q9($);if(!U)return;if(!K){J(null),X(!1);return}let W=await K9($);if(!U)return;J(W)}catch{if(U)J(null)}finally{if(U)X(!1)}};G();let q=null;if(Q>0)q=setInterval(G,Q);return()=>{if(U=!1,q)clearInterval(q)}},[$,Q]),{branch:Y,loading:Z}}import{jsxDEV as o,Fragment as b1}from"react/jsx-dev-runtime";var z9=xY.memo(()=>{let $=y8(),Q=T$(),J=P8()==="shortcuts",Z=J2(),X=M1(),{branch:U}=O9(X),G=M8(),q=n6(),K=o6(),W=C8(),O=T8(),B=k8(),_=S8(),b=f8(),z=i6(),H=v8(),F=q2(),A=R8(),[v,C]=dY(null);uY(()=>{let y=!1;new aQ(X,A).get().then((c)=>{if(!y)C(c)}).catch(()=>{if(!y)C(null)});let E=aQ.subscribe((c)=>{if(!y&&c.sessionId===A&&c.workspaceRoot===X)C(c.goal)});return()=>{y=!0,E()}},[A,X]);let N=G?r8(G):!1,w=(()=>{if(Q==="default")return null;if(Q==="autoEdit")return o(K0,{color:"magenta",children:[">> ","auto edit on ",o(K0,{color:"gray",children:"(shift+tab to cycle)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Q==="plan")return o(K0,{color:"cyan",children:["‖ plan mode on ",o(K0,{color:"gray",children:"(shift+tab to cycle)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Q==="yolo")return o(K0,{color:"red",children:["yolo mode on ",o(K0,{color:"gray",children:"(all tools auto-approved)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null})(),R=w!==null,T=[["Enter:发送","Shift+Enter:换行","Esc:中止"],["Shift+Tab:切换模式","Up/Down:历史","Tab:补全"],["Ctrl+A:行首","Ctrl+E:行尾","Ctrl+K:删到尾"],["Ctrl+U:删到首","Ctrl+W:删单词","Ctrl+C:退出"]];return o(h$,{flexDirection:"row",justifyContent:"space-between",paddingX:2,paddingY:0,children:[J?o(h$,{flexDirection:"column",gap:0,children:T.map((y,S)=>o(h$,{flexDirection:"row",children:[y.map((E,c)=>{let[Q0,d]=E.split(":");return o(h$,{flexDirection:"row",width:20,children:[o(K0,{color:"yellow",children:Q0},void 0,!1,void 0,this),o(K0,{color:"gray",children:":"},void 0,!1,void 0,this),o(K0,{color:"white",children:d},void 0,!1,void 0,this)]},c,!0,void 0,this)}),S===T.length-1&&o(K0,{color:"cyan",children:" ? 关闭"},void 0,!1,void 0,this)]},S,!0,void 0,this))},void 0,!1,void 0,this):o(h$,{flexDirection:"row",gap:1,children:[U&&o(b1,{children:[o(K0,{color:"gray",children:[" ",U]},void 0,!0,void 0,this),o(K0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),w,R&&o(K0,{color:"gray",children:"·"},void 0,!1,void 0,this),v&&o(b1,{children:[o(K0,{color:v.status==="active"?"green":v.status==="blocked"||v.status==="budget_limited"?"yellow":"gray",children:["goal:",v.status," ",v.objective.slice(0,32)]},void 0,!0,void 0,this),o(K0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o(K0,{color:"gray",children:"? for shortcuts"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o(h$,{flexDirection:"row",gap:1,children:!$?o(K0,{color:"red",children:"[WARN] API 密钥未配置"},void 0,!1,void 0,this):o(b1,{children:[N&&o(b1,{children:[W?o(K0,{color:"cyan",children:["Effort ",O]},void 0,!0,void 0,this):o(K0,{color:"gray",children:"Tab:Effort"},void 0,!1,void 0,this),o(K0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),B!=="auto"&&o(b1,{children:[o(K0,{color:B==="fast"?"yellow":"gray",children:["Speed ",B]},void 0,!0,void 0,this),o(K0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),_!=="auto"&&o(b1,{children:[o(K0,{color:"gray",children:["Output ",_]},void 0,!0,void 0,this),o(K0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b!=="auto"&&o(b1,{children:[o(K0,{color:"gray",children:["Style ",b]},void 0,!0,void 0,this),o(K0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),G&&o(K0,{color:"gray",children:G.model},void 0,!1,void 0,this),o(K0,{color:"gray",children:"·"},void 0,!1,void 0,this),K?o(K0,{color:"yellow",children:"压缩中..."},void 0,!1,void 0,this):o(K0,{color:q<20?"red":q<50?"yellow":"gray",children:[q,"%"]},void 0,!0,void 0,this),z>0.001&&o(b1,{children:[o(K0,{color:"gray",children:"·"},void 0,!1,void 0,this),o(K0,{color:"green",children:["$",z<0.01?z.toFixed(4):z.toFixed(3)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),H.length>0&&o(b1,{children:[o(K0,{color:"gray",children:"·"},void 0,!1,void 0,this),o(K0,{color:"yellow",children:["已排队 ",H.length]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),F>0&&o(b1,{children:[o(K0,{color:"gray",children:"·"},void 0,!1,void 0,this),o(K0,{color:"cyan",children:["已恢复 ",F," 条指令"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Z&&o(b1,{children:[o(K0,{color:"gray",children:"·"},void 0,!1,void 0,this),o(K0,{color:"yellow",children:"再按一次 Ctrl+C 退出"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as oQ,Text as iQ}from"ink";import lY from"react";import{jsxDEV as g$}from"react/jsx-dev-runtime";var _9=lY.memo(({suggestions:$,selectedIndex:Q,visible:Y,maxDisplay:J=8})=>{if(!Y||$.length===0)return null;let Z=0,X=Math.min(J,$.length),U=Q>=$.length;if(Q>=J&&!U)Z=Q-J+1,X=Q+1;let G=$.slice(Z,X),q=$.length>J;return g$(oQ,{flexDirection:"column",paddingX:2,paddingY:0,children:[G.map((K,W)=>{let B=Z+W===Q;return g$(oQ,{flexDirection:"row",paddingX:1,gap:2,children:[g$(iQ,{color:B?"cyan":"white",bold:B,children:K.command},void 0,!1,void 0,this),g$(iQ,{color:B?"cyan":"gray",dimColor:!B,children:["- ",K.description]},void 0,!0,void 0,this)]},K.command,!0,void 0,this)}),q&&g$(oQ,{paddingX:1,children:g$(iQ,{color:U?"cyan":"gray",bold:U,dimColor:!U,children:["... and ",$.length-J," more"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as W1,Text as v1,useInput as h3,useStdout as g3}from"ink";import m3 from"ink-select-input";import b6,{useMemo as p9}from"react";import{Box as q0,Text as B0}from"ink";import W$,{useEffect as B6,useMemo as H$,useRef as h9}from"react";import{Box as G6,Text as y9}from"ink";import X3 from"react";import{Text as A1}from"ink";import J3 from"react";import A9 from"string-width";import U8 from"string-width";function nQ({onlyFirst:$=!1}={}){return new RegExp("(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]",$?void 0:"g")}var rY=nQ();function tQ($){if(typeof $!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof $}\``);if(!$.includes("\x1B")&&!$.includes("›"))return $;return $.replace(rY,"")}var N9=($=0)=>(Q)=>`\x1B[${Q+$}m`,F9=($=0)=>(Q)=>`\x1B[${38+$};5;${Q}m`,H9=($=0)=>(Q,Y,J)=>`\x1B[${38+$};2;${Q};${Y};${J}m`,j0={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},YG=Object.keys(j0.modifier),aY=Object.keys(j0.color),oY=Object.keys(j0.bgColor),ZG=[...aY,...oY];function iY(){let $=new Map;for(let[Q,Y]of Object.entries(j0)){for(let[J,Z]of Object.entries(Y))j0[J]={open:`\x1B[${Z[0]}m`,close:`\x1B[${Z[1]}m`},Y[J]=j0[J],$.set(Z[0],Z[1]);Object.defineProperty(j0,Q,{value:Y,enumerable:!1})}return Object.defineProperty(j0,"codes",{value:$,enumerable:!1}),j0.color.close="\x1B[39m",j0.bgColor.close="\x1B[49m",j0.color.ansi=N9(),j0.color.ansi256=F9(),j0.color.ansi16m=H9(),j0.bgColor.ansi=N9(10),j0.bgColor.ansi256=F9(10),j0.bgColor.ansi16m=H9(10),Object.defineProperties(j0,{rgbToAnsi256:{value(Q,Y,J){if(Q===Y&&Y===J){if(Q<8)return 16;if(Q>248)return 231;return Math.round((Q-8)/247*24)+232}return 16+36*Math.round(Q/255*5)+6*Math.round(Y/255*5)+Math.round(J/255*5)},enumerable:!1},hexToRgb:{value(Q){let Y=/[a-f\d]{6}|[a-f\d]{3}/i.exec(Q.toString(16));if(!Y)return[0,0,0];let[J]=Y;if(J.length===3)J=[...J].map((X)=>X+X).join("");let Z=Number.parseInt(J,16);return[Z>>16&255,Z>>8&255,Z&255]},enumerable:!1},hexToAnsi256:{value:(Q)=>j0.rgbToAnsi256(...j0.hexToRgb(Q)),enumerable:!1},ansi256ToAnsi:{value(Q){if(Q<8)return 30+Q;if(Q<16)return 90+(Q-8);let Y,J,Z;if(Q>=232)Y=((Q-232)*10+8)/255,J=Y,Z=Y;else{Q-=16;let G=Q%36;Y=Math.floor(Q/36)/5,J=Math.floor(G/6)/5,Z=G%6/5}let X=Math.max(Y,J,Z)*2;if(X===0)return 30;let U=30+(Math.round(Z)<<2|Math.round(J)<<1|Math.round(Y));if(X===2)U+=60;return U},enumerable:!1},rgbToAnsi:{value:(Q,Y,J)=>j0.ansi256ToAnsi(j0.rgbToAnsi256(Q,Y,J)),enumerable:!1},hexToAnsi:{value:(Q)=>j0.ansi256ToAnsi(j0.hexToAnsi256(Q)),enumerable:!1}}),j0}var nY=iY(),W9=nY;var s8=new Set(["\x1B","›"]),tY=39,eQ="\x07",w9="[",sY="]",b9="m",t8=`${sY}8;;`,L9=($)=>`${s8.values().next().value}${w9}${$}${b9}`,B9=($)=>`${s8.values().next().value}${t8}${$}${eQ}`,eY=($)=>$.split(" ").map((Q)=>U8(Q)),sQ=($,Q,Y)=>{let J=[...Q],Z=!1,X=!1,U=U8(tQ($.at(-1)));for(let[G,q]of J.entries()){let K=U8(q);if(U+K<=Y)$[$.length-1]+=q;else $.push(q),U=0;if(s8.has(q))Z=!0,X=J.slice(G+1,G+1+t8.length).join("")===t8;if(Z){if(X){if(q===eQ)Z=!1,X=!1}else if(q===b9)Z=!1;continue}if(U+=K,U===Y&&G<J.length-1)$.push(""),U=0}if(!U&&$.at(-1).length>0&&$.length>1)$[$.length-2]+=$.pop()},$3=($)=>{let Q=$.split(" "),Y=Q.length;while(Y>0){if(U8(Q[Y-1])>0)break;Y--}if(Y===Q.length)return $;return Q.slice(0,Y).join(" ")+Q.slice(Y).join("")},Q3=($,Q,Y={})=>{if(Y.trim!==!1&&$.trim()==="")return"";let J="",Z,X,U=eY($),G=[""];for(let[O,B]of $.split(" ").entries()){if(Y.trim!==!1)G[G.length-1]=G.at(-1).trimStart();let _=U8(G.at(-1));if(O!==0){if(_>=Q&&(Y.wordWrap===!1||Y.trim===!1))G.push(""),_=0;if(_>0||Y.trim===!1)G[G.length-1]+=" ",_++}if(Y.hard&&U[O]>Q){let b=Q-_,z=1+Math.floor((U[O]-b-1)/Q);if(Math.floor((U[O]-1)/Q)<z)G.push("");sQ(G,B,Q);continue}if(_+U[O]>Q&&_>0&&U[O]>0){if(Y.wordWrap===!1&&_<Q){sQ(G,B,Q);continue}G.push("")}if(_+U[O]>Q&&Y.wordWrap===!1){sQ(G,B,Q);continue}G[G.length-1]+=B}if(Y.trim!==!1)G=G.map((O)=>$3(O));let q=G.join(`
119
- `),K=[...q],W=0;for(let[O,B]of K.entries()){if(J+=B,s8.has(B)){let{groups:b}=new RegExp(`(?:\\${w9}(?<code>\\d+)m|\\${t8}(?<uri>.*)${eQ})`).exec(q.slice(W))||{groups:{}};if(b.code!==void 0){let z=Number.parseFloat(b.code);Z=z===tY?void 0:z}else if(b.uri!==void 0)X=b.uri.length===0?void 0:b.uri}let _=W9.codes.get(Number(Z));if(K[O+1]===`
120
- `){if(X)J+=B9("");if(Z&&_)J+=L9(_)}else if(B===`
121
- `){if(Z&&_)J+=L9(Z);if(X)J+=B9(X)}W+=B.length}return J};function $6($,Q,Y){return String($).normalize().replaceAll(`\r
122
- `,`
123
- `).split(`
124
- `).map((J)=>Q3(J,Q,Y)).join(`
125
- `)}var Q6=($)=>{let Q=$.replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/_(.*?)_/g,"$1").replace(/~~(.*?)~~/g,"$1").replace(/`(.*?)`/g,"$1").replace(/<u>(.*?)<\/u>/g,"$1").replace(/\[(.*?)\]\(.*?\)/g,"$1");return A9(Q)};var R9=($)=>{return/[*_~`<[\]https?:]/.test($)},J6=($)=>{let Y=$.replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/_(.*?)_/g,"$1").replace(/~~(.*?)~~/g,"$1").replace(/`(.*?)`/g,"$1").replace(/<u>(.*?)<\/u>/g,"$1").replace(/\[(.*?)\]\(.*?\)/g,"$1").split(/\s+/).filter((J)=>J.length>0);if(Y.length===0)return 0;return Math.max(...Y.map((J)=>A9(J)))},e8=($,Q,Y=!1)=>{if(Q<=0)return[$];let J=$.trimEnd(),X=$6(J,Q,{hard:Y,trim:!1,wordWrap:!0}).split(`
126
- `).filter((U)=>U.length>0);return X.length>0?X:[""]},P9=($,Q,Y,J)=>{let Z=Math.max(0,Y-Q);if(J==="center"){let X=Math.floor(Z/2);return" ".repeat(X)+$+" ".repeat(Z-X)}if(J==="right")return" ".repeat(Z)+$;return $+" ".repeat(Z)};import{jsxDEV as H1,Fragment as Z3}from"react/jsx-dev-runtime";var Y6=2,Z6=1,X6=2;function U6($,Q){return`inline-${$}-${Q}`}var Y3=({text:$})=>{let Q=b0();if(!R9($))return H1(A1,{children:$},void 0,!1,void 0,this);let Y=[],J=0,Z=0,X=0,U=/(\*\*.*?\*\*|\*(?!\s).*?(?<!\s)\*|_(?!\s).*?(?<!\s)_|~~.*?~~|`+[^`]+`+|\[.*?\]\(.*?\)|https?:\/\/\S+)/g,G;while((G=U.exec($))!==null){if(G.index>J){let O=$.slice(J,G.index);Y.push(H1(A1,{children:O},U6("text",Z++),!1,void 0,this))}let q=G[0],K=null,W=U6("match",X++);try{if(q.startsWith("**")&&q.endsWith("**")&&q.length>Y6*2)K=H1(A1,{bold:!0,children:q.slice(Y6,-Y6)},W,!1,void 0,this);else if(q.length>Z6*2&&(q.startsWith("*")&&q.endsWith("*")||q.startsWith("_")&&q.endsWith("_"))){let O=$.substring(G.index-1,G.index),B=$.substring(U.lastIndex,U.lastIndex+1);if(!(/\w/.test(O)||/\w/.test(B)||/[./\\]/.test(O+B)))K=H1(A1,{italic:!0,children:q.slice(Z6,-Z6)},W,!1,void 0,this)}else if(q.startsWith("~~")&&q.endsWith("~~")&&q.length>X6*2)K=H1(A1,{strikethrough:!0,children:q.slice(X6,-X6)},W,!1,void 0,this);else if(q.startsWith("`")&&q.endsWith("`")){let O=q.match(/^(`+)([^`]+)\1$/);if(O&&O[2])K=H1(A1,{color:Q.colors.syntax.keyword,backgroundColor:Q.colors.background.secondary,bold:!0,children:` ${O[2]} `},W,!1,void 0,this)}else if(q.startsWith("[")&&q.includes("](")&&q.endsWith(")")){let O=q.match(/\[(.*?)\]\((.*?)\)/);if(O){let B=O[1],_=O[2];K=H1(A1,{children:[B,H1(A1,{color:Q.colors.info,children:[" (",_,")"]},void 0,!0,void 0,this)]},W,!0,void 0,this)}}else if(q.match(/^https?:\/\//))K=H1(A1,{color:Q.colors.info,children:q},W,!1,void 0,this)}catch(O){console.error("InlineRenderer 解析错误:",q,O),K=null}Y.push(K??H1(A1,{children:q},W,!1,void 0,this)),J=U.lastIndex}if(J<$.length){let q=$.slice(J);Y.push(H1(A1,{children:q},U6("text",Z++),!1,void 0,this))}return H1(Z3,{children:Y.filter((q)=>q!==null)},void 0,!1,void 0,this)},R1=J3.memo(Y3);import{jsxDEV as m$}from"react/jsx-dev-runtime";var U3="▎",M9=X3.memo(({lines:$,level:Q})=>{let Y=b0(),J=U3.repeat(Q);return m$(G6,{flexDirection:"column",children:$.map((Z,X)=>{if(Z.trim()==="")return m$(G6,{height:1},X,!1,void 0,this);return m$(G6,{flexDirection:"row",children:[m$(y9,{dimColor:!0,color:Y.colors.text.muted,children:[J," "]},void 0,!0,void 0,this),m$(y9,{italic:!0,wrap:"wrap",children:m$(R1,{text:Z},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},X,!0,void 0,this)})},void 0,!1,void 0,this)});import{Box as QQ,Text as j1}from"ink";import{isPlainObject as _6}from"lodash-es";import{common as z3,createLowlight as _3}from"lowlight";import k9 from"react";import{Box as $Q,Text as G8}from"ink";import V1,{Fragment as C9}from"react";import G3 from"string-width";var I9=new Map,v9=1000;function K6($){let Q=!0;for(let J=0;J<$.length;J++)if($.charCodeAt(J)>127){Q=!1;break}if(Q)return $.split("");if($.length<=v9){let J=I9.get($);if(J)return J}let Y=Array.from($);if($.length<=v9)I9.set($,Y);return Y}var q6=new Map;function D1($){if(/^[\x20-\x7E]*$/.test($))return $.length;if(q6.has($))return q6.get($);let Q=G3($);return q6.set($,Q),Q}import{jsxDEV as p$}from"react/jsx-dev-runtime";var O6=2,T9=V1.memo(({children:$,maxWidth:Q,maxHeight:Y,overflowDirection:J="top",additionalHiddenLinesCount:Z=0})=>{let X=b0(),U=[],G=Math.max(Math.round(Y??Number.MAX_SAFE_INTEGER),O6);function q(z){if(!V1.isValidElement(z))return;if(z.type===C9){V1.Children.forEach(z.props.children,q);return}if(z.type===$Q){K3(z,Q,U);return}}V1.Children.forEach($,q);let W=U.length>G||Z>0?G-1:G,O=W!==void 0?Math.max(0,U.length-W):0,B=O+Z,b=(O>0?J==="top"?U.slice(O):U.slice(0,W):U).map((z,H)=>p$($Q,{children:z.length>0?z.map((F,A)=>p$(G8,{...F.props,children:F.text},A,!1,void 0,this)):p$(G8,{children:" "},void 0,!1,void 0,this)},H,!1,void 0,this));return p$($Q,{flexDirection:"column",width:Q,flexShrink:0,children:[B>0&&J==="top"&&p$(G8,{color:X.colors.text.muted,dimColor:!0,children:["... ",B," line",B===1?"":"s"," hidden ..."]},void 0,!0,void 0,this),b,B>0&&J==="bottom"&&p$(G8,{color:X.colors.text.muted,dimColor:!0,children:["... ",B," line",B===1?"":"s"," hidden ..."]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)});function q3($){if(!V1.isValidElement($)||$.type!==$Q)return{noWrapSegments:[],segments:[]};let Q={noWrapSegments:[],segments:[]},Y=!1;function J(Z,X){if(Z===null||Z===void 0)return;if(typeof Z==="string"||typeof Z==="number"){let K=String(Z);if(!K)return;let W={text:K,props:X??{}};if(X===void 0||X.wrap==="wrap")Y=!0,Q.segments.push(W);else if(!Y)Q.noWrapSegments.push(W);else Q.segments.push(W);return}if(!V1.isValidElement(Z))return;if(Z.type===C9){V1.Children.forEach(Z.props.children,(K)=>J(K,X));return}if(Z.type!==G8)return;let{children:U,...G}=Z.props,q=X===void 0?G:{...X,...G};V1.Children.forEach(U,(K)=>J(K,q))}return V1.Children.forEach($.props.children,(Z)=>J(Z,void 0)),Q}function K3($,Q,Y){let J=q3($);if(J.segments.length===0&&J.noWrapSegments.length===0){Y.push([]);return}let Z=0;for(let O of J.noWrapSegments)Z+=D1(O.text);if(J.segments.length===0){let O=[],B=[];for(let _ of J.noWrapSegments){let b=_.text.split(`
127
- `);for(let z=0;z<b.length;z++){if(z>0)O.push(B),B=[];if(b[z])B.push({text:b[z],props:_.props})}}if(B.length>0)O.push(B);for(let _ of O)Y.push(_);return}let X=Q-Z;if(X<1){O3(J.noWrapSegments,Q,Y);return}let U=[],G=[],q=0;function K(){if(U.length===0)U.push([...J.noWrapSegments,...G]);else if(Z>0)U.push([{text:" ".repeat(Z),props:{}},...G]);else U.push(G);G=[],q=0}function W(O,B){if(G.length>0&&G[G.length-1].props===B)G[G.length-1].text+=O;else G.push({text:O,props:B})}for(let O of J.segments){let B=O.text.split(`
128
- `);for(let _=0;_<B.length;_++){if(_>0)K();let z=B[_].split(/(\s+)/);for(let H of z){if(!H)continue;let F=D1(H);if(q+F>X&&q>0){if(K(),/^\s+$/.test(H))continue}if(F>X){let v=K6(H);while(v.length>0){let C=0,N=0;for(let P of v){let w=D1(P);if(q+N+w>X)break;N+=w,C++}if(C>0){let P=v.slice(0,C).join("");W(P,O.props),q+=D1(P),v=v.slice(C)}if(v.length>0)K()}}else W(H,O.props),q+=F}}if(O.text.endsWith(`
129
- `))K()}if(G.length>0)K();for(let O of U)Y.push(O)}function O3($,Q,Y){let J=[],Z=[],X=0;for(let U of $){let G=U.text.split(`
130
- `);for(let q=0;q<G.length;q++){if(q>0)J.push(Z),Z=[],X=0;let K=G[q];if(!K)continue;let W=D1(K),O=Math.max(0,Q-D1("…"));if(W<=O&&X===0)Z.push({text:K,props:U.props}),X+=W;else{let B=K6(K),_=X,b=0;for(let H of B){let F=D1(H);if(_+F>O)break;_+=F,b++}let z=B.slice(0,b).join("");if(z)Z.push({text:z,props:U.props});Z.push({text:"…",props:{}}),X=_+D1("…")}}}if(Z.length>0)J.push(Z);if(J.length===0)J.push([{text:"…",props:{}}]);for(let U of J)Y.push(U)}import{jsxDEV as Z1}from"react/jsx-dev-runtime";var z6=_3(z3),N3=200,F$=new Map;function F3($,Q){let Y=`${Q??"__auto__"}:${$}`,J=F$.get(Y);if(J!==void 0)F$.delete(Y),F$.set(Y,J);return J}function H3($,Q,Y){let J=`${Q??"__auto__"}:${$}`;if(F$.size>=N3){let Z=F$.keys().next().value;if(Z!==void 0)F$.delete(Z)}F$.set(J,Y)}function W3($){return _6($)&&$.type==="text"&&typeof $.value==="string"}function L3($){return _6($)&&$.type==="element"}function B3($){return _6($)&&$.type==="root"&&Array.isArray($.children)}function JQ($,Q,Y=0){if(W3($))return Z1(j1,{wrap:"wrap",children:$.value},Y,!1,void 0,this);if(L3($)){let J=$.properties?.className?.[0]||"",Z=Q.default;if(J.includes("comment"))Z=Q.comment;else if(J.includes("string"))Z=Q.string;else if(J.includes("number"))Z=Q.number;else if(J.includes("keyword"))Z=Q.keyword;else if(J.includes("function"))Z=Q.function;else if(J.includes("variable"))Z=Q.variable;else if(J.includes("operator"))Z=Q.operator;else if(J.includes("type"))Z=Q.type;else if(J.includes("tag"))Z=Q.tag;else if(J.includes("attr"))Z=Q.attr;let X=$.children?.map((U,G)=>JQ(U,Q,G));return Z1(j1,{color:Z,wrap:"wrap",children:X},Y,!1,void 0,this)}if(B3($))return Z1(k9.Fragment,{children:$.children.map((J,Z)=>JQ(J,Q,Z))},Y,!1,void 0,this);return Z1(j1,{},Y,!1,void 0,this)}function w3($,Q,Y){let J=Y||l0.getTheme().colors.syntax;try{let Z=F3($,Q);if(Z)return JQ(Z,J);let X;if(!Q||!z6.registered(Q))X=z6.highlightAuto($);else X=z6.highlight(Q,$);let U=X;if(!U.children||U.children.length===0)return Z1(j1,{color:J.default,wrap:"wrap",children:$},void 0,!1,void 0,this);return H3($,Q,X),JQ(X,J)}catch(Z){return Z1(j1,{color:J.default,wrap:"wrap",children:$},void 0,!1,void 0,this)}}var YQ=k9.memo(({content:$,language:Q,showLineNumbers:Y=!0,terminalWidth:J,availableHeight:Z})=>{let X=b0(),U=$.split(`
131
- `),G=0;if(Z&&U.length>Z){let O=Math.max(Z,O6);if(U.length>O)G=U.length-O,U=U.slice(G)}let q=U.length+G,K=String(q).length+1,W=Math.max(20,J-4);return Z1(QQ,{borderStyle:"round",borderColor:X.colors.border.light,paddingX:1,paddingY:0,marginY:1,flexDirection:"column",children:[Q&&Z1(QQ,{marginBottom:0,children:Z1(j1,{color:X.colors.text.secondary,children:Q},void 0,!1,void 0,this)},void 0,!1,void 0,this),G>0&&Z1(QQ,{marginBottom:0,children:Z1(j1,{color:X.colors.text.muted,dimColor:!0,children:["... ",G," lines hidden ..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Z1(T9,{maxWidth:W,maxHeight:Z,children:U.map((O,B)=>{let _=B+G+1;return Z1(QQ,{flexDirection:"row",children:[Y&&Z1(j1,{color:X.colors.text.muted,dimColor:!0,wrap:"truncate",children:[String(_).padStart(K-1," ")," "]},void 0,!0,void 0,this),O.trim()===""?Z1(j1,{wrap:"wrap",children:" "},void 0,!1,void 0,this):w3(O,Q,X.colors.syntax)]},B,!0,void 0,this)})},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as S9,Text as q1,useInput as b3}from"ink";import A3,{useState as R3}from"react";import{jsxDEV as X1}from"react/jsx-dev-runtime";var f9=400;function P3($){let Q=$.split(`
132
- `),Y=[],J=0,Z=0;for(let X of Q){if(X.startsWith("---")||X.startsWith("+++"))continue;if(X.startsWith("@@")){let U=X.match(/@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@/);if(U)J=parseInt(U[1],10),Z=parseInt(U[3],10);Y.push({type:"header",content:X});continue}if(X.startsWith("-")){Y.push({type:"remove",content:X.substring(1),lineNumber:J}),J++;continue}if(X.startsWith("+")){Y.push({type:"add",content:X.substring(1),lineNumber:Z}),Z++;continue}if(X.startsWith(" ")||X===""){Y.push({type:"context",content:X.substring(1),lineNumber:Z}),J++,Z++;continue}}return Y}var N6=A3.memo(({patch:$,startLine:Q,matchLine:Y,terminalWidth:J,maxLines:Z=20,isFocused:X=!1})=>{let U=b0(),G=P3($),[q,K]=R3(!1);b3((A)=>{if(A.toLowerCase()==="e")K((v)=>!v)},{isActive:X&&G.length>Z});let O=Math.max(...G.map((A)=>A.lineNumber||0)).toString().length+1,B=G.filter((A)=>A.type==="add").length,_=G.filter((A)=>A.type==="remove").length,b=G.length,z=b>Z,H;if(!z)H=G;else if(q)H=G.slice(0,f9);else H=G.slice(0,Z);let F=b-H.length;return X1(S9,{flexDirection:"column",marginTop:1,marginBottom:1,children:[X1(q1,{color:U.colors.muted,children:"─".repeat(Math.max(0,Math.min(60,J)))},void 0,!1,void 0,this),z&&X1(q1,{color:U.colors.info,children:[q?`已展开 ${H.length}/${b} 行`:`显示前 ${Z} 行,共 ${b} 行`," · ",X1(q1,{color:U.colors.success,children:["+",B]},void 0,!0,void 0,this)," ",X1(q1,{color:U.colors.error,children:["-",_]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),z&&X1(q1,{color:U.colors.muted,children:"─".repeat(Math.max(0,Math.min(60,J)))},void 0,!1,void 0,this),H.map((A,v)=>{if(A.type==="header")return X1(q1,{color:U.colors.muted,dimColor:!0,children:A.content},v,!1,void 0,this);let C=A.lineNumber?A.lineNumber.toString().padStart(O," "):" ".repeat(O),N=" ",P,w;if(A.type==="add")N="+",w=U.colors.success,P=void 0;else if(A.type==="remove")N="-",w=U.colors.error,P=void 0;else w=U.colors.text.primary;let R=Math.max(0,J-O-2),T=A.content;if(T.length>R)T=T.substring(0,R-3)+"...";return X1(q1,{color:w,backgroundColor:P,children:[X1(q1,{dimColor:!0,children:C},void 0,!1,void 0,this),X1(q1,{children:N},void 0,!1,void 0,this),X1(q1,{children:[" ",T]},void 0,!0,void 0,this)]},v,!0,void 0,this)}),z&&X1(S9,{marginTop:1,children:q?X1(q1,{color:U.colors.info,dimColor:!0,children:[F>0?`已达显示上限 ${f9} 行,仍有 ${F} 行未显示`:"已显示全部内容",X?" · 按 E 折叠":""]},void 0,!0,void 0,this):X1(q1,{color:U.colors.info,dimColor:!0,children:["已隐藏剩余 ",F," 行",X?" · 按 E 展开全部":""]},void 0,!0,void 0,this)},void 0,!1,void 0,this),X1(q1,{color:U.colors.muted,children:"─".repeat(Math.max(0,Math.min(60,J)))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as F6,Text as D9}from"ink";import y3 from"react";import{jsxDEV as c$}from"react/jsx-dev-runtime";var M3=({itemText:$,type:Q,marker:Y,leadingWhitespace:J=""})=>{let Z=Q==="ol"?`${Y}. `:`${Y} `,X=Z.length,U=J.length;return c$(F6,{paddingLeft:U+1,flexDirection:"row",children:[c$(F6,{width:X,children:c$(D9,{children:Z},void 0,!1,void 0,this)},void 0,!1,void 0,this),c$(F6,{flexGrow:1,children:c$(D9,{wrap:"wrap",children:c$(R1,{text:$},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},H6=y3.memo(M3);import{Text as W6}from"ink";import I3,{useMemo as v3}from"react";import V9 from"string-width";import{jsxDEV as L6}from"react/jsx-dev-runtime";var j9=4,x$=3,C3=4,E9=I3.memo(({headers:$,rows:Q,terminalWidth:Y})=>{let J=b0(),Z=v3(()=>{if($.length===0||Q.length===0)return null;let O=$.length,B=$.map((w,R)=>{let T=Math.max(J6(w),x$);for(let y of Q)T=Math.max(T,J6(y[R]||""));return T}),_=$.map((w,R)=>{let T=Math.max(Q6(w),x$);for(let y of Q)T=Math.max(T,Q6(y[R]||""));return T}),b=1+O*3,z=Math.max(Y-b-j9,O*x$),H=B.reduce((w,R)=>w+R,0),F=_.reduce((w,R)=>w+R,0),A=!1,v;if(F<=z)v=_;else if(H<=z){let w=z-H,R=_.map((y,S)=>y-B[S]),T=R.reduce((y,S)=>y+S,0);v=B.map((y,S)=>{if(T===0)return y;let E=Math.floor(R[S]/T*w);return y+E})}else{A=!0;let w=z/H;v=B.map((R)=>Math.max(Math.floor(R*w),x$))}function C(){let w=1;for(let R=0;R<$.length;R++){let T=e8($[R],v[R],A);w=Math.max(w,T.length)}for(let R of Q)for(let T=0;T<R.length;T++){let y=e8(R[T]||"",v[T],A);w=Math.max(w,y.length)}return w}if(C()>C3)return{type:"vertical",columnWidths:v,needsHardWrap:A};return{type:"horizontal",columnWidths:v,needsHardWrap:A}},[$,Q,Y]);if(!Z)return null;if(Z.type==="vertical"){let O=Math.min(Y-1,40),B="─".repeat(O);return L6(W6,{children:Q.map((_,b)=>{let z=[];if(b>0)z.push(B);return _.forEach((H,F)=>{let A=$[F]||`Column ${F+1}`,v=(H||"").replace(/\n+/g," ").trim();z.push(`\x1B[1m${A}:\x1B[22m ${v}`)}),z.join(`
133
- `)}).join(`
134
- `)},void 0,!1,void 0,this)}let{columnWidths:X,needsHardWrap:U}=Z;function G(O){let _={top:{left:"┌",mid:"┬",right:"┐",h:"─"},middle:{left:"├",mid:"┼",right:"┤",h:"─"},bottom:{left:"└",mid:"┴",right:"┘",h:"─"}}[O],b=_.left;return X.forEach((z,H)=>{b+=_.h.repeat(z+2),b+=H<X.length-1?_.mid:_.right}),b}function q(O,B){let _=O.map((F,A)=>{let v=X[A]||x$;return e8(F||"",v,U)}),b=Math.max(..._.map((F)=>F.length),1),z=_.map((F)=>Math.floor((b-F.length)/2)),H=[];for(let F=0;F<b;F++){let A="│";for(let v=0;v<O.length;v++){let C=_[v],N=z[v],P=F-N,w=P>=0&&P<C.length?C[P]:"",R=X[v]||x$,T=V9(w),y=P9(B?`\x1B[1m${w}\x1B[22m`:w,T,R,B?"center":"left");A+=` ${y} │`}H.push(A)}return H}let K=[];if(K.push(G("top")),K.push(...q($,!0)),K.push(G("middle")),Q.forEach((O,B)=>{if(K.push(...q(O,!1)),B<Q.length-1)K.push(G("middle"))}),K.push(G("bottom")),Math.max(...K.map((O)=>V9(O)))>Y-j9){let O=Math.min(Y-1,40),B="─".repeat(O);return L6(W6,{children:Q.map((_,b)=>{let z=[];if(b>0)z.push(B);return _.forEach((H,F)=>{let A=$[F]||`Column ${F+1}`,v=(H||"").replace(/\n+/g," ").trim();z.push(`\x1B[1m${A}:\x1B[22m ${v}`)}),z.join(`
135
- `)}).join(`
136
- `)},void 0,!1,void 0,this)}return L6(W6,{color:J.colors.text.primary,children:K.join(`
137
- `)},void 0,!1,void 0,this)});import{jsxDEV as h}from"react/jsx-dev-runtime";var T3=($,Q,Y)=>{switch($){case"user":return{color:Q.info,prefix:"> "};case"assistant":return{color:Q.success,prefix:"• "};case"system":return{color:Q.warning,prefix:" "};case"tool":{let J=Y&&"phase"in Y?Y.phase:void 0;return{color:Q.text.secondary,prefix:J==="start"?"• ":J==="complete"?" └ ":" "}}default:return{color:Q.text.primary,prefix:" "}}},k3=W$.memo(({content:$,language:Q,terminalWidth:Y,isPending:J=!1,availableHeight:Z})=>{let X=b0();if(J&&Z!==void 0){let U=$.split(`
138
- `),G=4,q=Math.max(1,Z-4);if(U.length>q){let K=U.slice(0,q).join(`
139
- `);return h(q0,{flexDirection:"column",flexShrink:0,children:[h(YQ,{content:K,language:Q,showLineNumbers:!0,terminalWidth:Y},void 0,!1,void 0,this),h(B0,{color:X.colors.text.muted,dimColor:!0,children:"... generating more code ..."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}}return h(YQ,{content:$,language:Q,showLineNumbers:!0,terminalWidth:Y},void 0,!1,void 0,this)}),S3=W$.memo(({content:$,level:Q})=>{let Y=b0();switch(Q){case 1:return h(B0,{bold:!0,color:Y.colors.primary,children:h(R1,{text:$},void 0,!1,void 0,this)},void 0,!1,void 0,this);case 2:return h(B0,{bold:!0,color:Y.colors.primary,children:h(R1,{text:$},void 0,!1,void 0,this)},void 0,!1,void 0,this);case 3:return h(B0,{bold:!0,color:Y.colors.text.primary,children:h(R1,{text:$},void 0,!1,void 0,this)},void 0,!1,void 0,this);case 4:return h(B0,{italic:!0,color:Y.colors.text.muted,children:h(R1,{text:$},void 0,!1,void 0,this)},void 0,!1,void 0,this);default:return h(B0,{children:h(R1,{text:$},void 0,!1,void 0,this)},void 0,!1,void 0,this)}}),f3=W$.memo(({terminalWidth:$})=>{let Q=b0(),Y=Math.max(0,Math.min($-4,80));return h(B0,{dimColor:!0,color:Q.colors.text.muted,children:"─".repeat(Y)},void 0,!1,void 0,this)}),D3=W$.memo(({content:$})=>{return h(B0,{wrap:"wrap",children:h(R1,{text:$},void 0,!1,void 0,this)},void 0,!1,void 0,this)}),V3=W$.memo(({content:$})=>{let Q=b0();return h(q0,{flexDirection:"row",gap:1,children:[h(B0,{color:Q.colors.info,children:" "},void 0,!1,void 0,this),h(B0,{color:Q.colors.text.muted,italic:!0,children:$},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}),j3=W$.memo(({detail:$,terminalWidth:Q})=>{let Y=b0(),J=50,Z=$.split(`
140
- `);while(Z.length>0&&Z[0].trim()==="")Z.shift();while(Z.length>0&&Z[Z.length-1].trim()==="")Z.pop();let X=Z.length>50,U=X?Z.slice(0,50):Z,G=U.join(`
141
- `),q=G.includes("<<<DIFF>>>"),K=G.includes("```");if(q){let W=G.match(/<<<DIFF>>>\s*({[\s\S]*?})\s*<<<\/DIFF>>>/);if(W)try{let O=JSON.parse(W[1]);return h(q0,{flexDirection:"column",children:[h(N6,{patch:O.patch,startLine:O.startLine,matchLine:O.matchLine,terminalWidth:Q},void 0,!1,void 0,this),X&&h(q0,{marginTop:1,children:h(B0,{dimColor:!0,color:Y.colors.text.muted,children:["... 省略 ",Z.length-50," 行 ..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}catch{}}if(K){let W=G.match(/```(\w+)?\s*\n([\s\S]*?)\n```/);if(W){let O=W[1]||"text",B=W[2];return h(q0,{flexDirection:"column",children:[h(YQ,{content:B,language:O,showLineNumbers:!1,terminalWidth:Q},void 0,!1,void 0,this),X&&h(q0,{marginTop:1,children:h(B0,{dimColor:!0,color:Y.colors.text.muted,children:["... 省略 ",Z.length-50," 行 ..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}}return h(q0,{flexDirection:"column",children:[U.map((W,O)=>h(B0,{color:Y.colors.text.primary,children:W},O,!1,void 0,this)),X&&h(q0,{marginTop:1,children:h(B0,{dimColor:!0,color:Y.colors.text.muted,children:["... 省略 ",Z.length-50," 行 ..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});function E3($,Q,Y,J=80){if(!Y||Q===void 0||Q<=0)return{content:$,isTruncated:!1,hiddenLines:0};let X=Math.max(1,Q-8),U=Math.max(40,J*0.8),G=X*U;if($.length<=G)return{content:$,isTruncated:!1,hiddenLines:0};let q=Math.floor(G*0.9),K=$.length-q,W=K,O=$.indexOf(`
142
- `,K);if(O!==-1&&O-K<U)W=O+1;let B=$.slice(W),b=($.slice(0,W).match(/\n/g)||[]).length+1;return{content:B,isTruncated:!0,hiddenLines:b}}var s1=W$.memo(({content:$,role:Q,terminalWidth:Y,metadata:J,isPending:Z=!1,availableTerminalHeight:X,hidePrefix:U=!1,noMargin:G=!1,renderPlainTextOnly:q=!1,streamingLines:K,streamingHiddenLines:W,messageId:O,blocksOverride:B,currentLineOverride:_,streamingMode:b="text",renderCodeBlocksAsPlainText:z=!1})=>{let H=b0(),F=B!==void 0,A=H$(()=>T3(Q,H.colors,J),[Q,H.colors,J]),{color:v,prefix:C}=A,N=C.length+1,P=H$(()=>{if(!J||typeof J!=="object")return null;if(!("subtaskRef"in J))return null;let k=J.subtaskRef;if(!k||typeof k!=="object")return null;return k},[J]),w=Q==="tool"&&J?.phase==="start",R=!G&&!w,T=H$(()=>{if(!q)return[];return $.split(/\r?\n/)},[$,q]);if(!F&&Z){let k=K??$.split(/\r?\n/),u=W??0,j=!1,m=!1,f=!1;if(b!=="text")j=b==="code",m=b==="diff",f=b==="table";return h(q0,{flexDirection:"column",marginBottom:R?1:0,flexShrink:0,children:[u>0&&h(q0,{flexDirection:"row",flexShrink:0,children:[h(q0,{width:N,flexShrink:0},void 0,!1,void 0,this),h(B0,{color:H.colors.text.muted,dimColor:!0,children:["^ ",u," lines above (streaming...)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),k.map((n,_0)=>{if(b==="text"){if(n.match(t1.codeBlock))j=!j;else if(n.match(t1.diffStart))m=!0;else if(n.match(t1.diffEnd))m=!1;else if(n.match(t1.table))f=!0;else if(f&&!n.match(t1.table))f=!1}let N0=b==="text"&&!j&&!m&&!f,m0=N0?n.match(t1.ulItem):null,D0=N0?n.match(t1.olItem):null,w0=m0??D0;return h(q0,{flexDirection:"row",flexShrink:0,children:[_0===0&&!U?h(q0,{marginRight:1,flexShrink:0,children:h(B0,{color:v,bold:!0,children:C},void 0,!1,void 0,this)},void 0,!1,void 0,this):h(q0,{width:N,flexShrink:0},void 0,!1,void 0,this),h(q0,{flexGrow:1,flexShrink:0,children:w0?h(H6,{type:m0?"ul":"ol",marker:w0[2],itemText:w0[3],leadingWhitespace:w0[1]},void 0,!1,void 0,this):h(B0,{wrap:"wrap",children:n===""?" ":n},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},_0,!0,void 0,this)})]},void 0,!0,void 0,this)}if(!F&&q)return h(q0,{flexDirection:"column",marginBottom:R?1:0,flexShrink:0,children:T.map((k,u)=>h(q0,{flexDirection:"row",flexShrink:0,children:[u===0&&!U?h(q0,{marginRight:1,flexShrink:0,children:h(B0,{color:v,bold:!0,children:C},void 0,!1,void 0,this)},void 0,!1,void 0,this):h(q0,{width:N,flexShrink:0},void 0,!1,void 0,this),h(q0,{flexGrow:1,flexShrink:0,children:h(B0,{wrap:"wrap",children:k===""?" ":k},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},u,!0,void 0,this))},void 0,!1,void 0,this);let y=h9(null);B6(()=>{y.current=null},[O]);let S=H$(()=>{if(F)return null;if(!O)return null;return g9(O)},[O,F]);B6(()=>{if(F)return;if(!S||!O)return;y.current={messageId:O,blocks:S}},[S,O,F]),B6(()=>{if(F)return;if(!S||!O)return;m9(O)},[S,O,F]);let E=H$(()=>F?{content:$,isTruncated:!1,hiddenLines:0}:E3($,X,Z,Y),[$,X,Z,Y,F]),{content:c,isTruncated:Q0,hiddenLines:d}=E;if(!F&&Q==="tool"&&J&&"detail"in J){let k=J;if(k.detail)return h(q0,{flexDirection:"column",marginBottom:G?0:1,children:[h(q0,{flexDirection:"row",children:[h(q0,{marginRight:1,children:h(B0,{color:v,bold:!0,children:C},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(B0,{color:v,children:$},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h(q0,{marginLeft:C.length+1,children:h(j3,{detail:k.detail,terminalWidth:Y-(C.length+1)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}let{completedContent:I,currentLine:L}=H$(()=>{if(F)return{completedContent:"",currentLine:_??""};if(!Z)return{completedContent:c,currentLine:""};let k=c.lastIndexOf(`
143
- `);if(k===-1)return{completedContent:"",currentLine:c};return{completedContent:c.slice(0,k+1),currentLine:c.slice(k+1)}},[c,Z,F,_]),M=h9({content:"",blocks:[]}),V=H$(()=>{if(F)return B??[];if(S)return S;if(y.current&&y.current.messageId===O)return y.current.blocks;let k=M.current;if(!Z||!I.startsWith(k.content)){let f=w6(I);return M.current={content:I,blocks:f},f}if(I===k.content)return k.blocks;let u=I.slice(k.content.length),j=w6(u),m=[...k.blocks,...j];return M.current={content:I,blocks:m},m},[I,Z,F,B]);return h(q0,{flexDirection:"column",marginBottom:R?1:0,flexShrink:0,children:[Q0&&h(q0,{flexDirection:"row",flexShrink:0,children:[h(q0,{width:N,flexShrink:0},void 0,!1,void 0,this),h(B0,{color:H.colors.text.muted,dimColor:!0,children:["^ ",d," lines above (streaming...)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),V.map((k,u)=>{if(k.type==="empty")return h(q0,{height:1,flexShrink:0},u,!1,void 0,this);return h(q0,{flexDirection:"row",flexShrink:0,children:[u===0&&!U&&h(q0,{marginRight:1,flexShrink:0,children:h(B0,{color:v,bold:!0,children:C},void 0,!1,void 0,this)},void 0,!1,void 0,this),(u>0||U)&&h(q0,{width:N,flexShrink:0},void 0,!1,void 0,this),h(q0,{flexGrow:1,flexShrink:0,children:k.type==="code"?z?h(B0,{wrap:"wrap",children:k.content},void 0,!1,void 0,this):h(k3,{content:k.content,language:k.language,terminalWidth:Y-N,isPending:Z,availableHeight:X},void 0,!1,void 0,this):k.type==="table"&&k.tableData?h(E9,{headers:k.tableData.headers,rows:k.tableData.rows,terminalWidth:Y-N},void 0,!1,void 0,this):k.type==="heading"?h(S3,{content:k.content,level:k.level||1},void 0,!1,void 0,this):k.type==="list"?h(H6,{type:k.listType||"ul",marker:k.marker||"-",itemText:k.content,leadingWhitespace:" ".repeat(k.indentation||0)},void 0,!1,void 0,this):k.type==="hr"?h(f3,{terminalWidth:Y-N},void 0,!1,void 0,this):k.type==="diff"&&k.diffData?h(N6,{patch:k.diffData.patch,startLine:k.diffData.startLine,matchLine:k.diffData.matchLine,terminalWidth:Y-N},void 0,!1,void 0,this):k.type==="command-message"?h(V3,{content:k.content},void 0,!1,void 0,this):k.type==="blockquote"&&k.blockquoteLines?h(M9,{lines:k.blockquoteLines,level:k.blockquoteLevel||1},void 0,!1,void 0,this):h(D3,{content:k.content},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},u,!0,void 0,this)}),L&&h(q0,{flexDirection:"row",flexShrink:0,children:[V.length===0&&!U?h(q0,{marginRight:1,flexShrink:0,children:h(B0,{color:v,bold:!0,children:C},void 0,!1,void 0,this)},void 0,!1,void 0,this):h(q0,{width:N,flexShrink:0},void 0,!1,void 0,this),h(q0,{flexGrow:1,flexShrink:0,children:h(B0,{wrap:"wrap",children:L},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),P&&h(q0,{flexDirection:"row",flexShrink:0,children:[h(q0,{width:N,flexShrink:0},void 0,!1,void 0,this),h(q0,{flexDirection:"column",flexGrow:1,flexShrink:0,children:[h(B0,{color:H.colors.text.muted,children:["Subtask"," ",typeof P.agentType==="string"?`@${P.agentType}`:"",typeof P.status==="string"?` · ${P.status}`:""]},void 0,!0,void 0,this),typeof P.summary==="string"&&P.summary.trim()!==""&&h(B0,{wrap:"wrap",children:P.summary},void 0,!1,void 0,this),typeof P.childSessionId==="string"&&h(B0,{color:H.colors.text.muted,children:["Session ",P.childSessionId]},void 0,!0,void 0,this),typeof P.resumedFrom==="string"&&h(B0,{color:H.colors.text.muted,children:["Resumed from ",P.resumedFrom,typeof P.resumeDepth==="number"?` · depth ${P.resumeDepth}`:""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},($,Q)=>{return $.content===Q.content&&$.role===Q.role&&$.terminalWidth===Q.terminalWidth&&$.isPending===Q.isPending&&$.availableTerminalHeight===Q.availableTerminalHeight&&$.hidePrefix===Q.hidePrefix&&$.noMargin===Q.noMargin&&$.renderPlainTextOnly===Q.renderPlainTextOnly&&$.streamingHiddenLines===Q.streamingHiddenLines&&$.streamingLines===Q.streamingLines&&$.messageId===Q.messageId&&$.metadata===Q.metadata&&$.blocksOverride===Q.blocksOverride&&$.currentLineOverride===Q.currentLineOverride&&$.streamingMode===Q.streamingMode&&$.renderCodeBlocksAsPlainText===Q.renderCodeBlocksAsPlainText});import{jsxDEV as I0,Fragment as u3}from"react/jsx-dev-runtime";var p3=b6.memo(({label:$,isSelected:Q})=>I0(v1,{color:Q?"yellow":void 0,children:$},void 0,!1,void 0,this)),c3=b6.memo(({details:$,headerColor:Q,isPlanModeExit:Y,isPlanModeEnter:J,terminalWidth:Z})=>I0(u3,{children:[I0(W1,{marginBottom:1,children:I0(v1,{children:$.message},void 0,!1,void 0,this)},void 0,!1,void 0,this),$.planContent&&I0(W1,{flexDirection:"column",marginBottom:1,borderStyle:"single",borderColor:Q,padding:1,children:[I0(v1,{bold:!0,color:Q,children:"实施方案"},void 0,!1,void 0,this),I0(W1,{marginTop:1,children:I0(s1,{content:$.planContent,role:"assistant",terminalWidth:Z-4},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!$.planContent&&$.details&&I0(W1,{flexDirection:"column",marginBottom:1,children:I0(s1,{content:$.details,role:"assistant",terminalWidth:Z},void 0,!1,void 0,this)},void 0,!1,void 0,this),$.risks&&$.risks.length>0&&I0(W1,{flexDirection:"column",marginBottom:1,children:[I0(v1,{color:"red",bold:!0,children:"风险提示:"},void 0,!1,void 0,this),$.risks.map((X,U)=>I0(W1,{marginLeft:2,children:I0(v1,{color:"red",children:["• ",X]},void 0,!0,void 0,this)},U,!1,void 0,this))]},void 0,!0,void 0,this),$.affectedFiles&&$.affectedFiles.length>0&&I0(W1,{flexDirection:"column",marginBottom:1,children:[I0(v1,{color:"yellow",children:"影响的文件:"},void 0,!1,void 0,this),$.affectedFiles.slice(0,3).map((X,U)=>I0(W1,{marginLeft:2,children:I0(v1,{children:["• ",X]},void 0,!0,void 0,this)},U,!1,void 0,this)),$.affectedFiles.length>3&&I0(W1,{marginLeft:2,children:I0(v1,{color:"gray",children:["...还有 ",$.affectedFiles.length-3," 个文件"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this));function x3($,Q,Y,J){return`使用 ↑↓ 选择,回车确认 · ${Q||Y||J?"Y/N":$?"Y/S/N":"Y/S/P/N"} 快捷键 · Esc 取消`}var c9=b6.memo(({details:$,onResponse:Q})=>{let{stdout:Y}=g3(),J=Y.columns||80,X=s0()==="confirmation-prompt",U=k0(!1),G=$.type==="exitPlanMode",q=$.type==="enterPlanMode",K=$.type==="maxTurnsExceeded",W=$.type==="mcpSampling";h3((_,b)=>{if(b.ctrl&&_==="c"||b.meta&&_==="c"){U();return}if(b.escape){Q({approved:!1,reason:"用户取消"});return}let z=_.toLowerCase();if(G){if(z==="y"){Q({approved:!0,targetMode:"autoEdit"});return}if(z==="s"){Q({approved:!0,targetMode:"default"});return}if(z==="n"){Q({approved:!1,reason:"方案需要改进"});return}}else if(q){if(z==="y"){Q({approved:!0});return}if(z==="n"){Q({approved:!1,reason:"用户拒绝进入 Plan 模式"});return}}else if(K){if(z==="y"){Q({approved:!0});return}if(z==="n"){Q({approved:!1,reason:"用户选择停止"});return}}else if(W){if(z==="y"){Q({approved:!0,scope:"once"});return}if(z==="n"){Q({approved:!1,reason:"用户拒绝 MCP Sampling"});return}}else{if(z==="y"){Q({approved:!0,scope:"once"});return}if(z==="s"){Q({approved:!0,scope:"session"});return}if(z==="p"){Q({approved:!0,scope:"project"});return}if(z==="n"){Q({approved:!1,reason:"用户拒绝"});return}}},{isActive:X});let O=p9(()=>{if(G)return[{key:"approve-auto",label:"[Y] 批准,自动执行",value:{approved:!0,targetMode:"autoEdit"}},{key:"approve-default",label:"[S] 批准,逐步确认",value:{approved:!0,targetMode:"default"}},{key:"reject",label:"[N] 继续优化方案",value:{approved:!1,reason:"方案需要改进"}}];if(q)return[{key:"approve",label:"[Y] 进入规划模式",value:{approved:!0}},{key:"reject",label:"[N] 直接执行",value:{approved:!1,reason:"用户拒绝进入 Plan 模式"}}];if(K)return[{key:"continue",label:"[Y] 继续执行",value:{approved:!0}},{key:"stop",label:"[N] 停止",value:{approved:!1,reason:"用户选择停止"}}];if(W)return[{key:"approve-once",label:"[Y] 允许本次 Sampling",value:{approved:!0,scope:"once"}},{key:"reject",label:"[N] 拒绝",value:{approved:!1,reason:"用户拒绝 MCP Sampling"}}];return[{key:"approve-once",label:"[Y] 允许(仅本次)",value:{approved:!0,scope:"once"}},{key:"approve-session",label:"[S] 允许(本次会话)",value:{approved:!0,scope:"session"}},{key:"approve-project",label:"[P] 允许并记住(本项目)",value:{approved:!0,scope:"project"}},{key:"reject",label:"[N] 拒绝",value:{approved:!1,reason:"用户拒绝"}}]},[G,q,K,W]),B=p9(()=>{if(G)return{color:"cyan",title:"方案审核"};if(q)return{color:"magenta",title:"进入规划模式"};if(K)return{color:"yellow",title:"已达最大轮次"};return{color:"yellow",title:$.title||"操作确认"}},[G,q,K,$.title]);return I0(W1,{flexDirection:"column",borderStyle:"round",borderColor:X?B.color:"gray",padding:1,children:[I0(W1,{marginBottom:1,children:I0(v1,{bold:!0,color:B.color,children:B.title},void 0,!1,void 0,this)},void 0,!1,void 0,this),I0(c3,{details:$,headerColor:B.color,isPlanModeExit:G,isPlanModeEnter:q,terminalWidth:J},void 0,!1,void 0,this),I0(W1,{flexDirection:"column",children:[I0(v1,{color:"gray",children:x3(G,q,K,W)},void 0,!1,void 0,this),I0(m3,{items:O,isFocused:X,itemComponent:p3,onSelect:(_)=>{Q(_.value)}},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)});import{Box as L0,Text as Y0,useInput as d3}from"ink";import x9 from"ink-text-input";import{useState as E1}from"react";import{jsxDEV as g}from"react/jsx-dev-runtime";var q8=[{action:"add",description:"Add a new hook"},{action:"status",description:"Show hooks status"},{action:"list",description:"List all configured hooks"},{action:"trust",description:"Trust the current project hook digest"},{action:"revoke",description:"Revoke project hook trust"}],ZQ=[{location:"local",name:"Project settings (local)",description:"Saved in .blade/settings.local.json"},{location:"project",name:"Project settings",description:"Checked in at .blade/settings.json"},{location:"user",name:"User settings",description:"Saved in at ~/.blade/settings.json"}],XQ=[{event:"PreToolUse",description:"Before tool execution"},{event:"PostToolUse",description:"After tool execution"},{event:"PostToolUseFailure",description:"After tool execution fails"},{event:"PermissionRequest",description:"When permission is requested"},{event:"UserPromptSubmit",description:"Before processing user prompt"},{event:"Stop",description:"When Claude stops responding"},{event:"SubagentStop",description:"When subagent stops"},{event:"SessionStart",description:"When session starts"},{event:"SessionEnd",description:"When session ends"},{event:"Notification",description:"When notification is sent"},{event:"Compaction",description:"Before context compaction"}],l3=[`jq -r '.tool_input.file_path | select(endswith(".go"))' | xargs -r gofmt -w`,`jq -r '"\\(.tool_input.command) - \\(.tool_input.description // "No description")"' >> ~/.blade/bash-command-log.txt`,"/usr/local/bin/security_check.sh","python3 ~/hooks/validate_changes.py"],u9=({onClose:$,onSave:Q})=>{let Y=l0.getTheme(),[J,Z]=E1("action"),[X,U]=E1(0),[G,q]=E1(0),[K,W]=E1(0),[O,B]=E1(""),[_,b]=E1(""),[z,H]=E1(null),[F,A]=E1(!1),[v,C]=E1(null),N=q8[X],P=XQ[G],w=ZQ[K],R=()=>{if(v){C(null);return}switch(J){case"action":$();break;case"event":Z("action");break;case"matcher":Z("event");break;case"command":Z("matcher");break;case"location":Z("command");break;case"confirm":Z("location");break}};d3((L,M)=>{if(M.escape){R();return}if(J==="action"){if(M.upArrow)U((V)=>V>0?V-1:q8.length-1);else if(M.downArrow)U((V)=>V<q8.length-1?V+1:0);else if(M.return)T()}else if(J==="event"){if(M.upArrow)q((V)=>V>0?V-1:XQ.length-1);else if(M.downArrow)q((V)=>V<XQ.length-1?V+1:0);else if(M.return)Z("matcher")}else if(J==="location"){if(M.upArrow)W((V)=>V>0?V-1:ZQ.length-1);else if(M.downArrow)W((V)=>V<ZQ.length-1?V+1:0);else if(M.return)Z("confirm")}else if(J==="confirm"){if(M.return)I()}});let T=()=>{let L=q8[X].action;if(L==="add")Z("event");else if(L==="status")y();else if(L==="list")c();else if(L==="trust")S();else if(L==="revoke")E()},y=async()=>{let L=F1.getInstance(),M=L.isEnabled(A0()),V=L.getConfig(A0()),k=await L.getTrustStatus(A0()),u={};for(let m of Object.values(R6)){let f=V[m];if(f&&Array.isArray(f)){let n=f.reduce((_0,N0)=>_0+(N0.hooks?.length||0),0);if(n>0)u[m]=n}}let j=[`Status: ${M?"Enabled":"Disabled"}`,`Trust: ${k.state}`,`Digest: ${k.currentDigest??"none"}`,""];if(Object.keys(u).length>0){j.push("Configured hooks:");for(let[m,f]of Object.entries(u))j.push(` ${m}: ${f} hook(s)`)}else j.push("No hooks configured");C(j.join(`
144
- `))},S=async()=>{try{let L=await F1.getInstance().trustProject(A0());C(`Trust: ${L.state}
145
- Digest: ${L.currentDigest??"none"}`)}catch(L){H(L instanceof Error?L.message:"Failed to trust hooks")}},E=async()=>{try{let L=await F1.getInstance().revokeProjectTrust(A0());C(`Trust: ${L.state}`)}catch(L){H(L instanceof Error?L.message:"Failed to revoke hook trust")}},c=()=>{let M=F1.getInstance().getConfig(A0()),V=[],k=!1;for(let u of Object.values(R6)){let j=M[u];if(!j||!Array.isArray(j)||j.length===0)continue;k=!0,V.push(`${u}:`);for(let m of j){let f=m.matcher,n="all";if(f?.tools)n=`tools: ${Array.isArray(f.tools)?f.tools.join(", "):f.tools}`;V.push(` [${n}]`);for(let _0 of m.hooks||[])if(_0.type==="command")V.push(` -> ${_0.command}`)}V.push("")}if(!k)V.push("No hooks configured"),V.push(""),V.push("Configure hooks in .blade/settings.local.json");C(V.join(`
146
- `))},Q0=()=>{Z("command")},d=()=>{if(!_.trim()){H("Command cannot be empty");return}H(null),Z("location")},I=async()=>{A(!0),H(null);try{let L=F1.getInstance(),M=await import("node:fs/promises"),V=await import("node:path"),k=await import("node:os"),u={matcher:O.trim()?{tools:O.trim()}:{},hooks:[{type:"command",command:_.trim()}]},j;switch(w.location){case"local":j=V.join(A0(),".blade","settings.local.json");break;case"project":j=V.join(A0(),".blade","settings.json");break;case"user":j=V.join(k.homedir(),".blade","settings.json");break}await M.mkdir(V.dirname(j),{recursive:!0});let m={};try{let N0=await M.readFile(j,"utf-8");m=JSON.parse(N0)}catch{}let f=m.hooks||{},n=f[P.event]||[],_0={...f,enabled:!0,[P.event]:[...n,u]};if(m.hooks=_0,await M.writeFile(j,JSON.stringify(m,null,2),"utf-8"),await L.reloadConfig(),Q)Q({event:P.event,matcher:O.trim(),command:_.trim()});$()}catch(L){H(`Failed to save hook: ${L instanceof Error?L.message:"Unknown error"}`),A(!1)}};return g(L0,{flexDirection:"column",padding:1,children:[g(L0,{marginBottom:1,children:g(Y0,{bold:!0,color:Y.colors.success,children:"Hooks Manager"},void 0,!1,void 0,this)},void 0,!1,void 0,this),g(L0,{marginBottom:1,children:g(Y0,{color:Y.colors.warning,children:"[WARN] Configured hooks run only after this exact project digest is trusted. Function hooks registered by application code are exempt."},void 0,!1,void 0,this)},void 0,!1,void 0,this),v&&g(L0,{flexDirection:"column",marginBottom:1,children:[g(Y0,{children:v},void 0,!1,void 0,this),g(L0,{marginTop:1,children:g(Y0,{color:Y.colors.muted,children:"Esc to go back"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),J==="action"&&!v&&g(L0,{flexDirection:"column",children:[g(L0,{flexDirection:"column",marginTop:1,children:q8.map((L,M)=>g(L0,{children:[g(Y0,{color:M===X?Y.colors.primary:void 0,bold:M===X,children:[M===X?"> ":" ",L.action]},void 0,!0,void 0,this),g(Y0,{color:Y.colors.muted,children:[" - ",L.description]},void 0,!0,void 0,this)]},L.action,!0,void 0,this))},void 0,!1,void 0,this),g(L0,{marginTop:1,children:g(Y0,{color:Y.colors.muted,children:"Up/Down to select · Enter to continue · Esc to close"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),J==="event"&&g(L0,{flexDirection:"column",children:[g(Y0,{bold:!0,children:"Select Event:"},void 0,!1,void 0,this),g(L0,{flexDirection:"column",marginTop:1,children:XQ.map((L,M)=>g(L0,{children:[g(Y0,{color:M===G?Y.colors.primary:void 0,bold:M===G,children:[M===G?"> ":" ",L.event]},void 0,!0,void 0,this),g(Y0,{color:Y.colors.muted,children:[" - ",L.description]},void 0,!0,void 0,this)]},L.event,!0,void 0,this))},void 0,!1,void 0,this),g(L0,{marginTop:1,children:g(Y0,{color:Y.colors.muted,children:"Up/Down to select · Enter to continue · Esc to go back"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),J!=="event"&&g(L0,{marginBottom:1,children:g(Y0,{children:["Event:"," ",g(Y0,{bold:!0,color:Y.colors.primary,children:P.event},void 0,!1,void 0,this),g(Y0,{color:Y.colors.muted,children:[" - ",P.description]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),(J==="matcher"||J==="command"||J==="confirm")&&g(L0,{flexDirection:"column",marginBottom:1,children:[g(Y0,{color:Y.colors.muted,children:"Input to command is JSON of tool call arguments."},void 0,!1,void 0,this),g(Y0,{color:Y.colors.muted,children:"Exit code 0 - stdout/stderr not shown"},void 0,!1,void 0,this),g(Y0,{color:Y.colors.muted,children:"Exit code 2 - show stderr to model and block tool call"},void 0,!1,void 0,this),g(Y0,{color:Y.colors.muted,children:"Other exit codes - show stderr to user only but continue with tool call"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),J==="matcher"&&g(L0,{flexDirection:"column",children:[g(L0,{children:[g(Y0,{bold:!0,children:"Matcher: "},void 0,!1,void 0,this),g(x9,{value:O,onChange:B,onSubmit:Q0,placeholder:"e.g., Read, Bash, Edit|Write (empty = all tools)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),g(L0,{marginTop:1,children:g(Y0,{color:Y.colors.muted,children:"Tool name pattern (supports | for multiple). Leave empty to match all."},void 0,!1,void 0,this)},void 0,!1,void 0,this),g(L0,{marginTop:1,children:g(Y0,{color:Y.colors.muted,children:"Enter to continue · Esc to go back"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(J==="command"||J==="confirm")&&g(L0,{marginBottom:1,children:g(Y0,{children:["Matcher: ",g(Y0,{bold:!0,children:O||"(all tools)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),J==="command"&&g(L0,{flexDirection:"column",children:[g(L0,{children:g(Y0,{bold:!0,children:"Command: "},void 0,!1,void 0,this)},void 0,!1,void 0,this),g(L0,{borderStyle:"single",borderColor:Y.colors.border.light,paddingX:1,marginTop:1,children:g(x9,{value:_,onChange:b,onSubmit:d,placeholder:"Enter shell command..."},void 0,!1,void 0,this)},void 0,!1,void 0,this),g(L0,{flexDirection:"column",marginTop:1,children:[g(Y0,{bold:!0,children:"Examples:"},void 0,!1,void 0,this),l3.map((L,M)=>g(Y0,{color:Y.colors.muted,children:["• ",L]},M,!0,void 0,this))]},void 0,!0,void 0,this),g(L0,{marginTop:1,children:g(Y0,{color:Y.colors.muted,children:"Enter to continue · Esc to go back"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),J==="location"&&g(L0,{flexDirection:"column",children:[g(L0,{flexDirection:"column",borderStyle:"round",borderColor:Y.colors.border.light,paddingX:2,paddingY:1,marginBottom:1,children:[g(Y0,{bold:!0,color:Y.colors.primary,children:"Save hook configuration"},void 0,!1,void 0,this),g(Y0,{children:" "},void 0,!1,void 0,this),g(Y0,{children:[" ","Event: ",P.event," - ",P.description]},void 0,!0,void 0,this),g(Y0,{children:[" Matcher: ",O||"(all)"]},void 0,!0,void 0,this),g(Y0,{children:[" Command: ",_]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),g(Y0,{bold:!0,children:"Where should this hook be saved?"},void 0,!1,void 0,this),g(L0,{flexDirection:"column",marginTop:1,children:ZQ.map((L,M)=>g(L0,{children:[g(Y0,{color:M===K?Y.colors.primary:void 0,bold:M===K,children:[M===K?"> ":" ",M+1,". ",L.name]},void 0,!0,void 0,this),g(Y0,{color:Y.colors.muted,children:[" ",L.description]},void 0,!0,void 0,this)]},L.location,!0,void 0,this))},void 0,!1,void 0,this),g(L0,{marginTop:1,children:g(Y0,{color:Y.colors.muted,children:"Enter to confirm · Esc to go back"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),J==="confirm"&&g(L0,{flexDirection:"column",children:[g(L0,{flexDirection:"column",borderStyle:"round",borderColor:Y.colors.success,paddingX:2,paddingY:1,children:[g(Y0,{bold:!0,children:["Saving hook to ",w.description,"..."]},void 0,!0,void 0,this),g(Y0,{children:" "},void 0,!1,void 0,this),g(Y0,{children:["Event: ",P.event]},void 0,!0,void 0,this),g(Y0,{children:["Matcher: ",O||"(all tools)"]},void 0,!0,void 0,this),g(Y0,{children:["Command: ",_]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),g(L0,{marginTop:1,children:g(Y0,{color:Y.colors.muted,children:F?"Saving...":"Enter to confirm · Esc to go back"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),z&&g(L0,{marginTop:1,children:g(Y0,{color:Y.colors.error,children:z},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{useMemoizedFn as e9}from"ahooks";import{Box as JZ,Text as YZ}from"ink";import ZZ from"react";import{useMemoizedFn as n3}from"ahooks";import L$ from"chalk";import{Text as t3,useInput as s3}from"ink";import{useEffect as M6,useRef as I6}from"react";var h1={TIMEOUT_MS:100,RAPID_INPUT_THRESHOLD_MS:150,LARGE_INPUT_THRESHOLD:300,MEDIUM_SIZE_MULTI_CHUNK_THRESHOLD:200};import{execSync as u$}from"node:child_process";import{existsSync as r3,readFileSync as P6}from"node:fs";import{basename as d9,isAbsolute as a3}from"node:path";function l9($){try{let Q=Buffer.from($,"base64");if(Q.length<4)return"image/png";if(Q[0]===137&&Q[1]===80&&Q[2]===78&&Q[3]===71)return"image/png";if(Q[0]===255&&Q[1]===216&&Q[2]===255)return"image/jpeg";if(Q[0]===71&&Q[1]===73&&Q[2]===70)return"image/gif";if(Q[0]===82&&Q[1]===73&&Q[2]===70&&Q[3]===70){if(Q.length>=12&&Q[8]===87&&Q[9]===69&&Q[10]===66&&Q[11]===80)return"image/webp"}return"image/png"}catch{return"image/png"}}function r9(){let $=process.platform,Q={darwin:"/tmp/blade_cli_latest_screenshot.png",linux:"/tmp/blade_cli_latest_screenshot.png",win32:process.env.TEMP?`${process.env.TEMP}\\blade_cli_latest_screenshot.png`:"C:\\Temp\\blade_cli_latest_screenshot.png"},Y={darwin:{checkImage:"osascript -e 'the clipboard as «class PNGf»'",saveImage:(J)=>`osascript -e 'set png_data to (the clipboard as «class PNGf»)' -e 'set fp to open for access POSIX file "${J}" with write permission' -e 'write png_data to fp' -e 'close access fp'`,getPath:"osascript -e 'get POSIX path of (the clipboard as «class furl»)'",deleteFile:(J)=>`rm -f "${J}"`},linux:{checkImage:'xclip -selection clipboard -t TARGETS -o | grep -E "image/(png|jpeg|jpg|gif|webp)"',saveImage:(J)=>`xclip -selection clipboard -t image/png -o > "${J}" || wl-paste --type image/png > "${J}"`,getPath:"xclip -selection clipboard -t text/plain -o",deleteFile:(J)=>`rm -f "${J}"`},win32:{checkImage:'powershell -Command "(Get-Clipboard -Format Image) -ne $null"',saveImage:(J)=>`powershell -Command "$img = Get-Clipboard -Format Image; if ($img) { $img.Save('${J.replace(/\\/g,"\\\\")}', [System.Drawing.Imaging.ImageFormat]::Png) }"`,getPath:'powershell -Command "Get-Clipboard"',deleteFile:(J)=>`del /f "${J}"`}};return{commands:Y[$]||Y.linux,screenshotPath:Q[$]||Q.linux}}function o3(){let{commands:$}=r9();try{return u$($.getPath,{encoding:"utf-8"}).trim()}catch(Q){return console.error("Failed to get clipboard path:",Q),null}}function a9($){if($.startsWith('"')&&$.endsWith('"')||$.startsWith("'")&&$.endsWith("'"))return $.slice(1,-1);return $}function o9($){if(process.platform==="win32")return $;let Q="__DOUBLE_BACKSLASH__";return $.replace(/\\\\/g,Q).replace(/\\(.)/g,"$1").replace(new RegExp(Q,"g"),"\\")}function y6($){let Q=a9($.trim()),Y=o9(Q);return/\.(png|jpe?g|gif|webp)$/i.test(Y)}function i3($){let Q=a9($.trim()),Y=o9(Q);if(y6(Y))return Y;return null}async function i9($){let Q=i3($);if(!Q)return null;let Y;try{if(a3(Q))Y=P6(Q);else{let U=o3();if(U&&Q===d9(U))Y=P6(U);else return null}}catch(U){return console.error("Failed to read image file:",U),null}let J=Y.toString("base64"),Z=l9(J),X=d9(Q);return{path:Q,base64:J,mediaType:Z,filename:X}}async function n9(){let $=process.platform,Q={darwin:"pbpaste",linux:"xclip -selection clipboard -o || wl-paste",win32:'powershell -Command "Get-Clipboard"'},Y=Q[$]||Q.linux;try{return u$(Y,{encoding:"utf-8"})||null}catch{return null}}async function t9(){let{commands:$,screenshotPath:Q}=r9();try{if(u$($.checkImage,{stdio:"ignore"}),u$($.saveImage(Q),{stdio:"ignore"}),!r3(Q))return null;let J=P6(Q).toString("base64"),Z=l9(J);return u$($.deleteFile(Q),{stdio:"ignore"}),{base64:J,mediaType:Z}}catch(Y){try{u$($.deleteFile(Q),{stdio:"ignore"})}catch{}return null}}import{jsxDEV as QZ}from"react/jsx-dev-runtime";var e3=/\r\n/g,$Z=/\r/g;function B$($){if(!$.includes("\r"))return $;return $.replace(e3,`
147
- `).replace($Z,`
148
- `)}function w$($,Q,Y){let J=Math.max(0,Math.min(Y,Q.length)),Z=Q.slice(0,J),X=Q.slice(J);return{newValue:Z+$+X,newCursorPosition:J+$.length}}function s9({value:$,placeholder:Q="",focus:Y=!0,onChange:J,cursorPosition:Z,onChangeCursorPosition:X,onPaste:U,onImagePaste:G,disabledKeys:q=[]}){let K=I6({chunks:[],timeoutId:null,firstInputTime:null,lastInputTime:null,totalLength:0}),W=I6($),O=I6(Z);M6(()=>{W.current=$,O.current=Z},[$,Z]),M6(()=>{return()=>{if(K.current.timeoutId)clearTimeout(K.current.timeoutId)}},[]),M6(()=>{if(Z>$.length)X($.length)},[$,Z,X]);let B=n3(()=>{let H=K.current;if(H.timeoutId)clearTimeout(H.timeoutId);let F=setTimeout(async()=>{let A=K.current.chunks,v=K.current.totalLength;if(A.length===0)return;let C=B$(A.join(""));K.current={chunks:[],timeoutId:null,firstInputTime:null,lastInputTime:null,totalLength:0};let N=W.current,P=O.current;if(G&&y6(C))try{let E=await i9(C);if(E){let c=await G(E.base64,E.mediaType,E.filename);if(c?.prompt){let Q0=B$(c.prompt),{newValue:d,newCursorPosition:I}=w$(Q0,N,P);J(d),X(I)}return}}catch(E){console.error("Failed to process image path:",E)}let w=C.includes(`
149
- `),R=v>h1.MEDIUM_SIZE_MULTI_CHUNK_THRESHOLD&&A.length>3;if((v>h1.LARGE_INPUT_THRESHOLD||w||R)&&U){let E=await U(C);if(E?.prompt){let c=B$(E.prompt),{newValue:Q0,newCursorPosition:d}=w$(c,N,P);J(Q0),X(d);return}}let{newValue:y,newCursorPosition:S}=w$(C,N,P);J(y),X(S)},h1.TIMEOUT_MS);K.current.timeoutId=F});s3((H,F)=>{let A=B$(H);if(q.some((R)=>F[R])||F.ctrl&&H==="c"||F.ctrl&&H==="l"||F.ctrl&&H==="t"||F.ctrl&&H==="o"||F.meta&&H==="l"||F.meta&&H==="t"||F.meta&&H==="o"||F.shift&&F.tab||A==="?"&&$==="")return;let C=Date.now(),N=K.current,P=Z,w=$;if(F.leftArrow)P--;else if(F.rightArrow)P++;else if(F.backspace||F.delete){if(H===""){if(Z>0)w=$.slice(0,Z-1)+$.slice(Z,$.length),P--}else if(Z<$.length)w=$.slice(0,Z)+$.slice(Z+1,$.length)}else if(F.ctrl&&A==="a")P=0;else if(F.ctrl&&A==="e")P=$.length;else if(F.ctrl&&A==="k")w=$.slice(0,Z);else if(F.ctrl&&A==="u")w=$.slice(Z),P=0;else if(F.ctrl&&A==="w"){let T=$.slice(0,Z).match(/\s*\S+\s*$/);if(T){let y=T[0].length;w=$.slice(0,Z-y)+$.slice(Z),P-=y}}else if(F.ctrl&&A==="v"){let R=process.platform==="darwin";(async()=>{if(G){let y=await t9();if(y){let S=await G(y.base64,y.mediaType,"clipboard.png");if(S?.prompt){let E=B$(S.prompt),{newValue:c,newCursorPosition:Q0}=w$(E,W.current,O.current);J(c),X(Q0)}return}}if(R)return;let T=await n9();if(T){let y=B$(T),S=y.includes(`
150
- `),E=y.length>h1.LARGE_INPUT_THRESHOLD;if((S||E)&&U){let d=await U(y);if(d?.prompt){let I=B$(d.prompt),{newValue:L,newCursorPosition:M}=w$(I,W.current,O.current);J(L),X(M);return}}let{newValue:c,newCursorPosition:Q0}=w$(y,W.current,O.current);J(c),X(Q0)}})().catch(()=>{});return}else if(F.pageUp)P=0;else if(F.pageDown)P=$.length;else if(A===`
151
- `&&(F.shift||F.meta)){let{newValue:R,newCursorPosition:T}=w$(A,$,Z);J(R),X(T);return}else if(!F.ctrl&&!F.meta){if(!N.firstInputTime)N.firstInputTime=C;N.lastInputTime=C;let R=C-(N.firstInputTime||C),T=A.length>h1.LARGE_INPUT_THRESHOLD,y=A.includes(`
152
- `)&&A.length>1,S=R<h1.RAPID_INPUT_THRESHOLD_MS&&N.chunks.length>0,E=R<h1.RAPID_INPUT_THRESHOLD_MS&&A.length>10,c=N.timeoutId!==null;if(U&&(T||y||S||E||c)){N.chunks.push(A),N.totalLength+=A.length,B();return}if(A.length===1&&!N.timeoutId)N.chunks=[],N.firstInputTime=null,N.lastInputTime=null,N.totalLength=0;w=$.slice(0,Z)+A+$.slice(Z,$.length),P+=A.length}if(P<0)P=0;if(P>w.length)P=w.length;if(w!==$)J(w);if(P!==Z)X(P)},{isActive:Y});let _=Y,b=$,z=Q?L$.grey(Q):void 0;if(_)if(z=Q.length>0?L$.inverse(Q[0])+L$.grey(Q.slice(1)):L$.inverse(" "),$.length===0)b=L$.inverse(" ");else{b="";for(let H=0;H<$.length;H++)if(H===Z&&Z<$.length)b+=L$.inverse($[H]);else b+=$[H];if(Z>=$.length)b+=L$.inverse(" ")}return QZ(t3,{children:Q?$.length>0?b:z:b},void 0,!1,void 0,this)}import{jsxDEV as v6}from"react/jsx-dev-runtime";var $J=ZZ.memo(({input:$,cursorPosition:Q,onChange:Y,onChangeCursorPosition:J,onAddPasteMapping:Z,onAddImagePasteMapping:X})=>{let G=s0()==="main-input",q=$.trimStart().startsWith("!"),K=e9((O)=>{let B=O.split(`
153
- `).length,_=O.length,b=500,z=10;if(_>500||B>10){let H=Z(O),F=O.slice(0,30).replace(/\n/g," "),A=`${_} chars, ${B} lines: ${F}...`;return{prompt:`${l8(H)}${A}${mQ()}`}}return{}}),W=e9(async(O,B,_)=>{try{let b=X(O,B);return{prompt:`${l8(b)}[Image #${b}]${mQ()}`}}catch(b){return console.error("[Image Paste] Failed to process image:",b),{prompt:`[Image paste failed: ${b instanceof Error?b.message:"Unknown error"}] `}}});return v6(JZ,{flexDirection:"row",width:"100%",paddingX:2,paddingY:0,flexShrink:0,flexGrow:0,overflow:"hidden",borderStyle:"round",borderColor:q?"yellow":"gray",children:[v6(YZ,{color:q?"yellow":"blue",bold:!0,children:q?"$ ":"> "},void 0,!1,void 0,this),v6(s9,{value:$,cursorPosition:Q,onChange:Y,onChangeCursorPosition:J,onPaste:K,onImagePaste:W,placeholder:" 输入命令...",focus:G,disabledKeys:["upArrow","downArrow","tab","return","escape"]},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as UQ,Text as P1}from"ink";import KZ,{useEffect as OZ,useState as zZ}from"react";import{useEffect as qZ,useState as ZJ}from"react";import{useEffect as XZ,useState as UZ}from"react";var GZ=15000,QJ=["思考中","构思中","推理中","琢磨中","分析中","斟酌中","酝酿中","推敲中","揣摩中","审视中","处理中","编排中","打磨中","编织中","拼装中","调配中","组装中","搭建中","铸造中","雕琢中","搜寻中","梳理中","排查中","勘探中","钻研中","翻阅中","遍历中","扫描中","检索中","追踪中","计算中","编译中","解析中","运算中","推演中","迭代中","收敛中","演绎中","归纳中","求解中","生成中","编写中","起草中","绘制中","勾勒中","渲染中","合成中","调和中","编曲中","烹制中","施工中","酿造中","发酵中","煎熬中","折腾中","捣鼓中","鼓捣中","腾挪中","筹备中","蓄力中"],JJ=["Esc - 中止任务 / 隐藏建议 / 双击清空输入","Shift+Tab - 切换模式 (DEFAULT → AUTO_EDIT → PLAN)","Tab - 选中建议 / 切换 thinking 模式","Up/Down - 浏览建议或输入历史","? - 显示快捷键帮助(输入框为空时)","Ctrl+C - 停止任务(双击退出)","Ctrl+L - 清屏","Ctrl+T - 展开/折叠 thinking 内容","Ctrl+O - 展开/折叠历史消息","Ctrl+A / Ctrl+E - 光标跳到行首/行尾","Ctrl+U / Ctrl+K - 删到行首/行尾","Ctrl+W - 删除前一个单词","Shift+Enter - 插入换行","/help - 显示所有可用命令","/init - 分析项目并生成 BLADE.md","/resume - 恢复历史会话","/compact - 压缩上下文,节省 token","/theme - 切换主题","/model - 管理和切换模型","/permissions - 管理权限规则","/mcp - 查看 MCP 服务器状态","/agents - 管理 subagent 配置","/clear - 清除对话历史","/status - 查看当前配置","/context - 可视化 token 使用情况","/git - Git 查询和 AI 辅助","/git review - AI Code Review","/git commit - AI 生成 commit message","/hooks - 管理 Hook 配置","/tasks - 查看后台任务","/skills - 查看可用 Skills","/plugins - 管理插件","/memory - 管理项目记忆","/ide - 管理 IDE 集成","@ 文件路径 - 附加文件到上下文","@dir/ - 附加整个目录","@file.ts:10-20 - 附加指定行范围","Plan 模式 - 先规划后编码(Shift+Tab 切换)","Auto Edit 模式 - 自动批准工具调用","MCP 协议 - 扩展外部工具集成","Subagents - 并行执行子任务","Hooks - 自定义工具执行流程","Skills - 可复用的技能模板","Plugins - 扩展功能插件","提示:/init 让 AI 理解你的项目结构","提示:Plan 模式适合复杂多步骤任务","提示:Auto Edit 可加速重复性操作","提示:@ 引用可提供更精准的上下文","提示:定期 /compact 节省 token","提示:Esc 可随时中断任务","提示:/resume 继续未完成的对话","提示:/model once 临时切换模型"];function YJ($,Q,Y=!1){let[J,Z]=UZ("");return XZ(()=>{if(Q){Z("等待用户确认...");return}if(!$){Z("");return}if(Y)return;let X=()=>{if(Math.random()<0.25){let K=Math.floor(Math.random()*JJ.length);return JJ[K]}let q=Math.floor(Math.random()*QJ.length);return QJ[q]};Z(X());let U=setInterval(()=>{Z(X())},GZ);return()=>{clearInterval(U)}},[$,Q,Y]),J}function XJ($,Q=!1,Y=!1){let[J,Z]=ZJ(0),[X,U]=ZJ(null),G=YJ($,Q,Y);return qZ(()=>{if(!$){Z(0),U(null);return}if(Y)return;if(X===null)U(Date.now());let q=setInterval(()=>{if(X!==null){let K=Math.floor((Date.now()-X)/1000);Z(K)}},1000);return()=>{clearInterval(q)}},[$,X,Y]),{currentPhrase:G,elapsedTime:J}}import{jsxDEV as e0,Fragment as NZ}from"react/jsx-dev-runtime";var C6=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],_Z=80;function UJ($){if($<60)return`${$}s`;let Q=Math.floor($/60),Y=$%60;return`${Q}m ${Y}s`}var GJ=KZ.memo(({message:$,paused:Q=!1})=>{let Y=o1(),J=y8(),Z=Y||!J,[X,U]=zZ(0),G=b0(),K=j$()>=_Z,{currentPhrase:W,elapsedTime:O}=XJ(Z,!1,Q);if(OZ(()=>{if(!Z||Q){U(0);return}let _=setInterval(()=>{U((b)=>(b+1)%C6.length)},150);return()=>clearInterval(_)},[Z,Q]),!Z)return null;let B=$||W||"正在思考中...";if(K)return e0(UQ,{paddingX:2,paddingBottom:1,flexDirection:"row",gap:1,children:[e0(P1,{color:G.colors.warning,bold:!0,children:C6[X]},void 0,!1,void 0,this),e0(P1,{color:G.colors.text.primary,children:B},void 0,!1,void 0,this),O>0&&e0(NZ,{children:[e0(P1,{color:G.colors.muted,children:"|"},void 0,!1,void 0,this),e0(P1,{color:G.colors.info,children:["已用时: ",UJ(O)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),e0(P1,{color:G.colors.muted,children:"|"},void 0,!1,void 0,this),e0(P1,{color:G.colors.secondary,children:"Esc 取消"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return e0(UQ,{paddingX:2,paddingBottom:1,flexDirection:"column",children:[e0(UQ,{flexDirection:"row",gap:1,children:[e0(P1,{color:G.colors.warning,bold:!0,children:C6[X]},void 0,!1,void 0,this),e0(P1,{color:G.colors.text.primary,children:B},void 0,!1,void 0,this)]},void 0,!0,void 0,this),O>0&&e0(UQ,{marginLeft:2,flexDirection:"row",gap:1,children:[e0(P1,{color:G.colors.info,children:["已用时: ",UJ(O)]},void 0,!0,void 0,this),e0(P1,{color:G.colors.muted,children:"|"},void 0,!1,void 0,this),e0(P1,{color:G.colors.secondary,children:"Esc 取消"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)});import{Box as KQ,Text as f0,useInput as FZ,useStdout as HZ}from"ink";import WZ from"ink-text-input";import LZ,{useCallback as GQ,useEffect as BZ,useMemo as wZ,useState as b$}from"react";import{jsxDEV as F0}from"react/jsx-dev-runtime";var zJ=LZ.memo(({details:$,onComplete:Q})=>{let{stdout:Y}=HZ(),J=Y.columns||80,Z=s0()==="confirmation-prompt",X=k0(!1),U=$.fields??[],[G,q]=b$("field"),[K,W]=b$(0),[O,B]=b$(()=>qJ($)),[_,b]=b$(""),[z,H]=b$(0),[F,A]=b$([]),[v,C]=b$(),N=U[K],P=wZ(()=>bZ(N),[N]);BZ(()=>{if(!N)return;let S=O[N.name];b(typeof S==="string"||typeof S==="number"?String(S):""),A(Array.isArray(S)?[...S]:[]);let E=P.findIndex((c)=>c.value===String(S));H(E>=0?E:0),C(void 0)},[O,N,P]);let w=GQ((S)=>{if(B(S),K<U.length-1){W((E)=>E+1);return}q("review")},[K,U.length]),R=GQ((S)=>{if(!N)return;let E={...O};if(S===void 0)delete E[N.name];else E[N.name]=S;w(E)},[O,N,w]),T=GQ((S)=>{if(!N)return;try{R(KJ(N,S))}catch(E){C(E instanceof Error?E.message:String(E))}},[N,R]),y=GQ(()=>{try{let S=OJ($,{action:"accept",content:O});Q({action:S.action,...S.content?{content:S.content}:{}})}catch(S){C(S instanceof Error?S.message:String(S))}},[O,$,Q]);if(FZ((S,E)=>{if(E.ctrl&&S==="c"||E.meta&&S==="c"){X();return}if(E.escape){Q({action:"cancel"});return}if($.mode==="url"){if(S.toLowerCase()==="y")Q({action:"accept"},!0);else if(S.toLowerCase()==="n")Q({action:"decline"});return}if(G==="review"){if(S.toLowerCase()==="y"||E.return)y();else if(S.toLowerCase()==="e")W(0),q("field");else if(S.toLowerCase()==="d")Q({action:"decline"});return}if(!N){if(E.return)y();return}if(T6(N))return;if(S.toLowerCase()==="d"){Q({action:"decline"});return}if(E.upArrow){H((c)=>c>0?c-1:Math.max(P.length-1,0));return}if(E.downArrow||E.tab){H((c)=>c<P.length-1?c+1:0);return}if(S===" "&&N.type==="multi-select"){let c=P[z];if(c)A((Q0)=>Q0.includes(c.value)?Q0.filter((d)=>d!==c.value):[...Q0,c.value]);return}if(E.return)if(N.type==="multi-select")R(F);else{let c=P[z];if(c)R(c.typedValue)}},{isActive:Z}),$.mode==="url")return F0(qQ,{width:J,color:"yellow",children:[F0(f0,{bold:!0,color:"yellow",children:"MCP external authorization"},void 0,!1,void 0,this),F0(f0,{children:$.message},void 0,!1,void 0,this),F0(f0,{color:"yellow",children:['Only continue if you trust MCP server "',$.serverName,'".']},void 0,!0,void 0,this),F0(f0,{children:["Domain: ",F0(f0,{color:"cyan",children:$.domain},void 0,!1,void 0,this)]},void 0,!0,void 0,this),F0(f0,{wrap:"wrap",children:["URL: ",F0(f0,{color:"cyan",children:$.url},void 0,!1,void 0,this)]},void 0,!0,void 0,this),F0(f0,{color:"gray",children:"[Y] Open URL · [N] Decline · Esc Cancel"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(G==="review")return F0(qQ,{width:J,color:"green",children:[F0(f0,{bold:!0,color:"green",children:"Review MCP form response"},void 0,!1,void 0,this),F0(f0,{children:$.message},void 0,!1,void 0,this),U.map((S)=>F0(f0,{children:[S.title,": ",RZ(O[S.name])]},S.name,!0,void 0,this)),v&&F0(f0,{color:"red",children:v},void 0,!1,void 0,this),F0(f0,{color:"gray",children:"[Y] Submit · [E] Edit · [D] Decline · Esc Cancel"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(!N)return F0(qQ,{width:J,color:"cyan",children:[F0(f0,{children:$.message},void 0,!1,void 0,this),F0(f0,{color:"gray",children:"This form has no fields."},void 0,!1,void 0,this),F0(f0,{color:"gray",children:"Press Enter to submit · [D] Decline · Esc Cancel"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return F0(qQ,{width:J,color:"cyan",children:[F0(f0,{bold:!0,color:"cyan",children:["MCP input requested by ",$.serverName]},void 0,!0,void 0,this),F0(f0,{children:$.message},void 0,!1,void 0,this),F0(KQ,{flexDirection:"column",marginTop:1,children:[F0(f0,{bold:!0,children:[N.title,N.required?" *":""]},void 0,!0,void 0,this),N.description&&F0(f0,{color:"gray",children:N.description},void 0,!1,void 0,this),F0(f0,{color:"gray",children:AZ(N)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),T6(N)?F0(KQ,{children:[F0(f0,{color:"cyan",children:"> "},void 0,!1,void 0,this),F0(WZ,{value:_,onChange:b,onSubmit:T,focus:Z,placeholder:N.defaultValue===void 0?N.required?"Required":"Optional":String(N.defaultValue)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):F0(KQ,{flexDirection:"column",children:P.map((S,E)=>{let c=N.type==="multi-select"&&F.includes(S.value);return F0(f0,{color:z===E?"yellow":void 0,children:[z===E?"> ":" ",N.type==="multi-select"?c?"(*) ":"( ) ":"",S.label]},S.value,!0,void 0,this)})},void 0,!1,void 0,this),v&&F0(f0,{color:"red",children:v},void 0,!1,void 0,this),F0(f0,{color:"gray",children:[T6(N)?"Enter to continue":N.type==="multi-select"?"Space to toggle · Enter to continue":"Up/Down to select · Enter to continue"," · [D] Decline · Esc Cancel"]},void 0,!0,void 0,this),F0(f0,{color:"gray",children:["Field ",K+1," of ",U.length]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)});function qQ({children:$,width:Q,color:Y}){return F0(KQ,{flexDirection:"column",gap:1,borderStyle:"round",borderColor:Y,padding:1,width:Math.min(Q-4,88),children:$},void 0,!1,void 0,this)}function T6($){return $.type==="string"||$.type==="number"||$.type==="integer"}function bZ($){if(!$)return[];if($.type==="boolean")return[{value:"true",label:"Yes",typedValue:!0},{value:"false",label:"No",typedValue:!1}];return($.options??[]).map((Q)=>({...Q,typedValue:Q.value}))}function AZ($){let Q=[];if($.format)Q.push(`format: ${$.format}`);if($.minimum!==void 0)Q.push(`min: ${$.minimum}`);if($.maximum!==void 0)Q.push(`max: ${$.maximum}`);if($.minLength!==void 0)Q.push(`min length: ${$.minLength}`);if($.maxLength!==void 0)Q.push(`max length: ${$.maxLength}`);if($.minItems!==void 0)Q.push(`min selections: ${$.minItems}`);if($.maxItems!==void 0)Q.push(`max selections: ${$.maxItems}`);return Q.join(" · ")}function RZ($){if($===void 0)return"(omitted)";if(Array.isArray($))return $.join(", ")||"(none)";return String($)}import NQ from"ansi-escapes";import{Box as $$,Static as yJ,useStdout as hZ}from"ink";import gZ,{useEffect as p1,useMemo as MJ,useRef as Q$,useState as E6}from"react";import{useStdout as PZ}from"ink";import{debounce as yZ}from"lodash-es";import{useEffect as MZ,useState as IZ}from"react";function _J($=200){let{stdout:Q}=PZ(),[Y,J]=IZ(Q.rows||24);return MZ(()=>{let Z=yZ(()=>{J(Q.rows||24)},$);return Z(),Q.on("resize",Z),()=>{Q.off("resize",Z),Z.cancel()}},[Q,$]),Y}import A$ from"chalk";import vZ from"string-width";var z0={active:!1,renderedLineCount:0,lastRenderedLines:[],terminalWidth:process.stdout.columns||80,terminalHeight:process.stdout.rows||24,prefixIndent:4,isFirstRender:!0},zQ="\x1B",k6=`${zQ}[2K`,OQ=($)=>$>0?`${zQ}[${$}A`:"",NJ=`${zQ}[?25l`,FJ=`${zQ}[?25h`;function HJ($,Q){z0.active=!0,z0.renderedLineCount=0,z0.lastRenderedLines=[],z0.terminalWidth=$,z0.terminalHeight=Q,z0.isFirstRender=!0}function WJ($,Q){z0.terminalWidth=$,z0.terminalHeight=Q}function LJ($,Q,Y,J){if(!z0.active)return;let Z=8,X=Math.max(1,z0.terminalHeight-Z),U=[],G=l0.getTheme(),q=" ".repeat(z0.prefixIndent),K=A$.dim.hex(G.colors.border.light);if(Q>0)U.push(`${q}${A$.dim.hex(G.colors.text.muted)(`^ ${Q} lines above (streaming...)`)}`);let W=Y==="code",O=Y==="diff",B="",_=$;if(W&&$.length>0)B=$[0].match(/^```(\w+)?/)?.[1]||"",_=$.slice(1);else if(O&&$.length>0&&$[0]==="<<<DIFF>>>")_=$.slice(1);let b=_.slice(-X);if(W&&Q===0){let H=B?` ${A$.hex(G.colors.text.secondary)(B)}`:"";U.push(`${q}${K("╭─")}${H}`)}for(let H=0;H<b.length;H++){let F=b[H],A=q;if(H===0&&!J&&z0.isFirstRender&&!W&&!O)A=A$.bold.hex(G.colors.success)("• ")+" ",z0.isFirstRender=!1;let v=W?4:0,C=z0.terminalWidth-z0.prefixIndent-2-v,N=F;if(vZ(F)>C)N=F.slice(0,C);if(W)U.push(`${q}${K("│")} ${N}`);else if(O){let P=N;if(P.startsWith("+"))U.push(`${A}${A$.green(N)}`);else if(P.startsWith("-"))U.push(`${A}${A$.red(N)}`);else if(P.startsWith("@@"))U.push(`${A}${A$.dim(N)}`);else U.push(`${A}${N}`)}else U.push(`${A}${N}`);if(H===0&&!J&&z0.isFirstRender)z0.isFirstRender=!1}let z=[];if(z.push(NJ),z0.renderedLineCount>0)z.push(OQ(z0.renderedLineCount)),z.push("\r");for(let H=0;H<U.length;H++){let F=U[H],A=z0.lastRenderedLines[H];if(F!==A)z.push(k6),z.push(F);if(H<U.length-1)z.push(`
154
- `)}if(U.length<z0.renderedLineCount){for(let F=U.length;F<z0.renderedLineCount;F++)z.push(`
155
- `),z.push(k6);let H=z0.renderedLineCount-U.length;z.push(OQ(H))}z.push(FJ),process.stdout.write(z.join("")),z0.renderedLineCount=U.length,z0.lastRenderedLines=U}function g1(){if(!z0.active)return;if(z0.renderedLineCount>0){let $=[];$.push(NJ),$.push(OQ(z0.renderedLineCount)),$.push("\r");for(let Q=0;Q<z0.renderedLineCount;Q++)if($.push(k6),Q<z0.renderedLineCount-1)$.push(`
156
- `);if(z0.renderedLineCount>1)$.push(OQ(z0.renderedLineCount-1)),$.push("\r");$.push(FJ),process.stdout.write($.join(""))}z0.active=!1,z0.renderedLineCount=0,z0.lastRenderedLines=[],z0.isFirstRender=!0}function C1(){return z0.active}import{Box as CZ,Text as BJ}from"ink";import TZ from"react";import{jsxDEV as S6}from"react/jsx-dev-runtime";var f6=TZ.memo(({collapsedCount:$})=>{let Q=b0();if($<=0)return null;let Y=Q.colors.text.muted;return S6(CZ,{flexDirection:"row",marginBottom:1,children:[S6(BJ,{color:Y,children:[">"," ",$," 条历史消息"]},void 0,!0,void 0,this),S6(BJ,{color:Y,children:" [Ctrl+O 展开]"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});f6.displayName="CollapsedHistorySummary";import{Box as K8,Text as O8}from"ink";import kZ from"ink-big-text";import SZ from"ink-gradient";import fZ from"react";import{jsxDEV as L1}from"react/jsx-dev-runtime";var bJ=fZ.memo(()=>{return L1(K8,{flexDirection:"column",paddingX:2,paddingTop:1,paddingBottom:1,children:[L1(K8,{flexDirection:"column",children:L1(SZ,{name:"pastel",children:L1(kZ,{text:"BLADE",font:"block"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),L1(K8,{marginBottom:1,children:L1(O8,{color:"white",dimColor:!0,children:wJ()},void 0,!1,void 0,this)},void 0,!1,void 0,this),L1(K8,{flexDirection:"column",marginBottom:1,children:[L1(K8,{marginBottom:1,children:L1(O8,{color:"white",bold:!0,children:"使用指南:"},void 0,!1,void 0,this)},void 0,!1,void 0,this),L1(O8,{color:"white",children:"1. 输入问题、编辑文件或运行命令"},void 0,!1,void 0,this),L1(O8,{color:"white",children:"2. 使用 /init 创建项目配置文件"},void 0,!1,void 0,this),L1(O8,{color:"white",children:"3. 输入 /help 查看所有 slash 命令"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)});import{Box as _Q,Text as D6}from"ink";import AJ from"react";import{jsxDEV as e1}from"react/jsx-dev-runtime";var RJ=AJ.memo(({tasks:$,visible:Q=!0,compact:Y=!1})=>{let{colors:J}=b0();if(!Q||$.length===0)return null;let Z={total:$.length,completed:$.filter((X)=>X.status==="completed").length,inProgress:$.filter((X)=>X.status==="in_progress").length};return e1(_Q,{flexDirection:"column",borderStyle:"single",borderColor:J.border.light,paddingX:1,paddingY:Y?0:1,marginBottom:1,children:[e1(_Q,{marginBottom:Y?0:1,children:[e1(D6,{dimColor:!0,children:"Tasks "},void 0,!1,void 0,this),e1(D6,{color:J.text.muted,children:[Z.completed,"/",Z.total]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),e1(_Q,{flexDirection:"column",children:$.map((X,U)=>e1(DZ,{task:X,compact:Y},X.id||U,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}),DZ=AJ.memo(({task:$,compact:Q})=>{let Y,J=!1,Z;switch($.status){case"completed":Y="[OK]",J=!0,Z=$.subject;break;case"in_progress":Y=">",J=!1,Z=$.activeForm||$.subject;break;case"pending":default:Y="-",J=!0,Z=$.subject;break}return e1(_Q,{paddingY:Q?0:0,children:e1(D6,{dimColor:J,children:[Y," ",Z]},void 0,!0,void 0,this)},void 0,!1,void 0,this)});import{Box as V6,Text as d$}from"ink";import VZ,{useMemo as PJ}from"react";import{jsxDEV as m1}from"react/jsx-dev-runtime";function jZ($,Q=60){if(!$)return"";let Y=$.split(`
157
- `)[0]||"";if(Y.length<=Q)return Y;return`${Y.slice(0,Q)}...`}function EZ($){if(!$)return 0;return $.split(`
158
- `).length}var j6=VZ.memo(({content:$,isStreaming:Q=!1,isExpanded:Y})=>{let J=b0(),Z=PJ(()=>EZ($),[$]),X=PJ(()=>jZ($),[$]),U=J.colors.info,G=J.colors.muted;return m1(V6,{flexDirection:"column",marginBottom:1,children:[m1(V6,{flexDirection:"row",children:[m1(d$,{color:U,children:Y?"v":">"},void 0,!1,void 0,this),m1(d$,{children:" "},void 0,!1,void 0,this),m1(d$,{color:G,children:["Thinking",Q?"...":` (${Z} lines)`]},void 0,!0,void 0,this),!Y&&!Q&&X&&m1(d$,{color:G,children:[" - ",X]},void 0,!0,void 0,this),m1(d$,{color:G,dimColor:!0,children:[" ","[Ctrl+T]"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Y&&$&&m1(V6,{marginLeft:2,marginTop:1,borderStyle:"round",borderColor:"gray",paddingX:1,paddingY:0,children:m1(d$,{color:G,children:$},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});j6.displayName="ThinkingBlock";import{jsxDEV as a0}from"react/jsx-dev-runtime";var vJ=gZ.memo(()=>{let $=r6(),Q=z2(),Y=_2(),J=N2(),Z=o1(),X=e6(),U=Y2(),G=v8(),q=K2(),K=O2(),W=a6(),O=H2(),B=F2(),_=j$(),b=_J(),{stdout:z}=hZ(),H=r1(),[F,A]=E6(null),[v,C]=E6([]),[N,P]=E6(new Set),w=Q$(B),R=Q$(null),T=Q$(0),y=Q$(0),S=Q$(new Set),E=Q$(new Set),c=Q$([]),Q0=Q$(null);p1(()=>{if(w.current!==B){if(C1())g1();if(z)z.write(NQ.clearTerminal);H.incrementClearCount(),w.current=B}},[B,z,H]);let d=$,I=J;p1(()=>{if(!J||Z){Q0.current=null;return}if(Q0.current===J)return;if(Q0.current=J,C1())g1();if(z)z.write(NQ.eraseScreen+NQ.cursorTo(0,0));S.current=new Set,E.current=new Set(d.filter((j)=>j.role==="tool").map((j)=>j.id)),R.current=null,T.current=0,y.current=0,c.current=[],C([]),P(new Set),H.incrementClearCount(),H.clearFinalizingStreamingMessageId()},[J,Z,z,H,d]);let L=Q??J;p1(()=>{if(C1())g1();R.current=null,T.current=0,y.current=0,S.current=new Set,E.current=new Set(d.filter((j)=>j.role==="tool").map((j)=>j.id)),c.current=[],C([]),P(new Set)},[W]),p1(()=>{if(!L)return;if(R.current===L)return;R.current=L,T.current=0,y.current=0,E.current=new Set(d.filter((j)=>j.role==="tool").map((j)=>j.id)),c.current=[],C([])},[L,d]),p1(()=>{if(!L)return;let j=h6(L);if(!j||j.length<=T.current)return;let m=j.slice(T.current);T.current=j.length;let f=m,n=c.current;if(n.length>0)if(f.some((D0)=>D0.type!=="empty"))f=[...n,...f],c.current=[];else{c.current=[...n,...f];return}let _0=f.length;while(_0>0&&f[_0-1].type==="empty")_0-=1;if(_0!==f.length)c.current=f.slice(_0),f=f.slice(0,_0);if(f.length===0)return;let N0=y.current;y.current+=1;let m0=N0>0;if(C1())g1();P((D0)=>{if(!L||D0.has(L))return D0;let w0=new Set(D0);return w0.add(L),w0}),C((D0)=>[...D0,a0($$,{flexDirection:"column",children:a0(s1,{content:"",role:"assistant",terminalWidth:_,isPending:!1,hidePrefix:m0,noMargin:!0,blocksOverride:f,renderCodeBlocksAsPlainText:!1},void 0,!1,void 0,this)},`streaming-${L}-${N0}`,!1,void 0,this)])},[L,Y.version,_,W]),p1(()=>{if(!L)return;let j=E.current,m=d.filter((f)=>f.role==="tool"&&!j.has(f.id)&&!S.current.has(f.id));if(m.length===0)return;if(C1())g1();for(let f of m)S.current.add(f.id);C((f)=>[...f,...m.map((n)=>a0($$,{flexDirection:"column",children:a0(s1,{content:n.content,role:n.role,terminalWidth:_,metadata:n.metadata,isPending:!1,messageId:n.id},void 0,!1,void 0,this)},`streaming-tool-${n.id}`,!1,void 0,this))])},[L,d,_]),p1(()=>{if(!L){if(C1())g1();return}if(!C1())HJ(_,b);else WJ(_,b);let j=IJ(L);if(!j||j.lines.length===0)return;let f=Math.max(1,b-8),n=Math.max(0,j.lines.length-f),_0=j.lines.slice(-f),N0=(h6(L)?.length??0)>0;LJ(_0,n,j.mode,N0)},[L,Y.version,b,_]),p1(()=>{if(!L&&C1())g1()},[L]),p1(()=>{if(F===null&&d.length>O){if(A(d.length),C1())g1();if(z)z.write(NQ.clearTerminal);H.incrementClearCount()}},[d.length,O,F,z,H]);let M=MJ(()=>{return X.some((j)=>j.status==="pending"||j.status==="in_progress")},[X]),V=B?0:F??0,k=V,u=MJ(()=>{let j=[];if(j.push(a0(bJ,{},"header",!1,void 0,this)),k>0)j.push(a0(f6,{collapsedCount:k},"collapsed-summary",!1,void 0,this));for(let m=V;m<d.length;m++){let f=d[m];if(I&&f.id===I)continue;if(f.role==="tool"&&S.current.has(f.id))continue;if(f.role==="assistant"&&N.has(f.id))continue;j.push(a0($$,{flexDirection:"column",children:a0(s1,{content:f.content,role:f.role,terminalWidth:_,metadata:f.metadata,isPending:!1,messageId:f.id},void 0,!1,void 0,this)},f.id,!1,void 0,this))}return j},[d,V,k,_,I,N]);return a0($$,{flexDirection:"column",paddingX:2,children:a0($$,{flexDirection:"column",children:[a0(yJ,{items:u,children:(j)=>j},W,!1,void 0,this),q&&a0($$,{marginBottom:1,children:a0(j6,{content:q,isStreaming:Z,isExpanded:K},void 0,!1,void 0,this)},void 0,!1,void 0,this),v.length>0&&a0(yJ,{items:v,children:(j)=>j},`streaming-${W}`,!1,void 0,this),U&&M&&a0($$,{marginTop:1,children:a0(RJ,{tasks:X,visible:!0,compact:!1},void 0,!1,void 0,this)},void 0,!1,void 0,this),G.map((j,m)=>a0($$,{flexDirection:"column",children:a0(s1,{content:j.displayText,role:"user",terminalWidth:_},void 0,!1,void 0,this)},`pending-${m}`,!1,void 0,this))]},void 0,!0,void 0,this)},void 0,!1,void 0,this)});import{useMemoizedFn as FQ,useMount as mZ}from"ahooks";import{Box as B1,Text as H0,useFocus as pZ,useFocusManager as cZ,useInput as xZ}from"ink";import uZ from"ink-select-input";import{memo as dZ,useMemo as lZ,useState as HQ}from"react";import{jsxDEV as t,Fragment as oZ}from"react/jsx-dev-runtime";var rZ=({isSelected:$})=>t(B1,{marginRight:1,children:t(H0,{color:$?"yellow":"gray",children:$?">":" "},void 0,!1,void 0,this)},void 0,!1,void 0,this),aZ=({isSelected:$,label:Q})=>t(H0,{bold:$,color:$?"yellow":void 0,children:Q},void 0,!1,void 0,this),CJ=dZ(({onClose:$,onEdit:Q})=>{let Y=Z2(),J=I8()??"",{isFocused:Z}=pZ({id:"model-selector"}),X=cZ(),[U,G]=HQ(""),[q,K]=HQ(!1),[W,O]=HQ(null),B=k0(!1),[_]=HQ(()=>{let w=process.stdout?.columns||80;return Math.max(20,w-8)});mZ(()=>{if(X?.focus("model-selector"),Y.length>0)G(Y[0].id)}),xZ((w,R)=>{if(q)return;if(R.ctrl&&w==="c"||R.meta&&w==="c"){B();return}if(R.escape){$();return}if(!Z)return;if(w==="d"||w==="D"){z();return}if((w==="e"||w==="E")&&Q)H()},{isActive:!0});let b=FQ(async(w)=>{if(q)return;let R=w.value;if(R===J){$();return}K(!0),O(null);try{await u0().setCurrentModel(R),$()}catch(T){O(T.message),K(!1)}}),z=FQ(async()=>{if(q||U===J)return;K(!0),O(null);try{if(await u0().removeModel(U),Y.length<=1)$()}catch(w){O(w.message)}finally{K(!1)}}),H=FQ(()=>{if(q||!Q)return;let w=Y.find((R)=>R.id===U);if(!w)return;Q(w)}),F=FQ((w)=>{G(w.value)}),A=lZ(()=>{return Y.find((w)=>w.id===U)},[Y,U]),v=A?WQ()?.modelProviders[A.provider]:void 0,C=Y.map((w)=>{let R=w.id===J?" (当前)":"";return{label:g6(w)+R,value:w.id}}),N=U===J;return t(B1,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:1,width:"100%",children:[t(B1,{flexDirection:"row",justifyContent:"space-between",marginBottom:1,children:[t(H0,{bold:!0,color:"cyan",children:"模型管理"},void 0,!1,void 0,this),t(H0,{dimColor:!0,children:[q?"处理中...":N?"Enter=关闭 • E=编辑 • Esc=取消":"Enter=切换 • D=删除 • E=编辑 • Esc=取消"," • Ctrl+C=退出"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),t(B1,{flexDirection:"row",children:[t(B1,{flexDirection:"column",flexGrow:2,marginRight:2,borderStyle:"single",borderColor:"gray",padding:1,children:[t(H0,{dimColor:!0,children:["已配置模型 (",Y.length,")"]},void 0,!0,void 0,this),t(B1,{marginTop:1,children:t(uZ,{items:C,onSelect:b,onHighlight:F,indicatorComponent:rZ,itemComponent:aZ},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t(B1,{flexDirection:"column",flexGrow:3,borderStyle:"single",borderColor:"gray",padding:1,children:[t(H0,{dimColor:!0,children:"模型详情"},void 0,!1,void 0,this),t(B1,{marginY:1,children:t(H0,{color:N?"green":"yellow",children:N?"* 当前使用":"* 可切换"},void 0,!1,void 0,this)},void 0,!1,void 0,this),A?t(B1,{flexDirection:"column",children:[t(H0,{children:[t(H0,{dimColor:!0,children:"名称: "},void 0,!1,void 0,this),t(H0,{bold:!0,color:"cyan",children:g6(A)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t(H0,{children:[t(H0,{dimColor:!0,children:"Provider: "},void 0,!1,void 0,this),t(H0,{bold:!0,children:v?.name??A.provider},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v&&t(oZ,{children:[t(H0,{children:[t(H0,{dimColor:!0,children:"Channel ID: "},void 0,!1,void 0,this),t(H0,{children:A.provider},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t(H0,{children:[t(H0,{dimColor:!0,children:"Wire API: "},void 0,!1,void 0,this),t(H0,{children:v.wireApi},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t(H0,{children:[t(H0,{dimColor:!0,children:"Endpoint: "},void 0,!1,void 0,this),t(H0,{color:"blueBright",children:v.baseUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),t(H0,{children:[t(H0,{dimColor:!0,children:"Model: "},void 0,!1,void 0,this),t(H0,{bold:!0,children:A.model},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.overrides?.baseUrl&&t(H0,{children:[t(H0,{dimColor:!0,children:"Base URL override: "},void 0,!1,void 0,this),t(H0,{color:"blueBright",children:A.overrides.baseUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t(H0,{children:[t(H0,{dimColor:!0,children:"Context Window: "},void 0,!1,void 0,this),t(H0,{children:f1().resolveConfig(A).contextWindow},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):t(H0,{dimColor:!0,children:"请选择一个模型查看详情"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),W&&t(B1,{marginTop:1,children:t(H0,{color:"red",children:W},void 0,!1,void 0,this)},void 0,!1,void 0,this),t(B1,{justifyContent:"center",marginTop:1,children:t(H0,{dimColor:!0,children:"─".repeat(_)},void 0,!1,void 0,this)},void 0,!1,void 0,this),t(B1,{justifyContent:"center",children:t(H0,{dimColor:!0,children:"提示:D=删除 * E=编辑 * Up/Down=移动 * Enter/ESC=确认"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{useMemoizedFn as m6}from"ahooks";import{Box as H5,Text as p6,useInput as W5}from"ink";import{useState as y$}from"react";import{Box as R$,Text as c1,useInput as iZ}from"ink";import nZ from"ink-text-input";import{jsxDEV as i0}from"react/jsx-dev-runtime";var TJ=({provider:$,value:Q,onChange:Y,onSubmit:J,onCancel:Z,error:X})=>{return iZ((U,G)=>{if(G.escape)Z()}),i0(R$,{flexDirection:"column",children:[i0(R$,{marginBottom:1,children:i0(c1,{bold:!0,color:"blue",children:"Step 2: 输入 API Key"},void 0,!1,void 0,this)},void 0,!1,void 0,this),i0(R$,{marginBottom:1,children:i0(c1,{children:["Provider: ",i0(c1,{bold:!0,children:$.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),i0(R$,{marginBottom:1,children:i0(c1,{dimColor:!0,children:"API 密钥将存储在 ~/.blade/auth.json(权限 600),不会写入模型配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),i0(R$,{children:[i0(c1,{bold:!0,color:"cyan",children:[">"," "]},void 0,!0,void 0,this),i0(nZ,{value:Q,onChange:Y,onSubmit:J,placeholder:"sk-...",mask:"*"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),X&&i0(R$,{marginTop:1,children:i0(c1,{color:"red",children:X},void 0,!1,void 0,this)},void 0,!1,void 0,this),i0(R$,{marginTop:1,children:i0(c1,{dimColor:!0,children:["输入完成后按 ",i0(c1,{bold:!0,children:"Enter"},void 0,!1,void 0,this),",",i0(c1,{bold:!0,children:"Esc"},void 0,!1,void 0,this)," 返回"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{Box as LQ,Text as J$,useInput as tZ}from"ink";import sZ from"ink-text-input";import{useState as BQ}from"react";import{jsxDEV as K1}from"react/jsx-dev-runtime";var wQ=["id","name","baseUrl","model"];function kJ($){switch($){case"id":return"Channel ID";case"name":return"Channel name";case"baseUrl":return"Base URL";case"model":return"Model ID"}}function eZ($,Q,Y){switch($){case"id":return"team-gateway";case"name":return Y||"Team Gateway";case"baseUrl":return Q==="anthropic-messages"?"https://gateway.example.com":"https://gateway.example.com/v1";case"model":return Q==="anthropic-messages"?"claude-opus-4-8":"vendor-model-2026"}}function $5($,Q){let Y=$.id.trim(),J={name:$.name.trim()||Y,baseUrl:$.baseUrl.trim(),wireApi:Q},Z=fJ(Y,J);if(!$.model.trim())Z.push("Model ID must not be empty");if(Z.length>0)throw Error(Z[0]);return{provider:Y,model:$.model.trim(),displayName:$.model.trim(),modelProvider:J}}var DJ=({wireApi:$,initialConfig:Q,onSubmit:Y,onCancel:J})=>{let Z={id:Q?.provider??"",name:Q?.modelProvider?.name??"",baseUrl:Q?.modelProvider?.baseUrl??"",model:Q?.model??""},[X,U]=BQ(Q?3:0),[G,q]=BQ(Q?.model??""),[K,W]=BQ(Z),[O,B]=BQ(),_=wQ[X];tZ((z,H)=>{if(!H.escape)return;if(B(void 0),X===0){J();return}let F=X-1,A=wQ[F];U(F),q(K[A])});let b=(z)=>{let H=z.trim();if(_==="id"&&!SJ.test(H)){B("Channel ID 必须以小写字母开头,且仅包含小写字母、数字、.、_ 或 -");return}if(_==="baseUrl")try{let A=new URL(H);if(!["http:","https:"].includes(A.protocol))throw Error()}catch{B("Base URL 必须是绝对 HTTP(S) URL");return}if(_==="model"&&!H){B("Model ID 不能为空");return}let F={...K,[_]:_==="name"&&!H?K.id:H};if(W(F),B(void 0),X===wQ.length-1){try{Y($5(F,$))}catch(A){B(A instanceof Error?A.message:"渠道配置无效")}return}U(X+1),q("")};return K1(LQ,{flexDirection:"column",children:[K1(LQ,{marginBottom:1,children:K1(J$,{bold:!0,color:"blue",children:"配置自定义 Provider 渠道"},void 0,!1,void 0,this)},void 0,!1,void 0,this),K1(J$,{dimColor:!0,children:["Protocol:"," ",$==="anthropic-messages"?"Anthropic Messages":"OpenAI Chat Completions"]},void 0,!0,void 0,this),wQ.slice(0,X).map((z)=>K1(J$,{children:[kJ(z),": ",K1(J$,{color:"cyan",children:K[z]},void 0,!1,void 0,this)]},z,!0,void 0,this)),K1(LQ,{marginTop:1,children:[K1(J$,{bold:!0,children:[kJ(_),": "]},void 0,!0,void 0,this),K1(sZ,{value:G,onChange:(z)=>{q(z),B(void 0)},onSubmit:b,placeholder:eZ(_,$,K.id)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),_==="name"&&K1(J$,{dimColor:!0,children:"留空使用 Channel ID"},void 0,!1,void 0,this),O&&K1(J$,{color:"red",children:O},void 0,!1,void 0,this),K1(LQ,{marginTop:1,children:K1(J$,{dimColor:!0,children:"Enter 继续 · Esc 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{useEffect as EJ,useState as l$}from"react";var hJ=()=>{let[$,Q]=l$([]),[Y,J]=l$(!0),[Z,X]=l$(null);return EJ(()=>{(async()=>{try{Q(await VJ())}catch(G){X(G instanceof Error?G.message:"加载 Provider 列表失败")}finally{J(!1)}})()},[]),{providers:$,isLoading:Y,error:Z}},gJ=($)=>{let[Q,Y]=l$([]),[J,Z]=l$(!1),[X,U]=l$(null);return EJ(()=>{if(!$){Y([]);return}(async()=>{Z(!0),U(null);try{Y(await jJ($))}catch(q){U(q instanceof Error?q.message:"加载模型列表失败")}finally{Z(!1)}})()},[$]),{models:Q,isLoading:J,error:X}};import{Box as x1,Text as y1,useInput as Q5}from"ink";import J5 from"ink-select-input";import Y5 from"ink-text-input";import{useMemo as mJ,useState as Z5}from"react";import{jsxDEV as h0,Fragment as q5}from"react/jsx-dev-runtime";var X5=({isSelected:$})=>h0(x1,{marginRight:1,children:h0(y1,{color:$?"yellow":"gray",children:$?">":" "},void 0,!1,void 0,this)},void 0,!1,void 0,this),U5=($)=>{let Q=[$.name];if($.contextWindow){let Y=$.contextWindow>=1e6?`${($.contextWindow/1e6).toFixed(1)}M`:$.contextWindow>=1000?`${Math.round($.contextWindow/1000)}K`:`${$.contextWindow}`;Q.push(`[${Y} ctx]`)}if($.reasoning)Q.push("[reasoning]");if($.input.includes("image"))Q.push("[vision]");if($.cost.input||$.cost.output)Q.push(`[$${$.cost.input}/$${$.cost.output}]`);return Q.join(" ")},G5=({isSelected:$,label:Q})=>h0(y1,{bold:$,color:$?"yellow":void 0,children:Q},void 0,!1,void 0,this),pJ=({provider:$,models:Q,isLoading:Y,error:J,onSelect:Z,onCancel:X})=>{let[U,G]=Z5("");Q5((W,O)=>{if(O.escape)if(U)G("");else X()});let q=mJ(()=>{if(!U)return Q;let W=U.toLowerCase();return Q.filter((O)=>O.name.toLowerCase().includes(W)||O.id.toLowerCase().includes(W))},[Q,U]),K=mJ(()=>q.map((W)=>({key:W.id,label:U5(W),value:W})),[q]);if(Y)return h0(x1,{flexDirection:"column",children:h0(y1,{color:"yellow",children:["正在加载 ",$.name," 模型列表..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this);if(J)return h0(x1,{flexDirection:"column",children:[h0(y1,{color:"red",children:J},void 0,!1,void 0,this),h0(y1,{dimColor:!0,children:"按 Esc 返回"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return h0(x1,{flexDirection:"column",children:[h0(x1,{marginBottom:1,children:h0(y1,{bold:!0,color:"blue",children:"Step 3: 选择模型"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h0(x1,{marginBottom:1,children:h0(y1,{children:["Provider: ",h0(y1,{bold:!0,children:$.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),h0(q5,{children:[h0(x1,{marginBottom:1,children:[h0(y1,{color:"cyan",children:"> "},void 0,!1,void 0,this),h0(Y5,{value:U,onChange:G,placeholder:`搜索 ${Q.length} 个模型...`},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h0(x1,{marginBottom:1,children:h0(y1,{dimColor:!0,children:"模型元数据来自内置 catalog"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h0(x1,{flexDirection:"column",height:12,children:h0(J5,{items:K,onSelect:(W)=>Z(W.value),indicatorComponent:X5,itemComponent:G5,limit:10},void 0,!1,void 0,this)},void 0,!1,void 0,this),q.length===0&&h0(y1,{color:"yellow",children:"内置 catalog 中没有匹配模型"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};import{Box as P$,Text as Y$,useInput as K5}from"ink";import O5 from"ink-select-input";import z5 from"ink-text-input";import{useMemo as cJ,useState as _5}from"react";import{jsxDEV as n0}from"react/jsx-dev-runtime";var N5=({isSelected:$})=>n0(P$,{marginRight:1,children:n0(Y$,{color:$?"yellow":"gray",children:$?">":" "},void 0,!1,void 0,this)},void 0,!1,void 0,this),F5=({isSelected:$,label:Q})=>n0(Y$,{bold:$,color:$?"yellow":void 0,children:Q},void 0,!1,void 0,this),xJ=({providers:$,isLoading:Q,error:Y,onSelect:J,onCancel:Z})=>{let[X,U]=_5("");K5((K,W)=>{if(W.escape)if(X)U("");else Z()});let G=cJ(()=>{if(!X)return $;let K=X.toLowerCase();return $.filter((W)=>W.name.toLowerCase().includes(K)||W.id.toLowerCase().includes(K))},[$,X]),q=cJ(()=>G.map((K)=>({key:K.id,label:`${K.name} - ${K.modelCount} models${K.configured?" [configured]":""}`,value:K})),[G]);if(Q)return n0(P$,{flexDirection:"column",children:n0(Y$,{color:"yellow",children:"正在加载 Provider 列表..."},void 0,!1,void 0,this)},void 0,!1,void 0,this);if(Y)return n0(P$,{flexDirection:"column",children:[n0(Y$,{color:"red",children:Y},void 0,!1,void 0,this),n0(Y$,{dimColor:!0,children:"按 Esc 返回"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return n0(P$,{flexDirection:"column",children:[n0(P$,{marginBottom:1,children:n0(Y$,{bold:!0,color:"blue",children:"Step 1: 选择 API 提供商"},void 0,!1,void 0,this)},void 0,!1,void 0,this),n0(P$,{marginBottom:1,children:[n0(Y$,{color:"cyan",children:"> "},void 0,!1,void 0,this),n0(z5,{value:X,onChange:U,placeholder:`搜索 ${$.length} 个 Provider...`},void 0,!1,void 0,this)]},void 0,!0,void 0,this),n0(P$,{flexDirection:"column",height:12,children:n0(O5,{items:q,onSelect:(K)=>J(K.value),indicatorComponent:N5,itemComponent:F5,limit:10},void 0,!1,void 0,this)},void 0,!1,void 0,this),G.length===0&&n0(Y$,{color:"yellow",children:"未找到匹配的 Provider,按 Esc 清除搜索"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};function uJ($){if($==="custom")return"provider";if($==="model")return"provider";if($==="credential")return"model";return}import{jsxDEV as Z$}from"react/jsx-dev-runtime";var c6=({mode:$,initialConfig:Q,modelId:Y,onComplete:J,onCancel:Z})=>{let[X,U]=y$("provider"),[G,q]=y$(),[K,W]=y$(),[O,B]=y$(),[_,b]=y$(""),[z,H]=y$(),[F,A]=y$(!1),v=hJ(),C=gJ(G?.id),N=k0(!1);W5((T,y)=>{if(y.ctrl&&T==="c"||y.meta&&T==="c")$==="setup"?N():Z()});let P=m6(async(T)=>{if(!G)return;let y=O??(K?{provider:G.id,model:K.id,displayName:Q?.displayName}:void 0);if(!y)return;A(!0),H(void 0);try{if(y.modelProvider)f1().registerModelProvider(y.provider,y.modelProvider,[y.model]);if(T?.trim())await f1().setApiKey(y.provider,T.trim());let S={displayName:y.displayName,provider:y.provider,model:y.model,overrides:y.overrides};if($==="setup")await J(y);else if($==="add"){let E=y.modelProvider?await u0().addModelWithProvider(S,y.modelProvider):await u0().addModel(S);await u0().setCurrentModel(E.id),await J(y)}else if(Y){if(y.modelProvider)await u0().updateModelWithProvider(Y,S,y.modelProvider);else await u0().updateModel(Y,S);await J(y)}}catch(S){if(y.modelProvider){await f1().credentials.delete(y.provider);let E=WQ();f1().configureModelProviders(E?.modelProviders??{},E?.models??[])}H(S instanceof Error?S.message:"保存配置失败"),A(!1)}}),w=m6((T)=>{if(W(T),G?.configured)P();else if(G?.supportsApiKey)U("credential");else H(`${G?.name??"Provider"} 需要 OAuth 或环境凭证,请先在外部完成认证`)}),R=m6(()=>{if(H(void 0),X==="credential"&&O){U("custom");return}let T=uJ(X);if(T)U(T)});return Z$(H5,{flexDirection:"column",padding:1,children:[Z$(p6,{bold:!0,color:"blue",children:$==="edit"?"编辑模型":"添加模型"},void 0,!1,void 0,this),X==="provider"&&Z$(xJ,{...v,onSelect:(T)=>{q(T),W(void 0),B(void 0),U(T.factoryWireApi?"custom":"model")},onCancel:$==="setup"?()=>{return}:Z},void 0,!1,void 0,this),X==="custom"&&G?.factoryWireApi&&Z$(DJ,{wireApi:G.factoryWireApi,initialConfig:O,onSubmit:(T)=>{B(T),U("credential")},onCancel:R},void 0,!1,void 0,this),X==="model"&&G&&Z$(pJ,{provider:G,...C,onSelect:w,onCancel:R},void 0,!1,void 0,this),X==="credential"&&G&&Z$(TJ,{provider:G,value:_,onChange:b,onSubmit:()=>void P(_),onCancel:R,error:z},void 0,!1,void 0,this),F&&Z$(p6,{color:"yellow",children:"正在保存配置..."},void 0,!1,void 0,this),z&&X!=="credential"&&Z$(p6,{color:"red",children:z},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{useMemoizedFn as z8}from"ahooks";import{promises as aJ}from"fs";import{Box as O1,Text as V0,useInput as L5}from"ink";import dJ from"ink-select-input";import B5 from"ink-text-input";import w5 from"os";import bQ from"path";import{useEffect as b5,useMemo as AQ,useRef as A5,useState as X$}from"react";import{jsxDEV as G0}from"react/jsx-dev-runtime";var _8=[{key:"allow",label:"Allow"},{key:"ask",label:"Ask"},{key:"deny",label:"Deny"},{key:"info",label:"Info"}],R5={allow:"Add a new rule...",ask:"Add a new rule...",deny:"Add a new rule..."},P5={allow:"Allow permission rules",ask:"Ask permission rules",deny:"Deny permission rules"},lJ={project:"[项目共享配置]",global:"[用户全局配置]",local:"[本地配置]"},y5=["project","global","local"],M5={allow:[],ask:[],deny:[]},I5={localExists:!1,projectExists:!1,globalExists:!1},rJ={allow:[],ask:[],deny:[]};function v5($){let Q=(J)=>Array.isArray(J)?J.filter((Z)=>typeof Z==="string"):[],Y=$?.permissions??{};return{allow:Q(Y?.allow),ask:Q(Y?.ask),deny:Q(Y?.deny)}}async function C5($){try{let Q=await aJ.readFile($,"utf-8"),Y=JSON.parse(Q);return{exists:!0,raw:Y,permissions:v5(Y)}}catch(Q){if(Q.code==="ENOENT")return{exists:!1,raw:{},permissions:{...rJ}};return console.warn(`[PermissionsManager] Failed to read ${$}:`,Q),{exists:!0,raw:{},permissions:{...rJ}}}}function T5($,Q){let Y=$.padEnd(32," "),J=Q==="local"?`${lJ[Q]} <- 可删除`:lJ[Q];return`${Y} ${J}`}var oJ=({onClose:$})=>{let Y=s0()==="permissions-manager",J=k0(!1),[Z,X]=X$(0),U=_8[Z].key,[G,q]=X$(M5),[K,W]=X$(I5),[O,B]=X$(!0),[_,b]=X$("list"),[z,H]=X$(""),[F,A]=X$(null),[v,C]=X$(null),N=A5(!1),P=AQ(()=>bQ.join(A0(),".blade","settings.local.json"),[]),w=AQ(()=>bQ.join(A0(),".blade","settings.json"),[]),R=AQ(()=>bQ.join(w5.homedir(),".blade","settings.json"),[]),T=z8(async()=>{B(!0);let m=await Promise.all([{source:"local",path:P},{source:"project",path:w},{source:"global",path:R}].map(async({source:N0,path:m0})=>{let D0=await C5(m0);return{source:N0,path:m0,...D0}})),f={localExists:m.find((N0)=>N0.source==="local")?.exists??!1,projectExists:m.find((N0)=>N0.source==="project")?.exists??!1,globalExists:m.find((N0)=>N0.source==="global")?.exists??!1};W(f);let n={allow:[],ask:[],deny:[]},_0=Object.fromEntries(m.map((N0)=>[N0.source,N0]));["allow","ask","deny"].forEach((N0)=>{y5.forEach((m0)=>{(_0[m0]?.permissions[N0]??[]).forEach((w0,_1)=>{let N1={key:`${m0}:${_1}:${w0}`,rule:w0,source:m0};n[N0].push(N1)})})}),q(n),B(!1)});b5(()=>{T()},[T]);let y=z8(async(j,m)=>{try{let f=bQ.join(A0(),".blade","settings.local.json"),n={allow:[],ask:[],deny:[]};try{let N0=await aJ.readFile(f,"utf-8"),D0=JSON.parse(N0).permissions||{};n={allow:Array.isArray(D0.allow)?D0.allow:[],ask:Array.isArray(D0.ask)?D0.ask:[],deny:Array.isArray(D0.deny)?D0.deny:[]}}catch(N0){}let _0=m(n);await u0().updateConfig({permissions:_0},{scope:"local",immediate:!0}),await T()}catch(f){throw console.error("[PermissionsManager] 修改权限规则失败:",f),f}});L5((j,m)=>{if(m.ctrl&&j==="c"||m.meta&&j==="c"){J();return}if(_==="locked"){if(N.current){N.current=!1;return}b("list"),A(null),C(null);return}if(m.escape){if(_==="list"||U==="info")$();else b("list"),H(""),A(null),C(null);return}if(_==="list"){if(m.tab&&m.shift)X((f)=>(f-1+_8.length)%_8.length);else if(m.tab)X((f)=>(f+1)%_8.length);else if(j?.toLowerCase()==="q")$()}},{isActive:Y});let S=z8((j)=>{let m=j.value;if(U==="info")return;if(m.type==="add"){b("add"),H(""),C(null);return}if(m.entry.source!=="local"){b("locked"),N.current=!0,A({tab:U,entry:m.entry}),C({type:"error",text:m.entry.source==="project"?"此规则定义在项目共享配置中,无法在此删除。":"此规则来自用户全局配置,无法在此删除。"});return}b("confirm-delete"),A({tab:U,entry:m.entry}),C(null)}),E=z8(async()=>{if(U==="info")return;let j=z.trim();if(!j){C({type:"error",text:"Permission rule 不能为空"});return}if(G[U].map((f)=>f.rule).includes(j)){C({type:"error",text:"该规则已存在"});return}try{await y(U,(f)=>{let n={allow:[...f.allow],ask:[...f.ask],deny:[...f.deny]};return n[U]=[...new Set([...f[U],j])],n}),b("list"),H(""),C({type:"success",text:"已添加本地权限规则"})}catch(f){C({type:"error",text:`保存失败: ${f instanceof Error?f.message:"未知错误"}`})}}),c=z8(async()=>{if(!F)return;let{tab:j,entry:m}=F;try{await y(j,(f)=>{let n={allow:[...f.allow],ask:[...f.ask],deny:[...f.deny]};return n[j]=f[j].filter((_0)=>_0!==m.rule),n}),b("list"),A(null),C({type:"success",text:"已删除本地权限规则"})}catch(f){C({type:"error",text:`删除失败: ${f instanceof Error?f.message:"未知错误"}`})}}),Q0=AQ(()=>{if(U==="info")return[];let j=U;return[{key:"add-new-rule",label:`› ${R5[j]}`,value:{type:"add"}},...G[j].map((f)=>({key:f.key,label:T5(f.rule,f.source),value:{type:"rule",entry:f}}))]},[U,G]),d=()=>G0(O1,{marginBottom:1,children:_8.map((j,m)=>G0(O1,{marginRight:2,children:G0(V0,{color:m===Z?"yellow":"gray",children:["[",j.label,"]"]},void 0,!0,void 0,this)},j.key,!1,void 0,this))},void 0,!1,void 0,this),I=()=>G0(O1,{flexDirection:"column",gap:1,children:[G0(V0,{children:"配置文件优先级(从高到低):"},void 0,!1,void 0,this),G0(O1,{flexDirection:"column",marginLeft:2,children:[G0(V0,{children:["1. .blade/settings.local.json (本地配置,不提交 Git)"," ",K.localExists?"[OK] 存在":"[X] 不存在"]},void 0,!0,void 0,this),G0(V0,{children:["2. .blade/settings.json (项目配置,提交 Git)"," ",K.projectExists?"[OK] 存在":"[X] 不存在"]},void 0,!0,void 0,this),G0(V0,{children:["3. ~/.blade/settings.json (用户全局配置)"," ",K.globalExists?"[OK] 存在":"[X] 不存在"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),G0(V0,{children:"说明:"},void 0,!1,void 0,this),G0(O1,{flexDirection:"column",marginLeft:2,children:[G0(V0,{children:"- /permissions 命令只管理本地配置 (.blade/settings.local.json)"},void 0,!1,void 0,this),G0(V0,{children:"- 修改全局或项目配置请直接编辑对应文件"},void 0,!1,void 0,this),G0(V0,{children:"- 本地配置不会提交到 Git"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),L=(j)=>G0(O1,{flexDirection:"column",gap:1,children:[G0(V0,{bold:!0,children:P5[j]},void 0,!1,void 0,this),G0(V0,{children:"Permission rules are a tool name, optionally followed by a specifier in parentheses."},void 0,!1,void 0,this),G0(V0,{color:"gray",children:"例如: WebFetch 或 Bash(ls:*)"},void 0,!1,void 0,this),G0(O1,{marginTop:1,children:G0(B5,{value:z,onChange:H,onSubmit:E},void 0,!1,void 0,this)},void 0,!1,void 0,this),G0(V0,{color:"gray",children:"Enter 提交 · Esc 取消"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),M=(j,m)=>G0(O1,{flexDirection:"column",gap:1,children:[G0(V0,{bold:!0,children:["Delete ",j," permission rule?"]},void 0,!0,void 0,this),G0(V0,{children:m.rule},void 0,!1,void 0,this),G0(V0,{color:"gray",children:"From project local settings"},void 0,!1,void 0,this),G0(V0,{children:"Are you sure you want to delete this permission rule?"},void 0,!1,void 0,this),G0(dJ,{items:[{label:"Yes",value:"yes"},{label:"No",value:"no"}],onSelect:(f)=>{if(f.value==="yes")c();else b("list"),A(null)}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),V=(j)=>G0(O1,{flexDirection:"column",gap:1,children:[G0(V0,{bold:!0,children:"Cannot delete this rule"},void 0,!1,void 0,this),G0(V0,{children:j.rule},void 0,!1,void 0,this),G0(V0,{color:"gray",children:j.source==="project"?"This rule is defined in .blade/settings.json. 请手动编辑该文件以移除规则。":"This rule is defined in ~/.blade/settings.json. 请手动编辑该文件以移除规则。"},void 0,!1,void 0,this),G0(V0,{color:"gray",children:"按任意键继续"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),k=(j)=>G0(dJ,{items:Q0,isFocused:_==="list",onSelect:S},void 0,!1,void 0,this),u=()=>{if(O)return G0(V0,{children:"加载中..."},void 0,!1,void 0,this);if(U==="info")return I();if(_==="add")return L(U);if(_==="confirm-delete"&&F)return M(F.tab,F.entry);if(_==="locked"&&F)return V(F.entry);return k(U)};return G0(O1,{flexDirection:"column",borderStyle:"round",borderColor:Y?"cyan":"gray",padding:1,width:80,children:[G0(V0,{color:"cyan",bold:!0,children:"权限管理器"},void 0,!1,void 0,this),d(),G0(O1,{flexDirection:"column",gap:1,children:u()},void 0,!1,void 0,this),v&&G0(O1,{marginTop:1,children:G0(V0,{color:v.type==="success"?"green":"red",children:v.text},void 0,!1,void 0,this)},void 0,!1,void 0,this),G0(O1,{marginTop:1,children:G0(V0,{color:"gray",children:"Tab 切换视图 · Esc 关闭 · Q 退出"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{Box as R0,Text as Z0,useInput as k5}from"ink";import{useState as N8}from"react";import{jsxDEV as x}from"react/jsx-dev-runtime";function $4({workspaceRoot:$,onCancel:Q}){let Y=iJ($),J=Y.getAll(),[Z,X]=N8(0),[U,G]=N8(!1),[q,K]=N8(""),[W,O]=N8(null),[,B]=N8(0),_=Y.getBySource(),b=Y.getStats(),z=Y.getSourcePolicy(),H=k0(!1,Q),F=async()=>{let N=J[Z];if(!N||U)return;if(N.source==="cli"){K(`${N.manifest.name} 由 --plugin-dir 管理,不能持久化切换`);return}if(N.status==="error"){K(N.error??`${N.manifest.name} 当前不可用`);return}G(!0),K("");try{let P=await nJ(Y.getWorkspaceRoot(),N.manifest.name,N.status!=="active","local");K(P.effectiveEnabled?`已启用 ${N.manifest.name}`:`已禁用 ${N.manifest.name}`),B((w)=>w+1)}catch(P){K(P instanceof Error?P.message:String(P))}finally{G(!1)}},A=async()=>{if(U)return;G(!0),K("");try{await tJ(Y.getWorkspaceRoot()),X(0),K("插件列表已刷新"),B((N)=>N+1)}catch(N){K(N instanceof Error?N.message:String(N))}finally{G(!1)}},v=async()=>{let N=J[Z];if(!N||U)return;if(!N.installation){K(`${N.manifest.name} 不是 Blade 受管安装,不能自动更新`);return}G(!0),O(null),K("");try{let{result:P}=await sJ(Y.getWorkspaceRoot(),N.manifest.name,{trusted:!0});if(!P.success)throw Error(P.error);K(P.changed?`已更新 ${N.manifest.name} 到 ${P.installation?.revision}`:`${N.manifest.name} 已是最新版本`),B((w)=>w+1)}catch(P){K(P instanceof Error?P.message:String(P))}finally{G(!1)}},C=async()=>{let N=J[Z];if(!N||U)return;if(!N.installation){K(`${N.manifest.name} 不是 Blade 受管安装,不能自动卸载`);return}if(W!==N.manifest.name){O(N.manifest.name),K(`再次按 x 确认卸载 ${N.manifest.name}`);return}G(!0),K("");try{let{result:P}=await eJ(Y.getWorkspaceRoot(),N.manifest.name,!0);if(!P.success)throw Error(P.error);O(null),X(0),K(`已卸载 ${N.manifest.name}`),B((w)=>w+1)}catch(P){K(P instanceof Error?P.message:String(P))}finally{G(!1)}};if(k5((N,P)=>{if(P.escape)Q?.();else if(P.ctrl&&N==="c"||P.meta&&N==="c")H();else if((P.upArrow||N==="k")&&J.length>0)O(null),X((w)=>(w-1+J.length)%J.length);else if((P.downArrow||N==="j")&&J.length>0)O(null),X((w)=>(w+1)%J.length);else if(N===" "||P.return)F();else if(N==="r")A();else if(N==="u")v();else if(N==="x")C()}),J.length===0)return x(R0,{flexDirection:"column",paddingY:1,children:[x(R0,{marginBottom:1,children:x(Z0,{bold:!0,color:"cyan",children:"插件管理器"},void 0,!1,void 0,this)},void 0,!1,void 0,this),x(R0,{paddingLeft:2,children:x(Z0,{color:"gray",children:"没有已加载的插件"},void 0,!1,void 0,this)},void 0,!1,void 0,this),x(R0,{marginTop:1,paddingLeft:2,flexDirection:"column",children:[x(Z0,{color:"gray",children:"插件目录位置:"},void 0,!1,void 0,this),x(Z0,{color:"gray",dimColor:!0,children:[" ","• ~/.blade/plugins/ - 用户级插件"]},void 0,!0,void 0,this),x(Z0,{color:"gray",dimColor:!0,children:[" ","• .blade/plugins/ - 项目级插件"]},void 0,!0,void 0,this),x(Z0,{color:"gray",dimColor:!0,children:[" ","• --plugin-dir - CLI 指定的插件"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),x(R0,{marginTop:1,paddingLeft:2,children:x(Z0,{color:"gray",children:"使用 /plugins install <url> 安装新插件"},void 0,!1,void 0,this)},void 0,!1,void 0,this),x(R0,{marginTop:1,children:x(Z0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return x(R0,{flexDirection:"column",paddingY:1,children:[x(R0,{marginBottom:1,children:[x(Z0,{bold:!0,color:"cyan",children:"插件管理器"},void 0,!1,void 0,this),x(Z0,{color:"gray",children:[" (共 ",b.total," 个插件)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),x(R0,{paddingLeft:2,marginBottom:1,children:x(Z0,{color:"gray",children:["启用: ",b.active," | 禁用: ",b.inactive," | 命令: ",b.commands," | 技能:"," ",b.skills," | 代理: ",b.agents]},void 0,!0,void 0,this)},void 0,!1,void 0,this),x(R0,{paddingLeft:2,marginBottom:1,children:x(Z0,{color:"gray",children:["来源策略: ",z.restrictToAllowedSources?"restricted":"open"," | Git SHA: ",z.requireGitCommitSha?"required":"optional"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),_.cli.length>0&&x(R0,{flexDirection:"column",marginBottom:1,children:[x(R0,{paddingLeft:1,children:[x(Z0,{bold:!0,color:"magenta",children:"CLI 指定"},void 0,!1,void 0,this),x(Z0,{color:"gray",children:" (--plugin-dir)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),_.cli.map((N)=>{let P=N.status==="active"?"[on]":"[off]",w=J.indexOf(N)===Z;return x(R0,{flexDirection:"column",paddingLeft:2,children:[x(Z0,{children:[x(Z0,{bold:!0,color:w?"cyan":"green",children:[w?"› ":" ",P," ",N.manifest.name]},void 0,!0,void 0,this),x(Z0,{color:"gray",children:[" v",N.manifest.version]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),x(R0,{paddingLeft:2,children:x(Z0,{color:"gray",children:N.manifest.description},void 0,!1,void 0,this)},void 0,!1,void 0,this),N.commands.length>0&&x(R0,{paddingLeft:2,children:x(Z0,{color:"blue",children:["命令:"," ",N.commands.map((R)=>`/${R.namespacedName}`).join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},N.manifest.name,!0,void 0,this)})]},void 0,!0,void 0,this),_.project.length>0&&x(R0,{flexDirection:"column",marginBottom:1,children:[x(R0,{paddingLeft:1,children:[x(Z0,{bold:!0,color:"yellow",children:"项目级"},void 0,!1,void 0,this),x(Z0,{color:"gray",children:" (.blade/plugins/)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),_.project.map((N)=>{let P=N.status==="active"?"[on]":"[off]",w=J.indexOf(N)===Z;return x(R0,{flexDirection:"column",paddingLeft:2,children:[x(Z0,{children:[x(Z0,{bold:!0,color:w?"cyan":"green",children:[w?"› ":" ",P," ",N.manifest.name]},void 0,!0,void 0,this),x(Z0,{color:"gray",children:[" v",N.manifest.version]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),x(R0,{paddingLeft:2,children:x(Z0,{color:"gray",children:N.manifest.description},void 0,!1,void 0,this)},void 0,!1,void 0,this),N.commands.length>0&&x(R0,{paddingLeft:2,children:x(Z0,{color:"blue",children:["命令:"," ",N.commands.map((R)=>`/${R.namespacedName}`).join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},N.manifest.name,!0,void 0,this)})]},void 0,!0,void 0,this),_.user.length>0&&x(R0,{flexDirection:"column",marginBottom:1,children:[x(R0,{paddingLeft:1,children:[x(Z0,{bold:!0,color:"cyan",children:"用户级"},void 0,!1,void 0,this),x(Z0,{color:"gray",children:" (~/.blade/plugins/)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),_.user.map((N)=>{let P=N.status==="active"?"[on]":"[off]",w=J.indexOf(N)===Z;return x(R0,{flexDirection:"column",paddingLeft:2,children:[x(Z0,{children:[x(Z0,{bold:!0,color:w?"cyan":"green",children:[w?"› ":" ",P," ",N.manifest.name]},void 0,!0,void 0,this),x(Z0,{color:"gray",children:[" v",N.manifest.version]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),x(R0,{paddingLeft:2,children:x(Z0,{color:"gray",children:N.manifest.description},void 0,!1,void 0,this)},void 0,!1,void 0,this),N.commands.length>0&&x(R0,{paddingLeft:2,children:x(Z0,{color:"blue",children:["命令:"," ",N.commands.map((R)=>`/${R.namespacedName}`).join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},N.manifest.name,!0,void 0,this)})]},void 0,!0,void 0,this),x(R0,{marginTop:1,paddingLeft:2,flexDirection:"column",children:[x(Z0,{color:"gray",children:"可用命令:"},void 0,!1,void 0,this),x(Z0,{color:"gray",dimColor:!0,children:[" ","• /plugins list - 列出所有插件"]},void 0,!0,void 0,this),x(Z0,{color:"gray",dimColor:!0,children:[" ","• /plugins info <name> - 显示插件详情"]},void 0,!0,void 0,this),x(Z0,{color:"gray",dimColor:!0,children:[" ","• /plugins install <url> - 安装插件"]},void 0,!0,void 0,this),x(Z0,{color:"gray",dimColor:!0,children:[" ","• /plugins enable/disable <name> - 启用/禁用插件"]},void 0,!0,void 0,this),x(Z0,{color:"gray",dimColor:!0,children:[" ","• /plugins policy show|set - 来源与 SHA 策略"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),x(R0,{marginTop:1,children:x(Z0,{dimColor:!0,children:"↑/↓ 选择 · Space/Enter 启停 · u 信任并更新 · x 卸载 · r 刷新 · ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this),q&&x(R0,{marginTop:1,children:x(Z0,{color:q.includes("失败")?"red":"cyan",children:q},void 0,!1,void 0,this)},void 0,!1,void 0,this),U&&x(Z0,{color:"gray",children:"处理中..."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{Box as $1,Text as Q1,useInput as Q4,useStdout as S5}from"ink";import f5 from"ink-text-input";import x6,{useCallback as F8,useMemo as D5,useState as U$}from"react";import{jsxDEV as W0}from"react/jsx-dev-runtime";var V5=x6.memo(({option:$,index:Q,isSelected:Y,isMultiSelect:J,isHighlighted:Z})=>W0($1,{flexDirection:"column",marginBottom:1,children:[W0(Q1,{color:Z?"yellow":Y?"green":void 0,bold:Z,children:[J?Y?"(*) ":"( ) ":Z?"> ":" ",Q+1,". ",$.label]},void 0,!0,void 0,this),W0($1,{marginLeft:4,children:W0(Q1,{color:"gray",children:$.description},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)),j5=x6.memo(({questions:$,answers:Q})=>W0($1,{flexDirection:"column",marginBottom:1,children:$.map((Y)=>{let J=Q[Y.header],Z=Array.isArray(J)?J.join(", "):J||"(no answer)";return W0($1,{marginBottom:1,children:[W0(Q1,{backgroundColor:"blue",color:"white",children:[" ",Y.header," "]},void 0,!0,void 0,this),W0(Q1,{color:"green",children:[" ",Z]},void 0,!0,void 0,this)]},Y.header,!0,void 0,this)})},void 0,!1,void 0,this)),J4=x6.memo(({questions:$,onComplete:Q,onCancel:Y})=>{let{stdout:J}=S5(),Z=J.columns||80,U=s0()==="confirmation-prompt",G=k0(!1),[q,K]=U$("answering"),[W,O]=U$(0),[B,_]=U$({}),[b,z]=U$(0),[H,F]=U$([]),[A,v]=U$(!1),[C,N]=U$(""),[P,w]=U$(0),R=$[W],T=D5(()=>{if(!R)return[];return[...R.options.map((d)=>({label:d.label,value:d.label,description:d.description})),{label:"Type something...",value:"__other__",description:"Enter custom response"}]},[R]),y=F8((d)=>{let I={...B,[R.header]:d};if(_(I),W<$.length-1)O(W+1),z(0),F([]),v(!1),N("");else K("submit"),w(0)},[B,R?.header,W,$.length]),S=F8((d)=>{let I=T[d];if(!I)return;if(I.value==="__other__"){v(!0);return}if(R.multiSelect)F((L)=>L.includes(I.value)?L.filter((M)=>M!==I.value):[...L,I.value]);else y(I.value)},[T,R?.multiSelect,y]),E=F8((d)=>{if(d.trim())y(d.trim())},[y]),c=F8(()=>{K("answering"),O(0),z(0),F([]),v(!1)},[]),Q0=F8(()=>{Q(B)},[B,Q]);if(Q4((d,I)=>{if(I.ctrl&&d==="c"||I.meta&&d==="c"){G();return}if(A){if(I.escape)v(!1),N("");return}if(I.escape){Y();return}let L=parseInt(d);if(L>=1&&L<=T.length){S(L-1);return}if(I.upArrow){z((M)=>M>0?M-1:T.length-1);return}if(I.downArrow||I.tab){z((M)=>M<T.length-1?M+1:0);return}if(I.return){if(R.multiSelect&&H.length>0)y(H);else S(b);return}if(d===" "&&R.multiSelect){let M=T[b];if(M&&M.value!=="__other__")F((V)=>V.includes(M.value)?V.filter((k)=>k!==M.value):[...V,M.value]);return}},{isActive:U&&q==="answering"&&!A}),Q4((d,I)=>{if(I.ctrl&&d==="c"||I.meta&&d==="c"){G();return}if(I.escape){Y();return}if(I.upArrow||I.downArrow||I.tab){w((L)=>L===0?1:0);return}if(I.return){if(P===0)Q0();else c();return}if(d.toLowerCase()==="y"){Q0();return}if(d.toLowerCase()==="e"){c();return}},{isActive:U&&q==="submit"}),q==="submit")return W0($1,{flexDirection:"column",borderStyle:"round",borderColor:U?"green":"gray",padding:1,width:Math.min(Z-4,80),children:[W0($1,{marginBottom:1,children:W0(Q1,{bold:!0,color:"green",children:"[OK] Review Your Answers"},void 0,!1,void 0,this)},void 0,!1,void 0,this),W0(j5,{questions:$,answers:B},void 0,!1,void 0,this),W0($1,{flexDirection:"column",marginTop:1,children:[W0(Q1,{color:P===0?"yellow":void 0,bold:P===0,children:[P===0?"> ":" ","[Y] Submit answers"]},void 0,!0,void 0,this),W0(Q1,{color:P===1?"yellow":void 0,bold:P===1,children:[P===1?"> ":" ","[E] Edit answers"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),W0($1,{marginTop:1,children:W0(Q1,{color:"gray",children:"Enter to confirm · Up/Down to navigate · Y/E for quick select"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(!R)return null;return W0($1,{flexDirection:"column",borderStyle:"round",borderColor:U?"cyan":"gray",padding:1,width:Math.min(Z-4,80),children:[W0($1,{marginBottom:1,children:[W0(Q1,{backgroundColor:"blue",color:"white",children:[" ",R.header," "]},void 0,!0,void 0,this),W0(Q1,{children:[" ",R.question]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),A?W0($1,{flexDirection:"column",marginTop:1,children:[W0(Q1,{color:"yellow",children:"Enter your response:"},void 0,!1,void 0,this),W0($1,{marginTop:1,children:[W0(Q1,{color:"cyan",children:"> "},void 0,!1,void 0,this),W0(f5,{value:C,onChange:N,onSubmit:E,focus:U},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W0($1,{marginTop:1,children:W0(Q1,{color:"gray",children:"(Press Enter to submit, ESC to go back)"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):W0($1,{flexDirection:"column",children:T.map((d,I)=>W0(V5,{option:d,index:I,isSelected:H.includes(d.value),isMultiSelect:R.multiSelect,isHighlighted:b===I},d.value,!1,void 0,this))},void 0,!1,void 0,this),!A&&W0($1,{marginTop:1,flexDirection:"column",children:[W0(Q1,{color:"gray",children:R.multiSelect?"Space to toggle · Enter to confirm · 1-9 for quick select":"Enter to select · Up/Down or Tab to navigate · 1-9 for quick select"},void 0,!1,void 0,this),R.multiSelect&&H.length>0&&W0(Q1,{color:"green",children:["Selected: ",H.join(", ")]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),$.length>1&&W0($1,{marginTop:1,children:W0(Q1,{color:"gray",children:["Question ",W+1," of ",$.length]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{basename as E5}from"node:path";import{Box as a$,Text as w1,useInput as h5}from"ink";import g5 from"ink-select-input";import{useEffect as u6,useMemo as r$,useRef as q4,useState as RQ}from"react";function Y4($){return`${$.projectPath}\x00${$.sessionId}`}function Z4($){return $.title?.trim()||`Session ${$.sessionId.slice(0,8)}`}function X4($){return $.taskDelivery?` | delivery:${$.taskDelivery.status}`:""}function U4($,Q){if(Q!=="fork")return[...$];return $.filter((Y)=>Y.relationType!=="subagent")}function G4($){return{title:$==="fork"?"选择要 fork 的会话:":"选择要恢复的会话:",instructions:"(Left/Right to page | Up/Down to select | Enter to confirm | Esc to cancel)"}}import{jsxDEV as d0}from"react/jsx-dev-runtime";function m5($){let Q=new Date($),J=new Date().getTime()-Q.getTime(),Z=Math.floor(J/86400000);if(Z===0)return`今天 ${Q.getHours().toString().padStart(2,"0")}:${Q.getMinutes().toString().padStart(2,"0")}`;if(Z===1)return"昨天";if(Z<7)return`${Z}天前`;return`${Q.getMonth()+1}/${Q.getDate()}`}function p5($){return E5($)}function c5($){switch($){case"queued":return"QUEUED";case"running":return"RUNNING";case"failed":return"FAILED";case"cancelled":return"CANCELLED";case"interrupted":return"INTERRUPTED";case"completed":return"DONE"}}var x5=({isSelected:$})=>d0(a$,{marginRight:1,children:d0(w1,{color:$?"cyan":"gray",children:$?">":" "},void 0,!1,void 0,this)},void 0,!1,void 0,this),u5=({isSelected:$,label:Q})=>d0(w1,{color:$?"cyan":"white",bold:$,children:Q},void 0,!1,void 0,this),H8=20,K4=({intent:$,sessions:Q,onSelect:Y,onCancel:J})=>{let[Z,X]=RQ([]),[U,G]=RQ(!1),[q,K]=RQ(0),[W,O]=RQ(!1),B=q4(!1),_=q4(!0);u6(()=>{return _.current=!0,()=>{_.current=!1}},[]);let z=s0()==="session-selector",H=k0(!1);h5((R,T)=>{if(T.ctrl&&R==="c"||T.meta&&R==="c"){H();return}if(B.current)return;if(T.escape&&J){J();return}if(T.leftArrow||R==="h"||R==="H"){if(q>0)K((y)=>y-1);return}if(T.rightArrow||R==="l"||R==="L"){if(q<C-1)K((y)=>y+1);return}},{isActive:z}),u6(()=>{if(Q){X(Q);return}(async()=>{G(!0);try{let T=await E0.listSessions({includeSubagents:!1});X(T)}catch(T){console.error("[SessionSelector] Failed to load sessions:",T),X([])}finally{G(!1)}})()},[Q]);let F=r$(()=>U4(Q||Z,$),[$,Q,Z]),A=r$(()=>G4($),[$]),v=r$(()=>{return F.map((R)=>{let T=p5(R.taskSourceProjectPath??R.projectPath),y=m5(R.lastMessageTime),S=Z4(R),E=`[${c5(R.taskStatus)}]`,c=R.gitBranch?` (${R.gitBranch})`:"",Q0=R.hasErrors?" [!]":"",d=R.taskRetriedFrom?` ↻ retry:${R.taskRetriedFrom.sessionId.slice(0,6)}`:R.relationType==="subagent"?" ↳ subagent":R.relationType==="fork"?" ↳ fork":"",I=R.taskIsolation==="worktree"?` | wt:${R.taskWorktreeBranch??"managed"}`:R.taskIsolation==="local"?" | local":"",L=R.taskDiffStat?` | ${R.taskDiffStat.changedFiles} files +${R.taskDiffStat.additions} -${R.taskDiffStat.deletions}`:"",M=R.taskStatus==="queued"&&R.taskQueuePosition?` | queue:${R.taskQueuePosition}/${R.taskQueueDepth??R.taskQueuePosition}`:"",V=X4(R);return{key:Y4(R),label:`${E} ${S} · ${y} | ${T}${c} | ${R.messageCount} 条消息${I}${M}${L}${V}${Q0}${d}`,value:R}})},[F]),C=r$(()=>Math.max(1,Math.ceil(v.length/H8)),[v.length]),N=r$(()=>{let R=q*H8;return v.slice(R,R+H8)},[v,q]),P=r$(()=>({start:q*H8+1,end:Math.min((q+1)*H8,v.length)}),[q,v.length]);u6(()=>{K(0)},[F.length]);let w=(R)=>{if(B.current)return;B.current=!0,O(!0);let T=()=>{if(!_.current)return;B.current=!1,O(!1)};Promise.resolve().then(()=>Y(R.value)).then(T,T)};if(U)return d0(a$,{flexDirection:"column",paddingX:2,paddingY:1,children:d0(w1,{children:"正在加载会话列表..."},void 0,!1,void 0,this)},void 0,!1,void 0,this);if(F.length===0)return d0(a$,{flexDirection:"column",paddingX:2,paddingY:1,children:[d0(w1,{color:"yellow",children:"没有找到历史会话"},void 0,!1,void 0,this),d0(w1,{dimColor:!0,children:[`
159
- `,"提示: 开始一次对话后,会话历史将保存到 ~/.blade/projects/"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);return d0(a$,{flexDirection:"column",paddingX:2,paddingY:1,children:[d0(w1,{bold:!0,color:"cyan",children:A.title},void 0,!1,void 0,this),d0(w1,{dimColor:!0,children:[`
160
- `,A.instructions,`
161
- `]},void 0,!0,void 0,this),d0(g5,{items:N,onSelect:w,isFocused:z&&!W,indicatorComponent:x5,itemComponent:u5},void 0,!1,void 0,this),W&&d0(w1,{color:"cyan",children:$==="fork"?"Forking…":"Resuming…"},void 0,!1,void 0,this),d0(a$,{marginTop:1,flexDirection:"column",children:[d0(w1,{dimColor:!0,children:["第 ",q+1,"/",C," 页 · 共 ",F.length," 个会话 · 显示"," ",P.start,"-",P.end]},void 0,!0,void 0,this),C>1&&d0(a$,{marginTop:1,children:[d0(w1,{color:q>0?"cyan":"gray",children:q>0?"<< 上一页":" "},void 0,!1,void 0,this),d0(w1,{children:" "},void 0,!1,void 0,this),d0(w1,{color:q<C-1?"cyan":"gray",children:q<C-1?"下一页 >>":""},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};import{Box as g0,Text as v0,useInput as d5}from"ink";import{jsxDEV as s}from"react/jsx-dev-runtime";function z4({onCancel:$}){let Q=M1(),J=O4({cwd:Q}).getAll(),Z=J.filter((q)=>q.source==="builtin"),X=J.filter((q)=>q.source==="user"),U=J.filter((q)=>q.source==="project"),G=k0(!1,$);if(d5((q,K)=>{if(K.escape)$?.();else if(K.ctrl&&q==="c"||K.meta&&q==="c")G()}),J.length===0)return s(g0,{flexDirection:"column",paddingY:1,children:[s(g0,{marginBottom:1,children:s(v0,{bold:!0,color:"cyan",children:"所有 Skills"},void 0,!1,void 0,this)},void 0,!1,void 0,this),s(g0,{paddingLeft:2,children:s(v0,{color:"gray",children:"没有找到任何 Skill"},void 0,!1,void 0,this)},void 0,!1,void 0,this),s(g0,{marginTop:1,paddingLeft:2,children:s(v0,{color:"gray",children:"配置文件位置: ~/.blade/skills/ 或 .blade/skills/"},void 0,!1,void 0,this)},void 0,!1,void 0,this),s(g0,{marginTop:1,children:s(v0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return s(g0,{flexDirection:"column",paddingY:1,children:[s(g0,{marginBottom:1,children:[s(v0,{bold:!0,color:"cyan",children:"所有 Skills"},void 0,!1,void 0,this),s(v0,{color:"gray",children:[" (找到 ",J.length," 个)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),U.length>0&&s(g0,{flexDirection:"column",marginBottom:1,children:[s(g0,{paddingLeft:1,children:[s(v0,{bold:!0,color:"yellow",children:"项目级"},void 0,!1,void 0,this),s(v0,{color:"gray",children:" (.blade/skills/)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),U.map((q)=>{let W=q.description.length>80?`${q.description.substring(0,80)}...`:q.description;return s(g0,{flexDirection:"column",paddingLeft:2,children:[s(v0,{children:[s(v0,{bold:!0,color:"green",children:["• ",q.name]},void 0,!0,void 0,this),s(v0,{color:"gray",children:[" - ",W]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),q.allowedTools&&q.allowedTools.length>0&&s(g0,{paddingLeft:2,children:s(v0,{color:"gray",children:["工具: ",q.allowedTools.join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this),s(g0,{paddingLeft:2,children:s(v0,{color:"gray",dimColor:!0,children:q.path},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},q.name,!0,void 0,this)})]},void 0,!0,void 0,this),X.length>0&&s(g0,{flexDirection:"column",marginBottom:1,children:[s(g0,{paddingLeft:1,children:[s(v0,{bold:!0,color:"yellow",children:"用户级"},void 0,!1,void 0,this),s(v0,{color:"gray",children:" (~/.blade/skills/)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),X.map((q)=>{let W=q.description.length>80?`${q.description.substring(0,80)}...`:q.description;return s(g0,{flexDirection:"column",paddingLeft:2,children:[s(v0,{children:[s(v0,{bold:!0,color:"green",children:["• ",q.name]},void 0,!0,void 0,this),s(v0,{color:"gray",children:[" - ",W]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),q.allowedTools&&q.allowedTools.length>0&&s(g0,{paddingLeft:2,children:s(v0,{color:"gray",children:["工具: ",q.allowedTools.join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this),s(g0,{paddingLeft:2,children:s(v0,{color:"gray",dimColor:!0,children:q.path},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},q.name,!0,void 0,this)})]},void 0,!0,void 0,this),Z.length>0&&s(g0,{flexDirection:"column",marginBottom:1,children:[s(g0,{paddingLeft:1,children:[s(v0,{bold:!0,color:"cyan",children:"内置"},void 0,!1,void 0,this),s(v0,{color:"gray",children:" (builtin)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Z.map((q)=>{let W=q.description.length>80?`${q.description.substring(0,80)}...`:q.description;return s(g0,{flexDirection:"column",paddingLeft:2,children:[s(v0,{children:[s(v0,{bold:!0,color:"green",children:["• ",q.name]},void 0,!0,void 0,this),s(v0,{color:"gray",children:[" - ",W]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),q.userInvocable&&s(g0,{paddingLeft:2,children:s(v0,{color:"blue",children:["命令: /",q.name]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},q.name,!0,void 0,this)})]},void 0,!0,void 0,this),s(g0,{marginTop:1,children:s(v0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{Box as _4,Text as u1}from"ink";import l5,{useEffect as r5,useMemo as a5,useState as N4}from"react";import{jsxDEV as z1,Fragment as H4}from"react/jsx-dev-runtime";var F4=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];function o5($){let Q=Math.floor($/1000);if(Q<60)return`${Q}s`;let Y=Math.floor(Q/60),J=Q%60;return`${Y}m ${J}s`}var W4=l5.memo(()=>{let $=$0((K)=>K.app.subagentProgresses),Q=$0((K)=>K.app.subagentProgress),Y=b0(),[J,Z]=N4(0),[X,U]=N4(()=>Date.now()),G=a5(()=>{let K=Object.values($);return K.length>0?K:Q?[Q]:[]},[Q,$]),q=G.some((K)=>K.status==="running");if(r5(()=>{if(!q){Z(0);return}let K=setInterval(()=>{Z((O)=>(O+1)%F4.length)},80),W=setInterval(()=>{U(Date.now())},1000);return()=>{clearInterval(K),clearInterval(W)}},[q]),G.length===0)return null;return z1(_4,{paddingX:2,paddingY:0,flexDirection:"column",children:G.map((K)=>{let W=K.status==="running"?F4[J]:K.status==="completed"?"[OK]":"[X]",O=K.status==="running"?Y.colors.info:K.status==="completed"?Y.colors.success:Y.colors.error,B=Math.max(0,X-K.startTime);return z1(_4,{flexDirection:"row",gap:1,children:[z1(u1,{color:O,bold:!0,children:W},void 0,!1,void 0,this),z1(u1,{color:Y.colors.muted,children:"Subagent"},void 0,!1,void 0,this),z1(u1,{color:Y.colors.text.primary,bold:!0,children:K.type},void 0,!1,void 0,this),z1(u1,{color:Y.colors.muted,children:"|"},void 0,!1,void 0,this),z1(u1,{color:Y.colors.text.secondary,children:K.description},void 0,!1,void 0,this),K.currentTool&&z1(H4,{children:[z1(u1,{color:Y.colors.muted,children:"|"},void 0,!1,void 0,this),z1(u1,{color:Y.colors.warning,children:K.currentTool},void 0,!1,void 0,this)]},void 0,!0,void 0,this),K.status==="running"&&B>0&&z1(H4,{children:[z1(u1,{color:Y.colors.muted,children:"|"},void 0,!1,void 0,this),z1(u1,{color:Y.colors.info,children:o5(B)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},K.id,!0,void 0,this)})},void 0,!1,void 0,this)});import{useMemoizedFn as i5}from"ahooks";import{Box as T1,Text as l,useInput as n5}from"ink";import t5 from"ink-select-input";import{useState as L4}from"react";import{jsxDEV as p}from"react/jsx-dev-runtime";var B4=M$.map(($)=>({label:$.label,value:$.id})),s5=({theme:$})=>{let{colors:Q}=$;return p(T1,{flexDirection:"column",paddingLeft:1,paddingTop:1,children:[p(l,{bold:!0,color:Q.text.primary,children:"代码预览"},void 0,!1,void 0,this),p(l,{children:" "},void 0,!1,void 0,this),p(l,{color:Q.syntax.comment,children:"# function"},void 0,!1,void 0,this),p(l,{children:[p(l,{color:Q.syntax.keyword,children:"def"},void 0,!1,void 0,this)," ",p(l,{color:Q.syntax.function,children:"fibonacci"},void 0,!1,void 0,this),p(l,{color:Q.text.primary,children:"("},void 0,!1,void 0,this),p(l,{color:Q.syntax.variable,children:"n"},void 0,!1,void 0,this),p(l,{color:Q.text.primary,children:"):"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),p(l,{children:[" ",p(l,{color:Q.syntax.variable,children:"a"},void 0,!1,void 0,this),p(l,{color:Q.syntax.operator,children:","},void 0,!1,void 0,this)," ",p(l,{color:Q.syntax.variable,children:"b"},void 0,!1,void 0,this)," ",p(l,{color:Q.syntax.operator,children:"="},void 0,!1,void 0,this)," ",p(l,{color:Q.syntax.number,children:"0"},void 0,!1,void 0,this),p(l,{color:Q.syntax.operator,children:","},void 0,!1,void 0,this)," ",p(l,{color:Q.syntax.number,children:"1"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),p(l,{children:[" ",p(l,{color:Q.syntax.keyword,children:"for"},void 0,!1,void 0,this)," ",p(l,{color:Q.syntax.variable,children:"_"},void 0,!1,void 0,this)," ",p(l,{color:Q.syntax.keyword,children:"in"},void 0,!1,void 0,this)," ",p(l,{color:Q.syntax.function,children:"range"},void 0,!1,void 0,this),p(l,{color:Q.text.primary,children:"("},void 0,!1,void 0,this),p(l,{color:Q.syntax.variable,children:"n"},void 0,!1,void 0,this),p(l,{color:Q.text.primary,children:"):"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),p(l,{children:[" ",p(l,{color:Q.syntax.variable,children:"a"},void 0,!1,void 0,this),p(l,{color:Q.syntax.operator,children:","},void 0,!1,void 0,this)," ",p(l,{color:Q.syntax.variable,children:"b"},void 0,!1,void 0,this)," ",p(l,{color:Q.syntax.operator,children:"="},void 0,!1,void 0,this)," ",p(l,{color:Q.syntax.variable,children:"b"},void 0,!1,void 0,this),p(l,{color:Q.syntax.operator,children:","},void 0,!1,void 0,this)," ",p(l,{color:Q.syntax.variable,children:"a"},void 0,!1,void 0,this)," ",p(l,{color:Q.syntax.operator,children:"+"},void 0,!1,void 0,this)," ",p(l,{color:Q.syntax.variable,children:"b"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),p(l,{children:[" ",p(l,{color:Q.syntax.keyword,children:"return"},void 0,!1,void 0,this)," ",p(l,{color:Q.syntax.variable,children:"a"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),p(l,{children:" "},void 0,!1,void 0,this),p(l,{color:Q.error,children:["- print(",p(l,{color:Q.syntax.string,children:'"Hello, "'},void 0,!1,void 0,this)," + name)"]},void 0,!0,void 0,this),p(l,{color:Q.success,children:["+ print(",p(l,{color:Q.syntax.string,children:['f"Hello, ',"{","name","}",'"']},void 0,!0,void 0,this),")"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},e5=({theme:$})=>{let{colors:Q}=$;return p(T1,{flexDirection:"column",paddingLeft:1,paddingTop:1,children:[p(l,{children:" "},void 0,!1,void 0,this),p(l,{bold:!0,color:Q.text.primary,children:"颜色配置"},void 0,!1,void 0,this),p(l,{children:" "},void 0,!1,void 0,this),p(l,{children:[p(l,{color:Q.text.muted,children:"Primary: "},void 0,!1,void 0,this),p(l,{color:Q.primary,children:Q.primary},void 0,!1,void 0,this)]},void 0,!0,void 0,this),p(l,{children:[p(l,{color:Q.text.muted,children:"Success: "},void 0,!1,void 0,this),p(l,{color:Q.success,children:Q.success},void 0,!1,void 0,this)]},void 0,!0,void 0,this),p(l,{children:[p(l,{color:Q.text.muted,children:"Error: "},void 0,!1,void 0,this),p(l,{color:Q.error,children:Q.error},void 0,!1,void 0,this)]},void 0,!0,void 0,this),p(l,{children:[p(l,{color:Q.text.muted,children:"Warning: "},void 0,!1,void 0,this),p(l,{color:Q.warning,children:Q.warning},void 0,!1,void 0,this)]},void 0,!0,void 0,this),p(l,{children:[p(l,{color:Q.text.muted,children:"Info: "},void 0,!1,void 0,this),p(l,{color:Q.info,children:Q.info},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},w4=()=>{let $=a1(),Q=l0.getCurrentThemeName(),Y=M$.findIndex((b)=>b.label===Q),J=Y>=0?M$[Y].theme:M$[0].theme,[Z,X]=L4(J),[U,G]=L4(!1),q=i5(async(b)=>{if(U)return;G(!0);try{await u0().setTheme(b.value),$.closeModal()}catch(z){console.error("主题切换失败:",z instanceof Error?z.message:z)}finally{G(!1)}}),K=(b)=>{let z=M$.find((H)=>H.id===b.value);if(z)X(z.theme)},O=s0()==="theme-selector",B=k0(!1);n5((b,z)=>{if(z.ctrl&&b==="c"||z.meta&&b==="c"){B();return}if(z.escape&&!U)$.closeModal()},{isActive:O});let _=(b)=>{let{isSelected:z,label:H}=b,A=H===Q?"[OK]":" ";return p(l,{color:z?Z.colors.primary:Z.colors.text.primary,children:[A," ",H]},void 0,!0,void 0,this)};return p(T1,{flexDirection:"column",height:"100%",children:[p(T1,{paddingX:2,paddingY:1,borderStyle:"single",borderColor:Z.colors.border.light,children:p(l,{bold:!0,color:Z.colors.primary,children:"主题选择器"},void 0,!1,void 0,this)},void 0,!1,void 0,this),p(T1,{flexDirection:"row",flexGrow:1,children:[p(T1,{width:"40%",borderStyle:"single",borderColor:Z.colors.border.light,paddingX:1,children:p(T1,{flexDirection:"column",children:[p(T1,{paddingTop:1,paddingBottom:1,children:p(l,{bold:!0,color:Z.colors.text.primary,children:["可用主题 (",B4.length,")"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),p(t5,{items:B4,initialIndex:Y>=0?Y:0,onSelect:q,onHighlight:K,itemComponent:_},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),p(T1,{width:"60%",flexDirection:"column",borderStyle:"single",borderColor:Z.colors.border.light,children:[p(s5,{theme:Z},void 0,!1,void 0,this),p(e5,{theme:Z},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),p(T1,{paddingX:2,paddingY:1,borderStyle:"single",borderColor:Z.colors.border.light,children:p(l,{color:Z.colors.text.muted,children:U?"正在保存...":"Enter: 选择主题 | Esc: 取消"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as P0}from"react/jsx-dev-runtime";var U1=i1("UI"),R4=({debug:$,continue:Q,...Y})=>{if($)U1.debug("[Debug] BladeInterface props:",{permissionMode:Y.permissionMode,yolo:Y.yolo,maxTurns:Y.maxTurns,continue:Q});let J=PQ(!1),Z=PQ(!1),X=PQ(!1),U=PQ(null),G=t6(),q=s6(),K=P8(),W=Q2(),O=$2(),B=a1(),_=r1(),b=M1(),z=U2(),H=T$(),F=o1(),A=X2();q$(()=>{if(l0.getCurrentThemeName()!==A)try{l0.setTheme(A)}catch{}},[A]);let v=G==="ready",C=G==="needsSetup",N=G==="idle",P=$X(()=>Y.agents?A4(Y.agents):void 0,[Y.agents]),{confirmationState:w,confirmationHandler:R,handleResponse:T,dismissAll:y}=g2(),{executeCommand:S,handleAbort:E,cleanupAgent:c}=V2(Y.systemPrompt,Y.appendSystemPrompt,R,Y.maxTurns,y,P),{getPreviousCommand:Q0,getNextCommand:d,addToHistory:I}=E2();$9();let L=p2("",0),M=t0(async()=>{let r=H,U0;if(r==="default")U0="autoEdit";else if(r==="autoEdit")U0="plan";else if(r==="plan")U0="default";else U0="default";try{await u0().setPermissionMode(U0)}catch(T0){U1.error("权限模式切换失败:",T0 instanceof Error?T0.message:T0)}}),V=t0(async(r)=>{try{let U0={displayName:r.displayName,provider:r.provider,model:r.model,overrides:r.overrides};if(r.modelProvider)await u0().addModelWithProvider(U0,r.modelProvider);else await u0().addModel(U0);B.setInitializationStatus("ready")}catch(U0){throw U1.error("初始化配置保存失败:",U0 instanceof Error?U0.message:U0),U0}}),k=t0(()=>{if(K==="shortcuts")B.closeModal();else B.setActiveModal("shortcuts")}),u=t0(async(r,U0,T0)=>{return g8({intent:U0,session:r,newSessionId:T0?.newSessionId,announceFork:T0?.announceFork},b,_,c)}),j=t0(async(r,U0)=>{let S1=(await h8(U0,b)).filter((c0)=>c0.sessionId===r);if(S1.length===0)throw Error(`Session not found: ${r}`);if(S1.length>1)throw Error(`Multiple workspaces contain session ${r}; use the session selector`);return S1[0]}),{showSuggestions:m,suggestions:f,selectedSuggestionIndex:n}=e2(L,S,Q0,d,I,E,F,M,k,K==="shortcuts");q$(()=>{if(L.value&&K==="shortcuts")B.closeModal()},[L.value,K,B]);let _0=t0(async()=>{X.current=!0;try{let r=Y.forkSession?"fork":"resume",U0=await h8(r,b);if(U0.length===0){if(Y.forkSession){U1.error("没有可供 fork 的历史会话"),I1(1);return}_.addAssistantMessage("没有找到历史会话,开始新对话。");return}let T0=U0[0];await u(T0,r,{newSessionId:Y.forkSession?Y.sessionId:void 0,announceFork:Y.forkSession?!1:void 0})}catch(r){if(U1.error("[BladeInterface] 继续会话失败:",r),Y.forkSession){I1(1);return}_.addAssistantMessage("继续会话失败,开始新对话。")}}),N0=t0(async()=>{X.current=!0;try{if(typeof Y.resume==="string"&&Y.resume!=="true"){let T0=Y.forkSession?"fork":"resume",w8=await j(Y.resume,T0);await u(w8,T0,{newSessionId:Y.forkSession?Y.sessionId:void 0,announceFork:Y.forkSession?!1:void 0});return}let r=Y.forkSession?"fork":"resume",U0=await h8(r,b);if(U0.length===0)U1.error("没有找到历史会话"),I1(1);B.showSessionSelector(U0,r)}catch(r){U1.error("[BladeInterface] 加载会话失败:",r),I1(1)}});q$(()=>{if(J.current)return;if(Q){J.current=!0,_0();return}if(Y.resume)J.current=!0,N0()},[Q,Y.resume,_0,N0]);let m0=t0(async(r)=>{let U0=w.details?.type;if(U0==="enterPlanMode"&&r.approved)try{await u0().setPermissionMode("plan"),U1.debug("[BladeInterface] Entered Plan mode")}catch(T0){U1.error("[BladeInterface] Failed to enter Plan mode:",T0)}if(U0==="exitPlanMode"&&r.approved)U1.debug("[BladeInterface] ExitPlanMode approved, Store auto-synced");T(r)}),D0=t0(()=>{_.addAssistantMessage("设置已取消"),_.addAssistantMessage("Blade 需要 API 配置才能正常工作。"),_.addAssistantMessage("您可以稍后运行 Blade 重新进入设置向导。"),I1(0)}),w0=t0(()=>{B.closeModal()}),_1=t0(async(r)=>{try{await u(r,W?.intent??"resume"),B.closeModal()}catch(U0){U1.error("[BladeInterface] Failed to restore session:",U0),_.addAssistantMessage(`会话操作失败: ${U0 instanceof Error?U0.message:"未知错误"}`),B.closeModal()}}),N1=t0(()=>{if(Y.resume)I1(0);else B.closeModal()}),v$=t0((r)=>{B.showModelEditWizard(r)}),G1=t0((r)=>{_.addAssistantMessage(`已添加模型配置: ${r.displayName??r.model},并已切换到该模型`),w0()}),CQ=t0((r)=>{_.addAssistantMessage(`已更新模型配置: ${r.displayName??r.model}`),w0()});q$(()=>{if(C){z.setFocus("model-config-wizard");return}if(w.isVisible)z.setFocus("confirmation-prompt");else if(K==="sessionSelector")z.setFocus("session-selector");else if(K==="themeSelector")z.setFocus("theme-selector");else if(K==="modelSelector")z.setFocus("model-selector");else if(K==="modelAddWizard"||K==="modelEditWizard")z.setFocus("model-config-wizard");else if(K==="permissionsManager")z.setFocus("permissions-manager");else if(K==="agentsManager")z.setFocus("agents-manager");else if(K==="agentCreationWizard")z.setFocus("agent-creation-wizard");else if(K==="hooksManager")z.setFocus("hooks-manager");else if(K==="shortcuts")z.setFocus("main-input");else z.setFocus("main-input")},[C,w.isVisible,K,z.setFocus]),q$(()=>{if(!v||X.current)return;if(b4().length>0){X.current=!0;return}X.current=!0,_.addAssistantMessage("请输入您的问题,我将为您提供帮助。")},[v]),q$(()=>{if(!q)return;if(U.current===q)return;if(U.current=q,G==="error")_.addAssistantMessage(`初始化失败: ${q}`);else _.addAssistantMessage(`${q}`),_.addAssistantMessage("请重新尝试设置,或检查文件权限")},[q,G,_.addAssistantMessage]);let O$=t0(async(r)=>{try{await S({displayText:r,text:r,images:[],parts:[{type:"text",text:r}]})}catch(U0){let T0=U0 instanceof Error?U0.message:"无法发送初始消息";_.addAssistantMessage(`初始消息发送失败:${T0}`)}});q$(()=>{let r=Y.initialMessage?.trim();if(!r||Z.current||!v||C)return;Z.current=!0,I(r),O$(r)},[Y.initialMessage,v,C,S,I]);let TQ=t0(async(r)=>{try{await u0().setPermissionMode(r)}catch(U0){U1.error("权限模式初始化失败:",U0 instanceof Error?U0.message:U0)}});if(q$(()=>{let r=Y.permissionMode;if($)U1.debug("[Debug] permissionMode from CLI:",r),U1.debug("[Debug] current permissionMode:",H);if(!r||r===H)return;TQ(r)},[Y.permissionMode,H]),N)return null;if(C)return P0(c6,{mode:"setup",onComplete:V,onCancel:D0},void 0,!1,void 0,this);if($)U1.debug("[Debug] 渲染主界面,条件检查:",{confirmationVisible:w.isVisible,activeModal:K});let X0=K==="modelSelector",C0=O,e=K==="modelAddWizard"?"add":K==="modelEditWizard"&&C0?"edit":null,O0=X0||Boolean(e),x0=K==="agentsManager",o0=K==="agentCreationWizard",p0=K==="skillsManager",kQ=K==="pluginsManager",n$=C0?{displayName:C0.displayName,provider:C0.provider,model:C0.model,overrides:C0.overrides}:void 0,L8=w.isVisible&&w.details?w.details.type==="mcpElicitation"&&w.details.mcpElicitation?P0(zJ,{details:w.details.mcpElicitation,onComplete:(r,U0)=>m0({approved:r.action==="accept",elicitation:r,...U0?{openExternalUrl:!0}:{}})},void 0,!1,void 0,this):w.details.type==="askUserQuestion"&&w.details.questions?P0(J4,{questions:w.details.questions,onComplete:(r)=>m0({approved:!0,answers:r}),onCancel:()=>m0({approved:!1})},void 0,!1,void 0,this):P0(c9,{details:w.details,onResponse:m0},void 0,!1,void 0,this):K==="themeSelector"?P0(w4,{},void 0,!1,void 0,this):K==="permissionsManager"?P0(oJ,{onClose:w0},void 0,!1,void 0,this):K==="sessionSelector"?P0(K4,{intent:W?.intent??"resume",sessions:W?.sessions,onSelect:_1,onCancel:N1},void 0,!1,void 0,this):K==="hooksManager"?P0(u9,{onClose:w0},void 0,!1,void 0,this):null,B8=Boolean(L8);return P0(G$,{flexDirection:"column",width:"100%",overflow:"hidden",children:[L8,P0(G$,{flexDirection:"column",display:B8?"none":"flex",children:[P0(vJ,{},void 0,!1,void 0,this),P0(W4,{},void 0,!1,void 0,this),P0(GJ,{paused:B8},void 0,!1,void 0,this),P0($J,{input:L.value,cursorPosition:L.cursorPosition,onChange:L.setValue,onChangeCursorPosition:L.setCursorPosition,onAddPasteMapping:L.addPasteMapping,onAddImagePasteMapping:L.addImagePasteMapping},void 0,!1,void 0,this),X0&&P0(G$,{marginTop:1,paddingX:2,children:P0(CJ,{onClose:w0,onEdit:v$},void 0,!1,void 0,this)},void 0,!1,void 0,this),e&&P0(G$,{marginTop:1,paddingX:2,children:P0(c6,{mode:e,modelId:C0?.id,initialConfig:e==="edit"?n$:void 0,onComplete:e==="edit"?CQ:G1,onCancel:w0},void 0,!1,void 0,this)},void 0,!1,void 0,this),x0&&P0(G$,{marginTop:1,paddingX:2,children:P0(U9,{workspaceRoot:b,onComplete:w0,onCancel:w0},void 0,!1,void 0,this)},void 0,!1,void 0,this),o0&&P0(G$,{marginTop:1,paddingX:2,children:P0(X8,{onComplete:w0,onCancel:w0},void 0,!1,void 0,this)},void 0,!1,void 0,this),p0&&P0(G$,{marginTop:1,paddingX:2,children:P0(z4,{onComplete:w0,onCancel:w0},void 0,!1,void 0,this)},void 0,!1,void 0,this),kQ&&P0(G$,{marginTop:1,paddingX:2,children:P0($4,{workspaceRoot:b,onComplete:w0,onCancel:w0},void 0,!1,void 0,this)},void 0,!1,void 0,this),P0(_9,{suggestions:f,selectedIndex:n,visible:m&&!O0},void 0,!1,void 0,this),P0(z9,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};import{Box as QX,Text as K$}from"ink";import JX from"react";import{jsxDEV as d1}from"react/jsx-dev-runtime";class W8 extends JX.Component{constructor($){super($);this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError($){return{hasError:!0,error:$,errorInfo:null}}componentDidCatch($,Q){this.setState({error:$,errorInfo:Q}),console.error("未捕获的错误:",$,Q)}render(){if(this.state.hasError)return d1(QX,{flexDirection:"column",padding:1,borderStyle:"round",borderColor:"red",children:[d1(K$,{color:"red",children:"应用发生错误"},void 0,!1,void 0,this),d1(K$,{children:" "},void 0,!1,void 0,this),d1(K$,{color:"red",children:this.state.error?.message},void 0,!1,void 0,this),d1(K$,{children:" "},void 0,!1,void 0,this),d1(K$,{color:"gray",children:"错误详情:"},void 0,!1,void 0,this),d1(K$,{color:"gray",children:this.state.error?.stack},void 0,!1,void 0,this),d1(K$,{children:" "},void 0,!1,void 0,this),d1(K$,{color:"yellow",children:"请重启应用或联系开发者"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return this.props.children}}import{Box as I$,Text as l1,useInput as YX}from"ink";import{useState as d6}from"react";import{jsxDEV as J1}from"react/jsx-dev-runtime";var yQ=[{key:"update",label:"Update now",description:`runs \`${y4()}\``},{key:"skip",label:"Skip",description:""},{key:"skip_until_next",label:"Skip until next version",description:""}],I4=({versionInfo:$,onComplete:Q})=>{let[Y,J]=d6(0),[Z,X]=d6(!1),[U,G]=d6(null);YX((K,W)=>{if(W.ctrl&&K==="c"){Y8().shutdown("SIGINT",0);return}if(Z||U)return;if(W.upArrow||K==="k")J((O)=>O>0?O-1:yQ.length-1);else if(W.downArrow||K==="j")J((O)=>O<yQ.length-1?O+1:0);else if(W.return)q(yQ[Y].key);else if(K==="1")q("update");else if(K==="2")q("skip");else if(K==="3")q("skip_until_next")});let q=async(K)=>{switch(K){case"update":{X(!0);let W=await M4();G(W.message),setTimeout(()=>{Y8().shutdown("SIGINT",0)},1500);break}case"skip":Q();break;case"skip_until_next":if($.latestVersion)await P4($.latestVersion);Q();break}};if(U)return J1(I$,{flexDirection:"column",marginY:1,children:J1(l1,{children:U},void 0,!1,void 0,this)},void 0,!1,void 0,this);if(Z)return J1(I$,{flexDirection:"column",marginY:1,children:J1(l1,{color:"cyan",children:"Updating..."},void 0,!1,void 0,this)},void 0,!1,void 0,this);return J1(I$,{flexDirection:"column",marginY:1,children:[J1(l1,{color:"yellow",bold:!0,children:["Update available! ",J1(l1,{color:"gray",children:[$.currentVersion," ","->"," ",$.latestVersion]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),J1(I$,{marginTop:1,children:J1(l1,{color:"gray",children:["Release notes:"," ",J1(l1,{color:"cyan",underline:!0,children:$.releaseNotesUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),J1(I$,{flexDirection:"column",marginTop:1,children:yQ.map((K,W)=>{let O=W===Y,B=O?"› ":" ",_=`${W+1}. `;return J1(I$,{children:J1(l1,{color:O?"cyan":void 0,children:[B,_,K.label,K.description&&J1(l1,{color:"gray",children:[" (",K.description,")"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},K.key,!1,void 0,this)})},void 0,!1,void 0,this),J1(I$,{marginTop:1,children:J1(l1,{color:"gray",children:"Press enter to continue"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{Box as MQ,Text as o$,useInput as ZX}from"ink";import{useState as v4}from"react";import{jsxDEV as k1}from"react/jsx-dev-runtime";var C4=({status:$,onTrust:Q,onContinueSafely:Y})=>{let J=l0.getTheme(),[Z,X]=v4(!1),[U,G]=v4(null);return ZX((q,K)=>{if(Z)return;if(K.return||q.toLowerCase()==="t"){X(!0),G(null),Q().catch((W)=>{G(W instanceof Error?W.message:"Failed to trust workspace"),X(!1)});return}if(q.toLowerCase()==="s"||K.escape)X(!0),G(null),Y().catch((W)=>{G(W instanceof Error?W.message:"Failed to continue safely"),X(!1)})}),k1(MQ,{flexDirection:"column",paddingX:1,children:[k1(o$,{bold:!0,color:J.colors.warning,children:"Workspace review required"},void 0,!1,void 0,this),k1(o$,{dimColor:!0,children:$.projectPath},void 0,!1,void 0,this),k1(MQ,{marginTop:1,flexDirection:"column",children:[k1(o$,{children:"This project contains configuration that can change models, start MCP processes, relax permissions, inject environment variables, or load instructions, commands, skills, agents, and plugins."},void 0,!1,void 0,this),$.sources.map((q)=>k1(o$,{children:[" ",q.path," · ",q.effects.length," effect(s)"]},`${q.kind}:${q.path}`,!0,void 0,this))]},void 0,!0,void 0,this),U&&k1(MQ,{marginTop:1,children:k1(o$,{color:J.colors.error,children:U},void 0,!1,void 0,this)},void 0,!1,void 0,this),k1(MQ,{marginTop:1,children:k1(o$,{bold:!0,children:Z?"Applying decision...":"[Enter/T] Trust and load [S/Esc] Continue safely"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};function T4($){return($ instanceof Error?$.message:String($)).replace(/sk-[a-zA-Z0-9]{32,}/g,"sk-***").replace(/apiKey['":\s]+[a-zA-Z0-9-_]+/gi,"apiKey: ***").replace(/API_KEY['":\s=]+[a-zA-Z0-9-_]+/gi,"API_KEY=***")}import{jsxDEV as i$}from"react/jsx-dev-runtime";function UX($){if(Y1().config.actions.setConfig($),$.debug)console.log("[Debug] 模型配置检查通过,准备就绪");r0().setInitializationStatus("ready")}var KF=($)=>{let[Q,Y]=vQ(!1),[J,Z]=vQ(null),[X,U]=vQ(!1),[G,q]=vQ(null),K=IQ((_,b)=>{let z=_ instanceof Error?_.message:String(_);if(r0().setInitializationError(z),r0().setInitializationStatus("error"),Y(!0),b)console.error("[FAIL] 应用初始化失败:",z)}),W=IQ(async()=>{try{let _=Y1().config.config??S4,b=f4(_,$);if(UX(b),b.resumeSessionId)D4().restoreSession(b.resumeSessionId,[]);if(b.debug)console.error("[Debug] 运行时配置:",b);let z=b.theme;if(z&&l0.hasTheme(z)){if(l0.setTheme(z),$.debug)console.log(`[OK] 已加载主题: ${z}`)}try{F1.getInstance().loadConfig(b.hooks||{},A0());let F=await V4(A0());if($.debug&&b.hooks?.enabled)console.log("[OK] Hooks 系统已启用");if($.debug)console.log(`[OK] Workspace resources: ${F.subagents.getAllNames().length} agents, ${F.skills.size} skills, ${F.commands.getCommandCount()+F.commands.getPluginCommandCount()} commands, ${F.plugins.getAll().length} plugins`);let v=Y1().session.sessionId;k4(v)}catch(H){if($.debug)console.warn("Hooks 初始化失败:",T4(H))}p8(async()=>{await E4.getInstance().killAll(),await j4.getInstance().disconnectAll(),F1.getInstance().cleanup()}),Y(!0)}catch(_){K(_,!!$.debug)}}),O=IQ(async()=>{let _=await l6.getInstance().getStatus(A0());if(_.state==="untrusted"||_.state==="error"){q(_);return}await W()}),B=IQ(async()=>{if($.versionCheckPromise){let _=await $.versionCheckPromise;if(_){Z(_),U(!0);return}}await O()});if(XX(()=>{B()},[]),X&&J)return i$(W8,{children:i$(I4,{versionInfo:J,onComplete:()=>{U(!1),O()}},void 0,!1,void 0,this)},void 0,!1,void 0,this);if(G)return i$(W8,{children:i$(C4,{status:G,onTrust:async()=>{await l6.getInstance().trust(A0()),await h4(),q(null),await W()},onContinueSafely:async()=>{q(null),await W()}},void 0,!1,void 0,this)},void 0,!1,void 0,this);if(!Q)return null;return i$(W8,{children:i$(R4,{...$},void 0,!1,void 0,this)},void 0,!1,void 0,this)};export{KF as AppWrapper};