blade-code 0.10.102 → 0.10.103
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/chunk-03qymy9e.js +1 -0
- package/dist/{chunk-cpk84yrx.js → chunk-07w0qapm.js} +1 -1
- package/dist/{chunk-9n5ystr6.js → chunk-0aa40zbs.js} +3 -3
- package/dist/{chunk-9sx3vsyj.js → chunk-0hr050ck.js} +1 -1
- package/dist/chunk-0kdrgmyy.js +1 -0
- package/dist/{chunk-qw57eqns.js → chunk-14bs89sm.js} +2 -2
- package/dist/{chunk-kwkkcs4y.js → chunk-181ef74x.js} +1 -1
- package/dist/{chunk-c6tq09mt.js → chunk-41cg66y0.js} +1 -1
- package/dist/{chunk-p0rvgzpx.js → chunk-41ympwz1.js} +1 -1
- package/dist/{chunk-anez8ekm.js → chunk-42bcht8b.js} +2 -2
- package/dist/{chunk-39qzk9nm.js → chunk-47e6tdbb.js} +1 -1
- package/dist/{chunk-enwtex3j.js → chunk-4qfke0gd.js} +2 -2
- package/dist/chunk-5sk7q6pw.js +1 -0
- package/dist/chunk-6v10cs0h.js +1 -0
- package/dist/{chunk-4fmtv329.js → chunk-6wsvgk20.js} +1 -1
- package/dist/chunk-7ab7jcvn.js +1 -0
- package/dist/{chunk-j00px1es.js → chunk-7fz3w4rk.js} +1 -1
- package/dist/chunk-8zjn51fr.js +1 -0
- package/dist/{chunk-ykkqywtq.js → chunk-946wkbmw.js} +1 -1
- package/dist/{chunk-k7vv9vne.js → chunk-9p20hhs0.js} +1 -1
- package/dist/{chunk-vw328ehw.js → chunk-a7ejfmtc.js} +1 -1
- package/dist/chunk-a8x3xygs.js +1 -0
- package/dist/{chunk-6kb69vkx.js → chunk-aa5zmwd9.js} +3 -3
- package/dist/{chunk-0zhdjaen.js → chunk-abd57h72.js} +1 -1
- package/dist/{chunk-rkk39efr.js → chunk-afa35v3f.js} +1 -1
- package/dist/{chunk-6r6yzw44.js → chunk-b0j9v359.js} +267 -265
- package/dist/{chunk-qjeadpj2.js → chunk-bt18xsc6.js} +1 -1
- package/dist/chunk-bx82y5ce.js +1 -0
- package/dist/chunk-c475tfqf.js +2 -0
- package/dist/{chunk-9b0896bm.js → chunk-c479s9v2.js} +1 -1
- package/dist/{chunk-a5jv8pn9.js → chunk-cpex23zk.js} +1 -1
- package/dist/{chunk-v6hffjwc.js → chunk-e1tt6b1w.js} +2 -2
- package/dist/{chunk-czcxx8tb.js → chunk-f3426b1c.js} +1 -1
- package/dist/{chunk-19xfer55.js → chunk-f945dzj6.js} +2 -2
- package/dist/{chunk-w9xfks7f.js → chunk-fhfzdyba.js} +1 -1
- package/dist/{chunk-qcy79mva.js → chunk-fva7jnjy.js} +1 -1
- package/dist/chunk-fw2x9p4c.js +6 -0
- package/dist/{chunk-pdqczfn3.js → chunk-gr80w0vh.js} +1 -1
- package/dist/{chunk-zxhv8xfp.js → chunk-gxgq70gm.js} +1 -1
- package/dist/{chunk-10taec1j.js → chunk-j2dyprdy.js} +1 -1
- package/dist/{chunk-ffp2rn7f.js → chunk-jaswqpe7.js} +1 -1
- package/dist/{chunk-1wgese5c.js → chunk-k9fveqq6.js} +1 -1
- package/dist/chunk-kdjtxpxw.js +1 -0
- package/dist/chunk-kf7whgr7.js +2 -0
- package/dist/{chunk-fn9cse83.js → chunk-khtxprbv.js} +1 -1
- package/dist/{chunk-m4wnqx0e.js → chunk-mgsvn9v4.js} +2 -2
- package/dist/{chunk-d8wzc602.js → chunk-n7mzxa8h.js} +2 -2
- package/dist/chunk-nz7kjzc0.js +1 -0
- package/dist/{chunk-70hwyc2w.js → chunk-q69fzq4y.js} +1 -1
- package/dist/{chunk-b8n5mx53.js → chunk-q6eb20fz.js} +1 -1
- package/dist/{chunk-hexj26gw.js → chunk-rahch228.js} +1 -1
- package/dist/{chunk-3awjdsef.js → chunk-rchz6j90.js} +1 -1
- package/dist/{chunk-2va6ex5v.js → chunk-rvk9r2cm.js} +1 -1
- package/dist/{chunk-425p4nwx.js → chunk-s10pmnrd.js} +2 -2
- package/dist/{chunk-na3jmz7f.js → chunk-s66fwx1p.js} +1 -1
- package/dist/chunk-s6vzjear.js +10 -0
- package/dist/{chunk-f9asjkfz.js → chunk-sdbbyagy.js} +1 -1
- package/dist/{chunk-9hsbjy6a.js → chunk-szxajr6e.js} +1 -1
- package/dist/{chunk-q3vza5gt.js → chunk-tgdhsm5t.js} +2 -2
- package/dist/chunk-v4w5b2cq.js +1 -0
- package/dist/chunk-vk4xbek0.js +1 -0
- package/dist/{chunk-53xtssbf.js → chunk-w7hy5wh1.js} +1 -1
- package/dist/{chunk-cp7xsjj2.js → chunk-wyhyw9rq.js} +2 -2
- package/dist/{chunk-6yezrqe7.js → chunk-wzmqkam9.js} +1 -1
- package/dist/{chunk-hpjnk87v.js → chunk-x3cxmwnz.js} +1 -1
- package/dist/chunk-xm8nyj5z.js +2 -0
- package/dist/{chunk-fpx3462x.js → chunk-xtb84adp.js} +1 -1
- package/dist/chunk-yr56ttgw.js +1 -0
- package/dist/{chunk-kt5jqaxp.js → chunk-ywarj5j9.js} +1 -1
- package/dist/{chunk-rej5bbbs.js → chunk-z9gd9spf.js} +1 -1
- package/dist/web/assets/{ChatView-C5kVDWL0.js → ChatView-_4ut_-Jh.js} +16 -16
- package/dist/web/assets/{CodeBlockHighlighter-BxJu15oF.js → CodeBlockHighlighter-DkDr6wE9.js} +1 -1
- package/dist/web/assets/{FilePreview-BDNq89O6.js → FilePreview-DCI-oqhJ.js} +1 -1
- package/dist/web/assets/{KanbanBoard-CCn0j1Ow.js → KanbanBoard-CB5C4tJC.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-15FrKNPV.js → MarkdownRenderer-ychfmIQK.js} +3 -3
- package/dist/web/assets/{SettingsModal-DCL04xT_.js → SettingsModal-SSdk0Bjr.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-Gyn_K98p.js → TaskSwitcher-EnaUhn3o.js} +1 -1
- package/dist/web/assets/{TerminalPanel-Cbh0NmHM.js → TerminalPanel-BcWxLSV3.js} +1 -1
- package/dist/web/assets/{arrow-left-wfNAFD9Y.js → arrow-left-Ob5r20g7.js} +1 -1
- package/dist/web/assets/{calendar-clock-BbbqqtLj.js → calendar-clock-eOALT8DB.js} +1 -1
- package/dist/web/assets/{chevrons-up-down-uCUY_a67.js → chevrons-up-down-BkZBwmbt.js} +1 -1
- package/dist/web/assets/{clock-3-DfiIeEEf.js → clock-3-DQp9SzYc.js} +1 -1
- package/dist/web/assets/{external-link-CilEshFB.js → external-link-BuGUowPD.js} +1 -1
- package/dist/web/assets/{folder-D9K0ykgI.js → folder-c92kw1oI.js} +1 -1
- package/dist/web/assets/{index-BKBXGV6s.js → index-CS8jtO_A.js} +16 -16
- package/dist/web/assets/{pause-D4a4_iHl.js → pause-DP_CXoH7.js} +1 -1
- package/dist/web/assets/{play-D9guMjPv.js → play-DcRwtohz.js} +1 -1
- package/dist/web/assets/{session-events-DelJesUm.js → session-events-CrAgnaj2.js} +1 -1
- package/dist/web/assets/{teamService-CAVeS_dL.js → teamService-JyVbGQhi.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-00rps629.js +0 -2
- package/dist/chunk-4t3h306m.js +0 -6
- package/dist/chunk-9018357g.js +0 -1
- package/dist/chunk-a8mgzsh7.js +0 -1
- package/dist/chunk-c3zcqqb7.js +0 -1
- package/dist/chunk-cwnaydst.js +0 -1
- package/dist/chunk-d7rg6t0n.js +0 -1
- package/dist/chunk-gdp02sqp.js +0 -1
- package/dist/chunk-kfmh3t1r.js +0 -1
- package/dist/chunk-kvdk0pfk.js +0 -1
- package/dist/chunk-maebpz1j.js +0 -2
- package/dist/chunk-n4cw6vt1.js +0 -1
- package/dist/chunk-p7t010gq.js +0 -1
- package/dist/chunk-ryemn19e.js +0 -10
- package/dist/chunk-xy5fmskp.js +0 -1
- package/dist/chunk-y3anmree.js +0 -1
- package/dist/chunk-yx4802a0.js +0 -2
- package/dist/chunk-zy6vm5jm.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{e as G3,f as U3}from"./chunk-
|
|
1
|
+
import{e as G3,f as U3}from"./chunk-7fz3w4rk.js";import{i as qZ,j as zZ,k as OZ}from"./chunk-jaswqpe7.js";import{u as P2}from"./chunk-khtxprbv.js";import{C as N6,G as MZ,I as h4,J as f4,K as X6,Q as l9,R as r9,V as E$,X as M9,Y as y9,_ as a9,aa as v8,ba as y3,ca as R3,fa as T3,ga as C3,ka as dJ,la as D6,na as k6,oa as f6,pa as yZ,qa as V9,sa as j9,ua as H6}from"./chunk-b0j9v359.js";import"./chunk-abd57h72.js";import{Ca as cY,Da as dY,Ea as lY,Ha as PZ}from"./chunk-xtb84adp.js";import{Ja as d9}from"./chunk-xm8nyj5z.js";import{Db as c9,Mb as R4,qb as x9,rb as u9}from"./chunk-0aa40zbs.js";import{Xb as E8}from"./chunk-8hprmrd5.js";import{Bd as C9,Cd as y4,Dd as I9,Fd as W2,Nd as f8,Qd as f0,ad as E9,pd as b9,ud as P9}from"./chunk-wzmqkam9.js";import"./chunk-s0tq8gyx.js";import"./chunk-x3cxmwnz.js";import{te as GZ}from"./chunk-j2dyprdy.js";import{ue as h8,ve as M2,xe as n$}from"./chunk-gr80w0vh.js";import"./chunk-z9gd9spf.js";import{$e as a0,Be as t1,Ce as K$,De as R1,Ee as UJ,Fe as H2,Ge as B9,He as OY,Ie as CJ,Je as eY,Ke as _Y,Le as J8,Me as Y$,Ne as AZ,Oe as G$,Pe as KZ,Qe as Z4,Re as V8,Ue as v9}from"./chunk-q6eb20fz.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-rchz6j90.js";import{pf as IJ}from"./chunk-w7hy5wh1.js";import"./chunk-2hb222re.js";import"./chunk-07w0qapm.js";import{Bf as T2,Ef as m3,Jf as M3,Sf as bZ}from"./chunk-ywarj5j9.js";import"./chunk-kf7whgr7.js";import"./chunk-fva7jnjy.js";import"./chunk-41ympwz1.js";import{og as OJ,qg as y$}from"./chunk-aa5zmwd9.js";import"./chunk-41cg66y0.js";import{sh as wZ,xh as P3,yh as BZ}from"./chunk-f945dzj6.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import{Hh as K8,Ih as L2,Kh as _J}from"./chunk-c475tfqf.js";import{Ph as Z$}from"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import{mi as LZ,pi as y1}from"./chunk-n7mzxa8h.js";import{ri as X3,si as Q3,vi as Q1}from"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import{Hi as iY}from"./chunk-14bs89sm.js";import{Ki as cJ}from"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import{Vi as M4}from"./chunk-tgdhsm5t.js";import{Xi as zJ}from"./chunk-fhfzdyba.js";import{useMemoizedFn as H4}from"ahooks";import{useEffect as yK,useState as F4}from"react";import{useMemoizedFn as t0}from"ahooks";import QZ from"ansi-escapes";import{Box as W1,useStdout as LK}from"ink";import{useEffect as L1,useMemo as wK,useRef as n8,useState as BK}from"react";import{useShallow as TZ}from"zustand/react/shallow";import{useStore as RZ}from"zustand";function Z0($){return RZ(J8,$)}var CZ=[],Y8=()=>Z0(($)=>$.session.sessionId),o$=()=>Z0(($)=>$.session.workspaceRoot),$2=()=>Z0(($)=>$.session.messages),lJ=()=>Z0(($)=>$.session.clearCount),rJ=()=>Z0(($)=>$.session.isCompacting),aJ=()=>Z0(($)=>$.session.tokenUsage.estimatedCostUsd),iJ=()=>Z0(($)=>{let{totalInputTokens:J,cacheReadTokens:Z,cacheWriteTokens:Y}=$.session.tokenUsage;return dJ({totalInputTokens:J,cacheReadTokens:Z,cacheWriteTokens:Y}).hitRate}),oJ=()=>Z0(($)=>$.session.providerCircuit),nJ=()=>Z0(($)=>$.session.providerAdmission),tJ=()=>Z0(($)=>$.session.providerRetry),sJ=()=>Z0(($)=>$.session.providerStall),eJ=()=>Z0(($)=>$.session.actionStationarity),P1=()=>Z0(($)=>$.session.actions),$9=()=>Z0(($)=>{let{totalTokens:J,maxContextTokens:Z}=$.session.tokenUsage;if(Z<=0)return 100;let Y=Math.max(0,100-J/Z*100);return Math.round(Y)}),J9=()=>Z0(($)=>$.app.initializationStatus),Y9=()=>Z0(($)=>$.app.initializationError),J2=()=>Z0(($)=>$.app.activeModal),Z9=()=>Z0(($)=>$.app.tasks),X9=()=>Z0(($)=>$.app.modelEditorTarget),Q9=()=>Z0(($)=>$.app.sessionSelectorData),K9=()=>Z0(($)=>$.app.awaitingSecondCtrlC),M1=()=>Z0(($)=>$.app.actions),Y2=()=>Z0(($)=>$.app.sideConversation),G9=()=>Z0(($)=>$.app.teams),Z2=()=>Z0(($)=>$.app.initializationStatus==="ready"),U9=()=>Z0(($)=>$.app.tasks.length>0),Z8=()=>Z0(($)=>$.config.config?.permissionMode||"default"),q9=()=>Z0(($)=>$.config.config?.models??CZ),X2=()=>Z0(($)=>{let J=$.config.config;if(!J)return;let Z=J.currentModelId;return J.models.find((X)=>X.id===Z)??J.models[0]}),Q2=()=>Z0(($)=>$.config.config?.currentModelId),z9=()=>Z0(($)=>$.config.config?.agentTeamsEnabled===!0),P0=()=>Z0(($)=>{return K$.getTheme()}),O9=()=>Z0(($)=>$.config.config?.codeTheme??"default"),r0=()=>Z0(($)=>$.focus.currentFocus),_9=()=>Z0(($)=>$.focus.actions),X8=()=>Z0(($)=>$.command.isProcessing),N9=()=>Z0(($)=>$.command.actions),Q8=()=>Z0(($)=>$.command.pendingCommands),H9=()=>Z0(($)=>$.command.recoveredSteeringCount),K2=()=>Z0(($)=>$.app.reasoningEffort!=="off"),G2=()=>Z0(($)=>$.app.reasoningEffort),U2=()=>Z0(($)=>$.app.serviceTier),q2=()=>Z0(($)=>$.app.responseVerbosity),z2=()=>Z0(($)=>$.app.communicationStyle),O2=()=>Z0(($)=>$.session.currentThinkingContent),F9=()=>Z0(($)=>$.session.thinkingExpanded),_2=()=>Z0(($)=>$.session.currentStreamingMessageId),N2=()=>Z0(TZ(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),W9=()=>Z0(($)=>$.session.finalizingStreamingMessageId),L9=()=>Z0(($)=>$.session.historyExpanded),w9=()=>Z0(($)=>$.session.expandedMessageCount);import{useMemoizedFn as X1}from"ahooks";import{useEffect as g1,useMemo as oZ,useRef as R2}from"react";class W4{options;requested=!1;scheduled=!1;inFlight=!1;disposed=!1;generation=0;activeRunController=null;scheduleCallback;constructor($){this.options=$;this.scheduleCallback=$.schedule??queueMicrotask}request(){if(this.disposed)return;this.requested=!0,this.scheduleIfRunnable()}notifyIdle(){this.scheduleIfRunnable()}dispose(){this.disposed=!0,this.requested=!1,this.scheduled=!1,this.generation++,this.activeRunController?.abort("pending-resume-coordinator-disposed"),this.activeRunController=null}scheduleIfRunnable(){if(this.disposed||!this.requested||this.scheduled||this.inFlight||!this.options.canRun())return;this.scheduled=!0;let $=this.generation;this.scheduleCallback(()=>{if(this.disposed||$!==this.generation)return;this.scheduled=!1,this.flush()})}async flush(){if(this.disposed||this.inFlight||!this.requested||!this.options.canRun())return;this.requested=!1,this.inFlight=!0;let $=new AbortController;this.activeRunController=$;let J="completed";try{J=await this.options.run($.signal)}finally{if(this.activeRunController===$)this.activeRunController=null;if(this.inFlight=!1,J==="deferred")this.requested=!0;this.scheduleIfRunnable()}}}class S8{options;finalized=!1;constructor($){this.options=$}get isFinalized(){return this.finalized}acceptsDeltas(){return!this.finalized&&!this.options.signal.aborted}startTurn(){this.finalized=!1}finalize(){if(!this.acceptsDeltas())return!1;return this.finalized=!0,this.commit(this.options.streamingBuffer.drainPendingBuffers()),!0}abortAndFinalize($){if(this.finalized)return $(),!1;this.finalized=!0;let J=this.options.streamingBuffer.drainPendingBuffers();return $(),this.commit(J),!0}discard(){this.finalized=!0,this.options.streamingBuffer.resetStreamingBuffers(),this.options.discardStreamingMessage(),this.options.clearThinking()}commit($){let J=this.options.getStreamingMessageId();if(J){if($.extraContent)H2(J,$.extraContent);B9(J)}this.options.finalizeStreamingMessage($.extraContent,$.extraThinking)}}function IZ($){if(!($ instanceof Error))return"未知错误";let Y=$.lastError??$;if(Y.responseBody)try{let K=JSON.parse(Y.responseBody)?.error?.message;if(K){let G=Y.statusCode?` (HTTP ${Y.statusCode})`:"";return`${K}${G}`}}catch{}let X=$.message.match(/Last error:\s*(.+)$/);if(X)return X[1];return $.message}function SZ($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function kZ($){if(!($ instanceof Error))return!1;let J=$.message;return J.includes("can only concatenate str")||J.includes("image_url")||J.includes("multimodal")||J.includes("vision")||J.includes("does not support images")}function F2($){let J=SZ($),Z=kZ($),Y;if(Z)Y="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Y=IZ($);return{displayMessage:Y,isAbort:J,isVisionNotSupported:Z}}import{appendFileSync as fZ,mkdirSync as vZ,writeFileSync as DZ}from"node:fs";import VZ from"node:os";import L4 from"node:path";var A9=null;function jZ(){let $=process.env.BLADE_STORAGE_ROOT||L4.join(VZ.homedir(),".blade");return L4.join($,"logs","stream-debug.log")}function EZ($){if(A9===$)return;let J=L4.dirname($);vZ(J,{recursive:!0,mode:493}),DZ($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
|
|
2
2
|
`),A9=$}function w4($,J,Z){try{let Y=jZ();EZ(Y);let X=new Date().toISOString(),Q=Z?` | ${JSON.stringify(Z)}`:"",K=`[${X}] [${$}] ${J}${Q}
|
|
3
3
|
`;fZ(Y,K)}catch{}}var k8=y1("UI");function A4($,J){if(J.state==="requires_attention"){let Z=J.reason==="interrupted_tool_call";$.addToolMessage("Turn recovery requires attention",{toolName:"Runtime Recovery",phase:"complete",summary:Z?"An interrupted tool may have partially completed":"A completed tool may already have changed external state",detail:`${J.turnId} · inspect workspace, processes, and external state before retrying`});return}$.addToolMessage(J.state==="completed"?"Recovered completed turn":"Resuming interrupted turn",{toolName:"Runtime Recovery",phase:"complete",summary:J.state==="completed"?"The durable final response was recovered":"No tool execution was recorded before interruption",detail:J.turnId})}function R9($,J){let Z=$.streamSession??new S8({signal:$.signal,streamingBuffer:$.streamingBuffer,getStreamingMessageId:$.getStreamingMessageId,finalizeStreamingMessage:$.sessionActions.finalizeStreamingMessage,discardStreamingMessage:$.sessionActions.discardStreamingMessage,clearThinking:()=>$.sessionActions.setCurrentThinkingContent(null)});return(Y)=>{switch(Y.kind){case"content_delta":if(!Z.acceptsDeltas())break;J.contentDeltaCount++,J.contentDeltaTotalLen+=Y.delta.length,w4("loopEventHandler","onContentDelta",{callCount:J.contentDeltaCount,deltaLen:Y.delta.length,totalLen:J.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(Y.delta);break;case"thinking_delta":if(!Z.acceptsDeltas())break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(Y.delta);break;case"stream_end":{$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),k8.debug("[loopEventHandler] stream_end",{contentDeltaCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:Z.isFinalized,signalAborted:$.signal.aborted}),w4("loopEventHandler","onStreamEnd",{contentDeltaCallCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:Z.isFinalized,signalAborted:$.signal.aborted}),Z.finalize();break}case"model_fallback":$.sessionActions.setProviderAdmission(null),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Z.discard();break;case"provider_admission":{let{kind:X,...Q}=Y;$.sessionActions.setProviderAdmission(Y.phase==="queued"?Q:null);break}case"provider_circuit":{let{kind:X,...Q}=Y;$.sessionActions.setProviderCircuit(Y.phase==="closed"?null:Q);break}case"provider_retry":{let{kind:X,...Q}=Y;$.sessionActions.setProviderRetry(Y.phase==="recovered"?null:Q);break}case"provider_stall":{let{kind:X,...Q}=Y;$.sessionActions.setProviderStall(Y.phase==="detected"?Q:null);break}case"action_stationarity":{let{kind:X,...Q}=Y;$.sessionActions.setActionStationarity(Y.phase==="recovered"?null:Q);break}case"turn_recovery":{A4($.sessionActions,Y.assessment);break}case"tool_start":{let X=Y.toolCall;if(!("function"in X))break;if(X.function.name===W2)break;if(k8.debug("[loopEventHandler] tool_start",{toolName:X.function.name,toolKind:Y.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(X.function.name))break;try{let Q=JSON.parse(X.function.arguments),K=M9(X.function.name,Q);$.sessionActions.addToolMessage(K,{toolCallId:X.id,toolName:X.function.name,phase:"start",summary:K,params:Q})}catch(Q){k8.error("[loopEventHandler] onToolStart error:",Q)}break}case"tool_progress":{let X=Y.toolCall;if(!("function"in X))break;if(X.function.name===W2)break;let Q=Y.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((Y.update.progress??0)/Y.update.total*100)))}%`:"",K=`${X.function.name}${Q}: ${Y.update.message}`;$.sessionActions.addToolMessage(K,{toolCallId:X.id,toolName:X.function.name,phase:"progress",summary:K,...Y.update.admission?{admission:Y.update.admission}:{}});break}case"tool_result":{let X=Y.toolCall;if(!("function"in X))break;if(X.function.name===W2)break;k8.debug("[loopEventHandler] tool_result",{toolName:X.function.name,success:Y.result.success});let Q=P9(y9(X.function.name,Y.result),b9);$.sessionActions.addToolMessage(Q.summary,{toolCallId:X.id,toolName:X.function.name,phase:"complete",summary:Q.summary,detail:Q.detail});break}case"structured_output":$.sessionActions.replaceLastAssistantMessage(JSON.stringify(Y.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(Y.usage);break;case"compaction":if($.sessionActions.setCompacting(Y.phase==="start"),Y.phase==="end"){if($.sessionActions.resetContextUsage(),Y.outcome!=="failed")J.compactionCount=(J.compactionCount??0)+1}break;case"turn_start":k8.debug("[loopEventHandler] turn_start",{turn:Y.turn,maxTurns:Y.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:Y.turn}),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Z.startTurn();break;case"task_update":$.appActions.setTasks(Y.tasks);break;case"goal_frontier_updated":$.appActions.setTasks(Y.tasks);break;case"mcp_catalog_changed":{let X=`MCP catalog r${Y.revision}: +${Y.added.length} -${Y.removed.length} ~${Y.updated.length}`;$.sessionActions.addToolMessage(X,{toolName:"MCP Catalog",phase:"complete",summary:X,detail:[Y.added.length>0?`Added: ${Y.added.join(", ")}`:"",Y.removed.length>0?`Removed: ${Y.removed.join(", ")}`:"",Y.updated.length>0?`Updated: ${Y.updated.join(", ")}`:""].filter(Boolean).join(`
|
|
4
4
|
`)});break}case"mcp_content_changed":{let X=`MCP ${Y.contentKind} r${Y.revision}: +${Y.added.length} -${Y.removed.length} ~${Y.updated.length}`;$.sessionActions.addToolMessage(X,{toolName:"MCP Content",phase:"complete",summary:X,detail:[Y.added.length>0?`Added: ${Y.added.join(", ")}`:"",Y.removed.length>0?`Removed: ${Y.removed.join(", ")}`:"",Y.updated.length>0?`Updated: ${Y.updated.join(", ")}`:""].filter(Boolean).join(`
|
|
@@ -118,7 +118,7 @@ ${h}`}]}}let $$=b4(e),g=await k($$);if(!g.accepted){let h=g.reason==="queue_full
|
|
|
118
118
|
|
|
119
119
|
**重要**:请直接返回 JSON,不要添加任何额外的解释或文字。`,G)).trim(),k=T.match(/```(?:json)?\s*\n([\s\S]*?)\n```/);if(k)T=k[1];let y=JSON.parse(T);if(!y.name||!y.description||!y.systemPrompt)throw Error("Missing required fields: name, description, or systemPrompt");if(!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(y.name))throw Error("Invalid name format. Must be kebab-case (lowercase, numbers, hyphens only)");K({name:y.name,description:y.description,tools:Array.isArray(y.tools)?y.tools:[],color:y.color||"blue",location:"project",systemPrompt:y.systemPrompt}),X("confirm")}catch(P){_(P instanceof Error?P.message:String(P))}finally{O(!1)}});T6(()=>{if(Y==="aiGenerating"&&!q&&!z)B()},[Y,q,z,B]);let w=j2(async()=>{try{let P=Q.location==="project"?V4.join(Z$(),".blade","agents"):V4.join(v5.homedir(),".blade","agents");await R6.promises.mkdir(P,{recursive:!0});let b=["---",`name: ${Q.name}`,`description: ${Q.description}`];if(Q.tools.length>0&&!Q.tools.includes("all")){b.push("tools:");for(let k of Q.tools)b.push(` - ${k}`)}if(Q.color)b.push(`color: ${Q.color}`);b.push("---");let v=[b.join(`
|
|
120
120
|
`),"",`# ${Q.name} Subagent`,"",Q.systemPrompt||"你是一个专门的代理,负责执行特定任务。",""].join(`
|
|
121
|
-
`),T=V4.join(P,`${Q.name}.md`);await R6.promises.writeFile(T,v,"utf-8"),$()}catch(P){console.error("保存配置失败:",P)}}),M=h0(!1,J);if(q0((P,b)=>{if(b.escape)S();else if(b.ctrl&&P==="c"||b.meta&&P==="c")M()},{isActive:Y!=="tools"}),Y==="mode")return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"cyan",children:"选择创建方式"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{dimColor:!0,children:"你可以手动配置每个细节,或让 AI 根据你的描述自动生成配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(E2,{items:[{label:"AI 智能生成 - 根据描述自动生成完整配置",value:"ai"},{label:"手动配置 - 逐步配置每个选项",value:"manual"}],onSelect:(P)=>{if(P.value==="ai")L("ai"),X("aiPrompt");else L("manual"),X("name")}},void 0,!1,void 0,this),E(N0,{marginTop:1,children:E(G0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 取消"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="aiPrompt")return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"cyan",children:"AI 智能生成"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{dimColor:!0,children:'描述你想要创建的 Agent(例如:"一个专门用于代码审查的 agent,能够分析代码质量和潜在bug")'},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:[E(G0,{color:"green",children:"描述: "},void 0,!1,void 0,this),E(g8,{value:G,onChange:U,onSubmit:(P)=>{if(!P.trim())return;X("aiGenerating")}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(N0,{children:E(G0,{dimColor:!0,children:"按 Enter 开始生成 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="aiGenerating"){if(z)return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"red",children:"AI 生成失败"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{color:"red",children:z},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{dimColor:!0,children:"按 ESC 返回修改描述"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"yellow",children:[E(E5,{type:"dots"},void 0,!1,void 0,this)," AI 正在生成配置..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{dimColor:!0,children:['根据你的描述:"',G,'"']},void 0,!0,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{color:"gray",children:"正在调用 LLM 生成 agent 配置,请稍候..."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}if(Y==="name"){let P=W==="edit";return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"cyan",children:["Step 1/7: ",P?"Agent 名称(不可修改)":"输入 Agent 名称"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{dimColor:!0,children:P?"编辑模式下名称不可修改(修改名称相当于创建新 Agent)":"名称只能包含小写字母、数字和连字符(例如:code-reviewer)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:[E(G0,{color:"green",children:"名称: "},void 0,!1,void 0,this),P?E(G0,{children:Q.name},void 0,!1,void 0,this):E(g8,{value:Q.name,onChange:(b)=>K({...Q,name:b}),onSubmit:(b)=>{if(m5(b))return;H()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(N0,{children:E(G0,{dimColor:!0,children:P?"按 Enter 继续 | ESC 返回":"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this),P&&E(g8,{value:"",onChange:()=>{},onSubmit:H,showCursor:!1},"edit-mode-dummy-input",!1,void 0,this)]},void 0,!0,void 0,this)}if(Y==="description")return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"cyan",children:"Step 2/7: 输入描述信息"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{dimColor:!0,children:"简短描述这个 Agent 的用途和使用场景(这将帮助主 Agent 决定何时使用它)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:[E(G0,{color:"green",children:"描述: "},void 0,!1,void 0,this),E(g8,{value:Q.description,onChange:(P)=>K({...Q,description:P}),onSubmit:(P)=>{if(!P.trim())return;H()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(N0,{children:E(G0,{dimColor:!0,children:"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="tools")return E(p5,{config:Q,setConfig:K,onNext:H,onPrev:S},void 0,!1,void 0,this);if(Y==="color")return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"cyan",children:"Step 4/7: 选择背景颜色"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{dimColor:!0,children:"为 Agent 选择一个颜色标识(用于在 UI 中区分不同的 Agents)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(E2,{items:g5,onSelect:(P)=>{let b=P.value==="none"?void 0:P.value;K({...Q,color:b}),H()}},void 0,!1,void 0,this),E(N0,{marginTop:1,children:E(G0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="location")return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"cyan",children:"Step 5/7: 选择保存位置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{dimColor:!0,children:"项目级配置仅在当前项目生效,用户级配置全局可用"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(E2,{items:[{label:"项目级 (.blade/agents/) - 仅当前项目",value:"project"},{label:"用户级 (~/.blade/agents/) - 全局可用",value:"user"}],onSelect:(P)=>{K({...Q,location:P.value}),H()}},void 0,!1,void 0,this),E(N0,{marginTop:1,children:E(G0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="systemPrompt")return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"cyan",children:"Step 6/7: 输入系统提示词"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{dimColor:!0,children:"定义 Agent 的行为和职责(可选,留空将使用默认提示)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:[E(G0,{color:"green",children:"提示词: "},void 0,!1,void 0,this),E(g8,{value:Q.systemPrompt,onChange:(P)=>K({...Q,systemPrompt:P}),onSubmit:()=>H()},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(N0,{children:E(G0,{dimColor:!0,children:"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="confirm")return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"cyan",children:"Step 7/7: 确认配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{flexDirection:"column",paddingLeft:2,marginBottom:1,children:[E(G0,{children:[E(G0,{bold:!0,color:"green",children:["名称:"," "]},void 0,!0,void 0,this),E(G0,{children:Q.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(G0,{children:[E(G0,{bold:!0,color:"green",children:["描述:"," "]},void 0,!0,void 0,this),E(G0,{children:Q.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(G0,{children:[E(G0,{bold:!0,color:"green",children:["工具:"," "]},void 0,!0,void 0,this),E(G0,{children:Q.tools.includes("all")?"所有工具":Q.tools.join(", ")||"所有工具"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(G0,{children:[E(G0,{bold:!0,color:"green",children:["颜色:"," "]},void 0,!0,void 0,this),E(G0,{children:Q.color||"默认"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(G0,{children:[E(G0,{bold:!0,color:"green",children:["位置:"," "]},void 0,!0,void 0,this),E(G0,{children:Q.location==="project"?"项目级":"用户级"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(G0,{children:[E(G0,{bold:!0,color:"green",children:["提示词:"," "]},void 0,!0,void 0,this),E(G0,{children:Q.systemPrompt||"(使用默认)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),E(E2,{items:[{label:"确认并保存",value:"save"},{label:"返回上一步",value:"back"},{label:"取消",value:"cancel"}],onSelect:(P)=>{if(P.value==="save")w();else if(P.value==="back")S();else J()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null}function p5({config:$,setConfig:J,onNext:Z,onPrev:Y}){let{isFocused:X}=V5({id:"step-tools"});q0((K,G)=>{if(G.escape)Y()},{isActive:X});let Q=(K)=>{if(K.includes("all"))J({...$,tools:["all"]});else J({...$,tools:K});Z()};return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"cyan",children:"Step 3/7: 选择可用工具"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{dimColor:!0,children:"方向键导航,空格切换勾选,Enter 确认进入下一步 | ESC 返回上一步"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(D5,{options:h5,defaultValue:$.tools,onSubmit:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import x5 from"node:fs";import{useMemoizedFn as x1}from"ahooks";import{Box as v0,Text as g0}from"ink";import j4 from"ink-select-input";import{useEffect as u5,useMemo as C6,useState as h2}from"react";import{jsxDEV as Y0}from"react/jsx-dev-runtime";var E4=10;function I6({workspaceRoot:$,initialMode:J="menu",onComplete:Z,onCancel:Y}){let X=T2($),[Q,K]=h2(J),[G,U]=h2(null),[q,O]=h2(0),[z,_]=h2(0),W=x1(()=>{X.clear(),X.loadFromStandardLocations(),O((T)=>T+1)}),L=C6(()=>{return X.getAllSubagents()},[q]),N=Math.ceil(L.length/E4)||1,A=C6(()=>{let T=z*E4;return L.slice(T,T+E4)},[L,z]);u5(()=>{let T=Math.max(0,N-1);if(z>T)_(T)},[N,z]);let I=x1(()=>{if(z<N-1)_((T)=>T+1)}),H=x1(()=>{if(z>0)_((T)=>T-1)}),S=[{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"}],B=x1((T)=>{if(T.value==="cancel"){Y?.();return}K(T.value)}),w=x1((T)=>{if(U(T.value),Q==="edit")K("editWizard");else if(Q==="delete")K("deleteConfirm")}),M=x1(async()=>{if(!G?.configPath)return;try{await x5.promises.unlink(G.configPath),W(),P()}catch(T){console.error("删除失败:",T)}}),P=x1(()=>{K("menu"),U(null)}),b=h0(!1,Y);if(q0((T,k)=>{if(k.escape){if(Q==="menu")Y?.();else if(Q==="list"||Q==="edit"||Q==="delete")_(0),P();else if(Q==="deleteConfirm")P()}else if(k.ctrl&&T==="c"||k.meta&&T==="c")b();else if(Q==="list"){if(k.leftArrow||T==="h")H();else if(k.rightArrow||T==="l")I()}},{isActive:Q!=="create"&&Q!=="editWizard"}),Q==="menu")return Y0(v0,{flexDirection:"column",paddingY:1,children:[Y0(v0,{marginBottom:1,children:Y0(g0,{bold:!0,color:"cyan",children:"Agents 管理"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Y0(j4,{items:S,onSelect:B},void 0,!1,void 0,this),Y0(v0,{marginTop:1,children:Y0(g0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 退出"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Q==="list"){if(L.length===0)return Y0(v0,{flexDirection:"column",paddingY:1,children:[Y0(v0,{marginBottom:1,children:Y0(g0,{bold:!0,color:"cyan",children:"所有 Agents"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Y0(v0,{paddingLeft:2,children:Y0(g0,{color:"gray",children:"没有找到任何 agent 配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Y0(v0,{marginTop:1,paddingLeft:2,children:Y0(g0,{color:"gray",children:"配置文件位置: .blade/agents/ 或 ~/.blade/agents/"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Y0(v0,{marginTop:1,paddingLeft:2,children:Y0(g0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return Y0(v0,{flexDirection:"column",paddingY:1,children:[Y0(v0,{marginBottom:1,children:[Y0(g0,{bold:!0,color:"cyan",children:"所有 Agents"},void 0,!1,void 0,this),Y0(g0,{color:"gray",children:[" (共 ",L.length," 个)"]},void 0,!0,void 0,this),N>1&&Y0(g0,{color:"yellow",children:[" ","第 ",z+1,"/",N," 页"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),A.map((T)=>Y0(v0,{flexDirection:"column",paddingLeft:2,children:[Y0(v0,{children:Y0(g0,{children:[Y0(g0,{bold:!0,color:T.color||"white",children:["• ",T.name]},void 0,!0,void 0,this),Y0(g0,{color:"gray",children:[" - ",T.description]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),T.tools&&T.tools.length>0&&Y0(v0,{paddingLeft:2,children:Y0(g0,{color:"gray",children:["工具: ",T.tools.join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this),T.configPath&&Y0(v0,{paddingLeft:2,children:Y0(g0,{color:"gray",dimColor:!0,children:T.configPath},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},T.name,!0,void 0,this)),Y0(v0,{marginTop:1,paddingLeft:2,children:N>1?Y0(g0,{dimColor:!0,children:"Left/Right to page | ESC 返回菜单"},void 0,!1,void 0,this):Y0(g0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}let v=(T)=>{if(L.length===0)return Y0(v0,{flexDirection:"column",paddingY:1,children:[Y0(v0,{marginBottom:1,children:Y0(g0,{bold:!0,color:"cyan",children:T},void 0,!1,void 0,this)},void 0,!1,void 0,this),Y0(v0,{paddingLeft:2,children:Y0(g0,{color:"gray",children:"没有找到任何 agent 配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Y0(v0,{marginTop:1,paddingLeft:2,children:Y0(g0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);let k=L.map((y)=>({key:y.name,label:`${y.name} - ${y.description}`,value:y}));return Y0(v0,{flexDirection:"column",paddingY:1,children:[Y0(v0,{marginBottom:1,children:Y0(g0,{bold:!0,color:"cyan",children:T},void 0,!1,void 0,this)},void 0,!1,void 0,this),Y0(j4,{items:k,onSelect:w},void 0,!1,void 0,this),Y0(v0,{marginTop:1,children:Y0(g0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};if(Q==="create")return Y0(m8,{onComplete:()=>{W(),P()},onCancel:P},void 0,!1,void 0,this);if(Q==="edit")return v("编辑 Agent");if(Q==="editWizard"&&G){let T={name:G.name,description:G.description,tools:G.tools||[],color:G.color,location:G.configPath?.includes(".blade/agents")?"project":"user",systemPrompt:G.systemPrompt||""};return Y0(m8,{initialConfig:T,onComplete:()=>{W(),P()},onCancel:P},void 0,!1,void 0,this)}if(Q==="delete")return v("删除 Agent");if(Q==="deleteConfirm"&&G)return Y0(v0,{flexDirection:"column",paddingY:1,children:[Y0(v0,{marginBottom:1,children:Y0(g0,{bold:!0,color:"red",children:"确认删除"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Y0(v0,{marginBottom:1,paddingLeft:2,children:Y0(g0,{children:["你确定要删除 Agent"," ",Y0(g0,{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),Y0(v0,{marginBottom:1,paddingLeft:2,children:Y0(g0,{dimColor:!0,children:["文件路径: ",G.configPath]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Y0(v0,{marginBottom:1,paddingLeft:2,children:Y0(g0,{color:"red",children:"此操作无法撤销!"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Y0(j4,{items:[{label:"确认删除",value:"confirm"},{label:"取消",value:"cancel"}],onSelect:(T)=>{if(T.value==="confirm")M();else P()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null}import{Box as O8,Text as W0}from"ink";import d5,{useEffect as l5,useState as r5}from"react";import{useEffect as c5,useState as S6}from"react";function v6($=Z$(),J=5000){let[Z,Y]=S6(null),[X,Q]=S6(!0);return c5(()=>{let K=!0,G=async()=>{try{let q=await k6($);if(!K)return;if(!q){Y(null),Q(!1);return}let O=await f6($);if(!K)return;Y(O)}catch{if(K)Y(null)}finally{if(K)Q(!1)}};G();let U=null;if(J>0)U=setInterval(G,J);return()=>{if(K=!1,U)clearInterval(U)}},[$,J]),{branch:Z,loading:X}}import{jsxDEV as X0,Fragment as m$}from"react/jsx-dev-runtime";var V6=d5.memo(()=>{let $=Z2(),J=Z8(),Y=J2()==="shortcuts",X=K9(),Q=o$(),{branch:K}=v6(Q),G=X2(),U=$9(),q=rJ(),O=K2(),z=G2(),_=U2(),W=q2(),L=z2(),N=aJ(),A=iJ(),I=Q8(),H=H9(),S=Y8(),[B,w]=r5(null);l5(()=>{let k=!1;new h4(Q,S).get().then((o)=>{if(!k)w(o)}).catch(()=>{if(!k)w(null)});let j=h4.subscribe((o)=>{if(!k&&o.sessionId===S&&o.workspaceRoot===Q)w(o.goal)});return()=>{k=!0,j()}},[S,Q]);let M=G?S2(G):!1,b=(()=>{if(J==="default")return null;if(J==="autoEdit")return X0(W0,{color:"magenta",children:[">> ","auto edit on ",X0(W0,{color:"gray",children:"(shift+tab to cycle)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(J==="plan")return X0(W0,{color:"cyan",children:["‖ plan mode on ",X0(W0,{color:"gray",children:"(shift+tab to cycle)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(J==="yolo")return X0(W0,{color:"red",children:["yolo mode on ",X0(W0,{color:"gray",children:"(all tools auto-approved)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null})(),v=b!==null,T=[["Enter:发送","Shift+Enter:换行","Esc:中止"],["Shift+Tab:切换模式","Up/Down:历史","Tab:补全"],["Ctrl+A:行首","Ctrl+E:行尾","Ctrl+K:删到尾"],["Ctrl+U:删到首","Ctrl+W:删单词","Ctrl+C:退出"],["Ctrl+O:浏览记录","PgUp/PgDn:翻页","g/G:首尾"]];return X0(O8,{flexDirection:"row",justifyContent:"space-between",paddingX:2,paddingY:0,children:[Y?X0(O8,{flexDirection:"column",gap:0,children:T.map((k,y)=>X0(O8,{flexDirection:"row",children:[k.map((j,o)=>{let[t,a]=j.split(":");return X0(O8,{flexDirection:"row",width:20,children:[X0(W0,{color:"yellow",children:t},void 0,!1,void 0,this),X0(W0,{color:"gray",children:":"},void 0,!1,void 0,this),X0(W0,{color:"white",children:a},void 0,!1,void 0,this)]},o,!0,void 0,this)}),y===T.length-1&&X0(W0,{color:"cyan",children:" ? 关闭"},void 0,!1,void 0,this)]},y,!0,void 0,this))},void 0,!1,void 0,this):X0(O8,{flexDirection:"row",gap:1,children:[K&&X0(m$,{children:[X0(W0,{color:"gray",children:[" ",K]},void 0,!0,void 0,this),X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b,v&&X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this),B&&X0(m$,{children:[X0(W0,{color:B.status==="active"?"green":B.status==="verifying"?"cyan":B.status==="blocked"||B.status==="budget_limited"?"yellow":"gray",children:["goal:",B.status," ",B.objective.slice(0,32),B.prematureStop?` recovery:${B.prematureStop.consecutiveCount}`:"",B.verificationStall?` verify-gap:${B.verificationStall.consecutiveCount}`:""]},void 0,!0,void 0,this),X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),X0(W0,{color:"gray",children:"? for shortcuts"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),X0(O8,{flexDirection:"row",gap:1,children:!$?X0(W0,{color:"red",children:"[WARN] API 密钥未配置"},void 0,!1,void 0,this):X0(m$,{children:[M&&X0(m$,{children:[O?X0(W0,{color:"cyan",children:["Effort ",z]},void 0,!0,void 0,this):X0(W0,{color:"gray",children:"Tab:Effort"},void 0,!1,void 0,this),X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),_!=="auto"&&X0(m$,{children:[X0(W0,{color:_==="fast"?"yellow":"gray",children:["Speed ",_]},void 0,!0,void 0,this),X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W!=="auto"&&X0(m$,{children:[X0(W0,{color:"gray",children:["Output ",W]},void 0,!0,void 0,this),X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),L!=="auto"&&X0(m$,{children:[X0(W0,{color:"gray",children:["Style ",L]},void 0,!0,void 0,this),X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),G&&X0(W0,{color:"gray",children:G.model},void 0,!1,void 0,this),X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this),q?X0(W0,{color:"yellow",children:"压缩中..."},void 0,!1,void 0,this):X0(W0,{color:U<20?"red":U<50?"yellow":"gray",children:[U,"%"]},void 0,!0,void 0,this),X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this),X0(W0,{color:A===void 0?"gray":"cyan",children:["Cache ",D6(A)]},void 0,!0,void 0,this),N>0.001&&X0(m$,{children:[X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this),X0(W0,{color:"green",children:["$",N<0.01?N.toFixed(4):N.toFixed(3)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),I.length>0&&X0(m$,{children:[X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this),X0(W0,{color:"yellow",children:["已排队 ",I.length]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),H>0&&X0(m$,{children:[X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this),X0(W0,{color:"cyan",children:["已恢复 ",H," 条指令"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),X&&X0(m$,{children:[X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this),X0(W0,{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 g4,Text as m4}from"ink";import a5 from"react";import{jsxDEV as _8}from"react/jsx-dev-runtime";var j6=a5.memo(({suggestions:$,selectedIndex:J,visible:Z,maxDisplay:Y=8})=>{if(!Z||$.length===0)return null;let X=0,Q=Math.min(Y,$.length),K=J>=$.length;if(J>=Y&&!K)X=J-Y+1,Q=J+1;let G=$.slice(X,Q),U=$.length>Y;return _8(g4,{flexDirection:"column",paddingX:2,paddingY:0,children:[G.map((q,O)=>{let _=X+O===J;return _8(g4,{flexDirection:"row",paddingX:1,gap:2,children:[_8(m4,{color:_?"cyan":"white",bold:_,children:q.command},void 0,!1,void 0,this),_8(m4,{color:_?"cyan":"gray",dimColor:!_,children:["- ",q.description]},void 0,!0,void 0,this)]},q.command,!0,void 0,this)}),U&&_8(g4,{paddingX:1,children:_8(m4,{color:K?"cyan":"gray",bold:K,dimColor:!K,children:["... and ",$.length-Y," more"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as v$,Text as s$,useStdout as rX}from"ink";import aX from"ink-select-input";import qJ,{useMemo as NY}from"react";import{Box as L0,Text as k0}from"ink";import c1,{useEffect as GJ,useMemo as u1,useRef as zY}from"react";import{Box as t4,Text as a6}from"ink";import GX from"react";import{Text as p$}from"ink";import XX from"react";import d6 from"string-width";import p8 from"string-width";function p4({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 i5=p4();function x4($){if(typeof $!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof $}\``);if(!$.includes("\x1B")&&!$.includes(""))return $;return $.replace(i5,"")}var E6=($=0)=>(J)=>`\x1B[${J+$}m`,h6=($=0)=>(J)=>`\x1B[${38+$};5;${J}m`,g6=($=0)=>(J,Z,Y)=>`\x1B[${38+$};2;${J};${Z};${Y}m`,c0={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]}},sq=Object.keys(c0.modifier),o5=Object.keys(c0.color),n5=Object.keys(c0.bgColor),eq=[...o5,...n5];function t5(){let $=new Map;for(let[J,Z]of Object.entries(c0)){for(let[Y,X]of Object.entries(Z))c0[Y]={open:`\x1B[${X[0]}m`,close:`\x1B[${X[1]}m`},Z[Y]=c0[Y],$.set(X[0],X[1]);Object.defineProperty(c0,J,{value:Z,enumerable:!1})}return Object.defineProperty(c0,"codes",{value:$,enumerable:!1}),c0.color.close="\x1B[39m",c0.bgColor.close="\x1B[49m",c0.color.ansi=E6(),c0.color.ansi256=h6(),c0.color.ansi16m=g6(),c0.bgColor.ansi=E6(10),c0.bgColor.ansi256=h6(10),c0.bgColor.ansi16m=g6(10),Object.defineProperties(c0,{rgbToAnsi256:{value(J,Z,Y){if(J===Z&&Z===Y){if(J<8)return 16;if(J>248)return 231;return Math.round((J-8)/247*24)+232}return 16+36*Math.round(J/255*5)+6*Math.round(Z/255*5)+Math.round(Y/255*5)},enumerable:!1},hexToRgb:{value(J){let Z=/[a-f\d]{6}|[a-f\d]{3}/i.exec(J.toString(16));if(!Z)return[0,0,0];let[Y]=Z;if(Y.length===3)Y=[...Y].map((Q)=>Q+Q).join("");let X=Number.parseInt(Y,16);return[X>>16&255,X>>8&255,X&255]},enumerable:!1},hexToAnsi256:{value:(J)=>c0.rgbToAnsi256(...c0.hexToRgb(J)),enumerable:!1},ansi256ToAnsi:{value(J){if(J<8)return 30+J;if(J<16)return 90+(J-8);let Z,Y,X;if(J>=232)Z=((J-232)*10+8)/255,Y=Z,X=Z;else{J-=16;let G=J%36;Z=Math.floor(J/36)/5,Y=Math.floor(G/6)/5,X=G%6/5}let Q=Math.max(Z,Y,X)*2;if(Q===0)return 30;let K=30+(Math.round(X)<<2|Math.round(Y)<<1|Math.round(Z));if(Q===2)K+=60;return K},enumerable:!1},rgbToAnsi:{value:(J,Z,Y)=>c0.ansi256ToAnsi(c0.rgbToAnsi256(J,Z,Y)),enumerable:!1},hexToAnsi:{value:(J)=>c0.ansi256ToAnsi(c0.hexToAnsi256(J)),enumerable:!1}}),c0}var s5=t5(),m6=s5;var m2=new Set(["\x1B",""]),e5=39,c4="\x07",u6="[",$X="]",c6="m",g2=`${$X}8;;`,p6=($)=>`${m2.values().next().value}${u6}${$}${c6}`,x6=($)=>`${m2.values().next().value}${g2}${$}${c4}`,JX=($)=>$.split(" ").map((J)=>p8(J)),u4=($,J,Z)=>{let Y=[...J],X=!1,Q=!1,K=p8(x4($.at(-1)));for(let[G,U]of Y.entries()){let q=p8(U);if(K+q<=Z)$[$.length-1]+=U;else $.push(U),K=0;if(m2.has(U))X=!0,Q=Y.slice(G+1,G+1+g2.length).join("")===g2;if(X){if(Q){if(U===c4)X=!1,Q=!1}else if(U===c6)X=!1;continue}if(K+=q,K===Z&&G<Y.length-1)$.push(""),K=0}if(!K&&$.at(-1).length>0&&$.length>1)$[$.length-2]+=$.pop()},YX=($)=>{let J=$.split(" "),Z=J.length;while(Z>0){if(p8(J[Z-1])>0)break;Z--}if(Z===J.length)return $;return J.slice(0,Z).join(" ")+J.slice(Z).join("")},ZX=($,J,Z={})=>{if(Z.trim!==!1&&$.trim()==="")return"";let Y="",X,Q,K=JX($),G=[""];for(let[z,_]of $.split(" ").entries()){if(Z.trim!==!1)G[G.length-1]=G.at(-1).trimStart();let W=p8(G.at(-1));if(z!==0){if(W>=J&&(Z.wordWrap===!1||Z.trim===!1))G.push(""),W=0;if(W>0||Z.trim===!1)G[G.length-1]+=" ",W++}if(Z.hard&&K[z]>J){let L=J-W,N=1+Math.floor((K[z]-L-1)/J);if(Math.floor((K[z]-1)/J)<N)G.push("");u4(G,_,J);continue}if(W+K[z]>J&&W>0&&K[z]>0){if(Z.wordWrap===!1&&W<J){u4(G,_,J);continue}G.push("")}if(W+K[z]>J&&Z.wordWrap===!1){u4(G,_,J);continue}G[G.length-1]+=_}if(Z.trim!==!1)G=G.map((z)=>YX(z));let U=G.join(`
|
|
121
|
+
`),T=V4.join(P,`${Q.name}.md`);await R6.promises.writeFile(T,v,"utf-8"),$()}catch(P){console.error("保存配置失败:",P)}}),M=h0(!1,J);if(q0((P,b)=>{if(b.escape)S();else if(b.ctrl&&P==="c"||b.meta&&P==="c")M()},{isActive:Y!=="tools"}),Y==="mode")return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"cyan",children:"选择创建方式"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{dimColor:!0,children:"你可以手动配置每个细节,或让 AI 根据你的描述自动生成配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(E2,{items:[{label:"AI 智能生成 - 根据描述自动生成完整配置",value:"ai"},{label:"手动配置 - 逐步配置每个选项",value:"manual"}],onSelect:(P)=>{if(P.value==="ai")L("ai"),X("aiPrompt");else L("manual"),X("name")}},void 0,!1,void 0,this),E(N0,{marginTop:1,children:E(G0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 取消"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="aiPrompt")return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"cyan",children:"AI 智能生成"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{dimColor:!0,children:'描述你想要创建的 Agent(例如:"一个专门用于代码审查的 agent,能够分析代码质量和潜在bug")'},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:[E(G0,{color:"green",children:"描述: "},void 0,!1,void 0,this),E(g8,{value:G,onChange:U,onSubmit:(P)=>{if(!P.trim())return;X("aiGenerating")}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(N0,{children:E(G0,{dimColor:!0,children:"按 Enter 开始生成 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="aiGenerating"){if(z)return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"red",children:"AI 生成失败"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{color:"red",children:z},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{dimColor:!0,children:"按 ESC 返回修改描述"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"yellow",children:[E(E5,{type:"dots"},void 0,!1,void 0,this)," AI 正在生成配置..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{dimColor:!0,children:['根据你的描述:"',G,'"']},void 0,!0,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{color:"gray",children:"正在调用 LLM 生成 agent 配置,请稍候..."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}if(Y==="name"){let P=W==="edit";return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"cyan",children:["Step 1/7: ",P?"Agent 名称(不可修改)":"输入 Agent 名称"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{dimColor:!0,children:P?"编辑模式下名称不可修改(修改名称相当于创建新 Agent)":"名称只能包含小写字母、数字和连字符(例如:code-reviewer)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:[E(G0,{color:"green",children:"名称: "},void 0,!1,void 0,this),P?E(G0,{children:Q.name},void 0,!1,void 0,this):E(g8,{value:Q.name,onChange:(b)=>K({...Q,name:b}),onSubmit:(b)=>{if(m5(b))return;H()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(N0,{children:E(G0,{dimColor:!0,children:P?"按 Enter 继续 | ESC 返回":"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this),P&&E(g8,{value:"",onChange:()=>{},onSubmit:H,showCursor:!1},"edit-mode-dummy-input",!1,void 0,this)]},void 0,!0,void 0,this)}if(Y==="description")return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"cyan",children:"Step 2/7: 输入描述信息"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{dimColor:!0,children:"简短描述这个 Agent 的用途和使用场景(这将帮助主 Agent 决定何时使用它)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:[E(G0,{color:"green",children:"描述: "},void 0,!1,void 0,this),E(g8,{value:Q.description,onChange:(P)=>K({...Q,description:P}),onSubmit:(P)=>{if(!P.trim())return;H()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(N0,{children:E(G0,{dimColor:!0,children:"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="tools")return E(p5,{config:Q,setConfig:K,onNext:H,onPrev:S},void 0,!1,void 0,this);if(Y==="color")return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"cyan",children:"Step 4/7: 选择背景颜色"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{dimColor:!0,children:"为 Agent 选择一个颜色标识(用于在 UI 中区分不同的 Agents)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(E2,{items:g5,onSelect:(P)=>{let b=P.value==="none"?void 0:P.value;K({...Q,color:b}),H()}},void 0,!1,void 0,this),E(N0,{marginTop:1,children:E(G0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="location")return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"cyan",children:"Step 5/7: 选择保存位置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{dimColor:!0,children:"项目级配置仅在当前项目生效,用户级配置全局可用"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(E2,{items:[{label:"项目级 (.blade/agents/) - 仅当前项目",value:"project"},{label:"用户级 (~/.blade/agents/) - 全局可用",value:"user"}],onSelect:(P)=>{K({...Q,location:P.value}),H()}},void 0,!1,void 0,this),E(N0,{marginTop:1,children:E(G0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="systemPrompt")return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"cyan",children:"Step 6/7: 输入系统提示词"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{dimColor:!0,children:"定义 Agent 的行为和职责(可选,留空将使用默认提示)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:[E(G0,{color:"green",children:"提示词: "},void 0,!1,void 0,this),E(g8,{value:Q.systemPrompt,onChange:(P)=>K({...Q,systemPrompt:P}),onSubmit:()=>H()},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(N0,{children:E(G0,{dimColor:!0,children:"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Y==="confirm")return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"cyan",children:"Step 7/7: 确认配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{flexDirection:"column",paddingLeft:2,marginBottom:1,children:[E(G0,{children:[E(G0,{bold:!0,color:"green",children:["名称:"," "]},void 0,!0,void 0,this),E(G0,{children:Q.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(G0,{children:[E(G0,{bold:!0,color:"green",children:["描述:"," "]},void 0,!0,void 0,this),E(G0,{children:Q.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(G0,{children:[E(G0,{bold:!0,color:"green",children:["工具:"," "]},void 0,!0,void 0,this),E(G0,{children:Q.tools.includes("all")?"所有工具":Q.tools.join(", ")||"所有工具"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(G0,{children:[E(G0,{bold:!0,color:"green",children:["颜色:"," "]},void 0,!0,void 0,this),E(G0,{children:Q.color||"默认"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(G0,{children:[E(G0,{bold:!0,color:"green",children:["位置:"," "]},void 0,!0,void 0,this),E(G0,{children:Q.location==="project"?"项目级":"用户级"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(G0,{children:[E(G0,{bold:!0,color:"green",children:["提示词:"," "]},void 0,!0,void 0,this),E(G0,{children:Q.systemPrompt||"(使用默认)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),E(E2,{items:[{label:"确认并保存",value:"save"},{label:"返回上一步",value:"back"},{label:"取消",value:"cancel"}],onSelect:(P)=>{if(P.value==="save")w();else if(P.value==="back")S();else J()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null}function p5({config:$,setConfig:J,onNext:Z,onPrev:Y}){let{isFocused:X}=V5({id:"step-tools"});q0((K,G)=>{if(G.escape)Y()},{isActive:X});let Q=(K)=>{if(K.includes("all"))J({...$,tools:["all"]});else J({...$,tools:K});Z()};return E(N0,{flexDirection:"column",paddingY:1,children:[E(N0,{marginBottom:1,children:E(G0,{bold:!0,color:"cyan",children:"Step 3/7: 选择可用工具"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(N0,{marginBottom:1,children:E(G0,{dimColor:!0,children:"方向键导航,空格切换勾选,Enter 确认进入下一步 | ESC 返回上一步"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E(D5,{options:h5,defaultValue:$.tools,onSubmit:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import x5 from"node:fs";import{useMemoizedFn as x1}from"ahooks";import{Box as v0,Text as g0}from"ink";import j4 from"ink-select-input";import{useEffect as u5,useMemo as C6,useState as h2}from"react";import{jsxDEV as Y0}from"react/jsx-dev-runtime";var E4=10;function I6({workspaceRoot:$,initialMode:J="menu",onComplete:Z,onCancel:Y}){let X=T2($),[Q,K]=h2(J),[G,U]=h2(null),[q,O]=h2(0),[z,_]=h2(0),W=x1(()=>{X.clear(),X.loadFromStandardLocations(),O((T)=>T+1)}),L=C6(()=>{return X.getAllSubagents()},[q]),N=Math.ceil(L.length/E4)||1,A=C6(()=>{let T=z*E4;return L.slice(T,T+E4)},[L,z]);u5(()=>{let T=Math.max(0,N-1);if(z>T)_(T)},[N,z]);let I=x1(()=>{if(z<N-1)_((T)=>T+1)}),H=x1(()=>{if(z>0)_((T)=>T-1)}),S=[{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"}],B=x1((T)=>{if(T.value==="cancel"){Y?.();return}K(T.value)}),w=x1((T)=>{if(U(T.value),Q==="edit")K("editWizard");else if(Q==="delete")K("deleteConfirm")}),M=x1(async()=>{if(!G?.configPath)return;try{await x5.promises.unlink(G.configPath),W(),P()}catch(T){console.error("删除失败:",T)}}),P=x1(()=>{K("menu"),U(null)}),b=h0(!1,Y);if(q0((T,k)=>{if(k.escape){if(Q==="menu")Y?.();else if(Q==="list"||Q==="edit"||Q==="delete")_(0),P();else if(Q==="deleteConfirm")P()}else if(k.ctrl&&T==="c"||k.meta&&T==="c")b();else if(Q==="list"){if(k.leftArrow||T==="h")H();else if(k.rightArrow||T==="l")I()}},{isActive:Q!=="create"&&Q!=="editWizard"}),Q==="menu")return Y0(v0,{flexDirection:"column",paddingY:1,children:[Y0(v0,{marginBottom:1,children:Y0(g0,{bold:!0,color:"cyan",children:"Agents 管理"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Y0(j4,{items:S,onSelect:B},void 0,!1,void 0,this),Y0(v0,{marginTop:1,children:Y0(g0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 退出"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Q==="list"){if(L.length===0)return Y0(v0,{flexDirection:"column",paddingY:1,children:[Y0(v0,{marginBottom:1,children:Y0(g0,{bold:!0,color:"cyan",children:"所有 Agents"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Y0(v0,{paddingLeft:2,children:Y0(g0,{color:"gray",children:"没有找到任何 agent 配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Y0(v0,{marginTop:1,paddingLeft:2,children:Y0(g0,{color:"gray",children:"配置文件位置: .blade/agents/ 或 ~/.blade/agents/"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Y0(v0,{marginTop:1,paddingLeft:2,children:Y0(g0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return Y0(v0,{flexDirection:"column",paddingY:1,children:[Y0(v0,{marginBottom:1,children:[Y0(g0,{bold:!0,color:"cyan",children:"所有 Agents"},void 0,!1,void 0,this),Y0(g0,{color:"gray",children:[" (共 ",L.length," 个)"]},void 0,!0,void 0,this),N>1&&Y0(g0,{color:"yellow",children:[" ","第 ",z+1,"/",N," 页"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),A.map((T)=>Y0(v0,{flexDirection:"column",paddingLeft:2,children:[Y0(v0,{children:Y0(g0,{children:[Y0(g0,{bold:!0,color:T.color||"white",children:["• ",T.name]},void 0,!0,void 0,this),Y0(g0,{color:"gray",children:[" - ",T.description]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),T.tools&&T.tools.length>0&&Y0(v0,{paddingLeft:2,children:Y0(g0,{color:"gray",children:["工具: ",T.tools.join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this),T.configPath&&Y0(v0,{paddingLeft:2,children:Y0(g0,{color:"gray",dimColor:!0,children:T.configPath},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},T.name,!0,void 0,this)),Y0(v0,{marginTop:1,paddingLeft:2,children:N>1?Y0(g0,{dimColor:!0,children:"Left/Right to page | ESC 返回菜单"},void 0,!1,void 0,this):Y0(g0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}let v=(T)=>{if(L.length===0)return Y0(v0,{flexDirection:"column",paddingY:1,children:[Y0(v0,{marginBottom:1,children:Y0(g0,{bold:!0,color:"cyan",children:T},void 0,!1,void 0,this)},void 0,!1,void 0,this),Y0(v0,{paddingLeft:2,children:Y0(g0,{color:"gray",children:"没有找到任何 agent 配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Y0(v0,{marginTop:1,paddingLeft:2,children:Y0(g0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);let k=L.map((y)=>({key:y.name,label:`${y.name} - ${y.description}`,value:y}));return Y0(v0,{flexDirection:"column",paddingY:1,children:[Y0(v0,{marginBottom:1,children:Y0(g0,{bold:!0,color:"cyan",children:T},void 0,!1,void 0,this)},void 0,!1,void 0,this),Y0(j4,{items:k,onSelect:w},void 0,!1,void 0,this),Y0(v0,{marginTop:1,children:Y0(g0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};if(Q==="create")return Y0(m8,{onComplete:()=>{W(),P()},onCancel:P},void 0,!1,void 0,this);if(Q==="edit")return v("编辑 Agent");if(Q==="editWizard"&&G){let T={name:G.name,description:G.description,tools:G.tools||[],color:G.color,location:G.configPath?.includes(".blade/agents")?"project":"user",systemPrompt:G.systemPrompt||""};return Y0(m8,{initialConfig:T,onComplete:()=>{W(),P()},onCancel:P},void 0,!1,void 0,this)}if(Q==="delete")return v("删除 Agent");if(Q==="deleteConfirm"&&G)return Y0(v0,{flexDirection:"column",paddingY:1,children:[Y0(v0,{marginBottom:1,children:Y0(g0,{bold:!0,color:"red",children:"确认删除"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Y0(v0,{marginBottom:1,paddingLeft:2,children:Y0(g0,{children:["你确定要删除 Agent"," ",Y0(g0,{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),Y0(v0,{marginBottom:1,paddingLeft:2,children:Y0(g0,{dimColor:!0,children:["文件路径: ",G.configPath]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Y0(v0,{marginBottom:1,paddingLeft:2,children:Y0(g0,{color:"red",children:"此操作无法撤销!"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Y0(j4,{items:[{label:"确认删除",value:"confirm"},{label:"取消",value:"cancel"}],onSelect:(T)=>{if(T.value==="confirm")M();else P()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null}import{Box as O8,Text as W0}from"ink";import d5,{useEffect as l5,useState as r5}from"react";import{useEffect as c5,useState as S6}from"react";function v6($=Z$(),J=5000){let[Z,Y]=S6(null),[X,Q]=S6(!0);return c5(()=>{let K=!0,G=async()=>{try{let q=await k6($);if(!K)return;if(!q){Y(null),Q(!1);return}let O=await f6($);if(!K)return;Y(O)}catch{if(K)Y(null)}finally{if(K)Q(!1)}};G();let U=null;if(J>0)U=setInterval(G,J);return()=>{if(K=!1,U)clearInterval(U)}},[$,J]),{branch:Z,loading:X}}import{jsxDEV as X0,Fragment as m$}from"react/jsx-dev-runtime";var V6=d5.memo(()=>{let $=Z2(),J=Z8(),Y=J2()==="shortcuts",X=K9(),Q=o$(),{branch:K}=v6(Q),G=X2(),U=$9(),q=rJ(),O=K2(),z=G2(),_=U2(),W=q2(),L=z2(),N=aJ(),A=iJ(),I=Q8(),H=H9(),S=Y8(),[B,w]=r5(null);l5(()=>{let k=!1;new h4(Q,S).get().then((o)=>{if(!k)w(o)}).catch(()=>{if(!k)w(null)});let j=h4.subscribe((o)=>{if(!k&&o.sessionId===S&&o.workspaceRoot===Q)w(o.goal)});return()=>{k=!0,j()}},[S,Q]);let M=G?S2(G):!1,b=(()=>{if(J==="default")return null;if(J==="autoEdit")return X0(W0,{color:"magenta",children:[">> ","auto edit on ",X0(W0,{color:"gray",children:"(shift+tab to cycle)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(J==="plan")return X0(W0,{color:"cyan",children:["‖ plan mode on ",X0(W0,{color:"gray",children:"(shift+tab to cycle)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(J==="yolo")return X0(W0,{color:"red",children:["yolo mode on ",X0(W0,{color:"gray",children:"(all tools auto-approved)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null})(),v=b!==null,T=[["Enter:发送","Shift+Enter:换行","Esc:中止"],["Shift+Tab:切换模式","Up/Down:历史","Tab:补全"],["Ctrl+A:行首","Ctrl+E:行尾","Ctrl+K:删到尾"],["Ctrl+U:删到首","Ctrl+W:删单词","Ctrl+C:退出"],["Ctrl+O:浏览记录","PgUp/PgDn:翻页","g/G:首尾"]];return X0(O8,{flexDirection:"row",justifyContent:"space-between",paddingX:2,paddingY:0,children:[Y?X0(O8,{flexDirection:"column",gap:0,children:T.map((k,y)=>X0(O8,{flexDirection:"row",children:[k.map((j,o)=>{let[t,a]=j.split(":");return X0(O8,{flexDirection:"row",width:20,children:[X0(W0,{color:"yellow",children:t},void 0,!1,void 0,this),X0(W0,{color:"gray",children:":"},void 0,!1,void 0,this),X0(W0,{color:"white",children:a},void 0,!1,void 0,this)]},o,!0,void 0,this)}),y===T.length-1&&X0(W0,{color:"cyan",children:" ? 关闭"},void 0,!1,void 0,this)]},y,!0,void 0,this))},void 0,!1,void 0,this):X0(O8,{flexDirection:"row",gap:1,children:[K&&X0(m$,{children:[X0(W0,{color:"gray",children:[" ",K]},void 0,!0,void 0,this),X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b,v&&X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this),B&&X0(m$,{children:[X0(W0,{color:B.status==="active"?"green":B.status==="verifying"?"cyan":B.status==="blocked"||B.status==="budget_limited"?"yellow":"gray",children:["goal:",B.status," ",B.objective.slice(0,32),B.prematureStop?` recovery:${B.prematureStop.consecutiveCount}`:"",B.verificationStall?` verify-gap:${B.verificationStall.consecutiveCount}`:"",B.frontierStall?` frontier:${B.frontierStall.category}:${B.frontierStall.consecutiveCount}`:""]},void 0,!0,void 0,this),X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),X0(W0,{color:"gray",children:"? for shortcuts"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),X0(O8,{flexDirection:"row",gap:1,children:!$?X0(W0,{color:"red",children:"[WARN] API 密钥未配置"},void 0,!1,void 0,this):X0(m$,{children:[M&&X0(m$,{children:[O?X0(W0,{color:"cyan",children:["Effort ",z]},void 0,!0,void 0,this):X0(W0,{color:"gray",children:"Tab:Effort"},void 0,!1,void 0,this),X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),_!=="auto"&&X0(m$,{children:[X0(W0,{color:_==="fast"?"yellow":"gray",children:["Speed ",_]},void 0,!0,void 0,this),X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W!=="auto"&&X0(m$,{children:[X0(W0,{color:"gray",children:["Output ",W]},void 0,!0,void 0,this),X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),L!=="auto"&&X0(m$,{children:[X0(W0,{color:"gray",children:["Style ",L]},void 0,!0,void 0,this),X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),G&&X0(W0,{color:"gray",children:G.model},void 0,!1,void 0,this),X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this),q?X0(W0,{color:"yellow",children:"压缩中..."},void 0,!1,void 0,this):X0(W0,{color:U<20?"red":U<50?"yellow":"gray",children:[U,"%"]},void 0,!0,void 0,this),X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this),X0(W0,{color:A===void 0?"gray":"cyan",children:["Cache ",D6(A)]},void 0,!0,void 0,this),N>0.001&&X0(m$,{children:[X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this),X0(W0,{color:"green",children:["$",N<0.01?N.toFixed(4):N.toFixed(3)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),I.length>0&&X0(m$,{children:[X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this),X0(W0,{color:"yellow",children:["已排队 ",I.length]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),H>0&&X0(m$,{children:[X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this),X0(W0,{color:"cyan",children:["已恢复 ",H," 条指令"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),X&&X0(m$,{children:[X0(W0,{color:"gray",children:"·"},void 0,!1,void 0,this),X0(W0,{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 g4,Text as m4}from"ink";import a5 from"react";import{jsxDEV as _8}from"react/jsx-dev-runtime";var j6=a5.memo(({suggestions:$,selectedIndex:J,visible:Z,maxDisplay:Y=8})=>{if(!Z||$.length===0)return null;let X=0,Q=Math.min(Y,$.length),K=J>=$.length;if(J>=Y&&!K)X=J-Y+1,Q=J+1;let G=$.slice(X,Q),U=$.length>Y;return _8(g4,{flexDirection:"column",paddingX:2,paddingY:0,children:[G.map((q,O)=>{let _=X+O===J;return _8(g4,{flexDirection:"row",paddingX:1,gap:2,children:[_8(m4,{color:_?"cyan":"white",bold:_,children:q.command},void 0,!1,void 0,this),_8(m4,{color:_?"cyan":"gray",dimColor:!_,children:["- ",q.description]},void 0,!0,void 0,this)]},q.command,!0,void 0,this)}),U&&_8(g4,{paddingX:1,children:_8(m4,{color:K?"cyan":"gray",bold:K,dimColor:!K,children:["... and ",$.length-Y," more"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as v$,Text as s$,useStdout as rX}from"ink";import aX from"ink-select-input";import qJ,{useMemo as NY}from"react";import{Box as L0,Text as k0}from"ink";import c1,{useEffect as GJ,useMemo as u1,useRef as zY}from"react";import{Box as t4,Text as a6}from"ink";import GX from"react";import{Text as p$}from"ink";import XX from"react";import d6 from"string-width";import p8 from"string-width";function p4({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 i5=p4();function x4($){if(typeof $!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof $}\``);if(!$.includes("\x1B")&&!$.includes(""))return $;return $.replace(i5,"")}var E6=($=0)=>(J)=>`\x1B[${J+$}m`,h6=($=0)=>(J)=>`\x1B[${38+$};5;${J}m`,g6=($=0)=>(J,Z,Y)=>`\x1B[${38+$};2;${J};${Z};${Y}m`,c0={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]}},sq=Object.keys(c0.modifier),o5=Object.keys(c0.color),n5=Object.keys(c0.bgColor),eq=[...o5,...n5];function t5(){let $=new Map;for(let[J,Z]of Object.entries(c0)){for(let[Y,X]of Object.entries(Z))c0[Y]={open:`\x1B[${X[0]}m`,close:`\x1B[${X[1]}m`},Z[Y]=c0[Y],$.set(X[0],X[1]);Object.defineProperty(c0,J,{value:Z,enumerable:!1})}return Object.defineProperty(c0,"codes",{value:$,enumerable:!1}),c0.color.close="\x1B[39m",c0.bgColor.close="\x1B[49m",c0.color.ansi=E6(),c0.color.ansi256=h6(),c0.color.ansi16m=g6(),c0.bgColor.ansi=E6(10),c0.bgColor.ansi256=h6(10),c0.bgColor.ansi16m=g6(10),Object.defineProperties(c0,{rgbToAnsi256:{value(J,Z,Y){if(J===Z&&Z===Y){if(J<8)return 16;if(J>248)return 231;return Math.round((J-8)/247*24)+232}return 16+36*Math.round(J/255*5)+6*Math.round(Z/255*5)+Math.round(Y/255*5)},enumerable:!1},hexToRgb:{value(J){let Z=/[a-f\d]{6}|[a-f\d]{3}/i.exec(J.toString(16));if(!Z)return[0,0,0];let[Y]=Z;if(Y.length===3)Y=[...Y].map((Q)=>Q+Q).join("");let X=Number.parseInt(Y,16);return[X>>16&255,X>>8&255,X&255]},enumerable:!1},hexToAnsi256:{value:(J)=>c0.rgbToAnsi256(...c0.hexToRgb(J)),enumerable:!1},ansi256ToAnsi:{value(J){if(J<8)return 30+J;if(J<16)return 90+(J-8);let Z,Y,X;if(J>=232)Z=((J-232)*10+8)/255,Y=Z,X=Z;else{J-=16;let G=J%36;Z=Math.floor(J/36)/5,Y=Math.floor(G/6)/5,X=G%6/5}let Q=Math.max(Z,Y,X)*2;if(Q===0)return 30;let K=30+(Math.round(X)<<2|Math.round(Y)<<1|Math.round(Z));if(Q===2)K+=60;return K},enumerable:!1},rgbToAnsi:{value:(J,Z,Y)=>c0.ansi256ToAnsi(c0.rgbToAnsi256(J,Z,Y)),enumerable:!1},hexToAnsi:{value:(J)=>c0.ansi256ToAnsi(c0.hexToAnsi256(J)),enumerable:!1}}),c0}var s5=t5(),m6=s5;var m2=new Set(["\x1B",""]),e5=39,c4="\x07",u6="[",$X="]",c6="m",g2=`${$X}8;;`,p6=($)=>`${m2.values().next().value}${u6}${$}${c6}`,x6=($)=>`${m2.values().next().value}${g2}${$}${c4}`,JX=($)=>$.split(" ").map((J)=>p8(J)),u4=($,J,Z)=>{let Y=[...J],X=!1,Q=!1,K=p8(x4($.at(-1)));for(let[G,U]of Y.entries()){let q=p8(U);if(K+q<=Z)$[$.length-1]+=U;else $.push(U),K=0;if(m2.has(U))X=!0,Q=Y.slice(G+1,G+1+g2.length).join("")===g2;if(X){if(Q){if(U===c4)X=!1,Q=!1}else if(U===c6)X=!1;continue}if(K+=q,K===Z&&G<Y.length-1)$.push(""),K=0}if(!K&&$.at(-1).length>0&&$.length>1)$[$.length-2]+=$.pop()},YX=($)=>{let J=$.split(" "),Z=J.length;while(Z>0){if(p8(J[Z-1])>0)break;Z--}if(Z===J.length)return $;return J.slice(0,Z).join(" ")+J.slice(Z).join("")},ZX=($,J,Z={})=>{if(Z.trim!==!1&&$.trim()==="")return"";let Y="",X,Q,K=JX($),G=[""];for(let[z,_]of $.split(" ").entries()){if(Z.trim!==!1)G[G.length-1]=G.at(-1).trimStart();let W=p8(G.at(-1));if(z!==0){if(W>=J&&(Z.wordWrap===!1||Z.trim===!1))G.push(""),W=0;if(W>0||Z.trim===!1)G[G.length-1]+=" ",W++}if(Z.hard&&K[z]>J){let L=J-W,N=1+Math.floor((K[z]-L-1)/J);if(Math.floor((K[z]-1)/J)<N)G.push("");u4(G,_,J);continue}if(W+K[z]>J&&W>0&&K[z]>0){if(Z.wordWrap===!1&&W<J){u4(G,_,J);continue}G.push("")}if(W+K[z]>J&&Z.wordWrap===!1){u4(G,_,J);continue}G[G.length-1]+=_}if(Z.trim!==!1)G=G.map((z)=>YX(z));let U=G.join(`
|
|
122
122
|
`),q=[...U],O=0;for(let[z,_]of q.entries()){if(Y+=_,m2.has(_)){let{groups:L}=new RegExp(`(?:\\${u6}(?<code>\\d+)m|\\${g2}(?<uri>.*)${c4})`).exec(U.slice(O))||{groups:{}};if(L.code!==void 0){let N=Number.parseFloat(L.code);X=N===e5?void 0:N}else if(L.uri!==void 0)Q=L.uri.length===0?void 0:L.uri}let W=m6.codes.get(Number(X));if(q[z+1]===`
|
|
123
123
|
`){if(Q)Y+=x6("");if(X&&W)Y+=p6(W)}else if(_===`
|
|
124
124
|
`){if(X&&W)Y+=p6(X);if(Q)Y+=x6(Q)}O+=_.length}return Y};function d4($,J,Z){return String($).normalize().replaceAll(`\r
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ui as $,Vi as F}from"./chunk-tgdhsm5t.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
|
|
2
2
|
`,{mode:384}),await J.chmod(this.filePath,384)}}var _=new K;
|
|
3
3
|
export{_ as g};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{s as cz,t as pz}from"./chunk-
|
|
1
|
+
import{s as cz,t as pz}from"./chunk-afa35v3f.js";import{u as S}from"./chunk-khtxprbv.js";import{A as Oz,v as gz,w as wz,x as Dz,y as _z,z as Nz}from"./chunk-k9fveqq6.js";import{H as E,Q as Bz,R as Gz,V as Uz,Y as jz,Z as Vz,aa as Kz,qa as Az,ra as qz,sa as Pz,ta as Rz}from"./chunk-b0j9v359.js";import"./chunk-abd57h72.js";import{Ha as uz}from"./chunk-xtb84adp.js";import{Ja as Fz}from"./chunk-xm8nyj5z.js";import{Db as Yz,Mb as Lz,rb as Xz}from"./chunk-0aa40zbs.js";import{Xb as g}from"./chunk-8hprmrd5.js";import{Cd as p,Dd as $z,Fd as h,Id as Wz,Nd as P,Qd as j,ad as zz,kd as y,ld as c,md as Hz,rd as Jz,ud as Qz,wd as Zz}from"./chunk-wzmqkam9.js";import"./chunk-s0tq8gyx.js";import"./chunk-x3cxmwnz.js";import{ve as mz}from"./chunk-gr80w0vh.js";import"./chunk-z9gd9spf.js";import{Qe as kz,Re as Iz}from"./chunk-q6eb20fz.js";import"./chunk-v508x7cg.js";import{af as m}from"./chunk-dg0d3303.js";import{ff as e}from"./chunk-rchz6j90.js";import"./chunk-w7hy5wh1.js";import{qf as Cz}from"./chunk-2hb222re.js";import"./chunk-07w0qapm.js";import"./chunk-ywarj5j9.js";import"./chunk-kf7whgr7.js";import{ig as fz}from"./chunk-fva7jnjy.js";import"./chunk-41ympwz1.js";import"./chunk-aa5zmwd9.js";import"./chunk-41cg66y0.js";import{ah as yz,dh as Mz}from"./chunk-f945dzj6.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import{Hh as C,Ih as t,Kh as f,Lh as u}from"./chunk-c475tfqf.js";import{Ph as bz}from"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import{pi as M}from"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import{wi as hz,zi as Sz}from"./chunk-9p20hhs0.js";import"./chunk-14bs89sm.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import{Vi as s}from"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";import{Readable as JH,Writable as QH}from"node:stream";import*as k from"@agentclientprotocol/sdk";import Ez from"node:path";import{PROTOCOL_VERSION as zH,RequestError as HH}from"@agentclientprotocol/sdk";import{createHash as lz}from"node:crypto";import{RequestError as Tz}from"@agentclientprotocol/sdk";import{nanoid as I}from"nanoid";var U=M("Agent"),i=4,iz=1000,a=4000,r=120000,o=0.2;function n(z){if(!z)return{};return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function az(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:n(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:n("headers"in z?z.headers:void 0)};return null}function rz(z){let J={};for(let H of z){let W=az(H);if(W)J[H.name]=W}return J}function xz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let H=J.image_url.url,W=/^data:([^;,]+);base64,(.+)$/s.exec(H);if(!W)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:W[1]??"image/png",data:W[2]??""}]})}function oz(z){let J=$z(z.metadata);return J?[{type:"text",text:p(J)}]:xz(z.content)}function nz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
2
|
`)}function sz(z){if(!e(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...y("capacity"),resource:z.resource}}function tz(z,J){let H=Math.max(0,J-1),W=Math.min(iz*2**H,a),Y=lz("sha256").update(`${z}\x00${J}`).digest().readUInt32BE(0)/4294967295,Z=1-o+2*o*Y;return Math.min(a,Math.max(0,Math.round(W*Z)))}function ez(z){if(!(z instanceof Tz)||!z.data||typeof z.data!=="object")return;let J=z.data;if(!Hz(J.taskFailure)||J.toolExecutionStarted!==!1||!Number.isInteger(J.toolCallsCount)||J.toolCallsCount<0||J.outputStarted!==!1)return;return{taskFailure:J.taskFailure,toolExecutionStarted:J.toolExecutionStarted,toolCallsCount:J.toolCallsCount,outputStarted:J.outputStarted}}class b{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,J,H,W,X={}){this.id=z;this.cwd=J;this.connection=H;this.clientCapabilities=W;this.options=X;this.messages=[...X.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(X.permissionMode),this.updateEgress=new Oz({maxPendingItems:wz,maxPendingBytes:Dz,writeTimeoutMs:_z,signal:H.signal,sizeOf:(Y)=>Buffer.byteLength(JSON.stringify(Y)),write:async(Y)=>{await H.sessionUpdate(Y)},onFailure:(Y)=>this.handleUpdateEgressFailure(Y)})}async refreshPersistedMessages(){let[z,J]=await Promise.all([j.loadSession(this.id,this.cwd),j.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(J.length>0)this.contextMessages=J}async loadModelContextOr(z){let J=await j.loadSessionModelContext(this.id,this.cwd);return J.length>0?J:[...z]}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return Kz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(U.debug(`[AcpSession ${this.id}] Initializing...`),await j.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),E.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async($)=>{await this.sendUpdateAndWait($)}),U.debug(`[AcpSession ${this.id}] ACP service context initialized`),await Lz.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:($)=>this.requestPermission($)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let J=this.options.mcpServers?rz(this.options.mcpServers):void 0,H=E.getInstance().getTerminalService(this.id);if(this.runtime=await Uz.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...J?{mcpServers:J}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async($,F)=>{let L=await H.execute($,{cwd:F.cwd,env:F.env,timeout:F.timeoutMs,signal:F.signal,allowLocalFallback:!1,onOutput:(B)=>F.onOutput?.("stdout",B)});return{exitCode:L.exitCode,stdout:L.stdout,stderr:L.stderr,...L.error?{error:L.error}:{},timedOut:L.failureKind==="timeout",aborted:L.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await S.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await qz(this.cwd),U.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Xz.subscribe(($)=>{if($.sessionId!==this.id||$.projectPath!==this.cwd)return;if($.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":$.properties}}),this.requestPendingResume();return}if($.type==="task.delivery"){if(!$.properties.taskDelivery||typeof $.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":$.properties.taskDelivery,...$.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if($.type.startsWith("team.")){let{teamName:F,messageId:L,content:B}=$.properties,G=$.properties.metadata;if($.type==="team.message.received"&&typeof F==="string"&&typeof L==="string"&&typeof B==="string"&&Gz(G,{messageId:L,teamName:F}))(async()=>{let V=await this.runtime?.enqueueSteering(B,{allowBeforeTurn:!0,messageId:L,origin:"team_message",metadata:G});if(!V?.accepted)return;if(await new Bz(F,s()).markDelivered([L]),V.delivery==="next_turn")this.requestPendingResume()})().catch((V)=>{U.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,V)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:$.type,...$.properties}}});return}if($.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":$.properties.taskStatus,...typeof $.properties.taskStatusReason==="string"?{"blade/taskStatusReason":$.properties.taskStatusReason}:{},...$.properties.taskFailure&&typeof $.properties.taskFailure==="object"?{"blade/taskFailure":$.properties.taskFailure}:{},...typeof $.properties.taskStartedAt==="string"?{"blade/taskStartedAt":$.properties.taskStartedAt}:{},...typeof $.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":$.properties.taskCompletedAt}:{},...$.properties.taskDiffStat&&typeof $.properties.taskDiffStat==="object"?{"blade/taskDiffStat":$.properties.taskDiffStat}:{},...typeof $.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":$.properties.taskQueuePosition}:{},...typeof $.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":$.properties.taskQueueDepth}:{},...typeof $.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":$.properties.taskConcurrencyLimit}:{},...typeof $.properties.taskInFlight==="number"?{"blade/taskInFlight":$.properties.taskInFlight}:{}}})});let X=await this.runtime.getGoal(),Y=this.runtime.getPendingSteeringCount()>0,Z=X?.status==="active"||X?.status==="verifying";if(Y||Z)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let $=this.runtime.getTurnRecoveryAssessment();if($.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":$}})}}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;if(!Zz(J))continue;let H=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!H)continue;for(let W of oz(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:H,content:W}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.ensurePendingResumeScheduled()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);U.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,J){try{U.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let $=await this.runtime.rewindSession(Z);return this.messages=[...$.messages],this.contextMessages=await this.loadModelContextOr($.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),$}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Z)=>{if(await this.setReasoningEffort(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Z)=>{if(await this.setServiceTier(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Z)=>{if(await this.setResponseVerbosity(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Z)=>{if(await this.setCommunicationStyle(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=!1,L,B=(V)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:V.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:V.result?.message||V.result?.error||`Subagent ${V.status}`}}]})},G=this.runtime.resumeSubagent({agentId:Z,prompt:$,onCompleted:(V)=>{if(F)B(V);else L=V}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.session.id,status:"in_progress",title:`Resuming ${G.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${G.source.id} at depth ${G.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),F=!0,L)B(L);return G}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Z)},getPrompt:async(Z,$,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Z,$,F)},complete:async(Z,$,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Z,$,F)},listTasks:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Z)},getTask:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Z)},cancelTask:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Z,$)},getLogs:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Z,$)},setLoggingLevel:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Z,$)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},sideConversation:{ask:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Z,{signal:$})}},codeReview:{run:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=await S.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Z,signal:$,onEvent:(G)=>{if(G.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.toolCall.id,status:"in_progress",title:`Review: ${G.toolCall.function.name}`,content:[],kind:this.mapToolKind(G.toolKind)});else if(G.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:G.toolCall.id,status:G.result.success?"completed":"failed",content:[]})}}),L=await F.completion,B=(await S.list(this.cwd,this.id)).find((G)=>G.start.reviewId===F.reviewId);if(!B)throw Error(`Review not found: ${F.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:F.reviewId,status:L.status,findings:L.findings.length,content:zz(B.start,L)}}},signal:J,acp:{sendMessage:(Z)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Z}})},sendToolStart:(Z,$,F)=>{let L=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,B=this.mapToolKind(F);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L,status:"in_progress",title:`${Z}`,content:[{type:"content",content:{type:"text",text:JSON.stringify($,null,2)}}],kind:B})},sendToolResult:(Z,$)=>{if($.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.summary}})}}},W=await Pz(z,H),X=W.data?.action;if(X==="start_goal"||X==="resume_goal")this.requestPendingResume();if(X==="rewind_session"&&Array.isArray(W.data?.messages))this.messages=[...W.data.messages],this.contextMessages=await this.loadModelContextOr(W.data.messages);if((W.message==="compact_completed"||W.message==="compact_fallback")&&W.data?.compactedMessages){this.contextMessages=[...W.data.compactedMessages];let Z=await j.loadSession(this.id,this.cwd);if(Z.length>0)this.messages=Z}let Y=W.content||W.message;if(Y)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y}});if(W.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${W.error}`}});return await this.flushUpdates(),{stopReason:W.success?"end_turn":"cancelled"}}catch(H){if(J.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};return U.error(`[AcpSession ${this.id}] Slash command error:`,H),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${H instanceof Error?H.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let J=new AbortController,H,W=new Promise((X)=>{H=X});this.pendingSideConversation=J,this.pendingSideConversationCompletion=W;try{return await this.handleSlashCommand(z,J.signal)}catch(X){if(J.signal.aborted||X instanceof Error&&X.name==="AbortError")return{stopReason:"cancelled"};throw X}finally{if(H(),this.pendingSideConversationCompletion===W)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===J){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=Rz(this.cwd,this.runtime?.getAgentResources()),J=["model","permissions","theme","config","exit","ide"],W=z.filter((X)=>!J.includes(X.name)&&(X.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((X)=>{let Y;if(X.usage){let Z=X.usage.replace(/^\/\w+\s*/,"").trim();if(Z)Y=Z}if(X.aliases?.length){let Z=`Aliases: ${X.aliases.join(", ")}`;Y=Y?`${Y} | ${Z}`:Z}return{name:X.name,description:X.description,input:Y?{hint:Y}:void 0}});U.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(W.map((X)=>X.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:W}),U.info(`[AcpSession ${this.id}] Sent ${W.length} available commands`)}catch(z){U.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,J={}){if(E.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let H=this.resolvePrompt(z.prompt),W=H.content,X=H.displayText,Y=z._meta?.outputSchema??(J.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((w)=>w.outputSchema)?.outputSchema:void 0),Z;if(Y!==void 0)Z=Wz(Y).schema;if(X.trimStart().startsWith("!")){if(Z)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(X)}let $=Fz(X);if($){if(Z)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(W)&&W.some((w)=>w.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand($.question?`/btw ${$.question}`:"/btw")}if(this.pendingPrompt){if(Z)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(X.trim()))return this.handleSlashCommand(X,this.pendingPrompt.signal);let w=await this.runtime.enqueueSteering(W,{allowBeforeTurn:!0});if(!w.accepted)throw Error(w.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(U.debug(`[AcpSession ${this.id}] Queued steering for active turn (${w.queued})`),w.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let F=new AbortController,L=()=>{F.abort(J.abortSignal?.reason)};if(J.abortSignal?.aborted)L();else J.abortSignal?.addEventListener("abort",L,{once:!0});let B=!1,G=!1,V=!1,R,T=new Promise((w)=>{R=w});this.pendingPrompt=F,this.pendingPromptCompletion=T;try{if(U.debug(`[AcpSession ${this.id}] Received prompt: ${X.slice(0,100)}...`),Az(X)){if(Z)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(X,F.signal)}let w={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:F.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(Q)=>{this.mode=this.mapPermissionModeToMode(Q),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(Q)=>{return this.requestPermission(Q)}}},N=await Yz(this.agent.chatStream(W,w,{pendingInputOnly:J.pendingInputOnly,goalContinuationOnly:J.goalContinuationOnly,outputSchema:Z}),async(Q)=>{switch(Q.kind){case"content_delta":if(Z)break;if(Q.delta.length>0)G=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q.delta}});break;case"thinking_delta":if(Q.delta.length>0)G=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:Q.delta}});break;case"tool_start":{V=!0;let K=Q.toolCall,O=K.function.name;if(O===h)break;let q=this.mapToolKind(Q.toolKind),D=`Executing ${O}`;if(O==="Task"&&"function"in K)try{let x=JSON.parse(K.function.arguments),_=x.resume_from??x.resume;if(typeof _==="string")D=`Resuming ${String(x.subagent_type||"subagent")} from ${_}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:K.id,status:"in_progress",title:D,content:[],kind:q});break}case"tool_progress":{V=!0;let K=Q.toolCall;if(K.function.name===h)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:K.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:Q.update.message}}]});break}case"tool_result":{V=!0;let K=Q.toolCall;if(K.function.name===h)break;let O=Q.result,q=[],D=O.metadata;if(D?.kind==="patch"&&Array.isArray(D.changes))for(let _ of D.changes){if(!_||typeof _!=="object"||!("path"in _)||typeof _.path!=="string")continue;q.push({type:"diff",path:_.path,oldText:"oldContent"in _&&typeof _.oldContent==="string"?_.oldContent:null,newText:"newContent"in _&&typeof _.newContent==="string"?_.newContent:null})}else if(D?.kind==="edit"&&typeof D.file_path==="string"&&typeof D.oldContent==="string"&&(typeof D.newContent==="string"||D.newContent===void 0))q.push({type:"diff",path:D.file_path,oldText:D.oldContent,newText:D.newContent??null});else{let _=K.function.name,dz=Vz(Qz(jz(_,O),Jz));q.push({type:"content",content:{type:"text",text:dz}})}if(K.function.name==="Task"&&(D?.verificationVerdict==="pass"||D?.verificationVerdict==="fail"||D?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${D.verificationVerdict.toUpperCase()}`}});let x=O.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:K.id,status:x,content:q});break}case"structured_output":G=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(Q.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${Q.revision} (${Q.serverName}): +${Q.added.length} -${Q.removed.length} ~${Q.updated.length}
|
|
3
3
|
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${Q.contentKind} r${Q.revision} (${Q.serverName}): +${Q.added.length} -${Q.removed.length} ~${Q.updated.length}
|
|
4
4
|
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${Q.revision} (${Q.serverName}): ${Q.uri}
|
|
@@ -7,7 +7,7 @@ import{s as cz,t as pz}from"./chunk-rkk39efr.js";import{u as S}from"./chunk-fn9c
|
|
|
7
7
|
`}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${Q.revision} (${Q.serverName}): ${Q.action}${Q.detailsOmitted?" details-omitted":""}
|
|
8
8
|
`}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${Q.revision} ${Q.taskId} (${Q.serverName}/${Q.toolName}): ${Q.status}${Q.hasResult?" result-available":""}
|
|
9
9
|
`}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${Q.files.length}${Q.blockedWrite?" (write retry required)":""}
|
|
10
|
-
`}});break;case"provider_admission":B=Q.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":Q.phase!=="admitted"?{phase:Q.phase,requestClass:Q.requestClass,resource:Q.resource,scope:Q.scope,...Q.reason!==void 0?{reason:Q.reason}:{},queuePosition:Q.queuePosition,queueDepth:Q.queueDepth,inFlight:Q.inFlight,limit:Q.limit,waitMs:Q.waitMs,maxWaitMs:Q.maxWaitMs,...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:Q.phase,reason:Q.reason,...Q.statusCode!==void 0?{statusCode:Q.statusCode}:{},...Q.retryAfterMs!==void 0?{retryAfterMs:Q.retryAfterMs}:{},...Q.nextProbeAt!==void 0?{nextProbeAt:Q.nextProbeAt}:{},openDurationMs:Q.openDurationMs,...Q.sampleCount!==void 0?{sampleCount:Q.sampleCount}:{},...Q.failureCount!==void 0?{failureCount:Q.failureCount}:{},...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:Q.phase,attempt:Q.attempt,maxRetries:Q.maxRetries,reason:Q.reason,...Q.statusCode!==void 0?{statusCode:Q.statusCode}:{},...Q.delayMs!==void 0?{delayMs:Q.delayMs}:{},...Q.nextRetryAt!==void 0?{nextRetryAt:Q.nextRetryAt}:{},...Q.mode!==void 0?{mode:Q.mode}:{},...Q.recoveryBudgetMs!==void 0?{recoveryBudgetMs:Q.recoveryBudgetMs}:{},...Q.recoveryElapsedMs!==void 0?{recoveryElapsedMs:Q.recoveryElapsedMs}:{},...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{},...Q.exhaustedBy!==void 0?{exhaustedBy:Q.exhaustedBy}:{}}}});break;case"turn_recovery":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Q.assessment}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:Q.phase,stallCount:Q.stallCount,durationMs:Q.durationMs,warningAfterMs:Q.warningAfterMs,timeoutMs:Q.timeoutMs,outputStarted:Q.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:Q.phase,toolName:Q.toolName,runLength:Q.runLength,nudgeThreshold:Q.nudgeThreshold,haltThreshold:Q.haltThreshold,progressAware:Q.progressAware}}});break;case"task_update":this.sendPlanUpdate(Q.tasks);break;case"goal_frontier_updated":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:Q.frontier.observedAt,_meta:{"blade/goalFrontier":{goalId:Q.goal.goalId,status:Q.goal.status,taskListId:Q.frontier.taskListId,total:Q.frontier.total,completed:Q.frontier.completed,inProgress:Q.frontier.inProgress,pending:Q.frontier.pending,blocked:Q.frontier.blocked,nextTask:Q.frontier.nextTask,digestSha256:Q.frontier.digestSha256}}}),this.sendPlanUpdate(Q.tasks);break;case"steering_applied":break;case"follow_up_started":{let K=0;for(let O of Q.messages){if(!O.recovered||O.persisted)continue;if(J.projectedRecoveredInputIds?.has(O.id))continue;for(let q of xz(O.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q});J.projectedRecoveredInputIds?.add(O.id),K++}if(K>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${K} queued instruction${K===1?"":"s"} recovered after restart]
|
|
10
|
+
`}});break;case"provider_admission":B=Q.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":Q.phase!=="admitted"?{phase:Q.phase,requestClass:Q.requestClass,resource:Q.resource,scope:Q.scope,...Q.reason!==void 0?{reason:Q.reason}:{},queuePosition:Q.queuePosition,queueDepth:Q.queueDepth,inFlight:Q.inFlight,limit:Q.limit,waitMs:Q.waitMs,maxWaitMs:Q.maxWaitMs,...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:Q.phase,reason:Q.reason,...Q.statusCode!==void 0?{statusCode:Q.statusCode}:{},...Q.retryAfterMs!==void 0?{retryAfterMs:Q.retryAfterMs}:{},...Q.nextProbeAt!==void 0?{nextProbeAt:Q.nextProbeAt}:{},openDurationMs:Q.openDurationMs,...Q.sampleCount!==void 0?{sampleCount:Q.sampleCount}:{},...Q.failureCount!==void 0?{failureCount:Q.failureCount}:{},...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:Q.phase,attempt:Q.attempt,maxRetries:Q.maxRetries,reason:Q.reason,...Q.statusCode!==void 0?{statusCode:Q.statusCode}:{},...Q.delayMs!==void 0?{delayMs:Q.delayMs}:{},...Q.nextRetryAt!==void 0?{nextRetryAt:Q.nextRetryAt}:{},...Q.mode!==void 0?{mode:Q.mode}:{},...Q.recoveryBudgetMs!==void 0?{recoveryBudgetMs:Q.recoveryBudgetMs}:{},...Q.recoveryElapsedMs!==void 0?{recoveryElapsedMs:Q.recoveryElapsedMs}:{},...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{},...Q.exhaustedBy!==void 0?{exhaustedBy:Q.exhaustedBy}:{}}}});break;case"turn_recovery":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Q.assessment}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:Q.phase,stallCount:Q.stallCount,durationMs:Q.durationMs,warningAfterMs:Q.warningAfterMs,timeoutMs:Q.timeoutMs,outputStarted:Q.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:Q.phase,toolName:Q.toolName,runLength:Q.runLength,nudgeThreshold:Q.nudgeThreshold,haltThreshold:Q.haltThreshold,progressAware:Q.progressAware}}});break;case"task_update":this.sendPlanUpdate(Q.tasks);break;case"goal_frontier_updated":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:Q.frontier.observedAt,_meta:{"blade/goalFrontier":{goalId:Q.goal.goalId,status:Q.goal.status,taskListId:Q.frontier.taskListId,total:Q.frontier.total,completed:Q.frontier.completed,inProgress:Q.frontier.inProgress,pending:Q.frontier.pending,blocked:Q.frontier.blocked,nextTask:Q.frontier.nextTask,digestSha256:Q.frontier.digestSha256,...Q.goal.frontierStall?{stall:{category:Q.goal.frontierStall.category,consecutiveCount:Q.goal.frontierStall.consecutiveCount}}:{}}}}),this.sendPlanUpdate(Q.tasks);break;case"steering_applied":break;case"follow_up_started":{let K=0;for(let O of Q.messages){if(!O.recovered||O.persisted)continue;if(J.projectedRecoveredInputIds?.has(O.id))continue;for(let q of xz(O.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q});J.projectedRecoveredInputIds?.add(O.id),K++}if(K>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${K} queued instruction${K===1?"":"s"} recovered after restart]
|
|
11
11
|
`}});break}case"goal_updated":if(Q.goal)this.sendUpdate(this.goalSessionUpdate(Q.goal));if(Q.goal&&Q.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${Q.goal.status}: ${Q.goal.objective}]
|
|
12
12
|
`}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:Q.goal.goalId,continuation:Q.continuation,...Q.prematureStopPattern?{prematureStopPattern:Q.prematureStopPattern}:{},...Q.prematureStopCount!==void 0?{prematureStopCount:Q.prematureStopCount}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:Q.phase,...Q.reason?{reason:Q.reason}:{},...Q.strategy?{strategy:Q.strategy}:{},...Q.outcome?{outcome:Q.outcome}:{},...Q.preTokens!==void 0?{preTokens:Q.preTokens}:{},...Q.preTokenSource?{preTokenSource:Q.preTokenSource}:{},...Q.estimatedPendingTokens!==void 0?{estimatedPendingTokens:Q.estimatedPendingTokens}:{},...Q.postTokens!==void 0?{postTokens:Q.postTokens}:{},...Q.sampleAttempts!==void 0?{sampleAttempts:Q.sampleAttempts}:{},...Q.inputReductions!==void 0?{inputReductions:Q.inputReductions}:{},...Q.messagesOmitted!==void 0?{messagesOmitted:Q.messagesOmitted}:{},...Q.filesOmitted!==void 0?{filesOmitted:Q.filesOmitted}:{},...Q.imagesOmitted!==void 0?{imagesOmitted:Q.imagesOmitted}:{},...Q.fallbackTargetTokens!==void 0?{fallbackTargetTokens:Q.fallbackTargetTokens}:{},...Q.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:Q.fallbackMessagesOmitted}:{},...Q.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:Q.fallbackMessagesTruncated}:{},...Q.failureReason?{failureReason:Q.failureReason}:{}}}});break;default:break}if(!await this.flushUpdates())F.abort("acp-egress-failed")});if(!await this.flushUpdates())F.abort("acp-egress-failed");this.contextMessages=[...w.messages];let v=await j.loadSession(this.id,this.cwd);if(this.messages=v.length>0?v:[...w.messages],!N.success){let Q=N.error?.type??"unknown",K=N.error?.details??N.error?.message??"Agent execution failed",O=sz(K)??c(K);throw Tz.internalError({failureType:Q,modelId:this.runtime.getCurrentModelId(),taskFailure:O,outputStarted:G,toolExecutionStarted:V,...Number.isInteger(N.metadata?.toolCallsCount)?{toolCallsCount:N.metadata.toolCallsCount}:{}},`Agent turn failed (${Q})`)}if(F.signal.aborted)return{stopReason:"cancelled"};let l={...N.metadata?.structuredOutput?{structuredOutput:N.metadata.structuredOutput,outputSchemaDigest:N.metadata.structuredOutputSchemaDigest}:{},...N.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:N.metadata.goalVerificationVerdict,...N.metadata.goalVerifierSessionId?{verifierSessionId:N.metadata.goalVerifierSessionId}:{},...N.metadata.goalVerificationEvidenceSha256?{evidenceSha256:N.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(l).length>0?{_meta:l}:{}}}catch(w){if(F.signal.aborted||w instanceof Error&&w.name==="AbortError")return{stopReason:"cancelled"};throw U.error(`[AcpSession ${this.id}] Prompt error:`,w),w}finally{if(J.abortSignal?.removeEventListener("abort",L),B&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(R(),this.pendingPromptCompletion===T)this.pendingPromptCompletion=null;if(this.pendingPrompt===F){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let J=z.trimStart().slice(1).trim();if(!J)throw Error("User shell command cannot be empty");let H=new AbortController,W,X=new Promise(($)=>{W=$});this.pendingUserShell=H,this.pendingUserShellCompletion=X;let Y,Z="";try{let $=await this.runtime.executeUserShellCommand(J,{signal:H.signal,onEvent:async(L)=>{if(Y=L.executionId,L.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.executionId,status:"in_progress",title:`! ${L.command}`,content:[],kind:"execute"});return}if(L.type==="output"){Z+=L.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:L.chunk}}]});return}let B=p(L.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.executionId,status:L.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Z?nz(L.record):B}}]})}}),F={role:"user",content:$.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify($.record))}};if(this.messages.push(F),this.contextMessages.push(F),$.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return H.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:$.record.status==="aborted"?"cancelled":"end_turn"}}catch($){if(Y)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Y,status:"failed",content:[{type:"content",content:{type:"text",text:$ instanceof Error?$.message:String($)}}]});if(H.signal.aborted)return{stopReason:"cancelled"};throw $}finally{if(W(),this.pendingUserShellCompletion===X)this.pendingUserShellCompletion=null;if(this.pendingUserShell===H){if(this.pendingUserShell=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}requestPendingResume(z={}){if(!this.canSendUpdates())return;if(!this.pendingResumeRequested){if(this.pendingResumeRequested=!0,!this.pendingResumeInFlight)this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}if(!z.defer)this.ensurePendingResumeScheduled()}ensurePendingResumeScheduled(z=0){if(!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeScheduled||this.pendingResumeInFlight)return;this.pendingResumeScheduled=!0;let J=this.pendingResumeGeneration,H=()=>{if(J!==this.pendingResumeGeneration)return;this.pendingResumeScheduled=!1,this.pendingResumeTimer=null,this.resumePendingIfIdle()};if(z>0)this.pendingResumeTimer=setTimeout(H,z),this.pendingResumeTimer.unref?.();else queueMicrotask(H)}clearPendingResumeRequest(){let z=this.pendingResumeRequested||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeTimer!==null;if(this.pendingResumeRequested=!1,this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,this.pendingResumeGeneration++,this.pendingResumeScheduled=!1,this.pendingResumeTimer!==null)clearTimeout(this.pendingResumeTimer),this.pendingResumeTimer=null;return z}preserveNewPendingInput(z){if(z==="pending_input"||!this.pendingResumeRequested||!this.runtime||this.runtime.getPendingSteeringCount()===0)return!1;return this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,!0}pendingResumeSessionUpdate(z,J){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:J.kind,attempt:J.attempt,maxAttempts:i,...J.delayMs!==void 0?{delayMs:J.delayMs,nextRetryAt:Date.now()+J.delayMs}:{},...J.taskFailure?{failure:{code:J.taskFailure.code,retryable:J.taskFailure.retryable,...J.taskFailure.resource?{resource:J.taskFailure.resource}:{}}}:{}}}}}async resumePendingIfIdle(){if(!this.pendingResumeRequested)return;if(!this.canSendUpdates()){this.clearPendingResumeRequest();return}if(this.pendingResumeInFlight||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;this.pendingResumeInFlight=!0,this.pendingResumeRequested=!1;let z=this.pendingResumeGeneration,J=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=J,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let H="preflight",W=!1,X,Y=null;try{let Z=this.runtime.getPendingSteeringCount()>0,$=Z?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let F=$?.status==="active"||$?.status==="verifying",L=this.runtime.getTurnRecoveryAssessment();if(L.state!=="none"&&(L.state==="requires_attention"||!Z&&!F))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":L}});if(!Z&&!F){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if(L.state==="requires_attention"){this.clearPendingResumeRequest();return}H=Z?"pending_input":"goal",W=!0;let B=r-(Date.now()-this.pendingResumeRecoveryStartedAt);if(B<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:H,taskFailure:y("timeout")})),!this.preserveNewPendingInput(H))this.clearPendingResumeRequest();return}let G=new AbortController;Y=setTimeout(()=>{G.abort("acp-pending-resume-budget-exhausted")},B),Y.unref?.();let V=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Z,goalContinuationOnly:F,projectedRecoveredInputIds:H==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:G.signal});if(z!==this.pendingResumeGeneration)return;if(G.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:H,taskFailure:y("timeout")})),!this.preserveNewPendingInput(H))this.clearPendingResumeRequest();return}if(V.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(J>1)this.sendUpdate(this.pendingResumeSessionUpdate("recovered",{attempt:J,kind:H}));this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Z){if(z!==this.pendingResumeGeneration)return;let $=W?ez(Z):{taskFailure:c(Z),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},L=(H==="preflight"||H==="pending_input"&&this.runtime.getPendingSteeringCount()>0)&&$?.taskFailure.retryable===!0&&!$.toolExecutionStarted&&$.toolCallsCount===0&&!$.outputStarted,B=tz(this.id,J),G=Date.now()-this.pendingResumeRecoveryStartedAt,V=J<i,R=G+B<=r;if(L&&V&&R)this.pendingResumeRequested=!0,X=B,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:J+1,kind:H,taskFailure:$.taskFailure,delayMs:B})),U.warn(`[AcpSession ${this.id}] Pending resume attempt ${J} failed; retrying in ${B}ms`);else{let T=L&&(!V||!R)?"exhausted":"failed";if(this.sendUpdate(this.pendingResumeSessionUpdate(T,{attempt:J,kind:H,taskFailure:$?.taskFailure})),U.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${J}, retryable=${L}, phase=${T})`,Z),!this.preserveNewPendingInput(H))this.clearPendingResumeRequest()}}finally{if(Y!==null)clearTimeout(Y);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.ensurePendingResumeScheduled(X)}}cancel(){U.info(`[AcpSession ${this.id}] Cancel requested`);let z=this.clearPendingResumeRequest();if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,z=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,z=!0;if(this.pendingSideConversation)this.pendingSideConversation.abort(),this.pendingSideConversation=null,z=!0;if(!z)U.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let H=["default","auto-edit","yolo","plan"].includes(z)?z:"default",W=this.mapModeIdToPermissionMode(H);await j.setSessionPermissionMode(this.id,this.cwd,W),this.mode=H,U.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(z){switch(z){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(U.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{try{await j.updateSessionMetadata(this.id,this.cwd,{selectedModelId:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:z})}}catch(H){if(J&&J!==z)await this.agent.switchModel(J).catch((W)=>{U.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,W)});throw H}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid reasoning effort")}if(J.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}}catch(H){throw await this.runtime.refresh({reasoningEffort:J.selection}),H}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid service tier")}if(J.selection===z)return;await this.runtime.refresh({serviceTier:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{serviceTier:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}}catch(H){throw await this.runtime.refresh({serviceTier:J.selection}),H}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid response verbosity")}if(J.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}}catch(H){throw await this.runtime.refresh({responseVerbosity:J.selection}),H}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getCommunicationStyleConfiguration(),H=this.runtime.resolveCommunicationStyleConfiguration(z);if(H.source!=="built-in"&&!H.contentSha256)throw Error("Custom communication style has no provenance");if(J.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{communicationStyle:z,communicationStyleDigest:H.source==="built-in"?null:H.contentSha256})}catch(W){if(!(W instanceof P)&&W.code!=="ENOENT")throw W;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...H.source!=="built-in"&&H.contentSha256?{communicationStyleDigest:H.contentSha256}:{}})}}catch(W){throw await this.runtime.refresh({communicationStyle:J.selection}),W}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((J)=>structuredClone(J)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&this.pendingSideConversation===null&&(this.runtime?.isIdleForResidency()??!1)}destroy(z={}){if(this.destroyPromise)return this.destroyFinished?Promise.resolve():this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(z.discardPendingInput===!0).finally(()=>{this.destroyFinished=!0}),this.destroyPromise}async destroyOwnedResources(z){if(this.destroyed=!0,this.clearPendingResumeRequest(),this.updateEgress.close(new Nz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,H=this.runtime,W=this.pendingPromptCompletion,X=this.pendingUserShellCompletion,Y=this.pendingSideConversationCompletion;this.agent=null,this.runtime=null;let Z,$=async(F)=>{try{await F()}catch(L){Z??=L}};if(await $(()=>this.cancel()),W)await $(()=>W);if(X)await $(()=>X);if(Y)await $(()=>Y);if(z&&W&&H)await $(()=>H.discardPendingInput());if(J)await $(()=>J.destroy());if(H)await $(()=>H.dispose());if(await $(()=>E.destroySession(this.id)),U.debug(`[AcpSession ${this.id}] Destroyed`),Z!==void 0)throw Z}resolvePrompt(z){let J=[],H=[],W=0,X=0,Y=0,Z=(L)=>{if(H.length>0)H.push({type:"text",text:`
|
|
13
13
|
`}),Y+=1;if(H.push(L),L.type==="text")Y+=L.text.length};for(let L of z)if(L.type==="text")J.push(L.text),Z({type:"text",text:L.text});else if(L.type==="image"){let B=`data:${L.mimeType};base64,${L.data}`;W+=1,X+=B.length,J.push(`[Image: ${L.mimeType}]`),Z({type:"image_url",image_url:{url:B}})}else if(L.type==="resource"){let B=L.resource;if("text"in B){let G=`<file path="${B.uri}">
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{$e as q,Le as a,Me as b,Ne as c,Oe as d,Pe as e,Qe as f,Re as g,Se as h,Te as i,Ue as j,Ve as k,We as l,Xe as m,Ye as n,Ze as o,_e as p}from"./chunk-q6eb20fz.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-f945dzj6.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import"./chunk-c475tfqf.js";import"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import"./chunk-14bs89sm.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Bb as d,Cb as e,Db as f,Eb as g,Fb as h,Gb as i,Hb as j,Ib as k,Pb as l,Qb as m,Rb as n,Sb as o,Ub as p,Vb as q,Wb as r,ub as a,vb as b,xb as c}from"./chunk-0aa40zbs.js";import"./chunk-8hprmrd5.js";import"./chunk-wzmqkam9.js";import"./chunk-s0tq8gyx.js";import"./chunk-x3cxmwnz.js";import"./chunk-dg0d3303.js";import"./chunk-rchz6j90.js";import"./chunk-2hb222re.js";import"./chunk-kf7whgr7.js";import"./chunk-fva7jnjy.js";import"./chunk-aa5zmwd9.js";import"./chunk-41cg66y0.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import"./chunk-c475tfqf.js";import"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import"./chunk-14bs89sm.js";import"./chunk-rvk9r2cm.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{g as i}from"./chunk-
|
|
1
|
+
import{g as i}from"./chunk-47e6tdbb.js";import{Ph as s}from"./chunk-0hr050ck.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
|
|
2
2
|
${e.path}`}).join(`
|
|
3
3
|
`)}async function l(t,e=r){let o=await e.registry.list(e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):p(o)),o}async function u(t,e=r){let o=await e.registry.bind(c(t.path,e),e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):`Bound project: ${o.path}`),o}async function j(t,e=r){let o=c(t.path,e),n=await e.registry.unbind(o);return e.write(t.json?JSON.stringify({path:o,removed:n},null,2):n?`Unbound project: ${o}`:`Project was not bound: ${o}`),n}var a={type:"boolean",default:!1,describe:"Print machine-readable JSON"},P={command:"list",aliases:["ls"],describe:"List bound projects",builder:(t)=>t.option("json",a),handler:async(t)=>{await l(t)}},b={command:"add <path>",aliases:["bind"],describe:"Bind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await u(t)}},h={command:"remove <path>",aliases:["rm","unbind"],describe:"Unbind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await j(t)}},y={command:"projects",aliases:["project"],describe:"Manage project bindings shared with Blade Web",builder:(t)=>t.command(P).command(b).command(h).demandCommand(1,"Choose list, add, or remove"),handler:()=>{return}};export{j as runProjectsRemove,l as runProjectsList,u as runProjectsAdd,y as projectsCommands,p as formatProjectList};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{h as a,i as b,j as c,k as d,l as e}from"./chunk-jaswqpe7.js";import"./chunk-14bs89sm.js";import"./chunk-fhfzdyba.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{vi as o}from"./chunk-s10pmnrd.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
|
|
2
2
|
export{e,i as f};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ci as a,Di as b,Ei as c,Fi as d,Gi as e,Hi as f}from"./chunk-14bs89sm.js";import"./chunk-fhfzdyba.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{va as h,xa as f,ya as k}from"./chunk-
|
|
1
|
+
import{va as h,xa as f,ya as k}from"./chunk-abd57h72.js";import"./chunk-fhfzdyba.js";var p={command:"status",describe:"Check the pinned Playwright Chromium installation",handler:async()=>{let c=await f();if(console.log(`Playwright: ${c.playwrightVersion}`),console.log(`Chromium executable: ${c.executablePath}`),!c.installed){console.error(`Chromium: unavailable (${c.error??"unknown error"})`),console.error(`Install with: ${h}`),process.exitCode=1;return}console.log(`Chromium: ${c.browserVersion}`),console.log("Status: ready")}},q={command:"install",describe:"Install Chromium for the pinned Playwright runtime",handler:async()=>{try{await k();let c=await f();if(!c.installed)throw Error(c.error??"Chromium is not runnable after installation");console.log(`Chromium installed: Playwright ${c.playwrightVersion}, ${c.browserVersion}`)}catch(c){console.error(`Browser installation failed: ${c instanceof Error?c.message:String(c)}`),process.exitCode=1}}},x={command:"browser",describe:"Manage the native Browser Tool runtime",builder:(c)=>c.command(p).command(q).demandCommand(1).strict(),handler:()=>{return}};export{p as browserStatusCommand,q as browserInstallCommand,x as browserCommands};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var t=["auto","low","medium","high"],s=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function n(e){return/(?:^|[/.:_-])gpt-5(?:$|[/.:_-])/i.test(e.id)}function f(e){return typeof e==="string"&&t.includes(e)}function p(e){if(e.api==="openai-codex-responses"||s.has(e.api)&&n(e))return["low","medium","high"];return[]}function u(e,r){let i=p(e);if(r!=="auto"&&!i.includes(r))throw Error(`Response verbosity ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};return{selection:r,effective:r,supported:i,providerValue:r}}var a=["auto","standard","fast","flex"],o=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function S(e){return typeof e==="string"&&a.includes(e)}function c(e){if(o.has(e.api))return["standard","fast","flex"];if(e.api==="anthropic-messages"&&/(?:^|-)claude-opus-4-6(?:-|$)/i.test(e.id))return["standard","fast"];return["standard"]}function l(e,r){let i=c(e);if(r!=="auto"&&!i.includes(r))throw Error(`Service tier ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};if(r==="standard")return{selection:r,effective:"standard",supported:i,...o.has(e.api)?{providerValue:"default"}:{}};if(r==="fast")return{selection:r,effective:"fast",supported:i,providerValue:e.api==="anthropic-messages"?"fast":"priority"};return{selection:r,effective:"flex",supported:i,providerValue:"flex"}}
|
|
2
|
-
export{f as
|
|
2
|
+
export{f as wi,p as xi,u as yi,S as zi,c as Ai,l as Bi};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Di as d,Fi as h}from"./chunk-14bs89sm.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
|
|
2
2
|
export{q as oe,w as pe};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{qe as a,re as b,se as c}from"./chunk-gxgq70gm.js";import"./chunk-j2dyprdy.js";import"./chunk-q6eb20fz.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-41ympwz1.js";import"./chunk-f945dzj6.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import"./chunk-c475tfqf.js";import"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import"./chunk-14bs89sm.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|